title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
AngularJS | angular.lowercase() Function - GeeksforGeeks | 22 Apr, 2019
The angular.lowercase() Function in AngularJS is used to convert the string into lowercase. It can be used when user wants to show the text in lowercase instead of uppercase or one wants to compare two strings.Syntax:
angular.lowercase(string)
Example: In this example the string is converted into lowercase.
<html ng-app="app"> <head> <script src= "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js"> </script> <title>angular.lowercase()</title> </head> <body style="text-align:center"> <h1 style="color:green">GeeksforGeeks</h1> <h2>angular.lowercase()</h2> <div ng-controller="geek"> <br> <b>Before: </b>{{ string1 }} <br><br> <button id="myButton" ng-mousedown="lower()">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.lower = function() { $scope.string2 = angular.lowercase($scope.obj1); } }); </script> </body></html>
Output:Before Click:After Click:
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to create footer to stay at the bottom of a Web page?
Differences between Functional Components and Class Components in React
Node.js fs.readFileSync() Method | [
{
"code": null,
"e": 29493,
"s": 29465,
"text": "\n22 Apr, 2019"
},
{
"code": null,
"e": 29711,
"s": 29493,
"text": "The angular.lowercase() Function in AngularJS is used to convert the string into lowercase. It can be used when user wants to show the text in lowercase instead of uppercase or one wants to compare two strings.Syntax:"
},
{
"code": null,
"e": 29737,
"s": 29711,
"text": "angular.lowercase(string)"
},
{
"code": null,
"e": 29802,
"s": 29737,
"text": "Example: In this example the string is converted into lowercase."
},
{
"code": "<html ng-app=\"app\"> <head> <script src= \"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js\"> </script> <title>angular.lowercase()</title> </head> <body style=\"text-align:center\"> <h1 style=\"color:green\">GeeksforGeeks</h1> <h2>angular.lowercase()</h2> <div ng-controller=\"geek\"> <br> <b>Before: </b>{{ string1 }} <br><br> <button id=\"myButton\" ng-mousedown=\"lower()\">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.lower = function() { $scope.string2 = angular.lowercase($scope.obj1); } }); </script> </body></html>",
"e": 30782,
"s": 29802,
"text": null
},
{
"code": null,
"e": 30815,
"s": 30782,
"text": "Output:Before Click:After Click:"
},
{
"code": null,
"e": 30832,
"s": 30815,
"text": "Web Technologies"
},
{
"code": null,
"e": 30930,
"s": 30832,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30970,
"s": 30930,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 31003,
"s": 30970,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 31048,
"s": 31003,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 31091,
"s": 31048,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 31141,
"s": 31091,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 31202,
"s": 31141,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 31264,
"s": 31202,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 31322,
"s": 31264,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 31394,
"s": 31322,
"text": "Differences between Functional Components and Class Components in React"
}
] |
Minimum cost to connect all cities - GeeksforGeeks | 08 Jun, 2021
There are n cities and there are roads in between some of the cities. Somehow all the roads are damaged simultaneously. We have to repair the roads to connect the cities again. There is a fixed cost to repair a particular road. Find out the minimum cost to connect all the cities by repairing roads. Input is in matrix(city) form, if city[i][j] = 0 then there is not any road between city i and city j, if city[i][j] = a > 0 then the cost to rebuild the path between city i and city j is a. Print out the minimum cost to connect all the cities. It is sure that all the cities were connected before the roads were damaged.
Examples:
Input : {{0, 1, 2, 3, 4},
{1, 0, 5, 0, 7},
{2, 5, 0, 6, 0},
{3, 0, 6, 0, 0},
{4, 7, 0, 0, 0}};
Output : 10
Input : {{0, 1, 1, 100, 0, 0},
{1, 0, 1, 0, 0, 0},
{1, 1, 0, 0, 0, 0},
{100, 0, 0, 0, 2, 2},
{0, 0, 0, 2, 0, 2},
{0, 0, 0, 2, 2, 0}};
Output : 106
Method: Here we have to connect all the cities by path which will cost us least. The way to do that is to find out the Minimum Spanning Tree(MST) of the map of the cities(i.e. each city is a node of the graph and all the damaged roads between cities are edges). And the total cost is the addition of the path edge values in the Minimum Spanning Tree.
Prerequisite: MST Prim’s Algorithm
C++
Java
Python3
C#
Javascript
// C++ code to find out minimum cost// path to connect all the cities#include <bits/stdc++.h> using namespace std; // Function to find out minimum valued node// among the nodes which are not yet included in MSTint minnode(int n, int keyval[], bool mstset[]) { int mini = numeric_limits<int>::max(); int mini_index; // Loop through all the values of the nodes // which are not yet included in MST and find // the minimum valued one. for (int i = 0; i < n; i++) { if (mstset[i] == false && keyval[i] < mini) { mini = keyval[i], mini_index = i; } } return mini_index;} // Function to find out the MST and// the cost of the MST.void findcost(int n, vector<vector<int>> city) { // Array to store the parent node of a // particular node. int parent[n]; // Array to store key value of each node. int keyval[n]; // Boolean Array to hold bool values whether // a node is included in MST or not. bool mstset[n]; // Set all the key values to infinite and // none of the nodes is included in MST. for (int i = 0; i < n; i++) { keyval[i] = numeric_limits<int>::max(); mstset[i] = false; } // Start to find the MST from node 0. // Parent of node 0 is none so set -1. // key value or minimum cost to reach // 0th node from 0th node is 0. parent[0] = -1; keyval[0] = 0; // Find the rest n-1 nodes of MST. for (int i = 0; i < n - 1; i++) { // First find out the minimum node // among the nodes which are not yet // included in MST. int u = minnode(n, keyval, mstset); // Now the uth node is included in MST. mstset[u] = true; // Update the values of neighbor // nodes of u which are not yet // included in MST. for (int v = 0; v < n; v++) { if (city[u][v] && mstset[v] == false && city[u][v] < keyval[v]) { keyval[v] = city[u][v]; parent[v] = u; } } } // Find out the cost by adding // the edge values of MST. int cost = 0; for (int i = 1; i < n; i++) cost += city[parent[i]][i]; cout << cost << endl;} // Utility Program:int main() { // Input 1 int n1 = 5; vector<vector<int>> city1 = {{0, 1, 2, 3, 4}, {1, 0, 5, 0, 7}, {2, 5, 0, 6, 0}, {3, 0, 6, 0, 0}, {4, 7, 0, 0, 0}}; findcost(n1, city1); // Input 2 int n2 = 6; vector<vector<int>> city2 = {{0, 1, 1, 100, 0, 0}, {1, 0, 1, 0, 0, 0}, {1, 1, 0, 0, 0, 0}, {100, 0, 0, 0, 2, 2}, {0, 0, 0, 2, 0, 2}, {0, 0, 0, 2, 2, 0}}; findcost(n2, city2); return 0;}
// Java code to find out minimum cost// path to connect all the citiesimport java.util.*; class GFG{ // Function to find out minimum valued node// among the nodes which are not yet included// in MSTstatic int minnode(int n, int keyval[], boolean mstset[]){ int mini = Integer.MAX_VALUE; int mini_index = 0; // Loop through all the values of the nodes // which are not yet included in MST and find // the minimum valued one. for(int i = 0; i < n; i++) { if (mstset[i] == false && keyval[i] < mini) { mini = keyval[i]; mini_index = i; } } return mini_index;} // Function to find out the MST and// the cost of the MST.static void findcost(int n, int city[][]){ // Array to store the parent node of a // particular node. int parent[] = new int[n]; // Array to store key value of each node. int keyval[] = new int[n]; // Boolean Array to hold bool values whether // a node is included in MST or not. boolean mstset[] = new boolean[n]; // Set all the key values to infinite and // none of the nodes is included in MST. for(int i = 0; i < n; i++) { keyval[i] = Integer.MAX_VALUE; mstset[i] = false; } // Start to find the MST from node 0. // Parent of node 0 is none so set -1. // key value or minimum cost to reach // 0th node from 0th node is 0. parent[0] = -1; keyval[0] = 0; // Find the rest n-1 nodes of MST. for(int i = 0; i < n - 1; i++) { // First find out the minimum node // among the nodes which are not yet // included in MST. int u = minnode(n, keyval, mstset); // Now the uth node is included in MST. mstset[u] = true; // Update the values of neighbor // nodes of u which are not yet // included in MST. for(int v = 0; v < n; v++) { if (city[u][v] > 0 && mstset[v] == false && city[u][v] < keyval[v]) { keyval[v] = city[u][v]; parent[v] = u; } } } // Find out the cost by adding // the edge values of MST. int cost = 0; for(int i = 1; i < n; i++) cost += city[parent[i]][i]; System.out.println(cost);} // Driver codepublic static void main(String args[]){ // Input 1 int n1 = 5; int city1[][] = { { 0, 1, 2, 3, 4 }, { 1, 0, 5, 0, 7 }, { 2, 5, 0, 6, 0 }, { 3, 0, 6, 0, 0 }, { 4, 7, 0, 0, 0 } }; findcost(n1, city1); // Input 2 int n2 = 6; int city2[][] = { { 0, 1, 1, 100, 0, 0 }, { 1, 0, 1, 0, 0, 0 }, { 1, 1, 0, 0, 0, 0 }, { 100, 0, 0, 0, 2, 2 }, { 0, 0, 0, 2, 0, 2 }, { 0, 0, 0, 2, 2, 0 } }; findcost(n2, city2); }} // This code is contributed by adityapande88
# Python3 code to find out minimum cost# path to connect all the cities # Function to find out minimum valued# node among the nodes which are not# yet included in MSTdef minnode(n, keyval, mstset): mini = 999999999999 mini_index = None # Loop through all the values of # the nodes which are not yet # included in MST and find the # minimum valued one. for i in range(n): if (mstset[i] == False and keyval[i] < mini): mini = keyval[i] mini_index = i return mini_index # Function to find out the MST and# the cost of the MST.def findcost(n, city): # Array to store the parent # node of a particular node. parent = [None] * n # Array to store key value # of each node. keyval = [None] * n # Boolean Array to hold bool # values whether a node is # included in MST or not. mstset = [None] * n # Set all the key values to infinite and # none of the nodes is included in MST. for i in range(n): keyval[i] = 9999999999999 mstset[i] = False # Start to find the MST from node 0. # Parent of node 0 is none so set -1. # key value or minimum cost to reach # 0th node from 0th node is 0. parent[0] = -1 keyval[0] = 0 # Find the rest n-1 nodes of MST. for i in range(n - 1): # First find out the minimum node # among the nodes which are not yet # included in MST. u = minnode(n, keyval, mstset) # Now the uth node is included in MST. mstset[u] = True # Update the values of neighbor # nodes of u which are not yet # included in MST. for v in range(n): if (city[u][v] and mstset[v] == False and city[u][v] < keyval[v]): keyval[v] = city[u][v] parent[v] = u # Find out the cost by adding # the edge values of MST. cost = 0 for i in range(1, n): cost += city[parent[i]][i] print(cost) # Driver Codeif __name__ == '__main__': # Input 1 n1 = 5 city1 = [[0, 1, 2, 3, 4], [1, 0, 5, 0, 7], [2, 5, 0, 6, 0], [3, 0, 6, 0, 0], [4, 7, 0, 0, 0]] findcost(n1, city1) # Input 2 n2 = 6 city2 = [[0, 1, 1, 100, 0, 0], [1, 0, 1, 0, 0, 0], [1, 1, 0, 0, 0, 0], [100, 0, 0, 0, 2, 2], [0, 0, 0, 2, 0, 2], [0, 0, 0, 2, 2, 0]] findcost(n2, city2) # This code is contributed by PranchalK
// C# code to find out minimum cost// path to connect all the citiesusing System; class GFG{ // Function to find out minimum valued node// among the nodes which are not yet included// in MSTstatic int minnode(int n, int[] keyval, bool[] mstset){ int mini = Int32.MaxValue; int mini_index = 0; // Loop through all the values of the nodes // which are not yet included in MST and find // the minimum valued one. for(int i = 0; i < n; i++) { if (mstset[i] == false && keyval[i] < mini) { mini = keyval[i]; mini_index = i; } } return mini_index;} // Function to find out the MST and// the cost of the MST.static void findcost(int n, int[,] city){ // Array to store the parent node of a // particular node. int[] parent = new int[n]; // Array to store key value of each node. int[] keyval = new int[n]; // Boolean Array to hold bool values whether // a node is included in MST or not. bool[] mstset = new bool[n]; // Set all the key values to infinite and // none of the nodes is included in MST. for(int i = 0; i < n; i++) { keyval[i] = Int32.MaxValue; mstset[i] = false; } // Start to find the MST from node 0. // Parent of node 0 is none so set -1. // key value or minimum cost to reach // 0th node from 0th node is 0. parent[0] = -1; keyval[0] = 0; // Find the rest n-1 nodes of MST. for(int i = 0; i < n - 1; i++) { // First find out the minimum node // among the nodes which are not yet // included in MST. int u = minnode(n, keyval, mstset); // Now the uth node is included in MST. mstset[u] = true; // Update the values of neighbor // nodes of u which are not yet // included in MST. for(int v = 0; v < n; v++) { if (city[u, v] > 0 && mstset[v] == false && city[u, v] < keyval[v]) { keyval[v] = city[u, v]; parent[v] = u; } } } // Find out the cost by adding // the edge values of MST. int cost = 0; for(int i = 1; i < n; i++) cost += city[parent[i], i]; Console.WriteLine(cost);} // Driver codepublic static void Main(string[] args){ // Input 1 int n1 = 5; int[,] city1 = { { 0, 1, 2, 3, 4 }, { 1, 0, 5, 0, 7 }, { 2, 5, 0, 6, 0 }, { 3, 0, 6, 0, 0 }, { 4, 7, 0, 0, 0 } }; findcost(n1, city1); // Input 2 int n2 = 6; int[,] city2 = { { 0, 1, 1, 100, 0, 0 }, { 1, 0, 1, 0, 0, 0 }, { 1, 1, 0, 0, 0, 0 }, { 100, 0, 0, 0, 2, 2 }, { 0, 0, 0, 2, 0, 2 }, { 0, 0, 0, 2, 2, 0 } }; findcost(n2, city2);}} // This code is contributed by ukasp
<script> // Javascript code to find out minimum cost// path to connect all the cities // Function to find out minimum valued node// among the nodes which are not yet included// in MSTfunction minnode(n, keyval, mstset){ let mini = Number.MAX_VALUE; let mini_index = 0; // Loop through all the values of the nodes // which are not yet included in MST and find // the minimum valued one. for(let i = 0; i < n; i++) { if (mstset[i] == false && keyval[i] < mini) { mini = keyval[i]; mini_index = i; } } return mini_index;} // Function to find out the MST and// the cost of the MST.function findcost(n, city){ // Array to store the parent node of a // particular node. let parent = Array(n).fill(0); // Array to store key value of each node. let keyval = Array(n).fill(0); // Boolean Array to hold bool values whether // a node is included in MST or not. let mstset = Array(n).fill(0); // Set all the key values to infinite and // none of the nodes is included in MST. for(let i = 0; i < n; i++) { keyval[i] = Number.MAX_VALUE; mstset[i] = false; } // Start to find the MST from node 0. // Parent of node 0 is none so set -1. // key value or minimum cost to reach // 0th node from 0th node is 0. parent[0] = -1; keyval[0] = 0; // Find the rest n-1 nodes of MST. for(let i = 0; i < n - 1; i++) { // First find out the minimum node // among the nodes which are not yet // included in MST. let u = minnode(n, keyval, mstset); // Now the uth node is included in MST. mstset[u] = true; // Update the values of neighbor // nodes of u which are not yet // included in MST. for(let v = 0; v < n; v++) { if (city[u][v] > 0 && mstset[v] == false && city[u][v] < keyval[v]) { keyval[v] = city[u][v]; parent[v] = u; } } } // Find out the cost by adding // the edge values of MST. let cost = 0; for(let i = 1; i < n; i++) cost += city[parent[i]][i]; document.write(cost + "<br/>") ;} // driver code // Input 1 let n1 = 5; let city1 = [[ 0, 1, 2, 3, 4 ], [ 1, 0, 5, 0, 7 ], [ 2, 5, 0, 6, 0 ], [ 3, 0, 6, 0, 0 ], [ 4, 7, 0, 0, 0 ]]; findcost(n1, city1); // Input 2 let n2 = 6; let city2 = [[ 0, 1, 1, 100, 0, 0 ], [ 1, 0, 1, 0, 0, 0 ], [ 1, 1, 0, 0, 0, 0 ], [ 100, 0, 0, 0, 2, 2 ], [ 0, 0, 0, 2, 0, 2 ], [ 0, 0, 0, 2, 2, 0 ]]; findcost(n2, city2); </script>
10
106
Complexity: The outer loop(i.e. the loop to add new node to MST) runs n times and in each iteration of the loop it takes O(n) time to find the minnode and O(n) time to update the neighboring nodes of u-th node. Hence the overall complexity is O(n2)
PranchalKatiyar
adityapande88
avijitmondal1998
ukasp
MST
Graph
Greedy
Greedy
Graph
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Topological Sorting
Bellman–Ford Algorithm | DP-23
Detect Cycle in a Directed Graph
Floyd Warshall Algorithm | DP-16
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Program for array rotation
Write a program to print all permutations of a given string
Huffman Coding | Greedy Algo-3
Coin Change | DP-7
Activity Selection Problem | Greedy Algo-1 | [
{
"code": null,
"e": 26411,
"s": 26383,
"text": "\n08 Jun, 2021"
},
{
"code": null,
"e": 27033,
"s": 26411,
"text": "There are n cities and there are roads in between some of the cities. Somehow all the roads are damaged simultaneously. We have to repair the roads to connect the cities again. There is a fixed cost to repair a particular road. Find out the minimum cost to connect all the cities by repairing roads. Input is in matrix(city) form, if city[i][j] = 0 then there is not any road between city i and city j, if city[i][j] = a > 0 then the cost to rebuild the path between city i and city j is a. Print out the minimum cost to connect all the cities. It is sure that all the cities were connected before the roads were damaged."
},
{
"code": null,
"e": 27044,
"s": 27033,
"text": "Examples: "
},
{
"code": null,
"e": 27187,
"s": 27044,
"text": "Input : {{0, 1, 2, 3, 4},\n {1, 0, 5, 0, 7},\n {2, 5, 0, 6, 0},\n {3, 0, 6, 0, 0},\n {4, 7, 0, 0, 0}};\nOutput : 10"
},
{
"code": null,
"e": 27379,
"s": 27187,
"text": "Input : {{0, 1, 1, 100, 0, 0},\n {1, 0, 1, 0, 0, 0},\n {1, 1, 0, 0, 0, 0},\n {100, 0, 0, 0, 2, 2},\n {0, 0, 0, 2, 0, 2},\n {0, 0, 0, 2, 2, 0}};\nOutput : 106"
},
{
"code": null,
"e": 27730,
"s": 27379,
"text": "Method: Here we have to connect all the cities by path which will cost us least. The way to do that is to find out the Minimum Spanning Tree(MST) of the map of the cities(i.e. each city is a node of the graph and all the damaged roads between cities are edges). And the total cost is the addition of the path edge values in the Minimum Spanning Tree."
},
{
"code": null,
"e": 27765,
"s": 27730,
"text": "Prerequisite: MST Prim’s Algorithm"
},
{
"code": null,
"e": 27769,
"s": 27765,
"text": "C++"
},
{
"code": null,
"e": 27774,
"s": 27769,
"text": "Java"
},
{
"code": null,
"e": 27782,
"s": 27774,
"text": "Python3"
},
{
"code": null,
"e": 27785,
"s": 27782,
"text": "C#"
},
{
"code": null,
"e": 27796,
"s": 27785,
"text": "Javascript"
},
{
"code": "// C++ code to find out minimum cost// path to connect all the cities#include <bits/stdc++.h> using namespace std; // Function to find out minimum valued node// among the nodes which are not yet included in MSTint minnode(int n, int keyval[], bool mstset[]) { int mini = numeric_limits<int>::max(); int mini_index; // Loop through all the values of the nodes // which are not yet included in MST and find // the minimum valued one. for (int i = 0; i < n; i++) { if (mstset[i] == false && keyval[i] < mini) { mini = keyval[i], mini_index = i; } } return mini_index;} // Function to find out the MST and// the cost of the MST.void findcost(int n, vector<vector<int>> city) { // Array to store the parent node of a // particular node. int parent[n]; // Array to store key value of each node. int keyval[n]; // Boolean Array to hold bool values whether // a node is included in MST or not. bool mstset[n]; // Set all the key values to infinite and // none of the nodes is included in MST. for (int i = 0; i < n; i++) { keyval[i] = numeric_limits<int>::max(); mstset[i] = false; } // Start to find the MST from node 0. // Parent of node 0 is none so set -1. // key value or minimum cost to reach // 0th node from 0th node is 0. parent[0] = -1; keyval[0] = 0; // Find the rest n-1 nodes of MST. for (int i = 0; i < n - 1; i++) { // First find out the minimum node // among the nodes which are not yet // included in MST. int u = minnode(n, keyval, mstset); // Now the uth node is included in MST. mstset[u] = true; // Update the values of neighbor // nodes of u which are not yet // included in MST. for (int v = 0; v < n; v++) { if (city[u][v] && mstset[v] == false && city[u][v] < keyval[v]) { keyval[v] = city[u][v]; parent[v] = u; } } } // Find out the cost by adding // the edge values of MST. int cost = 0; for (int i = 1; i < n; i++) cost += city[parent[i]][i]; cout << cost << endl;} // Utility Program:int main() { // Input 1 int n1 = 5; vector<vector<int>> city1 = {{0, 1, 2, 3, 4}, {1, 0, 5, 0, 7}, {2, 5, 0, 6, 0}, {3, 0, 6, 0, 0}, {4, 7, 0, 0, 0}}; findcost(n1, city1); // Input 2 int n2 = 6; vector<vector<int>> city2 = {{0, 1, 1, 100, 0, 0}, {1, 0, 1, 0, 0, 0}, {1, 1, 0, 0, 0, 0}, {100, 0, 0, 0, 2, 2}, {0, 0, 0, 2, 0, 2}, {0, 0, 0, 2, 2, 0}}; findcost(n2, city2); return 0;}",
"e": 30499,
"s": 27796,
"text": null
},
{
"code": "// Java code to find out minimum cost// path to connect all the citiesimport java.util.*; class GFG{ // Function to find out minimum valued node// among the nodes which are not yet included// in MSTstatic int minnode(int n, int keyval[], boolean mstset[]){ int mini = Integer.MAX_VALUE; int mini_index = 0; // Loop through all the values of the nodes // which are not yet included in MST and find // the minimum valued one. for(int i = 0; i < n; i++) { if (mstset[i] == false && keyval[i] < mini) { mini = keyval[i]; mini_index = i; } } return mini_index;} // Function to find out the MST and// the cost of the MST.static void findcost(int n, int city[][]){ // Array to store the parent node of a // particular node. int parent[] = new int[n]; // Array to store key value of each node. int keyval[] = new int[n]; // Boolean Array to hold bool values whether // a node is included in MST or not. boolean mstset[] = new boolean[n]; // Set all the key values to infinite and // none of the nodes is included in MST. for(int i = 0; i < n; i++) { keyval[i] = Integer.MAX_VALUE; mstset[i] = false; } // Start to find the MST from node 0. // Parent of node 0 is none so set -1. // key value or minimum cost to reach // 0th node from 0th node is 0. parent[0] = -1; keyval[0] = 0; // Find the rest n-1 nodes of MST. for(int i = 0; i < n - 1; i++) { // First find out the minimum node // among the nodes which are not yet // included in MST. int u = minnode(n, keyval, mstset); // Now the uth node is included in MST. mstset[u] = true; // Update the values of neighbor // nodes of u which are not yet // included in MST. for(int v = 0; v < n; v++) { if (city[u][v] > 0 && mstset[v] == false && city[u][v] < keyval[v]) { keyval[v] = city[u][v]; parent[v] = u; } } } // Find out the cost by adding // the edge values of MST. int cost = 0; for(int i = 1; i < n; i++) cost += city[parent[i]][i]; System.out.println(cost);} // Driver codepublic static void main(String args[]){ // Input 1 int n1 = 5; int city1[][] = { { 0, 1, 2, 3, 4 }, { 1, 0, 5, 0, 7 }, { 2, 5, 0, 6, 0 }, { 3, 0, 6, 0, 0 }, { 4, 7, 0, 0, 0 } }; findcost(n1, city1); // Input 2 int n2 = 6; int city2[][] = { { 0, 1, 1, 100, 0, 0 }, { 1, 0, 1, 0, 0, 0 }, { 1, 1, 0, 0, 0, 0 }, { 100, 0, 0, 0, 2, 2 }, { 0, 0, 0, 2, 0, 2 }, { 0, 0, 0, 2, 2, 0 } }; findcost(n2, city2); }} // This code is contributed by adityapande88",
"e": 33580,
"s": 30499,
"text": null
},
{
"code": "# Python3 code to find out minimum cost# path to connect all the cities # Function to find out minimum valued# node among the nodes which are not# yet included in MSTdef minnode(n, keyval, mstset): mini = 999999999999 mini_index = None # Loop through all the values of # the nodes which are not yet # included in MST and find the # minimum valued one. for i in range(n): if (mstset[i] == False and keyval[i] < mini): mini = keyval[i] mini_index = i return mini_index # Function to find out the MST and# the cost of the MST.def findcost(n, city): # Array to store the parent # node of a particular node. parent = [None] * n # Array to store key value # of each node. keyval = [None] * n # Boolean Array to hold bool # values whether a node is # included in MST or not. mstset = [None] * n # Set all the key values to infinite and # none of the nodes is included in MST. for i in range(n): keyval[i] = 9999999999999 mstset[i] = False # Start to find the MST from node 0. # Parent of node 0 is none so set -1. # key value or minimum cost to reach # 0th node from 0th node is 0. parent[0] = -1 keyval[0] = 0 # Find the rest n-1 nodes of MST. for i in range(n - 1): # First find out the minimum node # among the nodes which are not yet # included in MST. u = minnode(n, keyval, mstset) # Now the uth node is included in MST. mstset[u] = True # Update the values of neighbor # nodes of u which are not yet # included in MST. for v in range(n): if (city[u][v] and mstset[v] == False and city[u][v] < keyval[v]): keyval[v] = city[u][v] parent[v] = u # Find out the cost by adding # the edge values of MST. cost = 0 for i in range(1, n): cost += city[parent[i]][i] print(cost) # Driver Codeif __name__ == '__main__': # Input 1 n1 = 5 city1 = [[0, 1, 2, 3, 4], [1, 0, 5, 0, 7], [2, 5, 0, 6, 0], [3, 0, 6, 0, 0], [4, 7, 0, 0, 0]] findcost(n1, city1) # Input 2 n2 = 6 city2 = [[0, 1, 1, 100, 0, 0], [1, 0, 1, 0, 0, 0], [1, 1, 0, 0, 0, 0], [100, 0, 0, 0, 2, 2], [0, 0, 0, 2, 0, 2], [0, 0, 0, 2, 2, 0]] findcost(n2, city2) # This code is contributed by PranchalK",
"e": 36107,
"s": 33580,
"text": null
},
{
"code": "// C# code to find out minimum cost// path to connect all the citiesusing System; class GFG{ // Function to find out minimum valued node// among the nodes which are not yet included// in MSTstatic int minnode(int n, int[] keyval, bool[] mstset){ int mini = Int32.MaxValue; int mini_index = 0; // Loop through all the values of the nodes // which are not yet included in MST and find // the minimum valued one. for(int i = 0; i < n; i++) { if (mstset[i] == false && keyval[i] < mini) { mini = keyval[i]; mini_index = i; } } return mini_index;} // Function to find out the MST and// the cost of the MST.static void findcost(int n, int[,] city){ // Array to store the parent node of a // particular node. int[] parent = new int[n]; // Array to store key value of each node. int[] keyval = new int[n]; // Boolean Array to hold bool values whether // a node is included in MST or not. bool[] mstset = new bool[n]; // Set all the key values to infinite and // none of the nodes is included in MST. for(int i = 0; i < n; i++) { keyval[i] = Int32.MaxValue; mstset[i] = false; } // Start to find the MST from node 0. // Parent of node 0 is none so set -1. // key value or minimum cost to reach // 0th node from 0th node is 0. parent[0] = -1; keyval[0] = 0; // Find the rest n-1 nodes of MST. for(int i = 0; i < n - 1; i++) { // First find out the minimum node // among the nodes which are not yet // included in MST. int u = minnode(n, keyval, mstset); // Now the uth node is included in MST. mstset[u] = true; // Update the values of neighbor // nodes of u which are not yet // included in MST. for(int v = 0; v < n; v++) { if (city[u, v] > 0 && mstset[v] == false && city[u, v] < keyval[v]) { keyval[v] = city[u, v]; parent[v] = u; } } } // Find out the cost by adding // the edge values of MST. int cost = 0; for(int i = 1; i < n; i++) cost += city[parent[i], i]; Console.WriteLine(cost);} // Driver codepublic static void Main(string[] args){ // Input 1 int n1 = 5; int[,] city1 = { { 0, 1, 2, 3, 4 }, { 1, 0, 5, 0, 7 }, { 2, 5, 0, 6, 0 }, { 3, 0, 6, 0, 0 }, { 4, 7, 0, 0, 0 } }; findcost(n1, city1); // Input 2 int n2 = 6; int[,] city2 = { { 0, 1, 1, 100, 0, 0 }, { 1, 0, 1, 0, 0, 0 }, { 1, 1, 0, 0, 0, 0 }, { 100, 0, 0, 0, 2, 2 }, { 0, 0, 0, 2, 0, 2 }, { 0, 0, 0, 2, 2, 0 } }; findcost(n2, city2);}} // This code is contributed by ukasp",
"e": 39032,
"s": 36107,
"text": null
},
{
"code": "<script> // Javascript code to find out minimum cost// path to connect all the cities // Function to find out minimum valued node// among the nodes which are not yet included// in MSTfunction minnode(n, keyval, mstset){ let mini = Number.MAX_VALUE; let mini_index = 0; // Loop through all the values of the nodes // which are not yet included in MST and find // the minimum valued one. for(let i = 0; i < n; i++) { if (mstset[i] == false && keyval[i] < mini) { mini = keyval[i]; mini_index = i; } } return mini_index;} // Function to find out the MST and// the cost of the MST.function findcost(n, city){ // Array to store the parent node of a // particular node. let parent = Array(n).fill(0); // Array to store key value of each node. let keyval = Array(n).fill(0); // Boolean Array to hold bool values whether // a node is included in MST or not. let mstset = Array(n).fill(0); // Set all the key values to infinite and // none of the nodes is included in MST. for(let i = 0; i < n; i++) { keyval[i] = Number.MAX_VALUE; mstset[i] = false; } // Start to find the MST from node 0. // Parent of node 0 is none so set -1. // key value or minimum cost to reach // 0th node from 0th node is 0. parent[0] = -1; keyval[0] = 0; // Find the rest n-1 nodes of MST. for(let i = 0; i < n - 1; i++) { // First find out the minimum node // among the nodes which are not yet // included in MST. let u = minnode(n, keyval, mstset); // Now the uth node is included in MST. mstset[u] = true; // Update the values of neighbor // nodes of u which are not yet // included in MST. for(let v = 0; v < n; v++) { if (city[u][v] > 0 && mstset[v] == false && city[u][v] < keyval[v]) { keyval[v] = city[u][v]; parent[v] = u; } } } // Find out the cost by adding // the edge values of MST. let cost = 0; for(let i = 1; i < n; i++) cost += city[parent[i]][i]; document.write(cost + \"<br/>\") ;} // driver code // Input 1 let n1 = 5; let city1 = [[ 0, 1, 2, 3, 4 ], [ 1, 0, 5, 0, 7 ], [ 2, 5, 0, 6, 0 ], [ 3, 0, 6, 0, 0 ], [ 4, 7, 0, 0, 0 ]]; findcost(n1, city1); // Input 2 let n2 = 6; let city2 = [[ 0, 1, 1, 100, 0, 0 ], [ 1, 0, 1, 0, 0, 0 ], [ 1, 1, 0, 0, 0, 0 ], [ 100, 0, 0, 0, 2, 2 ], [ 0, 0, 0, 2, 0, 2 ], [ 0, 0, 0, 2, 2, 0 ]]; findcost(n2, city2); </script>",
"e": 41999,
"s": 39032,
"text": null
},
{
"code": null,
"e": 42006,
"s": 41999,
"text": "10\n106"
},
{
"code": null,
"e": 42258,
"s": 42008,
"text": "Complexity: The outer loop(i.e. the loop to add new node to MST) runs n times and in each iteration of the loop it takes O(n) time to find the minnode and O(n) time to update the neighboring nodes of u-th node. Hence the overall complexity is O(n2) "
},
{
"code": null,
"e": 42274,
"s": 42258,
"text": "PranchalKatiyar"
},
{
"code": null,
"e": 42288,
"s": 42274,
"text": "adityapande88"
},
{
"code": null,
"e": 42305,
"s": 42288,
"text": "avijitmondal1998"
},
{
"code": null,
"e": 42311,
"s": 42305,
"text": "ukasp"
},
{
"code": null,
"e": 42315,
"s": 42311,
"text": "MST"
},
{
"code": null,
"e": 42321,
"s": 42315,
"text": "Graph"
},
{
"code": null,
"e": 42328,
"s": 42321,
"text": "Greedy"
},
{
"code": null,
"e": 42335,
"s": 42328,
"text": "Greedy"
},
{
"code": null,
"e": 42341,
"s": 42335,
"text": "Graph"
},
{
"code": null,
"e": 42439,
"s": 42341,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 42459,
"s": 42439,
"text": "Topological Sorting"
},
{
"code": null,
"e": 42490,
"s": 42459,
"text": "Bellman–Ford Algorithm | DP-23"
},
{
"code": null,
"e": 42523,
"s": 42490,
"text": "Detect Cycle in a Directed Graph"
},
{
"code": null,
"e": 42556,
"s": 42523,
"text": "Floyd Warshall Algorithm | DP-16"
},
{
"code": null,
"e": 42624,
"s": 42556,
"text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)"
},
{
"code": null,
"e": 42651,
"s": 42624,
"text": "Program for array rotation"
},
{
"code": null,
"e": 42711,
"s": 42651,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 42742,
"s": 42711,
"text": "Huffman Coding | Greedy Algo-3"
},
{
"code": null,
"e": 42761,
"s": 42742,
"text": "Coin Change | DP-7"
}
] |
GATE | GATE CS 2013 | Question 7 - GeeksforGeeks | 28 Jun, 2021
Which one of the following is the tightest upper bound that represents the time complexity of inserting an object into a binary search tree of n nodes?(A) O(1)(B) O(Logn)(C) O(n)(D) O(nLogn)Answer: (C)Explanation: To insert an element, we need to search for its place first. The search operation may take O(n) for a skewed tree like following.
To insert 50, we will have to traverse all nodes.
10
\
20
\
30
\
40
Quiz of this Question
GATE-CS-2013
GATE-GATE CS 2013
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-2001 | Question 39
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 IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90 | [
{
"code": null,
"e": 25877,
"s": 25849,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 26221,
"s": 25877,
"text": "Which one of the following is the tightest upper bound that represents the time complexity of inserting an object into a binary search tree of n nodes?(A) O(1)(B) O(Logn)(C) O(n)(D) O(nLogn)Answer: (C)Explanation: To insert an element, we need to search for its place first. The search operation may take O(n) for a skewed tree like following."
},
{
"code": null,
"e": 26373,
"s": 26221,
"text": "To insert 50, we will have to traverse all nodes.\n 10\n \\\n 20\n \\\n 30\n \\\n 40\n"
},
{
"code": null,
"e": 26395,
"s": 26373,
"text": "Quiz of this Question"
},
{
"code": null,
"e": 26408,
"s": 26395,
"text": "GATE-CS-2013"
},
{
"code": null,
"e": 26426,
"s": 26408,
"text": "GATE-GATE CS 2013"
},
{
"code": null,
"e": 26431,
"s": 26426,
"text": "GATE"
},
{
"code": null,
"e": 26529,
"s": 26431,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26563,
"s": 26529,
"text": "GATE | Gate IT 2007 | Question 25"
},
{
"code": null,
"e": 26597,
"s": 26563,
"text": "GATE | GATE-CS-2001 | Question 39"
},
{
"code": null,
"e": 26631,
"s": 26597,
"text": "GATE | GATE-CS-2000 | Question 41"
},
{
"code": null,
"e": 26664,
"s": 26631,
"text": "GATE | GATE-CS-2005 | Question 6"
},
{
"code": null,
"e": 26700,
"s": 26664,
"text": "GATE | GATE MOCK 2017 | Question 21"
},
{
"code": null,
"e": 26734,
"s": 26700,
"text": "GATE | GATE-CS-2006 | Question 47"
},
{
"code": null,
"e": 26770,
"s": 26734,
"text": "GATE | GATE MOCK 2017 | Question 24"
},
{
"code": null,
"e": 26804,
"s": 26770,
"text": "GATE | Gate IT 2008 | Question 43"
},
{
"code": null,
"e": 26838,
"s": 26804,
"text": "GATE | GATE-CS-2009 | Question 38"
}
] |
Function Arguments in Golang - GeeksforGeeks | 13 Aug, 2019
A function in Golang is a collection of statements which is used to perform specific task and return the result to the caller. A function can also perform some specific task without returning anything. Golang supports two different ways to pass arguments to the function i.e. Pass by Value or Call by Value and Pass By Reference or Call By Reference. By default, Golang uses the call by value way to pass the arguments to the function.
Basic Terms in Parameter Passing to Function:
The parameters passed to function are called Actual Parameters.
The parameters received by the function are called Formal Parameters.
In this parameter passing, values of actual parameters are copied to function’s formal parameters and the two types of parameters are stored in different memory locations. So any changes made inside functions are not reflected in actual parameters of the caller.
Example 1: In the below program, you can see that the value of Z cannot be modified by the function modify.
// Go program to illustrate the// concept of the call by valuepackage main import "fmt" // function which modifies// the valuefunc modify(Z int) { Z = 70} // Main functionfunc main() { var Z int = 10 fmt.Printf("Before Function Call, value of Z is = %d", Z) // call by value modify(Z) fmt.Printf("\nAfter Function Call, value of Z is = %d", Z)}
Output:
Before Function Call, value of Z is = 10
After Function Call, value of Z is = 10
Example 2: In the below program, swap function is unable to swap the values as we are using the call by value.
// Go program to illustrate the// concept of the call by valuepackage main import "fmt" // function which swap valuesfunc swap(x, y int) int { // taking a temporary variable var tmp int tmp = x x = y y = tmp return tmp} // Main functionfunc main() { var f int = 700 var s int = 900 fmt.Printf("Values Before Function Call\n") fmt.Printf("f = %d and s = %d\n", f, s) // call by values swap(f, s) fmt.Printf("\nValues After Function Call\n") fmt.Printf("f = %d and s = %d", f, s)}
Output:
Values Before Function Call
f = 700 and s = 900
Values After Function Call
f = 700 and s = 900
Here, you will use the concept of Pointers. The dereference operator * is used to access the value at an address. The address operator & is used to get the address of a variable of any data type. Both the actual and formal parameters refer to the same locations, so any changes made inside the function are actually reflected in actual parameters of the caller.
Example 1: In the function call, we are passing the address of the variable and using the dereferencing operator * to modify the value. So after the function i.e. modify, you will find the updated value.
// Go program to illustrate the// concept of the call by Referencepackage main import "fmt" // function which modifies// the valuefunc modify(Z *int) { *Z = 70} // Main functionfunc main() { var Z int = 10 fmt.Printf("Before Function Call, value of Z is = %d", Z) // call by Reference // by passing the address // of the variable Z modify(&Z) fmt.Printf("\nAfter Function Call, value of Z is = %d", Z)}
Output:
Before Function Call, value of Z is = 10
After Function Call, value of Z is = 70
Example 2: By using the call by reference the swap function will be able to swap the values as shown below.
// Go program to illustrate the// concept of the call by Referencepackage main import "fmt" // function which swap values// taking the pointer to integerfunc swap(x, y *int) int { // taking a temporary variable var tmp int tmp = *x *x = *y *y = tmp return tmp} // Main functionfunc main() { var f int = 700 var s int = 900 fmt.Printf("Values Before Function Call\n") fmt.Printf("f = %d and s = %d\n", f, s) // call by Reference // by passing the address // of the variables swap(&f, &s) fmt.Printf("\nValues After Function Call\n") fmt.Printf("f = %d and s = %d", f, s)}
Output:
Values Before Function Call
f = 700 and s = 900
Values After Function Call
f = 900 and s = 700
Go-Functions
Golang
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
6 Best Books to Learn Go Programming Language
Arrays in Go
strings.Replace() Function in Golang With Examples
How to Split a String in Golang?
Golang Maps
Slices in Golang
Different Ways to Find the Type of Variable in Golang
Inheritance in GoLang
Interfaces in Golang
How to Trim a String in Golang? | [
{
"code": null,
"e": 25777,
"s": 25749,
"text": "\n13 Aug, 2019"
},
{
"code": null,
"e": 26213,
"s": 25777,
"text": "A function in Golang is a collection of statements which is used to perform specific task and return the result to the caller. A function can also perform some specific task without returning anything. Golang supports two different ways to pass arguments to the function i.e. Pass by Value or Call by Value and Pass By Reference or Call By Reference. By default, Golang uses the call by value way to pass the arguments to the function."
},
{
"code": null,
"e": 26259,
"s": 26213,
"text": "Basic Terms in Parameter Passing to Function:"
},
{
"code": null,
"e": 26323,
"s": 26259,
"text": "The parameters passed to function are called Actual Parameters."
},
{
"code": null,
"e": 26393,
"s": 26323,
"text": "The parameters received by the function are called Formal Parameters."
},
{
"code": null,
"e": 26656,
"s": 26393,
"text": "In this parameter passing, values of actual parameters are copied to function’s formal parameters and the two types of parameters are stored in different memory locations. So any changes made inside functions are not reflected in actual parameters of the caller."
},
{
"code": null,
"e": 26764,
"s": 26656,
"text": "Example 1: In the below program, you can see that the value of Z cannot be modified by the function modify."
},
{
"code": "// Go program to illustrate the// concept of the call by valuepackage main import \"fmt\" // function which modifies// the valuefunc modify(Z int) { Z = 70} // Main functionfunc main() { var Z int = 10 fmt.Printf(\"Before Function Call, value of Z is = %d\", Z) // call by value modify(Z) fmt.Printf(\"\\nAfter Function Call, value of Z is = %d\", Z)}",
"e": 27146,
"s": 26764,
"text": null
},
{
"code": null,
"e": 27154,
"s": 27146,
"text": "Output:"
},
{
"code": null,
"e": 27236,
"s": 27154,
"text": "Before Function Call, value of Z is = 10\nAfter Function Call, value of Z is = 10\n"
},
{
"code": null,
"e": 27347,
"s": 27236,
"text": "Example 2: In the below program, swap function is unable to swap the values as we are using the call by value."
},
{
"code": "// Go program to illustrate the// concept of the call by valuepackage main import \"fmt\" // function which swap valuesfunc swap(x, y int) int { // taking a temporary variable var tmp int tmp = x x = y y = tmp return tmp} // Main functionfunc main() { var f int = 700 var s int = 900 fmt.Printf(\"Values Before Function Call\\n\") fmt.Printf(\"f = %d and s = %d\\n\", f, s) // call by values swap(f, s) fmt.Printf(\"\\nValues After Function Call\\n\") fmt.Printf(\"f = %d and s = %d\", f, s)}",
"e": 27885,
"s": 27347,
"text": null
},
{
"code": null,
"e": 27893,
"s": 27885,
"text": "Output:"
},
{
"code": null,
"e": 27990,
"s": 27893,
"text": "Values Before Function Call\nf = 700 and s = 900\n\nValues After Function Call\nf = 700 and s = 900\n"
},
{
"code": null,
"e": 28352,
"s": 27990,
"text": "Here, you will use the concept of Pointers. The dereference operator * is used to access the value at an address. The address operator & is used to get the address of a variable of any data type. Both the actual and formal parameters refer to the same locations, so any changes made inside the function are actually reflected in actual parameters of the caller."
},
{
"code": null,
"e": 28556,
"s": 28352,
"text": "Example 1: In the function call, we are passing the address of the variable and using the dereferencing operator * to modify the value. So after the function i.e. modify, you will find the updated value."
},
{
"code": "// Go program to illustrate the// concept of the call by Referencepackage main import \"fmt\" // function which modifies// the valuefunc modify(Z *int) { *Z = 70} // Main functionfunc main() { var Z int = 10 fmt.Printf(\"Before Function Call, value of Z is = %d\", Z) // call by Reference // by passing the address // of the variable Z modify(&Z) fmt.Printf(\"\\nAfter Function Call, value of Z is = %d\", Z)}",
"e": 28994,
"s": 28556,
"text": null
},
{
"code": null,
"e": 29002,
"s": 28994,
"text": "Output:"
},
{
"code": null,
"e": 29084,
"s": 29002,
"text": "Before Function Call, value of Z is = 10\nAfter Function Call, value of Z is = 70\n"
},
{
"code": null,
"e": 29192,
"s": 29084,
"text": "Example 2: By using the call by reference the swap function will be able to swap the values as shown below."
},
{
"code": "// Go program to illustrate the// concept of the call by Referencepackage main import \"fmt\" // function which swap values// taking the pointer to integerfunc swap(x, y *int) int { // taking a temporary variable var tmp int tmp = *x *x = *y *y = tmp return tmp} // Main functionfunc main() { var f int = 700 var s int = 900 fmt.Printf(\"Values Before Function Call\\n\") fmt.Printf(\"f = %d and s = %d\\n\", f, s) // call by Reference // by passing the address // of the variables swap(&f, &s) fmt.Printf(\"\\nValues After Function Call\\n\") fmt.Printf(\"f = %d and s = %d\", f, s)}",
"e": 29829,
"s": 29192,
"text": null
},
{
"code": null,
"e": 29837,
"s": 29829,
"text": "Output:"
},
{
"code": null,
"e": 29934,
"s": 29837,
"text": "Values Before Function Call\nf = 700 and s = 900\n\nValues After Function Call\nf = 900 and s = 700\n"
},
{
"code": null,
"e": 29947,
"s": 29934,
"text": "Go-Functions"
},
{
"code": null,
"e": 29954,
"s": 29947,
"text": "Golang"
},
{
"code": null,
"e": 29966,
"s": 29954,
"text": "Go Language"
},
{
"code": null,
"e": 30064,
"s": 29966,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30110,
"s": 30064,
"text": "6 Best Books to Learn Go Programming Language"
},
{
"code": null,
"e": 30123,
"s": 30110,
"text": "Arrays in Go"
},
{
"code": null,
"e": 30174,
"s": 30123,
"text": "strings.Replace() Function in Golang With Examples"
},
{
"code": null,
"e": 30207,
"s": 30174,
"text": "How to Split a String in Golang?"
},
{
"code": null,
"e": 30219,
"s": 30207,
"text": "Golang Maps"
},
{
"code": null,
"e": 30236,
"s": 30219,
"text": "Slices in Golang"
},
{
"code": null,
"e": 30290,
"s": 30236,
"text": "Different Ways to Find the Type of Variable in Golang"
},
{
"code": null,
"e": 30312,
"s": 30290,
"text": "Inheritance in GoLang"
},
{
"code": null,
"e": 30333,
"s": 30312,
"text": "Interfaces in Golang"
}
] |
Pandas - Number of Months Between Two Dates - GeeksforGeeks | 18 Dec, 2021
In this article, we are going to find the number of months between two dates in pandas using Python.
Example 1:
We will take a dataframe and have two columns for the dates between which we want to get the difference. Use df.dates1-df.dates2 to find the difference between the two dates and then convert the result in the form of months. Convert into ‘int’ datatype else result will be in form of float.
Python3
# Importing required librariesimport pandas as pdimport numpy as npimport datetime # Making a dataframe which will have two# columns two store different datesdf = pd.DataFrame({'dates1': np.array( [datetime.datetime(2000, 10, 19), datetime.datetime(2021, 1, 8)]), 'dates2': np.array( [datetime.datetime(1998, 6, 20), datetime.datetime(2012, 10, 18)])}) # Used to convert the difference in terms of monthsdf['nb_months'] = ((df.dates1 - df.dates2)/np.timedelta64(1, 'M'))df['nb_months'] = df['nb_months'].astype(int)print(df)
Output:
Example 2:
We can also get the number of days between two dates by doing a slight modification in the code. It is shown as follows:
Python3
# Importing required librariesimport pandas as pdimport numpy as npimport datetime # Making a dataframe which will have# two columns two store different datesdf = pd.DataFrame({'dates1': np.array( [datetime.datetime(2000, 10, 19), datetime.datetime(2021, 1, 8)]), 'dates2': np.array( [datetime.datetime(1998, 6, 20), datetime.datetime(2012, 10, 18)])}) # Used to convert the difference in terms of daysdf['Number_of_days'] = ((df.dates1 - df.dates2)/np.timedelta64(1, 'D'))df['Number_of_days'] = df['Number_of_days'].astype(int)print(df)
Output:
Example 3:
In a similar way, we can get differences between the two dates in terms of weeks also.
Python3
# Importing required librariesimport pandas as pdimport numpy as npimport datetime # Making a dataframe which will# have two columns two store different datesdf= pd.DataFrame({'dates1': np.array( [datetime.datetime(2000, 10, 19), datetime.datetime(2021, 1, 8)]), 'dates2': np.array( [datetime.datetime(1998, 6, 20), datetime.datetime(2012, 10, 18)] )}) # Used to convert the difference in terms of weeksdf['Number_of_weeks'] = ((df.dates1 - df.dates2)/np.timedelta64(1, 'W'))df['Number_of_weeks'] = df['Number_of_weeks'].astype(int)print(df)
Output:
Example 4:
In a similar way, we can get differences between the two dates in terms of years also.
Python3
# Importing required librariesimport pandas as pdimport numpy as npimport datetime # Making a dataframe which will# have two columns two store different datesdf = pd.DataFrame({'dates1': np.array( [datetime.datetime(2000, 10, 19), datetime.datetime(2021, 1, 8)]), 'dates2': np.array( [datetime.datetime(1998, 6, 20), datetime.datetime(2012, 10, 18)])}) # Used to convert the difference in terms of yearsdf['Number_of_years'] = ((df.dates1 - df.dates2)/np.timedelta64(1, 'Y'))df['Number_of_years'] = df['Number_of_years'].astype(int)print(df)
Output:
sagartomar9927
Picked
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 ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n18 Dec, 2021"
},
{
"code": null,
"e": 25639,
"s": 25537,
"text": "In this article, we are going to find the number of months between two dates in pandas using Python. "
},
{
"code": null,
"e": 25650,
"s": 25639,
"text": "Example 1:"
},
{
"code": null,
"e": 25941,
"s": 25650,
"text": "We will take a dataframe and have two columns for the dates between which we want to get the difference. Use df.dates1-df.dates2 to find the difference between the two dates and then convert the result in the form of months. Convert into ‘int’ datatype else result will be in form of float."
},
{
"code": null,
"e": 25949,
"s": 25941,
"text": "Python3"
},
{
"code": "# Importing required librariesimport pandas as pdimport numpy as npimport datetime # Making a dataframe which will have two# columns two store different datesdf = pd.DataFrame({'dates1': np.array( [datetime.datetime(2000, 10, 19), datetime.datetime(2021, 1, 8)]), 'dates2': np.array( [datetime.datetime(1998, 6, 20), datetime.datetime(2012, 10, 18)])}) # Used to convert the difference in terms of monthsdf['nb_months'] = ((df.dates1 - df.dates2)/np.timedelta64(1, 'M'))df['nb_months'] = df['nb_months'].astype(int)print(df)",
"e": 26534,
"s": 25949,
"text": null
},
{
"code": null,
"e": 26542,
"s": 26534,
"text": "Output:"
},
{
"code": null,
"e": 26553,
"s": 26542,
"text": "Example 2:"
},
{
"code": null,
"e": 26674,
"s": 26553,
"text": "We can also get the number of days between two dates by doing a slight modification in the code. It is shown as follows:"
},
{
"code": null,
"e": 26682,
"s": 26674,
"text": "Python3"
},
{
"code": "# Importing required librariesimport pandas as pdimport numpy as npimport datetime # Making a dataframe which will have# two columns two store different datesdf = pd.DataFrame({'dates1': np.array( [datetime.datetime(2000, 10, 19), datetime.datetime(2021, 1, 8)]), 'dates2': np.array( [datetime.datetime(1998, 6, 20), datetime.datetime(2012, 10, 18)])}) # Used to convert the difference in terms of daysdf['Number_of_days'] = ((df.dates1 - df.dates2)/np.timedelta64(1, 'D'))df['Number_of_days'] = df['Number_of_days'].astype(int)print(df)",
"e": 27280,
"s": 26682,
"text": null
},
{
"code": null,
"e": 27288,
"s": 27280,
"text": "Output:"
},
{
"code": null,
"e": 27299,
"s": 27288,
"text": "Example 3:"
},
{
"code": null,
"e": 27386,
"s": 27299,
"text": "In a similar way, we can get differences between the two dates in terms of weeks also."
},
{
"code": null,
"e": 27394,
"s": 27386,
"text": "Python3"
},
{
"code": "# Importing required librariesimport pandas as pdimport numpy as npimport datetime # Making a dataframe which will# have two columns two store different datesdf= pd.DataFrame({'dates1': np.array( [datetime.datetime(2000, 10, 19), datetime.datetime(2021, 1, 8)]), 'dates2': np.array( [datetime.datetime(1998, 6, 20), datetime.datetime(2012, 10, 18)] )}) # Used to convert the difference in terms of weeksdf['Number_of_weeks'] = ((df.dates1 - df.dates2)/np.timedelta64(1, 'W'))df['Number_of_weeks'] = df['Number_of_weeks'].astype(int)print(df)",
"e": 27996,
"s": 27394,
"text": null
},
{
"code": null,
"e": 28004,
"s": 27996,
"text": "Output:"
},
{
"code": null,
"e": 28015,
"s": 28004,
"text": "Example 4:"
},
{
"code": null,
"e": 28102,
"s": 28015,
"text": "In a similar way, we can get differences between the two dates in terms of years also."
},
{
"code": null,
"e": 28110,
"s": 28102,
"text": "Python3"
},
{
"code": "# Importing required librariesimport pandas as pdimport numpy as npimport datetime # Making a dataframe which will# have two columns two store different datesdf = pd.DataFrame({'dates1': np.array( [datetime.datetime(2000, 10, 19), datetime.datetime(2021, 1, 8)]), 'dates2': np.array( [datetime.datetime(1998, 6, 20), datetime.datetime(2012, 10, 18)])}) # Used to convert the difference in terms of yearsdf['Number_of_years'] = ((df.dates1 - df.dates2)/np.timedelta64(1, 'Y'))df['Number_of_years'] = df['Number_of_years'].astype(int)print(df)",
"e": 28712,
"s": 28110,
"text": null
},
{
"code": null,
"e": 28720,
"s": 28712,
"text": "Output:"
},
{
"code": null,
"e": 28735,
"s": 28720,
"text": "sagartomar9927"
},
{
"code": null,
"e": 28742,
"s": 28735,
"text": "Picked"
},
{
"code": null,
"e": 28756,
"s": 28742,
"text": "Python-pandas"
},
{
"code": null,
"e": 28763,
"s": 28756,
"text": "Python"
},
{
"code": null,
"e": 28861,
"s": 28763,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28893,
"s": 28861,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28935,
"s": 28893,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28977,
"s": 28935,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 29004,
"s": 28977,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 29060,
"s": 29004,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 29099,
"s": 29060,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 29121,
"s": 29099,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 29152,
"s": 29121,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 29181,
"s": 29152,
"text": "Create a directory in Python"
}
] |
get_cookies driver method - Selenium Python - GeeksforGeeks | 15 May, 2020
Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python. Just being able to go to places isn’t terribly useful. What we’d really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. There are multiple strategies to find an element using Selenium, checkout – Locating Strategies. Selenium WebDriver offers various useful methods to control the session, or in other words, browser. For example, adding a cookie, pressing back button, navigating among tabs, etc.
This article revolves around get_cookies drrver method in Selenium. get_cookies method is used to get all cookies in current session. It returns a set of dictionaries, corresponding to cookies visible in the current session.
Syntax –
driver.get_cookies()
Example –Now one can use get_cookies method as a driver method as below –
diver.get("https://www.geeksforgeeks.org/")
driver.get_cookies()
To demonstrate, get_cookies method of WebDriver in Selenium Python. Let’ s visit https://www.geeksforgeeks.org/ and get all cookies.
Program –
# import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/") # get all cookies in scope of sessionprint(driver.get_cookies())
Output –Browser cookies are as verified below –Terminal Output –
Python-selenium
selenium
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | Get unique values from a list
Python | os.path.join() method
Defaultdict in Python
Create a directory in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n15 May, 2020"
},
{
"code": null,
"e": 26276,
"s": 25537,
"text": "Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python. Just being able to go to places isn’t terribly useful. What we’d really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. There are multiple strategies to find an element using Selenium, checkout – Locating Strategies. Selenium WebDriver offers various useful methods to control the session, or in other words, browser. For example, adding a cookie, pressing back button, navigating among tabs, etc."
},
{
"code": null,
"e": 26501,
"s": 26276,
"text": "This article revolves around get_cookies drrver method in Selenium. get_cookies method is used to get all cookies in current session. It returns a set of dictionaries, corresponding to cookies visible in the current session."
},
{
"code": null,
"e": 26510,
"s": 26501,
"text": "Syntax –"
},
{
"code": null,
"e": 26531,
"s": 26510,
"text": "driver.get_cookies()"
},
{
"code": null,
"e": 26605,
"s": 26531,
"text": "Example –Now one can use get_cookies method as a driver method as below –"
},
{
"code": null,
"e": 26671,
"s": 26605,
"text": "diver.get(\"https://www.geeksforgeeks.org/\")\ndriver.get_cookies()\n"
},
{
"code": null,
"e": 26804,
"s": 26671,
"text": "To demonstrate, get_cookies method of WebDriver in Selenium Python. Let’ s visit https://www.geeksforgeeks.org/ and get all cookies."
},
{
"code": null,
"e": 26814,
"s": 26804,
"text": "Program –"
},
{
"code": "# import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get(\"https://www.geeksforgeeks.org/\") # get all cookies in scope of sessionprint(driver.get_cookies())",
"e": 27053,
"s": 26814,
"text": null
},
{
"code": null,
"e": 27118,
"s": 27053,
"text": "Output –Browser cookies are as verified below –Terminal Output –"
},
{
"code": null,
"e": 27134,
"s": 27118,
"text": "Python-selenium"
},
{
"code": null,
"e": 27143,
"s": 27134,
"text": "selenium"
},
{
"code": null,
"e": 27150,
"s": 27143,
"text": "Python"
},
{
"code": null,
"e": 27248,
"s": 27150,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27280,
"s": 27248,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27322,
"s": 27280,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27364,
"s": 27322,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27420,
"s": 27364,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27447,
"s": 27420,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27486,
"s": 27447,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27517,
"s": 27486,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27539,
"s": 27517,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27568,
"s": 27539,
"text": "Create a directory in Python"
}
] |
modinfo command in Linux with Examples - GeeksforGeeks | 23 May, 2019
modinfo command in Linux system is used to display the information about a Linux Kernel module. This command extracts the information from the Linux kernel modules given on the command line. If the module name is not a file name, then the /lib/modules/kernel-version directory is searched by default. modinfo can understand modules from any of the Linux Kernel architecture.
Syntax:
modinfo [-0] [-F field] [-k kernel] [modulename|filename...]
Example:
modinfo bluetooth
Options:
modinfo command with help option: It will print the general syntax of the modinfo along with the various options and gives a brief description about each option.
modinfo -V: This option gives the version information of modinfo command.modinfo -V
modinfo -V
modinfo -F: This option only print this field value, one per line. Field names are case-insensitive. Common fields that may include author, description, license, parm, depends, and alias. There are possibly multiple parm, alias and depends on fields. The special field filename lists are the filename of the module.modinfo -F modulename
modinfo -F modulename
modinfo -b : This option is the root directory for modules.modinfo -b modulename
modinfo -b modulename
modinfo -k : This option provides the information about a kernel other than the running one. This option is particularly being useful for the distributions that need to extract information from a newly installed set of kernel modules. For example, to find which firmware files are needed by various modules inside a new kernel for which you need to make an initrd/initramfs image prior to booting.modinfo -k modulename
modinfo -k modulename
modinfo -0: This option use the ASCII zero character to separate field values, instead of a new line. This option is proven useful for scripts since a new line can theoretically appear inside a field.Example:modinfo bluetooth -0
Example:
modinfo bluetooth -0
modinfo -a –author, -d –description, -l –license, -p –parameters, -n –filename: These are the shortcuts used for the –field flag’s author, description, license, parm and filename arguments to make the transition from the old modutils modinfo easy.Example:modinfo bluetooth -amodinfo bluetooth -nmodinfo bluetooth -dmodinfo bluetooth -lmodinfo bluetooth -p
Example:
modinfo bluetooth -a
modinfo bluetooth -n
modinfo bluetooth -d
modinfo bluetooth -l
modinfo bluetooth -p
linux-command
Linux-misc-commands
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
scp command in Linux with Examples
mv command in Linux with examples
Docker - COPY Instruction
SED command in Linux | Set 2
chown command in Linux with Examples
nohup Command in Linux with Examples
Named Pipe or FIFO with example C program
Thread functions in C/C++
uniq Command in LINUX with examples
Start/Stop/Restart Services Using Systemctl in Linux | [
{
"code": null,
"e": 25651,
"s": 25623,
"text": "\n23 May, 2019"
},
{
"code": null,
"e": 26026,
"s": 25651,
"text": "modinfo command in Linux system is used to display the information about a Linux Kernel module. This command extracts the information from the Linux kernel modules given on the command line. If the module name is not a file name, then the /lib/modules/kernel-version directory is searched by default. modinfo can understand modules from any of the Linux Kernel architecture."
},
{
"code": null,
"e": 26034,
"s": 26026,
"text": "Syntax:"
},
{
"code": null,
"e": 26096,
"s": 26034,
"text": "modinfo [-0] [-F field] [-k kernel] [modulename|filename...]\n"
},
{
"code": null,
"e": 26105,
"s": 26096,
"text": "Example:"
},
{
"code": null,
"e": 26123,
"s": 26105,
"text": "modinfo bluetooth"
},
{
"code": null,
"e": 26132,
"s": 26123,
"text": "Options:"
},
{
"code": null,
"e": 26294,
"s": 26132,
"text": "modinfo command with help option: It will print the general syntax of the modinfo along with the various options and gives a brief description about each option."
},
{
"code": null,
"e": 26378,
"s": 26294,
"text": "modinfo -V: This option gives the version information of modinfo command.modinfo -V"
},
{
"code": null,
"e": 26389,
"s": 26378,
"text": "modinfo -V"
},
{
"code": null,
"e": 26726,
"s": 26389,
"text": "modinfo -F: This option only print this field value, one per line. Field names are case-insensitive. Common fields that may include author, description, license, parm, depends, and alias. There are possibly multiple parm, alias and depends on fields. The special field filename lists are the filename of the module.modinfo -F modulename"
},
{
"code": null,
"e": 26748,
"s": 26726,
"text": "modinfo -F modulename"
},
{
"code": null,
"e": 26829,
"s": 26748,
"text": "modinfo -b : This option is the root directory for modules.modinfo -b modulename"
},
{
"code": null,
"e": 26851,
"s": 26829,
"text": "modinfo -b modulename"
},
{
"code": null,
"e": 27270,
"s": 26851,
"text": "modinfo -k : This option provides the information about a kernel other than the running one. This option is particularly being useful for the distributions that need to extract information from a newly installed set of kernel modules. For example, to find which firmware files are needed by various modules inside a new kernel for which you need to make an initrd/initramfs image prior to booting.modinfo -k modulename"
},
{
"code": null,
"e": 27292,
"s": 27270,
"text": "modinfo -k modulename"
},
{
"code": null,
"e": 27521,
"s": 27292,
"text": "modinfo -0: This option use the ASCII zero character to separate field values, instead of a new line. This option is proven useful for scripts since a new line can theoretically appear inside a field.Example:modinfo bluetooth -0"
},
{
"code": null,
"e": 27530,
"s": 27521,
"text": "Example:"
},
{
"code": null,
"e": 27551,
"s": 27530,
"text": "modinfo bluetooth -0"
},
{
"code": null,
"e": 27907,
"s": 27551,
"text": "modinfo -a –author, -d –description, -l –license, -p –parameters, -n –filename: These are the shortcuts used for the –field flag’s author, description, license, parm and filename arguments to make the transition from the old modutils modinfo easy.Example:modinfo bluetooth -amodinfo bluetooth -nmodinfo bluetooth -dmodinfo bluetooth -lmodinfo bluetooth -p"
},
{
"code": null,
"e": 27916,
"s": 27907,
"text": "Example:"
},
{
"code": null,
"e": 27937,
"s": 27916,
"text": "modinfo bluetooth -a"
},
{
"code": null,
"e": 27958,
"s": 27937,
"text": "modinfo bluetooth -n"
},
{
"code": null,
"e": 27979,
"s": 27958,
"text": "modinfo bluetooth -d"
},
{
"code": null,
"e": 28000,
"s": 27979,
"text": "modinfo bluetooth -l"
},
{
"code": null,
"e": 28021,
"s": 28000,
"text": "modinfo bluetooth -p"
},
{
"code": null,
"e": 28035,
"s": 28021,
"text": "linux-command"
},
{
"code": null,
"e": 28055,
"s": 28035,
"text": "Linux-misc-commands"
},
{
"code": null,
"e": 28066,
"s": 28055,
"text": "Linux-Unix"
},
{
"code": null,
"e": 28164,
"s": 28066,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28199,
"s": 28164,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 28233,
"s": 28199,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 28259,
"s": 28233,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 28288,
"s": 28259,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 28325,
"s": 28288,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 28362,
"s": 28325,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 28404,
"s": 28362,
"text": "Named Pipe or FIFO with example C program"
},
{
"code": null,
"e": 28430,
"s": 28404,
"text": "Thread functions in C/C++"
},
{
"code": null,
"e": 28466,
"s": 28430,
"text": "uniq Command in LINUX with examples"
}
] |
Data Structures | Queue | Question 11 - GeeksforGeeks | 28 Nov, 2021
Consider the following pseudo code. Assume that IntQueue is an integer queue. What does the function fun do?
void fun(int n){ IntQueue q = new IntQueue(); q.enqueue(0); q.enqueue(1); for (int i = 0; i < n; i++) { int a = q.dequeue(); int b = q.dequeue(); q.enqueue(b); q.enqueue(a + b); print(a); }}
(A) Prints numbers from 0 to n-1(B) Prints numbers from n-1 to 0(C) Prints first n Fibonacci numbers(D) Prints first n Fibonacci numbers in reverse order.Answer: (C)Explanation: The function prints first n Fibonacci Numbers. Note that 0 and 1 are initially there in q. In every iteration of loop sum of the two queue items is enqueued and the front item is dequeued.Quiz of this Question
sumitgumber28
Data Structures
Data Structures-Queue
Data Structures
Data Structures
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Data Structures | Linked List | Question 5
Data Structures | Tree Traversals | Question 4
Data Structures | Linked List | Question 6
Difference between Singly linked list and Doubly linked list
Advantages and Disadvantages of Linked List
Data Structures | Graph | Question 9
FIFO vs LIFO approach in Programming
C program to implement Adjacency Matrix of a given Graph
Introduction to Data Structures
Data Structures | Stack | Question 1 | [
{
"code": null,
"e": 26293,
"s": 26265,
"text": "\n28 Nov, 2021"
},
{
"code": null,
"e": 26402,
"s": 26293,
"text": "Consider the following pseudo code. Assume that IntQueue is an integer queue. What does the function fun do?"
},
{
"code": "void fun(int n){ IntQueue q = new IntQueue(); q.enqueue(0); q.enqueue(1); for (int i = 0; i < n; i++) { int a = q.dequeue(); int b = q.dequeue(); q.enqueue(b); q.enqueue(a + b); print(a); }}",
"e": 26646,
"s": 26402,
"text": null
},
{
"code": null,
"e": 27034,
"s": 26646,
"text": "(A) Prints numbers from 0 to n-1(B) Prints numbers from n-1 to 0(C) Prints first n Fibonacci numbers(D) Prints first n Fibonacci numbers in reverse order.Answer: (C)Explanation: The function prints first n Fibonacci Numbers. Note that 0 and 1 are initially there in q. In every iteration of loop sum of the two queue items is enqueued and the front item is dequeued.Quiz of this Question"
},
{
"code": null,
"e": 27048,
"s": 27034,
"text": "sumitgumber28"
},
{
"code": null,
"e": 27064,
"s": 27048,
"text": "Data Structures"
},
{
"code": null,
"e": 27086,
"s": 27064,
"text": "Data Structures-Queue"
},
{
"code": null,
"e": 27102,
"s": 27086,
"text": "Data Structures"
},
{
"code": null,
"e": 27118,
"s": 27102,
"text": "Data Structures"
},
{
"code": null,
"e": 27216,
"s": 27118,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27259,
"s": 27216,
"text": "Data Structures | Linked List | Question 5"
},
{
"code": null,
"e": 27306,
"s": 27259,
"text": "Data Structures | Tree Traversals | Question 4"
},
{
"code": null,
"e": 27349,
"s": 27306,
"text": "Data Structures | Linked List | Question 6"
},
{
"code": null,
"e": 27410,
"s": 27349,
"text": "Difference between Singly linked list and Doubly linked list"
},
{
"code": null,
"e": 27454,
"s": 27410,
"text": "Advantages and Disadvantages of Linked List"
},
{
"code": null,
"e": 27491,
"s": 27454,
"text": "Data Structures | Graph | Question 9"
},
{
"code": null,
"e": 27528,
"s": 27491,
"text": "FIFO vs LIFO approach in Programming"
},
{
"code": null,
"e": 27585,
"s": 27528,
"text": "C program to implement Adjacency Matrix of a given Graph"
},
{
"code": null,
"e": 27617,
"s": 27585,
"text": "Introduction to Data Structures"
}
] |
Remove the common nodes in two Singly Linked Lists - GeeksforGeeks | 29 Oct, 2021
Given two Linked Lists L1 and L2, the task is to generate a new linked list with no common elements from the given two linked lists.
Example:
Input: L1 = 10 -> 15 -> 5 -> 20, L2 = 8 -> 5 -> 20 -> 10 Output: 8 -> 15 Explanation: Since both the linked list has 5, 10 and 20 in common. Therefore these elements are removed and the resultant list is 8 -> 15.
Input: L1 = 0 -> 5 -> 52 -> 21, L2 = 21 -> 5 -> 0 -> 52 Output: [ ] Explanation: Since all the elements of the two given linked list are common. So the resultant linked is empty.
Approach:
For each element(say X) in the first linked list: Traverse the second linked list and check if X is present in the linked list or not.If X is not present, then insert X in the resultant linked list as it not common in both linked list.For each element(say Y) in the second linked list: Traverse the first linked list and check if Y is present in the linked list or not.If Y is not present, then insert Y in the resultant linked list as it not common in both linked list.The resultant linked list will be the required linked list with no nodes common from the given two linked list.
For each element(say X) in the first linked list: Traverse the second linked list and check if X is present in the linked list or not.If X is not present, then insert X in the resultant linked list as it not common in both linked list.
Traverse the second linked list and check if X is present in the linked list or not.
If X is not present, then insert X in the resultant linked list as it not common in both linked list.
For each element(say Y) in the second linked list: Traverse the first linked list and check if Y is present in the linked list or not.If Y is not present, then insert Y in the resultant linked list as it not common in both linked list.
Traverse the first linked list and check if Y is present in the linked list or not.
If Y is not present, then insert Y in the resultant linked list as it not common in both linked list.
The resultant linked list will be the required linked list with no nodes common from the given two linked list.
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; // Link list nodestruct Node { int data; struct Node* next;}; // Function to print the element// of the Linked Listvoid printList(struct Node* p){ if (p == NULL) { cout << "[]"; } while (p != NULL) { cout << p->data << " -> "; p = p->next; }} // Function to push the node at the// beginning of the linked listvoid push(struct Node** head_ref, int new_data){ struct Node* new_node = (struct Node*)malloc( sizeof(struct Node)); new_node->data = new_data; new_node->next = (*head_ref); (*head_ref) = new_node;} // Function to insert unique// elements in the new LLvoid traverse(struct Node** head3, struct Node* temp1, struct Node* temp2){ // Traverse the first linked list while (temp1 != NULL) { // Value of current node int val = temp1->data; struct Node* t = temp2; int x = 0; // Traverse the second list while (t != NULL) { if (t->data == val) { x = 1; break; } t = t->next; } // If element is not common // then insert it in the // resultant linked list if (x == 0) { push(head3, temp1->data); } temp1 = temp1->next; }} // Function to remove the common nodes// in two Singly Linked Listsvoid removeCommonNodes(struct Node* head1, struct Node* head2){ // Head pointer for the resultant // linked list struct Node* head3 = NULL; // Find the node common between // linked list taking head1 as // first linked list traverse(&head3, head1, head2); // Find the node common between // linked list taking head2 as // first linked list traverse(&head3, head2, head1); // Print the resultant linked list printList(head3);} // Driver codeint main(){ // First list struct Node* head1 = NULL; push(&head1, 20); push(&head1, 5); push(&head1, 15); push(&head1, 10); // Second list struct Node* head2 = NULL; push(&head2, 10); push(&head2, 20); push(&head2, 15); push(&head2, 8); // Function call removeCommonNodes(head1, head2); return 0;}
// Java program for the above approachclass GFG{ // Link list nodestatic class Node { int data; Node next;}; // Function to print the element// of the Linked Liststatic void printList(Node p){ if (p == null) { System.out.print("[]"); } while (p != null) { System.out.print(p.data+ "->"); p = p.next; }} // Function to push the node at the// beginning of the linked liststatic Node push(Node head_ref, int new_data){ Node new_node = new Node(); new_node.data = new_data; new_node.next = head_ref; head_ref = new_node; return head_ref;} // Function to insert unique// elements in the new LLstatic Node traverse(Node head3, Node temp1, Node temp2){ // Traverse the first linked list while (temp1 != null) { // Value of current node int val = temp1.data; Node t = temp2; int x = 0; // Traverse the second list while (t != null) { if (t.data == val) { x = 1; break; } t = t.next; } // If element is not common // then insert it in the // resultant linked list if (x == 0) { head3 = push(head3, temp1.data); } temp1 = temp1.next; } return head3;} // Function to remove the common nodes// in two Singly Linked Listsstatic void removeCommonNodes(Node head1, Node head2){ // Head pointer for the resultant // linked list Node head3 = null; // Find the node common between // linked list taking head1 as // first linked list head3 = traverse(head3, head1, head2); // Find the node common between // linked list taking head2 as // first linked list head3 = traverse(head3, head2, head1); // Print the resultant linked list printList(head3);} // Driver codepublic static void main(String[] args){ // First list Node head1 = new Node(); head1 = push(head1, 20); head1 = push(head1, 5); head1 = push(head1, 15); head1 = push(head1, 10); // Second list Node head2 = new Node(); head2 = push(head2, 10); head2 = push(head2, 20); head2 = push(head2, 15); head2 = push(head2, 8); // Function call removeCommonNodes(head1, head2);}} // This code is contributed by sapnasingh4991
# Python3 program for the above approach # Link list nodeclass Node: def __init__(self): self.data = 0 self.next = None # Function to print the element# of the Linked Listdef printList(p): if (p == None): print('[]', end = '') while (p != None): print(p.data, end = ' -> ') p = p.next # Function to push the node at the# beginning of the linked listdef push(head_ref, new_data): new_node = Node() new_node.data = new_data new_node.next = (head_ref) (head_ref) = new_node return head_ref # Function to insert unique# elements in the new LLdef traverse(head3, temp1, temp2): # Traverse the first linked list while (temp1 != None): # Value of current node val = temp1.data t = temp2 x = 0 # Traverse the second list while (t != None): if (t.data == val): x = 1 break t = t.next # If element is not common # then insert it in the # resultant linked list if (x == 0): head3 = push(head3, temp1.data) temp1 = temp1.next return head3 # Function to remove the common nodes# in two Singly Linked Listsdef removeCommonNodes(head1, head2): # Head pointer for the resultant # linked list head3 = None # Find the node common between # linked list taking head1 as # first linked list head3 = traverse(head3, head1, head2) # Find the node common between # linked list taking head2 as # first linked list head3 = traverse(head3, head2, head1) # Print the resultant linked list printList(head3) # Driver codeif __name__=='__main__': # First list head1 = None head1 = push(head1, 20) head1 = push(head1, 5) head1 = push(head1, 15) head1 = push(head1, 10) # Second list head2 = None head2 = push(head2, 10) head2 = push(head2, 20) head2 = push(head2, 15) head2 = push(head2, 8) # Function call removeCommonNodes(head1, head2) # This code is contributed by rutvik_56
// C# program for the above approachusing System; class GFG{ // Link list nodeclass Node { public int data; public Node next;}; // Function to print the element// of the Linked Liststatic void printList(Node p){ if (p == null) { Console.Write("[]"); } while (p != null) { Console.Write(p.data+ "->"); p = p.next; }} // Function to push the node at the// beginning of the linked liststatic Node push(Node head_ref, int new_data){ Node new_node = new Node(); new_node.data = new_data; new_node.next = head_ref; head_ref = new_node; return head_ref;} // Function to insert unique// elements in the new LLstatic Node traverse(Node head3, Node temp1, Node temp2){ // Traverse the first linked list while (temp1 != null) { // Value of current node int val = temp1.data; Node t = temp2; int x = 0; // Traverse the second list while (t != null) { if (t.data == val) { x = 1; break; } t = t.next; } // If element is not common // then insert it in the // resultant linked list if (x == 0) { head3 = push(head3, temp1.data); } temp1 = temp1.next; } return head3;} // Function to remove the common nodes// in two Singly Linked Listsstatic void removeCommonNodes(Node head1, Node head2){ // Head pointer for the resultant // linked list Node head3 = null; // Find the node common between // linked list taking head1 as // first linked list head3 = traverse(head3, head1, head2); // Find the node common between // linked list taking head2 as // first linked list head3 = traverse(head3, head2, head1); // Print the resultant linked list printList(head3);} // Driver codepublic static void Main(String[] args){ // First list Node head1 = new Node(); head1 = push(head1, 20); head1 = push(head1, 5); head1 = push(head1, 15); head1 = push(head1, 10); // Second list Node head2 = new Node(); head2 = push(head2, 10); head2 = push(head2, 20); head2 = push(head2, 15); head2 = push(head2, 8); // Function call removeCommonNodes(head1, head2);}} // This code is contributed by PrinciRaj1992
<script>// javascript program for the above approach // Link list nodeclass Node { constructor() { this.data = 0; this.next = null; }} // Function to print the element // of the Linked List function printList(p) { if (p == null) { document.write(""); } while (p != null) { document.write(p.data + "->"); p = p.next; } } // Function to push the node at the // beginning of the linked list function push(head_ref , new_data) {var new_node = new Node(); new_node.data = new_data; new_node.next = head_ref; head_ref = new_node; return head_ref; } // Function to insert unique // elements in the new LL function traverse(head3, temp1, temp2) { // Traverse the first linked list while (temp1 != null) { // Value of current node var val = temp1.data; var t = temp2; var x = 0; // Traverse the second list while (t != null) { if (t.data == val) { x = 1; break; } t = t.next; } // If element is not common // then insert it in the // resultant linked list if (x == 0) { head3 = push(head3, temp1.data); } temp1 = temp1.next; } return head3; } // Function to remove the common nodes // in two Singly Linked Lists function removeCommonNodes(head1, head2) { // Head pointer for the resultant // linked listvar head3 = null; // Find the node common between // linked list taking head1 as // first linked list head3 = traverse(head3, head1, head2); // Find the node common between // linked list taking head2 as // first linked list head3 = traverse(head3, head2, head1); // Print the resultant linked list printList(head3); } // Driver code // First listvar head1 = new Node(); head1 = push(head1, 20); head1 = push(head1, 5); head1 = push(head1, 15); head1 = push(head1, 10); // Second listvar head2 = new Node(); head2 = push(head2, 10); head2 = push(head2, 20); head2 = push(head2, 15); head2 = push(head2, 8); // Function call removeCommonNodes(head1, head2); // This code contributed by aashish1995</script>
8 -> 5 ->
Time Complexity: O(M * N), where M and N are the lengths of the two given linked list.
sapnasingh4991
princiraj1992
rutvik_56
aashish1995
khushboogoyal499
Linked List
Linked List
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Circular Linked List | Set 2 (Traversal)
Swap nodes in a linked list without swapping data
Program to implement Singly Linked List in C++ using class
Circular Singly Linked List | Insertion
Given a linked list which is sorted, how will you insert in sorted way
Real-time application of Data Structures
Delete a node in a Doubly Linked List
Linked List Implementation in C#
Insert a node at a specific position in a linked list
Insertion Sort for Singly Linked List | [
{
"code": null,
"e": 26179,
"s": 26151,
"text": "\n29 Oct, 2021"
},
{
"code": null,
"e": 26312,
"s": 26179,
"text": "Given two Linked Lists L1 and L2, the task is to generate a new linked list with no common elements from the given two linked lists."
},
{
"code": null,
"e": 26323,
"s": 26312,
"text": "Example: "
},
{
"code": null,
"e": 26536,
"s": 26323,
"text": "Input: L1 = 10 -> 15 -> 5 -> 20, L2 = 8 -> 5 -> 20 -> 10 Output: 8 -> 15 Explanation: Since both the linked list has 5, 10 and 20 in common. Therefore these elements are removed and the resultant list is 8 -> 15."
},
{
"code": null,
"e": 26716,
"s": 26536,
"text": "Input: L1 = 0 -> 5 -> 52 -> 21, L2 = 21 -> 5 -> 0 -> 52 Output: [ ] Explanation: Since all the elements of the two given linked list are common. So the resultant linked is empty. "
},
{
"code": null,
"e": 26728,
"s": 26716,
"text": "Approach: "
},
{
"code": null,
"e": 27310,
"s": 26728,
"text": "For each element(say X) in the first linked list: Traverse the second linked list and check if X is present in the linked list or not.If X is not present, then insert X in the resultant linked list as it not common in both linked list.For each element(say Y) in the second linked list: Traverse the first linked list and check if Y is present in the linked list or not.If Y is not present, then insert Y in the resultant linked list as it not common in both linked list.The resultant linked list will be the required linked list with no nodes common from the given two linked list."
},
{
"code": null,
"e": 27546,
"s": 27310,
"text": "For each element(say X) in the first linked list: Traverse the second linked list and check if X is present in the linked list or not.If X is not present, then insert X in the resultant linked list as it not common in both linked list."
},
{
"code": null,
"e": 27631,
"s": 27546,
"text": "Traverse the second linked list and check if X is present in the linked list or not."
},
{
"code": null,
"e": 27733,
"s": 27631,
"text": "If X is not present, then insert X in the resultant linked list as it not common in both linked list."
},
{
"code": null,
"e": 27969,
"s": 27733,
"text": "For each element(say Y) in the second linked list: Traverse the first linked list and check if Y is present in the linked list or not.If Y is not present, then insert Y in the resultant linked list as it not common in both linked list."
},
{
"code": null,
"e": 28053,
"s": 27969,
"text": "Traverse the first linked list and check if Y is present in the linked list or not."
},
{
"code": null,
"e": 28155,
"s": 28053,
"text": "If Y is not present, then insert Y in the resultant linked list as it not common in both linked list."
},
{
"code": null,
"e": 28267,
"s": 28155,
"text": "The resultant linked list will be the required linked list with no nodes common from the given two linked list."
},
{
"code": null,
"e": 28319,
"s": 28267,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 28323,
"s": 28319,
"text": "C++"
},
{
"code": null,
"e": 28328,
"s": 28323,
"text": "Java"
},
{
"code": null,
"e": 28336,
"s": 28328,
"text": "Python3"
},
{
"code": null,
"e": 28339,
"s": 28336,
"text": "C#"
},
{
"code": null,
"e": 28350,
"s": 28339,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Link list nodestruct Node { int data; struct Node* next;}; // Function to print the element// of the Linked Listvoid printList(struct Node* p){ if (p == NULL) { cout << \"[]\"; } while (p != NULL) { cout << p->data << \" -> \"; p = p->next; }} // Function to push the node at the// beginning of the linked listvoid push(struct Node** head_ref, int new_data){ struct Node* new_node = (struct Node*)malloc( sizeof(struct Node)); new_node->data = new_data; new_node->next = (*head_ref); (*head_ref) = new_node;} // Function to insert unique// elements in the new LLvoid traverse(struct Node** head3, struct Node* temp1, struct Node* temp2){ // Traverse the first linked list while (temp1 != NULL) { // Value of current node int val = temp1->data; struct Node* t = temp2; int x = 0; // Traverse the second list while (t != NULL) { if (t->data == val) { x = 1; break; } t = t->next; } // If element is not common // then insert it in the // resultant linked list if (x == 0) { push(head3, temp1->data); } temp1 = temp1->next; }} // Function to remove the common nodes// in two Singly Linked Listsvoid removeCommonNodes(struct Node* head1, struct Node* head2){ // Head pointer for the resultant // linked list struct Node* head3 = NULL; // Find the node common between // linked list taking head1 as // first linked list traverse(&head3, head1, head2); // Find the node common between // linked list taking head2 as // first linked list traverse(&head3, head2, head1); // Print the resultant linked list printList(head3);} // Driver codeint main(){ // First list struct Node* head1 = NULL; push(&head1, 20); push(&head1, 5); push(&head1, 15); push(&head1, 10); // Second list struct Node* head2 = NULL; push(&head2, 10); push(&head2, 20); push(&head2, 15); push(&head2, 8); // Function call removeCommonNodes(head1, head2); return 0;}",
"e": 30659,
"s": 28350,
"text": null
},
{
"code": "// Java program for the above approachclass GFG{ // Link list nodestatic class Node { int data; Node next;}; // Function to print the element// of the Linked Liststatic void printList(Node p){ if (p == null) { System.out.print(\"[]\"); } while (p != null) { System.out.print(p.data+ \"->\"); p = p.next; }} // Function to push the node at the// beginning of the linked liststatic Node push(Node head_ref, int new_data){ Node new_node = new Node(); new_node.data = new_data; new_node.next = head_ref; head_ref = new_node; return head_ref;} // Function to insert unique// elements in the new LLstatic Node traverse(Node head3, Node temp1, Node temp2){ // Traverse the first linked list while (temp1 != null) { // Value of current node int val = temp1.data; Node t = temp2; int x = 0; // Traverse the second list while (t != null) { if (t.data == val) { x = 1; break; } t = t.next; } // If element is not common // then insert it in the // resultant linked list if (x == 0) { head3 = push(head3, temp1.data); } temp1 = temp1.next; } return head3;} // Function to remove the common nodes// in two Singly Linked Listsstatic void removeCommonNodes(Node head1, Node head2){ // Head pointer for the resultant // linked list Node head3 = null; // Find the node common between // linked list taking head1 as // first linked list head3 = traverse(head3, head1, head2); // Find the node common between // linked list taking head2 as // first linked list head3 = traverse(head3, head2, head1); // Print the resultant linked list printList(head3);} // Driver codepublic static void main(String[] args){ // First list Node head1 = new Node(); head1 = push(head1, 20); head1 = push(head1, 5); head1 = push(head1, 15); head1 = push(head1, 10); // Second list Node head2 = new Node(); head2 = push(head2, 10); head2 = push(head2, 20); head2 = push(head2, 15); head2 = push(head2, 8); // Function call removeCommonNodes(head1, head2);}} // This code is contributed by sapnasingh4991",
"e": 33020,
"s": 30659,
"text": null
},
{
"code": "# Python3 program for the above approach # Link list nodeclass Node: def __init__(self): self.data = 0 self.next = None # Function to print the element# of the Linked Listdef printList(p): if (p == None): print('[]', end = '') while (p != None): print(p.data, end = ' -> ') p = p.next # Function to push the node at the# beginning of the linked listdef push(head_ref, new_data): new_node = Node() new_node.data = new_data new_node.next = (head_ref) (head_ref) = new_node return head_ref # Function to insert unique# elements in the new LLdef traverse(head3, temp1, temp2): # Traverse the first linked list while (temp1 != None): # Value of current node val = temp1.data t = temp2 x = 0 # Traverse the second list while (t != None): if (t.data == val): x = 1 break t = t.next # If element is not common # then insert it in the # resultant linked list if (x == 0): head3 = push(head3, temp1.data) temp1 = temp1.next return head3 # Function to remove the common nodes# in two Singly Linked Listsdef removeCommonNodes(head1, head2): # Head pointer for the resultant # linked list head3 = None # Find the node common between # linked list taking head1 as # first linked list head3 = traverse(head3, head1, head2) # Find the node common between # linked list taking head2 as # first linked list head3 = traverse(head3, head2, head1) # Print the resultant linked list printList(head3) # Driver codeif __name__=='__main__': # First list head1 = None head1 = push(head1, 20) head1 = push(head1, 5) head1 = push(head1, 15) head1 = push(head1, 10) # Second list head2 = None head2 = push(head2, 10) head2 = push(head2, 20) head2 = push(head2, 15) head2 = push(head2, 8) # Function call removeCommonNodes(head1, head2) # This code is contributed by rutvik_56",
"e": 35155,
"s": 33020,
"text": null
},
{
"code": "// C# program for the above approachusing System; class GFG{ // Link list nodeclass Node { public int data; public Node next;}; // Function to print the element// of the Linked Liststatic void printList(Node p){ if (p == null) { Console.Write(\"[]\"); } while (p != null) { Console.Write(p.data+ \"->\"); p = p.next; }} // Function to push the node at the// beginning of the linked liststatic Node push(Node head_ref, int new_data){ Node new_node = new Node(); new_node.data = new_data; new_node.next = head_ref; head_ref = new_node; return head_ref;} // Function to insert unique// elements in the new LLstatic Node traverse(Node head3, Node temp1, Node temp2){ // Traverse the first linked list while (temp1 != null) { // Value of current node int val = temp1.data; Node t = temp2; int x = 0; // Traverse the second list while (t != null) { if (t.data == val) { x = 1; break; } t = t.next; } // If element is not common // then insert it in the // resultant linked list if (x == 0) { head3 = push(head3, temp1.data); } temp1 = temp1.next; } return head3;} // Function to remove the common nodes// in two Singly Linked Listsstatic void removeCommonNodes(Node head1, Node head2){ // Head pointer for the resultant // linked list Node head3 = null; // Find the node common between // linked list taking head1 as // first linked list head3 = traverse(head3, head1, head2); // Find the node common between // linked list taking head2 as // first linked list head3 = traverse(head3, head2, head1); // Print the resultant linked list printList(head3);} // Driver codepublic static void Main(String[] args){ // First list Node head1 = new Node(); head1 = push(head1, 20); head1 = push(head1, 5); head1 = push(head1, 15); head1 = push(head1, 10); // Second list Node head2 = new Node(); head2 = push(head2, 10); head2 = push(head2, 20); head2 = push(head2, 15); head2 = push(head2, 8); // Function call removeCommonNodes(head1, head2);}} // This code is contributed by PrinciRaj1992",
"e": 37547,
"s": 35155,
"text": null
},
{
"code": "<script>// javascript program for the above approach // Link list nodeclass Node { constructor() { this.data = 0; this.next = null; }} // Function to print the element // of the Linked List function printList(p) { if (p == null) { document.write(\"\"); } while (p != null) { document.write(p.data + \"->\"); p = p.next; } } // Function to push the node at the // beginning of the linked list function push(head_ref , new_data) {var new_node = new Node(); new_node.data = new_data; new_node.next = head_ref; head_ref = new_node; return head_ref; } // Function to insert unique // elements in the new LL function traverse(head3, temp1, temp2) { // Traverse the first linked list while (temp1 != null) { // Value of current node var val = temp1.data; var t = temp2; var x = 0; // Traverse the second list while (t != null) { if (t.data == val) { x = 1; break; } t = t.next; } // If element is not common // then insert it in the // resultant linked list if (x == 0) { head3 = push(head3, temp1.data); } temp1 = temp1.next; } return head3; } // Function to remove the common nodes // in two Singly Linked Lists function removeCommonNodes(head1, head2) { // Head pointer for the resultant // linked listvar head3 = null; // Find the node common between // linked list taking head1 as // first linked list head3 = traverse(head3, head1, head2); // Find the node common between // linked list taking head2 as // first linked list head3 = traverse(head3, head2, head1); // Print the resultant linked list printList(head3); } // Driver code // First listvar head1 = new Node(); head1 = push(head1, 20); head1 = push(head1, 5); head1 = push(head1, 15); head1 = push(head1, 10); // Second listvar head2 = new Node(); head2 = push(head2, 10); head2 = push(head2, 20); head2 = push(head2, 15); head2 = push(head2, 8); // Function call removeCommonNodes(head1, head2); // This code contributed by aashish1995</script>",
"e": 40064,
"s": 37547,
"text": null
},
{
"code": null,
"e": 40074,
"s": 40064,
"text": "8 -> 5 ->"
},
{
"code": null,
"e": 40164,
"s": 40076,
"text": "Time Complexity: O(M * N), where M and N are the lengths of the two given linked list. "
},
{
"code": null,
"e": 40179,
"s": 40164,
"text": "sapnasingh4991"
},
{
"code": null,
"e": 40193,
"s": 40179,
"text": "princiraj1992"
},
{
"code": null,
"e": 40203,
"s": 40193,
"text": "rutvik_56"
},
{
"code": null,
"e": 40215,
"s": 40203,
"text": "aashish1995"
},
{
"code": null,
"e": 40232,
"s": 40215,
"text": "khushboogoyal499"
},
{
"code": null,
"e": 40244,
"s": 40232,
"text": "Linked List"
},
{
"code": null,
"e": 40256,
"s": 40244,
"text": "Linked List"
},
{
"code": null,
"e": 40354,
"s": 40256,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 40395,
"s": 40354,
"text": "Circular Linked List | Set 2 (Traversal)"
},
{
"code": null,
"e": 40445,
"s": 40395,
"text": "Swap nodes in a linked list without swapping data"
},
{
"code": null,
"e": 40504,
"s": 40445,
"text": "Program to implement Singly Linked List in C++ using class"
},
{
"code": null,
"e": 40544,
"s": 40504,
"text": "Circular Singly Linked List | Insertion"
},
{
"code": null,
"e": 40615,
"s": 40544,
"text": "Given a linked list which is sorted, how will you insert in sorted way"
},
{
"code": null,
"e": 40656,
"s": 40615,
"text": "Real-time application of Data Structures"
},
{
"code": null,
"e": 40694,
"s": 40656,
"text": "Delete a node in a Doubly Linked List"
},
{
"code": null,
"e": 40727,
"s": 40694,
"text": "Linked List Implementation in C#"
},
{
"code": null,
"e": 40781,
"s": 40727,
"text": "Insert a node at a specific position in a linked list"
}
] |
Python | Find Dissimilar Elements in Tuples - GeeksforGeeks | 11 Nov, 2019
Sometimes, while working with tuples, we can have a problem in which we need dissimilar features of two records. This type of application can come in Data Science domain. Let’s discuss certain ways in which this problem can be solved.
Method #1 : Using set() + "^" operator
This task can be performed using symmetric difference functionality offered by XOR operator over sets. The conversion to set is done by set().
# Python3 code to demonstrate working of# Dissimilar elements in tuples# Using set() + "^" operator # initialize tuplestest_tup1 = (3, 4, 5, 6)test_tup2 = (5, 7, 4, 10) # printing original tuplesprint("The original tuple 1 : " + str(test_tup1))print("The original tuple 2 : " + str(test_tup2)) # Dissimilar elements in tuples# Using set() + "^" operatorres = tuple(set(test_tup1) ^ set(test_tup2)) # printing resultprint("The Dissimilar elements from tuples are : " + str(res))
The original tuple 1 : (3, 4, 5, 6)
The original tuple 2 : (5, 7, 4, 10)
The Dissimilar elements from tuples are : (3, 6, 7, 10)
Method #2 : Using symmetric_difference() + set()
This is method similar to above method, the difference is that instead of XOR operator, we use inbuilt function to perform the task of filtering dissimilar elements.
# Python3 code to demonstrate working of# Dissimilar elements in tuples# Using symmetric_difference() + set() # initialize tuplestest_tup1 = (3, 4, 5, 6)test_tup2 = (5, 7, 4, 10) # printing original tuplesprint("The original tuple 1 : " + str(test_tup1))print("The original tuple 2 : " + str(test_tup2)) # Dissimilar elements in tuples# Using symmetric_difference() + set()res = tuple(set(test_tup1).symmetric_difference(set(test_tup2))) # printing resultprint("The Dissimilar elements from tuples are : " + str(res))
The original tuple 1 : (3, 4, 5, 6)
The original tuple 2 : (5, 7, 4, 10)
The Dissimilar elements from tuples are : (3, 6, 7, 10)
Python tuple-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python? | [
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n11 Nov, 2019"
},
{
"code": null,
"e": 25772,
"s": 25537,
"text": "Sometimes, while working with tuples, we can have a problem in which we need dissimilar features of two records. This type of application can come in Data Science domain. Let’s discuss certain ways in which this problem can be solved."
},
{
"code": null,
"e": 25811,
"s": 25772,
"text": "Method #1 : Using set() + \"^\" operator"
},
{
"code": null,
"e": 25954,
"s": 25811,
"text": "This task can be performed using symmetric difference functionality offered by XOR operator over sets. The conversion to set is done by set()."
},
{
"code": "# Python3 code to demonstrate working of# Dissimilar elements in tuples# Using set() + \"^\" operator # initialize tuplestest_tup1 = (3, 4, 5, 6)test_tup2 = (5, 7, 4, 10) # printing original tuplesprint(\"The original tuple 1 : \" + str(test_tup1))print(\"The original tuple 2 : \" + str(test_tup2)) # Dissimilar elements in tuples# Using set() + \"^\" operatorres = tuple(set(test_tup1) ^ set(test_tup2)) # printing resultprint(\"The Dissimilar elements from tuples are : \" + str(res))",
"e": 26436,
"s": 25954,
"text": null
},
{
"code": null,
"e": 26566,
"s": 26436,
"text": "The original tuple 1 : (3, 4, 5, 6)\nThe original tuple 2 : (5, 7, 4, 10)\nThe Dissimilar elements from tuples are : (3, 6, 7, 10)\n"
},
{
"code": null,
"e": 26617,
"s": 26568,
"text": "Method #2 : Using symmetric_difference() + set()"
},
{
"code": null,
"e": 26783,
"s": 26617,
"text": "This is method similar to above method, the difference is that instead of XOR operator, we use inbuilt function to perform the task of filtering dissimilar elements."
},
{
"code": "# Python3 code to demonstrate working of# Dissimilar elements in tuples# Using symmetric_difference() + set() # initialize tuplestest_tup1 = (3, 4, 5, 6)test_tup2 = (5, 7, 4, 10) # printing original tuplesprint(\"The original tuple 1 : \" + str(test_tup1))print(\"The original tuple 2 : \" + str(test_tup2)) # Dissimilar elements in tuples# Using symmetric_difference() + set()res = tuple(set(test_tup1).symmetric_difference(set(test_tup2))) # printing resultprint(\"The Dissimilar elements from tuples are : \" + str(res))",
"e": 27305,
"s": 26783,
"text": null
},
{
"code": null,
"e": 27435,
"s": 27305,
"text": "The original tuple 1 : (3, 4, 5, 6)\nThe original tuple 2 : (5, 7, 4, 10)\nThe Dissimilar elements from tuples are : (3, 6, 7, 10)\n"
},
{
"code": null,
"e": 27457,
"s": 27435,
"text": "Python tuple-programs"
},
{
"code": null,
"e": 27464,
"s": 27457,
"text": "Python"
},
{
"code": null,
"e": 27480,
"s": 27464,
"text": "Python Programs"
},
{
"code": null,
"e": 27578,
"s": 27480,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27610,
"s": 27578,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27652,
"s": 27610,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27694,
"s": 27652,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27750,
"s": 27694,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27777,
"s": 27750,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27799,
"s": 27777,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27838,
"s": 27799,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 27884,
"s": 27838,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 27922,
"s": 27884,
"text": "Python | Convert a list to dictionary"
}
] |
Statement, Indentation and Comment in Python - GeeksforGeeks | 09 Aug, 2021
Instructions written in the source code for execution are called statements. There are different types of statements in the Python programming language like Assignment statements, Conditional statements, Looping statements, etc. These all help the user to get the required output. For example, n = 50 is an assignment statement.Multi-Line Statements: Statements in Python can be extended to one or more lines using parentheses (), braces {}, square brackets [], semi-colon (;), continuation character slash (\). When the programmer needs to do long calculations and cannot fit his statements into one line, one can make use of these characters. Example :
Declared using Continuation Character (\):
s = 1 + 2 + 3 + \
4 + 5 + 6 + \
7 + 8 + 9
Declared using parentheses () :
n = (1 * 2 * 3 + 7 + 8 + 9)
Declared using square brackets [] :
footballer = ['MESSI',
'NEYMAR',
'SUAREZ']
Declared using braces {} :
x = {1 + 2 + 3 + 4 + 5 + 6 +
7 + 8 + 9}
Declared using semicolons(;) :
flag = 2; ropes = 3; pole = 4
A block is a combination of all these statements. Block can be regarded as the grouping of statements for a specific purpose. Most of the programming languages like C, C++, Java use braces { } to define a block of code. One of the distinctive features of Python is its use of indentation to highlighting the blocks of code. Whitespace is used for indentation in Python. All statements with the same distance to the right belong to the same block of code. If a block has to be more deeply nested, it is simply indented further to the right. You can understand it better by looking at the following lines of code:
Python3
# Python program showing# indentation site = 'gfg' if site == 'gfg': print('Logging on to geeksforgeeks...')else: print('retype the URL.')print('All set !')
Output:
Logging on to geeksforgeeks...
All set !
The lines print(‘Logging on to geeksforgeeks...’) and print(‘retype the URL.’) are two separate code blocks. The two blocks of code in our example if-statement are both indented four spaces. The final print(‘All set!’) is not indented, and so it does not belong to the else-block.
Python3
j = 1while(j<= 5): print(j) j = j + 1
Output:
1
2
3
4
5
To indicate a block of code in Python, you must indent each line of the block by the same whitespace. The two lines of code in the while loop are both indented four spaces. It is required for indicating what block of code a statement belongs to. For example, j=1 and while(j<=5): is not indented, and so it is not within the while block. So, Python code structures by indentation.
Python developers often make use of the comment system as, without the use of it, things can get real confusing, real fast. Comments are the useful information that the developers provide to make the reader understand the source code. It explains the logic or a part of it used in the code. Comments are usually helpful to someone maintaining or enhancing your code when you are no longer around to answer questions about it. These are often cited as a useful programming convention that does not take part in the output of the program but improves the readability of the whole program. There are two types of comments in Python: Single line comments: Python single line comment starts with hashtag symbol with no white spaces (#) and lasts till the end of the line. If the comment exceeds one line then put a hashtag on the next line and continue the comment. Python’s single-line comments are proved useful for supplying short explanations for variables, function declarations, and expressions. See the following code snippet demonstrating single line comment:Code 1:
Python3
# This is a comment# Print “GeeksforGeeks !” to consoleprint("GeeksforGeeks")
Code 2:
Python3
a, b = 1, 3 # Declaring two integerssum = a + b # adding two integersprint(sum) # displaying the output
Multi-line string as a comment: Python multi-line comment is a piece of text enclosed in a delimiter (“””) on each end of the comment. Again there should be no white space between delimiter (“””). They are useful when the comment text does not fit into one line; therefore need to span across lines. Multi-line comments or paragraphs serve as documentation for others reading your code. See the following code snippet demonstrating multi-line comment:Code 1:
Python3
"""This would be a multiline comment in Python thatspans several lines and describes geeksforgeeks.A Computer Science portal for geeks. It containswell written, well thoughtand well-explained computer scienceand programming articles,quizzes and more...."""print("GeeksForGeeks")
Code 2:
Python3
'''This article on geeksforgeeks gives you aperfect example ofmulti-line comments''' print("GeeksForGeeks")
ManiRamu
ddeevviissaavviittaa
Picked
python-basics
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": 42675,
"s": 42647,
"text": "\n09 Aug, 2021"
},
{
"code": null,
"e": 43332,
"s": 42675,
"text": "Instructions written in the source code for execution are called statements. There are different types of statements in the Python programming language like Assignment statements, Conditional statements, Looping statements, etc. These all help the user to get the required output. For example, n = 50 is an assignment statement.Multi-Line Statements: Statements in Python can be extended to one or more lines using parentheses (), braces {}, square brackets [], semi-colon (;), continuation character slash (\\). When the programmer needs to do long calculations and cannot fit his statements into one line, one can make use of these characters. Example : "
},
{
"code": null,
"e": 43721,
"s": 43332,
"text": "Declared using Continuation Character (\\):\ns = 1 + 2 + 3 + \\\n 4 + 5 + 6 + \\\n 7 + 8 + 9\n\nDeclared using parentheses () :\nn = (1 * 2 * 3 + 7 + 8 + 9)\n\nDeclared using square brackets [] :\nfootballer = ['MESSI',\n 'NEYMAR',\n 'SUAREZ']\n\nDeclared using braces {} :\nx = {1 + 2 + 3 + 4 + 5 + 6 +\n 7 + 8 + 9}\n\nDeclared using semicolons(;) :\nflag = 2; ropes = 3; pole = 4"
},
{
"code": null,
"e": 44336,
"s": 43723,
"text": "A block is a combination of all these statements. Block can be regarded as the grouping of statements for a specific purpose. Most of the programming languages like C, C++, Java use braces { } to define a block of code. One of the distinctive features of Python is its use of indentation to highlighting the blocks of code. Whitespace is used for indentation in Python. All statements with the same distance to the right belong to the same block of code. If a block has to be more deeply nested, it is simply indented further to the right. You can understand it better by looking at the following lines of code: "
},
{
"code": null,
"e": 44344,
"s": 44336,
"text": "Python3"
},
{
"code": "# Python program showing# indentation site = 'gfg' if site == 'gfg': print('Logging on to geeksforgeeks...')else: print('retype the URL.')print('All set !')",
"e": 44507,
"s": 44344,
"text": null
},
{
"code": null,
"e": 44517,
"s": 44507,
"text": "Output: "
},
{
"code": null,
"e": 44558,
"s": 44517,
"text": "Logging on to geeksforgeeks...\nAll set !"
},
{
"code": null,
"e": 44841,
"s": 44558,
"text": "The lines print(‘Logging on to geeksforgeeks...’) and print(‘retype the URL.’) are two separate code blocks. The two blocks of code in our example if-statement are both indented four spaces. The final print(‘All set!’) is not indented, and so it does not belong to the else-block. "
},
{
"code": null,
"e": 44849,
"s": 44841,
"text": "Python3"
},
{
"code": "j = 1while(j<= 5): print(j) j = j + 1",
"e": 44895,
"s": 44849,
"text": null
},
{
"code": null,
"e": 44905,
"s": 44895,
"text": "Output: "
},
{
"code": null,
"e": 44915,
"s": 44905,
"text": "1\n2\n3\n4\n5"
},
{
"code": null,
"e": 45297,
"s": 44915,
"text": "To indicate a block of code in Python, you must indent each line of the block by the same whitespace. The two lines of code in the while loop are both indented four spaces. It is required for indicating what block of code a statement belongs to. For example, j=1 and while(j<=5): is not indented, and so it is not within the while block. So, Python code structures by indentation. "
},
{
"code": null,
"e": 46369,
"s": 45297,
"text": "Python developers often make use of the comment system as, without the use of it, things can get real confusing, real fast. Comments are the useful information that the developers provide to make the reader understand the source code. It explains the logic or a part of it used in the code. Comments are usually helpful to someone maintaining or enhancing your code when you are no longer around to answer questions about it. These are often cited as a useful programming convention that does not take part in the output of the program but improves the readability of the whole program. There are two types of comments in Python: Single line comments: Python single line comment starts with hashtag symbol with no white spaces (#) and lasts till the end of the line. If the comment exceeds one line then put a hashtag on the next line and continue the comment. Python’s single-line comments are proved useful for supplying short explanations for variables, function declarations, and expressions. See the following code snippet demonstrating single line comment:Code 1: "
},
{
"code": null,
"e": 46377,
"s": 46369,
"text": "Python3"
},
{
"code": "# This is a comment# Print “GeeksforGeeks !” to consoleprint(\"GeeksforGeeks\")",
"e": 46455,
"s": 46377,
"text": null
},
{
"code": null,
"e": 46465,
"s": 46455,
"text": "Code 2: "
},
{
"code": null,
"e": 46473,
"s": 46465,
"text": "Python3"
},
{
"code": "a, b = 1, 3 # Declaring two integerssum = a + b # adding two integersprint(sum) # displaying the output",
"e": 46577,
"s": 46473,
"text": null
},
{
"code": null,
"e": 47038,
"s": 46577,
"text": "Multi-line string as a comment: Python multi-line comment is a piece of text enclosed in a delimiter (“””) on each end of the comment. Again there should be no white space between delimiter (“””). They are useful when the comment text does not fit into one line; therefore need to span across lines. Multi-line comments or paragraphs serve as documentation for others reading your code. See the following code snippet demonstrating multi-line comment:Code 1: "
},
{
"code": null,
"e": 47046,
"s": 47038,
"text": "Python3"
},
{
"code": "\"\"\"This would be a multiline comment in Python thatspans several lines and describes geeksforgeeks.A Computer Science portal for geeks. It containswell written, well thoughtand well-explained computer scienceand programming articles,quizzes and more....\"\"\"print(\"GeeksForGeeks\")",
"e": 47325,
"s": 47046,
"text": null
},
{
"code": null,
"e": 47335,
"s": 47325,
"text": "Code 2: "
},
{
"code": null,
"e": 47343,
"s": 47335,
"text": "Python3"
},
{
"code": "'''This article on geeksforgeeks gives you aperfect example ofmulti-line comments''' print(\"GeeksForGeeks\")",
"e": 47451,
"s": 47343,
"text": null
},
{
"code": null,
"e": 47460,
"s": 47451,
"text": "ManiRamu"
},
{
"code": null,
"e": 47481,
"s": 47460,
"text": "ddeevviissaavviittaa"
},
{
"code": null,
"e": 47488,
"s": 47481,
"text": "Picked"
},
{
"code": null,
"e": 47502,
"s": 47488,
"text": "python-basics"
},
{
"code": null,
"e": 47509,
"s": 47502,
"text": "Python"
},
{
"code": null,
"e": 47607,
"s": 47509,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 47635,
"s": 47607,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 47685,
"s": 47635,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 47707,
"s": 47685,
"text": "Python map() function"
},
{
"code": null,
"e": 47751,
"s": 47707,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 47786,
"s": 47751,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 47818,
"s": 47786,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 47840,
"s": 47818,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 47882,
"s": 47840,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 47912,
"s": 47882,
"text": "Iterate over a list in Python"
}
] |
Python | Sort Flatten list of list - GeeksforGeeks | 11 May, 2020
The flattening of list of lists has been discussed earlier, but sometimes, in addition to flattening, it is also required to get the string in a sorted manner. Let’s discuss certain ways in which this can be done.
Method #1 : Using sorted() + list comprehensionThis idea is similar to flattening a list of list but in addition to it, we add a sorted function to sort the returned flattened list done by list comprehension.
# Python3 code to demonstrate# sort flatten list of list # using sorted + list comprehension # initializing list of list test_list = [[3, 5], [7, 3, 9], [1, 12]] # printing original list of list print("The original list : " + str(test_list)) # using sorted + list comprehension# sort flatten list of listres = sorted([j for i in test_list for j in i]) # print resultprint("The sorted and flattened list : " + str(res))
The original list : [[3, 5], [7, 3, 9], [1, 12]]
The sorted and flattened list : [1, 3, 3, 5, 7, 9, 12]
Method #2 : Using itertools.chain() + sorted()The task that was done by list comprehension above can also be performed using the chain function that links elements of list and then sorted function does the task of sorting.
# Python3 code to demonstrate# sort flatten list of list # using itertools.chain() + sorted()from itertools import chain # initializing list of list test_list = [[3, 5], [7, 3, 9], [1, 12]] # printing original list of list print("The original list : " + str(test_list)) # using itertools.chain() + sorted()# sort flatten list of listres = sorted(chain(*test_list)) # print resultprint("The sorted and flattened list : " + str(res))
The original list : [[3, 5], [7, 3, 9], [1, 12]]
The sorted and flattened list : [1, 3, 3, 5, 7, 9, 12]
Python list-programs
Python-list-of-lists
Python-sort
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python? | [
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n11 May, 2020"
},
{
"code": null,
"e": 25751,
"s": 25537,
"text": "The flattening of list of lists has been discussed earlier, but sometimes, in addition to flattening, it is also required to get the string in a sorted manner. Let’s discuss certain ways in which this can be done."
},
{
"code": null,
"e": 25960,
"s": 25751,
"text": "Method #1 : Using sorted() + list comprehensionThis idea is similar to flattening a list of list but in addition to it, we add a sorted function to sort the returned flattened list done by list comprehension."
},
{
"code": "# Python3 code to demonstrate# sort flatten list of list # using sorted + list comprehension # initializing list of list test_list = [[3, 5], [7, 3, 9], [1, 12]] # printing original list of list print(\"The original list : \" + str(test_list)) # using sorted + list comprehension# sort flatten list of listres = sorted([j for i in test_list for j in i]) # print resultprint(\"The sorted and flattened list : \" + str(res))",
"e": 26383,
"s": 25960,
"text": null
},
{
"code": null,
"e": 26488,
"s": 26383,
"text": "The original list : [[3, 5], [7, 3, 9], [1, 12]]\nThe sorted and flattened list : [1, 3, 3, 5, 7, 9, 12]\n"
},
{
"code": null,
"e": 26713,
"s": 26490,
"text": "Method #2 : Using itertools.chain() + sorted()The task that was done by list comprehension above can also be performed using the chain function that links elements of list and then sorted function does the task of sorting."
},
{
"code": "# Python3 code to demonstrate# sort flatten list of list # using itertools.chain() + sorted()from itertools import chain # initializing list of list test_list = [[3, 5], [7, 3, 9], [1, 12]] # printing original list of list print(\"The original list : \" + str(test_list)) # using itertools.chain() + sorted()# sort flatten list of listres = sorted(chain(*test_list)) # print resultprint(\"The sorted and flattened list : \" + str(res))",
"e": 27149,
"s": 26713,
"text": null
},
{
"code": null,
"e": 27254,
"s": 27149,
"text": "The original list : [[3, 5], [7, 3, 9], [1, 12]]\nThe sorted and flattened list : [1, 3, 3, 5, 7, 9, 12]\n"
},
{
"code": null,
"e": 27275,
"s": 27254,
"text": "Python list-programs"
},
{
"code": null,
"e": 27296,
"s": 27275,
"text": "Python-list-of-lists"
},
{
"code": null,
"e": 27308,
"s": 27296,
"text": "Python-sort"
},
{
"code": null,
"e": 27315,
"s": 27308,
"text": "Python"
},
{
"code": null,
"e": 27331,
"s": 27315,
"text": "Python Programs"
},
{
"code": null,
"e": 27429,
"s": 27331,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27461,
"s": 27429,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27503,
"s": 27461,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27545,
"s": 27503,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27601,
"s": 27545,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27628,
"s": 27601,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27650,
"s": 27628,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27689,
"s": 27650,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 27735,
"s": 27689,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 27773,
"s": 27735,
"text": "Python | Convert a list to dictionary"
}
] |
Java Program to Find Sum of N Numbers Using Recursion - GeeksforGeeks | 26 May, 2021
Recursion is a process by which a function calls itself repeatedly till it falls under the base condition and our motive is achieved.
To solve any problem using recursion, we should simply follow the below steps:
Assume/Identify the smaller problem from the problem which is similar to the bigger/original problem.Decide the answer to the smallest valid input or smallest invalid input which would act as our base condition.Approach the solution and link the answer to the smaller problem given by the recursive function to find the answer to the bigger/original problem using it.
Assume/Identify the smaller problem from the problem which is similar to the bigger/original problem.
Decide the answer to the smallest valid input or smallest invalid input which would act as our base condition.
Approach the solution and link the answer to the smaller problem given by the recursive function to find the answer to the bigger/original problem using it.
Here, we are illustrating the total Sum using recursion can be done using storing numbers in an array, and taking the summation of all the numbers using recursion.
Example
Input: N = 5, arr[] = {70, 60, 90, 40, 80}
Output: Total Sum = 340
Input: N = 8, arr[] = {8, 7, 6, 5, 4, 3, 2, 1}
Output: Total Sum = 36
Approach:
Now, we will apply the approach discussed above in this question to calculate the sum of all elements recursively.
Smaller problem will be the array from index 1 to last index.
Base condition will be when the index will reach the length of the array.ie out of the array that means that no element exist so the sum returned should be 0.
Now, our task is to solve the bigger/ original problem using the result calculated by smaller problem. So, to do that as we know smaller problem is from index1 to last index , so if we get the sum of this problem then after that for the whole sum of array we just need to add the first element / ith element to that answer and return our final answer.
Below is the implementation of the above approach.
Example:
Java
// Java program to calculate the sum of// the elements of the array recursively import java.io.*; class GFG { // recursive function public static int calculate_sum_using_recursion(int arr[], int i, int length) { // base condition - when reached end of the array // return 0 if (i == length) { return 0; } // recursive condition - current element + sum of // (n-1) elements return arr[i] + calculate_sum_using_recursion(arr, i + 1,length); } public static void main(String[] args) { int N = 5, total_sum = 0; // create 1-D array to store numbers int arr[] = { 89, 75, 82, 60, 95 }; // call function to calculate sum total_sum = calculate_sum_using_recursion(arr, 0, N); // print total sum System.out.println("The total of N numbers is : " + total_sum); }}
The total of N numbers is : 401
Approach 2:
We can apply recursion by not just one way but there can be one or more than one ways to solve a single problem using recursion.
In the above approach, we started recursion from forward direction and reached and hit the base condition at the end/last position.
In this approach, we will consider the length variable in the function as the changing parameter, where length variable will start from the last position and the base case will hit reaching to the front out of bound index which is -1.
Example:
Java
// Java program to calculate the sum of// the elements of array using recursion import java.io.*; class GFG { // recursive function public static int calculate_sum_using_recursion(int arr[], int length) { // base condition - when reached -1 index // return 0 if (length == -1) { return 0; } // recursive condition - current element + sum of // (n-1) elements return arr[length] + calculate_sum_using_recursion(arr,length - 1); } public static void main(String[] args) { int N = 8, total_sum = 0; // create 1-D array to store numbers int arr[] = { 8, 7, 6, 5, 4, 3, 2, 1 }; // call function to calculate sum total_sum = calculate_sum_using_recursion(arr, N - 1); // print total sum System.out.println("The total of N numbers is : " + total_sum); }}
The total of N numbers is : 36
clintra
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
Program to print ASCII Value of a character | [
{
"code": null,
"e": 25225,
"s": 25197,
"text": "\n26 May, 2021"
},
{
"code": null,
"e": 25359,
"s": 25225,
"text": "Recursion is a process by which a function calls itself repeatedly till it falls under the base condition and our motive is achieved."
},
{
"code": null,
"e": 25438,
"s": 25359,
"text": "To solve any problem using recursion, we should simply follow the below steps:"
},
{
"code": null,
"e": 25806,
"s": 25438,
"text": "Assume/Identify the smaller problem from the problem which is similar to the bigger/original problem.Decide the answer to the smallest valid input or smallest invalid input which would act as our base condition.Approach the solution and link the answer to the smaller problem given by the recursive function to find the answer to the bigger/original problem using it."
},
{
"code": null,
"e": 25908,
"s": 25806,
"text": "Assume/Identify the smaller problem from the problem which is similar to the bigger/original problem."
},
{
"code": null,
"e": 26019,
"s": 25908,
"text": "Decide the answer to the smallest valid input or smallest invalid input which would act as our base condition."
},
{
"code": null,
"e": 26176,
"s": 26019,
"text": "Approach the solution and link the answer to the smaller problem given by the recursive function to find the answer to the bigger/original problem using it."
},
{
"code": null,
"e": 26340,
"s": 26176,
"text": "Here, we are illustrating the total Sum using recursion can be done using storing numbers in an array, and taking the summation of all the numbers using recursion."
},
{
"code": null,
"e": 26348,
"s": 26340,
"text": "Example"
},
{
"code": null,
"e": 26486,
"s": 26348,
"text": "Input: N = 5, arr[] = {70, 60, 90, 40, 80}\nOutput: Total Sum = 340\n\nInput: N = 8, arr[] = {8, 7, 6, 5, 4, 3, 2, 1}\nOutput: Total Sum = 36"
},
{
"code": null,
"e": 26496,
"s": 26486,
"text": "Approach:"
},
{
"code": null,
"e": 26611,
"s": 26496,
"text": "Now, we will apply the approach discussed above in this question to calculate the sum of all elements recursively."
},
{
"code": null,
"e": 26673,
"s": 26611,
"text": "Smaller problem will be the array from index 1 to last index."
},
{
"code": null,
"e": 26832,
"s": 26673,
"text": "Base condition will be when the index will reach the length of the array.ie out of the array that means that no element exist so the sum returned should be 0."
},
{
"code": null,
"e": 27184,
"s": 26832,
"text": "Now, our task is to solve the bigger/ original problem using the result calculated by smaller problem. So, to do that as we know smaller problem is from index1 to last index , so if we get the sum of this problem then after that for the whole sum of array we just need to add the first element / ith element to that answer and return our final answer."
},
{
"code": null,
"e": 27235,
"s": 27184,
"text": "Below is the implementation of the above approach."
},
{
"code": null,
"e": 27245,
"s": 27235,
"text": "Example: "
},
{
"code": null,
"e": 27250,
"s": 27245,
"text": "Java"
},
{
"code": "// Java program to calculate the sum of// the elements of the array recursively import java.io.*; class GFG { // recursive function public static int calculate_sum_using_recursion(int arr[], int i, int length) { // base condition - when reached end of the array // return 0 if (i == length) { return 0; } // recursive condition - current element + sum of // (n-1) elements return arr[i] + calculate_sum_using_recursion(arr, i + 1,length); } public static void main(String[] args) { int N = 5, total_sum = 0; // create 1-D array to store numbers int arr[] = { 89, 75, 82, 60, 95 }; // call function to calculate sum total_sum = calculate_sum_using_recursion(arr, 0, N); // print total sum System.out.println(\"The total of N numbers is : \" + total_sum); }}",
"e": 28252,
"s": 27250,
"text": null
},
{
"code": null,
"e": 28287,
"s": 28255,
"text": "The total of N numbers is : 401"
},
{
"code": null,
"e": 28302,
"s": 28289,
"text": "Approach 2: "
},
{
"code": null,
"e": 28433,
"s": 28304,
"text": "We can apply recursion by not just one way but there can be one or more than one ways to solve a single problem using recursion."
},
{
"code": null,
"e": 28567,
"s": 28435,
"text": "In the above approach, we started recursion from forward direction and reached and hit the base condition at the end/last position."
},
{
"code": null,
"e": 28804,
"s": 28569,
"text": "In this approach, we will consider the length variable in the function as the changing parameter, where length variable will start from the last position and the base case will hit reaching to the front out of bound index which is -1."
},
{
"code": null,
"e": 28815,
"s": 28806,
"text": "Example:"
},
{
"code": null,
"e": 28822,
"s": 28817,
"text": "Java"
},
{
"code": "// Java program to calculate the sum of// the elements of array using recursion import java.io.*; class GFG { // recursive function public static int calculate_sum_using_recursion(int arr[], int length) { // base condition - when reached -1 index // return 0 if (length == -1) { return 0; } // recursive condition - current element + sum of // (n-1) elements return arr[length] + calculate_sum_using_recursion(arr,length - 1); } public static void main(String[] args) { int N = 8, total_sum = 0; // create 1-D array to store numbers int arr[] = { 8, 7, 6, 5, 4, 3, 2, 1 }; // call function to calculate sum total_sum = calculate_sum_using_recursion(arr, N - 1); // print total sum System.out.println(\"The total of N numbers is : \" + total_sum); }}",
"e": 29776,
"s": 28822,
"text": null
},
{
"code": null,
"e": 29810,
"s": 29779,
"text": "The total of N numbers is : 36"
},
{
"code": null,
"e": 29820,
"s": 29812,
"text": "clintra"
},
{
"code": null,
"e": 29827,
"s": 29820,
"text": "Picked"
},
{
"code": null,
"e": 29832,
"s": 29827,
"text": "Java"
},
{
"code": null,
"e": 29846,
"s": 29832,
"text": "Java Programs"
},
{
"code": null,
"e": 29851,
"s": 29846,
"text": "Java"
},
{
"code": null,
"e": 29949,
"s": 29851,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29964,
"s": 29949,
"text": "Stream In Java"
},
{
"code": null,
"e": 29985,
"s": 29964,
"text": "Constructors in Java"
},
{
"code": null,
"e": 30004,
"s": 29985,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 30034,
"s": 30004,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 30080,
"s": 30034,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 30106,
"s": 30080,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 30140,
"s": 30106,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 30187,
"s": 30140,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 30219,
"s": 30187,
"text": "How to Iterate HashMap in Java?"
}
] |
How To Make Ridgeline plot in Python with Seaborn? - GeeksforGeeks | 12 Nov, 2020
Prerequisite: Seaborn
Ridgeline plot is a set of overlapped density plots that help in comparing multiple distributions among datasets. The Ridgeline plots look like a mountain range, they can be quite useful for visualizing changes in distributions over time or space. Sometimes it is also known as “joyplot”, in reference to the iconic cover art for Joy Division’s album Unknown Pleasures. In this article, We will see how to generate Ridgeline plots for the dataset.
Like any another python library, seaborn can be easily installed using pip:
pip install seaborn
This library is a part of Anaconda distribution and usually works just by import if your IDE is supported by Anaconda, but it can be installed too by the following command:
conda install seaborn
Load the packages required to generate the Ridgeline plot with Python.
Read the Dataset. In this example, we use the read_csv() method to load the dataset. In the given example we will only display the top 5 entries using the head() method.
Generate RidgePlot. The Ridgeline Plot uses faceting meaning it creates small multiples, in a single column. To generate Ridgeline Plot Seaborn uses FacetGrid() method and all required information should be passed to it
Syntax: seaborn.FacetGrid(data, row, col, hue, palette, aspect, height)
Parameters:
data: Tidy (“long-form”) dataframe where each column is a variable and each row is an observation.row, col, hue: Variables that define subsets of the data, which will be drawn on separate facets in the grid.height: Height (in inches) of each facet.aspect: Aspect ratio of each facet, so that aspect * height gives the width of each facet in inches.palette: Colors to use for the different levels of the hue variable.
data: Tidy (“long-form”) dataframe where each column is a variable and each row is an observation.
row, col, hue: Variables that define subsets of the data, which will be drawn on separate facets in the grid.
height: Height (in inches) of each facet.
aspect: Aspect ratio of each facet, so that aspect * height gives the width of each facet in inches.
palette: Colors to use for the different levels of the hue variable.
Use the map() method to creates a density plot in each element of the grid. In this example, we need a density plot so use kdeplot() method which available in Seaborn.
Sample Database: Dataset used in the following example is downloaded from kaggle.com. The following link can be used for the same.
Database: titanic_train.csv
Example:
Python3
import seaborn as snsimport matplotlib.pyplot as pltimport pandas as pdfrom sklearn import preprocessing df = pd.read_csv("titanic_train.csv")df.dropna() le = preprocessing.LabelEncoder()df["Sex"] = le.fit_transform(df["Sex"]) rp = sns.FacetGrid(df, row="Sex", hue="Sex", aspect=5, height=1.25) rp.map(sns.kdeplot, 'Survived', clip_on=False, shade=True, alpha=0.7, lw=4, bw=.2) rp.map(plt.axhline, y=0, lw=4, clip_on=False)
Output :
Python-Seaborn
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n12 Nov, 2020"
},
{
"code": null,
"e": 25559,
"s": 25537,
"text": "Prerequisite: Seaborn"
},
{
"code": null,
"e": 26008,
"s": 25559,
"text": "Ridgeline plot is a set of overlapped density plots that help in comparing multiple distributions among datasets. The Ridgeline plots look like a mountain range, they can be quite useful for visualizing changes in distributions over time or space. Sometimes it is also known as “joyplot”, in reference to the iconic cover art for Joy Division’s album Unknown Pleasures. In this article, We will see how to generate Ridgeline plots for the dataset. "
},
{
"code": null,
"e": 26084,
"s": 26008,
"text": "Like any another python library, seaborn can be easily installed using pip:"
},
{
"code": null,
"e": 26105,
"s": 26084,
"text": "pip install seaborn\n"
},
{
"code": null,
"e": 26278,
"s": 26105,
"text": "This library is a part of Anaconda distribution and usually works just by import if your IDE is supported by Anaconda, but it can be installed too by the following command:"
},
{
"code": null,
"e": 26301,
"s": 26278,
"text": "conda install seaborn\n"
},
{
"code": null,
"e": 26372,
"s": 26301,
"text": "Load the packages required to generate the Ridgeline plot with Python."
},
{
"code": null,
"e": 26542,
"s": 26372,
"text": "Read the Dataset. In this example, we use the read_csv() method to load the dataset. In the given example we will only display the top 5 entries using the head() method."
},
{
"code": null,
"e": 26762,
"s": 26542,
"text": "Generate RidgePlot. The Ridgeline Plot uses faceting meaning it creates small multiples, in a single column. To generate Ridgeline Plot Seaborn uses FacetGrid() method and all required information should be passed to it"
},
{
"code": null,
"e": 26834,
"s": 26762,
"text": "Syntax: seaborn.FacetGrid(data, row, col, hue, palette, aspect, height)"
},
{
"code": null,
"e": 26846,
"s": 26834,
"text": "Parameters:"
},
{
"code": null,
"e": 27263,
"s": 26846,
"text": "data: Tidy (“long-form”) dataframe where each column is a variable and each row is an observation.row, col, hue: Variables that define subsets of the data, which will be drawn on separate facets in the grid.height: Height (in inches) of each facet.aspect: Aspect ratio of each facet, so that aspect * height gives the width of each facet in inches.palette: Colors to use for the different levels of the hue variable."
},
{
"code": null,
"e": 27362,
"s": 27263,
"text": "data: Tidy (“long-form”) dataframe where each column is a variable and each row is an observation."
},
{
"code": null,
"e": 27472,
"s": 27362,
"text": "row, col, hue: Variables that define subsets of the data, which will be drawn on separate facets in the grid."
},
{
"code": null,
"e": 27514,
"s": 27472,
"text": "height: Height (in inches) of each facet."
},
{
"code": null,
"e": 27615,
"s": 27514,
"text": "aspect: Aspect ratio of each facet, so that aspect * height gives the width of each facet in inches."
},
{
"code": null,
"e": 27684,
"s": 27615,
"text": "palette: Colors to use for the different levels of the hue variable."
},
{
"code": null,
"e": 27853,
"s": 27684,
"text": "Use the map() method to creates a density plot in each element of the grid. In this example, we need a density plot so use kdeplot() method which available in Seaborn. "
},
{
"code": null,
"e": 27984,
"s": 27853,
"text": "Sample Database: Dataset used in the following example is downloaded from kaggle.com. The following link can be used for the same."
},
{
"code": null,
"e": 28012,
"s": 27984,
"text": "Database: titanic_train.csv"
},
{
"code": null,
"e": 28022,
"s": 28012,
"text": " Example:"
},
{
"code": null,
"e": 28030,
"s": 28022,
"text": "Python3"
},
{
"code": "import seaborn as snsimport matplotlib.pyplot as pltimport pandas as pdfrom sklearn import preprocessing df = pd.read_csv(\"titanic_train.csv\")df.dropna() le = preprocessing.LabelEncoder()df[\"Sex\"] = le.fit_transform(df[\"Sex\"]) rp = sns.FacetGrid(df, row=\"Sex\", hue=\"Sex\", aspect=5, height=1.25) rp.map(sns.kdeplot, 'Survived', clip_on=False, shade=True, alpha=0.7, lw=4, bw=.2) rp.map(plt.axhline, y=0, lw=4, clip_on=False)",
"e": 28467,
"s": 28030,
"text": null
},
{
"code": null,
"e": 28476,
"s": 28467,
"text": "Output :"
},
{
"code": null,
"e": 28491,
"s": 28476,
"text": "Python-Seaborn"
},
{
"code": null,
"e": 28498,
"s": 28491,
"text": "Python"
},
{
"code": null,
"e": 28596,
"s": 28498,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28628,
"s": 28596,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28670,
"s": 28628,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28712,
"s": 28670,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28739,
"s": 28712,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 28795,
"s": 28739,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28834,
"s": 28795,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 28856,
"s": 28834,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28887,
"s": 28856,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 28916,
"s": 28887,
"text": "Create a directory in Python"
}
] |
Mongoose | deleteOne() Function - GeeksforGeeks | 20 May, 2020
The deleteOne() function is used to delete the first document that matches the conditions from the collection. It behaves like the remove() function but deletes at most one document regardless of the single option.
Installation of mongoose module:
You can visit the link to Install mongoose module. You can install this package by using this command.npm install mongooseAfter installing mongoose module, you can check your mongoose version in command prompt using the command.npm version mongooseAfter that, you can just create a folder and add a file, for example index.js. To run this file you need to run the following command.node index.js
You can visit the link to Install mongoose module. You can install this package by using this command.npm install mongoose
npm install mongoose
After installing mongoose module, you can check your mongoose version in command prompt using the command.npm version mongoose
npm version mongoose
After that, you can just create a folder and add a file, for example index.js. To run this file you need to run the following command.node index.js
node index.js
Filename: index.js
const mongoose = require('mongoose'); // Database connectionmongoose.connect('mongodb://127.0.0.1:27017/geeksforgeeks', { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true}); // User modelconst User = mongoose.model('User', { name: { type: String }, age: { type: Number }}); // Function call// Delete first document that matches// the condition i.e age >= 10User.deleteOne({ age: { $gte: 10 } }).then(function(){ console.log("Data deleted"); // Success}).catch(function(error){ console.log(error); // Failure});
Steps to run the program:
The project structure will look like this:Make sure you have installed mongoose module using following command:npm install mongooseBelow is the sample data in the database before the deleteOne() function is executed, You can use any GUI tool or terminal to see the database, like we have used Robo3T GUI tool as shown below:Run index.js file using below command:node index.jsAfter running above command, your can see the data is deleted from the database.
The project structure will look like this:
Make sure you have installed mongoose module using following command:npm install mongoose
npm install mongoose
Below is the sample data in the database before the deleteOne() function is executed, You can use any GUI tool or terminal to see the database, like we have used Robo3T GUI tool as shown below:
Run index.js file using below command:node index.js
node index.js
After running above command, your can see the data is deleted from the database.
So this is how you can use the mongoose deleteOne() function to delete the first document that matches the condition from the collection in MongoDB and Node.js.
Mongoose
MongoDB
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Spring Boot JpaRepository with Example
Aggregation in MongoDB
Mongoose Populate() Method
MongoDB - Check the existence of the fields in the specified collection
How to build a basic CRUD app with Node.js and ReactJS ?
Installation of Node.js on Linux
How to update Node.js and NPM to next version ?
Node.js fs.readFileSync() Method
Node.js fs.writeFile() Method
Node.js fs.readFile() Method | [
{
"code": null,
"e": 25373,
"s": 25345,
"text": "\n20 May, 2020"
},
{
"code": null,
"e": 25588,
"s": 25373,
"text": "The deleteOne() function is used to delete the first document that matches the conditions from the collection. It behaves like the remove() function but deletes at most one document regardless of the single option."
},
{
"code": null,
"e": 25621,
"s": 25588,
"text": "Installation of mongoose module:"
},
{
"code": null,
"e": 26017,
"s": 25621,
"text": "You can visit the link to Install mongoose module. You can install this package by using this command.npm install mongooseAfter installing mongoose module, you can check your mongoose version in command prompt using the command.npm version mongooseAfter that, you can just create a folder and add a file, for example index.js. To run this file you need to run the following command.node index.js"
},
{
"code": null,
"e": 26140,
"s": 26017,
"text": "You can visit the link to Install mongoose module. You can install this package by using this command.npm install mongoose"
},
{
"code": null,
"e": 26161,
"s": 26140,
"text": "npm install mongoose"
},
{
"code": null,
"e": 26288,
"s": 26161,
"text": "After installing mongoose module, you can check your mongoose version in command prompt using the command.npm version mongoose"
},
{
"code": null,
"e": 26309,
"s": 26288,
"text": "npm version mongoose"
},
{
"code": null,
"e": 26457,
"s": 26309,
"text": "After that, you can just create a folder and add a file, for example index.js. To run this file you need to run the following command.node index.js"
},
{
"code": null,
"e": 26471,
"s": 26457,
"text": "node index.js"
},
{
"code": null,
"e": 26490,
"s": 26471,
"text": "Filename: index.js"
},
{
"code": "const mongoose = require('mongoose'); // Database connectionmongoose.connect('mongodb://127.0.0.1:27017/geeksforgeeks', { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true}); // User modelconst User = mongoose.model('User', { name: { type: String }, age: { type: Number }}); // Function call// Delete first document that matches// the condition i.e age >= 10User.deleteOne({ age: { $gte: 10 } }).then(function(){ console.log(\"Data deleted\"); // Success}).catch(function(error){ console.log(error); // Failure});",
"e": 27046,
"s": 26490,
"text": null
},
{
"code": null,
"e": 27072,
"s": 27046,
"text": "Steps to run the program:"
},
{
"code": null,
"e": 27528,
"s": 27072,
"text": "The project structure will look like this:Make sure you have installed mongoose module using following command:npm install mongooseBelow is the sample data in the database before the deleteOne() function is executed, You can use any GUI tool or terminal to see the database, like we have used Robo3T GUI tool as shown below:Run index.js file using below command:node index.jsAfter running above command, your can see the data is deleted from the database."
},
{
"code": null,
"e": 27571,
"s": 27528,
"text": "The project structure will look like this:"
},
{
"code": null,
"e": 27661,
"s": 27571,
"text": "Make sure you have installed mongoose module using following command:npm install mongoose"
},
{
"code": null,
"e": 27682,
"s": 27661,
"text": "npm install mongoose"
},
{
"code": null,
"e": 27876,
"s": 27682,
"text": "Below is the sample data in the database before the deleteOne() function is executed, You can use any GUI tool or terminal to see the database, like we have used Robo3T GUI tool as shown below:"
},
{
"code": null,
"e": 27928,
"s": 27876,
"text": "Run index.js file using below command:node index.js"
},
{
"code": null,
"e": 27942,
"s": 27928,
"text": "node index.js"
},
{
"code": null,
"e": 28023,
"s": 27942,
"text": "After running above command, your can see the data is deleted from the database."
},
{
"code": null,
"e": 28184,
"s": 28023,
"text": "So this is how you can use the mongoose deleteOne() function to delete the first document that matches the condition from the collection in MongoDB and Node.js."
},
{
"code": null,
"e": 28193,
"s": 28184,
"text": "Mongoose"
},
{
"code": null,
"e": 28201,
"s": 28193,
"text": "MongoDB"
},
{
"code": null,
"e": 28209,
"s": 28201,
"text": "Node.js"
},
{
"code": null,
"e": 28226,
"s": 28209,
"text": "Web Technologies"
},
{
"code": null,
"e": 28324,
"s": 28226,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28363,
"s": 28324,
"text": "Spring Boot JpaRepository with Example"
},
{
"code": null,
"e": 28386,
"s": 28363,
"text": "Aggregation in MongoDB"
},
{
"code": null,
"e": 28413,
"s": 28386,
"text": "Mongoose Populate() Method"
},
{
"code": null,
"e": 28485,
"s": 28413,
"text": "MongoDB - Check the existence of the fields in the specified collection"
},
{
"code": null,
"e": 28542,
"s": 28485,
"text": "How to build a basic CRUD app with Node.js and ReactJS ?"
},
{
"code": null,
"e": 28575,
"s": 28542,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28623,
"s": 28575,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 28656,
"s": 28623,
"text": "Node.js fs.readFileSync() Method"
},
{
"code": null,
"e": 28686,
"s": 28656,
"text": "Node.js fs.writeFile() Method"
}
] |
How to Build a Restaurant Recommendation System Using Latent Factor Collaborative Filtering | by Theo Jeremiah | Towards Data Science | I usually watch youtube when I am taking a break from my work. I commit to myself to watch Youtube only for 5 to 10 minutes to rest my mind. Here is what usually happens, after I finished watching one video, the next video pops out from Youtube recommendations and I click on that video. When I take a look again at my watch, it turns out that I have been watching Youtube for more than an hour! :’)
Youtube’s recommendation system is one of the most powerful and complex recommendation systems that can keep its users to watch Youtube videos for hours. Many startups giants like Netflix, Youtube, and Amazon revenues are driven mostly from the recommendation systems that they build.
This article focuses on how to build a restaurant recommendation system using latent factor collaborative filtering from scratch.
Recommender Systems or Recommendation Systems are simple algorithms that aim to provide the most relevant and accurate items (products, movies, events, articles) to the user (customers, visitors, app users, readers) by filtering useful stuff from a huge pool of information base. Recommendation engines discover data patterns in the data set by learning consumers’ choices and produces the outcomes that co-relates to their needs and interests.
Imagine a physical clothing store. The good merchant knows the personal preferences of customers. Her/His high-quality recommendations make customers satisfied and increase profits. In the case of picking a restaurant to have lunch or dinner when you are traveling to other countries or cities, commonly you will ask your friend that lives in that country or city what is the best restaurant in town. The problem is you don’t have any friends that lived in that town. Your personal recommendations can be generated by an artificial friend: the recommender system.
There are various types of Recommendation systems but for this restaurant recommendation system that I build. I focused on using Matrix Factorization or Latent Factor Collaborative Filtering. Let’s start with the term Factorization.
When we think about factorization, it is a similar concept as six times four equals twenty-four. Twenty-four is a large number but we express it as a product of two small numbers six and four, so we manage to break down a big number into a product of two small ones. This similar concept is applied to Matrix Factorization.
A Recommendation System is an information filtering system that seeks to predict the rating a user would give for the item (in this case a restaurant). We can break down the large matrix of ratings from users and items into two smaller matrixes of user-feature and item-feature. For example, user A loves to eat hotdogs but hates to eat pizza and restaurant P have great hotdogs, we multiply the matrixes using dot product and the result will be the ratings (in the example above will be 11).
Let’s start building a Restaurant Recommendation System using the techniques discussed above which should be capable of recommending restaurants that best suits you.
We will use Yelp restaurant data that can be downloaded from here.
Yelp is a business directory service and crowd-sourced review forum. The company develops, hosts and markets the Yelp.com website and the Yelp mobile app, which publish crowd-sourced reviews about businesses. It also operates an online reservation service called Yelp Reservations.
Yelp attempted to solve the problem “What should I eat?” This quickly expanded to include other business to answer other questions. This can best be represented as “I’m in [town]. Where can I go to get the [best/fastest/cheapest/easiest] [food/service/etc]?” Your friend’s recommendations are likely the largest influencer of where you will go if you have no preference. Yelp provided a service for when that was either not available or not trusted.
Let’s start by importing all the packages that we needed throughout the notebook.
import numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport seaborn as snsfrom sklearn.model_selection import train_test_splitfrom sklearn.feature_extraction.text import TfidfVectorizerfrom nltk.corpus import stopwords from nltk.tokenize import WordPunctTokenizer
Now we import the dataset, we use the review dataset and business dataset.
df = pd.read_csv('yelp_review_arizona.csv')df_business = pd.read_csv('yelp_business.csv')df.head()
We need to clean up the text first, we need to remove all the punctuations and remove all the stopwords(repetitive words that we do not need such as have, do, I, you, he, etc). We are using the library from nltk.corpus for the stopwords.
We select only the stars and text for our data and we import the library that we will use.
#Select only stars and textyelp_data = df[['business_id', 'user_id', 'stars', 'text']]import stringfrom nltk.corpus import stopwordsstop = []for word in stopwords.words('english'): s = [char for char in word if char not in string.punctuation] stop.append(''.join(s))
Now let’s clean the text by creating a function.
def text_process(mess): """ Takes in a string of text, then performs the following: 1. Remove all punctuation 2. Remove all stopwords 3. Returns a list of the cleaned text """ # Check characters to see if they are in punctuation nopunc = [char for char in mess if char not in string.punctuation]# Join the characters again to form the string. nopunc = ''.join(nopunc) # Now just remove any stopwords return " ".join([word for word in nopunc.split() if word.lower() not in stop])yelp_data['text'] = yelp_data['text'].apply(text_process)
In order to use the text for the matrix factorization recommendation system, we will follow the architecture below to extract the features from the review text.
For each user, combine all the reviews to form a single paragraph, after we combine it all then we apply the TFIDF Vectorizer to extract the features from the text. The similar approach for each restaurant and we need to give the max_feature to match the dimensions of the matrixes.
userid_df = yelp_data[['user_id','text']]business_df = yelp_data[['business_id', 'text']]
userid_df = userid_df.groupby('user_id').agg({'text': ' '.join})business_df = business_df.groupby('business_id').agg({'text': ' '.join})
Now we apply the TFIDF Vectorizer to extract the features from the text.
from sklearn.feature_extraction.text import TfidfVectorizer#userid vectorizeruserid_vectorizer = TfidfVectorizer(tokenizer = WordPunctTokenizer().tokenize, max_features=5000)userid_vectors = userid_vectorizer.fit_transform(userid_df['text'])#Business id vectorizerbusinessid_vectorizer = TfidfVectorizer(tokenizer = WordPunctTokenizer().tokenize, max_features=5000)businessid_vectors = businessid_vectorizer.fit_transform(business_df['text'])
Then, we create a matrix of users and businesses with the ratings.
userid_rating_matrix = pd.pivot_table(yelp_data, values='stars', index=['user_id'], columns=['business_id'])
Let’s go back to the type of recommendation systems that we use, which is the latent factor collaborative filtering. We already have two matrixes (user-features, business-features) that we can multiply to predict the ratings that a user gives to a restaurant. In the next step, we need to update the values in the features of our two matrixes according to the Error.
To optimize the predictions we need to calculate the error using the function below.
Given P is the users-features matrix and Q is the business-features matrix. If we subtract the real ratings (r) with the predicted ratings (P.Q) and we square it, we get the LSE(Least Square Error). In the case of restaurant reviews, we have users that only give reviews to 10 restaurants but we also have users that give reviews to more than 200 restaurants. To avoid our model overfitting we have to add regularization to our LSE formula and it will become the formula written below.
We apply the equation to minimize the error using Gradient Decent to update the values of each feature in matrix P and matrix Q.
def matrix_factorization(R, P, Q, steps=25, gamma=0.001,lamda=0.02): for step in range(steps): for i in R.index: for j in R.columns: if R.loc[i,j]>0: eij=R.loc[i,j]-np.dot(P.loc[i],Q.loc[j]) P.loc[i]=P.loc[i]+gamma*(eij*Q.loc[j]-lamda*P.loc[i]) Q.loc[j]=Q.loc[j]+gamma*(eij*P.loc[i]-lamda*Q.loc[j]) e=0 for i in R.index: for j in R.columns: if R.loc[i,j]>0: e= e + pow(R.loc[i,j]-np.dot(P.loc[i],Q.loc[j]),2)+lamda*(pow(np.linalg.norm(P.loc[i]),2)+pow(np.linalg.norm(Q.loc[j]),2)) if e<0.001: break return P,QP, Q = matrix_factorization(userid_rating_matrix, P, Q, steps=25, gamma=0.001,lamda=0.02)
Now we already have our two matrixes updated. It is time to predict restaurant recommendations.
words = "i want to have dinner with beautiful views"test_df= pd.DataFrame([words], columns=['text'])test_df['text'] = test_df['text'].apply(text_process)test_vectors = userid_vectorizer.transform(test_df['text'])test_v_df = pd.DataFrame(test_vectors.toarray(), index=test_df.index, columns=userid_vectorizer.get_feature_names())predictItemRating=pd.DataFrame(np.dot(test_v_df.loc[0],Q.T),index=Q.index,columns=['Rating'])topRecommendations=pd.DataFrame.sort_values(predictItemRating,['Rating'],ascending=[0])[:7]for i in topRecommendations.index: print(df_business[df_business['business_id']==i]['name'].iloc[0]) print(df_business[df_business['business_id']==i]['categories'].iloc[0]) print(str(df_business[df_business['business_id']==i]['stars'].iloc[0])+ ' '+str(df_business[df_business['business_id']==i]['review_count'].iloc[0])) print('')
With the input “I want to have dinner with beautiful views” the model will recommend these restaurants.
Let’s take a look at one of the restaurants listed above. For example, Let’s open Compas Arizona Grill in Yelp to see the result of our recommendation systems.
It looks like the restaurant has quite a beautiful views and beautiful sunset. You can take your spouse to have a romantic dinner there (if you have one :D).
Congratulations you have created a Restaurant Recommendation System!
To see the dataset and full version of code, please visit the link below to see in the Github. | [
{
"code": null,
"e": 447,
"s": 47,
"text": "I usually watch youtube when I am taking a break from my work. I commit to myself to watch Youtube only for 5 to 10 minutes to rest my mind. Here is what usually happens, after I finished watching one video, the next video pops out from Youtube recommendations and I click on that video. When I take a look again at my watch, it turns out that I have been watching Youtube for more than an hour! :’)"
},
{
"code": null,
"e": 732,
"s": 447,
"text": "Youtube’s recommendation system is one of the most powerful and complex recommendation systems that can keep its users to watch Youtube videos for hours. Many startups giants like Netflix, Youtube, and Amazon revenues are driven mostly from the recommendation systems that they build."
},
{
"code": null,
"e": 862,
"s": 732,
"text": "This article focuses on how to build a restaurant recommendation system using latent factor collaborative filtering from scratch."
},
{
"code": null,
"e": 1307,
"s": 862,
"text": "Recommender Systems or Recommendation Systems are simple algorithms that aim to provide the most relevant and accurate items (products, movies, events, articles) to the user (customers, visitors, app users, readers) by filtering useful stuff from a huge pool of information base. Recommendation engines discover data patterns in the data set by learning consumers’ choices and produces the outcomes that co-relates to their needs and interests."
},
{
"code": null,
"e": 1871,
"s": 1307,
"text": "Imagine a physical clothing store. The good merchant knows the personal preferences of customers. Her/His high-quality recommendations make customers satisfied and increase profits. In the case of picking a restaurant to have lunch or dinner when you are traveling to other countries or cities, commonly you will ask your friend that lives in that country or city what is the best restaurant in town. The problem is you don’t have any friends that lived in that town. Your personal recommendations can be generated by an artificial friend: the recommender system."
},
{
"code": null,
"e": 2104,
"s": 1871,
"text": "There are various types of Recommendation systems but for this restaurant recommendation system that I build. I focused on using Matrix Factorization or Latent Factor Collaborative Filtering. Let’s start with the term Factorization."
},
{
"code": null,
"e": 2428,
"s": 2104,
"text": "When we think about factorization, it is a similar concept as six times four equals twenty-four. Twenty-four is a large number but we express it as a product of two small numbers six and four, so we manage to break down a big number into a product of two small ones. This similar concept is applied to Matrix Factorization."
},
{
"code": null,
"e": 2921,
"s": 2428,
"text": "A Recommendation System is an information filtering system that seeks to predict the rating a user would give for the item (in this case a restaurant). We can break down the large matrix of ratings from users and items into two smaller matrixes of user-feature and item-feature. For example, user A loves to eat hotdogs but hates to eat pizza and restaurant P have great hotdogs, we multiply the matrixes using dot product and the result will be the ratings (in the example above will be 11)."
},
{
"code": null,
"e": 3087,
"s": 2921,
"text": "Let’s start building a Restaurant Recommendation System using the techniques discussed above which should be capable of recommending restaurants that best suits you."
},
{
"code": null,
"e": 3154,
"s": 3087,
"text": "We will use Yelp restaurant data that can be downloaded from here."
},
{
"code": null,
"e": 3436,
"s": 3154,
"text": "Yelp is a business directory service and crowd-sourced review forum. The company develops, hosts and markets the Yelp.com website and the Yelp mobile app, which publish crowd-sourced reviews about businesses. It also operates an online reservation service called Yelp Reservations."
},
{
"code": null,
"e": 3886,
"s": 3436,
"text": "Yelp attempted to solve the problem “What should I eat?” This quickly expanded to include other business to answer other questions. This can best be represented as “I’m in [town]. Where can I go to get the [best/fastest/cheapest/easiest] [food/service/etc]?” Your friend’s recommendations are likely the largest influencer of where you will go if you have no preference. Yelp provided a service for when that was either not available or not trusted."
},
{
"code": null,
"e": 3968,
"s": 3886,
"text": "Let’s start by importing all the packages that we needed throughout the notebook."
},
{
"code": null,
"e": 4247,
"s": 3968,
"text": "import numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport seaborn as snsfrom sklearn.model_selection import train_test_splitfrom sklearn.feature_extraction.text import TfidfVectorizerfrom nltk.corpus import stopwords from nltk.tokenize import WordPunctTokenizer"
},
{
"code": null,
"e": 4322,
"s": 4247,
"text": "Now we import the dataset, we use the review dataset and business dataset."
},
{
"code": null,
"e": 4421,
"s": 4322,
"text": "df = pd.read_csv('yelp_review_arizona.csv')df_business = pd.read_csv('yelp_business.csv')df.head()"
},
{
"code": null,
"e": 4659,
"s": 4421,
"text": "We need to clean up the text first, we need to remove all the punctuations and remove all the stopwords(repetitive words that we do not need such as have, do, I, you, he, etc). We are using the library from nltk.corpus for the stopwords."
},
{
"code": null,
"e": 4750,
"s": 4659,
"text": "We select only the stars and text for our data and we import the library that we will use."
},
{
"code": null,
"e": 5023,
"s": 4750,
"text": "#Select only stars and textyelp_data = df[['business_id', 'user_id', 'stars', 'text']]import stringfrom nltk.corpus import stopwordsstop = []for word in stopwords.words('english'): s = [char for char in word if char not in string.punctuation] stop.append(''.join(s))"
},
{
"code": null,
"e": 5072,
"s": 5023,
"text": "Now let’s clean the text by creating a function."
},
{
"code": null,
"e": 5645,
"s": 5072,
"text": "def text_process(mess): \"\"\" Takes in a string of text, then performs the following: 1. Remove all punctuation 2. Remove all stopwords 3. Returns a list of the cleaned text \"\"\" # Check characters to see if they are in punctuation nopunc = [char for char in mess if char not in string.punctuation]# Join the characters again to form the string. nopunc = ''.join(nopunc) # Now just remove any stopwords return \" \".join([word for word in nopunc.split() if word.lower() not in stop])yelp_data['text'] = yelp_data['text'].apply(text_process)"
},
{
"code": null,
"e": 5806,
"s": 5645,
"text": "In order to use the text for the matrix factorization recommendation system, we will follow the architecture below to extract the features from the review text."
},
{
"code": null,
"e": 6089,
"s": 5806,
"text": "For each user, combine all the reviews to form a single paragraph, after we combine it all then we apply the TFIDF Vectorizer to extract the features from the text. The similar approach for each restaurant and we need to give the max_feature to match the dimensions of the matrixes."
},
{
"code": null,
"e": 6179,
"s": 6089,
"text": "userid_df = yelp_data[['user_id','text']]business_df = yelp_data[['business_id', 'text']]"
},
{
"code": null,
"e": 6316,
"s": 6179,
"text": "userid_df = userid_df.groupby('user_id').agg({'text': ' '.join})business_df = business_df.groupby('business_id').agg({'text': ' '.join})"
},
{
"code": null,
"e": 6389,
"s": 6316,
"text": "Now we apply the TFIDF Vectorizer to extract the features from the text."
},
{
"code": null,
"e": 6832,
"s": 6389,
"text": "from sklearn.feature_extraction.text import TfidfVectorizer#userid vectorizeruserid_vectorizer = TfidfVectorizer(tokenizer = WordPunctTokenizer().tokenize, max_features=5000)userid_vectors = userid_vectorizer.fit_transform(userid_df['text'])#Business id vectorizerbusinessid_vectorizer = TfidfVectorizer(tokenizer = WordPunctTokenizer().tokenize, max_features=5000)businessid_vectors = businessid_vectorizer.fit_transform(business_df['text'])"
},
{
"code": null,
"e": 6899,
"s": 6832,
"text": "Then, we create a matrix of users and businesses with the ratings."
},
{
"code": null,
"e": 7008,
"s": 6899,
"text": "userid_rating_matrix = pd.pivot_table(yelp_data, values='stars', index=['user_id'], columns=['business_id'])"
},
{
"code": null,
"e": 7375,
"s": 7008,
"text": "Let’s go back to the type of recommendation systems that we use, which is the latent factor collaborative filtering. We already have two matrixes (user-features, business-features) that we can multiply to predict the ratings that a user gives to a restaurant. In the next step, we need to update the values in the features of our two matrixes according to the Error."
},
{
"code": null,
"e": 7460,
"s": 7375,
"text": "To optimize the predictions we need to calculate the error using the function below."
},
{
"code": null,
"e": 7946,
"s": 7460,
"text": "Given P is the users-features matrix and Q is the business-features matrix. If we subtract the real ratings (r) with the predicted ratings (P.Q) and we square it, we get the LSE(Least Square Error). In the case of restaurant reviews, we have users that only give reviews to 10 restaurants but we also have users that give reviews to more than 200 restaurants. To avoid our model overfitting we have to add regularization to our LSE formula and it will become the formula written below."
},
{
"code": null,
"e": 8075,
"s": 7946,
"text": "We apply the equation to minimize the error using Gradient Decent to update the values of each feature in matrix P and matrix Q."
},
{
"code": null,
"e": 8855,
"s": 8075,
"text": "def matrix_factorization(R, P, Q, steps=25, gamma=0.001,lamda=0.02): for step in range(steps): for i in R.index: for j in R.columns: if R.loc[i,j]>0: eij=R.loc[i,j]-np.dot(P.loc[i],Q.loc[j]) P.loc[i]=P.loc[i]+gamma*(eij*Q.loc[j]-lamda*P.loc[i]) Q.loc[j]=Q.loc[j]+gamma*(eij*P.loc[i]-lamda*Q.loc[j]) e=0 for i in R.index: for j in R.columns: if R.loc[i,j]>0: e= e + pow(R.loc[i,j]-np.dot(P.loc[i],Q.loc[j]),2)+lamda*(pow(np.linalg.norm(P.loc[i]),2)+pow(np.linalg.norm(Q.loc[j]),2)) if e<0.001: break return P,QP, Q = matrix_factorization(userid_rating_matrix, P, Q, steps=25, gamma=0.001,lamda=0.02)"
},
{
"code": null,
"e": 8951,
"s": 8855,
"text": "Now we already have our two matrixes updated. It is time to predict restaurant recommendations."
},
{
"code": null,
"e": 9807,
"s": 8951,
"text": "words = \"i want to have dinner with beautiful views\"test_df= pd.DataFrame([words], columns=['text'])test_df['text'] = test_df['text'].apply(text_process)test_vectors = userid_vectorizer.transform(test_df['text'])test_v_df = pd.DataFrame(test_vectors.toarray(), index=test_df.index, columns=userid_vectorizer.get_feature_names())predictItemRating=pd.DataFrame(np.dot(test_v_df.loc[0],Q.T),index=Q.index,columns=['Rating'])topRecommendations=pd.DataFrame.sort_values(predictItemRating,['Rating'],ascending=[0])[:7]for i in topRecommendations.index: print(df_business[df_business['business_id']==i]['name'].iloc[0]) print(df_business[df_business['business_id']==i]['categories'].iloc[0]) print(str(df_business[df_business['business_id']==i]['stars'].iloc[0])+ ' '+str(df_business[df_business['business_id']==i]['review_count'].iloc[0])) print('')"
},
{
"code": null,
"e": 9911,
"s": 9807,
"text": "With the input “I want to have dinner with beautiful views” the model will recommend these restaurants."
},
{
"code": null,
"e": 10071,
"s": 9911,
"text": "Let’s take a look at one of the restaurants listed above. For example, Let’s open Compas Arizona Grill in Yelp to see the result of our recommendation systems."
},
{
"code": null,
"e": 10229,
"s": 10071,
"text": "It looks like the restaurant has quite a beautiful views and beautiful sunset. You can take your spouse to have a romantic dinner there (if you have one :D)."
},
{
"code": null,
"e": 10298,
"s": 10229,
"text": "Congratulations you have created a Restaurant Recommendation System!"
}
] |
Difference between Function and Predicate in Java 8 | Function and Predicate both functional interface was introduced in Java 8 to implement functional programming in Java.
Function interface is used to do the transformation.It can accepts one argument and produces a result. On the other side, Predicate can also accept only one argument but it can only return boolean value. It is used to test the condition.
public class Main {
public static void main(String args[]) {
List<Integer> numList = new ArrayList<>();
numList.add(5);
numList.add(10);
Predicate<Integer> pred = i -> i > 5;
numList.stream().filter(pred).forEach(i -> System.out.println(i));
}
}
public class Main {
public static void main(String args[]) {
List<Integer> numList = new ArrayList<>();
numList.add(78);
numList.add(10);
Function<Integer, Integer> fun = i -> i / 2;
numList.stream().map(fun).forEach(System.out::println);
}
} | [
{
"code": null,
"e": 1181,
"s": 1062,
"text": "Function and Predicate both functional interface was introduced in Java 8 to implement functional programming in Java."
},
{
"code": null,
"e": 1419,
"s": 1181,
"text": "Function interface is used to do the transformation.It can accepts one argument and produces a result. On the other side, Predicate can also accept only one argument but it can only return boolean value. It is used to test the condition."
},
{
"code": null,
"e": 1701,
"s": 1419,
"text": "public class Main {\n public static void main(String args[]) {\n List<Integer> numList = new ArrayList<>();\n numList.add(5);\n numList.add(10);\n Predicate<Integer> pred = i -> i > 5;\n numList.stream().filter(pred).forEach(i -> System.out.println(i));\n }\n}"
},
{
"code": null,
"e": 1984,
"s": 1701,
"text": "public class Main {\n public static void main(String args[]) {\n List<Integer> numList = new ArrayList<>();\n numList.add(78);\n numList.add(10);\n Function<Integer, Integer> fun = i -> i / 2;\n numList.stream().map(fun).forEach(System.out::println); \n }\n}"
}
] |
Tryit Editor v3.7 | CSS 2D Transforms
Tryit: The rotate() method | [
{
"code": null,
"e": 27,
"s": 9,
"text": "CSS 2D Transforms"
}
] |
IS vs AS Operators in C# | The "is" operator in C# checks whether the run-time type of an object is compatible with a given type or not.
The following is the syntax −
expr is type
Here, expr is the expression
type is the name of the type
The following is an example showing the usage of is operator in C# &minis;
Live Demo
using System;
class One { }
class Two { }
public class Demo {
public static void Test(object obj) {
One x;
Two y;
if (obj is One) {
Console.WriteLine("Class One");
x = (One)obj;
} else if (obj is Two) {
Console.WriteLine("Class Two");
y = (Two)obj;
} else {
Console.WriteLine("None of the classes!");
}
}
public static void Main() {
One o1 = new One();
Two t1 = new Two();
Test(o1);
Test(t1);
Test("str");
Console.ReadKey();
}
}
Class One
Class Two
None of the classes!
The "as" operator perform conversions between compatible types. It is like a cast operation and it performs only reference conversions, nullable conversions, and boxing conversions. The as operator can't perform other conversions, such as user-defined conversions, which should instead be performed by using cast expressions.
The following is an example showing the usage of as operation in C#. Here as is used for conversion −
string s = obj[i] as string;
Try to run the following code to work with ‘as’ operator in C# −
Live Demo
using System;
public class Demo {
public static void Main() {
object[] obj = new object[2];
obj[0] = "jack";
obj[1] = 32;
for (int i = 0; i < obj.Length; ++i) {
string s = obj[i] as string;
Console.Write("{0}: ", i);
if (s != null)
Console.WriteLine("'" + s + "'");
else
Console.WriteLine("This is not a string!");
}
Console.ReadKey();
}
}
0: 'jack'
1: This is not a string! | [
{
"code": null,
"e": 1172,
"s": 1062,
"text": "The \"is\" operator in C# checks whether the run-time type of an object is compatible with a given type or not."
},
{
"code": null,
"e": 1202,
"s": 1172,
"text": "The following is the syntax −"
},
{
"code": null,
"e": 1215,
"s": 1202,
"text": "expr is type"
},
{
"code": null,
"e": 1244,
"s": 1215,
"text": "Here, expr is the expression"
},
{
"code": null,
"e": 1273,
"s": 1244,
"text": "type is the name of the type"
},
{
"code": null,
"e": 1348,
"s": 1273,
"text": "The following is an example showing the usage of is operator in C# &minis;"
},
{
"code": null,
"e": 1359,
"s": 1348,
"text": " Live Demo"
},
{
"code": null,
"e": 1921,
"s": 1359,
"text": "using System;\n\nclass One { }\nclass Two { }\n\npublic class Demo {\n public static void Test(object obj) {\n One x;\n Two y;\n\n if (obj is One) {\n Console.WriteLine(\"Class One\");\n x = (One)obj;\n } else if (obj is Two) {\n Console.WriteLine(\"Class Two\");\n y = (Two)obj;\n } else {\n Console.WriteLine(\"None of the classes!\");\n }\n }\n\n public static void Main() {\n One o1 = new One();\n Two t1 = new Two();\n Test(o1);\n Test(t1);\n Test(\"str\");\n Console.ReadKey();\n }\n}"
},
{
"code": null,
"e": 1962,
"s": 1921,
"text": "Class One\nClass Two\nNone of the classes!"
},
{
"code": null,
"e": 2288,
"s": 1962,
"text": "The \"as\" operator perform conversions between compatible types. It is like a cast operation and it performs only reference conversions, nullable conversions, and boxing conversions. The as operator can't perform other conversions, such as user-defined conversions, which should instead be performed by using cast expressions."
},
{
"code": null,
"e": 2390,
"s": 2288,
"text": "The following is an example showing the usage of as operation in C#. Here as is used for conversion −"
},
{
"code": null,
"e": 2419,
"s": 2390,
"text": "string s = obj[i] as string;"
},
{
"code": null,
"e": 2484,
"s": 2419,
"text": "Try to run the following code to work with ‘as’ operator in C# −"
},
{
"code": null,
"e": 2495,
"s": 2484,
"text": " Live Demo"
},
{
"code": null,
"e": 2933,
"s": 2495,
"text": "using System;\n\npublic class Demo {\n public static void Main() {\n object[] obj = new object[2];\n obj[0] = \"jack\";\n obj[1] = 32;\n\n for (int i = 0; i < obj.Length; ++i) {\n string s = obj[i] as string;\n Console.Write(\"{0}: \", i);\n if (s != null)\n Console.WriteLine(\"'\" + s + \"'\");\n else\n Console.WriteLine(\"This is not a string!\");\n }\n Console.ReadKey();\n }\n}"
},
{
"code": null,
"e": 2968,
"s": 2933,
"text": "0: 'jack'\n1: This is not a string!"
}
] |
Customer Segmentation Data Science | by Arun Jagota | Towards Data Science | In marketing, customer segmentation is the process of grouping customers by common traits. Discerning buying habits by customer type helps to market appropriately. For instance, it reveals the sizes of the various segments, how much we make from them, etc. This can help decide how to apportion the marketing budget.
In data science, clustering is the process of grouping objects by some common traits.
See the connection? Clustering — a data science method — is a good fit for customer segmentation — a use case. That said, as often happens, there is more to it when we start digging. We call this modeling.
Let’s start by looking at specific traits we’d want to segment on. We’ll distinguish between B2B marketing and B2C marketing as the traits vary.
B2B Marketing
The customers are businesses, i.e. companies. One set of traits found useful to segment by are the so-called firmographics: industry, location, company size (small, medium, large, etc).
B2C Marketing
Here, the customers are consumers, i.e. people. Traits useful to consider for segmentation are the so-called demographic ones: age, gender, location, ethnicity, income level, and so on.
Modeling
Now, we abstract away from the specifics of B2B vs B2C and look at the modeling per se. While we will use B2B examples for illustration, the modeling is more general.
Single Structured Factor
First consider a single trait, say industry. We wish to segment customers just by this trait. First, let’s assume industry has a small number of clean values. (“Clean” means from a controlled vocabulary — such as ones in a drop-down list.)
This segmentation is easy to do. It just involves grouping and aggregating.
Single Unstructured Factor
Now suppose the industry values are not clean. They are stored in a text field in free-form. At data entry, whatever value makes sense is put.
Say there are 100K customer records in our database, and most have industry field values filled in.
Immediately our segmentation problem has become way harder. The same industry will often get expressed in different ways in different records. Word order may vary; acronyms may get used; connectives may or may not be present; synonyms may get used.
Strings Similarity Measure: A first reasonable attempt at solving this problem goes something like this. First, we define a similarity measure on pairs of industry strings. We start by defining an industry string’s set-of-words. This is just the set of distinct tokens in the string. People familiar with the term bag-of-words might think of this as the bag with word frequencies removed. Next, given two word-sets, we need a sensible way to quantify their similarity. Here is one: It is called Jaccard similarity.
The Jaccard Similarity of two sets is the number of elements they have in common divided by the number of elements in their union.
Below is an example.
Jaccard-coefficient({predictive analytics platform},{predictive analytics}) = 2⁄3
Grouping Records into Clusters: Next, we need to group the records into clusters using this similarity measure. Pairs of records in the same cluster should be similar to each other; pairs in different clusters not.
This is easier said than done. It’s not clear that we have even fully thought through our problem formulation yet. I’ll elaborate. The word ‘group’ seems to imply that a record should go into exactly one cluster. Is this really what we want? Not necessarily. Imagine an industry value Medical Informatics. We might want to place this in multiple clusters — some medical-related, some IT-related.
Industries at Multiple Levels: The values in the industry field may span multiple levels of an industry taxonomy. For example, one record may set the industry field value to a broad category, say Software. Another record may specify the industry at a finer-level, say Database Software. So maybe we want to do hierarchical clustering, not flat clustering. So a record whose industry is Database Software may be assigned to a cluster that is a descendant of the cluster whose industry is Software.
Clustering Algorithms: Which algorithm to use depends on which type of clustering we want — flat or hierarchical? Even within the flat category, the algorithm depends on whether we want the clustering to be hard or soft. (Hard meaning an item belongs to exactly one cluster.)
Flat Clustering: Algorithms suited to hard clustering include k-means clustering, dbscan, connected components clustering, and others. Algorithms for soft clustering are often softened versions of the hard clustering ones. One such is soft — also called probabilistic — k-means clustering. This is based on a powerful algorithm call the EM algorithm of which (hard) k-means clustering is a special case.
Hierarchical Clustering: Popular hierarchical clustering algorithms include agglomerative (bottom-up) clustering or divisive (top-down) clustering. In the former, items are first clustered into tight clusters, then clusters are clustered into coarser clusters. This process is repeated until we have a tree of clusters. Its leaves are the items. The tree’s root is a single cluster representing the entire data set.
Divisive clustering works in the opposite direction. It starts from the cluster representing the entire data set; a cluster is then split into two. The resulting clusters become the children of the former. Thus the tree of clusters is grown top-down.
Bottom-up vs Top-down: One might think, bottom-up or top-down, they are mirror image processes, so why to care which to use. The choice does matter. It is generally easier to merge two suitable small clusters than to split a large cluster into two good ones. This fact alone largely explains why bottom-up clustering is far more popular than top-down clustering.
Another important consideration is that bottom-up vs top-down clustering can produce different results. Building up bottom-up is not the same as splitting top-down. For this reason, top-down clustering is sometimes considered when bottom-up’s results are not sufficiently good, or we just want to know how much switching from bottom-up to top-down changes the tree in any particular instance.
Linguistic Structure In Industry Names: Coming back to our industry with unstructured values example, we might take a third tack. Take advantage of the linguistic structure implicitly present in industry names. This will probably work better. We illustrate this below on a toy example. The algorithm that emerges may be easily enhanced to accommodate more realistic scenarios.
Example: Imagine there are just six distinct industry values: Software, Database Software, Analytics Software, Manufacturing, Auto Manufacturing, Drug Manufacturing. (Some of these names are contrived, and not to be taken seriously.) The sought hierarchical structure is
Software ← Database Software, Software ← Analytics SoftwareManufacturing ← Auto Manufacturing, Manufacturing ← Drug Manufacturing
where p ← c denotes a parent-child instance.
Algorithm Leveraging Linguistic Structure: Below is the algorithm. It will yield our desired hierarchy in this example.
Order the set of distinct industry values by the number of words in them. Least number of words first. Denote this ordering as I1, I2, ..., Ik.For each i in 1..k If Ii does not have a parent, set Ii as a root of the hierarchy. For each j in (i+1)..k If Ij’s parent is not set and is_child(Ij,Ii) parent(Ij) = Ii
Let’s illustrate this algorithm in our example. First, we sort the industry names by the number of words in them. This yields the ordered list
Software, Manufacturing, Database Software, Analytics Software, Auto Manufacturing, Drug Manufacturing
Next, we make Software a root and scan to the right of it to find all its children. We discover
Software ← Database Software, Software ← Analytics Software
Next, we make Manufacturing a root of this hierarchy and scan to its right to find all its children, skipping over industry names that have already been parented. We discover
Manufacturing ← Auto Manufacturing, Manufacturing ← Drug Manufacturing
Next, we try to find the children of each of the two-word industry names. We don’t find any. So we are done.
Multiple Factors, Mixed Structure
Now consider segmenting companies by the combination of multiple factors. Specifically, by the key firmographics: industry, location, and company size. Some of these factors might be structured, others unstructured. For example industry, as before, is unstructured. Company size may be structured: represented by a fixed number of values such as small, medium, large. This complicates the problem significantly.
Multi-factor Similarity Metric: First, let’s define a suitable metric that quantifies how similar a pair of factor tuples is. This definition needs to be thought-through with care, as this metric will hugely influence which companies get grouped into which segments.
Preamble 1 — Factor Descriptions: First, let’s refine our factor descriptions. We’ll keep industry unstructured as before. We’ll make company size ordinal. This just means company size will have a fixed set of ordered values. As an example, small, medium, large. We can later add more values to company size, such as very small and very large. We can even have the set of values be automatically determined via a data-driven company size binning process. The resulting values might differ from data set to data set. So long as the values can be ordered, we are good. (By the way not every set of values can be ordered. Consider gender = female, male. There is no natural order. We could impose some artificial order but that might not go so well.)
For location, let’s keep it simple, to begin with, and just choose 5-digit zip. (This does limit our companies to being in the USA only.)
Preamble 2 — Some Notes on the Metric: Next, we define a suitable metric under these factor definitions. It’s important to note that should we modify our factor definitions, the metric might require large-scale revision. As an example, say we define location as a combination of zip, city, state, country. Quantifying how similar two locations are is now much more involved.
Similarity Metrics for Individual Factors
We will take the approach of defining similarity metrics for each factor individually, and upon these build our multi-factor similarity metric.
Common Part — Sigmoid Function: Before we dive into the individual metrics, we’d like to mention a key point that cuts across their design. In all of them, we use a sigmoid function as a soft approximation to a step function. We do this because we want the similarity to rapidly drop towards 0 when the values being compared are insufficiently similar. This gives us control over the similarity detection versus false-positive rates.
Because of this, let’s first define the sigmoid function.
sigmoid_{a,b}(x) = 1/(1+exp(-a*(x-b)))
a controls the sigmoid’s steepness, i.e. the extent to which it approximates the step function. bcontrols the soft threshold. Just as a step function, the sigmoid discriminates values flanking b.
Company Names Similarity Metric: Let’s start with the metric for comparing two company sizes. Let’s rank order the company size values as 1, 2, 3, ..., k. That is, 1 denotes the smallest company size bin and k the largest company size bin. Our similarity metric is
S(i,j) = sigmoid_{a,b}(-|i-j|)
Here a>0and b>0 give us control over the sigmoid’s steepness and the threshold. We have used -|i-j|rather than |i-j|as the argument, because we seek an inverted sigmoid behavior. We could instead absorb this negative sign into the a, but making it explicit is more intuitive.
S(i,j) has the simple intuition that the closer the bins i and j are in their rank order, i.e. in the sizes of the companies they represent, the higher the similarity value.
We’ll choose sensible defaults so you can forget about them if you don’t like free parameters. Specifically, we’ll set a to 1, the most commonly used sigmoid steepness. To better reveal what value of bmakes sense let us rewrite the sigmoid as sigmoid(b-|i-j|). We will set bto 1.5. This will get us the behavior that when |i-j|<=1.5the sigmoid’s value will cross 0.5 from below. We can, of course, fine-tune this behavior as we wish.
Zips Similarity Metric: Next, let’s work on a metric for zip values. We’ll take advantage of the fact that 5-digit zips are numbers and, generally speaking, the closer the numbers are the closer the zip locations are. We use
S(z1,z2) =sigmoid_{a,b}(-|z1-z2|)
This time we will choose a>0to be much less than 1 and b to ~ 20. The intuition is that we want S(z1,z2) to be greater than 0.5 even when |z1-z2| is around 20, roughly speaking. Plus we want the crossing to have low steepness. We can, of course, fine-tune these values as we see fit.
Substitution and Transposition Errors: While this metric models proximity well enough, it does not account for substitution or transposition errors. Let’s start by seeing an example of each. (We have intentionally omitted insertion and deletion errors because they change the number of digits.)
Substitution error: 21034, 21834, Transposition error: 21034, 20134
As in the examples above, we’ll consider only single-digit substitution errors and adjacent-digit transposition errors. Here is a simple metric that accommodates single digit substitution errors:
S2(z1,z2) = sigmoid_{a,b}(-sum_i NE(z1[i],z2[i]))
Here NE(x,y) equals 0 when xequals yand 1 when not. We will set ato 1 and bto 1.5, as the behavior we seek (on the sigmoid’s argument) is exactly what we sought for company size similarity.
Similarly, we can define a metric that accommodates up to one adjacent-digit transposition.
T(z1,z2) = sigmoid_{a,b}(-#adjacent-digit-transpositions(z1,z2))
We use the same aand bas we did for substitution scoring.
So now we can combine all these metrics into a single metric.
Sim(z1,z2) = Max(S(z1,z2),S2(z1,z2),T(z1,z2) )
Industries Similarity Metric: Finally, for industry, we will use the Jaccard coefficient on their word-sets as the similarity metric, further transformed via a sigmoid. That is
S_industry(I1,I2) = sigmoid_{a,b}(Jaccard-coefficient(I1,I2))
We will not describe how to choose the default values of a and bin detail. Rather, we will just note that ashould be positive and greater than 1 and b should be chosen to be the value of the Jaccard-coefficient we deem to be at the edge of similarity. Note that the Jaccard-coefficient returns a value between 0 and 1 where 0 denotes maximally dissimilar and 1 denotes maximally similar.
Multi-factor Metric
We are now ready to build our multi-factor metric on top of these metrics. First, let’s briefly discuss the pros and cons of this approach. This modular design makes it easy to add new factors or to delete existing ones. It also makes it easy to adjust the relative influence of the similarities of individual factor values towards the overall metric. That said, it does not naturally model interactions among factors. To model these, one will need to explicitly add in specific interaction terms.
Our multi-factor metric is
S(C1,C2) = w_zip*S_zip(C1.zip,C2.zip) + w_industry*S_industry(C1.industry,C2.industry) + w_company_size*S(C1.company_size_bin_rank,C2.company_size_bin_rank)
The factor weights let us control the relative influences of the individual factor similarities in the overall metric.
Specializations: Now that we have this metric, we can build various specializations of it by simply setting certain factor weights to 0. So we can realize all single-factor versions — similarity-by-zip, similarity-by-industry, similarity-by-company-size — and also all two-factor versions. Armed with these specializations we can build segments more flexibly. Effectively we can group by one factor, by two factors, or by all three factors. Note that“group by” really means “fuzzy group by”.
Clustering the Matrix of Similarities: The key point we’d like to bring out is that the natural way to leverage the pairwise similarity metrics we have defined is to compute pairwise similarities among all pairs of companies and capture these in a similarity matrix. (That is unless the number of companies is so large that computing pairwise similarities will run too slow. We will assume this is not the case.)
Clustering algorithms may then work directly on this matrix. This separates concerns. Clustering algorithms only operate on a similarity matrix, not caring how it was produced. The similarity metrics focus on quantifying the actual similarities, not caring how objects will be clustered downstream.
A Specific Algorithm — Graph Partitioning: Let’s see a concrete clustering algorithm on a similarity matrix. We’ll express the matrix as a graph. The graph’s nodes are the objects, in our case companies. Two nodes are connected by an edge if the corresponding objects are sufficiently similar. The weight on an edge captures the actual similarity value.
The high-level idea of the algorithm is to partition the graph into dense subgraphs connected by sparse crossing regions. Dense subgraphs will represent tight clusters. Sparse crossing regions will ensure that these clusters are well-separated.
Let’s refine this description. We need some key concepts first.
Subgraph Density: We define the density of a subgraph on k nodes as the sum of the weights on the edges that connect pairs of nodes within this set divided by k(k-1)/2. This assumes that the weight on an edge is between 0 and 1. Non-edges may be viewed as edges with weight 0. Under this representation, the density of a subgraph is the average weight of an edge in it.
Node Weights: We define the weight of a node as the sum of the weights of the edges touching the node. We define the weight of a node on a node-set as the sum of the weights of edges touching this node whose other endpoint is in that set. As an example, the weight of node a on nodes b, c, and d is the sum of the weights of the edges a-b, a-c, and a-d.
The Actual Algorithm: Next, we describe a simple heuristic algorithm that finds a good clustering.
find_one_good_cluster(G) C = {v}, where v is a highest-weight node in G Repeat Find a node v in G-C whose weight on C is sufficiently high. If no such v exists Close C. remaining_clusters = find_one_good_cluster(G-C) Return remaining_clusters + {C} Else Add v to C forever
The “sufficiently high” test biases the algorithm to find tight clusters. (Tightness is not guaranteed as the tightness check is done only when a node is added to a cluster.) The algorithm does not explicitly favor cross-cluster sparsity. This happens implicitly. A cluster keeps growing as long as a node outside of it has sufficiently high cumulative weight to nodes in it. Consequently, when a cluster stops growing, all nodes outside it have low cumulative weight to nodes in it. This favors sparse cross-cluster regions.
Summary
In this post, we have seen how clustering as a data science method is a good fit for market segmentation as a use case. We’ve looked into factors to use for B2B vs B2C segmentation. We have examined issues that arise when a factor has clean values; when a factor has a long tail of unstructured values; and when a factor has a small set of ordinal values.
We have discussed flat clustering, soft clustering, and hierarchical clustering. We have looked at how domain knowledge can guide us into what algorithms to use, even to the point of moving us away from standard algorithms. (I am referring to clustering industry names into a hierarchy of industries leveraging the linguistic structure implicit in these names.)
We have presented specific metrics for quantifying the similarities of some types of factors we encounter in B2B settings. We have then presented a multi-factor similarity measure, and described how to use it in multi-factor clustering (think segmenting a market by combinations of multiple factors). | [
{
"code": null,
"e": 363,
"s": 46,
"text": "In marketing, customer segmentation is the process of grouping customers by common traits. Discerning buying habits by customer type helps to market appropriately. For instance, it reveals the sizes of the various segments, how much we make from them, etc. This can help decide how to apportion the marketing budget."
},
{
"code": null,
"e": 449,
"s": 363,
"text": "In data science, clustering is the process of grouping objects by some common traits."
},
{
"code": null,
"e": 655,
"s": 449,
"text": "See the connection? Clustering — a data science method — is a good fit for customer segmentation — a use case. That said, as often happens, there is more to it when we start digging. We call this modeling."
},
{
"code": null,
"e": 800,
"s": 655,
"text": "Let’s start by looking at specific traits we’d want to segment on. We’ll distinguish between B2B marketing and B2C marketing as the traits vary."
},
{
"code": null,
"e": 814,
"s": 800,
"text": "B2B Marketing"
},
{
"code": null,
"e": 1000,
"s": 814,
"text": "The customers are businesses, i.e. companies. One set of traits found useful to segment by are the so-called firmographics: industry, location, company size (small, medium, large, etc)."
},
{
"code": null,
"e": 1014,
"s": 1000,
"text": "B2C Marketing"
},
{
"code": null,
"e": 1200,
"s": 1014,
"text": "Here, the customers are consumers, i.e. people. Traits useful to consider for segmentation are the so-called demographic ones: age, gender, location, ethnicity, income level, and so on."
},
{
"code": null,
"e": 1209,
"s": 1200,
"text": "Modeling"
},
{
"code": null,
"e": 1376,
"s": 1209,
"text": "Now, we abstract away from the specifics of B2B vs B2C and look at the modeling per se. While we will use B2B examples for illustration, the modeling is more general."
},
{
"code": null,
"e": 1401,
"s": 1376,
"text": "Single Structured Factor"
},
{
"code": null,
"e": 1641,
"s": 1401,
"text": "First consider a single trait, say industry. We wish to segment customers just by this trait. First, let’s assume industry has a small number of clean values. (“Clean” means from a controlled vocabulary — such as ones in a drop-down list.)"
},
{
"code": null,
"e": 1717,
"s": 1641,
"text": "This segmentation is easy to do. It just involves grouping and aggregating."
},
{
"code": null,
"e": 1744,
"s": 1717,
"text": "Single Unstructured Factor"
},
{
"code": null,
"e": 1887,
"s": 1744,
"text": "Now suppose the industry values are not clean. They are stored in a text field in free-form. At data entry, whatever value makes sense is put."
},
{
"code": null,
"e": 1987,
"s": 1887,
"text": "Say there are 100K customer records in our database, and most have industry field values filled in."
},
{
"code": null,
"e": 2236,
"s": 1987,
"text": "Immediately our segmentation problem has become way harder. The same industry will often get expressed in different ways in different records. Word order may vary; acronyms may get used; connectives may or may not be present; synonyms may get used."
},
{
"code": null,
"e": 2751,
"s": 2236,
"text": "Strings Similarity Measure: A first reasonable attempt at solving this problem goes something like this. First, we define a similarity measure on pairs of industry strings. We start by defining an industry string’s set-of-words. This is just the set of distinct tokens in the string. People familiar with the term bag-of-words might think of this as the bag with word frequencies removed. Next, given two word-sets, we need a sensible way to quantify their similarity. Here is one: It is called Jaccard similarity."
},
{
"code": null,
"e": 2882,
"s": 2751,
"text": "The Jaccard Similarity of two sets is the number of elements they have in common divided by the number of elements in their union."
},
{
"code": null,
"e": 2903,
"s": 2882,
"text": "Below is an example."
},
{
"code": null,
"e": 2985,
"s": 2903,
"text": "Jaccard-coefficient({predictive analytics platform},{predictive analytics}) = 2⁄3"
},
{
"code": null,
"e": 3200,
"s": 2985,
"text": "Grouping Records into Clusters: Next, we need to group the records into clusters using this similarity measure. Pairs of records in the same cluster should be similar to each other; pairs in different clusters not."
},
{
"code": null,
"e": 3596,
"s": 3200,
"text": "This is easier said than done. It’s not clear that we have even fully thought through our problem formulation yet. I’ll elaborate. The word ‘group’ seems to imply that a record should go into exactly one cluster. Is this really what we want? Not necessarily. Imagine an industry value Medical Informatics. We might want to place this in multiple clusters — some medical-related, some IT-related."
},
{
"code": null,
"e": 4093,
"s": 3596,
"text": "Industries at Multiple Levels: The values in the industry field may span multiple levels of an industry taxonomy. For example, one record may set the industry field value to a broad category, say Software. Another record may specify the industry at a finer-level, say Database Software. So maybe we want to do hierarchical clustering, not flat clustering. So a record whose industry is Database Software may be assigned to a cluster that is a descendant of the cluster whose industry is Software."
},
{
"code": null,
"e": 4369,
"s": 4093,
"text": "Clustering Algorithms: Which algorithm to use depends on which type of clustering we want — flat or hierarchical? Even within the flat category, the algorithm depends on whether we want the clustering to be hard or soft. (Hard meaning an item belongs to exactly one cluster.)"
},
{
"code": null,
"e": 4773,
"s": 4369,
"text": "Flat Clustering: Algorithms suited to hard clustering include k-means clustering, dbscan, connected components clustering, and others. Algorithms for soft clustering are often softened versions of the hard clustering ones. One such is soft — also called probabilistic — k-means clustering. This is based on a powerful algorithm call the EM algorithm of which (hard) k-means clustering is a special case."
},
{
"code": null,
"e": 5189,
"s": 4773,
"text": "Hierarchical Clustering: Popular hierarchical clustering algorithms include agglomerative (bottom-up) clustering or divisive (top-down) clustering. In the former, items are first clustered into tight clusters, then clusters are clustered into coarser clusters. This process is repeated until we have a tree of clusters. Its leaves are the items. The tree’s root is a single cluster representing the entire data set."
},
{
"code": null,
"e": 5440,
"s": 5189,
"text": "Divisive clustering works in the opposite direction. It starts from the cluster representing the entire data set; a cluster is then split into two. The resulting clusters become the children of the former. Thus the tree of clusters is grown top-down."
},
{
"code": null,
"e": 5803,
"s": 5440,
"text": "Bottom-up vs Top-down: One might think, bottom-up or top-down, they are mirror image processes, so why to care which to use. The choice does matter. It is generally easier to merge two suitable small clusters than to split a large cluster into two good ones. This fact alone largely explains why bottom-up clustering is far more popular than top-down clustering."
},
{
"code": null,
"e": 6196,
"s": 5803,
"text": "Another important consideration is that bottom-up vs top-down clustering can produce different results. Building up bottom-up is not the same as splitting top-down. For this reason, top-down clustering is sometimes considered when bottom-up’s results are not sufficiently good, or we just want to know how much switching from bottom-up to top-down changes the tree in any particular instance."
},
{
"code": null,
"e": 6573,
"s": 6196,
"text": "Linguistic Structure In Industry Names: Coming back to our industry with unstructured values example, we might take a third tack. Take advantage of the linguistic structure implicitly present in industry names. This will probably work better. We illustrate this below on a toy example. The algorithm that emerges may be easily enhanced to accommodate more realistic scenarios."
},
{
"code": null,
"e": 6844,
"s": 6573,
"text": "Example: Imagine there are just six distinct industry values: Software, Database Software, Analytics Software, Manufacturing, Auto Manufacturing, Drug Manufacturing. (Some of these names are contrived, and not to be taken seriously.) The sought hierarchical structure is"
},
{
"code": null,
"e": 6974,
"s": 6844,
"text": "Software ← Database Software, Software ← Analytics SoftwareManufacturing ← Auto Manufacturing, Manufacturing ← Drug Manufacturing"
},
{
"code": null,
"e": 7019,
"s": 6974,
"text": "where p ← c denotes a parent-child instance."
},
{
"code": null,
"e": 7139,
"s": 7019,
"text": "Algorithm Leveraging Linguistic Structure: Below is the algorithm. It will yield our desired hierarchy in this example."
},
{
"code": null,
"e": 7469,
"s": 7139,
"text": "Order the set of distinct industry values by the number of words in them. Least number of words first. Denote this ordering as I1, I2, ..., Ik.For each i in 1..k If Ii does not have a parent, set Ii as a root of the hierarchy. For each j in (i+1)..k If Ij’s parent is not set and is_child(Ij,Ii) parent(Ij) = Ii"
},
{
"code": null,
"e": 7612,
"s": 7469,
"text": "Let’s illustrate this algorithm in our example. First, we sort the industry names by the number of words in them. This yields the ordered list"
},
{
"code": null,
"e": 7715,
"s": 7612,
"text": "Software, Manufacturing, Database Software, Analytics Software, Auto Manufacturing, Drug Manufacturing"
},
{
"code": null,
"e": 7811,
"s": 7715,
"text": "Next, we make Software a root and scan to the right of it to find all its children. We discover"
},
{
"code": null,
"e": 7871,
"s": 7811,
"text": "Software ← Database Software, Software ← Analytics Software"
},
{
"code": null,
"e": 8046,
"s": 7871,
"text": "Next, we make Manufacturing a root of this hierarchy and scan to its right to find all its children, skipping over industry names that have already been parented. We discover"
},
{
"code": null,
"e": 8117,
"s": 8046,
"text": "Manufacturing ← Auto Manufacturing, Manufacturing ← Drug Manufacturing"
},
{
"code": null,
"e": 8226,
"s": 8117,
"text": "Next, we try to find the children of each of the two-word industry names. We don’t find any. So we are done."
},
{
"code": null,
"e": 8260,
"s": 8226,
"text": "Multiple Factors, Mixed Structure"
},
{
"code": null,
"e": 8672,
"s": 8260,
"text": "Now consider segmenting companies by the combination of multiple factors. Specifically, by the key firmographics: industry, location, and company size. Some of these factors might be structured, others unstructured. For example industry, as before, is unstructured. Company size may be structured: represented by a fixed number of values such as small, medium, large. This complicates the problem significantly."
},
{
"code": null,
"e": 8939,
"s": 8672,
"text": "Multi-factor Similarity Metric: First, let’s define a suitable metric that quantifies how similar a pair of factor tuples is. This definition needs to be thought-through with care, as this metric will hugely influence which companies get grouped into which segments."
},
{
"code": null,
"e": 9687,
"s": 8939,
"text": "Preamble 1 — Factor Descriptions: First, let’s refine our factor descriptions. We’ll keep industry unstructured as before. We’ll make company size ordinal. This just means company size will have a fixed set of ordered values. As an example, small, medium, large. We can later add more values to company size, such as very small and very large. We can even have the set of values be automatically determined via a data-driven company size binning process. The resulting values might differ from data set to data set. So long as the values can be ordered, we are good. (By the way not every set of values can be ordered. Consider gender = female, male. There is no natural order. We could impose some artificial order but that might not go so well.)"
},
{
"code": null,
"e": 9825,
"s": 9687,
"text": "For location, let’s keep it simple, to begin with, and just choose 5-digit zip. (This does limit our companies to being in the USA only.)"
},
{
"code": null,
"e": 10200,
"s": 9825,
"text": "Preamble 2 — Some Notes on the Metric: Next, we define a suitable metric under these factor definitions. It’s important to note that should we modify our factor definitions, the metric might require large-scale revision. As an example, say we define location as a combination of zip, city, state, country. Quantifying how similar two locations are is now much more involved."
},
{
"code": null,
"e": 10242,
"s": 10200,
"text": "Similarity Metrics for Individual Factors"
},
{
"code": null,
"e": 10386,
"s": 10242,
"text": "We will take the approach of defining similarity metrics for each factor individually, and upon these build our multi-factor similarity metric."
},
{
"code": null,
"e": 10820,
"s": 10386,
"text": "Common Part — Sigmoid Function: Before we dive into the individual metrics, we’d like to mention a key point that cuts across their design. In all of them, we use a sigmoid function as a soft approximation to a step function. We do this because we want the similarity to rapidly drop towards 0 when the values being compared are insufficiently similar. This gives us control over the similarity detection versus false-positive rates."
},
{
"code": null,
"e": 10878,
"s": 10820,
"text": "Because of this, let’s first define the sigmoid function."
},
{
"code": null,
"e": 10917,
"s": 10878,
"text": "sigmoid_{a,b}(x) = 1/(1+exp(-a*(x-b)))"
},
{
"code": null,
"e": 11113,
"s": 10917,
"text": "a controls the sigmoid’s steepness, i.e. the extent to which it approximates the step function. bcontrols the soft threshold. Just as a step function, the sigmoid discriminates values flanking b."
},
{
"code": null,
"e": 11378,
"s": 11113,
"text": "Company Names Similarity Metric: Let’s start with the metric for comparing two company sizes. Let’s rank order the company size values as 1, 2, 3, ..., k. That is, 1 denotes the smallest company size bin and k the largest company size bin. Our similarity metric is"
},
{
"code": null,
"e": 11409,
"s": 11378,
"text": "S(i,j) = sigmoid_{a,b}(-|i-j|)"
},
{
"code": null,
"e": 11685,
"s": 11409,
"text": "Here a>0and b>0 give us control over the sigmoid’s steepness and the threshold. We have used -|i-j|rather than |i-j|as the argument, because we seek an inverted sigmoid behavior. We could instead absorb this negative sign into the a, but making it explicit is more intuitive."
},
{
"code": null,
"e": 11859,
"s": 11685,
"text": "S(i,j) has the simple intuition that the closer the bins i and j are in their rank order, i.e. in the sizes of the companies they represent, the higher the similarity value."
},
{
"code": null,
"e": 12293,
"s": 11859,
"text": "We’ll choose sensible defaults so you can forget about them if you don’t like free parameters. Specifically, we’ll set a to 1, the most commonly used sigmoid steepness. To better reveal what value of bmakes sense let us rewrite the sigmoid as sigmoid(b-|i-j|). We will set bto 1.5. This will get us the behavior that when |i-j|<=1.5the sigmoid’s value will cross 0.5 from below. We can, of course, fine-tune this behavior as we wish."
},
{
"code": null,
"e": 12518,
"s": 12293,
"text": "Zips Similarity Metric: Next, let’s work on a metric for zip values. We’ll take advantage of the fact that 5-digit zips are numbers and, generally speaking, the closer the numbers are the closer the zip locations are. We use"
},
{
"code": null,
"e": 12552,
"s": 12518,
"text": "S(z1,z2) =sigmoid_{a,b}(-|z1-z2|)"
},
{
"code": null,
"e": 12836,
"s": 12552,
"text": "This time we will choose a>0to be much less than 1 and b to ~ 20. The intuition is that we want S(z1,z2) to be greater than 0.5 even when |z1-z2| is around 20, roughly speaking. Plus we want the crossing to have low steepness. We can, of course, fine-tune these values as we see fit."
},
{
"code": null,
"e": 13131,
"s": 12836,
"text": "Substitution and Transposition Errors: While this metric models proximity well enough, it does not account for substitution or transposition errors. Let’s start by seeing an example of each. (We have intentionally omitted insertion and deletion errors because they change the number of digits.)"
},
{
"code": null,
"e": 13199,
"s": 13131,
"text": "Substitution error: 21034, 21834, Transposition error: 21034, 20134"
},
{
"code": null,
"e": 13395,
"s": 13199,
"text": "As in the examples above, we’ll consider only single-digit substitution errors and adjacent-digit transposition errors. Here is a simple metric that accommodates single digit substitution errors:"
},
{
"code": null,
"e": 13445,
"s": 13395,
"text": "S2(z1,z2) = sigmoid_{a,b}(-sum_i NE(z1[i],z2[i]))"
},
{
"code": null,
"e": 13635,
"s": 13445,
"text": "Here NE(x,y) equals 0 when xequals yand 1 when not. We will set ato 1 and bto 1.5, as the behavior we seek (on the sigmoid’s argument) is exactly what we sought for company size similarity."
},
{
"code": null,
"e": 13727,
"s": 13635,
"text": "Similarly, we can define a metric that accommodates up to one adjacent-digit transposition."
},
{
"code": null,
"e": 13792,
"s": 13727,
"text": "T(z1,z2) = sigmoid_{a,b}(-#adjacent-digit-transpositions(z1,z2))"
},
{
"code": null,
"e": 13850,
"s": 13792,
"text": "We use the same aand bas we did for substitution scoring."
},
{
"code": null,
"e": 13912,
"s": 13850,
"text": "So now we can combine all these metrics into a single metric."
},
{
"code": null,
"e": 13959,
"s": 13912,
"text": "Sim(z1,z2) = Max(S(z1,z2),S2(z1,z2),T(z1,z2) )"
},
{
"code": null,
"e": 14136,
"s": 13959,
"text": "Industries Similarity Metric: Finally, for industry, we will use the Jaccard coefficient on their word-sets as the similarity metric, further transformed via a sigmoid. That is"
},
{
"code": null,
"e": 14198,
"s": 14136,
"text": "S_industry(I1,I2) = sigmoid_{a,b}(Jaccard-coefficient(I1,I2))"
},
{
"code": null,
"e": 14586,
"s": 14198,
"text": "We will not describe how to choose the default values of a and bin detail. Rather, we will just note that ashould be positive and greater than 1 and b should be chosen to be the value of the Jaccard-coefficient we deem to be at the edge of similarity. Note that the Jaccard-coefficient returns a value between 0 and 1 where 0 denotes maximally dissimilar and 1 denotes maximally similar."
},
{
"code": null,
"e": 14606,
"s": 14586,
"text": "Multi-factor Metric"
},
{
"code": null,
"e": 15104,
"s": 14606,
"text": "We are now ready to build our multi-factor metric on top of these metrics. First, let’s briefly discuss the pros and cons of this approach. This modular design makes it easy to add new factors or to delete existing ones. It also makes it easy to adjust the relative influence of the similarities of individual factor values towards the overall metric. That said, it does not naturally model interactions among factors. To model these, one will need to explicitly add in specific interaction terms."
},
{
"code": null,
"e": 15131,
"s": 15104,
"text": "Our multi-factor metric is"
},
{
"code": null,
"e": 15288,
"s": 15131,
"text": "S(C1,C2) = w_zip*S_zip(C1.zip,C2.zip) + w_industry*S_industry(C1.industry,C2.industry) + w_company_size*S(C1.company_size_bin_rank,C2.company_size_bin_rank)"
},
{
"code": null,
"e": 15407,
"s": 15288,
"text": "The factor weights let us control the relative influences of the individual factor similarities in the overall metric."
},
{
"code": null,
"e": 15899,
"s": 15407,
"text": "Specializations: Now that we have this metric, we can build various specializations of it by simply setting certain factor weights to 0. So we can realize all single-factor versions — similarity-by-zip, similarity-by-industry, similarity-by-company-size — and also all two-factor versions. Armed with these specializations we can build segments more flexibly. Effectively we can group by one factor, by two factors, or by all three factors. Note that“group by” really means “fuzzy group by”."
},
{
"code": null,
"e": 16312,
"s": 15899,
"text": "Clustering the Matrix of Similarities: The key point we’d like to bring out is that the natural way to leverage the pairwise similarity metrics we have defined is to compute pairwise similarities among all pairs of companies and capture these in a similarity matrix. (That is unless the number of companies is so large that computing pairwise similarities will run too slow. We will assume this is not the case.)"
},
{
"code": null,
"e": 16611,
"s": 16312,
"text": "Clustering algorithms may then work directly on this matrix. This separates concerns. Clustering algorithms only operate on a similarity matrix, not caring how it was produced. The similarity metrics focus on quantifying the actual similarities, not caring how objects will be clustered downstream."
},
{
"code": null,
"e": 16965,
"s": 16611,
"text": "A Specific Algorithm — Graph Partitioning: Let’s see a concrete clustering algorithm on a similarity matrix. We’ll express the matrix as a graph. The graph’s nodes are the objects, in our case companies. Two nodes are connected by an edge if the corresponding objects are sufficiently similar. The weight on an edge captures the actual similarity value."
},
{
"code": null,
"e": 17210,
"s": 16965,
"text": "The high-level idea of the algorithm is to partition the graph into dense subgraphs connected by sparse crossing regions. Dense subgraphs will represent tight clusters. Sparse crossing regions will ensure that these clusters are well-separated."
},
{
"code": null,
"e": 17274,
"s": 17210,
"text": "Let’s refine this description. We need some key concepts first."
},
{
"code": null,
"e": 17644,
"s": 17274,
"text": "Subgraph Density: We define the density of a subgraph on k nodes as the sum of the weights on the edges that connect pairs of nodes within this set divided by k(k-1)/2. This assumes that the weight on an edge is between 0 and 1. Non-edges may be viewed as edges with weight 0. Under this representation, the density of a subgraph is the average weight of an edge in it."
},
{
"code": null,
"e": 17998,
"s": 17644,
"text": "Node Weights: We define the weight of a node as the sum of the weights of the edges touching the node. We define the weight of a node on a node-set as the sum of the weights of edges touching this node whose other endpoint is in that set. As an example, the weight of node a on nodes b, c, and d is the sum of the weights of the edges a-b, a-c, and a-d."
},
{
"code": null,
"e": 18097,
"s": 17998,
"text": "The Actual Algorithm: Next, we describe a simple heuristic algorithm that finds a good clustering."
},
{
"code": null,
"e": 18417,
"s": 18097,
"text": "find_one_good_cluster(G) C = {v}, where v is a highest-weight node in G Repeat Find a node v in G-C whose weight on C is sufficiently high. If no such v exists Close C. remaining_clusters = find_one_good_cluster(G-C) Return remaining_clusters + {C} Else Add v to C forever"
},
{
"code": null,
"e": 18943,
"s": 18417,
"text": "The “sufficiently high” test biases the algorithm to find tight clusters. (Tightness is not guaranteed as the tightness check is done only when a node is added to a cluster.) The algorithm does not explicitly favor cross-cluster sparsity. This happens implicitly. A cluster keeps growing as long as a node outside of it has sufficiently high cumulative weight to nodes in it. Consequently, when a cluster stops growing, all nodes outside it have low cumulative weight to nodes in it. This favors sparse cross-cluster regions."
},
{
"code": null,
"e": 18951,
"s": 18943,
"text": "Summary"
},
{
"code": null,
"e": 19307,
"s": 18951,
"text": "In this post, we have seen how clustering as a data science method is a good fit for market segmentation as a use case. We’ve looked into factors to use for B2B vs B2C segmentation. We have examined issues that arise when a factor has clean values; when a factor has a long tail of unstructured values; and when a factor has a small set of ordinal values."
},
{
"code": null,
"e": 19669,
"s": 19307,
"text": "We have discussed flat clustering, soft clustering, and hierarchical clustering. We have looked at how domain knowledge can guide us into what algorithms to use, even to the point of moving us away from standard algorithms. (I am referring to clustering industry names into a hierarchy of industries leveraging the linguistic structure implicit in these names.)"
}
] |
Python 3 - Files I/O | This chapter covers all the basic I/O functions available in Python 3. For more functions, please refer to the standard Python documentation.
The simplest way to produce output is using the print statement where you can pass zero or more expressions separated by commas. This function converts the expressions you pass into a string and writes the result to standard output as follows −
#!/usr/bin/python3
print ("Python is really a great language,", "isn't it?")
This produces the following result on your standard screen −
Python is really a great language, isn't it?
Python 2 has two built-in functions to read data from standard input, which by default comes from the keyboard. These functions are input() and raw_input()
In Python 3, raw_input() function is deprecated. Moreover, input() functions read data from keyboard as string, irrespective of whether it is enclosed with quotes ('' or "" ) or not.
The input([prompt]) function is equivalent to raw_input, except that it assumes that the input is a valid Python expression and returns the evaluated result to you.
#!/usr/bin/python3
>>> x = input("something:")
something:10
>>> x
'10'
>>> x = input("something:")
something:'10' #entered data treated as string with or without ''
>>> x
"'10'"
Until now, you have been reading and writing to the standard input and output. Now, we will see how to use actual data files.
Python provides basic functions and methods necessary to manipulate files by default. You can do most of the file manipulation using a file object.
Before you can read or write a file, you have to open it using Python's built-in open() function. This function creates a file object, which would be utilized to call other support methods associated with it.
file object = open(file_name [, access_mode][, buffering])
Here are parameter details −
file_name − The file_name argument is a string value that contains the name of the file that you want to access.
file_name − The file_name argument is a string value that contains the name of the file that you want to access.
access_mode − The access_mode determines the mode in which the file has to be opened, i.e., read, write, append, etc. A complete list of possible values is given below in the table. This is an optional parameter and the default file access mode is read (r).
access_mode − The access_mode determines the mode in which the file has to be opened, i.e., read, write, append, etc. A complete list of possible values is given below in the table. This is an optional parameter and the default file access mode is read (r).
buffering − If the buffering value is set to 0, no buffering takes place. If the buffering value is 1, line buffering is performed while accessing a file. If you specify the buffering value as an integer greater than 1, then buffering action is performed with the indicated buffer size. If negative, the buffer size is the system default(default behavior).
buffering − If the buffering value is set to 0, no buffering takes place. If the buffering value is 1, line buffering is performed while accessing a file. If you specify the buffering value as an integer greater than 1, then buffering action is performed with the indicated buffer size. If negative, the buffer size is the system default(default behavior).
Here is a list of the different modes of opening a file −
r
Opens a file for reading only. The file pointer is placed at the beginning of the file. This is the default mode.
rb
Opens a file for reading only in binary format. The file pointer is placed at the beginning of the file. This is the default mode.
r+
Opens a file for both reading and writing. The file pointer placed at the beginning of the file.
rb+
Opens a file for both reading and writing in binary format. The file pointer placed at the beginning of the file.
w
Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.
wb
Opens a file for writing only in binary format. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.
w+
Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.
wb+
Opens a file for both writing and reading in binary format. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.
a
Opens a file for appending. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.
ab
Opens a file for appending in binary format. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.
a+
Opens a file for both appending and reading. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.
ab+
Opens a file for both appending and reading in binary format. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.
Once a file is opened and you have one file object, you can get various information related to that file.
Here is a list of all the attributes related to a file object −
file.closed
Returns true if file is closed, false otherwise.
file.mode
Returns access mode with which file was opened.
file.name
Returns name of the file.
Note − softspace attribute is not supported in Python 3.x
#!/usr/bin/python3
# Open a file
fo = open("foo.txt", "wb")
print ("Name of the file: ", fo.name)
print ("Closed or not : ", fo.closed)
print ("Opening mode : ", fo.mode)
fo.close()
This produces the following result −
Name of the file: foo.txt
Closed or not : False
Opening mode : wb
The close() method of a file object flushes any unwritten information and closes the file object, after which no more writing can be done.
Python automatically closes a file when the reference object of a file is reassigned to another file. It is a good practice to use the close() method to close a file.
fileObject.close();
#!/usr/bin/python3
# Open a file
fo = open("foo.txt", "wb")
print ("Name of the file: ", fo.name)
# Close opened file
fo.close()
This produces the following result −
Name of the file: foo.txt
The file object provides a set of access methods to make our lives easier. We would see how to use read() and write() methods to read and write files.
The write() method writes any string to an open file. It is important to note that Python strings can have binary data and not just text.
The write() method does not add a newline character ('\n') to the end of the string −
fileObject.write(string);
Here, passed parameter is the content to be written into the opened file.
#!/usr/bin/python3
# Open a file
fo = open("foo.txt", "w")
fo.write( "Python is a great language.\nYeah its great!!\n")
# Close opend file
fo.close()
The above method would create foo.txt file and would write given content in that file and finally it would close that file. If you would open this file, it would have the following content −
Python is a great language.
Yeah its great!!
The read() method reads a string from an open file. It is important to note that Python strings can have binary data. apart from text data.
fileObject.read([count]);
Here, passed parameter is the number of bytes to be read from the opened file. This method starts reading from the beginning of the file and if count is missing, then it tries to read as much as possible, maybe until the end of file.
Let us take a file foo.txt, which we created above.
#!/usr/bin/python3
# Open a file
fo = open("foo.txt", "r+")
str = fo.read(10)
print ("Read String is : ", str)
# Close opened file
fo.close()
This produces the following result −
Read String is : Python is
The tell() method tells you the current position within the file; in other words, the next read or write will occur at that many bytes from the beginning of the file.
The seek(offset[, from]) method changes the current file position. The offset argument indicates the number of bytes to be moved. The from argument specifies the reference position from where the bytes are to be moved.
If from is set to 0, the beginning of the file is used as the reference position. If it is set to 1, the current position is used as the reference position. If it is set to 2 then the end of the file would be taken as the reference position.
Let us take a file foo.txt, which we created above.
#!/usr/bin/python3
# Open a file
fo = open("foo.txt", "r+")
str = fo.read(10)
print ("Read String is : ", str)
# Check current position
position = fo.tell()
print ("Current file position : ", position)
# Reposition pointer at the beginning once again
position = fo.seek(0, 0)
str = fo.read(10)
print ("Again read String is : ", str)
# Close opened file
fo.close()
This produces the following result −
Read String is : Python is
Current file position : 10
Again read String is : Python is
Python os module provides methods that help you perform file-processing operations, such as renaming and deleting files.
To use this module, you need to import it first and then you can call any related functions.
The rename() method takes two arguments, the current filename and the new filename.
os.rename(current_file_name, new_file_name)
Following is an example to rename an existing file test1.txt −
#!/usr/bin/python3
import os
# Rename a file from test1.txt to test2.txt
os.rename( "test1.txt", "test2.txt" )
You can use the remove() method to delete files by supplying the name of the file to be deleted as the argument.
os.remove(file_name)
Following is an example to delete an existing file test2.txt −
#!/usr/bin/python3
import os
# Delete file test2.txt
os.remove("text2.txt")
All files are contained within various directories, and Python has no problem handling these too. The os module has several methods that help you create, remove, and change directories.
You can use the mkdir() method of the os module to create directories in the current directory. You need to supply an argument to this method, which contains the name of the directory to be created.
os.mkdir("newdir")
Following is an example to create a directory test in the current directory −
#!/usr/bin/python3
import os
# Create a directory "test"
os.mkdir("test")
You can use the chdir() method to change the current directory. The chdir() method takes an argument, which is the name of the directory that you want to make the current directory.
os.chdir("newdir")
Following is an example to go into "/home/newdir" directory −
#!/usr/bin/python3
import os
# Changing a directory to "/home/newdir"
os.chdir("/home/newdir")
The getcwd() method displays the current working directory.
os.getcwd()
Following is an example to give current directory −
#!/usr/bin/python3
import os
# This would give location of the current directory
os.getcwd()
The rmdir() method deletes the directory, which is passed as an argument in the method.
Before removing a directory, all the contents in it should be removed.
os.rmdir('dirname')
Following is an example to remove the "/tmp/test" directory. It is required to give fully qualified name of the directory, otherwise it would search for that directory in the current directory.
#!/usr/bin/python3
import os
# This would remove "/tmp/test" directory.
os.rmdir( "/tmp/test" )
There are three important sources, which provide a wide range of utility methods to handle and manipulate files & directories on Windows and Unix operating systems. They are as follows −
File Object Methods
The file object provides functions to manipulate files.
File Object Methods
The file object provides functions to manipulate files.
OS Object Methods
This provides methods to process files as well as directories.
OS Object Methods
This provides methods to process files as well as directories.
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2482,
"s": 2340,
"text": "This chapter covers all the basic I/O functions available in Python 3. For more functions, please refer to the standard Python documentation."
},
{
"code": null,
"e": 2727,
"s": 2482,
"text": "The simplest way to produce output is using the print statement where you can pass zero or more expressions separated by commas. This function converts the expressions you pass into a string and writes the result to standard output as follows −"
},
{
"code": null,
"e": 2805,
"s": 2727,
"text": "#!/usr/bin/python3\n\nprint (\"Python is really a great language,\", \"isn't it?\")"
},
{
"code": null,
"e": 2866,
"s": 2805,
"text": "This produces the following result on your standard screen −"
},
{
"code": null,
"e": 2912,
"s": 2866,
"text": "Python is really a great language, isn't it?\n"
},
{
"code": null,
"e": 3068,
"s": 2912,
"text": "Python 2 has two built-in functions to read data from standard input, which by default comes from the keyboard. These functions are input() and raw_input()"
},
{
"code": null,
"e": 3251,
"s": 3068,
"text": "In Python 3, raw_input() function is deprecated. Moreover, input() functions read data from keyboard as string, irrespective of whether it is enclosed with quotes ('' or \"\" ) or not."
},
{
"code": null,
"e": 3416,
"s": 3251,
"text": "The input([prompt]) function is equivalent to raw_input, except that it assumes that the input is a valid Python expression and returns the evaluated result to you."
},
{
"code": null,
"e": 3598,
"s": 3416,
"text": "#!/usr/bin/python3\n\n>>> x = input(\"something:\")\nsomething:10\n\n>>> x\n'10'\n\n>>> x = input(\"something:\")\nsomething:'10' #entered data treated as string with or without ''\n\n>>> x\n\"'10'\""
},
{
"code": null,
"e": 3724,
"s": 3598,
"text": "Until now, you have been reading and writing to the standard input and output. Now, we will see how to use actual data files."
},
{
"code": null,
"e": 3872,
"s": 3724,
"text": "Python provides basic functions and methods necessary to manipulate files by default. You can do most of the file manipulation using a file object."
},
{
"code": null,
"e": 4081,
"s": 3872,
"text": "Before you can read or write a file, you have to open it using Python's built-in open() function. This function creates a file object, which would be utilized to call other support methods associated with it."
},
{
"code": null,
"e": 4141,
"s": 4081,
"text": "file object = open(file_name [, access_mode][, buffering])\n"
},
{
"code": null,
"e": 4170,
"s": 4141,
"text": "Here are parameter details −"
},
{
"code": null,
"e": 4283,
"s": 4170,
"text": "file_name − The file_name argument is a string value that contains the name of the file that you want to access."
},
{
"code": null,
"e": 4396,
"s": 4283,
"text": "file_name − The file_name argument is a string value that contains the name of the file that you want to access."
},
{
"code": null,
"e": 4654,
"s": 4396,
"text": "access_mode − The access_mode determines the mode in which the file has to be opened, i.e., read, write, append, etc. A complete list of possible values is given below in the table. This is an optional parameter and the default file access mode is read (r)."
},
{
"code": null,
"e": 4912,
"s": 4654,
"text": "access_mode − The access_mode determines the mode in which the file has to be opened, i.e., read, write, append, etc. A complete list of possible values is given below in the table. This is an optional parameter and the default file access mode is read (r)."
},
{
"code": null,
"e": 5270,
"s": 4912,
"text": "buffering − If the buffering value is set to 0, no buffering takes place. If the buffering value is 1, line buffering is performed while accessing a file. If you specify the buffering value as an integer greater than 1, then buffering action is performed with the indicated buffer size. If negative, the buffer size is the system default(default behavior)."
},
{
"code": null,
"e": 5628,
"s": 5270,
"text": "buffering − If the buffering value is set to 0, no buffering takes place. If the buffering value is 1, line buffering is performed while accessing a file. If you specify the buffering value as an integer greater than 1, then buffering action is performed with the indicated buffer size. If negative, the buffer size is the system default(default behavior)."
},
{
"code": null,
"e": 5686,
"s": 5628,
"text": "Here is a list of the different modes of opening a file −"
},
{
"code": null,
"e": 5688,
"s": 5686,
"text": "r"
},
{
"code": null,
"e": 5802,
"s": 5688,
"text": "Opens a file for reading only. The file pointer is placed at the beginning of the file. This is the default mode."
},
{
"code": null,
"e": 5805,
"s": 5802,
"text": "rb"
},
{
"code": null,
"e": 5936,
"s": 5805,
"text": "Opens a file for reading only in binary format. The file pointer is placed at the beginning of the file. This is the default mode."
},
{
"code": null,
"e": 5939,
"s": 5936,
"text": "r+"
},
{
"code": null,
"e": 6036,
"s": 5939,
"text": "Opens a file for both reading and writing. The file pointer placed at the beginning of the file."
},
{
"code": null,
"e": 6040,
"s": 6036,
"text": "rb+"
},
{
"code": null,
"e": 6154,
"s": 6040,
"text": "Opens a file for both reading and writing in binary format. The file pointer placed at the beginning of the file."
},
{
"code": null,
"e": 6156,
"s": 6154,
"text": "w"
},
{
"code": null,
"e": 6287,
"s": 6156,
"text": "Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing."
},
{
"code": null,
"e": 6290,
"s": 6287,
"text": "wb"
},
{
"code": null,
"e": 6438,
"s": 6290,
"text": "Opens a file for writing only in binary format. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing."
},
{
"code": null,
"e": 6441,
"s": 6438,
"text": "w+"
},
{
"code": null,
"e": 6605,
"s": 6441,
"text": "Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing."
},
{
"code": null,
"e": 6609,
"s": 6605,
"text": "wb+"
},
{
"code": null,
"e": 6790,
"s": 6609,
"text": "Opens a file for both writing and reading in binary format. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing."
},
{
"code": null,
"e": 6792,
"s": 6790,
"text": "a"
},
{
"code": null,
"e": 6987,
"s": 6792,
"text": "Opens a file for appending. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing."
},
{
"code": null,
"e": 6990,
"s": 6987,
"text": "ab"
},
{
"code": null,
"e": 7202,
"s": 6990,
"text": "Opens a file for appending in binary format. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing."
},
{
"code": null,
"e": 7205,
"s": 7202,
"text": "a+"
},
{
"code": null,
"e": 7423,
"s": 7205,
"text": "Opens a file for both appending and reading. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing."
},
{
"code": null,
"e": 7427,
"s": 7423,
"text": "ab+"
},
{
"code": null,
"e": 7662,
"s": 7427,
"text": "Opens a file for both appending and reading in binary format. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing."
},
{
"code": null,
"e": 7768,
"s": 7662,
"text": "Once a file is opened and you have one file object, you can get various information related to that file."
},
{
"code": null,
"e": 7832,
"s": 7768,
"text": "Here is a list of all the attributes related to a file object −"
},
{
"code": null,
"e": 7844,
"s": 7832,
"text": "file.closed"
},
{
"code": null,
"e": 7893,
"s": 7844,
"text": "Returns true if file is closed, false otherwise."
},
{
"code": null,
"e": 7903,
"s": 7893,
"text": "file.mode"
},
{
"code": null,
"e": 7951,
"s": 7903,
"text": "Returns access mode with which file was opened."
},
{
"code": null,
"e": 7961,
"s": 7951,
"text": "file.name"
},
{
"code": null,
"e": 7987,
"s": 7961,
"text": "Returns name of the file."
},
{
"code": null,
"e": 8045,
"s": 7987,
"text": "Note − softspace attribute is not supported in Python 3.x"
},
{
"code": null,
"e": 8228,
"s": 8045,
"text": "#!/usr/bin/python3\n\n# Open a file\nfo = open(\"foo.txt\", \"wb\")\nprint (\"Name of the file: \", fo.name)\nprint (\"Closed or not : \", fo.closed)\nprint (\"Opening mode : \", fo.mode)\nfo.close()"
},
{
"code": null,
"e": 8265,
"s": 8228,
"text": "This produces the following result −"
},
{
"code": null,
"e": 8335,
"s": 8265,
"text": "Name of the file: foo.txt\nClosed or not : False\nOpening mode : wb\n"
},
{
"code": null,
"e": 8474,
"s": 8335,
"text": "The close() method of a file object flushes any unwritten information and closes the file object, after which no more writing can be done."
},
{
"code": null,
"e": 8641,
"s": 8474,
"text": "Python automatically closes a file when the reference object of a file is reassigned to another file. It is a good practice to use the close() method to close a file."
},
{
"code": null,
"e": 8662,
"s": 8641,
"text": "fileObject.close();\n"
},
{
"code": null,
"e": 8793,
"s": 8662,
"text": "#!/usr/bin/python3\n\n# Open a file\nfo = open(\"foo.txt\", \"wb\")\nprint (\"Name of the file: \", fo.name)\n\n# Close opened file\nfo.close()"
},
{
"code": null,
"e": 8830,
"s": 8793,
"text": "This produces the following result −"
},
{
"code": null,
"e": 8858,
"s": 8830,
"text": "Name of the file: foo.txt\n"
},
{
"code": null,
"e": 9009,
"s": 8858,
"text": "The file object provides a set of access methods to make our lives easier. We would see how to use read() and write() methods to read and write files."
},
{
"code": null,
"e": 9147,
"s": 9009,
"text": "The write() method writes any string to an open file. It is important to note that Python strings can have binary data and not just text."
},
{
"code": null,
"e": 9233,
"s": 9147,
"text": "The write() method does not add a newline character ('\\n') to the end of the string −"
},
{
"code": null,
"e": 9260,
"s": 9233,
"text": "fileObject.write(string);\n"
},
{
"code": null,
"e": 9334,
"s": 9260,
"text": "Here, passed parameter is the content to be written into the opened file."
},
{
"code": null,
"e": 9486,
"s": 9334,
"text": "#!/usr/bin/python3\n\n# Open a file\nfo = open(\"foo.txt\", \"w\")\nfo.write( \"Python is a great language.\\nYeah its great!!\\n\")\n\n# Close opend file\nfo.close()"
},
{
"code": null,
"e": 9677,
"s": 9486,
"text": "The above method would create foo.txt file and would write given content in that file and finally it would close that file. If you would open this file, it would have the following content −"
},
{
"code": null,
"e": 9723,
"s": 9677,
"text": "Python is a great language.\nYeah its great!!\n"
},
{
"code": null,
"e": 9863,
"s": 9723,
"text": "The read() method reads a string from an open file. It is important to note that Python strings can have binary data. apart from text data."
},
{
"code": null,
"e": 9890,
"s": 9863,
"text": "fileObject.read([count]);\n"
},
{
"code": null,
"e": 10124,
"s": 9890,
"text": "Here, passed parameter is the number of bytes to be read from the opened file. This method starts reading from the beginning of the file and if count is missing, then it tries to read as much as possible, maybe until the end of file."
},
{
"code": null,
"e": 10177,
"s": 10124,
"text": " Let us take a file foo.txt, which we created above."
},
{
"code": null,
"e": 10321,
"s": 10177,
"text": "#!/usr/bin/python3\n\n# Open a file\nfo = open(\"foo.txt\", \"r+\")\nstr = fo.read(10)\nprint (\"Read String is : \", str)\n\n# Close opened file\nfo.close()"
},
{
"code": null,
"e": 10358,
"s": 10321,
"text": "This produces the following result −"
},
{
"code": null,
"e": 10387,
"s": 10358,
"text": "Read String is : Python is\n"
},
{
"code": null,
"e": 10554,
"s": 10387,
"text": "The tell() method tells you the current position within the file; in other words, the next read or write will occur at that many bytes from the beginning of the file."
},
{
"code": null,
"e": 10773,
"s": 10554,
"text": "The seek(offset[, from]) method changes the current file position. The offset argument indicates the number of bytes to be moved. The from argument specifies the reference position from where the bytes are to be moved."
},
{
"code": null,
"e": 11015,
"s": 10773,
"text": "If from is set to 0, the beginning of the file is used as the reference position. If it is set to 1, the current position is used as the reference position. If it is set to 2 then the end of the file would be taken as the reference position."
},
{
"code": null,
"e": 11068,
"s": 11015,
"text": " Let us take a file foo.txt, which we created above."
},
{
"code": null,
"e": 11436,
"s": 11068,
"text": "#!/usr/bin/python3\n\n# Open a file\nfo = open(\"foo.txt\", \"r+\")\nstr = fo.read(10)\nprint (\"Read String is : \", str)\n\n# Check current position\nposition = fo.tell()\nprint (\"Current file position : \", position)\n\n# Reposition pointer at the beginning once again\nposition = fo.seek(0, 0)\nstr = fo.read(10)\nprint (\"Again read String is : \", str)\n\n# Close opened file\nfo.close()"
},
{
"code": null,
"e": 11473,
"s": 11436,
"text": "This produces the following result −"
},
{
"code": null,
"e": 11564,
"s": 11473,
"text": "Read String is : Python is\nCurrent file position : 10\nAgain read String is : Python is\n"
},
{
"code": null,
"e": 11685,
"s": 11564,
"text": "Python os module provides methods that help you perform file-processing operations, such as renaming and deleting files."
},
{
"code": null,
"e": 11778,
"s": 11685,
"text": "To use this module, you need to import it first and then you can call any related functions."
},
{
"code": null,
"e": 11862,
"s": 11778,
"text": "The rename() method takes two arguments, the current filename and the new filename."
},
{
"code": null,
"e": 11907,
"s": 11862,
"text": "os.rename(current_file_name, new_file_name)\n"
},
{
"code": null,
"e": 11970,
"s": 11907,
"text": "Following is an example to rename an existing file test1.txt −"
},
{
"code": null,
"e": 12082,
"s": 11970,
"text": "#!/usr/bin/python3\nimport os\n\n# Rename a file from test1.txt to test2.txt\nos.rename( \"test1.txt\", \"test2.txt\" )"
},
{
"code": null,
"e": 12195,
"s": 12082,
"text": "You can use the remove() method to delete files by supplying the name of the file to be deleted as the argument."
},
{
"code": null,
"e": 12217,
"s": 12195,
"text": "os.remove(file_name)\n"
},
{
"code": null,
"e": 12280,
"s": 12217,
"text": "Following is an example to delete an existing file test2.txt −"
},
{
"code": null,
"e": 12357,
"s": 12280,
"text": "#!/usr/bin/python3\nimport os\n\n# Delete file test2.txt\nos.remove(\"text2.txt\")"
},
{
"code": null,
"e": 12543,
"s": 12357,
"text": "All files are contained within various directories, and Python has no problem handling these too. The os module has several methods that help you create, remove, and change directories."
},
{
"code": null,
"e": 12742,
"s": 12543,
"text": "You can use the mkdir() method of the os module to create directories in the current directory. You need to supply an argument to this method, which contains the name of the directory to be created."
},
{
"code": null,
"e": 12762,
"s": 12742,
"text": "os.mkdir(\"newdir\")\n"
},
{
"code": null,
"e": 12840,
"s": 12762,
"text": "Following is an example to create a directory test in the current directory −"
},
{
"code": null,
"e": 12915,
"s": 12840,
"text": "#!/usr/bin/python3\nimport os\n\n# Create a directory \"test\"\nos.mkdir(\"test\")"
},
{
"code": null,
"e": 13097,
"s": 12915,
"text": "You can use the chdir() method to change the current directory. The chdir() method takes an argument, which is the name of the directory that you want to make the current directory."
},
{
"code": null,
"e": 13117,
"s": 13097,
"text": "os.chdir(\"newdir\")\n"
},
{
"code": null,
"e": 13179,
"s": 13117,
"text": "Following is an example to go into \"/home/newdir\" directory −"
},
{
"code": null,
"e": 13275,
"s": 13179,
"text": "#!/usr/bin/python3\nimport os\n\n# Changing a directory to \"/home/newdir\"\nos.chdir(\"/home/newdir\")"
},
{
"code": null,
"e": 13335,
"s": 13275,
"text": "The getcwd() method displays the current working directory."
},
{
"code": null,
"e": 13348,
"s": 13335,
"text": "os.getcwd()\n"
},
{
"code": null,
"e": 13400,
"s": 13348,
"text": "Following is an example to give current directory −"
},
{
"code": null,
"e": 13494,
"s": 13400,
"text": "#!/usr/bin/python3\nimport os\n\n# This would give location of the current directory\nos.getcwd()"
},
{
"code": null,
"e": 13582,
"s": 13494,
"text": "The rmdir() method deletes the directory, which is passed as an argument in the method."
},
{
"code": null,
"e": 13653,
"s": 13582,
"text": "Before removing a directory, all the contents in it should be removed."
},
{
"code": null,
"e": 13674,
"s": 13653,
"text": "os.rmdir('dirname')\n"
},
{
"code": null,
"e": 13868,
"s": 13674,
"text": "Following is an example to remove the \"/tmp/test\" directory. It is required to give fully qualified name of the directory, otherwise it would search for that directory in the current directory."
},
{
"code": null,
"e": 13968,
"s": 13868,
"text": "#!/usr/bin/python3\nimport os\n\n# This would remove \"/tmp/test\" directory.\nos.rmdir( \"/tmp/test\" )"
},
{
"code": null,
"e": 14155,
"s": 13968,
"text": "There are three important sources, which provide a wide range of utility methods to handle and manipulate files & directories on Windows and Unix operating systems. They are as follows −"
},
{
"code": null,
"e": 14231,
"s": 14155,
"text": "File Object Methods\nThe file object provides functions to manipulate files."
},
{
"code": null,
"e": 14251,
"s": 14231,
"text": "File Object Methods"
},
{
"code": null,
"e": 14307,
"s": 14251,
"text": "The file object provides functions to manipulate files."
},
{
"code": null,
"e": 14388,
"s": 14307,
"text": "OS Object Methods\nThis provides methods to process files as well as directories."
},
{
"code": null,
"e": 14406,
"s": 14388,
"text": "OS Object Methods"
},
{
"code": null,
"e": 14469,
"s": 14406,
"text": "This provides methods to process files as well as directories."
},
{
"code": null,
"e": 14506,
"s": 14469,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 14522,
"s": 14506,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 14555,
"s": 14522,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 14574,
"s": 14555,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 14609,
"s": 14574,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 14631,
"s": 14609,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 14665,
"s": 14631,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 14693,
"s": 14665,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 14728,
"s": 14693,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 14742,
"s": 14728,
"text": " Lets Kode It"
},
{
"code": null,
"e": 14775,
"s": 14742,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 14792,
"s": 14775,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 14799,
"s": 14792,
"text": " Print"
},
{
"code": null,
"e": 14810,
"s": 14799,
"text": " Add Notes"
}
] |
How can I create a simple message box in Tkinter? | Tkinter is a popular Python library for creating and developing applications. It has
various methods and functions that can be used for adding multiple features in an
application. Using Tkinter, we can create dialogue boxes and other widgets.
In this article, we will see how we can create a simple message box that will pop
up and display some information to select an option.
#Import the required libraries
from tkinter import *
from tkinter import messagebox
#Create an instance of tkinter frame or window
win= Tk()
#Set the geometry
win.geometry("700x100")
#Define the function for button
def pop_up():
messagebox.showerror("Error! Please check and correct.")
messagebox.showwarning("Warning! You can not proceed.")
#Create a button
Button(win, text="Click",command= pop_up).pack(pady=20)
#Keep Running the window
win.mainloop()
Running the above code will produce the following window.
If you click the “Click” button, the following error message will pop up.
Again, if you click the “OK” button, it will pop up the following warning message. | [
{
"code": null,
"e": 1305,
"s": 1062,
"text": "Tkinter is a popular Python library for creating and developing applications. It has\nvarious methods and functions that can be used for adding multiple features in an\napplication. Using Tkinter, we can create dialogue boxes and other widgets."
},
{
"code": null,
"e": 1440,
"s": 1305,
"text": "In this article, we will see how we can create a simple message box that will pop\nup and display some information to select an option."
},
{
"code": null,
"e": 1905,
"s": 1440,
"text": "#Import the required libraries\nfrom tkinter import *\nfrom tkinter import messagebox\n#Create an instance of tkinter frame or window\nwin= Tk()\n\n#Set the geometry\nwin.geometry(\"700x100\")\n\n#Define the function for button\ndef pop_up():\n messagebox.showerror(\"Error! Please check and correct.\")\n messagebox.showwarning(\"Warning! You can not proceed.\")\n\n#Create a button\nButton(win, text=\"Click\",command= pop_up).pack(pady=20)\n\n#Keep Running the window\nwin.mainloop()"
},
{
"code": null,
"e": 1963,
"s": 1905,
"text": "Running the above code will produce the following window."
},
{
"code": null,
"e": 2037,
"s": 1963,
"text": "If you click the “Click” button, the following error message will pop up."
},
{
"code": null,
"e": 2120,
"s": 2037,
"text": "Again, if you click the “OK” button, it will pop up the following warning message."
}
] |
Array Copying in Python - GeeksforGeeks | 11 Aug, 2021
Let us see how to copy arrays in Python. There are 3 ways to copy arrays :
Simply using the assignment operator.
Shallow Copy
Deep Copy
We can create a copy of an array by using the assignment operator (=).
Syntax :
new_arr = old_ arr
In Python, Assignment statements do not copy objects, they create bindings between a target and an object. When we use = operator user thinks that this creates a new object; well, it doesn’t. It only creates a new variable that shares the reference of the original object.
Example:
Python3
# importing the modulefrom numpy import * # creating the first arrayarr1 = array([2, 6, 9, 4]) # displaying the identity of arr1print(id(arr1)) # assigning arr1 to arr2arr2 = arr1 # displaying the identity of arr2print(id(arr2)) # making a change in arr1arr1[1] = 7 # displaying the arraysprint(arr1)print(arr2)
Output :
117854800
117854800
[2 7 9 4]
[2 7 9 4]
We can see that both the arrays reference the same object.
A shallow copy means constructing a new collection object and then populating it with references to the child objects found in the original. The copying process does not recurse and therefore won’t create copies of the child objects themselves. In the case of shallow copy, a reference of the object is copied in another object. It means that any changes made to a copy of the object do reflect in the original object. We will be implementing shallow copy using the view() function.
Example :
Python3
# importing the modulefrom numpy import * # creating the first arrayarr1 = array([2, 6, 9, 4]) # displaying the identity of arr1print(id(arr1)) # shallow copy arr1 in arr2 using view()arr2 = arr1.view() # displaying the identity of arr2print(id(arr2)) # making a change in arr1arr1[1] = 7 # displaying the arraysprint(arr1)print(arr2)
This time although the 2 arrays reference different objects, still on changing the value of one, the value of another also changes.
Deep copy is a process in which the copying process occurs recursively. It means first constructing a new collection object and then recursively populating it with copies of the child objects found in the original. In the case of deep copy, a copy of the object is copied into another object. It means that any changes made to a copy of the object do not reflect in the original object. We will be implementing deep copy using the copy() function.
Python3
# importing the modulefrom numpy import * # creating the first arrayarr1 = array([2, 6, 9, 4]) # displaying the identity of arr1print(id(arr1)) # shallow copy arr1 in arr2 using view()arr2 = arr1.copy() # displaying the identity of arr2print(id(arr2)) # making a change in arr1arr1[1] = 7 # displaying the arraysprint(arr1)print(arr2)
Output :
121258976
125714048
[2 7 9 4]
[2 6 9 4]
This time the changes made in one array are not reflected in the other array.
If you are dealing with NumPy matrices, then numpy.copy() will give you a deep copy. However, if your matrix is simply a list of lists then consider the below two approaches in the task of rotating an image (represented as a list of a list) 90 degrees:
Python3
import copy def rotate_matrix(image): # Copy method one copy_image_one = copy.deepcopy(image) print("Original", matrix) print("Copy of original", copy_image_one) N = len(matrix) # Part 1, reverse order within each row for row in range(N): for column in range(N): copy_image_one[row][column] = image[row][N-column-1] print("After modification") print("Original", matrix) print("Copy", copy_image_one) # Copy method two copy_image_two = [list(row) for row in copy_image_one] # Test on what happens when you remove list from the above code. # Part 2, transpose for row in range(N): for column in range(N): copy_image_two[column][row] = copy_image_one[row][column] return copy_image_two if __name__ == "__main__": matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] print("Rotated image", rotate_matrix(matrix))
Output:
Original [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Copy of original [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
After modification
Original [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Copy [[3, 2, 1], [6, 5, 4], [9, 8, 7]]
Rotated image [[3, 6, 9], [2, 5, 8], [1, 4, 7]]
mdurranibscs16seecs
arorakashish0911
Python-array
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Selecting rows in pandas DataFrame based on conditions
Python | os.path.join() method
Defaultdict in Python
Create a directory in Python
Python | Get unique values from a list
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 24316,
"s": 24288,
"text": "\n11 Aug, 2021"
},
{
"code": null,
"e": 24392,
"s": 24316,
"text": "Let us see how to copy arrays in Python. There are 3 ways to copy arrays : "
},
{
"code": null,
"e": 24430,
"s": 24392,
"text": "Simply using the assignment operator."
},
{
"code": null,
"e": 24443,
"s": 24430,
"text": "Shallow Copy"
},
{
"code": null,
"e": 24453,
"s": 24443,
"text": "Deep Copy"
},
{
"code": null,
"e": 24525,
"s": 24453,
"text": "We can create a copy of an array by using the assignment operator (=). "
},
{
"code": null,
"e": 24535,
"s": 24525,
"text": "Syntax : "
},
{
"code": null,
"e": 24554,
"s": 24535,
"text": "new_arr = old_ arr"
},
{
"code": null,
"e": 24827,
"s": 24554,
"text": "In Python, Assignment statements do not copy objects, they create bindings between a target and an object. When we use = operator user thinks that this creates a new object; well, it doesn’t. It only creates a new variable that shares the reference of the original object."
},
{
"code": null,
"e": 24836,
"s": 24827,
"text": "Example:"
},
{
"code": null,
"e": 24844,
"s": 24836,
"text": "Python3"
},
{
"code": "# importing the modulefrom numpy import * # creating the first arrayarr1 = array([2, 6, 9, 4]) # displaying the identity of arr1print(id(arr1)) # assigning arr1 to arr2arr2 = arr1 # displaying the identity of arr2print(id(arr2)) # making a change in arr1arr1[1] = 7 # displaying the arraysprint(arr1)print(arr2)",
"e": 25235,
"s": 24844,
"text": null
},
{
"code": null,
"e": 25245,
"s": 25235,
"text": "Output : "
},
{
"code": null,
"e": 25285,
"s": 25245,
"text": "117854800\n117854800\n[2 7 9 4]\n[2 7 9 4]"
},
{
"code": null,
"e": 25345,
"s": 25285,
"text": "We can see that both the arrays reference the same object. "
},
{
"code": null,
"e": 25828,
"s": 25345,
"text": "A shallow copy means constructing a new collection object and then populating it with references to the child objects found in the original. The copying process does not recurse and therefore won’t create copies of the child objects themselves. In the case of shallow copy, a reference of the object is copied in another object. It means that any changes made to a copy of the object do reflect in the original object. We will be implementing shallow copy using the view() function."
},
{
"code": null,
"e": 25839,
"s": 25828,
"text": "Example : "
},
{
"code": null,
"e": 25847,
"s": 25839,
"text": "Python3"
},
{
"code": "# importing the modulefrom numpy import * # creating the first arrayarr1 = array([2, 6, 9, 4]) # displaying the identity of arr1print(id(arr1)) # shallow copy arr1 in arr2 using view()arr2 = arr1.view() # displaying the identity of arr2print(id(arr2)) # making a change in arr1arr1[1] = 7 # displaying the arraysprint(arr1)print(arr2)",
"e": 26226,
"s": 25847,
"text": null
},
{
"code": null,
"e": 26358,
"s": 26226,
"text": "This time although the 2 arrays reference different objects, still on changing the value of one, the value of another also changes."
},
{
"code": null,
"e": 26806,
"s": 26358,
"text": "Deep copy is a process in which the copying process occurs recursively. It means first constructing a new collection object and then recursively populating it with copies of the child objects found in the original. In the case of deep copy, a copy of the object is copied into another object. It means that any changes made to a copy of the object do not reflect in the original object. We will be implementing deep copy using the copy() function."
},
{
"code": null,
"e": 26814,
"s": 26806,
"text": "Python3"
},
{
"code": "# importing the modulefrom numpy import * # creating the first arrayarr1 = array([2, 6, 9, 4]) # displaying the identity of arr1print(id(arr1)) # shallow copy arr1 in arr2 using view()arr2 = arr1.copy() # displaying the identity of arr2print(id(arr2)) # making a change in arr1arr1[1] = 7 # displaying the arraysprint(arr1)print(arr2)",
"e": 27192,
"s": 26814,
"text": null
},
{
"code": null,
"e": 27202,
"s": 27192,
"text": "Output : "
},
{
"code": null,
"e": 27242,
"s": 27202,
"text": "121258976\n125714048\n[2 7 9 4]\n[2 6 9 4]"
},
{
"code": null,
"e": 27320,
"s": 27242,
"text": "This time the changes made in one array are not reflected in the other array."
},
{
"code": null,
"e": 27573,
"s": 27320,
"text": "If you are dealing with NumPy matrices, then numpy.copy() will give you a deep copy. However, if your matrix is simply a list of lists then consider the below two approaches in the task of rotating an image (represented as a list of a list) 90 degrees:"
},
{
"code": null,
"e": 27581,
"s": 27573,
"text": "Python3"
},
{
"code": "import copy def rotate_matrix(image): # Copy method one copy_image_one = copy.deepcopy(image) print(\"Original\", matrix) print(\"Copy of original\", copy_image_one) N = len(matrix) # Part 1, reverse order within each row for row in range(N): for column in range(N): copy_image_one[row][column] = image[row][N-column-1] print(\"After modification\") print(\"Original\", matrix) print(\"Copy\", copy_image_one) # Copy method two copy_image_two = [list(row) for row in copy_image_one] # Test on what happens when you remove list from the above code. # Part 2, transpose for row in range(N): for column in range(N): copy_image_two[column][row] = copy_image_one[row][column] return copy_image_two if __name__ == \"__main__\": matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] print(\"Rotated image\", rotate_matrix(matrix))",
"e": 28503,
"s": 27581,
"text": null
},
{
"code": null,
"e": 28511,
"s": 28503,
"text": "Output:"
},
{
"code": null,
"e": 28754,
"s": 28511,
"text": "Original [[1, 2, 3], [4, 5, 6], [7, 8, 9]]\nCopy of original [[1, 2, 3], [4, 5, 6], [7, 8, 9]]\nAfter modification\nOriginal [[1, 2, 3], [4, 5, 6], [7, 8, 9]]\nCopy [[3, 2, 1], [6, 5, 4], [9, 8, 7]]\nRotated image [[3, 6, 9], [2, 5, 8], [1, 4, 7]]"
},
{
"code": null,
"e": 28776,
"s": 28756,
"text": "mdurranibscs16seecs"
},
{
"code": null,
"e": 28793,
"s": 28776,
"text": "arorakashish0911"
},
{
"code": null,
"e": 28806,
"s": 28793,
"text": "Python-array"
},
{
"code": null,
"e": 28813,
"s": 28806,
"text": "Python"
},
{
"code": null,
"e": 28911,
"s": 28813,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28943,
"s": 28911,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28985,
"s": 28943,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 29041,
"s": 28985,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 29083,
"s": 29041,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 29138,
"s": 29083,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 29169,
"s": 29138,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 29191,
"s": 29169,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 29220,
"s": 29191,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 29259,
"s": 29220,
"text": "Python | Get unique values from a list"
}
] |
How do I create a popup window using Tkinter? | Tkinter supports toplevel classes, and these classes contain toplevel window. Toplevel window is also known as child window. We can create a toplevel window by creating the object of Toplevel(parent).
The toplevel window inherits all the properties of Tkinter's parent object. It can contain widgets, frames, canvas and other objects as well.
In this example, we will create a button that will open a popup window.
#Import the required libraries
from tkinter import *
#Create an instance of Tkinter Frame
win = Tk()
#Set the geometry
win.geometry("700x250")
def open_win():
#Create a Button to Open the Toplevel Window
top= Toplevel(win)
top.geometry("700x250")
top.title("Child Window")
#Create a label in Toplevel window
Label(top, text= "Hello World!")
Label(win, text= "Click the button to Open Popup Window", font= ('Helvetica 18')).place(relx=.5, rely=.5, anchor= CENTER)
Button(win, text= "Click Me", background= "white", foreground= "blue", font= ('Helvetica 13 bold'), command= open_win).pack(pady= 50)
win.mainloop()
Running the above code will display a window with a Label and a button.
Now, clicking the button will open a New Popup window. | [
{
"code": null,
"e": 1263,
"s": 1062,
"text": "Tkinter supports toplevel classes, and these classes contain toplevel window. Toplevel window is also known as child window. We can create a toplevel window by creating the object of Toplevel(parent)."
},
{
"code": null,
"e": 1405,
"s": 1263,
"text": "The toplevel window inherits all the properties of Tkinter's parent object. It can contain widgets, frames, canvas and other objects as well."
},
{
"code": null,
"e": 1477,
"s": 1405,
"text": "In this example, we will create a button that will open a popup window."
},
{
"code": null,
"e": 2111,
"s": 1477,
"text": "#Import the required libraries\nfrom tkinter import *\n\n#Create an instance of Tkinter Frame\nwin = Tk()\n\n#Set the geometry\nwin.geometry(\"700x250\")\n\ndef open_win():\n #Create a Button to Open the Toplevel Window\n top= Toplevel(win)\n top.geometry(\"700x250\")\n top.title(\"Child Window\")\n #Create a label in Toplevel window\n Label(top, text= \"Hello World!\")\n\nLabel(win, text= \"Click the button to Open Popup Window\", font= ('Helvetica 18')).place(relx=.5, rely=.5, anchor= CENTER)\nButton(win, text= \"Click Me\", background= \"white\", foreground= \"blue\", font= ('Helvetica 13 bold'), command= open_win).pack(pady= 50)\nwin.mainloop()"
},
{
"code": null,
"e": 2183,
"s": 2111,
"text": "Running the above code will display a window with a Label and a button."
},
{
"code": null,
"e": 2238,
"s": 2183,
"text": "Now, clicking the button will open a New Popup window."
}
] |
How to make an Android Spinner with initial default text using Kotlin? | This example demonstrates how to make an Android Spinner with initial default text 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:id="@+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="30dp"
android:text="Spinner Sample Program"
android:textColor="@android:color/background_dark"
android:textSize="16sp" />
<Spinner
android:id="@+id/spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="10dp">
</Spinner>
</LinearLayout>
Step 3 − Add the following code to src/MainActivity.kt
import android.os.Bundle
import android.view.View
import android.widget.AdapterView
import android.widget.AdapterView.OnItemSelectedListener
import android.widget.ArrayAdapter
import android.widget.Spinner
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
lateinit var spinner: Spinner
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
spinner = findViewById(R.id.spinner)
val footballPlayers: MutableList<String?> = ArrayList()
footballPlayers.add(0, "Select a player from the list")
footballPlayers.add("Cristian Ronaldo")
footballPlayers.add("Lionel Messi")
footballPlayers.add("Neymar Jr")
footballPlayers.add("Isco")
footballPlayers.add("Gareth Bale")
footballPlayers.add("Luis Suarez")
val arrayAdapter: ArrayAdapter<String?> = ArrayAdapter<String?>(this, android.R.layout.simple_list_item_1, footballPlayers)
arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
spinner.adapter = arrayAdapter
spinner.onItemSelectedListener = object : OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>, view: View?, position: Int, id: Long) {
if (parent.getItemAtPosition(position) == "Choose Football players from lis") {
}
else {
val item = parent.getItemAtPosition(position).toString()
Toast.makeText(parent.context, "Selected: $item", Toast.LENGTH_SHORT).show()
}
}
override fun onNothingSelected(parent: AdapterView<*>?) {}
}
}
}
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.
Click here to download the project code. | [
{
"code": null,
"e": 1159,
"s": 1062,
"text": "This example demonstrates how to make an Android Spinner with initial default text using Kotlin."
},
{
"code": null,
"e": 1288,
"s": 1159,
"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": 1353,
"s": 1288,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2273,
"s": 1353,
"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:id=\"@+id/linearLayout\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:orientation=\"vertical\"\n tools:context=\".MainActivity\">\n <TextView\n android:id=\"@+id/textView\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_gravity=\"center\"\n android:layout_marginTop=\"30dp\"\n android:text=\"Spinner Sample Program\"\n android:textColor=\"@android:color/background_dark\"\n android:textSize=\"16sp\" />\n <Spinner\n android:id=\"@+id/spinner\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_gravity=\"center\"\n android:layout_marginTop=\"10dp\">\n </Spinner>\n</LinearLayout>"
},
{
"code": null,
"e": 2328,
"s": 2273,
"text": "Step 3 − Add the following code to src/MainActivity.kt"
},
{
"code": null,
"e": 4092,
"s": 2328,
"text": "import android.os.Bundle\nimport android.view.View\nimport android.widget.AdapterView\nimport android.widget.AdapterView.OnItemSelectedListener\nimport android.widget.ArrayAdapter\nimport android.widget.Spinner\nimport android.widget.Toast\nimport androidx.appcompat.app.AppCompatActivity\nclass MainActivity : AppCompatActivity() {\n lateinit var spinner: Spinner\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n spinner = findViewById(R.id.spinner)\n val footballPlayers: MutableList<String?> = ArrayList()\n footballPlayers.add(0, \"Select a player from the list\")\n footballPlayers.add(\"Cristian Ronaldo\")\n footballPlayers.add(\"Lionel Messi\")\n footballPlayers.add(\"Neymar Jr\")\n footballPlayers.add(\"Isco\")\n footballPlayers.add(\"Gareth Bale\")\n footballPlayers.add(\"Luis Suarez\")\n val arrayAdapter: ArrayAdapter<String?> = ArrayAdapter<String?>(this, android.R.layout.simple_list_item_1, footballPlayers)\n arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)\n spinner.adapter = arrayAdapter\n spinner.onItemSelectedListener = object : OnItemSelectedListener {\n override fun onItemSelected(parent: AdapterView<*>, view: View?, position: Int, id: Long) {\n if (parent.getItemAtPosition(position) == \"Choose Football players from lis\") {\n }\n else {\n val item = parent.getItemAtPosition(position).toString()\n Toast.makeText(parent.context, \"Selected: $item\", Toast.LENGTH_SHORT).show()\n }\n }\n override fun onNothingSelected(parent: AdapterView<*>?) {}\n }\n }\n}"
},
{
"code": null,
"e": 4147,
"s": 4092,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 4818,
"s": 4147,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" 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": 5167,
"s": 4818,
"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."
},
{
"code": null,
"e": 5208,
"s": 5167,
"text": "Click here to download the project code."
}
] |
Group by element in array JavaScript | Suppose, we have an array of objects like this −
const arr = [
{"name": "toto", "uuid": 1111},
{"name": "tata", "uuid": 2222},
{"name": "titi", "uuid": 1111}
];
We are required to write a JavaScript function that splits the objects into separate array of
arrays that have the similar values for the uuid property.
Therefore, the output should look like this −
const output = [
[
{"name": "toto", "uuid": 1111},
{"name": "titi", "uuid": 1111}
],
[
{"name": "tata", "uuid": 2222}
]
];
The code for this will be −
const arr = [
{"name": "toto", "uuid": 1111},
{"name": "tata", "uuid": 2222},
{"name": "titi", "uuid": 1111}
];
const groupByElement = arr => {
const hash = Object.create(null),
result = [];
arr.forEach(el => {
if (!hash[el.uuid]) {
hash[el.uuid] = [];
result.push(hash[el.uuid]);
};
hash[el.uuid].push(el);
});
return result;
};
console.log(groupByElement(arr));
The output in the console −
[
[ { name: 'toto', uuid: 1111 }, { name: 'titi', uuid: 1111 } ],
[ { name: 'tata', uuid: 2222 } ]
] | [
{
"code": null,
"e": 1111,
"s": 1062,
"text": "Suppose, we have an array of objects like this −"
},
{
"code": null,
"e": 1232,
"s": 1111,
"text": "const arr = [\n {\"name\": \"toto\", \"uuid\": 1111},\n {\"name\": \"tata\", \"uuid\": 2222},\n {\"name\": \"titi\", \"uuid\": 1111}\n];"
},
{
"code": null,
"e": 1385,
"s": 1232,
"text": "We are required to write a JavaScript function that splits the objects into separate array of\narrays that have the similar values for the uuid property."
},
{
"code": null,
"e": 1431,
"s": 1385,
"text": "Therefore, the output should look like this −"
},
{
"code": null,
"e": 1584,
"s": 1431,
"text": "const output = [\n [\n {\"name\": \"toto\", \"uuid\": 1111},\n {\"name\": \"titi\", \"uuid\": 1111}\n ],\n [\n {\"name\": \"tata\", \"uuid\": 2222}\n ]\n];"
},
{
"code": null,
"e": 1612,
"s": 1584,
"text": "The code for this will be −"
},
{
"code": null,
"e": 2036,
"s": 1612,
"text": "const arr = [\n {\"name\": \"toto\", \"uuid\": 1111},\n {\"name\": \"tata\", \"uuid\": 2222},\n {\"name\": \"titi\", \"uuid\": 1111}\n];\nconst groupByElement = arr => {\n const hash = Object.create(null),\n result = [];\n arr.forEach(el => {\n if (!hash[el.uuid]) {\n hash[el.uuid] = [];\n result.push(hash[el.uuid]);\n };\n hash[el.uuid].push(el);\n });\n return result;\n};\nconsole.log(groupByElement(arr));"
},
{
"code": null,
"e": 2064,
"s": 2036,
"text": "The output in the console −"
},
{
"code": null,
"e": 2171,
"s": 2064,
"text": "[\n [ { name: 'toto', uuid: 1111 }, { name: 'titi', uuid: 1111 } ],\n [ { name: 'tata', uuid: 2222 } ]\n]"
}
] |
Creating a Docker Image with Git Installed - GeeksforGeeks | 29 Oct, 2020
Version control is one of the most important aspects of any software development project and when we talk about version control, there is no better tool than Git. The majority of the developers depend upon Git to manage and share their project components among the team members.
Even if you are running your project on Docker, you can still access your git account inside Docker Containers. All you need to do is just install Git inside your Docker Container. In this article, we will discuss exactly the same. We will create an Ubuntu Image, install Git inside it, create a Container associated with the Image, and verify whether Git has been installed or not.
To create a Docker image with git follow the below steps:
You can use the following template to create your Dockerfile.
FROM ubuntu:latest
RUN apt-get -y update
RUN apt-get -y install git
In the above Dockerfile, we have specified instructions to pull the Ubuntu base image, update the OS, and install Git inside it.
After creating the Dockerfile, we can build the Docker Image using the Docker build command.
sudo docker build -t sample-image .
To verify whether the image has been built or not, you can list all the Images.
sudo docker images
After you have built the Image, you can run the Container associated with the Image, using the Docker Run command.
sudo docker run -it sample-image bash
The above command creates and runs a Container and fires up the bash of the Docker Container.
After you have the bash opened up, you can verify whether Git has been installed or not by checking the version of Git.
git --version
This command returns the version of the git installed.
Docker Container
linux
Advanced Computer Subject
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Copying Files to and from Docker Containers
Principal Component Analysis with Python
Python | Decision Tree Regression using sklearn
Fuzzy Logic | Introduction
Classifying data using Support Vector Machines(SVMs) in Python
How to create a REST API using Java Spring Boot
An introduction to Machine Learning
Mounting a Volume Inside Docker Container
Basics of API Testing Using Postman
ML | Stochastic Gradient Descent (SGD) | [
{
"code": null,
"e": 24276,
"s": 24248,
"text": "\n29 Oct, 2020"
},
{
"code": null,
"e": 24556,
"s": 24276,
"text": "Version control is one of the most important aspects of any software development project and when we talk about version control, there is no better tool than Git. The majority of the developers depend upon Git to manage and share their project components among the team members. "
},
{
"code": null,
"e": 24939,
"s": 24556,
"text": "Even if you are running your project on Docker, you can still access your git account inside Docker Containers. All you need to do is just install Git inside your Docker Container. In this article, we will discuss exactly the same. We will create an Ubuntu Image, install Git inside it, create a Container associated with the Image, and verify whether Git has been installed or not."
},
{
"code": null,
"e": 24997,
"s": 24939,
"text": "To create a Docker image with git follow the below steps:"
},
{
"code": null,
"e": 25060,
"s": 24997,
"text": "You can use the following template to create your Dockerfile. "
},
{
"code": null,
"e": 25130,
"s": 25060,
"text": "FROM ubuntu:latest\nRUN apt-get -y update\nRUN apt-get -y install git\n\n"
},
{
"code": null,
"e": 25259,
"s": 25130,
"text": "In the above Dockerfile, we have specified instructions to pull the Ubuntu base image, update the OS, and install Git inside it."
},
{
"code": null,
"e": 25352,
"s": 25259,
"text": "After creating the Dockerfile, we can build the Docker Image using the Docker build command."
},
{
"code": null,
"e": 25390,
"s": 25352,
"text": "sudo docker build -t sample-image .\n\n"
},
{
"code": null,
"e": 25470,
"s": 25390,
"text": "To verify whether the image has been built or not, you can list all the Images."
},
{
"code": null,
"e": 25490,
"s": 25470,
"text": "sudo docker images\n"
},
{
"code": null,
"e": 25605,
"s": 25490,
"text": "After you have built the Image, you can run the Container associated with the Image, using the Docker Run command."
},
{
"code": null,
"e": 25645,
"s": 25605,
"text": "sudo docker run -it sample-image bash\n\n"
},
{
"code": null,
"e": 25739,
"s": 25645,
"text": "The above command creates and runs a Container and fires up the bash of the Docker Container."
},
{
"code": null,
"e": 25859,
"s": 25739,
"text": "After you have the bash opened up, you can verify whether Git has been installed or not by checking the version of Git."
},
{
"code": null,
"e": 25875,
"s": 25859,
"text": "git --version\n\n"
},
{
"code": null,
"e": 25930,
"s": 25875,
"text": "This command returns the version of the git installed."
},
{
"code": null,
"e": 25947,
"s": 25930,
"text": "Docker Container"
},
{
"code": null,
"e": 25953,
"s": 25947,
"text": "linux"
},
{
"code": null,
"e": 25979,
"s": 25953,
"text": "Advanced Computer Subject"
},
{
"code": null,
"e": 26077,
"s": 25979,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26121,
"s": 26077,
"text": "Copying Files to and from Docker Containers"
},
{
"code": null,
"e": 26162,
"s": 26121,
"text": "Principal Component Analysis with Python"
},
{
"code": null,
"e": 26210,
"s": 26162,
"text": "Python | Decision Tree Regression using sklearn"
},
{
"code": null,
"e": 26237,
"s": 26210,
"text": "Fuzzy Logic | Introduction"
},
{
"code": null,
"e": 26300,
"s": 26237,
"text": "Classifying data using Support Vector Machines(SVMs) in Python"
},
{
"code": null,
"e": 26348,
"s": 26300,
"text": "How to create a REST API using Java Spring Boot"
},
{
"code": null,
"e": 26384,
"s": 26348,
"text": "An introduction to Machine Learning"
},
{
"code": null,
"e": 26426,
"s": 26384,
"text": "Mounting a Volume Inside Docker Container"
},
{
"code": null,
"e": 26462,
"s": 26426,
"text": "Basics of API Testing Using Postman"
}
] |
Number of distinct permutation a String can have - GeeksforGeeks | 27 Jan, 2022
We are given a string having only lowercase alphabets. The task is to find out total number of distinct permutation can be generated by that string.Examples:
Input : aab
Output : 3
Different permutations are "aab",
"aba" and "baa".
Input : ybghjhbuytb
Output : 1663200
A simple solution is to find all the distinct permutation and count them.We can find the count without finding all permutation. Idea is to find all the characters that is getting repeated, i.e., frequency of all the character. Then, we divide the factorial of the length of string by multiplication of factorial of frequency of characters.In second example, number of character is 11 and here h and y are repeated 2 times whereas g is repeated 3 times. So, number of permutation is 11! / (2!2!3!) = 1663200Below is the implementation of above idea.
C++
Java
Python3
C#
Javascript
// C++ program to find number of distinct// permutations of a string.#include<bits/stdc++.h>using namespace std;const int MAX_CHAR = 26; // Utility function to find factorial of n.int factorial(int n){ int fact = 1; for (int i = 2; i <= n; i++) fact = fact * i; return fact;} // Returns count of distinct permutations// of str.int countDistinctPermutations(string str){ int length = str.length(); int freq[MAX_CHAR]; memset(freq, 0, sizeof(freq)); // finding frequency of all the lower case // alphabet and storing them in array of // integer for (int i = 0; i < length; i++) if (str[i] >= 'a') freq[str[i] - 'a']++; // finding factorial of number of appearances // and multiplying them since they are // repeating alphabets int fact = 1; for (int i = 0; i < MAX_CHAR; i++) fact = fact * factorial(freq[i]); // finding factorial of size of string and // dividing it by factorial found after // multiplying return factorial(length) / fact;} // Driver codeint main(){ string str = "fvvfhvgv"; printf("%d", countDistinctPermutations(str)); return 0;}
// Java program to find number of distinct// permutations of a string.public class GFG { static final int MAX_CHAR = 26; // Utility function to find factorial of n. static int factorial(int n) { int fact = 1; for (int i = 2; i <= n; i++) fact = fact * i; return fact; } // Returns count of distinct permutations // of str. static int countDistinctPermutations(String str) { int length = str.length(); int[] freq = new int[MAX_CHAR]; // finding frequency of all the lower case // alphabet and storing them in array of // integer for (int i = 0; i < length; i++) if (str.charAt(i) >= 'a') freq[str.charAt(i) - 'a']++; // finding factorial of number of appearances // and multiplying them since they are // repeating alphabets int fact = 1; for (int i = 0; i < MAX_CHAR; i++) fact = fact * factorial(freq[i]); // finding factorial of size of string and // dividing it by factorial found after // multiplying return factorial(length) / fact; } // Driver code public static void main(String args[]) { String str = "fvvfhvgv"; System.out.println(countDistinctPermutations(str)); }}// This code is contributed by Sumit Ghosh
# Python program to find number of distinct# permutations of a string. MAX_CHAR = 26 # Utility function to find factorial of n.def factorial(n) : fact = 1; for i in range(2, n + 1) : fact = fact * i; return fact # Returns count of distinct permutations# of str.def countDistinctPermutations(st) : length = len(st) freq = [0] * MAX_CHAR # finding frequency of all the lower # case alphabet and storing them in # array of integer for i in range(0, length) : if (st[i] >= 'a') : freq[(ord)(st[i]) - 97] = freq[(ord)(st[i]) - 97] + 1; # finding factorial of number of # appearances and multiplying them # since they are repeating alphabets fact = 1 for i in range(0, MAX_CHAR) : fact = fact * factorial(freq[i]) # finding factorial of size of string # and dividing it by factorial found # after multiplying return factorial(length) // fact # Driver codest = "fvvfhvgv"print (countDistinctPermutations(st)) # This code is contributed by Nikita Tiwari.
// C# program to find number of distinct// permutations of a string.using System; public class GFG { static int MAX_CHAR = 26; // Utility function to find factorial of n. static int factorial(int n) { int fact = 1; for (int i = 2; i <= n; i++) fact = fact * i; return fact; } // Returns count of distinct permutations // of str. static int countDistinctPermutations(String str) { int length = str.Length; int[] freq = new int[MAX_CHAR]; // finding frequency of all the lower case // alphabet and storing them in array of // integer for (int i = 0; i < length; i++) if (str[i] >= 'a') freq[str[i] - 'a']++; // finding factorial of number of appearances // and multiplying them since they are // repeating alphabets int fact = 1; for (int i = 0; i < MAX_CHAR; i++) fact = fact * factorial(freq[i]); // finding factorial of size of string and // dividing it by factorial found after // multiplying return factorial(length) / fact; } // Driver code public static void Main(String []args) { String str = "fvvfhvgv"; Console.Write(countDistinctPermutations(str)); }} // This code is contributed by parashar.
<script> // Javascript program to find number of distinct // permutations of a string. let MAX_CHAR = 26; // Utility function to find factorial of n. function factorial(n) { let fact = 1; for (let i = 2; i <= n; i++) fact = fact * i; return fact; } // Returns count of distinct permutations // of str. function countDistinctPermutations(str) { let length = str.length; let freq = new Array(MAX_CHAR); freq.fill(0); // finding frequency of all the lower case // alphabet and storing them in array of // integer for (let i = 0; i < length; i++) if (str[i].charCodeAt() >= 'a'.charCodeAt()) freq[str[i].charCodeAt() - 'a'.charCodeAt()]++; // finding factorial of number of appearances // and multiplying them since they are // repeating alphabets let fact = 1; for (let i = 0; i < MAX_CHAR; i++) fact = fact * factorial(freq[i]); // finding factorial of size of string and // dividing it by factorial found after // multiplying return parseInt(factorial(length) / fact, 10); } let str = "fvvfhvgv"; document.write(countDistinctPermutations(str)); // This code is contributed by vaibhavrabadiya117.</script>
Output:
840
YouTubeGeeksforGeeks506K subscribersNumber of distinct permutation a String can have | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:48•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=jBL2TIZ0dhc" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
This article is contributed by Aditya Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
parashar
vaibhavrabadiya117
amartyaghoshgfg
Combinatorial
Strings
Strings
Combinatorial
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Count of subsets with sum equal to X
Python program to get all subsets of given size of a set
Heap's Algorithm for generating permutations
Make all combinations of size k
Count Derangements (Permutation such that no element appears in its original position)
Write a program to reverse an array or string
Reverse a string in Java
Longest Common Subsequence | DP-4
C++ Data Types
Check for Balanced Brackets in an expression (well-formedness) using Stack | [
{
"code": null,
"e": 26425,
"s": 26397,
"text": "\n27 Jan, 2022"
},
{
"code": null,
"e": 26585,
"s": 26425,
"text": "We are given a string having only lowercase alphabets. The task is to find out total number of distinct permutation can be generated by that string.Examples: "
},
{
"code": null,
"e": 26697,
"s": 26585,
"text": "Input : aab\nOutput : 3\nDifferent permutations are \"aab\",\n\"aba\" and \"baa\".\n\nInput : ybghjhbuytb\nOutput : 1663200"
},
{
"code": null,
"e": 27250,
"s": 26699,
"text": "A simple solution is to find all the distinct permutation and count them.We can find the count without finding all permutation. Idea is to find all the characters that is getting repeated, i.e., frequency of all the character. Then, we divide the factorial of the length of string by multiplication of factorial of frequency of characters.In second example, number of character is 11 and here h and y are repeated 2 times whereas g is repeated 3 times. So, number of permutation is 11! / (2!2!3!) = 1663200Below is the implementation of above idea. "
},
{
"code": null,
"e": 27254,
"s": 27250,
"text": "C++"
},
{
"code": null,
"e": 27259,
"s": 27254,
"text": "Java"
},
{
"code": null,
"e": 27267,
"s": 27259,
"text": "Python3"
},
{
"code": null,
"e": 27270,
"s": 27267,
"text": "C#"
},
{
"code": null,
"e": 27281,
"s": 27270,
"text": "Javascript"
},
{
"code": "// C++ program to find number of distinct// permutations of a string.#include<bits/stdc++.h>using namespace std;const int MAX_CHAR = 26; // Utility function to find factorial of n.int factorial(int n){ int fact = 1; for (int i = 2; i <= n; i++) fact = fact * i; return fact;} // Returns count of distinct permutations// of str.int countDistinctPermutations(string str){ int length = str.length(); int freq[MAX_CHAR]; memset(freq, 0, sizeof(freq)); // finding frequency of all the lower case // alphabet and storing them in array of // integer for (int i = 0; i < length; i++) if (str[i] >= 'a') freq[str[i] - 'a']++; // finding factorial of number of appearances // and multiplying them since they are // repeating alphabets int fact = 1; for (int i = 0; i < MAX_CHAR; i++) fact = fact * factorial(freq[i]); // finding factorial of size of string and // dividing it by factorial found after // multiplying return factorial(length) / fact;} // Driver codeint main(){ string str = \"fvvfhvgv\"; printf(\"%d\", countDistinctPermutations(str)); return 0;}",
"e": 28431,
"s": 27281,
"text": null
},
{
"code": "// Java program to find number of distinct// permutations of a string.public class GFG { static final int MAX_CHAR = 26; // Utility function to find factorial of n. static int factorial(int n) { int fact = 1; for (int i = 2; i <= n; i++) fact = fact * i; return fact; } // Returns count of distinct permutations // of str. static int countDistinctPermutations(String str) { int length = str.length(); int[] freq = new int[MAX_CHAR]; // finding frequency of all the lower case // alphabet and storing them in array of // integer for (int i = 0; i < length; i++) if (str.charAt(i) >= 'a') freq[str.charAt(i) - 'a']++; // finding factorial of number of appearances // and multiplying them since they are // repeating alphabets int fact = 1; for (int i = 0; i < MAX_CHAR; i++) fact = fact * factorial(freq[i]); // finding factorial of size of string and // dividing it by factorial found after // multiplying return factorial(length) / fact; } // Driver code public static void main(String args[]) { String str = \"fvvfhvgv\"; System.out.println(countDistinctPermutations(str)); }}// This code is contributed by Sumit Ghosh",
"e": 29826,
"s": 28431,
"text": null
},
{
"code": "# Python program to find number of distinct# permutations of a string. MAX_CHAR = 26 # Utility function to find factorial of n.def factorial(n) : fact = 1; for i in range(2, n + 1) : fact = fact * i; return fact # Returns count of distinct permutations# of str.def countDistinctPermutations(st) : length = len(st) freq = [0] * MAX_CHAR # finding frequency of all the lower # case alphabet and storing them in # array of integer for i in range(0, length) : if (st[i] >= 'a') : freq[(ord)(st[i]) - 97] = freq[(ord)(st[i]) - 97] + 1; # finding factorial of number of # appearances and multiplying them # since they are repeating alphabets fact = 1 for i in range(0, MAX_CHAR) : fact = fact * factorial(freq[i]) # finding factorial of size of string # and dividing it by factorial found # after multiplying return factorial(length) // fact # Driver codest = \"fvvfhvgv\"print (countDistinctPermutations(st)) # This code is contributed by Nikita Tiwari.",
"e": 30886,
"s": 29826,
"text": null
},
{
"code": "// C# program to find number of distinct// permutations of a string.using System; public class GFG { static int MAX_CHAR = 26; // Utility function to find factorial of n. static int factorial(int n) { int fact = 1; for (int i = 2; i <= n; i++) fact = fact * i; return fact; } // Returns count of distinct permutations // of str. static int countDistinctPermutations(String str) { int length = str.Length; int[] freq = new int[MAX_CHAR]; // finding frequency of all the lower case // alphabet and storing them in array of // integer for (int i = 0; i < length; i++) if (str[i] >= 'a') freq[str[i] - 'a']++; // finding factorial of number of appearances // and multiplying them since they are // repeating alphabets int fact = 1; for (int i = 0; i < MAX_CHAR; i++) fact = fact * factorial(freq[i]); // finding factorial of size of string and // dividing it by factorial found after // multiplying return factorial(length) / fact; } // Driver code public static void Main(String []args) { String str = \"fvvfhvgv\"; Console.Write(countDistinctPermutations(str)); }} // This code is contributed by parashar.",
"e": 32280,
"s": 30886,
"text": null
},
{
"code": "<script> // Javascript program to find number of distinct // permutations of a string. let MAX_CHAR = 26; // Utility function to find factorial of n. function factorial(n) { let fact = 1; for (let i = 2; i <= n; i++) fact = fact * i; return fact; } // Returns count of distinct permutations // of str. function countDistinctPermutations(str) { let length = str.length; let freq = new Array(MAX_CHAR); freq.fill(0); // finding frequency of all the lower case // alphabet and storing them in array of // integer for (let i = 0; i < length; i++) if (str[i].charCodeAt() >= 'a'.charCodeAt()) freq[str[i].charCodeAt() - 'a'.charCodeAt()]++; // finding factorial of number of appearances // and multiplying them since they are // repeating alphabets let fact = 1; for (let i = 0; i < MAX_CHAR; i++) fact = fact * factorial(freq[i]); // finding factorial of size of string and // dividing it by factorial found after // multiplying return parseInt(factorial(length) / fact, 10); } let str = \"fvvfhvgv\"; document.write(countDistinctPermutations(str)); // This code is contributed by vaibhavrabadiya117.</script>",
"e": 33624,
"s": 32280,
"text": null
},
{
"code": null,
"e": 33634,
"s": 33624,
"text": "Output: "
},
{
"code": null,
"e": 33638,
"s": 33634,
"text": "840"
},
{
"code": null,
"e": 34487,
"s": 33640,
"text": "YouTubeGeeksforGeeks506K subscribersNumber of distinct permutation a String can have | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:48•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=jBL2TIZ0dhc\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>"
},
{
"code": null,
"e": 34907,
"s": 34487,
"text": "This article is contributed by Aditya Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 34916,
"s": 34907,
"text": "parashar"
},
{
"code": null,
"e": 34935,
"s": 34916,
"text": "vaibhavrabadiya117"
},
{
"code": null,
"e": 34951,
"s": 34935,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 34965,
"s": 34951,
"text": "Combinatorial"
},
{
"code": null,
"e": 34973,
"s": 34965,
"text": "Strings"
},
{
"code": null,
"e": 34981,
"s": 34973,
"text": "Strings"
},
{
"code": null,
"e": 34995,
"s": 34981,
"text": "Combinatorial"
},
{
"code": null,
"e": 35093,
"s": 34995,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35130,
"s": 35093,
"text": "Count of subsets with sum equal to X"
},
{
"code": null,
"e": 35187,
"s": 35130,
"text": "Python program to get all subsets of given size of a set"
},
{
"code": null,
"e": 35232,
"s": 35187,
"text": "Heap's Algorithm for generating permutations"
},
{
"code": null,
"e": 35264,
"s": 35232,
"text": "Make all combinations of size k"
},
{
"code": null,
"e": 35351,
"s": 35264,
"text": "Count Derangements (Permutation such that no element appears in its original position)"
},
{
"code": null,
"e": 35397,
"s": 35351,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 35422,
"s": 35397,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 35456,
"s": 35422,
"text": "Longest Common Subsequence | DP-4"
},
{
"code": null,
"e": 35471,
"s": 35456,
"text": "C++ Data Types"
}
] |
chsh command in Linux with examples - GeeksforGeeks | 26 Aug, 2021
chsh command in Linux is used to change the user’s login shell(currently login shell). Shell is an interactive user interface with an operating system and can be considered an outer layer of the operating system. The bash shell is one of the most widely used login shells in Linux. This command allows the user to change the shell from the current shell. It can also give warning if the shell is not present in the /etc/shells file. The superuser can change the login shell for the existing accounts.
Syntax:
chsh [OPTIONS] [LOGIN]
Example 1: To show the list of all shells. You can use echo command along with ‘$SHELL’ to check the current shell
Example 2: To change the current logging shell
Options:
-l: Used to specifies your login shell.
-u: Prints the list of shells.
-v: Shows information about version and exits.
-s: Used to set the shell as your login shell.
sooda367
linux-command
Linux-Shell-Commands
Picked
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++
Basic Operators in Shell Scripting
nohup Command in Linux with Examples
Array Basics in Shell Scripting | Set 1
Named Pipe or FIFO with example C program
chown command in Linux with Examples
mv command in Linux with examples
Docker - COPY Instruction
Start/Stop/Restart Services Using Systemctl in Linux
SED command in Linux | Set 2 | [
{
"code": null,
"e": 24326,
"s": 24298,
"text": "\n26 Aug, 2021"
},
{
"code": null,
"e": 24828,
"s": 24326,
"text": "chsh command in Linux is used to change the user’s login shell(currently login shell). Shell is an interactive user interface with an operating system and can be considered an outer layer of the operating system. The bash shell is one of the most widely used login shells in Linux. This command allows the user to change the shell from the current shell. It can also give warning if the shell is not present in the /etc/shells file. The superuser can change the login shell for the existing accounts. "
},
{
"code": null,
"e": 24838,
"s": 24828,
"text": "Syntax: "
},
{
"code": null,
"e": 24861,
"s": 24838,
"text": "chsh [OPTIONS] [LOGIN]"
},
{
"code": null,
"e": 24977,
"s": 24861,
"text": "Example 1: To show the list of all shells. You can use echo command along with ‘$SHELL’ to check the current shell "
},
{
"code": null,
"e": 25025,
"s": 24977,
"text": "Example 2: To change the current logging shell "
},
{
"code": null,
"e": 25035,
"s": 25025,
"text": "Options: "
},
{
"code": null,
"e": 25075,
"s": 25035,
"text": "-l: Used to specifies your login shell."
},
{
"code": null,
"e": 25106,
"s": 25075,
"text": "-u: Prints the list of shells."
},
{
"code": null,
"e": 25153,
"s": 25106,
"text": "-v: Shows information about version and exits."
},
{
"code": null,
"e": 25200,
"s": 25153,
"text": "-s: Used to set the shell as your login shell."
},
{
"code": null,
"e": 25209,
"s": 25200,
"text": "sooda367"
},
{
"code": null,
"e": 25223,
"s": 25209,
"text": "linux-command"
},
{
"code": null,
"e": 25244,
"s": 25223,
"text": "Linux-Shell-Commands"
},
{
"code": null,
"e": 25251,
"s": 25244,
"text": "Picked"
},
{
"code": null,
"e": 25262,
"s": 25251,
"text": "Linux-Unix"
},
{
"code": null,
"e": 25360,
"s": 25262,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25369,
"s": 25360,
"text": "Comments"
},
{
"code": null,
"e": 25382,
"s": 25369,
"text": "Old Comments"
},
{
"code": null,
"e": 25408,
"s": 25382,
"text": "Thread functions in C/C++"
},
{
"code": null,
"e": 25443,
"s": 25408,
"text": "Basic Operators in Shell Scripting"
},
{
"code": null,
"e": 25480,
"s": 25443,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 25520,
"s": 25480,
"text": "Array Basics in Shell Scripting | Set 1"
},
{
"code": null,
"e": 25562,
"s": 25520,
"text": "Named Pipe or FIFO with example C program"
},
{
"code": null,
"e": 25599,
"s": 25562,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 25633,
"s": 25599,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 25659,
"s": 25633,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 25712,
"s": 25659,
"text": "Start/Stop/Restart Services Using Systemctl in Linux"
}
] |
Check if a number can be expressed as a sum of consecutive numbers - GeeksforGeeks | 21 Jan, 2022
Given a number n, the task is to check whether it can be expressed as a sum of two or more consecutive numbers or not. Examples:
Input : n = 10
Output : true
It can be expressed as sum of two consecutive
numbers 1 + 2 + 3 + 4.
Input : n = 16
Output : false
It cannot be expressed as sum of two consecutive
numbers.
Input : n = 5
Output : true
2 + 3 = 5
There is a direct and quick method to solve this. If a number is a power of two, then it cannot be expressed as a sum of consecutive numbers otherwise Yes.The idea is based on below two facts. 1) Sum of any two consecutive numbers is odd as one of them has to be even and the other odd. 2) 2n = 2n-1 + 2n-1If we take a closer look at 1) and 2), we can get the intuition behind the fact.Below is the implementation of the above idea.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to check if a number can// be expressed as sum of consecutive numbers#include<bits/stdc++.h>using namespace std; // This function returns true if n can be// expressed sum of consecutive.bool canBeSumofConsec(unsigned int n){ // We basically return true if n is a // power of two return ((n&(n-1)) && n);} // Driver codeint main(){ unsigned int n = 15; canBeSumofConsec(n)? cout << "true" : cout << "false"; return 0;}
// Java program to check if a number can// be expressed as sum of consecutive numbers class Test{ // This function returns true if n can be // expressed sum of consecutive. static boolean canBeSumofConsec(int n) { // We basically return true if n is a // power of two return (((n&(n-1))!=0) && n!=0); } // Driver method public static void main(String[] args) { int n = 15; System.out.println(canBeSumofConsec(n) ? "true" : "false"); }}
# Python 3 program to check if a number can# be expressed as sum of consecutive numbers # This function returns true if n # can be expressed sum of consecutive.def canBeSumofConsec(n) : # We basically return true if n is a # power of two return ((n&(n-1)) and n) # Driver coden = 15if(canBeSumofConsec(n)) : print("true")else : print("false") # This code is contributed by Nikita Tiwari.
// C# program to check if a number can be// expressed as sum of consecutive numbersusing System; class Test{ // This function returns true if n // can be expressed sum of consecutive. static bool canBeSumofConsec(int n) { // We basically return true if n is a // power of two return (((n & (n - 1)) != 0) && n != 0); } // Driver Code public static void Main() { int n = 15; Console.Write(canBeSumofConsec(n) ? "True" : "False"); }} // This code is contributed by Nitin Mittal.
<?php// php program to check if a number// can be expressed as sum of // consecutive numbers // This function returns true if n// can be expressed sum of consecutive.function canBeSumofConsec($n){ // We basically return true if n is a // power of two return (($n & ($n - 1)) && $n);} // Driver code $n = 15; if(canBeSumofConsec($n)) echo "true" ; else echo "false"; // This code is contributed by// nitin mittal. ?>
<script> // Javascript program to check if a number can// be expressed as sum of consecutive numbers // This function returns true if n can be // expressed sum of consecutive. function canBeSumofConsec(n) { // We basically return true if n is a // power of two return (((n&(n-1))!=0) && n!=0); } // function call let n = 15; document.write(canBeSumofConsec(n) ? "true" : "false"); </script>
Output:
True
Time Complexity: O(1)
Auxiliary Space: O(1)
Let number chosen to represent N as a sum of consecutive numbers be X + 1, X + 2, X + 3 .... Y
Sum of these chosen numbers = Sum of first Y natural numbers – Sum of first X natural number
Sum of first Y natural number = Sum of first X natural number = We know that,N = Sum of first Y natural number – Sum of first X natural numberLet Y – X = a, Y + X + 1 = bY + X + 1 > Y – X, b > a, 2N = a * bIt means that a and b are factor of 2N, we know that X and Y are integers so,1. b – a – 1 => multiple of 2 (Even number)2. b + a + 1 => multiple of 2 (Even number)
Both conditions must be satisfied
From 1 and 2 we can say that either one of them (a, b) should be Odd and another one Even
So if the number (2N) has only odd factors (can’t be possible as it is an even number (2N not N) ) or only even factors we can’t represent it as a sum of any consecutive natural numbers
So now, we have to now only check whether it has an odd factor or not
1. If the number (2N not N) does not have any odd factor (contains only even factor means can be represented as) then we can’t represent it as a sum of consecutive number
2. If the number (2N not N) has an odd factor then we can represent it as a sum of a consecutive number
After this we have to only check whether we can represent (2N as ) or not
if Yes then answer is false or 0
if No then answer is true or 1
Below is the implementation of the above idea :
C++14
C
Java
Python3
C#
Javascript
#include <bits/stdc++.h>using namespace std; long long int canBeSumofConsec(long long int n) { // Updating n with 2n n = 2 * n; // (n & (n - 1)) => Checking whether we can write 2n as 2^k // if yes (can't represent 2n as 2^k) then answer 1 // if no (can represent 2n as 2^k) then answer 0 return ((n & (n - 1)) != 0);} int main(){ long long int n = 10; cout<<canBeSumofConsec(n)<<"\n";}
#include <stdio.h> long long int canBeSumofConsec(long long int n) { // Updating n with 2n n = 2 * n; // (n & (n - 1)) => Checking whether we can write 2n as 2^k // if yes (can't represent 2n as 2^k) then answer 1 // if no (can represent 2n as 2^k) then answer 0 return ((n & (n - 1)) != 0);} int main(){ long long int n = 10; printf("%lld", canBeSumofConsec(n));}
import java.util.*;class GFG{ static int canBeSumofConsec( int n) { // Updating n with 2n n = 2 * n; // (n & (n - 1)) => Checking whether we can write 2n as 2^k // if yes (can't represent 2n as 2^k) then answer 1 // if no (can represent 2n as 2^k) then answer 0 return ((n & (n - 1)) != 0)?1:0;} public static void main(String[] args){ int n = 10; System.out.print(canBeSumofConsec(n)+"\n");}} // This code is contributed by umadevi9616
def canBeSumofConsec(n): # Updating n with 2n n = 2 * n; # (n & (n - 1)) => Checking whether we can write 2n as 2^k # if yes (can't represent 2n as 2^k) then answer 1 # if no (can represent 2n as 2^k) then answer 0 if((n & (n - 1)) != 0): return 1; else: return 0; if __name__ == '__main__': n = 10; print(canBeSumofConsec(n)); # This code is contributed by umadevi9616
using System; public class GFG { static int canBeSumofConsec(int n) { // Updating n with 2n n = 2 * n; // (n & (n - 1)) => Checking whether we can write 2n as 2^k // if yes (can't represent 2n as 2^k) then answer 1 // if no (can represent 2n as 2^k) then answer 0 return ((n & (n - 1)) != 0) ? 1 : 0; } public static void Main(String[] args) { int n = 10; Console.Write(canBeSumofConsec(n) + "\n"); }} // This code is contributed by umadevi9616
<script> function canBeSumofConsec(n) { // Updating n with 2n n = 2 * n; // (n & (n - 1)) => Checking whether we can write 2n as 2^k // if yes (can't represent 2n as 2^k) then answer 1 // if no (can represent 2n as 2^k) then answer 0 return ((n & (n - 1)) != 0) ? 1 : 0; } var n = 10; document.write(canBeSumofConsec(n) + "\n"); // This code is contributed by umadevi9616</script>
1
Time Complexity: O(1)
Auxiliary Space: O(1)
Reference: http://www.cut-the-knot.org/arithmetic/UnpropertyOfPowersOf2.shtmlThis article is contributed by Sahil Chhabra. 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.
nitin mittal
susmitakundugoaldanga
anshkush92
umadevi9616
subhammahato348
Bit Magic
Mathematical
Mathematical
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Cyclic Redundancy Check and Modulo-2 Division
Little and Big Endian Mystery
Binary representation of a given number
Bit Fields in C
Bits manipulation (Important tactics)
Program for Fibonacci numbers
C++ Data Types
Write a program to print all permutations of a given string
Set in C++ Standard Template Library (STL)
Coin Change | DP-7 | [
{
"code": null,
"e": 25276,
"s": 25248,
"text": "\n21 Jan, 2022"
},
{
"code": null,
"e": 25407,
"s": 25276,
"text": "Given a number n, the task is to check whether it can be expressed as a sum of two or more consecutive numbers or not. Examples: "
},
{
"code": null,
"e": 25641,
"s": 25407,
"text": "Input : n = 10 \nOutput : true\nIt can be expressed as sum of two consecutive\nnumbers 1 + 2 + 3 + 4.\n\nInput : n = 16 \nOutput : false\nIt cannot be expressed as sum of two consecutive\nnumbers.\n\nInput : n = 5 \nOutput : true\n2 + 3 = 5"
},
{
"code": null,
"e": 26078,
"s": 25643,
"text": "There is a direct and quick method to solve this. If a number is a power of two, then it cannot be expressed as a sum of consecutive numbers otherwise Yes.The idea is based on below two facts. 1) Sum of any two consecutive numbers is odd as one of them has to be even and the other odd. 2) 2n = 2n-1 + 2n-1If we take a closer look at 1) and 2), we can get the intuition behind the fact.Below is the implementation of the above idea. "
},
{
"code": null,
"e": 26082,
"s": 26078,
"text": "C++"
},
{
"code": null,
"e": 26087,
"s": 26082,
"text": "Java"
},
{
"code": null,
"e": 26095,
"s": 26087,
"text": "Python3"
},
{
"code": null,
"e": 26098,
"s": 26095,
"text": "C#"
},
{
"code": null,
"e": 26102,
"s": 26098,
"text": "PHP"
},
{
"code": null,
"e": 26113,
"s": 26102,
"text": "Javascript"
},
{
"code": "// C++ program to check if a number can// be expressed as sum of consecutive numbers#include<bits/stdc++.h>using namespace std; // This function returns true if n can be// expressed sum of consecutive.bool canBeSumofConsec(unsigned int n){ // We basically return true if n is a // power of two return ((n&(n-1)) && n);} // Driver codeint main(){ unsigned int n = 15; canBeSumofConsec(n)? cout << \"true\" : cout << \"false\"; return 0;}",
"e": 26590,
"s": 26113,
"text": null
},
{
"code": "// Java program to check if a number can// be expressed as sum of consecutive numbers class Test{ // This function returns true if n can be // expressed sum of consecutive. static boolean canBeSumofConsec(int n) { // We basically return true if n is a // power of two return (((n&(n-1))!=0) && n!=0); } // Driver method public static void main(String[] args) { int n = 15; System.out.println(canBeSumofConsec(n) ? \"true\" : \"false\"); }}",
"e": 27096,
"s": 26590,
"text": null
},
{
"code": "# Python 3 program to check if a number can# be expressed as sum of consecutive numbers # This function returns true if n # can be expressed sum of consecutive.def canBeSumofConsec(n) : # We basically return true if n is a # power of two return ((n&(n-1)) and n) # Driver coden = 15if(canBeSumofConsec(n)) : print(\"true\")else : print(\"false\") # This code is contributed by Nikita Tiwari.",
"e": 27512,
"s": 27096,
"text": null
},
{
"code": "// C# program to check if a number can be// expressed as sum of consecutive numbersusing System; class Test{ // This function returns true if n // can be expressed sum of consecutive. static bool canBeSumofConsec(int n) { // We basically return true if n is a // power of two return (((n & (n - 1)) != 0) && n != 0); } // Driver Code public static void Main() { int n = 15; Console.Write(canBeSumofConsec(n) ? \"True\" : \"False\"); }} // This code is contributed by Nitin Mittal.",
"e": 28060,
"s": 27512,
"text": null
},
{
"code": "<?php// php program to check if a number// can be expressed as sum of // consecutive numbers // This function returns true if n// can be expressed sum of consecutive.function canBeSumofConsec($n){ // We basically return true if n is a // power of two return (($n & ($n - 1)) && $n);} // Driver code $n = 15; if(canBeSumofConsec($n)) echo \"true\" ; else echo \"false\"; // This code is contributed by// nitin mittal. ?>",
"e": 28518,
"s": 28060,
"text": null
},
{
"code": "<script> // Javascript program to check if a number can// be expressed as sum of consecutive numbers // This function returns true if n can be // expressed sum of consecutive. function canBeSumofConsec(n) { // We basically return true if n is a // power of two return (((n&(n-1))!=0) && n!=0); } // function call let n = 15; document.write(canBeSumofConsec(n) ? \"true\" : \"false\"); </script>",
"e": 28982,
"s": 28518,
"text": null
},
{
"code": null,
"e": 28991,
"s": 28982,
"text": "Output: "
},
{
"code": null,
"e": 28996,
"s": 28991,
"text": "True"
},
{
"code": null,
"e": 29018,
"s": 28996,
"text": "Time Complexity: O(1)"
},
{
"code": null,
"e": 29040,
"s": 29018,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 29136,
"s": 29040,
"text": "Let number chosen to represent N as a sum of consecutive numbers be X + 1, X + 2, X + 3 .... Y "
},
{
"code": null,
"e": 29230,
"s": 29136,
"text": "Sum of these chosen numbers = Sum of first Y natural numbers – Sum of first X natural number "
},
{
"code": null,
"e": 29600,
"s": 29230,
"text": "Sum of first Y natural number = Sum of first X natural number = We know that,N = Sum of first Y natural number – Sum of first X natural numberLet Y – X = a, Y + X + 1 = bY + X + 1 > Y – X, b > a, 2N = a * bIt means that a and b are factor of 2N, we know that X and Y are integers so,1. b – a – 1 => multiple of 2 (Even number)2. b + a + 1 => multiple of 2 (Even number)"
},
{
"code": null,
"e": 29634,
"s": 29600,
"text": "Both conditions must be satisfied"
},
{
"code": null,
"e": 29724,
"s": 29634,
"text": "From 1 and 2 we can say that either one of them (a, b) should be Odd and another one Even"
},
{
"code": null,
"e": 29910,
"s": 29724,
"text": "So if the number (2N) has only odd factors (can’t be possible as it is an even number (2N not N) ) or only even factors we can’t represent it as a sum of any consecutive natural numbers"
},
{
"code": null,
"e": 29980,
"s": 29910,
"text": "So now, we have to now only check whether it has an odd factor or not"
},
{
"code": null,
"e": 30151,
"s": 29980,
"text": "1. If the number (2N not N) does not have any odd factor (contains only even factor means can be represented as) then we can’t represent it as a sum of consecutive number"
},
{
"code": null,
"e": 30255,
"s": 30151,
"text": "2. If the number (2N not N) has an odd factor then we can represent it as a sum of a consecutive number"
},
{
"code": null,
"e": 30329,
"s": 30255,
"text": "After this we have to only check whether we can represent (2N as ) or not"
},
{
"code": null,
"e": 30362,
"s": 30329,
"text": "if Yes then answer is false or 0"
},
{
"code": null,
"e": 30393,
"s": 30362,
"text": "if No then answer is true or 1"
},
{
"code": null,
"e": 30442,
"s": 30393,
"text": "Below is the implementation of the above idea : "
},
{
"code": null,
"e": 30448,
"s": 30442,
"text": "C++14"
},
{
"code": null,
"e": 30450,
"s": 30448,
"text": "C"
},
{
"code": null,
"e": 30455,
"s": 30450,
"text": "Java"
},
{
"code": null,
"e": 30463,
"s": 30455,
"text": "Python3"
},
{
"code": null,
"e": 30466,
"s": 30463,
"text": "C#"
},
{
"code": null,
"e": 30477,
"s": 30466,
"text": "Javascript"
},
{
"code": "#include <bits/stdc++.h>using namespace std; long long int canBeSumofConsec(long long int n) { // Updating n with 2n n = 2 * n; // (n & (n - 1)) => Checking whether we can write 2n as 2^k // if yes (can't represent 2n as 2^k) then answer 1 // if no (can represent 2n as 2^k) then answer 0 return ((n & (n - 1)) != 0);} int main(){ long long int n = 10; cout<<canBeSumofConsec(n)<<\"\\n\";}",
"e": 30891,
"s": 30477,
"text": null
},
{
"code": "#include <stdio.h> long long int canBeSumofConsec(long long int n) { // Updating n with 2n n = 2 * n; // (n & (n - 1)) => Checking whether we can write 2n as 2^k // if yes (can't represent 2n as 2^k) then answer 1 // if no (can represent 2n as 2^k) then answer 0 return ((n & (n - 1)) != 0);} int main(){ long long int n = 10; printf(\"%lld\", canBeSumofConsec(n));}",
"e": 31283,
"s": 30891,
"text": null
},
{
"code": "import java.util.*;class GFG{ static int canBeSumofConsec( int n) { // Updating n with 2n n = 2 * n; // (n & (n - 1)) => Checking whether we can write 2n as 2^k // if yes (can't represent 2n as 2^k) then answer 1 // if no (can represent 2n as 2^k) then answer 0 return ((n & (n - 1)) != 0)?1:0;} public static void main(String[] args){ int n = 10; System.out.print(canBeSumofConsec(n)+\"\\n\");}} // This code is contributed by umadevi9616 ",
"e": 31755,
"s": 31283,
"text": null
},
{
"code": "def canBeSumofConsec(n): # Updating n with 2n n = 2 * n; # (n & (n - 1)) => Checking whether we can write 2n as 2^k # if yes (can't represent 2n as 2^k) then answer 1 # if no (can represent 2n as 2^k) then answer 0 if((n & (n - 1)) != 0): return 1; else: return 0; if __name__ == '__main__': n = 10; print(canBeSumofConsec(n)); # This code is contributed by umadevi9616 ",
"e": 32175,
"s": 31755,
"text": null
},
{
"code": "using System; public class GFG { static int canBeSumofConsec(int n) { // Updating n with 2n n = 2 * n; // (n & (n - 1)) => Checking whether we can write 2n as 2^k // if yes (can't represent 2n as 2^k) then answer 1 // if no (can represent 2n as 2^k) then answer 0 return ((n & (n - 1)) != 0) ? 1 : 0; } public static void Main(String[] args) { int n = 10; Console.Write(canBeSumofConsec(n) + \"\\n\"); }} // This code is contributed by umadevi9616",
"e": 32707,
"s": 32175,
"text": null
},
{
"code": "<script> function canBeSumofConsec(n) { // Updating n with 2n n = 2 * n; // (n & (n - 1)) => Checking whether we can write 2n as 2^k // if yes (can't represent 2n as 2^k) then answer 1 // if no (can represent 2n as 2^k) then answer 0 return ((n & (n - 1)) != 0) ? 1 : 0; } var n = 10; document.write(canBeSumofConsec(n) + \"\\n\"); // This code is contributed by umadevi9616</script>",
"e": 33157,
"s": 32707,
"text": null
},
{
"code": null,
"e": 33159,
"s": 33157,
"text": "1"
},
{
"code": null,
"e": 33181,
"s": 33159,
"text": "Time Complexity: O(1)"
},
{
"code": null,
"e": 33203,
"s": 33181,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 33702,
"s": 33203,
"text": "Reference: http://www.cut-the-knot.org/arithmetic/UnpropertyOfPowersOf2.shtmlThis article is contributed by Sahil Chhabra. 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": 33715,
"s": 33702,
"text": "nitin mittal"
},
{
"code": null,
"e": 33737,
"s": 33715,
"text": "susmitakundugoaldanga"
},
{
"code": null,
"e": 33748,
"s": 33737,
"text": "anshkush92"
},
{
"code": null,
"e": 33760,
"s": 33748,
"text": "umadevi9616"
},
{
"code": null,
"e": 33776,
"s": 33760,
"text": "subhammahato348"
},
{
"code": null,
"e": 33786,
"s": 33776,
"text": "Bit Magic"
},
{
"code": null,
"e": 33799,
"s": 33786,
"text": "Mathematical"
},
{
"code": null,
"e": 33812,
"s": 33799,
"text": "Mathematical"
},
{
"code": null,
"e": 33822,
"s": 33812,
"text": "Bit Magic"
},
{
"code": null,
"e": 33920,
"s": 33822,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33929,
"s": 33920,
"text": "Comments"
},
{
"code": null,
"e": 33942,
"s": 33929,
"text": "Old Comments"
},
{
"code": null,
"e": 33988,
"s": 33942,
"text": "Cyclic Redundancy Check and Modulo-2 Division"
},
{
"code": null,
"e": 34018,
"s": 33988,
"text": "Little and Big Endian Mystery"
},
{
"code": null,
"e": 34058,
"s": 34018,
"text": "Binary representation of a given number"
},
{
"code": null,
"e": 34074,
"s": 34058,
"text": "Bit Fields in C"
},
{
"code": null,
"e": 34112,
"s": 34074,
"text": "Bits manipulation (Important tactics)"
},
{
"code": null,
"e": 34142,
"s": 34112,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 34157,
"s": 34142,
"text": "C++ Data Types"
},
{
"code": null,
"e": 34217,
"s": 34157,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 34260,
"s": 34217,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
Removing Spikes from Raman Spectra with Anomaly Detection: Whitaker-Hayes algorithm in Python | by Nicolas Coca, PhD | Towards Data Science | Abstract. In this article, I would like to comment on a new approach to remove spikes from Raman spectra, presented in the Chemometrics and Intelligent Laboratory Systems journal by D. Whitaker and K. Hayes1. In their publication, the authors use a modified Z-scores outlier detection based algorithm to locate such spikes, when present, followed by a simple moving average to remove them. Instead of calculating the Z-scores of the spectrum intensity, they calculate the Z-scores of the once-differenced spectrum. They also provided the code for the algorithm implementation in R. Here, I present the implementation of the algorithm in Python and show how I applied it to a different data set.
Raman spectroscopy is a widely used analytical technique which provides structural and electronic information from molecules and solids. It is applicable at both laboratory and mass-production scales, and has applications in many different fields such as physics, chemistry, biology, medicine or industry.
A typical issue known in Raman spectroscopy is that Raman spectra are sometimes ‘contaminated’ by spikes. Spikes are positive, narrow bandwidth peaks present at random position on the spectrum. They originate when a high-energy cosmic ray impacts in the charge-couple device detector used to measure Raman spectra. These spikes are problematic as they might hinder subsequent analysis, particularly if multivariate data analysis is required. Therefore, one of the first steps in the treatment of Raman spectral data is the cleaning of spikes.
First, the Python packages that will be needed are loaded:
import numpy as npimport pandas as pdimport matplotlib.pyplot as plt
Figure 1 shows the Raman spectrum of graphene. In the previous years, graphene has become a very popular material due to its remarkable physical properties, including superior electronic, thermal, optical and mechanical properties. Its characteristic Raman spectrum consists of several peaks as shown in the figure. From their shape and related intensity, a large amount of information such as doping, strain or grain boundaries can be learned. This spectrum is a clear example of a spectrum contaminated with a spike.
# load the data as data framedf = pd.read_csv(‘folder_name.../spectrum.txt’, delimiter = ‘\t’)# Transform the data to a numpy arraywavelength = np.array(df.Wavelength)intensity = np.array(df.Intensity)# Plot the spectrum:plt.plot(wavelength, intensity)plt.title(‘Spectrum’, fontsize = 20)plt.xticks(fontsize = 15)plt.yticks(fontsize = 15)plt.xlabel(‘Wavelength (nm)’, fontsize = 20)plt.ylabel(‘Intensity (a.u.)’, fontsize = 20)plt.show()
Z-score based approach for spike detection in Raman spectra
Spikes intensities are normally above the intensities of other Raman peaks in the spectrum, therefore using a z-scores based method could be a good starting point. The z-scores tell how far a value is from the average in units of standard deviation. So, if the population mean and population standard deviation are known, the standard score of a raw score x(i) is calculated as:
z(i) = (x(i)-μ) / σ
where μ is the mean and σ is the standard deviation of the population x (x(i) represent the values of a single Raman spectrum). More in detail information on how to detect outliers using Z-score approaches can be found in reference [3].
Let’s calculate the z-scores for the points in our spectrum:
def z_score(intensity): mean_int = np.mean(intensity) std_int = np.std(intensity) z_scores = (intensity — mean_int) / std_int return z_scoresintensity_z_score = np.array(z_score(intensity))plt.plot(wavelength, intensity_z_score)plt.xticks(fontsize = 15)plt.yticks(fontsize = 15)plt.xlabel( ‘Wavelength’ ,fontsize = 20)plt.ylabel( ‘Z-Score’ ,fontsize = 20)plt.show()
A threshold is then needed in order to tell whether a value is an outlier or not. A typical value for this threshold is 3.5, as proposed as guideline by the American Society of Quality control as the basis of an outlier-labeling rule2, while the authors of the publication used 6. In order to apply a threshold to exclude spikes, the absolute value of the Z-score must be taken:
|z(i)| = |(x(i)-μ) / σ|
calculated as
def z_score(intensity): mean_int = np.mean(intensity) std_int = np.std(intensity) z_scores = (intensity — mean_int) / std_int return z_scoresthreshold = 3.5intensity_z_score = np.array(abs(z_score(intensity)))plt.plot(wavelength, intensity_z_score)plt.plot(wavelength, threshold*np.ones(len(wavelength)), label = ‘threshold’)plt.xticks(fontsize = 15)plt.yticks(fontsize = 15)plt.xlabel( ‘Wavelength’ ,fontsize = 20)plt.ylabel( ‘|Z-Score|’ ,fontsize = 20)plt.show()
However, the z-score pretty much resembles the original spectrum and the threshold still cut off the main Raman peak. Let’s plot what was detected as spikes using a 3.5 threshold:
threshold = 3.5# 1 is assigned to spikes, 0 to non-spikes:spikes = abs(np.array(z_score(intensity))) > thresholdplt.plot(wavelength, spikes, color = ‘red’)plt.title(‘Spikes: ‘ + str(np.sum(spikes)), fontsize = 20)plt.grid()plt.xticks(fontsize = 15)plt.yticks(fontsize = 15)plt.xlabel( ‘Wavelength’ ,fontsize = 20)plt.ylabel( 'Z-scores > ' + str(threshold) ,fontsize = 20)plt.show()
Modified Z-score based approach for spike detection in Raman spectra
A second option would be making use of robust statistics and calculate the modified z-scores of the spectrum. This modified Z-score method uses the median (M) and median absolute deviation (MAD) rather than the mean and standard deviation:
z(i) = 0.6745 (x(i)-M) / MAD
where the MAD = median(|x-M|) and |...| represents the absolute value. Both the median and the MAD are robust measures of the central tendency and dispersion, respectively. The multiplier 0.6745 is the 0.75th quartile of the standard normal distribution, to which the MAD converges to4.
def modified_z_score(intensity): median_int = np.median(intensity) mad_int = np.median([np.abs(intensity — median_int)]) modified_z_scores = 0.6745 * (intensity — median_int) / mad_int return modified_z_scoresthreshold = 3.5intensity_modified_z_score = np.array(abs(modified_z_score(intensity)))plt.plot(wavelength, intensity_modified_z_score)plt.plot(wavelength, threshold*np.ones(len(wavelength)), label = 'threshold')plt.xticks(fontsize = 15)plt.yticks(fontsize = 15)plt.xlabel('Wavelength (nm)' ,fontsize = 20)plt.ylabel('|Modified Z-Score|' ,fontsize = 20)plt.show()
The same issue can still be observed:
# 1 is assigned to spikes, 0 to non-spikes:spikes = abs(np.array(modified_z_score(intensity))) > thresholdplt.plot(wavelength, spikes, color = ‘red’)plt.title(‘Spikes: ‘ + str(np.sum(spikes)), fontsize = 20)plt.grid()plt.xticks(fontsize = 15)plt.yticks(fontsize = 15)plt.xlabel( ‘Wavelength’ ,fontsize = 20)plt.ylabel( 'Modified Z-scores > ' + str(threshold) ,fontsize = 20)plt.show()
The 2D Raman peak is still detected as spike, so a more sensitive approach is required.
Whitaker and Hayes’ modified Z-score based approach for spike detection in Raman spectra
Whitaker and Hayes propose to make advantage of the high intensity and small width of spikes and therefore use the difference between consecutive spectrum points ∇x(i) = x(i)-x(i-1) to calculate the z-scores, where x(1), ..., x(n) are the values of a single Raman spectrum recorded at equally spaced wavenumbers and i = 2, ..., n. This step annihilates linear and slow moving curve linear trends, while sharp thin spikes will be preserved. Now,
z(i) = 0.6745 (∇x(i)-M) / MAD
So there is only an extra step included in which the difference between consecutive values are included.
# First we calculated ∇x(i):dist = 0delta_intensity = [] for i in np.arange(len(intensity)-1): dist = intensity[i+1] — intensity[i] delta_intensity.append(dist)delta_int = np.array(delta_intensity)# Alternatively to the for loop one can use: # delta_int = np.diff(intensity)intensity_modified_z_score = np.array(modified_z_score(delta_int))plt.plot(wavelength[1:], intensity_modified_z_score)plt.title('Modified Z-Score using ∇x(i)')plt.xticks(fontsize = 15)plt.yticks(fontsize = 15)plt.xlabel('Wavelength (nm)', fontsize = 20)plt.ylabel('Score', fontsize = 20)plt.show()
Again, in order to apply a threshold to exclude spikes, the absolute value of the modified Z-score must be taken:
|z(i)| =|0.6745 (∇x(i)-M) / MAD|
Resulting in
threshold = 3.5intensity_modified_z_score = np.array(np.abs(modified_z_score(delta_int)))plt.plot(wavelength[1:], intensity_modified_z_score)plt.plot(wavelength[1:], threshold*np.ones(len(wavelength[1:])), label = 'threshold')plt.title('Modified Z-Score of ∇x(i)', fontsize = 20)plt.xticks(fontsize = 15)plt.yticks(fontsize = 15)plt.xlabel('Wavelength (nm)', fontsize = 20)plt.ylabel('Score', fontsize = 20)plt.show()
And once more, the number of detected spikes can be calculated as
# 1 is assigned to spikes, 0 to non-spikes:spikes = abs(np.array(modified_z_score(intensity))) > thresholdplt.plot(wavelength, spikes, color = ‘red’)plt.title(‘Spikes: ‘ + str(np.sum(spikes)), fontsize = 20)plt.grid()plt.xticks(fontsize = 15)plt.yticks(fontsize = 15)plt.xlabel( ‘Wavelength’ ,fontsize = 20)#plt.ylabel( ‘Spike(1) or not(0)?’ ,fontsize = 20)plt.show()
For the 3.5 recommended threshold many false spikes are assigned. However, the value scored by this approach is much higher in comparison with the Raman peaks than before.
plt.plot(wavelength[1:],np.array(abs(modified_z_score(delta_int))), color='black', label = '|Modified Z-Score using ∇x(i)|')plt.plot(wavelength, np.array(abs(modified_z_score(intensity))), label = '|Modified Z-Score|', color = 'red')plt.plot(wavelength, np.array(abs(z_score(intensity))), label = '|Z-Score|', color = 'blue')plt.xticks(fontsize = 15)plt.yticks(fontsize = 15)plt.xlabel( 'Wavelength' ,fontsize = 20)plt.ylabel( 'Score' ,fontsize = 20)plt.legend()plt.show()
In general, the right threshold must be chosen depending on the data set. For this case, a threshold = 7 is already enough to obtain a clear selection.
Fixing the Raman spectrum
Once the spikes are detected, the next step is to remove them and fix the spectra. For this, interpolated values are obtained at each candidate wavenumber by calculating the mean of its immediate neighbors (within a 2m+1 values window).
def fixer(y,m): threshold = 7 # binarization threshold. spikes = abs(np.array(modified_z_score(np.diff(y)))) > threshold y_out = y.copy() # So we don’t overwrite y for i in np.arange(len(spikes)): if spikes[i] != 0: # If we have an spike in position i w = np.arange(i-m,i+1+m) # we select 2 m + 1 points around our spike w2 = w[spikes[w] == 0] # From such interval, we choose the ones which are not spikes y_out[i] = np.mean(y[w2]) # and we average their values return y_out# Does it work?plt.plot(wavelength, intensity, label = 'original data')plt.plot(wavelength, fixer(intensity,m=3), label = 'fixed spectrum')plt.title('Despiked spectrum',fontsize = 20)plt.xticks(fontsize = 15)plt.yticks(fontsize = 15)plt.xlabel('Wavelength (nm)' ,fontsize = 20)plt.ylabel('Intensity (a.u.)' ,fontsize = 20)plt.legend()plt.show()
So after calculation of the modified Z scores of ∇x, and thresholding by setting an appropiate threshold value, the spike is removed and smoothed by applying a moving average filter.
Other examples
To wrap up, two examples of spikes with different intensity signal are presented, showing the strenght of this approach.
Aknowledgements. I would like to thank Jorge Luis Hita and Ana Solaguren-Beascoa for taking the time to proofread this notes.
[1] Whitaker, Darren A., and Kevin Hayes. “A simple algorithm for despiking Raman spectra.” Chemometrics and Intelligent Laboratory Systems 179 (2018): 82–84.
[2] Iglewicz, B., and D. Hoaglin. “The ASQC basic references in quality control: statistical techniques.” How to detect and handle outliers 16 (1993): 1–87.
[3] Colin Gorrie’s Data Story: Three ways to detect outliers. http://colingorrie.github.io/outlier-detection.html
[4] Joao Rodrigues. “Outliers make us go MAD: Univariate Outlier Detection”. Medium. https://medium.com/james-blogs/outliers-make-us-go-mad-univariate-outlier-detection-b3a72f1ea8c7 | [
{
"code": null,
"e": 867,
"s": 172,
"text": "Abstract. In this article, I would like to comment on a new approach to remove spikes from Raman spectra, presented in the Chemometrics and Intelligent Laboratory Systems journal by D. Whitaker and K. Hayes1. In their publication, the authors use a modified Z-scores outlier detection based algorithm to locate such spikes, when present, followed by a simple moving average to remove them. Instead of calculating the Z-scores of the spectrum intensity, they calculate the Z-scores of the once-differenced spectrum. They also provided the code for the algorithm implementation in R. Here, I present the implementation of the algorithm in Python and show how I applied it to a different data set."
},
{
"code": null,
"e": 1173,
"s": 867,
"text": "Raman spectroscopy is a widely used analytical technique which provides structural and electronic information from molecules and solids. It is applicable at both laboratory and mass-production scales, and has applications in many different fields such as physics, chemistry, biology, medicine or industry."
},
{
"code": null,
"e": 1716,
"s": 1173,
"text": "A typical issue known in Raman spectroscopy is that Raman spectra are sometimes ‘contaminated’ by spikes. Spikes are positive, narrow bandwidth peaks present at random position on the spectrum. They originate when a high-energy cosmic ray impacts in the charge-couple device detector used to measure Raman spectra. These spikes are problematic as they might hinder subsequent analysis, particularly if multivariate data analysis is required. Therefore, one of the first steps in the treatment of Raman spectral data is the cleaning of spikes."
},
{
"code": null,
"e": 1775,
"s": 1716,
"text": "First, the Python packages that will be needed are loaded:"
},
{
"code": null,
"e": 1844,
"s": 1775,
"text": "import numpy as npimport pandas as pdimport matplotlib.pyplot as plt"
},
{
"code": null,
"e": 2363,
"s": 1844,
"text": "Figure 1 shows the Raman spectrum of graphene. In the previous years, graphene has become a very popular material due to its remarkable physical properties, including superior electronic, thermal, optical and mechanical properties. Its characteristic Raman spectrum consists of several peaks as shown in the figure. From their shape and related intensity, a large amount of information such as doping, strain or grain boundaries can be learned. This spectrum is a clear example of a spectrum contaminated with a spike."
},
{
"code": null,
"e": 2801,
"s": 2363,
"text": "# load the data as data framedf = pd.read_csv(‘folder_name.../spectrum.txt’, delimiter = ‘\\t’)# Transform the data to a numpy arraywavelength = np.array(df.Wavelength)intensity = np.array(df.Intensity)# Plot the spectrum:plt.plot(wavelength, intensity)plt.title(‘Spectrum’, fontsize = 20)plt.xticks(fontsize = 15)plt.yticks(fontsize = 15)plt.xlabel(‘Wavelength (nm)’, fontsize = 20)plt.ylabel(‘Intensity (a.u.)’, fontsize = 20)plt.show()"
},
{
"code": null,
"e": 2861,
"s": 2801,
"text": "Z-score based approach for spike detection in Raman spectra"
},
{
"code": null,
"e": 3240,
"s": 2861,
"text": "Spikes intensities are normally above the intensities of other Raman peaks in the spectrum, therefore using a z-scores based method could be a good starting point. The z-scores tell how far a value is from the average in units of standard deviation. So, if the population mean and population standard deviation are known, the standard score of a raw score x(i) is calculated as:"
},
{
"code": null,
"e": 3260,
"s": 3240,
"text": "z(i) = (x(i)-μ) / σ"
},
{
"code": null,
"e": 3497,
"s": 3260,
"text": "where μ is the mean and σ is the standard deviation of the population x (x(i) represent the values of a single Raman spectrum). More in detail information on how to detect outliers using Z-score approaches can be found in reference [3]."
},
{
"code": null,
"e": 3558,
"s": 3497,
"text": "Let’s calculate the z-scores for the points in our spectrum:"
},
{
"code": null,
"e": 3924,
"s": 3558,
"text": "def z_score(intensity): mean_int = np.mean(intensity) std_int = np.std(intensity) z_scores = (intensity — mean_int) / std_int return z_scoresintensity_z_score = np.array(z_score(intensity))plt.plot(wavelength, intensity_z_score)plt.xticks(fontsize = 15)plt.yticks(fontsize = 15)plt.xlabel( ‘Wavelength’ ,fontsize = 20)plt.ylabel( ‘Z-Score’ ,fontsize = 20)plt.show()"
},
{
"code": null,
"e": 4303,
"s": 3924,
"text": "A threshold is then needed in order to tell whether a value is an outlier or not. A typical value for this threshold is 3.5, as proposed as guideline by the American Society of Quality control as the basis of an outlier-labeling rule2, while the authors of the publication used 6. In order to apply a threshold to exclude spikes, the absolute value of the Z-score must be taken:"
},
{
"code": null,
"e": 4327,
"s": 4303,
"text": "|z(i)| = |(x(i)-μ) / σ|"
},
{
"code": null,
"e": 4341,
"s": 4327,
"text": "calculated as"
},
{
"code": null,
"e": 4806,
"s": 4341,
"text": "def z_score(intensity): mean_int = np.mean(intensity) std_int = np.std(intensity) z_scores = (intensity — mean_int) / std_int return z_scoresthreshold = 3.5intensity_z_score = np.array(abs(z_score(intensity)))plt.plot(wavelength, intensity_z_score)plt.plot(wavelength, threshold*np.ones(len(wavelength)), label = ‘threshold’)plt.xticks(fontsize = 15)plt.yticks(fontsize = 15)plt.xlabel( ‘Wavelength’ ,fontsize = 20)plt.ylabel( ‘|Z-Score|’ ,fontsize = 20)plt.show()"
},
{
"code": null,
"e": 4986,
"s": 4806,
"text": "However, the z-score pretty much resembles the original spectrum and the threshold still cut off the main Raman peak. Let’s plot what was detected as spikes using a 3.5 threshold:"
},
{
"code": null,
"e": 5368,
"s": 4986,
"text": "threshold = 3.5# 1 is assigned to spikes, 0 to non-spikes:spikes = abs(np.array(z_score(intensity))) > thresholdplt.plot(wavelength, spikes, color = ‘red’)plt.title(‘Spikes: ‘ + str(np.sum(spikes)), fontsize = 20)plt.grid()plt.xticks(fontsize = 15)plt.yticks(fontsize = 15)plt.xlabel( ‘Wavelength’ ,fontsize = 20)plt.ylabel( 'Z-scores > ' + str(threshold) ,fontsize = 20)plt.show()"
},
{
"code": null,
"e": 5437,
"s": 5368,
"text": "Modified Z-score based approach for spike detection in Raman spectra"
},
{
"code": null,
"e": 5677,
"s": 5437,
"text": "A second option would be making use of robust statistics and calculate the modified z-scores of the spectrum. This modified Z-score method uses the median (M) and median absolute deviation (MAD) rather than the mean and standard deviation:"
},
{
"code": null,
"e": 5706,
"s": 5677,
"text": "z(i) = 0.6745 (x(i)-M) / MAD"
},
{
"code": null,
"e": 5993,
"s": 5706,
"text": "where the MAD = median(|x-M|) and |...| represents the absolute value. Both the median and the MAD are robust measures of the central tendency and dispersion, respectively. The multiplier 0.6745 is the 0.75th quartile of the standard normal distribution, to which the MAD converges to4."
},
{
"code": null,
"e": 6565,
"s": 5993,
"text": "def modified_z_score(intensity): median_int = np.median(intensity) mad_int = np.median([np.abs(intensity — median_int)]) modified_z_scores = 0.6745 * (intensity — median_int) / mad_int return modified_z_scoresthreshold = 3.5intensity_modified_z_score = np.array(abs(modified_z_score(intensity)))plt.plot(wavelength, intensity_modified_z_score)plt.plot(wavelength, threshold*np.ones(len(wavelength)), label = 'threshold')plt.xticks(fontsize = 15)plt.yticks(fontsize = 15)plt.xlabel('Wavelength (nm)' ,fontsize = 20)plt.ylabel('|Modified Z-Score|' ,fontsize = 20)plt.show()"
},
{
"code": null,
"e": 6603,
"s": 6565,
"text": "The same issue can still be observed:"
},
{
"code": null,
"e": 6988,
"s": 6603,
"text": "# 1 is assigned to spikes, 0 to non-spikes:spikes = abs(np.array(modified_z_score(intensity))) > thresholdplt.plot(wavelength, spikes, color = ‘red’)plt.title(‘Spikes: ‘ + str(np.sum(spikes)), fontsize = 20)plt.grid()plt.xticks(fontsize = 15)plt.yticks(fontsize = 15)plt.xlabel( ‘Wavelength’ ,fontsize = 20)plt.ylabel( 'Modified Z-scores > ' + str(threshold) ,fontsize = 20)plt.show()"
},
{
"code": null,
"e": 7076,
"s": 6988,
"text": "The 2D Raman peak is still detected as spike, so a more sensitive approach is required."
},
{
"code": null,
"e": 7165,
"s": 7076,
"text": "Whitaker and Hayes’ modified Z-score based approach for spike detection in Raman spectra"
},
{
"code": null,
"e": 7610,
"s": 7165,
"text": "Whitaker and Hayes propose to make advantage of the high intensity and small width of spikes and therefore use the difference between consecutive spectrum points ∇x(i) = x(i)-x(i-1) to calculate the z-scores, where x(1), ..., x(n) are the values of a single Raman spectrum recorded at equally spaced wavenumbers and i = 2, ..., n. This step annihilates linear and slow moving curve linear trends, while sharp thin spikes will be preserved. Now,"
},
{
"code": null,
"e": 7640,
"s": 7610,
"text": "z(i) = 0.6745 (∇x(i)-M) / MAD"
},
{
"code": null,
"e": 7745,
"s": 7640,
"text": "So there is only an extra step included in which the difference between consecutive values are included."
},
{
"code": null,
"e": 8317,
"s": 7745,
"text": "# First we calculated ∇x(i):dist = 0delta_intensity = [] for i in np.arange(len(intensity)-1): dist = intensity[i+1] — intensity[i] delta_intensity.append(dist)delta_int = np.array(delta_intensity)# Alternatively to the for loop one can use: # delta_int = np.diff(intensity)intensity_modified_z_score = np.array(modified_z_score(delta_int))plt.plot(wavelength[1:], intensity_modified_z_score)plt.title('Modified Z-Score using ∇x(i)')plt.xticks(fontsize = 15)plt.yticks(fontsize = 15)plt.xlabel('Wavelength (nm)', fontsize = 20)plt.ylabel('Score', fontsize = 20)plt.show()"
},
{
"code": null,
"e": 8431,
"s": 8317,
"text": "Again, in order to apply a threshold to exclude spikes, the absolute value of the modified Z-score must be taken:"
},
{
"code": null,
"e": 8464,
"s": 8431,
"text": "|z(i)| =|0.6745 (∇x(i)-M) / MAD|"
},
{
"code": null,
"e": 8477,
"s": 8464,
"text": "Resulting in"
},
{
"code": null,
"e": 8895,
"s": 8477,
"text": "threshold = 3.5intensity_modified_z_score = np.array(np.abs(modified_z_score(delta_int)))plt.plot(wavelength[1:], intensity_modified_z_score)plt.plot(wavelength[1:], threshold*np.ones(len(wavelength[1:])), label = 'threshold')plt.title('Modified Z-Score of ∇x(i)', fontsize = 20)plt.xticks(fontsize = 15)plt.yticks(fontsize = 15)plt.xlabel('Wavelength (nm)', fontsize = 20)plt.ylabel('Score', fontsize = 20)plt.show()"
},
{
"code": null,
"e": 8961,
"s": 8895,
"text": "And once more, the number of detected spikes can be calculated as"
},
{
"code": null,
"e": 9329,
"s": 8961,
"text": "# 1 is assigned to spikes, 0 to non-spikes:spikes = abs(np.array(modified_z_score(intensity))) > thresholdplt.plot(wavelength, spikes, color = ‘red’)plt.title(‘Spikes: ‘ + str(np.sum(spikes)), fontsize = 20)plt.grid()plt.xticks(fontsize = 15)plt.yticks(fontsize = 15)plt.xlabel( ‘Wavelength’ ,fontsize = 20)#plt.ylabel( ‘Spike(1) or not(0)?’ ,fontsize = 20)plt.show()"
},
{
"code": null,
"e": 9501,
"s": 9329,
"text": "For the 3.5 recommended threshold many false spikes are assigned. However, the value scored by this approach is much higher in comparison with the Raman peaks than before."
},
{
"code": null,
"e": 9974,
"s": 9501,
"text": "plt.plot(wavelength[1:],np.array(abs(modified_z_score(delta_int))), color='black', label = '|Modified Z-Score using ∇x(i)|')plt.plot(wavelength, np.array(abs(modified_z_score(intensity))), label = '|Modified Z-Score|', color = 'red')plt.plot(wavelength, np.array(abs(z_score(intensity))), label = '|Z-Score|', color = 'blue')plt.xticks(fontsize = 15)plt.yticks(fontsize = 15)plt.xlabel( 'Wavelength' ,fontsize = 20)plt.ylabel( 'Score' ,fontsize = 20)plt.legend()plt.show()"
},
{
"code": null,
"e": 10126,
"s": 9974,
"text": "In general, the right threshold must be chosen depending on the data set. For this case, a threshold = 7 is already enough to obtain a clear selection."
},
{
"code": null,
"e": 10152,
"s": 10126,
"text": "Fixing the Raman spectrum"
},
{
"code": null,
"e": 10389,
"s": 10152,
"text": "Once the spikes are detected, the next step is to remove them and fix the spectra. For this, interpolated values are obtained at each candidate wavenumber by calculating the mean of its immediate neighbors (within a 2m+1 values window)."
},
{
"code": null,
"e": 11216,
"s": 10389,
"text": "def fixer(y,m): threshold = 7 # binarization threshold. spikes = abs(np.array(modified_z_score(np.diff(y)))) > threshold y_out = y.copy() # So we don’t overwrite y for i in np.arange(len(spikes)): if spikes[i] != 0: # If we have an spike in position i w = np.arange(i-m,i+1+m) # we select 2 m + 1 points around our spike w2 = w[spikes[w] == 0] # From such interval, we choose the ones which are not spikes y_out[i] = np.mean(y[w2]) # and we average their values return y_out# Does it work?plt.plot(wavelength, intensity, label = 'original data')plt.plot(wavelength, fixer(intensity,m=3), label = 'fixed spectrum')plt.title('Despiked spectrum',fontsize = 20)plt.xticks(fontsize = 15)plt.yticks(fontsize = 15)plt.xlabel('Wavelength (nm)' ,fontsize = 20)plt.ylabel('Intensity (a.u.)' ,fontsize = 20)plt.legend()plt.show()"
},
{
"code": null,
"e": 11399,
"s": 11216,
"text": "So after calculation of the modified Z scores of ∇x, and thresholding by setting an appropiate threshold value, the spike is removed and smoothed by applying a moving average filter."
},
{
"code": null,
"e": 11414,
"s": 11399,
"text": "Other examples"
},
{
"code": null,
"e": 11535,
"s": 11414,
"text": "To wrap up, two examples of spikes with different intensity signal are presented, showing the strenght of this approach."
},
{
"code": null,
"e": 11661,
"s": 11535,
"text": "Aknowledgements. I would like to thank Jorge Luis Hita and Ana Solaguren-Beascoa for taking the time to proofread this notes."
},
{
"code": null,
"e": 11820,
"s": 11661,
"text": "[1] Whitaker, Darren A., and Kevin Hayes. “A simple algorithm for despiking Raman spectra.” Chemometrics and Intelligent Laboratory Systems 179 (2018): 82–84."
},
{
"code": null,
"e": 11977,
"s": 11820,
"text": "[2] Iglewicz, B., and D. Hoaglin. “The ASQC basic references in quality control: statistical techniques.” How to detect and handle outliers 16 (1993): 1–87."
},
{
"code": null,
"e": 12091,
"s": 11977,
"text": "[3] Colin Gorrie’s Data Story: Three ways to detect outliers. http://colingorrie.github.io/outlier-detection.html"
}
] |
Comparison of boolean data type in C++ and Java - GeeksforGeeks | 12 Jun, 2017
The Boolean data type is one of the primitive data types in both C++ and Java. Although, it may seem to be the easiest of all the data types, as it can have only two values – true or false, but it surely is a tricky one as there are certain differences in its usage in both Java and C++, which if not taken care, can result in an error. The difference in its usage in C++ and Java are-
Declaration: The declaration of boolean data type in C++ involve the use of keyword bool, whereas declaration in Java is done by keyword boolean.C++ Code:#include<iostream>using namespace std;int main(){ bool a = true; // Syntax of Java // boolean b = false; return 0;} Java Code:class A{ public static void main(String args[]) { boolean a = true; // Syntax of C++ // bool b = false; }}Default Value: Default value is the value initially stored in the variable, when it is declared, but not initialized to any value. The default value of boolean data type in Java is false, whereas in C++, it has no default value and contains garbage value (only in case of global variables, it will have default value as false).C++ Code:#include<iostream>using namespace std;int main(){ // Declaring a boolean type array in C++ bool a[5]; int i; for (i=0; i<5; ++i) { cout << a[i] << " "; } return 0;}All the values stored in the array in the above program are garbage values and are not fixed.Java Code:class A{ public static void main(String args[]) { // Declaring a boolean type array in Java boolean a[]; a = new boolean[5]; int i; for(i=0; i<5; ++i) { System.out.println(a[i]); } }}Output:false
false
false
false
false
All the values in the array a will be false by default, as illustrated in the above output.Use in Mathematical Expressions: One important difference is that boolean data type variables cannot be used in mathematical expressions in java as it will give an error, whereas they can be used easily so in C++.The reason for this behaviour is that boolean variables are not converted into integer values (0 or 1) in Java, so they cannot be used so.C++ Code:#include<iostream>using namespace std;int main(){ int a; bool b = true; bool c = false; a = b + c; cout << a; return 0;}Output:1
The output will be 1 as true will be converted to value 1 and false will be converted to value 0, so a will store 1, whereas the same code will give an error in java, as shown below-Java Code:class A{ public static void main(String args[]) { int a; boolean b = true; boolean c = false; //The following line will give an error a = b + c; System.out.println(a); }}Use with Relational Operators: In Java, boolean variables cannot be used with the relational operators like <, >, <=, and >= , whereas in C++, they can be used in this manner . However, they can be used with == and != operators in both Java and C++ .This can be accounted to the fact that relational operators operate on numeric values and boolean variables are not stored as numeric values in Java, but are stored so in C++ (false is stored as 0 and true as 1) .C++ Code:#include<iostream>using namespace std;int main(){ bool a = true; bool b = false; if (a > b) { cout << "a is greater than b"; } else { cout << "a is smaller than b"; } return 0;}Output:a is greater than bJava Code:class a{ public static void main(String args[]) { boolean a = true; boolean b = false; //The following line will give an error if (a > b) { System.out.println("a is greater than b"); } else { System.out.println("a is smaller than b"); } }}Floating point value: In C++, floating, integer values can be easily assigned to a boolean variable, as they will be implicitly type-casted into boolean, whereas doing so in Java will result in an error.C++ Code:#include<iostream>using namespace std;int main(){ // storing integer value in bool type variable bool a = 7; // storing floating value in bool type variable bool b = 7.0; cout << a << " " << b; return 0;}Output:1 1The above output results as storing any value in a boolean variable other than 0, will result in 1 being stored in that variable.Java Code:class a{ public static void main(String args[]) { // invalid assignment in Java boolean a = 7; // invalid assignment in Java boolean b = 7.0; System.out.println(a); System.out.println(b); }}The size of boolean data type in C++ is 1 byte, whereas size of boolean in Java is not precisely defined and it depends upon the Java Virtual Machine (JVM).Boolean values in Java always take more than one byte, but how much more depends where the value is being stored – in the stack, or on the heap. The JVM uses a 32-bit stack cell, which will cause each boolean value to occupy the complete stack cell of 32 bits. However, the size of boolean values on the heap are implementation dependent.This article is contributed by Mrigendra Singh. 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.My Personal Notes
arrow_drop_upSave
Declaration: The declaration of boolean data type in C++ involve the use of keyword bool, whereas declaration in Java is done by keyword boolean.C++ Code:#include<iostream>using namespace std;int main(){ bool a = true; // Syntax of Java // boolean b = false; return 0;} Java Code:class A{ public static void main(String args[]) { boolean a = true; // Syntax of C++ // bool b = false; }}
#include<iostream>using namespace std;int main(){ bool a = true; // Syntax of Java // boolean b = false; return 0;}
Java Code:
class A{ public static void main(String args[]) { boolean a = true; // Syntax of C++ // bool b = false; }}
Default Value: Default value is the value initially stored in the variable, when it is declared, but not initialized to any value. The default value of boolean data type in Java is false, whereas in C++, it has no default value and contains garbage value (only in case of global variables, it will have default value as false).C++ Code:#include<iostream>using namespace std;int main(){ // Declaring a boolean type array in C++ bool a[5]; int i; for (i=0; i<5; ++i) { cout << a[i] << " "; } return 0;}All the values stored in the array in the above program are garbage values and are not fixed.Java Code:class A{ public static void main(String args[]) { // Declaring a boolean type array in Java boolean a[]; a = new boolean[5]; int i; for(i=0; i<5; ++i) { System.out.println(a[i]); } }}Output:false
false
false
false
false
All the values in the array a will be false by default, as illustrated in the above output.
C++ Code:
#include<iostream>using namespace std;int main(){ // Declaring a boolean type array in C++ bool a[5]; int i; for (i=0; i<5; ++i) { cout << a[i] << " "; } return 0;}
All the values stored in the array in the above program are garbage values and are not fixed.
Java Code:
class A{ public static void main(String args[]) { // Declaring a boolean type array in Java boolean a[]; a = new boolean[5]; int i; for(i=0; i<5; ++i) { System.out.println(a[i]); } }}
Output:
false
false
false
false
false
All the values in the array a will be false by default, as illustrated in the above output.
Use in Mathematical Expressions: One important difference is that boolean data type variables cannot be used in mathematical expressions in java as it will give an error, whereas they can be used easily so in C++.The reason for this behaviour is that boolean variables are not converted into integer values (0 or 1) in Java, so they cannot be used so.C++ Code:#include<iostream>using namespace std;int main(){ int a; bool b = true; bool c = false; a = b + c; cout << a; return 0;}Output:1
The output will be 1 as true will be converted to value 1 and false will be converted to value 0, so a will store 1, whereas the same code will give an error in java, as shown below-Java Code:class A{ public static void main(String args[]) { int a; boolean b = true; boolean c = false; //The following line will give an error a = b + c; System.out.println(a); }}
The reason for this behaviour is that boolean variables are not converted into integer values (0 or 1) in Java, so they cannot be used so.
C++ Code:
#include<iostream>using namespace std;int main(){ int a; bool b = true; bool c = false; a = b + c; cout << a; return 0;}
Output:
1
The output will be 1 as true will be converted to value 1 and false will be converted to value 0, so a will store 1, whereas the same code will give an error in java, as shown below-
Java Code:
class A{ public static void main(String args[]) { int a; boolean b = true; boolean c = false; //The following line will give an error a = b + c; System.out.println(a); }}
Use with Relational Operators: In Java, boolean variables cannot be used with the relational operators like <, >, <=, and >= , whereas in C++, they can be used in this manner . However, they can be used with == and != operators in both Java and C++ .This can be accounted to the fact that relational operators operate on numeric values and boolean variables are not stored as numeric values in Java, but are stored so in C++ (false is stored as 0 and true as 1) .C++ Code:#include<iostream>using namespace std;int main(){ bool a = true; bool b = false; if (a > b) { cout << "a is greater than b"; } else { cout << "a is smaller than b"; } return 0;}Output:a is greater than bJava Code:class a{ public static void main(String args[]) { boolean a = true; boolean b = false; //The following line will give an error if (a > b) { System.out.println("a is greater than b"); } else { System.out.println("a is smaller than b"); } }}
This can be accounted to the fact that relational operators operate on numeric values and boolean variables are not stored as numeric values in Java, but are stored so in C++ (false is stored as 0 and true as 1) .
C++ Code:
#include<iostream>using namespace std;int main(){ bool a = true; bool b = false; if (a > b) { cout << "a is greater than b"; } else { cout << "a is smaller than b"; } return 0;}
Output:
a is greater than b
Java Code:
class a{ public static void main(String args[]) { boolean a = true; boolean b = false; //The following line will give an error if (a > b) { System.out.println("a is greater than b"); } else { System.out.println("a is smaller than b"); } }}
Floating point value: In C++, floating, integer values can be easily assigned to a boolean variable, as they will be implicitly type-casted into boolean, whereas doing so in Java will result in an error.C++ Code:#include<iostream>using namespace std;int main(){ // storing integer value in bool type variable bool a = 7; // storing floating value in bool type variable bool b = 7.0; cout << a << " " << b; return 0;}Output:1 1The above output results as storing any value in a boolean variable other than 0, will result in 1 being stored in that variable.Java Code:class a{ public static void main(String args[]) { // invalid assignment in Java boolean a = 7; // invalid assignment in Java boolean b = 7.0; System.out.println(a); System.out.println(b); }}
C++ Code:
#include<iostream>using namespace std;int main(){ // storing integer value in bool type variable bool a = 7; // storing floating value in bool type variable bool b = 7.0; cout << a << " " << b; return 0;}
Output:
1 1
The above output results as storing any value in a boolean variable other than 0, will result in 1 being stored in that variable.
Java Code:
class a{ public static void main(String args[]) { // invalid assignment in Java boolean a = 7; // invalid assignment in Java boolean b = 7.0; System.out.println(a); System.out.println(b); }}
The size of boolean data type in C++ is 1 byte, whereas size of boolean in Java is not precisely defined and it depends upon the Java Virtual Machine (JVM).Boolean values in Java always take more than one byte, but how much more depends where the value is being stored – in the stack, or on the heap. The JVM uses a 32-bit stack cell, which will cause each boolean value to occupy the complete stack cell of 32 bits. However, the size of boolean values on the heap are implementation dependent.This article is contributed by Mrigendra Singh. 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.My Personal Notes
arrow_drop_upSave
Boolean values in Java always take more than one byte, but how much more depends where the value is being stored – in the stack, or on the heap. The JVM uses a 32-bit stack cell, which will cause each boolean value to occupy the complete stack cell of 32 bits. However, the size of boolean values on the heap are implementation dependent.
This article is contributed by Mrigendra Singh. 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.
cpp-data-types
Java-Data Types
C++
Java
Java
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Friend class and function in C++
Sorting a vector in C++
std::string class in C++
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Object Oriented Programming (OOPs) Concept in Java
Stream In Java | [
{
"code": null,
"e": 25369,
"s": 25341,
"text": "\n12 Jun, 2017"
},
{
"code": null,
"e": 25755,
"s": 25369,
"text": "The Boolean data type is one of the primitive data types in both C++ and Java. Although, it may seem to be the easiest of all the data types, as it can have only two values – true or false, but it surely is a tricky one as there are certain differences in its usage in both Java and C++, which if not taken care, can result in an error. The difference in its usage in C++ and Java are-"
},
{
"code": null,
"e": 31041,
"s": 25755,
"text": "Declaration: The declaration of boolean data type in C++ involve the use of keyword bool, whereas declaration in Java is done by keyword boolean.C++ Code:#include<iostream>using namespace std;int main(){ bool a = true; // Syntax of Java // boolean b = false; return 0;} Java Code:class A{ public static void main(String args[]) { boolean a = true; // Syntax of C++ // bool b = false; }}Default Value: Default value is the value initially stored in the variable, when it is declared, but not initialized to any value. The default value of boolean data type in Java is false, whereas in C++, it has no default value and contains garbage value (only in case of global variables, it will have default value as false).C++ Code:#include<iostream>using namespace std;int main(){ // Declaring a boolean type array in C++ bool a[5]; int i; for (i=0; i<5; ++i) { cout << a[i] << \" \"; } return 0;}All the values stored in the array in the above program are garbage values and are not fixed.Java Code:class A{ public static void main(String args[]) { // Declaring a boolean type array in Java boolean a[]; a = new boolean[5]; int i; for(i=0; i<5; ++i) { System.out.println(a[i]); } }}Output:false\nfalse\nfalse\nfalse\nfalse\nAll the values in the array a will be false by default, as illustrated in the above output.Use in Mathematical Expressions: One important difference is that boolean data type variables cannot be used in mathematical expressions in java as it will give an error, whereas they can be used easily so in C++.The reason for this behaviour is that boolean variables are not converted into integer values (0 or 1) in Java, so they cannot be used so.C++ Code:#include<iostream>using namespace std;int main(){ int a; bool b = true; bool c = false; a = b + c; cout << a; return 0;}Output:1\nThe output will be 1 as true will be converted to value 1 and false will be converted to value 0, so a will store 1, whereas the same code will give an error in java, as shown below-Java Code:class A{ public static void main(String args[]) { int a; boolean b = true; boolean c = false; //The following line will give an error a = b + c; System.out.println(a); }}Use with Relational Operators: In Java, boolean variables cannot be used with the relational operators like <, >, <=, and >= , whereas in C++, they can be used in this manner . However, they can be used with == and != operators in both Java and C++ .This can be accounted to the fact that relational operators operate on numeric values and boolean variables are not stored as numeric values in Java, but are stored so in C++ (false is stored as 0 and true as 1) .C++ Code:#include<iostream>using namespace std;int main(){ bool a = true; bool b = false; if (a > b) { cout << \"a is greater than b\"; } else { cout << \"a is smaller than b\"; } return 0;}Output:a is greater than bJava Code:class a{ public static void main(String args[]) { boolean a = true; boolean b = false; //The following line will give an error if (a > b) { System.out.println(\"a is greater than b\"); } else { System.out.println(\"a is smaller than b\"); } }}Floating point value: In C++, floating, integer values can be easily assigned to a boolean variable, as they will be implicitly type-casted into boolean, whereas doing so in Java will result in an error.C++ Code:#include<iostream>using namespace std;int main(){ // storing integer value in bool type variable bool a = 7; // storing floating value in bool type variable bool b = 7.0; cout << a << \" \" << b; return 0;}Output:1 1The above output results as storing any value in a boolean variable other than 0, will result in 1 being stored in that variable.Java Code:class a{ public static void main(String args[]) { // invalid assignment in Java boolean a = 7; // invalid assignment in Java boolean b = 7.0; System.out.println(a); System.out.println(b); }}The size of boolean data type in C++ is 1 byte, whereas size of boolean in Java is not precisely defined and it depends upon the Java Virtual Machine (JVM).Boolean values in Java always take more than one byte, but how much more depends where the value is being stored – in the stack, or on the heap. The JVM uses a 32-bit stack cell, which will cause each boolean value to occupy the complete stack cell of 32 bits. However, the size of boolean values on the heap are implementation dependent.This article is contributed by Mrigendra Singh. 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.My Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 31494,
"s": 31041,
"text": "Declaration: The declaration of boolean data type in C++ involve the use of keyword bool, whereas declaration in Java is done by keyword boolean.C++ Code:#include<iostream>using namespace std;int main(){ bool a = true; // Syntax of Java // boolean b = false; return 0;} Java Code:class A{ public static void main(String args[]) { boolean a = true; // Syntax of C++ // bool b = false; }}"
},
{
"code": "#include<iostream>using namespace std;int main(){ bool a = true; // Syntax of Java // boolean b = false; return 0;} ",
"e": 31637,
"s": 31494,
"text": null
},
{
"code": null,
"e": 31648,
"s": 31637,
"text": "Java Code:"
},
{
"code": "class A{ public static void main(String args[]) { boolean a = true; // Syntax of C++ // bool b = false; }}",
"e": 31795,
"s": 31648,
"text": null
},
{
"code": null,
"e": 32813,
"s": 31795,
"text": "Default Value: Default value is the value initially stored in the variable, when it is declared, but not initialized to any value. The default value of boolean data type in Java is false, whereas in C++, it has no default value and contains garbage value (only in case of global variables, it will have default value as false).C++ Code:#include<iostream>using namespace std;int main(){ // Declaring a boolean type array in C++ bool a[5]; int i; for (i=0; i<5; ++i) { cout << a[i] << \" \"; } return 0;}All the values stored in the array in the above program are garbage values and are not fixed.Java Code:class A{ public static void main(String args[]) { // Declaring a boolean type array in Java boolean a[]; a = new boolean[5]; int i; for(i=0; i<5; ++i) { System.out.println(a[i]); } }}Output:false\nfalse\nfalse\nfalse\nfalse\nAll the values in the array a will be false by default, as illustrated in the above output."
},
{
"code": null,
"e": 32823,
"s": 32813,
"text": "C++ Code:"
},
{
"code": "#include<iostream>using namespace std;int main(){ // Declaring a boolean type array in C++ bool a[5]; int i; for (i=0; i<5; ++i) { cout << a[i] << \" \"; } return 0;}",
"e": 33020,
"s": 32823,
"text": null
},
{
"code": null,
"e": 33114,
"s": 33020,
"text": "All the values stored in the array in the above program are garbage values and are not fixed."
},
{
"code": null,
"e": 33125,
"s": 33114,
"text": "Java Code:"
},
{
"code": "class A{ public static void main(String args[]) { // Declaring a boolean type array in Java boolean a[]; a = new boolean[5]; int i; for(i=0; i<5; ++i) { System.out.println(a[i]); } }}",
"e": 33380,
"s": 33125,
"text": null
},
{
"code": null,
"e": 33388,
"s": 33380,
"text": "Output:"
},
{
"code": null,
"e": 33419,
"s": 33388,
"text": "false\nfalse\nfalse\nfalse\nfalse\n"
},
{
"code": null,
"e": 33511,
"s": 33419,
"text": "All the values in the array a will be false by default, as illustrated in the above output."
},
{
"code": null,
"e": 34447,
"s": 33511,
"text": "Use in Mathematical Expressions: One important difference is that boolean data type variables cannot be used in mathematical expressions in java as it will give an error, whereas they can be used easily so in C++.The reason for this behaviour is that boolean variables are not converted into integer values (0 or 1) in Java, so they cannot be used so.C++ Code:#include<iostream>using namespace std;int main(){ int a; bool b = true; bool c = false; a = b + c; cout << a; return 0;}Output:1\nThe output will be 1 as true will be converted to value 1 and false will be converted to value 0, so a will store 1, whereas the same code will give an error in java, as shown below-Java Code:class A{ public static void main(String args[]) { int a; boolean b = true; boolean c = false; //The following line will give an error a = b + c; System.out.println(a); }}"
},
{
"code": null,
"e": 34586,
"s": 34447,
"text": "The reason for this behaviour is that boolean variables are not converted into integer values (0 or 1) in Java, so they cannot be used so."
},
{
"code": null,
"e": 34596,
"s": 34586,
"text": "C++ Code:"
},
{
"code": "#include<iostream>using namespace std;int main(){ int a; bool b = true; bool c = false; a = b + c; cout << a; return 0;}",
"e": 34735,
"s": 34596,
"text": null
},
{
"code": null,
"e": 34743,
"s": 34735,
"text": "Output:"
},
{
"code": null,
"e": 34746,
"s": 34743,
"text": "1\n"
},
{
"code": null,
"e": 34929,
"s": 34746,
"text": "The output will be 1 as true will be converted to value 1 and false will be converted to value 0, so a will store 1, whereas the same code will give an error in java, as shown below-"
},
{
"code": null,
"e": 34940,
"s": 34929,
"text": "Java Code:"
},
{
"code": "class A{ public static void main(String args[]) { int a; boolean b = true; boolean c = false; //The following line will give an error a = b + c; System.out.println(a); }}",
"e": 35177,
"s": 34940,
"text": null
},
{
"code": null,
"e": 36259,
"s": 35177,
"text": "Use with Relational Operators: In Java, boolean variables cannot be used with the relational operators like <, >, <=, and >= , whereas in C++, they can be used in this manner . However, they can be used with == and != operators in both Java and C++ .This can be accounted to the fact that relational operators operate on numeric values and boolean variables are not stored as numeric values in Java, but are stored so in C++ (false is stored as 0 and true as 1) .C++ Code:#include<iostream>using namespace std;int main(){ bool a = true; bool b = false; if (a > b) { cout << \"a is greater than b\"; } else { cout << \"a is smaller than b\"; } return 0;}Output:a is greater than bJava Code:class a{ public static void main(String args[]) { boolean a = true; boolean b = false; //The following line will give an error if (a > b) { System.out.println(\"a is greater than b\"); } else { System.out.println(\"a is smaller than b\"); } }}"
},
{
"code": null,
"e": 36473,
"s": 36259,
"text": "This can be accounted to the fact that relational operators operate on numeric values and boolean variables are not stored as numeric values in Java, but are stored so in C++ (false is stored as 0 and true as 1) ."
},
{
"code": null,
"e": 36483,
"s": 36473,
"text": "C++ Code:"
},
{
"code": "#include<iostream>using namespace std;int main(){ bool a = true; bool b = false; if (a > b) { cout << \"a is greater than b\"; } else { cout << \"a is smaller than b\"; } return 0;}",
"e": 36712,
"s": 36483,
"text": null
},
{
"code": null,
"e": 36720,
"s": 36712,
"text": "Output:"
},
{
"code": null,
"e": 36740,
"s": 36720,
"text": "a is greater than b"
},
{
"code": null,
"e": 36751,
"s": 36740,
"text": "Java Code:"
},
{
"code": "class a{ public static void main(String args[]) { boolean a = true; boolean b = false; //The following line will give an error if (a > b) { System.out.println(\"a is greater than b\"); } else { System.out.println(\"a is smaller than b\"); } }}",
"e": 37097,
"s": 36751,
"text": null
},
{
"code": null,
"e": 37943,
"s": 37097,
"text": "Floating point value: In C++, floating, integer values can be easily assigned to a boolean variable, as they will be implicitly type-casted into boolean, whereas doing so in Java will result in an error.C++ Code:#include<iostream>using namespace std;int main(){ // storing integer value in bool type variable bool a = 7; // storing floating value in bool type variable bool b = 7.0; cout << a << \" \" << b; return 0;}Output:1 1The above output results as storing any value in a boolean variable other than 0, will result in 1 being stored in that variable.Java Code:class a{ public static void main(String args[]) { // invalid assignment in Java boolean a = 7; // invalid assignment in Java boolean b = 7.0; System.out.println(a); System.out.println(b); }}"
},
{
"code": null,
"e": 37953,
"s": 37943,
"text": "C++ Code:"
},
{
"code": "#include<iostream>using namespace std;int main(){ // storing integer value in bool type variable bool a = 7; // storing floating value in bool type variable bool b = 7.0; cout << a << \" \" << b; return 0;}",
"e": 38182,
"s": 37953,
"text": null
},
{
"code": null,
"e": 38190,
"s": 38182,
"text": "Output:"
},
{
"code": null,
"e": 38194,
"s": 38190,
"text": "1 1"
},
{
"code": null,
"e": 38324,
"s": 38194,
"text": "The above output results as storing any value in a boolean variable other than 0, will result in 1 being stored in that variable."
},
{
"code": null,
"e": 38335,
"s": 38324,
"text": "Java Code:"
},
{
"code": "class a{ public static void main(String args[]) { // invalid assignment in Java boolean a = 7; // invalid assignment in Java boolean b = 7.0; System.out.println(a); System.out.println(b); }}",
"e": 38592,
"s": 38335,
"text": null
},
{
"code": null,
"e": 39548,
"s": 38592,
"text": "The size of boolean data type in C++ is 1 byte, whereas size of boolean in Java is not precisely defined and it depends upon the Java Virtual Machine (JVM).Boolean values in Java always take more than one byte, but how much more depends where the value is being stored – in the stack, or on the heap. The JVM uses a 32-bit stack cell, which will cause each boolean value to occupy the complete stack cell of 32 bits. However, the size of boolean values on the heap are implementation dependent.This article is contributed by Mrigendra Singh. 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.My Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 39887,
"s": 39548,
"text": "Boolean values in Java always take more than one byte, but how much more depends where the value is being stored – in the stack, or on the heap. The JVM uses a 32-bit stack cell, which will cause each boolean value to occupy the complete stack cell of 32 bits. However, the size of boolean values on the heap are implementation dependent."
},
{
"code": null,
"e": 40190,
"s": 39887,
"text": "This article is contributed by Mrigendra Singh. 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": 40315,
"s": 40190,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 40330,
"s": 40315,
"text": "cpp-data-types"
},
{
"code": null,
"e": 40346,
"s": 40330,
"text": "Java-Data Types"
},
{
"code": null,
"e": 40350,
"s": 40346,
"text": "C++"
},
{
"code": null,
"e": 40355,
"s": 40350,
"text": "Java"
},
{
"code": null,
"e": 40360,
"s": 40355,
"text": "Java"
},
{
"code": null,
"e": 40364,
"s": 40360,
"text": "CPP"
},
{
"code": null,
"e": 40462,
"s": 40364,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 40490,
"s": 40462,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 40510,
"s": 40490,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 40543,
"s": 40510,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 40567,
"s": 40543,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 40592,
"s": 40567,
"text": "std::string class in C++"
},
{
"code": null,
"e": 40607,
"s": 40592,
"text": "Arrays in Java"
},
{
"code": null,
"e": 40651,
"s": 40607,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 40673,
"s": 40651,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 40724,
"s": 40673,
"text": "Object Oriented Programming (OOPs) Concept in Java"
}
] |
How to create a data frame with a column having repeated values in R? | To create a data frame with a column having repeated values, we simply need to use rep function and we can repeat the values in a sequence of the values passed or repeating each value a particular number of times. For example, if we have three values 1, 2, 3 then the data frame can be created by repeating these values as 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3 or by repeating the same as 1, 1, 1, 2, 2, 2, 3, 3, 3.
Live Demo
x<-rep(c(1,2,3,4),times=5)
df1<-data.frame(x)
df1
x
1 1
2 2
3 3
4 4
5 1
6 2
7 3
8 4
9 1
10 2
11 3
12 4
13 1
14 2
15 3
16 4
17 1
18 2
19 3
20 4
Live Demo
y<-rep(c(1,2,3,4),each=5)
df2<-data.frame(y)
df2
y
1 1
2 1
3 1
4 1
5 1
6 2
7 2
8 2
9 2
10 2
11 3
12 3
13 3
14 3
15 3
16 4
17 4
18 4
19 4
20 4
Live Demo
z<-rep(c("A","B","C","D","E"),each=4)
df3<-data.frame(z)
df3
z
1 A
2 A
3 A
4 A
5 B
6 B
7 B
8 B
9 C
10 C
11 C
12 C
13 D
14 D
15 D
16 D
17 E
18 E
19 E
20 E
Live Demo
w<-rep(c("A","B","C","D","E"),times=4)
df4<-data.frame(w)
df4
w
1 A
2 B
3 C
4 D
5 E
6 A
7 B
8 C
9 D
10 E
11 A
12 B
13 C
14 D
15 E
16 A
17 B
18 C
19 D
20 E | [
{
"code": null,
"e": 1475,
"s": 1062,
"text": "To create a data frame with a column having repeated values, we simply need to use rep function and we can repeat the values in a sequence of the values passed or repeating each value a particular number of times. For example, if we have three values 1, 2, 3 then the data frame can be created by repeating these values as 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3 or by repeating the same as 1, 1, 1, 2, 2, 2, 3, 3, 3."
},
{
"code": null,
"e": 1486,
"s": 1475,
"text": " Live Demo"
},
{
"code": null,
"e": 1536,
"s": 1486,
"text": "x<-rep(c(1,2,3,4),times=5)\ndf1<-data.frame(x)\ndf1"
},
{
"code": null,
"e": 1641,
"s": 1536,
"text": " x\n1 1\n2 2\n3 3\n4 4\n5 1\n6 2\n7 3\n8 4\n9 1\n10 2\n11 3\n12 4\n13 1\n14 2\n15 3\n16 4\n17 1\n18 2\n19 3\n20 4"
},
{
"code": null,
"e": 1652,
"s": 1641,
"text": " Live Demo"
},
{
"code": null,
"e": 1701,
"s": 1652,
"text": "y<-rep(c(1,2,3,4),each=5)\ndf2<-data.frame(y)\ndf2"
},
{
"code": null,
"e": 1806,
"s": 1701,
"text": " y\n1 1\n2 1\n3 1\n4 1\n5 1\n6 2\n7 2\n8 2\n9 2\n10 2\n11 3\n12 3\n13 3\n14 3\n15 3\n16 4\n17 4\n18 4\n19 4\n20 4"
},
{
"code": null,
"e": 1817,
"s": 1806,
"text": " Live Demo"
},
{
"code": null,
"e": 1878,
"s": 1817,
"text": "z<-rep(c(\"A\",\"B\",\"C\",\"D\",\"E\"),each=4)\ndf3<-data.frame(z)\ndf3"
},
{
"code": null,
"e": 1983,
"s": 1878,
"text": " z\n1 A\n2 A\n3 A\n4 A\n5 B\n6 B\n7 B\n8 B\n9 C\n10 C\n11 C\n12 C\n13 D\n14 D\n15 D\n16 D\n17 E\n18 E\n19 E\n20 E"
},
{
"code": null,
"e": 1994,
"s": 1983,
"text": " Live Demo"
},
{
"code": null,
"e": 2056,
"s": 1994,
"text": "w<-rep(c(\"A\",\"B\",\"C\",\"D\",\"E\"),times=4)\ndf4<-data.frame(w)\ndf4"
},
{
"code": null,
"e": 2161,
"s": 2056,
"text": " w\n1 A\n2 B\n3 C\n4 D\n5 E\n6 A\n7 B\n8 C\n9 D\n10 E\n11 A\n12 B\n13 C\n14 D\n15 E\n16 A\n17 B\n18 C\n19 D\n20 E"
}
] |
How to Resample Time Series Data in Python? | 19 Dec, 2021
In time series, data consistency is of prime importance, resampling ensures that the data is distributed with a consistent frequency. Resampling can also provide a different perception of looking at the data, in other words, it can add additional insights about the data based on the resampling frequency.
resample() function: It is a primarily used for time series data.
Syntax:
# import the python pandas library
import pandas as pd
# syntax for the resample function.
pd.series.resample(rule, axis=0, closed='left',
convention='start', kind=None, offset=None,
origin='start_day')
Resampling primarily involves changing the time-frequency of the original observations. The two popular methods of resampling in time series are as follows
Upsampling
Downsampling
Upsampling involves increasing the time-frequency of the data, it is a data disaggregation procedure where we break down the time frequency from a higher level to a lower level. For example Breaking down the time-frequency from months to days, or days to hours or hours to seconds. Upsampling usually blows up the size of the data, depending on the sampling frequency. If D is the size of original data and D’ is the size of Upsampled data, then D’ > D
Now, let’s look at an example using Python to perform resampling in time-series data.
Click here to download the practice dataset Detergent sales data.csv used for the implementation.
Example:
Python3
# import the python pandas libraryimport pandas as pd # read data using read_csvdata = pd.read_csv("Detergent sales data.csv", header=0, index_col=0, parse_dates=True, squeeze=True)
Output:
The detergent sales data shows sales value for the first 6 months. Assume the task here is to predict the value of the daily sales. Given monthly data, we are asked to predict the daily sales data, which signifies the use of Upsampling.
Python3
# Use resample function to upsample months # to days using the mean sales of monthupsampled = data.resample('D').mean()
Output:
The output shows a few samples of the dataset which is upsampled from months to days, based on the mean value of the month. You can also try using sum(), median() that best suits the problem.
The dataset has been upsampled with nan values for the remaining days except for those days which were originally available in our dataset. (total sales data for each month).
Now, we can fill these nan values using a technique called Interpolation. Pandas provide a function called DataFrame.interpolate() for this purpose. Interpolation is a method that involves filling the nan values using one of the techniques like nearest’, ‘zero’, ‘slinear’, ‘quadratic’, ‘cubic’, ‘spline’, ‘barycentric’, ‘polynomial’. We will choose “linear” interpolation. This draws a straight line between available data, in this case on the last of the month, and fills in values at the chosen frequency from this line.
Python3
# use interpolate function with method linear# to upsample the values of the upsampled days # linearlyinterpolated = upsampled.interpolate(method='linear') # Printing the linear interpolated values for month 2print(interpolated['2021-02']) .
Output:
Another common interpolation method is to use a polynomial or a spline to connect the values. This creates more curves and can look realistic on many datasets. Using a spline interpolation requires you to specify the order (number of terms in the polynomial).
Python3
# use interpolate function with method polynomial# This upsamples the values of the remaining# days with a quadratic function of degree 2.interpolated = upsampled.interpolate(method='polynomial', order=2) # Printing the polynomial interpolated valueprint(interpolated)
Output:
Thus, we can use resample() and interpolate() function to upsample the data. Try this out using different configurations of these functions.
Downsampling involves decreasing the time-frequency of the data, it is a data aggregation procedure where we aggregate the time frequency from a lower level to a higher level. For example summarizing the time-frequency from days to months, or hours to days or seconds to hours. Downsampling usually shrinks the size of the data, depending on the sampling frequency. If D is the size of original data and D’ is the size of Upsampled data, then D’ < D.
For example, car sales data shows sales value for the first 6 months daywise. Assume the task here is to predict the value of the quarterly sales. Given daily data, we are asked to predict the quarterly sales data, which signifies the use of downsampling.
Click here to download the practice dataset car-sales.csv used in this implementation.
Example:
Python3
# import the python pandas libraryimport pandas as pd # read the data using pandas read_csv() function.data = pd.read_csv("car-sales.csv", header=0, index_col=0, parse_dates=True, squeeze=True)# printing the first 6 rows of the datasetprint(data.head(6))
Output:
We can use quarterly resampling frequency ‘Q’ to aggregate the data quarter-wise.
Python3
# Use resample function to downsample days# to months using the mean sales of month.downsampled = data.resample('Q').mean() # printing the downsampled data.print(downsampled)
Output:
Now, this downsampled data can be used for predicting quarterly sales.
Picked
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n19 Dec, 2021"
},
{
"code": null,
"e": 360,
"s": 54,
"text": "In time series, data consistency is of prime importance, resampling ensures that the data is distributed with a consistent frequency. Resampling can also provide a different perception of looking at the data, in other words, it can add additional insights about the data based on the resampling frequency."
},
{
"code": null,
"e": 427,
"s": 360,
"text": "resample() function: It is a primarily used for time series data."
},
{
"code": null,
"e": 435,
"s": 427,
"text": "Syntax:"
},
{
"code": null,
"e": 641,
"s": 435,
"text": "# import the python pandas library\nimport pandas as pd\n\n# syntax for the resample function.\npd.series.resample(rule, axis=0, closed='left',\n convention='start', kind=None, offset=None,\n origin='start_day')"
},
{
"code": null,
"e": 797,
"s": 641,
"text": "Resampling primarily involves changing the time-frequency of the original observations. The two popular methods of resampling in time series are as follows"
},
{
"code": null,
"e": 808,
"s": 797,
"text": "Upsampling"
},
{
"code": null,
"e": 821,
"s": 808,
"text": "Downsampling"
},
{
"code": null,
"e": 1274,
"s": 821,
"text": "Upsampling involves increasing the time-frequency of the data, it is a data disaggregation procedure where we break down the time frequency from a higher level to a lower level. For example Breaking down the time-frequency from months to days, or days to hours or hours to seconds. Upsampling usually blows up the size of the data, depending on the sampling frequency. If D is the size of original data and D’ is the size of Upsampled data, then D’ > D"
},
{
"code": null,
"e": 1360,
"s": 1274,
"text": "Now, let’s look at an example using Python to perform resampling in time-series data."
},
{
"code": null,
"e": 1458,
"s": 1360,
"text": "Click here to download the practice dataset Detergent sales data.csv used for the implementation."
},
{
"code": null,
"e": 1467,
"s": 1458,
"text": "Example:"
},
{
"code": null,
"e": 1475,
"s": 1467,
"text": "Python3"
},
{
"code": "# import the python pandas libraryimport pandas as pd # read data using read_csvdata = pd.read_csv(\"Detergent sales data.csv\", header=0, index_col=0, parse_dates=True, squeeze=True)",
"e": 1676,
"s": 1475,
"text": null
},
{
"code": null,
"e": 1684,
"s": 1676,
"text": "Output:"
},
{
"code": null,
"e": 1922,
"s": 1684,
"text": "The detergent sales data shows sales value for the first 6 months. Assume the task here is to predict the value of the daily sales. Given monthly data, we are asked to predict the daily sales data, which signifies the use of Upsampling. "
},
{
"code": null,
"e": 1930,
"s": 1922,
"text": "Python3"
},
{
"code": "# Use resample function to upsample months # to days using the mean sales of monthupsampled = data.resample('D').mean()",
"e": 2050,
"s": 1930,
"text": null
},
{
"code": null,
"e": 2058,
"s": 2050,
"text": "Output:"
},
{
"code": null,
"e": 2250,
"s": 2058,
"text": "The output shows a few samples of the dataset which is upsampled from months to days, based on the mean value of the month. You can also try using sum(), median() that best suits the problem."
},
{
"code": null,
"e": 2425,
"s": 2250,
"text": "The dataset has been upsampled with nan values for the remaining days except for those days which were originally available in our dataset. (total sales data for each month)."
},
{
"code": null,
"e": 2950,
"s": 2425,
"text": "Now, we can fill these nan values using a technique called Interpolation. Pandas provide a function called DataFrame.interpolate() for this purpose. Interpolation is a method that involves filling the nan values using one of the techniques like nearest’, ‘zero’, ‘slinear’, ‘quadratic’, ‘cubic’, ‘spline’, ‘barycentric’, ‘polynomial’. We will choose “linear” interpolation. This draws a straight line between available data, in this case on the last of the month, and fills in values at the chosen frequency from this line. "
},
{
"code": null,
"e": 2958,
"s": 2950,
"text": "Python3"
},
{
"code": "# use interpolate function with method linear# to upsample the values of the upsampled days # linearlyinterpolated = upsampled.interpolate(method='linear') # Printing the linear interpolated values for month 2print(interpolated['2021-02']) .",
"e": 3201,
"s": 2958,
"text": null
},
{
"code": null,
"e": 3209,
"s": 3201,
"text": "Output:"
},
{
"code": null,
"e": 3469,
"s": 3209,
"text": "Another common interpolation method is to use a polynomial or a spline to connect the values. This creates more curves and can look realistic on many datasets. Using a spline interpolation requires you to specify the order (number of terms in the polynomial)."
},
{
"code": null,
"e": 3477,
"s": 3469,
"text": "Python3"
},
{
"code": "# use interpolate function with method polynomial# This upsamples the values of the remaining# days with a quadratic function of degree 2.interpolated = upsampled.interpolate(method='polynomial', order=2) # Printing the polynomial interpolated valueprint(interpolated)",
"e": 3747,
"s": 3477,
"text": null
},
{
"code": null,
"e": 3755,
"s": 3747,
"text": "Output:"
},
{
"code": null,
"e": 3896,
"s": 3755,
"text": "Thus, we can use resample() and interpolate() function to upsample the data. Try this out using different configurations of these functions."
},
{
"code": null,
"e": 4347,
"s": 3896,
"text": "Downsampling involves decreasing the time-frequency of the data, it is a data aggregation procedure where we aggregate the time frequency from a lower level to a higher level. For example summarizing the time-frequency from days to months, or hours to days or seconds to hours. Downsampling usually shrinks the size of the data, depending on the sampling frequency. If D is the size of original data and D’ is the size of Upsampled data, then D’ < D."
},
{
"code": null,
"e": 4604,
"s": 4347,
"text": "For example, car sales data shows sales value for the first 6 months daywise. Assume the task here is to predict the value of the quarterly sales. Given daily data, we are asked to predict the quarterly sales data, which signifies the use of downsampling. "
},
{
"code": null,
"e": 4691,
"s": 4604,
"text": "Click here to download the practice dataset car-sales.csv used in this implementation."
},
{
"code": null,
"e": 4700,
"s": 4691,
"text": "Example:"
},
{
"code": null,
"e": 4708,
"s": 4700,
"text": "Python3"
},
{
"code": "# import the python pandas libraryimport pandas as pd # read the data using pandas read_csv() function.data = pd.read_csv(\"car-sales.csv\", header=0, index_col=0, parse_dates=True, squeeze=True)# printing the first 6 rows of the datasetprint(data.head(6))",
"e": 5001,
"s": 4708,
"text": null
},
{
"code": null,
"e": 5009,
"s": 5001,
"text": "Output:"
},
{
"code": null,
"e": 5091,
"s": 5009,
"text": "We can use quarterly resampling frequency ‘Q’ to aggregate the data quarter-wise."
},
{
"code": null,
"e": 5099,
"s": 5091,
"text": "Python3"
},
{
"code": "# Use resample function to downsample days# to months using the mean sales of month.downsampled = data.resample('Q').mean() # printing the downsampled data.print(downsampled)",
"e": 5275,
"s": 5099,
"text": null
},
{
"code": null,
"e": 5283,
"s": 5275,
"text": "Output:"
},
{
"code": null,
"e": 5354,
"s": 5283,
"text": "Now, this downsampled data can be used for predicting quarterly sales."
},
{
"code": null,
"e": 5361,
"s": 5354,
"text": "Picked"
},
{
"code": null,
"e": 5375,
"s": 5361,
"text": "Python-pandas"
},
{
"code": null,
"e": 5382,
"s": 5375,
"text": "Python"
},
{
"code": null,
"e": 5480,
"s": 5382,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5512,
"s": 5480,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 5539,
"s": 5512,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 5560,
"s": 5539,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 5583,
"s": 5560,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 5639,
"s": 5583,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 5670,
"s": 5639,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 5712,
"s": 5670,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 5754,
"s": 5712,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 5793,
"s": 5754,
"text": "Python | datetime.timedelta() function"
}
] |
Find frequency of each word in a string in Python | 31 Mar, 2020
Write a python code to find the frequency of each word in a given string.
Examples:
Input : str[] = "Apple Mango Orange Mango Guava Guava Mango"
Output : frequency of Apple is : 1
frequency of Mango is : 3
frequency of Orange is : 1
frequency of Guava is : 2
Input : str = "Train Bus Bus Train Taxi Aeroplane Taxi Bus"
Output : frequency of Train is : 2
frequency of Bus is : 3
frequency of Taxi is : 2
frequency of Aeroplane is : 1
Approach 1 using list():1. Split the string into a list containing the words by using split function (i.e. string.split()) in python with delimiter space.
Note:
string_name.split(separator) method is used to split the string
by specified separator(delimiter) into the list.
If delimiter is not provided then white space is a separator.
For example:
CODE : str='This is my book'
str.split()
OUTPUT : ['This', 'is', 'my', 'book']
2. Initialize a new empty list.3. Now append the word to the new list from previous string if that word is not present in the new list.4. Iterate over the new list and use count function (i.e. string.count(newstring[iteration])) to find the frequency of word at each iteration.
Note:
string_name.count(substring) is used to find no. of occurrence of
substring in a given string.
For example:
CODE : str='Apple Mango Apple'
str.count('Apple')
str2='Apple'
str.count(str2)
OUTPUT : 2
2
Python3
# Python code to find frequency of each worddef freq(str): # break the string into list of words str = str.split() str2 = [] # loop till string values present in list str for i in str: # checking for the duplicacy if i not in str2: # insert value in str2 str2.append(i) for i in range(0, len(str2)): # count the frequency of each word(present # in str2) in str and print print('Frequency of', str2[i], 'is :', str.count(str2[i])) def main(): str ='apple mango apple orange orange apple guava mango mango' freq(str) if __name__=="__main__": main() # call main function
Output:
Frequency of apple is : 3
Frequency of mango is : 3
Frequency of orange is : 2
Frequency of guava is : 1
Approach 2 using set():1. Split the string into a list containing the words by using split function (i.e. string.split()) in python with delimiter space.2. Use set() method to remove a duplicate and to give a set of unique words3. Iterate over the set and use count function (i.e. string.count(newstring[iteration])) to find the frequency of word at each iteration.
Python3
# Python3 code to find frequency of each word# function for calculating the frequencydef freq(str): # break the string into list of words str_list = str.split() # gives set of unique words unique_words = set(str_list) for words in unique_words : print('Frequency of ', words , 'is :', str_list.count(words)) # driver codeif __name__ == "__main__": str ='apple mango apple orange orange apple guava mango mango' # calling the freq function freq(str)
Output:
Frequency of apple is : 3
Frequency of mango is : 3
Frequency of orange is : 2
Frequency of guava is : 1
Approach 3 (Using Dictionary)
# Find frequency of each word in a string in Python# using dictionary. def count(elements): # check if each word has '.' at its last. If so then ignore '.' if elements[-1] == '.': elements = elements[0:len(elements) - 1] # if there exists a key as "elements" then simply # increase its value. if elements in dictionary: dictionary[elements] += 1 # if the dictionary does not have the key as "elements" # then create a key "elements" and assign its value to 1. else: dictionary.update({elements: 1}) # driver input to check the program. Sentence = "Apple Mango Orange Mango Guava Guava Mango" # Declare a dictionarydictionary = {} # split all the word of the string.lst = Sentence.split() # take each word from lst and pass it to the method count.for elements in lst: count(elements) # print the keys and its corresponding values.for allKeys in dictionary: print ("Frequency of ", allKeys, end = " ") print (":", end = " ") print (dictionary[allKeys], end = " ") print() # This code is contributed by Ronit Shrivastava.
ankthon
Ronit_shrivastava
frequency-counting
Python
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Rotate axis tick labels in Seaborn and Matplotlib
Deque in Python
Stack in Python
sum() function in Python
Print lists in Python (5 Different Ways)
Write a program to reverse an array or string
Reverse a string in Java
C++ Data Types
Write a program to print all permutations of a given string
Check for Balanced Brackets in an expression (well-formedness) using Stack | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n31 Mar, 2020"
},
{
"code": null,
"e": 127,
"s": 53,
"text": "Write a python code to find the frequency of each word in a given string."
},
{
"code": null,
"e": 137,
"s": 127,
"text": "Examples:"
},
{
"code": null,
"e": 545,
"s": 137,
"text": "Input : str[] = \"Apple Mango Orange Mango Guava Guava Mango\" \nOutput : frequency of Apple is : 1\n frequency of Mango is : 3\n frequency of Orange is : 1\n frequency of Guava is : 2\n\nInput : str = \"Train Bus Bus Train Taxi Aeroplane Taxi Bus\"\nOutput : frequency of Train is : 2\n frequency of Bus is : 3\n frequency of Taxi is : 2\n frequency of Aeroplane is : 1\n"
},
{
"code": null,
"e": 700,
"s": 545,
"text": "Approach 1 using list():1. Split the string into a list containing the words by using split function (i.e. string.split()) in python with delimiter space."
},
{
"code": null,
"e": 988,
"s": 700,
"text": "Note:\nstring_name.split(separator) method is used to split the string \nby specified separator(delimiter) into the list.\nIf delimiter is not provided then white space is a separator. \n\nFor example:\nCODE : str='This is my book'\n str.split()\nOUTPUT : ['This', 'is', 'my', 'book']\n"
},
{
"code": null,
"e": 1266,
"s": 988,
"text": "2. Initialize a new empty list.3. Now append the word to the new list from previous string if that word is not present in the new list.4. Iterate over the new list and use count function (i.e. string.count(newstring[iteration])) to find the frequency of word at each iteration."
},
{
"code": null,
"e": 1513,
"s": 1266,
"text": "Note:\nstring_name.count(substring) is used to find no. of occurrence of \nsubstring in a given string.\n\nFor example:\nCODE : str='Apple Mango Apple'\n str.count('Apple')\n str2='Apple'\n str.count(str2)\nOUTPUT : 2\n 2\n"
},
{
"code": null,
"e": 1521,
"s": 1513,
"text": "Python3"
},
{
"code": "# Python code to find frequency of each worddef freq(str): # break the string into list of words str = str.split() str2 = [] # loop till string values present in list str for i in str: # checking for the duplicacy if i not in str2: # insert value in str2 str2.append(i) for i in range(0, len(str2)): # count the frequency of each word(present # in str2) in str and print print('Frequency of', str2[i], 'is :', str.count(str2[i])) def main(): str ='apple mango apple orange orange apple guava mango mango' freq(str) if __name__==\"__main__\": main() # call main function",
"e": 2260,
"s": 1521,
"text": null
},
{
"code": null,
"e": 2268,
"s": 2260,
"text": "Output:"
},
{
"code": null,
"e": 2386,
"s": 2268,
"text": "Frequency of apple is : 3\nFrequency of mango is : 3\nFrequency of orange is : 2\nFrequency of guava is : 1\n"
},
{
"code": null,
"e": 2752,
"s": 2386,
"text": "Approach 2 using set():1. Split the string into a list containing the words by using split function (i.e. string.split()) in python with delimiter space.2. Use set() method to remove a duplicate and to give a set of unique words3. Iterate over the set and use count function (i.e. string.count(newstring[iteration])) to find the frequency of word at each iteration."
},
{
"code": null,
"e": 2760,
"s": 2752,
"text": "Python3"
},
{
"code": "# Python3 code to find frequency of each word# function for calculating the frequencydef freq(str): # break the string into list of words str_list = str.split() # gives set of unique words unique_words = set(str_list) for words in unique_words : print('Frequency of ', words , 'is :', str_list.count(words)) # driver codeif __name__ == \"__main__\": str ='apple mango apple orange orange apple guava mango mango' # calling the freq function freq(str)",
"e": 3263,
"s": 2760,
"text": null
},
{
"code": null,
"e": 3271,
"s": 3263,
"text": "Output:"
},
{
"code": null,
"e": 3389,
"s": 3271,
"text": "Frequency of apple is : 3\nFrequency of mango is : 3\nFrequency of orange is : 2\nFrequency of guava is : 1\n"
},
{
"code": null,
"e": 3419,
"s": 3389,
"text": "Approach 3 (Using Dictionary)"
},
{
"code": "# Find frequency of each word in a string in Python# using dictionary. def count(elements): # check if each word has '.' at its last. If so then ignore '.' if elements[-1] == '.': elements = elements[0:len(elements) - 1] # if there exists a key as \"elements\" then simply # increase its value. if elements in dictionary: dictionary[elements] += 1 # if the dictionary does not have the key as \"elements\" # then create a key \"elements\" and assign its value to 1. else: dictionary.update({elements: 1}) # driver input to check the program. Sentence = \"Apple Mango Orange Mango Guava Guava Mango\" # Declare a dictionarydictionary = {} # split all the word of the string.lst = Sentence.split() # take each word from lst and pass it to the method count.for elements in lst: count(elements) # print the keys and its corresponding values.for allKeys in dictionary: print (\"Frequency of \", allKeys, end = \" \") print (\":\", end = \" \") print (dictionary[allKeys], end = \" \") print() # This code is contributed by Ronit Shrivastava.",
"e": 4525,
"s": 3419,
"text": null
},
{
"code": null,
"e": 4533,
"s": 4525,
"text": "ankthon"
},
{
"code": null,
"e": 4551,
"s": 4533,
"text": "Ronit_shrivastava"
},
{
"code": null,
"e": 4570,
"s": 4551,
"text": "frequency-counting"
},
{
"code": null,
"e": 4577,
"s": 4570,
"text": "Python"
},
{
"code": null,
"e": 4585,
"s": 4577,
"text": "Strings"
},
{
"code": null,
"e": 4593,
"s": 4585,
"text": "Strings"
},
{
"code": null,
"e": 4691,
"s": 4593,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4741,
"s": 4691,
"text": "Rotate axis tick labels in Seaborn and Matplotlib"
},
{
"code": null,
"e": 4757,
"s": 4741,
"text": "Deque in Python"
},
{
"code": null,
"e": 4773,
"s": 4757,
"text": "Stack in Python"
},
{
"code": null,
"e": 4798,
"s": 4773,
"text": "sum() function in Python"
},
{
"code": null,
"e": 4839,
"s": 4798,
"text": "Print lists in Python (5 Different Ways)"
},
{
"code": null,
"e": 4885,
"s": 4839,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 4910,
"s": 4885,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 4925,
"s": 4910,
"text": "C++ Data Types"
},
{
"code": null,
"e": 4985,
"s": 4925,
"text": "Write a program to print all permutations of a given string"
}
] |
How to add a class to DOM element in JavaScript? | 03 Jan, 2022
DOM (Document Object Model) is a way of manipulating the document (HTML document). This article will deal with how to access and set class names to the DOM elements. In DOM, all HTML elements are defined as objects. We will be using Javascript against CSS to manipulate them.
Following are the properties of Javascript that we will be using to add a class to the DOM element:
classList Property: It returns the class name as a DOMTokenList object. It has a method called “add” which is used to add class name to elements.Syntax:element.classList.add("className")Example:htmlhtml<!DOCTYPE html><html> <head> <style> .geek { background-color: green; font-size: 50px; } </style></head> <body> <button onclick="myClass()">Try it</button> <div id="gfg">Geeks for Geeks</div> <script> function myClass() { var elem = document.getElementById("gfg"); // Adding class to div element elem.classList.add("geek"); } </script> </body> </html>Output:Before clicking the button:After clicking the button:
Syntax:
element.classList.add("className")
Example:
html
<!DOCTYPE html><html> <head> <style> .geek { background-color: green; font-size: 50px; } </style></head> <body> <button onclick="myClass()">Try it</button> <div id="gfg">Geeks for Geeks</div> <script> function myClass() { var elem = document.getElementById("gfg"); // Adding class to div element elem.classList.add("geek"); } </script> </body> </html>
After clicking the button:
className Property: This property returns the className of the element. If the element has already a class then it will simply add another one to it or else it will append our new class to it.Syntax:HTMLElementObject.classNameExample:htmlhtml<!DOCTYPE html><html> <head> <style> .geekClass { background-color: green; text-align: center; font-size: 50px; } </style></head> <body> <div id="gfg"> Geeks For Geeks </div> <button onclick="myClassName()">Add Class</button> <script> function myClassName() { var element = document.getElementById("gfg"); // Adding the class geekClass to element // with id gfg space is given in className // (" geekClass") as if there is already // a class attached to an element than our // new class won't overwrite and will append // one more class to the element element.className += " geekClass"; } </script> </body> </html>Output:Before clicking the button:After clicking the button:
Syntax:
HTMLElementObject.className
Example:
html
<!DOCTYPE html><html> <head> <style> .geekClass { background-color: green; text-align: center; font-size: 50px; } </style></head> <body> <div id="gfg"> Geeks For Geeks </div> <button onclick="myClassName()">Add Class</button> <script> function myClassName() { var element = document.getElementById("gfg"); // Adding the class geekClass to element // with id gfg space is given in className // (" geekClass") as if there is already // a class attached to an element than our // new class won't overwrite and will append // one more class to the element element.className += " geekClass"; } </script> </body> </html>
Supported Browsers: The browser supported by classList property are listed below:
Chrome 8+
Opera 11.5+
Safari 5.1+
Edge 10+
Mozilla Firefox 3.6+
sooda367
HTML-Misc
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n03 Jan, 2022"
},
{
"code": null,
"e": 304,
"s": 28,
"text": "DOM (Document Object Model) is a way of manipulating the document (HTML document). This article will deal with how to access and set class names to the DOM elements. In DOM, all HTML elements are defined as objects. We will be using Javascript against CSS to manipulate them."
},
{
"code": null,
"e": 404,
"s": 304,
"text": "Following are the properties of Javascript that we will be using to add a class to the DOM element:"
},
{
"code": null,
"e": 1142,
"s": 404,
"text": "classList Property: It returns the class name as a DOMTokenList object. It has a method called “add” which is used to add class name to elements.Syntax:element.classList.add(\"className\")Example:htmlhtml<!DOCTYPE html><html> <head> <style> .geek { background-color: green; font-size: 50px; } </style></head> <body> <button onclick=\"myClass()\">Try it</button> <div id=\"gfg\">Geeks for Geeks</div> <script> function myClass() { var elem = document.getElementById(\"gfg\"); // Adding class to div element elem.classList.add(\"geek\"); } </script> </body> </html>Output:Before clicking the button:After clicking the button:"
},
{
"code": null,
"e": 1150,
"s": 1142,
"text": "Syntax:"
},
{
"code": null,
"e": 1185,
"s": 1150,
"text": "element.classList.add(\"className\")"
},
{
"code": null,
"e": 1194,
"s": 1185,
"text": "Example:"
},
{
"code": null,
"e": 1199,
"s": 1194,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <style> .geek { background-color: green; font-size: 50px; } </style></head> <body> <button onclick=\"myClass()\">Try it</button> <div id=\"gfg\">Geeks for Geeks</div> <script> function myClass() { var elem = document.getElementById(\"gfg\"); // Adding class to div element elem.classList.add(\"geek\"); } </script> </body> </html>",
"e": 1675,
"s": 1199,
"text": null
},
{
"code": null,
"e": 1702,
"s": 1675,
"text": "After clicking the button:"
},
{
"code": null,
"e": 2822,
"s": 1702,
"text": "className Property: This property returns the className of the element. If the element has already a class then it will simply add another one to it or else it will append our new class to it.Syntax:HTMLElementObject.classNameExample:htmlhtml<!DOCTYPE html><html> <head> <style> .geekClass { background-color: green; text-align: center; font-size: 50px; } </style></head> <body> <div id=\"gfg\"> Geeks For Geeks </div> <button onclick=\"myClassName()\">Add Class</button> <script> function myClassName() { var element = document.getElementById(\"gfg\"); // Adding the class geekClass to element // with id gfg space is given in className // (\" geekClass\") as if there is already // a class attached to an element than our // new class won't overwrite and will append // one more class to the element element.className += \" geekClass\"; } </script> </body> </html>Output:Before clicking the button:After clicking the button:"
},
{
"code": null,
"e": 2830,
"s": 2822,
"text": "Syntax:"
},
{
"code": null,
"e": 2858,
"s": 2830,
"text": "HTMLElementObject.className"
},
{
"code": null,
"e": 2867,
"s": 2858,
"text": "Example:"
},
{
"code": null,
"e": 2872,
"s": 2867,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <style> .geekClass { background-color: green; text-align: center; font-size: 50px; } </style></head> <body> <div id=\"gfg\"> Geeks For Geeks </div> <button onclick=\"myClassName()\">Add Class</button> <script> function myClassName() { var element = document.getElementById(\"gfg\"); // Adding the class geekClass to element // with id gfg space is given in className // (\" geekClass\") as if there is already // a class attached to an element than our // new class won't overwrite and will append // one more class to the element element.className += \" geekClass\"; } </script> </body> </html>",
"e": 3690,
"s": 2872,
"text": null
},
{
"code": null,
"e": 3772,
"s": 3690,
"text": "Supported Browsers: The browser supported by classList property are listed below:"
},
{
"code": null,
"e": 3782,
"s": 3772,
"text": "Chrome 8+"
},
{
"code": null,
"e": 3794,
"s": 3782,
"text": "Opera 11.5+"
},
{
"code": null,
"e": 3806,
"s": 3794,
"text": "Safari 5.1+"
},
{
"code": null,
"e": 3815,
"s": 3806,
"text": "Edge 10+"
},
{
"code": null,
"e": 3836,
"s": 3815,
"text": "Mozilla Firefox 3.6+"
},
{
"code": null,
"e": 3845,
"s": 3836,
"text": "sooda367"
},
{
"code": null,
"e": 3855,
"s": 3845,
"text": "HTML-Misc"
},
{
"code": null,
"e": 3862,
"s": 3855,
"text": "Picked"
},
{
"code": null,
"e": 3873,
"s": 3862,
"text": "JavaScript"
},
{
"code": null,
"e": 3890,
"s": 3873,
"text": "Web Technologies"
}
] |
Powershell - Logical Operators Examples | The following scripts demonstrates the logical operators.
> $a = 10
> $b = 20
> $a -AND $b
True
> $a -OR $b
True
> -NOT ($a -AND $b) | [
{
"code": null,
"e": 2226,
"s": 2168,
"text": "The following scripts demonstrates the logical operators."
}
] |
Modify given array by incrementing first occurrence of every element by K | 01 Jul, 2022
Given an array arr[] consisting of N integers, read every element of the array one by one and perform the following operations:
If the current element arr[i] had previously occurred in the array, increase its first occurrence by K.
Otherwise, insert arr[i] into the sequence
The task is to print the final sequence of integers obtained by performing the above operations
Examples:
Input: arr[] = {1, 2, 3, 2, 3}, K = 1Output: [1, 4, 3, 2, 3]Explanation:
Arrival : 1Since 1 is the first element in the stream, simply insert it into the solution.Therefore, b[] = [1]
Arrival: 2Since 2 is not existing in the array, simply insert it into the solution.Therefore, b[] = [1, 2]
Arrival: 3Since 3 is not existing in the array, simply insert it into the solution.Therefore, b[] = [1, 2, 3]
Arrival: 2Since 2 already exists, increasing its first occurrence by K(=1)modifies the array b[] to [1, 3, 3, 2]
Arrival: 3Since 3 already exists, increasing its first occurrence by K(=1)modifies the array b[] to [1, 4, 3, 2, 3]
Input: arr[] = {1, 4, 1, 1, 4}, K = 6Output: [7, 10, 7, 1, 4]
Naive Approach: The simplest approach to solve the problem is to traverse the array, and for every array element arr[i], traverse in the range [0, i – 1] to check if arr[i] is already present in the array or not. If found to be true, increase the first occurrence of arr[i] by K.
Time Complexity: O(N2)Auxiliary Space: O(1)
Efficient Approach: The above approach can be optimized using Hashing. Follow the steps below to solve the problem:
Traverse the array and store the occurrence of every array element in a Map paired with the index of its occurrence in increasing order.
If arr[i] is found to be already present in the Map, remove the first occurrence of arr[i] from the Map. Insert that index paired with arr[i] + K as the key back into the Map.
Repeat the above steps for all array elements. Once, the entire array is traversed, obtain the sequence of integers from the Map and print the final sequence.
Below is the implementation of the above approach:
C++
Java
Javascript
// C++ Program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Print the required final sequencevoid printSequence(vector<int>& A, int n, int k){ // Stores the array element-index pairs unordered_map<int, set<int> > mp; // Stores the required sequence vector<int> sol; // Insert all array elements for (int x : A) sol.push_back(x); for (int i = 0; i < n; i++) { // If current element has // not occurred previously if (mp.find(sol[i]) == mp.end() || mp[sol[i]].size() == 0) { mp[sol[i]].insert(i); } // Otherwise else { // Iterator to the first index // containing sol[i] auto idxx = mp[sol[i]].begin(); int idx = *idxx; // Remove that occurrence mp[sol[i]].erase(idxx); // Increment by K sol[idx] += k; // Insert the incremented // element at that index mp[sol[idx]].insert(idx); mp[sol[i]].insert(i); } } // Print the final sequence for (int x : sol) { cout << x << " "; }} // Driver Codeint main(){ int N = 5; int K = 6; vector<int> A = { 1, 4, 1, 1, 4 }; printSequence(A, N, K);}
// Java Program to implement the above approachimport java.util.*; public class Main { // Driver Code public static void main(String[] args) { int N = 5; int K = 6; int[] A = { 1, 4, 1, 1, 4 }; printSequence(A, N, K); } // Print the required final sequence public static void printSequence(int[] A, int n, int k) { // Stores the array element-index pairs HashMap<Integer, ArrayList<Integer> > mp = new HashMap<>(); // Stores the required sequence ArrayList<Integer> sol = new ArrayList<>(); // Insert all array elements for (int x : A) { sol.add(x); } for (int i = 0; i < n; i++) { // If current element has // not occurred previously if (!mp.containsKey(sol.get(i)) || mp.get(sol.get(i)).size() == 0) { mp.put(sol.get(i), new ArrayList<>(Arrays.asList(i))); } // Otherwise else { // first index containing sol[i] int idx = mp.get(sol.get(i)).get(0); // Remove that occurrence mp.get(sol.get(i)).remove((Integer)idx); // Increment by K sol.set(idx, sol.get(idx) + k); // Insert the incremented // element at that index mp.putIfAbsent( sol.get(idx), new ArrayList<>(Arrays.asList())); mp.get(sol.get(idx)).add((Integer)idx); mp.putIfAbsent( sol.get(i), new ArrayList<>(Arrays.asList())); mp.get(sol.get(i)).add((Integer)i); } } // Print the final sequence for (int x : sol) { System.out.print(x + " "); } }} // This code is contributed by Tapesh (tapeshdua420)
<script> // Javascript program to implement// the above approach // Print the required final sequencefunction printSequence(A, n, k){ // Stores the array element-index pairs var mp = new Map(); // Stores the required sequence var sol = []; // Insert all array elements A.forEach(x => { sol.push(x); }); for(var i = 0; i < n; i++) { // If current element has // not occurred previously if (!mp.has(sol[i]) || mp.get(sol[i]).size == 0) { var tmp = new Set(); tmp.add(i) mp.set(sol[i],tmp) } // Otherwise else { // Iterator to the first index // containing sol[i] var idxx = [...mp.get(sol[i])].sort( (a, b) => a - b)[0]; var idx = idxx; // Remove that occurrence var x = mp.get(sol[i]); x.delete(idxx); mp.set(sol[i], x); // Increment by K sol[idx] += k; // Insert the incremented // element at that index if (!mp.has(sol[idx])) mp.set(sol[idx], new Set()) x = mp.get(sol[idx]); x.add(idx); mp.set(sol[idx], x); x = mp.get(sol[i]); x.add(i); mp.set(sol[i], x); } } // Print the final sequence sol.forEach(x => { document.write(x + " "); });} // Driver Codevar N = 5;var K = 6;var A = [ 1, 4, 1, 1, 4 ]; printSequence(A, N, K); // This code is contributed by importantly </script>
7 10 7 1 4
Time Complexity: O(NlogN)Auxiliary Space: O(N)
importantly
tapeshdua420
cpp-map
cpp-set
frequency-counting
Arrays
Hash
Searching
Arrays
Searching
Hash
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Stack Data Structure (Introduction and Program)
Multidimensional Arrays in Java
Introduction to Arrays
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Hashing | Set 1 (Introduction)
Count pairs with given sum
Internal Working of HashMap in Java
Hash Functions and list/types of Hash functions | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n01 Jul, 2022"
},
{
"code": null,
"e": 180,
"s": 52,
"text": "Given an array arr[] consisting of N integers, read every element of the array one by one and perform the following operations:"
},
{
"code": null,
"e": 284,
"s": 180,
"text": "If the current element arr[i] had previously occurred in the array, increase its first occurrence by K."
},
{
"code": null,
"e": 327,
"s": 284,
"text": "Otherwise, insert arr[i] into the sequence"
},
{
"code": null,
"e": 423,
"s": 327,
"text": "The task is to print the final sequence of integers obtained by performing the above operations"
},
{
"code": null,
"e": 433,
"s": 423,
"text": "Examples:"
},
{
"code": null,
"e": 506,
"s": 433,
"text": "Input: arr[] = {1, 2, 3, 2, 3}, K = 1Output: [1, 4, 3, 2, 3]Explanation:"
},
{
"code": null,
"e": 617,
"s": 506,
"text": "Arrival : 1Since 1 is the first element in the stream, simply insert it into the solution.Therefore, b[] = [1]"
},
{
"code": null,
"e": 724,
"s": 617,
"text": "Arrival: 2Since 2 is not existing in the array, simply insert it into the solution.Therefore, b[] = [1, 2]"
},
{
"code": null,
"e": 834,
"s": 724,
"text": "Arrival: 3Since 3 is not existing in the array, simply insert it into the solution.Therefore, b[] = [1, 2, 3]"
},
{
"code": null,
"e": 947,
"s": 834,
"text": "Arrival: 2Since 2 already exists, increasing its first occurrence by K(=1)modifies the array b[] to [1, 3, 3, 2]"
},
{
"code": null,
"e": 1063,
"s": 947,
"text": "Arrival: 3Since 3 already exists, increasing its first occurrence by K(=1)modifies the array b[] to [1, 4, 3, 2, 3]"
},
{
"code": null,
"e": 1125,
"s": 1063,
"text": "Input: arr[] = {1, 4, 1, 1, 4}, K = 6Output: [7, 10, 7, 1, 4]"
},
{
"code": null,
"e": 1405,
"s": 1125,
"text": "Naive Approach: The simplest approach to solve the problem is to traverse the array, and for every array element arr[i], traverse in the range [0, i – 1] to check if arr[i] is already present in the array or not. If found to be true, increase the first occurrence of arr[i] by K."
},
{
"code": null,
"e": 1449,
"s": 1405,
"text": "Time Complexity: O(N2)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 1565,
"s": 1449,
"text": "Efficient Approach: The above approach can be optimized using Hashing. Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 1702,
"s": 1565,
"text": "Traverse the array and store the occurrence of every array element in a Map paired with the index of its occurrence in increasing order."
},
{
"code": null,
"e": 1878,
"s": 1702,
"text": "If arr[i] is found to be already present in the Map, remove the first occurrence of arr[i] from the Map. Insert that index paired with arr[i] + K as the key back into the Map."
},
{
"code": null,
"e": 2037,
"s": 1878,
"text": "Repeat the above steps for all array elements. Once, the entire array is traversed, obtain the sequence of integers from the Map and print the final sequence."
},
{
"code": null,
"e": 2088,
"s": 2037,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 2092,
"s": 2088,
"text": "C++"
},
{
"code": null,
"e": 2097,
"s": 2092,
"text": "Java"
},
{
"code": null,
"e": 2108,
"s": 2097,
"text": "Javascript"
},
{
"code": "// C++ Program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Print the required final sequencevoid printSequence(vector<int>& A, int n, int k){ // Stores the array element-index pairs unordered_map<int, set<int> > mp; // Stores the required sequence vector<int> sol; // Insert all array elements for (int x : A) sol.push_back(x); for (int i = 0; i < n; i++) { // If current element has // not occurred previously if (mp.find(sol[i]) == mp.end() || mp[sol[i]].size() == 0) { mp[sol[i]].insert(i); } // Otherwise else { // Iterator to the first index // containing sol[i] auto idxx = mp[sol[i]].begin(); int idx = *idxx; // Remove that occurrence mp[sol[i]].erase(idxx); // Increment by K sol[idx] += k; // Insert the incremented // element at that index mp[sol[idx]].insert(idx); mp[sol[i]].insert(i); } } // Print the final sequence for (int x : sol) { cout << x << \" \"; }} // Driver Codeint main(){ int N = 5; int K = 6; vector<int> A = { 1, 4, 1, 1, 4 }; printSequence(A, N, K);}",
"e": 3416,
"s": 2108,
"text": null
},
{
"code": "// Java Program to implement the above approachimport java.util.*; public class Main { // Driver Code public static void main(String[] args) { int N = 5; int K = 6; int[] A = { 1, 4, 1, 1, 4 }; printSequence(A, N, K); } // Print the required final sequence public static void printSequence(int[] A, int n, int k) { // Stores the array element-index pairs HashMap<Integer, ArrayList<Integer> > mp = new HashMap<>(); // Stores the required sequence ArrayList<Integer> sol = new ArrayList<>(); // Insert all array elements for (int x : A) { sol.add(x); } for (int i = 0; i < n; i++) { // If current element has // not occurred previously if (!mp.containsKey(sol.get(i)) || mp.get(sol.get(i)).size() == 0) { mp.put(sol.get(i), new ArrayList<>(Arrays.asList(i))); } // Otherwise else { // first index containing sol[i] int idx = mp.get(sol.get(i)).get(0); // Remove that occurrence mp.get(sol.get(i)).remove((Integer)idx); // Increment by K sol.set(idx, sol.get(idx) + k); // Insert the incremented // element at that index mp.putIfAbsent( sol.get(idx), new ArrayList<>(Arrays.asList())); mp.get(sol.get(idx)).add((Integer)idx); mp.putIfAbsent( sol.get(i), new ArrayList<>(Arrays.asList())); mp.get(sol.get(i)).add((Integer)i); } } // Print the final sequence for (int x : sol) { System.out.print(x + \" \"); } }} // This code is contributed by Tapesh (tapeshdua420)",
"e": 5337,
"s": 3416,
"text": null
},
{
"code": "<script> // Javascript program to implement// the above approach // Print the required final sequencefunction printSequence(A, n, k){ // Stores the array element-index pairs var mp = new Map(); // Stores the required sequence var sol = []; // Insert all array elements A.forEach(x => { sol.push(x); }); for(var i = 0; i < n; i++) { // If current element has // not occurred previously if (!mp.has(sol[i]) || mp.get(sol[i]).size == 0) { var tmp = new Set(); tmp.add(i) mp.set(sol[i],tmp) } // Otherwise else { // Iterator to the first index // containing sol[i] var idxx = [...mp.get(sol[i])].sort( (a, b) => a - b)[0]; var idx = idxx; // Remove that occurrence var x = mp.get(sol[i]); x.delete(idxx); mp.set(sol[i], x); // Increment by K sol[idx] += k; // Insert the incremented // element at that index if (!mp.has(sol[idx])) mp.set(sol[idx], new Set()) x = mp.get(sol[idx]); x.add(idx); mp.set(sol[idx], x); x = mp.get(sol[i]); x.add(i); mp.set(sol[i], x); } } // Print the final sequence sol.forEach(x => { document.write(x + \" \"); });} // Driver Codevar N = 5;var K = 6;var A = [ 1, 4, 1, 1, 4 ]; printSequence(A, N, K); // This code is contributed by importantly </script>",
"e": 6969,
"s": 5337,
"text": null
},
{
"code": null,
"e": 6980,
"s": 6969,
"text": "7 10 7 1 4"
},
{
"code": null,
"e": 7029,
"s": 6982,
"text": "Time Complexity: O(NlogN)Auxiliary Space: O(N)"
},
{
"code": null,
"e": 7043,
"s": 7031,
"text": "importantly"
},
{
"code": null,
"e": 7056,
"s": 7043,
"text": "tapeshdua420"
},
{
"code": null,
"e": 7064,
"s": 7056,
"text": "cpp-map"
},
{
"code": null,
"e": 7072,
"s": 7064,
"text": "cpp-set"
},
{
"code": null,
"e": 7091,
"s": 7072,
"text": "frequency-counting"
},
{
"code": null,
"e": 7098,
"s": 7091,
"text": "Arrays"
},
{
"code": null,
"e": 7103,
"s": 7098,
"text": "Hash"
},
{
"code": null,
"e": 7113,
"s": 7103,
"text": "Searching"
},
{
"code": null,
"e": 7120,
"s": 7113,
"text": "Arrays"
},
{
"code": null,
"e": 7130,
"s": 7120,
"text": "Searching"
},
{
"code": null,
"e": 7135,
"s": 7130,
"text": "Hash"
},
{
"code": null,
"e": 7233,
"s": 7135,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7301,
"s": 7233,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 7345,
"s": 7301,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 7393,
"s": 7345,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 7425,
"s": 7393,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 7448,
"s": 7425,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 7533,
"s": 7448,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 7564,
"s": 7533,
"text": "Hashing | Set 1 (Introduction)"
},
{
"code": null,
"e": 7591,
"s": 7564,
"text": "Count pairs with given sum"
},
{
"code": null,
"e": 7627,
"s": 7591,
"text": "Internal Working of HashMap in Java"
}
] |
Python program to Increment Suffix Number in String | 02 Dec, 2020
Given a String, the task is to write a Python program to increment the number which is at end of the string.
Input : test_str = ‘geeks006’ Output : geeks7 Explanation : Suffix 006 incremented to 7.
Input : test_str = ‘geeks007’ Output : geeks8 Explanation : Suffix 007 incremented to 8.
Method #1 : Using findall() + join() + replace()
In this, strategy we perform the task of finding number using findall(), then perform the task of separating numeric string and prefix string, then an increment of a numeric string is performed. At last, the string is joined to get a prefix followed by an incremented number.
Python3
# Python3 code to demonstrate working of # Increment Suffix Number# Using findall() + join() + replace()import re # initializing stringtest_str = 'geeks006' # printing original stringprint("The original string is : " + str(test_str)) # getting suffix number reg = re.compile(r'[ 0 - 9]')mtch = reg.findall(test_str) # getting number num = ''.join(mtch[-3 : ])pre_str = test_str.replace(num, '') # Increment number add_val = int(num) + 1 # joining prefix str and added value res = pre_str + str(add_val) # printing result print("Incremented numeric String : " + str(res))
Output:
The original string is : geeks006
Incremented numeric String : geeks61
Method #2 : Using sub() + group() + zfill()
In this, we perform the task of grouping numbers using group() and incrementing, zfill() is used for task of filling the required leading values in numerical. The sub() is used to find the numerical part of strings.
Python3
# Python3 code to demonstrate working of # Increment Suffix Number# Using sub() + group() + zfill()import re # initializing stringtest_str = 'geeks006' # printing original stringprint("The original string is : " + str(test_str)) # fstring used to form string # zfill fills values post incrementres = re.sub(r'[0-9]+$', lambda x: f"{str(int(x.group())+1).zfill(len(x.group()))}", test_str) # printing result print("Incremented numeric String : " + str(res))
Output:
The original string is : geeks006
Incremented numeric String : geeks007
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n02 Dec, 2020"
},
{
"code": null,
"e": 137,
"s": 28,
"text": "Given a String, the task is to write a Python program to increment the number which is at end of the string."
},
{
"code": null,
"e": 226,
"s": 137,
"text": "Input : test_str = ‘geeks006’ Output : geeks7 Explanation : Suffix 006 incremented to 7."
},
{
"code": null,
"e": 317,
"s": 226,
"text": "Input : test_str = ‘geeks007’ Output : geeks8 Explanation : Suffix 007 incremented to 8. "
},
{
"code": null,
"e": 366,
"s": 317,
"text": "Method #1 : Using findall() + join() + replace()"
},
{
"code": null,
"e": 642,
"s": 366,
"text": "In this, strategy we perform the task of finding number using findall(), then perform the task of separating numeric string and prefix string, then an increment of a numeric string is performed. At last, the string is joined to get a prefix followed by an incremented number."
},
{
"code": null,
"e": 650,
"s": 642,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of # Increment Suffix Number# Using findall() + join() + replace()import re # initializing stringtest_str = 'geeks006' # printing original stringprint(\"The original string is : \" + str(test_str)) # getting suffix number reg = re.compile(r'[ 0 - 9]')mtch = reg.findall(test_str) # getting number num = ''.join(mtch[-3 : ])pre_str = test_str.replace(num, '') # Increment number add_val = int(num) + 1 # joining prefix str and added value res = pre_str + str(add_val) # printing result print(\"Incremented numeric String : \" + str(res)) ",
"e": 1233,
"s": 650,
"text": null
},
{
"code": null,
"e": 1241,
"s": 1233,
"text": "Output:"
},
{
"code": null,
"e": 1312,
"s": 1241,
"text": "The original string is : geeks006\nIncremented numeric String : geeks61"
},
{
"code": null,
"e": 1356,
"s": 1312,
"text": "Method #2 : Using sub() + group() + zfill()"
},
{
"code": null,
"e": 1572,
"s": 1356,
"text": "In this, we perform the task of grouping numbers using group() and incrementing, zfill() is used for task of filling the required leading values in numerical. The sub() is used to find the numerical part of strings."
},
{
"code": null,
"e": 1580,
"s": 1572,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of # Increment Suffix Number# Using sub() + group() + zfill()import re # initializing stringtest_str = 'geeks006' # printing original stringprint(\"The original string is : \" + str(test_str)) # fstring used to form string # zfill fills values post incrementres = re.sub(r'[0-9]+$', lambda x: f\"{str(int(x.group())+1).zfill(len(x.group()))}\", test_str) # printing result print(\"Incremented numeric String : \" + str(res)) ",
"e": 2071,
"s": 1580,
"text": null
},
{
"code": null,
"e": 2079,
"s": 2071,
"text": "Output:"
},
{
"code": null,
"e": 2151,
"s": 2079,
"text": "The original string is : geeks006\nIncremented numeric String : geeks007"
},
{
"code": null,
"e": 2174,
"s": 2151,
"text": "Python string-programs"
},
{
"code": null,
"e": 2181,
"s": 2174,
"text": "Python"
},
{
"code": null,
"e": 2197,
"s": 2181,
"text": "Python Programs"
}
] |
Levene’s Test in R Programming | 25 Aug, 2020
In statistics, Levene’s test is an inferential statistic used to evaluate the equality of variances for a variable determined for two or more groups. Some standard statistical procedures find that variances of the populations from which various samples are formed are equal. Levene’s test assesses this assumption. It examines the null hypothesis that the population variances are equal called homogeneity of variance or homoscedasticity. It compares the variances of k samples, where k can be more than two samples. It’s an alternative to Bartlett’s test that is less sensitive to departures from normality. There are several solutions to test for the equality (homogeneity) of variance across groups, including:
F-test
Bartlett’s test
Levene’s test
Fligner-Killeen test
It is very much easy to perform these tests in R programming. In this article let’s perform Levene’s test in R.
A hypothesis is a statement about the given problem. Hypothesis testing is a statistical method that is used in making a statistical decision using experimental data. Hypothesis testing is basically an assumption that we make about a population parameter. It evaluates two mutually exclusive statements about a population to determine which statement is best supported by the sample data. To know more about the statistical hypothesis please refer to Understanding Hypothesis Testing. For Levene’s test the statistical hypotheses are:
Null Hypothesis: All populations variances are equal
Alternative Hypothesis: At least two of them differ
R provides a function leveneTest() which is available in car package that can be used to compute Levene’s test. The syntax for this function is given below:
Syntax: leveneTest(formula, dataset)
Parameters:
formula: a formula of the form values ~ groups
dataset: a matrix or data frame
Levene’s test with one independent variable:
Consider the R’s inbuilt PlantGrowth dataset that gives the dried weight of three groups of ten batches of plants, wherever every group of ten batches got a different treatment. The weight variable gives the weight of the batch and the group variable gives the treatment received either ctrl, trt1 or trt2. To view the data set please type below command:
R
print(PlantGrowth)
Output:
weight group
1 4.17 ctrl
2 5.58 ctrl
3 5.18 ctrl
4 6.11 ctrl
5 4.50 ctrl
6 4.61 ctrl
7 5.17 ctrl
8 4.53 ctrl
9 5.33 ctrl
10 5.14 ctrl
11 4.81 trt1
12 4.17 trt1
13 4.41 trt1
14 3.59 trt1
15 5.87 trt1
16 3.83 trt1
17 6.03 trt1
18 4.89 trt1
19 4.32 trt1
20 4.69 trt1
21 6.31 trt2
22 5.12 trt2
23 5.54 trt2
24 5.50 trt2
25 5.37 trt2
26 5.29 trt2
27 4.92 trt2
28 6.15 trt2
29 5.80 trt2
30 5.26 trt2
As mentioned above, Levene’s test is an alternative to Bartlett’s test when the data is not normally distributed. Here let’s consider only one independent variable. To perform the test, use the below command:
R
# R program to illustrate# Levene’s test # Import required packagelibrary(car) # Using leveneTest()result = leveneTest(weight ~ group, PlantGrowth) # print the resultprint(result)
Output:
Levene's Test for Homogeneity of Variance (center = median)
Df F value Pr(>F)
group 2 1.1192 0.3412
27
Levene’s test with multiple independent variables:
If one wants to do the test with multiple independent variables then the interaction() function must be used to collapse multiple factors into a single variable containing all combinations of the factors. Here let’s take the R’s inbuilt ToothGrowth data set.
R
# R program to illustrate# Levene’s test # Import required packagelibrary(car) # Using leveneTest()result = leveneTest(len ~ interaction(supp, dose), data = ToothGrowth) # print the resultprint(result)
Output:
Levene's Test for Homogeneity of Variance (center = median)
Df F value Pr(>F)
group 5 1.7086 0.1484
54
data-science
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
R - if statement
Logistic Regression in R Programming
How to filter R DataFrame by values in a column?
Replace Specific Characters in String in R
How to import an Excel File into R ?
Joining of Dataframes in R Programming | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n25 Aug, 2020"
},
{
"code": null,
"e": 742,
"s": 28,
"text": "In statistics, Levene’s test is an inferential statistic used to evaluate the equality of variances for a variable determined for two or more groups. Some standard statistical procedures find that variances of the populations from which various samples are formed are equal. Levene’s test assesses this assumption. It examines the null hypothesis that the population variances are equal called homogeneity of variance or homoscedasticity. It compares the variances of k samples, where k can be more than two samples. It’s an alternative to Bartlett’s test that is less sensitive to departures from normality. There are several solutions to test for the equality (homogeneity) of variance across groups, including:"
},
{
"code": null,
"e": 749,
"s": 742,
"text": "F-test"
},
{
"code": null,
"e": 765,
"s": 749,
"text": "Bartlett’s test"
},
{
"code": null,
"e": 779,
"s": 765,
"text": "Levene’s test"
},
{
"code": null,
"e": 800,
"s": 779,
"text": "Fligner-Killeen test"
},
{
"code": null,
"e": 912,
"s": 800,
"text": "It is very much easy to perform these tests in R programming. In this article let’s perform Levene’s test in R."
},
{
"code": null,
"e": 1447,
"s": 912,
"text": "A hypothesis is a statement about the given problem. Hypothesis testing is a statistical method that is used in making a statistical decision using experimental data. Hypothesis testing is basically an assumption that we make about a population parameter. It evaluates two mutually exclusive statements about a population to determine which statement is best supported by the sample data. To know more about the statistical hypothesis please refer to Understanding Hypothesis Testing. For Levene’s test the statistical hypotheses are:"
},
{
"code": null,
"e": 1500,
"s": 1447,
"text": "Null Hypothesis: All populations variances are equal"
},
{
"code": null,
"e": 1552,
"s": 1500,
"text": "Alternative Hypothesis: At least two of them differ"
},
{
"code": null,
"e": 1709,
"s": 1552,
"text": "R provides a function leveneTest() which is available in car package that can be used to compute Levene’s test. The syntax for this function is given below:"
},
{
"code": null,
"e": 1746,
"s": 1709,
"text": "Syntax: leveneTest(formula, dataset)"
},
{
"code": null,
"e": 1760,
"s": 1748,
"text": "Parameters:"
},
{
"code": null,
"e": 1807,
"s": 1760,
"text": "formula: a formula of the form values ~ groups"
},
{
"code": null,
"e": 1839,
"s": 1807,
"text": "dataset: a matrix or data frame"
},
{
"code": null,
"e": 1884,
"s": 1839,
"text": "Levene’s test with one independent variable:"
},
{
"code": null,
"e": 2239,
"s": 1884,
"text": "Consider the R’s inbuilt PlantGrowth dataset that gives the dried weight of three groups of ten batches of plants, wherever every group of ten batches got a different treatment. The weight variable gives the weight of the batch and the group variable gives the treatment received either ctrl, trt1 or trt2. To view the data set please type below command:"
},
{
"code": null,
"e": 2241,
"s": 2239,
"text": "R"
},
{
"code": "print(PlantGrowth)",
"e": 2260,
"s": 2241,
"text": null
},
{
"code": null,
"e": 2268,
"s": 2260,
"text": "Output:"
},
{
"code": null,
"e": 2768,
"s": 2268,
"text": " weight group\n1 4.17 ctrl\n2 5.58 ctrl\n3 5.18 ctrl\n4 6.11 ctrl\n5 4.50 ctrl\n6 4.61 ctrl\n7 5.17 ctrl\n8 4.53 ctrl\n9 5.33 ctrl\n10 5.14 ctrl\n11 4.81 trt1\n12 4.17 trt1\n13 4.41 trt1\n14 3.59 trt1\n15 5.87 trt1\n16 3.83 trt1\n17 6.03 trt1\n18 4.89 trt1\n19 4.32 trt1\n20 4.69 trt1\n21 6.31 trt2\n22 5.12 trt2\n23 5.54 trt2\n24 5.50 trt2\n25 5.37 trt2\n26 5.29 trt2\n27 4.92 trt2\n28 6.15 trt2\n29 5.80 trt2\n30 5.26 trt2\n\n\n"
},
{
"code": null,
"e": 2977,
"s": 2768,
"text": "As mentioned above, Levene’s test is an alternative to Bartlett’s test when the data is not normally distributed. Here let’s consider only one independent variable. To perform the test, use the below command:"
},
{
"code": null,
"e": 2979,
"s": 2977,
"text": "R"
},
{
"code": "# R program to illustrate# Levene’s test # Import required packagelibrary(car) # Using leveneTest()result = leveneTest(weight ~ group, PlantGrowth) # print the resultprint(result)",
"e": 3162,
"s": 2979,
"text": null
},
{
"code": null,
"e": 3170,
"s": 3162,
"text": "Output:"
},
{
"code": null,
"e": 3298,
"s": 3170,
"text": "Levene's Test for Homogeneity of Variance (center = median)\n Df F value Pr(>F)\ngroup 2 1.1192 0.3412\n 27 \n"
},
{
"code": null,
"e": 3349,
"s": 3298,
"text": "Levene’s test with multiple independent variables:"
},
{
"code": null,
"e": 3608,
"s": 3349,
"text": "If one wants to do the test with multiple independent variables then the interaction() function must be used to collapse multiple factors into a single variable containing all combinations of the factors. Here let’s take the R’s inbuilt ToothGrowth data set."
},
{
"code": null,
"e": 3610,
"s": 3608,
"text": "R"
},
{
"code": "# R program to illustrate# Levene’s test # Import required packagelibrary(car) # Using leveneTest()result = leveneTest(len ~ interaction(supp, dose), data = ToothGrowth) # print the resultprint(result)",
"e": 3835,
"s": 3610,
"text": null
},
{
"code": null,
"e": 3843,
"s": 3835,
"text": "Output:"
},
{
"code": null,
"e": 3976,
"s": 3843,
"text": "Levene's Test for Homogeneity of Variance (center = median)\n Df F value Pr(>F)\ngroup 5 1.7086 0.1484\n 54 \n"
},
{
"code": null,
"e": 3989,
"s": 3976,
"text": "data-science"
},
{
"code": null,
"e": 4000,
"s": 3989,
"text": "R Language"
},
{
"code": null,
"e": 4098,
"s": 4000,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4150,
"s": 4098,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 4208,
"s": 4150,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 4243,
"s": 4208,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 4281,
"s": 4243,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 4298,
"s": 4281,
"text": "R - if statement"
},
{
"code": null,
"e": 4335,
"s": 4298,
"text": "Logistic Regression in R Programming"
},
{
"code": null,
"e": 4384,
"s": 4335,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 4427,
"s": 4384,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 4464,
"s": 4427,
"text": "How to import an Excel File into R ?"
}
] |
Zoho Off Campus Drive | Set 26 (Software Developer) | 04 Dec, 2018
Round 1: Written test
The first round comprised of 40 one mark questions (without options) from C output questions and flow chart questions (Test Duration: 2 hour) :-
C output questions part covered questions from iterations, pointers, array and data structures.
Suggestion: I would suggest to do quizzes from geeksforgeeks to get in touch with all concepts of C and other subjects.
Tips :- Solve the questions with calm mind. Don’t stress yourself during test because you have to do 40 questions in 120 minutes. Don’t spend too much time on any question if you are not able to do it in the first attempt.
Round 2: Coding round
You will be provided laptop and turbo C compiler. Java and C++ not allowed for second round.
Some of the questions are.
1. Print second frequently occurring number in given series
Example :
Input: 1 1 2 3 1 2 4
Output: 2
Explanation: 1 occurs 3 times, 2 occurs 2 times, 3 occurs 1 time and 4 occurs 1 time. Hence second frequently occurring number in given series is 2
2. Print only numbers which is present in Fibonacci series (0 1 1 2 3 5 8 ........)
Example:
Input: 2 10 4 8
Output: 2 8
Input: 1 10 6 8 13 21
Output: 1 8 13 21
3. Print pattern like this
Example:
Input: 1
Output: 0
Input: 2
Output:
0 0
0 1
1 0
1 1
Input: 3
Output:
0 0 0
0 0 1
0 1 0
0 1 1
1 0 0
1 0 1
1 1 0
1 1 1
4. NxN matrix will be provided. 0->block, 1->Not a blockAlways starting point is (0,0), Ending point is (N-1,N-1).You have to go from starting point to ending point. One valid solution is enough.Example:
Input:
N=4
1 1 0 0
1 0 0 1
1 1 1 1
0 0 0 1
Output:
_ 1 0 0
_ 0 0 1
_ _ _ _
0 0 0 _
5. Insert 0 after consecutive (K times) of 1 is found.Example:
Input:
Number of bits: 12
Bits: 1 0 1 1 0 1 1 0 1 1 1 1
Consecutive K: 2
Output:
1 0 1 1 0 0 1 1 0 0 1 1 0 1 1 0
Round 3: Advance programming round
You have to code for Railway reservation system.
(Test Duration : 3 hours)
Round 4 and 5: Interview (technical and HR)
In technical interview some puzzles and programming questions were asked.
In HR interview some basic HR questions were asked.
Finally 3 got selected for extend interview process.
In extend interview process they will assign a mentor for you. Your mentor will give some task from Java, Javascript etc..After one month they confirmed my offer.
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.
Off-Campus
Zoho
Interview Experiences
Zoho
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n04 Dec, 2018"
},
{
"code": null,
"e": 74,
"s": 52,
"text": "Round 1: Written test"
},
{
"code": null,
"e": 219,
"s": 74,
"text": "The first round comprised of 40 one mark questions (without options) from C output questions and flow chart questions (Test Duration: 2 hour) :-"
},
{
"code": null,
"e": 315,
"s": 219,
"text": "C output questions part covered questions from iterations, pointers, array and data structures."
},
{
"code": null,
"e": 435,
"s": 315,
"text": "Suggestion: I would suggest to do quizzes from geeksforgeeks to get in touch with all concepts of C and other subjects."
},
{
"code": null,
"e": 658,
"s": 435,
"text": "Tips :- Solve the questions with calm mind. Don’t stress yourself during test because you have to do 40 questions in 120 minutes. Don’t spend too much time on any question if you are not able to do it in the first attempt."
},
{
"code": null,
"e": 680,
"s": 658,
"text": "Round 2: Coding round"
},
{
"code": null,
"e": 773,
"s": 680,
"text": "You will be provided laptop and turbo C compiler. Java and C++ not allowed for second round."
},
{
"code": null,
"e": 800,
"s": 773,
"text": "Some of the questions are."
},
{
"code": null,
"e": 860,
"s": 800,
"text": "1. Print second frequently occurring number in given series"
},
{
"code": null,
"e": 870,
"s": 860,
"text": "Example :"
},
{
"code": null,
"e": 902,
"s": 870,
"text": "Input: 1 1 2 3 1 2 4\nOutput: 2\n"
},
{
"code": null,
"e": 1050,
"s": 902,
"text": "Explanation: 1 occurs 3 times, 2 occurs 2 times, 3 occurs 1 time and 4 occurs 1 time. Hence second frequently occurring number in given series is 2"
},
{
"code": null,
"e": 1134,
"s": 1050,
"text": "2. Print only numbers which is present in Fibonacci series (0 1 1 2 3 5 8 ........)"
},
{
"code": null,
"e": 1143,
"s": 1134,
"text": "Example:"
},
{
"code": null,
"e": 1213,
"s": 1143,
"text": "Input: 2 10 4 8\nOutput: 2 8 \nInput: 1 10 6 8 13 21\nOutput: 1 8 13 21\n"
},
{
"code": null,
"e": 1240,
"s": 1213,
"text": "3. Print pattern like this"
},
{
"code": null,
"e": 1370,
"s": 1240,
"text": "Example:\nInput: 1\nOutput: 0\n\nInput: 2\nOutput: \n0 0\n0 1\n1 0\n1 1\n\nInput: 3\nOutput:\n0 0 0\n0 0 1\n0 1 0\n0 1 1\n1 0 0\n1 0 1\n1 1 0\n1 1 1\n"
},
{
"code": null,
"e": 1574,
"s": 1370,
"text": "4. NxN matrix will be provided. 0->block, 1->Not a blockAlways starting point is (0,0), Ending point is (N-1,N-1).You have to go from starting point to ending point. One valid solution is enough.Example:"
},
{
"code": null,
"e": 1694,
"s": 1574,
"text": " \n Input:\n N=4 \n 1 1 0 0\n 1 0 0 1\n 1 1 1 1\n 0 0 0 1\n Output:\n _ 1 0 0\n _ 0 0 1\n _ _ _ _\n 0 0 0 _\n"
},
{
"code": null,
"e": 1757,
"s": 1694,
"text": "5. Insert 0 after consecutive (K times) of 1 is found.Example:"
},
{
"code": null,
"e": 1871,
"s": 1757,
"text": "Input:\nNumber of bits: 12\nBits: 1 0 1 1 0 1 1 0 1 1 1 1\nConsecutive K: 2\n\nOutput:\n1 0 1 1 0 0 1 1 0 0 1 1 0 1 1 0"
},
{
"code": null,
"e": 1906,
"s": 1871,
"text": "Round 3: Advance programming round"
},
{
"code": null,
"e": 1955,
"s": 1906,
"text": "You have to code for Railway reservation system."
},
{
"code": null,
"e": 1981,
"s": 1955,
"text": "(Test Duration : 3 hours)"
},
{
"code": null,
"e": 2025,
"s": 1981,
"text": "Round 4 and 5: Interview (technical and HR)"
},
{
"code": null,
"e": 2099,
"s": 2025,
"text": "In technical interview some puzzles and programming questions were asked."
},
{
"code": null,
"e": 2151,
"s": 2099,
"text": "In HR interview some basic HR questions were asked."
},
{
"code": null,
"e": 2204,
"s": 2151,
"text": "Finally 3 got selected for extend interview process."
},
{
"code": null,
"e": 2367,
"s": 2204,
"text": "In extend interview process they will assign a mentor for you. Your mentor will give some task from Java, Javascript etc..After one month they confirmed my offer."
},
{
"code": null,
"e": 2622,
"s": 2367,
"text": "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": 2747,
"s": 2622,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 2758,
"s": 2747,
"text": "Off-Campus"
},
{
"code": null,
"e": 2763,
"s": 2758,
"text": "Zoho"
},
{
"code": null,
"e": 2785,
"s": 2763,
"text": "Interview Experiences"
},
{
"code": null,
"e": 2790,
"s": 2785,
"text": "Zoho"
}
] |
Length of diagonal of a parallelogram using adjacent sides and angle between them | 08 Apr, 2021
Given two integers a and b where a and b represents the length of adjacent sides of a parallelogram and an angle 0 between them, the task is to find the length of diagonal of the parallelogram.
Examples:
Input: a = 6, b = 10, 0=30Output: 6.14
Input: a = 3, b = 5, 0=45Output: 3.58
Approach: Consider a parallelogram ABCD with sides a and b, now apply cosine rule at angle A in the triangle ABD to find the length of diagonal p, similarly find diagonal q from triangle ABC.
Therefore the diagonals is given by:
C++
Java
Python3
C#
Javascript
// C++ program to find length// Of diagonal of a parallelogram// Using sides and angle between them.#include <bits/stdc++.h>using namespace std;#define PI 3.147 // Function to return the length// Of diagonal of a parallelogram// using sides and angle between them.double Length_Diagonal(int a, int b, double theta){ double diagonal = sqrt((pow(a, 2) + pow(b, 2)) - 2 * a * b * cos(theta * (PI / 180))); return diagonal;} // Driver Codeint main(){ // Given sides int a = 3; int b = 5; // Given angle double theta = 45; // Function call double ans = Length_Diagonal(a, b, theta); // Print the final answer printf("%.2f", ans);} // This code is contributed by Amit Katiyar
// Java program to find length// Of diagonal of a parallelogram// Using sides and angle between them.class GFG{ // Function to return the length// Of diagonal of a parallelogram// using sides and angle between them.static double Length_Diagonal(int a, int b, double theta){ double diagonal = Math.sqrt((Math.pow(a, 2) + Math.pow(b, 2)) - 2 * a * b * Math.cos(theta * (Math.PI / 180))); return diagonal;} // Driver Codepublic static void main(String[] args){ // Given sides int a = 3; int b = 5; // Given angle double theta = 45; // Function call double ans = Length_Diagonal(a, b, theta); // Print the final answer System.out.printf("%.2f", ans);}} // This code is contributed by amal kumar choubey
# Python3 Program to find length# Of diagonal of a parallelogram# Using sides and angle between them. import math # Function to return the length# Of diagonal of a parallelogram# using sides and angle between them. def Length_Diagonal(a, b, theta): diagonal = math.sqrt( ((a**2) + (b**2)) - 2 * a*b * math.cos(math.radians(theta))) return diagonal # Driver Code # Given Sidesa = 3b = 5 # Given Angletheta = 45 # Function Call ans = Length_Diagonal(a, b, theta) # Print the final answerprint(round(ans, 2))
// C# program to find length// Of diagonal of a parallelogram// Using sides and angle between them.using System; class GFG{ // Function to return the length// Of diagonal of a parallelogram// using sides and angle between them.static double Length_Diagonal(int a, int b, double theta){ double diagonal = Math.Sqrt((Math.Pow(a, 2) + Math.Pow(b, 2)) - 2 * a * b * Math.Cos(theta * (Math.PI / 180))); return diagonal;} // Driver Codepublic static void Main(String[] args){ // Given sides int a = 3; int b = 5; // Given angle double theta = 45; // Function call double ans = Length_Diagonal(a, b, theta); // Print the readonly answer Console.Write("{0:F2}", ans);}} // This code is contributed by amal kumar choubey
<script> // javascript program to find length// Of diagonal of a parallelogram// Using sides and angle between them. // Function to return the length// Of diagonal of a parallelogram// using sides and angle between them.function Length_Diagonal(a , b,theta){ var diagonal = Math.sqrt((Math.pow(a, 2) + Math.pow(b, 2)) - 2 * a * b * Math.cos(theta * (Math.PI / 180))); return diagonal;} // Driver Code // Given sidesvar a = 3;var b = 5; // Given anglevar theta = 45; // Function callvar ans = Length_Diagonal(a, b, theta); // Print the final answerdocument.write(ans.toFixed(2)); // This code is contributed by 29AjayKumar </script>
3.58
Time Complexity: O(1)Auxiliary Space: O(1)
Amal Kumar Choubey
amit143katiyar
29AjayKumar
Geometric
School Programming
Geometric
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program for distance between two points on earth
Optimum location of point to minimize total distance
Check if two given circles touch or intersect each other
Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping)
Line Clipping | Set 1 (Cohen–Sutherland Algorithm)
Python Dictionary
Reverse a string in Java
Arrays in C/C++
Introduction To PYTHON
Interfaces in Java | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n08 Apr, 2021"
},
{
"code": null,
"e": 222,
"s": 28,
"text": "Given two integers a and b where a and b represents the length of adjacent sides of a parallelogram and an angle 0 between them, the task is to find the length of diagonal of the parallelogram."
},
{
"code": null,
"e": 232,
"s": 222,
"text": "Examples:"
},
{
"code": null,
"e": 272,
"s": 232,
"text": "Input: a = 6, b = 10, 0=30Output: 6.14 "
},
{
"code": null,
"e": 310,
"s": 272,
"text": "Input: a = 3, b = 5, 0=45Output: 3.58"
},
{
"code": null,
"e": 502,
"s": 310,
"text": "Approach: Consider a parallelogram ABCD with sides a and b, now apply cosine rule at angle A in the triangle ABD to find the length of diagonal p, similarly find diagonal q from triangle ABC."
},
{
"code": null,
"e": 540,
"s": 502,
"text": "Therefore the diagonals is given by: "
},
{
"code": null,
"e": 546,
"s": 542,
"text": "C++"
},
{
"code": null,
"e": 551,
"s": 546,
"text": "Java"
},
{
"code": null,
"e": 559,
"s": 551,
"text": "Python3"
},
{
"code": null,
"e": 562,
"s": 559,
"text": "C#"
},
{
"code": null,
"e": 573,
"s": 562,
"text": "Javascript"
},
{
"code": "// C++ program to find length// Of diagonal of a parallelogram// Using sides and angle between them.#include <bits/stdc++.h>using namespace std;#define PI 3.147 // Function to return the length// Of diagonal of a parallelogram// using sides and angle between them.double Length_Diagonal(int a, int b, double theta){ double diagonal = sqrt((pow(a, 2) + pow(b, 2)) - 2 * a * b * cos(theta * (PI / 180))); return diagonal;} // Driver Codeint main(){ // Given sides int a = 3; int b = 5; // Given angle double theta = 45; // Function call double ans = Length_Diagonal(a, b, theta); // Print the final answer printf(\"%.2f\", ans);} // This code is contributed by Amit Katiyar",
"e": 1302,
"s": 573,
"text": null
},
{
"code": "// Java program to find length// Of diagonal of a parallelogram// Using sides and angle between them.class GFG{ // Function to return the length// Of diagonal of a parallelogram// using sides and angle between them.static double Length_Diagonal(int a, int b, double theta){ double diagonal = Math.sqrt((Math.pow(a, 2) + Math.pow(b, 2)) - 2 * a * b * Math.cos(theta * (Math.PI / 180))); return diagonal;} // Driver Codepublic static void main(String[] args){ // Given sides int a = 3; int b = 5; // Given angle double theta = 45; // Function call double ans = Length_Diagonal(a, b, theta); // Print the final answer System.out.printf(\"%.2f\", ans);}} // This code is contributed by amal kumar choubey",
"e": 2200,
"s": 1302,
"text": null
},
{
"code": "# Python3 Program to find length# Of diagonal of a parallelogram# Using sides and angle between them. import math # Function to return the length# Of diagonal of a parallelogram# using sides and angle between them. def Length_Diagonal(a, b, theta): diagonal = math.sqrt( ((a**2) + (b**2)) - 2 * a*b * math.cos(math.radians(theta))) return diagonal # Driver Code # Given Sidesa = 3b = 5 # Given Angletheta = 45 # Function Call ans = Length_Diagonal(a, b, theta) # Print the final answerprint(round(ans, 2))",
"e": 2735,
"s": 2200,
"text": null
},
{
"code": "// C# program to find length// Of diagonal of a parallelogram// Using sides and angle between them.using System; class GFG{ // Function to return the length// Of diagonal of a parallelogram// using sides and angle between them.static double Length_Diagonal(int a, int b, double theta){ double diagonal = Math.Sqrt((Math.Pow(a, 2) + Math.Pow(b, 2)) - 2 * a * b * Math.Cos(theta * (Math.PI / 180))); return diagonal;} // Driver Codepublic static void Main(String[] args){ // Given sides int a = 3; int b = 5; // Given angle double theta = 45; // Function call double ans = Length_Diagonal(a, b, theta); // Print the readonly answer Console.Write(\"{0:F2}\", ans);}} // This code is contributed by amal kumar choubey",
"e": 3645,
"s": 2735,
"text": null
},
{
"code": "<script> // javascript program to find length// Of diagonal of a parallelogram// Using sides and angle between them. // Function to return the length// Of diagonal of a parallelogram// using sides and angle between them.function Length_Diagonal(a , b,theta){ var diagonal = Math.sqrt((Math.pow(a, 2) + Math.pow(b, 2)) - 2 * a * b * Math.cos(theta * (Math.PI / 180))); return diagonal;} // Driver Code // Given sidesvar a = 3;var b = 5; // Given anglevar theta = 45; // Function callvar ans = Length_Diagonal(a, b, theta); // Print the final answerdocument.write(ans.toFixed(2)); // This code is contributed by 29AjayKumar </script>",
"e": 4412,
"s": 3645,
"text": null
},
{
"code": null,
"e": 4417,
"s": 4412,
"text": "3.58"
},
{
"code": null,
"e": 4462,
"s": 4419,
"text": "Time Complexity: O(1)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 4481,
"s": 4462,
"text": "Amal Kumar Choubey"
},
{
"code": null,
"e": 4496,
"s": 4481,
"text": "amit143katiyar"
},
{
"code": null,
"e": 4508,
"s": 4496,
"text": "29AjayKumar"
},
{
"code": null,
"e": 4518,
"s": 4508,
"text": "Geometric"
},
{
"code": null,
"e": 4537,
"s": 4518,
"text": "School Programming"
},
{
"code": null,
"e": 4547,
"s": 4537,
"text": "Geometric"
},
{
"code": null,
"e": 4645,
"s": 4547,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4694,
"s": 4645,
"text": "Program for distance between two points on earth"
},
{
"code": null,
"e": 4747,
"s": 4694,
"text": "Optimum location of point to minimize total distance"
},
{
"code": null,
"e": 4804,
"s": 4747,
"text": "Check if two given circles touch or intersect each other"
},
{
"code": null,
"e": 4857,
"s": 4804,
"text": "Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping)"
},
{
"code": null,
"e": 4908,
"s": 4857,
"text": "Line Clipping | Set 1 (Cohen–Sutherland Algorithm)"
},
{
"code": null,
"e": 4926,
"s": 4908,
"text": "Python Dictionary"
},
{
"code": null,
"e": 4951,
"s": 4926,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 4967,
"s": 4951,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 4990,
"s": 4967,
"text": "Introduction To PYTHON"
}
] |
How to convert a String to an Int in Java? | 28 Aug, 2019
Given String str containing digits as characters, the task is to convert this given string to integer in Java.
Examples:
Input: str = "1234"
Output: 1234
Input: str = "213s"
Output: 0
Since the String contains other than digits,
hence the integer value will be 0
Method 1: Use Integer.parseInt() methodThis is the most simple method to convert String to integer. This function parses the string argument as a signed decimal integer.Syntax:public static int parseInt(String s)
throws NumberFormatException
Below is the implementation of the above approach:// Java program to convert String to int// using Integer.parseInt() method import java.io.*; class GFG { // Function to convert String to integer public static int convert(String str) { int val = 0; System.out.println("String = " + str); // Convert the String try { val = Integer.parseInt(str); } catch (NumberFormatException e) { // This is thrown when the String // contains characters other than digits System.out.println("Invalid String"); } return val; } // Driver code public static void main(String[] args) { String str = "1234"; int val = convert(str); System.out.println("Integer value = " + val); System.out.println(); str = "123s"; val = convert(str); System.out.println("Integer value = " + val); }}Output:String = 1234
Integer value = 1234
String = 123s
Invalid String
Integer value = 0
Syntax:
public static int parseInt(String s)
throws NumberFormatException
Below is the implementation of the above approach:
// Java program to convert String to int// using Integer.parseInt() method import java.io.*; class GFG { // Function to convert String to integer public static int convert(String str) { int val = 0; System.out.println("String = " + str); // Convert the String try { val = Integer.parseInt(str); } catch (NumberFormatException e) { // This is thrown when the String // contains characters other than digits System.out.println("Invalid String"); } return val; } // Driver code public static void main(String[] args) { String str = "1234"; int val = convert(str); System.out.println("Integer value = " + val); System.out.println(); str = "123s"; val = convert(str); System.out.println("Integer value = " + val); }}
String = 1234
Integer value = 1234
String = 123s
Invalid String
Integer value = 0
Method 2: Use Ints::tryParse method of Guava libraryAnother method to convert String to integer is to use Ints::tryParse method of Guava library. It is similar to the Integer.parseInt() method, but this method is more concise and powerful.Syntax:public static Integer tryParse(String s)
Below is the implementation of the above approach:// Java program to convert String to int// using Ints::tryParse method import java.io.*;import java.util.*;import com.google.common.primitives.Ints; class GFG { // Function to convert String to integer public static int convert(String str) { int val = 0; System.out.println("String = " + str); // Convert the String val = Optional.ofNullable(str) .map(Ints::tryParse) .orElse(0); return val; } // Driver code public static void main(String[] args) { String str = "1234"; int val = convert(str); System.out.println("Integer value = " + val); System.out.println(); str = "123s"; val = convert(str); System.out.println("Integer value = " + val); }}Output:String = 1234
Integer value = 1234
String = 123s
Integer value = 0
Syntax:
public static Integer tryParse(String s)
Below is the implementation of the above approach:
// Java program to convert String to int// using Ints::tryParse method import java.io.*;import java.util.*;import com.google.common.primitives.Ints; class GFG { // Function to convert String to integer public static int convert(String str) { int val = 0; System.out.println("String = " + str); // Convert the String val = Optional.ofNullable(str) .map(Ints::tryParse) .orElse(0); return val; } // Driver code public static void main(String[] args) { String str = "1234"; int val = convert(str); System.out.println("Integer value = " + val); System.out.println(); str = "123s"; val = convert(str); System.out.println("Integer value = " + val); }}
String = 1234
Integer value = 1234
String = 123s
Integer value = 0
Java-Strings
Java
Java-Strings
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n28 Aug, 2019"
},
{
"code": null,
"e": 163,
"s": 52,
"text": "Given String str containing digits as characters, the task is to convert this given string to integer in Java."
},
{
"code": null,
"e": 173,
"s": 163,
"text": "Examples:"
},
{
"code": null,
"e": 317,
"s": 173,
"text": "Input: str = \"1234\"\nOutput: 1234\n\nInput: str = \"213s\"\nOutput: 0\nSince the String contains other than digits,\nhence the integer value will be 0\n"
},
{
"code": null,
"e": 1610,
"s": 317,
"text": "Method 1: Use Integer.parseInt() methodThis is the most simple method to convert String to integer. This function parses the string argument as a signed decimal integer.Syntax:public static int parseInt(String s)\n throws NumberFormatException\nBelow is the implementation of the above approach:// Java program to convert String to int// using Integer.parseInt() method import java.io.*; class GFG { // Function to convert String to integer public static int convert(String str) { int val = 0; System.out.println(\"String = \" + str); // Convert the String try { val = Integer.parseInt(str); } catch (NumberFormatException e) { // This is thrown when the String // contains characters other than digits System.out.println(\"Invalid String\"); } return val; } // Driver code public static void main(String[] args) { String str = \"1234\"; int val = convert(str); System.out.println(\"Integer value = \" + val); System.out.println(); str = \"123s\"; val = convert(str); System.out.println(\"Integer value = \" + val); }}Output:String = 1234\nInteger value = 1234\n\nString = 123s\nInvalid String\nInteger value = 0\n"
},
{
"code": null,
"e": 1618,
"s": 1610,
"text": "Syntax:"
},
{
"code": null,
"e": 1697,
"s": 1618,
"text": "public static int parseInt(String s)\n throws NumberFormatException\n"
},
{
"code": null,
"e": 1748,
"s": 1697,
"text": "Below is the implementation of the above approach:"
},
{
"code": "// Java program to convert String to int// using Integer.parseInt() method import java.io.*; class GFG { // Function to convert String to integer public static int convert(String str) { int val = 0; System.out.println(\"String = \" + str); // Convert the String try { val = Integer.parseInt(str); } catch (NumberFormatException e) { // This is thrown when the String // contains characters other than digits System.out.println(\"Invalid String\"); } return val; } // Driver code public static void main(String[] args) { String str = \"1234\"; int val = convert(str); System.out.println(\"Integer value = \" + val); System.out.println(); str = \"123s\"; val = convert(str); System.out.println(\"Integer value = \" + val); }}",
"e": 2647,
"s": 1748,
"text": null
},
{
"code": null,
"e": 2731,
"s": 2647,
"text": "String = 1234\nInteger value = 1234\n\nString = 123s\nInvalid String\nInteger value = 0\n"
},
{
"code": null,
"e": 3945,
"s": 2731,
"text": "Method 2: Use Ints::tryParse method of Guava libraryAnother method to convert String to integer is to use Ints::tryParse method of Guava library. It is similar to the Integer.parseInt() method, but this method is more concise and powerful.Syntax:public static Integer tryParse(String s)\nBelow is the implementation of the above approach:// Java program to convert String to int// using Ints::tryParse method import java.io.*;import java.util.*;import com.google.common.primitives.Ints; class GFG { // Function to convert String to integer public static int convert(String str) { int val = 0; System.out.println(\"String = \" + str); // Convert the String val = Optional.ofNullable(str) .map(Ints::tryParse) .orElse(0); return val; } // Driver code public static void main(String[] args) { String str = \"1234\"; int val = convert(str); System.out.println(\"Integer value = \" + val); System.out.println(); str = \"123s\"; val = convert(str); System.out.println(\"Integer value = \" + val); }}Output:String = 1234\nInteger value = 1234\n\nString = 123s\nInteger value = 0\n"
},
{
"code": null,
"e": 3953,
"s": 3945,
"text": "Syntax:"
},
{
"code": null,
"e": 3995,
"s": 3953,
"text": "public static Integer tryParse(String s)\n"
},
{
"code": null,
"e": 4046,
"s": 3995,
"text": "Below is the implementation of the above approach:"
},
{
"code": "// Java program to convert String to int// using Ints::tryParse method import java.io.*;import java.util.*;import com.google.common.primitives.Ints; class GFG { // Function to convert String to integer public static int convert(String str) { int val = 0; System.out.println(\"String = \" + str); // Convert the String val = Optional.ofNullable(str) .map(Ints::tryParse) .orElse(0); return val; } // Driver code public static void main(String[] args) { String str = \"1234\"; int val = convert(str); System.out.println(\"Integer value = \" + val); System.out.println(); str = \"123s\"; val = convert(str); System.out.println(\"Integer value = \" + val); }}",
"e": 4848,
"s": 4046,
"text": null
},
{
"code": null,
"e": 4917,
"s": 4848,
"text": "String = 1234\nInteger value = 1234\n\nString = 123s\nInteger value = 0\n"
},
{
"code": null,
"e": 4930,
"s": 4917,
"text": "Java-Strings"
},
{
"code": null,
"e": 4935,
"s": 4930,
"text": "Java"
},
{
"code": null,
"e": 4948,
"s": 4935,
"text": "Java-Strings"
},
{
"code": null,
"e": 4953,
"s": 4948,
"text": "Java"
}
] |
How to sort rows in a table using JavaScript? | 28 Jun, 2019
Since JavaScript doesn’t provide any inbuilt functions to sort a table we will be required to use native methods to sort a given table. We will look into the methods in this article.
Approach:A basic algorithm and similar approach will be used for both of the following examples. Loop the program to switch and sort the elements until it is sorted.
// executes on action like button click
Function() {
// main loop that runs until table is sorted
While (condition = true) {
// runs for all rows
for (i = 1; i < row.length; i++ ) {
// check if switch is required
if (element_A > element_B){
// perform switch
PerformSwitch();
}
}
}
}
Example 1: This example sorts the table using a while loop to switch the rows until the rows are sorted.
<!DOCTYPE html><html> <head> <title>GeeksforGeeks</title> <style> table { border-spacing: 0; width: 80%; border: 1px solid #dddd; } th, td { text-align: left; padding: 15px; } tr:nth-child(even) { background-color: #008000 } </style></head> <body> <center> <h1 style="color:green">GeeksforGeeks</h1> <p> <button onclick="sortTable()">Sort</button> </p> <table id="table"> <tr> <th>Country</th> <th>Capital</th> </tr> <tr> <td>United states of America</td> <td>Washington DC</td> </tr> <tr> <td>India</td> <td>New Delhi</td> </tr> <tr> <td>Australia</td> <td>Canberra</td> </tr> <tr> <td>Germany</td> <td>Berlin</td> </tr> </table> <script> // JavaScript Program to illustrate // Table sort on a button click function sortTable() { var table, i, x, y; table = document.getElementById("table"); var switching = true; // Run loop until no switching is needed while (switching) { switching = false; var rows = table.rows; // Loop to go through all rows for (i = 1; i < (rows.length - 1); i++) { var Switch = false; // Fetch 2 elements that need to be compared x = rows[i].getElementsByTagName("TD")[0]; y = rows[i + 1].getElementsByTagName("TD")[0]; // Check if 2 rows need to be switched if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) { // If yes, mark Switch as needed and break loop Switch = true; break; } } if (Switch) { // Function to switch rows and mark switch as completed rows[i].parentNode.insertBefore(rows[i + 1], rows[i]); switching = true; } } } </script> </center></body> </html>
Output before click:
Output after click:
Example 2: This example sorts the table using the same loop technique but executes the function for both the given columns, as well as in both directions (ascending and descending).
<!DOCTYPE html><html> <head> <title>GeeksforGeeks</title> <style> table { border-spacing: 0; width: 80%; border: 1px solid #dddd; } th, td { text-align: left; padding: 15px; } tr:nth-child(even) { background-color: #008000 } </style></head> <body> <center> <h1 style="color:green"> GeeksforGeeks </h1> <p><strong> Click the headers to sort in ascending and descending. </strong></p> <table id="table"> <tr> <!--Calls sortTable function(0 for country and 1 for capital) when headers are clicked--> <th onclick="sortTable(0)">Country</th> <th onclick="sortTable(1)">Capital</th> </tr> <tr> <td>United states of America</td> <td>Washington DC</td> </tr> <tr> <td>India</td> <td>New Delhi</td> </tr> <tr> <td>Australia</td> <td>Canberra</td> </tr> <tr> <td>Germany</td> <td>Berlin</td> </tr> </table> <script> // JavaScript program to illustrate // Table sort for both columns and both directions. function sortTable(n) { var table; table = document.getElementById("table"); var rows, i, x, y, count = 0; var switching = true; // Order is set as ascending var direction = "ascending"; // Run loop until no switching is needed while (switching) { switching = false; var rows = table.rows; //Loop to go through all rows for (i = 1; i < (rows.length - 1); i++) { var Switch = false; // Fetch 2 elements that need to be compared x = rows[i].getElementsByTagName("TD")[n]; y = rows[i + 1].getElementsByTagName("TD")[n]; // Check the direction of order if (direction == "ascending") { // Check if 2 rows need to be switched if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) { // If yes, mark Switch as needed and break loop Switch = true; break; } } else if (direction == "descending") { // Check direction if (x.innerHTML.toLowerCase() < y.innerHTML.toLowerCase()) { // If yes, mark Switch as needed and break loop Switch = true; break; } } } if (Switch) { // Function to switch rows and mark switch as completed rows[i].parentNode.insertBefore(rows[i + 1], rows[i]); switching = true; // Increase count for each switch count++; } else { // Run while loop again for descending order if (count == 0 && direction == "ascending") { direction = "descending"; switching = true; } } } } </script> </center></body> </html>
Output before sort
Output for 1st column sort(ascending):
Output for 2nd column sort(descending):
JavaScript-Misc
Picked
HTML
JavaScript
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
REST API (Introduction)
CSS to put icon inside an input element in a form
Types of CSS (Cascading Style Sheet)
HTTP headers | Content-Type
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Roadmap to Learn JavaScript For Beginners
Difference Between PUT and PATCH Request | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Jun, 2019"
},
{
"code": null,
"e": 211,
"s": 28,
"text": "Since JavaScript doesn’t provide any inbuilt functions to sort a table we will be required to use native methods to sort a given table. We will look into the methods in this article."
},
{
"code": null,
"e": 377,
"s": 211,
"text": "Approach:A basic algorithm and similar approach will be used for both of the following examples. Loop the program to switch and sort the elements until it is sorted."
},
{
"code": null,
"e": 755,
"s": 377,
"text": "// executes on action like button click\nFunction() { \n // main loop that runs until table is sorted\n While (condition = true) { \n // runs for all rows\n for (i = 1; i < row.length; i++ ) { \n // check if switch is required\n if (element_A > element_B){ \n // perform switch\n PerformSwitch(); \n }\n }\n }\n}\n"
},
{
"code": null,
"e": 860,
"s": 755,
"text": "Example 1: This example sorts the table using a while loop to switch the rows until the rows are sorted."
},
{
"code": "<!DOCTYPE html><html> <head> <title>GeeksforGeeks</title> <style> table { border-spacing: 0; width: 80%; border: 1px solid #dddd; } th, td { text-align: left; padding: 15px; } tr:nth-child(even) { background-color: #008000 } </style></head> <body> <center> <h1 style=\"color:green\">GeeksforGeeks</h1> <p> <button onclick=\"sortTable()\">Sort</button> </p> <table id=\"table\"> <tr> <th>Country</th> <th>Capital</th> </tr> <tr> <td>United states of America</td> <td>Washington DC</td> </tr> <tr> <td>India</td> <td>New Delhi</td> </tr> <tr> <td>Australia</td> <td>Canberra</td> </tr> <tr> <td>Germany</td> <td>Berlin</td> </tr> </table> <script> // JavaScript Program to illustrate // Table sort on a button click function sortTable() { var table, i, x, y; table = document.getElementById(\"table\"); var switching = true; // Run loop until no switching is needed while (switching) { switching = false; var rows = table.rows; // Loop to go through all rows for (i = 1; i < (rows.length - 1); i++) { var Switch = false; // Fetch 2 elements that need to be compared x = rows[i].getElementsByTagName(\"TD\")[0]; y = rows[i + 1].getElementsByTagName(\"TD\")[0]; // Check if 2 rows need to be switched if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) { // If yes, mark Switch as needed and break loop Switch = true; break; } } if (Switch) { // Function to switch rows and mark switch as completed rows[i].parentNode.insertBefore(rows[i + 1], rows[i]); switching = true; } } } </script> </center></body> </html>",
"e": 3460,
"s": 860,
"text": null
},
{
"code": null,
"e": 3481,
"s": 3460,
"text": "Output before click:"
},
{
"code": null,
"e": 3501,
"s": 3481,
"text": "Output after click:"
},
{
"code": null,
"e": 3683,
"s": 3501,
"text": "Example 2: This example sorts the table using the same loop technique but executes the function for both the given columns, as well as in both directions (ascending and descending)."
},
{
"code": "<!DOCTYPE html><html> <head> <title>GeeksforGeeks</title> <style> table { border-spacing: 0; width: 80%; border: 1px solid #dddd; } th, td { text-align: left; padding: 15px; } tr:nth-child(even) { background-color: #008000 } </style></head> <body> <center> <h1 style=\"color:green\"> GeeksforGeeks </h1> <p><strong> Click the headers to sort in ascending and descending. </strong></p> <table id=\"table\"> <tr> <!--Calls sortTable function(0 for country and 1 for capital) when headers are clicked--> <th onclick=\"sortTable(0)\">Country</th> <th onclick=\"sortTable(1)\">Capital</th> </tr> <tr> <td>United states of America</td> <td>Washington DC</td> </tr> <tr> <td>India</td> <td>New Delhi</td> </tr> <tr> <td>Australia</td> <td>Canberra</td> </tr> <tr> <td>Germany</td> <td>Berlin</td> </tr> </table> <script> // JavaScript program to illustrate // Table sort for both columns and both directions. function sortTable(n) { var table; table = document.getElementById(\"table\"); var rows, i, x, y, count = 0; var switching = true; // Order is set as ascending var direction = \"ascending\"; // Run loop until no switching is needed while (switching) { switching = false; var rows = table.rows; //Loop to go through all rows for (i = 1; i < (rows.length - 1); i++) { var Switch = false; // Fetch 2 elements that need to be compared x = rows[i].getElementsByTagName(\"TD\")[n]; y = rows[i + 1].getElementsByTagName(\"TD\")[n]; // Check the direction of order if (direction == \"ascending\") { // Check if 2 rows need to be switched if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) { // If yes, mark Switch as needed and break loop Switch = true; break; } } else if (direction == \"descending\") { // Check direction if (x.innerHTML.toLowerCase() < y.innerHTML.toLowerCase()) { // If yes, mark Switch as needed and break loop Switch = true; break; } } } if (Switch) { // Function to switch rows and mark switch as completed rows[i].parentNode.insertBefore(rows[i + 1], rows[i]); switching = true; // Increase count for each switch count++; } else { // Run while loop again for descending order if (count == 0 && direction == \"ascending\") { direction = \"descending\"; switching = true; } } } } </script> </center></body> </html>",
"e": 7635,
"s": 3683,
"text": null
},
{
"code": null,
"e": 7654,
"s": 7635,
"text": "Output before sort"
},
{
"code": null,
"e": 7693,
"s": 7654,
"text": "Output for 1st column sort(ascending):"
},
{
"code": null,
"e": 7733,
"s": 7693,
"text": "Output for 2nd column sort(descending):"
},
{
"code": null,
"e": 7749,
"s": 7733,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 7756,
"s": 7749,
"text": "Picked"
},
{
"code": null,
"e": 7761,
"s": 7756,
"text": "HTML"
},
{
"code": null,
"e": 7772,
"s": 7761,
"text": "JavaScript"
},
{
"code": null,
"e": 7777,
"s": 7772,
"text": "HTML"
},
{
"code": null,
"e": 7875,
"s": 7777,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7923,
"s": 7875,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 7947,
"s": 7923,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 7997,
"s": 7947,
"text": "CSS to put icon inside an input element in a form"
},
{
"code": null,
"e": 8034,
"s": 7997,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 8062,
"s": 8034,
"text": "HTTP headers | Content-Type"
},
{
"code": null,
"e": 8123,
"s": 8062,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 8195,
"s": 8123,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 8235,
"s": 8195,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 8277,
"s": 8235,
"text": "Roadmap to Learn JavaScript For Beginners"
}
] |
HTTP status codes | Server Error Responses | 15 Jul, 2020
HTTP status codes is a conversation between your browser and the site server. The server gives responses to the browser’s request in the form of a three-digit code known as HTTP status codes. Categories of HTTP status codes are.
Informational responses (100–199)
Successful responses (200–299)
Redirects (300–399)
Client errors (400–499)
Server errors (500–599)
Server Error Responses: Server error response occurs when the server fails to fulfill the request of the visitor.
500 Internal Server Error: 500 Internal Server Error is a common error message that occurs when the server meets an unexpected situation and it doesn’t know how to handle it.Status:500 Internal Server Error
500 Internal Server Error
501 Not Implemented: 501 Not Implemented occurs when the requested method is not supported by the server. The server either does not perceive the request or it comes up short on the capacity to fulfill the request. GET and HEAD are the only methods that the server support.Status:501 Not Implemented
501 Not Implemented
502 Bad Gateway: 502 Bad Gateway occurs when the server is working as a gateway and it receives an invalid response from the upstream server.Status:502 Bad Gateway
502 Bad Gateway
503 Service Unavailable: 503 Service Unavailable occurs when the server is unable to handle the requests (the server is temporarily overloading or down).Status:503 Service Unavailable
503 Service Unavailable
504 Gateway Timeout: 504 Gateway Timeout occurs when the server is acting as a gateway and did not get a response from the upstream server on time.Status:504 Gateway Timeout
504 Gateway Timeout
505 HTTP Version Not Supported: 505 HTTP Version Not Supported occurs when the HTTP protocol version used in the request is not supported by the server.Status:505 HTTP Version Not Supported
505 HTTP Version Not Supported
506 Variant Also Negotiated: 506 Variant Also Negotiated occurs when there is an internal configuration error in the server.Status:506 Variant Also Negotiated
506 Variant Also Negotiated
507 Insufficient Storage: 507 Insufficient Storage occurs when the server is unable to store or execute the (PUT or POST) operation that is required to complete the request successfully due to the large size of the operation.Status:507 Insufficient Storage
507 Insufficient Storage
508 Loop Detected: 508 Loop Detected occurs when an infinite loop is detected by the server while processing the request. The request is terminated by the server.Status:508 Loop Detected
508 Loop Detected
510 Not Extended: 509 Not Extended occurs when there are no further resources(extensions) for the server to complete the required request.Status:510 Not Extended
510 Not Extended
511 Network Authentication Required: The 511 Network Authentication Required occurs when the visitors need to authenticate in order to gain network access.Status:511 Network Authentication Required
511 Network Authentication Required
Supported Browsers: The browsers compatible with the HTTP status code Server Error Responses are listed below.
Google Chrome
Internet Explorer
Firefox
Safari
Opera
HTTP- response-status-codes
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
REST API (Introduction)
Difference Between PUT and PATCH Request
ReactJS | Router
Roadmap to Learn JavaScript For Beginners
How to float three div side by side using CSS?
How to get character array from string in JavaScript? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n15 Jul, 2020"
},
{
"code": null,
"e": 257,
"s": 28,
"text": "HTTP status codes is a conversation between your browser and the site server. The server gives responses to the browser’s request in the form of a three-digit code known as HTTP status codes. Categories of HTTP status codes are."
},
{
"code": null,
"e": 291,
"s": 257,
"text": "Informational responses (100–199)"
},
{
"code": null,
"e": 322,
"s": 291,
"text": "Successful responses (200–299)"
},
{
"code": null,
"e": 342,
"s": 322,
"text": "Redirects (300–399)"
},
{
"code": null,
"e": 366,
"s": 342,
"text": "Client errors (400–499)"
},
{
"code": null,
"e": 390,
"s": 366,
"text": "Server errors (500–599)"
},
{
"code": null,
"e": 504,
"s": 390,
"text": "Server Error Responses: Server error response occurs when the server fails to fulfill the request of the visitor."
},
{
"code": null,
"e": 711,
"s": 504,
"text": "500 Internal Server Error: 500 Internal Server Error is a common error message that occurs when the server meets an unexpected situation and it doesn’t know how to handle it.Status:500 Internal Server Error"
},
{
"code": null,
"e": 737,
"s": 711,
"text": "500 Internal Server Error"
},
{
"code": null,
"e": 1037,
"s": 737,
"text": "501 Not Implemented: 501 Not Implemented occurs when the requested method is not supported by the server. The server either does not perceive the request or it comes up short on the capacity to fulfill the request. GET and HEAD are the only methods that the server support.Status:501 Not Implemented"
},
{
"code": null,
"e": 1057,
"s": 1037,
"text": "501 Not Implemented"
},
{
"code": null,
"e": 1221,
"s": 1057,
"text": "502 Bad Gateway: 502 Bad Gateway occurs when the server is working as a gateway and it receives an invalid response from the upstream server.Status:502 Bad Gateway"
},
{
"code": null,
"e": 1237,
"s": 1221,
"text": "502 Bad Gateway"
},
{
"code": null,
"e": 1421,
"s": 1237,
"text": "503 Service Unavailable: 503 Service Unavailable occurs when the server is unable to handle the requests (the server is temporarily overloading or down).Status:503 Service Unavailable"
},
{
"code": null,
"e": 1445,
"s": 1421,
"text": "503 Service Unavailable"
},
{
"code": null,
"e": 1619,
"s": 1445,
"text": "504 Gateway Timeout: 504 Gateway Timeout occurs when the server is acting as a gateway and did not get a response from the upstream server on time.Status:504 Gateway Timeout"
},
{
"code": null,
"e": 1639,
"s": 1619,
"text": "504 Gateway Timeout"
},
{
"code": null,
"e": 1830,
"s": 1639,
"text": "505 HTTP Version Not Supported: 505 HTTP Version Not Supported occurs when the HTTP protocol version used in the request is not supported by the server.Status:505 HTTP Version Not Supported "
},
{
"code": null,
"e": 1862,
"s": 1830,
"text": "505 HTTP Version Not Supported "
},
{
"code": null,
"e": 2021,
"s": 1862,
"text": "506 Variant Also Negotiated: 506 Variant Also Negotiated occurs when there is an internal configuration error in the server.Status:506 Variant Also Negotiated"
},
{
"code": null,
"e": 2049,
"s": 2021,
"text": "506 Variant Also Negotiated"
},
{
"code": null,
"e": 2306,
"s": 2049,
"text": "507 Insufficient Storage: 507 Insufficient Storage occurs when the server is unable to store or execute the (PUT or POST) operation that is required to complete the request successfully due to the large size of the operation.Status:507 Insufficient Storage"
},
{
"code": null,
"e": 2331,
"s": 2306,
"text": "507 Insufficient Storage"
},
{
"code": null,
"e": 2518,
"s": 2331,
"text": "508 Loop Detected: 508 Loop Detected occurs when an infinite loop is detected by the server while processing the request. The request is terminated by the server.Status:508 Loop Detected"
},
{
"code": null,
"e": 2536,
"s": 2518,
"text": "508 Loop Detected"
},
{
"code": null,
"e": 2698,
"s": 2536,
"text": "510 Not Extended: 509 Not Extended occurs when there are no further resources(extensions) for the server to complete the required request.Status:510 Not Extended"
},
{
"code": null,
"e": 2715,
"s": 2698,
"text": "510 Not Extended"
},
{
"code": null,
"e": 2913,
"s": 2715,
"text": "511 Network Authentication Required: The 511 Network Authentication Required occurs when the visitors need to authenticate in order to gain network access.Status:511 Network Authentication Required"
},
{
"code": null,
"e": 2949,
"s": 2913,
"text": "511 Network Authentication Required"
},
{
"code": null,
"e": 3060,
"s": 2949,
"text": "Supported Browsers: The browsers compatible with the HTTP status code Server Error Responses are listed below."
},
{
"code": null,
"e": 3074,
"s": 3060,
"text": "Google Chrome"
},
{
"code": null,
"e": 3092,
"s": 3074,
"text": "Internet Explorer"
},
{
"code": null,
"e": 3100,
"s": 3092,
"text": "Firefox"
},
{
"code": null,
"e": 3107,
"s": 3100,
"text": "Safari"
},
{
"code": null,
"e": 3113,
"s": 3107,
"text": "Opera"
},
{
"code": null,
"e": 3141,
"s": 3113,
"text": "HTTP- response-status-codes"
},
{
"code": null,
"e": 3158,
"s": 3141,
"text": "Web Technologies"
},
{
"code": null,
"e": 3256,
"s": 3158,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3317,
"s": 3256,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3360,
"s": 3317,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 3432,
"s": 3360,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 3472,
"s": 3432,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 3496,
"s": 3472,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 3537,
"s": 3496,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 3554,
"s": 3537,
"text": "ReactJS | Router"
},
{
"code": null,
"e": 3596,
"s": 3554,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 3643,
"s": 3596,
"text": "How to float three div side by side using CSS?"
}
] |
BigDecimal abs() Method in Java | 04 Dec, 2018
The java.math.BigDecimal.abs() is used to return a BigDecimal whose value is the absolute value of the BigDecimal and whose scale is this.scale().Syntax :public BigDecimal abs()Parameters: The method does not accept any parameters.Return Value: Returns a BigDecimal whose value is the absolute value of this BigDecimal scale is this.scale().Below programs will illustrate the use of java.math.BigDecimal.abs() method :Program 1// Java program to demonstrate abs() methodimport java.io.*;import java.math.*; public class GFG { public static void main(String[] args) { // Creating a BigDecimal object BigDecimal num; // Assigning value to num num = new BigDecimal("-51"); // Displaying the result System.out.println("Absolute value is " + num.abs()); }}Output:Absolute value is 51
Program 2// Java program to demonstrate abs() methodimport java.io.*;import java.math.*; public class GFG { public static void main(String[] args) { // creating a BigDecimal object BigDecimal num; // assign value to num num = new BigDecimal("-63.93471"); System.out.println("Absolute value is " + num.abs()); }}Output:Absolute value is 63.93471
The java.math.BigDecimal.abs(MathContext mc) returns a BigDecimal whose value is the absolute value of the BigDecimal obtained by rounding it off according to the precision settings specified by mc, an object of MathContext class.Syntax:public BigDecimal abs(MathContext mc)Parameters : The function accepts only one parameter mc of MathContext class object, which specifies precision settings to be used for rounding off the BigDecimal.Return Value: Returns a BigDecimal whose value is the absolute value of this BigDecimal obtained by rounding it off according to the precision settings specified by the object mc.Exception : The method throws an ArithmeticException, if the result is inexact but the rounding mode is UNNECESSARY.Below programs illustrate the use of java.math.BigDecimal.abs() method with specified MathContext :Program 1import java.io.*;import java.math.*; public class GFG { public static void main(String[] args) { // Create 2 BigDecimal objects BigDecimal num, absv; MathContext mc = new MathContext(2); // Assign value to num num = new BigDecimal("51.93471"); // Assign absolute value of num to absv rounded // to 2 precision using mc absv = num.abs(mc); System.out.println("Absolute value, rounded to 2 precision is " + absv); }}Output:Absolute value, rounded to 2 precision is 52
Program 2import java.io.*;import java.math.*; public class GFG { public static void main(String[] args) { // Create 2 BigDecimal objects BigDecimal num, absv; MathContext mc = new MathContext(15); // Assign value to num num = new BigDecimal("143567812363.93471"); // Assign absolute value of num to absv rounded // to 15 precision using mc absv = num.abs(mc); System.out.println("Absolute value, rounded to 15 precision is " + absv); }}Output:Absolute value, rounded to 15 precision is 143567812363.935
The java.math.BigDecimal.abs() is used to return a BigDecimal whose value is the absolute value of the BigDecimal and whose scale is this.scale().Syntax :public BigDecimal abs()Parameters: The method does not accept any parameters.Return Value: Returns a BigDecimal whose value is the absolute value of this BigDecimal scale is this.scale().Below programs will illustrate the use of java.math.BigDecimal.abs() method :Program 1// Java program to demonstrate abs() methodimport java.io.*;import java.math.*; public class GFG { public static void main(String[] args) { // Creating a BigDecimal object BigDecimal num; // Assigning value to num num = new BigDecimal("-51"); // Displaying the result System.out.println("Absolute value is " + num.abs()); }}Output:Absolute value is 51
Program 2// Java program to demonstrate abs() methodimport java.io.*;import java.math.*; public class GFG { public static void main(String[] args) { // creating a BigDecimal object BigDecimal num; // assign value to num num = new BigDecimal("-63.93471"); System.out.println("Absolute value is " + num.abs()); }}Output:Absolute value is 63.93471
Syntax :
public BigDecimal abs()
Parameters: The method does not accept any parameters.
Return Value: Returns a BigDecimal whose value is the absolute value of this BigDecimal scale is this.scale().
Below programs will illustrate the use of java.math.BigDecimal.abs() method :Program 1
// Java program to demonstrate abs() methodimport java.io.*;import java.math.*; public class GFG { public static void main(String[] args) { // Creating a BigDecimal object BigDecimal num; // Assigning value to num num = new BigDecimal("-51"); // Displaying the result System.out.println("Absolute value is " + num.abs()); }}
Absolute value is 51
Program 2
// Java program to demonstrate abs() methodimport java.io.*;import java.math.*; public class GFG { public static void main(String[] args) { // creating a BigDecimal object BigDecimal num; // assign value to num num = new BigDecimal("-63.93471"); System.out.println("Absolute value is " + num.abs()); }}
Absolute value is 63.93471
The java.math.BigDecimal.abs(MathContext mc) returns a BigDecimal whose value is the absolute value of the BigDecimal obtained by rounding it off according to the precision settings specified by mc, an object of MathContext class.Syntax:public BigDecimal abs(MathContext mc)Parameters : The function accepts only one parameter mc of MathContext class object, which specifies precision settings to be used for rounding off the BigDecimal.Return Value: Returns a BigDecimal whose value is the absolute value of this BigDecimal obtained by rounding it off according to the precision settings specified by the object mc.Exception : The method throws an ArithmeticException, if the result is inexact but the rounding mode is UNNECESSARY.Below programs illustrate the use of java.math.BigDecimal.abs() method with specified MathContext :Program 1import java.io.*;import java.math.*; public class GFG { public static void main(String[] args) { // Create 2 BigDecimal objects BigDecimal num, absv; MathContext mc = new MathContext(2); // Assign value to num num = new BigDecimal("51.93471"); // Assign absolute value of num to absv rounded // to 2 precision using mc absv = num.abs(mc); System.out.println("Absolute value, rounded to 2 precision is " + absv); }}Output:Absolute value, rounded to 2 precision is 52
Program 2import java.io.*;import java.math.*; public class GFG { public static void main(String[] args) { // Create 2 BigDecimal objects BigDecimal num, absv; MathContext mc = new MathContext(15); // Assign value to num num = new BigDecimal("143567812363.93471"); // Assign absolute value of num to absv rounded // to 15 precision using mc absv = num.abs(mc); System.out.println("Absolute value, rounded to 15 precision is " + absv); }}Output:Absolute value, rounded to 15 precision is 143567812363.935
Syntax:
public BigDecimal abs(MathContext mc)
Parameters : The function accepts only one parameter mc of MathContext class object, which specifies precision settings to be used for rounding off the BigDecimal.
Return Value: Returns a BigDecimal whose value is the absolute value of this BigDecimal obtained by rounding it off according to the precision settings specified by the object mc.
Exception : The method throws an ArithmeticException, if the result is inexact but the rounding mode is UNNECESSARY.
Below programs illustrate the use of java.math.BigDecimal.abs() method with specified MathContext :Program 1
import java.io.*;import java.math.*; public class GFG { public static void main(String[] args) { // Create 2 BigDecimal objects BigDecimal num, absv; MathContext mc = new MathContext(2); // Assign value to num num = new BigDecimal("51.93471"); // Assign absolute value of num to absv rounded // to 2 precision using mc absv = num.abs(mc); System.out.println("Absolute value, rounded to 2 precision is " + absv); }}
Absolute value, rounded to 2 precision is 52
Program 2
import java.io.*;import java.math.*; public class GFG { public static void main(String[] args) { // Create 2 BigDecimal objects BigDecimal num, absv; MathContext mc = new MathContext(15); // Assign value to num num = new BigDecimal("143567812363.93471"); // Assign absolute value of num to absv rounded // to 15 precision using mc absv = num.abs(mc); System.out.println("Absolute value, rounded to 15 precision is " + absv); }}
Absolute value, rounded to 15 precision is 143567812363.935
Reference: https://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#abs()
Java-BigDecimal
Java-Functions
Java-lang package
java-math
Java-math-package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Collections in Java
Multidimensional Arrays in Java
Stream In Java
Set in Java
Singleton Class in Java | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n04 Dec, 2018"
},
{
"code": null,
"e": 3262,
"s": 28,
"text": "The java.math.BigDecimal.abs() is used to return a BigDecimal whose value is the absolute value of the BigDecimal and whose scale is this.scale().Syntax :public BigDecimal abs()Parameters: The method does not accept any parameters.Return Value: Returns a BigDecimal whose value is the absolute value of this BigDecimal scale is this.scale().Below programs will illustrate the use of java.math.BigDecimal.abs() method :Program 1// Java program to demonstrate abs() methodimport java.io.*;import java.math.*; public class GFG { public static void main(String[] args) { // Creating a BigDecimal object BigDecimal num; // Assigning value to num num = new BigDecimal(\"-51\"); // Displaying the result System.out.println(\"Absolute value is \" + num.abs()); }}Output:Absolute value is 51\nProgram 2// Java program to demonstrate abs() methodimport java.io.*;import java.math.*; public class GFG { public static void main(String[] args) { // creating a BigDecimal object BigDecimal num; // assign value to num num = new BigDecimal(\"-63.93471\"); System.out.println(\"Absolute value is \" + num.abs()); }}Output:Absolute value is 63.93471\nThe java.math.BigDecimal.abs(MathContext mc) returns a BigDecimal whose value is the absolute value of the BigDecimal obtained by rounding it off according to the precision settings specified by mc, an object of MathContext class.Syntax:public BigDecimal abs(MathContext mc)Parameters : The function accepts only one parameter mc of MathContext class object, which specifies precision settings to be used for rounding off the BigDecimal.Return Value: Returns a BigDecimal whose value is the absolute value of this BigDecimal obtained by rounding it off according to the precision settings specified by the object mc.Exception : The method throws an ArithmeticException, if the result is inexact but the rounding mode is UNNECESSARY.Below programs illustrate the use of java.math.BigDecimal.abs() method with specified MathContext :Program 1import java.io.*;import java.math.*; public class GFG { public static void main(String[] args) { // Create 2 BigDecimal objects BigDecimal num, absv; MathContext mc = new MathContext(2); // Assign value to num num = new BigDecimal(\"51.93471\"); // Assign absolute value of num to absv rounded // to 2 precision using mc absv = num.abs(mc); System.out.println(\"Absolute value, rounded to 2 precision is \" + absv); }}Output:Absolute value, rounded to 2 precision is 52\nProgram 2import java.io.*;import java.math.*; public class GFG { public static void main(String[] args) { // Create 2 BigDecimal objects BigDecimal num, absv; MathContext mc = new MathContext(15); // Assign value to num num = new BigDecimal(\"143567812363.93471\"); // Assign absolute value of num to absv rounded // to 15 precision using mc absv = num.abs(mc); System.out.println(\"Absolute value, rounded to 15 precision is \" + absv); }}Output:Absolute value, rounded to 15 precision is 143567812363.935\n"
},
{
"code": null,
"e": 4500,
"s": 3262,
"text": "The java.math.BigDecimal.abs() is used to return a BigDecimal whose value is the absolute value of the BigDecimal and whose scale is this.scale().Syntax :public BigDecimal abs()Parameters: The method does not accept any parameters.Return Value: Returns a BigDecimal whose value is the absolute value of this BigDecimal scale is this.scale().Below programs will illustrate the use of java.math.BigDecimal.abs() method :Program 1// Java program to demonstrate abs() methodimport java.io.*;import java.math.*; public class GFG { public static void main(String[] args) { // Creating a BigDecimal object BigDecimal num; // Assigning value to num num = new BigDecimal(\"-51\"); // Displaying the result System.out.println(\"Absolute value is \" + num.abs()); }}Output:Absolute value is 51\nProgram 2// Java program to demonstrate abs() methodimport java.io.*;import java.math.*; public class GFG { public static void main(String[] args) { // creating a BigDecimal object BigDecimal num; // assign value to num num = new BigDecimal(\"-63.93471\"); System.out.println(\"Absolute value is \" + num.abs()); }}Output:Absolute value is 63.93471\n"
},
{
"code": null,
"e": 4509,
"s": 4500,
"text": "Syntax :"
},
{
"code": null,
"e": 4533,
"s": 4509,
"text": "public BigDecimal abs()"
},
{
"code": null,
"e": 4588,
"s": 4533,
"text": "Parameters: The method does not accept any parameters."
},
{
"code": null,
"e": 4699,
"s": 4588,
"text": "Return Value: Returns a BigDecimal whose value is the absolute value of this BigDecimal scale is this.scale()."
},
{
"code": null,
"e": 4786,
"s": 4699,
"text": "Below programs will illustrate the use of java.math.BigDecimal.abs() method :Program 1"
},
{
"code": "// Java program to demonstrate abs() methodimport java.io.*;import java.math.*; public class GFG { public static void main(String[] args) { // Creating a BigDecimal object BigDecimal num; // Assigning value to num num = new BigDecimal(\"-51\"); // Displaying the result System.out.println(\"Absolute value is \" + num.abs()); }}",
"e": 5171,
"s": 4786,
"text": null
},
{
"code": null,
"e": 5193,
"s": 5171,
"text": "Absolute value is 51\n"
},
{
"code": null,
"e": 5203,
"s": 5193,
"text": "Program 2"
},
{
"code": "// Java program to demonstrate abs() methodimport java.io.*;import java.math.*; public class GFG { public static void main(String[] args) { // creating a BigDecimal object BigDecimal num; // assign value to num num = new BigDecimal(\"-63.93471\"); System.out.println(\"Absolute value is \" + num.abs()); }}",
"e": 5559,
"s": 5203,
"text": null
},
{
"code": null,
"e": 5587,
"s": 5559,
"text": "Absolute value is 63.93471\n"
},
{
"code": null,
"e": 7584,
"s": 5587,
"text": "The java.math.BigDecimal.abs(MathContext mc) returns a BigDecimal whose value is the absolute value of the BigDecimal obtained by rounding it off according to the precision settings specified by mc, an object of MathContext class.Syntax:public BigDecimal abs(MathContext mc)Parameters : The function accepts only one parameter mc of MathContext class object, which specifies precision settings to be used for rounding off the BigDecimal.Return Value: Returns a BigDecimal whose value is the absolute value of this BigDecimal obtained by rounding it off according to the precision settings specified by the object mc.Exception : The method throws an ArithmeticException, if the result is inexact but the rounding mode is UNNECESSARY.Below programs illustrate the use of java.math.BigDecimal.abs() method with specified MathContext :Program 1import java.io.*;import java.math.*; public class GFG { public static void main(String[] args) { // Create 2 BigDecimal objects BigDecimal num, absv; MathContext mc = new MathContext(2); // Assign value to num num = new BigDecimal(\"51.93471\"); // Assign absolute value of num to absv rounded // to 2 precision using mc absv = num.abs(mc); System.out.println(\"Absolute value, rounded to 2 precision is \" + absv); }}Output:Absolute value, rounded to 2 precision is 52\nProgram 2import java.io.*;import java.math.*; public class GFG { public static void main(String[] args) { // Create 2 BigDecimal objects BigDecimal num, absv; MathContext mc = new MathContext(15); // Assign value to num num = new BigDecimal(\"143567812363.93471\"); // Assign absolute value of num to absv rounded // to 15 precision using mc absv = num.abs(mc); System.out.println(\"Absolute value, rounded to 15 precision is \" + absv); }}Output:Absolute value, rounded to 15 precision is 143567812363.935\n"
},
{
"code": null,
"e": 7592,
"s": 7584,
"text": "Syntax:"
},
{
"code": null,
"e": 7630,
"s": 7592,
"text": "public BigDecimal abs(MathContext mc)"
},
{
"code": null,
"e": 7794,
"s": 7630,
"text": "Parameters : The function accepts only one parameter mc of MathContext class object, which specifies precision settings to be used for rounding off the BigDecimal."
},
{
"code": null,
"e": 7974,
"s": 7794,
"text": "Return Value: Returns a BigDecimal whose value is the absolute value of this BigDecimal obtained by rounding it off according to the precision settings specified by the object mc."
},
{
"code": null,
"e": 8091,
"s": 7974,
"text": "Exception : The method throws an ArithmeticException, if the result is inexact but the rounding mode is UNNECESSARY."
},
{
"code": null,
"e": 8200,
"s": 8091,
"text": "Below programs illustrate the use of java.math.BigDecimal.abs() method with specified MathContext :Program 1"
},
{
"code": "import java.io.*;import java.math.*; public class GFG { public static void main(String[] args) { // Create 2 BigDecimal objects BigDecimal num, absv; MathContext mc = new MathContext(2); // Assign value to num num = new BigDecimal(\"51.93471\"); // Assign absolute value of num to absv rounded // to 2 precision using mc absv = num.abs(mc); System.out.println(\"Absolute value, rounded to 2 precision is \" + absv); }}",
"e": 8708,
"s": 8200,
"text": null
},
{
"code": null,
"e": 8754,
"s": 8708,
"text": "Absolute value, rounded to 2 precision is 52\n"
},
{
"code": null,
"e": 8764,
"s": 8754,
"text": "Program 2"
},
{
"code": "import java.io.*;import java.math.*; public class GFG { public static void main(String[] args) { // Create 2 BigDecimal objects BigDecimal num, absv; MathContext mc = new MathContext(15); // Assign value to num num = new BigDecimal(\"143567812363.93471\"); // Assign absolute value of num to absv rounded // to 15 precision using mc absv = num.abs(mc); System.out.println(\"Absolute value, rounded to 15 precision is \" + absv); }}",
"e": 9286,
"s": 8764,
"text": null
},
{
"code": null,
"e": 9347,
"s": 9286,
"text": "Absolute value, rounded to 15 precision is 143567812363.935\n"
},
{
"code": null,
"e": 9432,
"s": 9347,
"text": "Reference: https://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#abs()"
},
{
"code": null,
"e": 9448,
"s": 9432,
"text": "Java-BigDecimal"
},
{
"code": null,
"e": 9463,
"s": 9448,
"text": "Java-Functions"
},
{
"code": null,
"e": 9481,
"s": 9463,
"text": "Java-lang package"
},
{
"code": null,
"e": 9491,
"s": 9481,
"text": "java-math"
},
{
"code": null,
"e": 9509,
"s": 9491,
"text": "Java-math-package"
},
{
"code": null,
"e": 9514,
"s": 9509,
"text": "Java"
},
{
"code": null,
"e": 9519,
"s": 9514,
"text": "Java"
},
{
"code": null,
"e": 9617,
"s": 9519,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 9668,
"s": 9617,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 9699,
"s": 9668,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 9718,
"s": 9699,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 9748,
"s": 9718,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 9766,
"s": 9748,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 9786,
"s": 9766,
"text": "Collections in Java"
},
{
"code": null,
"e": 9818,
"s": 9786,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 9833,
"s": 9818,
"text": "Stream In Java"
},
{
"code": null,
"e": 9845,
"s": 9833,
"text": "Set in Java"
}
] |
Setting up local DNS server between client-server machines | 05 Mar, 2021
In this, article you will see the overview of DNS server and how to set up the local DNS server between the client and server machines. And here we will use Wireshark. Let’s discuss it one by one.
Introduction :A DNS server is computer server that contains a database of public IP addresses and their associated hostname, and in most cases serves to resolve, or translate, those names to IP addresses as requested. DNS servers run special software and communicate with each other using special protocols.
To set up the DNS server we need two virtual machines, here, we will implement with the help of 2 Ubuntu virtual machines running on my laptop and I named the server virtual machine as Ubuntu and the client virtual machine as Ubuntu client. To understand how DNS server works we use Wireshark packet capture to see how the request is handled by the DNS server.
Step-1 :Installing Wireshark on Server virtual machine :
In this, you can use given below command to Install Wireshark with this command. After installing Wireshark we will start setting up the DNS server.
sudo apt-get install wireshark
Step-2 :Configuring client virtual machine :
We need to add the IP Address of the custom DNS server to the client machine. This is done by adding the IP address of the server to the file /etc/resolv.conf which stores the order of DNS server resolution. This ensures that the custom DNS server will be used to resolve names. To find the IP Address of the server virtual machine first go to server virtual machine and this command in the terminal
ifconfig
The value after the inet is IP Address in my case my IP address of the server machine is 10.0.2.15.
Now, go the client virtual machine and in the terminal run this command and enter user password to open that file.
sudo gedit /etc/resolv.conf
You will find the screen similar to this, Now add this line in the first line of the file and save it.
nameserver 10.0.2.15
Note – Change 10.0.2.15 to your server machine IP Address in my case my server IP Address is 10.0.2.15.
Step-3 :Configuring Server virtual machine :
To set up the DNS server we need a software called bind9, bind9 server is used as the DNS server on the server virtual machine. It can be installed using the below command.
sudo apt-get install bind9
After installing bind9 Let’s check the status of the bind9 server whether it’s running or not with this command.
sudo service bind9 status
If you see active (running) then we are good to go, If you see something else like failure or stopped or inactive type this command and restart your server virtual machine this will fix the issue.
sudo service bind9 restart
Now, we just finished setting up the local DNS server now we are going to see how it works.
Step-4 :Performing the packet capture with Wireshark :
Go to the server virtual machine and open terminal and type this command to open the Wireshark.
Note – Open Wireshark with admin privilege using sudo command as shown below this command.
sudo wireshark
After Wireshark gets opened double click on any or click on any and right click and click on start capture.
Now quickly go to Client virtual machine and open terminal and ping any website for example, ping www.flipkart.com
ping www.flipkart.com
After 15 or 20 seconds press <CRTL> + C to stop the pinging the www.flipkart.com.
Now go to the server virtual machine and stop the capturing of the Wireshark by pressing the red button on top left side of the panel this will stop the capturing of the Wireshark.
Now, type DNS on apply display filter and press enter.
Now, Observe the first frame of the packet capture in Fig 7, source is IP address of the client virtual machine and the destination is the IP address of the server which implies that the client is sending request to the server virtual machine to get the results for the webpage www.flipkart.com
Now, observe the frame number 191, source is IP address of the server virtual machine and the destination is the IP address of the client virtual machine which implies that the server virtual machine sending the response to the client virtual machine.
Technical Scripter 2020
Computer Networks
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GSM in Wireless Communication
Secure Socket Layer (SSL)
Wireless Application Protocol
Mobile Internet Protocol (or Mobile IP)
Advanced Encryption Standard (AES)
Introduction of Mobile Ad hoc Network (MANET)
Intrusion Detection System (IDS)
Cryptography and its Types
Difference between URL and URI
Dynamic Host Configuration Protocol (DHCP) | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n05 Mar, 2021"
},
{
"code": null,
"e": 250,
"s": 52,
"text": "In this, article you will see the overview of DNS server and how to set up the local DNS server between the client and server machines. And here we will use Wireshark. Let’s discuss it one by one. "
},
{
"code": null,
"e": 558,
"s": 250,
"text": "Introduction :A DNS server is computer server that contains a database of public IP addresses and their associated hostname, and in most cases serves to resolve, or translate, those names to IP addresses as requested. DNS servers run special software and communicate with each other using special protocols."
},
{
"code": null,
"e": 919,
"s": 558,
"text": "To set up the DNS server we need two virtual machines, here, we will implement with the help of 2 Ubuntu virtual machines running on my laptop and I named the server virtual machine as Ubuntu and the client virtual machine as Ubuntu client. To understand how DNS server works we use Wireshark packet capture to see how the request is handled by the DNS server."
},
{
"code": null,
"e": 976,
"s": 919,
"text": "Step-1 :Installing Wireshark on Server virtual machine :"
},
{
"code": null,
"e": 1125,
"s": 976,
"text": "In this, you can use given below command to Install Wireshark with this command. After installing Wireshark we will start setting up the DNS server."
},
{
"code": null,
"e": 1156,
"s": 1125,
"text": "sudo apt-get install wireshark"
},
{
"code": null,
"e": 1201,
"s": 1156,
"text": "Step-2 :Configuring client virtual machine :"
},
{
"code": null,
"e": 1601,
"s": 1201,
"text": "We need to add the IP Address of the custom DNS server to the client machine. This is done by adding the IP address of the server to the file /etc/resolv.conf which stores the order of DNS server resolution. This ensures that the custom DNS server will be used to resolve names. To find the IP Address of the server virtual machine first go to server virtual machine and this command in the terminal"
},
{
"code": null,
"e": 1610,
"s": 1601,
"text": "ifconfig"
},
{
"code": null,
"e": 1710,
"s": 1610,
"text": "The value after the inet is IP Address in my case my IP address of the server machine is 10.0.2.15."
},
{
"code": null,
"e": 1825,
"s": 1710,
"text": "Now, go the client virtual machine and in the terminal run this command and enter user password to open that file."
},
{
"code": null,
"e": 1853,
"s": 1825,
"text": "sudo gedit /etc/resolv.conf"
},
{
"code": null,
"e": 1956,
"s": 1853,
"text": "You will find the screen similar to this, Now add this line in the first line of the file and save it."
},
{
"code": null,
"e": 1977,
"s": 1956,
"text": "nameserver 10.0.2.15"
},
{
"code": null,
"e": 2081,
"s": 1977,
"text": "Note – Change 10.0.2.15 to your server machine IP Address in my case my server IP Address is 10.0.2.15."
},
{
"code": null,
"e": 2126,
"s": 2081,
"text": "Step-3 :Configuring Server virtual machine :"
},
{
"code": null,
"e": 2299,
"s": 2126,
"text": "To set up the DNS server we need a software called bind9, bind9 server is used as the DNS server on the server virtual machine. It can be installed using the below command."
},
{
"code": null,
"e": 2326,
"s": 2299,
"text": "sudo apt-get install bind9"
},
{
"code": null,
"e": 2439,
"s": 2326,
"text": "After installing bind9 Let’s check the status of the bind9 server whether it’s running or not with this command."
},
{
"code": null,
"e": 2465,
"s": 2439,
"text": "sudo service bind9 status"
},
{
"code": null,
"e": 2662,
"s": 2465,
"text": "If you see active (running) then we are good to go, If you see something else like failure or stopped or inactive type this command and restart your server virtual machine this will fix the issue."
},
{
"code": null,
"e": 2689,
"s": 2662,
"text": "sudo service bind9 restart"
},
{
"code": null,
"e": 2781,
"s": 2689,
"text": "Now, we just finished setting up the local DNS server now we are going to see how it works."
},
{
"code": null,
"e": 2836,
"s": 2781,
"text": "Step-4 :Performing the packet capture with Wireshark :"
},
{
"code": null,
"e": 2932,
"s": 2836,
"text": "Go to the server virtual machine and open terminal and type this command to open the Wireshark."
},
{
"code": null,
"e": 3023,
"s": 2932,
"text": "Note – Open Wireshark with admin privilege using sudo command as shown below this command."
},
{
"code": null,
"e": 3038,
"s": 3023,
"text": "sudo wireshark"
},
{
"code": null,
"e": 3146,
"s": 3038,
"text": "After Wireshark gets opened double click on any or click on any and right click and click on start capture."
},
{
"code": null,
"e": 3262,
"s": 3146,
"text": "Now quickly go to Client virtual machine and open terminal and ping any website for example, ping www.flipkart.com "
},
{
"code": null,
"e": 3284,
"s": 3262,
"text": "ping www.flipkart.com"
},
{
"code": null,
"e": 3366,
"s": 3284,
"text": "After 15 or 20 seconds press <CRTL> + C to stop the pinging the www.flipkart.com."
},
{
"code": null,
"e": 3547,
"s": 3366,
"text": "Now go to the server virtual machine and stop the capturing of the Wireshark by pressing the red button on top left side of the panel this will stop the capturing of the Wireshark."
},
{
"code": null,
"e": 3602,
"s": 3547,
"text": "Now, type DNS on apply display filter and press enter."
},
{
"code": null,
"e": 3897,
"s": 3602,
"text": "Now, Observe the first frame of the packet capture in Fig 7, source is IP address of the client virtual machine and the destination is the IP address of the server which implies that the client is sending request to the server virtual machine to get the results for the webpage www.flipkart.com"
},
{
"code": null,
"e": 4149,
"s": 3897,
"text": "Now, observe the frame number 191, source is IP address of the server virtual machine and the destination is the IP address of the client virtual machine which implies that the server virtual machine sending the response to the client virtual machine."
},
{
"code": null,
"e": 4173,
"s": 4149,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 4191,
"s": 4173,
"text": "Computer Networks"
},
{
"code": null,
"e": 4209,
"s": 4191,
"text": "Computer Networks"
},
{
"code": null,
"e": 4307,
"s": 4209,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4337,
"s": 4307,
"text": "GSM in Wireless Communication"
},
{
"code": null,
"e": 4363,
"s": 4337,
"text": "Secure Socket Layer (SSL)"
},
{
"code": null,
"e": 4393,
"s": 4363,
"text": "Wireless Application Protocol"
},
{
"code": null,
"e": 4433,
"s": 4393,
"text": "Mobile Internet Protocol (or Mobile IP)"
},
{
"code": null,
"e": 4468,
"s": 4433,
"text": "Advanced Encryption Standard (AES)"
},
{
"code": null,
"e": 4514,
"s": 4468,
"text": "Introduction of Mobile Ad hoc Network (MANET)"
},
{
"code": null,
"e": 4547,
"s": 4514,
"text": "Intrusion Detection System (IDS)"
},
{
"code": null,
"e": 4574,
"s": 4547,
"text": "Cryptography and its Types"
},
{
"code": null,
"e": 4605,
"s": 4574,
"text": "Difference between URL and URI"
}
] |
Minimum value of distance of farthest node in a Graph | 09 Aug, 2021
Given an acyclic undirected graph having N nodes and N-1 edges in the form of a 2D array arr[][] in which every row consists of two numbers L and R which denotes the edge between L and R. For every node X in the tree, let dis(X) denotes the number of edges from X to the farthest node. The task is to find the minimum value of dis(x) for the given graph.
Examples:
Input: N = 6, arr[][] = { {1, 4}, {2, 3}, {3, 4}, {4, 5}, {5, 6} } Output: 2 Explanation: Below is the graph from the above information:
As we can see from the above graph the farthest node from vertex 0 is at distance 3. By repeating the DFS traversal for all the node in the graph, we have maximum distance[] from source node to farthest node as: distance[] = {3, 4, 3, 2, 3, 4} and the minimum of the distances is the required result.
Input: N = 6, arr[][] = { {1, 2}, {1, 3}, {1, 4}, {2, 5}, {2, 6} } Output: 2 Explanation: The distance[] from every node to farthest node for the above graph is: distance[] = {3, 4, 3, 2, 3, 4} and the minimum of the distances is 1.
Approach: The idea is to use DFS Traversal to solve this problem. Below are the steps:
For any Node(say a) traverse the graph using DFS Traversal with the distance of node with itself as 0.For every recursive call for Node a, keep updating the distance of the recursive node with the node a in an array(say distance[]).By taking the maximum of the distance with every recursive call for Node a give the number of edges between the nodes a and it’s farthest node.Repeat the above steps for all the node in the graph and keep updating the farthest node distance from every node in the distance array(distance[]).The minimum value of the array distance[] is the desired result.
For any Node(say a) traverse the graph using DFS Traversal with the distance of node with itself as 0.
For every recursive call for Node a, keep updating the distance of the recursive node with the node a in an array(say distance[]).
By taking the maximum of the distance with every recursive call for Node a give the number of edges between the nodes a and it’s farthest node.
Repeat the above steps for all the node in the graph and keep updating the farthest node distance from every node in the distance array(distance[]).
The minimum value of the array distance[] is the desired result.
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; // Distance vector to find the distance of// a node to it's farthest nodevector<int> dist; // To keep the track of visited array// while DFS Traversalvector<int> vis; // Function for DFS traversal to update// the distance vectorvoid dfs(int u, vector<int> Adj[], int s){ // Mark the visited array for vertex u vis[u] = true; // Traverse the adjacency list for u for (auto& it : Adj[u]) { // If the any node is not visited, // then recursively call for next // vertex with distance increment // by 1 if (vis[it] == false) { dfs(it, Adj, s + 1); } } // Update the maximum distance for the // farthest vertex from node u dist[u] = max(dist[u], s);} // Function to find the minimum of the// farthest vertex for every vertex in// the graphvoid minFarthestDistance(int arr[][2], int n){ // Resize distance vector dist.resize(n + 1, 0); // To create adjacency list for graph vector<int> Adj[n + 1]; // Create Adjacency list for every // edge given in arr[][] for (int i = 0; i < n - 1; i++) { Adj[arr[i][0]].push_back(arr[i][1]); Adj[arr[i][1]].push_back(arr[i][0]); } // DFS Traversal for every node in the // graph to update the distance vector for (int i = 1; i <= n; i++) { // Clear and resize vis[] before // DFS traversal for every vertex vis.clear(); vis.resize(n + 1, false); // DFS Traversal for vertex i dfs(i, Adj, 0); } cout << *min_element(dist.begin() + 1, dist.end());} // Driver Codeint main(){ // Number of Nodes int N = 6; int arr[][2] = { { 1, 4 }, { 2, 3 }, { 3, 4 }, { 4, 5 }, { 5, 6 } }; minFarthestDistance(arr, N); return 0;}
// Java program for the above approachimport java.util.*; class GFG{ // Distance vector to find the distance// of a node to it's farthest nodestatic int[] dist; // To keep the track of visited array// while DFS Traversalstatic boolean[] vis; // Function for DFS traversal to update// the distance vectorstatic void dfs(int u, Vector<Integer>[] Adj, int s){ // Mark the visited array for vertex u vis[u] = true; // Traverse the adjacency list for u for (int it : Adj[u]) { // If the any node is not visited, // then recursively call for next // vertex with distance increment // by 1 if (vis[it] == false) { dfs(it, Adj, s + 1); } } // Update the maximum distance for // the farthest vertex from node u dist[u] = Math.max(dist[u], s);} // Function to find the minimum of the// farthest vertex for every vertex in// the graphstatic void minFarthestDistance(int[][] arr, int n){ // Resize distance vector dist = new int[n + 1]; Arrays.fill(dist, 0); // To create adjacency list for graph @SuppressWarnings("unchecked") Vector<Integer>[] Adj = new Vector[n + 1]; for(int i = 0; i < n + 1; i++) { Adj[i] = new Vector<>(); } // Create Adjacency list for every // edge given in arr[][] for(int i = 0; i < n - 1; i++) { Adj[arr[i][0]].add(arr[i][1]); Adj[arr[i][1]].add(arr[i][0]); } // DFS Traversal for every node in the // graph to update the distance vector for(int i = 1; i <= n; i++) { // Clear and resize vis[] before // DFS traversal for every vertex vis = new boolean[n + 1]; Arrays.fill(vis, false); // DFS Traversal for vertex i dfs(i, Adj, 0); } int min = Integer.MAX_VALUE; for(int i = 1; i < dist.length; i++) { if (dist[i] < min) min = dist[i]; } System.out.println(min);} // Driver Codepublic static void main(String[] args){ // Number of Nodes int N = 6; int[][] arr = { { 1, 4 }, { 2, 3 }, { 3, 4 }, { 4, 5 }, { 5, 6 } }; minFarthestDistance(arr, N);}} // This code is contributed by sanjeev2552
# Python3 program for the above approach # Function for DFS traversal to update# the distance vectordef dfs(u, s): global vis, Adj, dist # Mark the visited array for vertex u vis[u] = True # Traverse the adjacency list for u for it in Adj[u]: # If the any node is not visited, # then recursively call for next # vertex with distance increment # by 1 if (vis[it] == False): dfs(it, s + 1) # Update the maximum distance for the # farthest vertex from node u dist[u] = max(dist[u], s) # Function to find the minimum of the# farthest vertex for every vertex in# the graphdef minFarthestDistance(arr, n): global dist, vis, Adj # Create Adjacency list for every # edge given in arr[][] for i in range(n - 1): Adj[arr[i][0]].append(arr[i][1]) Adj[arr[i][1]].append(arr[i][0]) # DFS Traversal for every node in the # graph to update the distance vector for i in range(1, n + 1): # Clear and resize vis[] before # DFS traversal for every vertex # vis.clear() for j in range(n + 1): vis[j] = False # vis.resize(n + 1, false) # DFS Traversal for vertex i dfs(i, 0) print(min(dist[i] for i in range(1, n + 1))) # Driver Codeif __name__ == '__main__': dist = [0 for i in range(1001)] vis = [False for i in range(1001)] Adj = [[] for i in range(1001)] # Number of Nodes N = 6 arr = [ [ 1, 4 ], [ 2, 3 ], [ 3, 4 ], [ 4, 5 ], [ 5, 6 ] ] minFarthestDistance(arr, N) # This code is contributed by mohit kumar 29
// C# program for the above approachusing System;using System.Collections.Generic;class GFG{ // Distance vector to find the distance // of a node to it's farthest node static int[] dist; // To keep the track of visited array // while DFS Traversal static bool[] vis; // Function for DFS traversal to update // the distance vector static void dfs(int u, List<List<int>> Adj, int s) { // Mark the visited array for vertex u vis[u] = true; // Traverse the adjacency list for u foreach(int it in Adj[u]) { // If the any node is not visited, // then recursively call for next // vertex with distance increment // by 1 if (vis[it] == false) { dfs(it, Adj, s + 1); } } // Update the maximum distance for // the farthest vertex from node u dist[u] = Math.Max(dist[u], s); } // Function to find the minimum of the // farthest vertex for every vertex in // the graph static void minFarthestDistance(int[,] arr, int n) { // Resize distance vector dist = new int[n + 1]; Array.Fill(dist, 0); // To create adjacency list for graph List<List<int>> Adj = new List<List<int>>(); for(int i = 0; i < n + 1; i++) { Adj.Add(new List<int>()); } // Create Adjacency list for every // edge given in arr[][] for(int i = 0; i < n - 1; i++) { Adj[arr[i, 0]].Add(arr[i, 1]); Adj[arr[i, 1]].Add(arr[i, 0]); } // DFS Traversal for every node in the // graph to update the distance vector for(int i = 1; i <= n; i++) { // Clear and resize vis[] before // DFS traversal for every vertex vis = new bool[n + 1]; Array.Fill(vis, false); // DFS Traversal for vertex i dfs(i, Adj, 0); } int min = Int32.MaxValue; for(int i = 1; i < dist.Length; i++) { if (dist[i] < min) { min = dist[i]; } } Console.WriteLine(min); } // Driver Code static public void Main () { // Number of Nodes int N = 6; int[,] arr = { { 1, 4 }, { 2, 3 },{ 3, 4 }, { 4, 5 }, { 5, 6 } }; minFarthestDistance(arr, N); }} // This code is contributed by rag2127
<script>// Javascript program for the above approach // Distance vector to find the distance// of a node to it's farthest nodelet dist=[]; // To keep the track of visited array// while DFS Traversallet vis=[]; // Function for DFS traversal to update// the distance vectorfunction dfs(u,Adj,s){ // Mark the visited array for vertex u vis[u] = true; // Traverse the adjacency list for u for (let it=0;it<Adj[u].length;it++) { // If the any node is not visited, // then recursively call for next // vertex with distance increment // by 1 if (vis[Adj[u][it]] == false) { dfs(Adj[u][it], Adj, s + 1); } } // Update the maximum distance for // the farthest vertex from node u dist[u] = Math.max(dist[u], s);} // Function to find the minimum of the// farthest vertex for every vertex in// the graphfunction minFarthestDistance(arr,n){ // Resize distance vector dist = new Array(n + 1); for(let i=0;i<(n+1);i++) { dist[i]=0; } // To create adjacency list for graph let Adj = new Array(n + 1); for(let i = 0; i < n + 1; i++) { Adj[i] = []; } // Create Adjacency list for every // edge given in arr[][] for(let i = 0; i < n - 1; i++) { Adj[arr[i][0]].push(arr[i][1]); Adj[arr[i][1]].push(arr[i][0]); } // DFS Traversal for every node in the // graph to update the distance vector for(let i = 1; i <= n; i++) { // Clear and resize vis[] before // DFS traversal for every vertex vis = new Array(n + 1); for(let i=0;i<(n+1);i++) { vis[i]=false; } // DFS Traversal for vertex i dfs(i, Adj, 0); } let min = Number.MAX_VALUE; for(let i = 1; i < dist.length; i++) { if (dist[i] < min) min = dist[i]; } document.write(min);} // Driver Code// Number of Nodeslet N = 6;let arr=[[ 1, 4 ], [ 2, 3 ], [ 3, 4 ], [ 4, 5 ], [ 5, 6 ]];minFarthestDistance(arr, N); // This code is contributed by patel2127</script>
2
Time Complexity: O(V*(V+E)), where V is the number of vertices and E is the number of edges. Auxiliary Space: O(V + E)
sanjeev2552
mohit kumar 29
rag2127
patel2127
pankajsharmagfg
DFS
Algorithms
Competitive Programming
Graph
DFS
Graph
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete
Hash Functions and list/types of Hash functions
How to Start Learning DSA?
Complete Roadmap To Learn DSA From Scratch
Minimum cost to reach the top of the floor by climbing stairs
Competitive Programming - A Complete Guide
Practice for cracking any coding interview
Count of longest possible subarrays with sum not divisible by K
Top Programming Languages For Competitive Programming
Arrow operator -> in C/C++ with Examples | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n09 Aug, 2021"
},
{
"code": null,
"e": 407,
"s": 52,
"text": "Given an acyclic undirected graph having N nodes and N-1 edges in the form of a 2D array arr[][] in which every row consists of two numbers L and R which denotes the edge between L and R. For every node X in the tree, let dis(X) denotes the number of edges from X to the farthest node. The task is to find the minimum value of dis(x) for the given graph."
},
{
"code": null,
"e": 419,
"s": 407,
"text": "Examples: "
},
{
"code": null,
"e": 558,
"s": 419,
"text": "Input: N = 6, arr[][] = { {1, 4}, {2, 3}, {3, 4}, {4, 5}, {5, 6} } Output: 2 Explanation: Below is the graph from the above information: "
},
{
"code": null,
"e": 860,
"s": 558,
"text": "As we can see from the above graph the farthest node from vertex 0 is at distance 3. By repeating the DFS traversal for all the node in the graph, we have maximum distance[] from source node to farthest node as: distance[] = {3, 4, 3, 2, 3, 4} and the minimum of the distances is the required result. "
},
{
"code": null,
"e": 1094,
"s": 860,
"text": "Input: N = 6, arr[][] = { {1, 2}, {1, 3}, {1, 4}, {2, 5}, {2, 6} } Output: 2 Explanation: The distance[] from every node to farthest node for the above graph is: distance[] = {3, 4, 3, 2, 3, 4} and the minimum of the distances is 1. "
},
{
"code": null,
"e": 1183,
"s": 1094,
"text": "Approach: The idea is to use DFS Traversal to solve this problem. Below are the steps: "
},
{
"code": null,
"e": 1771,
"s": 1183,
"text": "For any Node(say a) traverse the graph using DFS Traversal with the distance of node with itself as 0.For every recursive call for Node a, keep updating the distance of the recursive node with the node a in an array(say distance[]).By taking the maximum of the distance with every recursive call for Node a give the number of edges between the nodes a and it’s farthest node.Repeat the above steps for all the node in the graph and keep updating the farthest node distance from every node in the distance array(distance[]).The minimum value of the array distance[] is the desired result."
},
{
"code": null,
"e": 1874,
"s": 1771,
"text": "For any Node(say a) traverse the graph using DFS Traversal with the distance of node with itself as 0."
},
{
"code": null,
"e": 2005,
"s": 1874,
"text": "For every recursive call for Node a, keep updating the distance of the recursive node with the node a in an array(say distance[])."
},
{
"code": null,
"e": 2149,
"s": 2005,
"text": "By taking the maximum of the distance with every recursive call for Node a give the number of edges between the nodes a and it’s farthest node."
},
{
"code": null,
"e": 2298,
"s": 2149,
"text": "Repeat the above steps for all the node in the graph and keep updating the farthest node distance from every node in the distance array(distance[])."
},
{
"code": null,
"e": 2363,
"s": 2298,
"text": "The minimum value of the array distance[] is the desired result."
},
{
"code": null,
"e": 2416,
"s": 2363,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 2420,
"s": 2416,
"text": "C++"
},
{
"code": null,
"e": 2425,
"s": 2420,
"text": "Java"
},
{
"code": null,
"e": 2433,
"s": 2425,
"text": "Python3"
},
{
"code": null,
"e": 2436,
"s": 2433,
"text": "C#"
},
{
"code": null,
"e": 2447,
"s": 2436,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Distance vector to find the distance of// a node to it's farthest nodevector<int> dist; // To keep the track of visited array// while DFS Traversalvector<int> vis; // Function for DFS traversal to update// the distance vectorvoid dfs(int u, vector<int> Adj[], int s){ // Mark the visited array for vertex u vis[u] = true; // Traverse the adjacency list for u for (auto& it : Adj[u]) { // If the any node is not visited, // then recursively call for next // vertex with distance increment // by 1 if (vis[it] == false) { dfs(it, Adj, s + 1); } } // Update the maximum distance for the // farthest vertex from node u dist[u] = max(dist[u], s);} // Function to find the minimum of the// farthest vertex for every vertex in// the graphvoid minFarthestDistance(int arr[][2], int n){ // Resize distance vector dist.resize(n + 1, 0); // To create adjacency list for graph vector<int> Adj[n + 1]; // Create Adjacency list for every // edge given in arr[][] for (int i = 0; i < n - 1; i++) { Adj[arr[i][0]].push_back(arr[i][1]); Adj[arr[i][1]].push_back(arr[i][0]); } // DFS Traversal for every node in the // graph to update the distance vector for (int i = 1; i <= n; i++) { // Clear and resize vis[] before // DFS traversal for every vertex vis.clear(); vis.resize(n + 1, false); // DFS Traversal for vertex i dfs(i, Adj, 0); } cout << *min_element(dist.begin() + 1, dist.end());} // Driver Codeint main(){ // Number of Nodes int N = 6; int arr[][2] = { { 1, 4 }, { 2, 3 }, { 3, 4 }, { 4, 5 }, { 5, 6 } }; minFarthestDistance(arr, N); return 0;}",
"e": 4314,
"s": 2447,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.*; class GFG{ // Distance vector to find the distance// of a node to it's farthest nodestatic int[] dist; // To keep the track of visited array// while DFS Traversalstatic boolean[] vis; // Function for DFS traversal to update// the distance vectorstatic void dfs(int u, Vector<Integer>[] Adj, int s){ // Mark the visited array for vertex u vis[u] = true; // Traverse the adjacency list for u for (int it : Adj[u]) { // If the any node is not visited, // then recursively call for next // vertex with distance increment // by 1 if (vis[it] == false) { dfs(it, Adj, s + 1); } } // Update the maximum distance for // the farthest vertex from node u dist[u] = Math.max(dist[u], s);} // Function to find the minimum of the// farthest vertex for every vertex in// the graphstatic void minFarthestDistance(int[][] arr, int n){ // Resize distance vector dist = new int[n + 1]; Arrays.fill(dist, 0); // To create adjacency list for graph @SuppressWarnings(\"unchecked\") Vector<Integer>[] Adj = new Vector[n + 1]; for(int i = 0; i < n + 1; i++) { Adj[i] = new Vector<>(); } // Create Adjacency list for every // edge given in arr[][] for(int i = 0; i < n - 1; i++) { Adj[arr[i][0]].add(arr[i][1]); Adj[arr[i][1]].add(arr[i][0]); } // DFS Traversal for every node in the // graph to update the distance vector for(int i = 1; i <= n; i++) { // Clear and resize vis[] before // DFS traversal for every vertex vis = new boolean[n + 1]; Arrays.fill(vis, false); // DFS Traversal for vertex i dfs(i, Adj, 0); } int min = Integer.MAX_VALUE; for(int i = 1; i < dist.length; i++) { if (dist[i] < min) min = dist[i]; } System.out.println(min);} // Driver Codepublic static void main(String[] args){ // Number of Nodes int N = 6; int[][] arr = { { 1, 4 }, { 2, 3 }, { 3, 4 }, { 4, 5 }, { 5, 6 } }; minFarthestDistance(arr, N);}} // This code is contributed by sanjeev2552",
"e": 6552,
"s": 4314,
"text": null
},
{
"code": "# Python3 program for the above approach # Function for DFS traversal to update# the distance vectordef dfs(u, s): global vis, Adj, dist # Mark the visited array for vertex u vis[u] = True # Traverse the adjacency list for u for it in Adj[u]: # If the any node is not visited, # then recursively call for next # vertex with distance increment # by 1 if (vis[it] == False): dfs(it, s + 1) # Update the maximum distance for the # farthest vertex from node u dist[u] = max(dist[u], s) # Function to find the minimum of the# farthest vertex for every vertex in# the graphdef minFarthestDistance(arr, n): global dist, vis, Adj # Create Adjacency list for every # edge given in arr[][] for i in range(n - 1): Adj[arr[i][0]].append(arr[i][1]) Adj[arr[i][1]].append(arr[i][0]) # DFS Traversal for every node in the # graph to update the distance vector for i in range(1, n + 1): # Clear and resize vis[] before # DFS traversal for every vertex # vis.clear() for j in range(n + 1): vis[j] = False # vis.resize(n + 1, false) # DFS Traversal for vertex i dfs(i, 0) print(min(dist[i] for i in range(1, n + 1))) # Driver Codeif __name__ == '__main__': dist = [0 for i in range(1001)] vis = [False for i in range(1001)] Adj = [[] for i in range(1001)] # Number of Nodes N = 6 arr = [ [ 1, 4 ], [ 2, 3 ], [ 3, 4 ], [ 4, 5 ], [ 5, 6 ] ] minFarthestDistance(arr, N) # This code is contributed by mohit kumar 29",
"e": 8205,
"s": 6552,
"text": null
},
{
"code": "// C# program for the above approachusing System;using System.Collections.Generic;class GFG{ // Distance vector to find the distance // of a node to it's farthest node static int[] dist; // To keep the track of visited array // while DFS Traversal static bool[] vis; // Function for DFS traversal to update // the distance vector static void dfs(int u, List<List<int>> Adj, int s) { // Mark the visited array for vertex u vis[u] = true; // Traverse the adjacency list for u foreach(int it in Adj[u]) { // If the any node is not visited, // then recursively call for next // vertex with distance increment // by 1 if (vis[it] == false) { dfs(it, Adj, s + 1); } } // Update the maximum distance for // the farthest vertex from node u dist[u] = Math.Max(dist[u], s); } // Function to find the minimum of the // farthest vertex for every vertex in // the graph static void minFarthestDistance(int[,] arr, int n) { // Resize distance vector dist = new int[n + 1]; Array.Fill(dist, 0); // To create adjacency list for graph List<List<int>> Adj = new List<List<int>>(); for(int i = 0; i < n + 1; i++) { Adj.Add(new List<int>()); } // Create Adjacency list for every // edge given in arr[][] for(int i = 0; i < n - 1; i++) { Adj[arr[i, 0]].Add(arr[i, 1]); Adj[arr[i, 1]].Add(arr[i, 0]); } // DFS Traversal for every node in the // graph to update the distance vector for(int i = 1; i <= n; i++) { // Clear and resize vis[] before // DFS traversal for every vertex vis = new bool[n + 1]; Array.Fill(vis, false); // DFS Traversal for vertex i dfs(i, Adj, 0); } int min = Int32.MaxValue; for(int i = 1; i < dist.Length; i++) { if (dist[i] < min) { min = dist[i]; } } Console.WriteLine(min); } // Driver Code static public void Main () { // Number of Nodes int N = 6; int[,] arr = { { 1, 4 }, { 2, 3 },{ 3, 4 }, { 4, 5 }, { 5, 6 } }; minFarthestDistance(arr, N); }} // This code is contributed by rag2127",
"e": 10379,
"s": 8205,
"text": null
},
{
"code": "<script>// Javascript program for the above approach // Distance vector to find the distance// of a node to it's farthest nodelet dist=[]; // To keep the track of visited array// while DFS Traversallet vis=[]; // Function for DFS traversal to update// the distance vectorfunction dfs(u,Adj,s){ // Mark the visited array for vertex u vis[u] = true; // Traverse the adjacency list for u for (let it=0;it<Adj[u].length;it++) { // If the any node is not visited, // then recursively call for next // vertex with distance increment // by 1 if (vis[Adj[u][it]] == false) { dfs(Adj[u][it], Adj, s + 1); } } // Update the maximum distance for // the farthest vertex from node u dist[u] = Math.max(dist[u], s);} // Function to find the minimum of the// farthest vertex for every vertex in// the graphfunction minFarthestDistance(arr,n){ // Resize distance vector dist = new Array(n + 1); for(let i=0;i<(n+1);i++) { dist[i]=0; } // To create adjacency list for graph let Adj = new Array(n + 1); for(let i = 0; i < n + 1; i++) { Adj[i] = []; } // Create Adjacency list for every // edge given in arr[][] for(let i = 0; i < n - 1; i++) { Adj[arr[i][0]].push(arr[i][1]); Adj[arr[i][1]].push(arr[i][0]); } // DFS Traversal for every node in the // graph to update the distance vector for(let i = 1; i <= n; i++) { // Clear and resize vis[] before // DFS traversal for every vertex vis = new Array(n + 1); for(let i=0;i<(n+1);i++) { vis[i]=false; } // DFS Traversal for vertex i dfs(i, Adj, 0); } let min = Number.MAX_VALUE; for(let i = 1; i < dist.length; i++) { if (dist[i] < min) min = dist[i]; } document.write(min);} // Driver Code// Number of Nodeslet N = 6;let arr=[[ 1, 4 ], [ 2, 3 ], [ 3, 4 ], [ 4, 5 ], [ 5, 6 ]];minFarthestDistance(arr, N); // This code is contributed by patel2127</script>",
"e": 12522,
"s": 10379,
"text": null
},
{
"code": null,
"e": 12524,
"s": 12522,
"text": "2"
},
{
"code": null,
"e": 12645,
"s": 12526,
"text": "Time Complexity: O(V*(V+E)), where V is the number of vertices and E is the number of edges. Auxiliary Space: O(V + E)"
},
{
"code": null,
"e": 12657,
"s": 12645,
"text": "sanjeev2552"
},
{
"code": null,
"e": 12672,
"s": 12657,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 12680,
"s": 12672,
"text": "rag2127"
},
{
"code": null,
"e": 12690,
"s": 12680,
"text": "patel2127"
},
{
"code": null,
"e": 12706,
"s": 12690,
"text": "pankajsharmagfg"
},
{
"code": null,
"e": 12710,
"s": 12706,
"text": "DFS"
},
{
"code": null,
"e": 12721,
"s": 12710,
"text": "Algorithms"
},
{
"code": null,
"e": 12745,
"s": 12721,
"text": "Competitive Programming"
},
{
"code": null,
"e": 12751,
"s": 12745,
"text": "Graph"
},
{
"code": null,
"e": 12755,
"s": 12751,
"text": "DFS"
},
{
"code": null,
"e": 12761,
"s": 12755,
"text": "Graph"
},
{
"code": null,
"e": 12772,
"s": 12761,
"text": "Algorithms"
},
{
"code": null,
"e": 12870,
"s": 12772,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 12937,
"s": 12870,
"text": "Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete"
},
{
"code": null,
"e": 12985,
"s": 12937,
"text": "Hash Functions and list/types of Hash functions"
},
{
"code": null,
"e": 13012,
"s": 12985,
"text": "How to Start Learning DSA?"
},
{
"code": null,
"e": 13055,
"s": 13012,
"text": "Complete Roadmap To Learn DSA From Scratch"
},
{
"code": null,
"e": 13117,
"s": 13055,
"text": "Minimum cost to reach the top of the floor by climbing stairs"
},
{
"code": null,
"e": 13160,
"s": 13117,
"text": "Competitive Programming - A Complete Guide"
},
{
"code": null,
"e": 13203,
"s": 13160,
"text": "Practice for cracking any coding interview"
},
{
"code": null,
"e": 13267,
"s": 13203,
"text": "Count of longest possible subarrays with sum not divisible by K"
},
{
"code": null,
"e": 13321,
"s": 13267,
"text": "Top Programming Languages For Competitive Programming"
}
] |
Turning a Dictionary into XML in Python | 01 Sep, 2021
XML stands for Extensible Markup Language. XML was designed to be self-descriptive and to store and transport data. XML tags are used to identify, store and organize the data. The basic building block of an XML document is defined by tags. An element has a beginning tag and an ending tag. All elements in an XML are contained in an outermost element called as the root element.
Example:
<geeksforgeeks>
<course>DSA</course>
<price>2499/-</price>
</geeksforgeeks>
In the above example, geeksforgeeks is the root element and <course>, <price>, <price> are the elements.
Now, let’s see how to Turn a Dictionary into XML:For turning a Dictionary into XML in Python we will use xml.etree.ElementTree library. The xml.etree.ElementTree library is usually used for parsing and also utilized in creating XML documents. The ElementTree class is employed to wrap a component structure and convert it from and to XML. The result of this conversion is an Element. For I/O, it’s easy to convert this to a byte string using the tostring() function in xml.etree.ElementTree.
This Element class defines the Element interface, and provides a reference implementation of this interface.
Syntax: Element(tag, attrib = {}, **extra)
Parameter:
tag: This is a string that identify what kind of data this element represents.
attrib: this is an optional dictionary, containing element attributes.
**extra: This contains additional attributes, given as keyword arguments.
Return: Element object
This function Generates a string representation of an XML element.
Syntax: tostring(element)
Parameter: XML element
Return: string representation of an XML element
This method Set the attribute key on the element to value.
Syntax: set(key, value)
Parameter:
key: represent the attribute.
value: represent value of attribute.
Return: None
Now, let’s see the python program for Turning a Dictionary into XML:
Python3
# import Element class, tostring function# from xml.etree.ElementTree libraryfrom xml.etree.ElementTree import Element,tostring # define a function to# convert a simple dictionary# of key/value pairs into XMLdef dict_to_xml(tag, d): elem = Element(tag) for key, val in d.items(): # create an Element # class object child = Element(key) child.text = str(val) elem.append(child) return elem # Driver Programs = { 'name': 'geeksforgeeks', 'city': 'noida', 'stock': 920 } # e stores the element instancee = dict_to_xml('company', s) # Element instance is different# every time you run the codeprint(e) # converting into a byte stringprint(tostring(e)) # We can attach attributes# to an element using# set() methode.set('_id','1000') print(tostring(e))
Output:
<Element ‘company’ at 0x7f411a9bd048> b'<company><name>geeksforgeeks</name><city>noida</city><stock>920</stock></company>’ b'<company _id=”1000′′><name>geeksforgeeks</name><city>noida</city><stock>920</stock></company>’
clintra
kalrap615
sumitgumber28
python-modules
Python-XML
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Convert integer to string in Python | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 Sep, 2021"
},
{
"code": null,
"e": 407,
"s": 28,
"text": "XML stands for Extensible Markup Language. XML was designed to be self-descriptive and to store and transport data. XML tags are used to identify, store and organize the data. The basic building block of an XML document is defined by tags. An element has a beginning tag and an ending tag. All elements in an XML are contained in an outermost element called as the root element."
},
{
"code": null,
"e": 417,
"s": 407,
"text": "Example: "
},
{
"code": null,
"e": 493,
"s": 417,
"text": "<geeksforgeeks>\n<course>DSA</course>\n<price>2499/-</price>\n</geeksforgeeks>"
},
{
"code": null,
"e": 598,
"s": 493,
"text": "In the above example, geeksforgeeks is the root element and <course>, <price>, <price> are the elements."
},
{
"code": null,
"e": 1090,
"s": 598,
"text": "Now, let’s see how to Turn a Dictionary into XML:For turning a Dictionary into XML in Python we will use xml.etree.ElementTree library. The xml.etree.ElementTree library is usually used for parsing and also utilized in creating XML documents. The ElementTree class is employed to wrap a component structure and convert it from and to XML. The result of this conversion is an Element. For I/O, it’s easy to convert this to a byte string using the tostring() function in xml.etree.ElementTree."
},
{
"code": null,
"e": 1200,
"s": 1090,
"text": "This Element class defines the Element interface, and provides a reference implementation of this interface. "
},
{
"code": null,
"e": 1244,
"s": 1200,
"text": "Syntax: Element(tag, attrib = {}, **extra) "
},
{
"code": null,
"e": 1256,
"s": 1244,
"text": "Parameter: "
},
{
"code": null,
"e": 1335,
"s": 1256,
"text": "tag: This is a string that identify what kind of data this element represents."
},
{
"code": null,
"e": 1406,
"s": 1335,
"text": "attrib: this is an optional dictionary, containing element attributes."
},
{
"code": null,
"e": 1480,
"s": 1406,
"text": "**extra: This contains additional attributes, given as keyword arguments."
},
{
"code": null,
"e": 1504,
"s": 1480,
"text": "Return: Element object "
},
{
"code": null,
"e": 1572,
"s": 1504,
"text": "This function Generates a string representation of an XML element. "
},
{
"code": null,
"e": 1598,
"s": 1572,
"text": "Syntax: tostring(element)"
},
{
"code": null,
"e": 1621,
"s": 1598,
"text": "Parameter: XML element"
},
{
"code": null,
"e": 1669,
"s": 1621,
"text": "Return: string representation of an XML element"
},
{
"code": null,
"e": 1729,
"s": 1669,
"text": "This method Set the attribute key on the element to value. "
},
{
"code": null,
"e": 1754,
"s": 1729,
"text": "Syntax: set(key, value) "
},
{
"code": null,
"e": 1766,
"s": 1754,
"text": "Parameter: "
},
{
"code": null,
"e": 1796,
"s": 1766,
"text": "key: represent the attribute."
},
{
"code": null,
"e": 1833,
"s": 1796,
"text": "value: represent value of attribute."
},
{
"code": null,
"e": 1847,
"s": 1833,
"text": "Return: None "
},
{
"code": null,
"e": 1916,
"s": 1847,
"text": "Now, let’s see the python program for Turning a Dictionary into XML:"
},
{
"code": null,
"e": 1924,
"s": 1916,
"text": "Python3"
},
{
"code": "# import Element class, tostring function# from xml.etree.ElementTree libraryfrom xml.etree.ElementTree import Element,tostring # define a function to# convert a simple dictionary# of key/value pairs into XMLdef dict_to_xml(tag, d): elem = Element(tag) for key, val in d.items(): # create an Element # class object child = Element(key) child.text = str(val) elem.append(child) return elem # Driver Programs = { 'name': 'geeksforgeeks', 'city': 'noida', 'stock': 920 } # e stores the element instancee = dict_to_xml('company', s) # Element instance is different# every time you run the codeprint(e) # converting into a byte stringprint(tostring(e)) # We can attach attributes# to an element using# set() methode.set('_id','1000') print(tostring(e))",
"e": 2730,
"s": 1924,
"text": null
},
{
"code": null,
"e": 2739,
"s": 2730,
"text": "Output: "
},
{
"code": null,
"e": 2961,
"s": 2739,
"text": "<Element ‘company’ at 0x7f411a9bd048> b'<company><name>geeksforgeeks</name><city>noida</city><stock>920</stock></company>’ b'<company _id=”1000′′><name>geeksforgeeks</name><city>noida</city><stock>920</stock></company>’ "
},
{
"code": null,
"e": 2969,
"s": 2961,
"text": "clintra"
},
{
"code": null,
"e": 2979,
"s": 2969,
"text": "kalrap615"
},
{
"code": null,
"e": 2993,
"s": 2979,
"text": "sumitgumber28"
},
{
"code": null,
"e": 3008,
"s": 2993,
"text": "python-modules"
},
{
"code": null,
"e": 3019,
"s": 3008,
"text": "Python-XML"
},
{
"code": null,
"e": 3026,
"s": 3019,
"text": "Python"
},
{
"code": null,
"e": 3124,
"s": 3026,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3142,
"s": 3124,
"text": "Python Dictionary"
},
{
"code": null,
"e": 3184,
"s": 3142,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 3206,
"s": 3184,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 3241,
"s": 3206,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 3267,
"s": 3241,
"text": "Python String | replace()"
},
{
"code": null,
"e": 3299,
"s": 3267,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3328,
"s": 3299,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 3355,
"s": 3328,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3385,
"s": 3355,
"text": "Iterate over a list in Python"
}
] |
Sorting a Hashmap according to values | 06 Apr, 2022
Given marks scored out of 100 by a student in subjects where the name of the subject is key and marks scored is the value. Our task is to sort the hashmap according to values i.e. according to marks.Example:
Input : Key = Math, Value = 98
Key = Data Structure, Value = 85
Key = Database, Value = 91
Key = Java, Value = 95
Key = Operating System, Value = 79
Key = Networking, Value = 80
Output : Key = Operating System, Value = 79
Key = Networking, Value = 80
Key = Data Structure, Value = 85
Key = Database, Value = 91
Key = Java, Value = 95
Key = Math, Value = 98
Solution: The idea is to store the entry set in a list and sort the list on the basis of values. Then fetch values and keys from the list and put them in a new hashmap. Thus, a new hashmap is sorted according to values.Below is the implementation of the above idea:
Java
// Java program to sort hashmap by valuesimport java.util.*;import java.lang.*; public class GFG { // function to sort hashmap by values public static HashMap<String, Integer> sortByValue(HashMap<String, Integer> hm) { // Create a list from elements of HashMap List<Map.Entry<String, Integer> > list = new LinkedList<Map.Entry<String, Integer> >(hm.entrySet()); // Sort the list Collections.sort(list, new Comparator<Map.Entry<String, Integer> >() { public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) { return (o1.getValue()).compareTo(o2.getValue()); } }); // put data from sorted list to hashmap HashMap<String, Integer> temp = new LinkedHashMap<String, Integer>(); for (Map.Entry<String, Integer> aa : list) { temp.put(aa.getKey(), aa.getValue()); } return temp; } // Driver Code public static void main(String[] args) { HashMap<String, Integer> hm = new HashMap<String, Integer>(); // enter data into hashmap hm.put("Math", 98); hm.put("Data Structure", 85); hm.put("Database", 91); hm.put("Java", 95); hm.put("Operating System", 79); hm.put("Networking", 80); Map<String, Integer> hm1 = sortByValue(hm); // print the sorted hashmap for (Map.Entry<String, Integer> en : hm1.entrySet()) { System.out.println("Key = " + en.getKey() + ", Value = " + en.getValue()); } }}
Key = Operating System, Value = 79
Key = Networking, Value = 80
Key = Data Structure, Value = 85
Key = Database, Value = 91
Key = Java, Value = 95
Key = Math, Value = 98
Using Java 8 Lambdas
Here we will change how we did sorting and will use lambda expression for sorting. The logic is the same, and even we also passed the comparator object but only using lambda.
Below is the implementation of the above approach:
Java
// Java program to sort hashmap by valuesimport java.lang.*;import java.util.*; public class GFG { // function to sort hashmap by values public static HashMap<String, Integer> sortByValue(HashMap<String, Integer> hm) { // Create a list from elements of HashMap List<Map.Entry<String, Integer> > list = new LinkedList<Map.Entry<String, Integer> >( hm.entrySet()); // Sort the list using lambda expression Collections.sort( list, (i1, i2) -> i1.getValue().compareTo(i2.getValue())); // put data from sorted list to hashmap HashMap<String, Integer> temp = new LinkedHashMap<String, Integer>(); for (Map.Entry<String, Integer> aa : list) { temp.put(aa.getKey(), aa.getValue()); } return temp; } // Driver Code public static void main(String[] args) { HashMap<String, Integer> hm = new HashMap<String, Integer>(); // enter data into hashmap hm.put("Math", 98); hm.put("Data Structure", 85); hm.put("Database", 91); hm.put("Java", 95); hm.put("Operating System", 79); hm.put("Networking", 80); Map<String, Integer> hm1 = sortByValue(hm); // print the sorted hashmap for (Map.Entry<String, Integer> en : hm1.entrySet()) { System.out.println("Key = " + en.getKey() + ", Value = " + en.getValue()); } }}
Key = Operating System, Value = 79
Key = Networking, Value = 80
Key = Data Structure, Value = 85
Key = Database, Value = 91
Key = Java, Value = 95
Key = Math, Value = 98
Using Streams in Java 8
Here we will use streams to sort the map. We will use the stream() method to get the stream of entrySet followed by the lambda expression inside sorted() method to sort the stream and finally, we will convert it into a map using toMap() method. Inside the toMap() method, we use the LinkedHashMap::new method reference to retain the sorted order of the map.
Java
// Java program to sort hashmap by valuesimport static java.util.stream.Collectors.*; import java.lang.*;import java.util.*;import java.util.stream.*;import java.util.stream.Collectors;public class gfg3 { // function to sort hashmap by values public static HashMap<String, Integer> sortByValue(HashMap<String, Integer> hm) { HashMap<String, Integer> temp = hm.entrySet() .stream() .sorted((i1, i2) -> i1.getValue().compareTo( i2.getValue())) .collect(Collectors.toMap( Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new)); return temp; } // Driver Code public static void main(String[] args) { HashMap<String, Integer> hm = new HashMap<String, Integer>(); // enter data into hashmap hm.put("Math", 98); hm.put("Data Structure", 85); hm.put("Database", 91); hm.put("Java", 95); hm.put("Operating System", 79); hm.put("Networking", 80); Map<String, Integer> hm1 = sortByValue(hm); // print the sorted hashmap for (Map.Entry<String, Integer> en : hm1.entrySet()) { System.out.println("Key = " + en.getKey() + ", Value = " + en.getValue()); } }}
Key = Operating System, Value = 79
Key = Networking, Value = 80
Key = Data Structure, Value = 85
Key = Database, Value = 91
Key = Java, Value = 95
Key = Math, Value = 98
rajatagrawal5
sagartomar9927
Java-Collections
Java-HashMap
java-LinkedList
Java-Map-Programs
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Interfaces in Java
Stream In Java
ArrayList in Java
Collections in Java
Singleton Class in Java
Stack Class in Java
Initializing a List in Java
Introduction to Java
Multithreading in Java
Constructors in Java | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n06 Apr, 2022"
},
{
"code": null,
"e": 262,
"s": 52,
"text": "Given marks scored out of 100 by a student in subjects where the name of the subject is key and marks scored is the value. Our task is to sort the hashmap according to values i.e. according to marks.Example: "
},
{
"code": null,
"e": 705,
"s": 262,
"text": "Input : Key = Math, Value = 98\n Key = Data Structure, Value = 85\n Key = Database, Value = 91\n Key = Java, Value = 95\n Key = Operating System, Value = 79\n Key = Networking, Value = 80\n\nOutput : Key = Operating System, Value = 79\n Key = Networking, Value = 80\n Key = Data Structure, Value = 85\n Key = Database, Value = 91\n Key = Java, Value = 95\n Key = Math, Value = 98"
},
{
"code": null,
"e": 973,
"s": 705,
"text": "Solution: The idea is to store the entry set in a list and sort the list on the basis of values. Then fetch values and keys from the list and put them in a new hashmap. Thus, a new hashmap is sorted according to values.Below is the implementation of the above idea: "
},
{
"code": null,
"e": 978,
"s": 973,
"text": "Java"
},
{
"code": "// Java program to sort hashmap by valuesimport java.util.*;import java.lang.*; public class GFG { // function to sort hashmap by values public static HashMap<String, Integer> sortByValue(HashMap<String, Integer> hm) { // Create a list from elements of HashMap List<Map.Entry<String, Integer> > list = new LinkedList<Map.Entry<String, Integer> >(hm.entrySet()); // Sort the list Collections.sort(list, new Comparator<Map.Entry<String, Integer> >() { public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) { return (o1.getValue()).compareTo(o2.getValue()); } }); // put data from sorted list to hashmap HashMap<String, Integer> temp = new LinkedHashMap<String, Integer>(); for (Map.Entry<String, Integer> aa : list) { temp.put(aa.getKey(), aa.getValue()); } return temp; } // Driver Code public static void main(String[] args) { HashMap<String, Integer> hm = new HashMap<String, Integer>(); // enter data into hashmap hm.put(\"Math\", 98); hm.put(\"Data Structure\", 85); hm.put(\"Database\", 91); hm.put(\"Java\", 95); hm.put(\"Operating System\", 79); hm.put(\"Networking\", 80); Map<String, Integer> hm1 = sortByValue(hm); // print the sorted hashmap for (Map.Entry<String, Integer> en : hm1.entrySet()) { System.out.println(\"Key = \" + en.getKey() + \", Value = \" + en.getValue()); } }}",
"e": 2612,
"s": 978,
"text": null
},
{
"code": null,
"e": 2782,
"s": 2612,
"text": "Key = Operating System, Value = 79\nKey = Networking, Value = 80\nKey = Data Structure, Value = 85\nKey = Database, Value = 91\nKey = Java, Value = 95\nKey = Math, Value = 98"
},
{
"code": null,
"e": 2804,
"s": 2782,
"text": " Using Java 8 Lambdas"
},
{
"code": null,
"e": 2979,
"s": 2804,
"text": "Here we will change how we did sorting and will use lambda expression for sorting. The logic is the same, and even we also passed the comparator object but only using lambda."
},
{
"code": null,
"e": 3030,
"s": 2979,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 3035,
"s": 3030,
"text": "Java"
},
{
"code": "// Java program to sort hashmap by valuesimport java.lang.*;import java.util.*; public class GFG { // function to sort hashmap by values public static HashMap<String, Integer> sortByValue(HashMap<String, Integer> hm) { // Create a list from elements of HashMap List<Map.Entry<String, Integer> > list = new LinkedList<Map.Entry<String, Integer> >( hm.entrySet()); // Sort the list using lambda expression Collections.sort( list, (i1, i2) -> i1.getValue().compareTo(i2.getValue())); // put data from sorted list to hashmap HashMap<String, Integer> temp = new LinkedHashMap<String, Integer>(); for (Map.Entry<String, Integer> aa : list) { temp.put(aa.getKey(), aa.getValue()); } return temp; } // Driver Code public static void main(String[] args) { HashMap<String, Integer> hm = new HashMap<String, Integer>(); // enter data into hashmap hm.put(\"Math\", 98); hm.put(\"Data Structure\", 85); hm.put(\"Database\", 91); hm.put(\"Java\", 95); hm.put(\"Operating System\", 79); hm.put(\"Networking\", 80); Map<String, Integer> hm1 = sortByValue(hm); // print the sorted hashmap for (Map.Entry<String, Integer> en : hm1.entrySet()) { System.out.println(\"Key = \" + en.getKey() + \", Value = \" + en.getValue()); } }}",
"e": 4587,
"s": 3035,
"text": null
},
{
"code": null,
"e": 4757,
"s": 4587,
"text": "Key = Operating System, Value = 79\nKey = Networking, Value = 80\nKey = Data Structure, Value = 85\nKey = Database, Value = 91\nKey = Java, Value = 95\nKey = Math, Value = 98"
},
{
"code": null,
"e": 4781,
"s": 4757,
"text": "Using Streams in Java 8"
},
{
"code": null,
"e": 5139,
"s": 4781,
"text": "Here we will use streams to sort the map. We will use the stream() method to get the stream of entrySet followed by the lambda expression inside sorted() method to sort the stream and finally, we will convert it into a map using toMap() method. Inside the toMap() method, we use the LinkedHashMap::new method reference to retain the sorted order of the map."
},
{
"code": null,
"e": 5144,
"s": 5139,
"text": "Java"
},
{
"code": "// Java program to sort hashmap by valuesimport static java.util.stream.Collectors.*; import java.lang.*;import java.util.*;import java.util.stream.*;import java.util.stream.Collectors;public class gfg3 { // function to sort hashmap by values public static HashMap<String, Integer> sortByValue(HashMap<String, Integer> hm) { HashMap<String, Integer> temp = hm.entrySet() .stream() .sorted((i1, i2) -> i1.getValue().compareTo( i2.getValue())) .collect(Collectors.toMap( Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new)); return temp; } // Driver Code public static void main(String[] args) { HashMap<String, Integer> hm = new HashMap<String, Integer>(); // enter data into hashmap hm.put(\"Math\", 98); hm.put(\"Data Structure\", 85); hm.put(\"Database\", 91); hm.put(\"Java\", 95); hm.put(\"Operating System\", 79); hm.put(\"Networking\", 80); Map<String, Integer> hm1 = sortByValue(hm); // print the sorted hashmap for (Map.Entry<String, Integer> en : hm1.entrySet()) { System.out.println(\"Key = \" + en.getKey() + \", Value = \" + en.getValue()); } }}",
"e": 6622,
"s": 5144,
"text": null
},
{
"code": null,
"e": 6792,
"s": 6622,
"text": "Key = Operating System, Value = 79\nKey = Networking, Value = 80\nKey = Data Structure, Value = 85\nKey = Database, Value = 91\nKey = Java, Value = 95\nKey = Math, Value = 98"
},
{
"code": null,
"e": 6806,
"s": 6792,
"text": "rajatagrawal5"
},
{
"code": null,
"e": 6821,
"s": 6806,
"text": "sagartomar9927"
},
{
"code": null,
"e": 6838,
"s": 6821,
"text": "Java-Collections"
},
{
"code": null,
"e": 6851,
"s": 6838,
"text": "Java-HashMap"
},
{
"code": null,
"e": 6867,
"s": 6851,
"text": "java-LinkedList"
},
{
"code": null,
"e": 6885,
"s": 6867,
"text": "Java-Map-Programs"
},
{
"code": null,
"e": 6890,
"s": 6885,
"text": "Java"
},
{
"code": null,
"e": 6895,
"s": 6890,
"text": "Java"
},
{
"code": null,
"e": 6912,
"s": 6895,
"text": "Java-Collections"
},
{
"code": null,
"e": 7010,
"s": 6912,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7029,
"s": 7010,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 7044,
"s": 7029,
"text": "Stream In Java"
},
{
"code": null,
"e": 7062,
"s": 7044,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 7082,
"s": 7062,
"text": "Collections in Java"
},
{
"code": null,
"e": 7106,
"s": 7082,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 7126,
"s": 7106,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 7154,
"s": 7126,
"text": "Initializing a List in Java"
},
{
"code": null,
"e": 7175,
"s": 7154,
"text": "Introduction to Java"
},
{
"code": null,
"e": 7198,
"s": 7175,
"text": "Multithreading in Java"
}
] |
How to display black navigation bar in Bootstrap ? | 24 Aug, 2021
A navigation bar is used in every website to make it more user-friendly so that the navigation through the website becomes easy and the user can directly search for the topic of their interest. There are two following ways to display a black navigation bar.
Using .navbar-dark and .bg-dark classes: The .navbar-dark class of bootstrap makes the text in the navbar white and the .bg-dark class makes the background color of the navbar class black.
Example:
HTML
<!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"/> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script> </head> <body> <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <a class="navbar-brand" href="#">Geeksforgeeks</a> <div class="collapse navbar-collapse"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="#">Home</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Course</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Job Portal</a> </li> </ul> <form class="form-inline my-2 my-lg-0"> <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search"/> <button class="btn btn-light my-2 my-sm-0" type="submit"> Search </button> </form> </div> </nav> </body></html>
Output:
Output
Setting background color using style property: We can set the background color of the navbar by using the style property of the <nav>tag.
Example:
HTML
<!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"/> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script> </head> <body> <nav class="navbar navbar-expand-lg navbar-dark" style="background-color: black" > <a class="navbar-brand" href="#">Geeksforgeeks</a> <div class="collapse navbar-collapse"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="#">Home</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Course</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Job Portal</a> </li> </ul> <form class="form-inline my-2 my-lg-0"> <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search"/> <button class="btn btn-light my-2 my-sm-0" type="submit"> Search </button> </form> </div> </nav> </body></html>
Output:
Bootstrap-Questions
HTML-Questions
Picked
Bootstrap
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Show Images on Click using HTML ?
How to Use Bootstrap with React?
How to set vertical alignment in Bootstrap ?
Tailwind CSS vs Bootstrap
How to toggle password visibility in forms using Bootstrap-icons ?
How to update Node.js and NPM to next version ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
REST API (Introduction)
Hide or show elements in HTML using display property | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n24 Aug, 2021"
},
{
"code": null,
"e": 286,
"s": 28,
"text": "A navigation bar is used in every website to make it more user-friendly so that the navigation through the website becomes easy and the user can directly search for the topic of their interest. There are two following ways to display a black navigation bar."
},
{
"code": null,
"e": 475,
"s": 286,
"text": "Using .navbar-dark and .bg-dark classes: The .navbar-dark class of bootstrap makes the text in the navbar white and the .bg-dark class makes the background color of the navbar class black."
},
{
"code": null,
"e": 484,
"s": 475,
"text": "Example:"
},
{
"code": null,
"e": 489,
"s": 484,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"utf-8\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" /> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"/> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script> </head> <body> <nav class=\"navbar navbar-expand-lg navbar-dark bg-dark\"> <a class=\"navbar-brand\" href=\"#\">Geeksforgeeks</a> <div class=\"collapse navbar-collapse\"> <ul class=\"navbar-nav mr-auto\"> <li class=\"nav-item active\"> <a class=\"nav-link\" href=\"#\">Home</a> </li> <li class=\"nav-item\"> <a class=\"nav-link\" href=\"#\">Course</a> </li> <li class=\"nav-item\"> <a class=\"nav-link\" href=\"#\">Job Portal</a> </li> </ul> <form class=\"form-inline my-2 my-lg-0\"> <input class=\"form-control mr-sm-2\" type=\"search\" placeholder=\"Search\" aria-label=\"Search\"/> <button class=\"btn btn-light my-2 my-sm-0\" type=\"submit\"> Search </button> </form> </div> </nav> </body></html>",
"e": 1958,
"s": 489,
"text": null
},
{
"code": null,
"e": 1966,
"s": 1958,
"text": "Output:"
},
{
"code": null,
"e": 1973,
"s": 1966,
"text": "Output"
},
{
"code": null,
"e": 2114,
"s": 1975,
"text": "Setting background color using style property: We can set the background color of the navbar by using the style property of the <nav>tag."
},
{
"code": null,
"e": 2123,
"s": 2114,
"text": "Example:"
},
{
"code": null,
"e": 2128,
"s": 2123,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"utf-8\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" /> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"/> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script> </head> <body> <nav class=\"navbar navbar-expand-lg navbar-dark\" style=\"background-color: black\" > <a class=\"navbar-brand\" href=\"#\">Geeksforgeeks</a> <div class=\"collapse navbar-collapse\"> <ul class=\"navbar-nav mr-auto\"> <li class=\"nav-item active\"> <a class=\"nav-link\" href=\"#\">Home</a> </li> <li class=\"nav-item\"> <a class=\"nav-link\" href=\"#\">Course</a> </li> <li class=\"nav-item\"> <a class=\"nav-link\" href=\"#\">Job Portal</a> </li> </ul> <form class=\"form-inline my-2 my-lg-0\"> <input class=\"form-control mr-sm-2\" type=\"search\" placeholder=\"Search\" aria-label=\"Search\"/> <button class=\"btn btn-light my-2 my-sm-0\" type=\"submit\"> Search </button> </form> </div> </nav> </body></html>",
"e": 3627,
"s": 2128,
"text": null
},
{
"code": null,
"e": 3635,
"s": 3627,
"text": "Output:"
},
{
"code": null,
"e": 3655,
"s": 3635,
"text": "Bootstrap-Questions"
},
{
"code": null,
"e": 3670,
"s": 3655,
"text": "HTML-Questions"
},
{
"code": null,
"e": 3677,
"s": 3670,
"text": "Picked"
},
{
"code": null,
"e": 3687,
"s": 3677,
"text": "Bootstrap"
},
{
"code": null,
"e": 3692,
"s": 3687,
"text": "HTML"
},
{
"code": null,
"e": 3709,
"s": 3692,
"text": "Web Technologies"
},
{
"code": null,
"e": 3714,
"s": 3709,
"text": "HTML"
},
{
"code": null,
"e": 3812,
"s": 3714,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3853,
"s": 3812,
"text": "How to Show Images on Click using HTML ?"
},
{
"code": null,
"e": 3886,
"s": 3853,
"text": "How to Use Bootstrap with React?"
},
{
"code": null,
"e": 3931,
"s": 3886,
"text": "How to set vertical alignment in Bootstrap ?"
},
{
"code": null,
"e": 3957,
"s": 3931,
"text": "Tailwind CSS vs Bootstrap"
},
{
"code": null,
"e": 4024,
"s": 3957,
"text": "How to toggle password visibility in forms using Bootstrap-icons ?"
},
{
"code": null,
"e": 4072,
"s": 4024,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 4134,
"s": 4072,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 4184,
"s": 4134,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 4208,
"s": 4184,
"text": "REST API (Introduction)"
}
] |
How to generate an XML file dynamically using PHP? | 13 Apr, 2021
A file can be generated using PHP from the database, and it can be done by the static or dynamic method in PHP. Static methods can be called directly – without creating an instance of a class. Here we are going to discuss how to create an XML file dynamically.
The first thing we need to do is fetch the data from the database. For that, we need to write a select query that will fetch all the details from the table.
$result=mysqli_query($con, "Select * from Table_name");
Now we need to create an XML file using DOMDocument in which we will specify the version. DOMDocument represents an entire HTML or XML document, serves as the root of the document tree.
$xml = new DOMDocument("1.0");
Now, we will create elements of the XML document. It will create new element node using createElement() function. It creates a new instance of class DOMElement. This node will not show up in the document unless it is inserted with (e.g.) DOMNode::appendChild().
$fitness=$xml->createElement("users");
Till now, we have created an XML file. So to display this we are going to use an echo tag that shows the data from a file in XML format. To save the XML file we will use the save command.
echo "".$xml->saveXML()."";
The next thing we need to do is fetch the elements from the table. Example: If a table has two elements then it should create two XML elements. For that, we will simply use a while loop inside which there will be mysql_fetch_array function to fetch all the data from the table.Since the database is connected to a local server it won’t run in your ide but once you have made the database it will work fine. To create the database follow the below mentioned procedure
Create a database fitness in mysql using a local server.
Then create a table user.
Then add the columns-uid, uname, email, password, description, role, pic.
Program:
php
<?php$con=mysqli_connect("localhost", "root", "", "fitness"); if(!$con){ echo "DB not Connected...";}else{$result=mysqli_query($con, "Select * from users");if($result>0){$xml = new DOMDocument("1.0"); // It will format the output in xml format otherwise// the output will be in a single row$xml->formatOutput=true;$fitness=$xml->createElement("users");$xml->appendChild($fitness);while($row=mysqli_fetch_array($result)){ $user=$xml->createElement("user"); $fitness->appendChild($user); $uid=$xml->createElement("uid", $row['uid']); $user->appendChild($uid); $uname=$xml->createElement("uname", $row['uname']); $user->appendChild($uname); $email=$xml->createElement("email", $row['email']); $user->appendChild($email); $password=$xml->createElement("password", $row['password']); $user->appendChild($password); $description=$xml->createElement("description", $row['description']); $user->appendChild($description); $role=$xml->createElement("role", $row['role']); $user->appendChild($role); $pic=$xml->createElement("pic", $row['pic']); $user->appendChild($pic); }echo "<xmp>".$xml->saveXML()."</xmp>";$xml->save("report.xml");}else{ echo "error";}}?>
Output:
coolbuddyrock08
HTML and XML
PHP-XML
Picked
PHP
Web Technologies
Web technologies Questions
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n13 Apr, 2021"
},
{
"code": null,
"e": 290,
"s": 28,
"text": "A file can be generated using PHP from the database, and it can be done by the static or dynamic method in PHP. Static methods can be called directly – without creating an instance of a class. Here we are going to discuss how to create an XML file dynamically. "
},
{
"code": null,
"e": 448,
"s": 290,
"text": "The first thing we need to do is fetch the data from the database. For that, we need to write a select query that will fetch all the details from the table. "
},
{
"code": null,
"e": 505,
"s": 448,
"text": "$result=mysqli_query($con, \"Select * from Table_name\"); "
},
{
"code": null,
"e": 692,
"s": 505,
"text": "Now we need to create an XML file using DOMDocument in which we will specify the version. DOMDocument represents an entire HTML or XML document, serves as the root of the document tree. "
},
{
"code": null,
"e": 723,
"s": 692,
"text": "$xml = new DOMDocument(\"1.0\");"
},
{
"code": null,
"e": 986,
"s": 723,
"text": "Now, we will create elements of the XML document. It will create new element node using createElement() function. It creates a new instance of class DOMElement. This node will not show up in the document unless it is inserted with (e.g.) DOMNode::appendChild(). "
},
{
"code": null,
"e": 1025,
"s": 986,
"text": "$fitness=$xml->createElement(\"users\");"
},
{
"code": null,
"e": 1214,
"s": 1025,
"text": "Till now, we have created an XML file. So to display this we are going to use an echo tag that shows the data from a file in XML format. To save the XML file we will use the save command. "
},
{
"code": null,
"e": 1242,
"s": 1214,
"text": "echo \"\".$xml->saveXML().\"\";"
},
{
"code": null,
"e": 1711,
"s": 1242,
"text": "The next thing we need to do is fetch the elements from the table. Example: If a table has two elements then it should create two XML elements. For that, we will simply use a while loop inside which there will be mysql_fetch_array function to fetch all the data from the table.Since the database is connected to a local server it won’t run in your ide but once you have made the database it will work fine. To create the database follow the below mentioned procedure "
},
{
"code": null,
"e": 1768,
"s": 1711,
"text": "Create a database fitness in mysql using a local server."
},
{
"code": null,
"e": 1794,
"s": 1768,
"text": "Then create a table user."
},
{
"code": null,
"e": 1868,
"s": 1794,
"text": "Then add the columns-uid, uname, email, password, description, role, pic."
},
{
"code": null,
"e": 1878,
"s": 1868,
"text": "Program: "
},
{
"code": null,
"e": 1882,
"s": 1878,
"text": "php"
},
{
"code": "<?php$con=mysqli_connect(\"localhost\", \"root\", \"\", \"fitness\"); if(!$con){ echo \"DB not Connected...\";}else{$result=mysqli_query($con, \"Select * from users\");if($result>0){$xml = new DOMDocument(\"1.0\"); // It will format the output in xml format otherwise// the output will be in a single row$xml->formatOutput=true;$fitness=$xml->createElement(\"users\");$xml->appendChild($fitness);while($row=mysqli_fetch_array($result)){ $user=$xml->createElement(\"user\"); $fitness->appendChild($user); $uid=$xml->createElement(\"uid\", $row['uid']); $user->appendChild($uid); $uname=$xml->createElement(\"uname\", $row['uname']); $user->appendChild($uname); $email=$xml->createElement(\"email\", $row['email']); $user->appendChild($email); $password=$xml->createElement(\"password\", $row['password']); $user->appendChild($password); $description=$xml->createElement(\"description\", $row['description']); $user->appendChild($description); $role=$xml->createElement(\"role\", $row['role']); $user->appendChild($role); $pic=$xml->createElement(\"pic\", $row['pic']); $user->appendChild($pic); }echo \"<xmp>\".$xml->saveXML().\"</xmp>\";$xml->save(\"report.xml\");}else{ echo \"error\";}}?>",
"e": 3126,
"s": 1882,
"text": null
},
{
"code": null,
"e": 3136,
"s": 3126,
"text": "Output: "
},
{
"code": null,
"e": 3154,
"s": 3138,
"text": "coolbuddyrock08"
},
{
"code": null,
"e": 3167,
"s": 3154,
"text": "HTML and XML"
},
{
"code": null,
"e": 3175,
"s": 3167,
"text": "PHP-XML"
},
{
"code": null,
"e": 3182,
"s": 3175,
"text": "Picked"
},
{
"code": null,
"e": 3186,
"s": 3182,
"text": "PHP"
},
{
"code": null,
"e": 3203,
"s": 3186,
"text": "Web Technologies"
},
{
"code": null,
"e": 3230,
"s": 3203,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 3234,
"s": 3230,
"text": "PHP"
}
] |
Interchange elements of first and last rows in matrix - GeeksforGeeks | 06 May, 2021
Given a 4 x 4 matrix, we have to interchange the elements of first and last row and show the resulting matrix.Examples :
Input : 3 4 5 0
2 6 1 2
2 7 1 2
2 1 1 2
Output : 2 1 1 2
2 6 1 2
2 7 1 2
3 4 5 0
Input : 9 7 5 1
2 3 4 1
5 6 6 5
1 2 3 1
Output : 1 2 3 1
2 3 4 1
5 6 6 5
9 7 5 1
The approach is very simple, we can simply swap the elements of first and last row of the matrix inorder to get the desired matrix as output.Below is the implementation of the approach :
C++
Java
Python3
C#
PHP
Javascript
// C++ code to swap the element of first// and last row and display the result#include <iostream>using namespace std; #define n 4 void interchangeFirstLast(int m[][n]){ int rows = n; // swapping of element between first // and last rows for (int i = 0; i < n; i++) { int t = m[0][i]; m[0][i] = m[rows - 1][i]; m[rows - 1][i] = t; }} // Driver functionint main(){ // input in the array int m[n][n] = { { 8, 9, 7, 6 }, { 4, 7, 6, 5 }, { 3, 2, 1, 8 }, { 9, 9, 7, 7 } }; interchangeFirstLast(m); // printing the interchanged matrix for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) cout << m[i][j] << " "; cout << endl; }} // This code is contributed by Anant Agarwal.
// Java code to swap the element of first// and last row and display the resultimport java.io.*; public class Interchange { static void interchangeFirstLast(int m[][]) { int rows = m.length; // swapping of element between first // and last rows for (int i = 0; i < m[0].length; i++) { int t = m[0][i]; m[0][i] = m[rows-1][i]; m[rows-1][i] = t; } } // Driver code public static void main(String args[]) throws IOException { // input in the array int m[][] = { { 8, 9, 7, 6 }, { 4, 7, 6, 5 }, { 3, 2, 1, 8 }, { 9, 9, 7, 7 } }; interchangeFirstLast(m); // printing the interchanged matrix for (int i = 0; i < m.length; i++) { for (int j = 0; j < m[0].length; j++) System.out.print(m[i][j] + " "); System.out.println(); } }}
# Python code to swap the element# of first and last row and display# the result def interchangeFirstLast(mat, n, m): rows = n # swapping of element between # first and last rows for i in range(n): t = mat[0][i] mat[0][i] = mat[rows-1][i] mat[rows-1][i] = t # Driver Programmat = [[8, 9, 7, 6], [4, 7, 6, 5], [3, 2, 1, 8], [9, 9, 7, 7]] n = 4m = 4interchangeFirstLast(mat, n, m) # printing the interchanged matrixfor i in range(n): for j in range(m): print(mat[i][j], end = " ") print("\n") # This code is contributed by Shrikant13.
// C# code to swap the element of first// and last row and display the resultusing System; class GFG{ public static void interchangeFirstLast(int[][] m){ int rows = m.Length; // swapping of element between first // and last rows for (int i = 0; i < m[0].Length; i++) { int t = m[0][i]; m[0][i] = m[rows - 1][i]; m[rows - 1][i] = t; }} // Driver codepublic static void Main(string[] args){ // input in the array int[][] m = new int[][] { new int[] {8, 9, 7, 6}, new int[] {4, 7, 6, 5}, new int[] {3, 2, 1, 8}, new int[] {9, 9, 7, 7} }; interchangeFirstLast(m); // printing the interchanged matrix for (int i = 0; i < m.Length; i++) { for (int j = 0; j < m[0].Length; j++) { Console.Write(m[i][j] + " "); } Console.WriteLine(); }}} // This code is contributed by Shrikant13
<?php// PHP code to swap the element of first// and last row and display the result$n = 4; function interchangeFirstLast(&$m){ global $n; $rows = $n; // swapping of element between first // and last rows for ($i = 0; $i < $n; $i++) { $t = $m[0][$i]; $m[0][$i] = $m[$rows - 1][$i]; $m[$rows - 1][$i] = $t; }} // Driver function // input in the array$m = array(array(8, 9, 7, 6), array(4, 7, 6, 5), array( 3, 2, 1, 8), array(9, 9, 7, 7)); interchangeFirstLast($m); // printing the interchanged matrixfor ($i = 0; $i < $n; $i++){ for ($j = 0; $j < $n; $j++) echo $m[$i][$j] . " "; echo "\n";}?>
<script>// Javascript code to swap the element of first// and last row and display the result function interchangeFirstLast(m) { let rows = m.length; // swapping of element between first // and last rows for (let i = 0; i < m[0].length; i++) { let t = m[0][i]; m[0][i] = m[rows-1][i]; m[rows-1][i] = t; } } // Driver code // input in the array let m = [[8, 9, 7, 6], [4, 7, 6, 5], [3, 2, 1, 8], [9, 9, 7, 7]] interchangeFirstLast(m); // printing the interchanged matrix for (let i = 0; i < m.length; i++) { for (let j = 0; j < m[0].length; j++) document.write(m[i][j] + " "); document.write("<br>"); } // This code is contributed by avanitrachhadiya2155</script>
Output :
9 9 7 7
4 7 6 5
3 2 1 8
8 9 7 6
shrikanth13
ukasp
don283978
avanitrachhadiya2155
Matrix
School Programming
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Sudoku | Backtracking-7
Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)
Program to multiply two matrices
Inplace rotate square matrix by 90 degrees | Set 1
Min Cost Path | DP-6
Python Dictionary
Arrays in C/C++
Reverse a string in Java
Inheritance in C++
Constructors in C++ | [
{
"code": null,
"e": 24654,
"s": 24626,
"text": "\n06 May, 2021"
},
{
"code": null,
"e": 24777,
"s": 24654,
"text": "Given a 4 x 4 matrix, we have to interchange the elements of first and last row and show the resulting matrix.Examples : "
},
{
"code": null,
"e": 25042,
"s": 24777,
"text": "Input : 3 4 5 0\n 2 6 1 2\n 2 7 1 2\n 2 1 1 2\nOutput : 2 1 1 2\n 2 6 1 2\n 2 7 1 2\n 3 4 5 0\n\nInput : 9 7 5 1\n 2 3 4 1\n 5 6 6 5\n 1 2 3 1\nOutput : 1 2 3 1\n 2 3 4 1\n 5 6 6 5\n 9 7 5 1"
},
{
"code": null,
"e": 25233,
"s": 25044,
"text": "The approach is very simple, we can simply swap the elements of first and last row of the matrix inorder to get the desired matrix as output.Below is the implementation of the approach : "
},
{
"code": null,
"e": 25237,
"s": 25233,
"text": "C++"
},
{
"code": null,
"e": 25242,
"s": 25237,
"text": "Java"
},
{
"code": null,
"e": 25250,
"s": 25242,
"text": "Python3"
},
{
"code": null,
"e": 25253,
"s": 25250,
"text": "C#"
},
{
"code": null,
"e": 25257,
"s": 25253,
"text": "PHP"
},
{
"code": null,
"e": 25268,
"s": 25257,
"text": "Javascript"
},
{
"code": "// C++ code to swap the element of first// and last row and display the result#include <iostream>using namespace std; #define n 4 void interchangeFirstLast(int m[][n]){ int rows = n; // swapping of element between first // and last rows for (int i = 0; i < n; i++) { int t = m[0][i]; m[0][i] = m[rows - 1][i]; m[rows - 1][i] = t; }} // Driver functionint main(){ // input in the array int m[n][n] = { { 8, 9, 7, 6 }, { 4, 7, 6, 5 }, { 3, 2, 1, 8 }, { 9, 9, 7, 7 } }; interchangeFirstLast(m); // printing the interchanged matrix for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) cout << m[i][j] << \" \"; cout << endl; }} // This code is contributed by Anant Agarwal.",
"e": 26138,
"s": 25268,
"text": null
},
{
"code": "// Java code to swap the element of first// and last row and display the resultimport java.io.*; public class Interchange { static void interchangeFirstLast(int m[][]) { int rows = m.length; // swapping of element between first // and last rows for (int i = 0; i < m[0].length; i++) { int t = m[0][i]; m[0][i] = m[rows-1][i]; m[rows-1][i] = t; } } // Driver code public static void main(String args[]) throws IOException { // input in the array int m[][] = { { 8, 9, 7, 6 }, { 4, 7, 6, 5 }, { 3, 2, 1, 8 }, { 9, 9, 7, 7 } }; interchangeFirstLast(m); // printing the interchanged matrix for (int i = 0; i < m.length; i++) { for (int j = 0; j < m[0].length; j++) System.out.print(m[i][j] + \" \"); System.out.println(); } }}",
"e": 27133,
"s": 26138,
"text": null
},
{
"code": "# Python code to swap the element# of first and last row and display# the result def interchangeFirstLast(mat, n, m): rows = n # swapping of element between # first and last rows for i in range(n): t = mat[0][i] mat[0][i] = mat[rows-1][i] mat[rows-1][i] = t # Driver Programmat = [[8, 9, 7, 6], [4, 7, 6, 5], [3, 2, 1, 8], [9, 9, 7, 7]] n = 4m = 4interchangeFirstLast(mat, n, m) # printing the interchanged matrixfor i in range(n): for j in range(m): print(mat[i][j], end = \" \") print(\"\\n\") # This code is contributed by Shrikant13.",
"e": 27738,
"s": 27133,
"text": null
},
{
"code": "// C# code to swap the element of first// and last row and display the resultusing System; class GFG{ public static void interchangeFirstLast(int[][] m){ int rows = m.Length; // swapping of element between first // and last rows for (int i = 0; i < m[0].Length; i++) { int t = m[0][i]; m[0][i] = m[rows - 1][i]; m[rows - 1][i] = t; }} // Driver codepublic static void Main(string[] args){ // input in the array int[][] m = new int[][] { new int[] {8, 9, 7, 6}, new int[] {4, 7, 6, 5}, new int[] {3, 2, 1, 8}, new int[] {9, 9, 7, 7} }; interchangeFirstLast(m); // printing the interchanged matrix for (int i = 0; i < m.Length; i++) { for (int j = 0; j < m[0].Length; j++) { Console.Write(m[i][j] + \" \"); } Console.WriteLine(); }}} // This code is contributed by Shrikant13",
"e": 28646,
"s": 27738,
"text": null
},
{
"code": "<?php// PHP code to swap the element of first// and last row and display the result$n = 4; function interchangeFirstLast(&$m){ global $n; $rows = $n; // swapping of element between first // and last rows for ($i = 0; $i < $n; $i++) { $t = $m[0][$i]; $m[0][$i] = $m[$rows - 1][$i]; $m[$rows - 1][$i] = $t; }} // Driver function // input in the array$m = array(array(8, 9, 7, 6), array(4, 7, 6, 5), array( 3, 2, 1, 8), array(9, 9, 7, 7)); interchangeFirstLast($m); // printing the interchanged matrixfor ($i = 0; $i < $n; $i++){ for ($j = 0; $j < $n; $j++) echo $m[$i][$j] . \" \"; echo \"\\n\";}?>",
"e": 29391,
"s": 28646,
"text": null
},
{
"code": "<script>// Javascript code to swap the element of first// and last row and display the result function interchangeFirstLast(m) { let rows = m.length; // swapping of element between first // and last rows for (let i = 0; i < m[0].length; i++) { let t = m[0][i]; m[0][i] = m[rows-1][i]; m[rows-1][i] = t; } } // Driver code // input in the array let m = [[8, 9, 7, 6], [4, 7, 6, 5], [3, 2, 1, 8], [9, 9, 7, 7]] interchangeFirstLast(m); // printing the interchanged matrix for (let i = 0; i < m.length; i++) { for (let j = 0; j < m[0].length; j++) document.write(m[i][j] + \" \"); document.write(\"<br>\"); } // This code is contributed by avanitrachhadiya2155</script>",
"e": 30255,
"s": 29391,
"text": null
},
{
"code": null,
"e": 30266,
"s": 30255,
"text": "Output : "
},
{
"code": null,
"e": 30302,
"s": 30266,
"text": "9 9 7 7 \n4 7 6 5 \n3 2 1 8 \n8 9 7 6 "
},
{
"code": null,
"e": 30316,
"s": 30304,
"text": "shrikanth13"
},
{
"code": null,
"e": 30322,
"s": 30316,
"text": "ukasp"
},
{
"code": null,
"e": 30332,
"s": 30322,
"text": "don283978"
},
{
"code": null,
"e": 30353,
"s": 30332,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 30360,
"s": 30353,
"text": "Matrix"
},
{
"code": null,
"e": 30379,
"s": 30360,
"text": "School Programming"
},
{
"code": null,
"e": 30386,
"s": 30379,
"text": "Matrix"
},
{
"code": null,
"e": 30484,
"s": 30386,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30493,
"s": 30484,
"text": "Comments"
},
{
"code": null,
"e": 30506,
"s": 30493,
"text": "Old Comments"
},
{
"code": null,
"e": 30530,
"s": 30506,
"text": "Sudoku | Backtracking-7"
},
{
"code": null,
"e": 30592,
"s": 30530,
"text": "Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)"
},
{
"code": null,
"e": 30625,
"s": 30592,
"text": "Program to multiply two matrices"
},
{
"code": null,
"e": 30676,
"s": 30625,
"text": "Inplace rotate square matrix by 90 degrees | Set 1"
},
{
"code": null,
"e": 30697,
"s": 30676,
"text": "Min Cost Path | DP-6"
},
{
"code": null,
"e": 30715,
"s": 30697,
"text": "Python Dictionary"
},
{
"code": null,
"e": 30731,
"s": 30715,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 30756,
"s": 30731,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 30775,
"s": 30756,
"text": "Inheritance in C++"
}
] |
Python calendar module | isleap() method - GeeksforGeeks | 22 Oct, 2018
Calendar module allows to output calendars like program, and provides additional useful functions related to the calendar. Functions and classes defined in Calendar module use an idealized calendar, the current Gregorian calendar extended indefinitely in both directions.
In Python, calendar.isleap() is a function provided in calendar module for simple text calendars.
isleap() method is used to get value True if the year is a leap year, otherwise gives False.
Syntax: isleap()
Parameter:
year: Year to be tested leap or not.
Returns: Returns True if the year is a leap year, otherwise False.
Code #1:
# Python program to explain working of isleap() method # importing calendar moduleimport calendar # checking whether given year is leap or notprint(calendar.isleap(2016))print(calendar.isleap(2001))
Output:
True
False
Code #2: Explaining working of isleap() method.
Below code prints 4th months calendar if given year is year, otherwise notifies year is not leap.
# Python code to demonstrate the working of isleap() # importing calendar module for calendar operations import calendar year = 2017 # calling isleap() method to verifyval = calendar.isleap(year) # checking the condition is True or notif val == True: # print 4th month of given leap year calendar.prmonth(year, 4, 2, 1) # Returned False, year is not a leapelse: print("% s is not a leap year" % year)
Output:
2017 is not a leap year
Python Calander-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Defaultdict in Python
Python | Get unique values from a list
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python | [
{
"code": null,
"e": 23901,
"s": 23873,
"text": "\n22 Oct, 2018"
},
{
"code": null,
"e": 24173,
"s": 23901,
"text": "Calendar module allows to output calendars like program, and provides additional useful functions related to the calendar. Functions and classes defined in Calendar module use an idealized calendar, the current Gregorian calendar extended indefinitely in both directions."
},
{
"code": null,
"e": 24271,
"s": 24173,
"text": "In Python, calendar.isleap() is a function provided in calendar module for simple text calendars."
},
{
"code": null,
"e": 24364,
"s": 24271,
"text": "isleap() method is used to get value True if the year is a leap year, otherwise gives False."
},
{
"code": null,
"e": 24498,
"s": 24364,
"text": "Syntax: isleap()\nParameter: \nyear: Year to be tested leap or not.\n\nReturns: Returns True if the year is a leap year, otherwise False."
},
{
"code": null,
"e": 24507,
"s": 24498,
"text": "Code #1:"
},
{
"code": "# Python program to explain working of isleap() method # importing calendar moduleimport calendar # checking whether given year is leap or notprint(calendar.isleap(2016))print(calendar.isleap(2001))",
"e": 24708,
"s": 24507,
"text": null
},
{
"code": null,
"e": 24716,
"s": 24708,
"text": "Output:"
},
{
"code": null,
"e": 24727,
"s": 24716,
"text": "True\nFalse"
},
{
"code": null,
"e": 24777,
"s": 24729,
"text": "Code #2: Explaining working of isleap() method."
},
{
"code": null,
"e": 24875,
"s": 24777,
"text": "Below code prints 4th months calendar if given year is year, otherwise notifies year is not leap."
},
{
"code": "# Python code to demonstrate the working of isleap() # importing calendar module for calendar operations import calendar year = 2017 # calling isleap() method to verifyval = calendar.isleap(year) # checking the condition is True or notif val == True: # print 4th month of given leap year calendar.prmonth(year, 4, 2, 1) # Returned False, year is not a leapelse: print(\"% s is not a leap year\" % year)",
"e": 25296,
"s": 24875,
"text": null
},
{
"code": null,
"e": 25304,
"s": 25296,
"text": "Output:"
},
{
"code": null,
"e": 25328,
"s": 25304,
"text": "2017 is not a leap year"
},
{
"code": null,
"e": 25351,
"s": 25328,
"text": "Python Calander-module"
},
{
"code": null,
"e": 25358,
"s": 25351,
"text": "Python"
},
{
"code": null,
"e": 25456,
"s": 25358,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25465,
"s": 25456,
"text": "Comments"
},
{
"code": null,
"e": 25478,
"s": 25465,
"text": "Old Comments"
},
{
"code": null,
"e": 25510,
"s": 25478,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 25566,
"s": 25510,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 25608,
"s": 25566,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 25650,
"s": 25608,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 25686,
"s": 25650,
"text": "Python | Pandas dataframe.groupby()"
},
{
"code": null,
"e": 25708,
"s": 25686,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 25747,
"s": 25708,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 25774,
"s": 25747,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 25805,
"s": 25774,
"text": "Python | os.path.join() method"
}
] |
How to read the data from a file in Java? | The read(byte[] b) method of the FileInputStream class reads up to the b.length from this file input stream to the array of bytes. The method blocks until some input is available.
import java.io.File;
import java.io.FileInputStream;
public class Sample {
public static void main(String args[]) throws Exception {
int count =0;
File file = new File("myData");
FileInputStream fis = new FileInputStream(file);
byte[] bytesArray = new byte[(int)file.length()];
fis.read(bytesArray);
String s = new String(bytesArray);
System.out.println("Contents of the given file are :: " +new String(bytesArray));
}
}
Contents of the given file are :: Hi how are you welcome to tutorialspoint | [
{
"code": null,
"e": 1242,
"s": 1062,
"text": "The read(byte[] b) method of the FileInputStream class reads up to the b.length from this file input stream to the array of bytes. The method blocks until some input is available."
},
{
"code": null,
"e": 1711,
"s": 1242,
"text": "import java.io.File;\nimport java.io.FileInputStream;\npublic class Sample {\n public static void main(String args[]) throws Exception {\n int count =0;\n File file = new File(\"myData\");\n FileInputStream fis = new FileInputStream(file);\n byte[] bytesArray = new byte[(int)file.length()];\n fis.read(bytesArray);\n String s = new String(bytesArray);\n System.out.println(\"Contents of the given file are :: \" +new String(bytesArray));\n }\n}"
},
{
"code": null,
"e": 1786,
"s": 1711,
"text": "Contents of the given file are :: Hi how are you welcome to tutorialspoint"
}
] |
Anomaly Detection in Time Series Sensor Data | by Bauyrjan Jyenis | Towards Data Science | Anomaly detection involves identifying the differences, deviations, and exceptions from the norm in a dataset. It’s sometimes referred to as outlier detection.
Anomaly detection is not a new concept or technique, it has been around for a number of years and is a common application of Machine Learning. The real world examples of its use cases include (but not limited to) detecting fraud transactions, fraudulent insurance claims, cyber attacks to detecting abnormal equipment behaviors.
In this article, I will focus on the application of anomaly detection in the Manufacturing industry which I believe is an industry that lagged far behind in the area of effectively taking advantage of Machine Learning techniques compared to other industries.
Manufacturing industry is considered a heavy industry in which they tend to utilize various types of heavy machinery such as giant motors, pumps, pipes, furnaces, conveyor belts, haul trucks, dozers, graders, and electric shovels etc. These are often considered as the most critical assets for their operations. Therefore, the integrity and reliability of these equipment is often the core focus of their Asset Management programs.
The prime reason why they care so much about these assets is that the failure of these equipment often results in production loss that could consequently lead to loss of hundreds of thousands of dollars if not millions depending on the size and scale of the operations. So this is a pretty serious deal for a Maintenance Manager of a manufacturing plant to run a robust Asset Management framework with highly skilled Reliability Engineers to ensure the reliability and availability of these critical assets.
Therefore, the ability to detect anomalies in advance and be able to mitigate risks is a very valuable capability which further allows preventing an unplanned downtime, unnecessary maintenance (condition based vs mandatory maintenance) and will also enable more effective way of managing critical components for these assets. The production loss from unplanned downtime, the cost of unnecessary maintenance and having excess or shortage of critical components translate into serious magnitudes in terms of dollar amount.
In this post, I will implement different anomaly detection techniques in Python with Scikit-learn (aka sklearn) and our goal is going to be to search for anomalies in the time series sensor readings from a pump with unsupervised learning algorithms. Let’s get started!
It is very hard to find a public data from a manufacturing industry for this particular use case but I was able to find one that is not perfect. The data set contains sensor readings from 53 sensors installed on a pump to measure various behaviors of the pump. This data set can be found here.
First, I will download the data using the following code and Kaggle API
!kaggle datasets download -d nphantawee/pump-sensor-data
Once downloaded, read the CSV file into the pandas DataFrame with the following code and check out the details of the data.
df = pd.read_csv('sensor.csv')df.info()<class 'pandas.core.frame.DataFrame'>RangeIndex: 220320 entries, 0 to 220319Data columns (total 55 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 Unnamed: 0 220320 non-null int64 1 timestamp 220320 non-null object 2 sensor_00 210112 non-null float64 3 sensor_01 219951 non-null float64 4 sensor_02 220301 non-null float64 5 sensor_03 220301 non-null float64 6 sensor_04 220301 non-null float64 7 sensor_05 220301 non-null float64 8 sensor_06 215522 non-null float64 9 sensor_07 214869 non-null float64 10 sensor_08 215213 non-null float64 11 sensor_09 215725 non-null float64 12 sensor_10 220301 non-null float64 13 sensor_11 220301 non-null float64 14 sensor_12 220301 non-null float64 15 sensor_13 220301 non-null float64 16 sensor_14 220299 non-null float64 17 sensor_15 0 non-null float64 18 sensor_16 220289 non-null float64 19 sensor_17 220274 non-null float64 20 sensor_18 220274 non-null float64 21 sensor_19 220304 non-null float64 22 sensor_20 220304 non-null float64 23 sensor_21 220304 non-null float64 24 sensor_22 220279 non-null float64 25 sensor_23 220304 non-null float64 26 sensor_24 220304 non-null float64 27 sensor_25 220284 non-null float64 28 sensor_26 220300 non-null float64 29 sensor_27 220304 non-null float64 30 sensor_28 220304 non-null float64 31 sensor_29 220248 non-null float64 32 sensor_30 220059 non-null float64 33 sensor_31 220304 non-null float64 34 sensor_32 220252 non-null float64 35 sensor_33 220304 non-null float64 36 sensor_34 220304 non-null float64 37 sensor_35 220304 non-null float64 38 sensor_36 220304 non-null float64 39 sensor_37 220304 non-null float64 40 sensor_38 220293 non-null float64 41 sensor_39 220293 non-null float64 42 sensor_40 220293 non-null float64 43 sensor_41 220293 non-null float64 44 sensor_42 220293 non-null float64 45 sensor_43 220293 non-null float64 46 sensor_44 220293 non-null float64 47 sensor_45 220293 non-null float64 48 sensor_46 220293 non-null float64 49 sensor_47 220293 non-null float64 50 sensor_48 220293 non-null float64 51 sensor_49 220293 non-null float64 52 sensor_50 143303 non-null float64 53 sensor_51 204937 non-null float64 54 machine_status 220320 non-null object dtypes: float64(52), int64(1), object(2)memory usage: 92.5+ MB
We can already see that the data requires some cleaning, there are missing values, an empty column and a timestamp with an incorrect data type. So I will apply the following steps to tidy up the data set.
Remove redundant columns
Remove duplicates
Handle missing values
Convert data types to the correct data type
# Drop duplicatesdf = df.drop_duplicates()# Entire "sensor_15" column is NaN therefore remove it from datadel df['sensor_15']# Let's convert the data type of timestamp column to datatime formatimport warningswarnings.filterwarnings("ignore")df_tidy['date'] = pd.to_datetime(df_tidy['timestamp'])del df_tidy['timestamp']
Next, let’s handle the missing values and for that let’s first see the columns that have missing values and see what percentage of the data is missing. To do that, I’ll write a function that calculates the percentage of missing values so I can use the same function multiple times throughout the notebook.
# Function that calculates the percentage of missing valuesdef calc_percent_NAs(df): nans = pd.DataFrame(df.isnull().sum().sort_values(ascending=False)/len(df), columns=['percent']) idx = nans['percent'] > 0 return nans[idx]# Let's use above function to look at top ten columns with NaNscalc_percent_NAs(df).head(10)
After some analysis, I decided to impute some of the missing values with their mean and drop the rest. After data wrangling process, my final tidy data looks as follows and is ready for the next step which is Exploratory Data Analysis. The tidy data set has 52 sensors, machine status column that contains three classes (NORMAL, BROKEN, RECOVERING) which represent normal operating, broken and recovering conditions of the pump respectively and then the datetime column which represents the timestamp.
Now that we have cleaned our data, we can start exploring to acquaint with the data set.
On top of some quantitative EDA, I performed additional graphical EDA to look for trends and any odd behaviors. In particular, it is interesting to see the sensor readings plotted over time with the machine status of “BROKEN” marked up on the same graph in red color. That way, we can clearly see when the pump breaks down and how that reflects in the sensor readings. The following code plots the mentioned graph for each of the sensors, but let’s take a look at that for the sensor_00.
# Extract the readings from the BROKEN state of the pumpbroken = df[df['machine_status']=='BROKEN']# Extract the names of the numerical columnsdf2 = df.drop(['machine_status'], axis=1)names=df2.columns# Plot time series for each sensor with BROKEN state marked with X in red colorfor name in names: _ = plt.figure(figsize=(18,3)) _ = plt.plot(broken[name], linestyle='none', marker='X', color='red', markersize=12) _ = plt.plot(df[name], color='blue') _ = plt.title(name) plt.show()
As seen clearly from the above plot, the red marks, which represent the broken state of the pump, perfectly overlaps with the observed disturbances of the sensor reading. Now we have a pretty good intuition about how each of the sensor reading behaves when the pump is broken vs operating normally.
In time series analysis, it is important that the data is stationary and have no autocorrelation. Stationarity refers to the behavior where the mean and standard deviation of the data changes over time, the data with such behavior is considered not stationary. On the other hand, autocorrelation refers to the behavior of the data where the data is correlated with itself in a different time period. As the next step, I will visually inspect the stationarity of each feature in the data set and the following code will do just that. Later, we will also perform the Dickey Fuller test to quantitatively verify the observed stationarity. In addition, we will inspect the autocorrelation of the features before feeding them into the clustering algorithms to detect anomalies.
# Resample the entire dataset by daily averagerollmean = df.resample(rule='D').mean()rollstd = df.resample(rule='D').std()# Plot time series for each sensor with its mean and standard deviationfor name in names: _ = plt.figure(figsize=(18,3)) _ = plt.plot(df[name], color='blue', label='Original') _ = plt.plot(rollmean[name], color='red', label='Rolling Mean') _ = plt.plot(rollstd[name], color='black', label='Rolling Std' ) _ = plt.legend(loc='best') _ = plt.title(name) plt.show()
Looking at the readings from one of the sensors, sensor_17 in this case, notice that the data actually looks pretty stationary where the rolling mean and standard deviation don’t seem to change over time except during the downtime of the pump which is expected. This was the case for most of the sensors in this data set but it may not always be the case in which situations various transformation methods must be applied to make the data stationary before training the data.
It is pretty computationally expensive to train models with all of the 52 sensors/features and it is not efficient. Therefore, I will employ Principal Component Analysis (PCA) technique to extract new features to be used for the modeling. In order to properly apply PCA, the data must be scaled and standardized. This is because PCA and most of the learning algorithms are distance based algorithms. If noticed from the first 10 rows of the tidy data, the magnitude of the values from each feature is not consistent. Some are very small while some others are really large values. I will perform the following steps using the Pipeline library.
Scale the dataPerform PCA and look at the most important principal components based on inertia
Scale the data
Perform PCA and look at the most important principal components based on inertia
# Standardize/scale the dataset and apply PCAfrom sklearn.preprocessing import StandardScalerfrom sklearn.decomposition import PCAfrom sklearn.pipeline import make_pipeline# Extract the names of the numerical columnsdf2 = df.drop(['machine_status'], axis=1)names=df2.columnsx = df[names]scaler = StandardScaler()pca = PCA()pipeline = make_pipeline(scaler, pca)pipeline.fit(x)# Plot the principal components against their inertiafeatures = range(pca.n_components_)_ = plt.figure(figsize=(15, 5))_ = plt.bar(features, pca.explained_variance_)_ = plt.xlabel('PCA feature')_ = plt.ylabel('Variance')_ = plt.xticks(features)_ = plt.title("Importance of the Principal Components based on inertia")plt.show()
It appears that the first two principal components are the most important as per the features extracted by the PCA in above importance plot. So as the next step, I will perform PCA with 2 components which will be my features to be used in the training of the models.
# Calculate PCA with 2 componentspca = PCA(n_components=2)principalComponents = pca.fit_transform(x)principalDf = pd.DataFrame(data = principalComponents, columns = ['pc1', 'pc2'])
Now, I will check again the stationarity and autocorrelation of these two principal components just to be sure they are stationary and not autocorrelated.
from statsmodels.tsa.stattools import adfuller# Run Augmented Dickey Fuller Testresult = adfuller(principalDf['pc1'])# Print p-valueprint(result[1])
Running the Dickey Fuller test on the 1st principal component, I got a p-value of 5.4536849418486247e-05 which is very small number (much smaller than 0.05). Thus, I will reject the Null Hypothesis and say the data is stationary. I performed the same on the 2nd component and got a similar result. So both of the principal components are stationary which is what I wanted.
Now, let’s check for autocorrelation in both of these principal components. It can be done one of the two ways; either with the pandas autocorr() method or ACF plot. I will use the latter in this case to quickly visually verify that there is no autocorrelation. The following code does just that.
# Plot ACFfrom statsmodels.graphics.tsaplots import plot_acfplot_acf(pca1.dropna(), lags=20, alpha=0.05)
Given my new features from PCA are stationary and not autocorrelated, I am ready for modeling.
In this step, I will perform the following learning algorithms to detect anomalies.
Benchmark model: Interquartile Range (IQR)K-Means clusteringIsolation Forest
Benchmark model: Interquartile Range (IQR)
K-Means clustering
Isolation Forest
Let’s start training with these algorithms.
Strategy:
Calculate IQR which is the difference between 75th (Q3)and 25th (Q1) percentiles.Calculate upper and lower bounds for the outlier.Filter the data points that fall outside the upper and lower bounds and flag them as outliers.Finally, plot the outliers on top of the time series data (the readings from sensor_11 in this case)
Calculate IQR which is the difference between 75th (Q3)and 25th (Q1) percentiles.
Calculate upper and lower bounds for the outlier.
Filter the data points that fall outside the upper and lower bounds and flag them as outliers.
Finally, plot the outliers on top of the time series data (the readings from sensor_11 in this case)
# Calculate IQR for the 1st principal component (pc1)q1_pc1, q3_pc1 = df['pc1'].quantile([0.25, 0.75])iqr_pc1 = q3_pc1 - q1_pc1# Calculate upper and lower bounds for outlier for pc1lower_pc1 = q1_pc1 - (1.5*iqr_pc1)upper_pc1 = q3_pc1 + (1.5*iqr_pc1)# Filter out the outliers from the pc1df['anomaly_pc1'] = ((df['pc1']>upper_pc1) | (df['pc1']<lower_pc1)).astype('int')# Calculate IQR for the 2nd principal component (pc2)q1_pc2, q3_pc2 = df['pc2'].quantile([0.25, 0.75])iqr_pc2 = q3_pc2 - q1_pc2# Calculate upper and lower bounds for outlier for pc2lower_pc2 = q1_pc2 - (1.5*iqr_pc2)upper_pc2 = q3_pc2 + (1.5*iqr_pc2)# Filter out the outliers from the pc2df['anomaly_pc2'] = ((df['pc2']>upper_pc2) | (df['pc2']<lower_pc2)).astype('int')# Let's plot the outliers from pc1 on top of the sensor_11 and see where they occured in the time seriesa = df[df['anomaly_pc1'] == 1] #anomaly_ = plt.figure(figsize=(18,6))_ = plt.plot(df['sensor_11'], color='blue', label='Normal')_ = plt.plot(a['sensor_11'], linestyle='none', marker='X', color='red', markersize=12, label='Anomaly')_ = plt.xlabel('Date and Time')_ = plt.ylabel('Sensor Reading')_ = plt.title('Sensor_11 Anomalies')_ = plt.legend(loc='best')plt.show();
As seen above, the anomalies are detected right before the pump breaks down. This could be a very valuable information for an operator to see and be able to shut down the pump properly before it actually goes down hard. Let’s see if we detect similar pattern in anomalies from the next two algorithms.
Strategy:
Calculate the distance between each point and its nearest centroid. The biggest distances are considered as anomaly.We use outliers_fraction to provide information to the algorithm about the proportion of the outliers present in our data set. Situations may vary from data set to data set. However, as a starting figure, I estimate outliers_fraction=0.13 (13% of df are outliers as depicted).Calculate number_of_outliers using outliers_fraction.Set threshold as the minimum distance of these outliers.The anomaly result of anomaly1 contains the above method Cluster (0:normal, 1:anomaly).Visualize anomalies with Time Series view.
Calculate the distance between each point and its nearest centroid. The biggest distances are considered as anomaly.
We use outliers_fraction to provide information to the algorithm about the proportion of the outliers present in our data set. Situations may vary from data set to data set. However, as a starting figure, I estimate outliers_fraction=0.13 (13% of df are outliers as depicted).
Calculate number_of_outliers using outliers_fraction.
Set threshold as the minimum distance of these outliers.
The anomaly result of anomaly1 contains the above method Cluster (0:normal, 1:anomaly).
Visualize anomalies with Time Series view.
# Import necessary librariesfrom sklearn.cluster import KMeans# I will start k-means clustering with k=2 as I already know that there are 3 classes of "NORMAL" vs # "NOT NORMAL" which are combination of BROKEN" and"RECOVERING"kmeans = KMeans(n_clusters=2, random_state=42)kmeans.fit(principalDf.values)labels = kmeans.predict(principalDf.values)unique_elements, counts_elements = np.unique(labels, return_counts=True)clusters = np.asarray((unique_elements, counts_elements))# Write a function that calculates distance between each point and the centroid of the closest clusterdef getDistanceByPoint(data, model): """ Function that calculates the distance between a point and centroid of a cluster, returns the distances in pandas series""" distance = [] for i in range(0,len(data)): Xa = np.array(data.loc[i]) Xb = model.cluster_centers_[model.labels_[i]-1] distance.append(np.linalg.norm(Xa-Xb)) return pd.Series(distance, index=data.index)# Assume that 13% of the entire data set are anomalies outliers_fraction = 0.13# get the distance between each point and its nearest centroid. The biggest distances are considered as anomalydistance = getDistanceByPoint(principalDf, kmeans)# number of observations that equate to the 13% of the entire data setnumber_of_outliers = int(outliers_fraction*len(distance))# Take the minimum of the largest 13% of the distances as the thresholdthreshold = distance.nlargest(number_of_outliers).min()# anomaly1 contain the anomaly result of the above method Cluster (0:normal, 1:anomaly) principalDf['anomaly1'] = (distance >= threshold).astype(int)
# Import IsolationForestfrom sklearn.ensemble import IsolationForest# Assume that 13% of the entire data set are anomalies outliers_fraction = 0.13model = IsolationForest(contamination=outliers_fraction)model.fit(principalDf.values) principalDf['anomaly2'] = pd.Series(model.predict(principalDf.values))# visualizationdf['anomaly2'] = pd.Series(principalDf['anomaly2'].values, index=df.index)a = df.loc[df['anomaly2'] == -1] #anomaly_ = plt.figure(figsize=(18,6))_ = plt.plot(df['sensor_11'], color='blue', label='Normal')_ = plt.plot(a['sensor_11'], linestyle='none', marker='X', color='red', markersize=12, label='Anomaly')_ = plt.xlabel('Date and Time')_ = plt.ylabel('Sensor Reading')_ = plt.title('Sensor_11 Anomalies')_ = plt.legend(loc='best')plt.show();
It is interesting to see that all three models detected a lot of the similar anomalies. Just by visually looking at the above graphs, one could easily conclude that the Isolation Forest might be detecting a lot more anomalies than the other two. However, the following tables show, on the contrary, that IQR is detecting far more anomalies than that of K-Means and Isolation Forest.
Why do you think that is? Is IQR mostly detecting the anomalies that are closer together while the other two models are detecting the anomalies spread across different time periods? Is IQR more scientific approach than the other two? How do we define accuracy? For now, let me leave you with these questions to think about. I will write more about the model evaluation in more detail in my future posts.
So far, we have done anomaly detection with three different methods. In doing so, we went through most of the steps of the commonly applied Data Science Process which includes the following steps:
Problem identificationData wranglingExploratory data analysisPre-processing and training data developmentModelingDocumentation
Problem identification
Data wrangling
Exploratory data analysis
Pre-processing and training data development
Modeling
Documentation
One of the challenges I faced during this project is that training anomaly detection models with unsupervised learning algorithms with such a large data set can be computationally very expensive. For example, I couldn’t properly train SVM on this data as it was taking a very long time to train the model with no success.
I suggest the following next steps in which the first 3 steps are focused on improving the model and the last two are about making things real:
Feature selection with advanced Feature engineering techniqueAdvanced hyperparameter tuningImplement other learning algorithms such as SVM, DBSCAN etc.Predict the machine status with the best model given a test set — BAM!Deploy the best model into production — DOUBLE BAM!
Feature selection with advanced Feature engineering technique
Advanced hyperparameter tuning
Implement other learning algorithms such as SVM, DBSCAN etc.
Predict the machine status with the best model given a test set — BAM!
Deploy the best model into production — DOUBLE BAM!
I will continue improving the model besides implementing the above mentioned steps and I will plan to share the outcomes in another post in the future.
Jupyter notebook can be found on Github for details. Enjoy detecting anomalies and let’s connect on LinkedIn.
Detecting stationarity in time series data
A Gentle Introduction to Autocorrelation and Partial Autocorrelation
Principal Component Analysis
A One-Stop Shop for Principal Component Analysis
K-Means Clustering
Sklearn K-Means Documentation
Sklearn Isolation Forest Documentatio | [
{
"code": null,
"e": 332,
"s": 172,
"text": "Anomaly detection involves identifying the differences, deviations, and exceptions from the norm in a dataset. It’s sometimes referred to as outlier detection."
},
{
"code": null,
"e": 661,
"s": 332,
"text": "Anomaly detection is not a new concept or technique, it has been around for a number of years and is a common application of Machine Learning. The real world examples of its use cases include (but not limited to) detecting fraud transactions, fraudulent insurance claims, cyber attacks to detecting abnormal equipment behaviors."
},
{
"code": null,
"e": 920,
"s": 661,
"text": "In this article, I will focus on the application of anomaly detection in the Manufacturing industry which I believe is an industry that lagged far behind in the area of effectively taking advantage of Machine Learning techniques compared to other industries."
},
{
"code": null,
"e": 1352,
"s": 920,
"text": "Manufacturing industry is considered a heavy industry in which they tend to utilize various types of heavy machinery such as giant motors, pumps, pipes, furnaces, conveyor belts, haul trucks, dozers, graders, and electric shovels etc. These are often considered as the most critical assets for their operations. Therefore, the integrity and reliability of these equipment is often the core focus of their Asset Management programs."
},
{
"code": null,
"e": 1860,
"s": 1352,
"text": "The prime reason why they care so much about these assets is that the failure of these equipment often results in production loss that could consequently lead to loss of hundreds of thousands of dollars if not millions depending on the size and scale of the operations. So this is a pretty serious deal for a Maintenance Manager of a manufacturing plant to run a robust Asset Management framework with highly skilled Reliability Engineers to ensure the reliability and availability of these critical assets."
},
{
"code": null,
"e": 2381,
"s": 1860,
"text": "Therefore, the ability to detect anomalies in advance and be able to mitigate risks is a very valuable capability which further allows preventing an unplanned downtime, unnecessary maintenance (condition based vs mandatory maintenance) and will also enable more effective way of managing critical components for these assets. The production loss from unplanned downtime, the cost of unnecessary maintenance and having excess or shortage of critical components translate into serious magnitudes in terms of dollar amount."
},
{
"code": null,
"e": 2650,
"s": 2381,
"text": "In this post, I will implement different anomaly detection techniques in Python with Scikit-learn (aka sklearn) and our goal is going to be to search for anomalies in the time series sensor readings from a pump with unsupervised learning algorithms. Let’s get started!"
},
{
"code": null,
"e": 2944,
"s": 2650,
"text": "It is very hard to find a public data from a manufacturing industry for this particular use case but I was able to find one that is not perfect. The data set contains sensor readings from 53 sensors installed on a pump to measure various behaviors of the pump. This data set can be found here."
},
{
"code": null,
"e": 3016,
"s": 2944,
"text": "First, I will download the data using the following code and Kaggle API"
},
{
"code": null,
"e": 3073,
"s": 3016,
"text": "!kaggle datasets download -d nphantawee/pump-sensor-data"
},
{
"code": null,
"e": 3197,
"s": 3073,
"text": "Once downloaded, read the CSV file into the pandas DataFrame with the following code and check out the details of the data."
},
{
"code": null,
"e": 5972,
"s": 3197,
"text": "df = pd.read_csv('sensor.csv')df.info()<class 'pandas.core.frame.DataFrame'>RangeIndex: 220320 entries, 0 to 220319Data columns (total 55 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 Unnamed: 0 220320 non-null int64 1 timestamp 220320 non-null object 2 sensor_00 210112 non-null float64 3 sensor_01 219951 non-null float64 4 sensor_02 220301 non-null float64 5 sensor_03 220301 non-null float64 6 sensor_04 220301 non-null float64 7 sensor_05 220301 non-null float64 8 sensor_06 215522 non-null float64 9 sensor_07 214869 non-null float64 10 sensor_08 215213 non-null float64 11 sensor_09 215725 non-null float64 12 sensor_10 220301 non-null float64 13 sensor_11 220301 non-null float64 14 sensor_12 220301 non-null float64 15 sensor_13 220301 non-null float64 16 sensor_14 220299 non-null float64 17 sensor_15 0 non-null float64 18 sensor_16 220289 non-null float64 19 sensor_17 220274 non-null float64 20 sensor_18 220274 non-null float64 21 sensor_19 220304 non-null float64 22 sensor_20 220304 non-null float64 23 sensor_21 220304 non-null float64 24 sensor_22 220279 non-null float64 25 sensor_23 220304 non-null float64 26 sensor_24 220304 non-null float64 27 sensor_25 220284 non-null float64 28 sensor_26 220300 non-null float64 29 sensor_27 220304 non-null float64 30 sensor_28 220304 non-null float64 31 sensor_29 220248 non-null float64 32 sensor_30 220059 non-null float64 33 sensor_31 220304 non-null float64 34 sensor_32 220252 non-null float64 35 sensor_33 220304 non-null float64 36 sensor_34 220304 non-null float64 37 sensor_35 220304 non-null float64 38 sensor_36 220304 non-null float64 39 sensor_37 220304 non-null float64 40 sensor_38 220293 non-null float64 41 sensor_39 220293 non-null float64 42 sensor_40 220293 non-null float64 43 sensor_41 220293 non-null float64 44 sensor_42 220293 non-null float64 45 sensor_43 220293 non-null float64 46 sensor_44 220293 non-null float64 47 sensor_45 220293 non-null float64 48 sensor_46 220293 non-null float64 49 sensor_47 220293 non-null float64 50 sensor_48 220293 non-null float64 51 sensor_49 220293 non-null float64 52 sensor_50 143303 non-null float64 53 sensor_51 204937 non-null float64 54 machine_status 220320 non-null object dtypes: float64(52), int64(1), object(2)memory usage: 92.5+ MB"
},
{
"code": null,
"e": 6177,
"s": 5972,
"text": "We can already see that the data requires some cleaning, there are missing values, an empty column and a timestamp with an incorrect data type. So I will apply the following steps to tidy up the data set."
},
{
"code": null,
"e": 6202,
"s": 6177,
"text": "Remove redundant columns"
},
{
"code": null,
"e": 6220,
"s": 6202,
"text": "Remove duplicates"
},
{
"code": null,
"e": 6242,
"s": 6220,
"text": "Handle missing values"
},
{
"code": null,
"e": 6286,
"s": 6242,
"text": "Convert data types to the correct data type"
},
{
"code": null,
"e": 6606,
"s": 6286,
"text": "# Drop duplicatesdf = df.drop_duplicates()# Entire \"sensor_15\" column is NaN therefore remove it from datadel df['sensor_15']# Let's convert the data type of timestamp column to datatime formatimport warningswarnings.filterwarnings(\"ignore\")df_tidy['date'] = pd.to_datetime(df_tidy['timestamp'])del df_tidy['timestamp']"
},
{
"code": null,
"e": 6912,
"s": 6606,
"text": "Next, let’s handle the missing values and for that let’s first see the columns that have missing values and see what percentage of the data is missing. To do that, I’ll write a function that calculates the percentage of missing values so I can use the same function multiple times throughout the notebook."
},
{
"code": null,
"e": 7239,
"s": 6912,
"text": "# Function that calculates the percentage of missing valuesdef calc_percent_NAs(df): nans = pd.DataFrame(df.isnull().sum().sort_values(ascending=False)/len(df), columns=['percent']) idx = nans['percent'] > 0 return nans[idx]# Let's use above function to look at top ten columns with NaNscalc_percent_NAs(df).head(10)"
},
{
"code": null,
"e": 7741,
"s": 7239,
"text": "After some analysis, I decided to impute some of the missing values with their mean and drop the rest. After data wrangling process, my final tidy data looks as follows and is ready for the next step which is Exploratory Data Analysis. The tidy data set has 52 sensors, machine status column that contains three classes (NORMAL, BROKEN, RECOVERING) which represent normal operating, broken and recovering conditions of the pump respectively and then the datetime column which represents the timestamp."
},
{
"code": null,
"e": 7830,
"s": 7741,
"text": "Now that we have cleaned our data, we can start exploring to acquaint with the data set."
},
{
"code": null,
"e": 8318,
"s": 7830,
"text": "On top of some quantitative EDA, I performed additional graphical EDA to look for trends and any odd behaviors. In particular, it is interesting to see the sensor readings plotted over time with the machine status of “BROKEN” marked up on the same graph in red color. That way, we can clearly see when the pump breaks down and how that reflects in the sensor readings. The following code plots the mentioned graph for each of the sensors, but let’s take a look at that for the sensor_00."
},
{
"code": null,
"e": 8816,
"s": 8318,
"text": "# Extract the readings from the BROKEN state of the pumpbroken = df[df['machine_status']=='BROKEN']# Extract the names of the numerical columnsdf2 = df.drop(['machine_status'], axis=1)names=df2.columns# Plot time series for each sensor with BROKEN state marked with X in red colorfor name in names: _ = plt.figure(figsize=(18,3)) _ = plt.plot(broken[name], linestyle='none', marker='X', color='red', markersize=12) _ = plt.plot(df[name], color='blue') _ = plt.title(name) plt.show()"
},
{
"code": null,
"e": 9115,
"s": 8816,
"text": "As seen clearly from the above plot, the red marks, which represent the broken state of the pump, perfectly overlaps with the observed disturbances of the sensor reading. Now we have a pretty good intuition about how each of the sensor reading behaves when the pump is broken vs operating normally."
},
{
"code": null,
"e": 9888,
"s": 9115,
"text": "In time series analysis, it is important that the data is stationary and have no autocorrelation. Stationarity refers to the behavior where the mean and standard deviation of the data changes over time, the data with such behavior is considered not stationary. On the other hand, autocorrelation refers to the behavior of the data where the data is correlated with itself in a different time period. As the next step, I will visually inspect the stationarity of each feature in the data set and the following code will do just that. Later, we will also perform the Dickey Fuller test to quantitatively verify the observed stationarity. In addition, we will inspect the autocorrelation of the features before feeding them into the clustering algorithms to detect anomalies."
},
{
"code": null,
"e": 10394,
"s": 9888,
"text": "# Resample the entire dataset by daily averagerollmean = df.resample(rule='D').mean()rollstd = df.resample(rule='D').std()# Plot time series for each sensor with its mean and standard deviationfor name in names: _ = plt.figure(figsize=(18,3)) _ = plt.plot(df[name], color='blue', label='Original') _ = plt.plot(rollmean[name], color='red', label='Rolling Mean') _ = plt.plot(rollstd[name], color='black', label='Rolling Std' ) _ = plt.legend(loc='best') _ = plt.title(name) plt.show()"
},
{
"code": null,
"e": 10870,
"s": 10394,
"text": "Looking at the readings from one of the sensors, sensor_17 in this case, notice that the data actually looks pretty stationary where the rolling mean and standard deviation don’t seem to change over time except during the downtime of the pump which is expected. This was the case for most of the sensors in this data set but it may not always be the case in which situations various transformation methods must be applied to make the data stationary before training the data."
},
{
"code": null,
"e": 11513,
"s": 10870,
"text": "It is pretty computationally expensive to train models with all of the 52 sensors/features and it is not efficient. Therefore, I will employ Principal Component Analysis (PCA) technique to extract new features to be used for the modeling. In order to properly apply PCA, the data must be scaled and standardized. This is because PCA and most of the learning algorithms are distance based algorithms. If noticed from the first 10 rows of the tidy data, the magnitude of the values from each feature is not consistent. Some are very small while some others are really large values. I will perform the following steps using the Pipeline library."
},
{
"code": null,
"e": 11608,
"s": 11513,
"text": "Scale the dataPerform PCA and look at the most important principal components based on inertia"
},
{
"code": null,
"e": 11623,
"s": 11608,
"text": "Scale the data"
},
{
"code": null,
"e": 11704,
"s": 11623,
"text": "Perform PCA and look at the most important principal components based on inertia"
},
{
"code": null,
"e": 12406,
"s": 11704,
"text": "# Standardize/scale the dataset and apply PCAfrom sklearn.preprocessing import StandardScalerfrom sklearn.decomposition import PCAfrom sklearn.pipeline import make_pipeline# Extract the names of the numerical columnsdf2 = df.drop(['machine_status'], axis=1)names=df2.columnsx = df[names]scaler = StandardScaler()pca = PCA()pipeline = make_pipeline(scaler, pca)pipeline.fit(x)# Plot the principal components against their inertiafeatures = range(pca.n_components_)_ = plt.figure(figsize=(15, 5))_ = plt.bar(features, pca.explained_variance_)_ = plt.xlabel('PCA feature')_ = plt.ylabel('Variance')_ = plt.xticks(features)_ = plt.title(\"Importance of the Principal Components based on inertia\")plt.show()"
},
{
"code": null,
"e": 12673,
"s": 12406,
"text": "It appears that the first two principal components are the most important as per the features extracted by the PCA in above importance plot. So as the next step, I will perform PCA with 2 components which will be my features to be used in the training of the models."
},
{
"code": null,
"e": 12854,
"s": 12673,
"text": "# Calculate PCA with 2 componentspca = PCA(n_components=2)principalComponents = pca.fit_transform(x)principalDf = pd.DataFrame(data = principalComponents, columns = ['pc1', 'pc2'])"
},
{
"code": null,
"e": 13009,
"s": 12854,
"text": "Now, I will check again the stationarity and autocorrelation of these two principal components just to be sure they are stationary and not autocorrelated."
},
{
"code": null,
"e": 13158,
"s": 13009,
"text": "from statsmodels.tsa.stattools import adfuller# Run Augmented Dickey Fuller Testresult = adfuller(principalDf['pc1'])# Print p-valueprint(result[1])"
},
{
"code": null,
"e": 13531,
"s": 13158,
"text": "Running the Dickey Fuller test on the 1st principal component, I got a p-value of 5.4536849418486247e-05 which is very small number (much smaller than 0.05). Thus, I will reject the Null Hypothesis and say the data is stationary. I performed the same on the 2nd component and got a similar result. So both of the principal components are stationary which is what I wanted."
},
{
"code": null,
"e": 13828,
"s": 13531,
"text": "Now, let’s check for autocorrelation in both of these principal components. It can be done one of the two ways; either with the pandas autocorr() method or ACF plot. I will use the latter in this case to quickly visually verify that there is no autocorrelation. The following code does just that."
},
{
"code": null,
"e": 13933,
"s": 13828,
"text": "# Plot ACFfrom statsmodels.graphics.tsaplots import plot_acfplot_acf(pca1.dropna(), lags=20, alpha=0.05)"
},
{
"code": null,
"e": 14028,
"s": 13933,
"text": "Given my new features from PCA are stationary and not autocorrelated, I am ready for modeling."
},
{
"code": null,
"e": 14112,
"s": 14028,
"text": "In this step, I will perform the following learning algorithms to detect anomalies."
},
{
"code": null,
"e": 14189,
"s": 14112,
"text": "Benchmark model: Interquartile Range (IQR)K-Means clusteringIsolation Forest"
},
{
"code": null,
"e": 14232,
"s": 14189,
"text": "Benchmark model: Interquartile Range (IQR)"
},
{
"code": null,
"e": 14251,
"s": 14232,
"text": "K-Means clustering"
},
{
"code": null,
"e": 14268,
"s": 14251,
"text": "Isolation Forest"
},
{
"code": null,
"e": 14312,
"s": 14268,
"text": "Let’s start training with these algorithms."
},
{
"code": null,
"e": 14322,
"s": 14312,
"text": "Strategy:"
},
{
"code": null,
"e": 14647,
"s": 14322,
"text": "Calculate IQR which is the difference between 75th (Q3)and 25th (Q1) percentiles.Calculate upper and lower bounds for the outlier.Filter the data points that fall outside the upper and lower bounds and flag them as outliers.Finally, plot the outliers on top of the time series data (the readings from sensor_11 in this case)"
},
{
"code": null,
"e": 14729,
"s": 14647,
"text": "Calculate IQR which is the difference between 75th (Q3)and 25th (Q1) percentiles."
},
{
"code": null,
"e": 14779,
"s": 14729,
"text": "Calculate upper and lower bounds for the outlier."
},
{
"code": null,
"e": 14874,
"s": 14779,
"text": "Filter the data points that fall outside the upper and lower bounds and flag them as outliers."
},
{
"code": null,
"e": 14975,
"s": 14874,
"text": "Finally, plot the outliers on top of the time series data (the readings from sensor_11 in this case)"
},
{
"code": null,
"e": 16183,
"s": 14975,
"text": "# Calculate IQR for the 1st principal component (pc1)q1_pc1, q3_pc1 = df['pc1'].quantile([0.25, 0.75])iqr_pc1 = q3_pc1 - q1_pc1# Calculate upper and lower bounds for outlier for pc1lower_pc1 = q1_pc1 - (1.5*iqr_pc1)upper_pc1 = q3_pc1 + (1.5*iqr_pc1)# Filter out the outliers from the pc1df['anomaly_pc1'] = ((df['pc1']>upper_pc1) | (df['pc1']<lower_pc1)).astype('int')# Calculate IQR for the 2nd principal component (pc2)q1_pc2, q3_pc2 = df['pc2'].quantile([0.25, 0.75])iqr_pc2 = q3_pc2 - q1_pc2# Calculate upper and lower bounds for outlier for pc2lower_pc2 = q1_pc2 - (1.5*iqr_pc2)upper_pc2 = q3_pc2 + (1.5*iqr_pc2)# Filter out the outliers from the pc2df['anomaly_pc2'] = ((df['pc2']>upper_pc2) | (df['pc2']<lower_pc2)).astype('int')# Let's plot the outliers from pc1 on top of the sensor_11 and see where they occured in the time seriesa = df[df['anomaly_pc1'] == 1] #anomaly_ = plt.figure(figsize=(18,6))_ = plt.plot(df['sensor_11'], color='blue', label='Normal')_ = plt.plot(a['sensor_11'], linestyle='none', marker='X', color='red', markersize=12, label='Anomaly')_ = plt.xlabel('Date and Time')_ = plt.ylabel('Sensor Reading')_ = plt.title('Sensor_11 Anomalies')_ = plt.legend(loc='best')plt.show();"
},
{
"code": null,
"e": 16485,
"s": 16183,
"text": "As seen above, the anomalies are detected right before the pump breaks down. This could be a very valuable information for an operator to see and be able to shut down the pump properly before it actually goes down hard. Let’s see if we detect similar pattern in anomalies from the next two algorithms."
},
{
"code": null,
"e": 16495,
"s": 16485,
"text": "Strategy:"
},
{
"code": null,
"e": 17126,
"s": 16495,
"text": "Calculate the distance between each point and its nearest centroid. The biggest distances are considered as anomaly.We use outliers_fraction to provide information to the algorithm about the proportion of the outliers present in our data set. Situations may vary from data set to data set. However, as a starting figure, I estimate outliers_fraction=0.13 (13% of df are outliers as depicted).Calculate number_of_outliers using outliers_fraction.Set threshold as the minimum distance of these outliers.The anomaly result of anomaly1 contains the above method Cluster (0:normal, 1:anomaly).Visualize anomalies with Time Series view."
},
{
"code": null,
"e": 17243,
"s": 17126,
"text": "Calculate the distance between each point and its nearest centroid. The biggest distances are considered as anomaly."
},
{
"code": null,
"e": 17520,
"s": 17243,
"text": "We use outliers_fraction to provide information to the algorithm about the proportion of the outliers present in our data set. Situations may vary from data set to data set. However, as a starting figure, I estimate outliers_fraction=0.13 (13% of df are outliers as depicted)."
},
{
"code": null,
"e": 17574,
"s": 17520,
"text": "Calculate number_of_outliers using outliers_fraction."
},
{
"code": null,
"e": 17631,
"s": 17574,
"text": "Set threshold as the minimum distance of these outliers."
},
{
"code": null,
"e": 17719,
"s": 17631,
"text": "The anomaly result of anomaly1 contains the above method Cluster (0:normal, 1:anomaly)."
},
{
"code": null,
"e": 17762,
"s": 17719,
"text": "Visualize anomalies with Time Series view."
},
{
"code": null,
"e": 19391,
"s": 17762,
"text": "# Import necessary librariesfrom sklearn.cluster import KMeans# I will start k-means clustering with k=2 as I already know that there are 3 classes of \"NORMAL\" vs # \"NOT NORMAL\" which are combination of BROKEN\" and\"RECOVERING\"kmeans = KMeans(n_clusters=2, random_state=42)kmeans.fit(principalDf.values)labels = kmeans.predict(principalDf.values)unique_elements, counts_elements = np.unique(labels, return_counts=True)clusters = np.asarray((unique_elements, counts_elements))# Write a function that calculates distance between each point and the centroid of the closest clusterdef getDistanceByPoint(data, model): \"\"\" Function that calculates the distance between a point and centroid of a cluster, returns the distances in pandas series\"\"\" distance = [] for i in range(0,len(data)): Xa = np.array(data.loc[i]) Xb = model.cluster_centers_[model.labels_[i]-1] distance.append(np.linalg.norm(Xa-Xb)) return pd.Series(distance, index=data.index)# Assume that 13% of the entire data set are anomalies outliers_fraction = 0.13# get the distance between each point and its nearest centroid. The biggest distances are considered as anomalydistance = getDistanceByPoint(principalDf, kmeans)# number of observations that equate to the 13% of the entire data setnumber_of_outliers = int(outliers_fraction*len(distance))# Take the minimum of the largest 13% of the distances as the thresholdthreshold = distance.nlargest(number_of_outliers).min()# anomaly1 contain the anomaly result of the above method Cluster (0:normal, 1:anomaly) principalDf['anomaly1'] = (distance >= threshold).astype(int)"
},
{
"code": null,
"e": 20154,
"s": 19391,
"text": "# Import IsolationForestfrom sklearn.ensemble import IsolationForest# Assume that 13% of the entire data set are anomalies outliers_fraction = 0.13model = IsolationForest(contamination=outliers_fraction)model.fit(principalDf.values) principalDf['anomaly2'] = pd.Series(model.predict(principalDf.values))# visualizationdf['anomaly2'] = pd.Series(principalDf['anomaly2'].values, index=df.index)a = df.loc[df['anomaly2'] == -1] #anomaly_ = plt.figure(figsize=(18,6))_ = plt.plot(df['sensor_11'], color='blue', label='Normal')_ = plt.plot(a['sensor_11'], linestyle='none', marker='X', color='red', markersize=12, label='Anomaly')_ = plt.xlabel('Date and Time')_ = plt.ylabel('Sensor Reading')_ = plt.title('Sensor_11 Anomalies')_ = plt.legend(loc='best')plt.show();"
},
{
"code": null,
"e": 20537,
"s": 20154,
"text": "It is interesting to see that all three models detected a lot of the similar anomalies. Just by visually looking at the above graphs, one could easily conclude that the Isolation Forest might be detecting a lot more anomalies than the other two. However, the following tables show, on the contrary, that IQR is detecting far more anomalies than that of K-Means and Isolation Forest."
},
{
"code": null,
"e": 20941,
"s": 20537,
"text": "Why do you think that is? Is IQR mostly detecting the anomalies that are closer together while the other two models are detecting the anomalies spread across different time periods? Is IQR more scientific approach than the other two? How do we define accuracy? For now, let me leave you with these questions to think about. I will write more about the model evaluation in more detail in my future posts."
},
{
"code": null,
"e": 21138,
"s": 20941,
"text": "So far, we have done anomaly detection with three different methods. In doing so, we went through most of the steps of the commonly applied Data Science Process which includes the following steps:"
},
{
"code": null,
"e": 21265,
"s": 21138,
"text": "Problem identificationData wranglingExploratory data analysisPre-processing and training data developmentModelingDocumentation"
},
{
"code": null,
"e": 21288,
"s": 21265,
"text": "Problem identification"
},
{
"code": null,
"e": 21303,
"s": 21288,
"text": "Data wrangling"
},
{
"code": null,
"e": 21329,
"s": 21303,
"text": "Exploratory data analysis"
},
{
"code": null,
"e": 21374,
"s": 21329,
"text": "Pre-processing and training data development"
},
{
"code": null,
"e": 21383,
"s": 21374,
"text": "Modeling"
},
{
"code": null,
"e": 21397,
"s": 21383,
"text": "Documentation"
},
{
"code": null,
"e": 21719,
"s": 21397,
"text": "One of the challenges I faced during this project is that training anomaly detection models with unsupervised learning algorithms with such a large data set can be computationally very expensive. For example, I couldn’t properly train SVM on this data as it was taking a very long time to train the model with no success."
},
{
"code": null,
"e": 21863,
"s": 21719,
"text": "I suggest the following next steps in which the first 3 steps are focused on improving the model and the last two are about making things real:"
},
{
"code": null,
"e": 22136,
"s": 21863,
"text": "Feature selection with advanced Feature engineering techniqueAdvanced hyperparameter tuningImplement other learning algorithms such as SVM, DBSCAN etc.Predict the machine status with the best model given a test set — BAM!Deploy the best model into production — DOUBLE BAM!"
},
{
"code": null,
"e": 22198,
"s": 22136,
"text": "Feature selection with advanced Feature engineering technique"
},
{
"code": null,
"e": 22229,
"s": 22198,
"text": "Advanced hyperparameter tuning"
},
{
"code": null,
"e": 22290,
"s": 22229,
"text": "Implement other learning algorithms such as SVM, DBSCAN etc."
},
{
"code": null,
"e": 22361,
"s": 22290,
"text": "Predict the machine status with the best model given a test set — BAM!"
},
{
"code": null,
"e": 22413,
"s": 22361,
"text": "Deploy the best model into production — DOUBLE BAM!"
},
{
"code": null,
"e": 22565,
"s": 22413,
"text": "I will continue improving the model besides implementing the above mentioned steps and I will plan to share the outcomes in another post in the future."
},
{
"code": null,
"e": 22675,
"s": 22565,
"text": "Jupyter notebook can be found on Github for details. Enjoy detecting anomalies and let’s connect on LinkedIn."
},
{
"code": null,
"e": 22718,
"s": 22675,
"text": "Detecting stationarity in time series data"
},
{
"code": null,
"e": 22787,
"s": 22718,
"text": "A Gentle Introduction to Autocorrelation and Partial Autocorrelation"
},
{
"code": null,
"e": 22816,
"s": 22787,
"text": "Principal Component Analysis"
},
{
"code": null,
"e": 22865,
"s": 22816,
"text": "A One-Stop Shop for Principal Component Analysis"
},
{
"code": null,
"e": 22884,
"s": 22865,
"text": "K-Means Clustering"
},
{
"code": null,
"e": 22914,
"s": 22884,
"text": "Sklearn K-Means Documentation"
}
] |
Minimum Number of Refueling Stops in C++ | Suppose there is a car, that travels from a starting position to a destination which is t miles east of the starting position.
Now along the way, there are many gas stations. So each station[i] represents a gas station that is station[i][0] miles east of the starting position, and that station has station[i][1] liters of gas.
If the car starts with an infinite size of gas tank, which initially has startFuel liters of fuel in it. It uses 1 liter of gas per 1 mile that it drives.
When the car reaches one gas station, it may stop and refuel, so now it transfers all the gas from the station into the car. We have to find what is the least number of refueling stops the car must make in order to reach its destination? If it is impossible to reach the destination, return -1.
So, if the input is like Target = 100, startFuel = 20, stations = [10,40],[20,30],[30,20],[60,40], then the output will be 3. So initially there are 10 liters of gas, after reaching the first station, it will transfer 40 liters of gas, so currently there are (0 + 40) = 40 liters gas, then reach to 3rd station now transfer 20 liters of gas, so the current quantity is (20+20) = 40, then reach last station, take 40 liters of gas, so current quantity (10 + 40) = 50, so far we have covered 60 miles, so we have to go 40 miles more to reach destination, there is sufficient gas to reach to the target.
To solve this, we will follow these steps −
curr := 0
curr := 0
sort the array st
sort the array st
Define priority queue pq
Define priority queue pq
i := 0, cnt := 0
i := 0, cnt := 0
curr := curr + fuel
curr := curr + fuel
while curr <target, do −(increase cnt by 1)while (i < size of st and st[i, 0] <= curr), do −insert st[i, 1] into pq(increase i by 1)if pq is empty, then −Come out from the loopcurr := curr + top element of pqdelete element from pq
while curr <target, do −
(increase cnt by 1)
(increase cnt by 1)
while (i < size of st and st[i, 0] <= curr), do −insert st[i, 1] into pq(increase i by 1)
while (i < size of st and st[i, 0] <= curr), do −
insert st[i, 1] into pq
insert st[i, 1] into pq
(increase i by 1)
(increase i by 1)
if pq is empty, then −Come out from the loop
if pq is empty, then −
Come out from the loop
Come out from the loop
curr := curr + top element of pq
curr := curr + top element of pq
delete element from pq
delete element from pq
return (if curr >= target, then cnt, otherwise -1)
return (if curr >= target, then cnt, otherwise -1)
Let us see the following implementation to get better understanding −
Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int minRefuelStops(int target, int fuel, vector<vector<int>> &st) {
int curr = 0;
sort(st.begin(), st.end());
priority_queue<int> pq;
int i = 0;
int cnt = 0;
curr += fuel;
while (curr < target) {
cnt++;
while (i < st.size() && st[i][0] <= curr) {
pq.push(st[i][1]);
i++;
}
if (pq.empty())
break;
curr += pq.top();
pq.pop();
}
return curr >= target ? cnt : -1;
}
};
main(){
Solution ob;
vector<vector<int>> v = {{10,40},{20,30},{30,20},{60,40}};
cout << (ob.minRefuelStops(100, 10, v));
}
100, 10, {{10,40},{20,30},{30,20},{60,40}}
3 | [
{
"code": null,
"e": 1189,
"s": 1062,
"text": "Suppose there is a car, that travels from a starting position to a destination which is t miles east of the starting position."
},
{
"code": null,
"e": 1390,
"s": 1189,
"text": "Now along the way, there are many gas stations. So each station[i] represents a gas station that is station[i][0] miles east of the starting position, and that station has station[i][1] liters of gas."
},
{
"code": null,
"e": 1545,
"s": 1390,
"text": "If the car starts with an infinite size of gas tank, which initially has startFuel liters of fuel in it. It uses 1 liter of gas per 1 mile that it drives."
},
{
"code": null,
"e": 1840,
"s": 1545,
"text": "When the car reaches one gas station, it may stop and refuel, so now it transfers all the gas from the station into the car. We have to find what is the least number of refueling stops the car must make in order to reach its destination? If it is impossible to reach the destination, return -1."
},
{
"code": null,
"e": 2441,
"s": 1840,
"text": "So, if the input is like Target = 100, startFuel = 20, stations = [10,40],[20,30],[30,20],[60,40], then the output will be 3. So initially there are 10 liters of gas, after reaching the first station, it will transfer 40 liters of gas, so currently there are (0 + 40) = 40 liters gas, then reach to 3rd station now transfer 20 liters of gas, so the current quantity is (20+20) = 40, then reach last station, take 40 liters of gas, so current quantity (10 + 40) = 50, so far we have covered 60 miles, so we have to go 40 miles more to reach destination, there is sufficient gas to reach to the target."
},
{
"code": null,
"e": 2485,
"s": 2441,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 2495,
"s": 2485,
"text": "curr := 0"
},
{
"code": null,
"e": 2505,
"s": 2495,
"text": "curr := 0"
},
{
"code": null,
"e": 2523,
"s": 2505,
"text": "sort the array st"
},
{
"code": null,
"e": 2541,
"s": 2523,
"text": "sort the array st"
},
{
"code": null,
"e": 2566,
"s": 2541,
"text": "Define priority queue pq"
},
{
"code": null,
"e": 2591,
"s": 2566,
"text": "Define priority queue pq"
},
{
"code": null,
"e": 2608,
"s": 2591,
"text": "i := 0, cnt := 0"
},
{
"code": null,
"e": 2625,
"s": 2608,
"text": "i := 0, cnt := 0"
},
{
"code": null,
"e": 2645,
"s": 2625,
"text": "curr := curr + fuel"
},
{
"code": null,
"e": 2665,
"s": 2645,
"text": "curr := curr + fuel"
},
{
"code": null,
"e": 2896,
"s": 2665,
"text": "while curr <target, do −(increase cnt by 1)while (i < size of st and st[i, 0] <= curr), do −insert st[i, 1] into pq(increase i by 1)if pq is empty, then −Come out from the loopcurr := curr + top element of pqdelete element from pq"
},
{
"code": null,
"e": 2921,
"s": 2896,
"text": "while curr <target, do −"
},
{
"code": null,
"e": 2941,
"s": 2921,
"text": "(increase cnt by 1)"
},
{
"code": null,
"e": 2961,
"s": 2941,
"text": "(increase cnt by 1)"
},
{
"code": null,
"e": 3051,
"s": 2961,
"text": "while (i < size of st and st[i, 0] <= curr), do −insert st[i, 1] into pq(increase i by 1)"
},
{
"code": null,
"e": 3101,
"s": 3051,
"text": "while (i < size of st and st[i, 0] <= curr), do −"
},
{
"code": null,
"e": 3125,
"s": 3101,
"text": "insert st[i, 1] into pq"
},
{
"code": null,
"e": 3149,
"s": 3125,
"text": "insert st[i, 1] into pq"
},
{
"code": null,
"e": 3167,
"s": 3149,
"text": "(increase i by 1)"
},
{
"code": null,
"e": 3185,
"s": 3167,
"text": "(increase i by 1)"
},
{
"code": null,
"e": 3230,
"s": 3185,
"text": "if pq is empty, then −Come out from the loop"
},
{
"code": null,
"e": 3253,
"s": 3230,
"text": "if pq is empty, then −"
},
{
"code": null,
"e": 3276,
"s": 3253,
"text": "Come out from the loop"
},
{
"code": null,
"e": 3299,
"s": 3276,
"text": "Come out from the loop"
},
{
"code": null,
"e": 3332,
"s": 3299,
"text": "curr := curr + top element of pq"
},
{
"code": null,
"e": 3365,
"s": 3332,
"text": "curr := curr + top element of pq"
},
{
"code": null,
"e": 3388,
"s": 3365,
"text": "delete element from pq"
},
{
"code": null,
"e": 3411,
"s": 3388,
"text": "delete element from pq"
},
{
"code": null,
"e": 3462,
"s": 3411,
"text": "return (if curr >= target, then cnt, otherwise -1)"
},
{
"code": null,
"e": 3513,
"s": 3462,
"text": "return (if curr >= target, then cnt, otherwise -1)"
},
{
"code": null,
"e": 3583,
"s": 3513,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 3594,
"s": 3583,
"text": " Live Demo"
},
{
"code": null,
"e": 4315,
"s": 3594,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nclass Solution {\n public:\n int minRefuelStops(int target, int fuel, vector<vector<int>> &st) {\n int curr = 0;\n sort(st.begin(), st.end());\n priority_queue<int> pq;\n int i = 0;\n int cnt = 0;\n curr += fuel;\n while (curr < target) {\n cnt++;\n while (i < st.size() && st[i][0] <= curr) {\n pq.push(st[i][1]);\n i++;\n }\n if (pq.empty())\n break;\n curr += pq.top();\n pq.pop();\n }\n return curr >= target ? cnt : -1;\n }\n};\nmain(){\n Solution ob;\n vector<vector<int>> v = {{10,40},{20,30},{30,20},{60,40}};\n cout << (ob.minRefuelStops(100, 10, v));\n}"
},
{
"code": null,
"e": 4358,
"s": 4315,
"text": "100, 10, {{10,40},{20,30},{30,20},{60,40}}"
},
{
"code": null,
"e": 4360,
"s": 4358,
"text": "3"
}
] |
Introduction to Trees | Tree is a discrete structure that represents hierarchical relationships between individual elements or nodes. A tree in which a parent has no more than two children is called a binary tree.
Definition − A Tree is a connected acyclic undirected graph. There is a unique path between every pair of vertices in G. A tree with N number of vertices contains (N−1) number of edges. The vertex which is of 0 degree is called root of the tree. The vertex which is of 1 degree is called leaf node of the tree and the degree of an internal node is at least 2.
Example − The following is an example of a tree −
The center of a tree is a vertex with minimal eccentricity. The eccentricity of a vertex X in a tree G is the maximum distance between the vertex X and any other vertex of the tree. The maximum eccentricity is the tree diameter. If a tree has only one center, it is called Central Tree and if a tree has only more than one centers, it is called Bi-central Tree. Every tree is either central or bi-central.
Step 1 − Remove all the vertices of degree 1 from the given tree and also remove their incident edges.
Step 2 − Repeat step 1 until either a single vertex or two vertices joined by an edge is left. If a single vertex is left then it is the center of the tree and if two vertices joined by an edge is left then it is the bi-center of the tree.
Problem 1
Find out the center/bi-center of the following tree −
Solution
At first, we will remove all vertices of degree 1 and also remove their incident edges and get the following tree −
Again, we will remove all vertices of degree 1 and also remove their incident edges and get the following tree −
Finally we got a single vertex ‘c’ and we stop the algorithm. As there is single vertex, this tree has one center ‘c’ and the tree is a central tree.
Problem 2
Find out the center/bi-center of the following tree −
Solution
At first, we will remove all vertices of degree 1 and also remove their incident edges and get the following tree −
Again, we will remove all vertices of degree 1 and also remove their incident edges and get the following tree −
Finally, we got two vertices ‘c’ and ‘d’ left, hence we stop the algorithm. As two vertices joined by an edge is left, this tree has bi-center ‘cd’ and the tree is bi-central.
Definition − A labeled tree is a tree the vertices of which are assigned unique numbers from 1 to n. We can count such trees for small values of n by hand so as to conjecture a general formula. The number of labeled trees of n number of vertices is nn−2. Two labeled trees are isomorphic if their graphs are isomorphic and the corresponding points of the two trees have the same labels.
Definition − An unlabeled tree is a tree the vertices of which are not assigned any numbers. The number of labeled trees of n number of vertices is (2n)!(n+1)!n! (nth Catalan number)
A rooted tree G is a connected acyclic graph with a special node that is called the root of the tree and every edge directly or indirectly originates from the root. An ordered rooted tree is a rooted tree where the children of each internal vertex are ordered. If every internal vertex of a rooted tree has not more than m children, it is called an m-ary tree. If every internal vertex of a rooted tree has exactly m children, it is called a full m-ary tree. If m=2, the rooted tree is called a binary tree.
Binary Search tree is a binary tree which satisfies the following property −
X in left sub-tree of vertex V,Value(X)≤Value(V)
Y in right sub-tree of vertex V,Value(Y)≥Value(V)
So, the value of all the vertices of the left sub-tree of an internal node V are less than or equal to V and the value of all the vertices of the right sub-tree of the internal node V are greater than or equal to V. The number of links from the root node to the deepest node is the height of the Binary Search Tree.
BST_Search(x, k)
if ( x = NIL or k = Value[x] )
return x;
if ( k < Value[x])
return BST_Search (left[x], k);
else
return BST_Search (right[x], k)
20 Lectures
1.5 hours
Lukáš Vyhnálek
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2414,
"s": 2224,
"text": "Tree is a discrete structure that represents hierarchical relationships between individual elements or nodes. A tree in which a parent has no more than two children is called a binary tree."
},
{
"code": null,
"e": 2774,
"s": 2414,
"text": "Definition − A Tree is a connected acyclic undirected graph. There is a unique path between every pair of vertices in G. A tree with N number of vertices contains (N−1) number of edges. The vertex which is of 0 degree is called root of the tree. The vertex which is of 1 degree is called leaf node of the tree and the degree of an internal node is at least 2."
},
{
"code": null,
"e": 2824,
"s": 2774,
"text": "Example − The following is an example of a tree −"
},
{
"code": null,
"e": 3230,
"s": 2824,
"text": "The center of a tree is a vertex with minimal eccentricity. The eccentricity of a vertex X in a tree G is the maximum distance between the vertex X and any other vertex of the tree. The maximum eccentricity is the tree diameter. If a tree has only one center, it is called Central Tree and if a tree has only more than one centers, it is called Bi-central Tree. Every tree is either central or bi-central."
},
{
"code": null,
"e": 3333,
"s": 3230,
"text": "Step 1 − Remove all the vertices of degree 1 from the given tree and also remove their incident edges."
},
{
"code": null,
"e": 3573,
"s": 3333,
"text": "Step 2 − Repeat step 1 until either a single vertex or two vertices joined by an edge is left. If a single vertex is left then it is the center of the tree and if two vertices joined by an edge is left then it is the bi-center of the tree."
},
{
"code": null,
"e": 3583,
"s": 3573,
"text": "Problem 1"
},
{
"code": null,
"e": 3637,
"s": 3583,
"text": "Find out the center/bi-center of the following tree −"
},
{
"code": null,
"e": 3646,
"s": 3637,
"text": "Solution"
},
{
"code": null,
"e": 3762,
"s": 3646,
"text": "At first, we will remove all vertices of degree 1 and also remove their incident edges and get the following tree −"
},
{
"code": null,
"e": 3875,
"s": 3762,
"text": "Again, we will remove all vertices of degree 1 and also remove their incident edges and get the following tree −"
},
{
"code": null,
"e": 4025,
"s": 3875,
"text": "Finally we got a single vertex ‘c’ and we stop the algorithm. As there is single vertex, this tree has one center ‘c’ and the tree is a central tree."
},
{
"code": null,
"e": 4035,
"s": 4025,
"text": "Problem 2"
},
{
"code": null,
"e": 4089,
"s": 4035,
"text": "Find out the center/bi-center of the following tree −"
},
{
"code": null,
"e": 4098,
"s": 4089,
"text": "Solution"
},
{
"code": null,
"e": 4214,
"s": 4098,
"text": "At first, we will remove all vertices of degree 1 and also remove their incident edges and get the following tree −"
},
{
"code": null,
"e": 4327,
"s": 4214,
"text": "Again, we will remove all vertices of degree 1 and also remove their incident edges and get the following tree −"
},
{
"code": null,
"e": 4504,
"s": 4327,
"text": "Finally, we got two vertices ‘c’ and ‘d’ left, hence we stop the algorithm. As two vertices joined by an edge is left, this tree has bi-center ‘cd’ and the tree is bi-central."
},
{
"code": null,
"e": 4891,
"s": 4504,
"text": "Definition − A labeled tree is a tree the vertices of which are assigned unique numbers from 1 to n. We can count such trees for small values of n by hand so as to conjecture a general formula. The number of labeled trees of n number of vertices is nn−2. Two labeled trees are isomorphic if their graphs are isomorphic and the corresponding points of the two trees have the same labels."
},
{
"code": null,
"e": 5074,
"s": 4891,
"text": "Definition − An unlabeled tree is a tree the vertices of which are not assigned any numbers. The number of labeled trees of n number of vertices is (2n)!(n+1)!n! (nth Catalan number)"
},
{
"code": null,
"e": 5582,
"s": 5074,
"text": "A rooted tree G is a connected acyclic graph with a special node that is called the root of the tree and every edge directly or indirectly originates from the root. An ordered rooted tree is a rooted tree where the children of each internal vertex are ordered. If every internal vertex of a rooted tree has not more than m children, it is called an m-ary tree. If every internal vertex of a rooted tree has exactly m children, it is called a full m-ary tree. If m=2, the rooted tree is called a binary tree."
},
{
"code": null,
"e": 5659,
"s": 5582,
"text": "Binary Search tree is a binary tree which satisfies the following property −"
},
{
"code": null,
"e": 5708,
"s": 5659,
"text": "X in left sub-tree of vertex V,Value(X)≤Value(V)"
},
{
"code": null,
"e": 5758,
"s": 5708,
"text": "Y in right sub-tree of vertex V,Value(Y)≥Value(V)"
},
{
"code": null,
"e": 6074,
"s": 5758,
"text": "So, the value of all the vertices of the left sub-tree of an internal node V are less than or equal to V and the value of all the vertices of the right sub-tree of the internal node V are greater than or equal to V. The number of links from the root node to the deepest node is the height of the Binary Search Tree."
},
{
"code": null,
"e": 6238,
"s": 6074,
"text": "BST_Search(x, k) \nif ( x = NIL or k = Value[x] ) \n return x; \nif ( k < Value[x]) \n return BST_Search (left[x], k); \nelse \n return BST_Search (right[x], k) "
},
{
"code": null,
"e": 6273,
"s": 6238,
"text": "\n 20 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 6292,
"s": 6273,
"text": " Lukáš Vyhnálek"
},
{
"code": null,
"e": 6299,
"s": 6292,
"text": " Print"
},
{
"code": null,
"e": 6310,
"s": 6299,
"text": " Add Notes"
}
] |
Bootstrap 4 .border-danger class | Use the border-danger class to set a red border to an element.
Set the border-danger class to an element as if we include any other class −
<div class="new border border-danger">
Red Border
</div>
Above, we have also set another class “new”, to style the element −
<style>
.new {
width: 120px;
height: 120px;
margin: 20px;
}
</style>
You can try to run the following code to implement the border-danger class −
Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
<style>
.new {
width: 120px;
height: 120px;
margin: 20px;
}
</style>
</head>
<body>
<div class="container">
<p>Rectangle with red border:</p>
<div class="new border border-danger">Red Border</div>
</div>
</body>
</html> | [
{
"code": null,
"e": 1125,
"s": 1062,
"text": "Use the border-danger class to set a red border to an element."
},
{
"code": null,
"e": 1202,
"s": 1125,
"text": "Set the border-danger class to an element as if we include any other class −"
},
{
"code": null,
"e": 1261,
"s": 1202,
"text": "<div class=\"new border border-danger\">\n Red Border\n</div>"
},
{
"code": null,
"e": 1329,
"s": 1261,
"text": "Above, we have also set another class “new”, to style the element −"
},
{
"code": null,
"e": 1404,
"s": 1329,
"text": "<style>\n.new {\n width: 120px;\n height: 120px;\n margin: 20px;\n}\n</style>"
},
{
"code": null,
"e": 1481,
"s": 1404,
"text": "You can try to run the following code to implement the border-danger class −"
},
{
"code": null,
"e": 1491,
"s": 1481,
"text": "Live Demo"
},
{
"code": null,
"e": 2227,
"s": 1491,
"text": "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <title>Bootstrap Example</title>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css\">\n <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js\"></script>\n <style>\n .new {\n width: 120px;\n height: 120px;\n margin: 20px;\n }\n </style>\n </head>\n<body>\n\n<div class=\"container\">\n <p>Rectangle with red border:</p>\n <div class=\"new border border-danger\">Red Border</div>\n</div>\n\n</body>\n</html>"
}
] |
Connectivity in a directed graph | To check connectivity of a graph, we will try to traverse all nodes using any traversal algorithm. After completing the traversal, if there is any node, which is not visited, then the graph is not connected.
For the directed graph, we will start traversing from all nodes to check connectivity. Sometimes one edge can have the only outward edge but no inward edge, so that node will be unvisited from any other starting node.
In this case, the traversal algorithm is recursive DFS traversal.
Input:
Adjacency matrix of a graph
0 1 0 0 0
0 0 1 0 0
0 0 0 1 1
1 0 0 0 0
0 1 0 0 0
Output:
The Graph is connected.
traverse(u, visited)
Input: The start node u and the visited node to mark which node is visited.
Output − Traverse all connected vertices.
Begin
mark u as visited
for all vertex v, if it is adjacent with u, do
if v is not visited, then
traverse(v, visited)
done
End
isConnected(graph)
Input: The graph.
Output: True if the graph is connected.
Begin
define visited array
for all vertices u in the graph, do
make all nodes unvisited
traverse(u, visited)
if any unvisited node is still remaining, then
return false
done
return true
End
#include<iostream>
#define NODE 5
using namespace std;
int graph[NODE][NODE] = {
{0, 1, 0, 0, 0},
{0, 0, 1, 0, 0},
{0, 0, 0, 1, 1},
{1, 0, 0, 0, 0},
{0, 1, 0, 0, 0}
};
void traverse(int u, bool visited[]) {
visited[u] = true; //mark v as visited
for(int v = 0; v<NODE; v++) {
if(graph[u][v]) {
if(!visited[v])
traverse(v, visited);
}
}
}
bool isConnected() {
bool *vis = new bool[NODE];
//for all vertex u as start point, check whether all nodes are visible or not
for(int u; u < NODE; u++) {
for(int i = 0; i<NODE; i++)
vis[i] = false; //initialize as no node is visited
traverse(u, vis);
for(int i = 0; i<NODE; i++) {
if(!vis[i]) //if there is a node, not visited by traversal, graph is not connected
return false;
}
}
return true;
}
int main() {
if(isConnected())
cout << "The Graph is connected.";
else
cout << "The Graph is not connected.";
}
The Graph is connected. | [
{
"code": null,
"e": 1270,
"s": 1062,
"text": "To check connectivity of a graph, we will try to traverse all nodes using any traversal algorithm. After completing the traversal, if there is any node, which is not visited, then the graph is not connected."
},
{
"code": null,
"e": 1488,
"s": 1270,
"text": "For the directed graph, we will start traversing from all nodes to check connectivity. Sometimes one edge can have the only outward edge but no inward edge, so that node will be unvisited from any other starting node."
},
{
"code": null,
"e": 1554,
"s": 1488,
"text": "In this case, the traversal algorithm is recursive DFS traversal."
},
{
"code": null,
"e": 1692,
"s": 1554,
"text": "Input:\nAdjacency matrix of a graph\n 0 1 0 0 0\n 0 0 1 0 0\n 0 0 0 1 1\n 1 0 0 0 0\n 0 1 0 0 0\n\nOutput:\nThe Graph is connected. "
},
{
"code": null,
"e": 1713,
"s": 1692,
"text": "traverse(u, visited)"
},
{
"code": null,
"e": 1789,
"s": 1713,
"text": "Input: The start node u and the visited node to mark which node is visited."
},
{
"code": null,
"e": 1831,
"s": 1789,
"text": "Output − Traverse all connected vertices."
},
{
"code": null,
"e": 1982,
"s": 1831,
"text": "Begin\n mark u as visited\n for all vertex v, if it is adjacent with u, do\n if v is not visited, then\n traverse(v, visited)\n done\nEnd"
},
{
"code": null,
"e": 2001,
"s": 1982,
"text": "isConnected(graph)"
},
{
"code": null,
"e": 2019,
"s": 2001,
"text": "Input: The graph."
},
{
"code": null,
"e": 2059,
"s": 2019,
"text": "Output: True if the graph is connected."
},
{
"code": null,
"e": 2288,
"s": 2059,
"text": "Begin\n define visited array\n for all vertices u in the graph, do\n make all nodes unvisited\n traverse(u, visited)\n if any unvisited node is still remaining, then\n return false\n done\n return true\nEnd"
},
{
"code": null,
"e": 3358,
"s": 2288,
"text": "#include<iostream>\n#define NODE 5\nusing namespace std;\n\nint graph[NODE][NODE] = {\n {0, 1, 0, 0, 0},\n {0, 0, 1, 0, 0},\n {0, 0, 0, 1, 1},\n {1, 0, 0, 0, 0},\n {0, 1, 0, 0, 0}\n};\n \nvoid traverse(int u, bool visited[]) {\n visited[u] = true; //mark v as visited\n\n for(int v = 0; v<NODE; v++) {\n if(graph[u][v]) {\n if(!visited[v])\n traverse(v, visited);\n }\n }\n}\n\nbool isConnected() {\n bool *vis = new bool[NODE];\n //for all vertex u as start point, check whether all nodes are visible or not\n\n for(int u; u < NODE; u++) {\n for(int i = 0; i<NODE; i++)\n vis[i] = false; //initialize as no node is visited\n \n traverse(u, vis);\n for(int i = 0; i<NODE; i++) {\n if(!vis[i]) //if there is a node, not visited by traversal, graph is not connected\n return false;\n }\n }\n return true;\n}\n\nint main() {\n if(isConnected())\n cout << \"The Graph is connected.\";\n else\n cout << \"The Graph is not connected.\";\n}"
},
{
"code": null,
"e": 3382,
"s": 3358,
"text": "The Graph is connected."
}
] |
Find all collections in MongoDB with specific field? | Let us implement the above syntax in order to find all documents in MongoDB with field name “StudentFirstName”. The query is as follows −
> db.getCollectionNames().forEach(function(myCollectionName) {
... var frequency = db[myCollectionName].find({"StudentFirstName": {$exists: true}}).count();
... if (frequency > 0) {
... print(myCollectionName);
... }
... });
This will produce the following output −
multiDimensionalArrayProjection
removeKeyFieldsDemo
stringOrIntegerQueryDemo
Let us verify the removeKeyFieldsDemo collection has field with name “StudentFirstName” or not. Following is the query −
> db.removeKeyFieldsDemo.find({"StudentFirstName":{$exists:true}});
This will produce the following output displaying the StudentFirstName field exist −
{ "_id" : ObjectId("5cc6c8289cb58ca2b005e672"), "StudentFirstName" : "John", "StudentLastName" : "Doe" }
{ "_id" : ObjectId("5cc6c8359cb58ca2b005e673"), "StudentFirstName" : "John", "StudentLastName" : "Smith" } | [
{
"code": null,
"e": 1200,
"s": 1062,
"text": "Let us implement the above syntax in order to find all documents in MongoDB with field name “StudentFirstName”. The query is as follows −"
},
{
"code": null,
"e": 1440,
"s": 1200,
"text": "> db.getCollectionNames().forEach(function(myCollectionName) {\n... var frequency = db[myCollectionName].find({\"StudentFirstName\": {$exists: true}}).count();\n... if (frequency > 0) {\n... print(myCollectionName);\n... }\n... });"
},
{
"code": null,
"e": 1481,
"s": 1440,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1558,
"s": 1481,
"text": "multiDimensionalArrayProjection\nremoveKeyFieldsDemo\nstringOrIntegerQueryDemo"
},
{
"code": null,
"e": 1679,
"s": 1558,
"text": "Let us verify the removeKeyFieldsDemo collection has field with name “StudentFirstName” or not. Following is the query −"
},
{
"code": null,
"e": 1747,
"s": 1679,
"text": "> db.removeKeyFieldsDemo.find({\"StudentFirstName\":{$exists:true}});"
},
{
"code": null,
"e": 1832,
"s": 1747,
"text": "This will produce the following output displaying the StudentFirstName field exist −"
},
{
"code": null,
"e": 2044,
"s": 1832,
"text": "{ \"_id\" : ObjectId(\"5cc6c8289cb58ca2b005e672\"), \"StudentFirstName\" : \"John\", \"StudentLastName\" : \"Doe\" }\n{ \"_id\" : ObjectId(\"5cc6c8359cb58ca2b005e673\"), \"StudentFirstName\" : \"John\", \"StudentLastName\" : \"Smith\" }"
}
] |
SIP - The Offer/Answer Model | The use of SDP with SIP is given in the SDP offer answer RFC 3264. The default message body type in SIP is application/sdp.
The calling party lists the media capabilities that they are willing to receive in SDP, usually in either an INVITE or in an ACK.
The calling party lists the media capabilities that they are willing to receive in SDP, usually in either an INVITE or in an ACK.
The called party lists their media capabilities in the 200 OK response to the INVITE.
The called party lists their media capabilities in the 200 OK response to the INVITE.
A typical SIP use of SDP includes the following fields: version, origin, subject, time, connection, and one or more media and attribute.
The subject and time fields are not used by SIP but are included for compatibility.
The subject and time fields are not used by SIP but are included for compatibility.
In the SDP standard, the subject field is a required field and must contain at least one character, suggested to be s=- if there is no subject.
In the SDP standard, the subject field is a required field and must contain at least one character, suggested to be s=- if there is no subject.
The time field is usually set to t = 00. SIP uses the connection, media, and attribute fields to set up sessions between UAs.
The time field is usually set to t = 00. SIP uses the connection, media, and attribute fields to set up sessions between UAs.
The origin field has limited use with SIP.
The origin field has limited use with SIP.
The session-id is usually kept constant throughout a SIP session.
The session-id is usually kept constant throughout a SIP session.
The version is incremented each time the SDP is changed. If the SDP being sent is unchanged from that sent previously, the version is kept the same.
The version is incremented each time the SDP is changed. If the SDP being sent is unchanged from that sent previously, the version is kept the same.
As the type of media session and codec to be used are part of the connection negotiation, SIP can use SDP to specify multiple alternative media types and to selectively accept or decline those media types.
As the type of media session and codec to be used are part of the connection negotiation, SIP can use SDP to specify multiple alternative media types and to selectively accept or decline those media types.
The offer/answer specification, RFC 3264, recommends that an attribute containing a = rtpmap: be used for each media field. A media stream is declined by setting the port number to zero for the corresponding media field in the SDP response.
In the following example, the caller Tesla wants to set up an audio and video call with two possible audio codecs and a video codec in the SDP carried in the initial INVITE −
v = 0
o = John 0844526 2890844526 IN IP4 172.22.1.102
s = -
c = IN IP4 172.22.1.102
t = 0 0
m = audio 6000 RTP/AVP 97 98
a = rtpmap:97 AMR/16000/1
a = rtpmap:98 AMR-WB/8000/1
m = video 49172 RTP/AVP 32
a = rtpmap:32 MPV/90000
The codecs are referenced by the RTP/AVP profile numbers 97, 98.
The called party Marry answers the call, chooses the second codec for the first media field, and declines the second media field, only wanting AMR session.
v = 0
o = Marry 2890844526 2890844526 IN IP4 172.22.1.110
s = -
c = IN IP4 200.201.202.203
t = 0 0
m = audio 60000 RTP/AVP 8
a = rtpmap:97 AMR/16000
m = video 0 RTP/AVP 32
If this audio-only call is not acceptable, then Tom would send an ACK then a BYE to cancel the call. Otherwise, the audio session would be established and RTP packets exchanged.
As this example illustrates, unless the number and order of media fields is maintained, the calling party would not know for certain which media sessions were being accepted and declined by the called party.
The offer/answer rules are summarized in the following sections.
An SDP offer must include all required SDP fields (this includes v=, o=, s=, c=,and t=). These are mandatory fields in SDP.
It usually includes a media field (m=) but it does not have to. The media lines contain all codecs listed in preference order. The only exception to this is if the endpoint supports a huge number of codecs, the most likely to be accepted or most preferred should be listed. Different media types include audio, video, text, MSRP, BFCP, and so forth.
An SDP answer to an offer must be constructed according to the following rules −
The answer must have the same number of m= lines in the same order as the answer.
The answer must have the same number of m= lines in the same order as the answer.
Individual media streams can be declined by setting the port number to 0.
Individual media streams can be declined by setting the port number to 0.
Streams are accepted by sending a nonzero port number.
Streams are accepted by sending a nonzero port number.
The listed payloads for each media type must be a subset of the payloads listed in the offer.
The listed payloads for each media type must be a subset of the payloads listed in the offer.
For dynamic payloads, the same dynamic payload number does not need to be used in each direction. Usually, only a single payload is selected.
For dynamic payloads, the same dynamic payload number does not need to be used in each direction. Usually, only a single payload is selected.
Either party can initiate another offer/answer exchange to modify a session. When a session is modified, the following rules must be followed −
The origin (o=) line version number must either be the same as the last one sent, which indicates that this SDP is identical to the previous exchange, or it may be incremented by one, which indicates new SDP that must be parsed.
The origin (o=) line version number must either be the same as the last one sent, which indicates that this SDP is identical to the previous exchange, or it may be incremented by one, which indicates new SDP that must be parsed.
The offer must include all existing media lines and they must be sent in the same order.
The offer must include all existing media lines and they must be sent in the same order.
Additional media streams can be added to the end of the m= line list.
Additional media streams can be added to the end of the m= line list.
An existing media stream can be deleted by setting the port number to 0. This media line must remain in the SDP and all future offer/answer exchanges for this session.
An existing media stream can be deleted by setting the port number to 0. This media line must remain in the SDP and all future offer/answer exchanges for this session.
One party in a call can temporarily place the other on hold. This is done by sending an INVITE with an identical SDP to that of the original INVITE but with a = sendonly attribute present.
The call is made active again by sending another INVITE with the a = sendrecv attribute present. The following illustration shows the call flow of a call hold.
27 Lectures
2.5 hours
Bernie Raffe
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 1974,
"s": 1850,
"text": "The use of SDP with SIP is given in the SDP offer answer RFC 3264. The default message body type in SIP is application/sdp."
},
{
"code": null,
"e": 2104,
"s": 1974,
"text": "The calling party lists the media capabilities that they are willing to receive in SDP, usually in either an INVITE or in an ACK."
},
{
"code": null,
"e": 2234,
"s": 2104,
"text": "The calling party lists the media capabilities that they are willing to receive in SDP, usually in either an INVITE or in an ACK."
},
{
"code": null,
"e": 2320,
"s": 2234,
"text": "The called party lists their media capabilities in the 200 OK response to the INVITE."
},
{
"code": null,
"e": 2406,
"s": 2320,
"text": "The called party lists their media capabilities in the 200 OK response to the INVITE."
},
{
"code": null,
"e": 2543,
"s": 2406,
"text": "A typical SIP use of SDP includes the following fields: version, origin, subject, time, connection, and one or more media and attribute."
},
{
"code": null,
"e": 2627,
"s": 2543,
"text": "The subject and time fields are not used by SIP but are included for compatibility."
},
{
"code": null,
"e": 2711,
"s": 2627,
"text": "The subject and time fields are not used by SIP but are included for compatibility."
},
{
"code": null,
"e": 2855,
"s": 2711,
"text": "In the SDP standard, the subject field is a required field and must contain at least one character, suggested to be s=- if there is no subject."
},
{
"code": null,
"e": 2999,
"s": 2855,
"text": "In the SDP standard, the subject field is a required field and must contain at least one character, suggested to be s=- if there is no subject."
},
{
"code": null,
"e": 3125,
"s": 2999,
"text": "The time field is usually set to t = 00. SIP uses the connection, media, and attribute fields to set up sessions between UAs."
},
{
"code": null,
"e": 3251,
"s": 3125,
"text": "The time field is usually set to t = 00. SIP uses the connection, media, and attribute fields to set up sessions between UAs."
},
{
"code": null,
"e": 3294,
"s": 3251,
"text": "The origin field has limited use with SIP."
},
{
"code": null,
"e": 3337,
"s": 3294,
"text": "The origin field has limited use with SIP."
},
{
"code": null,
"e": 3403,
"s": 3337,
"text": "The session-id is usually kept constant throughout a SIP session."
},
{
"code": null,
"e": 3469,
"s": 3403,
"text": "The session-id is usually kept constant throughout a SIP session."
},
{
"code": null,
"e": 3618,
"s": 3469,
"text": "The version is incremented each time the SDP is changed. If the SDP being sent is unchanged from that sent previously, the version is kept the same."
},
{
"code": null,
"e": 3767,
"s": 3618,
"text": "The version is incremented each time the SDP is changed. If the SDP being sent is unchanged from that sent previously, the version is kept the same."
},
{
"code": null,
"e": 3973,
"s": 3767,
"text": "As the type of media session and codec to be used are part of the connection negotiation, SIP can use SDP to specify multiple alternative media types and to selectively accept or decline those media types."
},
{
"code": null,
"e": 4179,
"s": 3973,
"text": "As the type of media session and codec to be used are part of the connection negotiation, SIP can use SDP to specify multiple alternative media types and to selectively accept or decline those media types."
},
{
"code": null,
"e": 4420,
"s": 4179,
"text": "The offer/answer specification, RFC 3264, recommends that an attribute containing a = rtpmap: be used for each media field. A media stream is declined by setting the port number to zero for the corresponding media field in the SDP response."
},
{
"code": null,
"e": 4595,
"s": 4420,
"text": "In the following example, the caller Tesla wants to set up an audio and video call with two possible audio codecs and a video codec in the SDP carried in the initial INVITE −"
},
{
"code": null,
"e": 4833,
"s": 4595,
"text": "v = 0 \no = John 0844526 2890844526 IN IP4 172.22.1.102 \ns = - \nc = IN IP4 172.22.1.102 \nt = 0 0 \nm = audio 6000 RTP/AVP 97 98 \na = rtpmap:97 AMR/16000/1 \na = rtpmap:98 AMR-WB/8000/1 \nm = video 49172 RTP/AVP 32 \na = rtpmap:32 MPV/90000 \n"
},
{
"code": null,
"e": 4898,
"s": 4833,
"text": "The codecs are referenced by the RTP/AVP profile numbers 97, 98."
},
{
"code": null,
"e": 5054,
"s": 4898,
"text": "The called party Marry answers the call, chooses the second codec for the first media field, and declines the second media field, only wanting AMR session."
},
{
"code": null,
"e": 5235,
"s": 5054,
"text": "v = 0 \no = Marry 2890844526 2890844526 IN IP4 172.22.1.110 \ns = - \nc = IN IP4 200.201.202.203 \nt = 0 0 \nm = audio 60000 RTP/AVP 8 \na = rtpmap:97 AMR/16000 \nm = video 0 RTP/AVP 32 \n"
},
{
"code": null,
"e": 5413,
"s": 5235,
"text": "If this audio-only call is not acceptable, then Tom would send an ACK then a BYE to cancel the call. Otherwise, the audio session would be established and RTP packets exchanged."
},
{
"code": null,
"e": 5621,
"s": 5413,
"text": "As this example illustrates, unless the number and order of media fields is maintained, the calling party would not know for certain which media sessions were being accepted and declined by the called party."
},
{
"code": null,
"e": 5686,
"s": 5621,
"text": "The offer/answer rules are summarized in the following sections."
},
{
"code": null,
"e": 5810,
"s": 5686,
"text": "An SDP offer must include all required SDP fields (this includes v=, o=, s=, c=,and t=). These are mandatory fields in SDP."
},
{
"code": null,
"e": 6160,
"s": 5810,
"text": "It usually includes a media field (m=) but it does not have to. The media lines contain all codecs listed in preference order. The only exception to this is if the endpoint supports a huge number of codecs, the most likely to be accepted or most preferred should be listed. Different media types include audio, video, text, MSRP, BFCP, and so forth."
},
{
"code": null,
"e": 6241,
"s": 6160,
"text": "An SDP answer to an offer must be constructed according to the following rules −"
},
{
"code": null,
"e": 6323,
"s": 6241,
"text": "The answer must have the same number of m= lines in the same order as the answer."
},
{
"code": null,
"e": 6405,
"s": 6323,
"text": "The answer must have the same number of m= lines in the same order as the answer."
},
{
"code": null,
"e": 6479,
"s": 6405,
"text": "Individual media streams can be declined by setting the port number to 0."
},
{
"code": null,
"e": 6553,
"s": 6479,
"text": "Individual media streams can be declined by setting the port number to 0."
},
{
"code": null,
"e": 6608,
"s": 6553,
"text": "Streams are accepted by sending a nonzero port number."
},
{
"code": null,
"e": 6663,
"s": 6608,
"text": "Streams are accepted by sending a nonzero port number."
},
{
"code": null,
"e": 6757,
"s": 6663,
"text": "The listed payloads for each media type must be a subset of the payloads listed in the offer."
},
{
"code": null,
"e": 6851,
"s": 6757,
"text": "The listed payloads for each media type must be a subset of the payloads listed in the offer."
},
{
"code": null,
"e": 6993,
"s": 6851,
"text": "For dynamic payloads, the same dynamic payload number does not need to be used in each direction. Usually, only a single payload is selected."
},
{
"code": null,
"e": 7135,
"s": 6993,
"text": "For dynamic payloads, the same dynamic payload number does not need to be used in each direction. Usually, only a single payload is selected."
},
{
"code": null,
"e": 7279,
"s": 7135,
"text": "Either party can initiate another offer/answer exchange to modify a session. When a session is modified, the following rules must be followed −"
},
{
"code": null,
"e": 7508,
"s": 7279,
"text": "The origin (o=) line version number must either be the same as the last one sent, which indicates that this SDP is identical to the previous exchange, or it may be incremented by one, which indicates new SDP that must be parsed."
},
{
"code": null,
"e": 7737,
"s": 7508,
"text": "The origin (o=) line version number must either be the same as the last one sent, which indicates that this SDP is identical to the previous exchange, or it may be incremented by one, which indicates new SDP that must be parsed."
},
{
"code": null,
"e": 7826,
"s": 7737,
"text": "The offer must include all existing media lines and they must be sent in the same order."
},
{
"code": null,
"e": 7915,
"s": 7826,
"text": "The offer must include all existing media lines and they must be sent in the same order."
},
{
"code": null,
"e": 7985,
"s": 7915,
"text": "Additional media streams can be added to the end of the m= line list."
},
{
"code": null,
"e": 8055,
"s": 7985,
"text": "Additional media streams can be added to the end of the m= line list."
},
{
"code": null,
"e": 8223,
"s": 8055,
"text": "An existing media stream can be deleted by setting the port number to 0. This media line must remain in the SDP and all future offer/answer exchanges for this session."
},
{
"code": null,
"e": 8391,
"s": 8223,
"text": "An existing media stream can be deleted by setting the port number to 0. This media line must remain in the SDP and all future offer/answer exchanges for this session."
},
{
"code": null,
"e": 8580,
"s": 8391,
"text": "One party in a call can temporarily place the other on hold. This is done by sending an INVITE with an identical SDP to that of the original INVITE but with a = sendonly attribute present."
},
{
"code": null,
"e": 8740,
"s": 8580,
"text": "The call is made active again by sending another INVITE with the a = sendrecv attribute present. The following illustration shows the call flow of a call hold."
},
{
"code": null,
"e": 8775,
"s": 8740,
"text": "\n 27 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 8789,
"s": 8775,
"text": " Bernie Raffe"
},
{
"code": null,
"e": 8796,
"s": 8789,
"text": " Print"
},
{
"code": null,
"e": 8807,
"s": 8796,
"text": " Add Notes"
}
] |
Java program to count the number of consonants in a given sentence | To count the number of consonants in a given sentence:
Read a sentence from the user.
Create a variable (count) initialize it with 0;
Compare each character in the sentence with the characters {'a', 'e', 'i', 'o', 'u' } If match doesn't occurs increment the count.
Finally print count.
import java.util.Scanner;
public class CountingConsonants {
public static void main(String args[]){
int count = 0;
System.out.println("Enter a sentence :");
Scanner sc = new Scanner(System.in);
String sentence = sc.nextLine();
for (int i=0 ; i<sentence.length(); i++){
char ch = sentence.charAt(i);
if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' ){
System.out.print("");
}else if(ch != ' '){
count++;
}
}
System.out.println("Number of consonants in the given sentence is "+count);
}
}
Enter a sentence :
Hi hello how are you welcome to tutorialspoint
Number of consonants in the given sentence is 21 | [
{
"code": null,
"e": 1117,
"s": 1062,
"text": "To count the number of consonants in a given sentence:"
},
{
"code": null,
"e": 1149,
"s": 1117,
"text": " Read a sentence from the user."
},
{
"code": null,
"e": 1198,
"s": 1149,
"text": " Create a variable (count) initialize it with 0;"
},
{
"code": null,
"e": 1330,
"s": 1198,
"text": " Compare each character in the sentence with the characters {'a', 'e', 'i', 'o', 'u' } If match doesn't occurs increment the count."
},
{
"code": null,
"e": 1352,
"s": 1330,
"text": " Finally print count."
},
{
"code": null,
"e": 1964,
"s": 1352,
"text": "import java.util.Scanner;\npublic class CountingConsonants {\n public static void main(String args[]){\n int count = 0;\n System.out.println(\"Enter a sentence :\");\n Scanner sc = new Scanner(System.in);\n String sentence = sc.nextLine();\n\n for (int i=0 ; i<sentence.length(); i++){\n char ch = sentence.charAt(i);\n if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' ){\n System.out.print(\"\");\n }else if(ch != ' '){\n count++;\n }\n }\n System.out.println(\"Number of consonants in the given sentence is \"+count);\n }\n}"
},
{
"code": null,
"e": 2079,
"s": 1964,
"text": "Enter a sentence :\nHi hello how are you welcome to tutorialspoint\nNumber of consonants in the given sentence is 21"
}
] |
C++ Utility Library - swap Function | It exchanges the values of a and b.
Following is the declaration for std::swap function.
template <class T> void swap (T& a, T& b);
template <class T> void swap (T& a, T& b)
noexcept (is_nothrow_move_constructible<T>::value && is_nothrow_move_assignable<T>::value);
a, b − These are two objects.
none
Basic guarantee − if the construction or assignment of type T throws.
Both a and b are modified.
In below example explains about std::swap function.
#include <iostream>
#include <utility>
int main () {
int foo[4];
int bar[] = {100,200,300,400};
std::swap(foo,bar);
std::cout << "foo contains:";
for (int i: foo) std::cout << ' ' << i;
std::cout << '\n';
return 0;
}
Let us compile and run the above program, this will produce the following result −
foo contains: 100 200 300 400
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2639,
"s": 2603,
"text": "It exchanges the values of a and b."
},
{
"code": null,
"e": 2692,
"s": 2639,
"text": "Following is the declaration for std::swap function."
},
{
"code": null,
"e": 2735,
"s": 2692,
"text": "template <class T> void swap (T& a, T& b);"
},
{
"code": null,
"e": 2872,
"s": 2735,
"text": "template <class T> void swap (T& a, T& b)\n noexcept (is_nothrow_move_constructible<T>::value && is_nothrow_move_assignable<T>::value);"
},
{
"code": null,
"e": 2902,
"s": 2872,
"text": "a, b − These are two objects."
},
{
"code": null,
"e": 2907,
"s": 2902,
"text": "none"
},
{
"code": null,
"e": 2977,
"s": 2907,
"text": "Basic guarantee − if the construction or assignment of type T throws."
},
{
"code": null,
"e": 3004,
"s": 2977,
"text": "Both a and b are modified."
},
{
"code": null,
"e": 3056,
"s": 3004,
"text": "In below example explains about std::swap function."
},
{
"code": null,
"e": 3298,
"s": 3056,
"text": "#include <iostream>\n#include <utility>\n\nint main () {\n\n int foo[4];\n int bar[] = {100,200,300,400};\n std::swap(foo,bar);\n\n std::cout << \"foo contains:\";\n for (int i: foo) std::cout << ' ' << i;\n std::cout << '\\n';\n\n return 0;\n}"
},
{
"code": null,
"e": 3381,
"s": 3298,
"text": "Let us compile and run the above program, this will produce the following result −"
},
{
"code": null,
"e": 3412,
"s": 3381,
"text": "foo contains: 100 200 300 400\n"
},
{
"code": null,
"e": 3419,
"s": 3412,
"text": " Print"
},
{
"code": null,
"e": 3430,
"s": 3419,
"text": " Add Notes"
}
] |
How to convert a single char into an int in C++ | The following is an example to convert a character into int.
Live Demo
#include <iostream>
using namespace std;
int main() {
char c = '8';
int i = c - 48;
cout << i;
i = c - '0';
cout <<"\t" << i;
return 0;
}
8 8
In the above program, a character ‘c’ is initialized with a value. The character is converted into integer value as shown below −
char c = '8';
int i = c - 48;
cout << i;
i = c - '0';
cout <<"\t" << i; | [
{
"code": null,
"e": 1123,
"s": 1062,
"text": "The following is an example to convert a character into int."
},
{
"code": null,
"e": 1134,
"s": 1123,
"text": " Live Demo"
},
{
"code": null,
"e": 1290,
"s": 1134,
"text": "#include <iostream>\nusing namespace std;\nint main() {\n char c = '8';\n int i = c - 48;\n cout << i;\n i = c - '0';\n cout <<\"\\t\" << i;\n return 0;\n}"
},
{
"code": null,
"e": 1294,
"s": 1290,
"text": "8 8"
},
{
"code": null,
"e": 1424,
"s": 1294,
"text": "In the above program, a character ‘c’ is initialized with a value. The character is converted into integer value as shown below −"
},
{
"code": null,
"e": 1496,
"s": 1424,
"text": "char c = '8';\nint i = c - 48;\ncout << i;\ni = c - '0';\ncout <<\"\\t\" << i;"
}
] |
Turning a Raspberry Pi 3B+ into a powerful object recognition edge server with Intel Movidius NCS2 | by Alexey Györi | Towards Data Science | In this part, we are going to use a readily compiled neural network in the Intel Neural Compute stick in order for it to be able to receive Base64 encoded images and turn them into bounding-box predictions. Additionally, an example for a front-end that sends camera input to the PI will be provided. Please make sure to also check out the amazing write-up on how to deploy and test models by Mattio Varile.
A pre-trained and compiled model will be provided in an attachment.
Training and compiling the model for a custom dataset and more details on the front end will be part of another story, so stay tuned!
0. Requirements
1. Preparing the Raspberry PI
1.1. Install the NOOBS image
1.2. Install the latest Intel OpenVINO software
1.3. Deploying object detection on the neural compute stick
3. Running the server and setting up auto-start on boot
4. Using a sample GUI to deploy our server
5. Conclusions and outlook
Update 1, 29.05.2019: system diagram now included,Update 2, 05.08.2019: pybase64 removed from requirements as not used
Raspberry PI, preferably a model 3B+ but any other model should do fine as well https://www.raspberrypi.org/products
Intel NCS2 https://software.intel.com/en-us/neural-compute-stick
Optional
Some USB webcam
Some other computer for the front end to run on
Flash the NOOBS image on a FAT32 formatted micro SD card. https://www.raspberrypi.org/downloads/
Boot up the USB image normally, set an account password, connect to the internet, etc...
Make sure to also install python3 and pip3 and wget
sudo apt-get updatesudo apt-get install python3-picamera python3-pip wget
Download the OpenVINO toolkit
cd ~/Downloads && wget https://download.01.org/opencv/2019/openvinotoolkit/l_openvino_toolkit_raspbi_p_2019.1.094.tgz
I recommend to follow the following guide up until (not including) the section “Build and Run Object Detection Samples”.
docs.openvinotoolkit.org
After doing everything successfully, you should see the following output when you open up a new terminal:
We are going to use a flask server which receives encoded images for prediction. You can find all of the code in the following github repository https://github.com/AlexeyGy/NCS2-server
a) Firstly create a new folder named detection_server in your home folder.
mkdir ~/detection_server && cd detection_server
b) create a requirements.txt file with the following content. This file contains the packages that are needed.
flask is the webserver and flask-cors is a wrapper which passes CORS headers (needed for cross-site scripts), more on it here
Note that OpenCV (cv2) is not part of this package list as that package is installed together with OpenVINO in step 1.2. This is because OpenVINO provides its own flavor of cv2 including support for CNN architectures.
flask-corsflask
now run
pip3 install -r requirements.txt
to install the packages automatically.
c) set up the server start script, create a file named RUN.SH
d) Download a pre-trained MobileNet-SSD architecture intermediate representation files which can differentiate between screws and rawl pegs. Stay tuned for the second part of this tutorial where we will cover training.
mkdir models && cd models && wget https://github.com/AlexeyGy/NCS2-server/raw/master/models/no_bn.bin && wget https://github.com/AlexeyGy/NCS2-server/raw/master/models/labelmap.prototxt && wget https://raw.githubusercontent.com/AlexeyGy/NCS2-server/master/models/no_bn.xml
You can see that the architecture contains three files, a labelmap that contains possible labels, a .bin file that contains the frozen network weights and a .xml file that contains the net topology. More info on this can be found here.
e) now let’s create the actual server, create the file server.py with the following content. More details on the individual functionalities will be provided below.
On line 12, we read the provided model files using the Intel OpenVino cv2.dnn.readNet function
line 14 sets a preferable target for our computation to run on
lines 17- 19 contain some standard config for our flask server,
line 23 uses the flask-cors wrapper to set the CORS header, more info here
lines 25–29 are optional, they set a filter for all incoming data which does not consist of images in the right format of jpg or png
line 31 sets the default route for our flask server, we accept POST requests which contain an image
line 37 allows us to accept a threshold in addition to the image which we pass to the server s.t. all predictions lower than the threshold are not returned
line 43 returns a JSON of the prediction results
the function in lines 46–50 does the actual image processing, we will get into the according util_mobilnet.py file in a moment. Here is a high level overview on what it does — firstly a preprocessing and scaling step is executed which is specific to the Mobilenet-SSD architecture — then the network does the inference (lines, 48–49) — finally a postprocessing step is executed including the threshold filtering
f) finally, let’s create and look at the util_mobilnet.py file
line 5 configures the dimensions which mobilnet requires, as it was trained on 300x300 square images, we set just this as our dimensions
the read_labels function reads the labelmap file line by line to define the supported classes
the preprocessing function in line 21 handles colors and dimensions of the incoming image, the arbitrarily looking transformations are needed for mobilnet to process the image correctly
The postprocess function in line 32 goes over all the predictions and filters out predictions below the threshold, additionally the background prediction is not returned
To minimize resource usage on the raspberry PI, we want to set-up a client server application where a flask server receives pictures and returns the bounding-box predictions.
I found out the best way to autostart flask is to a) add the flask start up to the .bashrc file in the pi home folder and b) to set the system to autostart to cli with autologin.
a) As for adding the lines to the .bashrc file, make sure to set the “Downloads” folder to the folder where you have downloaded your OpenVINO toolkit
b) run the following line in a terminal
sudo raspi-config
you will see the following screens where you should select the options 3 Boot options / 1 Desktop CLI / 2 Console Autologin
now, after starting, you will see that the Raspberry will start the flask server automatically on port 5000, congratulations!
The following steps should be executed on another machine but they can be done on the Raspberry as well if you chose to run the GUI on it (will lead to lower performance).
clone the repository https://github.com/AlexeyGy/NCS2-frontend
git clone https://github.com/AlexeyGy/NCS2-frontend
simply run the RUN.SH file to get a simple python server running. You can access it via localhost:8000, you may have to give it access to your camera before you see any images though.
The server will post webcam pictures to the address http://192.168.0.2:5000/, if you are on another machine than your raspberry, make sure to customize that to the address of your raspberry.
I will do another post on how the JavaScript frontend ensures that the bounding boxes drawing is only refreshed when it receives a new response from our raspberry server.
The given sample GUI was from a pilot demonstrator at FIR which we used to demonstrate possible use-cases for a smart contract plattform. More on that in a later post.
You can debug the set-up via your browser’s JavaScript console.
Here is a gif of the whole system of front- and backend running together:
Example detection of screws and rawl plugs
The running system is able to deliver 60fps video with about 8 fps on detections if ran on two machines. The user experience is not impacted as the predictions are displayed in an async way by the JavaScript frontend .I have found it actually to be true that too many detection fps lead to a worse user experience as the detections are updated too quickly!
With the onset of edge computing, as other competitors like Google have also entered the race we are up for some exciting future use-cases for neural compute sticks.
Write-up on how to deploy and test models by Mattio Varile
Intel Neural compute stick official tutorial
More information on Movidius on Raspberry inc. performance measurements by Adrian Rosebrock | [
{
"code": null,
"e": 579,
"s": 172,
"text": "In this part, we are going to use a readily compiled neural network in the Intel Neural Compute stick in order for it to be able to receive Base64 encoded images and turn them into bounding-box predictions. Additionally, an example for a front-end that sends camera input to the PI will be provided. Please make sure to also check out the amazing write-up on how to deploy and test models by Mattio Varile."
},
{
"code": null,
"e": 647,
"s": 579,
"text": "A pre-trained and compiled model will be provided in an attachment."
},
{
"code": null,
"e": 781,
"s": 647,
"text": "Training and compiling the model for a custom dataset and more details on the front end will be part of another story, so stay tuned!"
},
{
"code": null,
"e": 797,
"s": 781,
"text": "0. Requirements"
},
{
"code": null,
"e": 827,
"s": 797,
"text": "1. Preparing the Raspberry PI"
},
{
"code": null,
"e": 856,
"s": 827,
"text": "1.1. Install the NOOBS image"
},
{
"code": null,
"e": 904,
"s": 856,
"text": "1.2. Install the latest Intel OpenVINO software"
},
{
"code": null,
"e": 964,
"s": 904,
"text": "1.3. Deploying object detection on the neural compute stick"
},
{
"code": null,
"e": 1020,
"s": 964,
"text": "3. Running the server and setting up auto-start on boot"
},
{
"code": null,
"e": 1063,
"s": 1020,
"text": "4. Using a sample GUI to deploy our server"
},
{
"code": null,
"e": 1090,
"s": 1063,
"text": "5. Conclusions and outlook"
},
{
"code": null,
"e": 1209,
"s": 1090,
"text": "Update 1, 29.05.2019: system diagram now included,Update 2, 05.08.2019: pybase64 removed from requirements as not used"
},
{
"code": null,
"e": 1326,
"s": 1209,
"text": "Raspberry PI, preferably a model 3B+ but any other model should do fine as well https://www.raspberrypi.org/products"
},
{
"code": null,
"e": 1391,
"s": 1326,
"text": "Intel NCS2 https://software.intel.com/en-us/neural-compute-stick"
},
{
"code": null,
"e": 1400,
"s": 1391,
"text": "Optional"
},
{
"code": null,
"e": 1416,
"s": 1400,
"text": "Some USB webcam"
},
{
"code": null,
"e": 1464,
"s": 1416,
"text": "Some other computer for the front end to run on"
},
{
"code": null,
"e": 1561,
"s": 1464,
"text": "Flash the NOOBS image on a FAT32 formatted micro SD card. https://www.raspberrypi.org/downloads/"
},
{
"code": null,
"e": 1650,
"s": 1561,
"text": "Boot up the USB image normally, set an account password, connect to the internet, etc..."
},
{
"code": null,
"e": 1702,
"s": 1650,
"text": "Make sure to also install python3 and pip3 and wget"
},
{
"code": null,
"e": 1776,
"s": 1702,
"text": "sudo apt-get updatesudo apt-get install python3-picamera python3-pip wget"
},
{
"code": null,
"e": 1806,
"s": 1776,
"text": "Download the OpenVINO toolkit"
},
{
"code": null,
"e": 1924,
"s": 1806,
"text": "cd ~/Downloads && wget https://download.01.org/opencv/2019/openvinotoolkit/l_openvino_toolkit_raspbi_p_2019.1.094.tgz"
},
{
"code": null,
"e": 2045,
"s": 1924,
"text": "I recommend to follow the following guide up until (not including) the section “Build and Run Object Detection Samples”."
},
{
"code": null,
"e": 2070,
"s": 2045,
"text": "docs.openvinotoolkit.org"
},
{
"code": null,
"e": 2176,
"s": 2070,
"text": "After doing everything successfully, you should see the following output when you open up a new terminal:"
},
{
"code": null,
"e": 2361,
"s": 2176,
"text": "We are going to use a flask server which receives encoded images for prediction. You can find all of the code in the following github repository https://github.com/AlexeyGy/NCS2-server"
},
{
"code": null,
"e": 2436,
"s": 2361,
"text": "a) Firstly create a new folder named detection_server in your home folder."
},
{
"code": null,
"e": 2484,
"s": 2436,
"text": "mkdir ~/detection_server && cd detection_server"
},
{
"code": null,
"e": 2595,
"s": 2484,
"text": "b) create a requirements.txt file with the following content. This file contains the packages that are needed."
},
{
"code": null,
"e": 2721,
"s": 2595,
"text": "flask is the webserver and flask-cors is a wrapper which passes CORS headers (needed for cross-site scripts), more on it here"
},
{
"code": null,
"e": 2939,
"s": 2721,
"text": "Note that OpenCV (cv2) is not part of this package list as that package is installed together with OpenVINO in step 1.2. This is because OpenVINO provides its own flavor of cv2 including support for CNN architectures."
},
{
"code": null,
"e": 2955,
"s": 2939,
"text": "flask-corsflask"
},
{
"code": null,
"e": 2963,
"s": 2955,
"text": "now run"
},
{
"code": null,
"e": 2996,
"s": 2963,
"text": "pip3 install -r requirements.txt"
},
{
"code": null,
"e": 3035,
"s": 2996,
"text": "to install the packages automatically."
},
{
"code": null,
"e": 3097,
"s": 3035,
"text": "c) set up the server start script, create a file named RUN.SH"
},
{
"code": null,
"e": 3316,
"s": 3097,
"text": "d) Download a pre-trained MobileNet-SSD architecture intermediate representation files which can differentiate between screws and rawl pegs. Stay tuned for the second part of this tutorial where we will cover training."
},
{
"code": null,
"e": 3589,
"s": 3316,
"text": "mkdir models && cd models && wget https://github.com/AlexeyGy/NCS2-server/raw/master/models/no_bn.bin && wget https://github.com/AlexeyGy/NCS2-server/raw/master/models/labelmap.prototxt && wget https://raw.githubusercontent.com/AlexeyGy/NCS2-server/master/models/no_bn.xml"
},
{
"code": null,
"e": 3825,
"s": 3589,
"text": "You can see that the architecture contains three files, a labelmap that contains possible labels, a .bin file that contains the frozen network weights and a .xml file that contains the net topology. More info on this can be found here."
},
{
"code": null,
"e": 3989,
"s": 3825,
"text": "e) now let’s create the actual server, create the file server.py with the following content. More details on the individual functionalities will be provided below."
},
{
"code": null,
"e": 4084,
"s": 3989,
"text": "On line 12, we read the provided model files using the Intel OpenVino cv2.dnn.readNet function"
},
{
"code": null,
"e": 4147,
"s": 4084,
"text": "line 14 sets a preferable target for our computation to run on"
},
{
"code": null,
"e": 4211,
"s": 4147,
"text": "lines 17- 19 contain some standard config for our flask server,"
},
{
"code": null,
"e": 4286,
"s": 4211,
"text": "line 23 uses the flask-cors wrapper to set the CORS header, more info here"
},
{
"code": null,
"e": 4419,
"s": 4286,
"text": "lines 25–29 are optional, they set a filter for all incoming data which does not consist of images in the right format of jpg or png"
},
{
"code": null,
"e": 4519,
"s": 4419,
"text": "line 31 sets the default route for our flask server, we accept POST requests which contain an image"
},
{
"code": null,
"e": 4675,
"s": 4519,
"text": "line 37 allows us to accept a threshold in addition to the image which we pass to the server s.t. all predictions lower than the threshold are not returned"
},
{
"code": null,
"e": 4724,
"s": 4675,
"text": "line 43 returns a JSON of the prediction results"
},
{
"code": null,
"e": 5136,
"s": 4724,
"text": "the function in lines 46–50 does the actual image processing, we will get into the according util_mobilnet.py file in a moment. Here is a high level overview on what it does — firstly a preprocessing and scaling step is executed which is specific to the Mobilenet-SSD architecture — then the network does the inference (lines, 48–49) — finally a postprocessing step is executed including the threshold filtering"
},
{
"code": null,
"e": 5199,
"s": 5136,
"text": "f) finally, let’s create and look at the util_mobilnet.py file"
},
{
"code": null,
"e": 5336,
"s": 5199,
"text": "line 5 configures the dimensions which mobilnet requires, as it was trained on 300x300 square images, we set just this as our dimensions"
},
{
"code": null,
"e": 5430,
"s": 5336,
"text": "the read_labels function reads the labelmap file line by line to define the supported classes"
},
{
"code": null,
"e": 5616,
"s": 5430,
"text": "the preprocessing function in line 21 handles colors and dimensions of the incoming image, the arbitrarily looking transformations are needed for mobilnet to process the image correctly"
},
{
"code": null,
"e": 5786,
"s": 5616,
"text": "The postprocess function in line 32 goes over all the predictions and filters out predictions below the threshold, additionally the background prediction is not returned"
},
{
"code": null,
"e": 5961,
"s": 5786,
"text": "To minimize resource usage on the raspberry PI, we want to set-up a client server application where a flask server receives pictures and returns the bounding-box predictions."
},
{
"code": null,
"e": 6140,
"s": 5961,
"text": "I found out the best way to autostart flask is to a) add the flask start up to the .bashrc file in the pi home folder and b) to set the system to autostart to cli with autologin."
},
{
"code": null,
"e": 6290,
"s": 6140,
"text": "a) As for adding the lines to the .bashrc file, make sure to set the “Downloads” folder to the folder where you have downloaded your OpenVINO toolkit"
},
{
"code": null,
"e": 6330,
"s": 6290,
"text": "b) run the following line in a terminal"
},
{
"code": null,
"e": 6348,
"s": 6330,
"text": "sudo raspi-config"
},
{
"code": null,
"e": 6472,
"s": 6348,
"text": "you will see the following screens where you should select the options 3 Boot options / 1 Desktop CLI / 2 Console Autologin"
},
{
"code": null,
"e": 6598,
"s": 6472,
"text": "now, after starting, you will see that the Raspberry will start the flask server automatically on port 5000, congratulations!"
},
{
"code": null,
"e": 6770,
"s": 6598,
"text": "The following steps should be executed on another machine but they can be done on the Raspberry as well if you chose to run the GUI on it (will lead to lower performance)."
},
{
"code": null,
"e": 6833,
"s": 6770,
"text": "clone the repository https://github.com/AlexeyGy/NCS2-frontend"
},
{
"code": null,
"e": 6885,
"s": 6833,
"text": "git clone https://github.com/AlexeyGy/NCS2-frontend"
},
{
"code": null,
"e": 7069,
"s": 6885,
"text": "simply run the RUN.SH file to get a simple python server running. You can access it via localhost:8000, you may have to give it access to your camera before you see any images though."
},
{
"code": null,
"e": 7260,
"s": 7069,
"text": "The server will post webcam pictures to the address http://192.168.0.2:5000/, if you are on another machine than your raspberry, make sure to customize that to the address of your raspberry."
},
{
"code": null,
"e": 7431,
"s": 7260,
"text": "I will do another post on how the JavaScript frontend ensures that the bounding boxes drawing is only refreshed when it receives a new response from our raspberry server."
},
{
"code": null,
"e": 7599,
"s": 7431,
"text": "The given sample GUI was from a pilot demonstrator at FIR which we used to demonstrate possible use-cases for a smart contract plattform. More on that in a later post."
},
{
"code": null,
"e": 7663,
"s": 7599,
"text": "You can debug the set-up via your browser’s JavaScript console."
},
{
"code": null,
"e": 7737,
"s": 7663,
"text": "Here is a gif of the whole system of front- and backend running together:"
},
{
"code": null,
"e": 7780,
"s": 7737,
"text": "Example detection of screws and rawl plugs"
},
{
"code": null,
"e": 8137,
"s": 7780,
"text": "The running system is able to deliver 60fps video with about 8 fps on detections if ran on two machines. The user experience is not impacted as the predictions are displayed in an async way by the JavaScript frontend .I have found it actually to be true that too many detection fps lead to a worse user experience as the detections are updated too quickly!"
},
{
"code": null,
"e": 8303,
"s": 8137,
"text": "With the onset of edge computing, as other competitors like Google have also entered the race we are up for some exciting future use-cases for neural compute sticks."
},
{
"code": null,
"e": 8362,
"s": 8303,
"text": "Write-up on how to deploy and test models by Mattio Varile"
},
{
"code": null,
"e": 8407,
"s": 8362,
"text": "Intel Neural compute stick official tutorial"
}
] |
The system() Function in Perl | You can use system() Perl function to execute any Unix command, whose output will go to the output of the perl script. By default, it is the screen, i.e., STDOUT, but you can redirect it to any file by using redirection operator > −
#!/usr/bin/perl
system( "ls -l")
1;
When above code is executed, it lists down all the files and directories available in the current directory −
drwxr-xr-x 3 root root 4096 Sep 14 06:46 9-14
drwxr-xr-x 4 root root 4096 Sep 13 07:54 android
-rw-r--r-- 1 root root 574 Sep 17 15:16 index.htm
drwxr-xr-x 3 544 401 4096 Jul 6 16:49 MIME-Lite-3.01
-rw-r--r-- 1 root root 71 Sep 17 15:16 test.pl
drwx------ 2 root root 4096 Sep 17 15:11 vAtrJdy
Be careful when your command contains shell environmental variables like PATHorHOME. Try following three scenarios −
#!/usr/bin/perl
$PATH = "I am Perl Variable";
system('echo $PATH'); # Treats $PATH as shell variable
system("echo $PATH"); # Treats $PATH as Perl variable
system("echo \$PATH"); # Escaping $ works.
1;
When above code is executed, it produces the following result depending on what is set in shell variable $PATH.
/usr/local/bin:/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/sbin
I am Perl Variable
/usr/local/bin:/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/sbin | [
{
"code": null,
"e": 1295,
"s": 1062,
"text": "You can use system() Perl function to execute any Unix command, whose output will go to the output of the perl script. By default, it is the screen, i.e., STDOUT, but you can redirect it to any file by using redirection operator > −"
},
{
"code": null,
"e": 1331,
"s": 1295,
"text": "#!/usr/bin/perl\nsystem( \"ls -l\")\n1;"
},
{
"code": null,
"e": 1441,
"s": 1331,
"text": "When above code is executed, it lists down all the files and directories available in the current directory −"
},
{
"code": null,
"e": 1735,
"s": 1441,
"text": "drwxr-xr-x 3 root root 4096 Sep 14 06:46 9-14\ndrwxr-xr-x 4 root root 4096 Sep 13 07:54 android\n-rw-r--r-- 1 root root 574 Sep 17 15:16 index.htm\ndrwxr-xr-x 3 544 401 4096 Jul 6 16:49 MIME-Lite-3.01\n-rw-r--r-- 1 root root 71 Sep 17 15:16 test.pl\ndrwx------ 2 root root 4096 Sep 17 15:11 vAtrJdy"
},
{
"code": null,
"e": 1852,
"s": 1735,
"text": "Be careful when your command contains shell environmental variables like PATHorHOME. Try following three scenarios −"
},
{
"code": null,
"e": 2053,
"s": 1852,
"text": "#!/usr/bin/perl\n$PATH = \"I am Perl Variable\";\nsystem('echo $PATH'); # Treats $PATH as shell variable\nsystem(\"echo $PATH\"); # Treats $PATH as Perl variable\nsystem(\"echo \\$PATH\"); # Escaping $ works.\n1;"
},
{
"code": null,
"e": 2165,
"s": 2053,
"text": "When above code is executed, it produces the following result depending on what is set in shell variable $PATH."
},
{
"code": null,
"e": 2306,
"s": 2165,
"text": "/usr/local/bin:/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/sbin\nI am Perl Variable\n/usr/local/bin:/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/sbin"
}
] |
Convolutional Neural Networks for Beginners using Keras & TensorFlow 2 | by Jordi TORRES.AI | Towards Data Science | This is the updated version of a previous post introducing Convolutional Neural Networks that I wrote two years ago. In this post I update the Kera’s code that we use to explain the concepts. Since then, Keras has become TensorFlow’s high-level API for building and training deep learning models. I will use this update for improving the content.
Convolutional neuronal networks are widely used in computer vision tasks. These networks are composed of an input layer, an output layer and several hidden layers, some of which are convolutional, hence its name.
In this post, we will present a specific case that we will follow step by step to understand the basic concepts of this type of networks. Specifically, together with the reader, we will program a convolutional neural network to solve the same MNIST digit recognition problem seen above.
A convolutional neuronal network (with the acronyms CNNs or ConvNets) is a concrete case of Deep Learning neural networks, which were already used at the end of the 90s but which in recent years have become enormously popular when achieving very impressive results in the recognition of image, deeply impacting the area of computer vision.
The convolutional neural networks are very similar to the neural networks of the previous posts in the series: they are formed by neurons that have parameters in the form of weights and biases that can be learned. But a differential feature of the CNN is that they make the explicit assumption that the entries are images, which allows us to encode certain properties in the architecture to recognize specific elements in the images.
To get an intuitive idea of how these neural networks work, let’s think about how we recognize things. For example, if we see a face, we recognize it because it has ears, eyes, a nose, hair, etc. Then, to decide if something is a face, we do it as if we had some mental boxes of verification of the characteristics that we are marking. Sometimes a face may not have an ear because it is covered by hair, but we also classify it with a certain probability as face because we see the eyes, nose and mouth. Actually, we can see it as a classifier equivalent to the one presented in the post “Basic concepts of neural networks”, which predicts a probability that the input image is a face or no face.
But in reality, we must first know what an ear or a nose is like to know if they are in an image; that is, we must previously identify lines, edges, textures or shapes that are similar to those containing the ears or noses we have seen before. And this is what the layers of a convolutional neuronal network are entrusted to do.
But identifying these elements is not enough to be able to say that something is a face. We also must be able to identify how the parts of a face meet each other, relative sizes, etc.; otherwise, the face would not resemble what we are used to. Visually, an intuitive idea of what layers learn is often presented with this example from an article by Andrew Ng’s group.
The idea that we want to give with this visual example is that, in reality, in a convolutional neural network each layer is learning different levels of abstraction. The reader can imagine that, with networks with many layers, it is possible to identify more complex structures in the input data.
Now that we have an intuitive vision of how convolutional neural networks classify an image, we will present an example of recognition of MNIST digits and from it we will introduce the two layers that define convolutional networks that can be expressed as groups of specialized neurons in two operations: convolution and pooling.
The fundamental difference between a densely connected layer and a specialized layer in the convolution operation, which we will call the convolutional layer, is that the dense layer learns global patterns in its global input space, while the convolutional layers learn local patterns in small windows of two dimensions.
In an intuitive way, we could say that the main purpose of a convolutional layer is to detect features or visual features in images such as edges, lines, color drops, etc. This is a very interesting property because, once it has learned a characteristic at a specific point in the image, it can recognize it later in any part of it. Instead, in a densely connected neural network it has to learn the pattern again if it appears in a new location of the image.
Another important feature is that convolutional layers can learn spatial hierarchies of patterns by preserving spatial relationships. For example, a first convolutional layer can learn basic elements such as edges, and a second convolutional layer can learn patterns composed of basic elements learned in the previous layer. And so on until it learns very complex patterns. This allows convolutional neural networks to efficiently learn increasingly complex and abstract visual concepts.
In general, the convolutions layers operate on 3D tensors, called feature maps, with two spatial axes of height and width, as well as a channel axis also called depth. For an RGB color image, the dimension of the depth axis is 3, because the image has three channels: red, green and blue. For a black and white image, such as the MNIST digits, the depth axis dimension is 1 (gray level).
In the case of MNIST, as input to our neural network we can think of a space of two-dimensional neurons 28×28 (height = 28, width = 28, depth = 1). A first layer of hidden neurons connected to the neurons of the input layer that we have discussed will perform the convolutional operations that we have just described. But as we have explained, not all input neurons are connected with all the neurons of this first level of hidden neurons, as in the case of densely connected neural networks; it is only done by small localized areas of the space of input neurons that store the pixels of the image.
The explained, visually, could be represented as:
In the case of our previous example, each neuron of our hidden layer will be connected to a small region of 5×5 neurons (i.e. 25 neurons) of the input layer (28×28). Intuitively, we can think of a 5×5 size window that slides along the entire 28×28 neuron layer of input that contains the image. For each position of the window there is a neuron in the hidden layer that processes this information.
Visually, we start with the window in the top left corner of the image, and this gives the necessary information to the first neuron of the hidden layer. Then, we slide the window one position to the right to “connect” the 5×5 neurons of the input layer included in this window with the second neuron of the hidden layer. And so, successively, we go through the entire space of the input layer, from left to right and top to bottom.
Analyzing a little bit the concrete case we have proposed, we note that, if we have an input of 28×28 pixels and a window of 5×5, this defines a space of 24×24 neurons in the first hidden layer because we can only move the window 23 neurons to the right and 23 neurons to the bottom before hitting the right (or bottom) border of the input image.
We would like to point out to the reader that the assumption we have made is that the window moves forward 1 pixel away, both horizontally and vertically when a new row starts. Therefore, in each step, the new window overlaps the previous one except in this line of pixels that we have advanced. But, as we will see in the next section, in convolutional neural networks, different lengths of advance steps can be used (the parameter called stride). In convolutional neural networks you can also apply a technique of filling zeros around the margin of the image to improve the sweep that is done with the sliding window. The parameter to define this technique is called “padding”, which we will also present in more detail in the next section, with which you can specify the size of this padding.
In our case of study, and following the formalism previously presented, to “connect” each neuron of the hidden layer with the 25 corresponding neurons of the input layer we will use a bias value b and a W-weights matrix of size 5×5 that we will call filter (or kernel). The value of each point of the hidden layer corresponds to the scalar product between the filter and the handful of 25 neurons (5×5) of the input layer.
However, the particular and very important thing about convolutional networks is that we use the same filter (the same W matrix of weights and the same b bias) for all the neurons in the hidden layer: in our case for the 24×24 neurons (576 neurons in total) of the first layer. The reader can see in this particular case that this sharing drastically reduces the number of parameters that a neural network would have if we did not do it: it goes from 14,400 parameters that would have to be adjusted (5×5 × 24×24) to 25 (5×5) parameters plus biases b.
This shared W matrix together with the b bias, which we have already said we call a filter in this context of convolutional networks, is similar to the filters we use to retouch images, which in our case are used to look for local characteristics in small groups of entries. I recommend looking at the examples found in the GIMP image editor manual to get a visual and very intuitive idea of how a convolution process works.
But a filter defined by a matrix W and a bias b only allows detecting a specific characteristic in an image; therefore, in order to perform image recognition, it is proposed to use several filters at the same time, one for each characteristic that we want to detect. That is why a complete convolutional layer in a convolutional neuronal network includes several filters.
A usual way to visually represent this convolutional layer is shown in the following figure, where the level of hidden layers is composed of several filters. In our example we propose 32 filters, where each filter is defined with a W matrix of 5×5 and a bias b.
In this example, the first convolutional layer receives a size input tensor (28, 28, 1) and generates a size output (24, 24, 32), a 3D tensor containing the 32 outputs of 24×24 pixel result of computing the 32 filters on the input.
In addition to the convolutional layers that we have just described, convolutional neural networks accompany the convolution layer with pooling layers, which are usually applied immediately after the convolutional layers. A first approach to understand what these layers are for is to see that the pooling layers simplify the information collected by the convolutional layer and create a condensed version of the information contained in them.
In our MNIST example, we are going to choose a 2×2 window of the convolutional layer and we are going to synthesize the information in a point in the pooling layer. Visually, it can be expressed as follows:
There are several ways to condense the information, but a usual one, which we will use in our example, is known as max-pooling, which as a value keeps the maximum value of those that were in the 2×2 input window in our case. In this case we divide by 4 the size of the output of the pooling layer, leaving an image of 12×12.
Average-pooling can also be used instead of max-pooling, where each group of entry points is transformed into the average value of the group of points instead of its maximum value. But in general, max-pooling tends to work better than alternative solutions.
It is interesting to note that with the transformation of pooling we maintain the spatial relationship. To see it visually, take the following example of a 12×12 matrix where we have represented a “7” (Let’s imagine that the pixels where we pass over contain 1 and the rest 0; we have not added it to the drawing to simplify it). If we apply a max-pooling operation with a 2×2 window (we represent it in the central matrix that divides the space in a mosaic with regions of the size of the window), we obtain a 6×6 matrix where an equivalent representation of 7 is maintained (in the figure on the right where the zeros are marked in white and the points with value 1 in black):
As mentioned above, the convolutional layer hosts more than one filter and, therefore, as we apply the max-pooling to each of them separately, the pooling layer will contain as many pooling filters as there are convolutional filters:
The result is, since we had a space of 24×24 neurons in each convolutional filter, after doing the pooling we have 12×12 neurons which corresponds to the 12×12 regions (of size 2×2 each region) that appear when dividing the filter space.
In this post, we suggest to use the Colaboratory offered by Google and the code I will use in this post is available in the form of Jupyter notebooks in my GitHub here, and executed here using colab.
Before start to define our neural network we need to load the required Python libraries:
%tensorflow_version 2.ximport tensorflow as tffrom tensorflow import kerasimport numpy as npimport matplotlib.pyplot as plt
Let’s see how this example of convolutional neuronal network can be programmed using Keras. As we have said, there are several values to be specified in order to parameterize the convolution and pooling stages. In our case, we will use a simplified model with a stride of 1 in each dimension (size of the step with which the window slides) and a padding of 0 (filling with zeros around the image). Both hyperparameters will be presented below. The pooling will be a max-pooling as described above with a 2×2 window.Basic architecture of a convolutional neuronal network
Let’s move on to implement our first convolutional neuronal network, which will consist of a convolution followed by a max-pooling.
In our case, we will have 32 filters using a 5×5 window for the convolutional layer and a 2×2 window for the pooling layer. We will use the ReLU activation function. In this case, we are configuring a convolutional neural network to process an input tensor of size (28, 28, 1), which is the size of the MNIST images (the third parameter is the color channel which in our case is depth 1), and we specify it by means of the value of the argument input_shape = (28, 28,1) in our first layer:
from tensorflow.keras import Sequentialfrom tensorflow.keras.layers import Conv2Dfrom tensorflow.keras.layers import MaxPooling2Dmodel = Sequential()model.add(Conv2D(32, (5, 5), activation='relu', input_shape=(28, 28, 1)))model.add(MaxPooling2D((2, 2)))
With method summary() we can obtain details about our model:
model.summary()Model: "sequential"_________________________________________________________________Layer (type) Output Shape Param # =================================================================conv2d (Conv2D) (None, 24, 24, 32) 832 _________________________________________________________________max_pooling2d (MaxPooling2D) (None, 12, 12, 32) 0 =================================================================Total params: 832Trainable params: 832Non-trainable params: 0_________________________________________________________________
The number of parameters of the conv2D layer corresponds to the weight matrix W of 5×5 and a b bias for each of the filters is 832 parameters (32 × (25 + 1)). Max-pooling does not require parameters since it is a mathematical operation to find the maximum.
And in order to build a “deep” neural network, we can stack several layers like the one built in the previous section. To show the reader how to do it in our example, we will create a second group of layers that will have 64 filters with a 5×5 window in the convolutional layer and a 2×2 window in the pooling layer. In this case, the number of input channels will take the value of the 32 features that we have obtained from the previous layer, although, as we have seen previously, it is not necessary to specify it because Keras deduces it:
model = models.Sequential()model.add(layers.Conv2D(32,(5,5),activation=’relu’, input_shape=(28,28,1)))model.add(layers.MaxPooling2D((2, 2)))model.add(layers.Conv2D(64, (5, 5), activation=’relu’))model.add(layers.MaxPooling2D((2, 2)))
If the architecture of the model is shown with the summary() method, we can see:
_________________________________________________________________Layer (type) Output Shape Param #=================================================================conv2d_1 (Conv2D) (None, 24, 24, 32) 832_________________________________________________________________max_pooling2d_1 (MaxPooling2 (None, 12, 12, 32) 0_________________________________________________________________conv2d_2 (Conv2D) (None, 8, 8, 64) 51264_________________________________________________________________max_pooling2d_2 (MaxPooling2 (None, 4, 4, 64) 0=================================================================Total params: 52,096Trainable params: 52,096Non-trainable params: 0_________________________________________________________________
In this case, the size of the resulting second convolution layer is 8×8 since we now start from an input space of 12×12×32 and a sliding window of 5×5, taking into account that it has a stride of 1. The number of parameters 51,264 corresponds to the fact that the second layer will have 64 filters (as we have specified in the argument), with 801 parameters each (1 corresponds to the bias, and a W matrix of 5×5 for each of the 32 entries). That means ((5 × 5×32) +1) ×64 = 51264.
The reader can see that the output of the Conv2D and MaxPooling2D layers is a 3D form tensor (height, width, channels). The width and height dimensions tend to be reduced as we enter the hidden layers of the neural network. The number of kernels is controlled through the first argument passed to the Conv2D layer (usually size 32 or 64).
The next step, now that we have 64 4x4 filters, is to add a densely connected layer, which will serve to feed a final layer of softmax like the one introduced in a previous post to do the classification:
model.add(layers.Dense(10, activation=’softmax’))
In this example, we have to adjust the tensors to the input of the dense layer like the softmax, which is a 1D tensor, while the output of the previous one is a 3D tensor. That’s why we have to first flatten the 3D tensor to one of 1D. Our output (4,4,64) must be flattened to a vector of (1024) before applying the Softmax.
In this case, the number of parameters of the softmax layer is 10 × 1024 + 10, with an output of a vector of 10 as in the example in the previous post:
model = models.Sequential()model.add(layers.Conv2D(32,(5,5),activation=’relu’, input_shape=(28,28,1)))model.add(layers.MaxPooling2D((2, 2)))model.add(layers.Conv2D(64, (5, 5), activation=’relu’))model.add(layers.MaxPooling2D((2, 2)))model.add(layers.Flatten())model.add(layers.Dense(10, activation=’softmax’))
With the summary() method, we can see this information about the parameters of each layer and shape of the output tensors of each layer:
_________________________________________________________________Layer (type) Output Shape Param #=================================================================conv2d_1 (Conv2D) (None, 24, 24, 32) 832_________________________________________________________________max_pooling2d_1 (MaxPooling2 (None, 12, 12, 32) 0_________________________________________________________________conv2d_2 (Conv2D) (None, 8, 8, 64) 51264_________________________________________________________________max_pooling2d_2 (MaxPooling2 (None, 4, 4, 64) 0_________________________________________________________________flatten_1 (Flatten) (None, 1024) 0_________________________________________________________________dense_1 (Dense) (None, 10) 10250=================================================================Total params: 62,346Trainable params: 62,346Non-trainable params: 0_________________________________________________________________
Observing this summary, it is easily appreciated that in the convolutional layers is where more memory is required and, therefore, more computation to store the data. In contrast, in the densely connected layer of softmax, little memory space is needed but, in comparison, the model requires numerous parameters which must be learned. It is important to be aware of the sizes of the data and the parameters because, when we have models based on convolutional neural networks, they have many layers, as we will see later, and these values can shoot exponentially.
A more visual representation of the above information is shown in the following figure, where we see a graphic representation of the shape of the tensors that are passed between layers and their connections:
Once the neural network model is defined, we are ready to train the model, that is, adjust the parameters of all the convolutional layers. From here, to know how well our model does, we must do the same as we did in the Keras example of previous post “Deep Learning for Beginners: Practical Guide with Python and Keras”. For this reason, and to avoid repetitions, we will reuse the code already presented above:
from tensorflow.keras.utils import to_categoricalmnist = tf.keras.datasets.mnist(train_images, train_labels), (test_images, test_labels) = mnist.load_data()print (train_images.shape)print (train_labels.shape)train_images = train_images.reshape((60000, 28, 28, 1))train_images = train_images.astype('float32') / 255test_images = test_images.reshape((10000, 28, 28, 1))test_images = test_images.astype('float32') / 255train_labels = to_categorical(train_labels)test_labels = to_categorical(test_labels)model.compile(loss='categorical_crossentropy', optimizer='sgd', metrics=['accuracy'])model.fit(train_images, train_labels, batch_size=100, epochs=5, verbose=1)test_loss, test_acc = model.evaluate(test_images, test_labels)print('Test accuracy:', test_acc)
The result of this code will be:
Train on 60000 samplesEpoch 1/560000/60000 [==============================] - 4s 59us/sample - loss: 0.9310 - accuracy: 0.7577Epoch 2/560000/60000 [==============================] - 2s 34us/sample - loss: 0.2706 - accuracy: 0.9194Epoch 3/560000/60000 [==============================] - 2s 34us/sample - loss: 0.1943 - accuracy: 0.9421Epoch 4/560000/60000 [==============================] - 2s 34us/sample - loss: 0.1529 - accuracy: 0.9553Epoch 5/560000/60000 [==============================] - 2s 34us/sample - loss: 0.1284 - accuracy: 0.962610000/10000 [==============================] - 1s 76us/sample - loss: 0.1070 - accuracy: 0.9700Test accuracy: 0.9704
Remember that the code can be found in my GitHub and the reader can be verified that this code offers an accuracy of approximately 97%.
The main hyperparameters of the convolutional neural networks not seen until now are: the size of the filter window, the number of filters, the stride and padding.
The size of the window (window_height × window_width) that holds information from spatially close pixels is usually 3×3 or 5×5. The number of filters that tells us the number of characteristics that we want to handle (output_depth) is usually 32 or 64. In the Conv2D layers of Keras, these hyperparameters are what we pass as arguments in this order:
Conv2D(output_depth, (window_height, window_width))
To explain the concept of padding let’s use an example. Let’s suppose an image with 5×5 pixels. If we choose a 3×3 window to perform the convolution, we see that the tensor resulting from the operation is of size 3×3. That is, it shrinks a bit: exactly two pixels for each dimension, in this case. In the following figure it is visually displayed. Suppose that the figure on the left is the 5×5 image. In it, we have numbered the pixels to make it easier to see how the 3×3 drop moves to calculate the elements of the filter. In the center, it is represented how the 3×3 window has moved through the image, 2 positions to the right and two positions to the bottom. The result of applying the convolution operation returns the filter that we have represented on the left. Each element of this filter is labeled with a letter that associates it with the content of the sliding window with which its value is calculated.
This same effect can be observed in the convolutional neuronal network example that we are creating in this post. We start with an input image of 28×28 pixels and the resulting filters are 24×24 after the first convolution layer. And in the second convolution layer, we went from a 12×12 tensioner to an 8×8 tensioner.
But sometimes we want to obtain an output image of the same dimensions as the input and we can use the hyperparameter padding in the convolutional layers for this. With padding we can add zeros around the input images before sliding the window through it. In our case in the previous figure, for the output filter to have the same size as the input image, we can add a column to the right, a column to the left, a row above and a row below to the input image of zeros. Visually it can be seen in the following figure:
If we now slide the 3×3 window, we see that it can move 4 positions to the right and 4 positions down, generating the 25 windows that generate the filter size 5×5.
In Keras, the padding in the Conv2D layer is configured with the padding argument, which can have two values: “same”, which indicates that as many rows and columns of zeros are added as necessary so that the output has the same dimension as the entry; and “valid”, which indicates no padding (which is the default value of this argument in Keras).
Another hyperparameter that we can specify in a convolutional layer is the stride, which indicates the number of steps in which the filter window moves (in the previous example, the stride was one).
Large stride values decrease the size of the information that will be passed to the next layer. In the following figure we can see the same previous example but now with a stride value of 2:
As we can see, the 5×5 image has become a smaller 2×2 filter. But in reality convolutional strides to reduce sizes are rarely used in practice; for this, the pooling operations that we have presented before are used. In Keras, the stride in the Conv2D layer is configured with the stride argument, which defaults to the strides=(1,1) value, which separately indicates the progress in the two dimensions.
Now you can use the layers learned in this post into another example. Are you ready? Let me to suggest to you another dataset on which you can practice and apply directly the learned CNN concepts.
For that, we will use the Fashion-MNIST dataset, published by Zalando research with 10 different type of fashion products. This dataset consist of a training set of 60,000 examples and a test set of 10,000 examples. Each example is a 28x28 grayscale image, associated with a label from 10 classes. It shares the image size, color and the number of items as the previous example. Then, we can start applying the same model we used in the previous example.
First of all, I suggest to apply the same model used in the previous dataset. We will observe that the Accuracy obtained is 85.93%. Go to the colab and execute the following code to verify it:
fashion_mnist = keras.datasets.fashion_mnist(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']train_images = train_images.reshape((60000, 28, 28, 1))train_images = train_images.astype('float32') / 255test_images = test_images.reshape((10000, 28, 28, 1))test_images = test_images.astype('float32') / 255model = Sequential()model.add(Conv2D(32, (5, 5), activation='relu', input_shape=(28, 28, 1)))model.add(MaxPooling2D((2, 2)))model.add(Conv2D(64, (5, 5), activation='relu'))model.add(MaxPooling2D((2, 2)))model.add(Flatten())model.add(Dense(10, activation='softmax'))model.compile(optimizer='sgd', loss='sparse_categorical_crossentropy', metrics=['accuracy'])model.fit(train_images, train_labels, epochs=5)test_loss, test_acc = model.evaluate(test_images, test_labels)print('Test accuracy:', test_acc)
Can we improve the Accuracy? Of course, we still could improve our model. However, what means improve a model? As we learnt in a previous post it means to try to apply different (and better) hyperparameters. For instance, we can add more neurons in our model and add more layers. Let’s try:
model = Sequential()model.add(Conv2D(64, (7, 7), activation="relu", padding="same", input_shape=(28, 28, 1))model.add(MaxPooling2D(2, 2))model.add(Conv2D(128, (3, 3), activation="relu", padding="same"))model.add(MaxPooling2D(2, 2))model.add(Flatten())model.add(Dense(64, activation="relu"))model.add(Dense(10, activation="softmax"))
As you can see if we follow the colab code we can obtain an Accuracy of 86.28%. It seems that we need to do more improvements. I suggest to change the Optimizer, for instanceadam:
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
If we train again the previous network (follow the colab code) with this new optimizar, the Accuracy obtained is 90.99%. Not bad!
Can we improve it? Yes!. As you can see in the suggested colab code we can obtain a 92.56% of Accuracy adding a new type of layers not introduced before: BathNormalizaton and Dropout.
Finally, we can see in the colab code that we could increase the number of epochs or use advanced features of Keras as Callbacks in order to achieve an accuracy of 94.54%.
This is an introductory post and in a future post I hope to explain more type of layers or additional features of Keras not introduced here neither in this previous post (about the learning process). The purpose of sharing with you this example was to show that there are many (and many) thinks that we still need to learn. I encourage you to continue learning about Deep Learning, certainly an exciting topic with a great future. | [
{
"code": null,
"e": 519,
"s": 172,
"text": "This is the updated version of a previous post introducing Convolutional Neural Networks that I wrote two years ago. In this post I update the Kera’s code that we use to explain the concepts. Since then, Keras has become TensorFlow’s high-level API for building and training deep learning models. I will use this update for improving the content."
},
{
"code": null,
"e": 732,
"s": 519,
"text": "Convolutional neuronal networks are widely used in computer vision tasks. These networks are composed of an input layer, an output layer and several hidden layers, some of which are convolutional, hence its name."
},
{
"code": null,
"e": 1019,
"s": 732,
"text": "In this post, we will present a specific case that we will follow step by step to understand the basic concepts of this type of networks. Specifically, together with the reader, we will program a convolutional neural network to solve the same MNIST digit recognition problem seen above."
},
{
"code": null,
"e": 1359,
"s": 1019,
"text": "A convolutional neuronal network (with the acronyms CNNs or ConvNets) is a concrete case of Deep Learning neural networks, which were already used at the end of the 90s but which in recent years have become enormously popular when achieving very impressive results in the recognition of image, deeply impacting the area of computer vision."
},
{
"code": null,
"e": 1793,
"s": 1359,
"text": "The convolutional neural networks are very similar to the neural networks of the previous posts in the series: they are formed by neurons that have parameters in the form of weights and biases that can be learned. But a differential feature of the CNN is that they make the explicit assumption that the entries are images, which allows us to encode certain properties in the architecture to recognize specific elements in the images."
},
{
"code": null,
"e": 2490,
"s": 1793,
"text": "To get an intuitive idea of how these neural networks work, let’s think about how we recognize things. For example, if we see a face, we recognize it because it has ears, eyes, a nose, hair, etc. Then, to decide if something is a face, we do it as if we had some mental boxes of verification of the characteristics that we are marking. Sometimes a face may not have an ear because it is covered by hair, but we also classify it with a certain probability as face because we see the eyes, nose and mouth. Actually, we can see it as a classifier equivalent to the one presented in the post “Basic concepts of neural networks”, which predicts a probability that the input image is a face or no face."
},
{
"code": null,
"e": 2819,
"s": 2490,
"text": "But in reality, we must first know what an ear or a nose is like to know if they are in an image; that is, we must previously identify lines, edges, textures or shapes that are similar to those containing the ears or noses we have seen before. And this is what the layers of a convolutional neuronal network are entrusted to do."
},
{
"code": null,
"e": 3188,
"s": 2819,
"text": "But identifying these elements is not enough to be able to say that something is a face. We also must be able to identify how the parts of a face meet each other, relative sizes, etc.; otherwise, the face would not resemble what we are used to. Visually, an intuitive idea of what layers learn is often presented with this example from an article by Andrew Ng’s group."
},
{
"code": null,
"e": 3485,
"s": 3188,
"text": "The idea that we want to give with this visual example is that, in reality, in a convolutional neural network each layer is learning different levels of abstraction. The reader can imagine that, with networks with many layers, it is possible to identify more complex structures in the input data."
},
{
"code": null,
"e": 3815,
"s": 3485,
"text": "Now that we have an intuitive vision of how convolutional neural networks classify an image, we will present an example of recognition of MNIST digits and from it we will introduce the two layers that define convolutional networks that can be expressed as groups of specialized neurons in two operations: convolution and pooling."
},
{
"code": null,
"e": 4136,
"s": 3815,
"text": "The fundamental difference between a densely connected layer and a specialized layer in the convolution operation, which we will call the convolutional layer, is that the dense layer learns global patterns in its global input space, while the convolutional layers learn local patterns in small windows of two dimensions."
},
{
"code": null,
"e": 4596,
"s": 4136,
"text": "In an intuitive way, we could say that the main purpose of a convolutional layer is to detect features or visual features in images such as edges, lines, color drops, etc. This is a very interesting property because, once it has learned a characteristic at a specific point in the image, it can recognize it later in any part of it. Instead, in a densely connected neural network it has to learn the pattern again if it appears in a new location of the image."
},
{
"code": null,
"e": 5084,
"s": 4596,
"text": "Another important feature is that convolutional layers can learn spatial hierarchies of patterns by preserving spatial relationships. For example, a first convolutional layer can learn basic elements such as edges, and a second convolutional layer can learn patterns composed of basic elements learned in the previous layer. And so on until it learns very complex patterns. This allows convolutional neural networks to efficiently learn increasingly complex and abstract visual concepts."
},
{
"code": null,
"e": 5472,
"s": 5084,
"text": "In general, the convolutions layers operate on 3D tensors, called feature maps, with two spatial axes of height and width, as well as a channel axis also called depth. For an RGB color image, the dimension of the depth axis is 3, because the image has three channels: red, green and blue. For a black and white image, such as the MNIST digits, the depth axis dimension is 1 (gray level)."
},
{
"code": null,
"e": 6072,
"s": 5472,
"text": "In the case of MNIST, as input to our neural network we can think of a space of two-dimensional neurons 28×28 (height = 28, width = 28, depth = 1). A first layer of hidden neurons connected to the neurons of the input layer that we have discussed will perform the convolutional operations that we have just described. But as we have explained, not all input neurons are connected with all the neurons of this first level of hidden neurons, as in the case of densely connected neural networks; it is only done by small localized areas of the space of input neurons that store the pixels of the image."
},
{
"code": null,
"e": 6122,
"s": 6072,
"text": "The explained, visually, could be represented as:"
},
{
"code": null,
"e": 6520,
"s": 6122,
"text": "In the case of our previous example, each neuron of our hidden layer will be connected to a small region of 5×5 neurons (i.e. 25 neurons) of the input layer (28×28). Intuitively, we can think of a 5×5 size window that slides along the entire 28×28 neuron layer of input that contains the image. For each position of the window there is a neuron in the hidden layer that processes this information."
},
{
"code": null,
"e": 6953,
"s": 6520,
"text": "Visually, we start with the window in the top left corner of the image, and this gives the necessary information to the first neuron of the hidden layer. Then, we slide the window one position to the right to “connect” the 5×5 neurons of the input layer included in this window with the second neuron of the hidden layer. And so, successively, we go through the entire space of the input layer, from left to right and top to bottom."
},
{
"code": null,
"e": 7300,
"s": 6953,
"text": "Analyzing a little bit the concrete case we have proposed, we note that, if we have an input of 28×28 pixels and a window of 5×5, this defines a space of 24×24 neurons in the first hidden layer because we can only move the window 23 neurons to the right and 23 neurons to the bottom before hitting the right (or bottom) border of the input image."
},
{
"code": null,
"e": 8096,
"s": 7300,
"text": "We would like to point out to the reader that the assumption we have made is that the window moves forward 1 pixel away, both horizontally and vertically when a new row starts. Therefore, in each step, the new window overlaps the previous one except in this line of pixels that we have advanced. But, as we will see in the next section, in convolutional neural networks, different lengths of advance steps can be used (the parameter called stride). In convolutional neural networks you can also apply a technique of filling zeros around the margin of the image to improve the sweep that is done with the sliding window. The parameter to define this technique is called “padding”, which we will also present in more detail in the next section, with which you can specify the size of this padding."
},
{
"code": null,
"e": 8519,
"s": 8096,
"text": "In our case of study, and following the formalism previously presented, to “connect” each neuron of the hidden layer with the 25 corresponding neurons of the input layer we will use a bias value b and a W-weights matrix of size 5×5 that we will call filter (or kernel). The value of each point of the hidden layer corresponds to the scalar product between the filter and the handful of 25 neurons (5×5) of the input layer."
},
{
"code": null,
"e": 9071,
"s": 8519,
"text": "However, the particular and very important thing about convolutional networks is that we use the same filter (the same W matrix of weights and the same b bias) for all the neurons in the hidden layer: in our case for the 24×24 neurons (576 neurons in total) of the first layer. The reader can see in this particular case that this sharing drastically reduces the number of parameters that a neural network would have if we did not do it: it goes from 14,400 parameters that would have to be adjusted (5×5 × 24×24) to 25 (5×5) parameters plus biases b."
},
{
"code": null,
"e": 9496,
"s": 9071,
"text": "This shared W matrix together with the b bias, which we have already said we call a filter in this context of convolutional networks, is similar to the filters we use to retouch images, which in our case are used to look for local characteristics in small groups of entries. I recommend looking at the examples found in the GIMP image editor manual to get a visual and very intuitive idea of how a convolution process works."
},
{
"code": null,
"e": 9868,
"s": 9496,
"text": "But a filter defined by a matrix W and a bias b only allows detecting a specific characteristic in an image; therefore, in order to perform image recognition, it is proposed to use several filters at the same time, one for each characteristic that we want to detect. That is why a complete convolutional layer in a convolutional neuronal network includes several filters."
},
{
"code": null,
"e": 10130,
"s": 9868,
"text": "A usual way to visually represent this convolutional layer is shown in the following figure, where the level of hidden layers is composed of several filters. In our example we propose 32 filters, where each filter is defined with a W matrix of 5×5 and a bias b."
},
{
"code": null,
"e": 10362,
"s": 10130,
"text": "In this example, the first convolutional layer receives a size input tensor (28, 28, 1) and generates a size output (24, 24, 32), a 3D tensor containing the 32 outputs of 24×24 pixel result of computing the 32 filters on the input."
},
{
"code": null,
"e": 10806,
"s": 10362,
"text": "In addition to the convolutional layers that we have just described, convolutional neural networks accompany the convolution layer with pooling layers, which are usually applied immediately after the convolutional layers. A first approach to understand what these layers are for is to see that the pooling layers simplify the information collected by the convolutional layer and create a condensed version of the information contained in them."
},
{
"code": null,
"e": 11013,
"s": 10806,
"text": "In our MNIST example, we are going to choose a 2×2 window of the convolutional layer and we are going to synthesize the information in a point in the pooling layer. Visually, it can be expressed as follows:"
},
{
"code": null,
"e": 11338,
"s": 11013,
"text": "There are several ways to condense the information, but a usual one, which we will use in our example, is known as max-pooling, which as a value keeps the maximum value of those that were in the 2×2 input window in our case. In this case we divide by 4 the size of the output of the pooling layer, leaving an image of 12×12."
},
{
"code": null,
"e": 11596,
"s": 11338,
"text": "Average-pooling can also be used instead of max-pooling, where each group of entry points is transformed into the average value of the group of points instead of its maximum value. But in general, max-pooling tends to work better than alternative solutions."
},
{
"code": null,
"e": 12275,
"s": 11596,
"text": "It is interesting to note that with the transformation of pooling we maintain the spatial relationship. To see it visually, take the following example of a 12×12 matrix where we have represented a “7” (Let’s imagine that the pixels where we pass over contain 1 and the rest 0; we have not added it to the drawing to simplify it). If we apply a max-pooling operation with a 2×2 window (we represent it in the central matrix that divides the space in a mosaic with regions of the size of the window), we obtain a 6×6 matrix where an equivalent representation of 7 is maintained (in the figure on the right where the zeros are marked in white and the points with value 1 in black):"
},
{
"code": null,
"e": 12509,
"s": 12275,
"text": "As mentioned above, the convolutional layer hosts more than one filter and, therefore, as we apply the max-pooling to each of them separately, the pooling layer will contain as many pooling filters as there are convolutional filters:"
},
{
"code": null,
"e": 12747,
"s": 12509,
"text": "The result is, since we had a space of 24×24 neurons in each convolutional filter, after doing the pooling we have 12×12 neurons which corresponds to the 12×12 regions (of size 2×2 each region) that appear when dividing the filter space."
},
{
"code": null,
"e": 12947,
"s": 12747,
"text": "In this post, we suggest to use the Colaboratory offered by Google and the code I will use in this post is available in the form of Jupyter notebooks in my GitHub here, and executed here using colab."
},
{
"code": null,
"e": 13036,
"s": 12947,
"text": "Before start to define our neural network we need to load the required Python libraries:"
},
{
"code": null,
"e": 13160,
"s": 13036,
"text": "%tensorflow_version 2.ximport tensorflow as tffrom tensorflow import kerasimport numpy as npimport matplotlib.pyplot as plt"
},
{
"code": null,
"e": 13730,
"s": 13160,
"text": "Let’s see how this example of convolutional neuronal network can be programmed using Keras. As we have said, there are several values to be specified in order to parameterize the convolution and pooling stages. In our case, we will use a simplified model with a stride of 1 in each dimension (size of the step with which the window slides) and a padding of 0 (filling with zeros around the image). Both hyperparameters will be presented below. The pooling will be a max-pooling as described above with a 2×2 window.Basic architecture of a convolutional neuronal network"
},
{
"code": null,
"e": 13862,
"s": 13730,
"text": "Let’s move on to implement our first convolutional neuronal network, which will consist of a convolution followed by a max-pooling."
},
{
"code": null,
"e": 14352,
"s": 13862,
"text": "In our case, we will have 32 filters using a 5×5 window for the convolutional layer and a 2×2 window for the pooling layer. We will use the ReLU activation function. In this case, we are configuring a convolutional neural network to process an input tensor of size (28, 28, 1), which is the size of the MNIST images (the third parameter is the color channel which in our case is depth 1), and we specify it by means of the value of the argument input_shape = (28, 28,1) in our first layer:"
},
{
"code": null,
"e": 14616,
"s": 14352,
"text": "from tensorflow.keras import Sequentialfrom tensorflow.keras.layers import Conv2Dfrom tensorflow.keras.layers import MaxPooling2Dmodel = Sequential()model.add(Conv2D(32, (5, 5), activation='relu', input_shape=(28, 28, 1)))model.add(MaxPooling2D((2, 2)))"
},
{
"code": null,
"e": 14677,
"s": 14616,
"text": "With method summary() we can obtain details about our model:"
},
{
"code": null,
"e": 15293,
"s": 14677,
"text": "model.summary()Model: \"sequential\"_________________________________________________________________Layer (type) Output Shape Param # =================================================================conv2d (Conv2D) (None, 24, 24, 32) 832 _________________________________________________________________max_pooling2d (MaxPooling2D) (None, 12, 12, 32) 0 =================================================================Total params: 832Trainable params: 832Non-trainable params: 0_________________________________________________________________"
},
{
"code": null,
"e": 15550,
"s": 15293,
"text": "The number of parameters of the conv2D layer corresponds to the weight matrix W of 5×5 and a b bias for each of the filters is 832 parameters (32 × (25 + 1)). Max-pooling does not require parameters since it is a mathematical operation to find the maximum."
},
{
"code": null,
"e": 16094,
"s": 15550,
"text": "And in order to build a “deep” neural network, we can stack several layers like the one built in the previous section. To show the reader how to do it in our example, we will create a second group of layers that will have 64 filters with a 5×5 window in the convolutional layer and a 2×2 window in the pooling layer. In this case, the number of input channels will take the value of the 32 features that we have obtained from the previous layer, although, as we have seen previously, it is not necessary to specify it because Keras deduces it:"
},
{
"code": null,
"e": 16359,
"s": 16094,
"text": "model = models.Sequential()model.add(layers.Conv2D(32,(5,5),activation=’relu’, input_shape=(28,28,1)))model.add(layers.MaxPooling2D((2, 2)))model.add(layers.Conv2D(64, (5, 5), activation=’relu’))model.add(layers.MaxPooling2D((2, 2)))"
},
{
"code": null,
"e": 16440,
"s": 16359,
"text": "If the architecture of the model is shown with the summary() method, we can see:"
},
{
"code": null,
"e": 17229,
"s": 16440,
"text": "_________________________________________________________________Layer (type) Output Shape Param #=================================================================conv2d_1 (Conv2D) (None, 24, 24, 32) 832_________________________________________________________________max_pooling2d_1 (MaxPooling2 (None, 12, 12, 32) 0_________________________________________________________________conv2d_2 (Conv2D) (None, 8, 8, 64) 51264_________________________________________________________________max_pooling2d_2 (MaxPooling2 (None, 4, 4, 64) 0=================================================================Total params: 52,096Trainable params: 52,096Non-trainable params: 0_________________________________________________________________"
},
{
"code": null,
"e": 17711,
"s": 17229,
"text": "In this case, the size of the resulting second convolution layer is 8×8 since we now start from an input space of 12×12×32 and a sliding window of 5×5, taking into account that it has a stride of 1. The number of parameters 51,264 corresponds to the fact that the second layer will have 64 filters (as we have specified in the argument), with 801 parameters each (1 corresponds to the bias, and a W matrix of 5×5 for each of the 32 entries). That means ((5 × 5×32) +1) ×64 = 51264."
},
{
"code": null,
"e": 18050,
"s": 17711,
"text": "The reader can see that the output of the Conv2D and MaxPooling2D layers is a 3D form tensor (height, width, channels). The width and height dimensions tend to be reduced as we enter the hidden layers of the neural network. The number of kernels is controlled through the first argument passed to the Conv2D layer (usually size 32 or 64)."
},
{
"code": null,
"e": 18254,
"s": 18050,
"text": "The next step, now that we have 64 4x4 filters, is to add a densely connected layer, which will serve to feed a final layer of softmax like the one introduced in a previous post to do the classification:"
},
{
"code": null,
"e": 18304,
"s": 18254,
"text": "model.add(layers.Dense(10, activation=’softmax’))"
},
{
"code": null,
"e": 18629,
"s": 18304,
"text": "In this example, we have to adjust the tensors to the input of the dense layer like the softmax, which is a 1D tensor, while the output of the previous one is a 3D tensor. That’s why we have to first flatten the 3D tensor to one of 1D. Our output (4,4,64) must be flattened to a vector of (1024) before applying the Softmax."
},
{
"code": null,
"e": 18781,
"s": 18629,
"text": "In this case, the number of parameters of the softmax layer is 10 × 1024 + 10, with an output of a vector of 10 as in the example in the previous post:"
},
{
"code": null,
"e": 19124,
"s": 18781,
"text": "model = models.Sequential()model.add(layers.Conv2D(32,(5,5),activation=’relu’, input_shape=(28,28,1)))model.add(layers.MaxPooling2D((2, 2)))model.add(layers.Conv2D(64, (5, 5), activation=’relu’))model.add(layers.MaxPooling2D((2, 2)))model.add(layers.Flatten())model.add(layers.Dense(10, activation=’softmax’))"
},
{
"code": null,
"e": 19261,
"s": 19124,
"text": "With the summary() method, we can see this information about the parameters of each layer and shape of the output tensors of each layer:"
},
{
"code": null,
"e": 20189,
"s": 19261,
"text": "_________________________________________________________________Layer (type) Output Shape Param #=================================================================conv2d_1 (Conv2D) (None, 24, 24, 32) 832_________________________________________________________________max_pooling2d_1 (MaxPooling2 (None, 12, 12, 32) 0_________________________________________________________________conv2d_2 (Conv2D) (None, 8, 8, 64) 51264_________________________________________________________________max_pooling2d_2 (MaxPooling2 (None, 4, 4, 64) 0_________________________________________________________________flatten_1 (Flatten) (None, 1024) 0_________________________________________________________________dense_1 (Dense) (None, 10) 10250=================================================================Total params: 62,346Trainable params: 62,346Non-trainable params: 0_________________________________________________________________"
},
{
"code": null,
"e": 20752,
"s": 20189,
"text": "Observing this summary, it is easily appreciated that in the convolutional layers is where more memory is required and, therefore, more computation to store the data. In contrast, in the densely connected layer of softmax, little memory space is needed but, in comparison, the model requires numerous parameters which must be learned. It is important to be aware of the sizes of the data and the parameters because, when we have models based on convolutional neural networks, they have many layers, as we will see later, and these values can shoot exponentially."
},
{
"code": null,
"e": 20960,
"s": 20752,
"text": "A more visual representation of the above information is shown in the following figure, where we see a graphic representation of the shape of the tensors that are passed between layers and their connections:"
},
{
"code": null,
"e": 21372,
"s": 20960,
"text": "Once the neural network model is defined, we are ready to train the model, that is, adjust the parameters of all the convolutional layers. From here, to know how well our model does, we must do the same as we did in the Keras example of previous post “Deep Learning for Beginners: Practical Guide with Python and Keras”. For this reason, and to avoid repetitions, we will reuse the code already presented above:"
},
{
"code": null,
"e": 22180,
"s": 21372,
"text": "from tensorflow.keras.utils import to_categoricalmnist = tf.keras.datasets.mnist(train_images, train_labels), (test_images, test_labels) = mnist.load_data()print (train_images.shape)print (train_labels.shape)train_images = train_images.reshape((60000, 28, 28, 1))train_images = train_images.astype('float32') / 255test_images = test_images.reshape((10000, 28, 28, 1))test_images = test_images.astype('float32') / 255train_labels = to_categorical(train_labels)test_labels = to_categorical(test_labels)model.compile(loss='categorical_crossentropy', optimizer='sgd', metrics=['accuracy'])model.fit(train_images, train_labels, batch_size=100, epochs=5, verbose=1)test_loss, test_acc = model.evaluate(test_images, test_labels)print('Test accuracy:', test_acc)"
},
{
"code": null,
"e": 22213,
"s": 22180,
"text": "The result of this code will be:"
},
{
"code": null,
"e": 22872,
"s": 22213,
"text": "Train on 60000 samplesEpoch 1/560000/60000 [==============================] - 4s 59us/sample - loss: 0.9310 - accuracy: 0.7577Epoch 2/560000/60000 [==============================] - 2s 34us/sample - loss: 0.2706 - accuracy: 0.9194Epoch 3/560000/60000 [==============================] - 2s 34us/sample - loss: 0.1943 - accuracy: 0.9421Epoch 4/560000/60000 [==============================] - 2s 34us/sample - loss: 0.1529 - accuracy: 0.9553Epoch 5/560000/60000 [==============================] - 2s 34us/sample - loss: 0.1284 - accuracy: 0.962610000/10000 [==============================] - 1s 76us/sample - loss: 0.1070 - accuracy: 0.9700Test accuracy: 0.9704"
},
{
"code": null,
"e": 23008,
"s": 22872,
"text": "Remember that the code can be found in my GitHub and the reader can be verified that this code offers an accuracy of approximately 97%."
},
{
"code": null,
"e": 23172,
"s": 23008,
"text": "The main hyperparameters of the convolutional neural networks not seen until now are: the size of the filter window, the number of filters, the stride and padding."
},
{
"code": null,
"e": 23523,
"s": 23172,
"text": "The size of the window (window_height × window_width) that holds information from spatially close pixels is usually 3×3 or 5×5. The number of filters that tells us the number of characteristics that we want to handle (output_depth) is usually 32 or 64. In the Conv2D layers of Keras, these hyperparameters are what we pass as arguments in this order:"
},
{
"code": null,
"e": 23575,
"s": 23523,
"text": "Conv2D(output_depth, (window_height, window_width))"
},
{
"code": null,
"e": 24493,
"s": 23575,
"text": "To explain the concept of padding let’s use an example. Let’s suppose an image with 5×5 pixels. If we choose a 3×3 window to perform the convolution, we see that the tensor resulting from the operation is of size 3×3. That is, it shrinks a bit: exactly two pixels for each dimension, in this case. In the following figure it is visually displayed. Suppose that the figure on the left is the 5×5 image. In it, we have numbered the pixels to make it easier to see how the 3×3 drop moves to calculate the elements of the filter. In the center, it is represented how the 3×3 window has moved through the image, 2 positions to the right and two positions to the bottom. The result of applying the convolution operation returns the filter that we have represented on the left. Each element of this filter is labeled with a letter that associates it with the content of the sliding window with which its value is calculated."
},
{
"code": null,
"e": 24812,
"s": 24493,
"text": "This same effect can be observed in the convolutional neuronal network example that we are creating in this post. We start with an input image of 28×28 pixels and the resulting filters are 24×24 after the first convolution layer. And in the second convolution layer, we went from a 12×12 tensioner to an 8×8 tensioner."
},
{
"code": null,
"e": 25330,
"s": 24812,
"text": "But sometimes we want to obtain an output image of the same dimensions as the input and we can use the hyperparameter padding in the convolutional layers for this. With padding we can add zeros around the input images before sliding the window through it. In our case in the previous figure, for the output filter to have the same size as the input image, we can add a column to the right, a column to the left, a row above and a row below to the input image of zeros. Visually it can be seen in the following figure:"
},
{
"code": null,
"e": 25494,
"s": 25330,
"text": "If we now slide the 3×3 window, we see that it can move 4 positions to the right and 4 positions down, generating the 25 windows that generate the filter size 5×5."
},
{
"code": null,
"e": 25842,
"s": 25494,
"text": "In Keras, the padding in the Conv2D layer is configured with the padding argument, which can have two values: “same”, which indicates that as many rows and columns of zeros are added as necessary so that the output has the same dimension as the entry; and “valid”, which indicates no padding (which is the default value of this argument in Keras)."
},
{
"code": null,
"e": 26041,
"s": 25842,
"text": "Another hyperparameter that we can specify in a convolutional layer is the stride, which indicates the number of steps in which the filter window moves (in the previous example, the stride was one)."
},
{
"code": null,
"e": 26232,
"s": 26041,
"text": "Large stride values decrease the size of the information that will be passed to the next layer. In the following figure we can see the same previous example but now with a stride value of 2:"
},
{
"code": null,
"e": 26636,
"s": 26232,
"text": "As we can see, the 5×5 image has become a smaller 2×2 filter. But in reality convolutional strides to reduce sizes are rarely used in practice; for this, the pooling operations that we have presented before are used. In Keras, the stride in the Conv2D layer is configured with the stride argument, which defaults to the strides=(1,1) value, which separately indicates the progress in the two dimensions."
},
{
"code": null,
"e": 26833,
"s": 26636,
"text": "Now you can use the layers learned in this post into another example. Are you ready? Let me to suggest to you another dataset on which you can practice and apply directly the learned CNN concepts."
},
{
"code": null,
"e": 27288,
"s": 26833,
"text": "For that, we will use the Fashion-MNIST dataset, published by Zalando research with 10 different type of fashion products. This dataset consist of a training set of 60,000 examples and a test set of 10,000 examples. Each example is a 28x28 grayscale image, associated with a label from 10 classes. It shares the image size, color and the number of items as the previous example. Then, we can start applying the same model we used in the previous example."
},
{
"code": null,
"e": 27481,
"s": 27288,
"text": "First of all, I suggest to apply the same model used in the previous dataset. We will observe that the Accuracy obtained is 85.93%. Go to the colab and execute the following code to verify it:"
},
{
"code": null,
"e": 28474,
"s": 27481,
"text": "fashion_mnist = keras.datasets.fashion_mnist(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']train_images = train_images.reshape((60000, 28, 28, 1))train_images = train_images.astype('float32') / 255test_images = test_images.reshape((10000, 28, 28, 1))test_images = test_images.astype('float32') / 255model = Sequential()model.add(Conv2D(32, (5, 5), activation='relu', input_shape=(28, 28, 1)))model.add(MaxPooling2D((2, 2)))model.add(Conv2D(64, (5, 5), activation='relu'))model.add(MaxPooling2D((2, 2)))model.add(Flatten())model.add(Dense(10, activation='softmax'))model.compile(optimizer='sgd', loss='sparse_categorical_crossentropy', metrics=['accuracy'])model.fit(train_images, train_labels, epochs=5)test_loss, test_acc = model.evaluate(test_images, test_labels)print('Test accuracy:', test_acc)"
},
{
"code": null,
"e": 28765,
"s": 28474,
"text": "Can we improve the Accuracy? Of course, we still could improve our model. However, what means improve a model? As we learnt in a previous post it means to try to apply different (and better) hyperparameters. For instance, we can add more neurons in our model and add more layers. Let’s try:"
},
{
"code": null,
"e": 29107,
"s": 28765,
"text": "model = Sequential()model.add(Conv2D(64, (7, 7), activation=\"relu\", padding=\"same\", input_shape=(28, 28, 1))model.add(MaxPooling2D(2, 2))model.add(Conv2D(128, (3, 3), activation=\"relu\", padding=\"same\"))model.add(MaxPooling2D(2, 2))model.add(Flatten())model.add(Dense(64, activation=\"relu\"))model.add(Dense(10, activation=\"softmax\"))"
},
{
"code": null,
"e": 29287,
"s": 29107,
"text": "As you can see if we follow the colab code we can obtain an Accuracy of 86.28%. It seems that we need to do more improvements. I suggest to change the Optimizer, for instanceadam:"
},
{
"code": null,
"e": 29407,
"s": 29287,
"text": "model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])"
},
{
"code": null,
"e": 29537,
"s": 29407,
"text": "If we train again the previous network (follow the colab code) with this new optimizar, the Accuracy obtained is 90.99%. Not bad!"
},
{
"code": null,
"e": 29721,
"s": 29537,
"text": "Can we improve it? Yes!. As you can see in the suggested colab code we can obtain a 92.56% of Accuracy adding a new type of layers not introduced before: BathNormalizaton and Dropout."
},
{
"code": null,
"e": 29893,
"s": 29721,
"text": "Finally, we can see in the colab code that we could increase the number of epochs or use advanced features of Keras as Callbacks in order to achieve an accuracy of 94.54%."
}
] |
How do I create a java.sql.Date object in Java? | The java.sql.Date represents the date value in JDBC. The constructor of this class accepts a long value representing the desired date and creates respective Date object.
Date(long date)
You can create this object using this constructor.
Live Demo
import java.text.ParseException;
import java.text.SimpleDateFormat;
public class Demo {
public static void main(String args[]) throws ParseException {
String str = "26-09-1989";
SimpleDateFormat obj = new SimpleDateFormat("dd-MM-yyyy");
long epoch = obj.parse(str).getTime();
System.out.println("Date value: "+epoch);
//Creating java.util.Date object
java.util.Date date = new java.util.Date(epoch);
System.out.println(date);
}
}
Date value: 622751400000
Tue Sep 26 00:00:00 IST 1989
The valueOf() method of this class has two variants as shown below −
valueOf(LocalDate date);
valueOf(String s);
This method accepts a LocalDate object or a date string value (yyyy-[m]m-[d]d format) representing a desired date and creates/returns a java.sql.Date object.
Live Demo
import java.sql.Date;
import java.time.LocalDate;
public class Demo {
public static void main(String args[]) {
LocalDate localDate = LocalDate.of(2014, 9, 11);
Date date = Date.valueOf(localDate);
System.out.println(date);
}
}
Date Value: 2014-09-11
Live Demo
import java.sql.Date;
public class Demo {
public static void main(String args[]) {
String str = "2017-12-03";
Date date = Date.valueOf(str);
System.out.println("Date Value: "+date);
}
}
yyyy-[m]m-[d]d | [
{
"code": null,
"e": 1232,
"s": 1062,
"text": "The java.sql.Date represents the date value in JDBC. The constructor of this class accepts a long value representing the desired date and creates respective Date object."
},
{
"code": null,
"e": 1248,
"s": 1232,
"text": "Date(long date)"
},
{
"code": null,
"e": 1299,
"s": 1248,
"text": "You can create this object using this constructor."
},
{
"code": null,
"e": 1309,
"s": 1299,
"text": "Live Demo"
},
{
"code": null,
"e": 1801,
"s": 1309,
"text": "import java.text.ParseException;\nimport java.text.SimpleDateFormat;\npublic class Demo {\n public static void main(String args[]) throws ParseException { \n String str = \"26-09-1989\";\n SimpleDateFormat obj = new SimpleDateFormat(\"dd-MM-yyyy\"); \n long epoch = obj.parse(str).getTime(); \n System.out.println(\"Date value: \"+epoch);\n //Creating java.util.Date object\n java.util.Date date = new java.util.Date(epoch);\n System.out.println(date);\n }\n}"
},
{
"code": null,
"e": 1855,
"s": 1801,
"text": "Date value: 622751400000\nTue Sep 26 00:00:00 IST 1989"
},
{
"code": null,
"e": 1924,
"s": 1855,
"text": "The valueOf() method of this class has two variants as shown below −"
},
{
"code": null,
"e": 1949,
"s": 1924,
"text": "valueOf(LocalDate date);"
},
{
"code": null,
"e": 1968,
"s": 1949,
"text": "valueOf(String s);"
},
{
"code": null,
"e": 2126,
"s": 1968,
"text": "This method accepts a LocalDate object or a date string value (yyyy-[m]m-[d]d format) representing a desired date and creates/returns a java.sql.Date object."
},
{
"code": null,
"e": 2136,
"s": 2126,
"text": "Live Demo"
},
{
"code": null,
"e": 2389,
"s": 2136,
"text": "import java.sql.Date;\nimport java.time.LocalDate;\npublic class Demo {\n public static void main(String args[]) { \n LocalDate localDate = LocalDate.of(2014, 9, 11);\n Date date = Date.valueOf(localDate);\n System.out.println(date);\n }\n}"
},
{
"code": null,
"e": 2412,
"s": 2389,
"text": "Date Value: 2014-09-11"
},
{
"code": null,
"e": 2422,
"s": 2412,
"text": "Live Demo"
},
{
"code": null,
"e": 2634,
"s": 2422,
"text": "import java.sql.Date;\npublic class Demo {\n public static void main(String args[]) { \n String str = \"2017-12-03\";\n Date date = Date.valueOf(str);\n System.out.println(\"Date Value: \"+date);\n }\n}"
},
{
"code": null,
"e": 2649,
"s": 2634,
"text": "yyyy-[m]m-[d]d"
}
] |
Windows 10 Development - SQLite Database | In many applications, there are certain types of data, which have some sort of relationship to each other. These types of data, which are difficult to store in a file, can be stored in a database.
If you are familiar with the types of databases, such as SQL server or Oracle databases in any application, then it is very easy to understand SQLite database.
SQLite is a software library that implements a self-contained, server less, zero-configuration, transactional SQL database engine.
Important features are −
SQLite is the most widely deployed database engine in the world.
SQLite is the most widely deployed database engine in the world.
The source code for SQLite is Open source.
The source code for SQLite is Open source.
It has had a large impact on game and mobile application development, due to its portability and small footprint.
It has had a large impact on game and mobile application development, due to its portability and small footprint.
The following are the advantages of SQLite −
It is a very lightweight database.
It is platform independent and works on all platforms.
It has a small memory footprint.
It is reliable.
No need for any setup and installation.
It has no dependencies.
To use SQLite in your Universal Windows Platform (UWP) applications, you need to follow the steps given below.
Create a new Universal Windows blank app with the name UWPSQLiteDemo.
Create a new Universal Windows blank app with the name UWPSQLiteDemo.
Go to the Tools menu and select Extensions and Updates. The following dialog will open.
Go to the Tools menu and select Extensions and Updates. The following dialog will open.
After selecting Extensions and Updates, the following window will open.
Now select the Online option and search for SQLite, from the left pane.
Now select the Online option and search for SQLite, from the left pane.
Download and Install SQLite for Universal App Platform.
Download and Install SQLite for Universal App Platform.
Now, go to the Tools menu again and select NuGet Package Manager > Package Manager Console menu option as shown below.
Now, go to the Tools menu again and select NuGet Package Manager > Package Manager Console menu option as shown below.
Write the following command in the Package Manager Console and press enter to execute this command −
Write the following command in the Package Manager Console and press enter to execute this command −
Install-Package SQLite.Net-PCL
Now right click on References in the solution explorer and select Add References.
Now right click on References in the solution explorer and select Add References.
The following dialog will open.
Select Extensions from the left pane under Universal Windows, check SQLite for Universal App Platform in the middle pane, and click Ok.
Select Extensions from the left pane under Universal Windows, check SQLite for Universal App Platform in the middle pane, and click Ok.
Now you are ready to go and use SQLite in your UWP applications.
Now you are ready to go and use SQLite in your UWP applications.
You can create a database by using the following code.
string path = Path.Combine(Windows.Storage.ApplicationData.
Current.LocalFolder.Path, "db.sqlite");
SQLite.Net.SQLiteConnection conn = new SQLite.Net.SQLiteConnection(new
SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), path);
To create a table you need to call CreateTable method with table name object.
conn.CreateTable<Customer>();
You can insert the data into your table by using the following code.
conn.Insert(new Customer(){
Name = textBox.Text,
Age = textBox1.Text
});
Given below is the code to retrieve data from the table.
var query = conn.Table<Customer>();
string id = "";
string name = "";
string age = "";
foreach (var message in query) {
id = id + " " + message.Id;
name = name + " " + message.Name;
age = age + " " + message.Age;
}
Let us understand how to create a database, a table and how to insert and retrieve the data from the database with the help of a simple example. We will be adding Name and age and then we will retrieve the same data from the table. Given below is the XAML code in which different controls are added.
<Page
x:Class = "UWPSQLiteDemo.MainPage"
xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local = "using:UWPSQLiteDemo"
xmlns:d = "http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable = "d">
<Grid Background = "{ThemeResource ApplicationPageBackgroundThemeBrush}" >
<Button x:Name = "Retrieve" Content = "Retrieve" HorizontalAlignment = "Left"
VerticalAlignment = "Top" Margin = "384,406,0,0"
Click = "Retrieve_Click"/>
<Button x:Name = "Add" Content = "Add" HorizontalAlignment = "Left"
VerticalAlignment = "Top" Margin = "291,406,0,0" Click = "Add_Click"/>
<TextBlock x:Name = "textBlock" HorizontalAlignment = "Left"
TextWrapping = "Wrap" Text = "Name" VerticalAlignment = "Top"
Margin = "233,280,0,0" Width = "52"/>
<TextBox x:Name = "textBox" HorizontalAlignment = "Left" TextWrapping = "Wrap"
VerticalAlignment = "Top" Margin = "289,274,0,0" Width = "370"/>
<TextBlock x:Name = "textBlock1" HorizontalAlignment = "Left"
TextWrapping = "Wrap" Text = "Age" VerticalAlignment = "Top"
Margin = "233,342,0,0" Width = "52"/>
<TextBox x:Name = "textBox1" HorizontalAlignment = "Left" TextWrapping = "Wrap"
VerticalAlignment = "Top" Margin = "289,336,0,0" Width = "191"/>
<TextBlock x:Name = "textBlock2" HorizontalAlignment = "Left"
Margin = "290,468,0,0" TextWrapping = "Wrap"
VerticalAlignment = "Top" Width = "324" Height = "131"/>
</Grid>
</Page>
Given below is the C# implementation for events and SQLite database.
using SQLite.Net.Attributes;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The Blank Page item template is documented at
http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
namespace UWPSQLiteDemo {
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page {
string path;
SQLite.Net.SQLiteConnection conn;
public MainPage(){
this.InitializeComponent();
path = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path,
"db.sqlite");
conn = new SQLite.Net.SQLiteConnection(new
SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), path);
conn.CreateTable<Customer>();
}
private void Retrieve_Click(object sender, RoutedEventArgs e) {
var query = conn.Table<Customer>();
string id = "";
string name = "";
string age = "";
foreach (var message in query) {
id = id + " " + message.Id;
name = name + " " + message.Name;
age = age + " " + message.Age;
}
textBlock2.Text = "ID: " + id + "\nName: " + name + "\nAge: " + age;
}
private void Add_Click(object sender, RoutedEventArgs e){
var s = conn.Insert(new Customer(){
Name = textBox.Text,
Age = textBox1.Text
});
}
}
public class Customer {
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
public string Name { get; set; }
public string Age { get; set; }
}
}
When the above code is compiled and executed, you will see the following window.
Enter the Name and Age and click the Add button.
Now click on the Retrieve button. You will see the following data on the Text Block.
The ID field is a Primary Key and Auto Increment field, which is specified in the Customer class.
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
23 Lectures
2 hours
Pavan Lalwani
37 Lectures
13 hours
Trevoir Williams
46 Lectures
3.5 hours
Fettah Ben
55 Lectures
6 hours
Total Seminars
20 Lectures
2.5 hours
Brandon Dennis
52 Lectures
9 hours
Fabrice Chrzanowski
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2481,
"s": 2284,
"text": "In many applications, there are certain types of data, which have some sort of relationship to each other. These types of data, which are difficult to store in a file, can be stored in a database."
},
{
"code": null,
"e": 2641,
"s": 2481,
"text": "If you are familiar with the types of databases, such as SQL server or Oracle databases in any application, then it is very easy to understand SQLite database."
},
{
"code": null,
"e": 2772,
"s": 2641,
"text": "SQLite is a software library that implements a self-contained, server less, zero-configuration, transactional SQL database engine."
},
{
"code": null,
"e": 2797,
"s": 2772,
"text": "Important features are −"
},
{
"code": null,
"e": 2862,
"s": 2797,
"text": "SQLite is the most widely deployed database engine in the world."
},
{
"code": null,
"e": 2927,
"s": 2862,
"text": "SQLite is the most widely deployed database engine in the world."
},
{
"code": null,
"e": 2970,
"s": 2927,
"text": "The source code for SQLite is Open source."
},
{
"code": null,
"e": 3013,
"s": 2970,
"text": "The source code for SQLite is Open source."
},
{
"code": null,
"e": 3127,
"s": 3013,
"text": "It has had a large impact on game and mobile application development, due to its portability and small footprint."
},
{
"code": null,
"e": 3241,
"s": 3127,
"text": "It has had a large impact on game and mobile application development, due to its portability and small footprint."
},
{
"code": null,
"e": 3286,
"s": 3241,
"text": "The following are the advantages of SQLite −"
},
{
"code": null,
"e": 3321,
"s": 3286,
"text": "It is a very lightweight database."
},
{
"code": null,
"e": 3376,
"s": 3321,
"text": "It is platform independent and works on all platforms."
},
{
"code": null,
"e": 3409,
"s": 3376,
"text": "It has a small memory footprint."
},
{
"code": null,
"e": 3425,
"s": 3409,
"text": "It is reliable."
},
{
"code": null,
"e": 3465,
"s": 3425,
"text": "No need for any setup and installation."
},
{
"code": null,
"e": 3489,
"s": 3465,
"text": "It has no dependencies."
},
{
"code": null,
"e": 3600,
"s": 3489,
"text": "To use SQLite in your Universal Windows Platform (UWP) applications, you need to follow the steps given below."
},
{
"code": null,
"e": 3670,
"s": 3600,
"text": "Create a new Universal Windows blank app with the name UWPSQLiteDemo."
},
{
"code": null,
"e": 3740,
"s": 3670,
"text": "Create a new Universal Windows blank app with the name UWPSQLiteDemo."
},
{
"code": null,
"e": 3828,
"s": 3740,
"text": "Go to the Tools menu and select Extensions and Updates. The following dialog will open."
},
{
"code": null,
"e": 3916,
"s": 3828,
"text": "Go to the Tools menu and select Extensions and Updates. The following dialog will open."
},
{
"code": null,
"e": 3988,
"s": 3916,
"text": "After selecting Extensions and Updates, the following window will open."
},
{
"code": null,
"e": 4060,
"s": 3988,
"text": "Now select the Online option and search for SQLite, from the left pane."
},
{
"code": null,
"e": 4132,
"s": 4060,
"text": "Now select the Online option and search for SQLite, from the left pane."
},
{
"code": null,
"e": 4188,
"s": 4132,
"text": "Download and Install SQLite for Universal App Platform."
},
{
"code": null,
"e": 4244,
"s": 4188,
"text": "Download and Install SQLite for Universal App Platform."
},
{
"code": null,
"e": 4363,
"s": 4244,
"text": "Now, go to the Tools menu again and select NuGet Package Manager > Package Manager Console menu option as shown below."
},
{
"code": null,
"e": 4482,
"s": 4363,
"text": "Now, go to the Tools menu again and select NuGet Package Manager > Package Manager Console menu option as shown below."
},
{
"code": null,
"e": 4583,
"s": 4482,
"text": "Write the following command in the Package Manager Console and press enter to execute this command −"
},
{
"code": null,
"e": 4684,
"s": 4583,
"text": "Write the following command in the Package Manager Console and press enter to execute this command −"
},
{
"code": null,
"e": 4717,
"s": 4684,
"text": "Install-Package SQLite.Net-PCL \n"
},
{
"code": null,
"e": 4799,
"s": 4717,
"text": "Now right click on References in the solution explorer and select Add References."
},
{
"code": null,
"e": 4881,
"s": 4799,
"text": "Now right click on References in the solution explorer and select Add References."
},
{
"code": null,
"e": 4913,
"s": 4881,
"text": "The following dialog will open."
},
{
"code": null,
"e": 5049,
"s": 4913,
"text": "Select Extensions from the left pane under Universal Windows, check SQLite for Universal App Platform in the middle pane, and click Ok."
},
{
"code": null,
"e": 5185,
"s": 5049,
"text": "Select Extensions from the left pane under Universal Windows, check SQLite for Universal App Platform in the middle pane, and click Ok."
},
{
"code": null,
"e": 5250,
"s": 5185,
"text": "Now you are ready to go and use SQLite in your UWP applications."
},
{
"code": null,
"e": 5315,
"s": 5250,
"text": "Now you are ready to go and use SQLite in your UWP applications."
},
{
"code": null,
"e": 5370,
"s": 5315,
"text": "You can create a database by using the following code."
},
{
"code": null,
"e": 5606,
"s": 5370,
"text": "string path = Path.Combine(Windows.Storage.ApplicationData.\n Current.LocalFolder.Path, \"db.sqlite\"); \n\nSQLite.Net.SQLiteConnection conn = new SQLite.Net.SQLiteConnection(new \n SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), path);"
},
{
"code": null,
"e": 5684,
"s": 5606,
"text": "To create a table you need to call CreateTable method with table name object."
},
{
"code": null,
"e": 5716,
"s": 5684,
"text": "conn.CreateTable<Customer>(); \n"
},
{
"code": null,
"e": 5785,
"s": 5716,
"text": "You can insert the data into your table by using the following code."
},
{
"code": null,
"e": 5866,
"s": 5785,
"text": "conn.Insert(new Customer(){\n Name = textBox.Text, \n Age = textBox1.Text \n});"
},
{
"code": null,
"e": 5923,
"s": 5866,
"text": "Given below is the code to retrieve data from the table."
},
{
"code": null,
"e": 6157,
"s": 5923,
"text": "var query = conn.Table<Customer>(); \nstring id = \"\"; \nstring name = \"\"; \nstring age = \"\"; \n \nforeach (var message in query) { \n id = id + \" \" + message.Id; \n name = name + \" \" + message.Name; \n age = age + \" \" + message.Age; \n}"
},
{
"code": null,
"e": 6457,
"s": 6157,
"text": "Let us understand how to create a database, a table and how to insert and retrieve the data from the database with the help of a simple example. We will be adding Name and age and then we will retrieve the same data from the table. Given below is the XAML code in which different controls are added."
},
{
"code": null,
"e": 8209,
"s": 6457,
"text": "<Page \n x:Class = \"UWPSQLiteDemo.MainPage\" \n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" \n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\" \n xmlns:local = \"using:UWPSQLiteDemo\" \n xmlns:d = \"http://schemas.microsoft.com/expression/blend/2008\" \n xmlns:mc = \"http://schemas.openxmlformats.org/markup-compatibility/2006\" \n mc:Ignorable = \"d\"> \n\t\n <Grid Background = \"{ThemeResource ApplicationPageBackgroundThemeBrush}\" >\n <Button x:Name = \"Retrieve\" Content = \"Retrieve\" HorizontalAlignment = \"Left\" \n VerticalAlignment = \"Top\" Margin = \"384,406,0,0\" \n Click = \"Retrieve_Click\"/>\n\t\t\t\n <Button x:Name = \"Add\" Content = \"Add\" HorizontalAlignment = \"Left\" \n VerticalAlignment = \"Top\" Margin = \"291,406,0,0\" Click = \"Add_Click\"/>\n\t\t\t\n <TextBlock x:Name = \"textBlock\" HorizontalAlignment = \"Left\" \n TextWrapping = \"Wrap\" Text = \"Name\" VerticalAlignment = \"Top\" \n Margin = \"233,280,0,0\" Width = \"52\"/>\n\t\t\t\n <TextBox x:Name = \"textBox\" HorizontalAlignment = \"Left\" TextWrapping = \"Wrap\" \n VerticalAlignment = \"Top\" Margin = \"289,274,0,0\" Width = \"370\"/>\n\t\t\t\n <TextBlock x:Name = \"textBlock1\" HorizontalAlignment = \"Left\" \n TextWrapping = \"Wrap\" Text = \"Age\" VerticalAlignment = \"Top\" \n Margin = \"233,342,0,0\" Width = \"52\"/>\n\t\t\t\n <TextBox x:Name = \"textBox1\" HorizontalAlignment = \"Left\" TextWrapping = \"Wrap\" \n VerticalAlignment = \"Top\" Margin = \"289,336,0,0\" Width = \"191\"/>\n\t\t\t\n <TextBlock x:Name = \"textBlock2\" HorizontalAlignment = \"Left\" \n Margin = \"290,468,0,0\" TextWrapping = \"Wrap\" \n VerticalAlignment = \"Top\" Width = \"324\" Height = \"131\"/>\n\t\t\t\n </Grid>\n\t\n</Page>\t\t "
},
{
"code": null,
"e": 8278,
"s": 8209,
"text": "Given below is the C# implementation for events and SQLite database."
},
{
"code": null,
"e": 10365,
"s": 8278,
"text": "using SQLite.Net.Attributes; \n\nusing System; \nusing System.Collections.Generic; \nusing System.IO; \nusing System.Linq; \nusing System.Runtime.InteropServices.WindowsRuntime; \n\nusing Windows.Foundation; \nusing Windows.Foundation.Collections; \n\nusing Windows.UI.Xaml; \nusing Windows.UI.Xaml.Controls; \nusing Windows.UI.Xaml.Controls.Primitives; \nusing Windows.UI.Xaml.Data; \nusing Windows.UI.Xaml.Input; \nusing Windows.UI.Xaml.Media; \nusing Windows.UI.Xaml.Navigation; \n\n// The Blank Page item template is documented at \n http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409 \n \nnamespace UWPSQLiteDemo {\n \n /// <summary>\n /// An empty page that can be used on its own or navigated to within a Frame.\n /// </summary>\n\t\n public sealed partial class MainPage : Page {\n string path; \n SQLite.Net.SQLiteConnection conn; \n\t\t\n public MainPage(){\n this.InitializeComponent(); \n path = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path,\n \"db.sqlite\"); \n conn = new SQLite.Net.SQLiteConnection(new \n SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), path); \n conn.CreateTable<Customer>(); \n }\n\t\t\n private void Retrieve_Click(object sender, RoutedEventArgs e) { \n var query = conn.Table<Customer>(); \n string id = \"\"; \n string name = \"\"; \n string age = \"\"; \n\t\t\t\n foreach (var message in query) {\n id = id + \" \" + message.Id; \n name = name + \" \" + message.Name; \n age = age + \" \" + message.Age; \n }\n\t\t\t\n textBlock2.Text = \"ID: \" + id + \"\\nName: \" + name + \"\\nAge: \" + age; \n } \n\t\t\n private void Add_Click(object sender, RoutedEventArgs e){ \n \n var s = conn.Insert(new Customer(){\n Name = textBox.Text, \n Age = textBox1.Text \n }); \n\t\t\t\n } \n } \n\t\n public class Customer {\n [PrimaryKey, AutoIncrement] \n public int Id { get; set; } \n public string Name { get; set; } \n public string Age { get; set; } \n } \n\t\n} "
},
{
"code": null,
"e": 10446,
"s": 10365,
"text": "When the above code is compiled and executed, you will see the following window."
},
{
"code": null,
"e": 10495,
"s": 10446,
"text": "Enter the Name and Age and click the Add button."
},
{
"code": null,
"e": 10580,
"s": 10495,
"text": "Now click on the Retrieve button. You will see the following data on the Text Block."
},
{
"code": null,
"e": 10678,
"s": 10580,
"text": "The ID field is a Primary Key and Auto Increment field, which is specified in the Customer class."
},
{
"code": null,
"e": 10736,
"s": 10678,
"text": "[PrimaryKey, AutoIncrement] \npublic int Id { get; set; }\n"
},
{
"code": null,
"e": 10769,
"s": 10736,
"text": "\n 23 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 10784,
"s": 10769,
"text": " Pavan Lalwani"
},
{
"code": null,
"e": 10818,
"s": 10784,
"text": "\n 37 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 10836,
"s": 10818,
"text": " Trevoir Williams"
},
{
"code": null,
"e": 10871,
"s": 10836,
"text": "\n 46 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 10883,
"s": 10871,
"text": " Fettah Ben"
},
{
"code": null,
"e": 10916,
"s": 10883,
"text": "\n 55 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 10932,
"s": 10916,
"text": " Total Seminars"
},
{
"code": null,
"e": 10967,
"s": 10932,
"text": "\n 20 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 10983,
"s": 10967,
"text": " Brandon Dennis"
},
{
"code": null,
"e": 11016,
"s": 10983,
"text": "\n 52 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 11037,
"s": 11016,
"text": " Fabrice Chrzanowski"
},
{
"code": null,
"e": 11044,
"s": 11037,
"text": " Print"
},
{
"code": null,
"e": 11055,
"s": 11044,
"text": " Add Notes"
}
] |
Python - Element wise Matrix Difference - GeeksforGeeks | 25 Oct, 2021
Given two Matrixes, the task is to write a Python program to perform element-wise difference.
Examples:
Input : test_list1 = [[2, 4, 5], [5, 4, 2], [1, 2, 3]], test_list2 = [[6, 4, 6], [9, 6, 3], [7, 5, 4]] Output : [[4, 0, 1], [4, 2, 1], [6, 3, 1]] Explanation : 6 – 2 = 4, 4 – 4 = 0, 6 – 5 = 1. And so on.
Input : test_list1 = [[2, 4, 5], [1, 2, 3]], test_list2 = [[6, 4, 6], [7, 5, 4]] Output : [[4, 0, 1], [6, 3, 1]] Explanation : 6 – 2 = 4, 4 – 4 = 0, 6 – 5 = 1. And so on.
Method #1 : Using loop + zip()
In this, we perform task of combining indices within rows and rows using zip and nested loop is used to iterate through all the elements of all the rows.
Python3
# Python3 code to demonstrate working of# Element-wise Matrix Difference# Using loop + zip() # initializing liststest_list1 = [[2, 4, 5], [5, 4, 2], [1, 2, 3]]test_list2 = [[6, 4, 6], [9, 6, 3], [7, 5, 4]] # printing original listsprint("The original list 1 is : " + str(test_list1))print("The original list 2 is : " + str(test_list2)) res = [] # iterating for rowsfor sub1, sub2 in zip(test_list1, test_list2): temp = [] # iterate for elements for ele1, ele2 in zip(sub1, sub2): temp.append(ele2 - ele1) res.append(temp) # printing resultprint("The Matrix Difference : " + str(res))
The original list 1 is : [[2, 4, 5], [5, 4, 2], [1, 2, 3]]
The original list 2 is : [[6, 4, 6], [9, 6, 3], [7, 5, 4]]
The Matrix Difference : [[4, 0, 1], [4, 2, 1], [6, 3, 1]]
Method #2 : Using list comprehension + zip()
In this, we perform task of zipping using zip() and list comprehension is used to solve this problem in one liner way.
Python3
# Python3 code to demonstrate working of# Element-wise Matrix Difference# Using loop + zip() # initializing liststest_list1 = [[2, 4, 5], [5, 4, 2], [1, 2, 3]]test_list2 = [[6, 4, 6], [9, 6, 3], [7, 5, 4]] # printing original listsprint("The original list 1 is : " + str(test_list1))print("The original list 2 is : " + str(test_list2)) # using list comprehension to perform task in one lineres = [[ele2 - ele1 for ele1, ele2 in zip(sub1, sub2)] for sub1, sub2 in zip(test_list1, test_list2)] # printing resultprint("The Matrix Difference : " + str(res))
The original list 1 is : [[2, 4, 5], [5, 4, 2], [1, 2, 3]]
The original list 2 is : [[6, 4, 6], [9, 6, 3], [7, 5, 4]]
The Matrix Difference : [[4, 0, 1], [4, 2, 1], [6, 3, 1]]
anikaseth98
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python? | [
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n25 Oct, 2021"
},
{
"code": null,
"e": 25631,
"s": 25537,
"text": "Given two Matrixes, the task is to write a Python program to perform element-wise difference."
},
{
"code": null,
"e": 25641,
"s": 25631,
"text": "Examples:"
},
{
"code": null,
"e": 25846,
"s": 25641,
"text": "Input : test_list1 = [[2, 4, 5], [5, 4, 2], [1, 2, 3]], test_list2 = [[6, 4, 6], [9, 6, 3], [7, 5, 4]] Output : [[4, 0, 1], [4, 2, 1], [6, 3, 1]] Explanation : 6 – 2 = 4, 4 – 4 = 0, 6 – 5 = 1. And so on. "
},
{
"code": null,
"e": 26019,
"s": 25846,
"text": "Input : test_list1 = [[2, 4, 5], [1, 2, 3]], test_list2 = [[6, 4, 6], [7, 5, 4]] Output : [[4, 0, 1], [6, 3, 1]] Explanation : 6 – 2 = 4, 4 – 4 = 0, 6 – 5 = 1. And so on. "
},
{
"code": null,
"e": 26050,
"s": 26019,
"text": "Method #1 : Using loop + zip()"
},
{
"code": null,
"e": 26204,
"s": 26050,
"text": "In this, we perform task of combining indices within rows and rows using zip and nested loop is used to iterate through all the elements of all the rows."
},
{
"code": null,
"e": 26212,
"s": 26204,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Element-wise Matrix Difference# Using loop + zip() # initializing liststest_list1 = [[2, 4, 5], [5, 4, 2], [1, 2, 3]]test_list2 = [[6, 4, 6], [9, 6, 3], [7, 5, 4]] # printing original listsprint(\"The original list 1 is : \" + str(test_list1))print(\"The original list 2 is : \" + str(test_list2)) res = [] # iterating for rowsfor sub1, sub2 in zip(test_list1, test_list2): temp = [] # iterate for elements for ele1, ele2 in zip(sub1, sub2): temp.append(ele2 - ele1) res.append(temp) # printing resultprint(\"The Matrix Difference : \" + str(res))",
"e": 26816,
"s": 26212,
"text": null
},
{
"code": null,
"e": 26992,
"s": 26816,
"text": "The original list 1 is : [[2, 4, 5], [5, 4, 2], [1, 2, 3]]\nThe original list 2 is : [[6, 4, 6], [9, 6, 3], [7, 5, 4]]\nThe Matrix Difference : [[4, 0, 1], [4, 2, 1], [6, 3, 1]]"
},
{
"code": null,
"e": 27037,
"s": 26992,
"text": "Method #2 : Using list comprehension + zip()"
},
{
"code": null,
"e": 27156,
"s": 27037,
"text": "In this, we perform task of zipping using zip() and list comprehension is used to solve this problem in one liner way."
},
{
"code": null,
"e": 27164,
"s": 27156,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Element-wise Matrix Difference# Using loop + zip() # initializing liststest_list1 = [[2, 4, 5], [5, 4, 2], [1, 2, 3]]test_list2 = [[6, 4, 6], [9, 6, 3], [7, 5, 4]] # printing original listsprint(\"The original list 1 is : \" + str(test_list1))print(\"The original list 2 is : \" + str(test_list2)) # using list comprehension to perform task in one lineres = [[ele2 - ele1 for ele1, ele2 in zip(sub1, sub2)] for sub1, sub2 in zip(test_list1, test_list2)] # printing resultprint(\"The Matrix Difference : \" + str(res))",
"e": 27724,
"s": 27164,
"text": null
},
{
"code": null,
"e": 27900,
"s": 27724,
"text": "The original list 1 is : [[2, 4, 5], [5, 4, 2], [1, 2, 3]]\nThe original list 2 is : [[6, 4, 6], [9, 6, 3], [7, 5, 4]]\nThe Matrix Difference : [[4, 0, 1], [4, 2, 1], [6, 3, 1]]"
},
{
"code": null,
"e": 27912,
"s": 27900,
"text": "anikaseth98"
},
{
"code": null,
"e": 27933,
"s": 27912,
"text": "Python list-programs"
},
{
"code": null,
"e": 27940,
"s": 27933,
"text": "Python"
},
{
"code": null,
"e": 27956,
"s": 27940,
"text": "Python Programs"
},
{
"code": null,
"e": 28054,
"s": 27956,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28086,
"s": 28054,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28128,
"s": 28086,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28170,
"s": 28128,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28197,
"s": 28170,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 28253,
"s": 28197,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28275,
"s": 28253,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28314,
"s": 28275,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 28360,
"s": 28314,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 28398,
"s": 28360,
"text": "Python | Convert a list to dictionary"
}
] |
Biopython - Sequence Alignment - GeeksforGeeks | 11 Oct, 2020
Sequence alignment is a process in which two or more DNA, RNA or Protein sequences are arranged in order specifically to identify the region of similarity among them. Identification of similar provides a lot of information about what traits are conserved among species, how much close are different species genetically, how species evolve, etc. Biopython has a wide range of functionalities for sequence alignment.
Reading Sequence Alignment: Bio.AlignIo provided by Biopython is used to read and write sequence alignments. There are a lot of formats available in bioinformatics to specify sequence alignment data is similar to sequence data. Bio.AlignIO has an API similar to Bio.SeqIO, the only difference is that the Bio.SeqIO works on sequence data while the Bio.AlignIO works on sequence data alignment. Below are some steps to download a sample sequence alignment file :
First open the browser and visit http://pfam.xfam.org/family/browse, where you can see all Pfam families in alphabetical order.
Now choose any family having a lesser number of seed value, as it contains minimum data and easy to work. Let’s move one with PF18225 (http://pfam.xfam.org/family/PF18225).
Click on the alignment section and download the required sequence alignment file in Stockholm format.
Example:
Python3
# Import librariesfrom Bio import AlignIO # Creating Sequence Alignmentalignment = AlignIO.read(open("PF18225_seed.txt"), "stockholm") # Print alignment objectprint(alignment) # Show alignment sequence recordprint("Showing Alignment Sequence Record")for align in alignment: print(align.seq)
Output:
SingleLetterAlphabet() alignment with 5 rows and 65 columnsAINRNTQQLTQDLRAMPNWSLRFVYIVDRNNQDLLKRPLPPGIM...NRK B3PFT7_CELJU/62-126AVNATEREFTERIRTLPHWARRNVFVLDSQGFEIFDRELPSPVA...NRT K4KEM7_SIMAS/61-125MQNTPAERLPAIIEKAKSKHDINVWLLDRQGRDLLEQRVPAKVA...EGP B7RZ31_9GAMM/59-123ARRHGQEYFQQWLERQPKKVKEQVFAVDQFGRELLGRPLPEDMA...KKP A0A143HL37_9GAMM/57-121TRRHGPESFRFWLERQPVEARDRIYAIDRSGAEILDRPIPRGMA...NKP A0A0X3UC67_9GAMM/57-121
Showing Alignment Sequence RecordAINRNTQQLTQDLRAMPNWSLRFVYIVDRNNQDLLKRPLPPGIMVLAPRLTAKHPYDKVQDRNRKAVNATEREFTERIRTLPHWARRNVFVLDSQGFEIFDRELPSPVADLMRKLDLDRPFKKLERKNRTMQNTPAERLPAIIEKAKSKHDINVWLLDRQGRDLLEQRVPAKVATVANQLRGRKRRAFARHREGPARRHGQEYFQQWLERQPKKVKEQVFAVDQFGRELLGRPLPEDMAPMLIALNYRNRESHAQVDKKPTRRHGPESFRFWLERQPVEARDRIYAIDRSGAEILDRPIPRGMAPLFKVLSFRNREDQGLVNNKP
Reading Multiple Alignments: Generally, most sequence alignment files contain single alignment data, where the read() method is enough to parse it. In the case of multiple sequence alignments, more than two sequences are compared for the best sequence match among them and the result in a single file having multiple sequence alignment. If the sequence alignment format has more than one sequence alignment, then the parse() method is used instead of read() which returns an iterable object which can be iterated to get the actual alignments. A basic example is given below :
Python3
# Import librariesfrom Bio import AlignIO # Parsing Sequence Alignmentalignment = AlignIO.parse(open("PF18225_seed.txt"), "stockholm") # Show alignment generatorprint(alignment) # Printing alignment for alignment in alignments: print(alignment)
Output:
<generator object parse at 0x00000214C9FDB990>
SingleLetterAlphabet() alignment with 5 rows and 65 columnsAINRNTQQLTQDLRAMPNWSLRFVYIVDRNNQDLLKRPLPPGIM...NRK B3PFT7_CELJU/62-126AVNATEREFTERIRTLPHWARRNVFVLDSQGFEIFDRELPSPVA...NRT K4KEM7_SIMAS/61-125MQNTPAERLPAIIEKAKSKHDINVWLLDRQGRDLLEQRVPAKVA...EGP B7RZ31_9GAMM/59-123ARRHGQEYFQQWLERQPKKVKEQVFAVDQFGRELLGRPLPEDMA...KKP A0A143HL37_9GAMM/57-121TRRHGPESFRFWLERQPVEARDRIYAIDRSGAEILDRPIPRGMA...NKP A0A0X3UC67_9GAMM/57-121
Python-BioPython
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 25555,
"s": 25527,
"text": "\n11 Oct, 2020"
},
{
"code": null,
"e": 25970,
"s": 25555,
"text": "Sequence alignment is a process in which two or more DNA, RNA or Protein sequences are arranged in order specifically to identify the region of similarity among them. Identification of similar provides a lot of information about what traits are conserved among species, how much close are different species genetically, how species evolve, etc. Biopython has a wide range of functionalities for sequence alignment."
},
{
"code": null,
"e": 26432,
"s": 25970,
"text": "Reading Sequence Alignment: Bio.AlignIo provided by Biopython is used to read and write sequence alignments. There are a lot of formats available in bioinformatics to specify sequence alignment data is similar to sequence data. Bio.AlignIO has an API similar to Bio.SeqIO, the only difference is that the Bio.SeqIO works on sequence data while the Bio.AlignIO works on sequence data alignment. Below are some steps to download a sample sequence alignment file :"
},
{
"code": null,
"e": 26560,
"s": 26432,
"text": "First open the browser and visit http://pfam.xfam.org/family/browse, where you can see all Pfam families in alphabetical order."
},
{
"code": null,
"e": 26733,
"s": 26560,
"text": "Now choose any family having a lesser number of seed value, as it contains minimum data and easy to work. Let’s move one with PF18225 (http://pfam.xfam.org/family/PF18225)."
},
{
"code": null,
"e": 26835,
"s": 26733,
"text": "Click on the alignment section and download the required sequence alignment file in Stockholm format."
},
{
"code": null,
"e": 26844,
"s": 26835,
"text": "Example:"
},
{
"code": null,
"e": 26852,
"s": 26844,
"text": "Python3"
},
{
"code": "# Import librariesfrom Bio import AlignIO # Creating Sequence Alignmentalignment = AlignIO.read(open(\"PF18225_seed.txt\"), \"stockholm\") # Print alignment objectprint(alignment) # Show alignment sequence recordprint(\"Showing Alignment Sequence Record\")for align in alignment: print(align.seq)",
"e": 27150,
"s": 26852,
"text": null
},
{
"code": null,
"e": 27158,
"s": 27150,
"text": "Output:"
},
{
"code": null,
"e": 27576,
"s": 27158,
"text": "SingleLetterAlphabet() alignment with 5 rows and 65 columnsAINRNTQQLTQDLRAMPNWSLRFVYIVDRNNQDLLKRPLPPGIM...NRK B3PFT7_CELJU/62-126AVNATEREFTERIRTLPHWARRNVFVLDSQGFEIFDRELPSPVA...NRT K4KEM7_SIMAS/61-125MQNTPAERLPAIIEKAKSKHDINVWLLDRQGRDLLEQRVPAKVA...EGP B7RZ31_9GAMM/59-123ARRHGQEYFQQWLERQPKKVKEQVFAVDQFGRELLGRPLPEDMA...KKP A0A143HL37_9GAMM/57-121TRRHGPESFRFWLERQPVEARDRIYAIDRSGAEILDRPIPRGMA...NKP A0A0X3UC67_9GAMM/57-121"
},
{
"code": null,
"e": 27935,
"s": 27576,
"text": "Showing Alignment Sequence RecordAINRNTQQLTQDLRAMPNWSLRFVYIVDRNNQDLLKRPLPPGIMVLAPRLTAKHPYDKVQDRNRKAVNATEREFTERIRTLPHWARRNVFVLDSQGFEIFDRELPSPVADLMRKLDLDRPFKKLERKNRTMQNTPAERLPAIIEKAKSKHDINVWLLDRQGRDLLEQRVPAKVATVANQLRGRKRRAFARHREGPARRHGQEYFQQWLERQPKKVKEQVFAVDQFGRELLGRPLPEDMAPMLIALNYRNRESHAQVDKKPTRRHGPESFRFWLERQPVEARDRIYAIDRSGAEILDRPIPRGMAPLFKVLSFRNREDQGLVNNKP"
},
{
"code": null,
"e": 28511,
"s": 27935,
"text": "Reading Multiple Alignments: Generally, most sequence alignment files contain single alignment data, where the read() method is enough to parse it. In the case of multiple sequence alignments, more than two sequences are compared for the best sequence match among them and the result in a single file having multiple sequence alignment. If the sequence alignment format has more than one sequence alignment, then the parse() method is used instead of read() which returns an iterable object which can be iterated to get the actual alignments. A basic example is given below :"
},
{
"code": null,
"e": 28519,
"s": 28511,
"text": "Python3"
},
{
"code": "# Import librariesfrom Bio import AlignIO # Parsing Sequence Alignmentalignment = AlignIO.parse(open(\"PF18225_seed.txt\"), \"stockholm\") # Show alignment generatorprint(alignment) # Printing alignment for alignment in alignments: print(alignment)",
"e": 28772,
"s": 28519,
"text": null
},
{
"code": null,
"e": 28780,
"s": 28772,
"text": "Output:"
},
{
"code": null,
"e": 28827,
"s": 28780,
"text": "<generator object parse at 0x00000214C9FDB990>"
},
{
"code": null,
"e": 29245,
"s": 28827,
"text": "SingleLetterAlphabet() alignment with 5 rows and 65 columnsAINRNTQQLTQDLRAMPNWSLRFVYIVDRNNQDLLKRPLPPGIM...NRK B3PFT7_CELJU/62-126AVNATEREFTERIRTLPHWARRNVFVLDSQGFEIFDRELPSPVA...NRT K4KEM7_SIMAS/61-125MQNTPAERLPAIIEKAKSKHDINVWLLDRQGRDLLEQRVPAKVA...EGP B7RZ31_9GAMM/59-123ARRHGQEYFQQWLERQPKKVKEQVFAVDQFGRELLGRPLPEDMA...KKP A0A143HL37_9GAMM/57-121TRRHGPESFRFWLERQPVEARDRIYAIDRSGAEILDRPIPRGMA...NKP A0A0X3UC67_9GAMM/57-121"
},
{
"code": null,
"e": 29262,
"s": 29245,
"text": "Python-BioPython"
},
{
"code": null,
"e": 29269,
"s": 29262,
"text": "Python"
},
{
"code": null,
"e": 29367,
"s": 29269,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29399,
"s": 29367,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29441,
"s": 29399,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 29483,
"s": 29441,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 29539,
"s": 29483,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 29566,
"s": 29539,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 29597,
"s": 29566,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 29636,
"s": 29597,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 29665,
"s": 29636,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 29687,
"s": 29665,
"text": "Defaultdict in Python"
}
] |
Iterative Quick Sort - GeeksforGeeks | 06 Sep, 2021
Following is a typical recursive implementation of Quick Sort that uses last element as pivot.
C++
Java
Python3
C#
PHP
Javascript
// CPP code for recursive function of Quicksort#include <bits/stdc++.h> using namespace std; // Function to swap numbersvoid swap(int* a, int* b){ int temp = *a; *a = *b; *b = temp;} /* This function takes last element as pivot, places the pivot element at its correct position in sorted array, and places all smaller (smaller than pivot) to left of pivot and all greater elements to right of pivot */int partition(int arr[], int l, int h){ int x = arr[h]; int i = (l - 1); for (int j = l; j <= h - 1; j++) { if (arr[j] <= x) { i++; swap(&arr[i], &arr[j]); } } swap(&arr[i + 1], &arr[h]); return (i + 1);} /* A[] --> Array to be sorted,l --> Starting index,h --> Ending index */void quickSort(int A[], int l, int h){ if (l < h) { /* Partitioning index */ int p = partition(A, l, h); quickSort(A, l, p - 1); quickSort(A, p + 1, h); }} // Driver codeint main(){ int n = 5; int arr[n] = { 4, 2, 6, 9, 2 }; quickSort(arr, 0, n - 1); for (int i = 0; i < n; i++) { cout << arr[i] << " "; } return 0;}
// Java program for implementation of QuickSortimport java.util.*; class QuickSort { /* This function takes last element as pivot, places the pivot element at its correct position in sorted array, and places all smaller (smaller than pivot) to left of pivot and all greater elements to right of pivot */ static int partition(int arr[], int low, int high) { int pivot = arr[high]; int i = (low - 1); // index of smaller element for (int j = low; j <= high - 1; j++) { // If current element is smaller than or // equal to pivot if (arr[j] <= pivot) { i++; // swap arr[i] and arr[j] int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } // swap arr[i+1] and arr[high] (or pivot) int temp = arr[i + 1]; arr[i + 1] = arr[high]; arr[high] = temp; return i + 1; } /* The main function that implements QuickSort() arr[] --> Array to be sorted, low --> Starting index, high --> Ending index */ static void qSort(int arr[], int low, int high) { if (low < high) { /* pi is partitioning index, arr[pi] is now at right place */ int pi = partition(arr, low, high); // Recursively sort elements before // partition and after partition qSort(arr, low, pi - 1); qSort(arr, pi + 1, high); } } // Driver code public static void main(String args[]) { int n = 5; int arr[] = { 4, 2, 6, 9, 2 }; qSort(arr, 0, n - 1); for (int i = 0; i < n; i++) { System.out.print(arr[i] + " "); } }}
# A typical recursive Python# implementation of QuickSort # Function takes last element as pivot,# places the pivot element at its correct# position in sorted array, and places all# smaller (smaller than pivot) to left of# pivot and all greater elements to right# of pivotdef partition(arr, low, high): i = (low - 1) # index of smaller element pivot = arr[high] # pivot for j in range(low, high): # If current element is smaller # than or equal to pivot if arr[j] <= pivot: # increment index of # smaller element i += 1 arr[i], arr[j] = arr[j], arr[i] arr[i + 1], arr[high] = arr[high], arr[i + 1] return (i + 1) # The main function that implements QuickSort# arr[] --> Array to be sorted,# low --> Starting index,# high --> Ending index # Function to do Quick sortdef quickSort(arr, low, high): if low < high: # pi is partitioning index, arr[p] is now # at right place pi = partition(arr, low, high) # Separately sort elements before # partition and after partition quickSort(arr, low, pi-1) quickSort(arr, pi + 1, high) # Driver Codeif __name__ == '__main__' : arr = [4, 2, 6, 9, 2] n = len(arr) # Calling quickSort function quickSort(arr, 0, n - 1) for i in range(n): print(arr[i], end = " ")
// C# program for implementation of// QuickSortusing System; class GFG { /* This function takes last element as pivot, places the pivot element at its correct position in sorted array, and places all smaller (smaller than pivot) to left of pivot and all greater elements to right of pivot */ static int partition(int[] arr, int low, int high) { int temp; int pivot = arr[high]; // index of smaller element int i = (low - 1); for (int j = low; j <= high - 1; j++) { // If current element is // smaller than or // equal to pivot if (arr[j] <= pivot) { i++; // swap arr[i] and arr[j] temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } // swap arr[i+1] and arr[high] // (or pivot) temp = arr[i + 1]; arr[i + 1] = arr[high]; arr[high] = temp; return i + 1; } /* The main function that implements QuickSort() arr[] --> Array to be sorted, low --> Starting index, high --> Ending index */ static void qSort(int[] arr, int low, int high) { if (low < high) { /* pi is partitioning index, arr[pi] is now at right place */ int pi = partition(arr, low, high); // Recursively sort elements // before partition and after // partition qSort(arr, low, pi - 1); qSort(arr, pi + 1, high); } } // Driver code public static void Main() { int n = 5; int[] arr = { 4, 2, 6, 9, 2 }; qSort(arr, 0, n - 1); for (int i = 0; i < n; i++) Console.Write(arr[i] + " "); }} // This code is contributed by nitin mittal.
<?php// PHP code for recursive function// of Quicksort // Function to swap numbersfunction swap(&$a, &$b){ $temp = $a; $a = $b; $b = $temp;} /* This function takes last element as pivot,places the pivot element at its correctposition in sorted array, and placesall smaller (smaller than pivot) to leftof pivot and all greater elements toright of pivot */function partition (&$arr, $l, $h){ $x = $arr[$h]; $i = ($l - 1); for ($j = $l; $j <= $h - 1; $j++) { if ($arr[$j] <= $x) { $i++; swap ($arr[$i], $arr[$j]); } } swap ($arr[$i + 1], $arr[$h]); return ($i + 1);} /* A[] --> Array to be sorted,l --> Starting index,h --> Ending index */function quickSort(&$A, $l, $h){ if ($l < $h) { /* Partitioning index */ $p = partition($A, $l, $h); quickSort($A, $l, $p - 1); quickSort($A, $p + 1, $h); } } // Driver code$n = 5;$arr = array(4, 2, 6, 9, 2); quickSort($arr, 0, $n - 1); for($i = 0; $i < $n; $i++){ echo $arr[$i] . " ";} // This code is contributed by// rathbhupendra?>
<script> // JavaScript program for implementation of QuickSort /* This function takes last element as pivot, places the pivot element at its correct position in sorted array, and places all smaller (smaller than pivot) to left of pivot and all greater elements to right of pivot */ function partition(arr, low, high) { let temp; let pivot = arr[high]; // index of smaller element let i = (low - 1); for (let j = low; j <= high - 1; j++) { // If current element is // smaller than or // equal to pivot if (arr[j] <= pivot) { i++; // swap arr[i] and arr[j] temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } // swap arr[i+1] and arr[high] // (or pivot) temp = arr[i + 1]; arr[i + 1] = arr[high]; arr[high] = temp; return i + 1; } /* The main function that implements QuickSort() arr[] --> Array to be sorted, low --> Starting index, high --> Ending index */ function qSort(arr, low, high) { if (low < high) { /* pi is partitioning index, arr[pi] is now at right place */ let pi = partition(arr, low, high); // Recursively sort elements // before partition and after // partition qSort(arr, low, pi - 1); qSort(arr, pi + 1, high); } } let n = 5; let arr = [ 4, 2, 6, 9, 2 ]; qSort(arr, 0, n - 1); for (let i = 0; i < n; i++) document.write(arr[i] + " "); </script>
Output:
2 2 4 6 9
The above implementation can be optimized in many ways1) The above implementation uses the last index as a pivot. This causes worst-case behavior on already sorted arrays, which is a commonly occurring case. The problem can be solved by choosing either a random index for the pivot or choosing the middle index of the partition or choosing the median of the first, middle, and last element of the partition for the pivot. (See this for details)2) To reduce the recursion depth, recur first for the smaller half of the array, and use a tail call to recurse into the other. 3) Insertion sort works better for small subarrays. Insertion sort can be used for invocations on such small arrays (i.e. where the length is less than a threshold t determined experimentally). For example, this library implementation of Quicksort uses insertion sort below size 7. Despite the above optimizations, the function remains recursive and uses function call stack to store intermediate values of l and h. The function call stack stores other bookkeeping information together with parameters. Also, function calls involve overheads like storing activation records of the caller function and then resuming execution. The above function can be easily converted to an iterative version with the help of an auxiliary stack. Following is an iterative implementation of the above recursive code.
C++
C
Java
Python
C#
PHP
Javascript
// An iterative implementation of quick sort#include <bits/stdc++.h>using namespace std; // A utility function to swap two elementsvoid swap(int* a, int* b){ int t = *a; *a = *b; *b = t;} /* This function is same in both iterative and recursive*/int partition(int arr[], int l, int h){ int x = arr[h]; int i = (l - 1); for (int j = l; j <= h - 1; j++) { if (arr[j] <= x) { i++; swap(&arr[i], &arr[j]); } } swap(&arr[i + 1], &arr[h]); return (i + 1);} /* A[] --> Array to be sorted,l --> Starting index,h --> Ending index */void quickSortIterative(int arr[], int l, int h){ // Create an auxiliary stack int stack[h - l + 1]; // initialize top of stack int top = -1; // push initial values of l and h to stack stack[++top] = l; stack[++top] = h; // Keep popping from stack while is not empty while (top >= 0) { // Pop h and l h = stack[top--]; l = stack[top--]; // Set pivot element at its correct position // in sorted array int p = partition(arr, l, h); // If there are elements on left side of pivot, // then push left side to stack if (p - 1 > l) { stack[++top] = l; stack[++top] = p - 1; } // If there are elements on right side of pivot, // then push right side to stack if (p + 1 < h) { stack[++top] = p + 1; stack[++top] = h; } }} // A utility function to print contents of arrvoid printArr(int arr[], int n){ int i; for (i = 0; i < n; ++i) cout << arr[i] << " ";} // Driver codeint main(){ int arr[] = { 4, 3, 5, 2, 1, 3, 2, 3 }; int n = sizeof(arr) / sizeof(*arr); quickSortIterative(arr, 0, n - 1); printArr(arr, n); return 0;} // This is code is contributed by rathbhupendra
// An iterative implementation of quick sort#include <stdio.h> // A utility function to swap two elementsvoid swap(int* a, int* b){ int t = *a; *a = *b; *b = t;} /* This function is same in both iterative and recursive*/int partition(int arr[], int l, int h){ int x = arr[h]; int i = (l - 1); for (int j = l; j <= h - 1; j++) { if (arr[j] <= x) { i++; swap(&arr[i], &arr[j]); } } swap(&arr[i + 1], &arr[h]); return (i + 1);} /* A[] --> Array to be sorted, l --> Starting index, h --> Ending index */void quickSortIterative(int arr[], int l, int h){ // Create an auxiliary stack int stack[h - l + 1]; // initialize top of stack int top = -1; // push initial values of l and h to stack stack[++top] = l; stack[++top] = h; // Keep popping from stack while is not empty while (top >= 0) { // Pop h and l h = stack[top--]; l = stack[top--]; // Set pivot element at its correct position // in sorted array int p = partition(arr, l, h); // If there are elements on left side of pivot, // then push left side to stack if (p - 1 > l) { stack[++top] = l; stack[++top] = p - 1; } // If there are elements on right side of pivot, // then push right side to stack if (p + 1 < h) { stack[++top] = p + 1; stack[++top] = h; } }} // A utility function to print contents of arrvoid printArr(int arr[], int n){ int i; for (i = 0; i < n; ++i) printf("%d ", arr[i]);} // Driver program to test above functionsint main(){ int arr[] = { 4, 3, 5, 2, 1, 3, 2, 3 }; int n = sizeof(arr) / sizeof(*arr); quickSortIterative(arr, 0, n - 1); printArr(arr, n); return 0;}
// Java program for implementation of QuickSortimport java.util.*; class QuickSort { /* This function takes last element as pivot, places the pivot element at its correct position in sorted array, and places all smaller (smaller than pivot) to left of pivot and all greater elements to right of pivot */ static int partition(int arr[], int low, int high) { int pivot = arr[high]; // index of smaller element int i = (low - 1); for (int j = low; j <= high - 1; j++) { // If current element is smaller than or // equal to pivot if (arr[j] <= pivot) { i++; // swap arr[i] and arr[j] int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } // swap arr[i+1] and arr[high] (or pivot) int temp = arr[i + 1]; arr[i + 1] = arr[high]; arr[high] = temp; return i + 1; } /* A[] --> Array to be sorted, l --> Starting index, h --> Ending index */ static void quickSortIterative(int arr[], int l, int h) { // Create an auxiliary stack int[] stack = new int[h - l + 1]; // initialize top of stack int top = -1; // push initial values of l and h to stack stack[++top] = l; stack[++top] = h; // Keep popping from stack while is not empty while (top >= 0) { // Pop h and l h = stack[top--]; l = stack[top--]; // Set pivot element at its correct position // in sorted array int p = partition(arr, l, h); // If there are elements on left side of pivot, // then push left side to stack if (p - 1 > l) { stack[++top] = l; stack[++top] = p - 1; } // If there are elements on right side of pivot, // then push right side to stack if (p + 1 < h) { stack[++top] = p + 1; stack[++top] = h; } } } // Driver code public static void main(String args[]) { int arr[] = { 4, 3, 5, 2, 1, 3, 2, 3 }; int n = 8; // Function calling quickSortIterative(arr, 0, n - 1); for (int i = 0; i < n; i++) { System.out.print(arr[i] + " "); } }}
# Python program for implementation of Quicksort # This function is same in both iterative and recursivedef partition(arr, l, h): i = ( l - 1 ) x = arr[h] for j in range(l, h): if arr[j] <= x: # increment index of smaller element i = i + 1 arr[i], arr[j] = arr[j], arr[i] arr[i + 1], arr[h] = arr[h], arr[i + 1] return (i + 1) # Function to do Quick sort# arr[] --> Array to be sorted,# l --> Starting index,# h --> Ending indexdef quickSortIterative(arr, l, h): # Create an auxiliary stack size = h - l + 1 stack = [0] * (size) # initialize top of stack top = -1 # push initial values of l and h to stack top = top + 1 stack[top] = l top = top + 1 stack[top] = h # Keep popping from stack while is not empty while top >= 0: # Pop h and l h = stack[top] top = top - 1 l = stack[top] top = top - 1 # Set pivot element at its correct position in # sorted array p = partition( arr, l, h ) # If there are elements on left side of pivot, # then push left side to stack if p-1 > l: top = top + 1 stack[top] = l top = top + 1 stack[top] = p - 1 # If there are elements on right side of pivot, # then push right side to stack if p + 1 < h: top = top + 1 stack[top] = p + 1 top = top + 1 stack[top] = h # Driver code to test abovearr = [4, 3, 5, 2, 1, 3, 2, 3]n = len(arr)quickSortIterative(arr, 0, n-1)print ("Sorted array is:")for i in range(n): print ("% d" % arr[i]), # This code is contributed by Mohit Kumra
// C# program for implementation of QuickSortusing System; class GFG { /* This function takes last element as pivot, places the pivot element at its correct position in sorted array, and places all smaller (smaller than pivot) to left of pivot and all greater elements to right of pivot */ static int partition(int[] arr, int low, int high) { int temp; int pivot = arr[high]; // index of smaller element int i = (low - 1); for (int j = low; j <= high - 1; j++) { // If current element is smaller // than or equal to pivot if (arr[j] <= pivot) { i++; // swap arr[i] and arr[j] temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } // swap arr[i+1] and arr[high] // (or pivot) temp = arr[i + 1]; arr[i + 1] = arr[high]; arr[high] = temp; return i + 1; } /* A[] --> Array to be sorted, l --> Starting index, h --> Ending index */ static void quickSortIterative(int[] arr, int l, int h) { // Create an auxiliary stack int[] stack = new int[h - l + 1]; // initialize top of stack int top = -1; // push initial values of l and h to // stack stack[++top] = l; stack[++top] = h; // Keep popping from stack while // is not empty while (top >= 0) { // Pop h and l h = stack[top--]; l = stack[top--]; // Set pivot element at its // correct position in // sorted array int p = partition(arr, l, h); // If there are elements on // left side of pivot, then // push left side to stack if (p - 1 > l) { stack[++top] = l; stack[++top] = p - 1; } // If there are elements on // right side of pivot, then // push right side to stack if (p + 1 < h) { stack[++top] = p + 1; stack[++top] = h; } } } // Driver code public static void Main() { int[] arr = { 4, 3, 5, 2, 1, 3, 2, 3 }; int n = 8; // Function calling quickSortIterative(arr, 0, n - 1); for (int i = 0; i < n; i++) Console.Write(arr[i] + " "); }} // This code is contributed by anuj_67.
<?php// An iterative implementation of quick sort // A utility function to swap two elementsfunction swap ( &$a, &$b ){ $t = $a; $a = $b; $b = $t;} /* This function is same in both iterative and recursive*/function partition (&$arr, $l, $h){ $x = $arr[$h]; $i = ($l - 1); for ($j = $l; $j <= $h- 1; $j++) { if ($arr[$j] <= $x) { $i++; swap ($arr[$i], $arr[$j]); } } swap ($arr[$i + 1], $arr[$h]); return ($i + 1);} /* A[] --> Array to be sorted,l --> Starting index,h --> Ending index */function quickSortIterative (&$arr, $l, $h){ // Create an auxiliary stack $stack=array_fill(0, $h - $l + 1, 0); // initialize top of stack $top = -1; // push initial values of l and h to stack $stack[ ++$top ] = $l; $stack[ ++$top ] = $h; // Keep popping from stack while is not empty while ( $top >= 0 ) { // Pop h and l $h = $stack[ $top-- ]; $l = $stack[ $top-- ]; // Set pivot element at its correct position // in sorted array $p = partition( $arr, $l, $h ); // If there are elements on left side of pivot, // then push left side to stack if ( $p-1 > $l ) { $stack[ ++$top ] = $l; $stack[ ++$top ] = $p - 1; } // If there are elements on right side of pivot, // then push right side to stack if ( $p+1 < $h ) { $stack[ ++$top ] = $p + 1; $stack[ ++$top ] = $h; } }} // A utility function to print contents of arrfunction printArr( $arr, $n ){ for ( $i = 0; $i < $n; ++$i ) echo $arr[$i]." ";} // Driver code $arr = array(4, 3, 5, 2, 1, 3, 2, 3); $n = count($arr); quickSortIterative($arr, 0, $n - 1 ); printArr($arr, $n ); // This is code is contributed by chandan_jnu?>
<script> // Javascript program for implementation of QuickSort /* This function takes last element as pivot, places the pivot element at its correct position in sorted array, and places all smaller (smaller than pivot) to left of pivot and all greater elements to right of pivot */ function partition(arr, low, high) { let temp; let pivot = arr[high]; // index of smaller element let i = (low - 1); for (let j = low; j <= high - 1; j++) { // If current element is smaller // than or equal to pivot if (arr[j] <= pivot) { i++; // swap arr[i] and arr[j] temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } // swap arr[i+1] and arr[high] // (or pivot) temp = arr[i + 1]; arr[i + 1] = arr[high]; arr[high] = temp; return i + 1; } /* A[] --> Array to be sorted, l --> Starting index, h --> Ending index */ function quickSortIterative(arr, l, h) { // Create an auxiliary stack let stack = new Array(h - l + 1); stack.fill(0); // initialize top of stack let top = -1; // push initial values of l and h to // stack stack[++top] = l; stack[++top] = h; // Keep popping from stack while // is not empty while (top >= 0) { // Pop h and l h = stack[top--]; l = stack[top--]; // Set pivot element at its // correct position in // sorted array let p = partition(arr, l, h); // If there are elements on // left side of pivot, then // push left side to stack if (p - 1 > l) { stack[++top] = l; stack[++top] = p - 1; } // If there are elements on // right side of pivot, then // push right side to stack if (p + 1 < h) { stack[++top] = p + 1; stack[++top] = h; } } } let arr = [ 4, 3, 5, 2, 1, 3, 2, 3 ]; let n = 8; // Function calling quickSortIterative(arr, 0, n - 1); for (let i = 0; i < n; i++) document.write(arr[i] + " "); // This code is contributed by mukesh07.</script>
Output:
1 2 2 3 3 3 4 5
The above-mentioned optimizations for recursive quicksort can also be applied to the iterative version.1) Partition process is the same in both recursive and iterative. The same techniques to choose optimal pivot can also be applied to the iterative version.2) To reduce the stack size, first push the indexes of smaller half.3) Use insertion sort when the size reduces below an experimentally calculated threshold.References: http://en.wikipedia.org/wiki/QuicksortThis article is compiled by Aashish Barnwal and reviewed by GeeksforGeeks team. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
nitin mittal
vt_m
rathbhupendra
Chandan_Kumar
divyeshrabadiya07
mukesh07
ddeevviissaavviittaa
Quick Sort
Sorting
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge Sort
QuickSort
Bubble Sort
Insertion Sort
Selection Sort
HeapSort
std::sort() in C++ STL
Time Complexities of all Sorting Algorithms
Radix Sort
Merge two sorted arrays | [
{
"code": null,
"e": 35841,
"s": 35813,
"text": "\n06 Sep, 2021"
},
{
"code": null,
"e": 35938,
"s": 35841,
"text": "Following is a typical recursive implementation of Quick Sort that uses last element as pivot. "
},
{
"code": null,
"e": 35942,
"s": 35938,
"text": "C++"
},
{
"code": null,
"e": 35947,
"s": 35942,
"text": "Java"
},
{
"code": null,
"e": 35955,
"s": 35947,
"text": "Python3"
},
{
"code": null,
"e": 35958,
"s": 35955,
"text": "C#"
},
{
"code": null,
"e": 35962,
"s": 35958,
"text": "PHP"
},
{
"code": null,
"e": 35973,
"s": 35962,
"text": "Javascript"
},
{
"code": "// CPP code for recursive function of Quicksort#include <bits/stdc++.h> using namespace std; // Function to swap numbersvoid swap(int* a, int* b){ int temp = *a; *a = *b; *b = temp;} /* This function takes last element as pivot, places the pivot element at its correct position in sorted array, and places all smaller (smaller than pivot) to left of pivot and all greater elements to right of pivot */int partition(int arr[], int l, int h){ int x = arr[h]; int i = (l - 1); for (int j = l; j <= h - 1; j++) { if (arr[j] <= x) { i++; swap(&arr[i], &arr[j]); } } swap(&arr[i + 1], &arr[h]); return (i + 1);} /* A[] --> Array to be sorted,l --> Starting index,h --> Ending index */void quickSort(int A[], int l, int h){ if (l < h) { /* Partitioning index */ int p = partition(A, l, h); quickSort(A, l, p - 1); quickSort(A, p + 1, h); }} // Driver codeint main(){ int n = 5; int arr[n] = { 4, 2, 6, 9, 2 }; quickSort(arr, 0, n - 1); for (int i = 0; i < n; i++) { cout << arr[i] << \" \"; } return 0;}",
"e": 37106,
"s": 35973,
"text": null
},
{
"code": "// Java program for implementation of QuickSortimport java.util.*; class QuickSort { /* This function takes last element as pivot, places the pivot element at its correct position in sorted array, and places all smaller (smaller than pivot) to left of pivot and all greater elements to right of pivot */ static int partition(int arr[], int low, int high) { int pivot = arr[high]; int i = (low - 1); // index of smaller element for (int j = low; j <= high - 1; j++) { // If current element is smaller than or // equal to pivot if (arr[j] <= pivot) { i++; // swap arr[i] and arr[j] int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } // swap arr[i+1] and arr[high] (or pivot) int temp = arr[i + 1]; arr[i + 1] = arr[high]; arr[high] = temp; return i + 1; } /* The main function that implements QuickSort() arr[] --> Array to be sorted, low --> Starting index, high --> Ending index */ static void qSort(int arr[], int low, int high) { if (low < high) { /* pi is partitioning index, arr[pi] is now at right place */ int pi = partition(arr, low, high); // Recursively sort elements before // partition and after partition qSort(arr, low, pi - 1); qSort(arr, pi + 1, high); } } // Driver code public static void main(String args[]) { int n = 5; int arr[] = { 4, 2, 6, 9, 2 }; qSort(arr, 0, n - 1); for (int i = 0; i < n; i++) { System.out.print(arr[i] + \" \"); } }}",
"e": 38857,
"s": 37106,
"text": null
},
{
"code": "# A typical recursive Python# implementation of QuickSort # Function takes last element as pivot,# places the pivot element at its correct# position in sorted array, and places all# smaller (smaller than pivot) to left of# pivot and all greater elements to right# of pivotdef partition(arr, low, high): i = (low - 1) # index of smaller element pivot = arr[high] # pivot for j in range(low, high): # If current element is smaller # than or equal to pivot if arr[j] <= pivot: # increment index of # smaller element i += 1 arr[i], arr[j] = arr[j], arr[i] arr[i + 1], arr[high] = arr[high], arr[i + 1] return (i + 1) # The main function that implements QuickSort# arr[] --> Array to be sorted,# low --> Starting index,# high --> Ending index # Function to do Quick sortdef quickSort(arr, low, high): if low < high: # pi is partitioning index, arr[p] is now # at right place pi = partition(arr, low, high) # Separately sort elements before # partition and after partition quickSort(arr, low, pi-1) quickSort(arr, pi + 1, high) # Driver Codeif __name__ == '__main__' : arr = [4, 2, 6, 9, 2] n = len(arr) # Calling quickSort function quickSort(arr, 0, n - 1) for i in range(n): print(arr[i], end = \" \")",
"e": 40248,
"s": 38857,
"text": null
},
{
"code": "// C# program for implementation of// QuickSortusing System; class GFG { /* This function takes last element as pivot, places the pivot element at its correct position in sorted array, and places all smaller (smaller than pivot) to left of pivot and all greater elements to right of pivot */ static int partition(int[] arr, int low, int high) { int temp; int pivot = arr[high]; // index of smaller element int i = (low - 1); for (int j = low; j <= high - 1; j++) { // If current element is // smaller than or // equal to pivot if (arr[j] <= pivot) { i++; // swap arr[i] and arr[j] temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } // swap arr[i+1] and arr[high] // (or pivot) temp = arr[i + 1]; arr[i + 1] = arr[high]; arr[high] = temp; return i + 1; } /* The main function that implements QuickSort() arr[] --> Array to be sorted, low --> Starting index, high --> Ending index */ static void qSort(int[] arr, int low, int high) { if (low < high) { /* pi is partitioning index, arr[pi] is now at right place */ int pi = partition(arr, low, high); // Recursively sort elements // before partition and after // partition qSort(arr, low, pi - 1); qSort(arr, pi + 1, high); } } // Driver code public static void Main() { int n = 5; int[] arr = { 4, 2, 6, 9, 2 }; qSort(arr, 0, n - 1); for (int i = 0; i < n; i++) Console.Write(arr[i] + \" \"); }} // This code is contributed by nitin mittal.",
"e": 42113,
"s": 40248,
"text": null
},
{
"code": "<?php// PHP code for recursive function// of Quicksort // Function to swap numbersfunction swap(&$a, &$b){ $temp = $a; $a = $b; $b = $temp;} /* This function takes last element as pivot,places the pivot element at its correctposition in sorted array, and placesall smaller (smaller than pivot) to leftof pivot and all greater elements toright of pivot */function partition (&$arr, $l, $h){ $x = $arr[$h]; $i = ($l - 1); for ($j = $l; $j <= $h - 1; $j++) { if ($arr[$j] <= $x) { $i++; swap ($arr[$i], $arr[$j]); } } swap ($arr[$i + 1], $arr[$h]); return ($i + 1);} /* A[] --> Array to be sorted,l --> Starting index,h --> Ending index */function quickSort(&$A, $l, $h){ if ($l < $h) { /* Partitioning index */ $p = partition($A, $l, $h); quickSort($A, $l, $p - 1); quickSort($A, $p + 1, $h); } } // Driver code$n = 5;$arr = array(4, 2, 6, 9, 2); quickSort($arr, 0, $n - 1); for($i = 0; $i < $n; $i++){ echo $arr[$i] . \" \";} // This code is contributed by// rathbhupendra?>",
"e": 43203,
"s": 42113,
"text": null
},
{
"code": "<script> // JavaScript program for implementation of QuickSort /* This function takes last element as pivot, places the pivot element at its correct position in sorted array, and places all smaller (smaller than pivot) to left of pivot and all greater elements to right of pivot */ function partition(arr, low, high) { let temp; let pivot = arr[high]; // index of smaller element let i = (low - 1); for (let j = low; j <= high - 1; j++) { // If current element is // smaller than or // equal to pivot if (arr[j] <= pivot) { i++; // swap arr[i] and arr[j] temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } // swap arr[i+1] and arr[high] // (or pivot) temp = arr[i + 1]; arr[i + 1] = arr[high]; arr[high] = temp; return i + 1; } /* The main function that implements QuickSort() arr[] --> Array to be sorted, low --> Starting index, high --> Ending index */ function qSort(arr, low, high) { if (low < high) { /* pi is partitioning index, arr[pi] is now at right place */ let pi = partition(arr, low, high); // Recursively sort elements // before partition and after // partition qSort(arr, low, pi - 1); qSort(arr, pi + 1, high); } } let n = 5; let arr = [ 4, 2, 6, 9, 2 ]; qSort(arr, 0, n - 1); for (let i = 0; i < n; i++) document.write(arr[i] + \" \"); </script>",
"e": 44891,
"s": 43203,
"text": null
},
{
"code": null,
"e": 44901,
"s": 44891,
"text": "Output: "
},
{
"code": null,
"e": 44911,
"s": 44901,
"text": "2 2 4 6 9"
},
{
"code": null,
"e": 46285,
"s": 44911,
"text": "The above implementation can be optimized in many ways1) The above implementation uses the last index as a pivot. This causes worst-case behavior on already sorted arrays, which is a commonly occurring case. The problem can be solved by choosing either a random index for the pivot or choosing the middle index of the partition or choosing the median of the first, middle, and last element of the partition for the pivot. (See this for details)2) To reduce the recursion depth, recur first for the smaller half of the array, and use a tail call to recurse into the other. 3) Insertion sort works better for small subarrays. Insertion sort can be used for invocations on such small arrays (i.e. where the length is less than a threshold t determined experimentally). For example, this library implementation of Quicksort uses insertion sort below size 7. Despite the above optimizations, the function remains recursive and uses function call stack to store intermediate values of l and h. The function call stack stores other bookkeeping information together with parameters. Also, function calls involve overheads like storing activation records of the caller function and then resuming execution. The above function can be easily converted to an iterative version with the help of an auxiliary stack. Following is an iterative implementation of the above recursive code. "
},
{
"code": null,
"e": 46289,
"s": 46285,
"text": "C++"
},
{
"code": null,
"e": 46291,
"s": 46289,
"text": "C"
},
{
"code": null,
"e": 46296,
"s": 46291,
"text": "Java"
},
{
"code": null,
"e": 46303,
"s": 46296,
"text": "Python"
},
{
"code": null,
"e": 46306,
"s": 46303,
"text": "C#"
},
{
"code": null,
"e": 46310,
"s": 46306,
"text": "PHP"
},
{
"code": null,
"e": 46321,
"s": 46310,
"text": "Javascript"
},
{
"code": "// An iterative implementation of quick sort#include <bits/stdc++.h>using namespace std; // A utility function to swap two elementsvoid swap(int* a, int* b){ int t = *a; *a = *b; *b = t;} /* This function is same in both iterative and recursive*/int partition(int arr[], int l, int h){ int x = arr[h]; int i = (l - 1); for (int j = l; j <= h - 1; j++) { if (arr[j] <= x) { i++; swap(&arr[i], &arr[j]); } } swap(&arr[i + 1], &arr[h]); return (i + 1);} /* A[] --> Array to be sorted,l --> Starting index,h --> Ending index */void quickSortIterative(int arr[], int l, int h){ // Create an auxiliary stack int stack[h - l + 1]; // initialize top of stack int top = -1; // push initial values of l and h to stack stack[++top] = l; stack[++top] = h; // Keep popping from stack while is not empty while (top >= 0) { // Pop h and l h = stack[top--]; l = stack[top--]; // Set pivot element at its correct position // in sorted array int p = partition(arr, l, h); // If there are elements on left side of pivot, // then push left side to stack if (p - 1 > l) { stack[++top] = l; stack[++top] = p - 1; } // If there are elements on right side of pivot, // then push right side to stack if (p + 1 < h) { stack[++top] = p + 1; stack[++top] = h; } }} // A utility function to print contents of arrvoid printArr(int arr[], int n){ int i; for (i = 0; i < n; ++i) cout << arr[i] << \" \";} // Driver codeint main(){ int arr[] = { 4, 3, 5, 2, 1, 3, 2, 3 }; int n = sizeof(arr) / sizeof(*arr); quickSortIterative(arr, 0, n - 1); printArr(arr, n); return 0;} // This is code is contributed by rathbhupendra",
"e": 48176,
"s": 46321,
"text": null
},
{
"code": "// An iterative implementation of quick sort#include <stdio.h> // A utility function to swap two elementsvoid swap(int* a, int* b){ int t = *a; *a = *b; *b = t;} /* This function is same in both iterative and recursive*/int partition(int arr[], int l, int h){ int x = arr[h]; int i = (l - 1); for (int j = l; j <= h - 1; j++) { if (arr[j] <= x) { i++; swap(&arr[i], &arr[j]); } } swap(&arr[i + 1], &arr[h]); return (i + 1);} /* A[] --> Array to be sorted, l --> Starting index, h --> Ending index */void quickSortIterative(int arr[], int l, int h){ // Create an auxiliary stack int stack[h - l + 1]; // initialize top of stack int top = -1; // push initial values of l and h to stack stack[++top] = l; stack[++top] = h; // Keep popping from stack while is not empty while (top >= 0) { // Pop h and l h = stack[top--]; l = stack[top--]; // Set pivot element at its correct position // in sorted array int p = partition(arr, l, h); // If there are elements on left side of pivot, // then push left side to stack if (p - 1 > l) { stack[++top] = l; stack[++top] = p - 1; } // If there are elements on right side of pivot, // then push right side to stack if (p + 1 < h) { stack[++top] = p + 1; stack[++top] = h; } }} // A utility function to print contents of arrvoid printArr(int arr[], int n){ int i; for (i = 0; i < n; ++i) printf(\"%d \", arr[i]);} // Driver program to test above functionsint main(){ int arr[] = { 4, 3, 5, 2, 1, 3, 2, 3 }; int n = sizeof(arr) / sizeof(*arr); quickSortIterative(arr, 0, n - 1); printArr(arr, n); return 0;}",
"e": 49992,
"s": 48176,
"text": null
},
{
"code": "// Java program for implementation of QuickSortimport java.util.*; class QuickSort { /* This function takes last element as pivot, places the pivot element at its correct position in sorted array, and places all smaller (smaller than pivot) to left of pivot and all greater elements to right of pivot */ static int partition(int arr[], int low, int high) { int pivot = arr[high]; // index of smaller element int i = (low - 1); for (int j = low; j <= high - 1; j++) { // If current element is smaller than or // equal to pivot if (arr[j] <= pivot) { i++; // swap arr[i] and arr[j] int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } // swap arr[i+1] and arr[high] (or pivot) int temp = arr[i + 1]; arr[i + 1] = arr[high]; arr[high] = temp; return i + 1; } /* A[] --> Array to be sorted, l --> Starting index, h --> Ending index */ static void quickSortIterative(int arr[], int l, int h) { // Create an auxiliary stack int[] stack = new int[h - l + 1]; // initialize top of stack int top = -1; // push initial values of l and h to stack stack[++top] = l; stack[++top] = h; // Keep popping from stack while is not empty while (top >= 0) { // Pop h and l h = stack[top--]; l = stack[top--]; // Set pivot element at its correct position // in sorted array int p = partition(arr, l, h); // If there are elements on left side of pivot, // then push left side to stack if (p - 1 > l) { stack[++top] = l; stack[++top] = p - 1; } // If there are elements on right side of pivot, // then push right side to stack if (p + 1 < h) { stack[++top] = p + 1; stack[++top] = h; } } } // Driver code public static void main(String args[]) { int arr[] = { 4, 3, 5, 2, 1, 3, 2, 3 }; int n = 8; // Function calling quickSortIterative(arr, 0, n - 1); for (int i = 0; i < n; i++) { System.out.print(arr[i] + \" \"); } }}",
"e": 52385,
"s": 49992,
"text": null
},
{
"code": "# Python program for implementation of Quicksort # This function is same in both iterative and recursivedef partition(arr, l, h): i = ( l - 1 ) x = arr[h] for j in range(l, h): if arr[j] <= x: # increment index of smaller element i = i + 1 arr[i], arr[j] = arr[j], arr[i] arr[i + 1], arr[h] = arr[h], arr[i + 1] return (i + 1) # Function to do Quick sort# arr[] --> Array to be sorted,# l --> Starting index,# h --> Ending indexdef quickSortIterative(arr, l, h): # Create an auxiliary stack size = h - l + 1 stack = [0] * (size) # initialize top of stack top = -1 # push initial values of l and h to stack top = top + 1 stack[top] = l top = top + 1 stack[top] = h # Keep popping from stack while is not empty while top >= 0: # Pop h and l h = stack[top] top = top - 1 l = stack[top] top = top - 1 # Set pivot element at its correct position in # sorted array p = partition( arr, l, h ) # If there are elements on left side of pivot, # then push left side to stack if p-1 > l: top = top + 1 stack[top] = l top = top + 1 stack[top] = p - 1 # If there are elements on right side of pivot, # then push right side to stack if p + 1 < h: top = top + 1 stack[top] = p + 1 top = top + 1 stack[top] = h # Driver code to test abovearr = [4, 3, 5, 2, 1, 3, 2, 3]n = len(arr)quickSortIterative(arr, 0, n-1)print (\"Sorted array is:\")for i in range(n): print (\"% d\" % arr[i]), # This code is contributed by Mohit Kumra",
"e": 54085,
"s": 52385,
"text": null
},
{
"code": "// C# program for implementation of QuickSortusing System; class GFG { /* This function takes last element as pivot, places the pivot element at its correct position in sorted array, and places all smaller (smaller than pivot) to left of pivot and all greater elements to right of pivot */ static int partition(int[] arr, int low, int high) { int temp; int pivot = arr[high]; // index of smaller element int i = (low - 1); for (int j = low; j <= high - 1; j++) { // If current element is smaller // than or equal to pivot if (arr[j] <= pivot) { i++; // swap arr[i] and arr[j] temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } // swap arr[i+1] and arr[high] // (or pivot) temp = arr[i + 1]; arr[i + 1] = arr[high]; arr[high] = temp; return i + 1; } /* A[] --> Array to be sorted, l --> Starting index, h --> Ending index */ static void quickSortIterative(int[] arr, int l, int h) { // Create an auxiliary stack int[] stack = new int[h - l + 1]; // initialize top of stack int top = -1; // push initial values of l and h to // stack stack[++top] = l; stack[++top] = h; // Keep popping from stack while // is not empty while (top >= 0) { // Pop h and l h = stack[top--]; l = stack[top--]; // Set pivot element at its // correct position in // sorted array int p = partition(arr, l, h); // If there are elements on // left side of pivot, then // push left side to stack if (p - 1 > l) { stack[++top] = l; stack[++top] = p - 1; } // If there are elements on // right side of pivot, then // push right side to stack if (p + 1 < h) { stack[++top] = p + 1; stack[++top] = h; } } } // Driver code public static void Main() { int[] arr = { 4, 3, 5, 2, 1, 3, 2, 3 }; int n = 8; // Function calling quickSortIterative(arr, 0, n - 1); for (int i = 0; i < n; i++) Console.Write(arr[i] + \" \"); }} // This code is contributed by anuj_67.",
"e": 56619,
"s": 54085,
"text": null
},
{
"code": "<?php// An iterative implementation of quick sort // A utility function to swap two elementsfunction swap ( &$a, &$b ){ $t = $a; $a = $b; $b = $t;} /* This function is same in both iterative and recursive*/function partition (&$arr, $l, $h){ $x = $arr[$h]; $i = ($l - 1); for ($j = $l; $j <= $h- 1; $j++) { if ($arr[$j] <= $x) { $i++; swap ($arr[$i], $arr[$j]); } } swap ($arr[$i + 1], $arr[$h]); return ($i + 1);} /* A[] --> Array to be sorted,l --> Starting index,h --> Ending index */function quickSortIterative (&$arr, $l, $h){ // Create an auxiliary stack $stack=array_fill(0, $h - $l + 1, 0); // initialize top of stack $top = -1; // push initial values of l and h to stack $stack[ ++$top ] = $l; $stack[ ++$top ] = $h; // Keep popping from stack while is not empty while ( $top >= 0 ) { // Pop h and l $h = $stack[ $top-- ]; $l = $stack[ $top-- ]; // Set pivot element at its correct position // in sorted array $p = partition( $arr, $l, $h ); // If there are elements on left side of pivot, // then push left side to stack if ( $p-1 > $l ) { $stack[ ++$top ] = $l; $stack[ ++$top ] = $p - 1; } // If there are elements on right side of pivot, // then push right side to stack if ( $p+1 < $h ) { $stack[ ++$top ] = $p + 1; $stack[ ++$top ] = $h; } }} // A utility function to print contents of arrfunction printArr( $arr, $n ){ for ( $i = 0; $i < $n; ++$i ) echo $arr[$i].\" \";} // Driver code $arr = array(4, 3, 5, 2, 1, 3, 2, 3); $n = count($arr); quickSortIterative($arr, 0, $n - 1 ); printArr($arr, $n ); // This is code is contributed by chandan_jnu?>",
"e": 58473,
"s": 56619,
"text": null
},
{
"code": "<script> // Javascript program for implementation of QuickSort /* This function takes last element as pivot, places the pivot element at its correct position in sorted array, and places all smaller (smaller than pivot) to left of pivot and all greater elements to right of pivot */ function partition(arr, low, high) { let temp; let pivot = arr[high]; // index of smaller element let i = (low - 1); for (let j = low; j <= high - 1; j++) { // If current element is smaller // than or equal to pivot if (arr[j] <= pivot) { i++; // swap arr[i] and arr[j] temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } // swap arr[i+1] and arr[high] // (or pivot) temp = arr[i + 1]; arr[i + 1] = arr[high]; arr[high] = temp; return i + 1; } /* A[] --> Array to be sorted, l --> Starting index, h --> Ending index */ function quickSortIterative(arr, l, h) { // Create an auxiliary stack let stack = new Array(h - l + 1); stack.fill(0); // initialize top of stack let top = -1; // push initial values of l and h to // stack stack[++top] = l; stack[++top] = h; // Keep popping from stack while // is not empty while (top >= 0) { // Pop h and l h = stack[top--]; l = stack[top--]; // Set pivot element at its // correct position in // sorted array let p = partition(arr, l, h); // If there are elements on // left side of pivot, then // push left side to stack if (p - 1 > l) { stack[++top] = l; stack[++top] = p - 1; } // If there are elements on // right side of pivot, then // push right side to stack if (p + 1 < h) { stack[++top] = p + 1; stack[++top] = h; } } } let arr = [ 4, 3, 5, 2, 1, 3, 2, 3 ]; let n = 8; // Function calling quickSortIterative(arr, 0, n - 1); for (let i = 0; i < n; i++) document.write(arr[i] + \" \"); // This code is contributed by mukesh07.</script>",
"e": 60878,
"s": 58473,
"text": null
},
{
"code": null,
"e": 60887,
"s": 60878,
"text": "Output: "
},
{
"code": null,
"e": 60903,
"s": 60887,
"text": "1 2 2 3 3 3 4 5"
},
{
"code": null,
"e": 61574,
"s": 60903,
"text": "The above-mentioned optimizations for recursive quicksort can also be applied to the iterative version.1) Partition process is the same in both recursive and iterative. The same techniques to choose optimal pivot can also be applied to the iterative version.2) To reduce the stack size, first push the indexes of smaller half.3) Use insertion sort when the size reduces below an experimentally calculated threshold.References: http://en.wikipedia.org/wiki/QuicksortThis article is compiled by Aashish Barnwal and reviewed by GeeksforGeeks team. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 61587,
"s": 61574,
"text": "nitin mittal"
},
{
"code": null,
"e": 61592,
"s": 61587,
"text": "vt_m"
},
{
"code": null,
"e": 61606,
"s": 61592,
"text": "rathbhupendra"
},
{
"code": null,
"e": 61620,
"s": 61606,
"text": "Chandan_Kumar"
},
{
"code": null,
"e": 61638,
"s": 61620,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 61647,
"s": 61638,
"text": "mukesh07"
},
{
"code": null,
"e": 61668,
"s": 61647,
"text": "ddeevviissaavviittaa"
},
{
"code": null,
"e": 61679,
"s": 61668,
"text": "Quick Sort"
},
{
"code": null,
"e": 61687,
"s": 61679,
"text": "Sorting"
},
{
"code": null,
"e": 61695,
"s": 61687,
"text": "Sorting"
},
{
"code": null,
"e": 61793,
"s": 61695,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 61804,
"s": 61793,
"text": "Merge Sort"
},
{
"code": null,
"e": 61814,
"s": 61804,
"text": "QuickSort"
},
{
"code": null,
"e": 61826,
"s": 61814,
"text": "Bubble Sort"
},
{
"code": null,
"e": 61841,
"s": 61826,
"text": "Insertion Sort"
},
{
"code": null,
"e": 61856,
"s": 61841,
"text": "Selection Sort"
},
{
"code": null,
"e": 61865,
"s": 61856,
"text": "HeapSort"
},
{
"code": null,
"e": 61888,
"s": 61865,
"text": "std::sort() in C++ STL"
},
{
"code": null,
"e": 61932,
"s": 61888,
"text": "Time Complexities of all Sorting Algorithms"
},
{
"code": null,
"e": 61943,
"s": 61932,
"text": "Radix Sort"
}
] |
Port scanner using 'python-nmap' - GeeksforGeeks | 21 Apr, 2020
In this article, we will learn how to program a port scanner using the ‘nmap‘ module in Python. The program will take a range of port numbers as input and print the state (open or closed) of all the ports in that range.
Nmap: Nmap is a free and open-source network scanning tool. To run the program discussed in this article, you will need to have ‘nmap’ tool installed in your system. If it is not installed, visit Nmap download page.
We will be using the ‘python-nmap‘ module to achieve this task. Install the package (if not already installed) by the following command –
pip install python-nmap
Note: Doing ‘nmap’ scans on a target without proper permission and authority is illegal. Use localhost (127.0.0.1) as your target
Example:
import nmap # take the range of ports to # be scannedbegin = 75end = 80 # assign the target ip to be scanned to# a variabletarget = '127.0.0.1' # instantiate a PortScanner objectscanner = nmap.PortScanner() for i in range(begin,end+1): # scan the target port res = scanner.scan(target,str(i)) # the result is a dictionary containing # several information we only need to # check if the port is opened or closed # so we will access only that information # in the dictionary res = res['scan'][target]['tcp'][i]['state'] print(f'port {i} is {res}.')
Output:
port 75 is closed.
port 76 is closed.
port 77 is closed.
port 78 is closed.
port 79 is closed.
port 80 is open.
Note: The output can vary depending on the present status of the ports.
python-modules
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 ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n21 Apr, 2020"
},
{
"code": null,
"e": 25757,
"s": 25537,
"text": "In this article, we will learn how to program a port scanner using the ‘nmap‘ module in Python. The program will take a range of port numbers as input and print the state (open or closed) of all the ports in that range."
},
{
"code": null,
"e": 25973,
"s": 25757,
"text": "Nmap: Nmap is a free and open-source network scanning tool. To run the program discussed in this article, you will need to have ‘nmap’ tool installed in your system. If it is not installed, visit Nmap download page."
},
{
"code": null,
"e": 26111,
"s": 25973,
"text": "We will be using the ‘python-nmap‘ module to achieve this task. Install the package (if not already installed) by the following command –"
},
{
"code": null,
"e": 26136,
"s": 26111,
"text": "pip install python-nmap\n"
},
{
"code": null,
"e": 26266,
"s": 26136,
"text": "Note: Doing ‘nmap’ scans on a target without proper permission and authority is illegal. Use localhost (127.0.0.1) as your target"
},
{
"code": null,
"e": 26275,
"s": 26266,
"text": "Example:"
},
{
"code": "import nmap # take the range of ports to # be scannedbegin = 75end = 80 # assign the target ip to be scanned to# a variabletarget = '127.0.0.1' # instantiate a PortScanner objectscanner = nmap.PortScanner() for i in range(begin,end+1): # scan the target port res = scanner.scan(target,str(i)) # the result is a dictionary containing # several information we only need to # check if the port is opened or closed # so we will access only that information # in the dictionary res = res['scan'][target]['tcp'][i]['state'] print(f'port {i} is {res}.')",
"e": 26867,
"s": 26275,
"text": null
},
{
"code": null,
"e": 26875,
"s": 26867,
"text": "Output:"
},
{
"code": null,
"e": 26988,
"s": 26875,
"text": "port 75 is closed.\nport 76 is closed.\nport 77 is closed.\nport 78 is closed.\nport 79 is closed.\nport 80 is open.\n"
},
{
"code": null,
"e": 27060,
"s": 26988,
"text": "Note: The output can vary depending on the present status of the ports."
},
{
"code": null,
"e": 27075,
"s": 27060,
"text": "python-modules"
},
{
"code": null,
"e": 27090,
"s": 27075,
"text": "python-utility"
},
{
"code": null,
"e": 27097,
"s": 27090,
"text": "Python"
},
{
"code": null,
"e": 27195,
"s": 27097,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27227,
"s": 27195,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27269,
"s": 27227,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27311,
"s": 27269,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27338,
"s": 27311,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27394,
"s": 27338,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27433,
"s": 27394,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27455,
"s": 27433,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27486,
"s": 27455,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27515,
"s": 27486,
"text": "Create a directory in Python"
}
] |
Count of equal value pairs from given two Arrays such that a[i] equals b[j] - GeeksforGeeks | 13 Dec, 2021
Given two arrays a[] and b[] of length N and M respectively, sorted in non-decreasing order. The task is to find the number of pairs (i, j) such that, a[i] equals b[j].
Examples:
Input: a[] = {1, 1, 3, 3, 3, 5, 8, 8}, b[] = {1, 3, 3, 4, 5, 5, 5}Output: 11Explanation: Following are the 11 pairs with given condition The 11 pairs are {{1, 1}, {1, 1}, {3, 3}, {3, 3}, {3, 3}, {3, 3}, {3, 3}, {3, 3}, {5, 5}, {5, 5}, {5, 5}} .
Input: a[] = {1, 2, 3, 4}, b[] = {1, 1, 2}Output: 3
Approach: This problem can be solved by using the Two Pointer approach. Let i point to the first element of array a[] and j point to the first element of array b[]. While traversing the arrays, there will be 3 cases.
Case 1: a[i] = b[j] Let target denote arr[i], cnt1 denote number of elements of array a that are equal to target and cnt2 denote the number of elements of array b that are equal to target. So the total number of pairs such that a[i] = b[j] is cnt1 * cnt2 . So our answer is incremented by cnt1 * cnt2 .Case 2: a[i] < b[j] The only possibility of getting a[i] = b[j] in the future is by incrementing i, so we do i++.Case 3: a[i] > b[j] The only possibility of getting a[i] = b[j] in the future is by incrementing j, so we do j++ .
Follow the steps below to solve the given problem.
Initialize the variables ans, i and j as 0.
Initialize answer, i, and j to 0 and start traversing both of the arrays till i is less than N or j is less than M.If a[i] equals b[j], calculate cnt1 and cnt2 and increment the answer by cnt1 * cnt2.If a[i] is less than b[j], increment i.If a[i] is greater than b[j], increment j.
If a[i] equals b[j], calculate cnt1 and cnt2 and increment the answer by cnt1 * cnt2.
If a[i] is less than b[j], increment i.
If a[i] is greater than b[j], increment j.
After performing the above steps, print the values of ans as the answer.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ Program for above approach#include <bits/stdc++.h>using namespace std; // Function to find number of pairs with// satisfying the given conditionint findPairs(int* a, int* b, int n, int m){ // Initialize ans, i, j to 0 . int ans = 0, i = 0, j = 0; // Use the two pointer approach to // calculate the answer . while (i < n && j < m) { // Case - 1 if (a[i] == b[j]) { // Target denotes a[i] // or b[j] as a[i] = b[j]. // cnt1 denotes the number // of elements in array // a that are equal to target. // cnt2 denotes the number // of elements in array // b that are equal to target int target = a[i], cnt1 = 0, cnt2 = 0; // Calculate cnt1 while (i < n && a[i] == target) { cnt1++; i++; } // Calculate cnt2 while (j < m && b[j] == target) { cnt2++; j++; } // Increment the answer by (cnt1 * cnt2) ans += (cnt1 * cnt2); } // Case - 2 else if (a[i] < b[j]) i++; // Case - 3 else j++; } // Return the answer return ans;} // Driver Codeint main(){ int N = 8, M = 7; int a[] = { 1, 1, 3, 3, 3, 5, 8, 8 }; int b[] = { 1, 3, 3, 4, 5, 5, 5 }; cout << findPairs(a, b, N, M);}
// Java program for above approachimport java.io.*; class GFG{ // Function to find number of pairs with// satisfying the given conditionstatic int findPairs(int[] a, int[] b, int n, int m){ // Initialize ans, i, j to 0 . int ans = 0, i = 0, j = 0; // Use the two pointer approach to // calculate the answer . while (i < n && j < m) { // Case - 1 if (a[i] == b[j]) { // Target denotes a[i] // or b[j] as a[i] = b[j]. // cnt1 denotes the number // of elements in array // a that are equal to target. // cnt2 denotes the number // of elements in array // b that are equal to target int target = a[i], cnt1 = 0, cnt2 = 0; // Calculate cnt1 while (i < n && a[i] == target) { cnt1++; i++; } // Calculate cnt2 while (j < m && b[j] == target) { cnt2++; j++; } // Increment the answer by (cnt1 * cnt2) ans += (cnt1 * cnt2); } // Case - 2 else if (a[i] < b[j]) i++; // Case - 3 else j++; } // Return the answer return ans;} // Driver Codepublic static void main(String[] args){ int N = 8, M = 7; int a[] = { 1, 1, 3, 3, 3, 5, 8, 8 }; int b[] = { 1, 3, 3, 4, 5, 5, 5 }; System.out.println(findPairs(a, b, N, M));}} // This code is contributed by Potta Lokesh
# Python3 program for above approach # Function to find number of pairs with# satisfying the given conditiondef findPairs(a, b, n, m): # Initialize ans, i, j to 0 . ans = 0 i = 0 j = 0 # Use the two pointer approach to # calculate the answer . while (i < n and j < m): # Case - 1 if (a[i] == b[j]): # Target denotes a[i] # or b[j] as a[i] = b[j]. # cnt1 denotes the number # of elements in array # a that are equal to target. # cnt2 denotes the number # of elements in array # b that are equal to target target = a[i] cnt1 = 0 cnt2 = 0 # Calculate cnt1 while (i < n and a[i] == target): cnt1 += 1 i += 1 # Calculate cnt2 while (j < m and b[j] == target): cnt2 += 1 j += 1 # Increment the answer by (cnt1 * cnt2) ans += (cnt1 * cnt2) # Case - 2 elif (a[i] < b[j]): i += 1 # Case- 3 else: j += 1 # Return the answer return ans # Driver Codeif __name__ == "__main__": N = 8 M = 7 a = [ 1, 1, 3, 3, 3, 5, 8, 8 ] b = [ 1, 3, 3, 4, 5, 5, 5 ] print(findPairs(a, b, N, M)) # This code is contributed by ukasp
// C# program for above approachusing System; class GFG{ // Function to find number of pairs with// satisfying the given conditionstatic int findPairs(int[] a, int[] b, int n, int m){ // Initialize ans, i, j to 0 . int ans = 0, i = 0, j = 0; // Use the two pointer approach to // calculate the answer . while (i < n && j < m) { // Case - 1 if (a[i] == b[j]) { // Target denotes a[i] // or b[j] as a[i] = b[j]. // cnt1 denotes the number // of elements in array // a that are equal to target. // cnt2 denotes the number // of elements in array // b that are equal to target int target = a[i], cnt1 = 0, cnt2 = 0; // Calculate cnt1 while (i < n && a[i] == target) { cnt1++; i++; } // Calculate cnt2 while (j < m && b[j] == target) { cnt2++; j++; } // Increment the answer by (cnt1 * cnt2) ans += (cnt1 * cnt2); } // Case - 2 else if (a[i] < b[j]) i++; // Case - 3 else j++; } // Return the answer return ans;} // Driver Codepublic static void Main(){ int N = 8, M = 7; int []a = { 1, 1, 3, 3, 3, 5, 8, 8 }; int []b = { 1, 3, 3, 4, 5, 5, 5 }; Console.Write(findPairs(a, b, N, M));}} // This code is contributed by Samim Hossain Mondal.
<script>// Javascript Program for above approach // Function to find number of pairs with// satisfying the given conditionfunction findPairs(a, b, n, m){ // Initialize ans, i, j to 0 . let ans = 0, i = 0, j = 0; // Use the two pointer approach to // calculate the answer . while (i < n && j < m) { // Case - 1 if (a[i] == b[j]) { // Target denotes a[i] // or b[j] as a[i] = b[j]. // cnt1 denotes the number // of elements in array // a that are equal to target. // cnt2 denotes the number // of elements in array // b that are equal to target let target = a[i], cnt1 = 0, cnt2 = 0; // Calculate cnt1 while (i < n && a[i] == target) { cnt1++; i++; } // Calculate cnt2 while (j < m && b[j] == target) { cnt2++; j++; } // Increment the answer by (cnt1 * cnt2) ans += (cnt1 * cnt2); } // Case - 2 else if (a[i] < b[j]) i++; // Case - 3 else j++; } // Return the answer return ans;} // Driver Codelet N = 8, M = 7;let a = [ 1, 1, 3, 3, 3, 5, 8, 8 ];let b = [ 1, 3, 3, 4, 5, 5, 5 ]; document.write(findPairs(a, b, N, M)); // This code is contributed by saurabh_jaiswal.</script>
11
Time Complexity: O(N + M)Auxiliary Space: O(1)
lokeshpotta20
samim2000
ukasp
_saurabh_jaiswal
two-pointer-algorithm
Arrays
Combinatorial
Mathematical
Sorting
two-pointer-algorithm
Arrays
Mathematical
Sorting
Combinatorial
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Count pairs with given sum
Chocolate Distribution Problem
Window Sliding Technique
Reversal algorithm for array rotation
Next Greater Element
Write a program to print all permutations of a given string
Permutation and Combination in Python
itertools.combinations() module in Python to print all possible combinations
Combinational Sum
Factorial of a large number | [
{
"code": null,
"e": 26041,
"s": 26013,
"text": "\n13 Dec, 2021"
},
{
"code": null,
"e": 26210,
"s": 26041,
"text": "Given two arrays a[] and b[] of length N and M respectively, sorted in non-decreasing order. The task is to find the number of pairs (i, j) such that, a[i] equals b[j]."
},
{
"code": null,
"e": 26220,
"s": 26210,
"text": "Examples:"
},
{
"code": null,
"e": 26466,
"s": 26220,
"text": "Input: a[] = {1, 1, 3, 3, 3, 5, 8, 8}, b[] = {1, 3, 3, 4, 5, 5, 5}Output: 11Explanation: Following are the 11 pairs with given condition The 11 pairs are {{1, 1}, {1, 1}, {3, 3}, {3, 3}, {3, 3}, {3, 3}, {3, 3}, {3, 3}, {5, 5}, {5, 5}, {5, 5}} . "
},
{
"code": null,
"e": 26518,
"s": 26466,
"text": "Input: a[] = {1, 2, 3, 4}, b[] = {1, 1, 2}Output: 3"
},
{
"code": null,
"e": 26735,
"s": 26518,
"text": "Approach: This problem can be solved by using the Two Pointer approach. Let i point to the first element of array a[] and j point to the first element of array b[]. While traversing the arrays, there will be 3 cases."
},
{
"code": null,
"e": 27265,
"s": 26735,
"text": "Case 1: a[i] = b[j] Let target denote arr[i], cnt1 denote number of elements of array a that are equal to target and cnt2 denote the number of elements of array b that are equal to target. So the total number of pairs such that a[i] = b[j] is cnt1 * cnt2 . So our answer is incremented by cnt1 * cnt2 .Case 2: a[i] < b[j] The only possibility of getting a[i] = b[j] in the future is by incrementing i, so we do i++.Case 3: a[i] > b[j] The only possibility of getting a[i] = b[j] in the future is by incrementing j, so we do j++ ."
},
{
"code": null,
"e": 27316,
"s": 27265,
"text": "Follow the steps below to solve the given problem."
},
{
"code": null,
"e": 27360,
"s": 27316,
"text": "Initialize the variables ans, i and j as 0."
},
{
"code": null,
"e": 27642,
"s": 27360,
"text": "Initialize answer, i, and j to 0 and start traversing both of the arrays till i is less than N or j is less than M.If a[i] equals b[j], calculate cnt1 and cnt2 and increment the answer by cnt1 * cnt2.If a[i] is less than b[j], increment i.If a[i] is greater than b[j], increment j."
},
{
"code": null,
"e": 27728,
"s": 27642,
"text": "If a[i] equals b[j], calculate cnt1 and cnt2 and increment the answer by cnt1 * cnt2."
},
{
"code": null,
"e": 27768,
"s": 27728,
"text": "If a[i] is less than b[j], increment i."
},
{
"code": null,
"e": 27811,
"s": 27768,
"text": "If a[i] is greater than b[j], increment j."
},
{
"code": null,
"e": 27884,
"s": 27811,
"text": "After performing the above steps, print the values of ans as the answer."
},
{
"code": null,
"e": 27935,
"s": 27884,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 27939,
"s": 27935,
"text": "C++"
},
{
"code": null,
"e": 27944,
"s": 27939,
"text": "Java"
},
{
"code": null,
"e": 27952,
"s": 27944,
"text": "Python3"
},
{
"code": null,
"e": 27955,
"s": 27952,
"text": "C#"
},
{
"code": null,
"e": 27966,
"s": 27955,
"text": "Javascript"
},
{
"code": "// C++ Program for above approach#include <bits/stdc++.h>using namespace std; // Function to find number of pairs with// satisfying the given conditionint findPairs(int* a, int* b, int n, int m){ // Initialize ans, i, j to 0 . int ans = 0, i = 0, j = 0; // Use the two pointer approach to // calculate the answer . while (i < n && j < m) { // Case - 1 if (a[i] == b[j]) { // Target denotes a[i] // or b[j] as a[i] = b[j]. // cnt1 denotes the number // of elements in array // a that are equal to target. // cnt2 denotes the number // of elements in array // b that are equal to target int target = a[i], cnt1 = 0, cnt2 = 0; // Calculate cnt1 while (i < n && a[i] == target) { cnt1++; i++; } // Calculate cnt2 while (j < m && b[j] == target) { cnt2++; j++; } // Increment the answer by (cnt1 * cnt2) ans += (cnt1 * cnt2); } // Case - 2 else if (a[i] < b[j]) i++; // Case - 3 else j++; } // Return the answer return ans;} // Driver Codeint main(){ int N = 8, M = 7; int a[] = { 1, 1, 3, 3, 3, 5, 8, 8 }; int b[] = { 1, 3, 3, 4, 5, 5, 5 }; cout << findPairs(a, b, N, M);}",
"e": 29402,
"s": 27966,
"text": null
},
{
"code": "// Java program for above approachimport java.io.*; class GFG{ // Function to find number of pairs with// satisfying the given conditionstatic int findPairs(int[] a, int[] b, int n, int m){ // Initialize ans, i, j to 0 . int ans = 0, i = 0, j = 0; // Use the two pointer approach to // calculate the answer . while (i < n && j < m) { // Case - 1 if (a[i] == b[j]) { // Target denotes a[i] // or b[j] as a[i] = b[j]. // cnt1 denotes the number // of elements in array // a that are equal to target. // cnt2 denotes the number // of elements in array // b that are equal to target int target = a[i], cnt1 = 0, cnt2 = 0; // Calculate cnt1 while (i < n && a[i] == target) { cnt1++; i++; } // Calculate cnt2 while (j < m && b[j] == target) { cnt2++; j++; } // Increment the answer by (cnt1 * cnt2) ans += (cnt1 * cnt2); } // Case - 2 else if (a[i] < b[j]) i++; // Case - 3 else j++; } // Return the answer return ans;} // Driver Codepublic static void main(String[] args){ int N = 8, M = 7; int a[] = { 1, 1, 3, 3, 3, 5, 8, 8 }; int b[] = { 1, 3, 3, 4, 5, 5, 5 }; System.out.println(findPairs(a, b, N, M));}} // This code is contributed by Potta Lokesh",
"e": 30985,
"s": 29402,
"text": null
},
{
"code": "# Python3 program for above approach # Function to find number of pairs with# satisfying the given conditiondef findPairs(a, b, n, m): # Initialize ans, i, j to 0 . ans = 0 i = 0 j = 0 # Use the two pointer approach to # calculate the answer . while (i < n and j < m): # Case - 1 if (a[i] == b[j]): # Target denotes a[i] # or b[j] as a[i] = b[j]. # cnt1 denotes the number # of elements in array # a that are equal to target. # cnt2 denotes the number # of elements in array # b that are equal to target target = a[i] cnt1 = 0 cnt2 = 0 # Calculate cnt1 while (i < n and a[i] == target): cnt1 += 1 i += 1 # Calculate cnt2 while (j < m and b[j] == target): cnt2 += 1 j += 1 # Increment the answer by (cnt1 * cnt2) ans += (cnt1 * cnt2) # Case - 2 elif (a[i] < b[j]): i += 1 # Case- 3 else: j += 1 # Return the answer return ans # Driver Codeif __name__ == \"__main__\": N = 8 M = 7 a = [ 1, 1, 3, 3, 3, 5, 8, 8 ] b = [ 1, 3, 3, 4, 5, 5, 5 ] print(findPairs(a, b, N, M)) # This code is contributed by ukasp",
"e": 32357,
"s": 30985,
"text": null
},
{
"code": "// C# program for above approachusing System; class GFG{ // Function to find number of pairs with// satisfying the given conditionstatic int findPairs(int[] a, int[] b, int n, int m){ // Initialize ans, i, j to 0 . int ans = 0, i = 0, j = 0; // Use the two pointer approach to // calculate the answer . while (i < n && j < m) { // Case - 1 if (a[i] == b[j]) { // Target denotes a[i] // or b[j] as a[i] = b[j]. // cnt1 denotes the number // of elements in array // a that are equal to target. // cnt2 denotes the number // of elements in array // b that are equal to target int target = a[i], cnt1 = 0, cnt2 = 0; // Calculate cnt1 while (i < n && a[i] == target) { cnt1++; i++; } // Calculate cnt2 while (j < m && b[j] == target) { cnt2++; j++; } // Increment the answer by (cnt1 * cnt2) ans += (cnt1 * cnt2); } // Case - 2 else if (a[i] < b[j]) i++; // Case - 3 else j++; } // Return the answer return ans;} // Driver Codepublic static void Main(){ int N = 8, M = 7; int []a = { 1, 1, 3, 3, 3, 5, 8, 8 }; int []b = { 1, 3, 3, 4, 5, 5, 5 }; Console.Write(findPairs(a, b, N, M));}} // This code is contributed by Samim Hossain Mondal.",
"e": 33925,
"s": 32357,
"text": null
},
{
"code": "<script>// Javascript Program for above approach // Function to find number of pairs with// satisfying the given conditionfunction findPairs(a, b, n, m){ // Initialize ans, i, j to 0 . let ans = 0, i = 0, j = 0; // Use the two pointer approach to // calculate the answer . while (i < n && j < m) { // Case - 1 if (a[i] == b[j]) { // Target denotes a[i] // or b[j] as a[i] = b[j]. // cnt1 denotes the number // of elements in array // a that are equal to target. // cnt2 denotes the number // of elements in array // b that are equal to target let target = a[i], cnt1 = 0, cnt2 = 0; // Calculate cnt1 while (i < n && a[i] == target) { cnt1++; i++; } // Calculate cnt2 while (j < m && b[j] == target) { cnt2++; j++; } // Increment the answer by (cnt1 * cnt2) ans += (cnt1 * cnt2); } // Case - 2 else if (a[i] < b[j]) i++; // Case - 3 else j++; } // Return the answer return ans;} // Driver Codelet N = 8, M = 7;let a = [ 1, 1, 3, 3, 3, 5, 8, 8 ];let b = [ 1, 3, 3, 4, 5, 5, 5 ]; document.write(findPairs(a, b, N, M)); // This code is contributed by saurabh_jaiswal.</script>",
"e": 35352,
"s": 33925,
"text": null
},
{
"code": null,
"e": 35355,
"s": 35352,
"text": "11"
},
{
"code": null,
"e": 35402,
"s": 35355,
"text": "Time Complexity: O(N + M)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 35416,
"s": 35402,
"text": "lokeshpotta20"
},
{
"code": null,
"e": 35426,
"s": 35416,
"text": "samim2000"
},
{
"code": null,
"e": 35432,
"s": 35426,
"text": "ukasp"
},
{
"code": null,
"e": 35449,
"s": 35432,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 35471,
"s": 35449,
"text": "two-pointer-algorithm"
},
{
"code": null,
"e": 35478,
"s": 35471,
"text": "Arrays"
},
{
"code": null,
"e": 35492,
"s": 35478,
"text": "Combinatorial"
},
{
"code": null,
"e": 35505,
"s": 35492,
"text": "Mathematical"
},
{
"code": null,
"e": 35513,
"s": 35505,
"text": "Sorting"
},
{
"code": null,
"e": 35535,
"s": 35513,
"text": "two-pointer-algorithm"
},
{
"code": null,
"e": 35542,
"s": 35535,
"text": "Arrays"
},
{
"code": null,
"e": 35555,
"s": 35542,
"text": "Mathematical"
},
{
"code": null,
"e": 35563,
"s": 35555,
"text": "Sorting"
},
{
"code": null,
"e": 35577,
"s": 35563,
"text": "Combinatorial"
},
{
"code": null,
"e": 35675,
"s": 35577,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35702,
"s": 35675,
"text": "Count pairs with given sum"
},
{
"code": null,
"e": 35733,
"s": 35702,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 35758,
"s": 35733,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 35796,
"s": 35758,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 35817,
"s": 35796,
"text": "Next Greater Element"
},
{
"code": null,
"e": 35877,
"s": 35817,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 35915,
"s": 35877,
"text": "Permutation and Combination in Python"
},
{
"code": null,
"e": 35992,
"s": 35915,
"text": "itertools.combinations() module in Python to print all possible combinations"
},
{
"code": null,
"e": 36010,
"s": 35992,
"text": "Combinational Sum"
}
] |
Selecting only numeric or string columns names from PySpark DataFrame - GeeksforGeeks | 30 Apr, 2021
In this article, we will discuss how to select only numeric or string column names from a Spark DataFrame.
createDataFrame: This method is used to create a spark DataFrame.
isinstance: This is a Python function used to check if the specified object is of the specified type.
dtypes: It returns a list of tuple (columnNane,type). The returned list contains all columns present in DataFrame with their data types.
schema.fields: It is used to access DataFrame fields metadata.
Method #1:
In this method, dtypes function is used to get a list of tuple (columnNane, type).
Python3
from pyspark.sql import Rowfrom datetime import datefrom pyspark.sql import SparkSession spark = SparkSession.builder.getOrCreate() # Creating dataframe from list of Rowdf = spark.createDataFrame([ Row(a=1, b='string1', c=date(2021, 1, 1)), Row(a=2, b='string2', c=date(2021, 2, 1)), Row(a=4, b='string3', c=date(2021, 3, 1))]) # Printing DataFrame structureprint("DataFrame structure:", df) # Getting list of columns and printing# resultdt = df.dtypesprint("dtypes result:", dt) # Getting list of columns having type# string or bigint# This statement will loop over all the # tuples present in dt list# item[0] will contain column name and# item[1] will contain column typecolumnList = [item[0] for item in dt if item[1].startswith( 'string') or item[1].startswith('bigint')]print("Result: ", columnList)
Output:
DataFrame structure: DataFrame[a: bigint, b: string, c: date]
dtypes result: [('a', 'bigint'), ('b', 'string'), ('c', 'date')]
Result: ['a', 'b']
Method #2:
In this method schema.fields is used to get fields metadata then column data type is extracted from metadata and compared with the desired data type.
Python3
from pyspark.sql.types import StringType, LongTypefrom pyspark.sql import Rowfrom datetime import datefrom pyspark.sql import SparkSession # Initializing spark sessionspark = SparkSession.builder.getOrCreate() # Creating dataframe from list of Rowdf = spark.createDataFrame([ Row(a=1, b='string1', c=date(2021, 1, 1)), Row(a=2, b='string2', c=date(2021, 2, 1)), Row(a=4, b='string3', c=date(2021, 3, 1))]) # Printing DataFrame structureprint("DataFrame structure:", df) # Getting and printing metadatameta = df.schema.fieldsprint("Metadata: ", meta) # Getting list of columns having type # string or int# This statement will loop over all the fields# field.name will return column name and# field.dataType will return column typecolumnList = [field.name for field in df.schema.fields if isinstance( field.dataType, StringType) or isinstance(field.dataType, LongType)]print("Result: ", columnList)
Output:
DataFrame structure: DataFrame[a: bigint, b: string, c: date]
Metadata: [StructField(a,LongType,true), StructField(b,StringType,true), StructField(c,DateType,true)]
Result: [‘a’, ‘b’]
Picked
Python-Pyspark
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n30 Apr, 2021"
},
{
"code": null,
"e": 25644,
"s": 25537,
"text": "In this article, we will discuss how to select only numeric or string column names from a Spark DataFrame."
},
{
"code": null,
"e": 25710,
"s": 25644,
"text": "createDataFrame: This method is used to create a spark DataFrame."
},
{
"code": null,
"e": 25812,
"s": 25710,
"text": "isinstance: This is a Python function used to check if the specified object is of the specified type."
},
{
"code": null,
"e": 25949,
"s": 25812,
"text": "dtypes: It returns a list of tuple (columnNane,type). The returned list contains all columns present in DataFrame with their data types."
},
{
"code": null,
"e": 26012,
"s": 25949,
"text": "schema.fields: It is used to access DataFrame fields metadata."
},
{
"code": null,
"e": 26024,
"s": 26012,
"text": "Method #1: "
},
{
"code": null,
"e": 26107,
"s": 26024,
"text": "In this method, dtypes function is used to get a list of tuple (columnNane, type)."
},
{
"code": null,
"e": 26115,
"s": 26107,
"text": "Python3"
},
{
"code": "from pyspark.sql import Rowfrom datetime import datefrom pyspark.sql import SparkSession spark = SparkSession.builder.getOrCreate() # Creating dataframe from list of Rowdf = spark.createDataFrame([ Row(a=1, b='string1', c=date(2021, 1, 1)), Row(a=2, b='string2', c=date(2021, 2, 1)), Row(a=4, b='string3', c=date(2021, 3, 1))]) # Printing DataFrame structureprint(\"DataFrame structure:\", df) # Getting list of columns and printing# resultdt = df.dtypesprint(\"dtypes result:\", dt) # Getting list of columns having type# string or bigint# This statement will loop over all the # tuples present in dt list# item[0] will contain column name and# item[1] will contain column typecolumnList = [item[0] for item in dt if item[1].startswith( 'string') or item[1].startswith('bigint')]print(\"Result: \", columnList)",
"e": 26940,
"s": 26115,
"text": null
},
{
"code": null,
"e": 26948,
"s": 26940,
"text": "Output:"
},
{
"code": null,
"e": 27095,
"s": 26948,
"text": "DataFrame structure: DataFrame[a: bigint, b: string, c: date]\ndtypes result: [('a', 'bigint'), ('b', 'string'), ('c', 'date')]\nResult: ['a', 'b']"
},
{
"code": null,
"e": 27107,
"s": 27095,
"text": "Method #2: "
},
{
"code": null,
"e": 27257,
"s": 27107,
"text": "In this method schema.fields is used to get fields metadata then column data type is extracted from metadata and compared with the desired data type."
},
{
"code": null,
"e": 27265,
"s": 27257,
"text": "Python3"
},
{
"code": "from pyspark.sql.types import StringType, LongTypefrom pyspark.sql import Rowfrom datetime import datefrom pyspark.sql import SparkSession # Initializing spark sessionspark = SparkSession.builder.getOrCreate() # Creating dataframe from list of Rowdf = spark.createDataFrame([ Row(a=1, b='string1', c=date(2021, 1, 1)), Row(a=2, b='string2', c=date(2021, 2, 1)), Row(a=4, b='string3', c=date(2021, 3, 1))]) # Printing DataFrame structureprint(\"DataFrame structure:\", df) # Getting and printing metadatameta = df.schema.fieldsprint(\"Metadata: \", meta) # Getting list of columns having type # string or int# This statement will loop over all the fields# field.name will return column name and# field.dataType will return column typecolumnList = [field.name for field in df.schema.fields if isinstance( field.dataType, StringType) or isinstance(field.dataType, LongType)]print(\"Result: \", columnList)",
"e": 28181,
"s": 27265,
"text": null
},
{
"code": null,
"e": 28189,
"s": 28181,
"text": "Output:"
},
{
"code": null,
"e": 28251,
"s": 28189,
"text": "DataFrame structure: DataFrame[a: bigint, b: string, c: date]"
},
{
"code": null,
"e": 28355,
"s": 28251,
"text": "Metadata: [StructField(a,LongType,true), StructField(b,StringType,true), StructField(c,DateType,true)]"
},
{
"code": null,
"e": 28375,
"s": 28355,
"text": "Result: [‘a’, ‘b’]"
},
{
"code": null,
"e": 28382,
"s": 28375,
"text": "Picked"
},
{
"code": null,
"e": 28397,
"s": 28382,
"text": "Python-Pyspark"
},
{
"code": null,
"e": 28404,
"s": 28397,
"text": "Python"
},
{
"code": null,
"e": 28502,
"s": 28404,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28534,
"s": 28502,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28576,
"s": 28534,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28618,
"s": 28576,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28645,
"s": 28618,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 28701,
"s": 28645,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28723,
"s": 28701,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28762,
"s": 28723,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 28793,
"s": 28762,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 28822,
"s": 28793,
"text": "Create a directory in Python"
}
] |
JavaScript | padStart() Method - GeeksforGeeks | 07 Nov, 2019
The padStart() method in JavaScript is used to pad a string with another string until it reaches the given length. The padding is applied from the left end of the string.
Syntax:
string.padStart(targetLength, padString)
Parameters: This method accepts two parameters as mentioned above and described below:
targetLength: It is the length of the final string once the original string has been padded. If the value is less than the original string length, then the original string is returned.
padString: It is the string that is to be padded with the original string. If this value is too long to be within the targetLength, it truncated from the end. The default used string is the space character (” “).
Return Value: It returns the final string that is padded with the given string to the given length.
Example 1: This example uses padStart() method to pad strings into another string.
<!DOCTYPE html><html> <head> <title> JavaScript | padStart() method </title></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b>JavaScript | padStart() method</b> <p>Output for "Hello123" with "$": <span class="output"></span> </p> <p>Output for "Geeks" with "XX": <span class="output_2"></span> </p> <button onclick="padStrings()"> Pad Strings </button> <script type="text/javascript"> function padStrings() { exString = "Hello123"; exString2 = "Geeks"; prepended_out = exString.padStart(10, "$"); prepended_out2 = exString2.padStart(10, "XX"); document.querySelector('.output').textContent = prepended_out; document.querySelector('.output_2').textContent = prepended_out2; } </script></body> </html>
Output:
Before clicking the button:
After clicking the button:
Example 2: This example uses padStart() method to pad numbers into the another number.
<!DOCTYPE html><html> <head> <title> JavaScript | padStart() method </title></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b>JavaScript | padStart() method</b> <p>Output for "999" with "0": <span class="output"></span> </p> <p>Output for "123" with "**": <span class="output_2"></span> </p> <button onclick="padNumbers()"> Pad Numbers </button> <script type="text/javascript"> function padNumbers() { exNumber = 999; exNumber2 = 123; prepended_out = String(exNumber).padStart(5, "0"); prepended_out2 = String(exNumber2).padStart(5, "**"); document.querySelector('.output').textContent = prepended_out; document.querySelector('.output_2').textContent = prepended_out2; } </script></body> </html>
Output:
Before clicking the button:
After clicking the button:
Supported Browsers: The browser supported by padStart() method are listed below:
Google Chrome 57
Firefox 48
Edge 15
Safari 10
Opera 44
javascript-functions
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Difference Between PUT and PATCH Request
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": 26131,
"s": 26103,
"text": "\n07 Nov, 2019"
},
{
"code": null,
"e": 26302,
"s": 26131,
"text": "The padStart() method in JavaScript is used to pad a string with another string until it reaches the given length. The padding is applied from the left end of the string."
},
{
"code": null,
"e": 26310,
"s": 26302,
"text": "Syntax:"
},
{
"code": null,
"e": 26351,
"s": 26310,
"text": "string.padStart(targetLength, padString)"
},
{
"code": null,
"e": 26438,
"s": 26351,
"text": "Parameters: This method accepts two parameters as mentioned above and described below:"
},
{
"code": null,
"e": 26623,
"s": 26438,
"text": "targetLength: It is the length of the final string once the original string has been padded. If the value is less than the original string length, then the original string is returned."
},
{
"code": null,
"e": 26836,
"s": 26623,
"text": "padString: It is the string that is to be padded with the original string. If this value is too long to be within the targetLength, it truncated from the end. The default used string is the space character (” “)."
},
{
"code": null,
"e": 26936,
"s": 26836,
"text": "Return Value: It returns the final string that is padded with the given string to the given length."
},
{
"code": null,
"e": 27019,
"s": 26936,
"text": "Example 1: This example uses padStart() method to pad strings into another string."
},
{
"code": "<!DOCTYPE html><html> <head> <title> JavaScript | padStart() method </title></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b>JavaScript | padStart() method</b> <p>Output for \"Hello123\" with \"$\": <span class=\"output\"></span> </p> <p>Output for \"Geeks\" with \"XX\": <span class=\"output_2\"></span> </p> <button onclick=\"padStrings()\"> Pad Strings </button> <script type=\"text/javascript\"> function padStrings() { exString = \"Hello123\"; exString2 = \"Geeks\"; prepended_out = exString.padStart(10, \"$\"); prepended_out2 = exString2.padStart(10, \"XX\"); document.querySelector('.output').textContent = prepended_out; document.querySelector('.output_2').textContent = prepended_out2; } </script></body> </html>",
"e": 28010,
"s": 27019,
"text": null
},
{
"code": null,
"e": 28018,
"s": 28010,
"text": "Output:"
},
{
"code": null,
"e": 28046,
"s": 28018,
"text": "Before clicking the button:"
},
{
"code": null,
"e": 28073,
"s": 28046,
"text": "After clicking the button:"
},
{
"code": null,
"e": 28160,
"s": 28073,
"text": "Example 2: This example uses padStart() method to pad numbers into the another number."
},
{
"code": "<!DOCTYPE html><html> <head> <title> JavaScript | padStart() method </title></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b>JavaScript | padStart() method</b> <p>Output for \"999\" with \"0\": <span class=\"output\"></span> </p> <p>Output for \"123\" with \"**\": <span class=\"output_2\"></span> </p> <button onclick=\"padNumbers()\"> Pad Numbers </button> <script type=\"text/javascript\"> function padNumbers() { exNumber = 999; exNumber2 = 123; prepended_out = String(exNumber).padStart(5, \"0\"); prepended_out2 = String(exNumber2).padStart(5, \"**\"); document.querySelector('.output').textContent = prepended_out; document.querySelector('.output_2').textContent = prepended_out2; } </script></body> </html>",
"e": 29131,
"s": 28160,
"text": null
},
{
"code": null,
"e": 29139,
"s": 29131,
"text": "Output:"
},
{
"code": null,
"e": 29167,
"s": 29139,
"text": "Before clicking the button:"
},
{
"code": null,
"e": 29194,
"s": 29167,
"text": "After clicking the button:"
},
{
"code": null,
"e": 29275,
"s": 29194,
"text": "Supported Browsers: The browser supported by padStart() method are listed below:"
},
{
"code": null,
"e": 29292,
"s": 29275,
"text": "Google Chrome 57"
},
{
"code": null,
"e": 29303,
"s": 29292,
"text": "Firefox 48"
},
{
"code": null,
"e": 29311,
"s": 29303,
"text": "Edge 15"
},
{
"code": null,
"e": 29321,
"s": 29311,
"text": "Safari 10"
},
{
"code": null,
"e": 29330,
"s": 29321,
"text": "Opera 44"
},
{
"code": null,
"e": 29351,
"s": 29330,
"text": "javascript-functions"
},
{
"code": null,
"e": 29362,
"s": 29351,
"text": "JavaScript"
},
{
"code": null,
"e": 29379,
"s": 29362,
"text": "Web Technologies"
},
{
"code": null,
"e": 29477,
"s": 29379,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29517,
"s": 29477,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29562,
"s": 29517,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29623,
"s": 29562,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 29695,
"s": 29623,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 29736,
"s": 29695,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 29776,
"s": 29736,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29809,
"s": 29776,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 29854,
"s": 29809,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29897,
"s": 29854,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Sum of all the factors of a number - GeeksforGeeks | CoursesFor Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore MoreFor StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore MoreSchool CoursesSchool GuidePython ProgrammingLearn To Make AppsExplore moreAll Courses
For Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More
LIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore More
DSA Live Classes
System Design
Java Backend Development
Full Stack LIVE
Explore More
Self-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More
DSA- Self Paced
SDE Theory
Must-Do Coding Questions
Explore More
For StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More
LIVECompetitive ProgrammingData Structures with C++Data ScienceExplore More
Competitive Programming
Data Structures with C++
Data Science
Explore More
Self-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More
DSA- Self Paced
CIP
JAVA / Python / C++
Explore More
School CoursesSchool GuidePython ProgrammingLearn To Make AppsExplore more
School Guide
Python Programming
Learn To Make Apps
Explore more
All Courses
TutorialsAlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll AlgorithmsData StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data StructuresInterview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice QuizzesLanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlinML & Data ScienceMachine LearningData ScienceCS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware EngineeringGATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CSWeb TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHPSoftware DesignsSoftware Design PatternsSystem Design TutorialSchool LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesCS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved PapersStudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsStudent ChapterGeek on the TopInternshipCareers
AlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll Algorithms
Analysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity Question
Asymptotic Analysis
Worst, Average and Best Cases
Asymptotic Notations
Little o and little omega notations
Lower and Upper Bound Theory
Analysis of Loops
Solving Recurrences
Amortized Analysis
What does 'Space Complexity' mean ?
Pseudo-polynomial Algorithms
Polynomial Time Approximation Scheme
A Time Complexity Question
Searching Algorithms
Sorting Algorithms
Graph Algorithms
Pattern Searching
Geometric Algorithms
Mathematical
Bitwise Algorithms
Randomized Algorithms
Greedy Algorithms
Dynamic Programming
Divide and Conquer
Backtracking
Branch and Bound
All Algorithms
Data StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data Structures
Arrays
Linked List
Stack
Queue
Binary Tree
Binary Search Tree
Heap
Hashing
Graph
Advanced Data Structure
Matrix
Strings
All Data Structures
Interview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice Quizzes
Company Preparation
Top Topics
Practice Company Questions
Interview Experiences
Experienced Interviews
Internship Interviews
Competititve Programming
Design Patterns
System Design Tutorial
Multiple Choice Quizzes
LanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlin
C
C++
Java
Python
C#
JavaScript
jQuery
SQL
PHP
Scala
Perl
Go Language
HTML
CSS
Kotlin
ML & Data ScienceMachine LearningData Science
Machine Learning
Data Science
CS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware Engineering
Mathematics
Operating System
DBMS
Computer Networks
Computer Organization and Architecture
Theory of Computation
Compiler Design
Digital Logic
Software Engineering
GATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CS
GATE Computer Science Notes
Last Minute Notes
GATE CS Solved Papers
GATE CS Original Papers and Official Keys
GATE 2021 Dates
GATE CS 2021 Syllabus
Important Topics for GATE CS
Web TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHP
HTML
CSS
JavaScript
AngularJS
ReactJS
NodeJS
Bootstrap
jQuery
PHP
Software DesignsSoftware Design PatternsSystem Design Tutorial
Software Design Patterns
System Design Tutorial
School LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes
School Programming
MathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculus
Number System
Algebra
Trigonometry
Statistics
Probability
Geometry
Mensuration
Calculus
Maths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 Notes
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
Class 12 Notes
NCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
RD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
Physics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
CS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers
ISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer Exam
ISRO CS Original Papers and Official Keys
ISRO CS Solved Papers
ISRO CS Syllabus for Scientist/Engineer Exam
UGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers
UGC NET CS Notes Paper II
UGC NET CS Notes Paper III
UGC NET CS Solved Papers
StudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsStudent ChapterGeek on the TopInternshipCareers
Campus Ambassador Program
School Ambassador Program
Project
Geek of the Month
Campus Geek of the Month
Placement Course
Competititve Programming
Testimonials
Student Chapter
Geek on the Top
Internship
Careers
JobsApply for JobsPost a JobJOB-A-THON
Apply for Jobs
Post a Job
JOB-A-THON
PracticeAll DSA ProblemsProblem of the DayInterview Series: Weekly ContestsBi-Wizard Coding: School ContestsContests and EventsPractice SDE SheetCurated DSA ListsTop 50 Array ProblemsTop 50 String ProblemsTop 50 Tree ProblemsTop 50 Graph ProblemsTop 50 DP Problems
All DSA Problems
Problem of the Day
Interview Series: Weekly Contests
Bi-Wizard Coding: School Contests
Contests and Events
Practice SDE Sheet
Curated DSA ListsTop 50 Array ProblemsTop 50 String ProblemsTop 50 Tree ProblemsTop 50 Graph ProblemsTop 50 DP Problems
Top 50 Array Problems
Top 50 String Problems
Top 50 Tree Problems
Top 50 Graph Problems
Top 50 DP Problems
WriteCome write articles for us and get featuredPracticeLearn and code with the best industry expertsPremiumGet access to ad-free content, doubt assistance and more!JobsCome and find your dream job with usGeeks DigestQuizzesGeeks CampusGblog ArticlesIDECampus Mantri
Geeks Digest
Quizzes
Geeks Campus
Gblog Articles
IDE
Campus Mantri
Sign In
Sign In
Home
Saved Videos
Courses
For Working Professionals
LIVE
DSA Live Classes
System Design
Java Backend Development
Full Stack LIVE
Explore More
Self-Paced
DSA- Self Paced
SDE Theory
Must-Do Coding Questions
Explore More
For Students
LIVE
Competitive Programming
Data Structures with C++
Data Science
Explore More
Self-Paced
DSA- Self Paced
CIP
JAVA / Python / C++
Explore More
School Courses
School Guide
Python Programming
Learn To Make Apps
Explore more
Algorithms
Searching Algorithms
Sorting Algorithms
Graph Algorithms
Pattern Searching
Geometric Algorithms
Mathematical
Bitwise Algorithms
Randomized Algorithms
Greedy Algorithms
Dynamic Programming
Divide and Conquer
Backtracking
Branch and Bound
All Algorithms
Analysis of Algorithms
Asymptotic Analysis
Worst, Average and Best Cases
Asymptotic Notations
Little o and little omega notations
Lower and Upper Bound Theory
Analysis of Loops
Solving Recurrences
Amortized Analysis
What does 'Space Complexity' mean ?
Pseudo-polynomial Algorithms
Polynomial Time Approximation Scheme
A Time Complexity Question
Data Structures
Arrays
Linked List
Stack
Queue
Binary Tree
Binary Search Tree
Heap
Hashing
Graph
Advanced Data Structure
Matrix
Strings
All Data Structures
Interview Corner
Company Preparation
Top Topics
Practice Company Questions
Interview Experiences
Experienced Interviews
Internship Interviews
Competititve Programming
Design Patterns
System Design Tutorial
Multiple Choice Quizzes
Languages
C
C++
Java
Python
C#
JavaScript
jQuery
SQL
PHP
Scala
Perl
Go Language
HTML
CSS
Kotlin
ML & Data Science
Machine Learning
Data Science
CS Subjects
Mathematics
Operating System
DBMS
Computer Networks
Computer Organization and Architecture
Theory of Computation
Compiler Design
Digital Logic
Software Engineering
GATE
GATE Computer Science Notes
Last Minute Notes
GATE CS Solved Papers
GATE CS Original Papers and Official Keys
GATE 2021 Dates
GATE CS 2021 Syllabus
Important Topics for GATE CS
Web Technologies
HTML
CSS
JavaScript
AngularJS
ReactJS
NodeJS
Bootstrap
jQuery
PHP
Software Designs
Software Design Patterns
System Design Tutorial
School Learning
School Programming
Mathematics
Number System
Algebra
Trigonometry
Statistics
Probability
Geometry
Mensuration
Calculus
Maths Notes (Class 8-12)
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
Class 12 Notes
NCERT Solutions
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
RD Sharma Solutions
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
Physics Notes (Class 8-11)
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
CS Exams/PSUs
ISRO
ISRO CS Original Papers and Official Keys
ISRO CS Solved Papers
ISRO CS Syllabus for Scientist/Engineer Exam
UGC NET
UGC NET CS Notes Paper II
UGC NET CS Notes Paper III
UGC NET CS Solved Papers
Student
Campus Ambassador Program
School Ambassador Program
Project
Geek of the Month
Campus Geek of the Month
Placement Course
Competititve Programming
Testimonials
Student Chapter
Geek on the Top
Internship
Careers
Curated DSA Lists
Top 50 Array Problems
Top 50 String Problems
Top 50 Tree Problems
Top 50 Graph Problems
Top 50 DP Problems
Tutorials
Jobs
Apply for Jobs
Post a Job
JOB-A-THON
Practice
All DSA Problems
Problem of the Day
Interview Series: Weekly Contests
Bi-Wizard Coding: School Contests
Contests and Events
Practice SDE Sheet
For Working Professionals
LIVE
DSA Live Classes
System Design
Java Backend Development
Full Stack LIVE
Explore More
DSA Live Classes
System Design
Java Backend Development
Full Stack LIVE
Explore More
Self-Paced
DSA- Self Paced
SDE Theory
Must-Do Coding Questions
Explore More
DSA- Self Paced
SDE Theory
Must-Do Coding Questions
Explore More
For Students
LIVE
Competitive Programming
Data Structures with C++
Data Science
Explore More
Competitive Programming
Data Structures with C++
Data Science
Explore More
Self-Paced
DSA- Self Paced
CIP
JAVA / Python / C++
Explore More
DSA- Self Paced
CIP
JAVA / Python / C++
Explore More
School Courses
School Guide
Python Programming
Learn To Make Apps
Explore more
School Guide
Python Programming
Learn To Make Apps
Explore more
Algorithms
Searching Algorithms
Sorting Algorithms
Graph Algorithms
Pattern Searching
Geometric Algorithms
Mathematical
Bitwise Algorithms
Randomized Algorithms
Greedy Algorithms
Dynamic Programming
Divide and Conquer
Backtracking
Branch and Bound
All Algorithms
Searching Algorithms
Sorting Algorithms
Graph Algorithms
Pattern Searching
Geometric Algorithms
Mathematical
Bitwise Algorithms
Randomized Algorithms
Greedy Algorithms
Dynamic Programming
Divide and Conquer
Backtracking
Branch and Bound
All Algorithms
Analysis of Algorithms
Asymptotic Analysis
Worst, Average and Best Cases
Asymptotic Notations
Little o and little omega notations
Lower and Upper Bound Theory
Analysis of Loops
Solving Recurrences
Amortized Analysis
What does 'Space Complexity' mean ?
Pseudo-polynomial Algorithms
Polynomial Time Approximation Scheme
A Time Complexity Question
Asymptotic Analysis
Worst, Average and Best Cases
Asymptotic Notations
Little o and little omega notations
Lower and Upper Bound Theory
Analysis of Loops
Solving Recurrences
Amortized Analysis
What does 'Space Complexity' mean ?
Pseudo-polynomial Algorithms
Polynomial Time Approximation Scheme
A Time Complexity Question
Data Structures
Arrays
Linked List
Stack
Queue
Binary Tree
Binary Search Tree
Heap
Hashing
Graph
Advanced Data Structure
Matrix
Strings
All Data Structures
Arrays
Linked List
Stack
Queue
Binary Tree
Binary Search Tree
Heap
Hashing
Graph
Advanced Data Structure
Matrix
Strings
All Data Structures
Interview Corner
Company Preparation
Top Topics
Practice Company Questions
Interview Experiences
Experienced Interviews
Internship Interviews
Competititve Programming
Design Patterns
System Design Tutorial
Multiple Choice Quizzes
Company Preparation
Top Topics
Practice Company Questions
Interview Experiences
Experienced Interviews
Internship Interviews
Competititve Programming
Design Patterns
System Design Tutorial
Multiple Choice Quizzes
Languages
C
C++
Java
Python
C#
JavaScript
jQuery
SQL
PHP
Scala
Perl
Go Language
HTML
CSS
Kotlin
C
C++
Java
Python
C#
JavaScript
jQuery
SQL
PHP
Scala
Perl
Go Language
HTML
CSS
Kotlin
ML & Data Science
Machine Learning
Data Science
Machine Learning
Data Science
CS Subjects
Mathematics
Operating System
DBMS
Computer Networks
Computer Organization and Architecture
Theory of Computation
Compiler Design
Digital Logic
Software Engineering
Mathematics
Operating System
DBMS
Computer Networks
Computer Organization and Architecture
Theory of Computation
Compiler Design
Digital Logic
Software Engineering
GATE
GATE Computer Science Notes
Last Minute Notes
GATE CS Solved Papers
GATE CS Original Papers and Official Keys
GATE 2021 Dates
GATE CS 2021 Syllabus
Important Topics for GATE CS
GATE Computer Science Notes
Last Minute Notes
GATE CS Solved Papers
GATE CS Original Papers and Official Keys
GATE 2021 Dates
GATE CS 2021 Syllabus
Important Topics for GATE CS
Web Technologies
HTML
CSS
JavaScript
AngularJS
ReactJS
NodeJS
Bootstrap
jQuery
PHP
HTML
CSS
JavaScript
AngularJS
ReactJS
NodeJS
Bootstrap
jQuery
PHP
Software Designs
Software Design Patterns
System Design Tutorial
Software Design Patterns
System Design Tutorial
School Learning
School Programming
School Programming
Mathematics
Number System
Algebra
Trigonometry
Statistics
Probability
Geometry
Mensuration
Calculus
Number System
Algebra
Trigonometry
Statistics
Probability
Geometry
Mensuration
Calculus
Maths Notes (Class 8-12)
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
Class 12 Notes
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
Class 12 Notes
NCERT Solutions
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
RD Sharma Solutions
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
Physics Notes (Class 8-11)
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
CS Exams/PSUs
ISRO
ISRO CS Original Papers and Official Keys
ISRO CS Solved Papers
ISRO CS Syllabus for Scientist/Engineer Exam
ISRO CS Original Papers and Official Keys
ISRO CS Solved Papers
ISRO CS Syllabus for Scientist/Engineer Exam
UGC NET
UGC NET CS Notes Paper II
UGC NET CS Notes Paper III
UGC NET CS Solved Papers
UGC NET CS Notes Paper II
UGC NET CS Notes Paper III
UGC NET CS Solved Papers
Student
Campus Ambassador Program
School Ambassador Program
Project
Geek of the Month
Campus Geek of the Month
Placement Course
Competititve Programming
Testimonials
Student Chapter
Geek on the Top
Internship
Careers
Campus Ambassador Program
School Ambassador Program
Project
Geek of the Month
Campus Geek of the Month
Placement Course
Competititve Programming
Testimonials
Student Chapter
Geek on the Top
Internship
Careers
Curated DSA Lists
Top 50 Array Problems
Top 50 String Problems
Top 50 Tree Problems
Top 50 Graph Problems
Top 50 DP Problems
Top 50 Array Problems
Top 50 String Problems
Top 50 Tree Problems
Top 50 Graph Problems
Top 50 DP Problems
Tutorials
Jobs
Apply for Jobs
Post a Job
JOB-A-THON
Apply for Jobs
Post a Job
JOB-A-THON
Practice
All DSA Problems
Problem of the Day
Interview Series: Weekly Contests
Bi-Wizard Coding: School Contests
Contests and Events
Practice SDE Sheet
All DSA Problems
Problem of the Day
Interview Series: Weekly Contests
Bi-Wizard Coding: School Contests
Contests and Events
Practice SDE Sheet
GBlog
Puzzles
What's New ?
Array
Matrix
Strings
Hashing
Linked List
Stack
Queue
Binary Tree
Binary Search Tree
Heap
Graph
Searching
Sorting
Divide & Conquer
Mathematical
Geometric
Bitwise
Greedy
Backtracking
Branch and Bound
Dynamic Programming
Pattern Searching
Randomized
Sum of all the factors of a number
Sum of all proper divisors of a natural number
Sum of all divisors from 1 to n
Find all divisors of a natural number | Set 2
Find all factors of a natural number | Set 1
Count Divisors of n in O(n^1/3)
Total number of divisors for a given number
Write an iterative O(Log y) function for pow(x, y)
Write a program to calculate pow(x,n)
Modular Exponentiation (Power in Modular Arithmetic)
Modular exponentiation (Recursive)
Modular multiplicative inverse
Euclidean algorithms (Basic and Extended)
Program to find GCD or HCF of two numbers
Program to find LCM of two numbers
LCM of given array elements
Finding LCM of more than two (or array) numbers without using GCD
GCD of more than two (or array) numbers
Sieve of Eratosthenes
Sieve of Eratosthenes in 0(n) time complexity
How is the time complexity of Sieve of Eratosthenes is n*log(log(n))?
Segmented Sieve
Segmented Sieve (Print Primes in a Range)
Prime Factorization using Sieve O(log n) for multiple queries
Efficient program to print all prime factors of a given number
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7
Sum of all the factors of a number
Sum of all proper divisors of a natural number
Sum of all divisors from 1 to n
Find all divisors of a natural number | Set 2
Find all factors of a natural number | Set 1
Count Divisors of n in O(n^1/3)
Total number of divisors for a given number
Write an iterative O(Log y) function for pow(x, y)
Write a program to calculate pow(x,n)
Modular Exponentiation (Power in Modular Arithmetic)
Modular exponentiation (Recursive)
Modular multiplicative inverse
Euclidean algorithms (Basic and Extended)
Program to find GCD or HCF of two numbers
Program to find LCM of two numbers
LCM of given array elements
Finding LCM of more than two (or array) numbers without using GCD
GCD of more than two (or array) numbers
Sieve of Eratosthenes
Sieve of Eratosthenes in 0(n) time complexity
How is the time complexity of Sieve of Eratosthenes is n*log(log(n))?
Segmented Sieve
Segmented Sieve (Print Primes in a Range)
Prime Factorization using Sieve O(log n) for multiple queries
Efficient program to print all prime factors of a given number
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7
Difficulty Level :
Medium
Given a number n, the task is to find the sum of all the factors.Examples :
Input : n = 30
Output : 72
Dividers sum 1 + 2 + 3 + 5 + 6 +
10 + 15 + 30 = 72
Input : n = 15
Output : 24
Dividers sum 1 + 3 + 5 + 15 = 24
A simple solution is to traverse through all divisors and add them.
C++
Java
Python3
C#
PHP
Javascript
// Simple C++ program to// find sum of all divisors// of a natural number#include<bits/stdc++.h>using namespace std; // Function to calculate sum of all//divisors of a given numberint divSum(int n){ if(n == 1) return 1; // Sum of divisors int result = 0; // find all divisors which divides 'num' for (int i = 2; i <= sqrt(n); i++) { // if 'i' is divisor of 'n' if (n % i == 0) { // if both divisors are same // then add it once else add // both if (i == (n / i)) result += i; else result += (i + n/i); } } // Add 1 and n to result as above loop // considers proper divisors greater // than 1. return (result + n + 1);} // Driver program to run the caseint main(){ int n = 30; cout << divSum(n); return 0;}
// Simple Java program to// find sum of all divisors// of a natural numberimport java.io.*; class GFG { // Function to calculate sum of all //divisors of a given number static int divSum(int n) { if(n == 1) return 1; // Final result of summation // of divisors int result = 0; // find all divisors which divides 'num' for (int i = 2; i <= Math.sqrt(n); i++) { // if 'i' is divisor of 'n' if (n % i == 0) { // if both divisors are same // then add it once else add // both if (i == (n / i)) result += i; else result += (i + n / i); } } // Add 1 and n to result as above loop // considers proper divisors greater // than 1. return (result + n + 1); } // Driver program to run the case public static void main(String[] args) { int n = 30; System.out.println(divSum(n)); }} // This code is contributed by Prerna Saini.
# Simple Python 3 program to# find sum of all divisors of# a natural numberimport math # Function to calculate sum# of all divisors of given# natural numberdef divSum(n) : if(n == 1): return 1 # Final result of summation # of divisors result = 0 # find all divisors which # divides 'num' for i in range(2,(int)(math.sqrt(n))+1) : # if 'i' is divisor of 'n' if (n % i == 0) : # if both divisors are same # then add it only once # else add both if (i == (n/i)) : result = result + i else : result = result + (i + n//i) # Add 1 and n to result as above # loop considers proper divisors # greater than 1. return (result + n + 1) # Driver program to run the casen = 30print(divSum(n)) # This code is contributed by Nikita Tiwari.
// Simple C# program to// find sum of all divisors// of a natural numberusing System; class GFG { // Function to calculate sum of all //divisors of a given number static int divSum(int n) { if(n == 1) return 1; // Final result of summation // of divisors int result = 0; // find all divisors which divides 'num' for (int i = 2; i <= Math.Sqrt(n); i++) { // if 'i' is divisor of 'n' if (n % i == 0) { // if both divisors are same // then add it once else add // both if (i == (n / i)) result += i; else result += (i + n / i); } } // Add 1 and n to result as above loop // considers proper divisors greater // than 1. return (result + n + 1); } // Driver program to run the case public static void Main() { int n = 30; Console.WriteLine(divSum(n)); }} // This code is contributed by vt_m.
<?php// Find sum of all divisors// of a natural number // Function to calculate sum of all//divisors of a given numberfunction divSum($n){ if($n == 1) return 1; // Sum of divisors $result = 0; // find all divisors // which divides 'num' for ( $i = 2; $i <= sqrt($n); $i++) { // if 'i' is divisor of 'n' if ($n % $i == 0) { // if both divisors are same // then add it once else add // both if ($i == ($n / $i)) $result += $i; else $result += ($i + $n / $i); } } // Add 1 and n to result as // above loop considers proper // divisors greater than 1. return ($result + $n + 1);} // Driver Code$n = 30;echo divSum($n); // This code is contributed by SanjuTomar.?>
<script> // Find sum of all divisors// of a natural number // Function to calculate sum of all//divisors of a given numberfunction divSum(n){ if(n == 1) return 1; // Sum of divisors let result = 0; // find all divisors // which divides 'num' for ( let i = 2; i <= Math.sqrt(n); i++) { // if 'i' is divisor of 'n' if (n % i == 0) { // if both divisors are same // then add it once else add // both if (i == (n / i)) result += i; else result += (i + n / i); } } // Add 1 and n to result as // above loop considers proper // divisors greater than 1. return (result + n + 1);} // Driver Codelet n = 30;document.write(divSum(n)); // This code is contributed by _saurabh_jaiswal.</script>
Output :
72
An efficient solution is to use below formula. Let p1, p2, ... pk be prime factors of n. Let a1, a2, .. ak be highest powers of p1, p2, .. pk respectively that divide n, i.e., we can write n as n = (p1a1)*(p2a2)* ... (pkak).
Sum of divisors = (1 + p1 + p12 ... p1a1) *
(1 + p2 + p22 ... p2a2) *
.............................................
(1 + pk + pk2 ... pkak)
We can notice that individual terms of above
formula are Geometric Progressions (GP). We
can rewrite the formula as.
Sum of divisors = (p1a1+1 - 1)/(p1 -1) *
(p2a2+1 - 1)/(p2 -1) *
..................................
(pkak+1 - 1)/(pk -1)
How does above formula work?
Consider the number 18.
Sum of factors = 1 + 2 + 3 + 6 + 9 + 18
Writing divisors as powers of prime factors.
Sum of factors = (20)(30) + (21)(30) + (2^0)(31) +
(21)(31) + (20)(3^2) + (2^1)(32)
= (20)(30) + (2^0)(31) + (2^0)(32) +
(21)(3^0) + (21)(31) + (21)(32)
= (20)(30 + 31 + 32) +
(21)(30 + 31 + 32)
= (20 + 21)(30 + 31 + 32)
If we take a closer look, we can notice that the
above expression is in the form.
(1 + p1) * (1 + p2 + p22)
Where p1 = 2 and p2 = 3 and 18 = 2132
So the task reduces to finding all prime factors and their powers.
C++
Java
Python3
C#
PHP
Javascript
// Formula based CPP program to// find sum of all divisors of n.#include <bits/stdc++.h>using namespace std; // Returns sum of all factors of n.int sumofFactors(int n){ // Traversing through all prime factors. int res = 1; for (int i = 2; i <= sqrt(n); i++) { int curr_sum = 1; int curr_term = 1; while (n % i == 0) { // THE BELOW STATEMENT MAKES // IT BETTER THAN ABOVE METHOD // AS WE REDUCE VALUE OF n. n = n / i; curr_term *= i; curr_sum += curr_term; } res *= curr_sum; } // This condition is to handle // the case when n is a prime // number greater than 2. if (n >= 2) res *= (1 + n); return res;} // Driver codeint main(){ int n = 30; cout << sumofFactors(n); return 0;}
// Formula based Java program to// find sum of all divisors of n. import java.io.*;import java.math.*;public class GFG{ // Returns sum of all factors of n. static int sumofFactors(int n) { // Traversing through all prime factors. int res = 1; for (int i = 2; i <= Math.sqrt(n); i++) { int curr_sum = 1; int curr_term = 1; while (n % i == 0) { // THE BELOW STATEMENT MAKES // IT BETTER THAN ABOVE METHOD // AS WE REDUCE VALUE OF n. n = n / i; curr_term *= i; curr_sum += curr_term; } res *= curr_sum; } // This condition is to handle // the case when n is a prime // number greater than 2 if (n > 2) res *= (1 + n); return res; } // Driver code public static void main(String args[]) { int n = 30; System.out.println(sumofFactors(n)); }} /*This code is contributed by Nikita Tiwari.*/
# Formula based Python3 code to find# sum of all divisors of n.import math as m # Returns sum of all factors of n.def sumofFactors(n): # Traversing through all # prime factors res = 1 for i in range(2, int(m.sqrt(n) + 1)): curr_sum = 1 curr_term = 1 while n % i == 0: n = n / i; curr_term = curr_term * i; curr_sum += curr_term; res = res * curr_sum # This condition is to handle the # case when n is a prime number # greater than 2 if n > 2: res = res * (1 + n) return res; # driver code sum = sumofFactors(30)print ("Sum of all divisors is: ",sum) # This code is contributed by Saloni Gupta
// Formula based Java program to// find sum of all divisors of n.using System; public class GFG { // Returns sum of all factors of n. static int sumofFactors(int n) { // Traversing through all prime factors. int res = 1; for (int i = 2; i <= Math.Sqrt(n); i++) { int curr_sum = 1; int curr_term = 1; while (n % i == 0) { // THE BELOW STATEMENT MAKES // IT BETTER THAN ABOVE METHOD // AS WE REDUCE VALUE OF n. n = n / i; curr_term *= i; curr_sum += curr_term; } res *= curr_sum; } // This condition is to handle // the case when n is a prime // number greater than 2 if (n > 2) res *= (1 + n); return res; } // Driver code public static void Main() { int n = 30; Console.WriteLine(sumofFactors(n)); }} /*This code is contributed by vt_m.*/
<?php// Formula based PHP program to// find sum of all divisors of n. // Returns sum of all factors of n.function sumofFactors($n){ // Traversing through // all prime factors. $res = 1; for ($i = 2; $i <= sqrt($n); $i++) { $curr_sum = 1; $curr_term = 1; while ($n % $i == 0) { // THE BELOW STATEMENT MAKES // IT BETTER THAN ABOVE METHOD // AS WE REDUCE VALUE OF n. $n = $n / $i; $curr_term *= $i; $curr_sum += $curr_term; } $res *= $curr_sum; } // This condition is to handle // the case when n is a prime // number greater than 2 if ($n > 2) $res *= (1 + $n); return $res;} // Driver Code$n = 30;echo sumofFactors($n); // This code is contributed by Anuj_67.?>
<script> // Formula based Javascript program to// find sum of all divisors of n. // Returns sum of all factors of n.function sumofFactors(n){ // Traversing through // all prime factors. let res = 1; for (let i = 2; i <= Math.sqrt(n); i++) { let curr_sum = 1; let curr_term = 1; while (n % i == 0) { // THE BELOW STATEMENT MAKES // IT BETTER THAN ABOVE METHOD // AS WE REDUCE VALUE OF n. n = n / i; curr_term *= i; curr_sum += curr_term; } res *= curr_sum; } // This condition is to handle // the case when n is a prime // number greater than 2 if (n > 2) res *= (1 + n); return res;} // Driver Codelet n = 30;document.write(sumofFactors(n)); // This code is contributed by _saurabh_jaiswal.</script>
Output :
72
Further Optimization. If there are multiple queries, we can use Sieve to find prime factors and their powers.References: https://www.math.upenn.edu/~deturck/m170/wk3/lecture/sumdiv.html http://mathforum.org/library/drmath/view/71550.html
SanjuTomar
vt_m
arupjyoti_dutta
spp____
_saurabh_jaiswal
divisors
number-theory
prime-factor
Mathematical
number-theory
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Modulo Operator (%) in C/C++ with Examples
Prime Numbers
Print all possible combinations of r elements in a given array of size n
Program for Decimal to Binary Conversion
The Knight's tour problem | Backtracking-1
Operators in C / C++
Program for factorial of a number
Find minimum number of coins that make a given value
Program to find sum of elements in a given array | [
{
"code": null,
"e": 419,
"s": 0,
"text": "CoursesFor Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore MoreFor StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore MoreSchool CoursesSchool GuidePython ProgrammingLearn To Make AppsExplore moreAll Courses"
},
{
"code": null,
"e": 600,
"s": 419,
"text": "For Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More"
},
{
"code": null,
"e": 685,
"s": 600,
"text": "LIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore More"
},
{
"code": null,
"e": 702,
"s": 685,
"text": "DSA Live Classes"
},
{
"code": null,
"e": 716,
"s": 702,
"text": "System Design"
},
{
"code": null,
"e": 741,
"s": 716,
"text": "Java Backend Development"
},
{
"code": null,
"e": 757,
"s": 741,
"text": "Full Stack LIVE"
},
{
"code": null,
"e": 770,
"s": 757,
"text": "Explore More"
},
{
"code": null,
"e": 842,
"s": 770,
"text": "Self-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More"
},
{
"code": null,
"e": 858,
"s": 842,
"text": "DSA- Self Paced"
},
{
"code": null,
"e": 869,
"s": 858,
"text": "SDE Theory"
},
{
"code": null,
"e": 894,
"s": 869,
"text": "Must-Do Coding Questions"
},
{
"code": null,
"e": 907,
"s": 894,
"text": "Explore More"
},
{
"code": null,
"e": 1054,
"s": 907,
"text": "For StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More"
},
{
"code": null,
"e": 1130,
"s": 1054,
"text": "LIVECompetitive ProgrammingData Structures with C++Data ScienceExplore More"
},
{
"code": null,
"e": 1154,
"s": 1130,
"text": "Competitive Programming"
},
{
"code": null,
"e": 1179,
"s": 1154,
"text": "Data Structures with C++"
},
{
"code": null,
"e": 1192,
"s": 1179,
"text": "Data Science"
},
{
"code": null,
"e": 1205,
"s": 1192,
"text": "Explore More"
},
{
"code": null,
"e": 1265,
"s": 1205,
"text": "Self-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More"
},
{
"code": null,
"e": 1281,
"s": 1265,
"text": "DSA- Self Paced"
},
{
"code": null,
"e": 1285,
"s": 1281,
"text": "CIP"
},
{
"code": null,
"e": 1305,
"s": 1285,
"text": "JAVA / Python / C++"
},
{
"code": null,
"e": 1318,
"s": 1305,
"text": "Explore More"
},
{
"code": null,
"e": 1393,
"s": 1318,
"text": "School CoursesSchool GuidePython ProgrammingLearn To Make AppsExplore more"
},
{
"code": null,
"e": 1406,
"s": 1393,
"text": "School Guide"
},
{
"code": null,
"e": 1425,
"s": 1406,
"text": "Python Programming"
},
{
"code": null,
"e": 1444,
"s": 1425,
"text": "Learn To Make Apps"
},
{
"code": null,
"e": 1457,
"s": 1444,
"text": "Explore more"
},
{
"code": null,
"e": 1469,
"s": 1457,
"text": "All Courses"
},
{
"code": null,
"e": 3985,
"s": 1469,
"text": "TutorialsAlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll AlgorithmsData StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data StructuresInterview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice QuizzesLanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlinML & Data ScienceMachine LearningData ScienceCS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware EngineeringGATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CSWeb TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHPSoftware DesignsSoftware Design PatternsSystem Design TutorialSchool LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesCS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved PapersStudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsStudent ChapterGeek on the TopInternshipCareers"
},
{
"code": null,
"e": 4566,
"s": 3985,
"text": "AlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll Algorithms"
},
{
"code": null,
"e": 4899,
"s": 4566,
"text": "Analysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity Question"
},
{
"code": null,
"e": 4919,
"s": 4899,
"text": "Asymptotic Analysis"
},
{
"code": null,
"e": 4949,
"s": 4919,
"text": "Worst, Average and Best Cases"
},
{
"code": null,
"e": 4970,
"s": 4949,
"text": "Asymptotic Notations"
},
{
"code": null,
"e": 5006,
"s": 4970,
"text": "Little o and little omega notations"
},
{
"code": null,
"e": 5035,
"s": 5006,
"text": "Lower and Upper Bound Theory"
},
{
"code": null,
"e": 5053,
"s": 5035,
"text": "Analysis of Loops"
},
{
"code": null,
"e": 5073,
"s": 5053,
"text": "Solving Recurrences"
},
{
"code": null,
"e": 5092,
"s": 5073,
"text": "Amortized Analysis"
},
{
"code": null,
"e": 5128,
"s": 5092,
"text": "What does 'Space Complexity' mean ?"
},
{
"code": null,
"e": 5157,
"s": 5128,
"text": "Pseudo-polynomial Algorithms"
},
{
"code": null,
"e": 5194,
"s": 5157,
"text": "Polynomial Time Approximation Scheme"
},
{
"code": null,
"e": 5221,
"s": 5194,
"text": "A Time Complexity Question"
},
{
"code": null,
"e": 5242,
"s": 5221,
"text": "Searching Algorithms"
},
{
"code": null,
"e": 5261,
"s": 5242,
"text": "Sorting Algorithms"
},
{
"code": null,
"e": 5278,
"s": 5261,
"text": "Graph Algorithms"
},
{
"code": null,
"e": 5296,
"s": 5278,
"text": "Pattern Searching"
},
{
"code": null,
"e": 5317,
"s": 5296,
"text": "Geometric Algorithms"
},
{
"code": null,
"e": 5330,
"s": 5317,
"text": "Mathematical"
},
{
"code": null,
"e": 5349,
"s": 5330,
"text": "Bitwise Algorithms"
},
{
"code": null,
"e": 5371,
"s": 5349,
"text": "Randomized Algorithms"
},
{
"code": null,
"e": 5389,
"s": 5371,
"text": "Greedy Algorithms"
},
{
"code": null,
"e": 5409,
"s": 5389,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 5428,
"s": 5409,
"text": "Divide and Conquer"
},
{
"code": null,
"e": 5441,
"s": 5428,
"text": "Backtracking"
},
{
"code": null,
"e": 5458,
"s": 5441,
"text": "Branch and Bound"
},
{
"code": null,
"e": 5473,
"s": 5458,
"text": "All Algorithms"
},
{
"code": null,
"e": 5616,
"s": 5473,
"text": "Data StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data Structures"
},
{
"code": null,
"e": 5623,
"s": 5616,
"text": "Arrays"
},
{
"code": null,
"e": 5635,
"s": 5623,
"text": "Linked List"
},
{
"code": null,
"e": 5641,
"s": 5635,
"text": "Stack"
},
{
"code": null,
"e": 5647,
"s": 5641,
"text": "Queue"
},
{
"code": null,
"e": 5659,
"s": 5647,
"text": "Binary Tree"
},
{
"code": null,
"e": 5678,
"s": 5659,
"text": "Binary Search Tree"
},
{
"code": null,
"e": 5683,
"s": 5678,
"text": "Heap"
},
{
"code": null,
"e": 5691,
"s": 5683,
"text": "Hashing"
},
{
"code": null,
"e": 5697,
"s": 5691,
"text": "Graph"
},
{
"code": null,
"e": 5721,
"s": 5697,
"text": "Advanced Data Structure"
},
{
"code": null,
"e": 5728,
"s": 5721,
"text": "Matrix"
},
{
"code": null,
"e": 5736,
"s": 5728,
"text": "Strings"
},
{
"code": null,
"e": 5756,
"s": 5736,
"text": "All Data Structures"
},
{
"code": null,
"e": 5976,
"s": 5756,
"text": "Interview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice Quizzes"
},
{
"code": null,
"e": 5996,
"s": 5976,
"text": "Company Preparation"
},
{
"code": null,
"e": 6007,
"s": 5996,
"text": "Top Topics"
},
{
"code": null,
"e": 6034,
"s": 6007,
"text": "Practice Company Questions"
},
{
"code": null,
"e": 6056,
"s": 6034,
"text": "Interview Experiences"
},
{
"code": null,
"e": 6079,
"s": 6056,
"text": "Experienced Interviews"
},
{
"code": null,
"e": 6101,
"s": 6079,
"text": "Internship Interviews"
},
{
"code": null,
"e": 6126,
"s": 6101,
"text": "Competititve Programming"
},
{
"code": null,
"e": 6142,
"s": 6126,
"text": "Design Patterns"
},
{
"code": null,
"e": 6165,
"s": 6142,
"text": "System Design Tutorial"
},
{
"code": null,
"e": 6189,
"s": 6165,
"text": "Multiple Choice Quizzes"
},
{
"code": null,
"e": 6270,
"s": 6189,
"text": "LanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlin"
},
{
"code": null,
"e": 6272,
"s": 6270,
"text": "C"
},
{
"code": null,
"e": 6276,
"s": 6272,
"text": "C++"
},
{
"code": null,
"e": 6281,
"s": 6276,
"text": "Java"
},
{
"code": null,
"e": 6288,
"s": 6281,
"text": "Python"
},
{
"code": null,
"e": 6291,
"s": 6288,
"text": "C#"
},
{
"code": null,
"e": 6302,
"s": 6291,
"text": "JavaScript"
},
{
"code": null,
"e": 6309,
"s": 6302,
"text": "jQuery"
},
{
"code": null,
"e": 6313,
"s": 6309,
"text": "SQL"
},
{
"code": null,
"e": 6317,
"s": 6313,
"text": "PHP"
},
{
"code": null,
"e": 6323,
"s": 6317,
"text": "Scala"
},
{
"code": null,
"e": 6328,
"s": 6323,
"text": "Perl"
},
{
"code": null,
"e": 6340,
"s": 6328,
"text": "Go Language"
},
{
"code": null,
"e": 6345,
"s": 6340,
"text": "HTML"
},
{
"code": null,
"e": 6349,
"s": 6345,
"text": "CSS"
},
{
"code": null,
"e": 6356,
"s": 6349,
"text": "Kotlin"
},
{
"code": null,
"e": 6402,
"s": 6356,
"text": "ML & Data ScienceMachine LearningData Science"
},
{
"code": null,
"e": 6419,
"s": 6402,
"text": "Machine Learning"
},
{
"code": null,
"e": 6432,
"s": 6419,
"text": "Data Science"
},
{
"code": null,
"e": 6599,
"s": 6432,
"text": "CS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware Engineering"
},
{
"code": null,
"e": 6611,
"s": 6599,
"text": "Mathematics"
},
{
"code": null,
"e": 6628,
"s": 6611,
"text": "Operating System"
},
{
"code": null,
"e": 6633,
"s": 6628,
"text": "DBMS"
},
{
"code": null,
"e": 6651,
"s": 6633,
"text": "Computer Networks"
},
{
"code": null,
"e": 6690,
"s": 6651,
"text": "Computer Organization and Architecture"
},
{
"code": null,
"e": 6712,
"s": 6690,
"text": "Theory of Computation"
},
{
"code": null,
"e": 6728,
"s": 6712,
"text": "Compiler Design"
},
{
"code": null,
"e": 6742,
"s": 6728,
"text": "Digital Logic"
},
{
"code": null,
"e": 6763,
"s": 6742,
"text": "Software Engineering"
},
{
"code": null,
"e": 6938,
"s": 6763,
"text": "GATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CS"
},
{
"code": null,
"e": 6966,
"s": 6938,
"text": "GATE Computer Science Notes"
},
{
"code": null,
"e": 6984,
"s": 6966,
"text": "Last Minute Notes"
},
{
"code": null,
"e": 7006,
"s": 6984,
"text": "GATE CS Solved Papers"
},
{
"code": null,
"e": 7048,
"s": 7006,
"text": "GATE CS Original Papers and Official Keys"
},
{
"code": null,
"e": 7064,
"s": 7048,
"text": "GATE 2021 Dates"
},
{
"code": null,
"e": 7086,
"s": 7064,
"text": "GATE CS 2021 Syllabus"
},
{
"code": null,
"e": 7115,
"s": 7086,
"text": "Important Topics for GATE CS"
},
{
"code": null,
"e": 7189,
"s": 7115,
"text": "Web TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHP"
},
{
"code": null,
"e": 7194,
"s": 7189,
"text": "HTML"
},
{
"code": null,
"e": 7198,
"s": 7194,
"text": "CSS"
},
{
"code": null,
"e": 7209,
"s": 7198,
"text": "JavaScript"
},
{
"code": null,
"e": 7219,
"s": 7209,
"text": "AngularJS"
},
{
"code": null,
"e": 7227,
"s": 7219,
"text": "ReactJS"
},
{
"code": null,
"e": 7234,
"s": 7227,
"text": "NodeJS"
},
{
"code": null,
"e": 7244,
"s": 7234,
"text": "Bootstrap"
},
{
"code": null,
"e": 7251,
"s": 7244,
"text": "jQuery"
},
{
"code": null,
"e": 7255,
"s": 7251,
"text": "PHP"
},
{
"code": null,
"e": 7318,
"s": 7255,
"text": "Software DesignsSoftware Design PatternsSystem Design Tutorial"
},
{
"code": null,
"e": 7343,
"s": 7318,
"text": "Software Design Patterns"
},
{
"code": null,
"e": 7366,
"s": 7343,
"text": "System Design Tutorial"
},
{
"code": null,
"e": 7923,
"s": 7366,
"text": "School LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes"
},
{
"code": null,
"e": 7942,
"s": 7923,
"text": "School Programming"
},
{
"code": null,
"e": 8034,
"s": 7942,
"text": "MathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculus"
},
{
"code": null,
"e": 8048,
"s": 8034,
"text": "Number System"
},
{
"code": null,
"e": 8056,
"s": 8048,
"text": "Algebra"
},
{
"code": null,
"e": 8069,
"s": 8056,
"text": "Trigonometry"
},
{
"code": null,
"e": 8080,
"s": 8069,
"text": "Statistics"
},
{
"code": null,
"e": 8092,
"s": 8080,
"text": "Probability"
},
{
"code": null,
"e": 8101,
"s": 8092,
"text": "Geometry"
},
{
"code": null,
"e": 8113,
"s": 8101,
"text": "Mensuration"
},
{
"code": null,
"e": 8122,
"s": 8113,
"text": "Calculus"
},
{
"code": null,
"e": 8215,
"s": 8122,
"text": "Maths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 Notes"
},
{
"code": null,
"e": 8229,
"s": 8215,
"text": "Class 8 Notes"
},
{
"code": null,
"e": 8243,
"s": 8229,
"text": "Class 9 Notes"
},
{
"code": null,
"e": 8258,
"s": 8243,
"text": "Class 10 Notes"
},
{
"code": null,
"e": 8273,
"s": 8258,
"text": "Class 11 Notes"
},
{
"code": null,
"e": 8288,
"s": 8273,
"text": "Class 12 Notes"
},
{
"code": null,
"e": 8417,
"s": 8288,
"text": "NCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution"
},
{
"code": null,
"e": 8440,
"s": 8417,
"text": "Class 8 Maths Solution"
},
{
"code": null,
"e": 8463,
"s": 8440,
"text": "Class 9 Maths Solution"
},
{
"code": null,
"e": 8487,
"s": 8463,
"text": "Class 10 Maths Solution"
},
{
"code": null,
"e": 8511,
"s": 8487,
"text": "Class 11 Maths Solution"
},
{
"code": null,
"e": 8535,
"s": 8511,
"text": "Class 12 Maths Solution"
},
{
"code": null,
"e": 8668,
"s": 8535,
"text": "RD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution"
},
{
"code": null,
"e": 8691,
"s": 8668,
"text": "Class 8 Maths Solution"
},
{
"code": null,
"e": 8714,
"s": 8691,
"text": "Class 9 Maths Solution"
},
{
"code": null,
"e": 8738,
"s": 8714,
"text": "Class 10 Maths Solution"
},
{
"code": null,
"e": 8762,
"s": 8738,
"text": "Class 11 Maths Solution"
},
{
"code": null,
"e": 8786,
"s": 8762,
"text": "Class 12 Maths Solution"
},
{
"code": null,
"e": 8867,
"s": 8786,
"text": "Physics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes"
},
{
"code": null,
"e": 8881,
"s": 8867,
"text": "Class 8 Notes"
},
{
"code": null,
"e": 8895,
"s": 8881,
"text": "Class 9 Notes"
},
{
"code": null,
"e": 8910,
"s": 8895,
"text": "Class 10 Notes"
},
{
"code": null,
"e": 8925,
"s": 8910,
"text": "Class 11 Notes"
},
{
"code": null,
"e": 9131,
"s": 8925,
"text": "CS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers"
},
{
"code": null,
"e": 9242,
"s": 9131,
"text": "ISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer Exam"
},
{
"code": null,
"e": 9284,
"s": 9242,
"text": "ISRO CS Original Papers and Official Keys"
},
{
"code": null,
"e": 9306,
"s": 9284,
"text": "ISRO CS Solved Papers"
},
{
"code": null,
"e": 9351,
"s": 9306,
"text": "ISRO CS Syllabus for Scientist/Engineer Exam"
},
{
"code": null,
"e": 9434,
"s": 9351,
"text": "UGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers"
},
{
"code": null,
"e": 9460,
"s": 9434,
"text": "UGC NET CS Notes Paper II"
},
{
"code": null,
"e": 9487,
"s": 9460,
"text": "UGC NET CS Notes Paper III"
},
{
"code": null,
"e": 9512,
"s": 9487,
"text": "UGC NET CS Solved Papers"
},
{
"code": null,
"e": 9717,
"s": 9512,
"text": "StudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsStudent ChapterGeek on the TopInternshipCareers"
},
{
"code": null,
"e": 9743,
"s": 9717,
"text": "Campus Ambassador Program"
},
{
"code": null,
"e": 9769,
"s": 9743,
"text": "School Ambassador Program"
},
{
"code": null,
"e": 9777,
"s": 9769,
"text": "Project"
},
{
"code": null,
"e": 9795,
"s": 9777,
"text": "Geek of the Month"
},
{
"code": null,
"e": 9820,
"s": 9795,
"text": "Campus Geek of the Month"
},
{
"code": null,
"e": 9837,
"s": 9820,
"text": "Placement Course"
},
{
"code": null,
"e": 9862,
"s": 9837,
"text": "Competititve Programming"
},
{
"code": null,
"e": 9875,
"s": 9862,
"text": "Testimonials"
},
{
"code": null,
"e": 9891,
"s": 9875,
"text": "Student Chapter"
},
{
"code": null,
"e": 9907,
"s": 9891,
"text": "Geek on the Top"
},
{
"code": null,
"e": 9918,
"s": 9907,
"text": "Internship"
},
{
"code": null,
"e": 9926,
"s": 9918,
"text": "Careers"
},
{
"code": null,
"e": 9965,
"s": 9926,
"text": "JobsApply for JobsPost a JobJOB-A-THON"
},
{
"code": null,
"e": 9980,
"s": 9965,
"text": "Apply for Jobs"
},
{
"code": null,
"e": 9991,
"s": 9980,
"text": "Post a Job"
},
{
"code": null,
"e": 10002,
"s": 9991,
"text": "JOB-A-THON"
},
{
"code": null,
"e": 10267,
"s": 10002,
"text": "PracticeAll DSA ProblemsProblem of the DayInterview Series: Weekly ContestsBi-Wizard Coding: School ContestsContests and EventsPractice SDE SheetCurated DSA ListsTop 50 Array ProblemsTop 50 String ProblemsTop 50 Tree ProblemsTop 50 Graph ProblemsTop 50 DP Problems"
},
{
"code": null,
"e": 10284,
"s": 10267,
"text": "All DSA Problems"
},
{
"code": null,
"e": 10303,
"s": 10284,
"text": "Problem of the Day"
},
{
"code": null,
"e": 10337,
"s": 10303,
"text": "Interview Series: Weekly Contests"
},
{
"code": null,
"e": 10371,
"s": 10337,
"text": "Bi-Wizard Coding: School Contests"
},
{
"code": null,
"e": 10391,
"s": 10371,
"text": "Contests and Events"
},
{
"code": null,
"e": 10410,
"s": 10391,
"text": "Practice SDE Sheet"
},
{
"code": null,
"e": 10530,
"s": 10410,
"text": "Curated DSA ListsTop 50 Array ProblemsTop 50 String ProblemsTop 50 Tree ProblemsTop 50 Graph ProblemsTop 50 DP Problems"
},
{
"code": null,
"e": 10552,
"s": 10530,
"text": "Top 50 Array Problems"
},
{
"code": null,
"e": 10575,
"s": 10552,
"text": "Top 50 String Problems"
},
{
"code": null,
"e": 10596,
"s": 10575,
"text": "Top 50 Tree Problems"
},
{
"code": null,
"e": 10618,
"s": 10596,
"text": "Top 50 Graph Problems"
},
{
"code": null,
"e": 10637,
"s": 10618,
"text": "Top 50 DP Problems"
},
{
"code": null,
"e": 10908,
"s": 10641,
"text": "WriteCome write articles for us and get featuredPracticeLearn and code with the best industry expertsPremiumGet access to ad-free content, doubt assistance and more!JobsCome and find your dream job with usGeeks DigestQuizzesGeeks CampusGblog ArticlesIDECampus Mantri"
},
{
"code": null,
"e": 10921,
"s": 10908,
"text": "Geeks Digest"
},
{
"code": null,
"e": 10929,
"s": 10921,
"text": "Quizzes"
},
{
"code": null,
"e": 10942,
"s": 10929,
"text": "Geeks Campus"
},
{
"code": null,
"e": 10957,
"s": 10942,
"text": "Gblog Articles"
},
{
"code": null,
"e": 10961,
"s": 10957,
"text": "IDE"
},
{
"code": null,
"e": 10975,
"s": 10961,
"text": "Campus Mantri"
},
{
"code": null,
"e": 10983,
"s": 10975,
"text": "Sign In"
},
{
"code": null,
"e": 10991,
"s": 10983,
"text": "Sign In"
},
{
"code": null,
"e": 10996,
"s": 10991,
"text": "Home"
},
{
"code": null,
"e": 11009,
"s": 10996,
"text": "Saved Videos"
},
{
"code": null,
"e": 11017,
"s": 11009,
"text": "Courses"
},
{
"code": null,
"e": 15482,
"s": 11017,
"text": "\n\nFor Working Professionals\n \n\n\n\nLIVE\n \n\n\nDSA Live Classes\n\nSystem Design\n\nJava Backend Development\n\nFull Stack LIVE\n\nExplore More\n\n\nSelf-Paced\n \n\n\nDSA- Self Paced\n\nSDE Theory\n\nMust-Do Coding Questions\n\nExplore More\n\n\nFor Students\n \n\n\n\nLIVE\n \n\n\nCompetitive Programming\n\nData Structures with C++\n\nData Science\n\nExplore More\n\n\nSelf-Paced\n \n\n\nDSA- Self Paced\n\nCIP\n\nJAVA / Python / C++\n\nExplore More\n\n\nSchool Courses\n \n\n\nSchool Guide\n\nPython Programming\n\nLearn To Make Apps\n\nExplore more\n\n\nAlgorithms\n \n\n\nSearching Algorithms\n\nSorting Algorithms\n\nGraph Algorithms\n\nPattern Searching\n\nGeometric Algorithms\n\nMathematical\n\nBitwise Algorithms\n\nRandomized Algorithms\n\nGreedy Algorithms\n\nDynamic Programming\n\nDivide and Conquer\n\nBacktracking\n\nBranch and Bound\n\nAll Algorithms\n\n\nAnalysis of Algorithms\n \n\n\nAsymptotic Analysis\n\nWorst, Average and Best Cases\n\nAsymptotic Notations\n\nLittle o and little omega notations\n\nLower and Upper Bound Theory\n\nAnalysis of Loops\n\nSolving Recurrences\n\nAmortized Analysis\n\nWhat does 'Space Complexity' mean ?\n\nPseudo-polynomial Algorithms\n\nPolynomial Time Approximation Scheme\n\nA Time Complexity Question\n\n\nData Structures\n \n\n\nArrays\n\nLinked List\n\nStack\n\nQueue\n\nBinary Tree\n\nBinary Search Tree\n\nHeap\n\nHashing\n\nGraph\n\nAdvanced Data Structure\n\nMatrix\n\nStrings\n\nAll Data Structures\n\n\nInterview Corner\n \n\n\nCompany Preparation\n\nTop Topics\n\nPractice Company Questions\n\nInterview Experiences\n\nExperienced Interviews\n\nInternship Interviews\n\nCompetititve Programming\n\nDesign Patterns\n\nSystem Design Tutorial\n\nMultiple Choice Quizzes\n\n\nLanguages\n \n\n\nC\n\nC++\n\nJava\n\nPython\n\nC#\n\nJavaScript\n\njQuery\n\nSQL\n\nPHP\n\nScala\n\nPerl\n\nGo Language\n\nHTML\n\nCSS\n\nKotlin\n\n\nML & Data Science\n \n\n\nMachine Learning\n\nData Science\n\n\nCS Subjects\n \n\n\nMathematics\n\nOperating System\n\nDBMS\n\nComputer Networks\n\nComputer Organization and Architecture\n\nTheory of Computation\n\nCompiler Design\n\nDigital Logic\n\nSoftware Engineering\n\n\nGATE\n \n\n\nGATE Computer Science Notes\n\nLast Minute Notes\n\nGATE CS Solved Papers\n\nGATE CS Original Papers and Official Keys\n\nGATE 2021 Dates\n\nGATE CS 2021 Syllabus\n\nImportant Topics for GATE CS\n\n\nWeb Technologies\n \n\n\nHTML\n\nCSS\n\nJavaScript\n\nAngularJS\n\nReactJS\n\nNodeJS\n\nBootstrap\n\njQuery\n\nPHP\n\n\nSoftware Designs\n \n\n\nSoftware Design Patterns\n\nSystem Design Tutorial\n\n\nSchool Learning\n \n\n\nSchool Programming\n\n\nMathematics\n \n\n\nNumber System\n\nAlgebra\n\nTrigonometry\n\nStatistics\n\nProbability\n\nGeometry\n\nMensuration\n\nCalculus\n\n\nMaths Notes (Class 8-12)\n \n\n\nClass 8 Notes\n\nClass 9 Notes\n\nClass 10 Notes\n\nClass 11 Notes\n\nClass 12 Notes\n\n\nNCERT Solutions\n \n\n\nClass 8 Maths Solution\n\nClass 9 Maths Solution\n\nClass 10 Maths Solution\n\nClass 11 Maths Solution\n\nClass 12 Maths Solution\n\n\nRD Sharma Solutions\n \n\n\nClass 8 Maths Solution\n\nClass 9 Maths Solution\n\nClass 10 Maths Solution\n\nClass 11 Maths Solution\n\nClass 12 Maths Solution\n\n\nPhysics Notes (Class 8-11)\n \n\n\nClass 8 Notes\n\nClass 9 Notes\n\nClass 10 Notes\n\nClass 11 Notes\n\n\nCS Exams/PSUs\n \n\n\n\nISRO\n \n\n\nISRO CS Original Papers and Official Keys\n\nISRO CS Solved Papers\n\nISRO CS Syllabus for Scientist/Engineer Exam\n\n\nUGC NET\n \n\n\nUGC NET CS Notes Paper II\n\nUGC NET CS Notes Paper III\n\nUGC NET CS Solved Papers\n\n\nStudent\n \n\n\nCampus Ambassador Program\n\nSchool Ambassador Program\n\nProject\n\nGeek of the Month\n\nCampus Geek of the Month\n\nPlacement Course\n\nCompetititve Programming\n\nTestimonials\n\nStudent Chapter\n\nGeek on the Top\n\nInternship\n\nCareers\n\n\nCurated DSA Lists\n \n\n\nTop 50 Array Problems\n\nTop 50 String Problems\n\nTop 50 Tree Problems\n\nTop 50 Graph Problems\n\nTop 50 DP Problems\n\n\nTutorials\n \n\n\n\nJobs\n \n\n\nApply for Jobs\n\nPost a Job\n\nJOB-A-THON\n\n\nPractice\n \n\n\nAll DSA Problems\n\nProblem of the Day\n\nInterview Series: Weekly Contests\n\nBi-Wizard Coding: School Contests\n\nContests and Events\n\nPractice SDE Sheet\n"
},
{
"code": null,
"e": 15536,
"s": 15482,
"text": "\nFor Working Professionals\n \n\n"
},
{
"code": null,
"e": 15659,
"s": 15536,
"text": "\nLIVE\n \n\n\nDSA Live Classes\n\nSystem Design\n\nJava Backend Development\n\nFull Stack LIVE\n\nExplore More\n"
},
{
"code": null,
"e": 15678,
"s": 15659,
"text": "\nDSA Live Classes\n"
},
{
"code": null,
"e": 15694,
"s": 15678,
"text": "\nSystem Design\n"
},
{
"code": null,
"e": 15721,
"s": 15694,
"text": "\nJava Backend Development\n"
},
{
"code": null,
"e": 15739,
"s": 15721,
"text": "\nFull Stack LIVE\n"
},
{
"code": null,
"e": 15754,
"s": 15739,
"text": "\nExplore More\n"
},
{
"code": null,
"e": 15862,
"s": 15754,
"text": "\nSelf-Paced\n \n\n\nDSA- Self Paced\n\nSDE Theory\n\nMust-Do Coding Questions\n\nExplore More\n"
},
{
"code": null,
"e": 15880,
"s": 15862,
"text": "\nDSA- Self Paced\n"
},
{
"code": null,
"e": 15893,
"s": 15880,
"text": "\nSDE Theory\n"
},
{
"code": null,
"e": 15920,
"s": 15893,
"text": "\nMust-Do Coding Questions\n"
},
{
"code": null,
"e": 15935,
"s": 15920,
"text": "\nExplore More\n"
},
{
"code": null,
"e": 15976,
"s": 15935,
"text": "\nFor Students\n \n\n"
},
{
"code": null,
"e": 16088,
"s": 15976,
"text": "\nLIVE\n \n\n\nCompetitive Programming\n\nData Structures with C++\n\nData Science\n\nExplore More\n"
},
{
"code": null,
"e": 16114,
"s": 16088,
"text": "\nCompetitive Programming\n"
},
{
"code": null,
"e": 16141,
"s": 16114,
"text": "\nData Structures with C++\n"
},
{
"code": null,
"e": 16156,
"s": 16141,
"text": "\nData Science\n"
},
{
"code": null,
"e": 16171,
"s": 16156,
"text": "\nExplore More\n"
},
{
"code": null,
"e": 16267,
"s": 16171,
"text": "\nSelf-Paced\n \n\n\nDSA- Self Paced\n\nCIP\n\nJAVA / Python / C++\n\nExplore More\n"
},
{
"code": null,
"e": 16285,
"s": 16267,
"text": "\nDSA- Self Paced\n"
},
{
"code": null,
"e": 16291,
"s": 16285,
"text": "\nCIP\n"
},
{
"code": null,
"e": 16313,
"s": 16291,
"text": "\nJAVA / Python / C++\n"
},
{
"code": null,
"e": 16328,
"s": 16313,
"text": "\nExplore More\n"
},
{
"code": null,
"e": 16439,
"s": 16328,
"text": "\nSchool Courses\n \n\n\nSchool Guide\n\nPython Programming\n\nLearn To Make Apps\n\nExplore more\n"
},
{
"code": null,
"e": 16454,
"s": 16439,
"text": "\nSchool Guide\n"
},
{
"code": null,
"e": 16475,
"s": 16454,
"text": "\nPython Programming\n"
},
{
"code": null,
"e": 16496,
"s": 16475,
"text": "\nLearn To Make Apps\n"
},
{
"code": null,
"e": 16511,
"s": 16496,
"text": "\nExplore more\n"
},
{
"code": null,
"e": 16816,
"s": 16511,
"text": "\nAlgorithms\n \n\n\nSearching Algorithms\n\nSorting Algorithms\n\nGraph Algorithms\n\nPattern Searching\n\nGeometric Algorithms\n\nMathematical\n\nBitwise Algorithms\n\nRandomized Algorithms\n\nGreedy Algorithms\n\nDynamic Programming\n\nDivide and Conquer\n\nBacktracking\n\nBranch and Bound\n\nAll Algorithms\n"
},
{
"code": null,
"e": 16839,
"s": 16816,
"text": "\nSearching Algorithms\n"
},
{
"code": null,
"e": 16860,
"s": 16839,
"text": "\nSorting Algorithms\n"
},
{
"code": null,
"e": 16879,
"s": 16860,
"text": "\nGraph Algorithms\n"
},
{
"code": null,
"e": 16899,
"s": 16879,
"text": "\nPattern Searching\n"
},
{
"code": null,
"e": 16922,
"s": 16899,
"text": "\nGeometric Algorithms\n"
},
{
"code": null,
"e": 16937,
"s": 16922,
"text": "\nMathematical\n"
},
{
"code": null,
"e": 16958,
"s": 16937,
"text": "\nBitwise Algorithms\n"
},
{
"code": null,
"e": 16982,
"s": 16958,
"text": "\nRandomized Algorithms\n"
},
{
"code": null,
"e": 17002,
"s": 16982,
"text": "\nGreedy Algorithms\n"
},
{
"code": null,
"e": 17024,
"s": 17002,
"text": "\nDynamic Programming\n"
},
{
"code": null,
"e": 17045,
"s": 17024,
"text": "\nDivide and Conquer\n"
},
{
"code": null,
"e": 17060,
"s": 17045,
"text": "\nBacktracking\n"
},
{
"code": null,
"e": 17079,
"s": 17060,
"text": "\nBranch and Bound\n"
},
{
"code": null,
"e": 17096,
"s": 17079,
"text": "\nAll Algorithms\n"
},
{
"code": null,
"e": 17481,
"s": 17096,
"text": "\nAnalysis of Algorithms\n \n\n\nAsymptotic Analysis\n\nWorst, Average and Best Cases\n\nAsymptotic Notations\n\nLittle o and little omega notations\n\nLower and Upper Bound Theory\n\nAnalysis of Loops\n\nSolving Recurrences\n\nAmortized Analysis\n\nWhat does 'Space Complexity' mean ?\n\nPseudo-polynomial Algorithms\n\nPolynomial Time Approximation Scheme\n\nA Time Complexity Question\n"
},
{
"code": null,
"e": 17503,
"s": 17481,
"text": "\nAsymptotic Analysis\n"
},
{
"code": null,
"e": 17535,
"s": 17503,
"text": "\nWorst, Average and Best Cases\n"
},
{
"code": null,
"e": 17558,
"s": 17535,
"text": "\nAsymptotic Notations\n"
},
{
"code": null,
"e": 17596,
"s": 17558,
"text": "\nLittle o and little omega notations\n"
},
{
"code": null,
"e": 17627,
"s": 17596,
"text": "\nLower and Upper Bound Theory\n"
},
{
"code": null,
"e": 17647,
"s": 17627,
"text": "\nAnalysis of Loops\n"
},
{
"code": null,
"e": 17669,
"s": 17647,
"text": "\nSolving Recurrences\n"
},
{
"code": null,
"e": 17690,
"s": 17669,
"text": "\nAmortized Analysis\n"
},
{
"code": null,
"e": 17728,
"s": 17690,
"text": "\nWhat does 'Space Complexity' mean ?\n"
},
{
"code": null,
"e": 17759,
"s": 17728,
"text": "\nPseudo-polynomial Algorithms\n"
},
{
"code": null,
"e": 17798,
"s": 17759,
"text": "\nPolynomial Time Approximation Scheme\n"
},
{
"code": null,
"e": 17827,
"s": 17798,
"text": "\nA Time Complexity Question\n"
},
{
"code": null,
"e": 18024,
"s": 17827,
"text": "\nData Structures\n \n\n\nArrays\n\nLinked List\n\nStack\n\nQueue\n\nBinary Tree\n\nBinary Search Tree\n\nHeap\n\nHashing\n\nGraph\n\nAdvanced Data Structure\n\nMatrix\n\nStrings\n\nAll Data Structures\n"
},
{
"code": null,
"e": 18033,
"s": 18024,
"text": "\nArrays\n"
},
{
"code": null,
"e": 18047,
"s": 18033,
"text": "\nLinked List\n"
},
{
"code": null,
"e": 18055,
"s": 18047,
"text": "\nStack\n"
},
{
"code": null,
"e": 18063,
"s": 18055,
"text": "\nQueue\n"
},
{
"code": null,
"e": 18077,
"s": 18063,
"text": "\nBinary Tree\n"
},
{
"code": null,
"e": 18098,
"s": 18077,
"text": "\nBinary Search Tree\n"
},
{
"code": null,
"e": 18105,
"s": 18098,
"text": "\nHeap\n"
},
{
"code": null,
"e": 18115,
"s": 18105,
"text": "\nHashing\n"
},
{
"code": null,
"e": 18123,
"s": 18115,
"text": "\nGraph\n"
},
{
"code": null,
"e": 18149,
"s": 18123,
"text": "\nAdvanced Data Structure\n"
},
{
"code": null,
"e": 18158,
"s": 18149,
"text": "\nMatrix\n"
},
{
"code": null,
"e": 18168,
"s": 18158,
"text": "\nStrings\n"
},
{
"code": null,
"e": 18190,
"s": 18168,
"text": "\nAll Data Structures\n"
},
{
"code": null,
"e": 18458,
"s": 18190,
"text": "\nInterview Corner\n \n\n\nCompany Preparation\n\nTop Topics\n\nPractice Company Questions\n\nInterview Experiences\n\nExperienced Interviews\n\nInternship Interviews\n\nCompetititve Programming\n\nDesign Patterns\n\nSystem Design Tutorial\n\nMultiple Choice Quizzes\n"
},
{
"code": null,
"e": 18480,
"s": 18458,
"text": "\nCompany Preparation\n"
},
{
"code": null,
"e": 18493,
"s": 18480,
"text": "\nTop Topics\n"
},
{
"code": null,
"e": 18522,
"s": 18493,
"text": "\nPractice Company Questions\n"
},
{
"code": null,
"e": 18546,
"s": 18522,
"text": "\nInterview Experiences\n"
},
{
"code": null,
"e": 18571,
"s": 18546,
"text": "\nExperienced Interviews\n"
},
{
"code": null,
"e": 18595,
"s": 18571,
"text": "\nInternship Interviews\n"
},
{
"code": null,
"e": 18622,
"s": 18595,
"text": "\nCompetititve Programming\n"
},
{
"code": null,
"e": 18640,
"s": 18622,
"text": "\nDesign Patterns\n"
},
{
"code": null,
"e": 18665,
"s": 18640,
"text": "\nSystem Design Tutorial\n"
},
{
"code": null,
"e": 18691,
"s": 18665,
"text": "\nMultiple Choice Quizzes\n"
},
{
"code": null,
"e": 18830,
"s": 18691,
"text": "\nLanguages\n \n\n\nC\n\nC++\n\nJava\n\nPython\n\nC#\n\nJavaScript\n\njQuery\n\nSQL\n\nPHP\n\nScala\n\nPerl\n\nGo Language\n\nHTML\n\nCSS\n\nKotlin\n"
},
{
"code": null,
"e": 18834,
"s": 18830,
"text": "\nC\n"
},
{
"code": null,
"e": 18840,
"s": 18834,
"text": "\nC++\n"
},
{
"code": null,
"e": 18847,
"s": 18840,
"text": "\nJava\n"
},
{
"code": null,
"e": 18856,
"s": 18847,
"text": "\nPython\n"
},
{
"code": null,
"e": 18861,
"s": 18856,
"text": "\nC#\n"
},
{
"code": null,
"e": 18874,
"s": 18861,
"text": "\nJavaScript\n"
},
{
"code": null,
"e": 18883,
"s": 18874,
"text": "\njQuery\n"
},
{
"code": null,
"e": 18889,
"s": 18883,
"text": "\nSQL\n"
},
{
"code": null,
"e": 18895,
"s": 18889,
"text": "\nPHP\n"
},
{
"code": null,
"e": 18903,
"s": 18895,
"text": "\nScala\n"
},
{
"code": null,
"e": 18910,
"s": 18903,
"text": "\nPerl\n"
},
{
"code": null,
"e": 18924,
"s": 18910,
"text": "\nGo Language\n"
},
{
"code": null,
"e": 18931,
"s": 18924,
"text": "\nHTML\n"
},
{
"code": null,
"e": 18937,
"s": 18931,
"text": "\nCSS\n"
},
{
"code": null,
"e": 18946,
"s": 18937,
"text": "\nKotlin\n"
},
{
"code": null,
"e": 19024,
"s": 18946,
"text": "\nML & Data Science\n \n\n\nMachine Learning\n\nData Science\n"
},
{
"code": null,
"e": 19043,
"s": 19024,
"text": "\nMachine Learning\n"
},
{
"code": null,
"e": 19058,
"s": 19043,
"text": "\nData Science\n"
},
{
"code": null,
"e": 19271,
"s": 19058,
"text": "\nCS Subjects\n \n\n\nMathematics\n\nOperating System\n\nDBMS\n\nComputer Networks\n\nComputer Organization and Architecture\n\nTheory of Computation\n\nCompiler Design\n\nDigital Logic\n\nSoftware Engineering\n"
},
{
"code": null,
"e": 19285,
"s": 19271,
"text": "\nMathematics\n"
},
{
"code": null,
"e": 19304,
"s": 19285,
"text": "\nOperating System\n"
},
{
"code": null,
"e": 19311,
"s": 19304,
"text": "\nDBMS\n"
},
{
"code": null,
"e": 19331,
"s": 19311,
"text": "\nComputer Networks\n"
},
{
"code": null,
"e": 19372,
"s": 19331,
"text": "\nComputer Organization and Architecture\n"
},
{
"code": null,
"e": 19396,
"s": 19372,
"text": "\nTheory of Computation\n"
},
{
"code": null,
"e": 19414,
"s": 19396,
"text": "\nCompiler Design\n"
},
{
"code": null,
"e": 19430,
"s": 19414,
"text": "\nDigital Logic\n"
},
{
"code": null,
"e": 19453,
"s": 19430,
"text": "\nSoftware Engineering\n"
},
{
"code": null,
"e": 19670,
"s": 19453,
"text": "\nGATE\n \n\n\nGATE Computer Science Notes\n\nLast Minute Notes\n\nGATE CS Solved Papers\n\nGATE CS Original Papers and Official Keys\n\nGATE 2021 Dates\n\nGATE CS 2021 Syllabus\n\nImportant Topics for GATE CS\n"
},
{
"code": null,
"e": 19700,
"s": 19670,
"text": "\nGATE Computer Science Notes\n"
},
{
"code": null,
"e": 19720,
"s": 19700,
"text": "\nLast Minute Notes\n"
},
{
"code": null,
"e": 19744,
"s": 19720,
"text": "\nGATE CS Solved Papers\n"
},
{
"code": null,
"e": 19788,
"s": 19744,
"text": "\nGATE CS Original Papers and Official Keys\n"
},
{
"code": null,
"e": 19806,
"s": 19788,
"text": "\nGATE 2021 Dates\n"
},
{
"code": null,
"e": 19830,
"s": 19806,
"text": "\nGATE CS 2021 Syllabus\n"
},
{
"code": null,
"e": 19861,
"s": 19830,
"text": "\nImportant Topics for GATE CS\n"
},
{
"code": null,
"e": 19981,
"s": 19861,
"text": "\nWeb Technologies\n \n\n\nHTML\n\nCSS\n\nJavaScript\n\nAngularJS\n\nReactJS\n\nNodeJS\n\nBootstrap\n\njQuery\n\nPHP\n"
},
{
"code": null,
"e": 19988,
"s": 19981,
"text": "\nHTML\n"
},
{
"code": null,
"e": 19994,
"s": 19988,
"text": "\nCSS\n"
},
{
"code": null,
"e": 20007,
"s": 19994,
"text": "\nJavaScript\n"
},
{
"code": null,
"e": 20019,
"s": 20007,
"text": "\nAngularJS\n"
},
{
"code": null,
"e": 20029,
"s": 20019,
"text": "\nReactJS\n"
},
{
"code": null,
"e": 20038,
"s": 20029,
"text": "\nNodeJS\n"
},
{
"code": null,
"e": 20050,
"s": 20038,
"text": "\nBootstrap\n"
},
{
"code": null,
"e": 20059,
"s": 20050,
"text": "\njQuery\n"
},
{
"code": null,
"e": 20065,
"s": 20059,
"text": "\nPHP\n"
},
{
"code": null,
"e": 20160,
"s": 20065,
"text": "\nSoftware Designs\n \n\n\nSoftware Design Patterns\n\nSystem Design Tutorial\n"
},
{
"code": null,
"e": 20187,
"s": 20160,
"text": "\nSoftware Design Patterns\n"
},
{
"code": null,
"e": 20212,
"s": 20187,
"text": "\nSystem Design Tutorial\n"
},
{
"code": null,
"e": 20276,
"s": 20212,
"text": "\nSchool Learning\n \n\n\nSchool Programming\n"
},
{
"code": null,
"e": 20297,
"s": 20276,
"text": "\nSchool Programming\n"
},
{
"code": null,
"e": 20433,
"s": 20297,
"text": "\nMathematics\n \n\n\nNumber System\n\nAlgebra\n\nTrigonometry\n\nStatistics\n\nProbability\n\nGeometry\n\nMensuration\n\nCalculus\n"
},
{
"code": null,
"e": 20449,
"s": 20433,
"text": "\nNumber System\n"
},
{
"code": null,
"e": 20459,
"s": 20449,
"text": "\nAlgebra\n"
},
{
"code": null,
"e": 20474,
"s": 20459,
"text": "\nTrigonometry\n"
},
{
"code": null,
"e": 20487,
"s": 20474,
"text": "\nStatistics\n"
},
{
"code": null,
"e": 20501,
"s": 20487,
"text": "\nProbability\n"
},
{
"code": null,
"e": 20512,
"s": 20501,
"text": "\nGeometry\n"
},
{
"code": null,
"e": 20526,
"s": 20512,
"text": "\nMensuration\n"
},
{
"code": null,
"e": 20537,
"s": 20526,
"text": "\nCalculus\n"
},
{
"code": null,
"e": 20668,
"s": 20537,
"text": "\nMaths Notes (Class 8-12)\n \n\n\nClass 8 Notes\n\nClass 9 Notes\n\nClass 10 Notes\n\nClass 11 Notes\n\nClass 12 Notes\n"
},
{
"code": null,
"e": 20684,
"s": 20668,
"text": "\nClass 8 Notes\n"
},
{
"code": null,
"e": 20700,
"s": 20684,
"text": "\nClass 9 Notes\n"
},
{
"code": null,
"e": 20717,
"s": 20700,
"text": "\nClass 10 Notes\n"
},
{
"code": null,
"e": 20734,
"s": 20717,
"text": "\nClass 11 Notes\n"
},
{
"code": null,
"e": 20751,
"s": 20734,
"text": "\nClass 12 Notes\n"
},
{
"code": null,
"e": 20918,
"s": 20751,
"text": "\nNCERT Solutions\n \n\n\nClass 8 Maths Solution\n\nClass 9 Maths Solution\n\nClass 10 Maths Solution\n\nClass 11 Maths Solution\n\nClass 12 Maths Solution\n"
},
{
"code": null,
"e": 20943,
"s": 20918,
"text": "\nClass 8 Maths Solution\n"
},
{
"code": null,
"e": 20968,
"s": 20943,
"text": "\nClass 9 Maths Solution\n"
},
{
"code": null,
"e": 20994,
"s": 20968,
"text": "\nClass 10 Maths Solution\n"
},
{
"code": null,
"e": 21020,
"s": 20994,
"text": "\nClass 11 Maths Solution\n"
},
{
"code": null,
"e": 21046,
"s": 21020,
"text": "\nClass 12 Maths Solution\n"
},
{
"code": null,
"e": 21217,
"s": 21046,
"text": "\nRD Sharma Solutions\n \n\n\nClass 8 Maths Solution\n\nClass 9 Maths Solution\n\nClass 10 Maths Solution\n\nClass 11 Maths Solution\n\nClass 12 Maths Solution\n"
},
{
"code": null,
"e": 21242,
"s": 21217,
"text": "\nClass 8 Maths Solution\n"
},
{
"code": null,
"e": 21267,
"s": 21242,
"text": "\nClass 9 Maths Solution\n"
},
{
"code": null,
"e": 21293,
"s": 21267,
"text": "\nClass 10 Maths Solution\n"
},
{
"code": null,
"e": 21319,
"s": 21293,
"text": "\nClass 11 Maths Solution\n"
},
{
"code": null,
"e": 21345,
"s": 21319,
"text": "\nClass 12 Maths Solution\n"
},
{
"code": null,
"e": 21462,
"s": 21345,
"text": "\nPhysics Notes (Class 8-11)\n \n\n\nClass 8 Notes\n\nClass 9 Notes\n\nClass 10 Notes\n\nClass 11 Notes\n"
},
{
"code": null,
"e": 21478,
"s": 21462,
"text": "\nClass 8 Notes\n"
},
{
"code": null,
"e": 21494,
"s": 21478,
"text": "\nClass 9 Notes\n"
},
{
"code": null,
"e": 21511,
"s": 21494,
"text": "\nClass 10 Notes\n"
},
{
"code": null,
"e": 21528,
"s": 21511,
"text": "\nClass 11 Notes\n"
},
{
"code": null,
"e": 21570,
"s": 21528,
"text": "\nCS Exams/PSUs\n \n\n"
},
{
"code": null,
"e": 21715,
"s": 21570,
"text": "\nISRO\n \n\n\nISRO CS Original Papers and Official Keys\n\nISRO CS Solved Papers\n\nISRO CS Syllabus for Scientist/Engineer Exam\n"
},
{
"code": null,
"e": 21759,
"s": 21715,
"text": "\nISRO CS Original Papers and Official Keys\n"
},
{
"code": null,
"e": 21783,
"s": 21759,
"text": "\nISRO CS Solved Papers\n"
},
{
"code": null,
"e": 21830,
"s": 21783,
"text": "\nISRO CS Syllabus for Scientist/Engineer Exam\n"
},
{
"code": null,
"e": 21947,
"s": 21830,
"text": "\nUGC NET\n \n\n\nUGC NET CS Notes Paper II\n\nUGC NET CS Notes Paper III\n\nUGC NET CS Solved Papers\n"
},
{
"code": null,
"e": 21975,
"s": 21947,
"text": "\nUGC NET CS Notes Paper II\n"
},
{
"code": null,
"e": 22004,
"s": 21975,
"text": "\nUGC NET CS Notes Paper III\n"
},
{
"code": null,
"e": 22031,
"s": 22004,
"text": "\nUGC NET CS Solved Papers\n"
},
{
"code": null,
"e": 22288,
"s": 22031,
"text": "\nStudent\n \n\n\nCampus Ambassador Program\n\nSchool Ambassador Program\n\nProject\n\nGeek of the Month\n\nCampus Geek of the Month\n\nPlacement Course\n\nCompetititve Programming\n\nTestimonials\n\nStudent Chapter\n\nGeek on the Top\n\nInternship\n\nCareers\n"
},
{
"code": null,
"e": 22316,
"s": 22288,
"text": "\nCampus Ambassador Program\n"
},
{
"code": null,
"e": 22344,
"s": 22316,
"text": "\nSchool Ambassador Program\n"
},
{
"code": null,
"e": 22354,
"s": 22344,
"text": "\nProject\n"
},
{
"code": null,
"e": 22374,
"s": 22354,
"text": "\nGeek of the Month\n"
},
{
"code": null,
"e": 22401,
"s": 22374,
"text": "\nCampus Geek of the Month\n"
},
{
"code": null,
"e": 22420,
"s": 22401,
"text": "\nPlacement Course\n"
},
{
"code": null,
"e": 22447,
"s": 22420,
"text": "\nCompetititve Programming\n"
},
{
"code": null,
"e": 22462,
"s": 22447,
"text": "\nTestimonials\n"
},
{
"code": null,
"e": 22480,
"s": 22462,
"text": "\nStudent Chapter\n"
},
{
"code": null,
"e": 22498,
"s": 22480,
"text": "\nGeek on the Top\n"
},
{
"code": null,
"e": 22511,
"s": 22498,
"text": "\nInternship\n"
},
{
"code": null,
"e": 22521,
"s": 22511,
"text": "\nCareers\n"
},
{
"code": null,
"e": 22679,
"s": 22521,
"text": "\nCurated DSA Lists\n \n\n\nTop 50 Array Problems\n\nTop 50 String Problems\n\nTop 50 Tree Problems\n\nTop 50 Graph Problems\n\nTop 50 DP Problems\n"
},
{
"code": null,
"e": 22703,
"s": 22679,
"text": "\nTop 50 Array Problems\n"
},
{
"code": null,
"e": 22728,
"s": 22703,
"text": "\nTop 50 String Problems\n"
},
{
"code": null,
"e": 22751,
"s": 22728,
"text": "\nTop 50 Tree Problems\n"
},
{
"code": null,
"e": 22775,
"s": 22751,
"text": "\nTop 50 Graph Problems\n"
},
{
"code": null,
"e": 22796,
"s": 22775,
"text": "\nTop 50 DP Problems\n"
},
{
"code": null,
"e": 22834,
"s": 22796,
"text": "\nTutorials\n \n\n"
},
{
"code": null,
"e": 22907,
"s": 22834,
"text": "\nJobs\n \n\n\nApply for Jobs\n\nPost a Job\n\nJOB-A-THON\n"
},
{
"code": null,
"e": 22924,
"s": 22907,
"text": "\nApply for Jobs\n"
},
{
"code": null,
"e": 22937,
"s": 22924,
"text": "\nPost a Job\n"
},
{
"code": null,
"e": 22950,
"s": 22937,
"text": "\nJOB-A-THON\n"
},
{
"code": null,
"e": 23136,
"s": 22950,
"text": "\nPractice\n \n\n\nAll DSA Problems\n\nProblem of the Day\n\nInterview Series: Weekly Contests\n\nBi-Wizard Coding: School Contests\n\nContests and Events\n\nPractice SDE Sheet\n"
},
{
"code": null,
"e": 23155,
"s": 23136,
"text": "\nAll DSA Problems\n"
},
{
"code": null,
"e": 23176,
"s": 23155,
"text": "\nProblem of the Day\n"
},
{
"code": null,
"e": 23212,
"s": 23176,
"text": "\nInterview Series: Weekly Contests\n"
},
{
"code": null,
"e": 23248,
"s": 23212,
"text": "\nBi-Wizard Coding: School Contests\n"
},
{
"code": null,
"e": 23270,
"s": 23248,
"text": "\nContests and Events\n"
},
{
"code": null,
"e": 23291,
"s": 23270,
"text": "\nPractice SDE Sheet\n"
},
{
"code": null,
"e": 23297,
"s": 23291,
"text": "GBlog"
},
{
"code": null,
"e": 23305,
"s": 23297,
"text": "Puzzles"
},
{
"code": null,
"e": 23318,
"s": 23305,
"text": "What's New ?"
},
{
"code": null,
"e": 23324,
"s": 23318,
"text": "Array"
},
{
"code": null,
"e": 23331,
"s": 23324,
"text": "Matrix"
},
{
"code": null,
"e": 23339,
"s": 23331,
"text": "Strings"
},
{
"code": null,
"e": 23347,
"s": 23339,
"text": "Hashing"
},
{
"code": null,
"e": 23359,
"s": 23347,
"text": "Linked List"
},
{
"code": null,
"e": 23365,
"s": 23359,
"text": "Stack"
},
{
"code": null,
"e": 23371,
"s": 23365,
"text": "Queue"
},
{
"code": null,
"e": 23383,
"s": 23371,
"text": "Binary Tree"
},
{
"code": null,
"e": 23402,
"s": 23383,
"text": "Binary Search Tree"
},
{
"code": null,
"e": 23407,
"s": 23402,
"text": "Heap"
},
{
"code": null,
"e": 23413,
"s": 23407,
"text": "Graph"
},
{
"code": null,
"e": 23423,
"s": 23413,
"text": "Searching"
},
{
"code": null,
"e": 23431,
"s": 23423,
"text": "Sorting"
},
{
"code": null,
"e": 23448,
"s": 23431,
"text": "Divide & Conquer"
},
{
"code": null,
"e": 23461,
"s": 23448,
"text": "Mathematical"
},
{
"code": null,
"e": 23471,
"s": 23461,
"text": "Geometric"
},
{
"code": null,
"e": 23479,
"s": 23471,
"text": "Bitwise"
},
{
"code": null,
"e": 23486,
"s": 23479,
"text": "Greedy"
},
{
"code": null,
"e": 23499,
"s": 23486,
"text": "Backtracking"
},
{
"code": null,
"e": 23516,
"s": 23499,
"text": "Branch and Bound"
},
{
"code": null,
"e": 23536,
"s": 23516,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 23554,
"s": 23536,
"text": "Pattern Searching"
},
{
"code": null,
"e": 23565,
"s": 23554,
"text": "Randomized"
},
{
"code": null,
"e": 23600,
"s": 23565,
"text": "Sum of all the factors of a number"
},
{
"code": null,
"e": 23647,
"s": 23600,
"text": "Sum of all proper divisors of a natural number"
},
{
"code": null,
"e": 23679,
"s": 23647,
"text": "Sum of all divisors from 1 to n"
},
{
"code": null,
"e": 23725,
"s": 23679,
"text": "Find all divisors of a natural number | Set 2"
},
{
"code": null,
"e": 23770,
"s": 23725,
"text": "Find all factors of a natural number | Set 1"
},
{
"code": null,
"e": 23802,
"s": 23770,
"text": "Count Divisors of n in O(n^1/3)"
},
{
"code": null,
"e": 23846,
"s": 23802,
"text": "Total number of divisors for a given number"
},
{
"code": null,
"e": 23897,
"s": 23846,
"text": "Write an iterative O(Log y) function for pow(x, y)"
},
{
"code": null,
"e": 23935,
"s": 23897,
"text": "Write a program to calculate pow(x,n)"
},
{
"code": null,
"e": 23988,
"s": 23935,
"text": "Modular Exponentiation (Power in Modular Arithmetic)"
},
{
"code": null,
"e": 24023,
"s": 23988,
"text": "Modular exponentiation (Recursive)"
},
{
"code": null,
"e": 24054,
"s": 24023,
"text": "Modular multiplicative inverse"
},
{
"code": null,
"e": 24096,
"s": 24054,
"text": "Euclidean algorithms (Basic and Extended)"
},
{
"code": null,
"e": 24138,
"s": 24096,
"text": "Program to find GCD or HCF of two numbers"
},
{
"code": null,
"e": 24173,
"s": 24138,
"text": "Program to find LCM of two numbers"
},
{
"code": null,
"e": 24201,
"s": 24173,
"text": "LCM of given array elements"
},
{
"code": null,
"e": 24267,
"s": 24201,
"text": "Finding LCM of more than two (or array) numbers without using GCD"
},
{
"code": null,
"e": 24307,
"s": 24267,
"text": "GCD of more than two (or array) numbers"
},
{
"code": null,
"e": 24329,
"s": 24307,
"text": "Sieve of Eratosthenes"
},
{
"code": null,
"e": 24375,
"s": 24329,
"text": "Sieve of Eratosthenes in 0(n) time complexity"
},
{
"code": null,
"e": 24445,
"s": 24375,
"text": "How is the time complexity of Sieve of Eratosthenes is n*log(log(n))?"
},
{
"code": null,
"e": 24461,
"s": 24445,
"text": "Segmented Sieve"
},
{
"code": null,
"e": 24503,
"s": 24461,
"text": "Segmented Sieve (Print Primes in a Range)"
},
{
"code": null,
"e": 24565,
"s": 24503,
"text": "Prime Factorization using Sieve O(log n) for multiple queries"
},
{
"code": null,
"e": 24628,
"s": 24565,
"text": "Efficient program to print all prime factors of a given number"
},
{
"code": null,
"e": 24658,
"s": 24628,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 24718,
"s": 24658,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 24733,
"s": 24718,
"text": "C++ Data Types"
},
{
"code": null,
"e": 24776,
"s": 24733,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 24795,
"s": 24776,
"text": "Coin Change | DP-7"
},
{
"code": null,
"e": 24830,
"s": 24795,
"text": "Sum of all the factors of a number"
},
{
"code": null,
"e": 24877,
"s": 24830,
"text": "Sum of all proper divisors of a natural number"
},
{
"code": null,
"e": 24909,
"s": 24877,
"text": "Sum of all divisors from 1 to n"
},
{
"code": null,
"e": 24955,
"s": 24909,
"text": "Find all divisors of a natural number | Set 2"
},
{
"code": null,
"e": 25000,
"s": 24955,
"text": "Find all factors of a natural number | Set 1"
},
{
"code": null,
"e": 25032,
"s": 25000,
"text": "Count Divisors of n in O(n^1/3)"
},
{
"code": null,
"e": 25076,
"s": 25032,
"text": "Total number of divisors for a given number"
},
{
"code": null,
"e": 25127,
"s": 25076,
"text": "Write an iterative O(Log y) function for pow(x, y)"
},
{
"code": null,
"e": 25165,
"s": 25127,
"text": "Write a program to calculate pow(x,n)"
},
{
"code": null,
"e": 25218,
"s": 25165,
"text": "Modular Exponentiation (Power in Modular Arithmetic)"
},
{
"code": null,
"e": 25253,
"s": 25218,
"text": "Modular exponentiation (Recursive)"
},
{
"code": null,
"e": 25284,
"s": 25253,
"text": "Modular multiplicative inverse"
},
{
"code": null,
"e": 25326,
"s": 25284,
"text": "Euclidean algorithms (Basic and Extended)"
},
{
"code": null,
"e": 25368,
"s": 25326,
"text": "Program to find GCD or HCF of two numbers"
},
{
"code": null,
"e": 25403,
"s": 25368,
"text": "Program to find LCM of two numbers"
},
{
"code": null,
"e": 25431,
"s": 25403,
"text": "LCM of given array elements"
},
{
"code": null,
"e": 25497,
"s": 25431,
"text": "Finding LCM of more than two (or array) numbers without using GCD"
},
{
"code": null,
"e": 25537,
"s": 25497,
"text": "GCD of more than two (or array) numbers"
},
{
"code": null,
"e": 25559,
"s": 25537,
"text": "Sieve of Eratosthenes"
},
{
"code": null,
"e": 25605,
"s": 25559,
"text": "Sieve of Eratosthenes in 0(n) time complexity"
},
{
"code": null,
"e": 25675,
"s": 25605,
"text": "How is the time complexity of Sieve of Eratosthenes is n*log(log(n))?"
},
{
"code": null,
"e": 25691,
"s": 25675,
"text": "Segmented Sieve"
},
{
"code": null,
"e": 25733,
"s": 25691,
"text": "Segmented Sieve (Print Primes in a Range)"
},
{
"code": null,
"e": 25795,
"s": 25733,
"text": "Prime Factorization using Sieve O(log n) for multiple queries"
},
{
"code": null,
"e": 25858,
"s": 25795,
"text": "Efficient program to print all prime factors of a given number"
},
{
"code": null,
"e": 25888,
"s": 25858,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 25948,
"s": 25888,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 25963,
"s": 25948,
"text": "C++ Data Types"
},
{
"code": null,
"e": 26006,
"s": 25963,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 26025,
"s": 26006,
"text": "Coin Change | DP-7"
},
{
"code": null,
"e": 26051,
"s": 26025,
"text": "Difficulty Level :\nMedium"
},
{
"code": null,
"e": 26129,
"s": 26051,
"text": "Given a number n, the task is to find the sum of all the factors.Examples : "
},
{
"code": null,
"e": 26284,
"s": 26129,
"text": "Input : n = 30\nOutput : 72\nDividers sum 1 + 2 + 3 + 5 + 6 + \n 10 + 15 + 30 = 72 \n\nInput : n = 15\nOutput : 24\nDividers sum 1 + 3 + 5 + 15 = 24"
},
{
"code": null,
"e": 26356,
"s": 26286,
"text": "A simple solution is to traverse through all divisors and add them. "
},
{
"code": null,
"e": 26360,
"s": 26356,
"text": "C++"
},
{
"code": null,
"e": 26365,
"s": 26360,
"text": "Java"
},
{
"code": null,
"e": 26373,
"s": 26365,
"text": "Python3"
},
{
"code": null,
"e": 26376,
"s": 26373,
"text": "C#"
},
{
"code": null,
"e": 26380,
"s": 26376,
"text": "PHP"
},
{
"code": null,
"e": 26391,
"s": 26380,
"text": "Javascript"
},
{
"code": "// Simple C++ program to// find sum of all divisors// of a natural number#include<bits/stdc++.h>using namespace std; // Function to calculate sum of all//divisors of a given numberint divSum(int n){ if(n == 1) return 1; // Sum of divisors int result = 0; // find all divisors which divides 'num' for (int i = 2; i <= sqrt(n); i++) { // if 'i' is divisor of 'n' if (n % i == 0) { // if both divisors are same // then add it once else add // both if (i == (n / i)) result += i; else result += (i + n/i); } } // Add 1 and n to result as above loop // considers proper divisors greater // than 1. return (result + n + 1);} // Driver program to run the caseint main(){ int n = 30; cout << divSum(n); return 0;}",
"e": 27264,
"s": 26391,
"text": null
},
{
"code": "// Simple Java program to// find sum of all divisors// of a natural numberimport java.io.*; class GFG { // Function to calculate sum of all //divisors of a given number static int divSum(int n) { if(n == 1) return 1; // Final result of summation // of divisors int result = 0; // find all divisors which divides 'num' for (int i = 2; i <= Math.sqrt(n); i++) { // if 'i' is divisor of 'n' if (n % i == 0) { // if both divisors are same // then add it once else add // both if (i == (n / i)) result += i; else result += (i + n / i); } } // Add 1 and n to result as above loop // considers proper divisors greater // than 1. return (result + n + 1); } // Driver program to run the case public static void main(String[] args) { int n = 30; System.out.println(divSum(n)); }} // This code is contributed by Prerna Saini.",
"e": 28397,
"s": 27264,
"text": null
},
{
"code": "# Simple Python 3 program to# find sum of all divisors of# a natural numberimport math # Function to calculate sum# of all divisors of given# natural numberdef divSum(n) : if(n == 1): return 1 # Final result of summation # of divisors result = 0 # find all divisors which # divides 'num' for i in range(2,(int)(math.sqrt(n))+1) : # if 'i' is divisor of 'n' if (n % i == 0) : # if both divisors are same # then add it only once # else add both if (i == (n/i)) : result = result + i else : result = result + (i + n//i) # Add 1 and n to result as above # loop considers proper divisors # greater than 1. return (result + n + 1) # Driver program to run the casen = 30print(divSum(n)) # This code is contributed by Nikita Tiwari.",
"e": 29288,
"s": 28397,
"text": null
},
{
"code": "// Simple C# program to// find sum of all divisors// of a natural numberusing System; class GFG { // Function to calculate sum of all //divisors of a given number static int divSum(int n) { if(n == 1) return 1; // Final result of summation // of divisors int result = 0; // find all divisors which divides 'num' for (int i = 2; i <= Math.Sqrt(n); i++) { // if 'i' is divisor of 'n' if (n % i == 0) { // if both divisors are same // then add it once else add // both if (i == (n / i)) result += i; else result += (i + n / i); } } // Add 1 and n to result as above loop // considers proper divisors greater // than 1. return (result + n + 1); } // Driver program to run the case public static void Main() { int n = 30; Console.WriteLine(divSum(n)); }} // This code is contributed by vt_m.",
"e": 30402,
"s": 29288,
"text": null
},
{
"code": "<?php// Find sum of all divisors// of a natural number // Function to calculate sum of all//divisors of a given numberfunction divSum($n){ if($n == 1) return 1; // Sum of divisors $result = 0; // find all divisors // which divides 'num' for ( $i = 2; $i <= sqrt($n); $i++) { // if 'i' is divisor of 'n' if ($n % $i == 0) { // if both divisors are same // then add it once else add // both if ($i == ($n / $i)) $result += $i; else $result += ($i + $n / $i); } } // Add 1 and n to result as // above loop considers proper // divisors greater than 1. return ($result + $n + 1);} // Driver Code$n = 30;echo divSum($n); // This code is contributed by SanjuTomar.?>",
"e": 31219,
"s": 30402,
"text": null
},
{
"code": "<script> // Find sum of all divisors// of a natural number // Function to calculate sum of all//divisors of a given numberfunction divSum(n){ if(n == 1) return 1; // Sum of divisors let result = 0; // find all divisors // which divides 'num' for ( let i = 2; i <= Math.sqrt(n); i++) { // if 'i' is divisor of 'n' if (n % i == 0) { // if both divisors are same // then add it once else add // both if (i == (n / i)) result += i; else result += (i + n / i); } } // Add 1 and n to result as // above loop considers proper // divisors greater than 1. return (result + n + 1);} // Driver Codelet n = 30;document.write(divSum(n)); // This code is contributed by _saurabh_jaiswal.</script>",
"e": 32062,
"s": 31219,
"text": null
},
{
"code": null,
"e": 32073,
"s": 32062,
"text": "Output : "
},
{
"code": null,
"e": 32076,
"s": 32073,
"text": "72"
},
{
"code": null,
"e": 32303,
"s": 32076,
"text": "An efficient solution is to use below formula. Let p1, p2, ... pk be prime factors of n. Let a1, a2, .. ak be highest powers of p1, p2, .. pk respectively that divide n, i.e., we can write n as n = (p1a1)*(p2a2)* ... (pkak). "
},
{
"code": null,
"e": 32794,
"s": 32303,
"text": "Sum of divisors = (1 + p1 + p12 ... p1a1) * \n (1 + p2 + p22 ... p2a2) *\n .............................................\n (1 + pk + pk2 ... pkak) \n\nWe can notice that individual terms of above \nformula are Geometric Progressions (GP). We\ncan rewrite the formula as.\n\nSum of divisors = (p1a1+1 - 1)/(p1 -1) * \n (p2a2+1 - 1)/(p2 -1) *\n ..................................\n (pkak+1 - 1)/(pk -1)"
},
{
"code": null,
"e": 32825,
"s": 32794,
"text": "How does above formula work? "
},
{
"code": null,
"e": 33402,
"s": 32825,
"text": "Consider the number 18. \n\nSum of factors = 1 + 2 + 3 + 6 + 9 + 18\n\nWriting divisors as powers of prime factors.\nSum of factors = (20)(30) + (21)(30) + (2^0)(31) +\n (21)(31) + (20)(3^2) + (2^1)(32)\n = (20)(30) + (2^0)(31) + (2^0)(32) +\n (21)(3^0) + (21)(31) + (21)(32)\n = (20)(30 + 31 + 32) + \n (21)(30 + 31 + 32)\n = (20 + 21)(30 + 31 + 32)\nIf we take a closer look, we can notice that the\nabove expression is in the form.\n(1 + p1) * (1 + p2 + p22)\nWhere p1 = 2 and p2 = 3 and 18 = 2132"
},
{
"code": null,
"e": 33471,
"s": 33402,
"text": "So the task reduces to finding all prime factors and their powers. "
},
{
"code": null,
"e": 33475,
"s": 33471,
"text": "C++"
},
{
"code": null,
"e": 33480,
"s": 33475,
"text": "Java"
},
{
"code": null,
"e": 33488,
"s": 33480,
"text": "Python3"
},
{
"code": null,
"e": 33491,
"s": 33488,
"text": "C#"
},
{
"code": null,
"e": 33495,
"s": 33491,
"text": "PHP"
},
{
"code": null,
"e": 33506,
"s": 33495,
"text": "Javascript"
},
{
"code": "// Formula based CPP program to// find sum of all divisors of n.#include <bits/stdc++.h>using namespace std; // Returns sum of all factors of n.int sumofFactors(int n){ // Traversing through all prime factors. int res = 1; for (int i = 2; i <= sqrt(n); i++) { int curr_sum = 1; int curr_term = 1; while (n % i == 0) { // THE BELOW STATEMENT MAKES // IT BETTER THAN ABOVE METHOD // AS WE REDUCE VALUE OF n. n = n / i; curr_term *= i; curr_sum += curr_term; } res *= curr_sum; } // This condition is to handle // the case when n is a prime // number greater than 2. if (n >= 2) res *= (1 + n); return res;} // Driver codeint main(){ int n = 30; cout << sumofFactors(n); return 0;}",
"e": 34349,
"s": 33506,
"text": null
},
{
"code": "// Formula based Java program to// find sum of all divisors of n. import java.io.*;import java.math.*;public class GFG{ // Returns sum of all factors of n. static int sumofFactors(int n) { // Traversing through all prime factors. int res = 1; for (int i = 2; i <= Math.sqrt(n); i++) { int curr_sum = 1; int curr_term = 1; while (n % i == 0) { // THE BELOW STATEMENT MAKES // IT BETTER THAN ABOVE METHOD // AS WE REDUCE VALUE OF n. n = n / i; curr_term *= i; curr_sum += curr_term; } res *= curr_sum; } // This condition is to handle // the case when n is a prime // number greater than 2 if (n > 2) res *= (1 + n); return res; } // Driver code public static void main(String args[]) { int n = 30; System.out.println(sumofFactors(n)); }} /*This code is contributed by Nikita Tiwari.*/",
"e": 35475,
"s": 34349,
"text": null
},
{
"code": "# Formula based Python3 code to find# sum of all divisors of n.import math as m # Returns sum of all factors of n.def sumofFactors(n): # Traversing through all # prime factors res = 1 for i in range(2, int(m.sqrt(n) + 1)): curr_sum = 1 curr_term = 1 while n % i == 0: n = n / i; curr_term = curr_term * i; curr_sum += curr_term; res = res * curr_sum # This condition is to handle the # case when n is a prime number # greater than 2 if n > 2: res = res * (1 + n) return res; # driver code sum = sumofFactors(30)print (\"Sum of all divisors is: \",sum) # This code is contributed by Saloni Gupta",
"e": 36221,
"s": 35475,
"text": null
},
{
"code": "// Formula based Java program to// find sum of all divisors of n.using System; public class GFG { // Returns sum of all factors of n. static int sumofFactors(int n) { // Traversing through all prime factors. int res = 1; for (int i = 2; i <= Math.Sqrt(n); i++) { int curr_sum = 1; int curr_term = 1; while (n % i == 0) { // THE BELOW STATEMENT MAKES // IT BETTER THAN ABOVE METHOD // AS WE REDUCE VALUE OF n. n = n / i; curr_term *= i; curr_sum += curr_term; } res *= curr_sum; } // This condition is to handle // the case when n is a prime // number greater than 2 if (n > 2) res *= (1 + n); return res; } // Driver code public static void Main() { int n = 30; Console.WriteLine(sumofFactors(n)); }} /*This code is contributed by vt_m.*/",
"e": 37328,
"s": 36221,
"text": null
},
{
"code": "<?php// Formula based PHP program to// find sum of all divisors of n. // Returns sum of all factors of n.function sumofFactors($n){ // Traversing through // all prime factors. $res = 1; for ($i = 2; $i <= sqrt($n); $i++) { $curr_sum = 1; $curr_term = 1; while ($n % $i == 0) { // THE BELOW STATEMENT MAKES // IT BETTER THAN ABOVE METHOD // AS WE REDUCE VALUE OF n. $n = $n / $i; $curr_term *= $i; $curr_sum += $curr_term; } $res *= $curr_sum; } // This condition is to handle // the case when n is a prime // number greater than 2 if ($n > 2) $res *= (1 + $n); return $res;} // Driver Code$n = 30;echo sumofFactors($n); // This code is contributed by Anuj_67.?>",
"e": 38158,
"s": 37328,
"text": null
},
{
"code": "<script> // Formula based Javascript program to// find sum of all divisors of n. // Returns sum of all factors of n.function sumofFactors(n){ // Traversing through // all prime factors. let res = 1; for (let i = 2; i <= Math.sqrt(n); i++) { let curr_sum = 1; let curr_term = 1; while (n % i == 0) { // THE BELOW STATEMENT MAKES // IT BETTER THAN ABOVE METHOD // AS WE REDUCE VALUE OF n. n = n / i; curr_term *= i; curr_sum += curr_term; } res *= curr_sum; } // This condition is to handle // the case when n is a prime // number greater than 2 if (n > 2) res *= (1 + n); return res;} // Driver Codelet n = 30;document.write(sumofFactors(n)); // This code is contributed by _saurabh_jaiswal.</script>",
"e": 39029,
"s": 38158,
"text": null
},
{
"code": null,
"e": 39040,
"s": 39029,
"text": "Output : "
},
{
"code": null,
"e": 39043,
"s": 39040,
"text": "72"
},
{
"code": null,
"e": 39282,
"s": 39043,
"text": "Further Optimization. If there are multiple queries, we can use Sieve to find prime factors and their powers.References: https://www.math.upenn.edu/~deturck/m170/wk3/lecture/sumdiv.html http://mathforum.org/library/drmath/view/71550.html "
},
{
"code": null,
"e": 39293,
"s": 39282,
"text": "SanjuTomar"
},
{
"code": null,
"e": 39298,
"s": 39293,
"text": "vt_m"
},
{
"code": null,
"e": 39314,
"s": 39298,
"text": "arupjyoti_dutta"
},
{
"code": null,
"e": 39322,
"s": 39314,
"text": "spp____"
},
{
"code": null,
"e": 39339,
"s": 39322,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 39348,
"s": 39339,
"text": "divisors"
},
{
"code": null,
"e": 39362,
"s": 39348,
"text": "number-theory"
},
{
"code": null,
"e": 39375,
"s": 39362,
"text": "prime-factor"
},
{
"code": null,
"e": 39388,
"s": 39375,
"text": "Mathematical"
},
{
"code": null,
"e": 39402,
"s": 39388,
"text": "number-theory"
},
{
"code": null,
"e": 39415,
"s": 39402,
"text": "Mathematical"
},
{
"code": null,
"e": 39513,
"s": 39415,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 39537,
"s": 39513,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 39580,
"s": 39537,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 39594,
"s": 39580,
"text": "Prime Numbers"
},
{
"code": null,
"e": 39667,
"s": 39594,
"text": "Print all possible combinations of r elements in a given array of size n"
},
{
"code": null,
"e": 39708,
"s": 39667,
"text": "Program for Decimal to Binary Conversion"
},
{
"code": null,
"e": 39751,
"s": 39708,
"text": "The Knight's tour problem | Backtracking-1"
},
{
"code": null,
"e": 39772,
"s": 39751,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 39806,
"s": 39772,
"text": "Program for factorial of a number"
},
{
"code": null,
"e": 39859,
"s": 39806,
"text": "Find minimum number of coins that make a given value"
}
] |
Python - Convert Lists to Nested Dictionary - GeeksforGeeks | 14 May, 2020
Sometimes, while working with Python dictionaries, we can have a problem in which we need to convert list to nestings, i.e each list values representing new nested level. This kind of problem can have application in many domains including web development. Lets discuss certain way in which this task can be performed.
Method : Using zip() + list comprehensionThe combination of above functions can be combined to perform this task. In this, we iterate for zipped list and render the nested dictionaries using list comprehension.
# Python3 code to demonstrate working of # Convert Lists to Nestings Dictionary# Using list comprehension + zip() # initializing listtest_list1 = ["gfg", 'is', 'best']test_list2 = ['ratings', 'price', 'score']test_list3 = [5, 6, 7] # printing original listprint("The original list 1 is : " + str(test_list1))print("The original list 2 is : " + str(test_list2))print("The original list 3 is : " + str(test_list3)) # Convert Lists to Nestings Dictionary# Using list comprehension + zip()res = [{a: {b: c}} for (a, b, c) in zip(test_list1, test_list2, test_list3)] # printing result print("The constructed dictionary : " + str(res))
The original list 1 is : ['gfg', 'is', 'best']
The original list 2 is : ['ratings', 'price', 'score']
The original list 3 is : [5, 6, 7]
The constructed dictionary : [{'gfg': {'ratings': 5}}, {'is': {'price': 6}}, {'best': {'score': 7}}]
Python list-programs
Python-nested-dictionary
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
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
Convert integer to string in Python | [
{
"code": null,
"e": 25589,
"s": 25561,
"text": "\n14 May, 2020"
},
{
"code": null,
"e": 25907,
"s": 25589,
"text": "Sometimes, while working with Python dictionaries, we can have a problem in which we need to convert list to nestings, i.e each list values representing new nested level. This kind of problem can have application in many domains including web development. Lets discuss certain way in which this task can be performed."
},
{
"code": null,
"e": 26118,
"s": 25907,
"text": "Method : Using zip() + list comprehensionThe combination of above functions can be combined to perform this task. In this, we iterate for zipped list and render the nested dictionaries using list comprehension."
},
{
"code": "# Python3 code to demonstrate working of # Convert Lists to Nestings Dictionary# Using list comprehension + zip() # initializing listtest_list1 = [\"gfg\", 'is', 'best']test_list2 = ['ratings', 'price', 'score']test_list3 = [5, 6, 7] # printing original listprint(\"The original list 1 is : \" + str(test_list1))print(\"The original list 2 is : \" + str(test_list2))print(\"The original list 3 is : \" + str(test_list3)) # Convert Lists to Nestings Dictionary# Using list comprehension + zip()res = [{a: {b: c}} for (a, b, c) in zip(test_list1, test_list2, test_list3)] # printing result print(\"The constructed dictionary : \" + str(res)) ",
"e": 26753,
"s": 26118,
"text": null
},
{
"code": null,
"e": 26992,
"s": 26753,
"text": "The original list 1 is : ['gfg', 'is', 'best']\nThe original list 2 is : ['ratings', 'price', 'score']\nThe original list 3 is : [5, 6, 7]\nThe constructed dictionary : [{'gfg': {'ratings': 5}}, {'is': {'price': 6}}, {'best': {'score': 7}}]\n"
},
{
"code": null,
"e": 27015,
"s": 26994,
"text": "Python list-programs"
},
{
"code": null,
"e": 27040,
"s": 27015,
"text": "Python-nested-dictionary"
},
{
"code": null,
"e": 27047,
"s": 27040,
"text": "Python"
},
{
"code": null,
"e": 27145,
"s": 27047,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27180,
"s": 27145,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 27212,
"s": 27180,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27234,
"s": 27212,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27276,
"s": 27234,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27306,
"s": 27276,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 27332,
"s": 27306,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27361,
"s": 27332,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 27405,
"s": 27361,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 27442,
"s": 27405,
"text": "Create a Pandas DataFrame from Lists"
}
] |
Print all perfect squares from the given range - GeeksforGeeks | 08 Apr, 2021
Given a range [L, R], the task is to print all the perfect squares from the given range.Examples:
Input: L = 2, R = 24 Output: 4 9 16Input: L = 1, R = 100 Output: 1 4 9 16 25 36 49 64 81 100
Naive approach: Starting from L to R check whether the current element is a perfect square or not. If yes then print it.Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to print all the perfect// squares from the given rangevoid perfectSquares(float l, float r){ // For every element from the range for (int i = l; i <= r; i++) { // If current element is // a perfect square if (sqrt(i) == (int)sqrt(i)) cout << i << " "; }} // Driver codeint main(){ int l = 2, r = 24; perfectSquares(l, r); return 0;}
//Java implementation of the approachimport java.io.*; class GFG{ // Function to print all the perfect// squares from the given rangestatic void perfectSquares(int l, int r){ // For every element from the range for (int i = l; i <= r; i++) { // If current element is // a perfect square if (Math.sqrt(i) == (int)Math.sqrt(i)) System.out.print(i + " "); }} // Driver codepublic static void main (String[] args){ int l = 2, r = 24; perfectSquares(l, r);}} // This code is contributed by jit_t
# Python3 implementation of the approach # Function to print all the perfect# squares from the given rangedef perfectSquares(l, r): # For every element from the range for i in range(l, r + 1): # If current element is # a perfect square if (i**(.5) == int(i**(.5))): print(i, end=" ") # Driver codel = 2r = 24 perfectSquares(l, r) # This code is contributed by mohit kumar 29
// C# implementation of the approachusing System; class GFG{ // Function to print all the perfect// squares from the given rangestatic void perfectSquares(int l, int r){ // For every element from the range for (int i = l; i <= r; i++) { // If current element is // a perfect square if (Math.Sqrt(i) == (int)Math.Sqrt(i)) Console.Write(i + " "); }} // Driver codepublic static void Main(String[] args){ int l = 2, r = 24; perfectSquares(l, r);}} // This code is contributed by 29AjayKumar
<script>// js implementation of the approach // Function to print all the perfect// squares from the given rangefunction perfectSquares(l, r){ //For every element from the range for (let i = l; i <= r; i++) { // If current element is // a perfect square if (Math.sqrt(i) == parseInt(Math.sqrt(i))) document.write(i + " "); }} // Driver codelet l = 2;let r = 24;perfectSquares(l, r) // This code is contributed by sravan.</script>
4 9 16
It is solution with O(n). moreover the use of number of square roots leads to computational expense.Efficient approach: This method is based on the fact that the very first perfect square after number L will definitely be the square of ⌈sqrt(L)⌉. In very simple terms, the square root of L will be very close to the number whose square root we are trying to find. Therefore, the number will be pow(ceil(sqrt(L)), 2). The very first perfect square is important for this method. Now the original answer is hidden over this pattern i.e. 0 1 4 9 16 25 the difference between 0 and 1 is 1 the difference between 1 and 4 is 3 the difference between 4 and 9 is 5 and so on... which means that the difference between two perfect squares is always an odd number.Now, the question arises what must be added to get the next number and the answer is (sqrt(X) * 2) + 1 where X is the already known perfect square.Let the current perfect square be 4 then the next perfect square will definitely be 4 + (sqrt(4) * 2 + 1) = 9. Here, number 5 is added and the next number to be added will be 7 then 9 and so on... which makes a series of odd numbers.Addition is computationally less expensive than performing multiplication or finding square roots of every number.Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to print all the perfect// squares from the given rangevoid perfectSquares(float l, float r){ // Getting the very first number int number = ceil(sqrt(l)); // First number's square int n2 = number * number; // Next number is at the difference of number = (number * 2) + 1; // While the perfect squares // are from the range while ((n2 >= l && n2 <= r)) { // Print the perfect square cout << n2 << " "; // Get the next perfect square n2 = n2 + number; // Next odd number to be added number += 2; }} // Driver codeint main(){ int l = 2, r = 24; perfectSquares(l, r); return 0;}
// Java implementation of the approachclass GFG{ // Function to print all the perfect// squares from the given rangestatic void perfectSquares(float l, float r){ // Getting the very first number int number = (int) Math.ceil(Math.sqrt(l)); // First number's square int n2 = number * number; // Next number is at the difference of number = (number * 2) + 1; // While the perfect squares // are from the range while ((n2 >= l && n2 <= r)) { // Print the perfect square System.out.print(n2 + " "); // Get the next perfect square n2 = n2 + number; // Next odd number to be added number += 2; }} // Driver codepublic static void main(String[] args){ int l = 2, r = 24; perfectSquares(l, r); }} // This code is contributed by 29AjayKumar
# Python3 implementation of the approach from math import ceil, sqrt # Function to print all the perfect# squares from the given rangedef perfectSquares(l, r) : # Getting the very first number number = ceil(sqrt(l)); # First number's square n2 = number * number; # Next number is at the difference of number = (number * 2) + 1; # While the perfect squares # are from the range while ((n2 >= l and n2 <= r)) : # Print the perfect square print(n2, end= " "); # Get the next perfect square n2 = n2 + number; # Next odd number to be added number += 2; # Driver codeif __name__ == "__main__" : l = 2; r = 24; perfectSquares(l, r); # This code is contributed by AnkitRai01
// C# implementation of the approachusing System; class GFG{ // Function to print all the perfect// squares from the given rangestatic void perfectSquares(float l, float r){ // Getting the very first number int number = (int) Math.Ceiling(Math.Sqrt(l)); // First number's square int n2 = number * number; // Next number is at the difference of number = (number * 2) + 1; // While the perfect squares // are from the range while ((n2 >= l && n2 <= r)) { // Print the perfect square Console.Write(n2 + " "); // Get the next perfect square n2 = n2 + number; // Next odd number to be added number += 2; }} // Driver codepublic static void Main(String[] args){ int l = 2, r = 24; perfectSquares(l, r);}} // This code is contributed by Rajput Ji
<script>// Javascript implementation of the approach // Function to print all the perfect// squares from the given rangefunction perfectSquares(l, r){ // Getting the very first number let number = Math.ceil(Math.sqrt(l)); // First number's square let n2 = number * number; // Next number is at the difference of number = (number * 2) + 1; // While the perfect squares // are from the range while ((n2 >= l && n2 <= r)) { // Print the perfect square document.write(n2 + " "); // Get the next perfect square n2 = n2 + number; // Next odd number to be added number += 2; }} // Driver codelet l = 2, r = 24; perfectSquares(l, r); // This code is contributed by subhammahato348</script>
4 9 16
mohit kumar 29
jit_t
ankthon
29AjayKumar
Rajput-Ji
sravankumar8128
subhammahato348
maths-perfect-square
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Modulo Operator (%) in C/C++ with Examples
Prime Numbers
Program to find GCD or HCF of two numbers
Sieve of Eratosthenes
Print all possible combinations of r elements in a given array of size n
Operators in C / C++
The Knight's tour problem | Backtracking-1
Program for factorial of a number
Program for Decimal to Binary Conversion | [
{
"code": null,
"e": 26524,
"s": 26496,
"text": "\n08 Apr, 2021"
},
{
"code": null,
"e": 26624,
"s": 26524,
"text": "Given a range [L, R], the task is to print all the perfect squares from the given range.Examples: "
},
{
"code": null,
"e": 26719,
"s": 26624,
"text": "Input: L = 2, R = 24 Output: 4 9 16Input: L = 1, R = 100 Output: 1 4 9 16 25 36 49 64 81 100 "
},
{
"code": null,
"e": 26894,
"s": 26721,
"text": "Naive approach: Starting from L to R check whether the current element is a perfect square or not. If yes then print it.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26898,
"s": 26894,
"text": "C++"
},
{
"code": null,
"e": 26903,
"s": 26898,
"text": "Java"
},
{
"code": null,
"e": 26911,
"s": 26903,
"text": "Python3"
},
{
"code": null,
"e": 26914,
"s": 26911,
"text": "C#"
},
{
"code": null,
"e": 26925,
"s": 26914,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to print all the perfect// squares from the given rangevoid perfectSquares(float l, float r){ // For every element from the range for (int i = l; i <= r; i++) { // If current element is // a perfect square if (sqrt(i) == (int)sqrt(i)) cout << i << \" \"; }} // Driver codeint main(){ int l = 2, r = 24; perfectSquares(l, r); return 0;}",
"e": 27407,
"s": 26925,
"text": null
},
{
"code": "//Java implementation of the approachimport java.io.*; class GFG{ // Function to print all the perfect// squares from the given rangestatic void perfectSquares(int l, int r){ // For every element from the range for (int i = l; i <= r; i++) { // If current element is // a perfect square if (Math.sqrt(i) == (int)Math.sqrt(i)) System.out.print(i + \" \"); }} // Driver codepublic static void main (String[] args){ int l = 2, r = 24; perfectSquares(l, r);}} // This code is contributed by jit_t",
"e": 27954,
"s": 27407,
"text": null
},
{
"code": "# Python3 implementation of the approach # Function to print all the perfect# squares from the given rangedef perfectSquares(l, r): # For every element from the range for i in range(l, r + 1): # If current element is # a perfect square if (i**(.5) == int(i**(.5))): print(i, end=\" \") # Driver codel = 2r = 24 perfectSquares(l, r) # This code is contributed by mohit kumar 29",
"e": 28369,
"s": 27954,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ // Function to print all the perfect// squares from the given rangestatic void perfectSquares(int l, int r){ // For every element from the range for (int i = l; i <= r; i++) { // If current element is // a perfect square if (Math.Sqrt(i) == (int)Math.Sqrt(i)) Console.Write(i + \" \"); }} // Driver codepublic static void Main(String[] args){ int l = 2, r = 24; perfectSquares(l, r);}} // This code is contributed by 29AjayKumar",
"e": 28913,
"s": 28369,
"text": null
},
{
"code": "<script>// js implementation of the approach // Function to print all the perfect// squares from the given rangefunction perfectSquares(l, r){ //For every element from the range for (let i = l; i <= r; i++) { // If current element is // a perfect square if (Math.sqrt(i) == parseInt(Math.sqrt(i))) document.write(i + \" \"); }} // Driver codelet l = 2;let r = 24;perfectSquares(l, r) // This code is contributed by sravan.</script>",
"e": 29391,
"s": 28913,
"text": null
},
{
"code": null,
"e": 29398,
"s": 29391,
"text": "4 9 16"
},
{
"code": null,
"e": 30700,
"s": 29400,
"text": "It is solution with O(n). moreover the use of number of square roots leads to computational expense.Efficient approach: This method is based on the fact that the very first perfect square after number L will definitely be the square of ⌈sqrt(L)⌉. In very simple terms, the square root of L will be very close to the number whose square root we are trying to find. Therefore, the number will be pow(ceil(sqrt(L)), 2). The very first perfect square is important for this method. Now the original answer is hidden over this pattern i.e. 0 1 4 9 16 25 the difference between 0 and 1 is 1 the difference between 1 and 4 is 3 the difference between 4 and 9 is 5 and so on... which means that the difference between two perfect squares is always an odd number.Now, the question arises what must be added to get the next number and the answer is (sqrt(X) * 2) + 1 where X is the already known perfect square.Let the current perfect square be 4 then the next perfect square will definitely be 4 + (sqrt(4) * 2 + 1) = 9. Here, number 5 is added and the next number to be added will be 7 then 9 and so on... which makes a series of odd numbers.Addition is computationally less expensive than performing multiplication or finding square roots of every number.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 30704,
"s": 30700,
"text": "C++"
},
{
"code": null,
"e": 30709,
"s": 30704,
"text": "Java"
},
{
"code": null,
"e": 30717,
"s": 30709,
"text": "Python3"
},
{
"code": null,
"e": 30720,
"s": 30717,
"text": "C#"
},
{
"code": null,
"e": 30731,
"s": 30720,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to print all the perfect// squares from the given rangevoid perfectSquares(float l, float r){ // Getting the very first number int number = ceil(sqrt(l)); // First number's square int n2 = number * number; // Next number is at the difference of number = (number * 2) + 1; // While the perfect squares // are from the range while ((n2 >= l && n2 <= r)) { // Print the perfect square cout << n2 << \" \"; // Get the next perfect square n2 = n2 + number; // Next odd number to be added number += 2; }} // Driver codeint main(){ int l = 2, r = 24; perfectSquares(l, r); return 0;}",
"e": 31490,
"s": 30731,
"text": null
},
{
"code": "// Java implementation of the approachclass GFG{ // Function to print all the perfect// squares from the given rangestatic void perfectSquares(float l, float r){ // Getting the very first number int number = (int) Math.ceil(Math.sqrt(l)); // First number's square int n2 = number * number; // Next number is at the difference of number = (number * 2) + 1; // While the perfect squares // are from the range while ((n2 >= l && n2 <= r)) { // Print the perfect square System.out.print(n2 + \" \"); // Get the next perfect square n2 = n2 + number; // Next odd number to be added number += 2; }} // Driver codepublic static void main(String[] args){ int l = 2, r = 24; perfectSquares(l, r); }} // This code is contributed by 29AjayKumar",
"e": 32310,
"s": 31490,
"text": null
},
{
"code": "# Python3 implementation of the approach from math import ceil, sqrt # Function to print all the perfect# squares from the given rangedef perfectSquares(l, r) : # Getting the very first number number = ceil(sqrt(l)); # First number's square n2 = number * number; # Next number is at the difference of number = (number * 2) + 1; # While the perfect squares # are from the range while ((n2 >= l and n2 <= r)) : # Print the perfect square print(n2, end= \" \"); # Get the next perfect square n2 = n2 + number; # Next odd number to be added number += 2; # Driver codeif __name__ == \"__main__\" : l = 2; r = 24; perfectSquares(l, r); # This code is contributed by AnkitRai01",
"e": 33062,
"s": 32310,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ // Function to print all the perfect// squares from the given rangestatic void perfectSquares(float l, float r){ // Getting the very first number int number = (int) Math.Ceiling(Math.Sqrt(l)); // First number's square int n2 = number * number; // Next number is at the difference of number = (number * 2) + 1; // While the perfect squares // are from the range while ((n2 >= l && n2 <= r)) { // Print the perfect square Console.Write(n2 + \" \"); // Get the next perfect square n2 = n2 + number; // Next odd number to be added number += 2; }} // Driver codepublic static void Main(String[] args){ int l = 2, r = 24; perfectSquares(l, r);}} // This code is contributed by Rajput Ji",
"e": 33891,
"s": 33062,
"text": null
},
{
"code": "<script>// Javascript implementation of the approach // Function to print all the perfect// squares from the given rangefunction perfectSquares(l, r){ // Getting the very first number let number = Math.ceil(Math.sqrt(l)); // First number's square let n2 = number * number; // Next number is at the difference of number = (number * 2) + 1; // While the perfect squares // are from the range while ((n2 >= l && n2 <= r)) { // Print the perfect square document.write(n2 + \" \"); // Get the next perfect square n2 = n2 + number; // Next odd number to be added number += 2; }} // Driver codelet l = 2, r = 24; perfectSquares(l, r); // This code is contributed by subhammahato348</script>",
"e": 34652,
"s": 33891,
"text": null
},
{
"code": null,
"e": 34659,
"s": 34652,
"text": "4 9 16"
},
{
"code": null,
"e": 34676,
"s": 34661,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 34682,
"s": 34676,
"text": "jit_t"
},
{
"code": null,
"e": 34690,
"s": 34682,
"text": "ankthon"
},
{
"code": null,
"e": 34702,
"s": 34690,
"text": "29AjayKumar"
},
{
"code": null,
"e": 34712,
"s": 34702,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 34728,
"s": 34712,
"text": "sravankumar8128"
},
{
"code": null,
"e": 34744,
"s": 34728,
"text": "subhammahato348"
},
{
"code": null,
"e": 34765,
"s": 34744,
"text": "maths-perfect-square"
},
{
"code": null,
"e": 34778,
"s": 34765,
"text": "Mathematical"
},
{
"code": null,
"e": 34791,
"s": 34778,
"text": "Mathematical"
},
{
"code": null,
"e": 34889,
"s": 34791,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34913,
"s": 34889,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 34956,
"s": 34913,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 34970,
"s": 34956,
"text": "Prime Numbers"
},
{
"code": null,
"e": 35012,
"s": 34970,
"text": "Program to find GCD or HCF of two numbers"
},
{
"code": null,
"e": 35034,
"s": 35012,
"text": "Sieve of Eratosthenes"
},
{
"code": null,
"e": 35107,
"s": 35034,
"text": "Print all possible combinations of r elements in a given array of size n"
},
{
"code": null,
"e": 35128,
"s": 35107,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 35171,
"s": 35128,
"text": "The Knight's tour problem | Backtracking-1"
},
{
"code": null,
"e": 35205,
"s": 35171,
"text": "Program for factorial of a number"
}
] |
What is NULL ? Give an example to illustrate testing for NULL in SQL. What is dangling tuple problem ? - GeeksforGeeks | 03 Nov, 2021
What is NULL ?In Structured Query Language Null Or NULL is a special type of marker which is used to tell us about that a data value does not present in the database. In Structured Query Language (SQL) Null is a predefined word which is used to identity this marker. It is very important to understand that a NULL value is totally different than a zero value.
In other words we can say that a NULL attribute value is equivalent of nothing that means in database there is an attribute that has a value which indicates nothing or Null, An attributes does not exist or we can say that it is missing . In database a Null value in tables is that value in the fields that appears to be blank. It is a field that has no value.
An Example to illustrate testing for NULL in SQL :Suppose there is a table named as CUSTOMERS that having records as given below.
Now we can use IS NOT NULL operator and write a query which is as following.
SQL> SELECT *
FROM CUSTOMERS
WHERE SALARY IS NOT NULL;
After execution this query would produce the following result-
Here we can see that in CUSTOMERS table , ID no. 6 and 7 which is named as NAMAN and AYUSH and their salary column is empty and in other words it is Null . That’s why after query execution it would produce a table where these two names NAMAN and AYUSH not present because we use IS NOT NULL operator.
Now we can use IS NULL operator and write a query.
SQL> SELECT *
FROM CUSTOMERS
WHERE SALARY IS NULL;
After execution this query would produce the following results-
Here we can that in CUSTOMERS table , ID no. 6 and 7 which is named as NAMAN and AYUSH and their salary column is empty and in other words it is Null. That’s why after query execution it would produce a table where these two names NAMAN and AYUSH not present because we use IS NULL operator.
What is Dangling tuple problem?In DBMS if there is a tuple that does not participate in a natural join we called it as dangling tuple . It may gives indication consistency problem in the database.
Another definition of dangling problem tuple is that a tuple with a foreign key value that not appear in the referenced relation is known as dangling tuple. In DBMS Referential integrity constraints specify us exactly when dangling tuples indicate problem.
DBMS-SQL
DBMS
SQL
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Deadlock in DBMS
Types of Functional dependencies in DBMS
KDD Process in Data Mining
Conflict Serializability in DBMS
Two Phase Locking Protocol
SQL | DDL, DQL, DML, DCL and TCL Commands
How to find Nth highest salary from a table
SQL | ALTER (RENAME)
How to Update Multiple Columns in Single Update Statement in SQL?
MySQL | Group_CONCAT() Function | [
{
"code": null,
"e": 25575,
"s": 25547,
"text": "\n03 Nov, 2021"
},
{
"code": null,
"e": 25935,
"s": 25575,
"text": "What is NULL ?In Structured Query Language Null Or NULL is a special type of marker which is used to tell us about that a data value does not present in the database. In Structured Query Language (SQL) Null is a predefined word which is used to identity this marker. It is very important to understand that a NULL value is totally different than a zero value."
},
{
"code": null,
"e": 26295,
"s": 25935,
"text": "In other words we can say that a NULL attribute value is equivalent of nothing that means in database there is an attribute that has a value which indicates nothing or Null, An attributes does not exist or we can say that it is missing . In database a Null value in tables is that value in the fields that appears to be blank. It is a field that has no value."
},
{
"code": null,
"e": 26425,
"s": 26295,
"text": "An Example to illustrate testing for NULL in SQL :Suppose there is a table named as CUSTOMERS that having records as given below."
},
{
"code": null,
"e": 26502,
"s": 26425,
"text": "Now we can use IS NOT NULL operator and write a query which is as following."
},
{
"code": null,
"e": 26559,
"s": 26502,
"text": "SQL> SELECT * \nFROM CUSTOMERS \nWHERE SALARY IS NOT NULL;"
},
{
"code": null,
"e": 26622,
"s": 26559,
"text": "After execution this query would produce the following result-"
},
{
"code": null,
"e": 26923,
"s": 26622,
"text": "Here we can see that in CUSTOMERS table , ID no. 6 and 7 which is named as NAMAN and AYUSH and their salary column is empty and in other words it is Null . That’s why after query execution it would produce a table where these two names NAMAN and AYUSH not present because we use IS NOT NULL operator."
},
{
"code": null,
"e": 26974,
"s": 26923,
"text": "Now we can use IS NULL operator and write a query."
},
{
"code": null,
"e": 27027,
"s": 26974,
"text": "SQL> SELECT * \nFROM CUSTOMERS \nWHERE SALARY IS NULL;"
},
{
"code": null,
"e": 27091,
"s": 27027,
"text": "After execution this query would produce the following results-"
},
{
"code": null,
"e": 27383,
"s": 27091,
"text": "Here we can that in CUSTOMERS table , ID no. 6 and 7 which is named as NAMAN and AYUSH and their salary column is empty and in other words it is Null. That’s why after query execution it would produce a table where these two names NAMAN and AYUSH not present because we use IS NULL operator."
},
{
"code": null,
"e": 27580,
"s": 27383,
"text": "What is Dangling tuple problem?In DBMS if there is a tuple that does not participate in a natural join we called it as dangling tuple . It may gives indication consistency problem in the database."
},
{
"code": null,
"e": 27839,
"s": 27580,
"text": "Another definition of dangling problem tuple is that a tuple with a foreign key value that not appear in the referenced relation is known as dangling tuple. In DBMS Referential integrity constraints specify us exactly when dangling tuples indicate problem. "
},
{
"code": null,
"e": 27848,
"s": 27839,
"text": "DBMS-SQL"
},
{
"code": null,
"e": 27853,
"s": 27848,
"text": "DBMS"
},
{
"code": null,
"e": 27857,
"s": 27853,
"text": "SQL"
},
{
"code": null,
"e": 27862,
"s": 27857,
"text": "DBMS"
},
{
"code": null,
"e": 27866,
"s": 27862,
"text": "SQL"
},
{
"code": null,
"e": 27964,
"s": 27866,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27981,
"s": 27964,
"text": "Deadlock in DBMS"
},
{
"code": null,
"e": 28022,
"s": 27981,
"text": "Types of Functional dependencies in DBMS"
},
{
"code": null,
"e": 28049,
"s": 28022,
"text": "KDD Process in Data Mining"
},
{
"code": null,
"e": 28082,
"s": 28049,
"text": "Conflict Serializability in DBMS"
},
{
"code": null,
"e": 28109,
"s": 28082,
"text": "Two Phase Locking Protocol"
},
{
"code": null,
"e": 28151,
"s": 28109,
"text": "SQL | DDL, DQL, DML, DCL and TCL Commands"
},
{
"code": null,
"e": 28195,
"s": 28151,
"text": "How to find Nth highest salary from a table"
},
{
"code": null,
"e": 28216,
"s": 28195,
"text": "SQL | ALTER (RENAME)"
},
{
"code": null,
"e": 28282,
"s": 28216,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
}
] |
Java Program to Print the ASCII Value - GeeksforGeeks | 28 Dec, 2021
ASCII is an acronym that stands for American Standard Code for Information Interchange. In ASCII, a specific numerical value is given to different characters and symbols, for computers to store and manipulate, and while storing and manipulating the electronic device always works with the binary value of the ASCII number given. As it is impossible to do that in the original form.
Approaches: There are 4 ways to print ASCII value or code of a specific character which are listed below briefing the concept followed by a java example for the implementation part.
Using brute force Method Using the type-casting MethodUsing the format specifier MethodUsing Byte class Method
Using brute force Method
Using the type-casting Method
Using the format specifier Method
Using Byte class Method
Method 1: Assigning a Variable to the int Variable
In order to find the ASCII value of a character, simply assign the character to a new variable of integer type. Java automatically stores the ASCII value of that character inside the new variable.
Implementation: Brute force Method
Java
// Java program to print ASCII Value of Character// by assigning variable to integer public class GFG { // Main driver method public static void main(String[] args) { // Character whose ASCII is to be computed char ch = '}'; // Creating a new variable of type int // and assigning the character value. int ascii = ch; /* Java stores the ascii value there itself*/ // Printing the ASCII value of above character System.out.println("The ASCII value of " + ch + " is: " + ascii); }}
The ASCII value of } is: 125
Method 2: Using Type-Casting
Type-casting in java is a way to cast a variable into another datatype which means holding a value of another datatype occupying lesser bytes. In this approach, a character is a typecast of type char to the type int while printing, and it will print the ASCII value of the character.
Java
// Java program to print ASCII Value of Character// using type-casting // Importing java generic librariesimport java.util.*; public class GFG { // Main driver method public static void main(String[] args) { // Character whose ASCII is to be computed char ch = '}'; // Typecasting the character to int and // printing the same System.out.println("The ASCII value of " + ch + " is: " + (int)ch); }}
The ASCII value of } is: 125
Note: In above method 1 and method 2, both the methods are one type of typecasting. In method 1, typecasting is done automatically by the compiler. In method 2, typecasting it manually so the method 2 is much more efficient than method 1 as the compiler has to put lesser effort. Also, remember typecasting done automatically is called implicit typecasting and where it is done from the user end is called explicit typecasting
Method 3: Using format specifier (More Optimal)
In this approach, we generate the ASCII value of the given character with the help of a format specifier. We have stored the value of the given character inside a formal specifier by specifying the character to be an int. Hence, the ASCII value of that character is stored inside the format specifier.
Java
// Java program to print ASCII Value of Character// using format specifier // Importing format libraryimport java.util.Formatter; public class GFG { // Main driver method public static void main(String[] args) { // Character whose ASCII is to compute char character = '}'; // Initializing the format specifier Formatter formatSpecifier = new Formatter(); // Converting the character to integer and // ASCII value is stored in the format specifier formatSpecifier.format("%d", (int)character); // Print the corresponding ASCII value System.out.println( "The ASCII value of the character ' " + character + " ' is " + formatSpecifier); }}
The ASCII value of the character ' } ' is 125
Method 4: Finding the ASCII value by generating byte (Most Optimal)
Initializing the character as a string.Creating an array of type byte by using getBytes() method.Printing the element at ‘0’th index of the bytes array.
Initializing the character as a string.
Creating an array of type byte by using getBytes() method.
Printing the element at ‘0’th index of the bytes array.
This is the ASCII value of our character residing at the ‘0’th index of the string. This method is generally used to convert a whole string to their ASCII values. For the characters violating the encoding exception, the try-catch is given.
Java
// Java program to print ASCII Value of Character// by generating bytes. // Importing I/O libraryimport java.io.UnsupportedEncodingException; public class GFG { // Main driver method public static void main(String[] args) { // Try block to check exception try { // Character is initiated as a string String sp = "}"; // An array of byte type is created // by using getBytes method byte[] bytes = sp.getBytes("US-ASCII"); /*This is the ASCII value of the character / present at the '0'th index of above string.*/ // Printing the element at '0'th index // of array(bytes) using charAt() method System.out.println("The ASCII value of " + sp.charAt(0) + " is " + bytes[0]); } // Catch block to handle exception catch (UnsupportedEncodingException e) { // Message printed for exception System.out.println("OOPs!!!UnsupportedEncodingException occurs."); } }}
The ASCII value of } is 125
rkbhola5
Picked
Technical Scripter 2020
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
Program to print ASCII Value of a character | [
{
"code": null,
"e": 25250,
"s": 25222,
"text": "\n28 Dec, 2021"
},
{
"code": null,
"e": 25632,
"s": 25250,
"text": "ASCII is an acronym that stands for American Standard Code for Information Interchange. In ASCII, a specific numerical value is given to different characters and symbols, for computers to store and manipulate, and while storing and manipulating the electronic device always works with the binary value of the ASCII number given. As it is impossible to do that in the original form."
},
{
"code": null,
"e": 25814,
"s": 25632,
"text": "Approaches: There are 4 ways to print ASCII value or code of a specific character which are listed below briefing the concept followed by a java example for the implementation part."
},
{
"code": null,
"e": 25925,
"s": 25814,
"text": "Using brute force Method Using the type-casting MethodUsing the format specifier MethodUsing Byte class Method"
},
{
"code": null,
"e": 25951,
"s": 25925,
"text": "Using brute force Method "
},
{
"code": null,
"e": 25981,
"s": 25951,
"text": "Using the type-casting Method"
},
{
"code": null,
"e": 26015,
"s": 25981,
"text": "Using the format specifier Method"
},
{
"code": null,
"e": 26039,
"s": 26015,
"text": "Using Byte class Method"
},
{
"code": null,
"e": 26090,
"s": 26039,
"text": "Method 1: Assigning a Variable to the int Variable"
},
{
"code": null,
"e": 26287,
"s": 26090,
"text": "In order to find the ASCII value of a character, simply assign the character to a new variable of integer type. Java automatically stores the ASCII value of that character inside the new variable."
},
{
"code": null,
"e": 26322,
"s": 26287,
"text": "Implementation: Brute force Method"
},
{
"code": null,
"e": 26327,
"s": 26322,
"text": "Java"
},
{
"code": "// Java program to print ASCII Value of Character// by assigning variable to integer public class GFG { // Main driver method public static void main(String[] args) { // Character whose ASCII is to be computed char ch = '}'; // Creating a new variable of type int // and assigning the character value. int ascii = ch; /* Java stores the ascii value there itself*/ // Printing the ASCII value of above character System.out.println(\"The ASCII value of \" + ch + \" is: \" + ascii); }}",
"e": 26905,
"s": 26327,
"text": null
},
{
"code": null,
"e": 26934,
"s": 26905,
"text": "The ASCII value of } is: 125"
},
{
"code": null,
"e": 26964,
"s": 26934,
"text": "Method 2: Using Type-Casting "
},
{
"code": null,
"e": 27248,
"s": 26964,
"text": "Type-casting in java is a way to cast a variable into another datatype which means holding a value of another datatype occupying lesser bytes. In this approach, a character is a typecast of type char to the type int while printing, and it will print the ASCII value of the character."
},
{
"code": null,
"e": 27253,
"s": 27248,
"text": "Java"
},
{
"code": "// Java program to print ASCII Value of Character// using type-casting // Importing java generic librariesimport java.util.*; public class GFG { // Main driver method public static void main(String[] args) { // Character whose ASCII is to be computed char ch = '}'; // Typecasting the character to int and // printing the same System.out.println(\"The ASCII value of \" + ch + \" is: \" + (int)ch); }}",
"e": 27726,
"s": 27253,
"text": null
},
{
"code": null,
"e": 27755,
"s": 27726,
"text": "The ASCII value of } is: 125"
},
{
"code": null,
"e": 28184,
"s": 27755,
"text": "Note: In above method 1 and method 2, both the methods are one type of typecasting. In method 1, typecasting is done automatically by the compiler. In method 2, typecasting it manually so the method 2 is much more efficient than method 1 as the compiler has to put lesser effort. Also, remember typecasting done automatically is called implicit typecasting and where it is done from the user end is called explicit typecasting "
},
{
"code": null,
"e": 28232,
"s": 28184,
"text": "Method 3: Using format specifier (More Optimal)"
},
{
"code": null,
"e": 28534,
"s": 28232,
"text": "In this approach, we generate the ASCII value of the given character with the help of a format specifier. We have stored the value of the given character inside a formal specifier by specifying the character to be an int. Hence, the ASCII value of that character is stored inside the format specifier."
},
{
"code": null,
"e": 28539,
"s": 28534,
"text": "Java"
},
{
"code": "// Java program to print ASCII Value of Character// using format specifier // Importing format libraryimport java.util.Formatter; public class GFG { // Main driver method public static void main(String[] args) { // Character whose ASCII is to compute char character = '}'; // Initializing the format specifier Formatter formatSpecifier = new Formatter(); // Converting the character to integer and // ASCII value is stored in the format specifier formatSpecifier.format(\"%d\", (int)character); // Print the corresponding ASCII value System.out.println( \"The ASCII value of the character ' \" + character + \" ' is \" + formatSpecifier); }}",
"e": 29276,
"s": 28539,
"text": null
},
{
"code": null,
"e": 29322,
"s": 29276,
"text": "The ASCII value of the character ' } ' is 125"
},
{
"code": null,
"e": 29391,
"s": 29322,
"text": "Method 4: Finding the ASCII value by generating byte (Most Optimal) "
},
{
"code": null,
"e": 29544,
"s": 29391,
"text": "Initializing the character as a string.Creating an array of type byte by using getBytes() method.Printing the element at ‘0’th index of the bytes array."
},
{
"code": null,
"e": 29584,
"s": 29544,
"text": "Initializing the character as a string."
},
{
"code": null,
"e": 29643,
"s": 29584,
"text": "Creating an array of type byte by using getBytes() method."
},
{
"code": null,
"e": 29699,
"s": 29643,
"text": "Printing the element at ‘0’th index of the bytes array."
},
{
"code": null,
"e": 29939,
"s": 29699,
"text": "This is the ASCII value of our character residing at the ‘0’th index of the string. This method is generally used to convert a whole string to their ASCII values. For the characters violating the encoding exception, the try-catch is given."
},
{
"code": null,
"e": 29944,
"s": 29939,
"text": "Java"
},
{
"code": "// Java program to print ASCII Value of Character// by generating bytes. // Importing I/O libraryimport java.io.UnsupportedEncodingException; public class GFG { // Main driver method public static void main(String[] args) { // Try block to check exception try { // Character is initiated as a string String sp = \"}\"; // An array of byte type is created // by using getBytes method byte[] bytes = sp.getBytes(\"US-ASCII\"); /*This is the ASCII value of the character / present at the '0'th index of above string.*/ // Printing the element at '0'th index // of array(bytes) using charAt() method System.out.println(\"The ASCII value of \" + sp.charAt(0) + \" is \" + bytes[0]); } // Catch block to handle exception catch (UnsupportedEncodingException e) { // Message printed for exception System.out.println(\"OOPs!!!UnsupportedEncodingException occurs.\"); } }}",
"e": 31050,
"s": 29944,
"text": null
},
{
"code": null,
"e": 31078,
"s": 31050,
"text": "The ASCII value of } is 125"
},
{
"code": null,
"e": 31087,
"s": 31078,
"text": "rkbhola5"
},
{
"code": null,
"e": 31094,
"s": 31087,
"text": "Picked"
},
{
"code": null,
"e": 31118,
"s": 31094,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 31123,
"s": 31118,
"text": "Java"
},
{
"code": null,
"e": 31137,
"s": 31123,
"text": "Java Programs"
},
{
"code": null,
"e": 31142,
"s": 31137,
"text": "Java"
},
{
"code": null,
"e": 31240,
"s": 31142,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31255,
"s": 31240,
"text": "Stream In Java"
},
{
"code": null,
"e": 31276,
"s": 31255,
"text": "Constructors in Java"
},
{
"code": null,
"e": 31295,
"s": 31276,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 31325,
"s": 31295,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 31371,
"s": 31325,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 31397,
"s": 31371,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 31431,
"s": 31397,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 31478,
"s": 31431,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 31510,
"s": 31478,
"text": "How to Iterate HashMap in Java?"
}
] |
ListWheelScrollView Widget in Flutter - GeeksforGeeks | 14 Feb, 2022
ListWheelScrollView is a flutter widget that is used to build ListView with 3D-effect. We can also use ListView to create a list of items but we can’t add a 3D effect to it plus it also comes with a constrain that all the children inside this widget must be of the same size along the strolling axis. Flutter’s ListWheelScrollView adds its children in a scrollable wheel. That results in a 3D effect as if the children are rotating in a wheel. This widget comes with many properties. Some allow us to set the diameter of the wheel, make of off-set, or even add a magnification effect.
Syntax:
ListWheelScrollView({Key key,
ScrollController controller,
ScrollPhysics physics,
double diameterRatio,
double perspective,
double offAxisFraction,
bool useMagnifier,
double magnification,
double overAndUnderCenterOpacity,
double itemExtent,
double squeeze,
void Function(int) onSelectedItemChanged,
bool clipToSize,
bool renderChildrenOutsideViewport,
List<Widget> children})
Syntax:
const ListWheelScrollView.useDelegate(
{Key key,
ScrollController controller,
ScrollPhysics physics,
double diameterRatio: RenderListWheelViewport.defaultDiameterRatio,
double perspective: RenderListWheelViewport.defaultPerspective,
double offAxisFraction: 0.0,
bool useMagnifier: false,
double magnification: 1.0,
double overAndUnderCenterOpacity: 1.0,
@required double itemExtent,
double squeeze: 1.0,
ValueChanged<int> onSelectedItemChanged,
bool renderChildrenOutsideViewport: false,
Clip clipBehavior: Clip.hardEdge,
String restorationId,
@required ListWheelChildDelegate childDelegate}
)
childDelegate: This property takes ListWheelChildDelegate class as the parameter value (final). It lazily initiates the child.
//Implementation
final ListWheelChildDelegate childDelegate
childBehaviour: This property takes Clip enum as the parameter. It controls the portion of the content to be clipped.
controller: This property takes ScrollController class as the parameter and it is used to control the current item.
diameterRatio: This property takes a double value as the parameter and it determines the ratio between the size of the wheel and the size of vireport.
itemExtent: This property takes a double value as the parameter, which has to be a positive number. It decides the size of each child in the wheel.
magnification: This property also takes in a double value as the parameter and zoom-in value, by default it is set to 1.0.If it is greater than 1.0 the center element will be zoomed by that factor and vice-versa.
OffAxisFraction: This property also takes in a double value as the parameter and controls how the wheel is horizontally off-center.
//Implementation
final double offAxisFraction
onSelectedItemChanged: This property takes in ValueChanged<T> typedef as the parameter. It is always called when the center child widget in the wheel changes.
// Syntax
void ValueChanged (
T value
)
overAndUnderCenterOpacity: This property takes in a double value (final) as the parameter and accordingly applies opacity to the child widgets except the one in the center of the wheel.
perspective: This property also takes in a double value (final), which has to be a positive number as the parameter. It controls the distinction between the far-away parts and the near-by parts of the wheel.
physics: This widget also take in ScrollPhysics class as the parameter to determine the physical behaviour of the wheel in respect to the users behaviours (for example, when user scrolls or when user stop scrolling).
//Implementation
final ScrollPhysics physics
renderedChildOutsideViewport: This property takes in a boolean value (final) as the parameter to decide whether to display the child widget only inside the viewport or not.
restorationId: This property takes in the a String as the parameter. This saves and restores the scroll offset of the scrollabe in the wheel.
squeeze: This property takes in a double value (final) as the parameter. The double value must always be a positive number. This controls the compactness of the child widgets in the wheel.
//Implementation
final double squeeze
useMagnifier: This property also takes in a boolean value (final) as the parameter to control the magnification for the central item on the wheel.
Example:
The main.dart file.
Dart
import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { // This widget is the root // of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'ListWheelScrollView Example', theme: ThemeData( primarySwatch: Colors.blue, ), debugShowCheckedModeBanner: false, home: Wheel(), ); }} class Wheel extends StatefulWidget { @override _WheelState createState() => _WheelState();}class _WheelState extends State<Wheel> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("Geeksforgeeks"), backgroundColor: Colors.green, ), body: ListWheelScrollView( itemExtent: 100, // diameterRatio: 1.6, // offAxisFraction: -0.4, // squeeze: 0.8, clipToSize: true, children: <Widget>[ RaisedButton(onPressed:null , child: Text("Item 1",textAlign:TextAlign.start, style:TextStyle(color:Colors.black,fontWeight: FontWeight.bold,fontSize: 25),),) , RaisedButton(onPressed:null , child: Text("Item 2",textAlign:TextAlign.center, style:TextStyle(color:Colors.black,fontWeight: FontWeight.bold,fontSize: 25),),) , RaisedButton(onPressed:null , child: Text("Item 3",textAlign:TextAlign.center, style:TextStyle(color:Colors.black,fontWeight: FontWeight.bold,fontSize: 25),),) , RaisedButton(onPressed:null , child: Text("Item 4",textAlign:TextAlign.center, style:TextStyle(color:Colors.black,fontWeight: FontWeight.bold,fontSize: 25),),) , RaisedButton(onPressed:null , child: Text("Item 5",textAlign:TextAlign.center, style:TextStyle(color:Colors.black,fontWeight: FontWeight.bold,fontSize: 25),),) , RaisedButton(onPressed:null , child: Text("Item 6",textAlign:TextAlign.center, style:TextStyle(color:Colors.black,fontWeight: FontWeight.bold,fontSize: 25),),) , RaisedButton(onPressed:null , child: Text("Item 7",textAlign:TextAlign.center, style:TextStyle(color:Colors.black,fontWeight: FontWeight.bold,fontSize: 25),),) , RaisedButton(onPressed:null , child: Text("Item 8",textAlign:TextAlign.center, style:TextStyle(color:Colors.black,fontWeight: FontWeight.bold,fontSize: 25),),) , ], ), ); }}
The following properties are defined in the above example:
itemExtent: 100,
clipToSize: true
Output:
If the properties are defined as below:
itemExtent: 100,
clipToSize: true,
diameterRatio: 1
The following design changes can be observed:
If the properties are defined as below:
itemExtent: 100,
clipToSize: true,
diameterRatio: 1
offAxisFraction: -0.4
The following design changes can be observed:
If the properties are defined as below:
itemExtent: 200,
diameterRatio: 1.5,
clipToSize: true
The following design changes can be observed:
If the properties are defined as below:
itemExtent: 200,
diameterRatio: 1.5,
offAxisFraction: 0.4,
squeeze: 0.8,
clipToSize: true
The following design changes can be observed:
For the complete code, you can refer to https://github.com/singhteekam/Flutter-ListWheelScrollView-Widget
ankit_kumar_
varshagumber28
Flutter
Dart
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Flutter - DropDownButton Widget
Flutter - Custom Bottom Navigation Bar
Flutter - Checkbox Widget
Flutter - Flexible Widget
Flutter - BoxShadow Widget
Dart Tutorial
Flutter - Stack Widget
Operators in Dart
Flutter - Dialogs
Android Studio Setup for Flutter Development | [
{
"code": null,
"e": 25197,
"s": 25169,
"text": "\n14 Feb, 2022"
},
{
"code": null,
"e": 25782,
"s": 25197,
"text": "ListWheelScrollView is a flutter widget that is used to build ListView with 3D-effect. We can also use ListView to create a list of items but we can’t add a 3D effect to it plus it also comes with a constrain that all the children inside this widget must be of the same size along the strolling axis. Flutter’s ListWheelScrollView adds its children in a scrollable wheel. That results in a 3D effect as if the children are rotating in a wheel. This widget comes with many properties. Some allow us to set the diameter of the wheel, make of off-set, or even add a magnification effect."
},
{
"code": null,
"e": 26194,
"s": 25782,
"text": "Syntax:\nListWheelScrollView({Key key,\n ScrollController controller, \n ScrollPhysics physics, \n double diameterRatio, \n double perspective, \n double offAxisFraction, \n bool useMagnifier, \n double magnification, \n double overAndUnderCenterOpacity, \n double itemExtent, \n double squeeze, \n void Function(int) onSelectedItemChanged, \n bool clipToSize, \n bool renderChildrenOutsideViewport, \n List<Widget> children})"
},
{
"code": null,
"e": 26796,
"s": 26194,
"text": "Syntax:\nconst ListWheelScrollView.useDelegate(\n{Key key,\nScrollController controller,\nScrollPhysics physics,\ndouble diameterRatio: RenderListWheelViewport.defaultDiameterRatio,\ndouble perspective: RenderListWheelViewport.defaultPerspective,\ndouble offAxisFraction: 0.0,\nbool useMagnifier: false,\ndouble magnification: 1.0,\ndouble overAndUnderCenterOpacity: 1.0,\n@required double itemExtent,\ndouble squeeze: 1.0,\nValueChanged<int> onSelectedItemChanged,\nbool renderChildrenOutsideViewport: false,\nClip clipBehavior: Clip.hardEdge,\nString restorationId,\n@required ListWheelChildDelegate childDelegate}\n)"
},
{
"code": null,
"e": 26923,
"s": 26796,
"text": "childDelegate: This property takes ListWheelChildDelegate class as the parameter value (final). It lazily initiates the child."
},
{
"code": null,
"e": 26983,
"s": 26923,
"text": "//Implementation\nfinal ListWheelChildDelegate childDelegate"
},
{
"code": null,
"e": 27101,
"s": 26983,
"text": "childBehaviour: This property takes Clip enum as the parameter. It controls the portion of the content to be clipped."
},
{
"code": null,
"e": 27218,
"s": 27101,
"text": "controller: This property takes ScrollController class as the parameter and it is used to control the current item."
},
{
"code": null,
"e": 27369,
"s": 27218,
"text": "diameterRatio: This property takes a double value as the parameter and it determines the ratio between the size of the wheel and the size of vireport."
},
{
"code": null,
"e": 27517,
"s": 27369,
"text": "itemExtent: This property takes a double value as the parameter, which has to be a positive number. It decides the size of each child in the wheel."
},
{
"code": null,
"e": 27730,
"s": 27517,
"text": "magnification: This property also takes in a double value as the parameter and zoom-in value, by default it is set to 1.0.If it is greater than 1.0 the center element will be zoomed by that factor and vice-versa."
},
{
"code": null,
"e": 27862,
"s": 27730,
"text": "OffAxisFraction: This property also takes in a double value as the parameter and controls how the wheel is horizontally off-center."
},
{
"code": null,
"e": 27909,
"s": 27862,
"text": "//Implementation\n\nfinal double offAxisFraction"
},
{
"code": null,
"e": 28068,
"s": 27909,
"text": "onSelectedItemChanged: This property takes in ValueChanged<T> typedef as the parameter. It is always called when the center child widget in the wheel changes."
},
{
"code": null,
"e": 28108,
"s": 28068,
"text": "// Syntax\nvoid ValueChanged (\nT value\n)"
},
{
"code": null,
"e": 28294,
"s": 28108,
"text": "overAndUnderCenterOpacity: This property takes in a double value (final) as the parameter and accordingly applies opacity to the child widgets except the one in the center of the wheel."
},
{
"code": null,
"e": 28502,
"s": 28294,
"text": "perspective: This property also takes in a double value (final), which has to be a positive number as the parameter. It controls the distinction between the far-away parts and the near-by parts of the wheel."
},
{
"code": null,
"e": 28719,
"s": 28502,
"text": "physics: This widget also take in ScrollPhysics class as the parameter to determine the physical behaviour of the wheel in respect to the users behaviours (for example, when user scrolls or when user stop scrolling)."
},
{
"code": null,
"e": 28764,
"s": 28719,
"text": "//Implementation\nfinal ScrollPhysics physics"
},
{
"code": null,
"e": 28937,
"s": 28764,
"text": "renderedChildOutsideViewport: This property takes in a boolean value (final) as the parameter to decide whether to display the child widget only inside the viewport or not."
},
{
"code": null,
"e": 29079,
"s": 28937,
"text": "restorationId: This property takes in the a String as the parameter. This saves and restores the scroll offset of the scrollabe in the wheel."
},
{
"code": null,
"e": 29269,
"s": 29079,
"text": "squeeze: This property takes in a double value (final) as the parameter. The double value must always be a positive number. This controls the compactness of the child widgets in the wheel."
},
{
"code": null,
"e": 29307,
"s": 29269,
"text": "//Implementation\nfinal double squeeze"
},
{
"code": null,
"e": 29454,
"s": 29307,
"text": "useMagnifier: This property also takes in a boolean value (final) as the parameter to control the magnification for the central item on the wheel."
},
{
"code": null,
"e": 29463,
"s": 29454,
"text": "Example:"
},
{
"code": null,
"e": 29483,
"s": 29463,
"text": "The main.dart file."
},
{
"code": null,
"e": 29488,
"s": 29483,
"text": "Dart"
},
{
"code": "import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { // This widget is the root // of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'ListWheelScrollView Example', theme: ThemeData( primarySwatch: Colors.blue, ), debugShowCheckedModeBanner: false, home: Wheel(), ); }} class Wheel extends StatefulWidget { @override _WheelState createState() => _WheelState();}class _WheelState extends State<Wheel> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(\"Geeksforgeeks\"), backgroundColor: Colors.green, ), body: ListWheelScrollView( itemExtent: 100, // diameterRatio: 1.6, // offAxisFraction: -0.4, // squeeze: 0.8, clipToSize: true, children: <Widget>[ RaisedButton(onPressed:null , child: Text(\"Item 1\",textAlign:TextAlign.start, style:TextStyle(color:Colors.black,fontWeight: FontWeight.bold,fontSize: 25),),) , RaisedButton(onPressed:null , child: Text(\"Item 2\",textAlign:TextAlign.center, style:TextStyle(color:Colors.black,fontWeight: FontWeight.bold,fontSize: 25),),) , RaisedButton(onPressed:null , child: Text(\"Item 3\",textAlign:TextAlign.center, style:TextStyle(color:Colors.black,fontWeight: FontWeight.bold,fontSize: 25),),) , RaisedButton(onPressed:null , child: Text(\"Item 4\",textAlign:TextAlign.center, style:TextStyle(color:Colors.black,fontWeight: FontWeight.bold,fontSize: 25),),) , RaisedButton(onPressed:null , child: Text(\"Item 5\",textAlign:TextAlign.center, style:TextStyle(color:Colors.black,fontWeight: FontWeight.bold,fontSize: 25),),) , RaisedButton(onPressed:null , child: Text(\"Item 6\",textAlign:TextAlign.center, style:TextStyle(color:Colors.black,fontWeight: FontWeight.bold,fontSize: 25),),) , RaisedButton(onPressed:null , child: Text(\"Item 7\",textAlign:TextAlign.center, style:TextStyle(color:Colors.black,fontWeight: FontWeight.bold,fontSize: 25),),) , RaisedButton(onPressed:null , child: Text(\"Item 8\",textAlign:TextAlign.center, style:TextStyle(color:Colors.black,fontWeight: FontWeight.bold,fontSize: 25),),) , ], ), ); }}",
"e": 31929,
"s": 29488,
"text": null
},
{
"code": null,
"e": 31990,
"s": 31931,
"text": "The following properties are defined in the above example:"
},
{
"code": null,
"e": 32024,
"s": 31990,
"text": "itemExtent: 100,\nclipToSize: true"
},
{
"code": null,
"e": 32032,
"s": 32024,
"text": "Output:"
},
{
"code": null,
"e": 32072,
"s": 32032,
"text": "If the properties are defined as below:"
},
{
"code": null,
"e": 32124,
"s": 32072,
"text": "itemExtent: 100,\nclipToSize: true,\ndiameterRatio: 1"
},
{
"code": null,
"e": 32170,
"s": 32124,
"text": "The following design changes can be observed:"
},
{
"code": null,
"e": 32210,
"s": 32170,
"text": "If the properties are defined as below:"
},
{
"code": null,
"e": 32284,
"s": 32210,
"text": "itemExtent: 100,\nclipToSize: true,\ndiameterRatio: 1\noffAxisFraction: -0.4"
},
{
"code": null,
"e": 32330,
"s": 32284,
"text": "The following design changes can be observed:"
},
{
"code": null,
"e": 32370,
"s": 32330,
"text": "If the properties are defined as below:"
},
{
"code": null,
"e": 32424,
"s": 32370,
"text": "itemExtent: 200,\ndiameterRatio: 1.5,\nclipToSize: true"
},
{
"code": null,
"e": 32470,
"s": 32424,
"text": "The following design changes can be observed:"
},
{
"code": null,
"e": 32510,
"s": 32470,
"text": "If the properties are defined as below:"
},
{
"code": null,
"e": 32600,
"s": 32510,
"text": "itemExtent: 200,\ndiameterRatio: 1.5,\noffAxisFraction: 0.4,\nsqueeze: 0.8,\nclipToSize: true"
},
{
"code": null,
"e": 32646,
"s": 32600,
"text": "The following design changes can be observed:"
},
{
"code": null,
"e": 32752,
"s": 32646,
"text": "For the complete code, you can refer to https://github.com/singhteekam/Flutter-ListWheelScrollView-Widget"
},
{
"code": null,
"e": 32765,
"s": 32752,
"text": "ankit_kumar_"
},
{
"code": null,
"e": 32780,
"s": 32765,
"text": "varshagumber28"
},
{
"code": null,
"e": 32788,
"s": 32780,
"text": "Flutter"
},
{
"code": null,
"e": 32793,
"s": 32788,
"text": "Dart"
},
{
"code": null,
"e": 32891,
"s": 32793,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32923,
"s": 32891,
"text": "Flutter - DropDownButton Widget"
},
{
"code": null,
"e": 32962,
"s": 32923,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 32988,
"s": 32962,
"text": "Flutter - Checkbox Widget"
},
{
"code": null,
"e": 33014,
"s": 32988,
"text": "Flutter - Flexible Widget"
},
{
"code": null,
"e": 33041,
"s": 33014,
"text": "Flutter - BoxShadow Widget"
},
{
"code": null,
"e": 33055,
"s": 33041,
"text": "Dart Tutorial"
},
{
"code": null,
"e": 33078,
"s": 33055,
"text": "Flutter - Stack Widget"
},
{
"code": null,
"e": 33096,
"s": 33078,
"text": "Operators in Dart"
},
{
"code": null,
"e": 33114,
"s": 33096,
"text": "Flutter - Dialogs"
}
] |
DateTime.GetTypeCode() Method in C# - GeeksforGeeks | 05 Feb, 2019
This method is used to return the TypeCode for value type DateTime.
Syntax: public TypeCode GetTypeCode ();
Return Value: This method returns the enumerated constant, DateTime.
Below programs illustrate the use of DateTime.GetTypeCode() Method
Example 1:
// C# program to demonstrate the// DateTime.GetTypeCode()// Methodusing System; class GFG { // Main Method public static void Main() { // creating object of DateTime DateTime date = new DateTime(2010, 1, 1, 4, 0, 15); // getting Typecode of date // using GetTypeCode() method; TypeCode value = date.GetTypeCode(); // Display the hashcode Console.WriteLine("TypeCode is {0}", value); }}
TypeCode is DateTime
Example 2:
// C# program to demonstrate the// DateTime.GetTypeCode()// Methodusing System; class GFG { // Main Method public static void Main() { // calling check() method check(new DateTime(2010, 1, 3, 4, 0, 15)); check(new DateTime(2010, 1, 5, 4, 0, 15)); } public static void check(DateTime date) { // getting TypeCodeCode of date // using GetTypeCode() method; TypeCode value = date.GetTypeCode(); // Display the ShortTime Console.WriteLine("TypeCode of {0} is {1}", date, value); }}
TypeCode of 01/03/2010 04:00:15 is DateTime
TypeCode of 01/05/2010 04:00:15 is DateTime
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.datetime.gettypecode?view=netframework-4.7.2
CSharp DateTime Struct
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 50 C# Interview Questions & Answers
Extension Method in C#
HashSet in C# with Examples
Partial Classes in C#
C# | Inheritance
Convert String to Character Array in C#
Linked List Implementation in C#
C# | How to insert an element in an Array?
C# | List Class
Difference between Hashtable and Dictionary in C# | [
{
"code": null,
"e": 23911,
"s": 23883,
"text": "\n05 Feb, 2019"
},
{
"code": null,
"e": 23979,
"s": 23911,
"text": "This method is used to return the TypeCode for value type DateTime."
},
{
"code": null,
"e": 24019,
"s": 23979,
"text": "Syntax: public TypeCode GetTypeCode ();"
},
{
"code": null,
"e": 24088,
"s": 24019,
"text": "Return Value: This method returns the enumerated constant, DateTime."
},
{
"code": null,
"e": 24155,
"s": 24088,
"text": "Below programs illustrate the use of DateTime.GetTypeCode() Method"
},
{
"code": null,
"e": 24166,
"s": 24155,
"text": "Example 1:"
},
{
"code": "// C# program to demonstrate the// DateTime.GetTypeCode()// Methodusing System; class GFG { // Main Method public static void Main() { // creating object of DateTime DateTime date = new DateTime(2010, 1, 1, 4, 0, 15); // getting Typecode of date // using GetTypeCode() method; TypeCode value = date.GetTypeCode(); // Display the hashcode Console.WriteLine(\"TypeCode is {0}\", value); }}",
"e": 24653,
"s": 24166,
"text": null
},
{
"code": null,
"e": 24675,
"s": 24653,
"text": "TypeCode is DateTime\n"
},
{
"code": null,
"e": 24686,
"s": 24675,
"text": "Example 2:"
},
{
"code": "// C# program to demonstrate the// DateTime.GetTypeCode()// Methodusing System; class GFG { // Main Method public static void Main() { // calling check() method check(new DateTime(2010, 1, 3, 4, 0, 15)); check(new DateTime(2010, 1, 5, 4, 0, 15)); } public static void check(DateTime date) { // getting TypeCodeCode of date // using GetTypeCode() method; TypeCode value = date.GetTypeCode(); // Display the ShortTime Console.WriteLine(\"TypeCode of {0} is {1}\", date, value); }}",
"e": 25328,
"s": 24686,
"text": null
},
{
"code": null,
"e": 25417,
"s": 25328,
"text": "TypeCode of 01/03/2010 04:00:15 is DateTime\nTypeCode of 01/05/2010 04:00:15 is DateTime\n"
},
{
"code": null,
"e": 25428,
"s": 25417,
"text": "Reference:"
},
{
"code": null,
"e": 25524,
"s": 25428,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.datetime.gettypecode?view=netframework-4.7.2"
},
{
"code": null,
"e": 25547,
"s": 25524,
"text": "CSharp DateTime Struct"
},
{
"code": null,
"e": 25561,
"s": 25547,
"text": "CSharp-method"
},
{
"code": null,
"e": 25564,
"s": 25561,
"text": "C#"
},
{
"code": null,
"e": 25662,
"s": 25564,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25671,
"s": 25662,
"text": "Comments"
},
{
"code": null,
"e": 25684,
"s": 25671,
"text": "Old Comments"
},
{
"code": null,
"e": 25724,
"s": 25684,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 25747,
"s": 25724,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 25775,
"s": 25747,
"text": "HashSet in C# with Examples"
},
{
"code": null,
"e": 25797,
"s": 25775,
"text": "Partial Classes in C#"
},
{
"code": null,
"e": 25814,
"s": 25797,
"text": "C# | Inheritance"
},
{
"code": null,
"e": 25854,
"s": 25814,
"text": "Convert String to Character Array in C#"
},
{
"code": null,
"e": 25887,
"s": 25854,
"text": "Linked List Implementation in C#"
},
{
"code": null,
"e": 25930,
"s": 25887,
"text": "C# | How to insert an element in an Array?"
},
{
"code": null,
"e": 25946,
"s": 25930,
"text": "C# | List Class"
}
] |
How to align button to right side of text box in Bootstrap? - GeeksforGeeks | 18 Aug, 2021
Bootstrap allows us to align elements by using the utility class float. As we want to align the button to the right side of the text box, we have to use the float-right class. Syntax:
<button class="btn btn-success btn-lg float-right" type="submit">Submit</button>
Example:
html
<!DOCTYPE html><html> <head> <title>Bootstrap Button Alignment</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script></head> <body> <div class="container"> <h1 style="text-align:center;color:green;"> GeeksforGeeks </h1> <form> <div class="form-group"> <label for="">Enter Your Name:</label> <input class="form-control" type="text" placeholder="Input Your Name Here"> </div> <div class="form-group"> <button class="btn btn-success btn-lg float-right" type="submit"> Submit </button> </div> </form> </div></body> </html>
Output:
Note: Although by default, elements like buttons, are left-aligned still we can use float-left class to mention it specifically. We can also use the class float-none to remove any hierarchical floating. It is important to note that we are using Bootstrap 4 here, in Bootstrap 3 or Bootstrap 2 we can use the helper classes like pull-left, pull-right to align the elements to the left or right accordingly.
kapoorsagar226
Bootstrap-4
Bootstrap-Misc
Picked
Bootstrap
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Show Images on Click using HTML ?
How to set Bootstrap Timepicker using datetimepicker library ?
Difference between Bootstrap 4 and Bootstrap 5
How to Use Bootstrap with React?
Tailwind CSS vs Bootstrap
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": 24239,
"s": 24211,
"text": "\n18 Aug, 2021"
},
{
"code": null,
"e": 24425,
"s": 24239,
"text": "Bootstrap allows us to align elements by using the utility class float. As we want to align the button to the right side of the text box, we have to use the float-right class. Syntax: "
},
{
"code": null,
"e": 24506,
"s": 24425,
"text": "<button class=\"btn btn-success btn-lg float-right\" type=\"submit\">Submit</button>"
},
{
"code": null,
"e": 24517,
"s": 24506,
"text": "Example: "
},
{
"code": null,
"e": 24522,
"s": 24517,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Bootstrap Button Alignment</title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script></head> <body> <div class=\"container\"> <h1 style=\"text-align:center;color:green;\"> GeeksforGeeks </h1> <form> <div class=\"form-group\"> <label for=\"\">Enter Your Name:</label> <input class=\"form-control\" type=\"text\" placeholder=\"Input Your Name Here\"> </div> <div class=\"form-group\"> <button class=\"btn btn-success btn-lg float-right\" type=\"submit\"> Submit </button> </div> </form> </div></body> </html>",
"e": 25747,
"s": 24522,
"text": null
},
{
"code": null,
"e": 25757,
"s": 25747,
"text": "Output: "
},
{
"code": null,
"e": 26164,
"s": 25757,
"text": "Note: Although by default, elements like buttons, are left-aligned still we can use float-left class to mention it specifically. We can also use the class float-none to remove any hierarchical floating. It is important to note that we are using Bootstrap 4 here, in Bootstrap 3 or Bootstrap 2 we can use the helper classes like pull-left, pull-right to align the elements to the left or right accordingly. "
},
{
"code": null,
"e": 26179,
"s": 26164,
"text": "kapoorsagar226"
},
{
"code": null,
"e": 26191,
"s": 26179,
"text": "Bootstrap-4"
},
{
"code": null,
"e": 26206,
"s": 26191,
"text": "Bootstrap-Misc"
},
{
"code": null,
"e": 26213,
"s": 26206,
"text": "Picked"
},
{
"code": null,
"e": 26223,
"s": 26213,
"text": "Bootstrap"
},
{
"code": null,
"e": 26240,
"s": 26223,
"text": "Web Technologies"
},
{
"code": null,
"e": 26338,
"s": 26240,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26347,
"s": 26338,
"text": "Comments"
},
{
"code": null,
"e": 26360,
"s": 26347,
"text": "Old Comments"
},
{
"code": null,
"e": 26401,
"s": 26360,
"text": "How to Show Images on Click using HTML ?"
},
{
"code": null,
"e": 26464,
"s": 26401,
"text": "How to set Bootstrap Timepicker using datetimepicker library ?"
},
{
"code": null,
"e": 26511,
"s": 26464,
"text": "Difference between Bootstrap 4 and Bootstrap 5"
},
{
"code": null,
"e": 26544,
"s": 26511,
"text": "How to Use Bootstrap with React?"
},
{
"code": null,
"e": 26570,
"s": 26544,
"text": "Tailwind CSS vs Bootstrap"
},
{
"code": null,
"e": 26626,
"s": 26570,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 26659,
"s": 26626,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 26721,
"s": 26659,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 26764,
"s": 26721,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Java program to check for URL in a String | A program can be created to check if a string is a correct URL or not. An example of an URL is given as follows −
String = https://www.wikipedia.org/
The above string is a valid URL
A program that demonstrates this is given as follows.
Live Demo
import java.net.URL;
public class Example {
public static boolean check_URL(String str) {
try {
new URL(str).toURI();
return true;
}catch (Exception e) {
return false;
}
}
public static void main(String[] args) {
String str = "http://www.wikipedia.org/";
System.out.println("String = " + str);
if (check_URL(str))
System.out.println("The above string is a URL");
else
System.out.println("The above string is not a URL");
}
}
String = http://www.wikipedia.org/
The above string is a URL
Now let us understand the above program.
In the function check_URL(), a URL object is created. If there is no exception when the object is created, then true is returned. Otherwise, false is returned. The code snippet that demonstrates this is given as follows.
public static boolean check_URL(String str) {
try {
new URL(str).toURI();
return true;
}catch (Exception e) {
return false;
}
}
In the function main(), the string is printed. Then the function check_URL() is called with string str. If true is returned, then str is a URL and that is printed otherwise str is not a URL and that is printed. The code snippet that demonstrates this is given as follows.
public static void main(String[] args) {
String str = "http://www.wikipedia.org/";
System.out.println("String = " + str);
if (check_URL(str))
System.out.println("The above string is a URL");
else
System.out.println("The above string is not a URL");
} | [
{
"code": null,
"e": 1176,
"s": 1062,
"text": "A program can be created to check if a string is a correct URL or not. An example of an URL is given as follows −"
},
{
"code": null,
"e": 1244,
"s": 1176,
"text": "String = https://www.wikipedia.org/\nThe above string is a valid URL"
},
{
"code": null,
"e": 1298,
"s": 1244,
"text": "A program that demonstrates this is given as follows."
},
{
"code": null,
"e": 1309,
"s": 1298,
"text": " Live Demo"
},
{
"code": null,
"e": 1791,
"s": 1309,
"text": "import java.net.URL;\npublic class Example {\n public static boolean check_URL(String str) {\n try {\n new URL(str).toURI();\n return true;\n }catch (Exception e) {\n return false;\n }\n}\npublic static void main(String[] args) {\n String str = \"http://www.wikipedia.org/\";\n System.out.println(\"String = \" + str);\n if (check_URL(str))\n System.out.println(\"The above string is a URL\");\n else\n System.out.println(\"The above string is not a URL\");\n }\n}"
},
{
"code": null,
"e": 1852,
"s": 1791,
"text": "String = http://www.wikipedia.org/\nThe above string is a URL"
},
{
"code": null,
"e": 1893,
"s": 1852,
"text": "Now let us understand the above program."
},
{
"code": null,
"e": 2114,
"s": 1893,
"text": "In the function check_URL(), a URL object is created. If there is no exception when the object is created, then true is returned. Otherwise, false is returned. The code snippet that demonstrates this is given as follows."
},
{
"code": null,
"e": 2269,
"s": 2114,
"text": "public static boolean check_URL(String str) {\n try {\n new URL(str).toURI();\n return true;\n }catch (Exception e) {\n return false;\n }\n}"
},
{
"code": null,
"e": 2541,
"s": 2269,
"text": "In the function main(), the string is printed. Then the function check_URL() is called with string str. If true is returned, then str is a URL and that is printed otherwise str is not a URL and that is printed. The code snippet that demonstrates this is given as follows."
},
{
"code": null,
"e": 2816,
"s": 2541,
"text": "public static void main(String[] args) {\n String str = \"http://www.wikipedia.org/\";\n System.out.println(\"String = \" + str);\n if (check_URL(str))\n System.out.println(\"The above string is a URL\");\n else\n System.out.println(\"The above string is not a URL\");\n}"
}
] |
Generating Modern Art using
Generative Adversarial Network(GAN) on Spell | by Anish Shrestha | Towards Data Science | You need to have a good understanding of:
Image processingPython Programming LanguageNumpy — Scientific Computing LibraryKeras — Deep Learning Library
Image processing
Python Programming Language
Numpy — Scientific Computing Library
Keras — Deep Learning Library
And some basic knowledge of:
Generative Adversarial Network (GAN)
Generative Adversarial Network (GAN)
Image data used in this project has been collected from WikiArts.org.
In this tutorial, we are going to look at the step by step process to create a Generative Adversarial Network to generate Modern Art and write a code for that using Python and Keras together.
After that, for training the model, we are going to use a powerful GPU Instance of Spell platform. Everything will be explained along the way and links will be provided for further readings.
Let’s get started!
Before getting started, let’s look at our image dataset.
WikiArt has a huge collection of modern art with various different styles. For our particular project, we are going to use images of Cubism Style.
You can know more about the art styles and Modern Art from WikiArt.org.
You can either download images that you like from WikiArt or head to this repository by cs-chan to download the 26GB of WikiArt images.
Since it has a collection of all the different types, we are only going to pick cubism and store them in folder named dataset.
Images in our dataset are of different sizes, to feed them into our Generative Adversarial Neural Network we are going to resize all our images to 128X128.
Before starting, create a python file at the root directory where your dataset folder is located.
Now let’s write a small python script to select all the images from the folder and resize them to 128X128 and save them on cubism_data.npy file.
## image_resizer.py# Importing required librariesimport osimport numpy as npfrom PIL import Image# Defining an image size and image channel# We are going to resize all our images to 128X128 size and since our images are colored images# We are setting our image channels to 3 (RGB)IMAGE_SIZE = 128IMAGE_CHANNELS = 3IMAGE_DIR = 'dataset/'# Defining image dir path. Change this if you have different directoryimages_path = IMAGE_DIR training_data = []# Iterating over the images inside the directory and resizing them using# Pillow's resize method.print('resizing...')for filename in os.listdir(images_path): path = os.path.join(images_path, filename) image = Image.open(path).resize((IMAGE_SIZE, IMAGE_SIZE), Image.ANTIALIAS) training_data.append(np.asarray(image))training_data = np.reshape( training_data, (-1, IMAGE_SIZE, IMAGE_SIZE, IMAGE_CHANNELS))training_data = training_data / 127.5 - 1print('saving file...')np.save('cubism_data.npy', training_data)
Let’s break it down.
In our code block above, in the first few lines, we have imported all the required libraries to perform the resizing operation.
import osimport numpy as npfrom PIL import ImageIMAGE_SIZE = 128IMAGE_CHANNELS = 3IMAGE_DIR = 'dataset/'images_path = IMAGE_DIR
Here, we are using Pillow to resize all images to our desired size and appending them on a list as numpy array.
training_data = []for filename in os.listdir(images_path): path = os.path.join(images_path, filename) image = Image.open(path).resize((IMAGE_SIZE, IMAGE_SIZE), Image.ANTIALIAS)training_data.append(np.asarray(image))
After that, we are using numpy to reshape the array in a suitable format and normalizing data.
training_data = np.reshape(training_data, (-1, IMAGE_SIZE, IMAGE_SIZE, IMAGE_CHANNELS))training_data = training_data / 127.5–1
After normalization, we are saving our image array in npy binary file so that we don’t have to go through all the images every time.
np.save(‘cubism_data.npy’, training_data)
That’s it for processing our image data.
Now it’s time for the most exciting part of our project, from here on we are going to write our code for Generative Adversarial Network (GAN).
We are going to use Keras — A Deep Learning Library to create our GAN.
Before starting let’s briefly understand what is GAN and it’s structure.
Generative adversarial networks (GANs) are an exciting recent innovation in machine learning. It was first introduced by Ian Godfellow in his paper Generative Adversarial Networks.
GANs are generative models: after given some training data, they can create new data instances that look like your training data. For example, GANs can create images that look like photographs of human faces, even though the faces don’t belong to any real person.
For a great example of GAN you can visit https://www.thispersondoesnotexist.com/ which was created by Nvidia. It generates a high quality image of a person who does not even exist.
Sounds interesting right?
Let’s understand it’s structure and how it works.
GAN composes of two types of models: Generative Model and a Discriminative Model.
Generative Models are responsible for generating different kinds of noise data whereas discriminative models are responsible to discriminate whether the given data is real or fake.
Generative models constantly trains itself to fool discriminative models by generating fake noise data and discriminative models trains itself from the training set to classify either the data is from dataset or not and not to be fooled by generative models.
Discriminator in GAN uses a cross entropy loss, since discriminators job is to classify; cross entropy loss is the best one out there.
This formula represents the cross entropy loss between p: the true distribution and q: the estimated distribution.
(p) and (q) are the of m dimensions where m is the number of classes.
In GAN, discriminator is a binary classifier. It needs to classify either the data is real or fake. Which means m = 2. The true distribution is one hot vector consisting of only 2 terms.
For n number of samples, we can sum over the losses.
This above shown equation is of binary cross entropy loss, where y can take two values 0 and 1.
GAN’s have a latent vector z, image G(z) is magically generated out of it. We apply the discriminator function D with real image x and the generated image G(z).
The intention of the loss function is to push the predictions of the real image towards 1 and the fake images to 0. We do so by log probability term.
Note: ~ sign means: is distributed as and Ex here means expectations: since we don’t know how samples are fed into the discriminator, we are representing them as expectations rather than the sum.
If we observe the joint loss function we are maximizing the discriminator term, which means log of D(x) should inch closer to zero, and log D(G(z)) should be closer to 1. Here generator is trying to make D(G(z)) inch closer to 1 while discriminator is trying to do the opposite.
Now without any delay let’s write our GAN.
We are going to name our file art_gan.py and store it in the root directory. This file will contain all the hyperparameters and functions for our generator and discriminator.
Let’s write some code:
from keras.layers import Input, Reshape, Dropout, Dense, Flatten, BatchNormalization, Activation, ZeroPadding2Dfrom keras.layers.advanced_activations import LeakyReLUfrom keras.layers.convolutional import UpSampling2D, Conv2Dfrom keras.models import Sequential, Model, load_modelfrom keras.optimizers import Adamimport numpy as npfrom PIL import Imageimport os
Here we are importing all the required libraries and helper functions for creating our GAN.
All the imports are self-explanatory. Here we are importing a bunch of keras layers for creating our models.
Now let’s define some parameters:
# Preview image FramePREVIEW_ROWS = 4PREVIEW_COLS = 7PREVIEW_MARGIN = 4SAVE_FREQ = 100# Size vector to generate images fromNOISE_SIZE = 100# ConfigurationEPOCHS = 10000 # number of iterationsBATCH_SIZE = 32GENERATE_RES = 3IMAGE_SIZE = 128 # rows/colsIMAGE_CHANNELS = 3
Here in the first few lines, we have defined Image frame size and padding to save our generated images.
NOISE_SIZE here is a latent dimension size to generate our images.
EPOCHS is a number of iterations: it defines how many times we want to iterate over our training images and BATCH_SIZE is a number of images to feed in every iteration.
IMAGE_SIZE is our image size which we resized earlier to 128X128 and IMAGE_CHANNELS is a number of channel in our images; which is 3.
Note: Images should always be of square size
Let's load our npy data file which we’ve created earlier.
training_data = np.load(‘cubism_data.npy’)
To load the npy file we are using numpy’s load function and passing file path as a parameter.
Since we have our data file in the root directory we no additional path parameters were required. If you have stored your data somewhere else, you can use the following code to load data:
training_data = np.load(os.path.join(‘dirname’, ‘filename.npy’))
That’s it for loading our training data.
Now we can create our Generator and Discriminator functions.
Let’s see that in code:
def build_discriminator(image_shape): model = Sequential() model.add(Conv2D(32, kernel_size=3, strides=2, input_shape=image_shape, padding=”same”)) model.add(LeakyReLU(alpha=0.2)) model.add(Dropout(0.25)) model.add(Conv2D(64, kernel_size=3, strides=2, padding=”same”)) model.add(ZeroPadding2D(padding=((0, 1), (0, 1)))) model.add(BatchNormalization(momentum=0.8)) model.add(LeakyReLU(alpha=0.2)) model.add(Dropout(0.25)) model.add(Conv2D(128, kernel_size=3, strides=2, padding=”same”)) model.add(BatchNormalization(momentum=0.8)) model.add(LeakyReLU(alpha=0.2)) model.add(Dropout(0.25)) model.add(Conv2D(256, kernel_size=3, strides=1, padding=”same”)) model.add(BatchNormalization(momentum=0.8)) model.add(LeakyReLU(alpha=0.2)) model.add(Dropout(0.25)) model.add(Conv2D(512, kernel_size=3, strides=1, padding=”same”)) model.add(BatchNormalization(momentum=0.8)) model.add(LeakyReLU(alpha=0.2)) model.add(Dropout(0.25)) model.add(Flatten()) model.add(Dense(1, activation=’sigmoid’)) input_image = Input(shape=image_shape) validity = model(input_image) return Model(input_image, validity)
breaking it down:
If you have some knowledge of keras than the code is self-explanatory.
In general, we are defining a function which takes image_shape as a parameter.
Inside that function, we are initializing a Sequential model from keras which helps us in creating linear stacks of layers.
model = Sequential()
After that, we are appending a bunch of layers in sequential model.
Our first layer is a convolutional layer of 32 shape having kernel_size of 3 and our stride value is 2 with padding same. Since it is a first layer it holds input_shape.
To understand what is going on here, you can refer to keras official documentation page.
But in simple language, here we are defining a convolutional layer which has a filter of size 3X3 and that filter strides over our image data. We have padding of same which means, no additional paddings are added. It remains the same as the original.
model.add(Conv2D(32, kernel_size=3, strides=2, input_shape=image_shape, padding=”same”))model.add(LeakyReLU(alpha=0.2))
After that, we are adding a LeakyRelu layer which is an activation function.
Similarly in other block of layers are added in a sequential model with some dropouts and batch normalization to prevent overfitting.
The last layer of our model is a Fully connected layer with an activation function sigmoid.
Since our discriminator’s job is to classify whether the given image is fake or not, it is a binary classification task and sigmoid is an activation that squeezes every value to values between 0 and 1.
model.add(Flatten())model.add(Dense(1, activation=’sigmoid’))
Now after initializing our discriminator model let’s create a generative model as well.
def build_generator(noise_size, channels): model = Sequential() model.add(Dense(4 * 4 * 256, activation=”relu”, input_dim=noise_size)) model.add(Reshape((4, 4, 256))) model.add(UpSampling2D()) model.add(Conv2D(256, kernel_size=3, padding=”same”)) model.add(BatchNormalization(momentum=0.8)) model.add(Activation(“relu”)) model.add(UpSampling2D()) model.add(Conv2D(256, kernel_size=3, padding=”same”)) model.add(BatchNormalization(momentum=0.8)) model.add(Activation(“relu”)) for i in range(GENERATE_RES): model.add(UpSampling2D()) model.add(Conv2D(256, kernel_size=3, padding=”same”)) model.add(BatchNormalization(momentum=0.8)) model.add(Activation(“relu”)) model.summary() model.add(Conv2D(channels, kernel_size=3, padding=”same”)) model.add(Activation(“tanh”)) input = Input(shape=(noise_size,)) generated_image = model(input) return Model(input, generated_image)
Breaking it down:
Here we have defined a function that takes noise_size and channels as parameters.
Inside the function, we have again initialized a sequential model.
Since our generator model has to generate images from noise vector, our first layer is a fully connected dense layer of size 4096 (4 * 4 * 256) which takes noise_size as a parameter.
model.add(Dense(4 * 4 * 256, activation=”relu”, input_dim=noise_size))
Note: We have defined its size to be of 4096 to for resizing it in 4X4X256 shaped layer.
After that, we are using Reshape layer to reshape our fully connected layer in the shape of 4X4X256.
model.add(Reshape((4, 4, 256)))
Layer blocks after this are just a Convolutional layer with batch normalizations and activation function relu.
Just to see and understand what it looks like, let’s look at the model summary:
From the shape of 4X4 it is extended up to the size of 128X128 which is our training_data shape.
Our generator model takes noise as an input and outputs an image.
After initializing both the generator and discriminator model, let’s write a helper function to save the image after some iteration.
def save_images(cnt, noise): image_array = np.full(( PREVIEW_MARGIN + (PREVIEW_ROWS * (IMAGE_SIZE + PREVIEW_MARGIN)), PREVIEW_MARGIN + (PREVIEW_COLS * (IMAGE_SIZE + PREVIEW_MARGIN)), 3), 255, dtype=np.uint8)generated_images = generator.predict(noise)generated_images = 0.5 * generated_images + 0.5image_count = 0 for row in range(PREVIEW_ROWS): for col in range(PREVIEW_COLS): r = row * (IMAGE_SIZE + PREVIEW_MARGIN) + PREVIEW_MARGIN c = col * (IMAGE_SIZE + PREVIEW_MARGIN) + PREVIEW_MARGIN image_array[r:r + IMAGE_SIZE, c:c + IMAGE_SIZE] = generated_images[image_count] * 255 image_count += 1output_path = 'output' if not os.path.exists(output_path): os.makedirs(output_path)filename = os.path.join(output_path, f"trained-{cnt}.png") im = Image.fromarray(image_array) im.save(filename)
Our save_images function takes to count and noise as an input.
Inside the function, it generates frames from the parameters we’ve defined above and stores our generated image array which are generated from the noise input.
After that, it saves it as an image.
Now, it’s time for us to compile the models and train them.
Let’s write a block of code for that as well:
image_shape = (IMAGE_SIZE, IMAGE_SIZE, IMAGE_CHANNELS)optimizer = Adam(1.5e-4, 0.5)discriminator = build_discriminator(image_shape)discriminator.compile(loss=”binary_crossentropy”,optimizer=optimizer, metrics=[“accuracy”])generator = build_generator(NOISE_SIZE, IMAGE_CHANNELS)random_input = Input(shape=(NOISE_SIZE,))generated_image = generator(random_input)discriminator.trainable = Falsevalidity = discriminator(generated_image)combined = Model(random_input, validity)combined.compile(loss=”binary_crossentropy”,optimizer=optimizer, metrics=[“accuracy”])y_real = np.ones((BATCH_SIZE, 1))y_fake = np.zeros((BATCH_SIZE, 1))fixed_noise = np.random.normal(0, 1, (PREVIEW_ROWS * PREVIEW_COLS, NOISE_SIZE))cnt = 1for epoch in range(EPOCHS): idx = np.random.randint(0, training_data.shape[0], BATCH_SIZE) x_real = training_data[idx] noise= np.random.normal(0, 1, (BATCH_SIZE, NOISE_SIZE)) x_fake = generator.predict(noise) discriminator_metric_real = discriminator.train_on_batch(x_real, y_real)discriminator_metric_generated = discriminator.train_on_batch( x_fake, y_fake) discriminator_metric = 0.5 * np.add(discriminator_metric_real, discriminator_metric_generated)generator_metric = combined.train_on_batch(noise, y_real)if epoch % SAVE_FREQ == 0: save_images(cnt, fixed_noise) cnt += 1 print(f”{epoch} epoch, Discriminator accuracy: {100* discriminator_metric[1]}, Generator accuracy: {100 * generator_metric[1]}”)
Breaking it down:
Here in the first few lines, we have defined our input shape: which is 128X128X3 (image_size, image_size, image_channel).
After that, we are using Adam as our optimizer.
Note: All the parameters has been sourced from the paper [1].
image_shape = (IMAGE_SIZE, IMAGE_SIZE, IMAGE_CHANNELS)optimizer = Adam(1.5e-4, 0.5)discriminator = build_discriminator(image_shape)discriminator.compile(loss=”binary_crossentropy”,optimizer=optimizer, metrics=[“accuracy”])
After initializing the optimizer, we are calling our build_discriminator function and passing the image shape then compiling it with a loss function and an optimizer.
Since it is a classification model, we are using accuracy as its performance metric.
Similarly, in the next line, we are calling our build_generator function and passing our random_input noise vector as its input.
generator = build_generator(NOISE_SIZE, IMAGE_CHANNELS)random_input = Input(shape=(NOISE_SIZE,))generated_image = generator(random_input)
It returns a generated image as it’s output.
Now, one important part of GAN is we should prevent our discriminator from training.
discriminator.trainable = Falsevalidity = discriminator(generated_image)combined = Model(random_input, validity)combined.compile(loss=”binary_crossentropy”,optimizer=optimizer, metrics=[“accuracy”])
Since we are only training generators here, we do not want to adjust the weights of the discriminator.
This is what really an “Adversarial” in Adversarial Network means.
If we do not set this, the generator will get its weight adjusted so it gets better at fooling the discriminator and it also adjusts the weights of the discriminator to make it better at being fooled.
We don’t want this. So, we have to train them separately and fight against each other.
We are then compiling the generative model with loss function and optimizer.
After that, we are defining two vectors as y_real and y_fake.
y_real = np.ones((BATCH_SIZE, 1))y_fake = np.zeros((BATCH_SIZE, 1))fixed_noise = np.random.normal(0, 1, (PREVIEW_ROWS * PREVIEW_COLS, NOISE_SIZE))
These vectors are composed of random 0’s and 1’s values.
After that we are creating a fixed_noise: this will result in generating images that are saved later on which we can see it getting better on every iteration.
After that, we are going to iterate over our training data with the range of epochs we’ve defined.
cnt = 1for epoch in range(EPOCHS): idx = np.random.randint(0, training_data.shape[0], BATCH_SIZE) x_real = training_data[idx] noise= np.random.normal(0, 1, (BATCH_SIZE, NOISE_SIZE)) x_fake = generator.predict(noise) discriminator_metric_real = discriminator.train_on_batch(x_real, y_real) discriminator_metric_generated = discriminator.train_on_batch( x_fake, y_fake) discriminator_metric = 0.5 * np.add(discriminator_metric_real, discriminator_metric_generated) generator_metric = combined.train_on_batch(noisse, y_real) if epoch % SAVE_FREQ == 0: save_images(cnt, fixed_noise) cnt += 1 print(f”{epoch} epoch, Discriminator accuracy: {100* discriminator_metric[1]}, Generator accuracy: {100 * generator_metric[1]}”)
During the iteration process, we are taking a sample from a real image and putting that on x_real. After that, we are defining a noise vector and passing that to our generator model to generate a fake image in x_fake.
Then we are training our discriminator model in both real and fake images separately.
discriminator_metric_real = discriminator.train_on_batch(x_real, y_real)discriminator_metric_generated = discriminator.train_on_batch( x_fake, y_fake)
Some research has shown that training them separately can get us some better results.
After training, we are taking the metric from both models and taking the average.
discriminator_metric = 0.5 * np.add(discriminator_metric_real, discriminator_metric_generated)
This way we get the metric for the discriminator model, now for the generator model, we are training it on our noise vector and y_real: which is a vector of 1’s.
Here we are trying to train the generator. Overtime generator will get better from these inputs and the discriminator will not be able to discriminate whether the input is fake or real.
One thing to note here, our combined model is based on the generator model linked directly to the discriminator model. Here our Input is what the generator wants as an input: which is noise and output is what the discriminator gives us.
Now in the end we have an if statement which checks for our checkpoint.
if epoch % SAVE_FREQ == 0: save_images(cnt, fixed_noise) cnt += 1 print(f”{epoch} epoch, Discriminator accuracy: {100* discriminator_metric[1]}, Generator accuracy: {100 * generator_metric[1]}”)
If it reaches the checkpoint then it saves the current iteration noise and prints the current accuracy of generator and discriminator.
This is all for the coding part to create GAN, but we are not finished yet.
We have just written code for it, now we have to actually train those models and see the output how it performs.
Training GAN in a normal laptop is kind of impossible since it requires high computation power.
Normal laptops with normal CPUs cannot handle such huge tasks, so we are going to use Spell: Which is the fastest and most powerful end-to-end platform for Machine Learning and Deep Learning.
The spell is a powerful platform for building and managing machine learning projects. The spell takes care of infrastructure, making machine learning projects easier to start, faster to get results, more organized, and safer than managing infrastructure on your own.
In every signup with Spell, you can get 10$ free credit!
In simple words, we are going to upload our data file in the spell platform and let it handle all our training task. Spell runs our task in their Powerful GPUs so that we don’t have to worry about anything. We can monitor our logs from their Web GUI and all our outputs are saved safely as well.
There are few things to cover before running our project at Spell.
First off, we must create our account on Spell. There is good and easy documentation to get started on their official page.
After account creation, we can install Spell CLI using pip install:
pip install spell
This installs all the power of spell into our laptop. We can either use the Web GUI or we can easily log in to the spell server and execute commands from our cmd or bash.
To upload our project on Spell, we are going to use command-line tools.
Let’s open the command line terminal in the root directory of our project folder and login to the server by using spell login command:
spell login
After a successful login, now we can upload our training data file and run our code in the Spell server:
Spell upload “filename”
After that our training_data will be uploaded to the server.
Note: Before running code in the server, code has been pushed to the github.
Now we are ready to execute our code in the Spell server.
In the command line let’s run the following command:
Spell run python art_gan.py -t V100 -m uploads/art_gan/cubism_data.npy
The command above runs our code in the Spell server with the Machine type V100 which is a GPU machine. The last argument there mounts the dataset directory so that it can be accessed by our code.
Now that code is executed successfully you can see the logs on your console. If you want to monitor in GUI then you can log in to the Web GUI of Spell and see under Runs Section.
As you can see, it holds all the information about our recent run.
As we have written code for; in every 100th iteration our generated image is saved in the output directory and log with accuracy metric are printed.
You can view them in logs section.
Awesome isn’t it? You can do your other works while it trains and saves the output for you.
Now after the training completes Spell automatically saves our output in the resources/runs directory.
After that, we can download the outputs from the runs of Spell to our local machine by using the following command:
spell cp [OPTIONS] SOURCE_PATH [LOCAL_DIR]
For this project it will be:
spell cp runs/44
You just have to enter the runs/<number of your run> to download the content of that runs.
That’s it!! Now you have outputs of the GAN trained on Spell’s GPU machine in your local machine. You can now visualize how your GAN performed from that output images.
GANs are an exciting and rapidly changing field, delivering on the promise of generative models in their ability to generate realistic examples across a range of problem domains. It is not an easy task to understand GAN or any Machine Learning and Deep Learning field overnight. It needs patience and a lot of practice plus understanding.
In previous days it was not possible for Aspiring ML enthusiast likes us to perform repetitive practice to see what went how. But now, a platform like Spell helps us to provide a system to run and manage our projects so that we can run and test our models.
What we have created is just a simple representation of how GAN can be created and what GAN can do. There are still more advanced tweaks yet to perform.
To take it further you can tweak the parameters and see how differently it generates the images.
There are still a lot of things one can research.
For any queries and discussion, you can join the Spell community from here: https://chat.spell.ml/
[1] Generative Adversarial Network, Ian J. Goodfellow, Jean Pouget-Abadie, Mehdi Mirza, Bing Xu, David Warde-Farley, Sherjil Ozair, Aaron Courville, Yoshua Bengio, 2014
[2] A Gentle Introduction to Generative Adversarial Networks (GANs), Jason Brownlee, 2019 [Online] https://machinelearningmastery.com/what-are-generative-adversarial-networks-gans/
[3] A Beginner’s Guide to Generative Adversarial Networks (GANs), Chris, 2019 [Online] https://skymind.ai/wiki/generative-adversarial-network-gan | [
{
"code": null,
"e": 214,
"s": 172,
"text": "You need to have a good understanding of:"
},
{
"code": null,
"e": 323,
"s": 214,
"text": "Image processingPython Programming LanguageNumpy — Scientific Computing LibraryKeras — Deep Learning Library"
},
{
"code": null,
"e": 340,
"s": 323,
"text": "Image processing"
},
{
"code": null,
"e": 368,
"s": 340,
"text": "Python Programming Language"
},
{
"code": null,
"e": 405,
"s": 368,
"text": "Numpy — Scientific Computing Library"
},
{
"code": null,
"e": 435,
"s": 405,
"text": "Keras — Deep Learning Library"
},
{
"code": null,
"e": 464,
"s": 435,
"text": "And some basic knowledge of:"
},
{
"code": null,
"e": 501,
"s": 464,
"text": "Generative Adversarial Network (GAN)"
},
{
"code": null,
"e": 538,
"s": 501,
"text": "Generative Adversarial Network (GAN)"
},
{
"code": null,
"e": 608,
"s": 538,
"text": "Image data used in this project has been collected from WikiArts.org."
},
{
"code": null,
"e": 800,
"s": 608,
"text": "In this tutorial, we are going to look at the step by step process to create a Generative Adversarial Network to generate Modern Art and write a code for that using Python and Keras together."
},
{
"code": null,
"e": 991,
"s": 800,
"text": "After that, for training the model, we are going to use a powerful GPU Instance of Spell platform. Everything will be explained along the way and links will be provided for further readings."
},
{
"code": null,
"e": 1010,
"s": 991,
"text": "Let’s get started!"
},
{
"code": null,
"e": 1067,
"s": 1010,
"text": "Before getting started, let’s look at our image dataset."
},
{
"code": null,
"e": 1214,
"s": 1067,
"text": "WikiArt has a huge collection of modern art with various different styles. For our particular project, we are going to use images of Cubism Style."
},
{
"code": null,
"e": 1286,
"s": 1214,
"text": "You can know more about the art styles and Modern Art from WikiArt.org."
},
{
"code": null,
"e": 1422,
"s": 1286,
"text": "You can either download images that you like from WikiArt or head to this repository by cs-chan to download the 26GB of WikiArt images."
},
{
"code": null,
"e": 1549,
"s": 1422,
"text": "Since it has a collection of all the different types, we are only going to pick cubism and store them in folder named dataset."
},
{
"code": null,
"e": 1705,
"s": 1549,
"text": "Images in our dataset are of different sizes, to feed them into our Generative Adversarial Neural Network we are going to resize all our images to 128X128."
},
{
"code": null,
"e": 1803,
"s": 1705,
"text": "Before starting, create a python file at the root directory where your dataset folder is located."
},
{
"code": null,
"e": 1948,
"s": 1803,
"text": "Now let’s write a small python script to select all the images from the folder and resize them to 128X128 and save them on cubism_data.npy file."
},
{
"code": null,
"e": 2917,
"s": 1948,
"text": "## image_resizer.py# Importing required librariesimport osimport numpy as npfrom PIL import Image# Defining an image size and image channel# We are going to resize all our images to 128X128 size and since our images are colored images# We are setting our image channels to 3 (RGB)IMAGE_SIZE = 128IMAGE_CHANNELS = 3IMAGE_DIR = 'dataset/'# Defining image dir path. Change this if you have different directoryimages_path = IMAGE_DIR training_data = []# Iterating over the images inside the directory and resizing them using# Pillow's resize method.print('resizing...')for filename in os.listdir(images_path): path = os.path.join(images_path, filename) image = Image.open(path).resize((IMAGE_SIZE, IMAGE_SIZE), Image.ANTIALIAS) training_data.append(np.asarray(image))training_data = np.reshape( training_data, (-1, IMAGE_SIZE, IMAGE_SIZE, IMAGE_CHANNELS))training_data = training_data / 127.5 - 1print('saving file...')np.save('cubism_data.npy', training_data)"
},
{
"code": null,
"e": 2938,
"s": 2917,
"text": "Let’s break it down."
},
{
"code": null,
"e": 3066,
"s": 2938,
"text": "In our code block above, in the first few lines, we have imported all the required libraries to perform the resizing operation."
},
{
"code": null,
"e": 3194,
"s": 3066,
"text": "import osimport numpy as npfrom PIL import ImageIMAGE_SIZE = 128IMAGE_CHANNELS = 3IMAGE_DIR = 'dataset/'images_path = IMAGE_DIR"
},
{
"code": null,
"e": 3306,
"s": 3194,
"text": "Here, we are using Pillow to resize all images to our desired size and appending them on a list as numpy array."
},
{
"code": null,
"e": 3522,
"s": 3306,
"text": "training_data = []for filename in os.listdir(images_path): path = os.path.join(images_path, filename) image = Image.open(path).resize((IMAGE_SIZE, IMAGE_SIZE), Image.ANTIALIAS)training_data.append(np.asarray(image))"
},
{
"code": null,
"e": 3617,
"s": 3522,
"text": "After that, we are using numpy to reshape the array in a suitable format and normalizing data."
},
{
"code": null,
"e": 3744,
"s": 3617,
"text": "training_data = np.reshape(training_data, (-1, IMAGE_SIZE, IMAGE_SIZE, IMAGE_CHANNELS))training_data = training_data / 127.5–1"
},
{
"code": null,
"e": 3877,
"s": 3744,
"text": "After normalization, we are saving our image array in npy binary file so that we don’t have to go through all the images every time."
},
{
"code": null,
"e": 3919,
"s": 3877,
"text": "np.save(‘cubism_data.npy’, training_data)"
},
{
"code": null,
"e": 3960,
"s": 3919,
"text": "That’s it for processing our image data."
},
{
"code": null,
"e": 4103,
"s": 3960,
"text": "Now it’s time for the most exciting part of our project, from here on we are going to write our code for Generative Adversarial Network (GAN)."
},
{
"code": null,
"e": 4174,
"s": 4103,
"text": "We are going to use Keras — A Deep Learning Library to create our GAN."
},
{
"code": null,
"e": 4247,
"s": 4174,
"text": "Before starting let’s briefly understand what is GAN and it’s structure."
},
{
"code": null,
"e": 4428,
"s": 4247,
"text": "Generative adversarial networks (GANs) are an exciting recent innovation in machine learning. It was first introduced by Ian Godfellow in his paper Generative Adversarial Networks."
},
{
"code": null,
"e": 4692,
"s": 4428,
"text": "GANs are generative models: after given some training data, they can create new data instances that look like your training data. For example, GANs can create images that look like photographs of human faces, even though the faces don’t belong to any real person."
},
{
"code": null,
"e": 4873,
"s": 4692,
"text": "For a great example of GAN you can visit https://www.thispersondoesnotexist.com/ which was created by Nvidia. It generates a high quality image of a person who does not even exist."
},
{
"code": null,
"e": 4899,
"s": 4873,
"text": "Sounds interesting right?"
},
{
"code": null,
"e": 4949,
"s": 4899,
"text": "Let’s understand it’s structure and how it works."
},
{
"code": null,
"e": 5031,
"s": 4949,
"text": "GAN composes of two types of models: Generative Model and a Discriminative Model."
},
{
"code": null,
"e": 5212,
"s": 5031,
"text": "Generative Models are responsible for generating different kinds of noise data whereas discriminative models are responsible to discriminate whether the given data is real or fake."
},
{
"code": null,
"e": 5471,
"s": 5212,
"text": "Generative models constantly trains itself to fool discriminative models by generating fake noise data and discriminative models trains itself from the training set to classify either the data is from dataset or not and not to be fooled by generative models."
},
{
"code": null,
"e": 5606,
"s": 5471,
"text": "Discriminator in GAN uses a cross entropy loss, since discriminators job is to classify; cross entropy loss is the best one out there."
},
{
"code": null,
"e": 5721,
"s": 5606,
"text": "This formula represents the cross entropy loss between p: the true distribution and q: the estimated distribution."
},
{
"code": null,
"e": 5791,
"s": 5721,
"text": "(p) and (q) are the of m dimensions where m is the number of classes."
},
{
"code": null,
"e": 5978,
"s": 5791,
"text": "In GAN, discriminator is a binary classifier. It needs to classify either the data is real or fake. Which means m = 2. The true distribution is one hot vector consisting of only 2 terms."
},
{
"code": null,
"e": 6031,
"s": 5978,
"text": "For n number of samples, we can sum over the losses."
},
{
"code": null,
"e": 6127,
"s": 6031,
"text": "This above shown equation is of binary cross entropy loss, where y can take two values 0 and 1."
},
{
"code": null,
"e": 6288,
"s": 6127,
"text": "GAN’s have a latent vector z, image G(z) is magically generated out of it. We apply the discriminator function D with real image x and the generated image G(z)."
},
{
"code": null,
"e": 6438,
"s": 6288,
"text": "The intention of the loss function is to push the predictions of the real image towards 1 and the fake images to 0. We do so by log probability term."
},
{
"code": null,
"e": 6634,
"s": 6438,
"text": "Note: ~ sign means: is distributed as and Ex here means expectations: since we don’t know how samples are fed into the discriminator, we are representing them as expectations rather than the sum."
},
{
"code": null,
"e": 6913,
"s": 6634,
"text": "If we observe the joint loss function we are maximizing the discriminator term, which means log of D(x) should inch closer to zero, and log D(G(z)) should be closer to 1. Here generator is trying to make D(G(z)) inch closer to 1 while discriminator is trying to do the opposite."
},
{
"code": null,
"e": 6956,
"s": 6913,
"text": "Now without any delay let’s write our GAN."
},
{
"code": null,
"e": 7131,
"s": 6956,
"text": "We are going to name our file art_gan.py and store it in the root directory. This file will contain all the hyperparameters and functions for our generator and discriminator."
},
{
"code": null,
"e": 7154,
"s": 7131,
"text": "Let’s write some code:"
},
{
"code": null,
"e": 7515,
"s": 7154,
"text": "from keras.layers import Input, Reshape, Dropout, Dense, Flatten, BatchNormalization, Activation, ZeroPadding2Dfrom keras.layers.advanced_activations import LeakyReLUfrom keras.layers.convolutional import UpSampling2D, Conv2Dfrom keras.models import Sequential, Model, load_modelfrom keras.optimizers import Adamimport numpy as npfrom PIL import Imageimport os"
},
{
"code": null,
"e": 7607,
"s": 7515,
"text": "Here we are importing all the required libraries and helper functions for creating our GAN."
},
{
"code": null,
"e": 7716,
"s": 7607,
"text": "All the imports are self-explanatory. Here we are importing a bunch of keras layers for creating our models."
},
{
"code": null,
"e": 7750,
"s": 7716,
"text": "Now let’s define some parameters:"
},
{
"code": null,
"e": 8019,
"s": 7750,
"text": "# Preview image FramePREVIEW_ROWS = 4PREVIEW_COLS = 7PREVIEW_MARGIN = 4SAVE_FREQ = 100# Size vector to generate images fromNOISE_SIZE = 100# ConfigurationEPOCHS = 10000 # number of iterationsBATCH_SIZE = 32GENERATE_RES = 3IMAGE_SIZE = 128 # rows/colsIMAGE_CHANNELS = 3"
},
{
"code": null,
"e": 8123,
"s": 8019,
"text": "Here in the first few lines, we have defined Image frame size and padding to save our generated images."
},
{
"code": null,
"e": 8190,
"s": 8123,
"text": "NOISE_SIZE here is a latent dimension size to generate our images."
},
{
"code": null,
"e": 8359,
"s": 8190,
"text": "EPOCHS is a number of iterations: it defines how many times we want to iterate over our training images and BATCH_SIZE is a number of images to feed in every iteration."
},
{
"code": null,
"e": 8493,
"s": 8359,
"text": "IMAGE_SIZE is our image size which we resized earlier to 128X128 and IMAGE_CHANNELS is a number of channel in our images; which is 3."
},
{
"code": null,
"e": 8538,
"s": 8493,
"text": "Note: Images should always be of square size"
},
{
"code": null,
"e": 8596,
"s": 8538,
"text": "Let's load our npy data file which we’ve created earlier."
},
{
"code": null,
"e": 8639,
"s": 8596,
"text": "training_data = np.load(‘cubism_data.npy’)"
},
{
"code": null,
"e": 8733,
"s": 8639,
"text": "To load the npy file we are using numpy’s load function and passing file path as a parameter."
},
{
"code": null,
"e": 8921,
"s": 8733,
"text": "Since we have our data file in the root directory we no additional path parameters were required. If you have stored your data somewhere else, you can use the following code to load data:"
},
{
"code": null,
"e": 8986,
"s": 8921,
"text": "training_data = np.load(os.path.join(‘dirname’, ‘filename.npy’))"
},
{
"code": null,
"e": 9027,
"s": 8986,
"text": "That’s it for loading our training data."
},
{
"code": null,
"e": 9088,
"s": 9027,
"text": "Now we can create our Generator and Discriminator functions."
},
{
"code": null,
"e": 9112,
"s": 9088,
"text": "Let’s see that in code:"
},
{
"code": null,
"e": 10280,
"s": 9112,
"text": "def build_discriminator(image_shape): model = Sequential() model.add(Conv2D(32, kernel_size=3, strides=2, input_shape=image_shape, padding=”same”)) model.add(LeakyReLU(alpha=0.2)) model.add(Dropout(0.25)) model.add(Conv2D(64, kernel_size=3, strides=2, padding=”same”)) model.add(ZeroPadding2D(padding=((0, 1), (0, 1)))) model.add(BatchNormalization(momentum=0.8)) model.add(LeakyReLU(alpha=0.2)) model.add(Dropout(0.25)) model.add(Conv2D(128, kernel_size=3, strides=2, padding=”same”)) model.add(BatchNormalization(momentum=0.8)) model.add(LeakyReLU(alpha=0.2)) model.add(Dropout(0.25)) model.add(Conv2D(256, kernel_size=3, strides=1, padding=”same”)) model.add(BatchNormalization(momentum=0.8)) model.add(LeakyReLU(alpha=0.2)) model.add(Dropout(0.25)) model.add(Conv2D(512, kernel_size=3, strides=1, padding=”same”)) model.add(BatchNormalization(momentum=0.8)) model.add(LeakyReLU(alpha=0.2)) model.add(Dropout(0.25)) model.add(Flatten()) model.add(Dense(1, activation=’sigmoid’)) input_image = Input(shape=image_shape) validity = model(input_image) return Model(input_image, validity)"
},
{
"code": null,
"e": 10298,
"s": 10280,
"text": "breaking it down:"
},
{
"code": null,
"e": 10369,
"s": 10298,
"text": "If you have some knowledge of keras than the code is self-explanatory."
},
{
"code": null,
"e": 10448,
"s": 10369,
"text": "In general, we are defining a function which takes image_shape as a parameter."
},
{
"code": null,
"e": 10572,
"s": 10448,
"text": "Inside that function, we are initializing a Sequential model from keras which helps us in creating linear stacks of layers."
},
{
"code": null,
"e": 10593,
"s": 10572,
"text": "model = Sequential()"
},
{
"code": null,
"e": 10661,
"s": 10593,
"text": "After that, we are appending a bunch of layers in sequential model."
},
{
"code": null,
"e": 10831,
"s": 10661,
"text": "Our first layer is a convolutional layer of 32 shape having kernel_size of 3 and our stride value is 2 with padding same. Since it is a first layer it holds input_shape."
},
{
"code": null,
"e": 10920,
"s": 10831,
"text": "To understand what is going on here, you can refer to keras official documentation page."
},
{
"code": null,
"e": 11171,
"s": 10920,
"text": "But in simple language, here we are defining a convolutional layer which has a filter of size 3X3 and that filter strides over our image data. We have padding of same which means, no additional paddings are added. It remains the same as the original."
},
{
"code": null,
"e": 11292,
"s": 11171,
"text": "model.add(Conv2D(32, kernel_size=3, strides=2, input_shape=image_shape, padding=”same”))model.add(LeakyReLU(alpha=0.2))"
},
{
"code": null,
"e": 11369,
"s": 11292,
"text": "After that, we are adding a LeakyRelu layer which is an activation function."
},
{
"code": null,
"e": 11503,
"s": 11369,
"text": "Similarly in other block of layers are added in a sequential model with some dropouts and batch normalization to prevent overfitting."
},
{
"code": null,
"e": 11595,
"s": 11503,
"text": "The last layer of our model is a Fully connected layer with an activation function sigmoid."
},
{
"code": null,
"e": 11797,
"s": 11595,
"text": "Since our discriminator’s job is to classify whether the given image is fake or not, it is a binary classification task and sigmoid is an activation that squeezes every value to values between 0 and 1."
},
{
"code": null,
"e": 11859,
"s": 11797,
"text": "model.add(Flatten())model.add(Dense(1, activation=’sigmoid’))"
},
{
"code": null,
"e": 11947,
"s": 11859,
"text": "Now after initializing our discriminator model let’s create a generative model as well."
},
{
"code": null,
"e": 12910,
"s": 11947,
"text": "def build_generator(noise_size, channels): model = Sequential() model.add(Dense(4 * 4 * 256, activation=”relu”, input_dim=noise_size)) model.add(Reshape((4, 4, 256))) model.add(UpSampling2D()) model.add(Conv2D(256, kernel_size=3, padding=”same”)) model.add(BatchNormalization(momentum=0.8)) model.add(Activation(“relu”)) model.add(UpSampling2D()) model.add(Conv2D(256, kernel_size=3, padding=”same”)) model.add(BatchNormalization(momentum=0.8)) model.add(Activation(“relu”)) for i in range(GENERATE_RES): model.add(UpSampling2D()) model.add(Conv2D(256, kernel_size=3, padding=”same”)) model.add(BatchNormalization(momentum=0.8)) model.add(Activation(“relu”)) model.summary() model.add(Conv2D(channels, kernel_size=3, padding=”same”)) model.add(Activation(“tanh”)) input = Input(shape=(noise_size,)) generated_image = model(input) return Model(input, generated_image)"
},
{
"code": null,
"e": 12928,
"s": 12910,
"text": "Breaking it down:"
},
{
"code": null,
"e": 13010,
"s": 12928,
"text": "Here we have defined a function that takes noise_size and channels as parameters."
},
{
"code": null,
"e": 13077,
"s": 13010,
"text": "Inside the function, we have again initialized a sequential model."
},
{
"code": null,
"e": 13260,
"s": 13077,
"text": "Since our generator model has to generate images from noise vector, our first layer is a fully connected dense layer of size 4096 (4 * 4 * 256) which takes noise_size as a parameter."
},
{
"code": null,
"e": 13331,
"s": 13260,
"text": "model.add(Dense(4 * 4 * 256, activation=”relu”, input_dim=noise_size))"
},
{
"code": null,
"e": 13420,
"s": 13331,
"text": "Note: We have defined its size to be of 4096 to for resizing it in 4X4X256 shaped layer."
},
{
"code": null,
"e": 13521,
"s": 13420,
"text": "After that, we are using Reshape layer to reshape our fully connected layer in the shape of 4X4X256."
},
{
"code": null,
"e": 13553,
"s": 13521,
"text": "model.add(Reshape((4, 4, 256)))"
},
{
"code": null,
"e": 13664,
"s": 13553,
"text": "Layer blocks after this are just a Convolutional layer with batch normalizations and activation function relu."
},
{
"code": null,
"e": 13744,
"s": 13664,
"text": "Just to see and understand what it looks like, let’s look at the model summary:"
},
{
"code": null,
"e": 13841,
"s": 13744,
"text": "From the shape of 4X4 it is extended up to the size of 128X128 which is our training_data shape."
},
{
"code": null,
"e": 13907,
"s": 13841,
"text": "Our generator model takes noise as an input and outputs an image."
},
{
"code": null,
"e": 14040,
"s": 13907,
"text": "After initializing both the generator and discriminator model, let’s write a helper function to save the image after some iteration."
},
{
"code": null,
"e": 14944,
"s": 14040,
"text": "def save_images(cnt, noise): image_array = np.full(( PREVIEW_MARGIN + (PREVIEW_ROWS * (IMAGE_SIZE + PREVIEW_MARGIN)), PREVIEW_MARGIN + (PREVIEW_COLS * (IMAGE_SIZE + PREVIEW_MARGIN)), 3), 255, dtype=np.uint8)generated_images = generator.predict(noise)generated_images = 0.5 * generated_images + 0.5image_count = 0 for row in range(PREVIEW_ROWS): for col in range(PREVIEW_COLS): r = row * (IMAGE_SIZE + PREVIEW_MARGIN) + PREVIEW_MARGIN c = col * (IMAGE_SIZE + PREVIEW_MARGIN) + PREVIEW_MARGIN image_array[r:r + IMAGE_SIZE, c:c + IMAGE_SIZE] = generated_images[image_count] * 255 image_count += 1output_path = 'output' if not os.path.exists(output_path): os.makedirs(output_path)filename = os.path.join(output_path, f\"trained-{cnt}.png\") im = Image.fromarray(image_array) im.save(filename)"
},
{
"code": null,
"e": 15007,
"s": 14944,
"text": "Our save_images function takes to count and noise as an input."
},
{
"code": null,
"e": 15167,
"s": 15007,
"text": "Inside the function, it generates frames from the parameters we’ve defined above and stores our generated image array which are generated from the noise input."
},
{
"code": null,
"e": 15204,
"s": 15167,
"text": "After that, it saves it as an image."
},
{
"code": null,
"e": 15264,
"s": 15204,
"text": "Now, it’s time for us to compile the models and train them."
},
{
"code": null,
"e": 15310,
"s": 15264,
"text": "Let’s write a block of code for that as well:"
},
{
"code": null,
"e": 16736,
"s": 15310,
"text": "image_shape = (IMAGE_SIZE, IMAGE_SIZE, IMAGE_CHANNELS)optimizer = Adam(1.5e-4, 0.5)discriminator = build_discriminator(image_shape)discriminator.compile(loss=”binary_crossentropy”,optimizer=optimizer, metrics=[“accuracy”])generator = build_generator(NOISE_SIZE, IMAGE_CHANNELS)random_input = Input(shape=(NOISE_SIZE,))generated_image = generator(random_input)discriminator.trainable = Falsevalidity = discriminator(generated_image)combined = Model(random_input, validity)combined.compile(loss=”binary_crossentropy”,optimizer=optimizer, metrics=[“accuracy”])y_real = np.ones((BATCH_SIZE, 1))y_fake = np.zeros((BATCH_SIZE, 1))fixed_noise = np.random.normal(0, 1, (PREVIEW_ROWS * PREVIEW_COLS, NOISE_SIZE))cnt = 1for epoch in range(EPOCHS): idx = np.random.randint(0, training_data.shape[0], BATCH_SIZE) x_real = training_data[idx] noise= np.random.normal(0, 1, (BATCH_SIZE, NOISE_SIZE)) x_fake = generator.predict(noise) discriminator_metric_real = discriminator.train_on_batch(x_real, y_real)discriminator_metric_generated = discriminator.train_on_batch( x_fake, y_fake) discriminator_metric = 0.5 * np.add(discriminator_metric_real, discriminator_metric_generated)generator_metric = combined.train_on_batch(noise, y_real)if epoch % SAVE_FREQ == 0: save_images(cnt, fixed_noise) cnt += 1 print(f”{epoch} epoch, Discriminator accuracy: {100* discriminator_metric[1]}, Generator accuracy: {100 * generator_metric[1]}”)"
},
{
"code": null,
"e": 16754,
"s": 16736,
"text": "Breaking it down:"
},
{
"code": null,
"e": 16876,
"s": 16754,
"text": "Here in the first few lines, we have defined our input shape: which is 128X128X3 (image_size, image_size, image_channel)."
},
{
"code": null,
"e": 16924,
"s": 16876,
"text": "After that, we are using Adam as our optimizer."
},
{
"code": null,
"e": 16986,
"s": 16924,
"text": "Note: All the parameters has been sourced from the paper [1]."
},
{
"code": null,
"e": 17209,
"s": 16986,
"text": "image_shape = (IMAGE_SIZE, IMAGE_SIZE, IMAGE_CHANNELS)optimizer = Adam(1.5e-4, 0.5)discriminator = build_discriminator(image_shape)discriminator.compile(loss=”binary_crossentropy”,optimizer=optimizer, metrics=[“accuracy”])"
},
{
"code": null,
"e": 17376,
"s": 17209,
"text": "After initializing the optimizer, we are calling our build_discriminator function and passing the image shape then compiling it with a loss function and an optimizer."
},
{
"code": null,
"e": 17461,
"s": 17376,
"text": "Since it is a classification model, we are using accuracy as its performance metric."
},
{
"code": null,
"e": 17590,
"s": 17461,
"text": "Similarly, in the next line, we are calling our build_generator function and passing our random_input noise vector as its input."
},
{
"code": null,
"e": 17728,
"s": 17590,
"text": "generator = build_generator(NOISE_SIZE, IMAGE_CHANNELS)random_input = Input(shape=(NOISE_SIZE,))generated_image = generator(random_input)"
},
{
"code": null,
"e": 17773,
"s": 17728,
"text": "It returns a generated image as it’s output."
},
{
"code": null,
"e": 17858,
"s": 17773,
"text": "Now, one important part of GAN is we should prevent our discriminator from training."
},
{
"code": null,
"e": 18057,
"s": 17858,
"text": "discriminator.trainable = Falsevalidity = discriminator(generated_image)combined = Model(random_input, validity)combined.compile(loss=”binary_crossentropy”,optimizer=optimizer, metrics=[“accuracy”])"
},
{
"code": null,
"e": 18160,
"s": 18057,
"text": "Since we are only training generators here, we do not want to adjust the weights of the discriminator."
},
{
"code": null,
"e": 18227,
"s": 18160,
"text": "This is what really an “Adversarial” in Adversarial Network means."
},
{
"code": null,
"e": 18428,
"s": 18227,
"text": "If we do not set this, the generator will get its weight adjusted so it gets better at fooling the discriminator and it also adjusts the weights of the discriminator to make it better at being fooled."
},
{
"code": null,
"e": 18515,
"s": 18428,
"text": "We don’t want this. So, we have to train them separately and fight against each other."
},
{
"code": null,
"e": 18592,
"s": 18515,
"text": "We are then compiling the generative model with loss function and optimizer."
},
{
"code": null,
"e": 18654,
"s": 18592,
"text": "After that, we are defining two vectors as y_real and y_fake."
},
{
"code": null,
"e": 18801,
"s": 18654,
"text": "y_real = np.ones((BATCH_SIZE, 1))y_fake = np.zeros((BATCH_SIZE, 1))fixed_noise = np.random.normal(0, 1, (PREVIEW_ROWS * PREVIEW_COLS, NOISE_SIZE))"
},
{
"code": null,
"e": 18858,
"s": 18801,
"text": "These vectors are composed of random 0’s and 1’s values."
},
{
"code": null,
"e": 19017,
"s": 18858,
"text": "After that we are creating a fixed_noise: this will result in generating images that are saved later on which we can see it getting better on every iteration."
},
{
"code": null,
"e": 19116,
"s": 19017,
"text": "After that, we are going to iterate over our training data with the range of epochs we’ve defined."
},
{
"code": null,
"e": 19861,
"s": 19116,
"text": "cnt = 1for epoch in range(EPOCHS): idx = np.random.randint(0, training_data.shape[0], BATCH_SIZE) x_real = training_data[idx] noise= np.random.normal(0, 1, (BATCH_SIZE, NOISE_SIZE)) x_fake = generator.predict(noise) discriminator_metric_real = discriminator.train_on_batch(x_real, y_real) discriminator_metric_generated = discriminator.train_on_batch( x_fake, y_fake) discriminator_metric = 0.5 * np.add(discriminator_metric_real, discriminator_metric_generated) generator_metric = combined.train_on_batch(noisse, y_real) if epoch % SAVE_FREQ == 0: save_images(cnt, fixed_noise) cnt += 1 print(f”{epoch} epoch, Discriminator accuracy: {100* discriminator_metric[1]}, Generator accuracy: {100 * generator_metric[1]}”)"
},
{
"code": null,
"e": 20079,
"s": 19861,
"text": "During the iteration process, we are taking a sample from a real image and putting that on x_real. After that, we are defining a noise vector and passing that to our generator model to generate a fake image in x_fake."
},
{
"code": null,
"e": 20165,
"s": 20079,
"text": "Then we are training our discriminator model in both real and fake images separately."
},
{
"code": null,
"e": 20316,
"s": 20165,
"text": "discriminator_metric_real = discriminator.train_on_batch(x_real, y_real)discriminator_metric_generated = discriminator.train_on_batch( x_fake, y_fake)"
},
{
"code": null,
"e": 20402,
"s": 20316,
"text": "Some research has shown that training them separately can get us some better results."
},
{
"code": null,
"e": 20484,
"s": 20402,
"text": "After training, we are taking the metric from both models and taking the average."
},
{
"code": null,
"e": 20579,
"s": 20484,
"text": "discriminator_metric = 0.5 * np.add(discriminator_metric_real, discriminator_metric_generated)"
},
{
"code": null,
"e": 20741,
"s": 20579,
"text": "This way we get the metric for the discriminator model, now for the generator model, we are training it on our noise vector and y_real: which is a vector of 1’s."
},
{
"code": null,
"e": 20927,
"s": 20741,
"text": "Here we are trying to train the generator. Overtime generator will get better from these inputs and the discriminator will not be able to discriminate whether the input is fake or real."
},
{
"code": null,
"e": 21164,
"s": 20927,
"text": "One thing to note here, our combined model is based on the generator model linked directly to the discriminator model. Here our Input is what the generator wants as an input: which is noise and output is what the discriminator gives us."
},
{
"code": null,
"e": 21236,
"s": 21164,
"text": "Now in the end we have an if statement which checks for our checkpoint."
},
{
"code": null,
"e": 21432,
"s": 21236,
"text": "if epoch % SAVE_FREQ == 0: save_images(cnt, fixed_noise) cnt += 1 print(f”{epoch} epoch, Discriminator accuracy: {100* discriminator_metric[1]}, Generator accuracy: {100 * generator_metric[1]}”)"
},
{
"code": null,
"e": 21567,
"s": 21432,
"text": "If it reaches the checkpoint then it saves the current iteration noise and prints the current accuracy of generator and discriminator."
},
{
"code": null,
"e": 21643,
"s": 21567,
"text": "This is all for the coding part to create GAN, but we are not finished yet."
},
{
"code": null,
"e": 21756,
"s": 21643,
"text": "We have just written code for it, now we have to actually train those models and see the output how it performs."
},
{
"code": null,
"e": 21852,
"s": 21756,
"text": "Training GAN in a normal laptop is kind of impossible since it requires high computation power."
},
{
"code": null,
"e": 22044,
"s": 21852,
"text": "Normal laptops with normal CPUs cannot handle such huge tasks, so we are going to use Spell: Which is the fastest and most powerful end-to-end platform for Machine Learning and Deep Learning."
},
{
"code": null,
"e": 22311,
"s": 22044,
"text": "The spell is a powerful platform for building and managing machine learning projects. The spell takes care of infrastructure, making machine learning projects easier to start, faster to get results, more organized, and safer than managing infrastructure on your own."
},
{
"code": null,
"e": 22368,
"s": 22311,
"text": "In every signup with Spell, you can get 10$ free credit!"
},
{
"code": null,
"e": 22664,
"s": 22368,
"text": "In simple words, we are going to upload our data file in the spell platform and let it handle all our training task. Spell runs our task in their Powerful GPUs so that we don’t have to worry about anything. We can monitor our logs from their Web GUI and all our outputs are saved safely as well."
},
{
"code": null,
"e": 22731,
"s": 22664,
"text": "There are few things to cover before running our project at Spell."
},
{
"code": null,
"e": 22855,
"s": 22731,
"text": "First off, we must create our account on Spell. There is good and easy documentation to get started on their official page."
},
{
"code": null,
"e": 22923,
"s": 22855,
"text": "After account creation, we can install Spell CLI using pip install:"
},
{
"code": null,
"e": 22941,
"s": 22923,
"text": "pip install spell"
},
{
"code": null,
"e": 23112,
"s": 22941,
"text": "This installs all the power of spell into our laptop. We can either use the Web GUI or we can easily log in to the spell server and execute commands from our cmd or bash."
},
{
"code": null,
"e": 23184,
"s": 23112,
"text": "To upload our project on Spell, we are going to use command-line tools."
},
{
"code": null,
"e": 23319,
"s": 23184,
"text": "Let’s open the command line terminal in the root directory of our project folder and login to the server by using spell login command:"
},
{
"code": null,
"e": 23331,
"s": 23319,
"text": "spell login"
},
{
"code": null,
"e": 23436,
"s": 23331,
"text": "After a successful login, now we can upload our training data file and run our code in the Spell server:"
},
{
"code": null,
"e": 23460,
"s": 23436,
"text": "Spell upload “filename”"
},
{
"code": null,
"e": 23521,
"s": 23460,
"text": "After that our training_data will be uploaded to the server."
},
{
"code": null,
"e": 23598,
"s": 23521,
"text": "Note: Before running code in the server, code has been pushed to the github."
},
{
"code": null,
"e": 23656,
"s": 23598,
"text": "Now we are ready to execute our code in the Spell server."
},
{
"code": null,
"e": 23709,
"s": 23656,
"text": "In the command line let’s run the following command:"
},
{
"code": null,
"e": 23780,
"s": 23709,
"text": "Spell run python art_gan.py -t V100 -m uploads/art_gan/cubism_data.npy"
},
{
"code": null,
"e": 23976,
"s": 23780,
"text": "The command above runs our code in the Spell server with the Machine type V100 which is a GPU machine. The last argument there mounts the dataset directory so that it can be accessed by our code."
},
{
"code": null,
"e": 24155,
"s": 23976,
"text": "Now that code is executed successfully you can see the logs on your console. If you want to monitor in GUI then you can log in to the Web GUI of Spell and see under Runs Section."
},
{
"code": null,
"e": 24222,
"s": 24155,
"text": "As you can see, it holds all the information about our recent run."
},
{
"code": null,
"e": 24371,
"s": 24222,
"text": "As we have written code for; in every 100th iteration our generated image is saved in the output directory and log with accuracy metric are printed."
},
{
"code": null,
"e": 24406,
"s": 24371,
"text": "You can view them in logs section."
},
{
"code": null,
"e": 24498,
"s": 24406,
"text": "Awesome isn’t it? You can do your other works while it trains and saves the output for you."
},
{
"code": null,
"e": 24601,
"s": 24498,
"text": "Now after the training completes Spell automatically saves our output in the resources/runs directory."
},
{
"code": null,
"e": 24717,
"s": 24601,
"text": "After that, we can download the outputs from the runs of Spell to our local machine by using the following command:"
},
{
"code": null,
"e": 24760,
"s": 24717,
"text": "spell cp [OPTIONS] SOURCE_PATH [LOCAL_DIR]"
},
{
"code": null,
"e": 24789,
"s": 24760,
"text": "For this project it will be:"
},
{
"code": null,
"e": 24806,
"s": 24789,
"text": "spell cp runs/44"
},
{
"code": null,
"e": 24897,
"s": 24806,
"text": "You just have to enter the runs/<number of your run> to download the content of that runs."
},
{
"code": null,
"e": 25065,
"s": 24897,
"text": "That’s it!! Now you have outputs of the GAN trained on Spell’s GPU machine in your local machine. You can now visualize how your GAN performed from that output images."
},
{
"code": null,
"e": 25404,
"s": 25065,
"text": "GANs are an exciting and rapidly changing field, delivering on the promise of generative models in their ability to generate realistic examples across a range of problem domains. It is not an easy task to understand GAN or any Machine Learning and Deep Learning field overnight. It needs patience and a lot of practice plus understanding."
},
{
"code": null,
"e": 25661,
"s": 25404,
"text": "In previous days it was not possible for Aspiring ML enthusiast likes us to perform repetitive practice to see what went how. But now, a platform like Spell helps us to provide a system to run and manage our projects so that we can run and test our models."
},
{
"code": null,
"e": 25814,
"s": 25661,
"text": "What we have created is just a simple representation of how GAN can be created and what GAN can do. There are still more advanced tweaks yet to perform."
},
{
"code": null,
"e": 25911,
"s": 25814,
"text": "To take it further you can tweak the parameters and see how differently it generates the images."
},
{
"code": null,
"e": 25961,
"s": 25911,
"text": "There are still a lot of things one can research."
},
{
"code": null,
"e": 26060,
"s": 25961,
"text": "For any queries and discussion, you can join the Spell community from here: https://chat.spell.ml/"
},
{
"code": null,
"e": 26229,
"s": 26060,
"text": "[1] Generative Adversarial Network, Ian J. Goodfellow, Jean Pouget-Abadie, Mehdi Mirza, Bing Xu, David Warde-Farley, Sherjil Ozair, Aaron Courville, Yoshua Bengio, 2014"
},
{
"code": null,
"e": 26410,
"s": 26229,
"text": "[2] A Gentle Introduction to Generative Adversarial Networks (GANs), Jason Brownlee, 2019 [Online] https://machinelearningmastery.com/what-are-generative-adversarial-networks-gans/"
}
] |
io.popen() function in Lua Programming | Sometimes we want to execute the system's command and then make use of whatever was returned by them, and in order to do that we simply can either make use of the os.execute() function or io.popen() function.
The difference between the os.execute() function and the io.popen() function is that the output value of the os.execute() function is much harder to deal with, and that is the reason why it is recommended to use the io.popen() function, whose output value is much easier to handle and make use of.
io.popen() starts the program in a separate process and returns a file handle that you can use to read data from this program.
output = io.popen(command)
Now that we know what io.popen() function does, let’s use it in a Lua example.
Consider the example shown below −
local handle = io.popen("echo hello")
local result = handle:read("*a")
handle:close()
In the above code, we made use of io.popen that returns a file handle that we can use to read the output of the command.
hello | [
{
"code": null,
"e": 1271,
"s": 1062,
"text": "Sometimes we want to execute the system's command and then make use of whatever was returned by them, and in order to do that we simply can either make use of the os.execute() function or io.popen() function."
},
{
"code": null,
"e": 1569,
"s": 1271,
"text": "The difference between the os.execute() function and the io.popen() function is that the output value of the os.execute() function is much harder to deal with, and that is the reason why it is recommended to use the io.popen() function, whose output value is much easier to handle and make use of."
},
{
"code": null,
"e": 1696,
"s": 1569,
"text": "io.popen() starts the program in a separate process and returns a file handle that you can use to read data from this program."
},
{
"code": null,
"e": 1723,
"s": 1696,
"text": "output = io.popen(command)"
},
{
"code": null,
"e": 1802,
"s": 1723,
"text": "Now that we know what io.popen() function does, let’s use it in a Lua example."
},
{
"code": null,
"e": 1837,
"s": 1802,
"text": "Consider the example shown below −"
},
{
"code": null,
"e": 1923,
"s": 1837,
"text": "local handle = io.popen(\"echo hello\")\nlocal result = handle:read(\"*a\")\nhandle:close()"
},
{
"code": null,
"e": 2044,
"s": 1923,
"text": "In the above code, we made use of io.popen that returns a file handle that we can use to read the output of the command."
},
{
"code": null,
"e": 2050,
"s": 2044,
"text": "hello"
}
] |
Hierarchical Linear Modeling: A Step by Step Guide | by Kay Chansiri | Towards Data Science | In most cases, data tends to be clustered. Hierarchical Linear Modeling (HLM) enables you to explore and understand your data and decreases Type I error rates. This tutorial uses R to demonstrate the basic steps of HLM in social science research.
Before beginning the analysis, let’s briefly talk about what is HLM first.
HLM (AKA multilevel modeling) analyzes data that is clustered in an organized pattern(s), such as universities in states, non-white males in tech companies, and clinics in hospitals. HLM is an ordinary least square (OLS) that requires all assumptions met (check out my tutorial for OLS assumption and data screening) except the independence of errors assumption. The assumption is likely violated as HLM allows data across clusters to be correlated.
Predictors in HLM can be categorized into random and fixed effects. Random effects refer to variables that are not the main focus of a study but may impact the dependent variable and therefore needed to be included in the model. Fixed effects, on the other hand, are key predictors of the study. For example, a psychologist wants to predict the impact of adverse childhood trauma on one’s tendency to develop borderline personality disorder (BPD) in adulthood. Participants are from collectivist and individualistic cultures, and both cultures likely define parents’ behaviors differently. People in individualistic cultures, such as those in America or the U.K., probably consider parents’ spanking abusive, whereas collectivist individuals, such as Asians and Africans, may consider spanking as a way to enhance a child’s discipline. Thus, participants from different cultures may be variously impacted by the same behavior from their parents during childhood and may develop BPD symptoms at a different level. According to the example, childhood trauma is treated as the fixed effects based on personality literature and the researcher’s interest as a psychologist. Cultures could be treated as random effects as the variable potentially impact borderline personality development but not the main focus of the study. It is noteworthy that random effects should be categorical, whereas fixed effects could be dummy variables (a categorical variable with two levels) or continuous variables.
Some of you may think, why don’t we use a single level regression model and control for potential random effects (e.g., cultures according to the mentioned example)? Doing so may introduce wrong standard error estimates as residuals (i.e., observations in the same group) tend to be correlated. For instance, people from the same culture may view a behavior in the same way. A single-level model’s error term represents clustered data errors across levels, limiting us from knowing how much effects that the key predictor (e.g., childhood trauma) has on one’s tendency to develop BPD after controlling for cultures in which participants are nested.
Still confused? Let’s look at the equations below:
yi = β0 + β1xi +ei A single regression model — (1)
yij = β0 + uj + eij A variance components model — (2)
yij = β0 + β1xij + uj + eij A mixed model (with random intercepts) — (3)
i is the number of observation (e.g., participant #1, #2, #3..).
j is the category of culture that each observation belongs to (i.e., j = 1 is collectivism, and j = 0 is individualism).
β1 is adverse childhood trauma
y is BPD tendency.
u is variance in y that is not explained by cultures, controlling for other predictors.
e is variance in y that is not explained by childhood trauma controlling for other predictors.
According to equation 1, the error term (ei) indicates an unexplained variance of the outcome that is not accounted for by the key independent variable (e.g., childhood trauma). Equation 2 shows two error terms, including the error term of the random effects (uj) (i.e., cultures) and the error term of the fixed effects nested in the random effects (eij) (childhood trauma scores in different cultures). Equation 3 represents a mixed model that integrates equations 1 and 2, accounting for more accurate error estimates relative to the single-level regression model in equation 1.
Now that you have some foundation of HLM let’s see what you need before the analysis.
Data in a long format: Data is typically structured in a wide format (i.e., each column represents one variable, and each row depicts one observation). You need to convert data into a long format (i.e., a case’s data is distributed across rows. One column describes variable types, and another column contains values of those variables). Check out this tutorial for how to reshape data from a wide to long format.
R packages: nlme for linear and non-linear model testing
install.packages("nlme")library(nlme)
A fictional data set is used for this tutorial. We will look at whether one’s narcissism predicts their intimate relationship satisfaction, assuming that narcissistic symptoms (e.g., self absorb, lying, a lack of empathy) vary across times in which different life events occur. Thus, fixed effects are narcissistic personality disorder symptoms (NPD). The outcome variable is one’s intimate relationship satisfaction (Satisfaction). The random effects are Time with three levels coded as 1 (before marriage), 2 (1 year after marriage), and 3 (5 years after marriage).
Step 1: Import data
#Set working directorysetwd("insert your file location:")#import datalibrary(foreign)data<-read.spss("HLM.sav(your data name)," use.value.label = TRUE, to.data.frame = TRUE)
Step 2: Data cleaning
This tutorial assumes that your data has been cleaned. Check out my data preparation tutorial if you would like to learn more about cleaning your data. For my current data set, all of the assumptions, except the independence of errors, are met, consistent with the HLM requirement.
Step 1:An intercept only model.
An intercept only model is the simplest form of HLM and recommended as the first step before adding any other predictive terms. This type of model testing allows us to understand whether the outcome variable scores (i.e., relationship satisfaction in this tutorial) are significantly different from zero (i.e., participants have indicated certain relationship satisfaction levels) without considering other predictors. For an OLS model, an intercept is also known as the constant, which in an intercept only model is the mean of the outcome variable, as shown in the below equation:
We will use the gls function (i.e., generalized least squares) to fit a linear model. The gls function enables errors to be correlated and to have heterogeneous variances, which are likely the case for clustered data. I will identify my intercept only model as ‘model1.’
model1=gls(Satisfaction~1, data = data, method = "ML," na.action = "na.omit")summary(model1)
Here are the results:
Generalized least squares fit by maximum likelihood Model: Satisfaction ~ 1 Data: data AIC BIC logLik 6543.89 6555.678 -3269.945Coefficients: Value Std.Error t-value p-value(Intercept) 5.087982 0.01582679 321.479 0Standardized residuals: Min Q1 Med Q3 Max -4.9894040 -0.5142181 0.0960345 0.7644064 1.1131222Residual standard error: 0.8193328 Degrees of freedom: 2681 total; 2680 residual
The p-value is significant, indicating that participants’ relationship satisfaction is significantly different from zero.
Step 2: A random intercept model.
This step added my random effects (i.e., Time) to see whether the predictor increases a significant variance explained in my dependent variable relative to the previous intercept only model (Model 1).
Statistically speaking, if you still remember the earlier equations, the intercept for the overall regression of an intercept only model is still β0. However, for each group of random effects(i.e., each point of Time after marriage), the intercept is β0+uj (when uj represents errors of the dependent variable that are not explained by Time).
To test the random intercept model, I will use the lme function as an alternative approach in addition to the mentioned gls function. Like gls, the lme function is used to test a linear mixed-effects model, allowing nested random effects and the correlations among within-group errors. Both lme and gls enable the maximum likelihood application.
Before including Time as random effects, make sure that the variable is categorical:
is.factor(data$Time)[1] FALSE
The output says ‘false,’ so I need to convert Time into a categorical variable.
data$Time = as.factor(data$Time)#Check again whether Time is categoricalis.factor(data$Time)[1] TRUE
Modeling the random intercept:
model2 = lme(Satisfaction~1, data = data, method = “ML”, na.action = “na.omit”, random = ~1|Time)summary(model2)
The results:
Linear mixed-effects model fit by maximum likelihood Data: data AIC BIC logLik 6533.549 6551.231 -3263.775Random effects: Formula: ~1 | Time (Intercept) ResidualStdDev: 0.06596515 0.8165719Fixed effects: Satisfaction ~ 1 Value Std.Error DF t-value p-value(Intercept) 5.092783 0.04124424 2678 123.4786 0Standardized Within-Group Residuals: Min Q1 Med Q3 Max -5.0747125 -0.4169725 0.1953434 0.6985522 1.2158700Number of Observations: 2681Number of Groups: 3
Now, you may wonder how I could know whether my random effects (i.e., Time) are significant. There are a couple of ways to look at this.
Compare the AIC of the intercept only model (Model1) and AIC of the random intercept model (Model 2). AIC = 2k — 2(log-likelihood), when k is the number of variables in the model including the intercept), and the log-likelihood is a model fit measure, which can be obtained from statistical output. Check out this useful information from Satisticshowto.
Compare the AIC of the intercept only model (Model1) and AIC of the random intercept model (Model 2). AIC = 2k — 2(log-likelihood), when k is the number of variables in the model including the intercept), and the log-likelihood is a model fit measure, which can be obtained from statistical output. Check out this useful information from Satisticshowto.
From my model 1’s and 2’s outputs, you will see that model 1’s AIC = 6543.89, and Model 2’s AIC = 6533.549. Generally, the two AIC values that differ more than 2 indicate a significant difference in model fitting. The lower the AIC value is, the better fit a model. You can see that including Time as random effects in Model 2 improves my Model 1 (6543.89 -6533.549 > 2).
2. In addition to AIC, we can compare the intercept only model and the random intercept using the ANOVA function.
anova(model1, model2)
Here are the results:
Model df AIC BIC logLik Test L.Ratio p-valuemodel1 1 2 6543.890 6555.678 -3269.945 model2 2 3 6533.549 6551.231 -3263.775 1 vs 2 12.34079 4e-04
The p-value, 4e-04, is equal to 4 x 10^-4, indicating that the results are highly significant. Adding the random intercept thus significantly improves the intercept only model.
In addition to the gls and lme functions from the package nlme, we can use lmer from package lme4. In general, both lme and lmer are effective functions for mixed data analysis with some differences to be considered:
lmer does not analyze some correlation structures that lme does.nlme is a larger toolkit and their codes about mixed models are easier to understand.nlme can be used to define cross random effects easier and quicker than lme.Models fitted by the nlme packages (e.g., lme and gls function) and the lme4 package (e.g., the lmer function) assume that the sampling variances are known.
lmer does not analyze some correlation structures that lme does.
nlme is a larger toolkit and their codes about mixed models are easier to understand.
nlme can be used to define cross random effects easier and quicker than lme.
Models fitted by the nlme packages (e.g., lme and gls function) and the lme4 package (e.g., the lmer function) assume that the sampling variances are known.
To put it simply, I would say for a simple HLM analysis, both lme4 and nlme should provide close parameter values. You may check out this page for comparisons of the packages.
If you want to try lme4, you need to install merTools first:
install.packages(“merTools”)library(lme4)library(merTools)
Let’s run our random intercept model using lmer from lme4
model2.1<-lmer(Satisfaction~1+(1|Time), REML = FALSE, data = data)summary(model2.1)
Results:
Linear mixed model fit by maximum likelihood ['lmerMod']Formula: Satisfaction ~ 1 + (1 | Time) Data: dataAIC BIC logLik deviance df.resid 6533.5 6551.2 -3263.8 6527.5 2678Scaled residuals: Min 1Q Median 3Q Max -5.0747 -0.4170 0.1953 0.6986 1.2159Random effects: Groups Name Variance Std.Dev. Time (Intercept) 0.004351 0.06597 Residual 0.666790 0.81657 Number of obs: 2681, groups: Time, 3Fixed effects: Estimate Std. Error t value(Intercept) 5.09278 0.04124 123.5
You can see that the parameters of model 2 (lme4) and model 2.1 (nlme) are quite close.
We can also run an ICC (AKA Intraclass Correlation Coefficient) to see the correlation of observations within groups (i.e., relationship satisfaction within each Time point in my case). The ICC index can range from 0 to 1, with more values indicate higher homogeneity within groups (Gelman & Hill, 2007).
ICC(outcome = “Satisfaction”, group = “Time”, data = data)[1] 0.01019326
You can see that my ICC value is approximately .01, indicating that the relationship satisfaction of participants nested within a point of Time is quite different from each other.
Before moving to the next HLM analysis step, I want to make sure that my fixed effects regression coefficient is accurate. To do so, I will request a 95% confidence interval (CI) using confint.
If you are not familiar with a CI, the term refers to a range of values that may include the true population parameter with a certain range of percent confidence (mostly 95%). The formula is
x bar is the sample mean
z is confidence level value
n is sample size
s is sample SD
A CI, let’s say at 95%, contains two endpoints. We may set a lower 1% limit, meaning that the probability that the true population parameter is below the 1% limit of our data scores is only 1%. We may also set an upper 96% limit, meaning that the probability that the true population parameter is beyond the 96% limit of our data scores is only 4%. The upper and lower limits together indicate that an interval or the probability that we will find the true population parameter out of the range that we set (1% — 96%) is 5% (1% + 4%). So we have a 95% confidence interval that the true parameter will be in the upper and lower limit range of our sample. If you want to learn more about CI and its relation to t-distribution, check out this link.
Now, confidence levels are different from a confidence interval. If we re-run a study several times and estimate a parameter of interest with a 95% CI, we will get different 95% CI values each Time due to errors in our data that could be caused by several factors, such as participants’ factors, measurement errors, our moods during each analysis. However, 95% of those different CI values will cover the true parameter value, and this concept is confidence levels. If we set a lower limit of our confidence levels at 1%, it means that out of many experiments that we conduct repeatedly, the true parameter value will be lower than this 1% limit in only 1% of those many experiments. If we set an upper 96% limit, the probability that we will find the true parameter value higher than the upper limit is 4% of several experiments that we repeatedly conduct.
As humans like symmetrical things, people often set a 95% CI as a lower 2.5% limit and an upper 97.5% limit. The true population parameter value will be below the interval in 2.5% of repeated studies and above it in another 2.5% of those studies. Thus, the confidence levels will cover the true parameter in 95% of all conducted studies.
Let’s get back to our example. If I want to know the confidence levels of model 2.1, I will use the following code.
confint(model2.1)
Results:
2.5 % 97.5 %.sig01 0.0267156 0.2084871.sigma 0.7951820 0.8389382(Intercept) 4.9785129 5.2081911
The results indicate that if I re-rerun my study several times, 95% of the times, the intercept coefficient (i.e., the true mean of relationship satisfaction in population considering the random effects of Time) would be somewhere between 4.98–5.21 approximately.
Step 3: Fixed effects in the random intercept model
As I am mainly interested in the NPD’s fixed effects, I will include the predictor in my random intercept model (model 2 or model 2.1). I still let the intercept vary, meaning that each point of Time may have different intercepts of relationship satisfaction scores. To generate fixed effects in the random intercept model, I will use lme() from the nlme package.
model3 = lme(Satisfaction~ NPD, data = data, method = “ML”, na.action = “na.omit”, random = ~1|Time)summary(model3)
Results:
Linear mixed-effects model fit by maximum likelihood Data: data AIC BIC logLik 6468.46 6492.036 -3230.23Random effects: Formula: ~1 | Time (Intercept) ResidualStdDev: 0.07411888 0.8063175Fixed effects: Satisfaction ~ NPD Value Std.Error DF t-value p-value(Intercept) 4.672165 0.06842444 2677 68.28210 0NPD 0.122980 0.01491822 2677 8.24362 0 Correlation: (Intr)NPD -0.746Standardized Within-Group Residuals: Min Q1 Med Q3 Max -5.0666244 -0.4724214 0.1792983 0.7452213 1.6161859Number of Observations: 2681Number of Groups: 3
The fixed effects are significant. Let’s compare whether the random intercept model with fixed effects (Model 3) is better than the random intercept model (Model 2).
anova(model3, model2)
Results:
Model df AIC BIC logLik Test L.Ratio p-valuemodel3 1 4 6468.460 6492.036 -3230.230 model2 2 3 6533.549 6551.231 -3263.775 1 vs 2 67.0889 <.0001
The results show a significant difference across the two models, indicating that adding fixed effects significantly improved the random intercept model.
An alternative for model fitting in Step 3 is to use the lmer function:
model3.1 <-lmer(Satisfaction~1+NPD+(1| Time), REML = FALSE, data = data)summary(model3.1)
Results:
Linear mixed model fit by maximum likelihood ['lmerMod']Formula: Satisfaction ~ 1 + NPD + (1 | Time) Data: dataAIC BIC logLik deviance df.resid 6468.5 6492.0 -3230.2 6460.5 2677Scaled residuals: Min 1Q Median 3Q Max -5.0666 -0.4724 0.1793 0.7452 1.6162Random effects: Groups Name Variance Std.Dev. Time (Intercept) 0.005494 0.07412 Residual 0.650148 0.80632 Number of obs: 2681, groups: Time, 3Fixed effects: Estimate Std. Error t value(Intercept) 4.67216 0.06840 68.308NPD 0.12298 0.01491 8.247Correlation of Fixed Effects: (Intr)NPD -0.746
You see that the parameter estimates are quite close across the lme and lmer functions.
Step 4: Adding a random slope term.
In HLM, adding random slopes allow regression lines across groups of random effects to vary in terms of slope coefficients. In my case, the slopes between one’s NPD and the outcome (relationship satisfaction) across different levels of Time could vary as people’s NPD symptoms may be weakened or strengthened across Time points, depending on their life events. To test the assumption, I will nest NPD traits in Time and allow the slopes of NPD and relationship satisfaction to vary across different Time levels.
model4= lme(Satisfaction~ NPD, data = data, method = “ML”, na.action = “na.omit”, random = ~NPD|Time, control = lmeControl(msMaxIter = 200))summary(model4)
Results:
Linear mixed-effects model fit by maximum likelihood Data: data AIC BIC logLik 6472.46 6507.823 -3230.23Random effects: Formula: ~NPD | Time Structure: General positive-definite, Log-Cholesky parametrization StdDev Corr (Intercept) 0.072374062 (Intr)NPD 0.002428596 0.131 Residual 0.806315723Fixed effects: Satisfaction ~ NPD Value Std.Error DF t-value p-value(Intercept) 4.672058 0.06779927 2677 68.91016 0NPD 0.123021 0.01498469 2677 8.20977 0 Correlation: (Intr)NPD -0.742Standardized Within-Group Residuals: Min Q1 Med Q3 Max -5.0663508 -0.4722466 0.1806865 0.7456579 1.6137660Number of Observations: 2681Number of Groups: 3
The output suggests that the variation in the intercept of Time is fitted with a larger SD of 0.0724. The variation in NPD slopes in predicting relationship satisfaction is fitted with a smaller SD of 0.0024. The results indicate that participants’ relationship satisfaction likely differs across levels of Time more than the severity of NPD symptoms within each point of Time.
A weak positive correlation (Corr; r=0.131) between the intercept of Time and the NPD slope means that a more positive value of the intercept is slightly related to a more positive value of the slope. If participants’ intercepts increase by one unit of SD, the slopes will only increase by 0.131 SDs. In other words, the intercept of relationship satisfaction obviously differs across Time, whereas a variation in the slope of the correlation between NPD and relationship satisfaction is subtler. Thus, it is highly likely that Model 4 (adding the random slope term) does not significantly improve Model 3(the random intercept model). Let’s test the assumption.
anova(model3, model4)
Results:
Model df AIC BIC logLik Test L.Ratio p-valuemodel3 1 4 6468.46 6492.036 -3230.23 model4 2 6 6472.46 6507.823 -3230.23 1 vs 2 0.000787942 0.9996
As expected, adding the random slope term does not significantly improve the random intercept model and increased the AIC value (i.e., worse fit). To exclude the random slope term or not depends on several factors, such as theories that inform your data, whether excluding or including the random slope makes the models converge, and whether you would like to get a parsimonious or maximal model. It all depends on your decision and field of study. This article provides additional detail about random effects that are worth reading.
Additional steps:
If you have an interaction term, you may test whether adding the term improves your model. I will test whether adding borderline personality disorder traits (BPD), which are highly comorbid with NPD, as a moderator will improve my random intercept model (model 3). I choose to ignore the random slope model (model4) as the term does not improve the model, and studies argue that NPD traits may not change across Time points.
model3withBPD<-lme(Satisfaction~NPD+BPD+BPD*NPD,data = data, method = “ML”, na.action = “na.omit”, random = ~1|Time)summary(model3withBPD)
Results:
Linear mixed-effects model fit by maximum likelihood Data: data AIC BIC logLik 6425.735 6461.098 -3206.867Random effects: Formula: ~1 | Time (Intercept) ResidualStdDev: 0.07982052 0.7992555Fixed effects: Satisfaction ~ NPD + BPD + BPD * NPD Value Std.Error DF t-value p-value(Intercept) 4.443310 0.09474416 2675 46.89799 0NPD 0.153825 0.02988573 2675 5.14709 0BPD 0.017154 0.00251750 2675 6.81408 0NPD:BPD -0.003436 0.00058873 2675 -5.83621 0 Correlation: (Intr) NPD BPD NPD -0.807 BPD -0.417 0.251 NPD:BPD 0.600 -0.578 -0.907Standardized Within-Group Residuals: Min Q1 Med Q3 Max -5.2024359 -0.4590723 0.1866308 0.7317000 1.8891006Number of Observations: 2681Number of Groups: 3
The interaction term is significant. We will see whether adding the interaction improves Model 3:
anova(model3, model3withBPD)
As expected, adding the interaction term significantly improves my random intercept only model:
Model df AIC BIC logLik Test L.Ratio p-valuemodel3 1 4 6468.460 6492.036 -3230.230 model3withBPD 2 6 6425.735 6461.098 -3206.867 1 vs 2 46.72568 <.0001
I hope by now, you have got a sense of how to conduct simple HLM. Please stay tuned for more complex HLM analysis in the future.
For the full codes used in this tutorial, please see below: | [
{
"code": null,
"e": 418,
"s": 171,
"text": "In most cases, data tends to be clustered. Hierarchical Linear Modeling (HLM) enables you to explore and understand your data and decreases Type I error rates. This tutorial uses R to demonstrate the basic steps of HLM in social science research."
},
{
"code": null,
"e": 493,
"s": 418,
"text": "Before beginning the analysis, let’s briefly talk about what is HLM first."
},
{
"code": null,
"e": 943,
"s": 493,
"text": "HLM (AKA multilevel modeling) analyzes data that is clustered in an organized pattern(s), such as universities in states, non-white males in tech companies, and clinics in hospitals. HLM is an ordinary least square (OLS) that requires all assumptions met (check out my tutorial for OLS assumption and data screening) except the independence of errors assumption. The assumption is likely violated as HLM allows data across clusters to be correlated."
},
{
"code": null,
"e": 2436,
"s": 943,
"text": "Predictors in HLM can be categorized into random and fixed effects. Random effects refer to variables that are not the main focus of a study but may impact the dependent variable and therefore needed to be included in the model. Fixed effects, on the other hand, are key predictors of the study. For example, a psychologist wants to predict the impact of adverse childhood trauma on one’s tendency to develop borderline personality disorder (BPD) in adulthood. Participants are from collectivist and individualistic cultures, and both cultures likely define parents’ behaviors differently. People in individualistic cultures, such as those in America or the U.K., probably consider parents’ spanking abusive, whereas collectivist individuals, such as Asians and Africans, may consider spanking as a way to enhance a child’s discipline. Thus, participants from different cultures may be variously impacted by the same behavior from their parents during childhood and may develop BPD symptoms at a different level. According to the example, childhood trauma is treated as the fixed effects based on personality literature and the researcher’s interest as a psychologist. Cultures could be treated as random effects as the variable potentially impact borderline personality development but not the main focus of the study. It is noteworthy that random effects should be categorical, whereas fixed effects could be dummy variables (a categorical variable with two levels) or continuous variables."
},
{
"code": null,
"e": 3085,
"s": 2436,
"text": "Some of you may think, why don’t we use a single level regression model and control for potential random effects (e.g., cultures according to the mentioned example)? Doing so may introduce wrong standard error estimates as residuals (i.e., observations in the same group) tend to be correlated. For instance, people from the same culture may view a behavior in the same way. A single-level model’s error term represents clustered data errors across levels, limiting us from knowing how much effects that the key predictor (e.g., childhood trauma) has on one’s tendency to develop BPD after controlling for cultures in which participants are nested."
},
{
"code": null,
"e": 3136,
"s": 3085,
"text": "Still confused? Let’s look at the equations below:"
},
{
"code": null,
"e": 3187,
"s": 3136,
"text": "yi = β0 + β1xi +ei A single regression model — (1)"
},
{
"code": null,
"e": 3241,
"s": 3187,
"text": "yij = β0 + uj + eij A variance components model — (2)"
},
{
"code": null,
"e": 3314,
"s": 3241,
"text": "yij = β0 + β1xij + uj + eij A mixed model (with random intercepts) — (3)"
},
{
"code": null,
"e": 3379,
"s": 3314,
"text": "i is the number of observation (e.g., participant #1, #2, #3..)."
},
{
"code": null,
"e": 3500,
"s": 3379,
"text": "j is the category of culture that each observation belongs to (i.e., j = 1 is collectivism, and j = 0 is individualism)."
},
{
"code": null,
"e": 3531,
"s": 3500,
"text": "β1 is adverse childhood trauma"
},
{
"code": null,
"e": 3550,
"s": 3531,
"text": "y is BPD tendency."
},
{
"code": null,
"e": 3638,
"s": 3550,
"text": "u is variance in y that is not explained by cultures, controlling for other predictors."
},
{
"code": null,
"e": 3733,
"s": 3638,
"text": "e is variance in y that is not explained by childhood trauma controlling for other predictors."
},
{
"code": null,
"e": 4315,
"s": 3733,
"text": "According to equation 1, the error term (ei) indicates an unexplained variance of the outcome that is not accounted for by the key independent variable (e.g., childhood trauma). Equation 2 shows two error terms, including the error term of the random effects (uj) (i.e., cultures) and the error term of the fixed effects nested in the random effects (eij) (childhood trauma scores in different cultures). Equation 3 represents a mixed model that integrates equations 1 and 2, accounting for more accurate error estimates relative to the single-level regression model in equation 1."
},
{
"code": null,
"e": 4401,
"s": 4315,
"text": "Now that you have some foundation of HLM let’s see what you need before the analysis."
},
{
"code": null,
"e": 4815,
"s": 4401,
"text": "Data in a long format: Data is typically structured in a wide format (i.e., each column represents one variable, and each row depicts one observation). You need to convert data into a long format (i.e., a case’s data is distributed across rows. One column describes variable types, and another column contains values of those variables). Check out this tutorial for how to reshape data from a wide to long format."
},
{
"code": null,
"e": 4872,
"s": 4815,
"text": "R packages: nlme for linear and non-linear model testing"
},
{
"code": null,
"e": 4910,
"s": 4872,
"text": "install.packages(\"nlme\")library(nlme)"
},
{
"code": null,
"e": 5478,
"s": 4910,
"text": "A fictional data set is used for this tutorial. We will look at whether one’s narcissism predicts their intimate relationship satisfaction, assuming that narcissistic symptoms (e.g., self absorb, lying, a lack of empathy) vary across times in which different life events occur. Thus, fixed effects are narcissistic personality disorder symptoms (NPD). The outcome variable is one’s intimate relationship satisfaction (Satisfaction). The random effects are Time with three levels coded as 1 (before marriage), 2 (1 year after marriage), and 3 (5 years after marriage)."
},
{
"code": null,
"e": 5498,
"s": 5478,
"text": "Step 1: Import data"
},
{
"code": null,
"e": 5672,
"s": 5498,
"text": "#Set working directorysetwd(\"insert your file location:\")#import datalibrary(foreign)data<-read.spss(\"HLM.sav(your data name),\" use.value.label = TRUE, to.data.frame = TRUE)"
},
{
"code": null,
"e": 5694,
"s": 5672,
"text": "Step 2: Data cleaning"
},
{
"code": null,
"e": 5976,
"s": 5694,
"text": "This tutorial assumes that your data has been cleaned. Check out my data preparation tutorial if you would like to learn more about cleaning your data. For my current data set, all of the assumptions, except the independence of errors, are met, consistent with the HLM requirement."
},
{
"code": null,
"e": 6008,
"s": 5976,
"text": "Step 1:An intercept only model."
},
{
"code": null,
"e": 6591,
"s": 6008,
"text": "An intercept only model is the simplest form of HLM and recommended as the first step before adding any other predictive terms. This type of model testing allows us to understand whether the outcome variable scores (i.e., relationship satisfaction in this tutorial) are significantly different from zero (i.e., participants have indicated certain relationship satisfaction levels) without considering other predictors. For an OLS model, an intercept is also known as the constant, which in an intercept only model is the mean of the outcome variable, as shown in the below equation:"
},
{
"code": null,
"e": 6862,
"s": 6591,
"text": "We will use the gls function (i.e., generalized least squares) to fit a linear model. The gls function enables errors to be correlated and to have heterogeneous variances, which are likely the case for clustered data. I will identify my intercept only model as ‘model1.’"
},
{
"code": null,
"e": 6955,
"s": 6862,
"text": "model1=gls(Satisfaction~1, data = data, method = \"ML,\" na.action = \"na.omit\")summary(model1)"
},
{
"code": null,
"e": 6977,
"s": 6955,
"text": "Here are the results:"
},
{
"code": null,
"e": 7443,
"s": 6977,
"text": "Generalized least squares fit by maximum likelihood Model: Satisfaction ~ 1 Data: data AIC BIC logLik 6543.89 6555.678 -3269.945Coefficients: Value Std.Error t-value p-value(Intercept) 5.087982 0.01582679 321.479 0Standardized residuals: Min Q1 Med Q3 Max -4.9894040 -0.5142181 0.0960345 0.7644064 1.1131222Residual standard error: 0.8193328 Degrees of freedom: 2681 total; 2680 residual"
},
{
"code": null,
"e": 7565,
"s": 7443,
"text": "The p-value is significant, indicating that participants’ relationship satisfaction is significantly different from zero."
},
{
"code": null,
"e": 7599,
"s": 7565,
"text": "Step 2: A random intercept model."
},
{
"code": null,
"e": 7800,
"s": 7599,
"text": "This step added my random effects (i.e., Time) to see whether the predictor increases a significant variance explained in my dependent variable relative to the previous intercept only model (Model 1)."
},
{
"code": null,
"e": 8143,
"s": 7800,
"text": "Statistically speaking, if you still remember the earlier equations, the intercept for the overall regression of an intercept only model is still β0. However, for each group of random effects(i.e., each point of Time after marriage), the intercept is β0+uj (when uj represents errors of the dependent variable that are not explained by Time)."
},
{
"code": null,
"e": 8489,
"s": 8143,
"text": "To test the random intercept model, I will use the lme function as an alternative approach in addition to the mentioned gls function. Like gls, the lme function is used to test a linear mixed-effects model, allowing nested random effects and the correlations among within-group errors. Both lme and gls enable the maximum likelihood application."
},
{
"code": null,
"e": 8574,
"s": 8489,
"text": "Before including Time as random effects, make sure that the variable is categorical:"
},
{
"code": null,
"e": 8604,
"s": 8574,
"text": "is.factor(data$Time)[1] FALSE"
},
{
"code": null,
"e": 8684,
"s": 8604,
"text": "The output says ‘false,’ so I need to convert Time into a categorical variable."
},
{
"code": null,
"e": 8785,
"s": 8684,
"text": "data$Time = as.factor(data$Time)#Check again whether Time is categoricalis.factor(data$Time)[1] TRUE"
},
{
"code": null,
"e": 8816,
"s": 8785,
"text": "Modeling the random intercept:"
},
{
"code": null,
"e": 8929,
"s": 8816,
"text": "model2 = lme(Satisfaction~1, data = data, method = “ML”, na.action = “na.omit”, random = ~1|Time)summary(model2)"
},
{
"code": null,
"e": 8942,
"s": 8929,
"text": "The results:"
},
{
"code": null,
"e": 9487,
"s": 8942,
"text": "Linear mixed-effects model fit by maximum likelihood Data: data AIC BIC logLik 6533.549 6551.231 -3263.775Random effects: Formula: ~1 | Time (Intercept) ResidualStdDev: 0.06596515 0.8165719Fixed effects: Satisfaction ~ 1 Value Std.Error DF t-value p-value(Intercept) 5.092783 0.04124424 2678 123.4786 0Standardized Within-Group Residuals: Min Q1 Med Q3 Max -5.0747125 -0.4169725 0.1953434 0.6985522 1.2158700Number of Observations: 2681Number of Groups: 3"
},
{
"code": null,
"e": 9624,
"s": 9487,
"text": "Now, you may wonder how I could know whether my random effects (i.e., Time) are significant. There are a couple of ways to look at this."
},
{
"code": null,
"e": 9978,
"s": 9624,
"text": "Compare the AIC of the intercept only model (Model1) and AIC of the random intercept model (Model 2). AIC = 2k — 2(log-likelihood), when k is the number of variables in the model including the intercept), and the log-likelihood is a model fit measure, which can be obtained from statistical output. Check out this useful information from Satisticshowto."
},
{
"code": null,
"e": 10332,
"s": 9978,
"text": "Compare the AIC of the intercept only model (Model1) and AIC of the random intercept model (Model 2). AIC = 2k — 2(log-likelihood), when k is the number of variables in the model including the intercept), and the log-likelihood is a model fit measure, which can be obtained from statistical output. Check out this useful information from Satisticshowto."
},
{
"code": null,
"e": 10704,
"s": 10332,
"text": "From my model 1’s and 2’s outputs, you will see that model 1’s AIC = 6543.89, and Model 2’s AIC = 6533.549. Generally, the two AIC values that differ more than 2 indicate a significant difference in model fitting. The lower the AIC value is, the better fit a model. You can see that including Time as random effects in Model 2 improves my Model 1 (6543.89 -6533.549 > 2)."
},
{
"code": null,
"e": 10818,
"s": 10704,
"text": "2. In addition to AIC, we can compare the intercept only model and the random intercept using the ANOVA function."
},
{
"code": null,
"e": 10840,
"s": 10818,
"text": "anova(model1, model2)"
},
{
"code": null,
"e": 10862,
"s": 10840,
"text": "Here are the results:"
},
{
"code": null,
"e": 11057,
"s": 10862,
"text": "Model df AIC BIC logLik Test L.Ratio p-valuemodel1 1 2 6543.890 6555.678 -3269.945 model2 2 3 6533.549 6551.231 -3263.775 1 vs 2 12.34079 4e-04"
},
{
"code": null,
"e": 11234,
"s": 11057,
"text": "The p-value, 4e-04, is equal to 4 x 10^-4, indicating that the results are highly significant. Adding the random intercept thus significantly improves the intercept only model."
},
{
"code": null,
"e": 11451,
"s": 11234,
"text": "In addition to the gls and lme functions from the package nlme, we can use lmer from package lme4. In general, both lme and lmer are effective functions for mixed data analysis with some differences to be considered:"
},
{
"code": null,
"e": 11833,
"s": 11451,
"text": "lmer does not analyze some correlation structures that lme does.nlme is a larger toolkit and their codes about mixed models are easier to understand.nlme can be used to define cross random effects easier and quicker than lme.Models fitted by the nlme packages (e.g., lme and gls function) and the lme4 package (e.g., the lmer function) assume that the sampling variances are known."
},
{
"code": null,
"e": 11898,
"s": 11833,
"text": "lmer does not analyze some correlation structures that lme does."
},
{
"code": null,
"e": 11984,
"s": 11898,
"text": "nlme is a larger toolkit and their codes about mixed models are easier to understand."
},
{
"code": null,
"e": 12061,
"s": 11984,
"text": "nlme can be used to define cross random effects easier and quicker than lme."
},
{
"code": null,
"e": 12218,
"s": 12061,
"text": "Models fitted by the nlme packages (e.g., lme and gls function) and the lme4 package (e.g., the lmer function) assume that the sampling variances are known."
},
{
"code": null,
"e": 12394,
"s": 12218,
"text": "To put it simply, I would say for a simple HLM analysis, both lme4 and nlme should provide close parameter values. You may check out this page for comparisons of the packages."
},
{
"code": null,
"e": 12455,
"s": 12394,
"text": "If you want to try lme4, you need to install merTools first:"
},
{
"code": null,
"e": 12514,
"s": 12455,
"text": "install.packages(“merTools”)library(lme4)library(merTools)"
},
{
"code": null,
"e": 12572,
"s": 12514,
"text": "Let’s run our random intercept model using lmer from lme4"
},
{
"code": null,
"e": 12656,
"s": 12572,
"text": "model2.1<-lmer(Satisfaction~1+(1|Time), REML = FALSE, data = data)summary(model2.1)"
},
{
"code": null,
"e": 12665,
"s": 12656,
"text": "Results:"
},
{
"code": null,
"e": 13216,
"s": 12665,
"text": "Linear mixed model fit by maximum likelihood ['lmerMod']Formula: Satisfaction ~ 1 + (1 | Time) Data: dataAIC BIC logLik deviance df.resid 6533.5 6551.2 -3263.8 6527.5 2678Scaled residuals: Min 1Q Median 3Q Max -5.0747 -0.4170 0.1953 0.6986 1.2159Random effects: Groups Name Variance Std.Dev. Time (Intercept) 0.004351 0.06597 Residual 0.666790 0.81657 Number of obs: 2681, groups: Time, 3Fixed effects: Estimate Std. Error t value(Intercept) 5.09278 0.04124 123.5"
},
{
"code": null,
"e": 13304,
"s": 13216,
"text": "You can see that the parameters of model 2 (lme4) and model 2.1 (nlme) are quite close."
},
{
"code": null,
"e": 13609,
"s": 13304,
"text": "We can also run an ICC (AKA Intraclass Correlation Coefficient) to see the correlation of observations within groups (i.e., relationship satisfaction within each Time point in my case). The ICC index can range from 0 to 1, with more values indicate higher homogeneity within groups (Gelman & Hill, 2007)."
},
{
"code": null,
"e": 13682,
"s": 13609,
"text": "ICC(outcome = “Satisfaction”, group = “Time”, data = data)[1] 0.01019326"
},
{
"code": null,
"e": 13862,
"s": 13682,
"text": "You can see that my ICC value is approximately .01, indicating that the relationship satisfaction of participants nested within a point of Time is quite different from each other."
},
{
"code": null,
"e": 14056,
"s": 13862,
"text": "Before moving to the next HLM analysis step, I want to make sure that my fixed effects regression coefficient is accurate. To do so, I will request a 95% confidence interval (CI) using confint."
},
{
"code": null,
"e": 14247,
"s": 14056,
"text": "If you are not familiar with a CI, the term refers to a range of values that may include the true population parameter with a certain range of percent confidence (mostly 95%). The formula is"
},
{
"code": null,
"e": 14272,
"s": 14247,
"text": "x bar is the sample mean"
},
{
"code": null,
"e": 14300,
"s": 14272,
"text": "z is confidence level value"
},
{
"code": null,
"e": 14317,
"s": 14300,
"text": "n is sample size"
},
{
"code": null,
"e": 14332,
"s": 14317,
"text": "s is sample SD"
},
{
"code": null,
"e": 15078,
"s": 14332,
"text": "A CI, let’s say at 95%, contains two endpoints. We may set a lower 1% limit, meaning that the probability that the true population parameter is below the 1% limit of our data scores is only 1%. We may also set an upper 96% limit, meaning that the probability that the true population parameter is beyond the 96% limit of our data scores is only 4%. The upper and lower limits together indicate that an interval or the probability that we will find the true population parameter out of the range that we set (1% — 96%) is 5% (1% + 4%). So we have a 95% confidence interval that the true parameter will be in the upper and lower limit range of our sample. If you want to learn more about CI and its relation to t-distribution, check out this link."
},
{
"code": null,
"e": 15936,
"s": 15078,
"text": "Now, confidence levels are different from a confidence interval. If we re-run a study several times and estimate a parameter of interest with a 95% CI, we will get different 95% CI values each Time due to errors in our data that could be caused by several factors, such as participants’ factors, measurement errors, our moods during each analysis. However, 95% of those different CI values will cover the true parameter value, and this concept is confidence levels. If we set a lower limit of our confidence levels at 1%, it means that out of many experiments that we conduct repeatedly, the true parameter value will be lower than this 1% limit in only 1% of those many experiments. If we set an upper 96% limit, the probability that we will find the true parameter value higher than the upper limit is 4% of several experiments that we repeatedly conduct."
},
{
"code": null,
"e": 16274,
"s": 15936,
"text": "As humans like symmetrical things, people often set a 95% CI as a lower 2.5% limit and an upper 97.5% limit. The true population parameter value will be below the interval in 2.5% of repeated studies and above it in another 2.5% of those studies. Thus, the confidence levels will cover the true parameter in 95% of all conducted studies."
},
{
"code": null,
"e": 16390,
"s": 16274,
"text": "Let’s get back to our example. If I want to know the confidence levels of model 2.1, I will use the following code."
},
{
"code": null,
"e": 16408,
"s": 16390,
"text": "confint(model2.1)"
},
{
"code": null,
"e": 16417,
"s": 16408,
"text": "Results:"
},
{
"code": null,
"e": 16526,
"s": 16417,
"text": "2.5 % 97.5 %.sig01 0.0267156 0.2084871.sigma 0.7951820 0.8389382(Intercept) 4.9785129 5.2081911"
},
{
"code": null,
"e": 16790,
"s": 16526,
"text": "The results indicate that if I re-rerun my study several times, 95% of the times, the intercept coefficient (i.e., the true mean of relationship satisfaction in population considering the random effects of Time) would be somewhere between 4.98–5.21 approximately."
},
{
"code": null,
"e": 16842,
"s": 16790,
"text": "Step 3: Fixed effects in the random intercept model"
},
{
"code": null,
"e": 17206,
"s": 16842,
"text": "As I am mainly interested in the NPD’s fixed effects, I will include the predictor in my random intercept model (model 2 or model 2.1). I still let the intercept vary, meaning that each point of Time may have different intercepts of relationship satisfaction scores. To generate fixed effects in the random intercept model, I will use lme() from the nlme package."
},
{
"code": null,
"e": 17322,
"s": 17206,
"text": "model3 = lme(Satisfaction~ NPD, data = data, method = “ML”, na.action = “na.omit”, random = ~1|Time)summary(model3)"
},
{
"code": null,
"e": 17331,
"s": 17322,
"text": "Results:"
},
{
"code": null,
"e": 17961,
"s": 17331,
"text": "Linear mixed-effects model fit by maximum likelihood Data: data AIC BIC logLik 6468.46 6492.036 -3230.23Random effects: Formula: ~1 | Time (Intercept) ResidualStdDev: 0.07411888 0.8063175Fixed effects: Satisfaction ~ NPD Value Std.Error DF t-value p-value(Intercept) 4.672165 0.06842444 2677 68.28210 0NPD 0.122980 0.01491822 2677 8.24362 0 Correlation: (Intr)NPD -0.746Standardized Within-Group Residuals: Min Q1 Med Q3 Max -5.0666244 -0.4724214 0.1792983 0.7452213 1.6161859Number of Observations: 2681Number of Groups: 3"
},
{
"code": null,
"e": 18127,
"s": 17961,
"text": "The fixed effects are significant. Let’s compare whether the random intercept model with fixed effects (Model 3) is better than the random intercept model (Model 2)."
},
{
"code": null,
"e": 18149,
"s": 18127,
"text": "anova(model3, model2)"
},
{
"code": null,
"e": 18158,
"s": 18149,
"text": "Results:"
},
{
"code": null,
"e": 18350,
"s": 18158,
"text": "Model df AIC BIC logLik Test L.Ratio p-valuemodel3 1 4 6468.460 6492.036 -3230.230 model2 2 3 6533.549 6551.231 -3263.775 1 vs 2 67.0889 <.0001"
},
{
"code": null,
"e": 18503,
"s": 18350,
"text": "The results show a significant difference across the two models, indicating that adding fixed effects significantly improved the random intercept model."
},
{
"code": null,
"e": 18575,
"s": 18503,
"text": "An alternative for model fitting in Step 3 is to use the lmer function:"
},
{
"code": null,
"e": 18665,
"s": 18575,
"text": "model3.1 <-lmer(Satisfaction~1+NPD+(1| Time), REML = FALSE, data = data)summary(model3.1)"
},
{
"code": null,
"e": 18674,
"s": 18665,
"text": "Results:"
},
{
"code": null,
"e": 19319,
"s": 18674,
"text": "Linear mixed model fit by maximum likelihood ['lmerMod']Formula: Satisfaction ~ 1 + NPD + (1 | Time) Data: dataAIC BIC logLik deviance df.resid 6468.5 6492.0 -3230.2 6460.5 2677Scaled residuals: Min 1Q Median 3Q Max -5.0666 -0.4724 0.1793 0.7452 1.6162Random effects: Groups Name Variance Std.Dev. Time (Intercept) 0.005494 0.07412 Residual 0.650148 0.80632 Number of obs: 2681, groups: Time, 3Fixed effects: Estimate Std. Error t value(Intercept) 4.67216 0.06840 68.308NPD 0.12298 0.01491 8.247Correlation of Fixed Effects: (Intr)NPD -0.746"
},
{
"code": null,
"e": 19407,
"s": 19319,
"text": "You see that the parameter estimates are quite close across the lme and lmer functions."
},
{
"code": null,
"e": 19443,
"s": 19407,
"text": "Step 4: Adding a random slope term."
},
{
"code": null,
"e": 19955,
"s": 19443,
"text": "In HLM, adding random slopes allow regression lines across groups of random effects to vary in terms of slope coefficients. In my case, the slopes between one’s NPD and the outcome (relationship satisfaction) across different levels of Time could vary as people’s NPD symptoms may be weakened or strengthened across Time points, depending on their life events. To test the assumption, I will nest NPD traits in Time and allow the slopes of NPD and relationship satisfaction to vary across different Time levels."
},
{
"code": null,
"e": 20111,
"s": 19955,
"text": "model4= lme(Satisfaction~ NPD, data = data, method = “ML”, na.action = “na.omit”, random = ~NPD|Time, control = lmeControl(msMaxIter = 200))summary(model4)"
},
{
"code": null,
"e": 20120,
"s": 20111,
"text": "Results:"
},
{
"code": null,
"e": 20874,
"s": 20120,
"text": "Linear mixed-effects model fit by maximum likelihood Data: data AIC BIC logLik 6472.46 6507.823 -3230.23Random effects: Formula: ~NPD | Time Structure: General positive-definite, Log-Cholesky parametrization StdDev Corr (Intercept) 0.072374062 (Intr)NPD 0.002428596 0.131 Residual 0.806315723Fixed effects: Satisfaction ~ NPD Value Std.Error DF t-value p-value(Intercept) 4.672058 0.06779927 2677 68.91016 0NPD 0.123021 0.01498469 2677 8.20977 0 Correlation: (Intr)NPD -0.742Standardized Within-Group Residuals: Min Q1 Med Q3 Max -5.0663508 -0.4722466 0.1806865 0.7456579 1.6137660Number of Observations: 2681Number of Groups: 3"
},
{
"code": null,
"e": 21252,
"s": 20874,
"text": "The output suggests that the variation in the intercept of Time is fitted with a larger SD of 0.0724. The variation in NPD slopes in predicting relationship satisfaction is fitted with a smaller SD of 0.0024. The results indicate that participants’ relationship satisfaction likely differs across levels of Time more than the severity of NPD symptoms within each point of Time."
},
{
"code": null,
"e": 21914,
"s": 21252,
"text": "A weak positive correlation (Corr; r=0.131) between the intercept of Time and the NPD slope means that a more positive value of the intercept is slightly related to a more positive value of the slope. If participants’ intercepts increase by one unit of SD, the slopes will only increase by 0.131 SDs. In other words, the intercept of relationship satisfaction obviously differs across Time, whereas a variation in the slope of the correlation between NPD and relationship satisfaction is subtler. Thus, it is highly likely that Model 4 (adding the random slope term) does not significantly improve Model 3(the random intercept model). Let’s test the assumption."
},
{
"code": null,
"e": 21936,
"s": 21914,
"text": "anova(model3, model4)"
},
{
"code": null,
"e": 21945,
"s": 21936,
"text": "Results:"
},
{
"code": null,
"e": 22143,
"s": 21945,
"text": "Model df AIC BIC logLik Test L.Ratio p-valuemodel3 1 4 6468.46 6492.036 -3230.23 model4 2 6 6472.46 6507.823 -3230.23 1 vs 2 0.000787942 0.9996"
},
{
"code": null,
"e": 22677,
"s": 22143,
"text": "As expected, adding the random slope term does not significantly improve the random intercept model and increased the AIC value (i.e., worse fit). To exclude the random slope term or not depends on several factors, such as theories that inform your data, whether excluding or including the random slope makes the models converge, and whether you would like to get a parsimonious or maximal model. It all depends on your decision and field of study. This article provides additional detail about random effects that are worth reading."
},
{
"code": null,
"e": 22695,
"s": 22677,
"text": "Additional steps:"
},
{
"code": null,
"e": 23120,
"s": 22695,
"text": "If you have an interaction term, you may test whether adding the term improves your model. I will test whether adding borderline personality disorder traits (BPD), which are highly comorbid with NPD, as a moderator will improve my random intercept model (model 3). I choose to ignore the random slope model (model4) as the term does not improve the model, and studies argue that NPD traits may not change across Time points."
},
{
"code": null,
"e": 23259,
"s": 23120,
"text": "model3withBPD<-lme(Satisfaction~NPD+BPD+BPD*NPD,data = data, method = “ML”, na.action = “na.omit”, random = ~1|Time)summary(model3withBPD)"
},
{
"code": null,
"e": 23268,
"s": 23259,
"text": "Results:"
},
{
"code": null,
"e": 24123,
"s": 23268,
"text": "Linear mixed-effects model fit by maximum likelihood Data: data AIC BIC logLik 6425.735 6461.098 -3206.867Random effects: Formula: ~1 | Time (Intercept) ResidualStdDev: 0.07982052 0.7992555Fixed effects: Satisfaction ~ NPD + BPD + BPD * NPD Value Std.Error DF t-value p-value(Intercept) 4.443310 0.09474416 2675 46.89799 0NPD 0.153825 0.02988573 2675 5.14709 0BPD 0.017154 0.00251750 2675 6.81408 0NPD:BPD -0.003436 0.00058873 2675 -5.83621 0 Correlation: (Intr) NPD BPD NPD -0.807 BPD -0.417 0.251 NPD:BPD 0.600 -0.578 -0.907Standardized Within-Group Residuals: Min Q1 Med Q3 Max -5.2024359 -0.4590723 0.1866308 0.7317000 1.8891006Number of Observations: 2681Number of Groups: 3"
},
{
"code": null,
"e": 24221,
"s": 24123,
"text": "The interaction term is significant. We will see whether adding the interaction improves Model 3:"
},
{
"code": null,
"e": 24250,
"s": 24221,
"text": "anova(model3, model3withBPD)"
},
{
"code": null,
"e": 24346,
"s": 24250,
"text": "As expected, adding the interaction term significantly improves my random intercept only model:"
},
{
"code": null,
"e": 24555,
"s": 24346,
"text": "Model df AIC BIC logLik Test L.Ratio p-valuemodel3 1 4 6468.460 6492.036 -3230.230 model3withBPD 2 6 6425.735 6461.098 -3206.867 1 vs 2 46.72568 <.0001"
},
{
"code": null,
"e": 24684,
"s": 24555,
"text": "I hope by now, you have got a sense of how to conduct simple HLM. Please stay tuned for more complex HLM analysis in the future."
}
] |
jQuery Effects - Sliding | The jQuery slide methods slide elements up and down.
Click to slide down/up the panel
Because time is valuable, we deliver quick and easy learning.
At W3Schools, you can study everything you need to learn, in an accessible and handy format.
jQuery slideDown()
Demonstrates the jQuery slideDown() method.
jQuery slideUp()
Demonstrates the jQuery slideUp() method.
jQuery slideToggle()
Demonstrates the jQuery slideToggle() method.
With jQuery you can create a sliding effect on elements.
jQuery has the following slide methods:
slideDown()
slideUp()
slideToggle()
The jQuery slideDown() method is used to slide down an element.
Syntax:
The optional speed parameter specifies the duration of the effect. It can take the following values: "slow", "fast", or
milliseconds.
The optional callback parameter is a function to be executed after the sliding completes.
The following example demonstrates the slideDown() method:
The jQuery slideUp() method is used to slide up an element.
Syntax:
The optional speed parameter specifies the duration of the effect. It can take the following values: "slow", "fast", or
milliseconds.
The optional callback parameter is a function to be executed after the sliding completes.
The following example demonstrates the slideUp() method:
The jQuery slideToggle() method toggles between the slideDown() and slideUp()
methods.
If the elements have been slid down, slideToggle() will slide them up.
If the elements have been slid up, slideToggle() will slide them down.
The optional speed parameter can take the following values: "slow", "fast", milliseconds.
The optional callback parameter is a function to be executed after the
sliding completes.
The following example demonstrates the slideToggle() method:
Use a jQuery method to slide up a <div> element.
$("div").();
Start the Exercise
For a complete overview of all jQuery effects, please go to our
jQuery Effect Reference.
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
[email protected]
Your message has been sent to W3Schools. | [
{
"code": null,
"e": 53,
"s": 0,
"text": "The jQuery slide methods slide elements up and down."
},
{
"code": null,
"e": 86,
"s": 53,
"text": "Click to slide down/up the panel"
},
{
"code": null,
"e": 148,
"s": 86,
"text": "Because time is valuable, we deliver quick and easy learning."
},
{
"code": null,
"e": 241,
"s": 148,
"text": "At W3Schools, you can study everything you need to learn, in an accessible and handy format."
},
{
"code": null,
"e": 304,
"s": 241,
"text": "jQuery slideDown()\nDemonstrates the jQuery slideDown() method."
},
{
"code": null,
"e": 363,
"s": 304,
"text": "jQuery slideUp()\nDemonstrates the jQuery slideUp() method."
},
{
"code": null,
"e": 430,
"s": 363,
"text": "jQuery slideToggle()\nDemonstrates the jQuery slideToggle() method."
},
{
"code": null,
"e": 487,
"s": 430,
"text": "With jQuery you can create a sliding effect on elements."
},
{
"code": null,
"e": 527,
"s": 487,
"text": "jQuery has the following slide methods:"
},
{
"code": null,
"e": 539,
"s": 527,
"text": "slideDown()"
},
{
"code": null,
"e": 549,
"s": 539,
"text": "slideUp()"
},
{
"code": null,
"e": 563,
"s": 549,
"text": "slideToggle()"
},
{
"code": null,
"e": 627,
"s": 563,
"text": "The jQuery slideDown() method is used to slide down an element."
},
{
"code": null,
"e": 635,
"s": 627,
"text": "Syntax:"
},
{
"code": null,
"e": 770,
"s": 635,
"text": "The optional speed parameter specifies the duration of the effect. It can take the following values: \"slow\", \"fast\", or \nmilliseconds."
},
{
"code": null,
"e": 860,
"s": 770,
"text": "The optional callback parameter is a function to be executed after the sliding completes."
},
{
"code": null,
"e": 919,
"s": 860,
"text": "The following example demonstrates the slideDown() method:"
},
{
"code": null,
"e": 979,
"s": 919,
"text": "The jQuery slideUp() method is used to slide up an element."
},
{
"code": null,
"e": 987,
"s": 979,
"text": "Syntax:"
},
{
"code": null,
"e": 1122,
"s": 987,
"text": "The optional speed parameter specifies the duration of the effect. It can take the following values: \"slow\", \"fast\", or \nmilliseconds."
},
{
"code": null,
"e": 1212,
"s": 1122,
"text": "The optional callback parameter is a function to be executed after the sliding completes."
},
{
"code": null,
"e": 1269,
"s": 1212,
"text": "The following example demonstrates the slideUp() method:"
},
{
"code": null,
"e": 1357,
"s": 1269,
"text": "The jQuery slideToggle() method toggles between the slideDown() and slideUp() \nmethods."
},
{
"code": null,
"e": 1428,
"s": 1357,
"text": "If the elements have been slid down, slideToggle() will slide them up."
},
{
"code": null,
"e": 1500,
"s": 1428,
"text": "If the elements have been slid up, slideToggle() will slide them down. "
},
{
"code": null,
"e": 1590,
"s": 1500,
"text": "The optional speed parameter can take the following values: \"slow\", \"fast\", milliseconds."
},
{
"code": null,
"e": 1681,
"s": 1590,
"text": "The optional callback parameter is a function to be executed after the \nsliding completes."
},
{
"code": null,
"e": 1742,
"s": 1681,
"text": "The following example demonstrates the slideToggle() method:"
},
{
"code": null,
"e": 1791,
"s": 1742,
"text": "Use a jQuery method to slide up a <div> element."
},
{
"code": null,
"e": 1805,
"s": 1791,
"text": "$(\"div\").();\n"
},
{
"code": null,
"e": 1824,
"s": 1805,
"text": "Start the Exercise"
},
{
"code": null,
"e": 1914,
"s": 1824,
"text": "For a complete overview of all jQuery effects, please go to our \njQuery Effect Reference."
},
{
"code": null,
"e": 1947,
"s": 1914,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 1989,
"s": 1947,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 2096,
"s": 1989,
"text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:"
},
{
"code": null,
"e": 2115,
"s": 2096,
"text": "[email protected]"
}
] |
How to build your own dataset for Data Science projects | by Rashi Desai | Towards Data Science | When we talk about Data Science, the thing that precedes is data.
When I started my Data Science journey, it was the Chicago Crime Dataset or Wine Quality or Walmart sales — the common project datasets that I could get my hands on. Next, when I did IBM Data Science Professional Certification, I learned about APIs and access to robust datasets, but that comes with a price!
For a beginner data scientist, the dilemma would surely be — what to do after learning the theory? Sure there are plenty of datasets available but the free ones rarely give you a pragmatic insight into solving actual problems or sometimes they are too small to use for deep learning applications.
You want to begin with a project, construct a model and run for the results and actively looking for a dataset? Why not build your own dataset?
The first option has to be web scraping, that goes without saying. So, in this story, I will start by introducing data types and accepted data formats for Data Science projects and next, I will illustrate a quirky way of scrapping Google for your exclusive dataset (a project in itself!)
NOTE: This requires working knowledge of Python and understanding of reading and writing different file formats in Python.
Discrete data has distinct and separate values. Example: number of heads in 100 coin flips. Discrete data comes into picture only if it can take on definite values. This type of data cannot be measured but can be counted.
Continuous Data represents data that can be measured, has units and therefore can be involved in math computations. Examples: age, height, weight, salary. Continuous data can be described using intervals on the real number line.
Interval values represent ordered units that have the same difference between two intervals. Therefore we speak of interval data when we have a variable that contains numeric values that are ordered and we know the exact differences between those values. Example: The difference between 60 and 50 degrees is a measurable 10 degrees, as is the difference between 80 and 70 degrees.
Ratio values are also ordered units that have the same difference. Ratio values are the same as interval values, with the difference that they do have an absolute zero. Good examples are height, weight, length etc.
Ratio data can be added, subtracted, multiplied, divided, have measures of central tendency — mean, median, mode, standard deviation and coefficient of variation.
Categorical data represents characteristics of the data. It can be anything like a person’s gender, language, income ≥50K or <50K etc. Categorical data can also take on numerical values like 1 for female and 0 for male. (Note that those numbers don’t have mathematical meaning).
Nominal values represent discrete and unordered units and are used to label variables that have no quantitative value. When I say unordered, that means nominal data that has no order. Examples:
Colors — red, green, yellow, blue, orangeSeasons — Fall, Winter, Summer, SpringType of bank accounts — Checking, SavingsStates — Illinois, New York, California, Michigan
Colors — red, green, yellow, blue, orange
Seasons — Fall, Winter, Summer, Spring
Type of bank accounts — Checking, Savings
States — Illinois, New York, California, Michigan
Therefore, even if you change the order of values for nominal data, the meaning remains unchanged. A type of nominal data that contains only two categories (male and female) is called dichotomous
Ordinal values represent discrete and ordered units. It is therefore nearly the same as nominal data, except that it’s ordering matters. Examples:
Letter Grade — A, B, C, D, FApparel size — XS, S, M, L , XL, XXLRankings — 1,2,3Education — Elementary, High School, Bachelors, Master
Letter Grade — A, B, C, D, F
Apparel size — XS, S, M, L , XL, XXL
Rankings — 1,2,3
Education — Elementary, High School, Bachelors, Master
Because of orderliness, ordinal data is usually used when dealing with non-numeric features like happiness, customer satisfaction and similar.
The other types of data that can be used in Data Science are:
ImageAudioVideoTextTime Series
Image
Audio
Video
Text
Time Series
I am sure each of us must have been a hoarder of images. Puppies, cats, actors, exotic travel destinations. Anything works here 😄
In a lifetime, you will run out of projects to do.
Problem Statements:
Identifies the breed of a pupDetect mood of the pup
Identifies the breed of a pup
Detect mood of the pup
Dig up your hard drive for all those puppy images you’ve had in your lifetime. Begin with OpenCV, Python Imaging Library or matplotlib libraries to read the images. Make sure to keep all the images in one file format: jpeg or png. Once the images have been read, you can proceed as with any other model you’d build with a Googled dataset. Divide as 70%–30% training and test dataset, use some for validation, you got your dataset!
Ever thought of that?
Believe it or not, downloading a bunch of images is easy using google-image-downloader in Python
pip install googleimagedownloader
Next, make sure you have Google Chrome. Get the version of Chromedriver that corresponds to the version of Google Chrome that you are running and use the following command line code to download images in batches from Google Chrome
$ googleimagesdownload -k "puppies" -s medium -l 200 -o dataset/train -i puppies -cd ~/chromedriver
This command will scrape 200 images from Google Images using the keyword ‘puppies’. It will output those images to: dataset/train/puppies/. The -cd argument points to the location of the ‘chromedriver’ executable file we downloaded earlier.
Sound good?
Taylor Swift, Arijit Singh, Black Pink, BTS, J Balvin — choose your favorites from around the globe.
Problem Statement: Identify the language from an audio file.
For building your own audio dataset, collect songs (audio files) at one place. The only thing tedious about this would be collecting enough number of songs to build a model on training data, validate it and test it. Secondly, importing mp3 files in Python can be a task.
I would recommend starting by converting the mp3 files to WAV for ease. You can follow the documentation on how to read and write WAV files in Python to kickstart your work. The wave module provides a convenient interface to the WAV sound format.
One more way to have diverse audio is to source your files from soundcloud. There are tools on the internet that you can use to download audio from Soundcloud in mp3. That’s a long route for sure but once you have audio files, follow what you would ideally do with audio file projects in Python.
Guess any number of Play Date edits would work! 😛
Problem Statements:
Identify if a person is wearing a maskIdentify if the social distancing measures are followed — distance between peopleHome security system — is the person known?
Identify if a person is wearing a mask
Identify if the social distancing measures are followed — distance between people
Home security system — is the person known?
With video, the data science projects would mostly be facial recognition ones and given the extraordinary times, many of the projects similar to above problem statements are bring built by data scientists from over the world.
To build a video dataset, your source can be your family videos, you pranking your siblings, basically anything with human figures and that moves. OpenCV again would be your hero. OpenCV provides a very simple interface to read, write and display a video.
The first step to reading a video file would be to create a VideoCapture object. The video format accepted is mp4 and I believe it won’t require us format conversions unless shot on iPhones.
Next, you can apply the facial recognition algorithms to solve the problems.
Next up is acquiring data from your Fitbit or your iWatch.
In one of my blogs, I had a comment from a reader on this idea as a Data Science project and here I am writing about how to make a dataset of your own!
If you use any wearables, that could make for an interesting dataset — companies that compile with General Data Protection Regulations should send over all your personal data in nicely (ish) formatted csv files. And the next thing you know is analyzing your very own data!
I’ve recently downloaded two years worth of my fitness data from Fitbit. You can follow the process to export your Fitbit account data from here.
Thank you for reading! I hope you enjoyed the article. Do let me know what datasets are you looking forward to building and working over the summer in your Data Science journey.
Happy Data Tenting!
Disclaimer: The views expressed in this article are my own and do not represent a strict outlook.
Rashi is a graduate student at the University of Illinois, Chicago. She loves to visualize data and create insightful stories. When not rushing to meet school deadlines, she adores writing about technology, UX, and more with a good cup of hot chocolate. | [
{
"code": null,
"e": 238,
"s": 172,
"text": "When we talk about Data Science, the thing that precedes is data."
},
{
"code": null,
"e": 547,
"s": 238,
"text": "When I started my Data Science journey, it was the Chicago Crime Dataset or Wine Quality or Walmart sales — the common project datasets that I could get my hands on. Next, when I did IBM Data Science Professional Certification, I learned about APIs and access to robust datasets, but that comes with a price!"
},
{
"code": null,
"e": 844,
"s": 547,
"text": "For a beginner data scientist, the dilemma would surely be — what to do after learning the theory? Sure there are plenty of datasets available but the free ones rarely give you a pragmatic insight into solving actual problems or sometimes they are too small to use for deep learning applications."
},
{
"code": null,
"e": 988,
"s": 844,
"text": "You want to begin with a project, construct a model and run for the results and actively looking for a dataset? Why not build your own dataset?"
},
{
"code": null,
"e": 1276,
"s": 988,
"text": "The first option has to be web scraping, that goes without saying. So, in this story, I will start by introducing data types and accepted data formats for Data Science projects and next, I will illustrate a quirky way of scrapping Google for your exclusive dataset (a project in itself!)"
},
{
"code": null,
"e": 1399,
"s": 1276,
"text": "NOTE: This requires working knowledge of Python and understanding of reading and writing different file formats in Python."
},
{
"code": null,
"e": 1621,
"s": 1399,
"text": "Discrete data has distinct and separate values. Example: number of heads in 100 coin flips. Discrete data comes into picture only if it can take on definite values. This type of data cannot be measured but can be counted."
},
{
"code": null,
"e": 1850,
"s": 1621,
"text": "Continuous Data represents data that can be measured, has units and therefore can be involved in math computations. Examples: age, height, weight, salary. Continuous data can be described using intervals on the real number line."
},
{
"code": null,
"e": 2231,
"s": 1850,
"text": "Interval values represent ordered units that have the same difference between two intervals. Therefore we speak of interval data when we have a variable that contains numeric values that are ordered and we know the exact differences between those values. Example: The difference between 60 and 50 degrees is a measurable 10 degrees, as is the difference between 80 and 70 degrees."
},
{
"code": null,
"e": 2446,
"s": 2231,
"text": "Ratio values are also ordered units that have the same difference. Ratio values are the same as interval values, with the difference that they do have an absolute zero. Good examples are height, weight, length etc."
},
{
"code": null,
"e": 2609,
"s": 2446,
"text": "Ratio data can be added, subtracted, multiplied, divided, have measures of central tendency — mean, median, mode, standard deviation and coefficient of variation."
},
{
"code": null,
"e": 2888,
"s": 2609,
"text": "Categorical data represents characteristics of the data. It can be anything like a person’s gender, language, income ≥50K or <50K etc. Categorical data can also take on numerical values like 1 for female and 0 for male. (Note that those numbers don’t have mathematical meaning)."
},
{
"code": null,
"e": 3082,
"s": 2888,
"text": "Nominal values represent discrete and unordered units and are used to label variables that have no quantitative value. When I say unordered, that means nominal data that has no order. Examples:"
},
{
"code": null,
"e": 3252,
"s": 3082,
"text": "Colors — red, green, yellow, blue, orangeSeasons — Fall, Winter, Summer, SpringType of bank accounts — Checking, SavingsStates — Illinois, New York, California, Michigan"
},
{
"code": null,
"e": 3294,
"s": 3252,
"text": "Colors — red, green, yellow, blue, orange"
},
{
"code": null,
"e": 3333,
"s": 3294,
"text": "Seasons — Fall, Winter, Summer, Spring"
},
{
"code": null,
"e": 3375,
"s": 3333,
"text": "Type of bank accounts — Checking, Savings"
},
{
"code": null,
"e": 3425,
"s": 3375,
"text": "States — Illinois, New York, California, Michigan"
},
{
"code": null,
"e": 3621,
"s": 3425,
"text": "Therefore, even if you change the order of values for nominal data, the meaning remains unchanged. A type of nominal data that contains only two categories (male and female) is called dichotomous"
},
{
"code": null,
"e": 3768,
"s": 3621,
"text": "Ordinal values represent discrete and ordered units. It is therefore nearly the same as nominal data, except that it’s ordering matters. Examples:"
},
{
"code": null,
"e": 3903,
"s": 3768,
"text": "Letter Grade — A, B, C, D, FApparel size — XS, S, M, L , XL, XXLRankings — 1,2,3Education — Elementary, High School, Bachelors, Master"
},
{
"code": null,
"e": 3932,
"s": 3903,
"text": "Letter Grade — A, B, C, D, F"
},
{
"code": null,
"e": 3969,
"s": 3932,
"text": "Apparel size — XS, S, M, L , XL, XXL"
},
{
"code": null,
"e": 3986,
"s": 3969,
"text": "Rankings — 1,2,3"
},
{
"code": null,
"e": 4041,
"s": 3986,
"text": "Education — Elementary, High School, Bachelors, Master"
},
{
"code": null,
"e": 4184,
"s": 4041,
"text": "Because of orderliness, ordinal data is usually used when dealing with non-numeric features like happiness, customer satisfaction and similar."
},
{
"code": null,
"e": 4246,
"s": 4184,
"text": "The other types of data that can be used in Data Science are:"
},
{
"code": null,
"e": 4277,
"s": 4246,
"text": "ImageAudioVideoTextTime Series"
},
{
"code": null,
"e": 4283,
"s": 4277,
"text": "Image"
},
{
"code": null,
"e": 4289,
"s": 4283,
"text": "Audio"
},
{
"code": null,
"e": 4295,
"s": 4289,
"text": "Video"
},
{
"code": null,
"e": 4300,
"s": 4295,
"text": "Text"
},
{
"code": null,
"e": 4312,
"s": 4300,
"text": "Time Series"
},
{
"code": null,
"e": 4442,
"s": 4312,
"text": "I am sure each of us must have been a hoarder of images. Puppies, cats, actors, exotic travel destinations. Anything works here 😄"
},
{
"code": null,
"e": 4493,
"s": 4442,
"text": "In a lifetime, you will run out of projects to do."
},
{
"code": null,
"e": 4513,
"s": 4493,
"text": "Problem Statements:"
},
{
"code": null,
"e": 4565,
"s": 4513,
"text": "Identifies the breed of a pupDetect mood of the pup"
},
{
"code": null,
"e": 4595,
"s": 4565,
"text": "Identifies the breed of a pup"
},
{
"code": null,
"e": 4618,
"s": 4595,
"text": "Detect mood of the pup"
},
{
"code": null,
"e": 5049,
"s": 4618,
"text": "Dig up your hard drive for all those puppy images you’ve had in your lifetime. Begin with OpenCV, Python Imaging Library or matplotlib libraries to read the images. Make sure to keep all the images in one file format: jpeg or png. Once the images have been read, you can proceed as with any other model you’d build with a Googled dataset. Divide as 70%–30% training and test dataset, use some for validation, you got your dataset!"
},
{
"code": null,
"e": 5071,
"s": 5049,
"text": "Ever thought of that?"
},
{
"code": null,
"e": 5168,
"s": 5071,
"text": "Believe it or not, downloading a bunch of images is easy using google-image-downloader in Python"
},
{
"code": null,
"e": 5202,
"s": 5168,
"text": "pip install googleimagedownloader"
},
{
"code": null,
"e": 5433,
"s": 5202,
"text": "Next, make sure you have Google Chrome. Get the version of Chromedriver that corresponds to the version of Google Chrome that you are running and use the following command line code to download images in batches from Google Chrome"
},
{
"code": null,
"e": 5533,
"s": 5433,
"text": "$ googleimagesdownload -k \"puppies\" -s medium -l 200 -o dataset/train -i puppies -cd ~/chromedriver"
},
{
"code": null,
"e": 5774,
"s": 5533,
"text": "This command will scrape 200 images from Google Images using the keyword ‘puppies’. It will output those images to: dataset/train/puppies/. The -cd argument points to the location of the ‘chromedriver’ executable file we downloaded earlier."
},
{
"code": null,
"e": 5786,
"s": 5774,
"text": "Sound good?"
},
{
"code": null,
"e": 5887,
"s": 5786,
"text": "Taylor Swift, Arijit Singh, Black Pink, BTS, J Balvin — choose your favorites from around the globe."
},
{
"code": null,
"e": 5948,
"s": 5887,
"text": "Problem Statement: Identify the language from an audio file."
},
{
"code": null,
"e": 6219,
"s": 5948,
"text": "For building your own audio dataset, collect songs (audio files) at one place. The only thing tedious about this would be collecting enough number of songs to build a model on training data, validate it and test it. Secondly, importing mp3 files in Python can be a task."
},
{
"code": null,
"e": 6466,
"s": 6219,
"text": "I would recommend starting by converting the mp3 files to WAV for ease. You can follow the documentation on how to read and write WAV files in Python to kickstart your work. The wave module provides a convenient interface to the WAV sound format."
},
{
"code": null,
"e": 6762,
"s": 6466,
"text": "One more way to have diverse audio is to source your files from soundcloud. There are tools on the internet that you can use to download audio from Soundcloud in mp3. That’s a long route for sure but once you have audio files, follow what you would ideally do with audio file projects in Python."
},
{
"code": null,
"e": 6812,
"s": 6762,
"text": "Guess any number of Play Date edits would work! 😛"
},
{
"code": null,
"e": 6832,
"s": 6812,
"text": "Problem Statements:"
},
{
"code": null,
"e": 6995,
"s": 6832,
"text": "Identify if a person is wearing a maskIdentify if the social distancing measures are followed — distance between peopleHome security system — is the person known?"
},
{
"code": null,
"e": 7034,
"s": 6995,
"text": "Identify if a person is wearing a mask"
},
{
"code": null,
"e": 7116,
"s": 7034,
"text": "Identify if the social distancing measures are followed — distance between people"
},
{
"code": null,
"e": 7160,
"s": 7116,
"text": "Home security system — is the person known?"
},
{
"code": null,
"e": 7386,
"s": 7160,
"text": "With video, the data science projects would mostly be facial recognition ones and given the extraordinary times, many of the projects similar to above problem statements are bring built by data scientists from over the world."
},
{
"code": null,
"e": 7642,
"s": 7386,
"text": "To build a video dataset, your source can be your family videos, you pranking your siblings, basically anything with human figures and that moves. OpenCV again would be your hero. OpenCV provides a very simple interface to read, write and display a video."
},
{
"code": null,
"e": 7833,
"s": 7642,
"text": "The first step to reading a video file would be to create a VideoCapture object. The video format accepted is mp4 and I believe it won’t require us format conversions unless shot on iPhones."
},
{
"code": null,
"e": 7910,
"s": 7833,
"text": "Next, you can apply the facial recognition algorithms to solve the problems."
},
{
"code": null,
"e": 7969,
"s": 7910,
"text": "Next up is acquiring data from your Fitbit or your iWatch."
},
{
"code": null,
"e": 8121,
"s": 7969,
"text": "In one of my blogs, I had a comment from a reader on this idea as a Data Science project and here I am writing about how to make a dataset of your own!"
},
{
"code": null,
"e": 8394,
"s": 8121,
"text": "If you use any wearables, that could make for an interesting dataset — companies that compile with General Data Protection Regulations should send over all your personal data in nicely (ish) formatted csv files. And the next thing you know is analyzing your very own data!"
},
{
"code": null,
"e": 8540,
"s": 8394,
"text": "I’ve recently downloaded two years worth of my fitness data from Fitbit. You can follow the process to export your Fitbit account data from here."
},
{
"code": null,
"e": 8718,
"s": 8540,
"text": "Thank you for reading! I hope you enjoyed the article. Do let me know what datasets are you looking forward to building and working over the summer in your Data Science journey."
},
{
"code": null,
"e": 8738,
"s": 8718,
"text": "Happy Data Tenting!"
},
{
"code": null,
"e": 8836,
"s": 8738,
"text": "Disclaimer: The views expressed in this article are my own and do not represent a strict outlook."
}
] |
Merge objects in array with similar key JavaScript | Let’s say, we have the following array of objects −
const arr = [
{id: 1, h1: 'Daily tests'},
{id: 2, h1: 'Details'},
{id: 1, h2: 'Daily classes'},
{id: 3, h2: 'Results'},
{id: 2, h3: 'Admissions'},
{id: 1, h4: 'Students'},
{id: 2, h5: 'Alumni'},
{id: 3, h3: 'Appreciations'},
{id: 1, h5: 'Tiny Tots'},
{id: 1, h6: 'Extras'},
];
We have to write a function that converts this array into an array where all the headings (h1, h2,
h3 ...) that have the same id get clubbed inside the same object. Therefore, let’s write the code
for this function −
const arr = [
{id: 1, h1: 'Daily tests'},
{id: 2, h1: 'Details'},
{id: 1, h2: 'Daily classes'},
{id: 3, h2: 'Results'},
{id: 2, h3: 'Admissions'},
{id: 1, h4: 'Students'},
{id: 2, h5: 'Alumni'},
{id: 3, h3: 'Appreciations'},
{id: 1, h5: 'Tiny Tots'},
{id: 1, h6: 'Extras'},
];
const clubArray = (arr) => {
return arr.reduce((acc, val, ind) => {
const index = acc.findIndex(el => el.id === val.id);
if(index !== -1){
const key = Object.keys(val)[1];
acc[index][key] = val[key];
} else {
acc.push(val);
};
return acc;
}, []);
};
console.log(clubArray(arr));
The output in the console will be −
[
{
id: 1,
h1: 'Daily tests',
h2: 'Daily classes',
h4: 'Students',
h5: 'Tiny Tots',
h6: 'Extras'
},
{ id: 2, h1: 'Details', h3: 'Admissions', h5: 'Alumni' },
{ id: 3, h2: 'Results', h3: 'Appreciations' }
] | [
{
"code": null,
"e": 1114,
"s": 1062,
"text": "Let’s say, we have the following array of objects −"
},
{
"code": null,
"e": 1421,
"s": 1114,
"text": "const arr = [\n {id: 1, h1: 'Daily tests'},\n {id: 2, h1: 'Details'},\n {id: 1, h2: 'Daily classes'},\n {id: 3, h2: 'Results'},\n {id: 2, h3: 'Admissions'},\n {id: 1, h4: 'Students'},\n {id: 2, h5: 'Alumni'},\n {id: 3, h3: 'Appreciations'},\n {id: 1, h5: 'Tiny Tots'},\n {id: 1, h6: 'Extras'},\n];"
},
{
"code": null,
"e": 1638,
"s": 1421,
"text": "We have to write a function that converts this array into an array where all the headings (h1, h2,\nh3 ...) that have the same id get clubbed inside the same object. Therefore, let’s write the code\nfor this function −"
},
{
"code": null,
"e": 2287,
"s": 1638,
"text": "const arr = [\n {id: 1, h1: 'Daily tests'},\n {id: 2, h1: 'Details'},\n {id: 1, h2: 'Daily classes'},\n {id: 3, h2: 'Results'},\n {id: 2, h3: 'Admissions'},\n {id: 1, h4: 'Students'},\n {id: 2, h5: 'Alumni'},\n {id: 3, h3: 'Appreciations'},\n {id: 1, h5: 'Tiny Tots'},\n {id: 1, h6: 'Extras'},\n];\nconst clubArray = (arr) => {\n return arr.reduce((acc, val, ind) => {\n const index = acc.findIndex(el => el.id === val.id);\n if(index !== -1){\n const key = Object.keys(val)[1];\n acc[index][key] = val[key];\n } else {\n acc.push(val);\n };\n return acc;\n }, []);\n};\nconsole.log(clubArray(arr));"
},
{
"code": null,
"e": 2323,
"s": 2287,
"text": "The output in the console will be −"
},
{
"code": null,
"e": 2577,
"s": 2323,
"text": "[\n {\n id: 1,\n h1: 'Daily tests',\n h2: 'Daily classes',\n h4: 'Students',\n h5: 'Tiny Tots',\n h6: 'Extras'\n },\n { id: 2, h1: 'Details', h3: 'Admissions', h5: 'Alumni' },\n { id: 3, h2: 'Results', h3: 'Appreciations' }\n]"
}
] |
CodeIgniter - Quick Guide | CodeIgniter is an application development framework, which can be used to develop websites, using PHP. It is an Open Source framework. It has a very rich set of functionality, which will increase the speed of website development work.
If you know PHP well, then CodeIgniter will make your task easier. It has a very rich set of libraries and helpers. By using CodeIgniter, you will save a lot of time, if you are developing a website from scratch. Not only that, a website built in CodeIgniter is secure too, as it has the ability to prevent various attacks that take place through websites.
Some of the important features of CodeIgniter are listed below −
Model-View-Controller Based System
Model-View-Controller Based System
Extremely Light Weight
Extremely Light Weight
Full Featured database classes with support for several platforms.
Full Featured database classes with support for several platforms.
Query Builder Database Support
Query Builder Database Support
Form and Data Validation
Form and Data Validation
Security and XSS Filtering
Security and XSS Filtering
Session Management
Session Management
Email Sending Class. Supports Attachments, HTML/Text email, multiple protocols (sendmail, SMTP, and Mail) and more.
Email Sending Class. Supports Attachments, HTML/Text email, multiple protocols (sendmail, SMTP, and Mail) and more.
Image Manipulation Library (cropping, resizing, rotating, etc.). Supports GD, ImageMagick, and NetPBM
Image Manipulation Library (cropping, resizing, rotating, etc.). Supports GD, ImageMagick, and NetPBM
File Uploading Class
File Uploading Class
FTP Class
FTP Class
Localization
Localization
Pagination
Pagination
Data Encryption
Data Encryption
Benchmarking
Benchmarking
Full Page Caching
Full Page Caching
Error Logging
Error Logging
Application Profiling
Application Profiling
Calendaring Class
Calendaring Class
User Agent Class
User Agent Class
Zip Encoding Class
Zip Encoding Class
Template Engine Class
Template Engine Class
Trackback Class
Trackback Class
XML-RPC Library
XML-RPC Library
Unit Testing Class
Unit Testing Class
Search-engine Friendly URLs
Search-engine Friendly URLs
Flexible URI Routing
Flexible URI Routing
Support for Hooks and Class Extensions
Support for Hooks and Class Extensions
Large library of “helper” functions
Large library of “helper” functions
It is very easy to install CodeIgniter. Just follow the steps given below −
Step-1 − Download the CodeIgniter from the link CodeIgniter
Step-1 − Download the CodeIgniter from the link CodeIgniter
Step-2 − Unzip the folder.
Step-2 − Unzip the folder.
Step-3 − Upload all files and folders to your server.
Step-3 − Upload all files and folders to your server.
Step-4 − After uploading all the files to your server, visit the URL of your server, e.g., www.domain-name.com.
Step-4 − After uploading all the files to your server, visit the URL of your server, e.g., www.domain-name.com.
On visiting the URL, you will see the following screen −
The architecture of CodeIgniter application is shown below.
As shown in the figure, whenever a request comes to CodeIgniter, it will first go to index.php page.
As shown in the figure, whenever a request comes to CodeIgniter, it will first go to index.php page.
In the second step, Routing will decide whether to pass this request to step-3 for caching or to pass this request to step-4 for security check.
In the second step, Routing will decide whether to pass this request to step-3 for caching or to pass this request to step-4 for security check.
If the requested page is already in Caching, then Routing will pass the request to step-3 and the response will go back to the user.
If the requested page is already in Caching, then Routing will pass the request to step-3 and the response will go back to the user.
If the requested page does not exist in Caching, then Routing will pass the requested page to step-4 for Security checks.
If the requested page does not exist in Caching, then Routing will pass the requested page to step-4 for Security checks.
Before passing the request to Application Controller, the Security of the submitted data is checked. After the Security check, the Application Controller loads necessary Models, Libraries, Helpers, Plugins and Scripts and pass it on to View.
Before passing the request to Application Controller, the Security of the submitted data is checked. After the Security check, the Application Controller loads necessary Models, Libraries, Helpers, Plugins and Scripts and pass it on to View.
The View will render the page with available data and pass it on for Caching. As the requested page was not cached before so this time it will be cached in Caching, to process this page quickly for future requests.
The View will render the page with available data and pass it on for Caching. As the requested page was not cached before so this time it will be cached in Caching, to process this page quickly for future requests.
The image given below shows the directory structure of the CodeIgniter.
CodeIgniter directory structure is divided into 3 folders −
Application
System
User_guide
As the name indicates the Application folder contains all the code of your application that you are building. This is the folder where you will develop your project. The Application folder contains several other folders, which are explained below −
Cache − This folder contains all the cached pages of your application. These cached pages will increase the overall speed of accessing the pages.
Cache − This folder contains all the cached pages of your application. These cached pages will increase the overall speed of accessing the pages.
Config − This folder contains various files to configure the application. With the help of config.php file, user can configure the application. Using database.php file, user can configure the database of the application.
Config − This folder contains various files to configure the application. With the help of config.php file, user can configure the application. Using database.php file, user can configure the database of the application.
Controllers − This folder holds the controllers of your application. It is the basic part of your application.
Controllers − This folder holds the controllers of your application. It is the basic part of your application.
Core − This folder will contain base class of your application.
Core − This folder will contain base class of your application.
Helpers − In this folder, you can put helper class of your application.
Helpers − In this folder, you can put helper class of your application.
Hooks − The files in this folder provide a means to tap into and modify the inner workings of the framework without hacking the core files.
Hooks − The files in this folder provide a means to tap into and modify the inner workings of the framework without hacking the core files.
Language − This folder contains language related files.
Language − This folder contains language related files.
Libraries − This folder contains files of the libraries developed for your application.
Libraries − This folder contains files of the libraries developed for your application.
Logs − This folder contains files related to the log of the system.
Logs − This folder contains files related to the log of the system.
Models − The database login will be placed in this folder.
Models − The database login will be placed in this folder.
Third_party − In this folder, you can place any plugins, which will be used for your application.
Third_party − In this folder, you can place any plugins, which will be used for your application.
Views − Application’s HTML files will be placed in this folder.
Views − Application’s HTML files will be placed in this folder.
This folder contains CodeIgniter core codes, libraries, helpers and other files, which help make the coding easy. These libraries and helpers are loaded and used in web app development.
This folder contains all the CodeIgniter code of consequence, organized into various folders −
Core − This folder contains CodeIgniter’s core class. Do not modify anything here. All of your work will take place in the application folder. Even if your intent is to extend the CodeIgniter core, you have to do it with hooks, and hooks live in the application folder.
Core − This folder contains CodeIgniter’s core class. Do not modify anything here. All of your work will take place in the application folder. Even if your intent is to extend the CodeIgniter core, you have to do it with hooks, and hooks live in the application folder.
Database − The database folder contains core database drivers and other database utilities.
Database − The database folder contains core database drivers and other database utilities.
Fonts − The fonts folder contains font related information and utilities.
Fonts − The fonts folder contains font related information and utilities.
Helpers − The helpers folder contains standard CodeIgniter helpers (such as date, cookie, and URL helpers).
Helpers − The helpers folder contains standard CodeIgniter helpers (such as date, cookie, and URL helpers).
Language − The language folder contains language files. You can ignore it for now.
Language − The language folder contains language files. You can ignore it for now.
Libraries − The libraries folder contains standard CodeIgniter libraries (to help you with e-mail, calendars, file uploads, and more). You can create your own libraries or extend (and even replace) standard ones, but those will be saved in the application/libraries directory to keep them separate from the standard CodeIgniter libraries saved in this particular folder.
Libraries − The libraries folder contains standard CodeIgniter libraries (to help you with e-mail, calendars, file uploads, and more). You can create your own libraries or extend (and even replace) standard ones, but those will be saved in the application/libraries directory to keep them separate from the standard CodeIgniter libraries saved in this particular folder.
This is your user guide to CodeIgniter. It is basically, the offline version of user guide on CodeIgniter website. Using this, one can learn the functions of various libraries, helpers and classes. It is recommended to go through this user guide before building your first web app in CodeIgniter.
Beside these three folders, there is one more important file named “index.php”. In this file, we can set the application environment and error level and we can define system and application folder name. It is recommended, not to edit these settings if you do not have enough knowledge about what you are going to do.
CodeIgniter is based on the Model-View-Controller (MVC) development pattern. MVC is a software approach that separates application logic from presentation. In practice, it permits your web pages to contain minimal scripting since the presentation is separate from the PHP scripting.
The Model represents your data structures. Typically, your model classes will contain functions that help you retrieve, insert and update information in your database.
The Model represents your data structures. Typically, your model classes will contain functions that help you retrieve, insert and update information in your database.
The View is information that is being presented to a user. A View will normally be a web page, but in CodeIgniter, a view can also be a page fragment like a header or footer. It can also be an RSS page, or any other type of “page”.
The View is information that is being presented to a user. A View will normally be a web page, but in CodeIgniter, a view can also be a page fragment like a header or footer. It can also be an RSS page, or any other type of “page”.
The Controller serves as an intermediary between the Model, the View, and any other resources needed to process the HTTP request and generate a web page.
The Controller serves as an intermediary between the Model, the View, and any other resources needed to process the HTTP request and generate a web page.
A controller is a simple class file. As the name suggests, it controls the whole application by URI.
First, go to application/controllers folder. You will find two files there, index.html and Welcome.php. These files come with the CodeIgniter.
Keep these files as they are. Create a new file under the same path named “Test.php”. Write the following code in that file −
<?php
class Test extends CI_Controller {
public function index() {
echo "Hello World!";
}
}
?>
The Test class extends an in-built class called CI_Controller. This class must be extended whenever you want to make your own Controller class.
The above controller can be called by URI as follows −
http://www.your-domain.com/index.php/test
Notice the word “test” in the above URI after index.php. This indicates the class name of controller. As we have given the name of the controller “Test”, we are writing “test” after the index.php. The class name must start with uppercase letter but we need to write lowercase letter when we call that controller by URI. The general syntax for calling the controller is as follows −
http://www.your-domain.com/index.php/controller/method-name
Let us modify the above class and create another method named “hello”.
<?php
class Test extends CI_Controller {
public function index() {
echo "This is default function.";
}
public function hello() {
echo "This is hello function.";
}
}
?>
We can execute the above controller in the following three ways −
http://www.your-domain.com/index.php/test
http://www.your-domain.com/index.php/test/index
http://www.your-domain.com/index.php/test/hello
After visiting the first URI in the browser, we get the output as shown in the picture given below. As you can see, we got the output of the method “index”, even though we did not pass the name of the method the URI. We have used only controller name in the URI. In such situations, the CodeIgniter calls the default method “index”.
Visiting the second URI in the browser, we get the same output as shown in the above picture. Here, we have passed method’s name after controller’s name in the URI. As the name of the method is “index”, we are getting the same output.
Visiting the third URI in the browser, we get the output as shown in picture given below. As you can see, we are getting the output of the method “hello” because we have passed “hello” as the method name, after the name of the controller “test” in the URI.
The name of the controller class must start with an uppercase letter.
The name of the controller class must start with an uppercase letter.
The controller must be called with lowercase letter.
The controller must be called with lowercase letter.
Do not use the same name of the method as your parent class, as it will override parent class’s functionality.
Do not use the same name of the method as your parent class, as it will override parent class’s functionality.
This can be a simple or complex webpage, which can be called by the controller. The webpage may contain header, footer, sidebar etc. View cannot be called directly. Let us create a simple view. Create a new file under application/views with name “test.php” and copy the below given code in that file.
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<title>CodeIgniter View Example</title>
</head>
<body>
CodeIgniter View Example
</body>
</html>
Change the code of application/controllers/test.php file as shown in the below.
The view can be loaded by the following syntax −
$this->load->view('name');
Where name is the view file, which is being rendered. If you have planned to store the view file in some directory then you can use the following syntax −
$this->load->view('directory-name/name');
It is not necessary to specify the extension as php, unless something other than .php is used.
The index() method is calling the view method and passing the “test” as argument to view() method because we have stored the html coding in “test.php” file under application/views/test.php.
<?php
class Test extends CI_Controller {
public function index() {
$this->load->view('test');
}
}
?>
Here is the output of the above code −
The following flowchart illustrates of how everything works −
Models classes are designed to work with information in the database. As an example, if you are using CodeIgniter to manage users in your application then you must have model class, which contains functions to insert, delete, update and retrieve your users’ data.
Model classes are stored in application/models directory. Following code shows how to create model class in CodeIgniter.
<?php
Class Model_name extends CI_Model {
Public function __construct() {
parent::__construct();
}
}
?>
Where Model_name is the name of the model class that you want to give. Each model class must inherit the CodeIgniter’s CI_Model class. The first letter of the model class must be in capital letter. Following is the code for users’ model class.
<?php
Class User_model extends CI_Model {
Public function __construct() {
parent::__construct();
}
}
?>
The above model class must be saved as User_model.php. The class name and file name must be same.
Model can be called in controller. Following code can be used to load any model.
$this->load->model('model_name');
Where model_name is the name of the model to be loaded. After loading the model you can simply call its method as shown below.
$this->model_name->method();
There may be situations where you want some model class throughout your application. In such situations, it is better if we autoload it.
/*
| ---------------------------------------------------------------
| Auto-Load Models
| ---------------------------------------------------------------
| Prototype:
|
| $autoload['model'] = array('first_model', 'second_model');
|
| You can also supply an alternative model name to be assigned
| in the controller:
|
| $autoload['model'] = array('first_model' => 'first');
*/
$autoload['model'] = array();
As shown in the above figure, pass the name of the model in the array that you want to autoload and it will be autoloaded, while system is in initialization state and is accessible throughout the application.
As the name suggests, it will help you build your system. It is divided into small functions to serve different functionality. A number of helpers are available in CodeIgniter, which are listed in the table below. We can build our own helpers too.
Helpers are typically stored in your system/helpers, or application/helpers directory. Custom helpers are stored in application/helpers directory and systems’ helpers are stored in system/helpers directory. CodeIgniter will look first in your application/helpers directory. If the directory does not exist or the specified helper is not located, CodeIgniter will instead, look in your global system/helpers/ directory. Each helper, whether it is custom or system helper, must be loaded before using it.
Array Helper
The Array Helper file contains functions that assist in working with arrays.
CAPTCHA Helper
The CAPTCHA Helper file contains functions that assist in creating CAPTCHA images.
Cookie Helper
The Cookie Helper file contains functions that assist in working with cookies.
Date Helper
The Date Helper file contains functions that help you work with dates.
Directory Helper
The Directory Helper file contains functions that assist in working with directories.
Download Helper
The Download Helper lets you download data to your desktop.
Email Helper
The Email Helper provides some assistive functions for working with Email. For a more robust email solution, see CodeIgniter’s Email Class.
File Helper
The File Helper file contains functions that assist in working with files.
Form Helper
The Form Helper file contains functions that assist in working with forms.
HTML Helper
The HTML Helper file contains functions that assist in working with HTML.
Inflector Helper
The Inflector Helper file contains functions that permits you to change words to plural, singular, camel case, etc.
Language Helper
The Language Helper file contains functions that assist in working with language files.
Number Helper
The Number Helper file contains functions that help you work with numeric data.
Path Helper
The Path Helper file contains functions that permits you to work with file paths on the server.
Security Helper
The Security Helper file contains security related functions.
Smiley Helper
The Smiley Helper file contains functions that let you manage smileys (emoticons).
String Helper
The String Helper file contains functions that assist in working with strings.
Text Helper
The Text Helper file contains functions that assist in working with text.
Typography Helper
The Typography Helper file contains functions that help your format text in semantically relevant ways.
URL Helper
The URL Helper file contains functions that assist in working with URLs.
XML Helper
The XML Helper file contains functions that assist in working with XML data.
A helper can be loaded as shown below −
$this->load->helper('name');
Where name is the name of the helper. For example, if you want to load the URL Helper, then it can be loaded as −
$this->load->helper('url');
CodeIgniter has user-friendly URI routing system, so that you can easily re-route URL. Typically, there is a one-to-one relationship between a URL string and its corresponding controller class/method. The segments in a URI normally follow this pattern −
your-domain.com/class/method/id/
The first segment represents the controller class that should be invoked.
The first segment represents the controller class that should be invoked.
The second segment represents the class function, or method, that should be called.
The second segment represents the class function, or method, that should be called.
The third, and any additional segments, represent the ID and any variables that will be passed to the controller.
The third, and any additional segments, represent the ID and any variables that will be passed to the controller.
In some situations, you may want to change this default routing mechanism. CodeIgniter provides facility through which you can set your own routing rules.
There is a particular file where you can handle all these. The file is located at application/config/routes.php. You will find an array called $route in which you can customize your routing rules. The key in the $route array will decide what to route and the value will decide where to route. There are three reserved routes in CodeIgniter.
$route['default_controller']
This route indicates which controller class should be loaded, if the URI contains no data, which will be the case when people load your root URL. You are encouraged to have a default route otherwise a 404 page will appear, by default. We can set home page of website here so it will be loaded by default.
$route['404_override']
This route indicates which controller class should be loaded if the requested controller is not found. It will override the default 404 error page. It won’t affect to the show_404() function, which will continue loading the default error_404.php file in application/views/errors/error_404.php.
$route['translate_uri_dashes']
As evident by the Boolean value, this is not exactly a route. This option enables you to automatically replace dashes (‘-‘) with underscores in the controller and method URI segments, thus saving you additional route entries if you need to do that. This is required because the dash is not a valid class or method-name character and will cause a fatal error, if you try to use it.
Routes can be customized by wildcards or by using regular expressions but keep in mind that these customized rules for routing must come after the reserved rules.
We can use two wildcard characters as explained below −
(:num) − It will match a segment containing only numbers.
(:num) − It will match a segment containing only numbers.
(:any) − It will match a segment containing any character.
(:any) − It will match a segment containing any character.
Example
$route['product/:num']='catalog/product_lookup';
In the above example, if the literal word “product” is found in the first segment of the URL, and a number is found in the second segment, the “catalog” class and the “product_lookup” method are used instead.
Like wildcards, we can also use regular expressions in $route array key part. If any URI matches with regular expression, then it will be routed to the value part set into $route array.
Example
$route['products/([a-z]+)/(\d+)']='$1/id_$2';
In the above example, a URI similar to products/shoes/123 would instead call the “shoes” controller class and the “id_123” method.
After setting up the site, the next thing that we should do is to configure the site. The application/config folder contains a group of files that set basic configuration of your site.
The base URL of the site can be configured in application/config/config.php file. It is URL to your CodeIgniter root. Typically, this will be your base URL, with a trailing slash e.g.
http://example.com/
If this is not set, then CodeIgniter will try to guess the protocol, domain and path to your installation. However, you should always configure this explicitly and never rely on autoguessing, especially in production environments. You can configure the base URL in the $config array with key “base_url” as shown below −
$config['base_url'] = 'http://your-domain.com';
The database of the site can be configured in application/config/database.php file. Often we need to set up database for different environment like development and production. With the multidimensional array provided in the CodeIgniter, we can setup database for different environment. The configuration settings are stored in the array as shown below −
$db['default'] = array(
'dsn' => '',
'hostname' => 'localhost',
'username' => 'root',
'password' => '',
'database' => 'database_name',
'dbdriver' => 'mysqli',
'dbprefix' => '',
'pconnect' => TRUE,
'db_debug' => TRUE,
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array()
);
You can leave few options to their default values except hostname, username, password, database and dbdriver.
hostname − Specify location of your database here e.g. localhost or IP address
hostname − Specify location of your database here e.g. localhost or IP address
username − Set username of your database here.
username − Set username of your database here.
password − Set password of your database here.
password − Set password of your database here.
database − Set name of the database here.
database − Set name of the database here.
dbdriver − Set type of database that you are using e.g. MySQL, MySQLi, Postgre SQL, ODBC, and MS SQL.
dbdriver − Set type of database that you are using e.g. MySQL, MySQLi, Postgre SQL, ODBC, and MS SQL.
By changing the key of the array $db, you can set other configuration of database as shown below. Here, we have set the key to ‘test’ to set the database for testing environment, by keeping the other database environment as it is.
$db['test'] = array(
'dsn' => '',
'hostname' => 'localhost',
'username' => 'root',
'password' => '',
'database' => 'database_name',
'dbdriver' => 'mysqli',
'dbprefix' => '',
'pconnect' => TRUE,
'db_debug' => TRUE,
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array()
);
You can simply switch to different environment by changing the value of a variable as shown below −
$active_group = ‘default’; //This will set the default environment
$active_group = ‘test’; //This will set the test environment
This file specifies, by default, which systems should be loaded. In order to keep the framework as light-weight as possible, only the absolute minimal resources are loaded by default. One should autoload the frequently used system, rather than loading it at local level, repeatedly. Following are the things you can load automatically −
Libraries − It is a list of libraries, which should be auto loaded. Provide a list of libraries in an array as shown below to be autoloaded by CodeIgniter. In this example, we are auto loading database, email and session libraries.
Libraries − It is a list of libraries, which should be auto loaded. Provide a list of libraries in an array as shown below to be autoloaded by CodeIgniter. In this example, we are auto loading database, email and session libraries.
$autoload['libraries'] = array('database', 'email', 'session');
Drivers − These classes are located in system/libraries/ or in your application/libraries/ directory, but are also placed inside their own subdirectory and they extend the CI_Driver_Library class. They offer multiple interchangeable driver options. Following is an example to autoload cache drivers.
Drivers − These classes are located in system/libraries/ or in your application/libraries/ directory, but are also placed inside their own subdirectory and they extend the CI_Driver_Library class. They offer multiple interchangeable driver options. Following is an example to autoload cache drivers.
$autoload['drivers'] = array('cache');
Helper files − It is a list of helper files, to be autoloaded. Provide a list of libraries in the array, as shown below, to be autoloaded by CodeIgniter. In the given example, we are autoloading URL and file helpers.
Helper files − It is a list of helper files, to be autoloaded. Provide a list of libraries in the array, as shown below, to be autoloaded by CodeIgniter. In the given example, we are autoloading URL and file helpers.
$autoload['helper'] = array('url', 'file');
Custom config files − These files are intended for use, only if you have created custom config files. Otherwise, leave it blank. Following is an example of how to autoload more than one config files.
Custom config files − These files are intended for use, only if you have created custom config files. Otherwise, leave it blank. Following is an example of how to autoload more than one config files.
$autoload['config'] = array('config1', 'config2');
Language files − It is a list of language files, which should be auto loaded. Look at the example given below. Provide a list of languages in an array as shown below to be auto loaded by CodeIgniter. Keep in mind that do not include the "_lang" part of your file. For example, "codeigniter_lang.php" would be referenced as array('codeigniter');
Language files − It is a list of language files, which should be auto loaded. Look at the example given below. Provide a list of languages in an array as shown below to be auto loaded by CodeIgniter. Keep in mind that do not include the "_lang" part of your file. For example, "codeigniter_lang.php" would be referenced as array('codeigniter');
Models − It is a list of models file, which should be autoloaded. Provide a list of models in an array as shown below to be autoloaded by CodeIgniter. Following is the example of how to auto load more than one models files.
Models − It is a list of models file, which should be autoloaded. Provide a list of models in an array as shown below to be autoloaded by CodeIgniter. Following is the example of how to auto load more than one models files.
$autoload['model'] = array('first_model', 'second_model');
Like any other framework, we need to interact with the database very often and CodeIgniter makes this job easy for us. It provides rich set of functionalities to interact with database.
In this section, we will understand how the CRUD (Create, Read, Update, Delete) functions work with CodeIgniter. We will use stud table to select, update, delete, and insert the data in stud table.
We can connect to database in the following two way −
Automatic Connecting − Automatic connection can be done by using the file application/config/autoload.php. Automatic connection will load the database for each and every page. We just need to add the database library as shown below −
Automatic Connecting − Automatic connection can be done by using the file application/config/autoload.php. Automatic connection will load the database for each and every page. We just need to add the database library as shown below −
$autoload['libraries'] = array(‘database’);
Manual Connecting − If you want database connectivity for only some of the pages, then we can go for manual connecting. We can connect to database manually by adding the following line in any class.
Manual Connecting − If you want database connectivity for only some of the pages, then we can go for manual connecting. We can connect to database manually by adding the following line in any class.
$this->load->database();
Here, we are not passing any argument because everything is set in the database config file application/config/database.php
To insert a record in the database, the insert() function is used as shown in the following table −
Syntax
Parameters
$table (string) − Table name
$table (string) − Table name
$set (array) − An associative array of field/value pairs
$set (array) − An associative array of field/value pairs
$escape (bool) − Whether to escape values and identifiers
$escape (bool) − Whether to escape values and identifiers
Returns
Return Type
The following example shows how to insert a record in stud table. The $data is an array in which we have set the data and to insert this data to the table stud, we just need to pass this array to the insert function in the 2nd argument.
$data = array(
'roll_no' => ‘1’,
'name' => ‘Virat’
);
$this->db->insert("stud", $data);
To update a record in the database, the update() function is used along with set() and where() functions as shown in the tables below. The set() function will set the data to be updated.
Syntax
Parameters
$key (mixed) − Field name, or an array of field/value pairs
$key (mixed) − Field name, or an array of field/value pairs
$value (string) − Field value, if $key is a single field
$value (string) − Field value, if $key is a single field
$escape (bool) − Whether to escape values and identifiers
$escape (bool) − Whether to escape values and identifiers
Returns
Return Type
The where() function will decide which record to update.
Syntax
Parameters
$key (mixed) − Name of field to compare, or associative array
$key (mixed) − Name of field to compare, or associative array
$value (mixed) − If a single key, compared to this value
$value (mixed) − If a single key, compared to this value
$escape (bool) − Whether to escape values and identifiers
$escape (bool) − Whether to escape values and identifiers
Returns
Return Type
Finally, the update() function will update data in the database.
Syntax
Parameters
$table (string) − Table name
$table (string) − Table name
$set (array) − An associative array of field/value pairs
$set (array) − An associative array of field/value pairs
$where (string) − The WHERE clause
$where (string) − The WHERE clause
$limit (int) − The LIMIT clause
$limit (int) − The LIMIT clause
Returns
Return Type
$data = array(
'roll_no' => ‘1’,
'name' => ‘Virat’
);
$this->db->set($data);
$this->db->where("roll_no", ‘1’);
$this->db->update("stud", $data);
To delete a record in the database, the delete() function is used as shown in the following table −
Syntax
Parameters
$table (mixed) − The table(s) to delete from; string or array
$table (mixed) − The table(s) to delete from; string or array
$where (string) − The WHERE clause
$where (string) − The WHERE clause
$limit (int) − The LIMIT clause
$limit (int) − The LIMIT clause
$reset_data (bool) − TRUE to reset the query “write” clause
$reset_data (bool) − TRUE to reset the query “write” clause
Returns
Return Type
Use the following code to to delete a record in the stud table. The first argument indicates the name of the table to delete record and the second argument decides which record to delete.
$this->db->delete("stud", "roll_no = 1");
To select a record in the database, the get function is used, as shown in the following table −
Syntax
Parameters
$table (string) − The table to query array
$table (string) − The table to query array
$limit (int) − The LIMIT clause
$limit (int) − The LIMIT clause
$offset (int) − The OFFSET clause
$offset (int) − The OFFSET clause
Returns
Return Type
Use the following code to get all the records from the database. The first statement fetches all the records from “stud” table and returns the object, which will be stored in $query object. The second statement calls the result() function with $query object to get all the records as array.
$query = $this->db->get("stud");
$data['records'] = $query->result();
Database connection can be closed manually, by executing the following code −
$this->db->close();
Create a controller class called Stud_controller.php and save it at application/controller/Stud_controller.php
Here is a complete example, wherein all of the above-mentioned operations are performed. Before executing the following example, create a database and table as instructed at the starting of this chapter and make necessary changes in the database config file stored at application/config/database.php
<?php
class Stud_controller extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->helper('url');
$this->load->database();
}
public function index() {
$query = $this->db->get("stud");
$data['records'] = $query->result();
$this->load->helper('url');
$this->load->view('Stud_view',$data);
}
public function add_student_view() {
$this->load->helper('form');
$this->load->view('Stud_add');
}
public function add_student() {
$this->load->model('Stud_Model');
$data = array(
'roll_no' => $this->input->post('roll_no'),
'name' => $this->input->post('name')
);
$this->Stud_Model->insert($data);
$query = $this->db->get("stud");
$data['records'] = $query->result();
$this->load->view('Stud_view',$data);
}
public function update_student_view() {
$this->load->helper('form');
$roll_no = $this->uri->segment('3');
$query = $this->db->get_where("stud",array("roll_no"=>$roll_no));
$data['records'] = $query->result();
$data['old_roll_no'] = $roll_no;
$this->load->view('Stud_edit',$data);
}
public function update_student(){
$this->load->model('Stud_Model');
$data = array(
'roll_no' => $this->input->post('roll_no'),
'name' => $this->input->post('name')
);
$old_roll_no = $this->input->post('old_roll_no');
$this->Stud_Model->update($data,$old_roll_no);
$query = $this->db->get("stud");
$data['records'] = $query->result();
$this->load->view('Stud_view',$data);
}
public function delete_student() {
$this->load->model('Stud_Model');
$roll_no = $this->uri->segment('3');
$this->Stud_Model->delete($roll_no);
$query = $this->db->get("stud");
$data['records'] = $query->result();
$this->load->view('Stud_view',$data);
}
}
?>
Create a model class called Stud_Model.php and save it in application/models/Stud_Model.php
<?php
class Stud_Model extends CI_Model {
function __construct() {
parent::__construct();
}
public function insert($data) {
if ($this->db->insert("stud", $data)) {
return true;
}
}
public function delete($roll_no) {
if ($this->db->delete("stud", "roll_no = ".$roll_no)) {
return true;
}
}
public function update($data,$old_roll_no) {
$this->db->set($data);
$this->db->where("roll_no", $old_roll_no);
$this->db->update("stud", $data);
}
}
?>
Create a view file called Stud_add.php and save it in application/views/Stud_add.php
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<title>Students Example</title>
</head>
<body>
<form method = "" action = "">
<?php
echo form_open('Stud_controller/add_student');
echo form_label('Roll No.');
echo form_input(array('id'=>'roll_no','name'=>'roll_no'));
echo "<br/>";
echo form_label('Name');
echo form_input(array('id'=>'name','name'=>'name'));
echo "<br/>";
echo form_submit(array('id'=>'submit','value'=>'Add'));
echo form_close();
?>
</form>
</body>
</html>
Create a view file called Stud_edit.php and save it in application/views/Stud_edit.php
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<title>Students Example</title>
</head>
<body>
<form method = "" action = "">
<?php
echo form_open('Stud_controller/update_student');
echo form_hidden('old_roll_no',$old_roll_no);
echo form_label('Roll No.');
echo form_input(array('id'⇒'roll_no',
'name'⇒'roll_no','value'⇒$records[0]→roll_no));
echo "
";
echo form_label('Name');
echo form_input(array('id'⇒'name','name'⇒'name',
'value'⇒$records[0]→name));
echo "
";
echo form_submit(array('id'⇒'sub mit','value'⇒'Edit'));
echo form_close();
?>
</form>
</body>
</html>
Create a view file called Stud_view.php and save it in application/views/Stud_view.php
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<title>Students Example</title>
</head>
<body>
<a href = "<?php echo base_url(); ?>
index.php/stud/add_view">Add</a>
<table border = "1">
<?php
$i = 1;
echo "<tr>";
echo "<td>Sr#</td>";
echo "<td>Roll No.</td>";
echo "<td>Name</td>";
echo "<td>Edit</td>";
echo "<td>Delete</td>";
echo "<tr>";
foreach($records as $r) {
echo "<tr>";
echo "<td>".$i++."</td>";
echo "<td>".$r->roll_no."</td>";
echo "<td>".$r->name."</td>";
echo "<td><a href = '".base_url()."index.php/stud/edit/"
.$r->roll_no."'>Edit</a></td>";
echo "<td><a href = '".base_url()."index.php/stud/delete/"
.$r->roll_no."'>Delete</a></td>";
echo "<tr>";
}
?>
</table>
</body>
</html>
Make the following change in the route file at application/config/routes.php and add the following line at the end of file.
$route['stud'] = "Stud_controller";
$route['stud/add'] = 'Stud_controller/add_student';
$route['stud/add_view'] = 'Stud_controller/add_student_view';
$route['stud/edit/(\d+)'] = 'Stud_controller/update_student_view/$1';
$route['stud/delete/(\d+)'] = 'Stud_controller/delete_student/$1';
Now, let us execute this example by visiting the following URL in the browser. Replace the yoursite.com with your URL.
http://yoursite.com/index.php/stud
The essential part of a CodeIgniter framework is its libraries. It provides a rich set of libraries, which indirectly increase the speed of developing an application. The system library is located at system/libraries. All we need to do is to load the library that we want to use. The library can be loaded as shown below −
$this->load->library('class name');
Where class name is the name of the library that we want to load. If we want to load multiple libraries, then we can simply pass an array as argument to library() function as shown below −
$this->load->library(array('email', 'table'));
The library classes are located in system/libraries. Each class has various functions to simplify the developing work. Following table shows the names of the library class and its description.
Benchmarking Class
Benchmarking class is always active, enabling the time difference between any two marked points to be calculated.
Caching Class
This class will cache the pages, to quickly access the page speed.
Calendaring Class
Using this class, you can dynamically create calendars.
Shopping Cart Class
Using this class, you can add or remove item from Shopping Cart. The items are saved in session and will remain active until the user is browsing the site.
Config Class
Configuration preferences can be retrieved, using this class. This class is initialized automatically.
Email Class
This class provides email related functionality, like send or reply to email.
Encryption Class
This class provides two-way data encryption functionality.
File Uploading Class
This class provides functionalities related to file uploading. You can set various preferences like type of file to be uploaded, size of the files etc.
Form Validation Class
This class provides various functions to validate form.
FTP Class
This class provides various FTP related functions like transferring files to remove server, moving, renaming or deleting files on server.
Image Manipulation Class
Manipulation of image like resize, thumbnail creation, cropping, rotating, watermarking can be done with the help of this class.
Input Class
This class pre-processes the input data for security reason.
Language Class
This class is used for internationalization.
Loader Class
This class loads elements like View files, Drivers, Helpers, Models etc.
Migrations Class
This class provides functionalities related to database migrations.
Output Class
This class sends the output to browser and also, caches that webpage.
Pagination Class
This class adds pagination functionalities to web page.
Template Parser Class
The Template Parser Class can perform simple text substitution for pseudo-variables contained within your view files. It can parse simple variables or variable tag pairs.
Security Class
This class contains security related functions like XSS Filtering, CSRF etc.
Session Library
This class provides functionalities to maintain session of your application.
HTML Table
This class is used to auto-generate HTML tables from array or database results.
Trackback Class
The Trackback Class provides functions that enable you to send and receive Trackback data.
Typography Class
The Typography Class provides methods that help to format text.
Unit Testing Class
This class provides functionalities to unit test your application and generate the result.
URI Class
The URI Class provides methods that help you retrieve information from your URI strings. If you use URI routing, you can also retrieve information about the rerouted segments.
User Agent Class
The User Agent Class provides functions that help identify information about the browser, mobile device, or robot visiting your site. In addition, you can get referrer information as well as language and supported character-set information.
XML-RPC and XML-RPC Server Classes
CodeIgniter’s XML-RPC classes permit you to send requests to another server, or set up your own XML-RPC server to receive requests.
Zip Encoding Class
This class is used to create zip archives of your data.
CodeIgniter has rich set of libraries, which you can find in system/libraries folder but CodeIgniter is not just limited to system libraries, you can create your own libraries too, which can be stored in application/libraries folder. You can create libraries in three ways.
Create new library
Extend the native library
Replace the native library
While creating new library one should keep in mind, the following things −
The name of the file must start with a capital letter e.g. Mylibrary.php
The class name must start with a capital letter e.g. class Mylibrary
The name of the class and name of the file must match.
Mylibrary.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Mylibrary {
public function some_function() {
}
}
/* End of file Mylibrary.php */
Loading the Custom Library
The above library can be loaded by simply executing the following line in your controller.
$this->load->library(‘mylibrary’);
mylibrary is the name of your library and you can write it in lowercase as well as uppercase letters. Use the name of the library without “.php” extension. After loading the library, you can also call the function of that class as shown below.
$this->mylibrary->some_function();
Sometimes, you may need to add your own functionality to the library provided by CodeIgniter. CodeIgniter provides facility by which you can extend the native library and add your own functions. To achieve this, you must extend the class of native library class. For example if you want to extend the Email library then it can be done as shown below −
Class MY_Email extends CI_Email {
}
Here, in the above example, MY_Email class is extending the native library’s email class CI_Email. This library can be loaded by the standard way of loading email library. Save the above code in file My_Email.php
In some situations, you do not want to use the native library the way it works and want to replace it with your own way. This can be done by replacing the native library. To achieve this, you just need to give the same class name as it is named in native library. For example, if you want to replace the Email class, then use the code as shown below. Save your file name with Email.php and give a class name to CI_Email.
Email.php
Class CI_Email {
}
Many times, while using application, we come across errors. It is very annoying for the users if the errors are not handled properly. CodeIgniter provides an easy error handling mechanism.
You would like the messages to be displayed, when the application is in developing mode rather than in production mode as the error messages can be solved easily at the developing stage.
The environment of your application can be changed, by changing the line given below from index.php file. This can be set to anything but normally there are three values (development, test, production) used for this purpose.
define('ENVIRONMENT', isset($_SERVER['CI_ENV']) ? $_SERVER['CI_ENV'] : 'development');
Different environment will require different levels of error reporting. By default, development mode will display errors and testing and live mode will hide them. CodeIgniter provides three functions as shown below to handle errors.
show_error() function displays errors in HTML format at the top of the screen.
show_error() function displays errors in HTML format at the top of the screen.
Syntax
Parameters
$message (mixed) − Error message
$message (mixed) − Error message
$status_code (int) − HTTP Response status code
$status_code (int) − HTTP Response status code
$heading (string) − Error page heading
$heading (string) − Error page heading
Return Type
show_404() function displays error if you are trying to access a page which does not exist.
show_404() function displays error if you are trying to access a page which does not exist.
Syntax
Parameters
$page (string) – URI string
$page (string) – URI string
$log_error (bool) – Whether to log the error
$log_error (bool) – Whether to log the error
Return Type
log_message() function is used to write log messages. This is useful when you want to write custom messages.
log_message() function is used to write log messages. This is useful when you want to write custom messages.
Syntax
Parameters
$level (string) − Log level: ‘error’, ‘debug’ or ‘info’
$level (string) − Log level: ‘error’, ‘debug’ or ‘info’
$message (string) − Message to log
$message (string) − Message to log
$php_error (bool) − Whether we’re logging a native PHP error message
$php_error (bool) − Whether we’re logging a native PHP error message
Return Type
Logging can be enabled in application/config/config.php file. Given below is the screenshot of config.php file, where you can set threshold value.
/*
|--------------------------------------------------------------------------------
| Error Logging Threshold
|--------------------------------------------------------------------------------
| You can enable error logging by setting a threshold over zero. The
| threshold determines what gets logged. Threshold options are:
|
| 0 = Disable logging, Error logging TURNED OFF
| 1 = Error Message (including PHP errors)
| 2 = Debug Message
| 3 = Informational Messages
| 4 = All Messages
|
| You can also pass an array with threshold levels to show individual error types
|
| array(2) = Debug Message, without Error Messages
| For a live site you'll usually only enable Errors (1) to be logged otherwise
| your log files will fill up very fast.
|
*/
$config['log_threshold'] = 0;
You can find the log messages in application/log/. Make sure that this directory is writable before you enable log files.
Various templates for error messages can be found in application/views/errors/cli or application/views/errors/html.
Using File Uploading class, we can upload files and we can also, restrict the type and size of the file to be uploaded. Follow the steps shown in the given example to understand the file uploading process in CodeIgniter.
Copy the following code and store it at application/view/Upload_form.php.
<html>
<head>
<title>Upload Form</title>
</head>
<body>
<?php echo $error;?>
<?php echo form_open_multipart('upload/do_upload');?>
<form action = "" method = "">
<input type = "file" name = "userfile" size = "20" />
<br /><br />
<input type = "submit" value = "upload" />
</form>
</body>
</html>
Copy the code given below and store it at application/view/Upload_success.php
<html>
<head>
<title>Upload Form</title>
</head>
<body>
<h3>Your file was successfully uploaded!</h3>
<ul>
<?phpforeach ($upload_data as $item => $value):?>
<li><?php echo $item;?>: <?php echo $value;?></li>
<?phpendforeach; ?>
</ul>
<p><?php echo anchor('upload', 'Upload Another File!'); ?></p>
</body>
</html>
Copy the code given below and store it at application/controllers/Upload.php. Create “uploads” folder at the root of CodeIgniter i.e. at the parent directory of application folder.
<?php
class Upload extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->helper(array('form', 'url'));
}
public function index() {
$this->load->view('upload_form', array('error' => ' ' ));
}
public function do_upload() {
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 100;
$config['max_width'] = 1024;
$config['max_height'] = 768;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('userfile')) {
$error = array('error' => $this->upload->display_errors());
$this->load->view('upload_form', $error);
}
else {
$data = array('upload_data' => $this->upload->data());
$this->load->view('upload_success', $data);
}
}
}
?>
Make the following change in the route file in application/config/routes.php and add the following line at the end of file.
$route['upload'] = 'Upload';
Now let us execute this example by visiting the following URL in the browser. Replace the yoursite.com with your URL.
http://yoursite.com/index.php/upload
It will produce the following screen −
After successfully uploading a file, you will see the following screen −
Sending email in CodeIgniter is much easier. You also configure the preferences regarding email in CodeIgniter. CodeIgniter provides following features for sending emails −
Multiple Protocols − Mail, Sendmail, and SMTP
TLS and SSL Encryption for SMTP
Multiple recipients
CC and BCCs
HTML or Plaintext email
Attachments
Word wrapping
Priorities
BCC Batch Mode, enabling large email lists to be broken into small BCC batches.
Email Debugging tools
Email class has the following functions to simplify the job of sending emails.
$from (string) − “From” e-mail address
$name (string) − “From” display name
$return_path (string) − Optional email address to redirect undelivered e-mail to
$replyto (string) − E-mail address for replies
$name (string) − Display name for the reply-to e-mail address
$to (mixed) − Comma-delimited string or an array of e-mail addresses
$cc (mixed) − Comma-delimited string or an array of e-mail addresses
$bcc (mixed) − Comma-delimited string or an array of e-mail addresses
$limit (int) − Maximum number of e-mails to send per batch
$subject (string) − E-mail subject line
$body (string) − E-mail message body
$str (string) − Alternative e-mail message body
$header (string) − Header name
$value (string) − Header value
$clear_attachments (bool) – Whether or not to clear attachments
$auto_clear (bool) − Whether to clear message data automatically
$filename (string) − File name
$disposition (string) − ‘disposition’ of the attachment. Most email clients make their own decision regardless of the MIME specification used here.iana
$newname (string) − Custom file name to use in the e-mail
$mime (string) − MIME type to use (useful for buffered data)
$filename (string) − Existing attachment filename
To send an email using CodeIgniter, first you have to load email library using the following −
$this->load->library('email');
After loading the library, simply execute the following functions to set necessary elements to send an email. The from() function is used to set − from where the email is being sent and to() function is used − to whom the email is being sent. The subject() and message() function is used to set the subject and message of the email.
$this->email->from('[email protected]', 'Your Name');
$this->email->to('[email protected]');
$this->email->subject('Email Test');
$this->email->message('Testing the email class.');
After that, execute the send() function as shown below to send an email.
$this->email->send();
Create a controller file Email_controller.php and save it in application/controller/Email_controller.php.
<?php
class Email_controller extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->library('session');
$this->load->helper('form');
}
public function index() {
$this->load->helper('form');
$this->load->view('email_form');
}
public function send_mail() {
$from_email = "[email protected]";
$to_email = $this->input->post('email');
//Load email library
$this->load->library('email');
$this->email->from($from_email, 'Your Name');
$this->email->to($to_email);
$this->email->subject('Email Test');
$this->email->message('Testing the email class.');
//Send mail
if($this->email->send())
$this->session->set_flashdata("email_sent","Email sent successfully.");
else
$this->session->set_flashdata("email_sent","Error in sending Email.");
$this->load->view('email_form');
}
}
?>
Create a view file called email_form.php and save it at application/views/email_form.php
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<title>CodeIgniter Email Example</title>
</head>
<body>
<?php
echo $this->session->flashdata('email_sent');
echo form_open('/Email_controller/send_mail');
?>
<input type = "email" name = "email" required />
<input type = "submit" value = "SEND MAIL">
<?php
echo form_close();
?>
</body>
</html>
Make the changes in the routes.php file in application/config/routes.php and add the following line at the end of the file.
$route['email'] = 'Email_Controller';
Execute the above example by visiting the following link. Replace the yoursite.com with the URL of your site.
http://yoursite.com/index.php/email
Validation is an important process while building web application. It ensures that the data that we are getting is proper and valid to store or process. CodeIgniter has made this task very easy. Let us understand this process with a simple example.
Create a view file myform.php and save the below code it in application/views/myform.php. This page will display form where user can submit his name and we will validate this page to ensure that it should not be empty while submitting.
<html>
<head>
<title>My Form</title>
</head>
<body>
<form action = "" method = "">
<?php echo validation_errors(); ?>
<?php echo form_open('form'); ?>
<h5>Name</h5>
<input type = "text" name = "name" value = "" size = "50" />
<div><input type = "submit" value = "Submit" /></div>
</form>
</body>
</html>
Create a view file formsuccess.php and save it in application/views/formsuccess.php. This page will be displayed if the form is validated successfully.
<html>
<head>
<title>My Form</title>
</head>
<body>
<h3>Your form was successfully submitted!</h3>
<p><?php echo anchor('form', 'Try it again!'); ?></p>
</body>
</html>
Create a controller file Form.php and save it in application/controller/Form.php. This form will either, show errors if it is not validated properly or redirected to formsuccess.php page.
<?php
class Form extends CI_Controller {
public function index() {
/* Load form helper */
$this->load->helper(array('form'));
/* Load form validation library */
$this->load->library('form_validation');
/* Set validation rule for name field in the form */
$this->form_validation->set_rules('name', 'Name', 'required');
if ($this->form_validation->run() == FALSE) {
$this->load->view('myform');
}
else {
$this->load->view('formsuccess');
}
}
}
?>
Add the following line in application/config/routes.php.
$route['validation'] = 'Form';
Let us execute this example by visiting the following URL in the browser. This URL may be different based on your site.
http://yoursite.com/index.php/validation
It will produce the following screen −
We have added a validation in the controller − Name is required field before submitting the form. So, if you click the submit button without entering anything in the name field, then you will be asked to enter the name before submitting as shown in the screen below.
After entering the name successfully, you will be redirected to the screen as shown below.
In the above example, we have used the required rule setting. There are many rules available in the CodeIgniter, which are described below.
The following is a list of all the native rules that are available to use −
required
matches
regex_match
differs
is_unique
min_length
max_length
exact_length
greater_than
greater_than_equal_to
less_than
less_than_equal_to
in_list
alpha
alpha_numeric
alpha_numeric_spaces
alpha_dash
numeric
integer
decimal
is_natural
is_natural_no_zero
valid_url
valid_email
valid_emails
valid_ip
valid_base64
When building websites, we often need to track user’s activity and state and for this purpose, we have to use session. CodeIgniter has session class for this purpose.
Sessions data are available globally through the site but to use those data we first need to initialize the session. We can do that by executing the following line in constructor.
$this->load->library('session');
After loading the session library, you can simply use the session object as shown below.
$this->session
In PHP, we simply use $_SESSION array to set any data in session as shown below.
$_SESSION[‘key’] = value;
Where ‘key’ is the key of array and value is assigned on right side of equal to sign.
The same thing can be done in CodeIgniter as shown below.
$this->session->set_userdata('some_name', 'some_value');
set_userdata() function takes two arguments. The first argument, some_name, is the name of the session variable, under which, some_value will be stored.
set_userdata() function also supports another syntax in which you can pass array to store values as shown below.
$newdata = array(
'username' => 'johndoe',
'email' => '[email protected]',
'logged_in' => TRUE
);
$this->session->set_userdata($newdata);
In PHP, we can remove data stored in session using the unset() function as shown below.
unset($_SESSION[‘some_name’]);
Removing session data in CodeIgniter is very simple as shown below. The below version of unset_userdata() function will remove only one variable from session.
$this->session->unset_userdata('some_name');
If you want to remove more values from session or to remove an entire array you can use the below version of unset_userdata() function.
$this->session->unset_userdata($array_items);
After setting data in session, we can also retrieve that data as shown below. Userdata() function will be used for this purpose. This function will return NULL if the data you are trying to access is not available.
$name = $this->session->userdata('name');
Create a controller class called Session_controller.php and save it in application/controller/Session_controller.php.
<?php
class Session_controller extends CI_Controller {
public function index() {
//loading session library
$this->load->library('session');
//adding data to session
$this->session->set_userdata('name','virat');
$this->load->view('session_view');
}
public function unset_session_data() {
//loading session library
$this->load->library('session');
//removing session data
$this->session->unset_userdata('name');
$this->load->view('session_view');
}
}
?>
Create a view file called session_view.php and save it in application/views/session_view.php
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<title>CodeIgniter Session Example</title>
</head>
<body>
Welcome <?php echo $this->session->userdata('name'); ?>
<br>
<a href = 'http://localhost:85/CodeIgniter-3.0.1/CodeIgniter3.0.1/index.php/sessionex/unset'>
Click Here</a> to unset session data.
</body>
</html>
Make the changes in the routes.php file in application/config/routes.php and add the following line at the end of the file.
$route['sessionex'] = 'Session_Controller';
Execute the above example by using the following address. Replace yoursite.com with the URL of your site.
While building web application, we need to store some data for only one time and after that we want to remove that data. For example, to display some error message or information message. In PHP, we have to do it manually but CodeIgniter has made this job simple for us. In CodeIgniter, flashdata will only be available until the next request, and it will get deleted automatically.
We can simply store flashdata as shown below.
$this->session->mark_as_flash('item');
mark_as_flash() function is used for this purpose, which takes only one argument of the value to be stored. We can also pass an array to store multiple values.
mark_as_flash() function is used for this purpose, which takes only one argument of the value to be stored. We can also pass an array to store multiple values.
set_flashdata() function can also be used, which takes two arguments, name and value, as shown below. We can also pass an array.
set_flashdata() function can also be used, which takes two arguments, name and value, as shown below. We can also pass an array.
$this->session->set_flashdata('item','value');
Flashdata can be retrieved using the flashdata() function which takes one argument of the item to be fetched as shown below. flashdata() function makes sure that you are getting only flash data and not any other data.
$this->session->flashdata('item');
If you do not pass any argument, then you can get an array with the same function.
Create a class called FlashData_Controller.php and save it at application/controller/FlashData_Controller.php.
<?php
class FlashData_Controller extends CI_Controller {
public function index() {
//Load session library
$this->load->library('session');
//redirect to home page
$this->load->view('flashdata_home');
}
public function add() {
//Load session library
$this->load->library('session');
$this->load->helper('url');
//add flash data
$this->session->set_flashdata('item','item-value');
//redirect to home page
redirect('flashdata');
}
}
?>
Create a view file called flashdata_home.php and save it in application/views/ flashdata_home.php
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<title>CodeIgniter Flashdata Example</title>
</head>
<body>
Flash Data Example
<h2><?php echo $this->session->flashdata('item'); ?></h2>
<a href = 'flashdata/add'>Click Here</a> to add flash data.
</body>
</html>
Make the changes in the routes.php file in application/config/routes.php and add the following line at the end of the file.
$route['flashdata'] = 'FlashData_Controller';
$route['flashdata/add'] = 'FlashData_Controller/add';
Execute the above example by visiting the following link. Replace the yoursite.com with the URL of your site.
http://yoursite.com/index.php/flashdata
After visiting the above URL, you will see a screen as shown below.
Click on “Click Here” link and you will see a screen as shown below. Here, in this screen you will see a value of flash data variable. Refresh the page again and you will see a screen like above and flash data variable will be removed automatically.
In some situations, where you want to remove data stored in session after some specific time-period, this can be done using tempdata functionality in CodeIgniter.
To add data as tempdata, we have to use mark_as_tempdata() function. This function takes two argument items or items to be stored as tempdata and the expiration time for those items are as shown below.
// 'item' will be erased after 300 seconds(5 minutes)
$this->session->mark_as_temp('item',300);
You can also pass an array to store multiple data. All the items stored below will be expired after 300 seconds.
$this->session->mark_as_temp(array('item','item2'),300);
You can also set different expiration time for each item as shown below.
// 'item' will be erased after 300 seconds, while 'item2'
// will do so after only 240 seconds
$this->session->mark_as_temp(array(
'item'=>300,
'item2'=>240
));
We can retrieve the tempdata using tempdata() function. This function assures that you are getting only tempdata and not any other data. Look at the example given below to see how to retrieve tempdata. tempdata() function will take one argument of the item to be fetched.
$this->session->tempdata('item');
If you omit the argument, then you can retrieve all the existing tempdata.
Tempdata is removed automatically after its expiration time but if you want to remove tempdata before that, then you can do as shown below using the unset_tempdata() function, which takes one argument of the item to be removed.
$this->session->unset_tempdata('item');
Create a class called Tempdata_controller.php and save it in application/controller/Tempdata_controller.php.
<?php
class Tempdata_controller extends CI_Controller {
public function index() {
$this->load->library('session');
$this->load->view('tempdata_view');
}
public function add() {
$this->load->library('session');
$this->load->helper('url');
//tempdata will be removed after 5 seconds
$this->session->set_tempdata('item','item-value',5);
redirect('tempdata');
}
}
?>
Create a file called tempdata_view.php and save it in application/views/tempdata_view.php
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<title>CodeIgniter Tempdata Example</title>
</head>
<body>
Temp Data Example
<h2><?php echo $this->session->tempdata('item'); ?></h2>
<a href = 'tempdata/add'>Click Here</a> to add temp data.
</body>
</html>
Make the changes in the routes.php file in application/config/routes.php and add the following line at the end of the file.
$route['tempdata'] = "Tempdata_controller";
$route['tempdata/add'] = "Tempdata_controller/add";
Execute the above example by visiting the following link. Replace the yoursite.com with the URL of your site.
http://yoursite.com/index.php/tempdata
After visiting the above URL, you will see a screen as shown below.
Click on “Click Here” link and you will see a screen as shown below.
Here, in this screen you will see a value of temp data variable. Refresh the same page after five seconds again as we have set the temp data for five seconds and you will see a screen like above and temp data variable will be removed automatically after five seconds. If you refresh the same page before 5 seconds, then the temp data will not be removed, as the time period is not over.
In PHP, we are using the session_destroy() function to destroy the session and in CodeIgniter we can destroy the function as shown below.
$this->session->sess_destroy();
After calling this function, all the session data including the flashdata and tempdata will be deleted permanently and cannot be retrieved back.
Cookie is a small piece of data sent from web server to store on client’s computer. CodeIgniter has one helper called “Cookie Helper” for cookie management.
Syntax
Parameters
$name (mixed) − Cookie name or associative array of all of the parameters available to this function
$name (mixed) − Cookie name or associative array of all of the parameters available to this function
$value (string) − Cookie value
$value (string) − Cookie value
$expire (int) − Number of seconds until expiration
$expire (int) − Number of seconds until expiration
$domain (string) − Cookie domain (usually: .yourdomain.com)
$domain (string) − Cookie domain (usually: .yourdomain.com)
$path (string) − Cookie path
$path (string) − Cookie path
$prefix (string) − Cookie name prefix
$prefix (string) − Cookie name prefix
$secure (bool) − Whether to only send the cookie through HTTPS
$secure (bool) − Whether to only send the cookie through HTTPS
$httponly (bool) − Whether to hide the cookie from JavaScript
$httponly (bool) − Whether to hide the cookie from JavaScript
Return Type
In the set_cookie() function, we can pass all the values using two ways. In the first way, only array can be passed and in the second way, individual parameters can also be passed.
Syntax
Parameters
$index (string) − Cookie name
$index (string) − Cookie name
$xss_clean (bool) − Whether to apply XSS filtering to the returned value
$xss_clean (bool) − Whether to apply XSS filtering to the returned value
Return
Return Type
The get_cookie() function is used to get the cookie that has been set using the set_cookie() function.
Syntax
Parameters
$name (string) − Cookie name
$name (string) − Cookie name
$domain (string) − Cookie domain (usually: .yourdomain.com)
$domain (string) − Cookie domain (usually: .yourdomain.com)
$path (string) − Cookie path
$path (string) − Cookie path
$prefix (string) − Cookie name prefix
$prefix (string) − Cookie name prefix
Return Type
The delete_cookie() function is used to delete the cookie().
Create a controller called Cookie_controller.php and save it at application/controller/Cookie_controller.php
<?php
class Cookie_controller extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->helper(array('cookie', 'url'));
}
public function index() {
set_cookie('cookie_name','cookie_value','3600');
$this->load->view('Cookie_view');
}
public function display_cookie() {
echo get_cookie('cookie_name');
$this->load->view('Cookie_view');
}
public function deletecookie() {
delete_cookie('cookie_name');
redirect('cookie/display');
}
}
?>
Create a view file called Cookie_view.php and save it at application/views/Cookie_view.php
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<title>CodeIgniter View Example</title>
</head>
<body>
<a href = 'display'>Click Here</a> to view the cookie.<br>
<a href = 'delete'>Click Here</a> to delete the cookie.
</body>
</html>
Change the routes.php file in application/config/routes.php to add route for the above controller and add the following line at the end of the file.
$route['cookie'] = "Cookie_controller";
$route['cookie/display'] = "Cookie_controller/display_cookie";
$route['cookie/delete'] = "Cookie_controller/deletecookie";
After that, you can execute the following URL in the browser to execute the example.
http://yoursite.com/index.php/cookie
It will produce an output as shown in the following screenshot.
CodeIgniter library functions and helper functions need to be initialized before they are used but there are some common functions, which do not need to be initialized.
These common functions and their descriptions are given below.
$version (string) − Version number
$file (string) − File path
$key (string) − Config item key
$code (int) − HTTP Response status code
$text (string) − A custom message to set with the status code
$str (string) − Input string
$url_encoded (bool) − Whether to remove URLencoded characters as well
$var (mixed) − Variable to escape (string or array)
$function_name (string) − Function name
Given below is an example, which demonstrates all of the above functions.
Here we have created only one controller in which we will use the above functions. Copy the below given code and save it at application/controller/CommonFun_Controller.php.
<?php
class CommonFun_Controller extends CI_Controller {
public function index() {
set_status_header(200);
echo is_php('5.3')."<br>";
var_dump(is_really_writable('./Form.php'));
echo config_item('language')."<br>";
echo remove_invisible_characters('This is a test','UTF8')."<br>";
$str = '< This > is \' a " test & string';
echo html_escape($str)."<br>";
echo "is_https():".var_dump(is_https())."<br>";
echo "is_cli():".var_dump(is_cli())."<br>";
var_dump(function_usable('test'))."<br>";
echo "get_mimes():".print_r(get_mimes())."<br>";
}
public function test() {
echo "Test function";
}
}
?>
Change the routes.php file at application/config/routes.php to add route for the above controller and add the following line at the end of the file.
$route['commonfunctions'] = 'CommonFun_Controller';
Type the following URL in the address bar of your browser to execute the example.
http://yoursite.com/index.php/commonfunctions
Caching a page will improve the page load speed. If the page is cached, then it will be stored in its fully rendered state. Next time, when the server gets a request for the cached page, it will be directly sent to the requested browser.
Cached files are stored in application/cache folder. Caching can be enabled on per page basis. While enabling the cache, we need to set the time, until which it needs to remain in cached folder and after that period, it will be deleted automatically.
Caching can be enabled by executing the following line in any of the controller’s method.
$this->output->cache($n);
Where $n is the number of minutes, you wish the page to remain cached between refreshes.
Cache file gets deleted when it expires but when you want to delete it manually, then you have to disable it. You can disable the caching by executing the following line.
// Deletes cache for the currently requested URI
$this->output->delete_cache();
// Deletes cache for /foo/bar
$this->output->delete_cache('/foo/bar');
Create a controller called Cache_controller.php and save it in application/controller/Cache_controller.php
<?php
class Cache_controller extends CI_Controller {
public function index() {
$this->output->cache(1);
$this->load->view('test');
}
public function delete_file_cache() {
$this->output->delete_cache('cachecontroller');
}
}
?>
Create a view file called test.php and save it in application/views/test.php
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<title>CodeIgniter View Example</title>
</head>
<body>
CodeIgniter View Example
</body>
</html>
Change the routes.php file in application/config/routes.php to add route for the above controller and add the following line at the end of the file.
$route['cachecontroller'] = 'Cache_controller';
$route['cachecontroller/delete'] = 'Cache_controller/delete_file_cache';
Type the following URL in the browser to execute the example.
http://yoursite.com/index.php/cachecontroller
After visiting the above URL, you will see that a cache file for this will be created in application/cache folder. To delete the file, visit the following URL.
http://yoursite.com/index.php/cachecontroller/delete
While building web application, we often need to redirect the user from one page to another page. CodeIgniter makes this job easy for us. The redirect() function is used for this purpose.
Syntax
Parameters
$uri (string) − URI string
$uri (string) − URI string
$method (string) − Redirect method (‘auto’, ‘location’ or ‘refresh’)
$method (string) − Redirect method (‘auto’, ‘location’ or ‘refresh’)
$code (string) − HTTP Response code (usually 302 or 303)
$code (string) − HTTP Response code (usually 302 or 303)
Return type
The first argument can have two types of URI. We can pass full site URL or URI segments to the controller you want to direct.
The second optional parameter can have any of the three values from auto, location or refresh. The default is auto.
The third optional parameter is only available with location redirects and it allows you to send specific HTTP response code.
Create a controller called Redirect_controller.php and save it in application/controller/Redirect_controller.php
<?php
class Redirect_controller extends CI_Controller {
public function index() {
/*Load the URL helper*/
$this->load->helper('url');
/*Redirect the user to some site*/
redirect('http://www.tutorialspoint.com');
}
public function computer_graphics() {
/*Load the URL helper*/
$this->load->helper('url');
redirect('http://www.tutorialspoint.com/computer_graphics/index.htm');
}
public function version2() {
/*Load the URL helper*/
$this->load->helper('url');
/*Redirect the user to some internal controller’s method*/
redirect('redirect/computer_graphics');
}
}
?>
Change the routes.php file in application/config/routes.php to add route for the above controller and add the following line at the end of the file.
$route['redirect'] = 'Redirect_controller';
$route['redirect/version2'] = 'Redirect_controller/version2';
$route['redirect/computer_graphics'] = 'Redirect_controller/computer_graphics';
Type the following URL in the browser, to execute the example.
http://yoursite.com/index.php/redirect
The above URL will redirect you to the tutorialspoint.com website and if you visit the following URL, then it will redirect you to the computer graphics tutorial at tutorialspoint.com.
http://yoursite.com/index.php/redirect/computer_graphics
When building a web application, we are very much concerned about the performance of the website in terms of how much time the controller took to execute and how much memory is used. Not only the performance, but we also need to see the insights of data like POST data, data of database queries, session data etc. for debugging purpose while developing some application. CodeIgniter has made this job easier for us by profiling an application.
To enable profiling of your application, simply execute the command given below in any of the method of your controller.
$this->output->enable_profiler(TRUE);
The report of the profiling can be seen at the bottom of the page after enabling it.
To disable profiling of your application, simply execute the command given below in any of the method of your controller.
$this->output->enable_profiler(FALSE);
Profiling can be done on section basis. You can enable or disable profiling of a section by setting a Boolean value TRUE or FALSE. If you want to set profiling on the application then you can do in a file located in application/config/profiler.php
For example, the following command will enable profiling queries for the whole application.
$config['queries'] = TRUE;
In the following table, the key is the parameter, which can be set in the config array to enable or disable a particular profile.
benchmarks
config
controller_info
get
http_headers
memory_usage
post
queries
uri_string
session_data
query_toggle_count
The profiler set in the file in application/config/profiler.php can be overridden by using the set_profiler_sections() function in controllers as shown below.
$sections = array(
'config' => TRUE,
'queries' => TRUE
);
$this->output->set_profiler_sections($sections);
If you want to measure the time taken to execute a set of lines or memory usage, you can calculate it by using Benchmarking points in CodeIgniter. There is a separate “Benchmarking” class for this purpose in CodeIgniter.
This class is loaded automatically; you do not have to load it. It can be used anywhere in your controller, view, and model classes. All you have to do is to mark a start point and end point and then execute the elapsed_time() function between these two marked points and you can get the time it took to execute that code as shown below.
<?php
$this->benchmark->mark('code_start');
// Some code happens here
$this->benchmark->mark('code_end');
echo $this->benchmark->elapsed_time('code_start', 'code_end');
?>
To display the memory usage, use the function memory_usage() as shown in the following code.
<?php
echo $this->benchmark->memory_usage();
?>
Create a controller called Profiler_controller.php and save it in application/controller/Profiler_controller.php
<?php
class Profiler_controller extends CI_Controller {
public function index() {
//enable profiler
$this->output->enable_profiler(TRUE);
$this->load->view('test');
}
public function disable() {
//disable profiler
$this->output->enable_profiler(FALSE);
$this->load->view('test');
}
}
?>
Create a view file called test.php and save it at application/views/test.php
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<title>CodeIgniter View Example</title>
</head>
<body>
CodeIgniter View Example
</body>
</html>
Change the routes.php file at application/config/routes.php to add route for the above controller and add the following line at the end of the file.
$route['profiler'] = "Profiler_controller";
$route['profiler/disable'] = "Profiler_controller/disable"
After that, you can type the following URL in the address bar of your browser to execute the example.
http://yoursite.com/index.php/profiler
The above URL will enable the profiler and it will produce an output as shown in the following screenshot.
To disable the profiling, execute the following URL.
http://yoursite.com/index.php/profiler/disable
Adding JavaScript and CSS (Cascading Style Sheet) file in CodeIgniter is very simple. You have to create JS and CSS folder in root directory and copy all the .js files in JS folder and .css files in CSS folder as shown in the figure.
For example, let us assume, you have created one JavaScript file sample.js and one CSS file style.css. Now, to add these files into your views, load URL helper in your controller as shown below.
$this->load->helper('url');
After loading the URL helper in controller, simply add the below given lines in the view file, to load the sample.js and style.css file in the view as shown below.
<link rel = "stylesheet" type = "text/css"
href = "<?php echo base_url(); ?>css/style.css">
<script type = 'text/javascript' src = "<?php echo base_url();
?>js/sample.js"></script>
Create a controller called Test.php and save it in application/controller/Test.php
<?php
class Test extends CI_Controller {
public function index() {
$this->load->helper('url');
$this->load->view('test');
}
}
?>
Create a view file called test.php and save it at application/views/test.php
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<title>CodeIgniter View Example</title>
<link rel = "stylesheet" type = "text/css"
href = "<?php echo base_url(); ?>css/style.css">
<script type = 'text/javascript' src = "<?php echo base_url();
?>js/sample.js"></script>
</head>
<body>
<a href = 'javascript:test()'>Click Here</a> to execute the javascript function.
</body>
</html>
Create a CSS file called style.css and save it at css/style.css
body {
background:#000;
color:#FFF;
}
Create a JS file called sample.js and save it at js/sample.js
function test() {
alert('test');
}
Change the routes.php file in application/config/routes.php to add route for the above controller and add the following line at the end of the file.
$route['profiler'] = "Profiler_controller";
$route['profiler/disable'] = "Profiler_controller/disable"
Use the following URL in the browser to execute the above example.
http://yoursite.com/index.php/test
The language class in CodeIgniter provides an easy way to support multiple languages for internationalization. To some extent, we can use different language files to display text in many different languages.
We can put different language files in application/language directory. System language files can be found at system/language directory, but to add your own language to your application, you should create a separate folder for each language in application/language directory.
To create a language file, you must end it with _lang.php. For example, you want to create a language file for French language, then you must save it with french_lang.php. Within this file you can store all your language texts in key, value combination in $lang array as shown below.
$lang[‘key’] = ‘val’;
To use any of the language in your application, you must first load the file of that particular language to retrieve various texts stored in that file. You can use the following code to load the language file.
$this->lang->load('filename', 'language');
filename − It is the name of file you want to load. Don’t use extension of file here but only name of file.
filename − It is the name of file you want to load. Don’t use extension of file here but only name of file.
Language − It is the language set containing it.
Language − It is the language set containing it.
To fetch a line from the language file simply execute the following code.
$this->lang->line('language_key');
Where language_key is the key parameter used to fetch value of the key in the loaded language file.
If you need some language globally, then you can autoload it in application/config/autoload.php file as shown below.
| -----------------------------------------------------------------------
| Auto-load Language files
| -----------------------------------------------------------------------
| Prototype:
| $autoload['config'] = array('config1', 'config2');
|
| NOTE: Do not include the "_lang" part of your file. For example
| "codeigniter_lang.php" would be referenced as array('codeigniter');
|
*/
$autoload['language'] = array();
Simply, pass the different languages to be autoloaded by CodeIgniter.
Create a controller called Lang_controller.php and save it in application/controller/Lang_controller.php
<?php
class Lang_controller extends CI_Controller {
public function index(){
//Load form helper
$this->load->helper('form');
//Get the selected language
$language = $this->input->post('language');
//Choose language file according to selected lanaguage
if($language == "french")
$this->lang->load('french_lang','french');
else if($language == "german")
$this->lang->load('german_lang','german');
else
$this->lang->load('english_lang','english');
//Fetch the message from language file.
$data['msg'] = $this->lang->line('msg');
$data['language'] = $language;
//Load the view file
$this->load->view('lang_view',$data);
}
}
?>
Create a view file called lang_view.php and save it at application/views/ lang_view.php
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<title>CodeIgniter Internationalization Example</title>
</head>
<body>
<?php
echo form_open('/lang');
?>
<select name = "language" onchange = "javascript:this.form.submit();">
<?php
$lang = array('english'=>"English",'french'=>"French",'german'=>"German");
foreach($lang as $key=>$val) {
if($key == $language)
echo "<option value = '".$key."' selected>".$val."</option>";
else
echo "<option value = '".$key."'>".$val."</option>";
}
?>
</select>
<br>
<?php
form_close();
echo $msg;
?>
</body>
</html>
Create three folders called English, French, and German in application/language as shown in the figure below.
Copy the below given code and save it in english_lang.php file in application/language/english folder.
<?php
$lang['msg'] = "CodeIgniter Internationalization example.";
?>
Copy the below given code and save it in french_lang.php file in application/language/French folder.
<?php
$lang['msg'] = "Exemple CodeIgniter internationalisation.";
?>
Copy the below given code and save it in german_lang.php file in application/language/german folder.
<?php
$lang['msg'] = "CodeIgniter Internationalisierung Beispiel.";
?>
Change the routes.php file in application/config/routes.php to add route for the above controller and add the following line at the end of the file.
$route['lang'] = "Lang_controller";
Execute the following URL in the browser to execute the above example.
http://yoursite.com/index.php/lang
It will produce an output as shown in the following screenshot. If you change the language in the dropdown list, the language of the sentence written below the dropdown will also change accordingly.
XSS means cross-site scripting. CodeIgniter comes with XSS filtering security. This filter will prevent any malicious JavaScript code or any other code that attempts to hijack cookie and do malicious activities. To filter data through the XSS filter, use the xss_clean() method as shown below.
$data = $this->security->xss_clean($data);
You should use this function only when you are submitting data. The optional second Boolean parameter can also be used to check image file for XSS attack. This is useful for file upload facility. If its value is true, means image is safe and not otherwise.
SQL injection is an attack made on database query. In PHP, we are use mysql_real_escape_string() function to prevent this along with other techniques but CodeIgniter provides inbuilt functions and libraries to prevent this.
We can prevent SQL Injection in CodeIgniter in the following three ways −
Escaping Queries
Query Biding
Active Record Class
<?php
$username = $this->input->post('username');
$query = 'SELECT * FROM subscribers_tbl WHERE user_name = '.
$this->db->escape($email);
$this->db->query($query);
?>
$this->db->escape() function automatically adds single quotes around the data and determines the data type so that it can escape only string data.
<?php
$sql = "SELECT * FROM some_table WHERE id = ? AND status = ? AND author = ?";
$this->db->query($sql, array(3, 'live', 'Rick'));
?>
In the above example, the question mark(?) will be replaced by the array in the second parameter of query() function. The main advantage of building query this way is that the values are automatically escaped which produce safe queries. CodeIgniter engine does it for you automatically, so you do not have to remember it.
<?php
$this->db->get_where('subscribers_tbl',array
('status'=> active','email' => '[email protected]'));
?>
Using active records, query syntax is generated by each database adapter. It also allows safer queries, since the values escape automatically.
In production environment, we often do not want to display any error message to the users. It is good if it is enabled in the development environment for debugging purposes. These error messages may contain some information, which we should not show to the site users for security reasons.
There are three CodeIgniter files related with errors.
Different environment requires different levels of error reporting. By default, development will show errors but testing and live will hide them. There is a file called index.php in root directory of CodeIgniter, which is used for this purpose. If we pass zero as argument to error_reporting() function then that will hide all the errors.
Even if you have turned off the PHP errors, MySQL errors are still open. You can turn this off in application/config/database.php. Set the db_debug option in $db array to FALSE as shown below.
$db['default']['db_debug'] = FALSE;
Another way is to transfer the errors to log files. So, it will not be displayed to users on the site. Simply, set the log_threshold value in $config array to 1 in application/cofig/config.php file as shown below.
$config['log_threshold'] = 1;
CSRF stands for cross-site request forgery. You can prevent this attack by enabling it in the application/config/config.php file as shown below.
$config['csrf_protection'] = TRUE;
When you are creating form using form_open() function, it will automatically insert a CSRF as hidden field. You can also manually add the CSRF using the get_csrf_token_name() and get_csrf_hash() function. The get_csrf_token_name() function will return the name of the CSRF and get_csrf_hash() will return the hash value of CSRF.
The CSRF token can be regenerated every time for submission or you can also keep it same throughout the life of CSRF cookie. By setting the value TRUE, in config array with key ‘csrf_regenerate’ will regenerate token as shown below.
$config['csrf_regenerate'] = TRUE;
You can also whitelist URLs from CSRF protection by setting it in the config array using the key ‘csrf_exclude_uris’ as shown below. You can also use regular expression.
$config['csrf_exclude_uris'] = array('api/person/add');
Many developers do not know how to handle password in web applications, which is probably why numerous hackers find it so easy to break into the systems. One should keep in mind the following points while handling passwords −
DO NOT store passwords in plain-text format.
DO NOT store passwords in plain-text format.
Always hash your passwords.
Always hash your passwords.
DO NOT use Base64 or similar encoding for storing passwords.
DO NOT use Base64 or similar encoding for storing passwords.
DO NOT use weak or broken hashing algorithms like MD5 or SHA1. Only use strong password hashing algorithms like BCrypt, which is used in PHP’s own Password Hashing functions.
DO NOT use weak or broken hashing algorithms like MD5 or SHA1. Only use strong password hashing algorithms like BCrypt, which is used in PHP’s own Password Hashing functions.
DO NOT ever display or send a password in plain-text format.
DO NOT ever display or send a password in plain-text format.
DO NOT put unnecessary limits on your users’ passwords.
DO NOT put unnecessary limits on your users’ passwords.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2554,
"s": 2319,
"text": "CodeIgniter is an application development framework, which can be used to develop websites, using PHP. It is an Open Source framework. It has a very rich set of functionality, which will increase the speed of website development work."
},
{
"code": null,
"e": 2911,
"s": 2554,
"text": "If you know PHP well, then CodeIgniter will make your task easier. It has a very rich set of libraries and helpers. By using CodeIgniter, you will save a lot of time, if you are developing a website from scratch. Not only that, a website built in CodeIgniter is secure too, as it has the ability to prevent various attacks that take place through websites."
},
{
"code": null,
"e": 2976,
"s": 2911,
"text": "Some of the important features of CodeIgniter are listed below −"
},
{
"code": null,
"e": 3011,
"s": 2976,
"text": "Model-View-Controller Based System"
},
{
"code": null,
"e": 3046,
"s": 3011,
"text": "Model-View-Controller Based System"
},
{
"code": null,
"e": 3069,
"s": 3046,
"text": "Extremely Light Weight"
},
{
"code": null,
"e": 3092,
"s": 3069,
"text": "Extremely Light Weight"
},
{
"code": null,
"e": 3159,
"s": 3092,
"text": "Full Featured database classes with support for several platforms."
},
{
"code": null,
"e": 3226,
"s": 3159,
"text": "Full Featured database classes with support for several platforms."
},
{
"code": null,
"e": 3257,
"s": 3226,
"text": "Query Builder Database Support"
},
{
"code": null,
"e": 3288,
"s": 3257,
"text": "Query Builder Database Support"
},
{
"code": null,
"e": 3313,
"s": 3288,
"text": "Form and Data Validation"
},
{
"code": null,
"e": 3338,
"s": 3313,
"text": "Form and Data Validation"
},
{
"code": null,
"e": 3365,
"s": 3338,
"text": "Security and XSS Filtering"
},
{
"code": null,
"e": 3392,
"s": 3365,
"text": "Security and XSS Filtering"
},
{
"code": null,
"e": 3411,
"s": 3392,
"text": "Session Management"
},
{
"code": null,
"e": 3430,
"s": 3411,
"text": "Session Management"
},
{
"code": null,
"e": 3546,
"s": 3430,
"text": "Email Sending Class. Supports Attachments, HTML/Text email, multiple protocols (sendmail, SMTP, and Mail) and more."
},
{
"code": null,
"e": 3662,
"s": 3546,
"text": "Email Sending Class. Supports Attachments, HTML/Text email, multiple protocols (sendmail, SMTP, and Mail) and more."
},
{
"code": null,
"e": 3764,
"s": 3662,
"text": "Image Manipulation Library (cropping, resizing, rotating, etc.). Supports GD, ImageMagick, and NetPBM"
},
{
"code": null,
"e": 3866,
"s": 3764,
"text": "Image Manipulation Library (cropping, resizing, rotating, etc.). Supports GD, ImageMagick, and NetPBM"
},
{
"code": null,
"e": 3887,
"s": 3866,
"text": "File Uploading Class"
},
{
"code": null,
"e": 3908,
"s": 3887,
"text": "File Uploading Class"
},
{
"code": null,
"e": 3918,
"s": 3908,
"text": "FTP Class"
},
{
"code": null,
"e": 3928,
"s": 3918,
"text": "FTP Class"
},
{
"code": null,
"e": 3941,
"s": 3928,
"text": "Localization"
},
{
"code": null,
"e": 3954,
"s": 3941,
"text": "Localization"
},
{
"code": null,
"e": 3965,
"s": 3954,
"text": "Pagination"
},
{
"code": null,
"e": 3976,
"s": 3965,
"text": "Pagination"
},
{
"code": null,
"e": 3992,
"s": 3976,
"text": "Data Encryption"
},
{
"code": null,
"e": 4008,
"s": 3992,
"text": "Data Encryption"
},
{
"code": null,
"e": 4021,
"s": 4008,
"text": "Benchmarking"
},
{
"code": null,
"e": 4034,
"s": 4021,
"text": "Benchmarking"
},
{
"code": null,
"e": 4052,
"s": 4034,
"text": "Full Page Caching"
},
{
"code": null,
"e": 4070,
"s": 4052,
"text": "Full Page Caching"
},
{
"code": null,
"e": 4084,
"s": 4070,
"text": "Error Logging"
},
{
"code": null,
"e": 4098,
"s": 4084,
"text": "Error Logging"
},
{
"code": null,
"e": 4120,
"s": 4098,
"text": "Application Profiling"
},
{
"code": null,
"e": 4142,
"s": 4120,
"text": "Application Profiling"
},
{
"code": null,
"e": 4160,
"s": 4142,
"text": "Calendaring Class"
},
{
"code": null,
"e": 4178,
"s": 4160,
"text": "Calendaring Class"
},
{
"code": null,
"e": 4195,
"s": 4178,
"text": "User Agent Class"
},
{
"code": null,
"e": 4212,
"s": 4195,
"text": "User Agent Class"
},
{
"code": null,
"e": 4231,
"s": 4212,
"text": "Zip Encoding Class"
},
{
"code": null,
"e": 4250,
"s": 4231,
"text": "Zip Encoding Class"
},
{
"code": null,
"e": 4272,
"s": 4250,
"text": "Template Engine Class"
},
{
"code": null,
"e": 4294,
"s": 4272,
"text": "Template Engine Class"
},
{
"code": null,
"e": 4310,
"s": 4294,
"text": "Trackback Class"
},
{
"code": null,
"e": 4326,
"s": 4310,
"text": "Trackback Class"
},
{
"code": null,
"e": 4342,
"s": 4326,
"text": "XML-RPC Library"
},
{
"code": null,
"e": 4358,
"s": 4342,
"text": "XML-RPC Library"
},
{
"code": null,
"e": 4377,
"s": 4358,
"text": "Unit Testing Class"
},
{
"code": null,
"e": 4396,
"s": 4377,
"text": "Unit Testing Class"
},
{
"code": null,
"e": 4424,
"s": 4396,
"text": "Search-engine Friendly URLs"
},
{
"code": null,
"e": 4452,
"s": 4424,
"text": "Search-engine Friendly URLs"
},
{
"code": null,
"e": 4473,
"s": 4452,
"text": "Flexible URI Routing"
},
{
"code": null,
"e": 4494,
"s": 4473,
"text": "Flexible URI Routing"
},
{
"code": null,
"e": 4533,
"s": 4494,
"text": "Support for Hooks and Class Extensions"
},
{
"code": null,
"e": 4572,
"s": 4533,
"text": "Support for Hooks and Class Extensions"
},
{
"code": null,
"e": 4608,
"s": 4572,
"text": "Large library of “helper” functions"
},
{
"code": null,
"e": 4644,
"s": 4608,
"text": "Large library of “helper” functions"
},
{
"code": null,
"e": 4720,
"s": 4644,
"text": "It is very easy to install CodeIgniter. Just follow the steps given below −"
},
{
"code": null,
"e": 4780,
"s": 4720,
"text": "Step-1 − Download the CodeIgniter from the link CodeIgniter"
},
{
"code": null,
"e": 4840,
"s": 4780,
"text": "Step-1 − Download the CodeIgniter from the link CodeIgniter"
},
{
"code": null,
"e": 4867,
"s": 4840,
"text": "Step-2 − Unzip the folder."
},
{
"code": null,
"e": 4894,
"s": 4867,
"text": "Step-2 − Unzip the folder."
},
{
"code": null,
"e": 4948,
"s": 4894,
"text": "Step-3 − Upload all files and folders to your server."
},
{
"code": null,
"e": 5002,
"s": 4948,
"text": "Step-3 − Upload all files and folders to your server."
},
{
"code": null,
"e": 5114,
"s": 5002,
"text": "Step-4 − After uploading all the files to your server, visit the URL of your server, e.g., www.domain-name.com."
},
{
"code": null,
"e": 5226,
"s": 5114,
"text": "Step-4 − After uploading all the files to your server, visit the URL of your server, e.g., www.domain-name.com."
},
{
"code": null,
"e": 5283,
"s": 5226,
"text": "On visiting the URL, you will see the following screen −"
},
{
"code": null,
"e": 5343,
"s": 5283,
"text": "The architecture of CodeIgniter application is shown below."
},
{
"code": null,
"e": 5444,
"s": 5343,
"text": "As shown in the figure, whenever a request comes to CodeIgniter, it will first go to index.php page."
},
{
"code": null,
"e": 5545,
"s": 5444,
"text": "As shown in the figure, whenever a request comes to CodeIgniter, it will first go to index.php page."
},
{
"code": null,
"e": 5690,
"s": 5545,
"text": "In the second step, Routing will decide whether to pass this request to step-3 for caching or to pass this request to step-4 for security check."
},
{
"code": null,
"e": 5835,
"s": 5690,
"text": "In the second step, Routing will decide whether to pass this request to step-3 for caching or to pass this request to step-4 for security check."
},
{
"code": null,
"e": 5968,
"s": 5835,
"text": "If the requested page is already in Caching, then Routing will pass the request to step-3 and the response will go back to the user."
},
{
"code": null,
"e": 6101,
"s": 5968,
"text": "If the requested page is already in Caching, then Routing will pass the request to step-3 and the response will go back to the user."
},
{
"code": null,
"e": 6223,
"s": 6101,
"text": "If the requested page does not exist in Caching, then Routing will pass the requested page to step-4 for Security checks."
},
{
"code": null,
"e": 6345,
"s": 6223,
"text": "If the requested page does not exist in Caching, then Routing will pass the requested page to step-4 for Security checks."
},
{
"code": null,
"e": 6587,
"s": 6345,
"text": "Before passing the request to Application Controller, the Security of the submitted data is checked. After the Security check, the Application Controller loads necessary Models, Libraries, Helpers, Plugins and Scripts and pass it on to View."
},
{
"code": null,
"e": 6829,
"s": 6587,
"text": "Before passing the request to Application Controller, the Security of the submitted data is checked. After the Security check, the Application Controller loads necessary Models, Libraries, Helpers, Plugins and Scripts and pass it on to View."
},
{
"code": null,
"e": 7044,
"s": 6829,
"text": "The View will render the page with available data and pass it on for Caching. As the requested page was not cached before so this time it will be cached in Caching, to process this page quickly for future requests."
},
{
"code": null,
"e": 7259,
"s": 7044,
"text": "The View will render the page with available data and pass it on for Caching. As the requested page was not cached before so this time it will be cached in Caching, to process this page quickly for future requests."
},
{
"code": null,
"e": 7331,
"s": 7259,
"text": "The image given below shows the directory structure of the CodeIgniter."
},
{
"code": null,
"e": 7391,
"s": 7331,
"text": "CodeIgniter directory structure is divided into 3 folders −"
},
{
"code": null,
"e": 7403,
"s": 7391,
"text": "Application"
},
{
"code": null,
"e": 7410,
"s": 7403,
"text": "System"
},
{
"code": null,
"e": 7421,
"s": 7410,
"text": "User_guide"
},
{
"code": null,
"e": 7670,
"s": 7421,
"text": "As the name indicates the Application folder contains all the code of your application that you are building. This is the folder where you will develop your project. The Application folder contains several other folders, which are explained below −"
},
{
"code": null,
"e": 7816,
"s": 7670,
"text": "Cache − This folder contains all the cached pages of your application. These cached pages will increase the overall speed of accessing the pages."
},
{
"code": null,
"e": 7962,
"s": 7816,
"text": "Cache − This folder contains all the cached pages of your application. These cached pages will increase the overall speed of accessing the pages."
},
{
"code": null,
"e": 8183,
"s": 7962,
"text": "Config − This folder contains various files to configure the application. With the help of config.php file, user can configure the application. Using database.php file, user can configure the database of the application."
},
{
"code": null,
"e": 8404,
"s": 8183,
"text": "Config − This folder contains various files to configure the application. With the help of config.php file, user can configure the application. Using database.php file, user can configure the database of the application."
},
{
"code": null,
"e": 8515,
"s": 8404,
"text": "Controllers − This folder holds the controllers of your application. It is the basic part of your application."
},
{
"code": null,
"e": 8626,
"s": 8515,
"text": "Controllers − This folder holds the controllers of your application. It is the basic part of your application."
},
{
"code": null,
"e": 8690,
"s": 8626,
"text": "Core − This folder will contain base class of your application."
},
{
"code": null,
"e": 8754,
"s": 8690,
"text": "Core − This folder will contain base class of your application."
},
{
"code": null,
"e": 8826,
"s": 8754,
"text": "Helpers − In this folder, you can put helper class of your application."
},
{
"code": null,
"e": 8898,
"s": 8826,
"text": "Helpers − In this folder, you can put helper class of your application."
},
{
"code": null,
"e": 9038,
"s": 8898,
"text": "Hooks − The files in this folder provide a means to tap into and modify the inner workings of the framework without hacking the core files."
},
{
"code": null,
"e": 9178,
"s": 9038,
"text": "Hooks − The files in this folder provide a means to tap into and modify the inner workings of the framework without hacking the core files."
},
{
"code": null,
"e": 9234,
"s": 9178,
"text": "Language − This folder contains language related files."
},
{
"code": null,
"e": 9290,
"s": 9234,
"text": "Language − This folder contains language related files."
},
{
"code": null,
"e": 9378,
"s": 9290,
"text": "Libraries − This folder contains files of the libraries developed for your application."
},
{
"code": null,
"e": 9466,
"s": 9378,
"text": "Libraries − This folder contains files of the libraries developed for your application."
},
{
"code": null,
"e": 9534,
"s": 9466,
"text": "Logs − This folder contains files related to the log of the system."
},
{
"code": null,
"e": 9602,
"s": 9534,
"text": "Logs − This folder contains files related to the log of the system."
},
{
"code": null,
"e": 9661,
"s": 9602,
"text": "Models − The database login will be placed in this folder."
},
{
"code": null,
"e": 9720,
"s": 9661,
"text": "Models − The database login will be placed in this folder."
},
{
"code": null,
"e": 9818,
"s": 9720,
"text": "Third_party − In this folder, you can place any plugins, which will be used for your application."
},
{
"code": null,
"e": 9916,
"s": 9818,
"text": "Third_party − In this folder, you can place any plugins, which will be used for your application."
},
{
"code": null,
"e": 9980,
"s": 9916,
"text": "Views − Application’s HTML files will be placed in this folder."
},
{
"code": null,
"e": 10044,
"s": 9980,
"text": "Views − Application’s HTML files will be placed in this folder."
},
{
"code": null,
"e": 10230,
"s": 10044,
"text": "This folder contains CodeIgniter core codes, libraries, helpers and other files, which help make the coding easy. These libraries and helpers are loaded and used in web app development."
},
{
"code": null,
"e": 10325,
"s": 10230,
"text": "This folder contains all the CodeIgniter code of consequence, organized into various folders −"
},
{
"code": null,
"e": 10595,
"s": 10325,
"text": "Core − This folder contains CodeIgniter’s core class. Do not modify anything here. All of your work will take place in the application folder. Even if your intent is to extend the CodeIgniter core, you have to do it with hooks, and hooks live in the application folder."
},
{
"code": null,
"e": 10865,
"s": 10595,
"text": "Core − This folder contains CodeIgniter’s core class. Do not modify anything here. All of your work will take place in the application folder. Even if your intent is to extend the CodeIgniter core, you have to do it with hooks, and hooks live in the application folder."
},
{
"code": null,
"e": 10957,
"s": 10865,
"text": "Database − The database folder contains core database drivers and other database utilities."
},
{
"code": null,
"e": 11049,
"s": 10957,
"text": "Database − The database folder contains core database drivers and other database utilities."
},
{
"code": null,
"e": 11123,
"s": 11049,
"text": "Fonts − The fonts folder contains font related information and utilities."
},
{
"code": null,
"e": 11197,
"s": 11123,
"text": "Fonts − The fonts folder contains font related information and utilities."
},
{
"code": null,
"e": 11305,
"s": 11197,
"text": "Helpers − The helpers folder contains standard CodeIgniter helpers (such as date, cookie, and URL helpers)."
},
{
"code": null,
"e": 11413,
"s": 11305,
"text": "Helpers − The helpers folder contains standard CodeIgniter helpers (such as date, cookie, and URL helpers)."
},
{
"code": null,
"e": 11496,
"s": 11413,
"text": "Language − The language folder contains language files. You can ignore it for now."
},
{
"code": null,
"e": 11579,
"s": 11496,
"text": "Language − The language folder contains language files. You can ignore it for now."
},
{
"code": null,
"e": 11950,
"s": 11579,
"text": "Libraries − The libraries folder contains standard CodeIgniter libraries (to help you with e-mail, calendars, file uploads, and more). You can create your own libraries or extend (and even replace) standard ones, but those will be saved in the application/libraries directory to keep them separate from the standard CodeIgniter libraries saved in this particular folder."
},
{
"code": null,
"e": 12321,
"s": 11950,
"text": "Libraries − The libraries folder contains standard CodeIgniter libraries (to help you with e-mail, calendars, file uploads, and more). You can create your own libraries or extend (and even replace) standard ones, but those will be saved in the application/libraries directory to keep them separate from the standard CodeIgniter libraries saved in this particular folder."
},
{
"code": null,
"e": 12618,
"s": 12321,
"text": "This is your user guide to CodeIgniter. It is basically, the offline version of user guide on CodeIgniter website. Using this, one can learn the functions of various libraries, helpers and classes. It is recommended to go through this user guide before building your first web app in CodeIgniter."
},
{
"code": null,
"e": 12935,
"s": 12618,
"text": "Beside these three folders, there is one more important file named “index.php”. In this file, we can set the application environment and error level and we can define system and application folder name. It is recommended, not to edit these settings if you do not have enough knowledge about what you are going to do."
},
{
"code": null,
"e": 13218,
"s": 12935,
"text": "CodeIgniter is based on the Model-View-Controller (MVC) development pattern. MVC is a software approach that separates application logic from presentation. In practice, it permits your web pages to contain minimal scripting since the presentation is separate from the PHP scripting."
},
{
"code": null,
"e": 13386,
"s": 13218,
"text": "The Model represents your data structures. Typically, your model classes will contain functions that help you retrieve, insert and update information in your database."
},
{
"code": null,
"e": 13554,
"s": 13386,
"text": "The Model represents your data structures. Typically, your model classes will contain functions that help you retrieve, insert and update information in your database."
},
{
"code": null,
"e": 13786,
"s": 13554,
"text": "The View is information that is being presented to a user. A View will normally be a web page, but in CodeIgniter, a view can also be a page fragment like a header or footer. It can also be an RSS page, or any other type of “page”."
},
{
"code": null,
"e": 14018,
"s": 13786,
"text": "The View is information that is being presented to a user. A View will normally be a web page, but in CodeIgniter, a view can also be a page fragment like a header or footer. It can also be an RSS page, or any other type of “page”."
},
{
"code": null,
"e": 14172,
"s": 14018,
"text": "The Controller serves as an intermediary between the Model, the View, and any other resources needed to process the HTTP request and generate a web page."
},
{
"code": null,
"e": 14326,
"s": 14172,
"text": "The Controller serves as an intermediary between the Model, the View, and any other resources needed to process the HTTP request and generate a web page."
},
{
"code": null,
"e": 14427,
"s": 14326,
"text": "A controller is a simple class file. As the name suggests, it controls the whole application by URI."
},
{
"code": null,
"e": 14570,
"s": 14427,
"text": "First, go to application/controllers folder. You will find two files there, index.html and Welcome.php. These files come with the CodeIgniter."
},
{
"code": null,
"e": 14696,
"s": 14570,
"text": "Keep these files as they are. Create a new file under the same path named “Test.php”. Write the following code in that file −"
},
{
"code": null,
"e": 14826,
"s": 14696,
"text": "<?php \n class Test extends CI_Controller {\n \n public function index() { \n echo \"Hello World!\"; \n } \n } \n?>"
},
{
"code": null,
"e": 14970,
"s": 14826,
"text": "The Test class extends an in-built class called CI_Controller. This class must be extended whenever you want to make your own Controller class."
},
{
"code": null,
"e": 15025,
"s": 14970,
"text": "The above controller can be called by URI as follows −"
},
{
"code": null,
"e": 15068,
"s": 15025,
"text": "http://www.your-domain.com/index.php/test\n"
},
{
"code": null,
"e": 15451,
"s": 15068,
"text": "Notice the word “test” in the above URI after index.php. This indicates the class name of controller. As we have given the name of the controller “Test”, we are writing “test” after the index.php. The class name must start with uppercase letter but we need to write lowercase letter when we call that controller by URI. The general syntax for calling the controller is as follows −"
},
{
"code": null,
"e": 15512,
"s": 15451,
"text": "http://www.your-domain.com/index.php/controller/method-name\n"
},
{
"code": null,
"e": 15583,
"s": 15512,
"text": "Let us modify the above class and create another method named “hello”."
},
{
"code": null,
"e": 15814,
"s": 15583,
"text": "<?php \n class Test extends CI_Controller { \n\t\n public function index() { \n echo \"This is default function.\"; \n } \n \n public function hello() { \n echo \"This is hello function.\"; \n } \n } \n?>"
},
{
"code": null,
"e": 15880,
"s": 15814,
"text": "We can execute the above controller in the following three ways −"
},
{
"code": null,
"e": 15922,
"s": 15880,
"text": "http://www.your-domain.com/index.php/test"
},
{
"code": null,
"e": 15970,
"s": 15922,
"text": "http://www.your-domain.com/index.php/test/index"
},
{
"code": null,
"e": 16018,
"s": 15970,
"text": "http://www.your-domain.com/index.php/test/hello"
},
{
"code": null,
"e": 16351,
"s": 16018,
"text": "After visiting the first URI in the browser, we get the output as shown in the picture given below. As you can see, we got the output of the method “index”, even though we did not pass the name of the method the URI. We have used only controller name in the URI. In such situations, the CodeIgniter calls the default method “index”."
},
{
"code": null,
"e": 16586,
"s": 16351,
"text": "Visiting the second URI in the browser, we get the same output as shown in the above picture. Here, we have passed method’s name after controller’s name in the URI. As the name of the method is “index”, we are getting the same output."
},
{
"code": null,
"e": 16843,
"s": 16586,
"text": "Visiting the third URI in the browser, we get the output as shown in picture given below. As you can see, we are getting the output of the method “hello” because we have passed “hello” as the method name, after the name of the controller “test” in the URI."
},
{
"code": null,
"e": 16913,
"s": 16843,
"text": "The name of the controller class must start with an uppercase letter."
},
{
"code": null,
"e": 16983,
"s": 16913,
"text": "The name of the controller class must start with an uppercase letter."
},
{
"code": null,
"e": 17036,
"s": 16983,
"text": "The controller must be called with lowercase letter."
},
{
"code": null,
"e": 17089,
"s": 17036,
"text": "The controller must be called with lowercase letter."
},
{
"code": null,
"e": 17200,
"s": 17089,
"text": "Do not use the same name of the method as your parent class, as it will override parent class’s functionality."
},
{
"code": null,
"e": 17311,
"s": 17200,
"text": "Do not use the same name of the method as your parent class, as it will override parent class’s functionality."
},
{
"code": null,
"e": 17612,
"s": 17311,
"text": "This can be a simple or complex webpage, which can be called by the controller. The webpage may contain header, footer, sidebar etc. View cannot be called directly. Let us create a simple view. Create a new file under application/views with name “test.php” and copy the below given code in that file."
},
{
"code": null,
"e": 17817,
"s": 17612,
"text": "<!DOCTYPE html> \n<html lang = \"en\"> \n\n <head> \n <meta charset = \"utf-8\"> \n <title>CodeIgniter View Example</title> \n </head>\n\t\n <body> \n CodeIgniter View Example \n </body>\n\t\n</html>"
},
{
"code": null,
"e": 17897,
"s": 17817,
"text": "Change the code of application/controllers/test.php file as shown in the below."
},
{
"code": null,
"e": 17946,
"s": 17897,
"text": "The view can be loaded by the following syntax −"
},
{
"code": null,
"e": 17974,
"s": 17946,
"text": "$this->load->view('name');\n"
},
{
"code": null,
"e": 18129,
"s": 17974,
"text": "Where name is the view file, which is being rendered. If you have planned to store the view file in some directory then you can use the following syntax −"
},
{
"code": null,
"e": 18172,
"s": 18129,
"text": "$this->load->view('directory-name/name');\n"
},
{
"code": null,
"e": 18267,
"s": 18172,
"text": "It is not necessary to specify the extension as php, unless something other than .php is used."
},
{
"code": null,
"e": 18457,
"s": 18267,
"text": "The index() method is calling the view method and passing the “test” as argument to view() method because we have stored the html coding in “test.php” file under application/views/test.php."
},
{
"code": null,
"e": 18593,
"s": 18457,
"text": "<?php \n class Test extends CI_Controller { \n\t\n public function index() { \n $this->load->view('test'); \n } \n } \n?>"
},
{
"code": null,
"e": 18632,
"s": 18593,
"text": "Here is the output of the above code −"
},
{
"code": null,
"e": 18694,
"s": 18632,
"text": "The following flowchart illustrates of how everything works −"
},
{
"code": null,
"e": 18958,
"s": 18694,
"text": "Models classes are designed to work with information in the database. As an example, if you are using CodeIgniter to manage users in your application then you must have model class, which contains functions to insert, delete, update and retrieve your users’ data."
},
{
"code": null,
"e": 19079,
"s": 18958,
"text": "Model classes are stored in application/models directory. Following code shows how to create model class in CodeIgniter."
},
{
"code": null,
"e": 19219,
"s": 19079,
"text": "<?php \n Class Model_name extends CI_Model { \n\t\n Public function __construct() { \n parent::__construct(); \n } \n } \n?> "
},
{
"code": null,
"e": 19463,
"s": 19219,
"text": "Where Model_name is the name of the model class that you want to give. Each model class must inherit the CodeIgniter’s CI_Model class. The first letter of the model class must be in capital letter. Following is the code for users’ model class."
},
{
"code": null,
"e": 19604,
"s": 19463,
"text": "<?php \n Class User_model extends CI_Model {\n\t\n Public function __construct() { \n parent::__construct(); \n } \n\t\t\n } \n?>"
},
{
"code": null,
"e": 19702,
"s": 19604,
"text": "The above model class must be saved as User_model.php. The class name and file name must be same."
},
{
"code": null,
"e": 19783,
"s": 19702,
"text": "Model can be called in controller. Following code can be used to load any model."
},
{
"code": null,
"e": 19818,
"s": 19783,
"text": "$this->load->model('model_name');\n"
},
{
"code": null,
"e": 19945,
"s": 19818,
"text": "Where model_name is the name of the model to be loaded. After loading the model you can simply call its method as shown below."
},
{
"code": null,
"e": 19975,
"s": 19945,
"text": "$this->model_name->method();\n"
},
{
"code": null,
"e": 20112,
"s": 19975,
"text": "There may be situations where you want some model class throughout your application. In such situations, it is better if we autoload it."
},
{
"code": null,
"e": 20526,
"s": 20112,
"text": "/*\n| ---------------------------------------------------------------\n| Auto-Load Models\n| ---------------------------------------------------------------\n| Prototype:\n|\n| $autoload['model'] = array('first_model', 'second_model');\n|\n| You can also supply an alternative model name to be assigned\n| in the controller:\n| \n| $autoload['model'] = array('first_model' => 'first');\n*/\n$autoload['model'] = array();"
},
{
"code": null,
"e": 20735,
"s": 20526,
"text": "As shown in the above figure, pass the name of the model in the array that you want to autoload and it will be autoloaded, while system is in initialization state and is accessible throughout the application."
},
{
"code": null,
"e": 20983,
"s": 20735,
"text": "As the name suggests, it will help you build your system. It is divided into small functions to serve different functionality. A number of helpers are available in CodeIgniter, which are listed in the table below. We can build our own helpers too."
},
{
"code": null,
"e": 21486,
"s": 20983,
"text": "Helpers are typically stored in your system/helpers, or application/helpers directory. Custom helpers are stored in application/helpers directory and systems’ helpers are stored in system/helpers directory. CodeIgniter will look first in your application/helpers directory. If the directory does not exist or the specified helper is not located, CodeIgniter will instead, look in your global system/helpers/ directory. Each helper, whether it is custom or system helper, must be loaded before using it."
},
{
"code": null,
"e": 21499,
"s": 21486,
"text": "Array Helper"
},
{
"code": null,
"e": 21576,
"s": 21499,
"text": "The Array Helper file contains functions that assist in working with arrays."
},
{
"code": null,
"e": 21591,
"s": 21576,
"text": "CAPTCHA Helper"
},
{
"code": null,
"e": 21674,
"s": 21591,
"text": "The CAPTCHA Helper file contains functions that assist in creating CAPTCHA images."
},
{
"code": null,
"e": 21688,
"s": 21674,
"text": "Cookie Helper"
},
{
"code": null,
"e": 21767,
"s": 21688,
"text": "The Cookie Helper file contains functions that assist in working with cookies."
},
{
"code": null,
"e": 21779,
"s": 21767,
"text": "Date Helper"
},
{
"code": null,
"e": 21850,
"s": 21779,
"text": "The Date Helper file contains functions that help you work with dates."
},
{
"code": null,
"e": 21867,
"s": 21850,
"text": "Directory Helper"
},
{
"code": null,
"e": 21953,
"s": 21867,
"text": "The Directory Helper file contains functions that assist in working with directories."
},
{
"code": null,
"e": 21969,
"s": 21953,
"text": "Download Helper"
},
{
"code": null,
"e": 22029,
"s": 21969,
"text": "The Download Helper lets you download data to your desktop."
},
{
"code": null,
"e": 22042,
"s": 22029,
"text": "Email Helper"
},
{
"code": null,
"e": 22182,
"s": 22042,
"text": "The Email Helper provides some assistive functions for working with Email. For a more robust email solution, see CodeIgniter’s Email Class."
},
{
"code": null,
"e": 22194,
"s": 22182,
"text": "File Helper"
},
{
"code": null,
"e": 22269,
"s": 22194,
"text": "The File Helper file contains functions that assist in working with files."
},
{
"code": null,
"e": 22281,
"s": 22269,
"text": "Form Helper"
},
{
"code": null,
"e": 22356,
"s": 22281,
"text": "The Form Helper file contains functions that assist in working with forms."
},
{
"code": null,
"e": 22368,
"s": 22356,
"text": "HTML Helper"
},
{
"code": null,
"e": 22442,
"s": 22368,
"text": "The HTML Helper file contains functions that assist in working with HTML."
},
{
"code": null,
"e": 22459,
"s": 22442,
"text": "Inflector Helper"
},
{
"code": null,
"e": 22575,
"s": 22459,
"text": "The Inflector Helper file contains functions that permits you to change words to plural, singular, camel case, etc."
},
{
"code": null,
"e": 22591,
"s": 22575,
"text": "Language Helper"
},
{
"code": null,
"e": 22679,
"s": 22591,
"text": "The Language Helper file contains functions that assist in working with language files."
},
{
"code": null,
"e": 22693,
"s": 22679,
"text": "Number Helper"
},
{
"code": null,
"e": 22773,
"s": 22693,
"text": "The Number Helper file contains functions that help you work with numeric data."
},
{
"code": null,
"e": 22785,
"s": 22773,
"text": "Path Helper"
},
{
"code": null,
"e": 22881,
"s": 22785,
"text": "The Path Helper file contains functions that permits you to work with file paths on the server."
},
{
"code": null,
"e": 22897,
"s": 22881,
"text": "Security Helper"
},
{
"code": null,
"e": 22959,
"s": 22897,
"text": "The Security Helper file contains security related functions."
},
{
"code": null,
"e": 22973,
"s": 22959,
"text": "Smiley Helper"
},
{
"code": null,
"e": 23056,
"s": 22973,
"text": "The Smiley Helper file contains functions that let you manage smileys (emoticons)."
},
{
"code": null,
"e": 23070,
"s": 23056,
"text": "String Helper"
},
{
"code": null,
"e": 23149,
"s": 23070,
"text": "The String Helper file contains functions that assist in working with strings."
},
{
"code": null,
"e": 23161,
"s": 23149,
"text": "Text Helper"
},
{
"code": null,
"e": 23235,
"s": 23161,
"text": "The Text Helper file contains functions that assist in working with text."
},
{
"code": null,
"e": 23253,
"s": 23235,
"text": "Typography Helper"
},
{
"code": null,
"e": 23357,
"s": 23253,
"text": "The Typography Helper file contains functions that help your format text in semantically relevant ways."
},
{
"code": null,
"e": 23368,
"s": 23357,
"text": "URL Helper"
},
{
"code": null,
"e": 23441,
"s": 23368,
"text": "The URL Helper file contains functions that assist in working with URLs."
},
{
"code": null,
"e": 23452,
"s": 23441,
"text": "XML Helper"
},
{
"code": null,
"e": 23529,
"s": 23452,
"text": "The XML Helper file contains functions that assist in working with XML data."
},
{
"code": null,
"e": 23569,
"s": 23529,
"text": "A helper can be loaded as shown below −"
},
{
"code": null,
"e": 23599,
"s": 23569,
"text": "$this->load->helper('name');\n"
},
{
"code": null,
"e": 23713,
"s": 23599,
"text": "Where name is the name of the helper. For example, if you want to load the URL Helper, then it can be loaded as −"
},
{
"code": null,
"e": 23742,
"s": 23713,
"text": "$this->load->helper('url');\n"
},
{
"code": null,
"e": 23996,
"s": 23742,
"text": "CodeIgniter has user-friendly URI routing system, so that you can easily re-route URL. Typically, there is a one-to-one relationship between a URL string and its corresponding controller class/method. The segments in a URI normally follow this pattern −"
},
{
"code": null,
"e": 24030,
"s": 23996,
"text": "your-domain.com/class/method/id/\n"
},
{
"code": null,
"e": 24104,
"s": 24030,
"text": "The first segment represents the controller class that should be invoked."
},
{
"code": null,
"e": 24178,
"s": 24104,
"text": "The first segment represents the controller class that should be invoked."
},
{
"code": null,
"e": 24262,
"s": 24178,
"text": "The second segment represents the class function, or method, that should be called."
},
{
"code": null,
"e": 24346,
"s": 24262,
"text": "The second segment represents the class function, or method, that should be called."
},
{
"code": null,
"e": 24460,
"s": 24346,
"text": "The third, and any additional segments, represent the ID and any variables that will be passed to the controller."
},
{
"code": null,
"e": 24574,
"s": 24460,
"text": "The third, and any additional segments, represent the ID and any variables that will be passed to the controller."
},
{
"code": null,
"e": 24729,
"s": 24574,
"text": "In some situations, you may want to change this default routing mechanism. CodeIgniter provides facility through which you can set your own routing rules."
},
{
"code": null,
"e": 25070,
"s": 24729,
"text": "There is a particular file where you can handle all these. The file is located at application/config/routes.php. You will find an array called $route in which you can customize your routing rules. The key in the $route array will decide what to route and the value will decide where to route. There are three reserved routes in CodeIgniter."
},
{
"code": null,
"e": 25099,
"s": 25070,
"text": "$route['default_controller']"
},
{
"code": null,
"e": 25404,
"s": 25099,
"text": "This route indicates which controller class should be loaded, if the URI contains no data, which will be the case when people load your root URL. You are encouraged to have a default route otherwise a 404 page will appear, by default. We can set home page of website here so it will be loaded by default."
},
{
"code": null,
"e": 25427,
"s": 25404,
"text": "$route['404_override']"
},
{
"code": null,
"e": 25721,
"s": 25427,
"text": "This route indicates which controller class should be loaded if the requested controller is not found. It will override the default 404 error page. It won’t affect to the show_404() function, which will continue loading the default error_404.php file in application/views/errors/error_404.php."
},
{
"code": null,
"e": 25752,
"s": 25721,
"text": "$route['translate_uri_dashes']"
},
{
"code": null,
"e": 26133,
"s": 25752,
"text": "As evident by the Boolean value, this is not exactly a route. This option enables you to automatically replace dashes (‘-‘) with underscores in the controller and method URI segments, thus saving you additional route entries if you need to do that. This is required because the dash is not a valid class or method-name character and will cause a fatal error, if you try to use it."
},
{
"code": null,
"e": 26296,
"s": 26133,
"text": "Routes can be customized by wildcards or by using regular expressions but keep in mind that these customized rules for routing must come after the reserved rules."
},
{
"code": null,
"e": 26352,
"s": 26296,
"text": "We can use two wildcard characters as explained below −"
},
{
"code": null,
"e": 26410,
"s": 26352,
"text": "(:num) − It will match a segment containing only numbers."
},
{
"code": null,
"e": 26468,
"s": 26410,
"text": "(:num) − It will match a segment containing only numbers."
},
{
"code": null,
"e": 26527,
"s": 26468,
"text": "(:any) − It will match a segment containing any character."
},
{
"code": null,
"e": 26586,
"s": 26527,
"text": "(:any) − It will match a segment containing any character."
},
{
"code": null,
"e": 26594,
"s": 26586,
"text": "Example"
},
{
"code": null,
"e": 26644,
"s": 26594,
"text": "$route['product/:num']='catalog/product_lookup';\n"
},
{
"code": null,
"e": 26853,
"s": 26644,
"text": "In the above example, if the literal word “product” is found in the first segment of the URL, and a number is found in the second segment, the “catalog” class and the “product_lookup” method are used instead."
},
{
"code": null,
"e": 27039,
"s": 26853,
"text": "Like wildcards, we can also use regular expressions in $route array key part. If any URI matches with regular expression, then it will be routed to the value part set into $route array."
},
{
"code": null,
"e": 27047,
"s": 27039,
"text": "Example"
},
{
"code": null,
"e": 27094,
"s": 27047,
"text": "$route['products/([a-z]+)/(\\d+)']='$1/id_$2';\n"
},
{
"code": null,
"e": 27225,
"s": 27094,
"text": "In the above example, a URI similar to products/shoes/123 would instead call the “shoes” controller class and the “id_123” method."
},
{
"code": null,
"e": 27410,
"s": 27225,
"text": "After setting up the site, the next thing that we should do is to configure the site. The application/config folder contains a group of files that set basic configuration of your site."
},
{
"code": null,
"e": 27594,
"s": 27410,
"text": "The base URL of the site can be configured in application/config/config.php file. It is URL to your CodeIgniter root. Typically, this will be your base URL, with a trailing slash e.g."
},
{
"code": null,
"e": 27615,
"s": 27594,
"text": "http://example.com/\n"
},
{
"code": null,
"e": 27935,
"s": 27615,
"text": "If this is not set, then CodeIgniter will try to guess the protocol, domain and path to your installation. However, you should always configure this explicitly and never rely on autoguessing, especially in production environments. You can configure the base URL in the $config array with key “base_url” as shown below −"
},
{
"code": null,
"e": 27984,
"s": 27935,
"text": "$config['base_url'] = 'http://your-domain.com';\n"
},
{
"code": null,
"e": 28338,
"s": 27984,
"text": "The database of the site can be configured in application/config/database.php file. Often we need to set up database for different environment like development and production. With the multidimensional array provided in the CodeIgniter, we can setup database for different environment. The configuration settings are stored in the array as shown below −"
},
{
"code": null,
"e": 28828,
"s": 28338,
"text": "$db['default'] = array( \n 'dsn' => '', \n 'hostname' => 'localhost', \n 'username' => 'root', \n 'password' => '', \n 'database' => 'database_name', \n 'dbdriver' => 'mysqli', \n 'dbprefix' => '', \n 'pconnect' => TRUE, \n 'db_debug' => TRUE, \n 'cache_on' => FALSE, \n 'cachedir' => '', \n 'char_set' => 'utf8', \n 'dbcollat' => 'utf8_general_ci',\n 'swap_pre' => '', \n 'encrypt' => FALSE, \n 'compress' => FALSE, \n 'stricton' => FALSE, \n 'failover' => array() \n);"
},
{
"code": null,
"e": 28938,
"s": 28828,
"text": "You can leave few options to their default values except hostname, username, password, database and dbdriver."
},
{
"code": null,
"e": 29017,
"s": 28938,
"text": "hostname − Specify location of your database here e.g. localhost or IP address"
},
{
"code": null,
"e": 29096,
"s": 29017,
"text": "hostname − Specify location of your database here e.g. localhost or IP address"
},
{
"code": null,
"e": 29143,
"s": 29096,
"text": "username − Set username of your database here."
},
{
"code": null,
"e": 29190,
"s": 29143,
"text": "username − Set username of your database here."
},
{
"code": null,
"e": 29237,
"s": 29190,
"text": "password − Set password of your database here."
},
{
"code": null,
"e": 29284,
"s": 29237,
"text": "password − Set password of your database here."
},
{
"code": null,
"e": 29326,
"s": 29284,
"text": "database − Set name of the database here."
},
{
"code": null,
"e": 29368,
"s": 29326,
"text": "database − Set name of the database here."
},
{
"code": null,
"e": 29470,
"s": 29368,
"text": "dbdriver − Set type of database that you are using e.g. MySQL, MySQLi, Postgre SQL, ODBC, and MS SQL."
},
{
"code": null,
"e": 29572,
"s": 29470,
"text": "dbdriver − Set type of database that you are using e.g. MySQL, MySQLi, Postgre SQL, ODBC, and MS SQL."
},
{
"code": null,
"e": 29803,
"s": 29572,
"text": "By changing the key of the array $db, you can set other configuration of database as shown below. Here, we have set the key to ‘test’ to set the database for testing environment, by keeping the other database environment as it is."
},
{
"code": null,
"e": 30290,
"s": 29803,
"text": "$db['test'] = array( \n 'dsn' => '', \n 'hostname' => 'localhost', \n 'username' => 'root', \n 'password' => '', \n 'database' => 'database_name', \n 'dbdriver' => 'mysqli', \n 'dbprefix' => '', \n 'pconnect' => TRUE, \n 'db_debug' => TRUE, \n 'cache_on' => FALSE, \n 'cachedir' => '', \n 'char_set' => 'utf8', \n 'dbcollat' => 'utf8_general_ci', \n 'swap_pre' => '', \n 'encrypt' => FALSE, \n 'compress' => FALSE, \n 'stricton' => FALSE, \n 'failover' => array()\n);"
},
{
"code": null,
"e": 30390,
"s": 30290,
"text": "You can simply switch to different environment by changing the value of a variable as shown below −"
},
{
"code": null,
"e": 30457,
"s": 30390,
"text": "$active_group = ‘default’; //This will set the default environment"
},
{
"code": null,
"e": 30518,
"s": 30457,
"text": "$active_group = ‘test’; //This will set the test environment"
},
{
"code": null,
"e": 30855,
"s": 30518,
"text": "This file specifies, by default, which systems should be loaded. In order to keep the framework as light-weight as possible, only the absolute minimal resources are loaded by default. One should autoload the frequently used system, rather than loading it at local level, repeatedly. Following are the things you can load automatically −"
},
{
"code": null,
"e": 31087,
"s": 30855,
"text": "Libraries − It is a list of libraries, which should be auto loaded. Provide a list of libraries in an array as shown below to be autoloaded by CodeIgniter. In this example, we are auto loading database, email and session libraries."
},
{
"code": null,
"e": 31319,
"s": 31087,
"text": "Libraries − It is a list of libraries, which should be auto loaded. Provide a list of libraries in an array as shown below to be autoloaded by CodeIgniter. In this example, we are auto loading database, email and session libraries."
},
{
"code": null,
"e": 31384,
"s": 31319,
"text": "$autoload['libraries'] = array('database', 'email', 'session');\n"
},
{
"code": null,
"e": 31684,
"s": 31384,
"text": "Drivers − These classes are located in system/libraries/ or in your application/libraries/ directory, but are also placed inside their own subdirectory and they extend the CI_Driver_Library class. They offer multiple interchangeable driver options. Following is an example to autoload cache drivers."
},
{
"code": null,
"e": 31984,
"s": 31684,
"text": "Drivers − These classes are located in system/libraries/ or in your application/libraries/ directory, but are also placed inside their own subdirectory and they extend the CI_Driver_Library class. They offer multiple interchangeable driver options. Following is an example to autoload cache drivers."
},
{
"code": null,
"e": 32024,
"s": 31984,
"text": "$autoload['drivers'] = array('cache');\n"
},
{
"code": null,
"e": 32241,
"s": 32024,
"text": "Helper files − It is a list of helper files, to be autoloaded. Provide a list of libraries in the array, as shown below, to be autoloaded by CodeIgniter. In the given example, we are autoloading URL and file helpers."
},
{
"code": null,
"e": 32458,
"s": 32241,
"text": "Helper files − It is a list of helper files, to be autoloaded. Provide a list of libraries in the array, as shown below, to be autoloaded by CodeIgniter. In the given example, we are autoloading URL and file helpers."
},
{
"code": null,
"e": 32503,
"s": 32458,
"text": "$autoload['helper'] = array('url', 'file');\n"
},
{
"code": null,
"e": 32703,
"s": 32503,
"text": "Custom config files − These files are intended for use, only if you have created custom config files. Otherwise, leave it blank. Following is an example of how to autoload more than one config files."
},
{
"code": null,
"e": 32903,
"s": 32703,
"text": "Custom config files − These files are intended for use, only if you have created custom config files. Otherwise, leave it blank. Following is an example of how to autoload more than one config files."
},
{
"code": null,
"e": 32955,
"s": 32903,
"text": "$autoload['config'] = array('config1', 'config2');\n"
},
{
"code": null,
"e": 33300,
"s": 32955,
"text": "Language files − It is a list of language files, which should be auto loaded. Look at the example given below. Provide a list of languages in an array as shown below to be auto loaded by CodeIgniter. Keep in mind that do not include the \"_lang\" part of your file. For example, \"codeigniter_lang.php\" would be referenced as array('codeigniter');"
},
{
"code": null,
"e": 33645,
"s": 33300,
"text": "Language files − It is a list of language files, which should be auto loaded. Look at the example given below. Provide a list of languages in an array as shown below to be auto loaded by CodeIgniter. Keep in mind that do not include the \"_lang\" part of your file. For example, \"codeigniter_lang.php\" would be referenced as array('codeigniter');"
},
{
"code": null,
"e": 33869,
"s": 33645,
"text": "Models − It is a list of models file, which should be autoloaded. Provide a list of models in an array as shown below to be autoloaded by CodeIgniter. Following is the example of how to auto load more than one models files."
},
{
"code": null,
"e": 34093,
"s": 33869,
"text": "Models − It is a list of models file, which should be autoloaded. Provide a list of models in an array as shown below to be autoloaded by CodeIgniter. Following is the example of how to auto load more than one models files."
},
{
"code": null,
"e": 34153,
"s": 34093,
"text": "$autoload['model'] = array('first_model', 'second_model');\n"
},
{
"code": null,
"e": 34339,
"s": 34153,
"text": "Like any other framework, we need to interact with the database very often and CodeIgniter makes this job easy for us. It provides rich set of functionalities to interact with database."
},
{
"code": null,
"e": 34537,
"s": 34339,
"text": "In this section, we will understand how the CRUD (Create, Read, Update, Delete) functions work with CodeIgniter. We will use stud table to select, update, delete, and insert the data in stud table."
},
{
"code": null,
"e": 34591,
"s": 34537,
"text": "We can connect to database in the following two way −"
},
{
"code": null,
"e": 34825,
"s": 34591,
"text": "Automatic Connecting − Automatic connection can be done by using the file application/config/autoload.php. Automatic connection will load the database for each and every page. We just need to add the database library as shown below −"
},
{
"code": null,
"e": 35059,
"s": 34825,
"text": "Automatic Connecting − Automatic connection can be done by using the file application/config/autoload.php. Automatic connection will load the database for each and every page. We just need to add the database library as shown below −"
},
{
"code": null,
"e": 35104,
"s": 35059,
"text": "$autoload['libraries'] = array(‘database’);\n"
},
{
"code": null,
"e": 35303,
"s": 35104,
"text": "Manual Connecting − If you want database connectivity for only some of the pages, then we can go for manual connecting. We can connect to database manually by adding the following line in any class."
},
{
"code": null,
"e": 35502,
"s": 35303,
"text": "Manual Connecting − If you want database connectivity for only some of the pages, then we can go for manual connecting. We can connect to database manually by adding the following line in any class."
},
{
"code": null,
"e": 35528,
"s": 35502,
"text": "$this->load->database();\n"
},
{
"code": null,
"e": 35652,
"s": 35528,
"text": "Here, we are not passing any argument because everything is set in the database config file application/config/database.php"
},
{
"code": null,
"e": 35752,
"s": 35652,
"text": "To insert a record in the database, the insert() function is used as shown in the following table −"
},
{
"code": null,
"e": 35759,
"s": 35752,
"text": "Syntax"
},
{
"code": null,
"e": 35770,
"s": 35759,
"text": "Parameters"
},
{
"code": null,
"e": 35799,
"s": 35770,
"text": "$table (string) − Table name"
},
{
"code": null,
"e": 35828,
"s": 35799,
"text": "$table (string) − Table name"
},
{
"code": null,
"e": 35885,
"s": 35828,
"text": "$set (array) − An associative array of field/value pairs"
},
{
"code": null,
"e": 35942,
"s": 35885,
"text": "$set (array) − An associative array of field/value pairs"
},
{
"code": null,
"e": 36000,
"s": 35942,
"text": "$escape (bool) − Whether to escape values and identifiers"
},
{
"code": null,
"e": 36058,
"s": 36000,
"text": "$escape (bool) − Whether to escape values and identifiers"
},
{
"code": null,
"e": 36066,
"s": 36058,
"text": "Returns"
},
{
"code": null,
"e": 36078,
"s": 36066,
"text": "Return Type"
},
{
"code": null,
"e": 36315,
"s": 36078,
"text": "The following example shows how to insert a record in stud table. The $data is an array in which we have set the data and to insert this data to the table stud, we just need to pass this array to the insert function in the 2nd argument."
},
{
"code": null,
"e": 36414,
"s": 36315,
"text": "$data = array( \n 'roll_no' => ‘1’, \n 'name' => ‘Virat’ \n); \n\n$this->db->insert(\"stud\", $data);"
},
{
"code": null,
"e": 36601,
"s": 36414,
"text": "To update a record in the database, the update() function is used along with set() and where() functions as shown in the tables below. The set() function will set the data to be updated."
},
{
"code": null,
"e": 36608,
"s": 36601,
"text": "Syntax"
},
{
"code": null,
"e": 36619,
"s": 36608,
"text": "Parameters"
},
{
"code": null,
"e": 36679,
"s": 36619,
"text": "$key (mixed) − Field name, or an array of field/value pairs"
},
{
"code": null,
"e": 36739,
"s": 36679,
"text": "$key (mixed) − Field name, or an array of field/value pairs"
},
{
"code": null,
"e": 36796,
"s": 36739,
"text": "$value (string) − Field value, if $key is a single field"
},
{
"code": null,
"e": 36853,
"s": 36796,
"text": "$value (string) − Field value, if $key is a single field"
},
{
"code": null,
"e": 36911,
"s": 36853,
"text": "$escape (bool) − Whether to escape values and identifiers"
},
{
"code": null,
"e": 36969,
"s": 36911,
"text": "$escape (bool) − Whether to escape values and identifiers"
},
{
"code": null,
"e": 36977,
"s": 36969,
"text": "Returns"
},
{
"code": null,
"e": 36989,
"s": 36977,
"text": "Return Type"
},
{
"code": null,
"e": 37046,
"s": 36989,
"text": "The where() function will decide which record to update."
},
{
"code": null,
"e": 37053,
"s": 37046,
"text": "Syntax"
},
{
"code": null,
"e": 37064,
"s": 37053,
"text": "Parameters"
},
{
"code": null,
"e": 37126,
"s": 37064,
"text": "$key (mixed) − Name of field to compare, or associative array"
},
{
"code": null,
"e": 37188,
"s": 37126,
"text": "$key (mixed) − Name of field to compare, or associative array"
},
{
"code": null,
"e": 37245,
"s": 37188,
"text": "$value (mixed) − If a single key, compared to this value"
},
{
"code": null,
"e": 37302,
"s": 37245,
"text": "$value (mixed) − If a single key, compared to this value"
},
{
"code": null,
"e": 37360,
"s": 37302,
"text": "$escape (bool) − Whether to escape values and identifiers"
},
{
"code": null,
"e": 37418,
"s": 37360,
"text": "$escape (bool) − Whether to escape values and identifiers"
},
{
"code": null,
"e": 37426,
"s": 37418,
"text": "Returns"
},
{
"code": null,
"e": 37438,
"s": 37426,
"text": "Return Type"
},
{
"code": null,
"e": 37503,
"s": 37438,
"text": "Finally, the update() function will update data in the database."
},
{
"code": null,
"e": 37510,
"s": 37503,
"text": "Syntax"
},
{
"code": null,
"e": 37521,
"s": 37510,
"text": "Parameters"
},
{
"code": null,
"e": 37550,
"s": 37521,
"text": "$table (string) − Table name"
},
{
"code": null,
"e": 37579,
"s": 37550,
"text": "$table (string) − Table name"
},
{
"code": null,
"e": 37636,
"s": 37579,
"text": "$set (array) − An associative array of field/value pairs"
},
{
"code": null,
"e": 37693,
"s": 37636,
"text": "$set (array) − An associative array of field/value pairs"
},
{
"code": null,
"e": 37728,
"s": 37693,
"text": "$where (string) − The WHERE clause"
},
{
"code": null,
"e": 37763,
"s": 37728,
"text": "$where (string) − The WHERE clause"
},
{
"code": null,
"e": 37795,
"s": 37763,
"text": "$limit (int) − The LIMIT clause"
},
{
"code": null,
"e": 37827,
"s": 37795,
"text": "$limit (int) − The LIMIT clause"
},
{
"code": null,
"e": 37835,
"s": 37827,
"text": "Returns"
},
{
"code": null,
"e": 37847,
"s": 37835,
"text": "Return Type"
},
{
"code": null,
"e": 38005,
"s": 37847,
"text": "$data = array( \n 'roll_no' => ‘1’, \n 'name' => ‘Virat’ \n); \n\n$this->db->set($data); \n$this->db->where(\"roll_no\", ‘1’); \n$this->db->update(\"stud\", $data);"
},
{
"code": null,
"e": 38105,
"s": 38005,
"text": "To delete a record in the database, the delete() function is used as shown in the following table −"
},
{
"code": null,
"e": 38112,
"s": 38105,
"text": "Syntax"
},
{
"code": null,
"e": 38123,
"s": 38112,
"text": "Parameters"
},
{
"code": null,
"e": 38185,
"s": 38123,
"text": "$table (mixed) − The table(s) to delete from; string or array"
},
{
"code": null,
"e": 38247,
"s": 38185,
"text": "$table (mixed) − The table(s) to delete from; string or array"
},
{
"code": null,
"e": 38282,
"s": 38247,
"text": "$where (string) − The WHERE clause"
},
{
"code": null,
"e": 38317,
"s": 38282,
"text": "$where (string) − The WHERE clause"
},
{
"code": null,
"e": 38349,
"s": 38317,
"text": "$limit (int) − The LIMIT clause"
},
{
"code": null,
"e": 38381,
"s": 38349,
"text": "$limit (int) − The LIMIT clause"
},
{
"code": null,
"e": 38441,
"s": 38381,
"text": "$reset_data (bool) − TRUE to reset the query “write” clause"
},
{
"code": null,
"e": 38501,
"s": 38441,
"text": "$reset_data (bool) − TRUE to reset the query “write” clause"
},
{
"code": null,
"e": 38509,
"s": 38501,
"text": "Returns"
},
{
"code": null,
"e": 38521,
"s": 38509,
"text": "Return Type"
},
{
"code": null,
"e": 38710,
"s": 38521,
"text": "Use the following code to to delete a record in the stud table. The first argument indicates the name of the table to delete record and the second argument decides which record to delete."
},
{
"code": null,
"e": 38753,
"s": 38710,
"text": "$this->db->delete(\"stud\", \"roll_no = 1\");\n"
},
{
"code": null,
"e": 38849,
"s": 38753,
"text": "To select a record in the database, the get function is used, as shown in the following table −"
},
{
"code": null,
"e": 38856,
"s": 38849,
"text": "Syntax"
},
{
"code": null,
"e": 38867,
"s": 38856,
"text": "Parameters"
},
{
"code": null,
"e": 38910,
"s": 38867,
"text": "$table (string) − The table to query array"
},
{
"code": null,
"e": 38953,
"s": 38910,
"text": "$table (string) − The table to query array"
},
{
"code": null,
"e": 38985,
"s": 38953,
"text": "$limit (int) − The LIMIT clause"
},
{
"code": null,
"e": 39017,
"s": 38985,
"text": "$limit (int) − The LIMIT clause"
},
{
"code": null,
"e": 39051,
"s": 39017,
"text": "$offset (int) − The OFFSET clause"
},
{
"code": null,
"e": 39085,
"s": 39051,
"text": "$offset (int) − The OFFSET clause"
},
{
"code": null,
"e": 39093,
"s": 39085,
"text": "Returns"
},
{
"code": null,
"e": 39105,
"s": 39093,
"text": "Return Type"
},
{
"code": null,
"e": 39396,
"s": 39105,
"text": "Use the following code to get all the records from the database. The first statement fetches all the records from “stud” table and returns the object, which will be stored in $query object. The second statement calls the result() function with $query object to get all the records as array."
},
{
"code": null,
"e": 39467,
"s": 39396,
"text": "$query = $this->db->get(\"stud\"); \n$data['records'] = $query->result();"
},
{
"code": null,
"e": 39545,
"s": 39467,
"text": "Database connection can be closed manually, by executing the following code −"
},
{
"code": null,
"e": 39567,
"s": 39545,
"text": "$this->db->close(); \n"
},
{
"code": null,
"e": 39678,
"s": 39567,
"text": "Create a controller class called Stud_controller.php and save it at application/controller/Stud_controller.php"
},
{
"code": null,
"e": 39978,
"s": 39678,
"text": "Here is a complete example, wherein all of the above-mentioned operations are performed. Before executing the following example, create a database and table as instructed at the starting of this chapter and make necessary changes in the database config file stored at application/config/database.php"
},
{
"code": null,
"e": 42186,
"s": 39978,
"text": "<?php \n class Stud_controller extends CI_Controller {\n\t\n function __construct() { \n parent::__construct(); \n $this->load->helper('url'); \n $this->load->database(); \n } \n \n public function index() { \n $query = $this->db->get(\"stud\"); \n $data['records'] = $query->result(); \n\t\t\t\n $this->load->helper('url'); \n $this->load->view('Stud_view',$data); \n } \n \n public function add_student_view() { \n $this->load->helper('form'); \n $this->load->view('Stud_add'); \n } \n \n public function add_student() { \n $this->load->model('Stud_Model');\n\t\t\t\n $data = array( \n 'roll_no' => $this->input->post('roll_no'), \n 'name' => $this->input->post('name') \n ); \n\t\t\t\n $this->Stud_Model->insert($data); \n \n $query = $this->db->get(\"stud\"); \n $data['records'] = $query->result(); \n $this->load->view('Stud_view',$data); \n } \n \n public function update_student_view() { \n $this->load->helper('form'); \n $roll_no = $this->uri->segment('3'); \n $query = $this->db->get_where(\"stud\",array(\"roll_no\"=>$roll_no));\n $data['records'] = $query->result(); \n $data['old_roll_no'] = $roll_no; \n $this->load->view('Stud_edit',$data); \n } \n \n public function update_student(){ \n $this->load->model('Stud_Model');\n\t\t\t\n $data = array( \n 'roll_no' => $this->input->post('roll_no'), \n 'name' => $this->input->post('name') \n ); \n\t\t\t\n $old_roll_no = $this->input->post('old_roll_no'); \n $this->Stud_Model->update($data,$old_roll_no); \n\t\t\t\n $query = $this->db->get(\"stud\"); \n $data['records'] = $query->result(); \n $this->load->view('Stud_view',$data); \n } \n \n public function delete_student() { \n $this->load->model('Stud_Model'); \n $roll_no = $this->uri->segment('3'); \n $this->Stud_Model->delete($roll_no); \n \n $query = $this->db->get(\"stud\"); \n $data['records'] = $query->result(); \n $this->load->view('Stud_view',$data); \n } \n } \n?>"
},
{
"code": null,
"e": 42278,
"s": 42186,
"text": "Create a model class called Stud_Model.php and save it in application/models/Stud_Model.php"
},
{
"code": null,
"e": 42904,
"s": 42278,
"text": "<?php \n class Stud_Model extends CI_Model {\n\t\n function __construct() { \n parent::__construct(); \n } \n \n public function insert($data) { \n if ($this->db->insert(\"stud\", $data)) { \n return true; \n } \n } \n \n public function delete($roll_no) { \n if ($this->db->delete(\"stud\", \"roll_no = \".$roll_no)) { \n return true; \n } \n } \n \n public function update($data,$old_roll_no) { \n $this->db->set($data); \n $this->db->where(\"roll_no\", $old_roll_no); \n $this->db->update(\"stud\", $data); \n } \n } \n?> "
},
{
"code": null,
"e": 42989,
"s": 42904,
"text": "Create a view file called Stud_add.php and save it in application/views/Stud_add.php"
},
{
"code": null,
"e": 43682,
"s": 42989,
"text": "<!DOCTYPE html> \n<html lang = \"en\">\n \n <head> \n <meta charset = \"utf-8\"> \n <title>Students Example</title> \n </head> \n\t\n <body> \n <form method = \"\" action = \"\">\n\t\t\n <?php \n echo form_open('Stud_controller/add_student');\n echo form_label('Roll No.'); \n echo form_input(array('id'=>'roll_no','name'=>'roll_no')); \n echo \"<br/>\"; \n\t\t\t\n echo form_label('Name'); \n echo form_input(array('id'=>'name','name'=>'name')); \n echo \"<br/>\"; \n\t\t\t\n echo form_submit(array('id'=>'submit','value'=>'Add')); \n echo form_close(); \n ?> \n\t\t\n </form> \n </body>\n\t\n</html>"
},
{
"code": null,
"e": 43769,
"s": 43682,
"text": "Create a view file called Stud_edit.php and save it in application/views/Stud_edit.php"
},
{
"code": null,
"e": 44616,
"s": 43769,
"text": "<!DOCTYPE html> \n<html lang = \"en\">\n \n <head> \n <meta charset = \"utf-8\"> \n <title>Students Example</title> \n </head> \n\t\n <body> \n <form method = \"\" action = \"\">\n\t\t\n <?php \n echo form_open('Stud_controller/update_student'); \n echo form_hidden('old_roll_no',$old_roll_no); \n echo form_label('Roll No.'); \n echo form_input(array('id'⇒'roll_no',\n 'name'⇒'roll_no','value'⇒$records[0]→roll_no)); \n echo \"\n \"; \n\n echo form_label('Name'); \n echo form_input(array('id'⇒'name','name'⇒'name',\n 'value'⇒$records[0]→name)); \n echo \"\n \"; \n\n echo form_submit(array('id'⇒'sub mit','value'⇒'Edit')); \n echo form_close();\n ?> \n\t\t\t\n </form> \n </body>\n\t\n</html>"
},
{
"code": null,
"e": 44703,
"s": 44616,
"text": "Create a view file called Stud_view.php and save it in application/views/Stud_view.php"
},
{
"code": null,
"e": 45788,
"s": 44703,
"text": "<!DOCTYPE html> \n<html lang = \"en\">\n \n <head> \n <meta charset = \"utf-8\"> \n <title>Students Example</title> \n </head>\n\t\n <body> \n <a href = \"<?php echo base_url(); ?>\n index.php/stud/add_view\">Add</a>\n\t\t\n <table border = \"1\"> \n <?php \n $i = 1; \n echo \"<tr>\"; \n echo \"<td>Sr#</td>\"; \n echo \"<td>Roll No.</td>\"; \n echo \"<td>Name</td>\"; \n echo \"<td>Edit</td>\"; \n echo \"<td>Delete</td>\"; \n echo \"<tr>\"; \n\t\t\t\t\n foreach($records as $r) { \n echo \"<tr>\"; \n echo \"<td>\".$i++.\"</td>\"; \n echo \"<td>\".$r->roll_no.\"</td>\"; \n echo \"<td>\".$r->name.\"</td>\"; \n echo \"<td><a href = '\".base_url().\"index.php/stud/edit/\"\n .$r->roll_no.\"'>Edit</a></td>\"; \n echo \"<td><a href = '\".base_url().\"index.php/stud/delete/\"\n .$r->roll_no.\"'>Delete</a></td>\"; \n echo \"<tr>\"; \n } \n ?>\n </table> \n\t\t\n </body>\n\t\n</html>"
},
{
"code": null,
"e": 45912,
"s": 45788,
"text": "Make the following change in the route file at application/config/routes.php and add the following line at the end of file."
},
{
"code": null,
"e": 46204,
"s": 45912,
"text": "$route['stud'] = \"Stud_controller\"; \n$route['stud/add'] = 'Stud_controller/add_student'; \n$route['stud/add_view'] = 'Stud_controller/add_student_view'; \n$route['stud/edit/(\\d+)'] = 'Stud_controller/update_student_view/$1'; \n$route['stud/delete/(\\d+)'] = 'Stud_controller/delete_student/$1';\n"
},
{
"code": null,
"e": 46323,
"s": 46204,
"text": "Now, let us execute this example by visiting the following URL in the browser. Replace the yoursite.com with your URL."
},
{
"code": null,
"e": 46359,
"s": 46323,
"text": "http://yoursite.com/index.php/stud\n"
},
{
"code": null,
"e": 46682,
"s": 46359,
"text": "The essential part of a CodeIgniter framework is its libraries. It provides a rich set of libraries, which indirectly increase the speed of developing an application. The system library is located at system/libraries. All we need to do is to load the library that we want to use. The library can be loaded as shown below −"
},
{
"code": null,
"e": 46719,
"s": 46682,
"text": "$this->load->library('class name');\n"
},
{
"code": null,
"e": 46908,
"s": 46719,
"text": "Where class name is the name of the library that we want to load. If we want to load multiple libraries, then we can simply pass an array as argument to library() function as shown below −"
},
{
"code": null,
"e": 46956,
"s": 46908,
"text": "$this->load->library(array('email', 'table'));\n"
},
{
"code": null,
"e": 47149,
"s": 46956,
"text": "The library classes are located in system/libraries. Each class has various functions to simplify the developing work. Following table shows the names of the library class and its description."
},
{
"code": null,
"e": 47168,
"s": 47149,
"text": "Benchmarking Class"
},
{
"code": null,
"e": 47282,
"s": 47168,
"text": "Benchmarking class is always active, enabling the time difference between any two marked points to be calculated."
},
{
"code": null,
"e": 47296,
"s": 47282,
"text": "Caching Class"
},
{
"code": null,
"e": 47363,
"s": 47296,
"text": "This class will cache the pages, to quickly access the page speed."
},
{
"code": null,
"e": 47381,
"s": 47363,
"text": "Calendaring Class"
},
{
"code": null,
"e": 47437,
"s": 47381,
"text": "Using this class, you can dynamically create calendars."
},
{
"code": null,
"e": 47457,
"s": 47437,
"text": "Shopping Cart Class"
},
{
"code": null,
"e": 47613,
"s": 47457,
"text": "Using this class, you can add or remove item from Shopping Cart. The items are saved in session and will remain active until the user is browsing the site."
},
{
"code": null,
"e": 47626,
"s": 47613,
"text": "Config Class"
},
{
"code": null,
"e": 47729,
"s": 47626,
"text": "Configuration preferences can be retrieved, using this class. This class is initialized automatically."
},
{
"code": null,
"e": 47741,
"s": 47729,
"text": "Email Class"
},
{
"code": null,
"e": 47819,
"s": 47741,
"text": "This class provides email related functionality, like send or reply to email."
},
{
"code": null,
"e": 47836,
"s": 47819,
"text": "Encryption Class"
},
{
"code": null,
"e": 47895,
"s": 47836,
"text": "This class provides two-way data encryption functionality."
},
{
"code": null,
"e": 47916,
"s": 47895,
"text": "File Uploading Class"
},
{
"code": null,
"e": 48068,
"s": 47916,
"text": "This class provides functionalities related to file uploading. You can set various preferences like type of file to be uploaded, size of the files etc."
},
{
"code": null,
"e": 48090,
"s": 48068,
"text": "Form Validation Class"
},
{
"code": null,
"e": 48146,
"s": 48090,
"text": "This class provides various functions to validate form."
},
{
"code": null,
"e": 48156,
"s": 48146,
"text": "FTP Class"
},
{
"code": null,
"e": 48294,
"s": 48156,
"text": "This class provides various FTP related functions like transferring files to remove server, moving, renaming or deleting files on server."
},
{
"code": null,
"e": 48319,
"s": 48294,
"text": "Image Manipulation Class"
},
{
"code": null,
"e": 48448,
"s": 48319,
"text": "Manipulation of image like resize, thumbnail creation, cropping, rotating, watermarking can be done with the help of this class."
},
{
"code": null,
"e": 48460,
"s": 48448,
"text": "Input Class"
},
{
"code": null,
"e": 48521,
"s": 48460,
"text": "This class pre-processes the input data for security reason."
},
{
"code": null,
"e": 48536,
"s": 48521,
"text": "Language Class"
},
{
"code": null,
"e": 48581,
"s": 48536,
"text": "This class is used for internationalization."
},
{
"code": null,
"e": 48594,
"s": 48581,
"text": "Loader Class"
},
{
"code": null,
"e": 48667,
"s": 48594,
"text": "This class loads elements like View files, Drivers, Helpers, Models etc."
},
{
"code": null,
"e": 48684,
"s": 48667,
"text": "Migrations Class"
},
{
"code": null,
"e": 48752,
"s": 48684,
"text": "This class provides functionalities related to database migrations."
},
{
"code": null,
"e": 48765,
"s": 48752,
"text": "Output Class"
},
{
"code": null,
"e": 48835,
"s": 48765,
"text": "This class sends the output to browser and also, caches that webpage."
},
{
"code": null,
"e": 48852,
"s": 48835,
"text": "Pagination Class"
},
{
"code": null,
"e": 48908,
"s": 48852,
"text": "This class adds pagination functionalities to web page."
},
{
"code": null,
"e": 48930,
"s": 48908,
"text": "Template Parser Class"
},
{
"code": null,
"e": 49101,
"s": 48930,
"text": "The Template Parser Class can perform simple text substitution for pseudo-variables contained within your view files. It can parse simple variables or variable tag pairs."
},
{
"code": null,
"e": 49116,
"s": 49101,
"text": "Security Class"
},
{
"code": null,
"e": 49193,
"s": 49116,
"text": "This class contains security related functions like XSS Filtering, CSRF etc."
},
{
"code": null,
"e": 49209,
"s": 49193,
"text": "Session Library"
},
{
"code": null,
"e": 49286,
"s": 49209,
"text": "This class provides functionalities to maintain session of your application."
},
{
"code": null,
"e": 49297,
"s": 49286,
"text": "HTML Table"
},
{
"code": null,
"e": 49377,
"s": 49297,
"text": "This class is used to auto-generate HTML tables from array or database results."
},
{
"code": null,
"e": 49393,
"s": 49377,
"text": "Trackback Class"
},
{
"code": null,
"e": 49484,
"s": 49393,
"text": "The Trackback Class provides functions that enable you to send and receive Trackback data."
},
{
"code": null,
"e": 49501,
"s": 49484,
"text": "Typography Class"
},
{
"code": null,
"e": 49565,
"s": 49501,
"text": "The Typography Class provides methods that help to format text."
},
{
"code": null,
"e": 49584,
"s": 49565,
"text": "Unit Testing Class"
},
{
"code": null,
"e": 49675,
"s": 49584,
"text": "This class provides functionalities to unit test your application and generate the result."
},
{
"code": null,
"e": 49685,
"s": 49675,
"text": "URI Class"
},
{
"code": null,
"e": 49861,
"s": 49685,
"text": "The URI Class provides methods that help you retrieve information from your URI strings. If you use URI routing, you can also retrieve information about the rerouted segments."
},
{
"code": null,
"e": 49878,
"s": 49861,
"text": "User Agent Class"
},
{
"code": null,
"e": 50119,
"s": 49878,
"text": "The User Agent Class provides functions that help identify information about the browser, mobile device, or robot visiting your site. In addition, you can get referrer information as well as language and supported character-set information."
},
{
"code": null,
"e": 50154,
"s": 50119,
"text": "XML-RPC and XML-RPC Server Classes"
},
{
"code": null,
"e": 50286,
"s": 50154,
"text": "CodeIgniter’s XML-RPC classes permit you to send requests to another server, or set up your own XML-RPC server to receive requests."
},
{
"code": null,
"e": 50305,
"s": 50286,
"text": "Zip Encoding Class"
},
{
"code": null,
"e": 50361,
"s": 50305,
"text": "This class is used to create zip archives of your data."
},
{
"code": null,
"e": 50635,
"s": 50361,
"text": "CodeIgniter has rich set of libraries, which you can find in system/libraries folder but CodeIgniter is not just limited to system libraries, you can create your own libraries too, which can be stored in application/libraries folder. You can create libraries in three ways."
},
{
"code": null,
"e": 50654,
"s": 50635,
"text": "Create new library"
},
{
"code": null,
"e": 50680,
"s": 50654,
"text": "Extend the native library"
},
{
"code": null,
"e": 50707,
"s": 50680,
"text": "Replace the native library"
},
{
"code": null,
"e": 50782,
"s": 50707,
"text": "While creating new library one should keep in mind, the following things −"
},
{
"code": null,
"e": 50855,
"s": 50782,
"text": "The name of the file must start with a capital letter e.g. Mylibrary.php"
},
{
"code": null,
"e": 50924,
"s": 50855,
"text": "The class name must start with a capital letter e.g. class Mylibrary"
},
{
"code": null,
"e": 50979,
"s": 50924,
"text": "The name of the class and name of the file must match."
},
{
"code": null,
"e": 50993,
"s": 50979,
"text": "Mylibrary.php"
},
{
"code": null,
"e": 51182,
"s": 50993,
"text": "<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');\n \n class Mylibrary {\n\t\n public function some_function() {\n }\n }\n\t\n/* End of file Mylibrary.php */"
},
{
"code": null,
"e": 51209,
"s": 51182,
"text": "Loading the Custom Library"
},
{
"code": null,
"e": 51300,
"s": 51209,
"text": "The above library can be loaded by simply executing the following line in your controller."
},
{
"code": null,
"e": 51336,
"s": 51300,
"text": "$this->load->library(‘mylibrary’);\n"
},
{
"code": null,
"e": 51580,
"s": 51336,
"text": "mylibrary is the name of your library and you can write it in lowercase as well as uppercase letters. Use the name of the library without “.php” extension. After loading the library, you can also call the function of that class as shown below."
},
{
"code": null,
"e": 51616,
"s": 51580,
"text": "$this->mylibrary->some_function();\n"
},
{
"code": null,
"e": 51968,
"s": 51616,
"text": "Sometimes, you may need to add your own functionality to the library provided by CodeIgniter. CodeIgniter provides facility by which you can extend the native library and add your own functions. To achieve this, you must extend the class of native library class. For example if you want to extend the Email library then it can be done as shown below −"
},
{
"code": null,
"e": 52005,
"s": 51968,
"text": "Class MY_Email extends CI_Email { \n}"
},
{
"code": null,
"e": 52218,
"s": 52005,
"text": "Here, in the above example, MY_Email class is extending the native library’s email class CI_Email. This library can be loaded by the standard way of loading email library. Save the above code in file My_Email.php"
},
{
"code": null,
"e": 52639,
"s": 52218,
"text": "In some situations, you do not want to use the native library the way it works and want to replace it with your own way. This can be done by replacing the native library. To achieve this, you just need to give the same class name as it is named in native library. For example, if you want to replace the Email class, then use the code as shown below. Save your file name with Email.php and give a class name to CI_Email."
},
{
"code": null,
"e": 52649,
"s": 52639,
"text": "Email.php"
},
{
"code": null,
"e": 52669,
"s": 52649,
"text": "Class CI_Email { \n}"
},
{
"code": null,
"e": 52858,
"s": 52669,
"text": "Many times, while using application, we come across errors. It is very annoying for the users if the errors are not handled properly. CodeIgniter provides an easy error handling mechanism."
},
{
"code": null,
"e": 53045,
"s": 52858,
"text": "You would like the messages to be displayed, when the application is in developing mode rather than in production mode as the error messages can be solved easily at the developing stage."
},
{
"code": null,
"e": 53270,
"s": 53045,
"text": "The environment of your application can be changed, by changing the line given below from index.php file. This can be set to anything but normally there are three values (development, test, production) used for this purpose."
},
{
"code": null,
"e": 53358,
"s": 53270,
"text": "define('ENVIRONMENT', isset($_SERVER['CI_ENV']) ? $_SERVER['CI_ENV'] : 'development');\n"
},
{
"code": null,
"e": 53591,
"s": 53358,
"text": "Different environment will require different levels of error reporting. By default, development mode will display errors and testing and live mode will hide them. CodeIgniter provides three functions as shown below to handle errors."
},
{
"code": null,
"e": 53670,
"s": 53591,
"text": "show_error() function displays errors in HTML format at the top of the screen."
},
{
"code": null,
"e": 53749,
"s": 53670,
"text": "show_error() function displays errors in HTML format at the top of the screen."
},
{
"code": null,
"e": 53756,
"s": 53749,
"text": "Syntax"
},
{
"code": null,
"e": 53767,
"s": 53756,
"text": "Parameters"
},
{
"code": null,
"e": 53800,
"s": 53767,
"text": "$message (mixed) − Error message"
},
{
"code": null,
"e": 53833,
"s": 53800,
"text": "$message (mixed) − Error message"
},
{
"code": null,
"e": 53880,
"s": 53833,
"text": "$status_code (int) − HTTP Response status code"
},
{
"code": null,
"e": 53927,
"s": 53880,
"text": "$status_code (int) − HTTP Response status code"
},
{
"code": null,
"e": 53966,
"s": 53927,
"text": "$heading (string) − Error page heading"
},
{
"code": null,
"e": 54005,
"s": 53966,
"text": "$heading (string) − Error page heading"
},
{
"code": null,
"e": 54017,
"s": 54005,
"text": "Return Type"
},
{
"code": null,
"e": 54109,
"s": 54017,
"text": "show_404() function displays error if you are trying to access a page which does not exist."
},
{
"code": null,
"e": 54201,
"s": 54109,
"text": "show_404() function displays error if you are trying to access a page which does not exist."
},
{
"code": null,
"e": 54208,
"s": 54201,
"text": "Syntax"
},
{
"code": null,
"e": 54219,
"s": 54208,
"text": "Parameters"
},
{
"code": null,
"e": 54247,
"s": 54219,
"text": "$page (string) – URI string"
},
{
"code": null,
"e": 54275,
"s": 54247,
"text": "$page (string) – URI string"
},
{
"code": null,
"e": 54320,
"s": 54275,
"text": "$log_error (bool) – Whether to log the error"
},
{
"code": null,
"e": 54365,
"s": 54320,
"text": "$log_error (bool) – Whether to log the error"
},
{
"code": null,
"e": 54377,
"s": 54365,
"text": "Return Type"
},
{
"code": null,
"e": 54486,
"s": 54377,
"text": "log_message() function is used to write log messages. This is useful when you want to write custom messages."
},
{
"code": null,
"e": 54595,
"s": 54486,
"text": "log_message() function is used to write log messages. This is useful when you want to write custom messages."
},
{
"code": null,
"e": 54602,
"s": 54595,
"text": "Syntax"
},
{
"code": null,
"e": 54613,
"s": 54602,
"text": "Parameters"
},
{
"code": null,
"e": 54669,
"s": 54613,
"text": "$level (string) − Log level: ‘error’, ‘debug’ or ‘info’"
},
{
"code": null,
"e": 54725,
"s": 54669,
"text": "$level (string) − Log level: ‘error’, ‘debug’ or ‘info’"
},
{
"code": null,
"e": 54760,
"s": 54725,
"text": "$message (string) − Message to log"
},
{
"code": null,
"e": 54795,
"s": 54760,
"text": "$message (string) − Message to log"
},
{
"code": null,
"e": 54864,
"s": 54795,
"text": "$php_error (bool) − Whether we’re logging a native PHP error message"
},
{
"code": null,
"e": 54933,
"s": 54864,
"text": "$php_error (bool) − Whether we’re logging a native PHP error message"
},
{
"code": null,
"e": 54945,
"s": 54933,
"text": "Return Type"
},
{
"code": null,
"e": 55092,
"s": 54945,
"text": "Logging can be enabled in application/config/config.php file. Given below is the screenshot of config.php file, where you can set threshold value."
},
{
"code": null,
"e": 55887,
"s": 55092,
"text": "/*\n|--------------------------------------------------------------------------------\n| Error Logging Threshold\n|--------------------------------------------------------------------------------\n| You can enable error logging by setting a threshold over zero. The \n| threshold determines what gets logged. Threshold options are:\n|\n| 0 = Disable logging, Error logging TURNED OFF\n| 1 = Error Message (including PHP errors)\n| 2 = Debug Message\n| 3 = Informational Messages\n| 4 = All Messages\n|\n| You can also pass an array with threshold levels to show individual error types\n|\n| array(2) = Debug Message, without Error Messages\n| For a live site you'll usually only enable Errors (1) to be logged otherwise \n| your log files will fill up very fast.\n|\n*/\n$config['log_threshold'] = 0;"
},
{
"code": null,
"e": 56009,
"s": 55887,
"text": "You can find the log messages in application/log/. Make sure that this directory is writable before you enable log files."
},
{
"code": null,
"e": 56125,
"s": 56009,
"text": "Various templates for error messages can be found in application/views/errors/cli or application/views/errors/html."
},
{
"code": null,
"e": 56346,
"s": 56125,
"text": "Using File Uploading class, we can upload files and we can also, restrict the type and size of the file to be uploaded. Follow the steps shown in the given example to understand the file uploading process in CodeIgniter."
},
{
"code": null,
"e": 56420,
"s": 56346,
"text": "Copy the following code and store it at application/view/Upload_form.php."
},
{
"code": null,
"e": 56806,
"s": 56420,
"text": "<html>\n \n <head> \n <title>Upload Form</title> \n </head>\n\t\n <body> \n <?php echo $error;?> \n <?php echo form_open_multipart('upload/do_upload');?> \n\t\t\n <form action = \"\" method = \"\">\n <input type = \"file\" name = \"userfile\" size = \"20\" /> \n <br /><br /> \n <input type = \"submit\" value = \"upload\" /> \n </form> \n\t\t\n </body>\n\t\n</html>"
},
{
"code": null,
"e": 56884,
"s": 56806,
"text": "Copy the code given below and store it at application/view/Upload_success.php"
},
{
"code": null,
"e": 57291,
"s": 56884,
"text": "<html>\n \n <head> \n <title>Upload Form</title> \n </head>\n\t\n <body> \n <h3>Your file was successfully uploaded!</h3> \n\t\t\n <ul> \n <?phpforeach ($upload_data as $item => $value):?> \n <li><?php echo $item;?>: <?php echo $value;?></li> \n <?phpendforeach; ?>\n </ul> \n\t\t\n <p><?php echo anchor('upload', 'Upload Another File!'); ?></p> \n </body>\n\t\n</html>"
},
{
"code": null,
"e": 57472,
"s": 57291,
"text": "Copy the code given below and store it at application/controllers/Upload.php. Create “uploads” folder at the root of CodeIgniter i.e. at the parent directory of application folder."
},
{
"code": null,
"e": 58465,
"s": 57472,
"text": "<?php\n \n class Upload extends CI_Controller {\n\t\n public function __construct() { \n parent::__construct(); \n $this->load->helper(array('form', 'url')); \n }\n\t\t\n public function index() { \n $this->load->view('upload_form', array('error' => ' ' )); \n } \n\t\t\n public function do_upload() { \n $config['upload_path'] = './uploads/'; \n $config['allowed_types'] = 'gif|jpg|png'; \n $config['max_size'] = 100; \n $config['max_width'] = 1024; \n $config['max_height'] = 768; \n $this->load->library('upload', $config);\n\t\t\t\n if ( ! $this->upload->do_upload('userfile')) {\n $error = array('error' => $this->upload->display_errors()); \n $this->load->view('upload_form', $error); \n }\n\t\t\t\n else { \n $data = array('upload_data' => $this->upload->data()); \n $this->load->view('upload_success', $data); \n } \n } \n } \n?>"
},
{
"code": null,
"e": 58589,
"s": 58465,
"text": "Make the following change in the route file in application/config/routes.php and add the following line at the end of file."
},
{
"code": null,
"e": 58619,
"s": 58589,
"text": "$route['upload'] = 'Upload';\n"
},
{
"code": null,
"e": 58737,
"s": 58619,
"text": "Now let us execute this example by visiting the following URL in the browser. Replace the yoursite.com with your URL."
},
{
"code": null,
"e": 58775,
"s": 58737,
"text": "http://yoursite.com/index.php/upload\n"
},
{
"code": null,
"e": 58814,
"s": 58775,
"text": "It will produce the following screen −"
},
{
"code": null,
"e": 58887,
"s": 58814,
"text": "After successfully uploading a file, you will see the following screen −"
},
{
"code": null,
"e": 59060,
"s": 58887,
"text": "Sending email in CodeIgniter is much easier. You also configure the preferences regarding email in CodeIgniter. CodeIgniter provides following features for sending emails −"
},
{
"code": null,
"e": 59106,
"s": 59060,
"text": "Multiple Protocols − Mail, Sendmail, and SMTP"
},
{
"code": null,
"e": 59138,
"s": 59106,
"text": "TLS and SSL Encryption for SMTP"
},
{
"code": null,
"e": 59158,
"s": 59138,
"text": "Multiple recipients"
},
{
"code": null,
"e": 59170,
"s": 59158,
"text": "CC and BCCs"
},
{
"code": null,
"e": 59194,
"s": 59170,
"text": "HTML or Plaintext email"
},
{
"code": null,
"e": 59206,
"s": 59194,
"text": "Attachments"
},
{
"code": null,
"e": 59220,
"s": 59206,
"text": "Word wrapping"
},
{
"code": null,
"e": 59231,
"s": 59220,
"text": "Priorities"
},
{
"code": null,
"e": 59311,
"s": 59231,
"text": "BCC Batch Mode, enabling large email lists to be broken into small BCC batches."
},
{
"code": null,
"e": 59333,
"s": 59311,
"text": "Email Debugging tools"
},
{
"code": null,
"e": 59412,
"s": 59333,
"text": "Email class has the following functions to simplify the job of sending emails."
},
{
"code": null,
"e": 59451,
"s": 59412,
"text": "$from (string) − “From” e-mail address"
},
{
"code": null,
"e": 59488,
"s": 59451,
"text": "$name (string) − “From” display name"
},
{
"code": null,
"e": 59569,
"s": 59488,
"text": "$return_path (string) − Optional email address to redirect undelivered e-mail to"
},
{
"code": null,
"e": 59616,
"s": 59569,
"text": "$replyto (string) − E-mail address for replies"
},
{
"code": null,
"e": 59678,
"s": 59616,
"text": "$name (string) − Display name for the reply-to e-mail address"
},
{
"code": null,
"e": 59747,
"s": 59678,
"text": "$to (mixed) − Comma-delimited string or an array of e-mail addresses"
},
{
"code": null,
"e": 59816,
"s": 59747,
"text": "$cc (mixed) − Comma-delimited string or an array of e-mail addresses"
},
{
"code": null,
"e": 59886,
"s": 59816,
"text": "$bcc (mixed) − Comma-delimited string or an array of e-mail addresses"
},
{
"code": null,
"e": 59945,
"s": 59886,
"text": "$limit (int) − Maximum number of e-mails to send per batch"
},
{
"code": null,
"e": 59985,
"s": 59945,
"text": "$subject (string) − E-mail subject line"
},
{
"code": null,
"e": 60022,
"s": 59985,
"text": "$body (string) − E-mail message body"
},
{
"code": null,
"e": 60070,
"s": 60022,
"text": "$str (string) − Alternative e-mail message body"
},
{
"code": null,
"e": 60101,
"s": 60070,
"text": "$header (string) − Header name"
},
{
"code": null,
"e": 60132,
"s": 60101,
"text": "$value (string) − Header value"
},
{
"code": null,
"e": 60196,
"s": 60132,
"text": "$clear_attachments (bool) – Whether or not to clear attachments"
},
{
"code": null,
"e": 60261,
"s": 60196,
"text": "$auto_clear (bool) − Whether to clear message data automatically"
},
{
"code": null,
"e": 60292,
"s": 60261,
"text": "$filename (string) − File name"
},
{
"code": null,
"e": 60444,
"s": 60292,
"text": "$disposition (string) − ‘disposition’ of the attachment. Most email clients make their own decision regardless of the MIME specification used here.iana"
},
{
"code": null,
"e": 60502,
"s": 60444,
"text": "$newname (string) − Custom file name to use in the e-mail"
},
{
"code": null,
"e": 60563,
"s": 60502,
"text": "$mime (string) − MIME type to use (useful for buffered data)"
},
{
"code": null,
"e": 60613,
"s": 60563,
"text": "$filename (string) − Existing attachment filename"
},
{
"code": null,
"e": 60708,
"s": 60613,
"text": "To send an email using CodeIgniter, first you have to load email library using the following −"
},
{
"code": null,
"e": 60740,
"s": 60708,
"text": "$this->load->library('email');\n"
},
{
"code": null,
"e": 61073,
"s": 60740,
"text": "After loading the library, simply execute the following functions to set necessary elements to send an email. The from() function is used to set − from where the email is being sent and to() function is used − to whom the email is being sent. The subject() and message() function is used to set the subject and message of the email."
},
{
"code": null,
"e": 61257,
"s": 61073,
"text": "$this->email->from('[email protected]', 'Your Name');\n$this->email->to('[email protected]');\n \n$this->email->subject('Email Test');\n$this->email->message('Testing the email class.');"
},
{
"code": null,
"e": 61330,
"s": 61257,
"text": "After that, execute the send() function as shown below to send an email."
},
{
"code": null,
"e": 61353,
"s": 61330,
"text": "$this->email->send();\n"
},
{
"code": null,
"e": 61459,
"s": 61353,
"text": "Create a controller file Email_controller.php and save it in application/controller/Email_controller.php."
},
{
"code": null,
"e": 62521,
"s": 61459,
"text": "<?php \n class Email_controller extends CI_Controller { \n \n function __construct() { \n parent::__construct(); \n $this->load->library('session'); \n $this->load->helper('form'); \n } \n\t\t\n public function index() { \n\t\n $this->load->helper('form'); \n $this->load->view('email_form'); \n } \n \n public function send_mail() { \n $from_email = \"[email protected]\"; \n $to_email = $this->input->post('email'); \n \n //Load email library \n $this->load->library('email'); \n \n $this->email->from($from_email, 'Your Name'); \n $this->email->to($to_email);\n $this->email->subject('Email Test'); \n $this->email->message('Testing the email class.'); \n \n //Send mail \n if($this->email->send()) \n $this->session->set_flashdata(\"email_sent\",\"Email sent successfully.\"); \n else \n $this->session->set_flashdata(\"email_sent\",\"Error in sending Email.\"); \n $this->load->view('email_form'); \n } \n } \n?>"
},
{
"code": null,
"e": 62610,
"s": 62521,
"text": "Create a view file called email_form.php and save it at application/views/email_form.php"
},
{
"code": null,
"e": 63085,
"s": 62610,
"text": "<!DOCTYPE html> \n<html lang = \"en\"> \n\n <head> \n <meta charset = \"utf-8\"> \n <title>CodeIgniter Email Example</title> \n </head>\n\t\n <body> \n <?php \n echo $this->session->flashdata('email_sent'); \n echo form_open('/Email_controller/send_mail'); \n ?> \n\t\t\n <input type = \"email\" name = \"email\" required /> \n <input type = \"submit\" value = \"SEND MAIL\"> \n\t\t\n <?php \n echo form_close(); \n ?> \n </body>\n\t\n</html>"
},
{
"code": null,
"e": 63209,
"s": 63085,
"text": "Make the changes in the routes.php file in application/config/routes.php and add the following line at the end of the file."
},
{
"code": null,
"e": 63248,
"s": 63209,
"text": "$route['email'] = 'Email_Controller';\n"
},
{
"code": null,
"e": 63358,
"s": 63248,
"text": "Execute the above example by visiting the following link. Replace the yoursite.com with the URL of your site."
},
{
"code": null,
"e": 63395,
"s": 63358,
"text": "http://yoursite.com/index.php/email\n"
},
{
"code": null,
"e": 63644,
"s": 63395,
"text": "Validation is an important process while building web application. It ensures that the data that we are getting is proper and valid to store or process. CodeIgniter has made this task very easy. Let us understand this process with a simple example."
},
{
"code": null,
"e": 63880,
"s": 63644,
"text": "Create a view file myform.php and save the below code it in application/views/myform.php. This page will display form where user can submit his name and we will validate this page to ensure that it should not be empty while submitting."
},
{
"code": null,
"e": 64278,
"s": 63880,
"text": "<html>\n \n <head> \n <title>My Form</title> \n </head>\n\t\n <body>\n <form action = \"\" method = \"\">\n <?php echo validation_errors(); ?> \n <?php echo form_open('form'); ?> \n <h5>Name</h5> \n <input type = \"text\" name = \"name\" value = \"\" size = \"50\" /> \n <div><input type = \"submit\" value = \"Submit\" /></div> \n </form> \n </body>\n\t\n</html>"
},
{
"code": null,
"e": 64430,
"s": 64278,
"text": "Create a view file formsuccess.php and save it in application/views/formsuccess.php. This page will be displayed if the form is validated successfully."
},
{
"code": null,
"e": 64643,
"s": 64430,
"text": "<html>\n \n <head> \n <title>My Form</title>\n </head> \n\t\n <body> \n <h3>Your form was successfully submitted!</h3> \n <p><?php echo anchor('form', 'Try it again!'); ?></p> \n </body>\n\t\n</html>"
},
{
"code": null,
"e": 64831,
"s": 64643,
"text": "Create a controller file Form.php and save it in application/controller/Form.php. This form will either, show errors if it is not validated properly or redirected to formsuccess.php page."
},
{
"code": null,
"e": 65434,
"s": 64831,
"text": "<?php\n \n class Form extends CI_Controller { \n\t\n public function index() { \n /* Load form helper */ \n $this->load->helper(array('form'));\n\t\t\t\n /* Load form validation library */ \n $this->load->library('form_validation');\n\t\t\t\n /* Set validation rule for name field in the form */ \n $this->form_validation->set_rules('name', 'Name', 'required'); \n\t\t\t\n if ($this->form_validation->run() == FALSE) { \n $this->load->view('myform'); \n } \n else { \n $this->load->view('formsuccess'); \n } \n }\n }\n?>"
},
{
"code": null,
"e": 65491,
"s": 65434,
"text": "Add the following line in application/config/routes.php."
},
{
"code": null,
"e": 65523,
"s": 65491,
"text": "$route['validation'] = 'Form';\n"
},
{
"code": null,
"e": 65643,
"s": 65523,
"text": "Let us execute this example by visiting the following URL in the browser. This URL may be different based on your site."
},
{
"code": null,
"e": 65685,
"s": 65643,
"text": "http://yoursite.com/index.php/validation\n"
},
{
"code": null,
"e": 65724,
"s": 65685,
"text": "It will produce the following screen −"
},
{
"code": null,
"e": 65991,
"s": 65724,
"text": "We have added a validation in the controller − Name is required field before submitting the form. So, if you click the submit button without entering anything in the name field, then you will be asked to enter the name before submitting as shown in the screen below."
},
{
"code": null,
"e": 66082,
"s": 65991,
"text": "After entering the name successfully, you will be redirected to the screen as shown below."
},
{
"code": null,
"e": 66222,
"s": 66082,
"text": "In the above example, we have used the required rule setting. There are many rules available in the CodeIgniter, which are described below."
},
{
"code": null,
"e": 66298,
"s": 66222,
"text": "The following is a list of all the native rules that are available to use −"
},
{
"code": null,
"e": 66307,
"s": 66298,
"text": "required"
},
{
"code": null,
"e": 66315,
"s": 66307,
"text": "matches"
},
{
"code": null,
"e": 66327,
"s": 66315,
"text": "regex_match"
},
{
"code": null,
"e": 66335,
"s": 66327,
"text": "differs"
},
{
"code": null,
"e": 66345,
"s": 66335,
"text": "is_unique"
},
{
"code": null,
"e": 66356,
"s": 66345,
"text": "min_length"
},
{
"code": null,
"e": 66367,
"s": 66356,
"text": "max_length"
},
{
"code": null,
"e": 66380,
"s": 66367,
"text": "exact_length"
},
{
"code": null,
"e": 66393,
"s": 66380,
"text": "greater_than"
},
{
"code": null,
"e": 66415,
"s": 66393,
"text": "greater_than_equal_to"
},
{
"code": null,
"e": 66425,
"s": 66415,
"text": "less_than"
},
{
"code": null,
"e": 66444,
"s": 66425,
"text": "less_than_equal_to"
},
{
"code": null,
"e": 66452,
"s": 66444,
"text": "in_list"
},
{
"code": null,
"e": 66458,
"s": 66452,
"text": "alpha"
},
{
"code": null,
"e": 66472,
"s": 66458,
"text": "alpha_numeric"
},
{
"code": null,
"e": 66493,
"s": 66472,
"text": "alpha_numeric_spaces"
},
{
"code": null,
"e": 66504,
"s": 66493,
"text": "alpha_dash"
},
{
"code": null,
"e": 66512,
"s": 66504,
"text": "numeric"
},
{
"code": null,
"e": 66520,
"s": 66512,
"text": "integer"
},
{
"code": null,
"e": 66528,
"s": 66520,
"text": "decimal"
},
{
"code": null,
"e": 66539,
"s": 66528,
"text": "is_natural"
},
{
"code": null,
"e": 66558,
"s": 66539,
"text": "is_natural_no_zero"
},
{
"code": null,
"e": 66568,
"s": 66558,
"text": "valid_url"
},
{
"code": null,
"e": 66580,
"s": 66568,
"text": "valid_email"
},
{
"code": null,
"e": 66593,
"s": 66580,
"text": "valid_emails"
},
{
"code": null,
"e": 66602,
"s": 66593,
"text": "valid_ip"
},
{
"code": null,
"e": 66615,
"s": 66602,
"text": "valid_base64"
},
{
"code": null,
"e": 66782,
"s": 66615,
"text": "When building websites, we often need to track user’s activity and state and for this purpose, we have to use session. CodeIgniter has session class for this purpose."
},
{
"code": null,
"e": 66962,
"s": 66782,
"text": "Sessions data are available globally through the site but to use those data we first need to initialize the session. We can do that by executing the following line in constructor."
},
{
"code": null,
"e": 66996,
"s": 66962,
"text": "$this->load->library('session');\n"
},
{
"code": null,
"e": 67085,
"s": 66996,
"text": "After loading the session library, you can simply use the session object as shown below."
},
{
"code": null,
"e": 67101,
"s": 67085,
"text": "$this->session\n"
},
{
"code": null,
"e": 67182,
"s": 67101,
"text": "In PHP, we simply use $_SESSION array to set any data in session as shown below."
},
{
"code": null,
"e": 67209,
"s": 67182,
"text": "$_SESSION[‘key’] = value;\n"
},
{
"code": null,
"e": 67295,
"s": 67209,
"text": "Where ‘key’ is the key of array and value is assigned on right side of equal to sign."
},
{
"code": null,
"e": 67353,
"s": 67295,
"text": "The same thing can be done in CodeIgniter as shown below."
},
{
"code": null,
"e": 67411,
"s": 67353,
"text": "$this->session->set_userdata('some_name', 'some_value');\n"
},
{
"code": null,
"e": 67564,
"s": 67411,
"text": "set_userdata() function takes two arguments. The first argument, some_name, is the name of the session variable, under which, some_value will be stored."
},
{
"code": null,
"e": 67677,
"s": 67564,
"text": "set_userdata() function also supports another syntax in which you can pass array to store values as shown below."
},
{
"code": null,
"e": 67839,
"s": 67677,
"text": "$newdata = array( \n 'username' => 'johndoe', \n 'email' => '[email protected]', \n 'logged_in' => TRUE\n); \n\n$this->session->set_userdata($newdata);"
},
{
"code": null,
"e": 67927,
"s": 67839,
"text": "In PHP, we can remove data stored in session using the unset() function as shown below."
},
{
"code": null,
"e": 67959,
"s": 67927,
"text": "unset($_SESSION[‘some_name’]);\n"
},
{
"code": null,
"e": 68118,
"s": 67959,
"text": "Removing session data in CodeIgniter is very simple as shown below. The below version of unset_userdata() function will remove only one variable from session."
},
{
"code": null,
"e": 68164,
"s": 68118,
"text": "$this->session->unset_userdata('some_name');\n"
},
{
"code": null,
"e": 68300,
"s": 68164,
"text": "If you want to remove more values from session or to remove an entire array you can use the below version of unset_userdata() function."
},
{
"code": null,
"e": 68347,
"s": 68300,
"text": "$this->session->unset_userdata($array_items);\n"
},
{
"code": null,
"e": 68562,
"s": 68347,
"text": "After setting data in session, we can also retrieve that data as shown below. Userdata() function will be used for this purpose. This function will return NULL if the data you are trying to access is not available."
},
{
"code": null,
"e": 68605,
"s": 68562,
"text": "$name = $this->session->userdata('name');\n"
},
{
"code": null,
"e": 68723,
"s": 68605,
"text": "Create a controller class called Session_controller.php and save it in application/controller/Session_controller.php."
},
{
"code": null,
"e": 69327,
"s": 68723,
"text": "<?php \n class Session_controller extends CI_Controller {\n\t\n public function index() { \n //loading session library \n $this->load->library('session');\n\t\t\t\n //adding data to session \n $this->session->set_userdata('name','virat');\n\t\t\t\n $this->load->view('session_view'); \n } \n\t\t\n public function unset_session_data() { \n //loading session library\n $this->load->library('session');\n\t\t\t\n //removing session data \n $this->session->unset_userdata('name'); \n $this->load->view('session_view'); \n } \n\t\t\n } \n?>"
},
{
"code": null,
"e": 69420,
"s": 69327,
"text": "Create a view file called session_view.php and save it in application/views/session_view.php"
},
{
"code": null,
"e": 69819,
"s": 69420,
"text": "<!DOCTYPE html> \n<html lang = \"en\">\n \n <head> \n <meta charset = \"utf-8\"> \n <title>CodeIgniter Session Example</title> \n </head>\n\t\n <body> \n Welcome <?php echo $this->session->userdata('name'); ?> \n <br> \n <a href = 'http://localhost:85/CodeIgniter-3.0.1/CodeIgniter3.0.1/index.php/sessionex/unset'>\n Click Here</a> to unset session data. \n </body>\n\t\n</html>"
},
{
"code": null,
"e": 69943,
"s": 69819,
"text": "Make the changes in the routes.php file in application/config/routes.php and add the following line at the end of the file."
},
{
"code": null,
"e": 69988,
"s": 69943,
"text": "$route['sessionex'] = 'Session_Controller';\n"
},
{
"code": null,
"e": 70094,
"s": 69988,
"text": "Execute the above example by using the following address. Replace yoursite.com with the URL of your site."
},
{
"code": null,
"e": 70477,
"s": 70094,
"text": "While building web application, we need to store some data for only one time and after that we want to remove that data. For example, to display some error message or information message. In PHP, we have to do it manually but CodeIgniter has made this job simple for us. In CodeIgniter, flashdata will only be available until the next request, and it will get deleted automatically."
},
{
"code": null,
"e": 70523,
"s": 70477,
"text": "We can simply store flashdata as shown below."
},
{
"code": null,
"e": 70563,
"s": 70523,
"text": "$this->session->mark_as_flash('item');\n"
},
{
"code": null,
"e": 70723,
"s": 70563,
"text": "mark_as_flash() function is used for this purpose, which takes only one argument of the value to be stored. We can also pass an array to store multiple values."
},
{
"code": null,
"e": 70883,
"s": 70723,
"text": "mark_as_flash() function is used for this purpose, which takes only one argument of the value to be stored. We can also pass an array to store multiple values."
},
{
"code": null,
"e": 71012,
"s": 70883,
"text": "set_flashdata() function can also be used, which takes two arguments, name and value, as shown below. We can also pass an array."
},
{
"code": null,
"e": 71141,
"s": 71012,
"text": "set_flashdata() function can also be used, which takes two arguments, name and value, as shown below. We can also pass an array."
},
{
"code": null,
"e": 71189,
"s": 71141,
"text": "$this->session->set_flashdata('item','value');\n"
},
{
"code": null,
"e": 71407,
"s": 71189,
"text": "Flashdata can be retrieved using the flashdata() function which takes one argument of the item to be fetched as shown below. flashdata() function makes sure that you are getting only flash data and not any other data."
},
{
"code": null,
"e": 71443,
"s": 71407,
"text": "$this->session->flashdata('item');\n"
},
{
"code": null,
"e": 71526,
"s": 71443,
"text": "If you do not pass any argument, then you can get an array with the same function."
},
{
"code": null,
"e": 71637,
"s": 71526,
"text": "Create a class called FlashData_Controller.php and save it at application/controller/FlashData_Controller.php."
},
{
"code": null,
"e": 72232,
"s": 71637,
"text": "<?php \n class FlashData_Controller extends CI_Controller {\n\t\n public function index() { \n //Load session library \n $this->load->library('session');\n\t\t\t\n //redirect to home page \n $this->load->view('flashdata_home'); \n } \n \n public function add() { \n //Load session library \n $this->load->library('session'); \n $this->load->helper('url'); \n \n //add flash data \n $this->session->set_flashdata('item','item-value'); \n \n //redirect to home page \n redirect('flashdata'); \n } \n } \n?>"
},
{
"code": null,
"e": 72330,
"s": 72232,
"text": "Create a view file called flashdata_home.php and save it in application/views/ flashdata_home.php"
},
{
"code": null,
"e": 72666,
"s": 72330,
"text": "<!DOCTYPE html> \n<html lang = \"en\">\n \n <head> \n <meta charset = \"utf-8\"> \n <title>CodeIgniter Flashdata Example</title> \n </head>\n\t\n <body> \n Flash Data Example \n <h2><?php echo $this->session->flashdata('item'); ?></h2> \n <a href = 'flashdata/add'>Click Here</a> to add flash data. \n </body>\n\t\n</html>"
},
{
"code": null,
"e": 72790,
"s": 72666,
"text": "Make the changes in the routes.php file in application/config/routes.php and add the following line at the end of the file."
},
{
"code": null,
"e": 72891,
"s": 72790,
"text": "$route['flashdata'] = 'FlashData_Controller'; \n$route['flashdata/add'] = 'FlashData_Controller/add';"
},
{
"code": null,
"e": 73001,
"s": 72891,
"text": "Execute the above example by visiting the following link. Replace the yoursite.com with the URL of your site."
},
{
"code": null,
"e": 73042,
"s": 73001,
"text": "http://yoursite.com/index.php/flashdata\n"
},
{
"code": null,
"e": 73110,
"s": 73042,
"text": "After visiting the above URL, you will see a screen as shown below."
},
{
"code": null,
"e": 73360,
"s": 73110,
"text": "Click on “Click Here” link and you will see a screen as shown below. Here, in this screen you will see a value of flash data variable. Refresh the page again and you will see a screen like above and flash data variable will be removed automatically."
},
{
"code": null,
"e": 73523,
"s": 73360,
"text": "In some situations, where you want to remove data stored in session after some specific time-period, this can be done using tempdata functionality in CodeIgniter."
},
{
"code": null,
"e": 73725,
"s": 73523,
"text": "To add data as tempdata, we have to use mark_as_tempdata() function. This function takes two argument items or items to be stored as tempdata and the expiration time for those items are as shown below."
},
{
"code": null,
"e": 73823,
"s": 73725,
"text": "// 'item' will be erased after 300 seconds(5 minutes) \n$this->session->mark_as_temp('item',300);\n"
},
{
"code": null,
"e": 73936,
"s": 73823,
"text": "You can also pass an array to store multiple data. All the items stored below will be expired after 300 seconds."
},
{
"code": null,
"e": 73994,
"s": 73936,
"text": "$this->session->mark_as_temp(array('item','item2'),300);\n"
},
{
"code": null,
"e": 74067,
"s": 73994,
"text": "You can also set different expiration time for each item as shown below."
},
{
"code": null,
"e": 74240,
"s": 74067,
"text": "// 'item' will be erased after 300 seconds, while 'item2' \n// will do so after only 240 seconds \n\n$this->session->mark_as_temp(array( \n 'item'=>300, \n 'item2'=>240 \n));"
},
{
"code": null,
"e": 74512,
"s": 74240,
"text": "We can retrieve the tempdata using tempdata() function. This function assures that you are getting only tempdata and not any other data. Look at the example given below to see how to retrieve tempdata. tempdata() function will take one argument of the item to be fetched."
},
{
"code": null,
"e": 74547,
"s": 74512,
"text": "$this->session->tempdata('item');\n"
},
{
"code": null,
"e": 74622,
"s": 74547,
"text": "If you omit the argument, then you can retrieve all the existing tempdata."
},
{
"code": null,
"e": 74850,
"s": 74622,
"text": "Tempdata is removed automatically after its expiration time but if you want to remove tempdata before that, then you can do as shown below using the unset_tempdata() function, which takes one argument of the item to be removed."
},
{
"code": null,
"e": 74891,
"s": 74850,
"text": "$this->session->unset_tempdata('item');\n"
},
{
"code": null,
"e": 75000,
"s": 74891,
"text": "Create a class called Tempdata_controller.php and save it in application/controller/Tempdata_controller.php."
},
{
"code": null,
"e": 75482,
"s": 75000,
"text": "<?php \n class Tempdata_controller extends CI_Controller {\n\t\n public function index() { \n $this->load->library('session'); \n $this->load->view('tempdata_view'); \n } \n \n public function add() { \n $this->load->library('session'); \n $this->load->helper('url'); \n \n //tempdata will be removed after 5 seconds \n $this->session->set_tempdata('item','item-value',5); \n \n redirect('tempdata'); \n } \n } \n?>"
},
{
"code": null,
"e": 75572,
"s": 75482,
"text": "Create a file called tempdata_view.php and save it in application/views/tempdata_view.php"
},
{
"code": null,
"e": 75902,
"s": 75572,
"text": "<!DOCTYPE html> \n<html lang = \"en\">\n \n <head> \n <meta charset = \"utf-8\"> \n <title>CodeIgniter Tempdata Example</title> \n </head>\n\t\n <body> \n Temp Data Example \n <h2><?php echo $this->session->tempdata('item'); ?></h2>\n <a href = 'tempdata/add'>Click Here</a> to add temp data. \n </body>\n\t\n</html>"
},
{
"code": null,
"e": 76026,
"s": 75902,
"text": "Make the changes in the routes.php file in application/config/routes.php and add the following line at the end of the file."
},
{
"code": null,
"e": 76123,
"s": 76026,
"text": "$route['tempdata'] = \"Tempdata_controller\"; \n$route['tempdata/add'] = \"Tempdata_controller/add\";"
},
{
"code": null,
"e": 76233,
"s": 76123,
"text": "Execute the above example by visiting the following link. Replace the yoursite.com with the URL of your site."
},
{
"code": null,
"e": 76273,
"s": 76233,
"text": "http://yoursite.com/index.php/tempdata\n"
},
{
"code": null,
"e": 76341,
"s": 76273,
"text": "After visiting the above URL, you will see a screen as shown below."
},
{
"code": null,
"e": 76410,
"s": 76341,
"text": "Click on “Click Here” link and you will see a screen as shown below."
},
{
"code": null,
"e": 76797,
"s": 76410,
"text": "Here, in this screen you will see a value of temp data variable. Refresh the same page after five seconds again as we have set the temp data for five seconds and you will see a screen like above and temp data variable will be removed automatically after five seconds. If you refresh the same page before 5 seconds, then the temp data will not be removed, as the time period is not over."
},
{
"code": null,
"e": 76935,
"s": 76797,
"text": "In PHP, we are using the session_destroy() function to destroy the session and in CodeIgniter we can destroy the function as shown below."
},
{
"code": null,
"e": 76968,
"s": 76935,
"text": "$this->session->sess_destroy();\n"
},
{
"code": null,
"e": 77113,
"s": 76968,
"text": "After calling this function, all the session data including the flashdata and tempdata will be deleted permanently and cannot be retrieved back."
},
{
"code": null,
"e": 77270,
"s": 77113,
"text": "Cookie is a small piece of data sent from web server to store on client’s computer. CodeIgniter has one helper called “Cookie Helper” for cookie management."
},
{
"code": null,
"e": 77277,
"s": 77270,
"text": "Syntax"
},
{
"code": null,
"e": 77288,
"s": 77277,
"text": "Parameters"
},
{
"code": null,
"e": 77389,
"s": 77288,
"text": "$name (mixed) − Cookie name or associative array of all of the parameters available to this function"
},
{
"code": null,
"e": 77490,
"s": 77389,
"text": "$name (mixed) − Cookie name or associative array of all of the parameters available to this function"
},
{
"code": null,
"e": 77521,
"s": 77490,
"text": "$value (string) − Cookie value"
},
{
"code": null,
"e": 77552,
"s": 77521,
"text": "$value (string) − Cookie value"
},
{
"code": null,
"e": 77603,
"s": 77552,
"text": "$expire (int) − Number of seconds until expiration"
},
{
"code": null,
"e": 77654,
"s": 77603,
"text": "$expire (int) − Number of seconds until expiration"
},
{
"code": null,
"e": 77714,
"s": 77654,
"text": "$domain (string) − Cookie domain (usually: .yourdomain.com)"
},
{
"code": null,
"e": 77774,
"s": 77714,
"text": "$domain (string) − Cookie domain (usually: .yourdomain.com)"
},
{
"code": null,
"e": 77803,
"s": 77774,
"text": "$path (string) − Cookie path"
},
{
"code": null,
"e": 77832,
"s": 77803,
"text": "$path (string) − Cookie path"
},
{
"code": null,
"e": 77870,
"s": 77832,
"text": "$prefix (string) − Cookie name prefix"
},
{
"code": null,
"e": 77908,
"s": 77870,
"text": "$prefix (string) − Cookie name prefix"
},
{
"code": null,
"e": 77971,
"s": 77908,
"text": "$secure (bool) − Whether to only send the cookie through HTTPS"
},
{
"code": null,
"e": 78034,
"s": 77971,
"text": "$secure (bool) − Whether to only send the cookie through HTTPS"
},
{
"code": null,
"e": 78096,
"s": 78034,
"text": "$httponly (bool) − Whether to hide the cookie from JavaScript"
},
{
"code": null,
"e": 78158,
"s": 78096,
"text": "$httponly (bool) − Whether to hide the cookie from JavaScript"
},
{
"code": null,
"e": 78170,
"s": 78158,
"text": "Return Type"
},
{
"code": null,
"e": 78351,
"s": 78170,
"text": "In the set_cookie() function, we can pass all the values using two ways. In the first way, only array can be passed and in the second way, individual parameters can also be passed."
},
{
"code": null,
"e": 78358,
"s": 78351,
"text": "Syntax"
},
{
"code": null,
"e": 78369,
"s": 78358,
"text": "Parameters"
},
{
"code": null,
"e": 78399,
"s": 78369,
"text": "$index (string) − Cookie name"
},
{
"code": null,
"e": 78429,
"s": 78399,
"text": "$index (string) − Cookie name"
},
{
"code": null,
"e": 78502,
"s": 78429,
"text": "$xss_clean (bool) − Whether to apply XSS filtering to the returned value"
},
{
"code": null,
"e": 78575,
"s": 78502,
"text": "$xss_clean (bool) − Whether to apply XSS filtering to the returned value"
},
{
"code": null,
"e": 78582,
"s": 78575,
"text": "Return"
},
{
"code": null,
"e": 78594,
"s": 78582,
"text": "Return Type"
},
{
"code": null,
"e": 78697,
"s": 78594,
"text": "The get_cookie() function is used to get the cookie that has been set using the set_cookie() function."
},
{
"code": null,
"e": 78704,
"s": 78697,
"text": "Syntax"
},
{
"code": null,
"e": 78715,
"s": 78704,
"text": "Parameters"
},
{
"code": null,
"e": 78744,
"s": 78715,
"text": "$name (string) − Cookie name"
},
{
"code": null,
"e": 78773,
"s": 78744,
"text": "$name (string) − Cookie name"
},
{
"code": null,
"e": 78833,
"s": 78773,
"text": "$domain (string) − Cookie domain (usually: .yourdomain.com)"
},
{
"code": null,
"e": 78893,
"s": 78833,
"text": "$domain (string) − Cookie domain (usually: .yourdomain.com)"
},
{
"code": null,
"e": 78922,
"s": 78893,
"text": "$path (string) − Cookie path"
},
{
"code": null,
"e": 78951,
"s": 78922,
"text": "$path (string) − Cookie path"
},
{
"code": null,
"e": 78989,
"s": 78951,
"text": "$prefix (string) − Cookie name prefix"
},
{
"code": null,
"e": 79027,
"s": 78989,
"text": "$prefix (string) − Cookie name prefix"
},
{
"code": null,
"e": 79039,
"s": 79027,
"text": "Return Type"
},
{
"code": null,
"e": 79100,
"s": 79039,
"text": "The delete_cookie() function is used to delete the cookie()."
},
{
"code": null,
"e": 79209,
"s": 79100,
"text": "Create a controller called Cookie_controller.php and save it at application/controller/Cookie_controller.php"
},
{
"code": null,
"e": 79828,
"s": 79209,
"text": "<?php \n class Cookie_controller extends CI_Controller { \n\t\n function __construct() { \n parent::__construct(); \n $this->load->helper(array('cookie', 'url')); \n } \n \n public function index() { \n set_cookie('cookie_name','cookie_value','3600'); \n $this->load->view('Cookie_view'); \n } \n \n public function display_cookie() { \n echo get_cookie('cookie_name'); \n $this->load->view('Cookie_view');\n } \n \n public function deletecookie() { \n delete_cookie('cookie_name'); \n redirect('cookie/display'); \n } \n\t\t\n } \n?>"
},
{
"code": null,
"e": 79919,
"s": 79828,
"text": "Create a view file called Cookie_view.php and save it at application/views/Cookie_view.php"
},
{
"code": null,
"e": 80222,
"s": 79919,
"text": "<!DOCTYPE html> \n<html lang = \"en\">\n \n <head> \n <meta charset = \"utf-8\"> \n <title>CodeIgniter View Example</title> \n </head> \n\t\n <body> \n <a href = 'display'>Click Here</a> to view the cookie.<br> \n <a href = 'delete'>Click Here</a> to delete the cookie. \n </body>\n\t\n</html>"
},
{
"code": null,
"e": 80371,
"s": 80222,
"text": "Change the routes.php file in application/config/routes.php to add route for the above controller and add the following line at the end of the file."
},
{
"code": null,
"e": 80536,
"s": 80371,
"text": "$route['cookie'] = \"Cookie_controller\"; \n$route['cookie/display'] = \"Cookie_controller/display_cookie\"; \n$route['cookie/delete'] = \"Cookie_controller/deletecookie\";"
},
{
"code": null,
"e": 80621,
"s": 80536,
"text": "After that, you can execute the following URL in the browser to execute the example."
},
{
"code": null,
"e": 80659,
"s": 80621,
"text": "http://yoursite.com/index.php/cookie\n"
},
{
"code": null,
"e": 80723,
"s": 80659,
"text": "It will produce an output as shown in the following screenshot."
},
{
"code": null,
"e": 80892,
"s": 80723,
"text": "CodeIgniter library functions and helper functions need to be initialized before they are used but there are some common functions, which do not need to be initialized."
},
{
"code": null,
"e": 80955,
"s": 80892,
"text": "These common functions and their descriptions are given below."
},
{
"code": null,
"e": 80990,
"s": 80955,
"text": "$version (string) − Version number"
},
{
"code": null,
"e": 81017,
"s": 80990,
"text": "$file (string) − File path"
},
{
"code": null,
"e": 81049,
"s": 81017,
"text": "$key (string) − Config item key"
},
{
"code": null,
"e": 81089,
"s": 81049,
"text": "$code (int) − HTTP Response status code"
},
{
"code": null,
"e": 81151,
"s": 81089,
"text": "$text (string) − A custom message to set with the status code"
},
{
"code": null,
"e": 81180,
"s": 81151,
"text": "$str (string) − Input string"
},
{
"code": null,
"e": 81250,
"s": 81180,
"text": "$url_encoded (bool) − Whether to remove URLencoded characters as well"
},
{
"code": null,
"e": 81302,
"s": 81250,
"text": "$var (mixed) − Variable to escape (string or array)"
},
{
"code": null,
"e": 81342,
"s": 81302,
"text": "$function_name (string) − Function name"
},
{
"code": null,
"e": 81416,
"s": 81342,
"text": "Given below is an example, which demonstrates all of the above functions."
},
{
"code": null,
"e": 81590,
"s": 81416,
"text": "Here we have created only one controller in which we will use the above functions. Copy the below given code and save it at application/controller/CommonFun_Controller.php."
},
{
"code": null,
"e": 82361,
"s": 81590,
"text": "<?php \n class CommonFun_Controller extends CI_Controller { \n\t\n public function index() {\n set_status_header(200); \n echo is_php('5.3').\"<br>\"; \n var_dump(is_really_writable('./Form.php')); \n\t\t\t\n echo config_item('language').\"<br>\"; \n echo remove_invisible_characters('This is a test','UTF8').\"<br>\"; \n\t\t\t\n $str = '< This > is \\' a \" test & string'; \n echo html_escape($str).\"<br>\"; \n echo \"is_https():\".var_dump(is_https()).\"<br>\"; \n echo \"is_cli():\".var_dump(is_cli()).\"<br>\"; \n\t\t\t\n var_dump(function_usable('test')).\"<br>\"; \n echo \"get_mimes():\".print_r(get_mimes()).\"<br>\"; \n } \n \n public function test() { \n echo \"Test function\"; \n } \n\t\t\n } \n?>"
},
{
"code": null,
"e": 82510,
"s": 82361,
"text": "Change the routes.php file at application/config/routes.php to add route for the above controller and add the following line at the end of the file."
},
{
"code": null,
"e": 82563,
"s": 82510,
"text": "$route['commonfunctions'] = 'CommonFun_Controller';\n"
},
{
"code": null,
"e": 82645,
"s": 82563,
"text": "Type the following URL in the address bar of your browser to execute the example."
},
{
"code": null,
"e": 82692,
"s": 82645,
"text": "http://yoursite.com/index.php/commonfunctions\n"
},
{
"code": null,
"e": 82930,
"s": 82692,
"text": "Caching a page will improve the page load speed. If the page is cached, then it will be stored in its fully rendered state. Next time, when the server gets a request for the cached page, it will be directly sent to the requested browser."
},
{
"code": null,
"e": 83181,
"s": 82930,
"text": "Cached files are stored in application/cache folder. Caching can be enabled on per page basis. While enabling the cache, we need to set the time, until which it needs to remain in cached folder and after that period, it will be deleted automatically."
},
{
"code": null,
"e": 83271,
"s": 83181,
"text": "Caching can be enabled by executing the following line in any of the controller’s method."
},
{
"code": null,
"e": 83298,
"s": 83271,
"text": "$this->output->cache($n);\n"
},
{
"code": null,
"e": 83387,
"s": 83298,
"text": "Where $n is the number of minutes, you wish the page to remain cached between refreshes."
},
{
"code": null,
"e": 83558,
"s": 83387,
"text": "Cache file gets deleted when it expires but when you want to delete it manually, then you have to disable it. You can disable the caching by executing the following line."
},
{
"code": null,
"e": 83714,
"s": 83558,
"text": "// Deletes cache for the currently requested URI \n$this->output->delete_cache();\n \n// Deletes cache for /foo/bar \n$this->output->delete_cache('/foo/bar');"
},
{
"code": null,
"e": 83821,
"s": 83714,
"text": "Create a controller called Cache_controller.php and save it in application/controller/Cache_controller.php"
},
{
"code": null,
"e": 84118,
"s": 83821,
"text": "<?php \n class Cache_controller extends CI_Controller { \n\t\n public function index() { \n $this->output->cache(1); \n $this->load->view('test'); \n }\n\t\t\n public function delete_file_cache() { \n $this->output->delete_cache('cachecontroller'); \n } \n } \n?>"
},
{
"code": null,
"e": 84196,
"s": 84118,
"text": "Create a view file called test.php and save it in application/views/test.php"
},
{
"code": null,
"e": 84401,
"s": 84196,
"text": "<!DOCTYPE html> \n<html lang = \"en\">\n \n <head> \n <meta charset = \"utf-8\"> \n <title>CodeIgniter View Example</title> \n </head>\n\t\n <body> \n CodeIgniter View Example \n </body>\n\t\n</html>"
},
{
"code": null,
"e": 84550,
"s": 84401,
"text": "Change the routes.php file in application/config/routes.php to add route for the above controller and add the following line at the end of the file."
},
{
"code": null,
"e": 84672,
"s": 84550,
"text": "$route['cachecontroller'] = 'Cache_controller'; \n$route['cachecontroller/delete'] = 'Cache_controller/delete_file_cache';"
},
{
"code": null,
"e": 84734,
"s": 84672,
"text": "Type the following URL in the browser to execute the example."
},
{
"code": null,
"e": 84781,
"s": 84734,
"text": "http://yoursite.com/index.php/cachecontroller\n"
},
{
"code": null,
"e": 84941,
"s": 84781,
"text": "After visiting the above URL, you will see that a cache file for this will be created in application/cache folder. To delete the file, visit the following URL."
},
{
"code": null,
"e": 84995,
"s": 84941,
"text": "http://yoursite.com/index.php/cachecontroller/delete\n"
},
{
"code": null,
"e": 85183,
"s": 84995,
"text": "While building web application, we often need to redirect the user from one page to another page. CodeIgniter makes this job easy for us. The redirect() function is used for this purpose."
},
{
"code": null,
"e": 85190,
"s": 85183,
"text": "Syntax"
},
{
"code": null,
"e": 85201,
"s": 85190,
"text": "Parameters"
},
{
"code": null,
"e": 85228,
"s": 85201,
"text": "$uri (string) − URI string"
},
{
"code": null,
"e": 85255,
"s": 85228,
"text": "$uri (string) − URI string"
},
{
"code": null,
"e": 85324,
"s": 85255,
"text": "$method (string) − Redirect method (‘auto’, ‘location’ or ‘refresh’)"
},
{
"code": null,
"e": 85393,
"s": 85324,
"text": "$method (string) − Redirect method (‘auto’, ‘location’ or ‘refresh’)"
},
{
"code": null,
"e": 85450,
"s": 85393,
"text": "$code (string) − HTTP Response code (usually 302 or 303)"
},
{
"code": null,
"e": 85507,
"s": 85450,
"text": "$code (string) − HTTP Response code (usually 302 or 303)"
},
{
"code": null,
"e": 85519,
"s": 85507,
"text": "Return type"
},
{
"code": null,
"e": 85645,
"s": 85519,
"text": "The first argument can have two types of URI. We can pass full site URL or URI segments to the controller you want to direct."
},
{
"code": null,
"e": 85761,
"s": 85645,
"text": "The second optional parameter can have any of the three values from auto, location or refresh. The default is auto."
},
{
"code": null,
"e": 85887,
"s": 85761,
"text": "The third optional parameter is only available with location redirects and it allows you to send specific HTTP response code."
},
{
"code": null,
"e": 86000,
"s": 85887,
"text": "Create a controller called Redirect_controller.php and save it in application/controller/Redirect_controller.php"
},
{
"code": null,
"e": 86743,
"s": 86000,
"text": "<?php \n class Redirect_controller extends CI_Controller { \n\t\n public function index() { \n /*Load the URL helper*/ \n $this->load->helper('url'); \n \n /*Redirect the user to some site*/ \n redirect('http://www.tutorialspoint.com'); \n }\n\t\t\n public function computer_graphics() { \n /*Load the URL helper*/ \n $this->load->helper('url'); \n redirect('http://www.tutorialspoint.com/computer_graphics/index.htm'); \n } \n \n public function version2() { \n /*Load the URL helper*/ \n $this->load->helper('url'); \n \n /*Redirect the user to some internal controller’s method*/ \n redirect('redirect/computer_graphics'); \n } \n\t\t\n } \n?>"
},
{
"code": null,
"e": 86892,
"s": 86743,
"text": "Change the routes.php file in application/config/routes.php to add route for the above controller and add the following line at the end of the file."
},
{
"code": null,
"e": 87080,
"s": 86892,
"text": "$route['redirect'] = 'Redirect_controller'; \n$route['redirect/version2'] = 'Redirect_controller/version2'; \n$route['redirect/computer_graphics'] = 'Redirect_controller/computer_graphics';"
},
{
"code": null,
"e": 87143,
"s": 87080,
"text": "Type the following URL in the browser, to execute the example."
},
{
"code": null,
"e": 87183,
"s": 87143,
"text": "http://yoursite.com/index.php/redirect\n"
},
{
"code": null,
"e": 87368,
"s": 87183,
"text": "The above URL will redirect you to the tutorialspoint.com website and if you visit the following URL, then it will redirect you to the computer graphics tutorial at tutorialspoint.com."
},
{
"code": null,
"e": 87426,
"s": 87368,
"text": "http://yoursite.com/index.php/redirect/computer_graphics\n"
},
{
"code": null,
"e": 87870,
"s": 87426,
"text": "When building a web application, we are very much concerned about the performance of the website in terms of how much time the controller took to execute and how much memory is used. Not only the performance, but we also need to see the insights of data like POST data, data of database queries, session data etc. for debugging purpose while developing some application. CodeIgniter has made this job easier for us by profiling an application."
},
{
"code": null,
"e": 87991,
"s": 87870,
"text": "To enable profiling of your application, simply execute the command given below in any of the method of your controller."
},
{
"code": null,
"e": 88030,
"s": 87991,
"text": "$this->output->enable_profiler(TRUE);\n"
},
{
"code": null,
"e": 88115,
"s": 88030,
"text": "The report of the profiling can be seen at the bottom of the page after enabling it."
},
{
"code": null,
"e": 88237,
"s": 88115,
"text": "To disable profiling of your application, simply execute the command given below in any of the method of your controller."
},
{
"code": null,
"e": 88277,
"s": 88237,
"text": "$this->output->enable_profiler(FALSE);\n"
},
{
"code": null,
"e": 88525,
"s": 88277,
"text": "Profiling can be done on section basis. You can enable or disable profiling of a section by setting a Boolean value TRUE or FALSE. If you want to set profiling on the application then you can do in a file located in application/config/profiler.php"
},
{
"code": null,
"e": 88617,
"s": 88525,
"text": "For example, the following command will enable profiling queries for the whole application."
},
{
"code": null,
"e": 88645,
"s": 88617,
"text": "$config['queries'] = TRUE;\n"
},
{
"code": null,
"e": 88775,
"s": 88645,
"text": "In the following table, the key is the parameter, which can be set in the config array to enable or disable a particular profile."
},
{
"code": null,
"e": 88786,
"s": 88775,
"text": "benchmarks"
},
{
"code": null,
"e": 88793,
"s": 88786,
"text": "config"
},
{
"code": null,
"e": 88809,
"s": 88793,
"text": "controller_info"
},
{
"code": null,
"e": 88813,
"s": 88809,
"text": "get"
},
{
"code": null,
"e": 88826,
"s": 88813,
"text": "http_headers"
},
{
"code": null,
"e": 88839,
"s": 88826,
"text": "memory_usage"
},
{
"code": null,
"e": 88844,
"s": 88839,
"text": "post"
},
{
"code": null,
"e": 88852,
"s": 88844,
"text": "queries"
},
{
"code": null,
"e": 88863,
"s": 88852,
"text": "uri_string"
},
{
"code": null,
"e": 88876,
"s": 88863,
"text": "session_data"
},
{
"code": null,
"e": 88895,
"s": 88876,
"text": "query_toggle_count"
},
{
"code": null,
"e": 89054,
"s": 88895,
"text": "The profiler set in the file in application/config/profiler.php can be overridden by using the set_profiler_sections() function in controllers as shown below."
},
{
"code": null,
"e": 89174,
"s": 89054,
"text": "$sections = array( \n 'config' => TRUE, \n 'queries' => TRUE \n); \n \n$this->output->set_profiler_sections($sections);"
},
{
"code": null,
"e": 89395,
"s": 89174,
"text": "If you want to measure the time taken to execute a set of lines or memory usage, you can calculate it by using Benchmarking points in CodeIgniter. There is a separate “Benchmarking” class for this purpose in CodeIgniter."
},
{
"code": null,
"e": 89733,
"s": 89395,
"text": "This class is loaded automatically; you do not have to load it. It can be used anywhere in your controller, view, and model classes. All you have to do is to mark a start point and end point and then execute the elapsed_time() function between these two marked points and you can get the time it took to execute that code as shown below."
},
{
"code": null,
"e": 89928,
"s": 89733,
"text": "<?php \n $this->benchmark->mark('code_start');\n \n // Some code happens here \n\n $this->benchmark->mark('code_end');\n \n echo $this->benchmark->elapsed_time('code_start', 'code_end'); \n?>"
},
{
"code": null,
"e": 90021,
"s": 89928,
"text": "To display the memory usage, use the function memory_usage() as shown in the following code."
},
{
"code": null,
"e": 90074,
"s": 90021,
"text": "<?php \n echo $this->benchmark->memory_usage(); \n?>"
},
{
"code": null,
"e": 90187,
"s": 90074,
"text": "Create a controller called Profiler_controller.php and save it in application/controller/Profiler_controller.php"
},
{
"code": null,
"e": 90581,
"s": 90187,
"text": "<?php \n class Profiler_controller extends CI_Controller {\n \n public function index() {\n\t\n //enable profiler\n $this->output->enable_profiler(TRUE); \n $this->load->view('test'); \n } \n \n public function disable() {\n\t\n //disable profiler \n $this->output->enable_profiler(FALSE); \n $this->load->view('test'); \n }\n\t\t\n } \n?> "
},
{
"code": null,
"e": 90658,
"s": 90581,
"text": "Create a view file called test.php and save it at application/views/test.php"
},
{
"code": null,
"e": 90863,
"s": 90658,
"text": "<!DOCTYPE html> \n<html lang = \"en\">\n \n <head> \n <meta charset = \"utf-8\"> \n <title>CodeIgniter View Example</title> \n </head>\n\t\n <body> \n CodeIgniter View Example \n </body>\n\t\n</html>"
},
{
"code": null,
"e": 91012,
"s": 90863,
"text": "Change the routes.php file at application/config/routes.php to add route for the above controller and add the following line at the end of the file."
},
{
"code": null,
"e": 91116,
"s": 91012,
"text": "$route['profiler'] = \"Profiler_controller\"; \n$route['profiler/disable'] = \"Profiler_controller/disable\""
},
{
"code": null,
"e": 91218,
"s": 91116,
"text": "After that, you can type the following URL in the address bar of your browser to execute the example."
},
{
"code": null,
"e": 91258,
"s": 91218,
"text": "http://yoursite.com/index.php/profiler\n"
},
{
"code": null,
"e": 91365,
"s": 91258,
"text": "The above URL will enable the profiler and it will produce an output as shown in the following screenshot."
},
{
"code": null,
"e": 91418,
"s": 91365,
"text": "To disable the profiling, execute the following URL."
},
{
"code": null,
"e": 91466,
"s": 91418,
"text": "http://yoursite.com/index.php/profiler/disable\n"
},
{
"code": null,
"e": 91700,
"s": 91466,
"text": "Adding JavaScript and CSS (Cascading Style Sheet) file in CodeIgniter is very simple. You have to create JS and CSS folder in root directory and copy all the .js files in JS folder and .css files in CSS folder as shown in the figure."
},
{
"code": null,
"e": 91895,
"s": 91700,
"text": "For example, let us assume, you have created one JavaScript file sample.js and one CSS file style.css. Now, to add these files into your views, load URL helper in your controller as shown below."
},
{
"code": null,
"e": 91924,
"s": 91895,
"text": "$this->load->helper('url');\n"
},
{
"code": null,
"e": 92088,
"s": 91924,
"text": "After loading the URL helper in controller, simply add the below given lines in the view file, to load the sample.js and style.css file in the view as shown below."
},
{
"code": null,
"e": 92278,
"s": 92088,
"text": "<link rel = \"stylesheet\" type = \"text/css\" \n href = \"<?php echo base_url(); ?>css/style.css\">\n\n<script type = 'text/javascript' src = \"<?php echo base_url(); \n ?>js/sample.js\"></script>"
},
{
"code": null,
"e": 92361,
"s": 92278,
"text": "Create a controller called Test.php and save it in application/controller/Test.php"
},
{
"code": null,
"e": 92534,
"s": 92361,
"text": "<?php \n class Test extends CI_Controller {\n\t\n public function index() { \n $this->load->helper('url'); \n $this->load->view('test'); \n } \n } \n?>"
},
{
"code": null,
"e": 92611,
"s": 92534,
"text": "Create a view file called test.php and save it at application/views/test.php"
},
{
"code": null,
"e": 93087,
"s": 92611,
"text": "<!DOCTYPE html> \n<html lang = \"en\">\n \n <head> \n <meta charset = \"utf-8\"> \n <title>CodeIgniter View Example</title> \n <link rel = \"stylesheet\" type = \"text/css\" \n href = \"<?php echo base_url(); ?>css/style.css\"> \n <script type = 'text/javascript' src = \"<?php echo base_url(); \n ?>js/sample.js\"></script> \n </head>\n\t\n <body> \n <a href = 'javascript:test()'>Click Here</a> to execute the javascript function. \n </body>\n\t\n</html>"
},
{
"code": null,
"e": 93151,
"s": 93087,
"text": "Create a CSS file called style.css and save it at css/style.css"
},
{
"code": null,
"e": 93198,
"s": 93151,
"text": "body { \n background:#000; \n color:#FFF; \n}"
},
{
"code": null,
"e": 93260,
"s": 93198,
"text": "Create a JS file called sample.js and save it at js/sample.js"
},
{
"code": null,
"e": 93300,
"s": 93260,
"text": "function test() { \n alert('test'); \n}"
},
{
"code": null,
"e": 93449,
"s": 93300,
"text": "Change the routes.php file in application/config/routes.php to add route for the above controller and add the following line at the end of the file."
},
{
"code": null,
"e": 93553,
"s": 93449,
"text": "$route['profiler'] = \"Profiler_controller\"; \n$route['profiler/disable'] = \"Profiler_controller/disable\""
},
{
"code": null,
"e": 93620,
"s": 93553,
"text": "Use the following URL in the browser to execute the above example."
},
{
"code": null,
"e": 93656,
"s": 93620,
"text": "http://yoursite.com/index.php/test\n"
},
{
"code": null,
"e": 93864,
"s": 93656,
"text": "The language class in CodeIgniter provides an easy way to support multiple languages for internationalization. To some extent, we can use different language files to display text in many different languages."
},
{
"code": null,
"e": 94139,
"s": 93864,
"text": "We can put different language files in application/language directory. System language files can be found at system/language directory, but to add your own language to your application, you should create a separate folder for each language in application/language directory."
},
{
"code": null,
"e": 94423,
"s": 94139,
"text": "To create a language file, you must end it with _lang.php. For example, you want to create a language file for French language, then you must save it with french_lang.php. Within this file you can store all your language texts in key, value combination in $lang array as shown below."
},
{
"code": null,
"e": 94446,
"s": 94423,
"text": "$lang[‘key’] = ‘val’;\n"
},
{
"code": null,
"e": 94656,
"s": 94446,
"text": "To use any of the language in your application, you must first load the file of that particular language to retrieve various texts stored in that file. You can use the following code to load the language file."
},
{
"code": null,
"e": 94700,
"s": 94656,
"text": "$this->lang->load('filename', 'language');\n"
},
{
"code": null,
"e": 94808,
"s": 94700,
"text": "filename − It is the name of file you want to load. Don’t use extension of file here but only name of file."
},
{
"code": null,
"e": 94916,
"s": 94808,
"text": "filename − It is the name of file you want to load. Don’t use extension of file here but only name of file."
},
{
"code": null,
"e": 94965,
"s": 94916,
"text": "Language − It is the language set containing it."
},
{
"code": null,
"e": 95014,
"s": 94965,
"text": "Language − It is the language set containing it."
},
{
"code": null,
"e": 95088,
"s": 95014,
"text": "To fetch a line from the language file simply execute the following code."
},
{
"code": null,
"e": 95124,
"s": 95088,
"text": "$this->lang->line('language_key');\n"
},
{
"code": null,
"e": 95224,
"s": 95124,
"text": "Where language_key is the key parameter used to fetch value of the key in the loaded language file."
},
{
"code": null,
"e": 95341,
"s": 95224,
"text": "If you need some language globally, then you can autoload it in application/config/autoload.php file as shown below."
},
{
"code": null,
"e": 95761,
"s": 95341,
"text": "| -----------------------------------------------------------------------\n| Auto-load Language files\n| -----------------------------------------------------------------------\n| Prototype:\n| $autoload['config'] = array('config1', 'config2');\n|\n| NOTE: Do not include the \"_lang\" part of your file. For example\n| \"codeigniter_lang.php\" would be referenced as array('codeigniter');\n|\n*/\n$autoload['language'] = array();"
},
{
"code": null,
"e": 95831,
"s": 95761,
"text": "Simply, pass the different languages to be autoloaded by CodeIgniter."
},
{
"code": null,
"e": 95936,
"s": 95831,
"text": "Create a controller called Lang_controller.php and save it in application/controller/Lang_controller.php"
},
{
"code": null,
"e": 96738,
"s": 95936,
"text": "<?php\n class Lang_controller extends CI_Controller {\n\n public function index(){\n //Load form helper\n $this->load->helper('form');\n\n //Get the selected language\n $language = $this->input->post('language');\n\t\t\n //Choose language file according to selected lanaguage\n if($language == \"french\")\n $this->lang->load('french_lang','french');\n else if($language == \"german\")\n $this->lang->load('german_lang','german');\n else\n $this->lang->load('english_lang','english');\n\t\t\n //Fetch the message from language file.\n $data['msg'] = $this->lang->line('msg');\n\t\t\n $data['language'] = $language;\n //Load the view file\n $this->load->view('lang_view',$data);\n }\n }\n?>"
},
{
"code": null,
"e": 96826,
"s": 96738,
"text": "Create a view file called lang_view.php and save it at application/views/ lang_view.php"
},
{
"code": null,
"e": 97632,
"s": 96826,
"text": "<!DOCTYPE html>\n<html lang = \"en\"> \n\n <head>\n <meta charset = \"utf-8\">\n <title>CodeIgniter Internationalization Example</title>\n </head>\n\t\n <body>\n <?php\n echo form_open('/lang');\n ?>\n\t\t\n <select name = \"language\" onchange = \"javascript:this.form.submit();\">\n <?php\n $lang = array('english'=>\"English\",'french'=>\"French\",'german'=>\"German\");\n\t\t\t\t\n foreach($lang as $key=>$val) {\n if($key == $language)\n echo \"<option value = '\".$key.\"' selected>\".$val.\"</option>\";\n else\n echo \"<option value = '\".$key.\"'>\".$val.\"</option>\";\n }\n\t\t\t\t\n ?>\n\t\t\t\n </select>\n\t\t\n <br>\n\t\t\n <?php\n form_close();\n echo $msg;\n ?>\n\t\t\n </body>\n\t\n</html>"
},
{
"code": null,
"e": 97742,
"s": 97632,
"text": "Create three folders called English, French, and German in application/language as shown in the figure below."
},
{
"code": null,
"e": 97845,
"s": 97742,
"text": "Copy the below given code and save it in english_lang.php file in application/language/english folder."
},
{
"code": null,
"e": 97917,
"s": 97845,
"text": "<?php\n $lang['msg'] = \"CodeIgniter Internationalization example.\";\n?>"
},
{
"code": null,
"e": 98018,
"s": 97917,
"text": "Copy the below given code and save it in french_lang.php file in application/language/French folder."
},
{
"code": null,
"e": 98090,
"s": 98018,
"text": "<?php\n $lang['msg'] = \"Exemple CodeIgniter internationalisation.\";\n?>"
},
{
"code": null,
"e": 98191,
"s": 98090,
"text": "Copy the below given code and save it in german_lang.php file in application/language/german folder."
},
{
"code": null,
"e": 98265,
"s": 98191,
"text": "<?php\n $lang['msg'] = \"CodeIgniter Internationalisierung Beispiel.\";\n?>"
},
{
"code": null,
"e": 98414,
"s": 98265,
"text": "Change the routes.php file in application/config/routes.php to add route for the above controller and add the following line at the end of the file."
},
{
"code": null,
"e": 98451,
"s": 98414,
"text": "$route['lang'] = \"Lang_controller\";\n"
},
{
"code": null,
"e": 98522,
"s": 98451,
"text": "Execute the following URL in the browser to execute the above example."
},
{
"code": null,
"e": 98558,
"s": 98522,
"text": "http://yoursite.com/index.php/lang\n"
},
{
"code": null,
"e": 98757,
"s": 98558,
"text": "It will produce an output as shown in the following screenshot. If you change the language in the dropdown list, the language of the sentence written below the dropdown will also change accordingly."
},
{
"code": null,
"e": 99051,
"s": 98757,
"text": "XSS means cross-site scripting. CodeIgniter comes with XSS filtering security. This filter will prevent any malicious JavaScript code or any other code that attempts to hijack cookie and do malicious activities. To filter data through the XSS filter, use the xss_clean() method as shown below."
},
{
"code": null,
"e": 99095,
"s": 99051,
"text": "$data = $this->security->xss_clean($data);\n"
},
{
"code": null,
"e": 99352,
"s": 99095,
"text": "You should use this function only when you are submitting data. The optional second Boolean parameter can also be used to check image file for XSS attack. This is useful for file upload facility. If its value is true, means image is safe and not otherwise."
},
{
"code": null,
"e": 99576,
"s": 99352,
"text": "SQL injection is an attack made on database query. In PHP, we are use mysql_real_escape_string() function to prevent this along with other techniques but CodeIgniter provides inbuilt functions and libraries to prevent this."
},
{
"code": null,
"e": 99650,
"s": 99576,
"text": "We can prevent SQL Injection in CodeIgniter in the following three ways −"
},
{
"code": null,
"e": 99667,
"s": 99650,
"text": "Escaping Queries"
},
{
"code": null,
"e": 99680,
"s": 99667,
"text": "Query Biding"
},
{
"code": null,
"e": 99700,
"s": 99680,
"text": "Active Record Class"
},
{
"code": null,
"e": 99882,
"s": 99700,
"text": "<?php\n $username = $this->input->post('username');\n $query = 'SELECT * FROM subscribers_tbl WHERE user_name = '.\n $this->db->escape($email);\n $this->db->query($query);\n?>"
},
{
"code": null,
"e": 100029,
"s": 99882,
"text": "$this->db->escape() function automatically adds single quotes around the data and determines the data type so that it can escape only string data."
},
{
"code": null,
"e": 100172,
"s": 100029,
"text": "<?php\n $sql = \"SELECT * FROM some_table WHERE id = ? AND status = ? AND author = ?\";\n $this->db->query($sql, array(3, 'live', 'Rick'));\n?>"
},
{
"code": null,
"e": 100494,
"s": 100172,
"text": "In the above example, the question mark(?) will be replaced by the array in the second parameter of query() function. The main advantage of building query this way is that the values are automatically escaped which produce safe queries. CodeIgniter engine does it for you automatically, so you do not have to remember it."
},
{
"code": null,
"e": 100611,
"s": 100494,
"text": "<?php\n $this->db->get_where('subscribers_tbl',array\n ('status'=> active','email' => '[email protected]'));\n?>"
},
{
"code": null,
"e": 100754,
"s": 100611,
"text": "Using active records, query syntax is generated by each database adapter. It also allows safer queries, since the values escape automatically."
},
{
"code": null,
"e": 101044,
"s": 100754,
"text": "In production environment, we often do not want to display any error message to the users. It is good if it is enabled in the development environment for debugging purposes. These error messages may contain some information, which we should not show to the site users for security reasons."
},
{
"code": null,
"e": 101099,
"s": 101044,
"text": "There are three CodeIgniter files related with errors."
},
{
"code": null,
"e": 101438,
"s": 101099,
"text": "Different environment requires different levels of error reporting. By default, development will show errors but testing and live will hide them. There is a file called index.php in root directory of CodeIgniter, which is used for this purpose. If we pass zero as argument to error_reporting() function then that will hide all the errors."
},
{
"code": null,
"e": 101631,
"s": 101438,
"text": "Even if you have turned off the PHP errors, MySQL errors are still open. You can turn this off in application/config/database.php. Set the db_debug option in $db array to FALSE as shown below."
},
{
"code": null,
"e": 101668,
"s": 101631,
"text": "$db['default']['db_debug'] = FALSE;\n"
},
{
"code": null,
"e": 101882,
"s": 101668,
"text": "Another way is to transfer the errors to log files. So, it will not be displayed to users on the site. Simply, set the log_threshold value in $config array to 1 in application/cofig/config.php file as shown below."
},
{
"code": null,
"e": 101913,
"s": 101882,
"text": "$config['log_threshold'] = 1;\n"
},
{
"code": null,
"e": 102058,
"s": 101913,
"text": "CSRF stands for cross-site request forgery. You can prevent this attack by enabling it in the application/config/config.php file as shown below."
},
{
"code": null,
"e": 102094,
"s": 102058,
"text": "$config['csrf_protection'] = TRUE;\n"
},
{
"code": null,
"e": 102423,
"s": 102094,
"text": "When you are creating form using form_open() function, it will automatically insert a CSRF as hidden field. You can also manually add the CSRF using the get_csrf_token_name() and get_csrf_hash() function. The get_csrf_token_name() function will return the name of the CSRF and get_csrf_hash() will return the hash value of CSRF."
},
{
"code": null,
"e": 102656,
"s": 102423,
"text": "The CSRF token can be regenerated every time for submission or you can also keep it same throughout the life of CSRF cookie. By setting the value TRUE, in config array with key ‘csrf_regenerate’ will regenerate token as shown below."
},
{
"code": null,
"e": 102692,
"s": 102656,
"text": "$config['csrf_regenerate'] = TRUE;\n"
},
{
"code": null,
"e": 102862,
"s": 102692,
"text": "You can also whitelist URLs from CSRF protection by setting it in the config array using the key ‘csrf_exclude_uris’ as shown below. You can also use regular expression."
},
{
"code": null,
"e": 102919,
"s": 102862,
"text": "$config['csrf_exclude_uris'] = array('api/person/add');\n"
},
{
"code": null,
"e": 103145,
"s": 102919,
"text": "Many developers do not know how to handle password in web applications, which is probably why numerous hackers find it so easy to break into the systems. One should keep in mind the following points while handling passwords −"
},
{
"code": null,
"e": 103190,
"s": 103145,
"text": "DO NOT store passwords in plain-text format."
},
{
"code": null,
"e": 103235,
"s": 103190,
"text": "DO NOT store passwords in plain-text format."
},
{
"code": null,
"e": 103263,
"s": 103235,
"text": "Always hash your passwords."
},
{
"code": null,
"e": 103291,
"s": 103263,
"text": "Always hash your passwords."
},
{
"code": null,
"e": 103352,
"s": 103291,
"text": "DO NOT use Base64 or similar encoding for storing passwords."
},
{
"code": null,
"e": 103413,
"s": 103352,
"text": "DO NOT use Base64 or similar encoding for storing passwords."
},
{
"code": null,
"e": 103588,
"s": 103413,
"text": "DO NOT use weak or broken hashing algorithms like MD5 or SHA1. Only use strong password hashing algorithms like BCrypt, which is used in PHP’s own Password Hashing functions."
},
{
"code": null,
"e": 103763,
"s": 103588,
"text": "DO NOT use weak or broken hashing algorithms like MD5 or SHA1. Only use strong password hashing algorithms like BCrypt, which is used in PHP’s own Password Hashing functions."
},
{
"code": null,
"e": 103824,
"s": 103763,
"text": "DO NOT ever display or send a password in plain-text format."
},
{
"code": null,
"e": 103885,
"s": 103824,
"text": "DO NOT ever display or send a password in plain-text format."
},
{
"code": null,
"e": 103941,
"s": 103885,
"text": "DO NOT put unnecessary limits on your users’ passwords."
},
{
"code": null,
"e": 103997,
"s": 103941,
"text": "DO NOT put unnecessary limits on your users’ passwords."
},
{
"code": null,
"e": 104004,
"s": 103997,
"text": " Print"
},
{
"code": null,
"e": 104015,
"s": 104004,
"text": " Add Notes"
}
] |
Shuffling Rows in Pandas DataFrames | by Giorgos Myrianthous | Towards Data Science | Data shuffling is a common task usually performed prior to model training in order to create more representative training and testing sets. For instance, consider that your original dataset is sorted based on a specific column.
If you split the data then the resulting sets won’t represent the true distribution of the dataset. Therefore, we have to shuffle the original dataset in order to minimise variance and ensure that the model will generalise well to new, unseen data points.
In today’s short guide we will discuss how to shuffle the rows of pandas DataFrames in various ways. Specifically, we will explore how to do so using
the sample() method in pandas
the shuffle() method in scikit-learn
the random.permutation() methods in numpy
First, let’s create an example pandas DataFrame that we’ll reference throughout this article in order to demonstrate how to shuffle the rows in many different ways.
import pandas as pddf = pd.DataFrame({ 'colA': [10, 20, 30, 40, 50, 60], 'colB': ['a', 'b', 'c', 'd', 'e', 'f'], 'colC': [True, False, False, True, False, True], 'colD': [0.5, 1.2, 2.4, 3.3, 5.5, 8.9],})print(df) colA colB colC colD0 10 a True 0.51 20 b False 1.22 30 c False 2.43 40 d True 3.34 50 e False 5.55 60 f True 8.9
The first option you have for shuffling pandas DataFrames is the panads.DataFrame.sample method that returns a random sample of items. In this method you can specify either the exact number or the fraction of records that you wish to sample. Since we want to shuffle the whole DataFrame, we are going to use frac=1 so that all records are returned.
df = df.sample(frac=1)print(df) colA colB colC colD4 50 e False 5.50 10 a True 0.52 30 c False 2.41 20 b False 1.25 60 f True 8.93 40 d True 3.3
If you want the shuffling to be reproducible, then also make sure to specify a valid value for the random_state argument. Additionally, you may sometimes want to reset the index of the returned DataFrame. In this case, the following should do the trick:
df = df.sample(frac=1).reset_index(drop=True)
Another function you can use in order to shuffle a DataFrame is sklearn.utils.shuffle() as shown below:
from sklearn.utils import shuffledf = shuffle(df)print(df) colA colB colC colD4 50 e False 5.55 60 f True 8.91 20 b False 1.22 30 c False 2.40 10 a True 0.53 40 d True 3.3
Again, make sure to configure random_state argument should you wish the results to be reproducible.
The other option we have is the numpy.random.permutation method that will randomly permute a sequence.
import numpy as npdf = df.iloc[np.random.permutation(len(df))]print(df) colA colB colC colD3 40 d True 3.30 10 a True 0.55 60 f True 8.91 20 b False 1.22 30 c False 2.44 50 e False 5.5
Once again, if you want the results to be reproducible you will have to set the random seed of numpy. For instance,
np.random.seed(100)
In today’s short guide we discussed the importance of data shuffling in the context of Machine Learning model. Additionally, we explored how to shuffle pandas DataFrames using sample() method, shuffle() method in sklearn and random.permutations() method in numpy.
If you want to learn more about how to split the data into training, testing and validation sets once the original dataset has been shuffled then make sure to read the article below.
towardsdatascience.com
Become a member and read every story on Medium. Your membership fee directly supports me and other writers you read.
You may also like | [
{
"code": null,
"e": 400,
"s": 172,
"text": "Data shuffling is a common task usually performed prior to model training in order to create more representative training and testing sets. For instance, consider that your original dataset is sorted based on a specific column."
},
{
"code": null,
"e": 656,
"s": 400,
"text": "If you split the data then the resulting sets won’t represent the true distribution of the dataset. Therefore, we have to shuffle the original dataset in order to minimise variance and ensure that the model will generalise well to new, unseen data points."
},
{
"code": null,
"e": 806,
"s": 656,
"text": "In today’s short guide we will discuss how to shuffle the rows of pandas DataFrames in various ways. Specifically, we will explore how to do so using"
},
{
"code": null,
"e": 836,
"s": 806,
"text": "the sample() method in pandas"
},
{
"code": null,
"e": 873,
"s": 836,
"text": "the shuffle() method in scikit-learn"
},
{
"code": null,
"e": 915,
"s": 873,
"text": "the random.permutation() methods in numpy"
},
{
"code": null,
"e": 1080,
"s": 915,
"text": "First, let’s create an example pandas DataFrame that we’ll reference throughout this article in order to demonstrate how to shuffle the rows in many different ways."
},
{
"code": null,
"e": 1480,
"s": 1080,
"text": "import pandas as pddf = pd.DataFrame({ 'colA': [10, 20, 30, 40, 50, 60], 'colB': ['a', 'b', 'c', 'd', 'e', 'f'], 'colC': [True, False, False, True, False, True], 'colD': [0.5, 1.2, 2.4, 3.3, 5.5, 8.9],})print(df) colA colB colC colD0 10 a True 0.51 20 b False 1.22 30 c False 2.43 40 d True 3.34 50 e False 5.55 60 f True 8.9"
},
{
"code": null,
"e": 1829,
"s": 1480,
"text": "The first option you have for shuffling pandas DataFrames is the panads.DataFrame.sample method that returns a random sample of items. In this method you can specify either the exact number or the fraction of records that you wish to sample. Since we want to shuffle the whole DataFrame, we are going to use frac=1 so that all records are returned."
},
{
"code": null,
"e": 2036,
"s": 1829,
"text": "df = df.sample(frac=1)print(df) colA colB colC colD4 50 e False 5.50 10 a True 0.52 30 c False 2.41 20 b False 1.25 60 f True 8.93 40 d True 3.3"
},
{
"code": null,
"e": 2290,
"s": 2036,
"text": "If you want the shuffling to be reproducible, then also make sure to specify a valid value for the random_state argument. Additionally, you may sometimes want to reset the index of the returned DataFrame. In this case, the following should do the trick:"
},
{
"code": null,
"e": 2336,
"s": 2290,
"text": "df = df.sample(frac=1).reset_index(drop=True)"
},
{
"code": null,
"e": 2440,
"s": 2336,
"text": "Another function you can use in order to shuffle a DataFrame is sklearn.utils.shuffle() as shown below:"
},
{
"code": null,
"e": 2674,
"s": 2440,
"text": "from sklearn.utils import shuffledf = shuffle(df)print(df) colA colB colC colD4 50 e False 5.55 60 f True 8.91 20 b False 1.22 30 c False 2.40 10 a True 0.53 40 d True 3.3"
},
{
"code": null,
"e": 2774,
"s": 2674,
"text": "Again, make sure to configure random_state argument should you wish the results to be reproducible."
},
{
"code": null,
"e": 2877,
"s": 2774,
"text": "The other option we have is the numpy.random.permutation method that will randomly permute a sequence."
},
{
"code": null,
"e": 3124,
"s": 2877,
"text": "import numpy as npdf = df.iloc[np.random.permutation(len(df))]print(df) colA colB colC colD3 40 d True 3.30 10 a True 0.55 60 f True 8.91 20 b False 1.22 30 c False 2.44 50 e False 5.5"
},
{
"code": null,
"e": 3240,
"s": 3124,
"text": "Once again, if you want the results to be reproducible you will have to set the random seed of numpy. For instance,"
},
{
"code": null,
"e": 3260,
"s": 3240,
"text": "np.random.seed(100)"
},
{
"code": null,
"e": 3524,
"s": 3260,
"text": "In today’s short guide we discussed the importance of data shuffling in the context of Machine Learning model. Additionally, we explored how to shuffle pandas DataFrames using sample() method, shuffle() method in sklearn and random.permutations() method in numpy."
},
{
"code": null,
"e": 3707,
"s": 3524,
"text": "If you want to learn more about how to split the data into training, testing and validation sets once the original dataset has been shuffled then make sure to read the article below."
},
{
"code": null,
"e": 3730,
"s": 3707,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 3847,
"s": 3730,
"text": "Become a member and read every story on Medium. Your membership fee directly supports me and other writers you read."
}
] |
JavaScript | Events | 10 Feb, 2022
Javascript has events to provide a dynamic interface to a webpage. These events are hooked to elements in the Document Object Model(DOM). These events by default use bubbling propagation i.e, upwards in the DOM from children to parent. We can bind events either as inline or in an external script. These are some javascript events: 1) onclick events: This is a mouse event and provokes any logic defined if the user clicks on the element it is bound to. Code #1:
html
<!doctype html><html> <head> <script> function hiThere() { alert('Hi there!'); } </script> </head> <body> <button type="button" onclick="hiThere()">Click me event</button> </body></html>
Output: Before clicking “click me event” key-
After clicking “click me event” key-
2) onkeyup event: This event is a keyboard event and executes instructions whenever a key is released after pressing. Code #2:
html
<!doctype html><html> <head> <script> var a = 0; var b = 0; var c = 0; function changeBackground() { var x = document.getElementById('bg'); x.style.backgroundColor = 'rgb('+a+', '+b+', '+c+')'; a += 1; b += a + 1; c += b + 1; if (a > 255) a = a - b; if (b > 255) b = a; if (c > 255) c = b; } </script> </head> <body> <input id="bg" onkeyup="changeBackground()" placeholder="write something" style="color:#fff"> </body></html>
Output: Before written of “gfg”-
After written of “gfg”-
3) onmouseover event: This event corresponds to hovering the mouse pointer over the element and its children, to which it is bound to. Code #3:
html
<!doctype html><html> <head> <script> function hov() { var e = document.getElementById('hover'); e.style.display = 'none'; } </script> </head> <body> <div id="hover" onmouseover="hov()" style="background-color:green;height:200px;width:200px;"> </div> </body></html>
Output: Before mouse is taken over green square-
Green square gets disappear after mouse is taken over it. 4) onmouseout event: Whenever the mouse cursor leaves the element which handles a mouseout event, a function associated with it is executed. Code #4:
html
<!doctype html><html> <head> <script> function out() { var e = document.getElementById('hover'); e.style.display = 'none'; } </script> </head> <body> <div id="hover" onmouseout="out()" style="background-color:green;height:200px;width:200px;"> </div> </body></html>
Output: Before mouse is taken over the green square-
Green square will disappear after mouse is taken over it and removed after some time. 5) onchange event: This event detects the change in value of any element listing to this event. Code #5:
html
<!doctype html><html> <head></head> <body> <input onchange="alert(this.value)" type="number"> </body></html>
Output: Before any key is pressed-
After 2 key is pressed-
6) onload event: When an element is loaded completely, this event is evoked. Code #6:
html
<!doctype html><html> <head></head> <body> <img onload="alert('Image completely loaded')" alt="GFG-Logo" src="https://media.geeksforgeeks.org/wp-content/cdn-uploads/GeeksforGeeksLogoHeader.png"> </body></html>
Output:
7) onfocus event: An element listing to this event executes instructions whenever it receives focus. Code #7:
html
<!doctype html><!doctype html><html> <head> <script> function focused() { var e = document.getElementById('inp'); if (confirm('Got it?')) { e.blur(); } } </script> </head> <body> <p >Take the focus into the input box below:</p> <input id="inp" onfocus="focused()"> </body></html>
Output: Before mouse is clicked inside of the box-
After mouse is clicked inside of the box-
8) onblur event: This event is evoked when an element loses focus. Code #8:
html
<!doctype html><html> <head></head> <body> <p>Write something in the input box and then click elsewhere in the document body.</p> <input onblur="alert(this.value)"> </body></html>
Output: Before “gfg” is entered inside of the box-
After “gfg” is entered inside of the box and pressed enter-
PS: onmouseup event listens to left and middle mouse click, but onmousedown event listens to left, middle, and right mouse clicks whereas onclick only handles left click.
gabaa406
manimega93
javascript-basics
JavaScript-Misc
JavaScript
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n10 Feb, 2022"
},
{
"code": null,
"e": 519,
"s": 54,
"text": "Javascript has events to provide a dynamic interface to a webpage. These events are hooked to elements in the Document Object Model(DOM). These events by default use bubbling propagation i.e, upwards in the DOM from children to parent. We can bind events either as inline or in an external script. These are some javascript events: 1) onclick events: This is a mouse event and provokes any logic defined if the user clicks on the element it is bound to. Code #1: "
},
{
"code": null,
"e": 524,
"s": 519,
"text": "html"
},
{
"code": "<!doctype html><html> <head> <script> function hiThere() { alert('Hi there!'); } </script> </head> <body> <button type=\"button\" onclick=\"hiThere()\">Click me event</button> </body></html>",
"e": 741,
"s": 524,
"text": null
},
{
"code": null,
"e": 789,
"s": 741,
"text": "Output: Before clicking “click me event” key- "
},
{
"code": null,
"e": 828,
"s": 789,
"text": "After clicking “click me event” key- "
},
{
"code": null,
"e": 957,
"s": 828,
"text": "2) onkeyup event: This event is a keyboard event and executes instructions whenever a key is released after pressing. Code #2: "
},
{
"code": null,
"e": 962,
"s": 957,
"text": "html"
},
{
"code": "<!doctype html><html> <head> <script> var a = 0; var b = 0; var c = 0; function changeBackground() { var x = document.getElementById('bg'); x.style.backgroundColor = 'rgb('+a+', '+b+', '+c+')'; a += 1; b += a + 1; c += b + 1; if (a > 255) a = a - b; if (b > 255) b = a; if (c > 255) c = b; } </script> </head> <body> <input id=\"bg\" onkeyup=\"changeBackground()\" placeholder=\"write something\" style=\"color:#fff\"> </body></html>",
"e": 1487,
"s": 962,
"text": null
},
{
"code": null,
"e": 1522,
"s": 1487,
"text": "Output: Before written of “gfg”- "
},
{
"code": null,
"e": 1548,
"s": 1522,
"text": "After written of “gfg”- "
},
{
"code": null,
"e": 1694,
"s": 1548,
"text": "3) onmouseover event: This event corresponds to hovering the mouse pointer over the element and its children, to which it is bound to. Code #3: "
},
{
"code": null,
"e": 1699,
"s": 1694,
"text": "html"
},
{
"code": "<!doctype html><html> <head> <script> function hov() { var e = document.getElementById('hover'); e.style.display = 'none'; } </script> </head> <body> <div id=\"hover\" onmouseover=\"hov()\" style=\"background-color:green;height:200px;width:200px;\"> </div> </body></html>",
"e": 2013,
"s": 1699,
"text": null
},
{
"code": null,
"e": 2064,
"s": 2013,
"text": "Output: Before mouse is taken over green square- "
},
{
"code": null,
"e": 2274,
"s": 2064,
"text": "Green square gets disappear after mouse is taken over it. 4) onmouseout event: Whenever the mouse cursor leaves the element which handles a mouseout event, a function associated with it is executed. Code #4: "
},
{
"code": null,
"e": 2279,
"s": 2274,
"text": "html"
},
{
"code": "<!doctype html><html> <head> <script> function out() { var e = document.getElementById('hover'); e.style.display = 'none'; } </script> </head> <body> <div id=\"hover\" onmouseout=\"out()\" style=\"background-color:green;height:200px;width:200px;\"> </div> </body></html>",
"e": 2589,
"s": 2279,
"text": null
},
{
"code": null,
"e": 2644,
"s": 2589,
"text": "Output: Before mouse is taken over the green square- "
},
{
"code": null,
"e": 2837,
"s": 2644,
"text": "Green square will disappear after mouse is taken over it and removed after some time. 5) onchange event: This event detects the change in value of any element listing to this event. Code #5: "
},
{
"code": null,
"e": 2842,
"s": 2837,
"text": "html"
},
{
"code": "<!doctype html><html> <head></head> <body> <input onchange=\"alert(this.value)\" type=\"number\"> </body></html>",
"e": 2957,
"s": 2842,
"text": null
},
{
"code": null,
"e": 2994,
"s": 2957,
"text": "Output: Before any key is pressed- "
},
{
"code": null,
"e": 3020,
"s": 2994,
"text": "After 2 key is pressed- "
},
{
"code": null,
"e": 3108,
"s": 3020,
"text": "6) onload event: When an element is loaded completely, this event is evoked. Code #6: "
},
{
"code": null,
"e": 3113,
"s": 3108,
"text": "html"
},
{
"code": "<!doctype html><html> <head></head> <body> <img onload=\"alert('Image completely loaded')\" alt=\"GFG-Logo\" src=\"https://media.geeksforgeeks.org/wp-content/cdn-uploads/GeeksforGeeksLogoHeader.png\"> </body></html>",
"e": 3339,
"s": 3113,
"text": null
},
{
"code": null,
"e": 3349,
"s": 3339,
"text": "Output: "
},
{
"code": null,
"e": 3463,
"s": 3351,
"text": "7) onfocus event: An element listing to this event executes instructions whenever it receives focus. Code #7: "
},
{
"code": null,
"e": 3468,
"s": 3463,
"text": "html"
},
{
"code": "<!doctype html><!doctype html><html> <head> <script> function focused() { var e = document.getElementById('inp'); if (confirm('Got it?')) { e.blur(); } } </script> </head> <body> <p >Take the focus into the input box below:</p> <input id=\"inp\" onfocus=\"focused()\"> </body></html>",
"e": 3806,
"s": 3468,
"text": null
},
{
"code": null,
"e": 3859,
"s": 3806,
"text": "Output: Before mouse is clicked inside of the box- "
},
{
"code": null,
"e": 3903,
"s": 3859,
"text": "After mouse is clicked inside of the box- "
},
{
"code": null,
"e": 3981,
"s": 3903,
"text": "8) onblur event: This event is evoked when an element loses focus. Code #8: "
},
{
"code": null,
"e": 3986,
"s": 3981,
"text": "html"
},
{
"code": "<!doctype html><html> <head></head> <body> <p>Write something in the input box and then click elsewhere in the document body.</p> <input onblur=\"alert(this.value)\"> </body></html>",
"e": 4185,
"s": 3986,
"text": null
},
{
"code": null,
"e": 4238,
"s": 4185,
"text": "Output: Before “gfg” is entered inside of the box- "
},
{
"code": null,
"e": 4300,
"s": 4238,
"text": "After “gfg” is entered inside of the box and pressed enter- "
},
{
"code": null,
"e": 4472,
"s": 4300,
"text": "PS: onmouseup event listens to left and middle mouse click, but onmousedown event listens to left, middle, and right mouse clicks whereas onclick only handles left click. "
},
{
"code": null,
"e": 4481,
"s": 4472,
"text": "gabaa406"
},
{
"code": null,
"e": 4492,
"s": 4481,
"text": "manimega93"
},
{
"code": null,
"e": 4510,
"s": 4492,
"text": "javascript-basics"
},
{
"code": null,
"e": 4526,
"s": 4510,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 4537,
"s": 4526,
"text": "JavaScript"
}
] |
Field getInt() method in Java with Examples | 26 Aug, 2019
The getInt() method of java.lang.reflect.Field used to get the value of int which has to be static or instance field type. This method also used to get the value of another primitive type convertible to type int via a widening conversion. When a class contains a static or instance int field and we want to get the value of that field then we can use this method to return the value of Field.
Syntax:
public int getInt(Object obj)
throws IllegalArgumentException,
IllegalAccessException
Parameters: This method accepts a single parameter obj which is the object to extract the int value from.
Return value: This method returns the value of field converted to type int.
Exception: This method throws following Exception:
IllegalAccessException: if Field object is enforcing Java language access control and the underlying field is inaccessible.IllegalArgumentException: if the specified object is not an instance of the class or interface declaring the underlying field or if the field value cannot be converted to the type int by a widening conversion.NullPointerException: if the specified object is null and the field is an instance field.ExceptionInInitializerError: if the initialization provoked by this method fails.
IllegalAccessException: if Field object is enforcing Java language access control and the underlying field is inaccessible.
IllegalArgumentException: if the specified object is not an instance of the class or interface declaring the underlying field or if the field value cannot be converted to the type int by a widening conversion.
NullPointerException: if the specified object is null and the field is an instance field.
ExceptionInInitializerError: if the initialization provoked by this method fails.
Below programs illustrate getInt() method:Program 1:
// Java program to demonstrate getInt() method import java.lang.reflect.Field; public class GFG { public static void main(String[] args) throws Exception { // Create the Employee class object Employee Employee = new Employee(); // Get the Salary field object Field field = Employee.class.getField("Salary"); // Apply getInt Method on Employee Object // to get the value of Salary field int value = field.getInt(Employee); // print result System.out.println("Value of int Field" + " Salary is " + value); }} // sample Employee classclass Employee { // static int values public static int Salary = 34113; public static String name = "Aman"; public static int getSalary() { return Salary; } public static void setSalary(int Salary) { Employee.Salary = Salary; } public static String getName() { return name; } public static void setName(String name) { Employee.name = name; }}
Value of int Field Salary is 34113
Program 2:
// Java program to demonstrate getInt() method import java.lang.reflect.Field; public class GFG { public static void main(String[] args) throws Exception { // Create the IntNumbers class object IntNumbers Int = new IntNumbers(); // Get the value field object Field field = IntNumbers.class.getField("value"); // Apply getInt Method on field Object // to get the value of value field int value = field.getInt(Int); // print result System.out.println("Value: " + value); } // IntNumbers class static class IntNumbers { // int field public static int value = 999994567; // getter and setter methods public static int getValue() { return value; } public static void setValue(int value) { IntNumbers.value = value; } }}
Value: 999994567
References: https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Field.html#getInt-java.lang.Object-
Java-Field
Java-Functions
java-lang-reflect-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": "\n26 Aug, 2019"
},
{
"code": null,
"e": 421,
"s": 28,
"text": "The getInt() method of java.lang.reflect.Field used to get the value of int which has to be static or instance field type. This method also used to get the value of another primitive type convertible to type int via a widening conversion. When a class contains a static or instance int field and we want to get the value of that field then we can use this method to return the value of Field."
},
{
"code": null,
"e": 429,
"s": 421,
"text": "Syntax:"
},
{
"code": null,
"e": 545,
"s": 429,
"text": "public int getInt(Object obj)\n throws IllegalArgumentException,\n IllegalAccessException\n"
},
{
"code": null,
"e": 651,
"s": 545,
"text": "Parameters: This method accepts a single parameter obj which is the object to extract the int value from."
},
{
"code": null,
"e": 727,
"s": 651,
"text": "Return value: This method returns the value of field converted to type int."
},
{
"code": null,
"e": 778,
"s": 727,
"text": "Exception: This method throws following Exception:"
},
{
"code": null,
"e": 1281,
"s": 778,
"text": "IllegalAccessException: if Field object is enforcing Java language access control and the underlying field is inaccessible.IllegalArgumentException: if the specified object is not an instance of the class or interface declaring the underlying field or if the field value cannot be converted to the type int by a widening conversion.NullPointerException: if the specified object is null and the field is an instance field.ExceptionInInitializerError: if the initialization provoked by this method fails."
},
{
"code": null,
"e": 1405,
"s": 1281,
"text": "IllegalAccessException: if Field object is enforcing Java language access control and the underlying field is inaccessible."
},
{
"code": null,
"e": 1615,
"s": 1405,
"text": "IllegalArgumentException: if the specified object is not an instance of the class or interface declaring the underlying field or if the field value cannot be converted to the type int by a widening conversion."
},
{
"code": null,
"e": 1705,
"s": 1615,
"text": "NullPointerException: if the specified object is null and the field is an instance field."
},
{
"code": null,
"e": 1787,
"s": 1705,
"text": "ExceptionInInitializerError: if the initialization provoked by this method fails."
},
{
"code": null,
"e": 1840,
"s": 1787,
"text": "Below programs illustrate getInt() method:Program 1:"
},
{
"code": "// Java program to demonstrate getInt() method import java.lang.reflect.Field; public class GFG { public static void main(String[] args) throws Exception { // Create the Employee class object Employee Employee = new Employee(); // Get the Salary field object Field field = Employee.class.getField(\"Salary\"); // Apply getInt Method on Employee Object // to get the value of Salary field int value = field.getInt(Employee); // print result System.out.println(\"Value of int Field\" + \" Salary is \" + value); }} // sample Employee classclass Employee { // static int values public static int Salary = 34113; public static String name = \"Aman\"; public static int getSalary() { return Salary; } public static void setSalary(int Salary) { Employee.Salary = Salary; } public static String getName() { return name; } public static void setName(String name) { Employee.name = name; }}",
"e": 2926,
"s": 1840,
"text": null
},
{
"code": null,
"e": 2962,
"s": 2926,
"text": "Value of int Field Salary is 34113\n"
},
{
"code": null,
"e": 2973,
"s": 2962,
"text": "Program 2:"
},
{
"code": "// Java program to demonstrate getInt() method import java.lang.reflect.Field; public class GFG { public static void main(String[] args) throws Exception { // Create the IntNumbers class object IntNumbers Int = new IntNumbers(); // Get the value field object Field field = IntNumbers.class.getField(\"value\"); // Apply getInt Method on field Object // to get the value of value field int value = field.getInt(Int); // print result System.out.println(\"Value: \" + value); } // IntNumbers class static class IntNumbers { // int field public static int value = 999994567; // getter and setter methods public static int getValue() { return value; } public static void setValue(int value) { IntNumbers.value = value; } }}",
"e": 3892,
"s": 2973,
"text": null
},
{
"code": null,
"e": 3910,
"s": 3892,
"text": "Value: 999994567\n"
},
{
"code": null,
"e": 4018,
"s": 3910,
"text": "References: https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Field.html#getInt-java.lang.Object-"
},
{
"code": null,
"e": 4029,
"s": 4018,
"text": "Java-Field"
},
{
"code": null,
"e": 4044,
"s": 4029,
"text": "Java-Functions"
},
{
"code": null,
"e": 4070,
"s": 4044,
"text": "java-lang-reflect-package"
},
{
"code": null,
"e": 4075,
"s": 4070,
"text": "Java"
},
{
"code": null,
"e": 4080,
"s": 4075,
"text": "Java"
}
] |
How to make a HTML div responsive using CSS ? | 30 Sep, 2020
The CSS Media Query can be used to make an HTML “div” responsive. The media queries allow the users to change or customize the web pages for many devices like desktops, mobile phones, tablets, etc without changing the markups. Using the media query, the user can change the style of a particular element for different sizes of screen.
The CSS @media rule consists of a media type and it can have one or more expressions, which can result to values like “true” or “false”.
Syntax:
@media not|only mediatype and (expressions) {
// Your CSS codes
}
The following meta viewport element has to included in the “head” section of the HTML file for the responsive web page to work.
<meta name=”viewport” content=”width=device-width, initial-scale=1.0”>
Example: In the following example, all three HTML “div” blocks are aligned horizontally. But whenever the screen size is reduced below “500px”, all the three blocks will automatically align vertically. The width property for the “div” element in the @media query for screen size is set to less than or equal to “500px”.
HTML
<!DOCTYPE html><html> <head> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <style> div { margin: 10px; } .first { width: 25%; display: inline-block; background-color: green; } .second { width: 25%; display: inline-block; background-color: blue; } .third { width: 25%; display: inline-block; background-color: yellow; } @media screen and (max-width: 500px) { .first, .second, .third { width: 70%; } } </style></head> <body> <h1>Geeks for Geeks</h1> <p>Responsive div using css.</p> <div class="first"> <p>First block</p> </div> <div class="second"> <p>Second block</p> </div> <div class="third"> <p>Third block </p> </div> <p> The media query will only apply if the media type is screen and the viewport is equal to or less than 500px </p></body> </html>
Output:
In the original window size, all the three blocks are aligned horizontally.
In the original window size, all the three blocks are aligned horizontally.
When the screen size is reduced to “500px”, all the three blocks are placed vertically.
When the screen size is reduced to “500px”, all the three blocks are placed vertically.
Similarly, one can add or change various styles for a particular HTML element for different screen sizes by adding CSS code in @media query section as shown in the above example.
CSS-Misc
HTML-Misc
CSS
HTML
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n30 Sep, 2020"
},
{
"code": null,
"e": 387,
"s": 52,
"text": "The CSS Media Query can be used to make an HTML “div” responsive. The media queries allow the users to change or customize the web pages for many devices like desktops, mobile phones, tablets, etc without changing the markups. Using the media query, the user can change the style of a particular element for different sizes of screen."
},
{
"code": null,
"e": 524,
"s": 387,
"text": "The CSS @media rule consists of a media type and it can have one or more expressions, which can result to values like “true” or “false”."
},
{
"code": null,
"e": 532,
"s": 524,
"text": "Syntax:"
},
{
"code": null,
"e": 605,
"s": 532,
"text": " \n@media not|only mediatype and (expressions) {\n // Your CSS codes\n}\n"
},
{
"code": null,
"e": 733,
"s": 605,
"text": "The following meta viewport element has to included in the “head” section of the HTML file for the responsive web page to work."
},
{
"code": null,
"e": 804,
"s": 733,
"text": "<meta name=”viewport” content=”width=device-width, initial-scale=1.0”>"
},
{
"code": null,
"e": 1124,
"s": 804,
"text": "Example: In the following example, all three HTML “div” blocks are aligned horizontally. But whenever the screen size is reduced below “500px”, all the three blocks will automatically align vertically. The width property for the “div” element in the @media query for screen size is set to less than or equal to “500px”."
},
{
"code": null,
"e": 1129,
"s": 1124,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> <style> div { margin: 10px; } .first { width: 25%; display: inline-block; background-color: green; } .second { width: 25%; display: inline-block; background-color: blue; } .third { width: 25%; display: inline-block; background-color: yellow; } @media screen and (max-width: 500px) { .first, .second, .third { width: 70%; } } </style></head> <body> <h1>Geeks for Geeks</h1> <p>Responsive div using css.</p> <div class=\"first\"> <p>First block</p> </div> <div class=\"second\"> <p>Second block</p> </div> <div class=\"third\"> <p>Third block </p> </div> <p> The media query will only apply if the media type is screen and the viewport is equal to or less than 500px </p></body> </html>",
"e": 2258,
"s": 1129,
"text": null
},
{
"code": null,
"e": 2266,
"s": 2258,
"text": "Output:"
},
{
"code": null,
"e": 2342,
"s": 2266,
"text": "In the original window size, all the three blocks are aligned horizontally."
},
{
"code": null,
"e": 2418,
"s": 2342,
"text": "In the original window size, all the three blocks are aligned horizontally."
},
{
"code": null,
"e": 2506,
"s": 2418,
"text": "When the screen size is reduced to “500px”, all the three blocks are placed vertically."
},
{
"code": null,
"e": 2594,
"s": 2506,
"text": "When the screen size is reduced to “500px”, all the three blocks are placed vertically."
},
{
"code": null,
"e": 2773,
"s": 2594,
"text": "Similarly, one can add or change various styles for a particular HTML element for different screen sizes by adding CSS code in @media query section as shown in the above example."
},
{
"code": null,
"e": 2782,
"s": 2773,
"text": "CSS-Misc"
},
{
"code": null,
"e": 2792,
"s": 2782,
"text": "HTML-Misc"
},
{
"code": null,
"e": 2796,
"s": 2792,
"text": "CSS"
},
{
"code": null,
"e": 2801,
"s": 2796,
"text": "HTML"
},
{
"code": null,
"e": 2818,
"s": 2801,
"text": "Web Technologies"
},
{
"code": null,
"e": 2845,
"s": 2818,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 2850,
"s": 2845,
"text": "HTML"
}
] |
C++ String Library - find | It searches the string for the first occurrence of the sequence specified by its arguments.
Following is the declaration for std::string::find.
size_t find (const string& str, size_t pos = 0) const;
size_t find (const string& str, size_t pos = 0) const noexcept;
size_t find (const string& str, size_t pos = 0) const noexcept;
str − It is a string object.
str − It is a string object.
len − It is used to copy the characters.
len − It is used to copy the characters.
pos − Position of the first character to be copied.
pos − Position of the first character to be copied.
none
if an exception is thrown, there are no changes in the string.
In below example for std::string::find.
#include <iostream>
#include <string>
int main () {
std::string str ("sairamkrishna Mammahe is a tech person in tutorialspoint.com.");
std::string str2 ("needle");
std::size_t found = str.find(str2);
if (found!=std::string::npos)
std::cout << "first 'needle' found at: " << found << '\n';
found=str.find("needles are small",found+1,6);
if (found!=std::string::npos)
std::cout << "second 'needle' found at: " << found << '\n';
found=str.find("haystack");
if (found!=std::string::npos)
std::cout << "'haystack' also found at: " << found << '\n';
found=str.find('.');
if (found!=std::string::npos)
std::cout << "Period found at: " << found << '\n';
str.replace(str.find(str2),str2.length(),"preposition");
std::cout << str << '\n';
return 0;
}
The sample output should be like this −
Period found at: 56
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2695,
"s": 2603,
"text": "It searches the string for the first occurrence of the sequence specified by its arguments."
},
{
"code": null,
"e": 2747,
"s": 2695,
"text": "Following is the declaration for std::string::find."
},
{
"code": null,
"e": 2802,
"s": 2747,
"text": "size_t find (const string& str, size_t pos = 0) const;"
},
{
"code": null,
"e": 2866,
"s": 2802,
"text": "size_t find (const string& str, size_t pos = 0) const noexcept;"
},
{
"code": null,
"e": 2930,
"s": 2866,
"text": "size_t find (const string& str, size_t pos = 0) const noexcept;"
},
{
"code": null,
"e": 2959,
"s": 2930,
"text": "str − It is a string object."
},
{
"code": null,
"e": 2988,
"s": 2959,
"text": "str − It is a string object."
},
{
"code": null,
"e": 3029,
"s": 2988,
"text": "len − It is used to copy the characters."
},
{
"code": null,
"e": 3070,
"s": 3029,
"text": "len − It is used to copy the characters."
},
{
"code": null,
"e": 3122,
"s": 3070,
"text": "pos − Position of the first character to be copied."
},
{
"code": null,
"e": 3174,
"s": 3122,
"text": "pos − Position of the first character to be copied."
},
{
"code": null,
"e": 3179,
"s": 3174,
"text": "none"
},
{
"code": null,
"e": 3242,
"s": 3179,
"text": "if an exception is thrown, there are no changes in the string."
},
{
"code": null,
"e": 3282,
"s": 3242,
"text": "In below example for std::string::find."
},
{
"code": null,
"e": 4093,
"s": 3282,
"text": "#include <iostream>\n#include <string>\n\nint main () {\n std::string str (\"sairamkrishna Mammahe is a tech person in tutorialspoint.com.\");\n std::string str2 (\"needle\");\n\n std::size_t found = str.find(str2);\n if (found!=std::string::npos)\n std::cout << \"first 'needle' found at: \" << found << '\\n';\n\n found=str.find(\"needles are small\",found+1,6);\n if (found!=std::string::npos)\n std::cout << \"second 'needle' found at: \" << found << '\\n';\n\n found=str.find(\"haystack\");\n if (found!=std::string::npos)\n std::cout << \"'haystack' also found at: \" << found << '\\n';\n\n found=str.find('.');\n if (found!=std::string::npos)\n std::cout << \"Period found at: \" << found << '\\n';\n\n str.replace(str.find(str2),str2.length(),\"preposition\");\n std::cout << str << '\\n';\n\n return 0;\n}"
},
{
"code": null,
"e": 4133,
"s": 4093,
"text": "The sample output should be like this −"
},
{
"code": null,
"e": 4154,
"s": 4133,
"text": "Period found at: 56\n"
},
{
"code": null,
"e": 4161,
"s": 4154,
"text": " Print"
},
{
"code": null,
"e": 4172,
"s": 4161,
"text": " Add Notes"
}
] |
Monitoring and Retraining Your Machine Learning Models | by Felipe de Pontes Adachi | Towards Data Science | Like everything in life, machine learning models go stale. In a world of ever-changing, non-stationary data, everyone needs to go back to school and recycle itself once in a while, and your model is no different.
Well, we know that retraining our model is important, but when exactly should we do it? If we do it too frequently, we’d end up wasting valuable time and effort, but to do it seldomly would surely affect our prediction’s quality. Unfortunately, there is no one-size-fits-all answer. Each case should be carefully assessed in order to determine the impact of staleness.
In this article, I’d like to share my approach to monitoring and retraining on a personal project: A fake news detector web application. I’m by no means an expert on the subject, so if you have any suggestions or considerations, please feel free to get in contact.
Our simple web application is basically a fake news detector: the user is able to enter a URL of a news article, and the system will output the result of its prediction: whether it’s fake or real.
For every input, the system logs the prediction’s result and additional metadata in a BigQuery table at GCP. That’s the data we’ll use to monitor our model’s performance and, when needed, to retrain it.
This article is divided into two parts: Monitoring and Retraining.
First, I’ll talk about how I used the prediction logs at BigQuery to set up a Google Data Studio dashboard in order to have some updated charts and indicators to assess my text classification model’s health.
In the Retraining section, I’ll show how I approached data versioning to manage my data and model artifacts for each retraining experiment while keeping data quality in mind. To do so, I used tools such as lakeFS, Great Expectations, and W&B. Everything discussed in this part can be found at the project’s repository.
Let’s begin by taking a look at the model_predictions table’s schema:
title (STRING): The new’s title.
content (STRING): The new’s text content.
model (STRING): The name of the model that generated the prediction.
prediction (STRING): The model’s prediction — “Real” or “Fake”.
confidence (FLOAT): The prediction’s level of confidence by the model. From 0 to 1.
url (STRING): The new’s URL.
prediction_date (DATETIME): Date and time of when the prediction was made.
ground_truth (STRING): Starts as NULL, and can be changed to “Real” or “Fake” in a labeling process.
coverage (FLOAT): The percentage of words in the news that are present in the model’s vocabulary.
word_count (INTEGER): The number of words in the news.
These fields are all calculated upon serving the prediction’s online request by our application. If you’re interested in knowing how those metrics were calculated in the first place, you can take a look at app.py at the project’s repository.
From these fields, we can set up an online dashboard with Google Data Studio to constantly monitor some indicators of our prediction model:
Data Studio has a very intuitive interface. In this example, we’re using only one data source, which is the model prediction table at BigQuery. So, from a blank dashboard, we can add a data source by simply clicking the Add Data button at the top, and then selecting the BigQuery option.
I chose not to display charts related to ground_truth , as this field can be frequently empty if there’s not an intention of retraining the model in the near future. But if labeling is done constantly, a Confusion Matrix would be a great addition to our dashboard.
In this example, since I don’t have a great number of records, we shouldn’t draw any statistical conclusion from these numbers. Hopefully, in the future, with more daily predictions, these charts will be more informative. Nonetheless, let’s go by and discuss each one of these indicators:
This is simply the number of predictions the application has served until now. To create it, go to Add a Chart at the top and select scorecard. Choose your table as Data Source and Record Count as Metric.
This is the percentage of records that have been manually labeled. This is important for the next step of retraining. Without ground truth, you can’t retrain your model.
Like Records, this is also a scorecard. But for this one, you have to create a new calculated field, by clicking ADD A FIELD at the bottom of the scorecard’s DATA tab:
Then, just select the newly-created field as your Metric, just like before.
The name of the last prediction’s model. Assumes we have only one application, and there can only be one model at a time.
This indicator is actually a Table chart, rather than a scorecard. As Dimension, select modeland prediction_date, then set Rows per page as 1 and then sort prediction_date in Descending order. Then you should hide everything possible at the STYLE tab.
The Real/Fake prediction’s percentage.
To create it, go to Add a Chart → Pie. Choose prediction as Dimension, and Record_count as Metric, and you’re good to go.
This graph shows us the average of two values over time, on a weekly basis: confidenceand coverage. From this, we should be able to see an unusual change in the model’s level of confidence in its predictions, and also how much of the news is present on the trained model’s vocabulary. If the coverage has a descending trend and goes below a predefined threshold, it might be time to retrain it.
This one’s a Time series. On the Dimension field, at the little calendar icon, you should be able to set the period. I chose ISO Year Week. As Metric, choose confidence as the first one, and AVG as aggregation for the metric. Then, go to Add metric and do the same with coverage. At the STYLE tab, you can change both series from Lines to Bars and set their colors.
This chart groups records by the number of words, according to each prediction category. Even though we need more data to have a real grasp of the word count distribution, it seems that Fake news is usually shorter than Real ones.
Another strange detail is that there are 5 Fake predictions with a word count between 0–100. That seems a little low for a piece of news, which led me to investigate further. I eventually found out that these records were extracted from the same website, and they all had a parsing error. The content was not the actual news, but rather an error message. This is important, and we should make sure that these kinds of records will never be ingested into our training-test dataset.
That was the closest I got to making a histogram at Data Studio. To create one go to Chart → Bar, and add a new field, at the bottom of the DATA tab. In the formula field, enter:
FLOOR(word_count/100)*100
For each record, the word count will be divided by 100, and then the largest integral value of the result is multiplied by 100. That will put the records into bins of hundreds. I named that field wc_bin. You can use it as the Dimension, and Record Count as Metric. You should also set Sort to Ascending, and choose wc_bin .
To split the histograms into Fake and Real, you can go to Add a Filter, right below Sort, and insert a filter like this one:
And just do the opposite for the next category.
Alright, now we have a way to check on our model’s health. If something is out of the usual, we could start labeling some of the records and take a look at some important classification metrics, such as Precision, Recall, and F-score. If you’re not happy with the results, we should start retraining the model.
The image below is an overview of the retraining process I set up for this project:
We have our Base Data, the original dataset we used in order to train our first prediction model. In addition, the application is constantly feeding us data from the online predictions. So, in order to retrain the model, we can extract this data and do some simple preprocessing, such as removing duplicate news. It is also very important to validate our data and make sure it complies with some assumptions we have regarding the data’s shape and distribution. Then, we move on by joining both data sources to finally retrain the model. Before replacing the old model, we must evaluate the newly-trained model with a test set to make sure of its quality.
Every time we wish to retrain the model, we follow these steps. But if we notice something wrong in the future, how do we debug our model? To do so, we need an orderly manner to store our model and data artifacts, in addition to the model’s performance results and code that generated it.
Managing data pipelines in an ML Application is not an easy task. Unlike traditional software development, where GIT has become the standard for code versioning, data versioning is still at its early stages, and there’s not a “definitive” way of doing so.
I decided to treat each retraining process as a single experiment and store the artifacts of each experiment in a single branch. This is a little different from what we’re used to with code versioning because in this case, I don’t expect to merge the branches back into the trunk. They are short-lived branches with the purpose of versioning our artifacts — datasets and models — according to different retraining experiments.
Even though there are a number of MLOps tools that provide data versioning functionality, such as MLflow and W&B, I opted to tackle data versioning as an infrastructure, by enabling Git-like operations over my object storage. For that purpose, I decided to try out the recently-released lakeFS, which enables me to add the Git-like engine on top of my existing S3 object storage. That way, my data versioning capability for the project is independent of any tools that I might add or replace in the future.
You can find the instructions to set up your lakeFS environment here.
I basically had to:
Create a PostgreSQL database on AWS RDSConfigure an S3 bucket for my repository
Create a PostgreSQL database on AWS RDS
Configure an S3 bucket for my repository
For the policy’s Principal, I created a user and created access keys for it. I’ll also use this user to authenticate lakeFS to AWS. You can read more about here and here.
3. Install lakeFS
I chose to install it via Docker, with the following command:
docker run --name lakefs -p 8000:8000-e LAKEFS_DATABASE_CONNECTION_STRING="<postgres-connection-str>"-e LAKEFS_AUTH_ENCRYPT_SECRET_KEY="<lakefs-secret-key>"-e LAKEFS_BLOCKSTORE_TYPE="s3"-e LAKEFS_GATEWAYS_S3_DOMAIN_NAME="s3.local.lakefs.io"-e LAKEFS_BLOCKSTORE_S3_CREDENTIALS_ACCESS_SECRET_KEY="<s3-secret-key>"-e LAKEFS_BLOCKSTORE_S3_CREDENTIALS_ACCESS_KEY_ID="<s3-access-key>" -e LAKEFS_BLOCKSTORE_S3_REGION="<s3-region>" treeverse/lakefs:latest run
Where postgres-connection-str is the connection string you obtained creating the PostgreSQL DB, lakefs-secret-key is any randomly generated string (just don’t forget it), s3-secret-key and s3-access-key are the key-pair you created for your AWS User earlier, and s3-region is the region of the bucket you created.
4. Setup
At localhost:8000, after setting a new administrator user and creating the repository, you should be able to see your list of repositories:
Now that we have everything set up, we need to translate that flowchart into a series of steps and implement it. We’ll basically need to:
Get data from online predictions (BigQuery)
Clean and assert data quality (Great Expectations)
Create a new branch from master (lakeFS)
Upload online predictions to a new branch (lakeFS)
Get base data from master branch (lakeFS)
Join online predictions to base data and split to train-test datasets
Upload train-test splits to branch (lakeFS)
Train model with the updated dataset
Log Experiment/Results (W&B)
Upload Model and Vocabulary to branch (lakeFS)
Commit changes to branch (lakeFS)
As for our data structure, we’ll define as external data our original dataset as well as data extracted from the web app’s online predictions. The interim folder will keep our data once the external sources are combined and split into appropriate train-test sets. The model files will also be stored in their own folder.
First, we need to get the new data from our BigQuery table. To use the Python APIs for accessing BigQuery, I need GCP credentials in JSON format. After creating a project, you can follow these instructions on “creating a service account” in this Google documentation in order to download your credentials.
Then, installing google-cloud-bigquery and setting an environment variable indicating the location of your credentials and initiating the BigQuery client should be enough for you to query your table. In this case, sunny-emissary-293912 is the name of my project, fakenewsdeploy the name of my dataset and model_predictions the name of my table.
We should always ensure the quality of data ingested into our storage. A great way to do that is using the tool Great Expectations. After I do some very simple cleaning, like removing duplicate news and news with low word count, we can do some basic assumptions about what we expect from our data.
In this example, we’ll only keep going with our retraining if our data passes some validations. The ground_truth should assume only Fake or Real values, the url value should be unique and every sample should have a non-null content. In addition, we assume that an excessively low coverage must be investigated, as it might be a sign of parsing errors, or maybe content in another language. Finally, the word_count should be above 100, as we have discussed previously in the Monitoring section of this article.
We can then generate an expectation_suite , which gives us a JSON file showing the validations passed by our data. We should also make sure to store this information for future reference (which will be done in the sequence).
We are only scratching the surface with Great Expectations here. Check out their website to know more functionalities.
Now that we trust our data, we can store it in a newly-created branch. In the early stages of Model Building/Evaluation of this project, I used W&B to track my experiments. I’ll keep using it during the retraining process, in conjunction with lakeFS. This way, the experiment identifier is the wandb’s run name, and I’ll just use the same name in order to create the branch:
Two things to point out here. In line 3, while starting the run, you see I configured a threshold. That’s for a nice W&B functionality where I can set up a threshold to be monitored during training. In this case, if the F1-Score of the trained model is below 0.9, W&B will send me an email letting me know. We’ll see the rest of it in the training code.
Another important issue here is how I’m doing operations at my lakeFS repository. This can be done in several different ways, but I chose to use the Python client. I created a lakefs_connector class to wrap the APIs into more tailored functions for my application. The class implementation is shown at the end of this article.
Let’s keep going by uploading online_predictions.csv to our branch. We’ll also save my_expectation_file.json to our wandb run.
Now we can access our expectation file whenever we need it, and make sure that the data’s state at this particular run complies with our assumptions:
Our base data is comprised of two files: True.csv and Fake.csv, both previously uploaded into our master branch. Let’s append the data from online_predictions.csv to our base data and then split it into train-test datasets:
The last series of steps is to finally train the model and upload our artifacts to the repository’s branch:
We’ll upload the train-test splits as well as our model’s files — the actual joblib model and the vocabulary used for our Vectorizer (which is also used to calculate our coverage field).
You can check the whole code for training the model here. I won’t get into specifics, since I already covered it in my previous article. I just want to point out an excerpt of it, related to the alert configuration we set up:
f1_score is the calculated F1-Score during the training process. Since we set up the threshold of 0.9 previously, if the score for this run ends up below this value, an alert will be sent to the configured destination. In my case, it’s my email:
Now, what is left to do is to commit our changes into our branch:
And we’ll have our data separated according to our retraining experiments, like this:
Since the run names are unique, we can easily match the data with our retraining’s results at our experiments dashboard at W&B:
In the code snippets above, we have done some operations to our repository, such as creating branches, downloading and uploading objects, and committing changes. To do so, I used bravado to generate a dynamic client, as instructed here. This way we have access to all of the lakeFS’ APIs as Python commands.
By instantiating the lakefs_conn class, we create a lakeFS client, and do the required repository operations through the object’s methods:
I wanted to share with you my take on monitoring my model’s performance and retraining it, but this is really the first step of a long process. As time goes on, the additional data enables us to have more insights, and we eventually discover better ways to monitor our application.
For example, in the future, we could plot the performance of multiple retrained models and compare them over time, to more accurately assess the impact of time over our predictions. Or, given enough ground truth information, we could add metrics such as precision and recall to our dashboard.
As for the retraining part, much can be improved. As we discover more about our data’s distribution, additional expectations can be added to our assertion stage. The addition of hooks for automatic pre-commit validation is also a natural evolution. Webhooks weren’t yet supported by lakeFS during the writing of this article, but it’s already an available feat since the latest release (0.33).
That’s it for now! If you have any feedback or questions, feel free to reach out!
Thank you for reading!
Continuous Delivery for Machine Learning
Data Versioning
Ensuring Data Quality in a Data Lake Environment
The ML Test Score: A Rubric for ML Production Readiness and Technical Debt Reduction
Why Data Versioning as an Infrastructure Matters
lakeFS — Documentation
Great Expectations — Documentation
Weights and Biases — Documentation | [
{
"code": null,
"e": 384,
"s": 171,
"text": "Like everything in life, machine learning models go stale. In a world of ever-changing, non-stationary data, everyone needs to go back to school and recycle itself once in a while, and your model is no different."
},
{
"code": null,
"e": 753,
"s": 384,
"text": "Well, we know that retraining our model is important, but when exactly should we do it? If we do it too frequently, we’d end up wasting valuable time and effort, but to do it seldomly would surely affect our prediction’s quality. Unfortunately, there is no one-size-fits-all answer. Each case should be carefully assessed in order to determine the impact of staleness."
},
{
"code": null,
"e": 1018,
"s": 753,
"text": "In this article, I’d like to share my approach to monitoring and retraining on a personal project: A fake news detector web application. I’m by no means an expert on the subject, so if you have any suggestions or considerations, please feel free to get in contact."
},
{
"code": null,
"e": 1215,
"s": 1018,
"text": "Our simple web application is basically a fake news detector: the user is able to enter a URL of a news article, and the system will output the result of its prediction: whether it’s fake or real."
},
{
"code": null,
"e": 1418,
"s": 1215,
"text": "For every input, the system logs the prediction’s result and additional metadata in a BigQuery table at GCP. That’s the data we’ll use to monitor our model’s performance and, when needed, to retrain it."
},
{
"code": null,
"e": 1485,
"s": 1418,
"text": "This article is divided into two parts: Monitoring and Retraining."
},
{
"code": null,
"e": 1693,
"s": 1485,
"text": "First, I’ll talk about how I used the prediction logs at BigQuery to set up a Google Data Studio dashboard in order to have some updated charts and indicators to assess my text classification model’s health."
},
{
"code": null,
"e": 2012,
"s": 1693,
"text": "In the Retraining section, I’ll show how I approached data versioning to manage my data and model artifacts for each retraining experiment while keeping data quality in mind. To do so, I used tools such as lakeFS, Great Expectations, and W&B. Everything discussed in this part can be found at the project’s repository."
},
{
"code": null,
"e": 2082,
"s": 2012,
"text": "Let’s begin by taking a look at the model_predictions table’s schema:"
},
{
"code": null,
"e": 2115,
"s": 2082,
"text": "title (STRING): The new’s title."
},
{
"code": null,
"e": 2157,
"s": 2115,
"text": "content (STRING): The new’s text content."
},
{
"code": null,
"e": 2226,
"s": 2157,
"text": "model (STRING): The name of the model that generated the prediction."
},
{
"code": null,
"e": 2290,
"s": 2226,
"text": "prediction (STRING): The model’s prediction — “Real” or “Fake”."
},
{
"code": null,
"e": 2374,
"s": 2290,
"text": "confidence (FLOAT): The prediction’s level of confidence by the model. From 0 to 1."
},
{
"code": null,
"e": 2403,
"s": 2374,
"text": "url (STRING): The new’s URL."
},
{
"code": null,
"e": 2478,
"s": 2403,
"text": "prediction_date (DATETIME): Date and time of when the prediction was made."
},
{
"code": null,
"e": 2579,
"s": 2478,
"text": "ground_truth (STRING): Starts as NULL, and can be changed to “Real” or “Fake” in a labeling process."
},
{
"code": null,
"e": 2677,
"s": 2579,
"text": "coverage (FLOAT): The percentage of words in the news that are present in the model’s vocabulary."
},
{
"code": null,
"e": 2732,
"s": 2677,
"text": "word_count (INTEGER): The number of words in the news."
},
{
"code": null,
"e": 2974,
"s": 2732,
"text": "These fields are all calculated upon serving the prediction’s online request by our application. If you’re interested in knowing how those metrics were calculated in the first place, you can take a look at app.py at the project’s repository."
},
{
"code": null,
"e": 3114,
"s": 2974,
"text": "From these fields, we can set up an online dashboard with Google Data Studio to constantly monitor some indicators of our prediction model:"
},
{
"code": null,
"e": 3402,
"s": 3114,
"text": "Data Studio has a very intuitive interface. In this example, we’re using only one data source, which is the model prediction table at BigQuery. So, from a blank dashboard, we can add a data source by simply clicking the Add Data button at the top, and then selecting the BigQuery option."
},
{
"code": null,
"e": 3667,
"s": 3402,
"text": "I chose not to display charts related to ground_truth , as this field can be frequently empty if there’s not an intention of retraining the model in the near future. But if labeling is done constantly, a Confusion Matrix would be a great addition to our dashboard."
},
{
"code": null,
"e": 3956,
"s": 3667,
"text": "In this example, since I don’t have a great number of records, we shouldn’t draw any statistical conclusion from these numbers. Hopefully, in the future, with more daily predictions, these charts will be more informative. Nonetheless, let’s go by and discuss each one of these indicators:"
},
{
"code": null,
"e": 4161,
"s": 3956,
"text": "This is simply the number of predictions the application has served until now. To create it, go to Add a Chart at the top and select scorecard. Choose your table as Data Source and Record Count as Metric."
},
{
"code": null,
"e": 4331,
"s": 4161,
"text": "This is the percentage of records that have been manually labeled. This is important for the next step of retraining. Without ground truth, you can’t retrain your model."
},
{
"code": null,
"e": 4499,
"s": 4331,
"text": "Like Records, this is also a scorecard. But for this one, you have to create a new calculated field, by clicking ADD A FIELD at the bottom of the scorecard’s DATA tab:"
},
{
"code": null,
"e": 4575,
"s": 4499,
"text": "Then, just select the newly-created field as your Metric, just like before."
},
{
"code": null,
"e": 4697,
"s": 4575,
"text": "The name of the last prediction’s model. Assumes we have only one application, and there can only be one model at a time."
},
{
"code": null,
"e": 4949,
"s": 4697,
"text": "This indicator is actually a Table chart, rather than a scorecard. As Dimension, select modeland prediction_date, then set Rows per page as 1 and then sort prediction_date in Descending order. Then you should hide everything possible at the STYLE tab."
},
{
"code": null,
"e": 4988,
"s": 4949,
"text": "The Real/Fake prediction’s percentage."
},
{
"code": null,
"e": 5110,
"s": 4988,
"text": "To create it, go to Add a Chart → Pie. Choose prediction as Dimension, and Record_count as Metric, and you’re good to go."
},
{
"code": null,
"e": 5505,
"s": 5110,
"text": "This graph shows us the average of two values over time, on a weekly basis: confidenceand coverage. From this, we should be able to see an unusual change in the model’s level of confidence in its predictions, and also how much of the news is present on the trained model’s vocabulary. If the coverage has a descending trend and goes below a predefined threshold, it might be time to retrain it."
},
{
"code": null,
"e": 5871,
"s": 5505,
"text": "This one’s a Time series. On the Dimension field, at the little calendar icon, you should be able to set the period. I chose ISO Year Week. As Metric, choose confidence as the first one, and AVG as aggregation for the metric. Then, go to Add metric and do the same with coverage. At the STYLE tab, you can change both series from Lines to Bars and set their colors."
},
{
"code": null,
"e": 6102,
"s": 5871,
"text": "This chart groups records by the number of words, according to each prediction category. Even though we need more data to have a real grasp of the word count distribution, it seems that Fake news is usually shorter than Real ones."
},
{
"code": null,
"e": 6583,
"s": 6102,
"text": "Another strange detail is that there are 5 Fake predictions with a word count between 0–100. That seems a little low for a piece of news, which led me to investigate further. I eventually found out that these records were extracted from the same website, and they all had a parsing error. The content was not the actual news, but rather an error message. This is important, and we should make sure that these kinds of records will never be ingested into our training-test dataset."
},
{
"code": null,
"e": 6762,
"s": 6583,
"text": "That was the closest I got to making a histogram at Data Studio. To create one go to Chart → Bar, and add a new field, at the bottom of the DATA tab. In the formula field, enter:"
},
{
"code": null,
"e": 6788,
"s": 6762,
"text": "FLOOR(word_count/100)*100"
},
{
"code": null,
"e": 7112,
"s": 6788,
"text": "For each record, the word count will be divided by 100, and then the largest integral value of the result is multiplied by 100. That will put the records into bins of hundreds. I named that field wc_bin. You can use it as the Dimension, and Record Count as Metric. You should also set Sort to Ascending, and choose wc_bin ."
},
{
"code": null,
"e": 7237,
"s": 7112,
"text": "To split the histograms into Fake and Real, you can go to Add a Filter, right below Sort, and insert a filter like this one:"
},
{
"code": null,
"e": 7285,
"s": 7237,
"text": "And just do the opposite for the next category."
},
{
"code": null,
"e": 7596,
"s": 7285,
"text": "Alright, now we have a way to check on our model’s health. If something is out of the usual, we could start labeling some of the records and take a look at some important classification metrics, such as Precision, Recall, and F-score. If you’re not happy with the results, we should start retraining the model."
},
{
"code": null,
"e": 7680,
"s": 7596,
"text": "The image below is an overview of the retraining process I set up for this project:"
},
{
"code": null,
"e": 8335,
"s": 7680,
"text": "We have our Base Data, the original dataset we used in order to train our first prediction model. In addition, the application is constantly feeding us data from the online predictions. So, in order to retrain the model, we can extract this data and do some simple preprocessing, such as removing duplicate news. It is also very important to validate our data and make sure it complies with some assumptions we have regarding the data’s shape and distribution. Then, we move on by joining both data sources to finally retrain the model. Before replacing the old model, we must evaluate the newly-trained model with a test set to make sure of its quality."
},
{
"code": null,
"e": 8624,
"s": 8335,
"text": "Every time we wish to retrain the model, we follow these steps. But if we notice something wrong in the future, how do we debug our model? To do so, we need an orderly manner to store our model and data artifacts, in addition to the model’s performance results and code that generated it."
},
{
"code": null,
"e": 8880,
"s": 8624,
"text": "Managing data pipelines in an ML Application is not an easy task. Unlike traditional software development, where GIT has become the standard for code versioning, data versioning is still at its early stages, and there’s not a “definitive” way of doing so."
},
{
"code": null,
"e": 9307,
"s": 8880,
"text": "I decided to treat each retraining process as a single experiment and store the artifacts of each experiment in a single branch. This is a little different from what we’re used to with code versioning because in this case, I don’t expect to merge the branches back into the trunk. They are short-lived branches with the purpose of versioning our artifacts — datasets and models — according to different retraining experiments."
},
{
"code": null,
"e": 9814,
"s": 9307,
"text": "Even though there are a number of MLOps tools that provide data versioning functionality, such as MLflow and W&B, I opted to tackle data versioning as an infrastructure, by enabling Git-like operations over my object storage. For that purpose, I decided to try out the recently-released lakeFS, which enables me to add the Git-like engine on top of my existing S3 object storage. That way, my data versioning capability for the project is independent of any tools that I might add or replace in the future."
},
{
"code": null,
"e": 9884,
"s": 9814,
"text": "You can find the instructions to set up your lakeFS environment here."
},
{
"code": null,
"e": 9904,
"s": 9884,
"text": "I basically had to:"
},
{
"code": null,
"e": 9984,
"s": 9904,
"text": "Create a PostgreSQL database on AWS RDSConfigure an S3 bucket for my repository"
},
{
"code": null,
"e": 10024,
"s": 9984,
"text": "Create a PostgreSQL database on AWS RDS"
},
{
"code": null,
"e": 10065,
"s": 10024,
"text": "Configure an S3 bucket for my repository"
},
{
"code": null,
"e": 10236,
"s": 10065,
"text": "For the policy’s Principal, I created a user and created access keys for it. I’ll also use this user to authenticate lakeFS to AWS. You can read more about here and here."
},
{
"code": null,
"e": 10254,
"s": 10236,
"text": "3. Install lakeFS"
},
{
"code": null,
"e": 10316,
"s": 10254,
"text": "I chose to install it via Docker, with the following command:"
},
{
"code": null,
"e": 10768,
"s": 10316,
"text": "docker run --name lakefs -p 8000:8000-e LAKEFS_DATABASE_CONNECTION_STRING=\"<postgres-connection-str>\"-e LAKEFS_AUTH_ENCRYPT_SECRET_KEY=\"<lakefs-secret-key>\"-e LAKEFS_BLOCKSTORE_TYPE=\"s3\"-e LAKEFS_GATEWAYS_S3_DOMAIN_NAME=\"s3.local.lakefs.io\"-e LAKEFS_BLOCKSTORE_S3_CREDENTIALS_ACCESS_SECRET_KEY=\"<s3-secret-key>\"-e LAKEFS_BLOCKSTORE_S3_CREDENTIALS_ACCESS_KEY_ID=\"<s3-access-key>\" -e LAKEFS_BLOCKSTORE_S3_REGION=\"<s3-region>\" treeverse/lakefs:latest run"
},
{
"code": null,
"e": 11082,
"s": 10768,
"text": "Where postgres-connection-str is the connection string you obtained creating the PostgreSQL DB, lakefs-secret-key is any randomly generated string (just don’t forget it), s3-secret-key and s3-access-key are the key-pair you created for your AWS User earlier, and s3-region is the region of the bucket you created."
},
{
"code": null,
"e": 11091,
"s": 11082,
"text": "4. Setup"
},
{
"code": null,
"e": 11231,
"s": 11091,
"text": "At localhost:8000, after setting a new administrator user and creating the repository, you should be able to see your list of repositories:"
},
{
"code": null,
"e": 11369,
"s": 11231,
"text": "Now that we have everything set up, we need to translate that flowchart into a series of steps and implement it. We’ll basically need to:"
},
{
"code": null,
"e": 11413,
"s": 11369,
"text": "Get data from online predictions (BigQuery)"
},
{
"code": null,
"e": 11464,
"s": 11413,
"text": "Clean and assert data quality (Great Expectations)"
},
{
"code": null,
"e": 11505,
"s": 11464,
"text": "Create a new branch from master (lakeFS)"
},
{
"code": null,
"e": 11556,
"s": 11505,
"text": "Upload online predictions to a new branch (lakeFS)"
},
{
"code": null,
"e": 11598,
"s": 11556,
"text": "Get base data from master branch (lakeFS)"
},
{
"code": null,
"e": 11668,
"s": 11598,
"text": "Join online predictions to base data and split to train-test datasets"
},
{
"code": null,
"e": 11712,
"s": 11668,
"text": "Upload train-test splits to branch (lakeFS)"
},
{
"code": null,
"e": 11749,
"s": 11712,
"text": "Train model with the updated dataset"
},
{
"code": null,
"e": 11778,
"s": 11749,
"text": "Log Experiment/Results (W&B)"
},
{
"code": null,
"e": 11825,
"s": 11778,
"text": "Upload Model and Vocabulary to branch (lakeFS)"
},
{
"code": null,
"e": 11859,
"s": 11825,
"text": "Commit changes to branch (lakeFS)"
},
{
"code": null,
"e": 12180,
"s": 11859,
"text": "As for our data structure, we’ll define as external data our original dataset as well as data extracted from the web app’s online predictions. The interim folder will keep our data once the external sources are combined and split into appropriate train-test sets. The model files will also be stored in their own folder."
},
{
"code": null,
"e": 12486,
"s": 12180,
"text": "First, we need to get the new data from our BigQuery table. To use the Python APIs for accessing BigQuery, I need GCP credentials in JSON format. After creating a project, you can follow these instructions on “creating a service account” in this Google documentation in order to download your credentials."
},
{
"code": null,
"e": 12831,
"s": 12486,
"text": "Then, installing google-cloud-bigquery and setting an environment variable indicating the location of your credentials and initiating the BigQuery client should be enough for you to query your table. In this case, sunny-emissary-293912 is the name of my project, fakenewsdeploy the name of my dataset and model_predictions the name of my table."
},
{
"code": null,
"e": 13129,
"s": 12831,
"text": "We should always ensure the quality of data ingested into our storage. A great way to do that is using the tool Great Expectations. After I do some very simple cleaning, like removing duplicate news and news with low word count, we can do some basic assumptions about what we expect from our data."
},
{
"code": null,
"e": 13639,
"s": 13129,
"text": "In this example, we’ll only keep going with our retraining if our data passes some validations. The ground_truth should assume only Fake or Real values, the url value should be unique and every sample should have a non-null content. In addition, we assume that an excessively low coverage must be investigated, as it might be a sign of parsing errors, or maybe content in another language. Finally, the word_count should be above 100, as we have discussed previously in the Monitoring section of this article."
},
{
"code": null,
"e": 13864,
"s": 13639,
"text": "We can then generate an expectation_suite , which gives us a JSON file showing the validations passed by our data. We should also make sure to store this information for future reference (which will be done in the sequence)."
},
{
"code": null,
"e": 13983,
"s": 13864,
"text": "We are only scratching the surface with Great Expectations here. Check out their website to know more functionalities."
},
{
"code": null,
"e": 14358,
"s": 13983,
"text": "Now that we trust our data, we can store it in a newly-created branch. In the early stages of Model Building/Evaluation of this project, I used W&B to track my experiments. I’ll keep using it during the retraining process, in conjunction with lakeFS. This way, the experiment identifier is the wandb’s run name, and I’ll just use the same name in order to create the branch:"
},
{
"code": null,
"e": 14712,
"s": 14358,
"text": "Two things to point out here. In line 3, while starting the run, you see I configured a threshold. That’s for a nice W&B functionality where I can set up a threshold to be monitored during training. In this case, if the F1-Score of the trained model is below 0.9, W&B will send me an email letting me know. We’ll see the rest of it in the training code."
},
{
"code": null,
"e": 15039,
"s": 14712,
"text": "Another important issue here is how I’m doing operations at my lakeFS repository. This can be done in several different ways, but I chose to use the Python client. I created a lakefs_connector class to wrap the APIs into more tailored functions for my application. The class implementation is shown at the end of this article."
},
{
"code": null,
"e": 15166,
"s": 15039,
"text": "Let’s keep going by uploading online_predictions.csv to our branch. We’ll also save my_expectation_file.json to our wandb run."
},
{
"code": null,
"e": 15316,
"s": 15166,
"text": "Now we can access our expectation file whenever we need it, and make sure that the data’s state at this particular run complies with our assumptions:"
},
{
"code": null,
"e": 15540,
"s": 15316,
"text": "Our base data is comprised of two files: True.csv and Fake.csv, both previously uploaded into our master branch. Let’s append the data from online_predictions.csv to our base data and then split it into train-test datasets:"
},
{
"code": null,
"e": 15648,
"s": 15540,
"text": "The last series of steps is to finally train the model and upload our artifacts to the repository’s branch:"
},
{
"code": null,
"e": 15835,
"s": 15648,
"text": "We’ll upload the train-test splits as well as our model’s files — the actual joblib model and the vocabulary used for our Vectorizer (which is also used to calculate our coverage field)."
},
{
"code": null,
"e": 16061,
"s": 15835,
"text": "You can check the whole code for training the model here. I won’t get into specifics, since I already covered it in my previous article. I just want to point out an excerpt of it, related to the alert configuration we set up:"
},
{
"code": null,
"e": 16307,
"s": 16061,
"text": "f1_score is the calculated F1-Score during the training process. Since we set up the threshold of 0.9 previously, if the score for this run ends up below this value, an alert will be sent to the configured destination. In my case, it’s my email:"
},
{
"code": null,
"e": 16373,
"s": 16307,
"text": "Now, what is left to do is to commit our changes into our branch:"
},
{
"code": null,
"e": 16459,
"s": 16373,
"text": "And we’ll have our data separated according to our retraining experiments, like this:"
},
{
"code": null,
"e": 16587,
"s": 16459,
"text": "Since the run names are unique, we can easily match the data with our retraining’s results at our experiments dashboard at W&B:"
},
{
"code": null,
"e": 16895,
"s": 16587,
"text": "In the code snippets above, we have done some operations to our repository, such as creating branches, downloading and uploading objects, and committing changes. To do so, I used bravado to generate a dynamic client, as instructed here. This way we have access to all of the lakeFS’ APIs as Python commands."
},
{
"code": null,
"e": 17034,
"s": 16895,
"text": "By instantiating the lakefs_conn class, we create a lakeFS client, and do the required repository operations through the object’s methods:"
},
{
"code": null,
"e": 17316,
"s": 17034,
"text": "I wanted to share with you my take on monitoring my model’s performance and retraining it, but this is really the first step of a long process. As time goes on, the additional data enables us to have more insights, and we eventually discover better ways to monitor our application."
},
{
"code": null,
"e": 17609,
"s": 17316,
"text": "For example, in the future, we could plot the performance of multiple retrained models and compare them over time, to more accurately assess the impact of time over our predictions. Or, given enough ground truth information, we could add metrics such as precision and recall to our dashboard."
},
{
"code": null,
"e": 18003,
"s": 17609,
"text": "As for the retraining part, much can be improved. As we discover more about our data’s distribution, additional expectations can be added to our assertion stage. The addition of hooks for automatic pre-commit validation is also a natural evolution. Webhooks weren’t yet supported by lakeFS during the writing of this article, but it’s already an available feat since the latest release (0.33)."
},
{
"code": null,
"e": 18085,
"s": 18003,
"text": "That’s it for now! If you have any feedback or questions, feel free to reach out!"
},
{
"code": null,
"e": 18108,
"s": 18085,
"text": "Thank you for reading!"
},
{
"code": null,
"e": 18149,
"s": 18108,
"text": "Continuous Delivery for Machine Learning"
},
{
"code": null,
"e": 18165,
"s": 18149,
"text": "Data Versioning"
},
{
"code": null,
"e": 18214,
"s": 18165,
"text": "Ensuring Data Quality in a Data Lake Environment"
},
{
"code": null,
"e": 18299,
"s": 18214,
"text": "The ML Test Score: A Rubric for ML Production Readiness and Technical Debt Reduction"
},
{
"code": null,
"e": 18348,
"s": 18299,
"text": "Why Data Versioning as an Infrastructure Matters"
},
{
"code": null,
"e": 18371,
"s": 18348,
"text": "lakeFS — Documentation"
},
{
"code": null,
"e": 18406,
"s": 18371,
"text": "Great Expectations — Documentation"
}
] |
XPath For Python | The RegEx of Web | Towards Data Science | XML path language (XPath) is a massively underappreciated tool in the world of web scraping and automation. Imagine RegEx, but for webpages — that is XPath.
Every element of a webpage is organized by the Document Object Model (DOM). The DOM is a tree-like structure, where each element represents a node, with paths to parent and child nodes.
XPath offers us a language for quickly traversing across this tree. And, like RegEx, we can add logic to our node selection to make our queries more powerful.
In this article, we will cover:
> XPath Essentials - Testing Our Queries - The Root - Paths in XPath> Navigating the Tree - Node Indexing - Extracting XPaths from the Browser> XPath Logic> Example with Python
First, before we do anything else, we need to understand how we can test our XPath strings. Fortunately, we can do that right here in the web browser.
I’ll be using Chrome throughout this article, but the procedure is very similar across all modern browsers.
On our webpage, we open Developer Tools — either by clicking Fn+12 on Windows or opening it from your browser options menu (see for Chrome above).
Next, we click ctrl+F to open the search bar within our Elements window. Here we can search by string, selector, or XPath.
This method is the easiest way to test our XPath queries quickly.
If our query matches something, that element will be highlighted yellow. Where our query matches multiple elements, we can cycle through them using the arrows to the right of the search bar!
Let’s start with the very beginning of our query. In the case of //div — what does the // mean?
Every XPath query begins at the root of our XML tree — the very top element. For HTML documents, this is the <html> tag.
Now, if we write html//div we are saying “look for any descendant node of html that is a div”.
The result is that both html/div and html/body/div/div/article/div/div will be found with our query. This is because in both cases, we see a div which is a descendant of html.
Because our XPath query always begins at the root (html), we don’t need to write html//div. Instead, we write //div.
The // example we just used is called a path expression. There’s a few of these, and they’re super useful:
// — match any descendent node
/ — match only the child nodes (nodes directly following another):
. — matches the currently active node (more on this later)
.. — matches the parent node of the currently active node
@ — select an attribute of the current node (href for example):
With a combination of these path expressions, we can traverse across the XML tree with ease.
For example, back to our example HTML section — we can select the a tag by finding the span tag with attribute class="u-textScreenReader", and traversing up the tree to its parent node, like so:
Every node in our DOM is numbered. If we have a list ul which contains five li items, we can access each of those items specifically by indexing from 1 to 5:
<ul> <li>London</li> <li>Miami</li> <li>New Dehli</li></li>
If we query //ul/li[1] we will return <li>London</li> — note that values are not zero-indexed. XPath indexing begins at 1.
An incredibly convenient feature in Chrome (and likely most modern browsers) is the ability to get the XPath of a node directly from the Elements window.
To do this, we right-click on the element we want the XPath for and click Copy > Copy XPath and paste the XPath for that element. Our span element returns:
//*[@id="_obv.shell._surface_1600536527994"]/div/div[1]/div[2] /div[1]/div[1]/a/span[1]
Alternatively, we can copy the full XPath, which provides the full path from the root to our element. For our span element this looks like:
/html/body/div[1]/div[2]/div/div[1]/div[2]/div[1]/div[1]/a/span[1]
Now, whether you want to call the following methods ‘advanced’ or not is debatable.
However, I justify this because, by using the previous Path Expressions alone, we can traverse the DOM very easily. In many cases, we won’t need anything more. But now and then, these ‘advanced’ methods can be incredibly useful.
There are many XPath functions that we won’t cover here, but a few of the most common ones are:
contains — searches for string A in string B, where contains(B, A):
not — we use this to negate parts of our query, like if we would like all span elements that don’t contain the class svgIcon-use:
boolean — the equal and opposite of not, if we would like all span elements that do contain an svg child node:
starts-with — similar to contains, but rather than containing string A, string B must start with string A.
ends-with — I’m sure you can figure this one out
These functions are just a scratch on the surface of XPath. A few items we haven’t even touched upon (I’ve added links to articles on them though):
More XPath axes
XPath operators
Selecting unknown nodes
Full list of XPath functions
Selenium is the best way to get familiar with XPath in Python (it is available for many other languages too). If you are not familiar with it, I wrote this article covering the setup and basics of the framework — it’s very easy to work with!
Once we have Selenium setup, we can select all elements of a webpage that satisfy an XPath query using the find_elements_by_xpath method.
We’ll try this out on webscraper.io. There, we can see that every item is contained in a div element with class="thumbnail". Here, we’ve highlighted the Acer Aspire product.
So, back to Selenium and XPath. First, we need to initialize our web driver and navigate to the Web Scraper training site:
from selenium import webdriverdriver = webdriver.Chrome('chromedriver.exe')driver.get('https://webscraper.io/test-sites/e-commerce/scroll')
Now, we need to select all div elements with class thumbnail:
shop_elems = driver.find_elements_by_xpath( "//div[@class='thumbnail']")
If we print out the value of shop_elems we will return a list of WebElement objects:
Great, we have our shop container WebElements — now what? Well, we can treat these objects as individual XML trees.
We do this using the WebElement get_element method coupled with By.XPATH — which is a new import:
from selenium.webdriver.common.by import Byshop_elems[0].get_element(By.XPATH, <XPath Query Here>)
Here, we are setting the first instance of div[@class="thumbnail"] as active, and we can use . to select the currently active node in an XPath query.
We can use this new method to loop through every item container on the page and extract details for each one iteratively!
Let’s try extracting the item name for each of our WebElements in shop_elems.
Back in the browser, we can find item names in descendant <a> tags. As there are no other descendant <a> tags, we can select this element with just //a. This gives us //div[@class='thumbnail']//a.
In our code, the WebElements contained in shop_elems have set div[@class='thumbnail'] as their active node, which we select with .:
shop_elems[0].find_element(By.XPATH, ".//a")
To get the item name, we simply access the text value of our object. We can integrate that into a for-loop to pull every item name from our WebScraper.io e-commerce page:
And that’s it; we’ve extracted the item name of product on our e-commerce front-page with XPath and Selenium. We can couple this with more XPath queries to extract more information, like the price, rating, number of reviews, etc.
That’s it for this introduction to XPath and Selenium. We’ve covered:
DOM, nodes, and branches
Testing XPath queries — Fn+12, Ctrl+F
Navigating the tree
Pulling XPaths from the browser
Some more advanced XPath logic
As I said before, this just scratches the surface of XPath, and I would definitely recommend working on your own little web scraping/automation projects and learning more!
I hope you enjoyed the article. If you have any ideas or questions, let me know via Twitter or in the comments below! If you’d like more content like this, I post on YouTube too.
Thanks for reading!
*All images are by the author unless stated otherwise. | [
{
"code": null,
"e": 329,
"s": 172,
"text": "XML path language (XPath) is a massively underappreciated tool in the world of web scraping and automation. Imagine RegEx, but for webpages — that is XPath."
},
{
"code": null,
"e": 515,
"s": 329,
"text": "Every element of a webpage is organized by the Document Object Model (DOM). The DOM is a tree-like structure, where each element represents a node, with paths to parent and child nodes."
},
{
"code": null,
"e": 674,
"s": 515,
"text": "XPath offers us a language for quickly traversing across this tree. And, like RegEx, we can add logic to our node selection to make our queries more powerful."
},
{
"code": null,
"e": 706,
"s": 674,
"text": "In this article, we will cover:"
},
{
"code": null,
"e": 888,
"s": 706,
"text": "> XPath Essentials - Testing Our Queries - The Root - Paths in XPath> Navigating the Tree - Node Indexing - Extracting XPaths from the Browser> XPath Logic> Example with Python"
},
{
"code": null,
"e": 1039,
"s": 888,
"text": "First, before we do anything else, we need to understand how we can test our XPath strings. Fortunately, we can do that right here in the web browser."
},
{
"code": null,
"e": 1147,
"s": 1039,
"text": "I’ll be using Chrome throughout this article, but the procedure is very similar across all modern browsers."
},
{
"code": null,
"e": 1294,
"s": 1147,
"text": "On our webpage, we open Developer Tools — either by clicking Fn+12 on Windows or opening it from your browser options menu (see for Chrome above)."
},
{
"code": null,
"e": 1417,
"s": 1294,
"text": "Next, we click ctrl+F to open the search bar within our Elements window. Here we can search by string, selector, or XPath."
},
{
"code": null,
"e": 1483,
"s": 1417,
"text": "This method is the easiest way to test our XPath queries quickly."
},
{
"code": null,
"e": 1674,
"s": 1483,
"text": "If our query matches something, that element will be highlighted yellow. Where our query matches multiple elements, we can cycle through them using the arrows to the right of the search bar!"
},
{
"code": null,
"e": 1770,
"s": 1674,
"text": "Let’s start with the very beginning of our query. In the case of //div — what does the // mean?"
},
{
"code": null,
"e": 1891,
"s": 1770,
"text": "Every XPath query begins at the root of our XML tree — the very top element. For HTML documents, this is the <html> tag."
},
{
"code": null,
"e": 1986,
"s": 1891,
"text": "Now, if we write html//div we are saying “look for any descendant node of html that is a div”."
},
{
"code": null,
"e": 2162,
"s": 1986,
"text": "The result is that both html/div and html/body/div/div/article/div/div will be found with our query. This is because in both cases, we see a div which is a descendant of html."
},
{
"code": null,
"e": 2279,
"s": 2162,
"text": "Because our XPath query always begins at the root (html), we don’t need to write html//div. Instead, we write //div."
},
{
"code": null,
"e": 2386,
"s": 2279,
"text": "The // example we just used is called a path expression. There’s a few of these, and they’re super useful:"
},
{
"code": null,
"e": 2417,
"s": 2386,
"text": "// — match any descendent node"
},
{
"code": null,
"e": 2484,
"s": 2417,
"text": "/ — match only the child nodes (nodes directly following another):"
},
{
"code": null,
"e": 2543,
"s": 2484,
"text": ". — matches the currently active node (more on this later)"
},
{
"code": null,
"e": 2601,
"s": 2543,
"text": ".. — matches the parent node of the currently active node"
},
{
"code": null,
"e": 2665,
"s": 2601,
"text": "@ — select an attribute of the current node (href for example):"
},
{
"code": null,
"e": 2758,
"s": 2665,
"text": "With a combination of these path expressions, we can traverse across the XML tree with ease."
},
{
"code": null,
"e": 2953,
"s": 2758,
"text": "For example, back to our example HTML section — we can select the a tag by finding the span tag with attribute class=\"u-textScreenReader\", and traversing up the tree to its parent node, like so:"
},
{
"code": null,
"e": 3111,
"s": 2953,
"text": "Every node in our DOM is numbered. If we have a list ul which contains five li items, we can access each of those items specifically by indexing from 1 to 5:"
},
{
"code": null,
"e": 3180,
"s": 3111,
"text": "<ul> <li>London</li> <li>Miami</li> <li>New Dehli</li></li>"
},
{
"code": null,
"e": 3303,
"s": 3180,
"text": "If we query //ul/li[1] we will return <li>London</li> — note that values are not zero-indexed. XPath indexing begins at 1."
},
{
"code": null,
"e": 3457,
"s": 3303,
"text": "An incredibly convenient feature in Chrome (and likely most modern browsers) is the ability to get the XPath of a node directly from the Elements window."
},
{
"code": null,
"e": 3613,
"s": 3457,
"text": "To do this, we right-click on the element we want the XPath for and click Copy > Copy XPath and paste the XPath for that element. Our span element returns:"
},
{
"code": null,
"e": 3701,
"s": 3613,
"text": "//*[@id=\"_obv.shell._surface_1600536527994\"]/div/div[1]/div[2] /div[1]/div[1]/a/span[1]"
},
{
"code": null,
"e": 3841,
"s": 3701,
"text": "Alternatively, we can copy the full XPath, which provides the full path from the root to our element. For our span element this looks like:"
},
{
"code": null,
"e": 3908,
"s": 3841,
"text": "/html/body/div[1]/div[2]/div/div[1]/div[2]/div[1]/div[1]/a/span[1]"
},
{
"code": null,
"e": 3992,
"s": 3908,
"text": "Now, whether you want to call the following methods ‘advanced’ or not is debatable."
},
{
"code": null,
"e": 4221,
"s": 3992,
"text": "However, I justify this because, by using the previous Path Expressions alone, we can traverse the DOM very easily. In many cases, we won’t need anything more. But now and then, these ‘advanced’ methods can be incredibly useful."
},
{
"code": null,
"e": 4317,
"s": 4221,
"text": "There are many XPath functions that we won’t cover here, but a few of the most common ones are:"
},
{
"code": null,
"e": 4385,
"s": 4317,
"text": "contains — searches for string A in string B, where contains(B, A):"
},
{
"code": null,
"e": 4515,
"s": 4385,
"text": "not — we use this to negate parts of our query, like if we would like all span elements that don’t contain the class svgIcon-use:"
},
{
"code": null,
"e": 4626,
"s": 4515,
"text": "boolean — the equal and opposite of not, if we would like all span elements that do contain an svg child node:"
},
{
"code": null,
"e": 4733,
"s": 4626,
"text": "starts-with — similar to contains, but rather than containing string A, string B must start with string A."
},
{
"code": null,
"e": 4782,
"s": 4733,
"text": "ends-with — I’m sure you can figure this one out"
},
{
"code": null,
"e": 4930,
"s": 4782,
"text": "These functions are just a scratch on the surface of XPath. A few items we haven’t even touched upon (I’ve added links to articles on them though):"
},
{
"code": null,
"e": 4946,
"s": 4930,
"text": "More XPath axes"
},
{
"code": null,
"e": 4962,
"s": 4946,
"text": "XPath operators"
},
{
"code": null,
"e": 4986,
"s": 4962,
"text": "Selecting unknown nodes"
},
{
"code": null,
"e": 5015,
"s": 4986,
"text": "Full list of XPath functions"
},
{
"code": null,
"e": 5257,
"s": 5015,
"text": "Selenium is the best way to get familiar with XPath in Python (it is available for many other languages too). If you are not familiar with it, I wrote this article covering the setup and basics of the framework — it’s very easy to work with!"
},
{
"code": null,
"e": 5395,
"s": 5257,
"text": "Once we have Selenium setup, we can select all elements of a webpage that satisfy an XPath query using the find_elements_by_xpath method."
},
{
"code": null,
"e": 5569,
"s": 5395,
"text": "We’ll try this out on webscraper.io. There, we can see that every item is contained in a div element with class=\"thumbnail\". Here, we’ve highlighted the Acer Aspire product."
},
{
"code": null,
"e": 5692,
"s": 5569,
"text": "So, back to Selenium and XPath. First, we need to initialize our web driver and navigate to the Web Scraper training site:"
},
{
"code": null,
"e": 5832,
"s": 5692,
"text": "from selenium import webdriverdriver = webdriver.Chrome('chromedriver.exe')driver.get('https://webscraper.io/test-sites/e-commerce/scroll')"
},
{
"code": null,
"e": 5894,
"s": 5832,
"text": "Now, we need to select all div elements with class thumbnail:"
},
{
"code": null,
"e": 5970,
"s": 5894,
"text": "shop_elems = driver.find_elements_by_xpath( \"//div[@class='thumbnail']\")"
},
{
"code": null,
"e": 6055,
"s": 5970,
"text": "If we print out the value of shop_elems we will return a list of WebElement objects:"
},
{
"code": null,
"e": 6171,
"s": 6055,
"text": "Great, we have our shop container WebElements — now what? Well, we can treat these objects as individual XML trees."
},
{
"code": null,
"e": 6269,
"s": 6171,
"text": "We do this using the WebElement get_element method coupled with By.XPATH — which is a new import:"
},
{
"code": null,
"e": 6368,
"s": 6269,
"text": "from selenium.webdriver.common.by import Byshop_elems[0].get_element(By.XPATH, <XPath Query Here>)"
},
{
"code": null,
"e": 6518,
"s": 6368,
"text": "Here, we are setting the first instance of div[@class=\"thumbnail\"] as active, and we can use . to select the currently active node in an XPath query."
},
{
"code": null,
"e": 6640,
"s": 6518,
"text": "We can use this new method to loop through every item container on the page and extract details for each one iteratively!"
},
{
"code": null,
"e": 6718,
"s": 6640,
"text": "Let’s try extracting the item name for each of our WebElements in shop_elems."
},
{
"code": null,
"e": 6915,
"s": 6718,
"text": "Back in the browser, we can find item names in descendant <a> tags. As there are no other descendant <a> tags, we can select this element with just //a. This gives us //div[@class='thumbnail']//a."
},
{
"code": null,
"e": 7047,
"s": 6915,
"text": "In our code, the WebElements contained in shop_elems have set div[@class='thumbnail'] as their active node, which we select with .:"
},
{
"code": null,
"e": 7092,
"s": 7047,
"text": "shop_elems[0].find_element(By.XPATH, \".//a\")"
},
{
"code": null,
"e": 7263,
"s": 7092,
"text": "To get the item name, we simply access the text value of our object. We can integrate that into a for-loop to pull every item name from our WebScraper.io e-commerce page:"
},
{
"code": null,
"e": 7493,
"s": 7263,
"text": "And that’s it; we’ve extracted the item name of product on our e-commerce front-page with XPath and Selenium. We can couple this with more XPath queries to extract more information, like the price, rating, number of reviews, etc."
},
{
"code": null,
"e": 7563,
"s": 7493,
"text": "That’s it for this introduction to XPath and Selenium. We’ve covered:"
},
{
"code": null,
"e": 7588,
"s": 7563,
"text": "DOM, nodes, and branches"
},
{
"code": null,
"e": 7626,
"s": 7588,
"text": "Testing XPath queries — Fn+12, Ctrl+F"
},
{
"code": null,
"e": 7646,
"s": 7626,
"text": "Navigating the tree"
},
{
"code": null,
"e": 7678,
"s": 7646,
"text": "Pulling XPaths from the browser"
},
{
"code": null,
"e": 7709,
"s": 7678,
"text": "Some more advanced XPath logic"
},
{
"code": null,
"e": 7881,
"s": 7709,
"text": "As I said before, this just scratches the surface of XPath, and I would definitely recommend working on your own little web scraping/automation projects and learning more!"
},
{
"code": null,
"e": 8060,
"s": 7881,
"text": "I hope you enjoyed the article. If you have any ideas or questions, let me know via Twitter or in the comments below! If you’d like more content like this, I post on YouTube too."
},
{
"code": null,
"e": 8080,
"s": 8060,
"text": "Thanks for reading!"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.