title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Transform data from a nested array to an object in JavaScript
Suppose, we have the following array of arrays − const arr = [ [ ['dog', 'Harry'], ['age', 2] ], [ ['dog', 'Roger'], ['age', 5] ] ]; We are required to write a JavaScript function that takes in one such nested array. The function should then prepare an object based on the array. The object for the above array should look like − const output = [ {dog: 'Harry', age: 2}, {dog: 'Roger', age: 5} ]; The code for this will be − const arr = [ [ ['dog', 'Harry'], ['age', 2] ], [ ['dog', 'Roger'], ['age', 5] ] ]; const prepareObjectArray = (arr = []) => { const copy = arr.slice(); copy.forEach((el, ind, array) => { el.forEach((element, index, subArray) => { subArray[element[0]] = element[1]; }); el.length = 0; array[ind] = Object.assign({}, array[ind]); }); return copy; }; console.log(prepareObjectArray(arr)); And the output in the console will be − [ { dog: 'Harry', age: 2 }, { dog: 'Roger', age: 5 } ]
[ { "code": null, "e": 1111, "s": 1062, "text": "Suppose, we have the following array of arrays −" }, { "code": null, "e": 1219, "s": 1111, "text": "const arr = [\n [\n ['dog', 'Harry'], ['age', 2]\n ],\n [\n ['dog', 'Roger'], ['age', 5]\n ]\n];" }, { "code": null, "e": 1366, "s": 1219, "text": "We are required to write a JavaScript function that takes in one such nested array. The function should then prepare an object based on the array." }, { "code": null, "e": 1416, "s": 1366, "text": "The object for the above array should look like −" }, { "code": null, "e": 1489, "s": 1416, "text": "const output = [\n {dog: 'Harry', age: 2},\n {dog: 'Roger', age: 5}\n];" }, { "code": null, "e": 1517, "s": 1489, "text": "The code for this will be −" }, { "code": null, "e": 1973, "s": 1517, "text": "const arr = [\n [\n ['dog', 'Harry'], ['age', 2]\n ],\n [\n ['dog', 'Roger'], ['age', 5]\n ]\n];\nconst prepareObjectArray = (arr = []) => {\n const copy = arr.slice();\n copy.forEach((el, ind, array) => {\n el.forEach((element, index, subArray) => {\n subArray[element[0]] = element[1];\n });\n el.length = 0;\n array[ind] = Object.assign({}, array[ind]);\n });\n return copy;\n};\nconsole.log(prepareObjectArray(arr));" }, { "code": null, "e": 2013, "s": 1973, "text": "And the output in the console will be −" }, { "code": null, "e": 2068, "s": 2013, "text": "[ { dog: 'Harry', age: 2 }, { dog: 'Roger', age: 5 } ]" } ]
Can we change return type of main() method in java?
The public static void main() method is the entry point of the Java program. Whenever you execute a program in Java, the JVM searches for the main method and starts executing from it. You can write the main method in your program with return type other than void, the program gets compiled without compilation errors. But, at the time of execution JVM does not consider this new method (with return type other than void) as the entry point of the program. It searches for the main method which is public, static, with return type void, and a String array as an argument. public static int main(String[] args){ } If such a method is not found, a run time error is generated. In the following Java program, we are trying to write the main method with the return type integer − Live Demo import java.util.Scanner; public class Sample{ public static int main(String[] args){ Scanner sc = new Scanner(System.in); int num = sc.nextInt(); System.out.println("This is a sample program"); return num; } } On executing, this program generates the following error − Error: Main method must return a value of type void in class Sample, please define the main method as: public static void main(String[] args)
[ { "code": null, "e": 1246, "s": 1062, "text": "The public static void main() method is the entry point of the Java program. Whenever you execute a program in Java, the JVM searches for the main method and starts executing from it." }, { "code": null, "e": 1381, "s": 1246, "text": "You can write the main method in your program with return type other than void, the program gets compiled without compilation errors. " }, { "code": null, "e": 1519, "s": 1381, "text": "But, at the time of execution JVM does not consider this new method (with return type other than void) as the entry point of the program." }, { "code": null, "e": 1634, "s": 1519, "text": "It searches for the main method which is public, static, with return type void, and a String array as an argument." }, { "code": null, "e": 1675, "s": 1634, "text": "public static int main(String[] args){\n}" }, { "code": null, "e": 1737, "s": 1675, "text": "If such a method is not found, a run time error is generated." }, { "code": null, "e": 1838, "s": 1737, "text": "In the following Java program, we are trying to write the main method with the return type integer −" }, { "code": null, "e": 1849, "s": 1838, "text": " Live Demo" }, { "code": null, "e": 2090, "s": 1849, "text": "import java.util.Scanner;\npublic class Sample{\n public static int main(String[] args){\n Scanner sc = new Scanner(System.in);\n int num = sc.nextInt();\n System.out.println(\"This is a sample program\");\n return num;\n }\n}" }, { "code": null, "e": 2149, "s": 2090, "text": "On executing, this program generates the following error −" }, { "code": null, "e": 2291, "s": 2149, "text": "Error: Main method must return a value of type void in class Sample, please\ndefine the main method as:\npublic static void main(String[] args)" } ]
Fractional Knapsack | Practice | GeeksforGeeks
Given weights and values of N items, we need to put these items in a knapsack of capacity W to get the maximum total value in the knapsack. Note: Unlike 0/1 knapsack, you are allowed to break the item. Example 1: Input: N = 3, W = 50 values[] = {60,100,120} weight[] = {10,20,30} Output: 220.00 Explanation:Total maximum value of item we can have is 240.00 from the given capacity of sack. Example 2: Input: N = 2, W = 50 values[] = {60,100} weight[] = {10,20} Output: 160.00 Explanation: Total maximum value of item we can have is 160.00 from the given capacity of sack. Your Task : Complete the function fractionalKnapsack() that receives maximum capacity , array of structure/class and size n and returns a double value representing the maximum value in knapsack. Note: The details of structure/class is defined in the comments above the given function. Expected Time Complexity : O(NlogN) Expected Auxilliary Space: O(1) Constraints: 1 <= N <= 105 1 <= W <= 105 0 sikkusaurav123in 8 hours This is correct but somewhere floating point mistake if someone find it please tag that thing : class Solution{ public: //Function to get the maximum total value in the knapsack. double fractionalKnapsack(int W, Item arr[], int n) { // Your code here vector<pair<float,int>>v; float profit=0.00; for(int i=0;i<n;i++) { v.push_back(make_pair((float(arr[i].value)/float(arr[i].weight)),i)); } sort(v.begin(),v.end()); reverse(v.begin(),v.end()); for(int i=0;i<n;i++) { if(W>0 && W>arr[v[i].second].weight) { profit=profit+float(arr[v[i].second].value); W=W-arr[v[i].second].weight; } else if(W>0 && W<arr[v[i].second].weight) { profit=profit+(float(arr[v[i].second].value)*float(float(W)/float(arr[v[i].second].weight))); W=W-arr[v[i].second].weight; } else if(W<=0) { break; } } return (profit); } }; 0 19003001002372 days ago class Solution{ public: static bool comp(Item a, Item b) { double r = (double)a.value/(double)a.weight; double r1 = (double)b.value/(double)b.weight; return r > r1; } //Function to get the maximum total value in the knapsack. double fractionalKnapsack(int W, Item arr[], int n) { // Your code here sort(arr,arr+n,comp); int cur_w = 0; double profit = 0.0; for(int i =0;i<n;i++) { if(cur_w + arr[i].weight <= W) { profit += arr[i].value; cur_w += arr[i].weight; } else { int remain = W - cur_w; profit += (double)remain/(double)arr[i].weight * arr[i].value; break; } } return profit; } }; 0 akshatjain232 days ago /* class Item { int value, weight; Item(int x, int y){ this.value = x; this.weight = y; } } */ class Solution { //Function to get the maximum total value in the knapsack. double fractionalKnapsack(int W, Item arr[], int n) { /* Sort the items in the descreasing order of there value per weight */ Arrays.sort(arr, new ItemComparator()); double max = 0; for(Item item : arr) { // If remaining capacity is 0, knapsack is full if( W == 0 ) break; /* If current item's weight not more than the capacity then include the item in the knapsack */ if( item.weight <= W ) { max += item.value; W -= item.weight; } else { /* Else store the fraction of the item updating remaining capacity */ max += (double)(item.value*W) / item.weight; W = 0; } } return max; } } class ItemComparator implements Comparator<Item> { @Override public int compare(Item item1, Item item2) { double valuePerWeight1 = (double)item1.value / item1.weight; double valuePerWeight2 = (double)item2.value / item2.weight; if( valuePerWeight2 > valuePerWeight1 ) { return 1; } else if( valuePerWeight2 < valuePerWeight1 ) { return -1; } return 0; } } +1 ksbsbisht1371 week ago static bool cmp(struct Item a,struct Item b) { double r1=(double)a.value/(double)a.weight; double r2=(double)b.value/(double)b.weight; if(r1<r2) return false; return true; } double fractionalKnapsack(int W, Item arr[], int n) { sort(arr,arr+n,cmp); double cost=0; for(int i=0;i<n;i++) { if(arr[i].weight<=W) { W-=arr[i].weight; cost+=arr[i].value; } else { cost+=((double)arr[i].value/(double)arr[i].weight)*W; break; } } return cost; } 0 ksbsbisht1371 week ago double fractionalKnapsack(int W, Item arr[], int n) { vector<pair<double,pair<int,int>>> vec; for(int i=0;i<n;i++) { vec.push_back({arr[i].value/(arr[i].weight*1.0),{arr[i].value,arr[i].weight}}); } sort(vec.begin(),vec.end(),greater<pair<double,pair<int,int>>> ()); double cost=0.0; for(int i=0;i<n;i++) { if(vec[i].second.second<=W) { W-=vec[i].second.second; cost+=vec[i].second.first; } else { if(W>0) { cost+=W*vec[i].first; break; } } } return cost; } 0 manasbass992 weeks ago def fractionalknapsack(self, W,Items,n): # code here res = 0.0 Items.sort(key=lambda x: -x.value/x.weight) for item in Items: if W >= item.weight: W -= item.weight res += item.value elif W > 0 and W<item.weight: res += item.value * W/item.weight W = 0 if W == 0: break return res 0 ponkey This comment was deleted. 0 dadwalabhishek101 month ago //You dont have to sort the values and put the complexity in nlogn and space comp O(N). Just use max heap and find out the value class Solution { public: //Function to get the maximum total value in the knapsack. double fractionalKnapsack(int W, Item arr[], int n) { // Your code here double ans = 0.0; priority_queue<pair<double, int>> pq; for(int i = 0;i<n;i++) { pq.push({(double)arr[i].value/(double)arr[i].weight, arr[i].weight}); } while(!pq.empty()) { if(W==0) return ans; int diff = min(pq.top().second, W); ans += diff*pq.top().first; W -= diff; pq.pop(); } return ans; } }; -1 gaurabhkumarjha271020011 month ago // easy c++ approach static bool comp (pair <double,double> a, pair<double,double> b){ double r= a.first / a.second; double r1= b.first/b.second; return r > r1; } double fractionalKnapsack(int W, Item arr[], int n) { vector <pair <double,double> > v; double res=0.0; for (int i=0; i< n; i++){ v.push_back ({arr[i].value, arr[i].weight}); } sort (v.begin(), v.end(), comp); for (int i=0; i< n; i++){ if (v[i].second <= W){ // first means value res+= v[i].first; // second means weight W-= v[i].second; }else{ if (W != 0) res+= (W* (v[i].first/v[i].second)); W=0; break; } } return res; } -1 badgujarsachin832 months ago static bool com(Item a,Item b){ double a1=(double)a.value/a.weight; double a2=(double)b.value/b.weight; return a1>a2; } //Function to get the maximum total value in the knapsack. double fractionalKnapsack(int W, Item arr[], int n) { // Your code here sort(arr,arr+n,com); double sum=0; for(int i=0;i<n;i++){ if(arr[i].weight<W){ sum+=(double)arr[i].value; W-=arr[i].weight; }else{ sum+=(double)arr[i].value*(double)W/(double)arr[i].weight; break; } } return sum; } We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 441, "s": 238, "text": "Given weights and values of N items, we need to put these items in a knapsack of capacity W to get the maximum total value in the knapsack.\nNote: Unlike 0/1 knapsack, you are allowed to break the item. " }, { "code": null, "e": 454, "s": 443, "text": "Example 1:" }, { "code": null, "e": 633, "s": 454, "text": "Input:\nN = 3, W = 50\nvalues[] = {60,100,120}\nweight[] = {10,20,30}\nOutput:\n220.00\nExplanation:Total maximum value of item\nwe can have is 240.00 from the given\ncapacity of sack. \n" }, { "code": null, "e": 644, "s": 633, "text": "Example 2:" }, { "code": null, "e": 815, "s": 644, "text": "Input:\nN = 2, W = 50\nvalues[] = {60,100}\nweight[] = {10,20}\nOutput:\n160.00\nExplanation:\nTotal maximum value of item\nwe can have is 160.00 from the given\ncapacity of sack." }, { "code": null, "e": 1102, "s": 817, "text": "Your Task :\nComplete the function fractionalKnapsack() that receives maximum capacity , array of structure/class and size n and returns a double value representing the maximum value in knapsack.\nNote: The details of structure/class is defined in the comments above the given function." }, { "code": null, "e": 1171, "s": 1102, "text": "\nExpected Time Complexity : O(NlogN)\nExpected Auxilliary Space: O(1)" }, { "code": null, "e": 1213, "s": 1171, "text": "\nConstraints:\n1 <= N <= 105\n1 <= W <= 105" }, { "code": null, "e": 1215, "s": 1213, "text": "0" }, { "code": null, "e": 1240, "s": 1215, "text": "sikkusaurav123in 8 hours" }, { "code": null, "e": 1336, "s": 1240, "text": "This is correct but somewhere floating point mistake if someone find it please tag that thing :" }, { "code": null, "e": 2303, "s": 1336, "text": "class Solution{ public: //Function to get the maximum total value in the knapsack. double fractionalKnapsack(int W, Item arr[], int n) { // Your code here vector<pair<float,int>>v; float profit=0.00; for(int i=0;i<n;i++) { v.push_back(make_pair((float(arr[i].value)/float(arr[i].weight)),i)); } sort(v.begin(),v.end()); reverse(v.begin(),v.end()); for(int i=0;i<n;i++) { if(W>0 && W>arr[v[i].second].weight) { profit=profit+float(arr[v[i].second].value); W=W-arr[v[i].second].weight; } else if(W>0 && W<arr[v[i].second].weight) { profit=profit+(float(arr[v[i].second].value)*float(float(W)/float(arr[v[i].second].weight))); W=W-arr[v[i].second].weight; } else if(W<=0) { break; } } return (profit); } };" }, { "code": null, "e": 2307, "s": 2305, "text": "0" }, { "code": null, "e": 2331, "s": 2307, "text": "19003001002372 days ago" }, { "code": null, "e": 3109, "s": 2331, "text": "class Solution{ public: static bool comp(Item a, Item b) { double r = (double)a.value/(double)a.weight; double r1 = (double)b.value/(double)b.weight; return r > r1; } //Function to get the maximum total value in the knapsack. double fractionalKnapsack(int W, Item arr[], int n) { // Your code here sort(arr,arr+n,comp); int cur_w = 0; double profit = 0.0; for(int i =0;i<n;i++) { if(cur_w + arr[i].weight <= W) { profit += arr[i].value; cur_w += arr[i].weight; } else { int remain = W - cur_w; profit += (double)remain/(double)arr[i].weight * arr[i].value; break; } } return profit; } };" }, { "code": null, "e": 3111, "s": 3109, "text": "0" }, { "code": null, "e": 3134, "s": 3111, "text": "akshatjain232 days ago" }, { "code": null, "e": 4675, "s": 3134, "text": "/*\nclass Item {\n int value, weight;\n Item(int x, int y){\n this.value = x;\n this.weight = y;\n }\n}\n*/\n\nclass Solution\n{\n //Function to get the maximum total value in the knapsack.\n double fractionalKnapsack(int W, Item arr[], int n) \n {\n /* Sort the items in the descreasing order of \n there value per weight */\n Arrays.sort(arr, new ItemComparator());\n \n double max = 0;\n \n for(Item item : arr) {\n \n // If remaining capacity is 0, knapsack is full\n if( W == 0 ) break;\n \n /* If current item's weight not more than the capacity\n then include the item in the knapsack */\n if( item.weight <= W ) {\n max += item.value;\n W -= item.weight;\n } else {\n /* Else store the fraction of the item updating remaining \n capacity */\n max += (double)(item.value*W) / item.weight;\n W = 0;\n }\n }\n \n return max;\n }\n}\nclass ItemComparator implements Comparator<Item> {\n @Override\n public int compare(Item item1, Item item2) {\n double valuePerWeight1 = (double)item1.value / item1.weight;\n double valuePerWeight2 = (double)item2.value / item2.weight;\n \n if( valuePerWeight2 > valuePerWeight1 ) {\n return 1;\n } else if( valuePerWeight2 < valuePerWeight1 ) {\n return -1;\n } \n return 0;\n }\n}" }, { "code": null, "e": 4678, "s": 4675, "text": "+1" }, { "code": null, "e": 4701, "s": 4678, "text": "ksbsbisht1371 week ago" }, { "code": null, "e": 5296, "s": 4701, "text": "static bool cmp(struct Item a,struct Item b) { double r1=(double)a.value/(double)a.weight; double r2=(double)b.value/(double)b.weight; if(r1<r2) return false; return true; } double fractionalKnapsack(int W, Item arr[], int n) { sort(arr,arr+n,cmp); double cost=0; for(int i=0;i<n;i++) { if(arr[i].weight<=W) { W-=arr[i].weight; cost+=arr[i].value; } else { cost+=((double)arr[i].value/(double)arr[i].weight)*W; break; } } return cost; }" }, { "code": null, "e": 5298, "s": 5296, "text": "0" }, { "code": null, "e": 5321, "s": 5298, "text": "ksbsbisht1371 week ago" }, { "code": null, "e": 5955, "s": 5321, "text": "double fractionalKnapsack(int W, Item arr[], int n) { vector<pair<double,pair<int,int>>> vec; for(int i=0;i<n;i++) { vec.push_back({arr[i].value/(arr[i].weight*1.0),{arr[i].value,arr[i].weight}}); } sort(vec.begin(),vec.end(),greater<pair<double,pair<int,int>>> ()); double cost=0.0; for(int i=0;i<n;i++) { if(vec[i].second.second<=W) { W-=vec[i].second.second; cost+=vec[i].second.first; } else { if(W>0) { cost+=W*vec[i].first; break; } } } return cost; }" }, { "code": null, "e": 5957, "s": 5955, "text": "0" }, { "code": null, "e": 5980, "s": 5957, "text": "manasbass992 weeks ago" }, { "code": null, "e": 6416, "s": 5980, "text": "def fractionalknapsack(self, W,Items,n):\n # code here\n res = 0.0\n Items.sort(key=lambda x: -x.value/x.weight)\n for item in Items:\n if W >= item.weight:\n W -= item.weight\n res += item.value\n elif W > 0 and W<item.weight:\n res += item.value * W/item.weight\n W = 0\n if W == 0:\n break\n return res" }, { "code": null, "e": 6418, "s": 6416, "text": "0" }, { "code": null, "e": 6425, "s": 6418, "text": "ponkey" }, { "code": null, "e": 6451, "s": 6425, "text": "This comment was deleted." }, { "code": null, "e": 6453, "s": 6451, "text": "0" }, { "code": null, "e": 6481, "s": 6453, "text": "dadwalabhishek101 month ago" }, { "code": null, "e": 7247, "s": 6481, "text": "//You dont have to sort the values and put the complexity in nlogn and space comp O(N). Just use max heap and find out the value\nclass Solution\n{\n public:\n //Function to get the maximum total value in the knapsack.\n double fractionalKnapsack(int W, Item arr[], int n)\n {\n // Your code here\n double ans = 0.0;\n priority_queue<pair<double, int>> pq;\n for(int i = 0;i<n;i++)\n {\n pq.push({(double)arr[i].value/(double)arr[i].weight, arr[i].weight});\n }\n while(!pq.empty())\n {\n if(W==0) return ans;\n int diff = min(pq.top().second, W);\n ans += diff*pq.top().first;\n W -= diff;\n pq.pop();\n }\n return ans;\n }\n \n};\n" }, { "code": null, "e": 7250, "s": 7247, "text": "-1" }, { "code": null, "e": 7285, "s": 7250, "text": "gaurabhkumarjha271020011 month ago" }, { "code": null, "e": 8099, "s": 7285, "text": "// easy c++ approach\nstatic bool comp (pair <double,double> a, pair<double,double> b){\n \n double r= a.first / a.second;\n double r1= b.first/b.second;\n return r > r1;\n }\n double fractionalKnapsack(int W, Item arr[], int n)\n {\n vector <pair <double,double> > v;\n double res=0.0;\n \n for (int i=0; i< n; i++){\n \n v.push_back ({arr[i].value, arr[i].weight});\n }\n sort (v.begin(), v.end(), comp);\n for (int i=0; i< n; i++){\n \n if (v[i].second <= W){ // first means value \n res+= v[i].first; // second means weight\n W-= v[i].second;\n }else{\n if (W != 0) \n res+= (W* (v[i].first/v[i].second));\n W=0;\n break;\n }\n } \n return res;\n }" }, { "code": null, "e": 8102, "s": 8099, "text": "-1" }, { "code": null, "e": 8131, "s": 8102, "text": "badgujarsachin832 months ago" }, { "code": null, "e": 8789, "s": 8131, "text": " static bool com(Item a,Item b){\n double a1=(double)a.value/a.weight;\n double a2=(double)b.value/b.weight;\n return a1>a2;\n }\n //Function to get the maximum total value in the knapsack.\n double fractionalKnapsack(int W, Item arr[], int n)\n {\n // Your code here\n sort(arr,arr+n,com);\n double sum=0;\n for(int i=0;i<n;i++){\n if(arr[i].weight<W){\n sum+=(double)arr[i].value;\n W-=arr[i].weight;\n }else{\n sum+=(double)arr[i].value*(double)W/(double)arr[i].weight;\n break;\n }\n }\n return sum;\n }" }, { "code": null, "e": 8935, "s": 8789, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 8971, "s": 8935, "text": " Login to access your submissions. " }, { "code": null, "e": 8981, "s": 8971, "text": "\nProblem\n" }, { "code": null, "e": 8991, "s": 8981, "text": "\nContest\n" }, { "code": null, "e": 9054, "s": 8991, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 9202, "s": 9054, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 9410, "s": 9202, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 9516, "s": 9410, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Check if a string consists only of special characters - GeeksforGeeks
11 May, 2021 Given string str of length N, the task is to check if the given string contains only special characters or not. If the string contains only special characters, then print “Yes”. Otherwise, print “No”. Examples: Input: str = “@#$&%!~”Output: YesExplanation: Given string contains only special characters. Therefore, the output is Yes. Input: str = “Geeks4Geeks@#”Output: NoExplanation: Given string contains alphabets, number, and special characters. Therefore, the output is No. Naive Approach: Iterate over the string and check if the string contains only special characters or not. Follow the steps below to solve the problem: Traverse the string and for each character, check if its ASCII value lies in the ranges [32, 47], [58, 64], [91, 96] or [123, 126]. If found to be true, it is a special character. Print Yes if all characters lie in one of the aforementioned ranges. Otherwise, print No. Time Complexity: O(N)Auxiliary Space: O(1) Space-Efficient Approach: The idea is to use Regular Expression to optimize the above approach. Follow the steps below: Create the following regular expression to check if the given string contains only special characters or not. regex = “[^a-zA-Z0-9]+” where, [^a-zA-Z0-9] represents only special characters. + represents one or more times. Match the given string with the Regular Expression using Pattern.matcher() in Java Print Yes if the string matches with the given regular expression. Otherwise, print No. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to check if the string// contains only special characters#include <iostream>#include <regex>using namespace std; // Function to check if the string contains only special characters.void onlySpecialCharacters(string str){ // Regex to check if the string contains only special characters. const regex pattern("[^a-zA-Z0-9]+"); // If the string // is empty then print "No" if (str.empty()) { cout<< "No"; return ; } // Print "Yes" if the the string contains only special characters // matched the ReGex if(regex_match(str, pattern)) { cout<< "Yes"; } else { cout<< "No"; }} // Driver Codeint main(){ // Given string str string str = "@#$&%!~"; onlySpecialCharacters(str) ; return 0;} // This code is contributed by yuvraj_chandra // Java program to check if the string// contains only special characters import java.util.regex.*;class GFG { // Function to check if a string // contains only special characters public static void onlySpecialCharacters( String str) { // Regex to check if a string contains // only special characters String regex = "[^a-zA-Z0-9]+"; // Compile the ReGex Pattern p = Pattern.compile(regex); // If the string is empty // then print No if (str == null) { System.out.println("No"); return; } // Find match between given string // & regular expression Matcher m = p.matcher(str); // Print Yes If the string matches // with the Regex if (m.matches()) System.out.println("Yes"); else System.out.println("No"); } // Driver Code public static void main(String args[]) { // Given string str String str = "@#$&%!~"; // Function Call onlySpecialCharacters(str); }} # Python program to check if the string# contains only special charactersimport re # Function to check if a string# contains only special charactersdef onlySpecialCharacters(Str): # Regex to check if a string contains # only special characters regex = "[^a-zA-Z0-9]+" # Compile the ReGex p=re.compile(regex) # If the string is empty # then print No if(len(Str) == 0): print("No") return # Print Yes If the string matches # with the Regex if(re.search(p, Str)): print("Yes") else: print("No") # Driver Code # Given string strStr = "@#$&%!~" # Function CallonlySpecialCharacters(Str) # This code is contributed by avanitrachhadiya2155 // C# program to check if// the string contains only// special charactersusing System;using System.Text.RegularExpressions; class GFG{ // Function to check if a string// contains only special characterspublic static void onlySpecialchars(String str){ // Regex to check if a string // contains only special // characters String regex = "[^a-zA-Z0-9]+"; // Compile the ReGex Regex rgex = new Regex(regex); // If the string is empty // then print No if (str == null) { Console.WriteLine("No"); return; } // Find match between given // string & regular expression MatchCollection matchedAuthors = rgex.Matches(str); // Print Yes If the string matches // with the Regex if (matchedAuthors.Count != 0) Console.WriteLine("Yes"); else Console.WriteLine("No");} // Driver Codepublic static void Main(String []args){ // Given string str String str = "@#$&%!~"; // Function Call onlySpecialchars(str);}} // This code is contributed by Princi Singh <script> // JavaScript program to check if // the string contains only // special characters // Function to check if a string // contains only special characters function onlySpecialchars(str) { // Regex to check if a string // contains only special // characters var regex = /^[^a-zA-Z0-9]+$/; // If the string is empty // then print No if (str.length < 1) { document.write("No"); return; } // Find match between given // string & regular expression var matchedAuthors = regex.test(str); // Print Yes If the string matches // with the Regex if (matchedAuthors) document.write("Yes"); else document.write("No"); } // Driver Code // Given string str var str = "@#$&%!~"; // Function Call onlySpecialchars(str); </script> Yes Time Complexity: O(N)Auxiliary Space: O(1) princi singh avanitrachhadiya2155 yuvraj_chandra rdtank ASCII Java-String-Programs regular-expression strings Pattern Searching Strings Strings Pattern Searching Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Minimize number of cuts required to break N length stick into N unit length sticks Check if an URL is valid or not using Regular Expression How to check if string contains only digits in Java String matching where one string contains wildcard characters Pattern Searching using Suffix Tree Reverse a string in Java Write a program to reverse an array or string Longest Common Subsequence | DP-4 Write a program to print all permutations of a given string C++ Data Types
[ { "code": null, "e": 25510, "s": 25482, "text": "\n11 May, 2021" }, { "code": null, "e": 25711, "s": 25510, "text": "Given string str of length N, the task is to check if the given string contains only special characters or not. If the string contains only special characters, then print “Yes”. Otherwise, print “No”." }, { "code": null, "e": 25721, "s": 25711, "text": "Examples:" }, { "code": null, "e": 25844, "s": 25721, "text": "Input: str = “@#$&%!~”Output: YesExplanation: Given string contains only special characters. Therefore, the output is Yes." }, { "code": null, "e": 25989, "s": 25844, "text": "Input: str = “Geeks4Geeks@#”Output: NoExplanation: Given string contains alphabets, number, and special characters. Therefore, the output is No." }, { "code": null, "e": 26139, "s": 25989, "text": "Naive Approach: Iterate over the string and check if the string contains only special characters or not. Follow the steps below to solve the problem:" }, { "code": null, "e": 26319, "s": 26139, "text": "Traverse the string and for each character, check if its ASCII value lies in the ranges [32, 47], [58, 64], [91, 96] or [123, 126]. If found to be true, it is a special character." }, { "code": null, "e": 26409, "s": 26319, "text": "Print Yes if all characters lie in one of the aforementioned ranges. Otherwise, print No." }, { "code": null, "e": 26452, "s": 26409, "text": "Time Complexity: O(N)Auxiliary Space: O(1)" }, { "code": null, "e": 26572, "s": 26452, "text": "Space-Efficient Approach: The idea is to use Regular Expression to optimize the above approach. Follow the steps below:" }, { "code": null, "e": 26682, "s": 26572, "text": "Create the following regular expression to check if the given string contains only special characters or not." }, { "code": null, "e": 26706, "s": 26682, "text": "regex = “[^a-zA-Z0-9]+”" }, { "code": null, "e": 26713, "s": 26706, "text": "where," }, { "code": null, "e": 26762, "s": 26713, "text": "[^a-zA-Z0-9] represents only special characters." }, { "code": null, "e": 26794, "s": 26762, "text": "+ represents one or more times." }, { "code": null, "e": 26877, "s": 26794, "text": "Match the given string with the Regular Expression using Pattern.matcher() in Java" }, { "code": null, "e": 26965, "s": 26877, "text": "Print Yes if the string matches with the given regular expression. Otherwise, print No." }, { "code": null, "e": 27016, "s": 26965, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 27020, "s": 27016, "text": "C++" }, { "code": null, "e": 27025, "s": 27020, "text": "Java" }, { "code": null, "e": 27033, "s": 27025, "text": "Python3" }, { "code": null, "e": 27036, "s": 27033, "text": "C#" }, { "code": null, "e": 27047, "s": 27036, "text": "Javascript" }, { "code": "// C++ program to check if the string// contains only special characters#include <iostream>#include <regex>using namespace std; // Function to check if the string contains only special characters.void onlySpecialCharacters(string str){ // Regex to check if the string contains only special characters. const regex pattern(\"[^a-zA-Z0-9]+\"); // If the string // is empty then print \"No\" if (str.empty()) { cout<< \"No\"; return ; } // Print \"Yes\" if the the string contains only special characters // matched the ReGex if(regex_match(str, pattern)) { cout<< \"Yes\"; } else { cout<< \"No\"; }} // Driver Codeint main(){ // Given string str string str = \"@#$&%!~\"; onlySpecialCharacters(str) ; return 0;} // This code is contributed by yuvraj_chandra", "e": 27830, "s": 27047, "text": null }, { "code": "// Java program to check if the string// contains only special characters import java.util.regex.*;class GFG { // Function to check if a string // contains only special characters public static void onlySpecialCharacters( String str) { // Regex to check if a string contains // only special characters String regex = \"[^a-zA-Z0-9]+\"; // Compile the ReGex Pattern p = Pattern.compile(regex); // If the string is empty // then print No if (str == null) { System.out.println(\"No\"); return; } // Find match between given string // & regular expression Matcher m = p.matcher(str); // Print Yes If the string matches // with the Regex if (m.matches()) System.out.println(\"Yes\"); else System.out.println(\"No\"); } // Driver Code public static void main(String args[]) { // Given string str String str = \"@#$&%!~\"; // Function Call onlySpecialCharacters(str); }}", "e": 28910, "s": 27830, "text": null }, { "code": "# Python program to check if the string# contains only special charactersimport re # Function to check if a string# contains only special charactersdef onlySpecialCharacters(Str): # Regex to check if a string contains # only special characters regex = \"[^a-zA-Z0-9]+\" # Compile the ReGex p=re.compile(regex) # If the string is empty # then print No if(len(Str) == 0): print(\"No\") return # Print Yes If the string matches # with the Regex if(re.search(p, Str)): print(\"Yes\") else: print(\"No\") # Driver Code # Given string strStr = \"@#$&%!~\" # Function CallonlySpecialCharacters(Str) # This code is contributed by avanitrachhadiya2155", "e": 29611, "s": 28910, "text": null }, { "code": "// C# program to check if// the string contains only// special charactersusing System;using System.Text.RegularExpressions; class GFG{ // Function to check if a string// contains only special characterspublic static void onlySpecialchars(String str){ // Regex to check if a string // contains only special // characters String regex = \"[^a-zA-Z0-9]+\"; // Compile the ReGex Regex rgex = new Regex(regex); // If the string is empty // then print No if (str == null) { Console.WriteLine(\"No\"); return; } // Find match between given // string & regular expression MatchCollection matchedAuthors = rgex.Matches(str); // Print Yes If the string matches // with the Regex if (matchedAuthors.Count != 0) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\");} // Driver Codepublic static void Main(String []args){ // Given string str String str = \"@#$&%!~\"; // Function Call onlySpecialchars(str);}} // This code is contributed by Princi Singh", "e": 30608, "s": 29611, "text": null }, { "code": "<script> // JavaScript program to check if // the string contains only // special characters // Function to check if a string // contains only special characters function onlySpecialchars(str) { // Regex to check if a string // contains only special // characters var regex = /^[^a-zA-Z0-9]+$/; // If the string is empty // then print No if (str.length < 1) { document.write(\"No\"); return; } // Find match between given // string & regular expression var matchedAuthors = regex.test(str); // Print Yes If the string matches // with the Regex if (matchedAuthors) document.write(\"Yes\"); else document.write(\"No\"); } // Driver Code // Given string str var str = \"@#$&%!~\"; // Function Call onlySpecialchars(str); </script>", "e": 31545, "s": 30608, "text": null }, { "code": null, "e": 31549, "s": 31545, "text": "Yes" }, { "code": null, "e": 31594, "s": 31551, "text": "Time Complexity: O(N)Auxiliary Space: O(1)" }, { "code": null, "e": 31607, "s": 31594, "text": "princi singh" }, { "code": null, "e": 31628, "s": 31607, "text": "avanitrachhadiya2155" }, { "code": null, "e": 31643, "s": 31628, "text": "yuvraj_chandra" }, { "code": null, "e": 31650, "s": 31643, "text": "rdtank" }, { "code": null, "e": 31656, "s": 31650, "text": "ASCII" }, { "code": null, "e": 31677, "s": 31656, "text": "Java-String-Programs" }, { "code": null, "e": 31696, "s": 31677, "text": "regular-expression" }, { "code": null, "e": 31704, "s": 31696, "text": "strings" }, { "code": null, "e": 31722, "s": 31704, "text": "Pattern Searching" }, { "code": null, "e": 31730, "s": 31722, "text": "Strings" }, { "code": null, "e": 31738, "s": 31730, "text": "Strings" }, { "code": null, "e": 31756, "s": 31738, "text": "Pattern Searching" }, { "code": null, "e": 31854, "s": 31756, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31937, "s": 31854, "text": "Minimize number of cuts required to break N length stick into N unit length sticks" }, { "code": null, "e": 31994, "s": 31937, "text": "Check if an URL is valid or not using Regular Expression" }, { "code": null, "e": 32046, "s": 31994, "text": "How to check if string contains only digits in Java" }, { "code": null, "e": 32108, "s": 32046, "text": "String matching where one string contains wildcard characters" }, { "code": null, "e": 32144, "s": 32108, "text": "Pattern Searching using Suffix Tree" }, { "code": null, "e": 32169, "s": 32144, "text": "Reverse a string in Java" }, { "code": null, "e": 32215, "s": 32169, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 32249, "s": 32215, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 32309, "s": 32249, "text": "Write a program to print all permutations of a given string" } ]
Check input character is alphabet, digit or special character in C
In this section, we will see how to check whether a given character is number, or the alphabet or some special character in C. The alphabets are from A – Z and a – z, Then the numbers are from 0 – 9. And all other characters are special characters. So If we check the conditions using these criteria, we can easily find them. #include <stdio.h> #include <conio.h> main() { char ch; printf("Enter a character: "); scanf("%c", &ch); if((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z')) printf("This is an alphabet"); else if(ch >= '0' && ch <= '9') printf("This is a number"); else printf("This is a special character"); } Enter a character: F This is an alphabet Enter a character: r This is an alphabet Enter a character: 7 This is a number Enter a character: # This is a special character
[ { "code": null, "e": 1189, "s": 1062, "text": "In this section, we will see how to check whether a given character is number, or the alphabet or some special character in C." }, { "code": null, "e": 1388, "s": 1189, "text": "The alphabets are from A – Z and a – z, Then the numbers are from 0 – 9. And all other characters are special characters. So If we check the conditions using these criteria, we can easily find them." }, { "code": null, "e": 1723, "s": 1388, "text": "#include <stdio.h>\n#include <conio.h>\nmain() {\n char ch;\n printf(\"Enter a character: \");\n scanf(\"%c\", &ch);\n if((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z'))\n printf(\"This is an alphabet\");\n else if(ch >= '0' && ch <= '9')\n printf(\"This is a number\");\n else\n printf(\"This is a special character\");\n}" }, { "code": null, "e": 1764, "s": 1723, "text": "Enter a character: F\nThis is an alphabet" }, { "code": null, "e": 1805, "s": 1764, "text": "Enter a character: r\nThis is an alphabet" }, { "code": null, "e": 1843, "s": 1805, "text": "Enter a character: 7\nThis is a number" }, { "code": null, "e": 1892, "s": 1843, "text": "Enter a character: #\nThis is a special character" } ]
Schedule Your Python Scripts On Windows Platform | by Ujjwal Dalmia | Towards Data Science
Let’s think of a scenario before we start with this tutorial: Your manager calls you and instructs, “the client wants refreshed data every day by 6 AM IST. Please change your shift timings and ensure script execution post client’s batch completes”. What does this mean? This means, starting today, you will start losing your precious sleep, time with family and friends, and above all, will be working on executing some random script at the most unproductive hour of the day. If the above sounds familiar and you want to save yourself from a nightmare like this, please read further. In this tutorial, we will learn to schedule Python scripts on a Windows platform. The achieve our objective, we need 3 things: Python Script —For this tutorial, I have written a small Python code that reads a “CSV” file from my Windows folder location. This “CSV” file contains 2 columns, each having random numbers. The code adds both the columns to create a new one and saves this new version of the CSV file at the same folder location. #### Importing the required libraryimport pandas as pd#### Reading csv filedf = pd.read_csv("C:\\Ujjwal\\New_File_V1.csv")#### Adding 2 columnsdf["Third_Column"] = df["Randome Numbers 1"] + df["Random Numbers 2"]#### Exporting the data to same locationdf.to_csv("C:\\Ujjwal\\New_File_V2.csv",index = False) Batch File — A batch file is a script file with a “.BAT” extension. These files are generally saved as simple text files and contain commands which can be executed on the command-line interface (command prompt). When the command prompt executes these files, it reads through the commands written in the file and executes them line by line. Scheduler — Last but not the least, we need a scheduler that can read the Batch file and executes the commands written in it at a set time. For this purpose, we will use Windows’ Task Scheduler will come in handy. In the previous section, we have already shared the sample Python code which we plan to schedule. The second component required is a Batch file. For our purpose, the Batch file will have 2 commands: Location of the Python Application— This is the Python application (“.exe” extension) which is used for the execution of the scripts. In our batch file, we will provide the location of this application as the first command. On my system, this location is as below: #### Location of Python ExecutableC:\Users\Ujjwal\Anaconda3\python.exe Location of the Python Script — This is the script that you want to schedule. We will provide the location of this script as the second command to the Batch file. Given we are working with Python scripts, ensure that the backslashes in the folder location are replaced with forward slash. The Windows location of my script is as follows. #### Windows LocationC:\Ujjwal\Executable.py#### Backslash replaced with forward slashC:/Ujjwal/Executable.py Final Script — The final Batch script will look something like below. Save this script in a text file with a .BAT extension at any Windows location. #### Final Batch ScriptC:\Users\Ujjwal\Anaconda3\python.exe "C:/Ujjwal/Executable.py" In this step, we will set up the schedule to execute our tasks periodically. The step by step process is as follows: Open Windows Task Scheduler — Go to Windows search, search for task scheduler, and open it. The task scheduler interface will look something like below: Create the New Task — Click on “Create Basic Task” in the right window pane to create a new task. A new window, prompting you to fill the task name and description will pop-up. The interface will look like below: Select Periodicity — Click next after filling the name and description details of the task. Now, the system will prompt you to select the trigger options where we can set the periodicity of the task. For our purpose, we are selecting the daily execution. A complete list of trigger options is as follows: Select Schedule Time — Click next after selecting the task frequency. Now, the system will prompt you to select a specific time at which you want the schedule to trigger. The interface screen would look something like below: Create Action — Click next after selecting the execution time. In this step, the scheduler will prompt you to select the action you want to schedule. Select “Start a program”. The interface will look like below: Select Batch File — Click next after selecting the desired action. Now, the application interface will ask for the location of the program you want to schedule. Select the batch file which we had created in the previous section. The application screen will look as follows: Finally — That’s it, click next and finish. Your Python script will execute at a specific time every day. I am sure that with a solution like above, you can automate all your repetitive tasks. I hope this tutorial was informative and you learned something new. Please comment and share your feedback. Stay tuned for more interesting topics for next time. Till then: HAPPY LEARNING ! ! ! !
[ { "code": null, "e": 233, "s": 171, "text": "Let’s think of a scenario before we start with this tutorial:" }, { "code": null, "e": 647, "s": 233, "text": "Your manager calls you and instructs, “the client wants refreshed data every day by 6 AM IST. Please change your shift timings and ensure script execution post client’s batch completes”. What does this mean? This means, starting today, you will start losing your precious sleep, time with family and friends, and above all, will be working on executing some random script at the most unproductive hour of the day." }, { "code": null, "e": 837, "s": 647, "text": "If the above sounds familiar and you want to save yourself from a nightmare like this, please read further. In this tutorial, we will learn to schedule Python scripts on a Windows platform." }, { "code": null, "e": 882, "s": 837, "text": "The achieve our objective, we need 3 things:" }, { "code": null, "e": 1195, "s": 882, "text": "Python Script —For this tutorial, I have written a small Python code that reads a “CSV” file from my Windows folder location. This “CSV” file contains 2 columns, each having random numbers. The code adds both the columns to create a new one and saves this new version of the CSV file at the same folder location." }, { "code": null, "e": 1502, "s": 1195, "text": "#### Importing the required libraryimport pandas as pd#### Reading csv filedf = pd.read_csv(\"C:\\\\Ujjwal\\\\New_File_V1.csv\")#### Adding 2 columnsdf[\"Third_Column\"] = df[\"Randome Numbers 1\"] + df[\"Random Numbers 2\"]#### Exporting the data to same locationdf.to_csv(\"C:\\\\Ujjwal\\\\New_File_V2.csv\",index = False)" }, { "code": null, "e": 1842, "s": 1502, "text": "Batch File — A batch file is a script file with a “.BAT” extension. These files are generally saved as simple text files and contain commands which can be executed on the command-line interface (command prompt). When the command prompt executes these files, it reads through the commands written in the file and executes them line by line." }, { "code": null, "e": 2056, "s": 1842, "text": "Scheduler — Last but not the least, we need a scheduler that can read the Batch file and executes the commands written in it at a set time. For this purpose, we will use Windows’ Task Scheduler will come in handy." }, { "code": null, "e": 2255, "s": 2056, "text": "In the previous section, we have already shared the sample Python code which we plan to schedule. The second component required is a Batch file. For our purpose, the Batch file will have 2 commands:" }, { "code": null, "e": 2520, "s": 2255, "text": "Location of the Python Application— This is the Python application (“.exe” extension) which is used for the execution of the scripts. In our batch file, we will provide the location of this application as the first command. On my system, this location is as below:" }, { "code": null, "e": 2591, "s": 2520, "text": "#### Location of Python ExecutableC:\\Users\\Ujjwal\\Anaconda3\\python.exe" }, { "code": null, "e": 2929, "s": 2591, "text": "Location of the Python Script — This is the script that you want to schedule. We will provide the location of this script as the second command to the Batch file. Given we are working with Python scripts, ensure that the backslashes in the folder location are replaced with forward slash. The Windows location of my script is as follows." }, { "code": null, "e": 3039, "s": 2929, "text": "#### Windows LocationC:\\Ujjwal\\Executable.py#### Backslash replaced with forward slashC:/Ujjwal/Executable.py" }, { "code": null, "e": 3188, "s": 3039, "text": "Final Script — The final Batch script will look something like below. Save this script in a text file with a .BAT extension at any Windows location." }, { "code": null, "e": 3274, "s": 3188, "text": "#### Final Batch ScriptC:\\Users\\Ujjwal\\Anaconda3\\python.exe \"C:/Ujjwal/Executable.py\"" }, { "code": null, "e": 3391, "s": 3274, "text": "In this step, we will set up the schedule to execute our tasks periodically. The step by step process is as follows:" }, { "code": null, "e": 3544, "s": 3391, "text": "Open Windows Task Scheduler — Go to Windows search, search for task scheduler, and open it. The task scheduler interface will look something like below:" }, { "code": null, "e": 3757, "s": 3544, "text": "Create the New Task — Click on “Create Basic Task” in the right window pane to create a new task. A new window, prompting you to fill the task name and description will pop-up. The interface will look like below:" }, { "code": null, "e": 4062, "s": 3757, "text": "Select Periodicity — Click next after filling the name and description details of the task. Now, the system will prompt you to select the trigger options where we can set the periodicity of the task. For our purpose, we are selecting the daily execution. A complete list of trigger options is as follows:" }, { "code": null, "e": 4287, "s": 4062, "text": "Select Schedule Time — Click next after selecting the task frequency. Now, the system will prompt you to select a specific time at which you want the schedule to trigger. The interface screen would look something like below:" }, { "code": null, "e": 4499, "s": 4287, "text": "Create Action — Click next after selecting the execution time. In this step, the scheduler will prompt you to select the action you want to schedule. Select “Start a program”. The interface will look like below:" }, { "code": null, "e": 4773, "s": 4499, "text": "Select Batch File — Click next after selecting the desired action. Now, the application interface will ask for the location of the program you want to schedule. Select the batch file which we had created in the previous section. The application screen will look as follows:" }, { "code": null, "e": 4879, "s": 4773, "text": "Finally — That’s it, click next and finish. Your Python script will execute at a specific time every day." }, { "code": null, "e": 4966, "s": 4879, "text": "I am sure that with a solution like above, you can automate all your repetitive tasks." }, { "code": null, "e": 5074, "s": 4966, "text": "I hope this tutorial was informative and you learned something new. Please comment and share your feedback." }, { "code": null, "e": 5139, "s": 5074, "text": "Stay tuned for more interesting topics for next time. Till then:" } ]
Sum of Query II | Practice | GeeksforGeeks
You are given an array arr[] of n integers and q queries in an array queries[] of length 2*q containing l, r pair for all q queries. You need to compute the following sum over q queries. Array is 1-Indexed. Example 1: Input: n = 4 arr = {1, 2, 3, 4} q = 2 queries = {1, 4, 2, 3} Output: 10 5 Explaination: In the first query we need sum from 1 to 4 which is 1+2+3+4 = 10. In the second query we need sum from 2 to 3 which is 2 + 3 = 5. Your Task: You do not need to read input or print anything. Your task is to complete the function querySum() which takes n, arr, q and queries as input parameters and returns the answer for all the queries. Expected Time Complexity: O(n+q) Expected Auxiliary Space: O(n) Constraints: 1 ≤ n, q ≤ 1000 1 ≤ arri ≤ 106 1 ≤ l ≤ r ≤ n 0 18pa1a04771 month ago 0.2/1.9 sec using square root decompositio import math class Solution: def querySum(self, n, arr, q, qe): val=int(math.sqrt(n)) d={} for i in range(n): if (i+1)//val in d: d[(i+1)//val]=d[(i+1)//val]+arr[i] else: d[(i+1)//val]=arr[i] ans=[] for l in range(0,len(qe),2): s=0 lf=qe[l] ri=qe[l+1] for k in range(lf,ri+1): if k//val==lf//val+1: break s=s+arr[k-1] if lf//val==ri//val: ans.append(s) continue for k in range(ri,lf-1,-1): if k//val==ri//val-1: break s=s+arr[k-1] for k in range((lf//val)+1,(ri//val)): if k in d: s=s+d[k] ans.append(s) return ans 0 kiransaisk4481 month ago simple python solution: class Solution: def querySum(self, n, arr, q, queries): # code here result = [] for i in range(0, 2*q-1, 2): left = queries[i] - 1 right = queries[i+1] result.append(sum(arr[left:right])) return result 0 mohankumarit20012 months ago vector<int> querySum(int n, int arr[], int q, int queries[]) { for(int i=1;i<n;i++){ arr[i]+=arr[i-1]; } vector<int> res; for(int i=0;i<2*q;i+=2){ if(queries[i]==0)res.push_back(arr[queries[i+1]-1]); res.push_back(arr[queries[i+1]-1]-arr[queries[i]-2]); } return res; } 0 annanyamathur2 months ago Using Segment Tree int tree[100000];int getSum(int l,int r,int start,int end,int index){ if(l>end || r<start) return 0; if(start>=l && end<=r) return tree[index]; int mid=(start+end)/2; return getSum(l,r,start,mid,2*index+1)+getSum(l,r,mid+1,end,2*index+2);}void constructST(int arr[],int start,int end,int index){ if(start==end) {tree[index]=arr[start]; return; } int mid=(start+end)/2; constructST(arr,start,mid,2*index+1); constructST(arr,mid+1,end,2*index+2); tree[index]=tree[2*index+1]+tree[2*index+2]; } vector<int> querySum(int n, int arr[], int q, int queries[]) { vector<int>r; constructST(arr,0,n-1,0); for(int i=0;i<2*q;i+=2) { //cout<<i<<"\t"<<queries[i]<<"\t"<<queries[i+1]<<"\n"; int a=getSum(queries[i]-1,queries[i+1]-1,0,n-1,0); r.push_back(a); } return r; } 0 kantariyaraj3 months ago Simple Java solution if(n == 0 || q == 0) return null; List<Integer> result = new ArrayList<>(); int[] sumList = new int[n]; sumList[0] = arr[0]; for(int i = 1; i < n; i++){ sumList[i] = arr[i] + sumList[i-1]; } for(int i = 0; i < q; i++){ int l = queries[2 * i] - 1; int r= queries[(2 * i) + 1] - 1; result.add(sumList[r]-sumList[l]); } return result; 0 chessnoobdj5 months ago Optimized c++ using prefix sum vector<int> querySum(int n, int arr[], int q, int queries[]) { vector <int> ans; for(int i=1; i<n; i++) arr[i] += arr[i-1]; for(int i=0; i<2*q; i += 2){ if(queries[i] == 1) ans.push_back(arr[queries[i+1]-1]); else ans.push_back(arr[queries[i+1]-1] - arr[queries[i]-2]); } return ans; } 0 gurshaansing6 months ago vector<int> ans; int i=0; while(q--) { int count=0; int start=queries[i]; int end=queries[i+1]; for(int j=start-1;j<end && j<n;j++) { count+=arr[j]; } ans.push_back(count); i+=2; } return ans; 0 Suraj Kumar Modi7 months ago Suraj Kumar Modi Simple JAVA SolutionExecution time : 0.04 sec class Solution{ List<integer> querySum(int n, int arr[], int q, int queries[]) { List<integer> ob = new ArrayList<integer>(); int l = q * 2; for(int i=0;i<l-1;i=i+2) {="" ob.add(sum(arr,queries[i],queries[i+1]));="" }="" return="" ob;="" }="" public="" int="" sum(int="" arr[],int="" l,int="" r)="" {="" int="" sum="0;" l="l" -="" 1;="" r="r" -="" 1;="" for(int="" i="l;i&lt;=r;i++)" sum+="arr[i];" return="" sum;="" }="" }="" <="" code=""> 0 19wh1a05367 months ago Python3 Total Time Taken : 0.3 / 1.9 class Solution: def querySum(self, n, arr, q, queries): # code here sol = [] for i in range(0, len(queries), 2): j = i+1 ans = 0 for a in range(queries[i]-1,queries[j]): ans += arr[a] sol.append(ans) return sol 0 pushpakninave0077 months ago they havent mentioned that the array is sorted. either way it would be easy pheeeew..... We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 425, "s": 238, "text": "You are given an array arr[] of n integers and q queries in an array queries[] of length 2*q containing l, r pair for all q queries. You need to compute the following sum over q queries." }, { "code": null, "e": 447, "s": 427, "text": "Array is 1-Indexed." }, { "code": null, "e": 458, "s": 447, "text": "Example 1:" }, { "code": null, "e": 679, "s": 458, "text": "Input: n = 4\narr = {1, 2, 3, 4}\nq = 2\nqueries = {1, 4, 2, 3}\nOutput: 10 5\nExplaination: In the first query we need sum \nfrom 1 to 4 which is 1+2+3+4 = 10. In the \nsecond query we need sum from 2 to 3 which is \n2 + 3 = 5." }, { "code": null, "e": 886, "s": 679, "text": "Your Task:\nYou do not need to read input or print anything. Your task is to complete the function querySum() which takes n, arr, q and queries as input parameters and returns the answer for all the queries." }, { "code": null, "e": 950, "s": 886, "text": "Expected Time Complexity: O(n+q)\nExpected Auxiliary Space: O(n)" }, { "code": null, "e": 1008, "s": 950, "text": "Constraints:\n1 ≤ n, q ≤ 1000\n1 ≤ arri ≤ 106\n1 ≤ l ≤ r ≤ n" }, { "code": null, "e": 1010, "s": 1008, "text": "0" }, { "code": null, "e": 1032, "s": 1010, "text": "18pa1a04771 month ago" }, { "code": null, "e": 1965, "s": 1032, "text": "0.2/1.9 sec using square root decompositio\nimport math\nclass Solution:\n def querySum(self, n, arr, q, qe):\n val=int(math.sqrt(n))\n d={}\n for i in range(n):\n if (i+1)//val in d:\n d[(i+1)//val]=d[(i+1)//val]+arr[i]\n else:\n d[(i+1)//val]=arr[i]\n ans=[]\n for l in range(0,len(qe),2):\n s=0\n lf=qe[l]\n ri=qe[l+1]\n for k in range(lf,ri+1):\n if k//val==lf//val+1:\n break\n s=s+arr[k-1]\n if lf//val==ri//val:\n ans.append(s)\n continue\n for k in range(ri,lf-1,-1):\n if k//val==ri//val-1:\n break\n s=s+arr[k-1]\n for k in range((lf//val)+1,(ri//val)):\n if k in d:\n s=s+d[k]\n ans.append(s)\n return ans" }, { "code": null, "e": 1967, "s": 1965, "text": "0" }, { "code": null, "e": 1992, "s": 1967, "text": "kiransaisk4481 month ago" }, { "code": null, "e": 2016, "s": 1992, "text": "simple python solution:" }, { "code": null, "e": 2290, "s": 2016, "text": "class Solution:\n def querySum(self, n, arr, q, queries):\n # code here\n result = []\n for i in range(0, 2*q-1, 2):\n left = queries[i] - 1\n right = queries[i+1]\n result.append(sum(arr[left:right]))\n return result" }, { "code": null, "e": 2292, "s": 2290, "text": "0" }, { "code": null, "e": 2321, "s": 2292, "text": "mohankumarit20012 months ago" }, { "code": null, "e": 2684, "s": 2321, "text": " vector<int> querySum(int n, int arr[], int q, int queries[])\n {\n for(int i=1;i<n;i++){\n arr[i]+=arr[i-1];\n }\n vector<int> res;\n for(int i=0;i<2*q;i+=2){\n if(queries[i]==0)res.push_back(arr[queries[i+1]-1]);\n res.push_back(arr[queries[i+1]-1]-arr[queries[i]-2]);\n }\n return res;\n }" }, { "code": null, "e": 2686, "s": 2684, "text": "0" }, { "code": null, "e": 2712, "s": 2686, "text": "annanyamathur2 months ago" }, { "code": null, "e": 2731, "s": 2712, "text": "Using Segment Tree" }, { "code": null, "e": 3599, "s": 2733, "text": "int tree[100000];int getSum(int l,int r,int start,int end,int index){ if(l>end || r<start) return 0; if(start>=l && end<=r) return tree[index]; int mid=(start+end)/2; return getSum(l,r,start,mid,2*index+1)+getSum(l,r,mid+1,end,2*index+2);}void constructST(int arr[],int start,int end,int index){ if(start==end) {tree[index]=arr[start]; return; } int mid=(start+end)/2; constructST(arr,start,mid,2*index+1); constructST(arr,mid+1,end,2*index+2); tree[index]=tree[2*index+1]+tree[2*index+2]; } vector<int> querySum(int n, int arr[], int q, int queries[]) { vector<int>r; constructST(arr,0,n-1,0); for(int i=0;i<2*q;i+=2) { //cout<<i<<\"\\t\"<<queries[i]<<\"\\t\"<<queries[i+1]<<\"\\n\"; int a=getSum(queries[i]-1,queries[i+1]-1,0,n-1,0); r.push_back(a); } return r; }" }, { "code": null, "e": 3601, "s": 3599, "text": "0" }, { "code": null, "e": 3626, "s": 3601, "text": "kantariyaraj3 months ago" }, { "code": null, "e": 3647, "s": 3626, "text": "Simple Java solution" }, { "code": null, "e": 4097, "s": 3647, "text": "if(n == 0 || q == 0) return null;\n List<Integer> result = new ArrayList<>();\n int[] sumList = new int[n];\n sumList[0] = arr[0];\n for(int i = 1; i < n; i++){\n sumList[i] = arr[i] + sumList[i-1]; \n }\n \n for(int i = 0; i < q; i++){\n int l = queries[2 * i] - 1;\n int r= queries[(2 * i) + 1] - 1;\n result.add(sumList[r]-sumList[l]);\n }\n \n return result;\n" }, { "code": null, "e": 4099, "s": 4097, "text": "0" }, { "code": null, "e": 4123, "s": 4099, "text": "chessnoobdj5 months ago" }, { "code": null, "e": 4154, "s": 4123, "text": "Optimized c++ using prefix sum" }, { "code": null, "e": 4556, "s": 4154, "text": "vector<int> querySum(int n, int arr[], int q, int queries[])\n {\n vector <int> ans;\n for(int i=1; i<n; i++)\n arr[i] += arr[i-1];\n for(int i=0; i<2*q; i += 2){\n if(queries[i] == 1)\n ans.push_back(arr[queries[i+1]-1]);\n else\n ans.push_back(arr[queries[i+1]-1] - arr[queries[i]-2]);\n }\n return ans;\n }" }, { "code": null, "e": 4558, "s": 4556, "text": "0" }, { "code": null, "e": 4583, "s": 4558, "text": "gurshaansing6 months ago" }, { "code": null, "e": 4900, "s": 4583, "text": "vector<int> ans; int i=0; while(q--) { int count=0; int start=queries[i]; int end=queries[i+1]; for(int j=start-1;j<end && j<n;j++) { count+=arr[j]; } ans.push_back(count); i+=2; } return ans;" }, { "code": null, "e": 4902, "s": 4900, "text": "0" }, { "code": null, "e": 4931, "s": 4902, "text": "Suraj Kumar Modi7 months ago" }, { "code": null, "e": 4948, "s": 4931, "text": "Suraj Kumar Modi" }, { "code": null, "e": 4994, "s": 4948, "text": "Simple JAVA SolutionExecution time : 0.04 sec" }, { "code": null, "e": 5462, "s": 4994, "text": "class Solution{ List<integer> querySum(int n, int arr[], int q, int queries[]) { List<integer> ob = new ArrayList<integer>(); int l = q * 2; for(int i=0;i<l-1;i=i+2) {=\"\" ob.add(sum(arr,queries[i],queries[i+1]));=\"\" }=\"\" return=\"\" ob;=\"\" }=\"\" public=\"\" int=\"\" sum(int=\"\" arr[],int=\"\" l,int=\"\" r)=\"\" {=\"\" int=\"\" sum=\"0;\" l=\"l\" -=\"\" 1;=\"\" r=\"r\" -=\"\" 1;=\"\" for(int=\"\" i=\"l;i&lt;=r;i++)\" sum+=\"arr[i];\" return=\"\" sum;=\"\" }=\"\" }=\"\" <=\"\" code=\"\">" }, { "code": null, "e": 5464, "s": 5462, "text": "0" }, { "code": null, "e": 5487, "s": 5464, "text": "19wh1a05367 months ago" }, { "code": null, "e": 5495, "s": 5487, "text": "Python3" }, { "code": null, "e": 5524, "s": 5495, "text": "Total Time Taken : 0.3 / 1.9" }, { "code": null, "e": 5818, "s": 5526, "text": "class Solution: def querySum(self, n, arr, q, queries): # code here sol = [] for i in range(0, len(queries), 2): j = i+1 ans = 0 for a in range(queries[i]-1,queries[j]): ans += arr[a] sol.append(ans) return sol " }, { "code": null, "e": 5820, "s": 5818, "text": "0" }, { "code": null, "e": 5849, "s": 5820, "text": "pushpakninave0077 months ago" }, { "code": null, "e": 5938, "s": 5849, "text": "they havent mentioned that the array is sorted. either way it would be easy pheeeew....." }, { "code": null, "e": 6084, "s": 5938, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 6120, "s": 6084, "text": " Login to access your submissions. " }, { "code": null, "e": 6130, "s": 6120, "text": "\nProblem\n" }, { "code": null, "e": 6140, "s": 6130, "text": "\nContest\n" }, { "code": null, "e": 6203, "s": 6140, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 6351, "s": 6203, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 6559, "s": 6351, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 6665, "s": 6559, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
What’s the best way to reload / refresh an iframe? - GeeksforGeeks
17 Jun, 2019 Suppose that a user creates a webpage. Now he has a webpage, which contains an IFrame and a Button. Once the user presses the button, he/she needs the IFrame to be reloaded/refreshed. How are we going to make this possible? We are going to be finding it in the article. The following syntax is work for both cases, where the IFrame is provided & loaded from the same domain, and where the IFrame is not from the same domain. Syntax: document.getElementById('YOUR IFRAME').contentDocument.location.reload(true); NOTE: In Firefox, if you are going to use window.frames[], it might not be indexed by id. So you have to index it by index or name. Example 1: <!DOCTYPE html><html> <head> <style> iframe { width: 786px; height: 600px; border: 0; overflow: hidden; } </style></head> <body> <center> <h2 style="color:green">GeeksforGeeks</h2> <h4 style="color:purple">Reload / Refresh an iframe</h4> <iframe id="iframeid" src="https://ide.geeksforgeeks.org/" width="600" height="450" frameborder="0" style="border:0" allowfullscreen> </iframe> <input type="button" id="btn" value="Refresh" /> <script> function reload() { document.getElementById('iframeid').src += ''; } btn.onclick = reload; </script> </center> </body> </html> Output:Before Refresh: After Refresh: Example 2: <!DOCTYPE html><html> <head> <style> body { text-align: center; } iframe { width: 786px; height: 600px; border: 0; overflow: hidden; } </style></head> <body> <h2 style="color:green">GeeksforGeeks</h2> <h4 style="color:purple">Reload / Refresh an iframe</h4> <iframe id="iframeid" src="Map Source" width="600" height="450" frameborder="0" style="border:0" allowfullscreen> </iframe> <input type="button" id="btn" value="Refresh" /> <script> function reload() { document.getElementById('iframeid').src += ''; } btn.onclick = reload; </script> </body> </html> Output:When we load the code: The Working: JavaScript-Misc Picked JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between var, let and const keywords in JavaScript Convert a string to an integer in JavaScript Differences between Functional Components and Class Components in React How to append HTML code to a div using JavaScript ? How to Open URL in New Tab using JavaScript ? 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": 24097, "s": 24069, "text": "\n17 Jun, 2019" }, { "code": null, "e": 24367, "s": 24097, "text": "Suppose that a user creates a webpage. Now he has a webpage, which contains an IFrame and a Button. Once the user presses the button, he/she needs the IFrame to be reloaded/refreshed. How are we going to make this possible? We are going to be finding it in the article." }, { "code": null, "e": 24522, "s": 24367, "text": "The following syntax is work for both cases, where the IFrame is provided & loaded from the same domain, and where the IFrame is not from the same domain." }, { "code": null, "e": 24530, "s": 24522, "text": "Syntax:" }, { "code": null, "e": 24608, "s": 24530, "text": "document.getElementById('YOUR IFRAME').contentDocument.location.reload(true);" }, { "code": null, "e": 24740, "s": 24608, "text": "NOTE: In Firefox, if you are going to use window.frames[], it might not be indexed by id. So you have to index it by index or name." }, { "code": null, "e": 24751, "s": 24740, "text": "Example 1:" }, { "code": "<!DOCTYPE html><html> <head> <style> iframe { width: 786px; height: 600px; border: 0; overflow: hidden; } </style></head> <body> <center> <h2 style=\"color:green\">GeeksforGeeks</h2> <h4 style=\"color:purple\">Reload / Refresh an iframe</h4> <iframe id=\"iframeid\" src=\"https://ide.geeksforgeeks.org/\" width=\"600\" height=\"450\" frameborder=\"0\" style=\"border:0\" allowfullscreen> </iframe> <input type=\"button\" id=\"btn\" value=\"Refresh\" /> <script> function reload() { document.getElementById('iframeid').src += ''; } btn.onclick = reload; </script> </center> </body> </html>", "e": 25612, "s": 24751, "text": null }, { "code": null, "e": 25635, "s": 25612, "text": "Output:Before Refresh:" }, { "code": null, "e": 25650, "s": 25635, "text": "After Refresh:" }, { "code": null, "e": 25661, "s": 25650, "text": "Example 2:" }, { "code": "<!DOCTYPE html><html> <head> <style> body { text-align: center; } iframe { width: 786px; height: 600px; border: 0; overflow: hidden; } </style></head> <body> <h2 style=\"color:green\">GeeksforGeeks</h2> <h4 style=\"color:purple\">Reload / Refresh an iframe</h4> <iframe id=\"iframeid\" src=\"Map Source\" width=\"600\" height=\"450\" frameborder=\"0\" style=\"border:0\" allowfullscreen> </iframe> <input type=\"button\" id=\"btn\" value=\"Refresh\" /> <script> function reload() { document.getElementById('iframeid').src += ''; } btn.onclick = reload; </script> </body> </html>", "e": 26466, "s": 25661, "text": null }, { "code": null, "e": 26496, "s": 26466, "text": "Output:When we load the code:" }, { "code": null, "e": 26509, "s": 26496, "text": "The Working:" }, { "code": null, "e": 26525, "s": 26509, "text": "JavaScript-Misc" }, { "code": null, "e": 26532, "s": 26525, "text": "Picked" }, { "code": null, "e": 26543, "s": 26532, "text": "JavaScript" }, { "code": null, "e": 26560, "s": 26543, "text": "Web Technologies" }, { "code": null, "e": 26658, "s": 26560, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26667, "s": 26658, "text": "Comments" }, { "code": null, "e": 26680, "s": 26667, "text": "Old Comments" }, { "code": null, "e": 26741, "s": 26680, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 26786, "s": 26741, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 26858, "s": 26786, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 26910, "s": 26858, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 26956, "s": 26910, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 27012, "s": 26956, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 27045, "s": 27012, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27107, "s": 27045, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 27150, "s": 27107, "text": "How to fetch data from an API in ReactJS ?" } ]
What to Do When Your Data Is Too Big for Your Memory? | by Sara A. Metwalli | Towards Data Science
When we are working on any data science project, one of the essential steps to take is to download some data from an API to the memory so we can process it. When doing that, there are some problems that we can face; one of these problems is having too much data to process. If the size of our data is larger than the size of our available memory (RAM), we might face some problems in getting the project done. So, what to do then? There are different options to solve the problem of big data, small problems. These solutions either cost time or money. Money-costing solution: One possible solution is to buy a new computer with a more robust CPU and larger RAM that is capable of handling the entire dataset. Or, rent a cloud or a virtual memory and then create some clustering arrangement to handle the workload.Time-costing solution: Your RAM might be too small to handle your data, but often, your hard drive is much larger than your RAM. So, why not just use it? Using the hard drive to deal with your date will make the processing of it much slower because even an SSD hard drive is slower than a RAM. Money-costing solution: One possible solution is to buy a new computer with a more robust CPU and larger RAM that is capable of handling the entire dataset. Or, rent a cloud or a virtual memory and then create some clustering arrangement to handle the workload. Time-costing solution: Your RAM might be too small to handle your data, but often, your hard drive is much larger than your RAM. So, why not just use it? Using the hard drive to deal with your date will make the processing of it much slower because even an SSD hard drive is slower than a RAM. Now, both those solutions are very valid, that is, if you have the resources to do so. If you have a big budget for your project or the time is not a constraint, then using one of those techniques is the simplest and most straightforward answer. But, What if you can’t? What if you’re working on a budget? What if your data is so big, loading it from the drive will increase your processing time 5X or 6X or even more? Is there a solution to handling big data that doesn’t cost money or time? I am glad you asked — or I asked?. There are some techniques that you can use to handle big data that don’t require spending any money or having to deal with long loading times. This article will cover 3 techniques that you can implement using Pandas to deal with large size datasets. The first technique we will cover is compressing the data. Compression here doesn’t mean putting the data in a ZIP file; it instead means storing the data in the memory in a compressed format. In other words, compressing the data is finding a way to represent the data in a different way that will use less memory. There are two types of data compression: lossless compression and lossy one. Both these types only affect the loading of your data and won’t cause any changes in the processing section of your code. Lossless compression doesn’t cause any losses in the data. That is, the original data and the compressed ones are semantically identical. You can perform lossless compression on your data frames in 3 ways: For the remainder of this article, I will use this dataset that contains COVID-19 cases in the united states divided into different counties. Load specific columns The dataset I am using has the following structure: import pandas as pddata = pd.read_csv("https://raw.githubusercontent.com/nytimes/covid-19-data/master/us-counties.csv")data.sample(10) Loading the entire dataset takes 111 MB of memory! However, I really only need two columns of this dataset, the county and the case columns, so why would I load the entire dataset? Loading only the two columns I need requires 36 MB, which is a 32% decrease in memory usage. I can use Pandas to load only the columns I need like this Code snippet for this section Manipulate datatypes Another way to decrease the memory usage of our data is to truncate numerical items in the data. For example, whenever we load a CSV into a column in a data frame, if the file contains numbers, it will store it as which takes 64 bytes to store one numerical value. However, we can truncate that and use other int formates to save some memory. int8 can store integers from -128 to 127. int16 can store integers from -32768 to 32767. int64 can store integers from -9223372036854775808 to 9223372036854775807. if you know that the numbers in a particular column will never be higher than 32767, you can use an int16 or int32 and reduce the memory usage of that column by 75%. So, assume that the number of cases in each county can’t exceed 32767 — which is not true in real-life — then, we can truncate that column to int16 instead of int64. Sparse columns If the data has a column or more with lots of empty values stored as NaN you save memory by using a sparse column representation so you won't waste memory storing all those empty values. Assume the county column has some NaN values and I just want to skip the rows containing NaN, I can do that easily using sparse series. What if performing lossless compression wasn’t enough? What if I need to compress my data even more? In this case, you can use lossy compression, so you sacrifice 100% accuracy in your data for the sake of memory usage. You can perform lossy compression in two ways: modify numeric values and sampling. Modifying numeric values: Sometimes, you don’t need full accuracy in your numeric data so that you can truncate them from int64 to int32 or int16. Sampling: Maybe you want to prove that some states have higher COVID cases than others, so you take a sample of some counties to see which states have more cases. Doing that is considered lossy compression because you’re not considering all rows. Another way to handle large datasets is by chunking them. That is cutting a large dataset into smaller chunks and then processing those chunks individually. After all the chunks have been processed, you can compare the results and calculate the final findings. This dataset contains 1923 rows. Let’s assume I want to find the country with the most number of cases. I can divide my dataset into chunks of 100 rows and process each of them individually and then get the maximum of the smaller results. Code snippet for this section Chunking is excellent if you need to load your dataset only once, but if you want to load multiple datasets, then indexing is the way to go. Think of indexing as the index of a book; you can know the necessary information about an aspect without needing to read the entire book. For example, let’s say I want to get the cases for a specific state. In this case, chunking would make sense; I could write a simple function that accomplishes that. In chunking, you need to read all data, while in indexing, you just need a part of the data. So, my small function loads all the rows in each chunk but only cares about the ones for the state I want. That leads to significant overhead. I can avoid having this by using a database next to Pandas. The simplest one I can use is SQLite. To do that, I first need to load my data frame into an SQLite database. Then I need to re-write my get_state_info function and use the database in it. By doing that, I can decrease the memory usage by 50%. Handing big datasets can be such a hassle, especially if it doesn’t fit in your memory. Some solutions for that can either be time or money consuming, which is you have the resource that could be the simplest, most straightforward approach. However, if you don’t have the resources, you can use some techniques in Pandas to decrease the memory usage of loading your data — techniques such as compression, indexing, and chucking.
[ { "code": null, "e": 329, "s": 172, "text": "When we are working on any data science project, one of the essential steps to take is to download some data from an API to the memory so we can process it." }, { "code": null, "e": 582, "s": 329, "text": "When doing that, there are some problems that we can face; one of these problems is having too much data to process. If the size of our data is larger than the size of our available memory (RAM), we might face some problems in getting the project done." }, { "code": null, "e": 603, "s": 582, "text": "So, what to do then?" }, { "code": null, "e": 724, "s": 603, "text": "There are different options to solve the problem of big data, small problems. These solutions either cost time or money." }, { "code": null, "e": 1279, "s": 724, "text": "Money-costing solution: One possible solution is to buy a new computer with a more robust CPU and larger RAM that is capable of handling the entire dataset. Or, rent a cloud or a virtual memory and then create some clustering arrangement to handle the workload.Time-costing solution: Your RAM might be too small to handle your data, but often, your hard drive is much larger than your RAM. So, why not just use it? Using the hard drive to deal with your date will make the processing of it much slower because even an SSD hard drive is slower than a RAM." }, { "code": null, "e": 1541, "s": 1279, "text": "Money-costing solution: One possible solution is to buy a new computer with a more robust CPU and larger RAM that is capable of handling the entire dataset. Or, rent a cloud or a virtual memory and then create some clustering arrangement to handle the workload." }, { "code": null, "e": 1835, "s": 1541, "text": "Time-costing solution: Your RAM might be too small to handle your data, but often, your hard drive is much larger than your RAM. So, why not just use it? Using the hard drive to deal with your date will make the processing of it much slower because even an SSD hard drive is slower than a RAM." }, { "code": null, "e": 2081, "s": 1835, "text": "Now, both those solutions are very valid, that is, if you have the resources to do so. If you have a big budget for your project or the time is not a constraint, then using one of those techniques is the simplest and most straightforward answer." }, { "code": null, "e": 2086, "s": 2081, "text": "But," }, { "code": null, "e": 2328, "s": 2086, "text": "What if you can’t? What if you’re working on a budget? What if your data is so big, loading it from the drive will increase your processing time 5X or 6X or even more? Is there a solution to handling big data that doesn’t cost money or time?" }, { "code": null, "e": 2363, "s": 2328, "text": "I am glad you asked — or I asked?." }, { "code": null, "e": 2613, "s": 2363, "text": "There are some techniques that you can use to handle big data that don’t require spending any money or having to deal with long loading times. This article will cover 3 techniques that you can implement using Pandas to deal with large size datasets." }, { "code": null, "e": 2806, "s": 2613, "text": "The first technique we will cover is compressing the data. Compression here doesn’t mean putting the data in a ZIP file; it instead means storing the data in the memory in a compressed format." }, { "code": null, "e": 3127, "s": 2806, "text": "In other words, compressing the data is finding a way to represent the data in a different way that will use less memory. There are two types of data compression: lossless compression and lossy one. Both these types only affect the loading of your data and won’t cause any changes in the processing section of your code." }, { "code": null, "e": 3333, "s": 3127, "text": "Lossless compression doesn’t cause any losses in the data. That is, the original data and the compressed ones are semantically identical. You can perform lossless compression on your data frames in 3 ways:" }, { "code": null, "e": 3475, "s": 3333, "text": "For the remainder of this article, I will use this dataset that contains COVID-19 cases in the united states divided into different counties." }, { "code": null, "e": 3497, "s": 3475, "text": "Load specific columns" }, { "code": null, "e": 3549, "s": 3497, "text": "The dataset I am using has the following structure:" }, { "code": null, "e": 3684, "s": 3549, "text": "import pandas as pddata = pd.read_csv(\"https://raw.githubusercontent.com/nytimes/covid-19-data/master/us-counties.csv\")data.sample(10)" }, { "code": null, "e": 3735, "s": 3684, "text": "Loading the entire dataset takes 111 MB of memory!" }, { "code": null, "e": 3958, "s": 3735, "text": "However, I really only need two columns of this dataset, the county and the case columns, so why would I load the entire dataset? Loading only the two columns I need requires 36 MB, which is a 32% decrease in memory usage." }, { "code": null, "e": 4017, "s": 3958, "text": "I can use Pandas to load only the columns I need like this" }, { "code": null, "e": 4047, "s": 4017, "text": "Code snippet for this section" }, { "code": null, "e": 4068, "s": 4047, "text": "Manipulate datatypes" }, { "code": null, "e": 4411, "s": 4068, "text": "Another way to decrease the memory usage of our data is to truncate numerical items in the data. For example, whenever we load a CSV into a column in a data frame, if the file contains numbers, it will store it as which takes 64 bytes to store one numerical value. However, we can truncate that and use other int formates to save some memory." }, { "code": null, "e": 4453, "s": 4411, "text": "int8 can store integers from -128 to 127." }, { "code": null, "e": 4500, "s": 4453, "text": "int16 can store integers from -32768 to 32767." }, { "code": null, "e": 4575, "s": 4500, "text": "int64 can store integers from -9223372036854775808 to 9223372036854775807." }, { "code": null, "e": 4741, "s": 4575, "text": "if you know that the numbers in a particular column will never be higher than 32767, you can use an int16 or int32 and reduce the memory usage of that column by 75%." }, { "code": null, "e": 4907, "s": 4741, "text": "So, assume that the number of cases in each county can’t exceed 32767 — which is not true in real-life — then, we can truncate that column to int16 instead of int64." }, { "code": null, "e": 4922, "s": 4907, "text": "Sparse columns" }, { "code": null, "e": 5109, "s": 4922, "text": "If the data has a column or more with lots of empty values stored as NaN you save memory by using a sparse column representation so you won't waste memory storing all those empty values." }, { "code": null, "e": 5245, "s": 5109, "text": "Assume the county column has some NaN values and I just want to skip the rows containing NaN, I can do that easily using sparse series." }, { "code": null, "e": 5465, "s": 5245, "text": "What if performing lossless compression wasn’t enough? What if I need to compress my data even more? In this case, you can use lossy compression, so you sacrifice 100% accuracy in your data for the sake of memory usage." }, { "code": null, "e": 5548, "s": 5465, "text": "You can perform lossy compression in two ways: modify numeric values and sampling." }, { "code": null, "e": 5695, "s": 5548, "text": "Modifying numeric values: Sometimes, you don’t need full accuracy in your numeric data so that you can truncate them from int64 to int32 or int16." }, { "code": null, "e": 5942, "s": 5695, "text": "Sampling: Maybe you want to prove that some states have higher COVID cases than others, so you take a sample of some counties to see which states have more cases. Doing that is considered lossy compression because you’re not considering all rows." }, { "code": null, "e": 6203, "s": 5942, "text": "Another way to handle large datasets is by chunking them. That is cutting a large dataset into smaller chunks and then processing those chunks individually. After all the chunks have been processed, you can compare the results and calculate the final findings." }, { "code": null, "e": 6236, "s": 6203, "text": "This dataset contains 1923 rows." }, { "code": null, "e": 6442, "s": 6236, "text": "Let’s assume I want to find the country with the most number of cases. I can divide my dataset into chunks of 100 rows and process each of them individually and then get the maximum of the smaller results." }, { "code": null, "e": 6472, "s": 6442, "text": "Code snippet for this section" }, { "code": null, "e": 6613, "s": 6472, "text": "Chunking is excellent if you need to load your dataset only once, but if you want to load multiple datasets, then indexing is the way to go." }, { "code": null, "e": 6751, "s": 6613, "text": "Think of indexing as the index of a book; you can know the necessary information about an aspect without needing to read the entire book." }, { "code": null, "e": 6917, "s": 6751, "text": "For example, let’s say I want to get the cases for a specific state. In this case, chunking would make sense; I could write a simple function that accomplishes that." }, { "code": null, "e": 7010, "s": 6917, "text": "In chunking, you need to read all data, while in indexing, you just need a part of the data." }, { "code": null, "e": 7251, "s": 7010, "text": "So, my small function loads all the rows in each chunk but only cares about the ones for the state I want. That leads to significant overhead. I can avoid having this by using a database next to Pandas. The simplest one I can use is SQLite." }, { "code": null, "e": 7323, "s": 7251, "text": "To do that, I first need to load my data frame into an SQLite database." }, { "code": null, "e": 7402, "s": 7323, "text": "Then I need to re-write my get_state_info function and use the database in it." }, { "code": null, "e": 7457, "s": 7402, "text": "By doing that, I can decrease the memory usage by 50%." }, { "code": null, "e": 7698, "s": 7457, "text": "Handing big datasets can be such a hassle, especially if it doesn’t fit in your memory. Some solutions for that can either be time or money consuming, which is you have the resource that could be the simplest, most straightforward approach." } ]
MySQL Cursor DECLARE Statement
A cursor in database is a construct which allows you to iterate/traversal the records of a table. In MySQL you can use cursors with in a stored program such as procedures, functions etc. In other words, you can iterate though the records of a table from a MySQL stored program using the cursors. The cursors provided by MySQL are embedded cursors. They are − READ ONLY − Using these cursors you cannot update any table. READ ONLY − Using these cursors you cannot update any table. Non-Scrollable − Using these cursors you can retrieve records from a table in one direction i.e., from top to bottom. Non-Scrollable − Using these cursors you can retrieve records from a table in one direction i.e., from top to bottom. Asensitive − These cursors are insensitive to the changes that are made in the table i.e. the modifications done in the table are not reflected in the cursor. Which means if we have created a cursor holding all the records in a table and, meanwhile if we add some more records to the table, these recent changes will not be reflected in the cursor we previously obtained. Asensitive − These cursors are insensitive to the changes that are made in the table i.e. the modifications done in the table are not reflected in the cursor. Which means if we have created a cursor holding all the records in a table and, meanwhile if we add some more records to the table, these recent changes will not be reflected in the cursor we previously obtained. While Declaring cursors in a stored program you need to make sure these (cursor declarations) always follow the variable and condition declarations. To use a cursor, you need to follow the steps given below (in the same order) Declare the cursor using the DECLARE Statement. Declare variables and conditions. Open the declared cursor using the OPEN Statement. Retrieve the desired records from a table using the FETCH Statement. Finally close the cursor using the CLOSEstatement. Using the DECLARE statement you can declare a cursor and associate It with the SELECT statement which fetches the desired records from a table. This SELECT statement associated with a cursor does not allow INTO clause. Once you declare a cursor you can retrieve records from it using the FETCH statement. You need to make sure the cursor declaration precedes handler declarations. You can create use cursors in a single stored program. Following is the syntax of the MySQL Cursor DECLARE Statement − DECLARE cursor_name CURSOR FOR select_statement; Assume we have created a table with name tutorials in MySQL database using CREATE statement as shown below − CREATE TABLE tutorials ( ID INT PRIMARY KEY, TITLE VARCHAR(100), AUTHOR VARCHAR(40), DATE VARCHAR(40) ); Now, we will insert 5 records in tutorials table using INSERT statements − insert into tutorials values(1, 'Java', 'Krishna', '2019-09-01'); insert into tutorials values(2, 'JFreeCharts', 'Satish', '2019-05-01'); insert into tutorials values(3, 'JavaSprings', 'Amit', '2019-05-01'); insert into tutorials values(4, 'Android', 'Ram', '2019-03-01'); insert into tutorials values(5, 'Cassandra', 'Pruthvi', '2019-04-06'); Let us create another table to back up the data − CREATE TABLE backup ( ID INT, TITLE VARCHAR(100), AUTHOR VARCHAR(40), DATE VARCHAR(40) ); Following procedure backups the contents of the tutorials table to the backup table using cursors − DELIMITER // CREATE PROCEDURE ExampleProc() BEGIN DECLARE done INT DEFAULT 0; DECLARE tutorialID INTEGER; DECLARE tutorialTitle, tutorialAuthor, tutorialDate VARCHAR(20); DECLARE cur CURSOR FOR SELECT * FROM tutorials; DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1; OPEN cur; label: LOOP FETCH cur INTO tutorialID, tutorialTitle, tutorialAuthor, tutorialDate; INSERT INTO backup VALUES(tutorialID, tutorialTitle, tutorialAuthor, tutorialDate); IF done = 1 THEN LEAVE label; END IF; END LOOP; CLOSE cur; END// DELIMITER ; You can call the above procedure as shown below − mysql> CALL ExampleProc; Query OK, 1 row affected (0.78 sec) If you verify the contents of the backup table you can see the inserted records as shown below − mysql> select * from backup; +------+-------------+---------+------------+ | ID | TITLE | AUTHOR | DATE | +------+-------------+---------+------------+ | 1 | Java | Krishna | 2019-09-01 | | 2 | JFreeCharts | Satish | 2019-05-01 | | 3 | JavaSprings | Amit | 2019-05-01 | | 4 | Android | Ram | 2019-03-01 | | 5 | Cassandra | Pruthvi | 2019-04-06 | +------+-------------+---------+------------+ 5 rows in set (0.08 sec) 31 Lectures 6 hours Eduonix Learning Solutions 84 Lectures 5.5 hours Frahaan Hussain 6 Lectures 3.5 hours DATAhill Solutions Srinivas Reddy 60 Lectures 10 hours Vijay Kumar Parvatha Reddy 10 Lectures 1 hours Harshit Srivastava 25 Lectures 4 hours Trevoir Williams Print Add Notes Bookmark this page
[ { "code": null, "e": 2520, "s": 2333, "text": "A cursor in database is a construct which allows you to iterate/traversal the records of a table. In MySQL you can use cursors with in a stored program such as procedures, functions etc." }, { "code": null, "e": 2692, "s": 2520, "text": "In other words, you can iterate though the records of a table from a MySQL stored program using the cursors. The cursors provided by MySQL are embedded cursors. They are −" }, { "code": null, "e": 2753, "s": 2692, "text": "READ ONLY − Using these cursors you cannot update any table." }, { "code": null, "e": 2814, "s": 2753, "text": "READ ONLY − Using these cursors you cannot update any table." }, { "code": null, "e": 2932, "s": 2814, "text": "Non-Scrollable − Using these cursors you can retrieve records from a table in one direction i.e., from top to bottom." }, { "code": null, "e": 3050, "s": 2932, "text": "Non-Scrollable − Using these cursors you can retrieve records from a table in one direction i.e., from top to bottom." }, { "code": null, "e": 3422, "s": 3050, "text": "Asensitive − These cursors are insensitive to the changes that are made in the table i.e. the modifications done in the table are not reflected in the cursor.\nWhich means if we have created a cursor holding all the records in a table and, meanwhile if we add some more records to the table, these recent changes will not be reflected in the cursor we previously obtained." }, { "code": null, "e": 3581, "s": 3422, "text": "Asensitive − These cursors are insensitive to the changes that are made in the table i.e. the modifications done in the table are not reflected in the cursor." }, { "code": null, "e": 3794, "s": 3581, "text": "Which means if we have created a cursor holding all the records in a table and, meanwhile if we add some more records to the table, these recent changes will not be reflected in the cursor we previously obtained." }, { "code": null, "e": 3943, "s": 3794, "text": "While Declaring cursors in a stored program you need to make sure these (cursor declarations) always follow the variable and condition declarations." }, { "code": null, "e": 4021, "s": 3943, "text": "To use a cursor, you need to follow the steps given below (in the same order)" }, { "code": null, "e": 4069, "s": 4021, "text": "Declare the cursor using the DECLARE Statement." }, { "code": null, "e": 4103, "s": 4069, "text": "Declare variables and conditions." }, { "code": null, "e": 4154, "s": 4103, "text": "Open the declared cursor using the OPEN Statement." }, { "code": null, "e": 4223, "s": 4154, "text": "Retrieve the desired records from a table using the FETCH Statement." }, { "code": null, "e": 4274, "s": 4223, "text": "Finally close the cursor using the CLOSEstatement." }, { "code": null, "e": 4493, "s": 4274, "text": "Using the DECLARE statement you can declare a cursor and associate It with the SELECT statement which fetches the desired records from a table. This SELECT statement associated with a cursor does not allow INTO clause." }, { "code": null, "e": 4710, "s": 4493, "text": "Once you declare a cursor you can retrieve records from it using the FETCH statement. You need to make sure the cursor declaration precedes handler declarations. You can create use cursors in a single stored program." }, { "code": null, "e": 4774, "s": 4710, "text": "Following is the syntax of the MySQL Cursor DECLARE Statement −" }, { "code": null, "e": 4824, "s": 4774, "text": "DECLARE cursor_name CURSOR FOR select_statement;\n" }, { "code": null, "e": 4933, "s": 4824, "text": "Assume we have created a table with name tutorials in MySQL database using CREATE statement as shown below −" }, { "code": null, "e": 5050, "s": 4933, "text": "CREATE TABLE tutorials (\n ID INT PRIMARY KEY,\n TITLE VARCHAR(100),\n AUTHOR VARCHAR(40),\n DATE VARCHAR(40)\n);" }, { "code": null, "e": 5125, "s": 5050, "text": "Now, we will insert 5 records in tutorials table using INSERT statements −" }, { "code": null, "e": 5469, "s": 5125, "text": "insert into tutorials values(1, 'Java', 'Krishna', '2019-09-01');\ninsert into tutorials values(2, 'JFreeCharts', 'Satish', '2019-05-01');\ninsert into tutorials values(3, 'JavaSprings', 'Amit', '2019-05-01');\ninsert into tutorials values(4, 'Android', 'Ram', '2019-03-01');\ninsert into tutorials values(5, 'Cassandra', 'Pruthvi', '2019-04-06');" }, { "code": null, "e": 5519, "s": 5469, "text": "Let us create another table to back up the data −" }, { "code": null, "e": 5621, "s": 5519, "text": "CREATE TABLE backup (\n ID INT,\n TITLE VARCHAR(100),\n AUTHOR VARCHAR(40),\n DATE VARCHAR(40)\n);" }, { "code": null, "e": 5721, "s": 5621, "text": "Following procedure backups the contents of the tutorials table to the backup table using cursors −" }, { "code": null, "e": 6332, "s": 5721, "text": "DELIMITER //\nCREATE PROCEDURE ExampleProc()\n BEGIN\n DECLARE done INT DEFAULT 0;\n DECLARE tutorialID INTEGER;\n DECLARE tutorialTitle, tutorialAuthor, tutorialDate VARCHAR(20);\n DECLARE cur CURSOR FOR SELECT * FROM tutorials;\n DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;\n OPEN cur;\n label: LOOP\n FETCH cur INTO tutorialID, tutorialTitle, tutorialAuthor, tutorialDate;\n INSERT INTO backup VALUES(tutorialID, tutorialTitle, tutorialAuthor, tutorialDate);\n IF done = 1 THEN LEAVE label;\n END IF;\n END LOOP;\n CLOSE cur;\n END//\nDELIMITER ;" }, { "code": null, "e": 6382, "s": 6332, "text": "You can call the above procedure as shown below −" }, { "code": null, "e": 6443, "s": 6382, "text": "mysql> CALL ExampleProc;\nQuery OK, 1 row affected (0.78 sec)" }, { "code": null, "e": 6540, "s": 6443, "text": "If you verify the contents of the backup table you can see the inserted records as shown below −" }, { "code": null, "e": 7008, "s": 6540, "text": "mysql> select * from backup;\n+------+-------------+---------+------------+\n| ID | TITLE | AUTHOR | DATE |\n+------+-------------+---------+------------+\n| 1 | Java | Krishna | 2019-09-01 |\n| 2 | JFreeCharts | Satish | 2019-05-01 |\n| 3 | JavaSprings | Amit | 2019-05-01 |\n| 4 | Android | Ram | 2019-03-01 |\n| 5 | Cassandra | Pruthvi | 2019-04-06 |\n+------+-------------+---------+------------+\n5 rows in set (0.08 sec)" }, { "code": null, "e": 7041, "s": 7008, "text": "\n 31 Lectures \n 6 hours \n" }, { "code": null, "e": 7069, "s": 7041, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 7104, "s": 7069, "text": "\n 84 Lectures \n 5.5 hours \n" }, { "code": null, "e": 7121, "s": 7104, "text": " Frahaan Hussain" }, { "code": null, "e": 7155, "s": 7121, "text": "\n 6 Lectures \n 3.5 hours \n" }, { "code": null, "e": 7190, "s": 7155, "text": " DATAhill Solutions Srinivas Reddy" }, { "code": null, "e": 7224, "s": 7190, "text": "\n 60 Lectures \n 10 hours \n" }, { "code": null, "e": 7252, "s": 7224, "text": " Vijay Kumar Parvatha Reddy" }, { "code": null, "e": 7285, "s": 7252, "text": "\n 10 Lectures \n 1 hours \n" }, { "code": null, "e": 7305, "s": 7285, "text": " Harshit Srivastava" }, { "code": null, "e": 7338, "s": 7305, "text": "\n 25 Lectures \n 4 hours \n" }, { "code": null, "e": 7356, "s": 7338, "text": " Trevoir Williams" }, { "code": null, "e": 7363, "s": 7356, "text": " Print" }, { "code": null, "e": 7374, "s": 7363, "text": " Add Notes" } ]
Advanced Python List Methods and Techniques - GeeksforGeeks
22 Sep, 2021 Lists are just like dynamically sized arrays, declared in other languages (vector in C++ and ArrayList in Java). Lists need not be homogeneous always which makes it a most powerful tool in Python. A single list may contain DataTypes like Integers, Strings, as well as Objects. Lists are mutable, and hence, they can be altered even after their creation. Lists are one of the most powerful tools in python. They have a lot of hidden tricks which makes them extremely versatile. Let’s explore some of these useful techniques which make our lives much easier !!! To sort a list in ascending or descending order, we use the sort() function with the following syntax: For ascending order: list.sort() For descending order: list.sort(reverse=True) Example: Python3 # sorting a list using sort() function my_list = [5, 2, 90, 24, 10] # sorting in ascending order it permanently# changes the order of the listmy_list.sort()print(my_list) # sorting in descending order it permanently# changes the order of the listmy_list.sort(reverse=True)print(my_list) Output: [2, 5, 10, 24, 90] [90, 24, 10, 5, 2] To temporarily change the order of the list use the sorted() function with the syntax: list.sorted() Python3 # temporary sorting using sorted() method my_list = [5, 2, 90, 24, 10] # ascending orderprint(sorted(my_list)) # descending ordermy_list_2 = sorted(my_list)print(my_list) Output: [2, 5, 10, 24, 90] [5, 2, 90, 24, 10] To reverse the order of a list we use the reverse() function. Its syntax is: list.reverse() Example: Python3 # reverse a list using reverse() my_list = [5, 2, 90, 24, 10] # reversemy_list.reverse()print(my_list) Output: [10, 24, 90, 2, 5] Or we could apply list comprehension to reverse a list: list = list[::-1] Example: Python3 # reverse using list comprehensionmy_list = [5, 2, 90, 24, 10] # reverseprint(my_list[::-1]) Output: [10, 24, 90, 2, 5] As dictionaries in python do not contain duplicate keys. We use the dict.fromkeys() function to convert our list into a dictionary with list elements as keys. And then we convert the dictionary back to list. This is a powerful trick to automatically remove all the duplicates. Its syntax is: My_list =[‘a’, ’b’, ’c’, ’b’, ’a’] Mylist = list(dict.fromkeys(My_List)) Example: Python3 # removing duplicates from a list using dictionaries my_list_1 = [5, 2, 90, 24, 10, 2, 90, 34]my_list_2 = ['a', 'a', 'a', 'b', 'c', 'd', 'd', 'e'] # removing duplicates from list 1my_list_1 = list(dict.fromkeys(my_list_1))print(my_list_1) # removing duplicates from list 2my_list_2 = list(dict.fromkeys(my_list_2))print(my_list_2) Output: [5, 2, 90, 24, 10, 34] ['a', 'b', 'c', 'd', 'e'] Python lists can be filtered with the help of filter() function or with the help of list comprehension. Below is the syntax: My_list = list(filter(filter_function , iterable_item)) The Filter function returns an iterator object which we must convert back into the list. Example: Python3 # filtering with the help of filter() function# creating a filter function filter all the values less than 20 # filter functiondef my_filter(n): if n > 20: return n # driver codeif __name__ == "__main__": my_list = [5, 2, 90, 24, 10, 2, 95, 36] my_filtered_list = list(filter(my_filter, my_list)) print(my_filtered_list) Output: [90, 24, 95, 36] We can also filter using list comprehension. It is a much easier and elegant way to filter lists, below is the syntax: My_list = [item for item in my_list if (condition)] Example: Python3 # filtering with the help of list comprehensionmy_list = [5, 2, 90, 24, 10, 2, 95, 36] # an elegant way to sort the listmy_list = [item for item in my_list if item > 20]print(my_list) Output: [90, 24, 95, 36] To modify the values in the list with the help of an external function, we make use of the map() function. Map() function returns a map object (iterator) of the results after applying the given function to each element of a given iterable(list, tuple etc.). Below is the syntax: My_list = list(map(function,iterable)) Example: Python3 # using map() function to modify the textdef squaring(n): return n**2 # driver codeif __name__ == "__main__": my_list = [5, 2, 90, 24, 10, 2, 95, 36] my_squared_list = list(map(squaring, my_list)) print(my_squared_list) Output: [25, 4, 8100, 576, 100, 4, 9025, 1296] A much cleaner approach is using list comprehension. Example: Python3 # the same result can be obtained by a much pythonic approach# i.e., by using list comprehensionmy_list = [5, 2, 90, 24, 10, 2, 95, 36] print([i**2 for i in my_list]) Output: [25, 4, 8100, 576, 100, 4, 9025, 1296] We can even combine lists with the help of the zip() function which results in a list of tuples. Here each item from list A is combined with corresponding elements from list B in the form of a tuple. Below is the syntax: My_list = zip(list_1, list_2) Example: Python3 # combing lists with the help of zip() functionmy_list_1 = [5, 2, 90, 24, 10]my_list_2 = [6, 3, 91, 25, 12] # combinedmy_combined_list = list(zip(my_list_1, my_list_2))print(my_combined_list) Output: [(5, 6), (2, 3), (90, 91), (24, 25), (10, 12)] To find the most frequent element we make use of the set() function. The set() function removes all the duplicates from the list, and the max() function returns the most frequent element (which is found with the help of ‘key’). The key is an optional single argument function. Below is the syntax: Most_frequent_value =max(set(my_list),key=mylist.count) Example : Python3 # to find the most frequent element from the listmy_list = ['a', 'a', 'a', 'b', 'c', 'd', 'd', 'e'] most_frequent_value = max(set(my_list), key=my_list.count) print("The most common element is:", most_frequent_value) Output: The most common element is: a To check whether an item exists in a list, we use the in statement. Example: Python3 my_list = ['a', 'a', 'a', 'b', 'c', 'd', 'd', 'e'] # to check whether 'c' is a member of my_list# returns true if presentprint('c' in my_list) # to check whether 'f' is a member of my_list# returns false if not presentprint('f' in my_list) Output: True False Sometimes we encounter a list where each element in itself is a list. To convert a list of lists into a single list, we use list comprehension. my_list = [item for List in list_of_lists for item in List ] Example: Python3 # to flatten a list_of_lists by using list comprehensionlist_of_lists = [[1, 2], [3, 4], [5, 6], [7, 8]] # using list comprehensionmy_list = [item for List in list_of_lists for item in List]print(my_list) Output: [1, 2, 3, 4, 5, 6, 7, 8] sweetyty anikaseth98 python-list Technical Scripter 2020 Python Technical Scripter python-list 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 Python | os.path.join() method Selecting rows in pandas DataFrame based on conditions Defaultdict in Python Python | Get unique values from a list Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24318, "s": 24290, "text": "\n22 Sep, 2021" }, { "code": null, "e": 24672, "s": 24318, "text": "Lists are just like dynamically sized arrays, declared in other languages (vector in C++ and ArrayList in Java). Lists need not be homogeneous always which makes it a most powerful tool in Python. A single list may contain DataTypes like Integers, Strings, as well as Objects. Lists are mutable, and hence, they can be altered even after their creation." }, { "code": null, "e": 24878, "s": 24672, "text": "Lists are one of the most powerful tools in python. They have a lot of hidden tricks which makes them extremely versatile. Let’s explore some of these useful techniques which make our lives much easier !!!" }, { "code": null, "e": 24981, "s": 24878, "text": "To sort a list in ascending or descending order, we use the sort() function with the following syntax:" }, { "code": null, "e": 25062, "s": 24981, "text": "For ascending order: \nlist.sort()\nFor descending order: \nlist.sort(reverse=True)" }, { "code": null, "e": 25071, "s": 25062, "text": "Example:" }, { "code": null, "e": 25079, "s": 25071, "text": "Python3" }, { "code": "# sorting a list using sort() function my_list = [5, 2, 90, 24, 10] # sorting in ascending order it permanently# changes the order of the listmy_list.sort()print(my_list) # sorting in descending order it permanently# changes the order of the listmy_list.sort(reverse=True)print(my_list)", "e": 25367, "s": 25079, "text": null }, { "code": null, "e": 25375, "s": 25367, "text": "Output:" }, { "code": null, "e": 25413, "s": 25375, "text": "[2, 5, 10, 24, 90]\n[90, 24, 10, 5, 2]" }, { "code": null, "e": 25501, "s": 25413, "text": "To temporarily change the order of the list use the sorted() function with the syntax: " }, { "code": null, "e": 25515, "s": 25501, "text": "list.sorted()" }, { "code": null, "e": 25523, "s": 25515, "text": "Python3" }, { "code": "# temporary sorting using sorted() method my_list = [5, 2, 90, 24, 10] # ascending orderprint(sorted(my_list)) # descending ordermy_list_2 = sorted(my_list)print(my_list)", "e": 25694, "s": 25523, "text": null }, { "code": null, "e": 25702, "s": 25694, "text": "Output:" }, { "code": null, "e": 25740, "s": 25702, "text": "[2, 5, 10, 24, 90]\n[5, 2, 90, 24, 10]" }, { "code": null, "e": 25817, "s": 25740, "text": "To reverse the order of a list we use the reverse() function. Its syntax is:" }, { "code": null, "e": 25832, "s": 25817, "text": "list.reverse()" }, { "code": null, "e": 25841, "s": 25832, "text": "Example:" }, { "code": null, "e": 25849, "s": 25841, "text": "Python3" }, { "code": "# reverse a list using reverse() my_list = [5, 2, 90, 24, 10] # reversemy_list.reverse()print(my_list)", "e": 25952, "s": 25849, "text": null }, { "code": null, "e": 25960, "s": 25952, "text": "Output:" }, { "code": null, "e": 25979, "s": 25960, "text": "[10, 24, 90, 2, 5]" }, { "code": null, "e": 26035, "s": 25979, "text": "Or we could apply list comprehension to reverse a list:" }, { "code": null, "e": 26054, "s": 26035, "text": " list = list[::-1]" }, { "code": null, "e": 26063, "s": 26054, "text": "Example:" }, { "code": null, "e": 26071, "s": 26063, "text": "Python3" }, { "code": "# reverse using list comprehensionmy_list = [5, 2, 90, 24, 10] # reverseprint(my_list[::-1])", "e": 26164, "s": 26071, "text": null }, { "code": null, "e": 26172, "s": 26164, "text": "Output:" }, { "code": null, "e": 26191, "s": 26172, "text": "[10, 24, 90, 2, 5]" }, { "code": null, "e": 26400, "s": 26191, "text": "As dictionaries in python do not contain duplicate keys. We use the dict.fromkeys() function to convert our list into a dictionary with list elements as keys. And then we convert the dictionary back to list. " }, { "code": null, "e": 26484, "s": 26400, "text": "This is a powerful trick to automatically remove all the duplicates. Its syntax is:" }, { "code": null, "e": 26557, "s": 26484, "text": "My_list =[‘a’, ’b’, ’c’, ’b’, ’a’]\nMylist = list(dict.fromkeys(My_List))" }, { "code": null, "e": 26566, "s": 26557, "text": "Example:" }, { "code": null, "e": 26574, "s": 26566, "text": "Python3" }, { "code": "# removing duplicates from a list using dictionaries my_list_1 = [5, 2, 90, 24, 10, 2, 90, 34]my_list_2 = ['a', 'a', 'a', 'b', 'c', 'd', 'd', 'e'] # removing duplicates from list 1my_list_1 = list(dict.fromkeys(my_list_1))print(my_list_1) # removing duplicates from list 2my_list_2 = list(dict.fromkeys(my_list_2))print(my_list_2)", "e": 26905, "s": 26574, "text": null }, { "code": null, "e": 26913, "s": 26905, "text": "Output:" }, { "code": null, "e": 26962, "s": 26913, "text": "[5, 2, 90, 24, 10, 34]\n['a', 'b', 'c', 'd', 'e']" }, { "code": null, "e": 27087, "s": 26962, "text": "Python lists can be filtered with the help of filter() function or with the help of list comprehension. Below is the syntax:" }, { "code": null, "e": 27143, "s": 27087, "text": "My_list = list(filter(filter_function , iterable_item))" }, { "code": null, "e": 27232, "s": 27143, "text": "The Filter function returns an iterator object which we must convert back into the list." }, { "code": null, "e": 27241, "s": 27232, "text": "Example:" }, { "code": null, "e": 27249, "s": 27241, "text": "Python3" }, { "code": "# filtering with the help of filter() function# creating a filter function filter all the values less than 20 # filter functiondef my_filter(n): if n > 20: return n # driver codeif __name__ == \"__main__\": my_list = [5, 2, 90, 24, 10, 2, 95, 36] my_filtered_list = list(filter(my_filter, my_list)) print(my_filtered_list)", "e": 27596, "s": 27249, "text": null }, { "code": null, "e": 27604, "s": 27596, "text": "Output:" }, { "code": null, "e": 27621, "s": 27604, "text": "[90, 24, 95, 36]" }, { "code": null, "e": 27740, "s": 27621, "text": "We can also filter using list comprehension. It is a much easier and elegant way to filter lists, below is the syntax:" }, { "code": null, "e": 27792, "s": 27740, "text": "My_list = [item for item in my_list if (condition)]" }, { "code": null, "e": 27801, "s": 27792, "text": "Example:" }, { "code": null, "e": 27809, "s": 27801, "text": "Python3" }, { "code": "# filtering with the help of list comprehensionmy_list = [5, 2, 90, 24, 10, 2, 95, 36] # an elegant way to sort the listmy_list = [item for item in my_list if item > 20]print(my_list)", "e": 27993, "s": 27809, "text": null }, { "code": null, "e": 28001, "s": 27993, "text": "Output:" }, { "code": null, "e": 28018, "s": 28001, "text": "[90, 24, 95, 36]" }, { "code": null, "e": 28297, "s": 28018, "text": "To modify the values in the list with the help of an external function, we make use of the map() function. Map() function returns a map object (iterator) of the results after applying the given function to each element of a given iterable(list, tuple etc.). Below is the syntax:" }, { "code": null, "e": 28336, "s": 28297, "text": "My_list = list(map(function,iterable))" }, { "code": null, "e": 28345, "s": 28336, "text": "Example:" }, { "code": null, "e": 28353, "s": 28345, "text": "Python3" }, { "code": "# using map() function to modify the textdef squaring(n): return n**2 # driver codeif __name__ == \"__main__\": my_list = [5, 2, 90, 24, 10, 2, 95, 36] my_squared_list = list(map(squaring, my_list)) print(my_squared_list)", "e": 28586, "s": 28353, "text": null }, { "code": null, "e": 28594, "s": 28586, "text": "Output:" }, { "code": null, "e": 28633, "s": 28594, "text": "[25, 4, 8100, 576, 100, 4, 9025, 1296]" }, { "code": null, "e": 28686, "s": 28633, "text": "A much cleaner approach is using list comprehension." }, { "code": null, "e": 28695, "s": 28686, "text": "Example:" }, { "code": null, "e": 28703, "s": 28695, "text": "Python3" }, { "code": "# the same result can be obtained by a much pythonic approach# i.e., by using list comprehensionmy_list = [5, 2, 90, 24, 10, 2, 95, 36] print([i**2 for i in my_list])", "e": 28870, "s": 28703, "text": null }, { "code": null, "e": 28878, "s": 28870, "text": "Output:" }, { "code": null, "e": 28917, "s": 28878, "text": "[25, 4, 8100, 576, 100, 4, 9025, 1296]" }, { "code": null, "e": 29138, "s": 28917, "text": "We can even combine lists with the help of the zip() function which results in a list of tuples. Here each item from list A is combined with corresponding elements from list B in the form of a tuple. Below is the syntax:" }, { "code": null, "e": 29168, "s": 29138, "text": "My_list = zip(list_1, list_2)" }, { "code": null, "e": 29177, "s": 29168, "text": "Example:" }, { "code": null, "e": 29185, "s": 29177, "text": "Python3" }, { "code": "# combing lists with the help of zip() functionmy_list_1 = [5, 2, 90, 24, 10]my_list_2 = [6, 3, 91, 25, 12] # combinedmy_combined_list = list(zip(my_list_1, my_list_2))print(my_combined_list)", "e": 29377, "s": 29185, "text": null }, { "code": null, "e": 29385, "s": 29377, "text": "Output:" }, { "code": null, "e": 29432, "s": 29385, "text": "[(5, 6), (2, 3), (90, 91), (24, 25), (10, 12)]" }, { "code": null, "e": 29730, "s": 29432, "text": "To find the most frequent element we make use of the set() function. The set() function removes all the duplicates from the list, and the max() function returns the most frequent element (which is found with the help of ‘key’). The key is an optional single argument function. Below is the syntax:" }, { "code": null, "e": 29786, "s": 29730, "text": "Most_frequent_value =max(set(my_list),key=mylist.count)" }, { "code": null, "e": 29796, "s": 29786, "text": "Example :" }, { "code": null, "e": 29804, "s": 29796, "text": "Python3" }, { "code": "# to find the most frequent element from the listmy_list = ['a', 'a', 'a', 'b', 'c', 'd', 'd', 'e'] most_frequent_value = max(set(my_list), key=my_list.count) print(\"The most common element is:\", most_frequent_value)", "e": 30021, "s": 29804, "text": null }, { "code": null, "e": 30029, "s": 30021, "text": "Output:" }, { "code": null, "e": 30059, "s": 30029, "text": "The most common element is: a" }, { "code": null, "e": 30128, "s": 30059, "text": "To check whether an item exists in a list, we use the in statement. " }, { "code": null, "e": 30137, "s": 30128, "text": "Example:" }, { "code": null, "e": 30145, "s": 30137, "text": "Python3" }, { "code": "my_list = ['a', 'a', 'a', 'b', 'c', 'd', 'd', 'e'] # to check whether 'c' is a member of my_list# returns true if presentprint('c' in my_list) # to check whether 'f' is a member of my_list# returns false if not presentprint('f' in my_list)", "e": 30386, "s": 30145, "text": null }, { "code": null, "e": 30394, "s": 30386, "text": "Output:" }, { "code": null, "e": 30405, "s": 30394, "text": "True\nFalse" }, { "code": null, "e": 30549, "s": 30405, "text": "Sometimes we encounter a list where each element in itself is a list. To convert a list of lists into a single list, we use list comprehension." }, { "code": null, "e": 30611, "s": 30549, "text": "my_list = [item for List in list_of_lists for item in List ]" }, { "code": null, "e": 30620, "s": 30611, "text": "Example:" }, { "code": null, "e": 30628, "s": 30620, "text": "Python3" }, { "code": "# to flatten a list_of_lists by using list comprehensionlist_of_lists = [[1, 2], [3, 4], [5, 6], [7, 8]] # using list comprehensionmy_list = [item for List in list_of_lists for item in List]print(my_list)", "e": 30881, "s": 30628, "text": null }, { "code": null, "e": 30889, "s": 30881, "text": "Output:" }, { "code": null, "e": 30914, "s": 30889, "text": "[1, 2, 3, 4, 5, 6, 7, 8]" }, { "code": null, "e": 30923, "s": 30914, "text": "sweetyty" }, { "code": null, "e": 30935, "s": 30923, "text": "anikaseth98" }, { "code": null, "e": 30947, "s": 30935, "text": "python-list" }, { "code": null, "e": 30971, "s": 30947, "text": "Technical Scripter 2020" }, { "code": null, "e": 30978, "s": 30971, "text": "Python" }, { "code": null, "e": 30997, "s": 30978, "text": "Technical Scripter" }, { "code": null, "e": 31009, "s": 30997, "text": "python-list" }, { "code": null, "e": 31107, "s": 31009, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31139, "s": 31107, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 31181, "s": 31139, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 31237, "s": 31181, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 31279, "s": 31237, "text": "Check if element exists in list in Python" }, { "code": null, "e": 31310, "s": 31279, "text": "Python | os.path.join() method" }, { "code": null, "e": 31365, "s": 31310, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 31387, "s": 31365, "text": "Defaultdict in Python" }, { "code": null, "e": 31426, "s": 31387, "text": "Python | Get unique values from a list" }, { "code": null, "e": 31455, "s": 31426, "text": "Create a directory in Python" } ]
PostgreSQL - JAVA Interface
Before we start using PostgreSQL in our Java programs, we need to make sure that we have PostgreSQL JDBC and Java set up on the machine. You can check Java tutorial for Java installation on your machine. Now let us check how to set up PostgreSQL JDBC driver. Download the latest version of postgresql-(VERSION).jdbc.jar from postgresql-jdbc repository. Download the latest version of postgresql-(VERSION).jdbc.jar from postgresql-jdbc repository. Add downloaded jar file postgresql-(VERSION).jdbc.jar in your class path, or you can use it along with -classpath option as explained below in the examples. Add downloaded jar file postgresql-(VERSION).jdbc.jar in your class path, or you can use it along with -classpath option as explained below in the examples. The following section assumes you have little knowledge about Java JDBC concepts. If you do not have, then it is suggested to spent half and hour with JDBC Tutorial to become comfortable with concepts explained below. The following Java code shows how to connect to an existing database. If the database does not exist, then it will be created and finally a database object will be returned. import java.sql.Connection; import java.sql.DriverManager; public class PostgreSQLJDBC { public static void main(String args[]) { Connection c = null; try { Class.forName("org.postgresql.Driver"); c = DriverManager .getConnection("jdbc:postgresql://localhost:5432/testdb", "postgres", "123"); } catch (Exception e) { e.printStackTrace(); System.err.println(e.getClass().getName()+": "+e.getMessage()); System.exit(0); } System.out.println("Opened database successfully"); } } Before you compile and run above program, find pg_hba.conf file in your PostgreSQL installation directory and add the following line − # IPv4 local connections: host all all 127.0.0.1/32 md5 You can start/restart the postgres server in case it is not running using the following command − [root@host]# service postgresql restart Stopping postgresql service: [ OK ] Starting postgresql service: [ OK ] Now, let us compile and run the above program to connect with testdb. Here, we are using postgres as user ID and 123 as password to access the database. You can change this as per your database configuration and setup. We are also assuming current version of JDBC driver postgresql-9.2-1002.jdbc3.jar is available in the current path. C:\JavaPostgresIntegration>javac PostgreSQLJDBC.java C:\JavaPostgresIntegration>java -cp c:\tools\postgresql-9.2-1002.jdbc3.jar;C:\JavaPostgresIntegration PostgreSQLJDBC Open database successfully The following Java program will be used to create a table in previously opened database. Make sure you do not have this table already in your target database. import java.sql.*; import java.sql.Connection; import java.sql.DriverManager; import java.sql.Statement; public class PostgreSQLJDBC { public static void main( String args[] ) { Connection c = null; Statement stmt = null; try { Class.forName("org.postgresql.Driver"); c = DriverManager .getConnection("jdbc:postgresql://localhost:5432/testdb", "manisha", "123"); System.out.println("Opened database successfully"); stmt = c.createStatement(); String sql = "CREATE TABLE COMPANY " + "(ID INT PRIMARY KEY NOT NULL," + " NAME TEXT NOT NULL, " + " AGE INT NOT NULL, " + " ADDRESS CHAR(50), " + " SALARY REAL)"; stmt.executeUpdate(sql); stmt.close(); c.close(); } catch ( Exception e ) { System.err.println( e.getClass().getName()+": "+ e.getMessage() ); System.exit(0); } System.out.println("Table created successfully"); } } When a program is compiled and executed, it will create the COMPANY table in testdb database and will display the following two lines − Opened database successfully Table created successfully The following Java program shows how we can create records in our COMPANY table created in above example − import java.sql.Connection; import java.sql.DriverManager; import java.sql.Statement; public class PostgreSQLJDBC { public static void main(String args[]) { Connection c = null; Statement stmt = null; try { Class.forName("org.postgresql.Driver"); c = DriverManager .getConnection("jdbc:postgresql://localhost:5432/testdb", "manisha", "123"); c.setAutoCommit(false); System.out.println("Opened database successfully"); stmt = c.createStatement(); String sql = "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) " + "VALUES (1, 'Paul', 32, 'California', 20000.00 );"; stmt.executeUpdate(sql); sql = "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) " + "VALUES (2, 'Allen', 25, 'Texas', 15000.00 );"; stmt.executeUpdate(sql); sql = "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) " + "VALUES (3, 'Teddy', 23, 'Norway', 20000.00 );"; stmt.executeUpdate(sql); sql = "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) " + "VALUES (4, 'Mark', 25, 'Rich-Mond ', 65000.00 );"; stmt.executeUpdate(sql); stmt.close(); c.commit(); c.close(); } catch (Exception e) { System.err.println( e.getClass().getName()+": "+ e.getMessage() ); System.exit(0); } System.out.println("Records created successfully"); } } When the above program is compiled and executed, it will create given records in COMPANY table and will display the following two lines − Opened database successfully Records created successfully The following Java program shows how we can fetch and display records from our COMPANY table created in above example − import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class PostgreSQLJDBC { public static void main( String args[] ) { Connection c = null; Statement stmt = null; try { Class.forName("org.postgresql.Driver"); c = DriverManager .getConnection("jdbc:postgresql://localhost:5432/testdb", "manisha", "123"); c.setAutoCommit(false); System.out.println("Opened database successfully"); stmt = c.createStatement(); ResultSet rs = stmt.executeQuery( "SELECT * FROM COMPANY;" ); while ( rs.next() ) { int id = rs.getInt("id"); String name = rs.getString("name"); int age = rs.getInt("age"); String address = rs.getString("address"); float salary = rs.getFloat("salary"); System.out.println( "ID = " + id ); System.out.println( "NAME = " + name ); System.out.println( "AGE = " + age ); System.out.println( "ADDRESS = " + address ); System.out.println( "SALARY = " + salary ); System.out.println(); } rs.close(); stmt.close(); c.close(); } catch ( Exception e ) { System.err.println( e.getClass().getName()+": "+ e.getMessage() ); System.exit(0); } System.out.println("Operation done successfully"); } } When the program is compiled and executed, it will produce the following result − Opened database successfully ID = 1 NAME = Paul AGE = 32 ADDRESS = California SALARY = 20000.0 ID = 2 NAME = Allen AGE = 25 ADDRESS = Texas SALARY = 15000.0 ID = 3 NAME = Teddy AGE = 23 ADDRESS = Norway SALARY = 20000.0 ID = 4 NAME = Mark AGE = 25 ADDRESS = Rich-Mond SALARY = 65000.0 Operation done successfully The following Java code shows how we can use the UPDATE statement to update any record and then fetch and display updated records from our COMPANY table − import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class PostgreSQLJDBC { public static void main( String args[] ) { Connection c = null; Statement stmt = null; try { Class.forName("org.postgresql.Driver"); c = DriverManager .getConnection("jdbc:postgresql://localhost:5432/testdb", "manisha", "123"); c.setAutoCommit(false); System.out.println("Opened database successfully"); stmt = c.createStatement(); String sql = "UPDATE COMPANY set SALARY = 25000.00 where ID=1;"; stmt.executeUpdate(sql); c.commit(); ResultSet rs = stmt.executeQuery( "SELECT * FROM COMPANY;" ); while ( rs.next() ) { int id = rs.getInt("id"); String name = rs.getString("name"); int age = rs.getInt("age"); String address = rs.getString("address"); float salary = rs.getFloat("salary"); System.out.println( "ID = " + id ); System.out.println( "NAME = " + name ); System.out.println( "AGE = " + age ); System.out.println( "ADDRESS = " + address ); System.out.println( "SALARY = " + salary ); System.out.println(); } rs.close(); stmt.close(); c.close(); } catch ( Exception e ) { System.err.println( e.getClass().getName()+": "+ e.getMessage() ); System.exit(0); } System.out.println("Operation done successfully"); } } When the program is compiled and executed, it will produce the following result − Opened database successfully ID = 2 NAME = Allen AGE = 25 ADDRESS = Texas SALARY = 15000.0 ID = 3 NAME = Teddy AGE = 23 ADDRESS = Norway SALARY = 20000.0 ID = 4 NAME = Mark AGE = 25 ADDRESS = Rich-Mond SALARY = 65000.0 ID = 1 NAME = Paul AGE = 32 ADDRESS = California SALARY = 25000.0 Operation done successfully The following Java code shows how we can use the DELETE statement to delete any record and then fetch and display remaining records from our COMPANY table − import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class PostgreSQLJDBC6 { public static void main( String args[] ) { Connection c = null; Statement stmt = null; try { Class.forName("org.postgresql.Driver"); c = DriverManager .getConnection("jdbc:postgresql://localhost:5432/testdb", "manisha", "123"); c.setAutoCommit(false); System.out.println("Opened database successfully"); stmt = c.createStatement(); String sql = "DELETE from COMPANY where ID = 2;"; stmt.executeUpdate(sql); c.commit(); ResultSet rs = stmt.executeQuery( "SELECT * FROM COMPANY;" ); while ( rs.next() ) { int id = rs.getInt("id"); String name = rs.getString("name"); int age = rs.getInt("age"); String address = rs.getString("address"); float salary = rs.getFloat("salary"); System.out.println( "ID = " + id ); System.out.println( "NAME = " + name ); System.out.println( "AGE = " + age ); System.out.println( "ADDRESS = " + address ); System.out.println( "SALARY = " + salary ); System.out.println(); } rs.close(); stmt.close(); c.close(); } catch ( Exception e ) { System.err.println( e.getClass().getName()+": "+ e.getMessage() ); System.exit(0); } System.out.println("Operation done successfully"); } } When the program is compiled and executed, it will produce the following result − Opened database successfully ID = 3 NAME = Teddy AGE = 23 ADDRESS = Norway SALARY = 20000.0 ID = 4 NAME = Mark AGE = 25 ADDRESS = Rich-Mond SALARY = 65000.0 ID = 1 NAME = Paul AGE = 32 ADDRESS = California SALARY = 25000.0 Operation done successfully 23 Lectures 1.5 hours John Elder 49 Lectures 3.5 hours Niyazi Erdogan 126 Lectures 10.5 hours Abhishek And Pukhraj 35 Lectures 5 hours Karthikeya T 5 Lectures 51 mins Vinay Kumar 5 Lectures 52 mins Vinay Kumar Print Add Notes Bookmark this page
[ { "code": null, "e": 3084, "s": 2825, "text": "Before we start using PostgreSQL in our Java programs, we need to make sure that we have PostgreSQL JDBC and Java set up on the machine. You can check Java tutorial for Java installation on your machine. Now let us check how to set up PostgreSQL JDBC driver." }, { "code": null, "e": 3178, "s": 3084, "text": "Download the latest version of postgresql-(VERSION).jdbc.jar from postgresql-jdbc repository." }, { "code": null, "e": 3272, "s": 3178, "text": "Download the latest version of postgresql-(VERSION).jdbc.jar from postgresql-jdbc repository." }, { "code": null, "e": 3429, "s": 3272, "text": "Add downloaded jar file postgresql-(VERSION).jdbc.jar in your class path, or you can use it along with -classpath option as explained below in the examples." }, { "code": null, "e": 3586, "s": 3429, "text": "Add downloaded jar file postgresql-(VERSION).jdbc.jar in your class path, or you can use it along with -classpath option as explained below in the examples." }, { "code": null, "e": 3804, "s": 3586, "text": "The following section assumes you have little knowledge about Java JDBC concepts. If you do not have, then it is suggested to spent half and hour with JDBC Tutorial to become comfortable with concepts explained below." }, { "code": null, "e": 3978, "s": 3804, "text": "The following Java code shows how to connect to an existing database. If the database does not exist, then it will be created and finally a database object will be returned." }, { "code": null, "e": 4560, "s": 3978, "text": "import java.sql.Connection;\nimport java.sql.DriverManager;\n\npublic class PostgreSQLJDBC {\n public static void main(String args[]) {\n Connection c = null;\n try {\n Class.forName(\"org.postgresql.Driver\");\n c = DriverManager\n .getConnection(\"jdbc:postgresql://localhost:5432/testdb\",\n \"postgres\", \"123\");\n } catch (Exception e) {\n e.printStackTrace();\n System.err.println(e.getClass().getName()+\": \"+e.getMessage());\n System.exit(0);\n }\n System.out.println(\"Opened database successfully\");\n }\n}" }, { "code": null, "e": 4695, "s": 4560, "text": "Before you compile and run above program, find pg_hba.conf file in your PostgreSQL installation directory and add the following line −" }, { "code": null, "e": 4779, "s": 4695, "text": "# IPv4 local connections:\nhost all all 127.0.0.1/32 md5" }, { "code": null, "e": 4877, "s": 4779, "text": "You can start/restart the postgres server in case it is not running using the following command −" }, { "code": null, "e": 5053, "s": 4877, "text": "[root@host]# service postgresql restart\nStopping postgresql service: [ OK ]\nStarting postgresql service: [ OK ]" }, { "code": null, "e": 5388, "s": 5053, "text": "Now, let us compile and run the above program to connect with testdb. Here, we are using postgres as user ID and 123 as password to access the database. You can change this as per your database configuration and setup. We are also assuming current version of JDBC driver postgresql-9.2-1002.jdbc3.jar is available in the current path." }, { "code": null, "e": 5585, "s": 5388, "text": "C:\\JavaPostgresIntegration>javac PostgreSQLJDBC.java\nC:\\JavaPostgresIntegration>java -cp c:\\tools\\postgresql-9.2-1002.jdbc3.jar;C:\\JavaPostgresIntegration PostgreSQLJDBC\nOpen database successfully" }, { "code": null, "e": 5744, "s": 5585, "text": "The following Java program will be used to create a table in previously opened database. Make sure you do not have this table already in your target database." }, { "code": null, "e": 6833, "s": 5744, "text": "import java.sql.*;\n\nimport java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.Statement;\n\n\npublic class PostgreSQLJDBC {\n public static void main( String args[] ) {\n Connection c = null;\n Statement stmt = null;\n try {\n Class.forName(\"org.postgresql.Driver\");\n c = DriverManager\n .getConnection(\"jdbc:postgresql://localhost:5432/testdb\",\n \"manisha\", \"123\");\n System.out.println(\"Opened database successfully\");\n\n stmt = c.createStatement();\n String sql = \"CREATE TABLE COMPANY \" +\n \"(ID INT PRIMARY KEY NOT NULL,\" +\n \" NAME TEXT NOT NULL, \" +\n \" AGE INT NOT NULL, \" +\n \" ADDRESS CHAR(50), \" +\n \" SALARY REAL)\";\n stmt.executeUpdate(sql);\n stmt.close();\n c.close();\n } catch ( Exception e ) {\n System.err.println( e.getClass().getName()+\": \"+ e.getMessage() );\n System.exit(0);\n }\n System.out.println(\"Table created successfully\");\n }\n}" }, { "code": null, "e": 6970, "s": 6833, "text": "When a program is compiled and executed, it will create the COMPANY table in testdb database and will display the following two lines −" }, { "code": null, "e": 7027, "s": 6970, "text": "Opened database successfully\nTable created successfully\n" }, { "code": null, "e": 7134, "s": 7027, "text": "The following Java program shows how we can create records in our COMPANY table created in above example −" }, { "code": null, "e": 8612, "s": 7134, "text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.Statement;\n\npublic class PostgreSQLJDBC {\n public static void main(String args[]) {\n Connection c = null;\n Statement stmt = null;\n try {\n Class.forName(\"org.postgresql.Driver\");\n c = DriverManager\n .getConnection(\"jdbc:postgresql://localhost:5432/testdb\",\n \"manisha\", \"123\");\n c.setAutoCommit(false);\n System.out.println(\"Opened database successfully\");\n\n stmt = c.createStatement();\n String sql = \"INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \"\n + \"VALUES (1, 'Paul', 32, 'California', 20000.00 );\";\n stmt.executeUpdate(sql);\n\n sql = \"INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \"\n + \"VALUES (2, 'Allen', 25, 'Texas', 15000.00 );\";\n stmt.executeUpdate(sql);\n\n sql = \"INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \"\n + \"VALUES (3, 'Teddy', 23, 'Norway', 20000.00 );\";\n stmt.executeUpdate(sql);\n\n sql = \"INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \"\n + \"VALUES (4, 'Mark', 25, 'Rich-Mond ', 65000.00 );\";\n stmt.executeUpdate(sql);\n\n stmt.close();\n c.commit();\n c.close();\n } catch (Exception e) {\n System.err.println( e.getClass().getName()+\": \"+ e.getMessage() );\n System.exit(0);\n }\n System.out.println(\"Records created successfully\");\n }\n}" }, { "code": null, "e": 8750, "s": 8612, "text": "When the above program is compiled and executed, it will create given records in COMPANY table and will display the following two lines −" }, { "code": null, "e": 8809, "s": 8750, "text": "Opened database successfully\nRecords created successfully\n" }, { "code": null, "e": 8929, "s": 8809, "text": "The following Java program shows how we can fetch and display records from our COMPANY table created in above example −" }, { "code": null, "e": 10410, "s": 8929, "text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.ResultSet;\nimport java.sql.Statement;\n\n\npublic class PostgreSQLJDBC {\n public static void main( String args[] ) {\n Connection c = null;\n Statement stmt = null;\n try {\n Class.forName(\"org.postgresql.Driver\");\n c = DriverManager\n .getConnection(\"jdbc:postgresql://localhost:5432/testdb\",\n \"manisha\", \"123\");\n c.setAutoCommit(false);\n System.out.println(\"Opened database successfully\");\n\n stmt = c.createStatement();\n ResultSet rs = stmt.executeQuery( \"SELECT * FROM COMPANY;\" );\n while ( rs.next() ) {\n int id = rs.getInt(\"id\");\n String name = rs.getString(\"name\");\n int age = rs.getInt(\"age\");\n String address = rs.getString(\"address\");\n float salary = rs.getFloat(\"salary\");\n System.out.println( \"ID = \" + id );\n System.out.println( \"NAME = \" + name );\n System.out.println( \"AGE = \" + age );\n System.out.println( \"ADDRESS = \" + address );\n System.out.println( \"SALARY = \" + salary );\n System.out.println();\n }\n rs.close();\n stmt.close();\n c.close();\n } catch ( Exception e ) {\n System.err.println( e.getClass().getName()+\": \"+ e.getMessage() );\n System.exit(0);\n }\n System.out.println(\"Operation done successfully\");\n }\n}" }, { "code": null, "e": 10492, "s": 10410, "text": "When the program is compiled and executed, it will produce the following result −" }, { "code": null, "e": 10810, "s": 10492, "text": "Opened database successfully\nID = 1\nNAME = Paul\nAGE = 32\nADDRESS = California\nSALARY = 20000.0\n\nID = 2\nNAME = Allen\nAGE = 25\nADDRESS = Texas\nSALARY = 15000.0\n\nID = 3\nNAME = Teddy\nAGE = 23\nADDRESS = Norway\nSALARY = 20000.0\n\nID = 4\nNAME = Mark\nAGE = 25\nADDRESS = Rich-Mond\nSALARY = 65000.0\n\nOperation done successfully\n" }, { "code": null, "e": 10965, "s": 10810, "text": "The following Java code shows how we can use the UPDATE statement to update any record and then fetch and display updated records from our COMPANY table −" }, { "code": null, "e": 12576, "s": 10965, "text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.ResultSet;\nimport java.sql.Statement;\n\n\npublic class PostgreSQLJDBC {\n public static void main( String args[] ) {\n Connection c = null;\n Statement stmt = null;\n try {\n Class.forName(\"org.postgresql.Driver\");\n c = DriverManager\n .getConnection(\"jdbc:postgresql://localhost:5432/testdb\",\n \"manisha\", \"123\");\n c.setAutoCommit(false);\n System.out.println(\"Opened database successfully\");\n\n stmt = c.createStatement();\n String sql = \"UPDATE COMPANY set SALARY = 25000.00 where ID=1;\";\n stmt.executeUpdate(sql);\n c.commit();\n\n ResultSet rs = stmt.executeQuery( \"SELECT * FROM COMPANY;\" );\n while ( rs.next() ) {\n int id = rs.getInt(\"id\");\n String name = rs.getString(\"name\");\n int age = rs.getInt(\"age\");\n String address = rs.getString(\"address\");\n float salary = rs.getFloat(\"salary\");\n System.out.println( \"ID = \" + id );\n System.out.println( \"NAME = \" + name );\n System.out.println( \"AGE = \" + age );\n System.out.println( \"ADDRESS = \" + address );\n System.out.println( \"SALARY = \" + salary );\n System.out.println();\n }\n rs.close();\n stmt.close();\n c.close();\n } catch ( Exception e ) {\n System.err.println( e.getClass().getName()+\": \"+ e.getMessage() );\n System.exit(0);\n }\n System.out.println(\"Operation done successfully\");\n }\n}" }, { "code": null, "e": 12658, "s": 12576, "text": "When the program is compiled and executed, it will produce the following result −" }, { "code": null, "e": 12976, "s": 12658, "text": "Opened database successfully\nID = 2\nNAME = Allen\nAGE = 25\nADDRESS = Texas\nSALARY = 15000.0\n\nID = 3\nNAME = Teddy\nAGE = 23\nADDRESS = Norway\nSALARY = 20000.0\n\nID = 4\nNAME = Mark\nAGE = 25\nADDRESS = Rich-Mond\nSALARY = 65000.0\n\nID = 1\nNAME = Paul\nAGE = 32\nADDRESS = California\nSALARY = 25000.0\n\nOperation done successfully\n" }, { "code": null, "e": 13133, "s": 12976, "text": "The following Java code shows how we can use the DELETE statement to delete any record and then fetch and display remaining records from our COMPANY table −" }, { "code": null, "e": 14730, "s": 13133, "text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.ResultSet;\nimport java.sql.Statement;\n\n\npublic class PostgreSQLJDBC6 {\n public static void main( String args[] ) {\n Connection c = null;\n Statement stmt = null;\n try {\n Class.forName(\"org.postgresql.Driver\");\n c = DriverManager\n .getConnection(\"jdbc:postgresql://localhost:5432/testdb\",\n \"manisha\", \"123\");\n c.setAutoCommit(false);\n System.out.println(\"Opened database successfully\");\n\n stmt = c.createStatement();\n String sql = \"DELETE from COMPANY where ID = 2;\";\n stmt.executeUpdate(sql);\n c.commit();\n\n ResultSet rs = stmt.executeQuery( \"SELECT * FROM COMPANY;\" );\n while ( rs.next() ) {\n int id = rs.getInt(\"id\");\n String name = rs.getString(\"name\");\n int age = rs.getInt(\"age\");\n String address = rs.getString(\"address\");\n float salary = rs.getFloat(\"salary\");\n System.out.println( \"ID = \" + id );\n System.out.println( \"NAME = \" + name );\n System.out.println( \"AGE = \" + age );\n System.out.println( \"ADDRESS = \" + address );\n System.out.println( \"SALARY = \" + salary );\n System.out.println();\n }\n rs.close();\n stmt.close();\n c.close();\n } catch ( Exception e ) {\n System.err.println( e.getClass().getName()+\": \"+ e.getMessage() );\n System.exit(0);\n }\n System.out.println(\"Operation done successfully\");\n }\n}" }, { "code": null, "e": 14812, "s": 14730, "text": "When the program is compiled and executed, it will produce the following result −" }, { "code": null, "e": 15066, "s": 14812, "text": "Opened database successfully\nID = 3\nNAME = Teddy\nAGE = 23\nADDRESS = Norway\nSALARY = 20000.0\n\nID = 4\nNAME = Mark\nAGE = 25\nADDRESS = Rich-Mond\nSALARY = 65000.0\n\nID = 1\nNAME = Paul\nAGE = 32\nADDRESS = California\nSALARY = 25000.0\nOperation done successfully\n" }, { "code": null, "e": 15101, "s": 15066, "text": "\n 23 Lectures \n 1.5 hours \n" }, { "code": null, "e": 15113, "s": 15101, "text": " John Elder" }, { "code": null, "e": 15148, "s": 15113, "text": "\n 49 Lectures \n 3.5 hours \n" }, { "code": null, "e": 15164, "s": 15148, "text": " Niyazi Erdogan" }, { "code": null, "e": 15201, "s": 15164, "text": "\n 126 Lectures \n 10.5 hours \n" }, { "code": null, "e": 15223, "s": 15201, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 15256, "s": 15223, "text": "\n 35 Lectures \n 5 hours \n" }, { "code": null, "e": 15270, "s": 15256, "text": " Karthikeya T" }, { "code": null, "e": 15301, "s": 15270, "text": "\n 5 Lectures \n 51 mins\n" }, { "code": null, "e": 15314, "s": 15301, "text": " Vinay Kumar" }, { "code": null, "e": 15345, "s": 15314, "text": "\n 5 Lectures \n 52 mins\n" }, { "code": null, "e": 15358, "s": 15345, "text": " Vinay Kumar" }, { "code": null, "e": 15365, "s": 15358, "text": " Print" }, { "code": null, "e": 15376, "s": 15365, "text": " Add Notes" } ]
PDFBox - Loading a Document
In the previous examples, you have seen how to create a new document and add pages to it. This chapter teaches you how to load a PDF document that already exists in your system, and perform some operations on it. The load() method of the PDDocument class is used to load an existing PDF document. Follow the steps given below to load an existing PDF document. Load an existing PDF document using the static method load() of the PDDocument class. This method accepts a file object as a parameter, since this is a static method you can invoke it using class name as shown below. File file = new File("path of the document") PDDocument.load(file); Perform the required operations such as adding pages adding text, adding images to the loaded document. After adding all the pages, save the PDF document using the save() method of the PDDocument class as shown in the following code block. document.save("Path"); Finally close the document using the close() method of the PDDocument class as shown below. document.close(); Suppose we have a PDF document which contains a single page, in the path, C:/PdfBox_Examples/ as shown in the following screenshot. This example demonstrates how to load an existing PDF Document. Here, we will load the PDF document sample.pdf shown above, add a page to it, and save it in the same path with the same name. Step 1 − Save this code in a file with name LoadingExistingDocument.java. import java.io.File; import java.io.IOException; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDPage; public class LoadingExistingDocument { public static void main(String args[]) throws IOException { //Loading an existing document File file = new File("C:/PdfBox_Examples/sample.pdf"); PDDocument document = PDDocument.load(file); System.out.println("PDF loaded"); //Adding a blank page to the document document.addPage(new PDPage()); //Saving the document document.save("C:/PdfBox_Examples/sample.pdf"); //Closing the document document.close(); } } Compile and execute the saved Java file from the command prompt using the following commands javac LoadingExistingDocument.java java LoadingExistingDocument Upon execution, the above program loads the specified PDF document and adds a blank page to it displaying the following message. PDF loaded If you verify the specified path, you can find an additional page added to the specified PDF document as shown below. Print Add Notes Bookmark this page
[ { "code": null, "e": 2240, "s": 2027, "text": "In the previous examples, you have seen how to create a new document and add pages to it. This chapter teaches you how to load a PDF document that already exists in your system, and perform some operations on it." }, { "code": null, "e": 2387, "s": 2240, "text": "The load() method of the PDDocument class is used to load an existing PDF document. Follow the steps given below to load an existing PDF document." }, { "code": null, "e": 2604, "s": 2387, "text": "Load an existing PDF document using the static method load() of the PDDocument class. This method accepts a file object as a parameter, since this is a static method you can invoke it using class name as shown below." }, { "code": null, "e": 2674, "s": 2604, "text": "File file = new File(\"path of the document\") \nPDDocument.load(file);\n" }, { "code": null, "e": 2778, "s": 2674, "text": "Perform the required operations such as adding pages adding text, adding images to the loaded document." }, { "code": null, "e": 2914, "s": 2778, "text": "After adding all the pages, save the PDF document using the save() method of the PDDocument class as shown in the following code block." }, { "code": null, "e": 2938, "s": 2914, "text": "document.save(\"Path\");\n" }, { "code": null, "e": 3030, "s": 2938, "text": "Finally close the document using the close() method of the PDDocument class as shown below." }, { "code": null, "e": 3049, "s": 3030, "text": "document.close();\n" }, { "code": null, "e": 3181, "s": 3049, "text": "Suppose we have a PDF document which contains a single page, in the path, C:/PdfBox_Examples/ as shown in the following screenshot." }, { "code": null, "e": 3372, "s": 3181, "text": "This example demonstrates how to load an existing PDF Document. Here, we will load the PDF document sample.pdf shown above, add a page to it, and save it in the same path with the same name." }, { "code": null, "e": 3446, "s": 3372, "text": "Step 1 − Save this code in a file with name LoadingExistingDocument.java." }, { "code": null, "e": 4146, "s": 3446, "text": "import java.io.File;\nimport java.io.IOException;\n \nimport org.apache.pdfbox.pdmodel.PDDocument; \nimport org.apache.pdfbox.pdmodel.PDPage;\npublic class LoadingExistingDocument {\n\n public static void main(String args[]) throws IOException {\n \n //Loading an existing document \n File file = new File(\"C:/PdfBox_Examples/sample.pdf\"); \n PDDocument document = PDDocument.load(file); \n \n System.out.println(\"PDF loaded\"); \n \n //Adding a blank page to the document \n document.addPage(new PDPage()); \n\n //Saving the document \n document.save(\"C:/PdfBox_Examples/sample.pdf\");\n\n //Closing the document \n document.close(); \n \n } \n}" }, { "code": null, "e": 4239, "s": 4146, "text": "Compile and execute the saved Java file from the command prompt using the following commands" }, { "code": null, "e": 4307, "s": 4239, "text": "javac LoadingExistingDocument.java \njava LoadingExistingDocument \n" }, { "code": null, "e": 4436, "s": 4307, "text": "Upon execution, the above program loads the specified PDF document and adds a blank page to it displaying the following message." }, { "code": null, "e": 4448, "s": 4436, "text": "PDF loaded\n" }, { "code": null, "e": 4566, "s": 4448, "text": "If you verify the specified path, you can find an additional page added to the specified PDF document as shown below." }, { "code": null, "e": 4573, "s": 4566, "text": " Print" }, { "code": null, "e": 4584, "s": 4573, "text": " Add Notes" } ]
Expected Number of Trials until Success - GeeksforGeeks
24 Oct, 2021 Consider the following famous puzzle. In a country, all families want a boy. They keep having babies till a boy is born. What is the expected ratio of boys and girls in the country? This puzzle can be easily solved if we know following interesting result in probability and expectation. If probability of success is p in every trial, then expected number of trials until success is 1/p Proof: Let R be a random variable that indicates number of trials until success. The expected value of R is sum of following infinite series E[R] = 1*p + 2*(1-p)*p + 3*(1-p)2*p + 4*(1-p)3*p + ........ Taking 'p' out E[R] = p[1 + 2*(1-p) + 3*(1-p)2 + 4*(1-p)3 + .......] ---->(1) Multiplying both sides with '(1-p)' and subtracting (1-p)*E[R] = p[1*(1-p) + 2*(1-p)2 + 3*(1-p)3 + .......] --->(2) Subtracting (2) from (1), we get p*E[R] = p[1 + (1-p) + (1-p)2 + (1-p)3 + ........] Cancelling p from both sides E[R] = [1 + (1-p) + (1-p)2 + (1-p)3 + ........] Above is an infinite geometric progression with ratio (1-p). Since (1-p) is less than, we can apply sum formula. E[R] = 1/[1 - (1-p)] = 1/p Solution of Boys/Girls ratio puzzle: Let us use the above result to solve the puzzle. In the given puzzle, probability of success in every trial is 1/2 (assuming that girls and boys are equally likely). Let p be probability of having a baby boy. Number of kids until a baby boy is born = 1/p = 1/(1/2) = 2 Since expected number of kids in a family is 2, ratio of boys and girls is 50:50. Let us discuss another problem that uses above result. Coupon Collector Problem: Suppose there are n types of coupons in a lottery and each lot contains one coupon (with probability 1 = n each). How many lots have to be bought (in expectation) until we have at least one coupon of each type. The solution of this problem is also based on above result. Let Xi be the number of lots bought before i’th new coupon is collected. Note that X1 is 1 as the first coupon is always a new coupon (not collected before). Let ‘p’ be probability that 2nd coupon is collected in next buy. The value of p is (n-1)/n. So the number of trials needed before 2nd new coupon is picked is 1/p which means n/(n-1). [This is where we use above result] Similarly, the number of trials needed before 3rd new coupon is collected is n/(n-2) Using Linearity of expectation, we can say that the total number of expected trials = 1 + n/(n-1) + n/(n-2) + n/(n-3) + .... + n/2 + n/1 = n[1/n + 1/(n-1) + 1/(n-2) + 1/(n-3) + ....+ 1/2 + 1/1] = n * Hn Here Hn is n-th Harmonic number Since Logn <= Hn <= Logn + 1, we need to buy around nLogn lots to collect all n coupons. Exercise: 1) A 6 faced fair dice is thrown until a ‘5’ is seen as result of dice throw. What is the expected number of throws? 2) What is the ratio of boys and girls in above puzzle if probability of a baby boy is 1/3? Reference: http://www.cse.iitd.ac.in/~mohanty/col106/Resources/linearity_expectation.pdf http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-042j-mathematics-for-computer-science-fall-2010/video-lectures/lecture-22-expectation-i/ Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. anikaseth98 harmonic progression Mathematical Randomized Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C++ Data Types Set in C++ Standard Template Library (STL) Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Program to find GCD or HCF of two numbers QuickSort using Random Pivoting Shuffle or Randomize a list in Java Estimating the value of Pi using Monte Carlo Random Walk (Implementation in Python) Generating Random String Using PHP
[ { "code": null, "e": 34596, "s": 34568, "text": "\n24 Oct, 2021" }, { "code": null, "e": 34635, "s": 34596, "text": "Consider the following famous puzzle. " }, { "code": null, "e": 34780, "s": 34635, "text": "In a country, all families want a boy. They keep having babies till a boy is born. What is the expected ratio of boys and girls in the country? " }, { "code": null, "e": 34886, "s": 34780, "text": "This puzzle can be easily solved if we know following interesting result in probability and expectation. " }, { "code": null, "e": 34986, "s": 34886, "text": "If probability of success is p in every trial, then expected number of trials until success is 1/p " }, { "code": null, "e": 35068, "s": 34986, "text": "Proof: Let R be a random variable that indicates number of trials until success. " }, { "code": null, "e": 35707, "s": 35070, "text": "The expected value of R is sum of following infinite series\nE[R] = 1*p + 2*(1-p)*p + 3*(1-p)2*p + 4*(1-p)3*p + ........ \n\nTaking 'p' out\nE[R] = p[1 + 2*(1-p) + 3*(1-p)2 + 4*(1-p)3 + .......] ---->(1)\n\nMultiplying both sides with '(1-p)' and subtracting \n(1-p)*E[R] = p[1*(1-p) + 2*(1-p)2 + 3*(1-p)3 + .......] --->(2)\n\nSubtracting (2) from (1), we get\n\np*E[R] = p[1 + (1-p) + (1-p)2 + (1-p)3 + ........] \n\nCancelling p from both sides\nE[R] = [1 + (1-p) + (1-p)2 + (1-p)3 + ........] \n\nAbove is an infinite geometric progression with ratio (1-p). \nSince (1-p) is less than, we can apply sum formula.\n E[R] = 1/[1 - (1-p)]\n = 1/p" }, { "code": null, "e": 35912, "s": 35707, "text": "Solution of Boys/Girls ratio puzzle: Let us use the above result to solve the puzzle. In the given puzzle, probability of success in every trial is 1/2 (assuming that girls and boys are equally likely). " }, { "code": null, "e": 36180, "s": 35912, "text": "Let p be probability of having a baby boy.\nNumber of kids until a baby boy is born = 1/p \n = 1/(1/2)\n = 2 \nSince expected number of kids in a family is 2,\nratio of boys and girls is 50:50. " }, { "code": null, "e": 36236, "s": 36180, "text": "Let us discuss another problem that uses above result. " }, { "code": null, "e": 36474, "s": 36236, "text": "Coupon Collector Problem: Suppose there are n types of coupons in a lottery and each lot contains one coupon (with probability 1 = n each). How many lots have to be bought (in expectation) until we have at least one coupon of each type. " }, { "code": null, "e": 36535, "s": 36474, "text": "The solution of this problem is also based on above result. " }, { "code": null, "e": 36609, "s": 36535, "text": "Let Xi be the number of lots bought before i’th new coupon is collected. " }, { "code": null, "e": 36695, "s": 36609, "text": "Note that X1 is 1 as the first coupon is always a new coupon (not collected before). " }, { "code": null, "e": 36915, "s": 36695, "text": "Let ‘p’ be probability that 2nd coupon is collected in next buy. The value of p is (n-1)/n. So the number of trials needed before 2nd new coupon is picked is 1/p which means n/(n-1). [This is where we use above result] " }, { "code": null, "e": 37001, "s": 36915, "text": "Similarly, the number of trials needed before 3rd new coupon is collected is n/(n-2) " }, { "code": null, "e": 37380, "s": 37003, "text": "Using Linearity of expectation, \nwe can say that the total number of expected trials = \n 1 + n/(n-1) + n/(n-2) + n/(n-3) + .... + n/2 + n/1\n = n[1/n + 1/(n-1) + 1/(n-2) + 1/(n-3) + ....+ 1/2 + 1/1]\n = n * Hn\nHere Hn is n-th Harmonic number\n\nSince Logn <= Hn <= Logn + 1, we need to buy around \nnLogn lots to collect all n coupons. " }, { "code": null, "e": 37508, "s": 37380, "text": "Exercise: 1) A 6 faced fair dice is thrown until a ‘5’ is seen as result of dice throw. What is the expected number of throws? " }, { "code": null, "e": 37601, "s": 37508, "text": "2) What is the ratio of boys and girls in above puzzle if probability of a baby boy is 1/3? " }, { "code": null, "e": 37691, "s": 37601, "text": "Reference: http://www.cse.iitd.ac.in/~mohanty/col106/Resources/linearity_expectation.pdf " }, { "code": null, "e": 37854, "s": 37691, "text": "http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-042j-mathematics-for-computer-science-fall-2010/video-lectures/lecture-22-expectation-i/ " }, { "code": null, "e": 37980, "s": 37854, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 37994, "s": 37982, "text": "anikaseth98" }, { "code": null, "e": 38015, "s": 37994, "text": "harmonic progression" }, { "code": null, "e": 38028, "s": 38015, "text": "Mathematical" }, { "code": null, "e": 38039, "s": 38028, "text": "Randomized" }, { "code": null, "e": 38052, "s": 38039, "text": "Mathematical" }, { "code": null, "e": 38150, "s": 38052, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38165, "s": 38150, "text": "C++ Data Types" }, { "code": null, "e": 38208, "s": 38165, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 38232, "s": 38208, "text": "Merge two sorted arrays" }, { "code": null, "e": 38275, "s": 38232, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 38317, "s": 38275, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 38349, "s": 38317, "text": "QuickSort using Random Pivoting" }, { "code": null, "e": 38385, "s": 38349, "text": "Shuffle or Randomize a list in Java" }, { "code": null, "e": 38430, "s": 38385, "text": "Estimating the value of Pi using Monte Carlo" }, { "code": null, "e": 38469, "s": 38430, "text": "Random Walk (Implementation in Python)" } ]
Dual Boot Kali Linux with Windows - GeeksforGeeks
14 Oct, 2020 Sometimes we came across situations like when we want to start learning Linux and command line stuff but using Linux as a main Operating System without having a basic idea of it is not a good option. So in order to do that we may install the same alongside windows. And choose which Operating System we want to work on at which time. Before proceeding with the tutorial make sure you have backed up your data to an external drive. Prerequisites 20gb free disk space on other OS External Drive to boot Kali Linux Note: Un allocates a minimum of 20GB of data in your hard disk to Free Space memory. 1. Free up some space in the hard drive and open the run dialogue box by pressing the “windows+r” key combination. 2. Enter the following command in the dialogue box compmgmt.msc 3. Select the “Disk Management” option from the left pane and select the partition you wish to delete and then right-click on the partition and click on delete partition to free up some space. You may also shrink a volume by right-clicking on the volume, select the shrink volume option, and then enter the size to shrink and hit Enter. It should display the free space as highlighted below 1. Download Kali Linux. 2. Burn the Kali Linux ISO to the External Drive from which Kali Linux is to be booted. 3. Open the BIOS settings of the system and change the Boot device to the external device which has Kali Linux image burned and boot from the device. 4. In order to use the Graphical Version to install the OS click on Graphical Installation. 5. The next option is to select a language, So select your desired language and hit enter. 6. The next step is to select a country, territory, or area. So select your respective one. 7. The next step is to configure your keymap. Confirm the keymap you want to use and click Next. 8. In the next step it is asking for a hostname, Enter the same and press the continue button. 9. The next step is to enter the domain name of your choice you may leave it blank if you don’t have any. 10. Enter a strong password for your Kali Linux OS and click continue. 11. The next step is to select a time zone of your choice which you want to use as a default time zone for the Kali Linux machine. 12. Now click on the “Manual” option and press continue to confirm. 13. Now select the Free Space and create a new partition with that and click continue. Also, it is recommended for new users to not use a separate partition for root, home, and swap areas. 14. Now click on create a new partition. 15. Now enter the partition size to be created. 16. Now select the partition type as “Logical”. 17. Now if you are new to Linux then use the following settings for the partition or you may also adjust them as per your need. And then click on “Done setting up the partition“ 18. Now just click on finish partitioning and write changes to disk. 19. Now select the “no” option in order to continue. 20. Now in order to write changes to the disk select the “yes” option and then click on continue. 21. Now, wait for a few minutes for the Kali system to be installed alongside the other Operating System. 22. The next option is to select whether to install the GRUB boot loader to the master boot record or not. Click on yes to add the same. 23. Choose your respective hard disk to boot into, from the list of devices. 24. This will start installing the Kali Linux OS and will take a few minutes to completely install the same and will reboot after the successful completion of the installation. 25. Once the complete process is finished successfully, It will give us a choice to boot form 2 Operating System which means the dual boot is successful. Kali-Linux Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. nohup Command in Linux with Examples scp command in Linux with Examples Thread functions in C/C++ mv command in Linux with examples SED command in Linux | Set 2 chown command in Linux with Examples Docker - COPY Instruction Array Basics in Shell Scripting | Set 1 Basic Operators in Shell Scripting nslookup command in Linux with Examples
[ { "code": null, "e": 24406, "s": 24378, "text": "\n14 Oct, 2020" }, { "code": null, "e": 24838, "s": 24406, "text": "Sometimes we came across situations like when we want to start learning Linux and command line stuff but using Linux as a main Operating System without having a basic idea of it is not a good option. So in order to do that we may install the same alongside windows. And choose which Operating System we want to work on at which time. Before proceeding with the tutorial make sure you have backed up your data to an external drive. " }, { "code": null, "e": 24852, "s": 24838, "text": "Prerequisites" }, { "code": null, "e": 24885, "s": 24852, "text": "20gb free disk space on other OS" }, { "code": null, "e": 24919, "s": 24885, "text": "External Drive to boot Kali Linux" }, { "code": null, "e": 25004, "s": 24919, "text": "Note: Un allocates a minimum of 20GB of data in your hard disk to Free Space memory." }, { "code": null, "e": 25121, "s": 25006, "text": "1. Free up some space in the hard drive and open the run dialogue box by pressing the “windows+r” key combination." }, { "code": null, "e": 25172, "s": 25121, "text": "2. Enter the following command in the dialogue box" }, { "code": null, "e": 25186, "s": 25172, "text": "compmgmt.msc\n" }, { "code": null, "e": 25577, "s": 25186, "text": "3. Select the “Disk Management” option from the left pane and select the partition you wish to delete and then right-click on the partition and click on delete partition to free up some space. You may also shrink a volume by right-clicking on the volume, select the shrink volume option, and then enter the size to shrink and hit Enter. It should display the free space as highlighted below" }, { "code": null, "e": 25601, "s": 25577, "text": "1. Download Kali Linux." }, { "code": null, "e": 25689, "s": 25601, "text": "2. Burn the Kali Linux ISO to the External Drive from which Kali Linux is to be booted." }, { "code": null, "e": 25839, "s": 25689, "text": "3. Open the BIOS settings of the system and change the Boot device to the external device which has Kali Linux image burned and boot from the device." }, { "code": null, "e": 25931, "s": 25839, "text": "4. In order to use the Graphical Version to install the OS click on Graphical Installation." }, { "code": null, "e": 26022, "s": 25931, "text": "5. The next option is to select a language, So select your desired language and hit enter." }, { "code": null, "e": 26114, "s": 26022, "text": "6. The next step is to select a country, territory, or area. So select your respective one." }, { "code": null, "e": 26211, "s": 26114, "text": "7. The next step is to configure your keymap. Confirm the keymap you want to use and click Next." }, { "code": null, "e": 26306, "s": 26211, "text": "8. In the next step it is asking for a hostname, Enter the same and press the continue button." }, { "code": null, "e": 26412, "s": 26306, "text": "9. The next step is to enter the domain name of your choice you may leave it blank if you don’t have any." }, { "code": null, "e": 26483, "s": 26412, "text": "10. Enter a strong password for your Kali Linux OS and click continue." }, { "code": null, "e": 26614, "s": 26483, "text": "11. The next step is to select a time zone of your choice which you want to use as a default time zone for the Kali Linux machine." }, { "code": null, "e": 26682, "s": 26614, "text": "12. Now click on the “Manual” option and press continue to confirm." }, { "code": null, "e": 26871, "s": 26682, "text": "13. Now select the Free Space and create a new partition with that and click continue. Also, it is recommended for new users to not use a separate partition for root, home, and swap areas." }, { "code": null, "e": 26912, "s": 26871, "text": "14. Now click on create a new partition." }, { "code": null, "e": 26960, "s": 26912, "text": "15. Now enter the partition size to be created." }, { "code": null, "e": 27008, "s": 26960, "text": "16. Now select the partition type as “Logical”." }, { "code": null, "e": 27186, "s": 27008, "text": "17. Now if you are new to Linux then use the following settings for the partition or you may also adjust them as per your need. And then click on “Done setting up the partition“" }, { "code": null, "e": 27255, "s": 27186, "text": "18. Now just click on finish partitioning and write changes to disk." }, { "code": null, "e": 27308, "s": 27255, "text": "19. Now select the “no” option in order to continue." }, { "code": null, "e": 27406, "s": 27308, "text": "20. Now in order to write changes to the disk select the “yes” option and then click on continue." }, { "code": null, "e": 27512, "s": 27406, "text": "21. Now, wait for a few minutes for the Kali system to be installed alongside the other Operating System." }, { "code": null, "e": 27649, "s": 27512, "text": "22. The next option is to select whether to install the GRUB boot loader to the master boot record or not. Click on yes to add the same." }, { "code": null, "e": 27726, "s": 27649, "text": "23. Choose your respective hard disk to boot into, from the list of devices." }, { "code": null, "e": 27903, "s": 27726, "text": "24. This will start installing the Kali Linux OS and will take a few minutes to completely install the same and will reboot after the successful completion of the installation." }, { "code": null, "e": 28058, "s": 27903, "text": "25. Once the complete process is finished successfully, It will give us a choice to boot form 2 Operating System which means the dual boot is successful. " }, { "code": null, "e": 28069, "s": 28058, "text": "Kali-Linux" }, { "code": null, "e": 28080, "s": 28069, "text": "Linux-Unix" }, { "code": null, "e": 28178, "s": 28080, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28215, "s": 28178, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 28250, "s": 28215, "text": "scp command in Linux with Examples" }, { "code": null, "e": 28276, "s": 28250, "text": "Thread functions in C/C++" }, { "code": null, "e": 28310, "s": 28276, "text": "mv command in Linux with examples" }, { "code": null, "e": 28339, "s": 28310, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 28376, "s": 28339, "text": "chown command in Linux with Examples" }, { "code": null, "e": 28402, "s": 28376, "text": "Docker - COPY Instruction" }, { "code": null, "e": 28442, "s": 28402, "text": "Array Basics in Shell Scripting | Set 1" }, { "code": null, "e": 28477, "s": 28442, "text": "Basic Operators in Shell Scripting" } ]
Print 1 To N Without Loop | Practice | GeeksforGeeks
Print numbers from 1 to N without the help of loops. Example 1: Input: N = 10 Output: 1 2 3 4 5 6 7 8 9 10 Example 2: Input: N = 5 Output: 1 2 3 4 5 Your Task: This is a function problem. You only need to complete the function printNos() that takes N as parameter and prints number from 1 to N recursively. Don't print newline, it will be added by the driver code. Expected Time Complexity: O(N). Expected Auxiliary Space: O(N) (Recursive). Constraints: 1 <= N <= 105 0 yasugupta20011 week ago class Solution{ void print(int N) { if(N == 0) { return; } else { print(N-1); System.out.print(N + " "); } } public void printNos(int N) { //Your code here print(N); }} -1 kumarrohit5120001 week ago // { Driver Code Starts//Initial Template for C #include <stdio.h> // } Driver Code Ends//User function Template for C void printNos(int N){ if(N>0) { printNos(N-1); printf("%d",N); }//Your code here return;}int main(){ printNos(10); getchar(); return 0;}// { Driver Code Starts./* Driver program to test printNos */int main(){ int T; //taking testcases scanf("%d", &T); while(T--) { int N; //input N scanf("%d", &N); //calling printNos() function printNos(N); printf("\n"); } return 0;} // } Driver Code Ends 0 kumarrohit5120001 week ago #include<stdio.h> void printNos(int N) { if(N>0) { printNos(N-1); printf("%d",N); } return; } int main() { printNos(10); getchar(); return 0; } 0 niharbastia2971 week ago void printNos(int N) { //Your code here if(N == 0) return; printNos(N-1); cout<< N <<" "; } 0 dipanshusharma93132 weeks ago // java solution class Solution{ public void print(int N){ if(N == 1){ return; } N = N-1; print(N); System.out.print(N+" "); } public void printNos(int N) { //Your code here print(N); System.out.print(N+" "); }} 0 dipanshusharma9313 This comment was deleted. 0 bhushanrane3 weeks ago cout<<N<<" "; 0 shivjeetpaswan863 weeks ago in cpp language void print_n_number(int n) { if (n == 0) { return; } print_n_number(n - 1); cout << n << " "; } 0 sumit20445553 weeks ago if(N <= 0): return self.printNos(N - 1) print(N, end = " ") 0 sumit20445553 weeks ago /Your code here if(N==0) return; printNos(N-1); cout<<N<<" "; } We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 291, "s": 238, "text": "Print numbers from 1 to N without the help of loops." }, { "code": null, "e": 302, "s": 291, "text": "Example 1:" }, { "code": null, "e": 346, "s": 302, "text": "Input:\nN = 10\nOutput: 1 2 3 4 5 6 7 8 9 10\n" }, { "code": null, "e": 358, "s": 346, "text": "\nExample 2:" }, { "code": null, "e": 389, "s": 358, "text": "Input:\nN = 5\nOutput: 1 2 3 4 5" }, { "code": null, "e": 607, "s": 391, "text": "Your Task:\nThis is a function problem. You only need to complete the function printNos() that takes N as parameter and prints number from 1 to N recursively. Don't print newline, it will be added by the driver code." }, { "code": null, "e": 684, "s": 607, "text": "\nExpected Time Complexity: O(N).\nExpected Auxiliary Space: O(N) (Recursive)." }, { "code": null, "e": 712, "s": 684, "text": "\nConstraints:\n1 <= N <= 105" }, { "code": null, "e": 714, "s": 712, "text": "0" }, { "code": null, "e": 738, "s": 714, "text": "yasugupta20011 week ago" }, { "code": null, "e": 996, "s": 738, "text": "class Solution{ void print(int N) { if(N == 0) { return; } else { print(N-1); System.out.print(N + \" \"); } } public void printNos(int N) { //Your code here print(N); }} " }, { "code": null, "e": 999, "s": 996, "text": "-1" }, { "code": null, "e": 1026, "s": 999, "text": "kumarrohit5120001 week ago" }, { "code": null, "e": 1074, "s": 1026, "text": "// { Driver Code Starts//Initial Template for C" }, { "code": null, "e": 1093, "s": 1074, "text": "#include <stdio.h>" }, { "code": null, "e": 1145, "s": 1093, "text": "// } Driver Code Ends//User function Template for C" }, { "code": null, "e": 1632, "s": 1145, "text": "void printNos(int N){ if(N>0) { printNos(N-1); printf(\"%d\",N); }//Your code here return;}int main(){ printNos(10); getchar(); return 0;}// { Driver Code Starts./* Driver program to test printNos */int main(){ int T; //taking testcases scanf(\"%d\", &T); while(T--) { int N; //input N scanf(\"%d\", &N); //calling printNos() function printNos(N); printf(\"\\n\"); } return 0;} // } Driver Code Ends" }, { "code": null, "e": 1634, "s": 1632, "text": "0" }, { "code": null, "e": 1661, "s": 1634, "text": "kumarrohit5120001 week ago" }, { "code": null, "e": 1681, "s": 1663, "text": "#include<stdio.h>" }, { "code": null, "e": 1702, "s": 1681, "text": "void printNos(int N)" }, { "code": null, "e": 1704, "s": 1702, "text": "{" }, { "code": null, "e": 1712, "s": 1704, "text": "if(N>0)" }, { "code": null, "e": 1714, "s": 1712, "text": "{" }, { "code": null, "e": 1729, "s": 1714, "text": "printNos(N-1);" }, { "code": null, "e": 1745, "s": 1729, "text": "printf(\"%d\",N);" }, { "code": null, "e": 1747, "s": 1745, "text": "}" }, { "code": null, "e": 1755, "s": 1747, "text": "return;" }, { "code": null, "e": 1757, "s": 1755, "text": "}" }, { "code": null, "e": 1768, "s": 1757, "text": "int main()" }, { "code": null, "e": 1770, "s": 1768, "text": "{" }, { "code": null, "e": 1784, "s": 1770, "text": "printNos(10);" }, { "code": null, "e": 1795, "s": 1784, "text": "getchar();" }, { "code": null, "e": 1805, "s": 1795, "text": "return 0;" }, { "code": null, "e": 1807, "s": 1805, "text": "}" }, { "code": null, "e": 1811, "s": 1809, "text": "0" }, { "code": null, "e": 1836, "s": 1811, "text": "niharbastia2971 week ago" }, { "code": null, "e": 1981, "s": 1836, "text": " void printNos(int N) { //Your code here if(N == 0) return; printNos(N-1); cout<< N <<\" \"; }" }, { "code": null, "e": 1983, "s": 1981, "text": "0" }, { "code": null, "e": 2013, "s": 1983, "text": "dipanshusharma93132 weeks ago" }, { "code": null, "e": 2030, "s": 2013, "text": "// java solution" }, { "code": null, "e": 2291, "s": 2030, "text": "class Solution{ public void print(int N){ if(N == 1){ return; } N = N-1; print(N); System.out.print(N+\" \"); } public void printNos(int N) { //Your code here print(N); System.out.print(N+\" \"); }}" }, { "code": null, "e": 2293, "s": 2291, "text": "0" }, { "code": null, "e": 2312, "s": 2293, "text": "dipanshusharma9313" }, { "code": null, "e": 2338, "s": 2312, "text": "This comment was deleted." }, { "code": null, "e": 2340, "s": 2338, "text": "0" }, { "code": null, "e": 2363, "s": 2340, "text": "bhushanrane3 weeks ago" }, { "code": null, "e": 2377, "s": 2363, "text": "cout<<N<<\" \";" }, { "code": null, "e": 2379, "s": 2377, "text": "0" }, { "code": null, "e": 2407, "s": 2379, "text": "shivjeetpaswan863 weeks ago" }, { "code": null, "e": 2423, "s": 2407, "text": "in cpp language" }, { "code": null, "e": 2450, "s": 2423, "text": "void print_n_number(int n)" }, { "code": null, "e": 2452, "s": 2450, "text": "{" }, { "code": null, "e": 2464, "s": 2452, "text": "if (n == 0)" }, { "code": null, "e": 2466, "s": 2464, "text": "{" }, { "code": null, "e": 2474, "s": 2466, "text": "return;" }, { "code": null, "e": 2476, "s": 2474, "text": "}" }, { "code": null, "e": 2499, "s": 2476, "text": "print_n_number(n - 1);" }, { "code": null, "e": 2517, "s": 2499, "text": "cout << n << \" \";" }, { "code": null, "e": 2519, "s": 2517, "text": "}" }, { "code": null, "e": 2523, "s": 2521, "text": "0" }, { "code": null, "e": 2547, "s": 2523, "text": "sumit20445553 weeks ago" }, { "code": null, "e": 2618, "s": 2547, "text": " if(N <= 0): return self.printNos(N - 1) print(N, end = \" \")" }, { "code": null, "e": 2620, "s": 2618, "text": "0" }, { "code": null, "e": 2644, "s": 2620, "text": "sumit20445553 weeks ago" }, { "code": null, "e": 2738, "s": 2644, "text": "/Your code here if(N==0) return; printNos(N-1); cout<<N<<\" \"; }" }, { "code": null, "e": 2884, "s": 2738, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 2920, "s": 2884, "text": " Login to access your submissions. " }, { "code": null, "e": 2930, "s": 2920, "text": "\nProblem\n" }, { "code": null, "e": 2940, "s": 2930, "text": "\nContest\n" }, { "code": null, "e": 3003, "s": 2940, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 3151, "s": 3003, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 3359, "s": 3151, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 3465, "s": 3359, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Number of minimum picks to get 'k' pairs of socks from a drawer | Practice | GeeksforGeeks
A drawer contains socks of n different colours. The number of socks available of ith colour is given by a[i] where a is an array of n elements. Tony wants to take k pairs of socks out of the drawer. However, he cannot see the colour of the sock that he is picking. You have to tell what is the minimum number of socks Tony has to pick in one attempt from the drawer such that he can be absolutely sure, without seeing their colours, that he will have at least k matching pairs. Example 1: Input: N = 4, K = 6 a[] = {3, 4, 5, 3} Output: 15 Explanation: All 15 socks have to be picked in order to obtain 6 pairs. Example 2: Input: N = 2, K = 3 a[] = {4, 6} Output: 7 Explanation: The Worst case scenario after 6 picks can be {3,3} or {1,5} of each coloured socks. Hence 7th pick will ensure 3rd pair. Your Task: You don't need to read input or print anything. Complete the function find_min() which takes the array a[], size of array N, and value K as input parameters and returns the minimum number of socks Tony has to pick. If it is not possible to pick then return -1. Expected Time Complexity: O(N) Expected Auxiliary Space: O(1) Constraints: 1 ≤ N ≤ 105 1 ≤ a[i] ≤ 106 +3 fungkwe6 months ago Here is the explanation of an O(n) approach. I hope it's clear enough to understand. We won't do the simulation of taking k socks out one by one, because that will be O(k) = O(n*a[i]). Instead we calculate it with the formula: ans = n + k*2 - 1 This formula will work for the "worst" case, i.e. if number of socks a[i] is an odd number for all color. The case is better when where are some colors with even number a[i]. Firstly we need to find: total = Total number of socks = ∑a[i] even = Number of colors having even number of socks = ∑(1- a[i]%2) The concept is: For the last (even - 1) pairs you only need to pick 1 sock instead of 2. For example when n = 6 and total = 16: n = 6, total = 16 k = 1 2 3 4 5 6 7 8 9 ------------------------------------------- even = 0 | 7 9 11 13 15 -1 -1 -1 -1 <- even = 2 | 7 9 11 13 15 16 -1 -1 -1 <- ans even = 4 | 7 9 11 13 14 15 16 -1 -1 <- even = 6 | 7 9 11 12 13 14 15 16 -1 <- We can figure out that ans increases by 1 instead of 2 starting from the value last(sorry for the weird naming): when even = 0, last = ?? when even = 2, last = 15 when even = 4, last = 13 when even = 6, last = 11 ∴ last = total - (even - 1) = total - even + 1 So let's “patch” the value of ans with the following code: last = total - even + 1 diff = ans - last if diff > 0: ans -= diff // 2 Finally, don't forget to return -1 in case ans > total: return ans if ans <= total else -1 Here is the full solution. 0 malimukesh3 months ago I also had confusion while seeing the examples which is not explained clearly, specially the second example which confuses more. Input: N = 2, K = 3 a[] = {4, 6} Output: 7 How ans is 7 here, let me explain: You can see that you need 3 pair and you can simply pick 6 socks from index 1 and say I got 3 pair of same color. so, there is a catch. you can not see it before so I can say that these 6 socks are 1 from index 0 and 5 are from index 1, which fails to given create 3 pair so socks with same color. so if you pick 7 socks, possibility of these to be 1 - 6 2 - 5 3 - 5 4 - 3 from all sets you can get 3 pairs of socks, so ans is 7 -6 jbbm81856 months ago class Solution: def find_min(self,a, n, k): SP=0 res=n for i in range(len(a)): if i<n and SP<k: a[i]-=1 while a[i]>=2: SP+=1 if (SP==k): res+=1 break a[i]-=2 res+=2 print(a,res) for j in range(n): if j<n and SP<k: if a[j]>0: SP+=1 res+=1 return res if(SP==k) else -1 0 ankit31106 months ago int find_min(int a[], int n, int k) { // Your code geos here int p=0;int sum=0; for(int i=0;i<n;i++){ p+=a[i]/2; if(a[i]%2==0){ sum+=(a[i]-2)/2; }else{ sum+=(a[i]-1)/2; } } if(p<k){ return -1; }else if(sum>=k){ return (2*(k-1))+n+1; }else{ return (2*sum)+n+(k-sum); } } -1 gowthamreddyuppunuri6 months ago // Your code geos here int ans = n;//min n socks are needed as we take one from each color, 0pairs are done till now int n_pairs = 0; //use odd numbers completely to increase worst cases for(int i=0; i<n && n_pairs<k; i++){ a[i] -= 1;//initially taking one from each color while(a[i] >= 2){ n_pairs += 1; if(n_pairs == k){ ans += 1; a[i] -= 1; break; } ans += 2; a[i] -= 2; } } //even socks are left for(int i=0; i<n && n_pairs<k; i++){ if(a[i] > 0){ n_pairs += 1; ans += 1; a[i] -= 1; } } return (n_pairs==k?ans:-1); +19 arpitprasad9286 months ago i cant even understand what the question wants to say? can anyone please explain explain it in a simple way. please +1 mastermind_6 months ago C++ Shorter Solution ~ O(N) int find_min(int a[], int n, int k) { int cnt = 0, cnt2 = 0; for (int i=0;i<n;i++) cnt +=(a[i]+1)/2-1, cnt2+=(a[i]%2==0); if (cnt2 + cnt < k)return -1; return n + 2 * k - max(1, k - cnt); } Idea: Consider choosing the last k'th pair, then we might choose all elements which don't lead to the k'th complete pair at worst. Then finally add element that lead to complete k'th pair. +6 rohit_iiitl6 months ago Algorithm: We need to find the worst case. Initially take 1 socks of each color and reduce each element by 1. After that just try to keep every element as odd by picking pair of each color (if possible) and res++ accordingly. If socksPair is still less than k, then in another loop, take all remaining socks till we get K pairs. At last if we get K pairs then return res, otherwise return -1. int find_min(int a[], int n, int k) { int res = n, socksPair = 0; for(int i=0; socksPair<k && i<n; i++) { a[i]--; while(a[i]>=2) { socksPair += 1; if(socksPair == k) { res += 1; break; } res += 2; a[i] -= 2; } } for(int i=0; socksPair<k && i<n; i++) { if(a[i] > 0) socksPair++, res++; } return (socksPair == k)? res : -1; } 0 Nitin Sharma10 months ago Nitin Sharma Simple java solutionhttps://github.com/nitinsha... 0 Mridul Kapoor11 months ago Mridul Kapoor Simple CPP SolutionExpected Time Complexity: O(N)Expected Auxiliary Space: O(1) https://uploads.disquscdn.c... We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 704, "s": 226, "text": "A drawer contains socks of n different colours. The number of socks available of ith colour is given by a[i] where a is an array of n elements. Tony wants to take k pairs of socks out of the drawer. However, he cannot see the colour of the sock that he is picking. You have to tell what is the minimum number of socks Tony has to pick in one attempt from the drawer such that he can be absolutely sure, without seeing their colours, that he will have at least k matching pairs." }, { "code": null, "e": 715, "s": 704, "text": "Example 1:" }, { "code": null, "e": 838, "s": 715, "text": "Input:\nN = 4, K = 6\na[] = {3, 4, 5, 3}\nOutput: 15\nExplanation: \nAll 15 socks have to be picked in order\nto obtain 6 pairs." }, { "code": null, "e": 849, "s": 838, "text": "Example 2:" }, { "code": null, "e": 1027, "s": 849, "text": "Input: N = 2, K = 3\na[] = {4, 6}\nOutput: 7\nExplanation: The Worst case scenario after 6\npicks can be {3,3} or {1,5} of each\ncoloured socks. Hence 7th pick will ensure\n3rd pair. " }, { "code": null, "e": 1302, "s": 1027, "text": "Your Task: \nYou don't need to read input or print anything. Complete the function find_min() which takes the array a[], size of array N, and value K as input parameters and returns the minimum number of socks Tony has to pick. If it is not possible to pick then return -1. " }, { "code": null, "e": 1364, "s": 1302, "text": "Expected Time Complexity: O(N)\nExpected Auxiliary Space: O(1)" }, { "code": null, "e": 1405, "s": 1364, "text": "Constraints:\n1 ≤ N ≤ 105 \n1 ≤ a[i] ≤ 106" }, { "code": null, "e": 1408, "s": 1405, "text": "+3" }, { "code": null, "e": 1428, "s": 1408, "text": "fungkwe6 months ago" }, { "code": null, "e": 1513, "s": 1428, "text": "Here is the explanation of an O(n) approach. I hope it's clear enough to understand." }, { "code": null, "e": 1655, "s": 1513, "text": "We won't do the simulation of taking k socks out one by one, because that will be O(k) = O(n*a[i]). Instead we calculate it with the formula:" }, { "code": null, "e": 1673, "s": 1655, "text": "ans = n + k*2 - 1" }, { "code": null, "e": 1873, "s": 1673, "text": "This formula will work for the \"worst\" case, i.e. if number of socks a[i] is an odd number for all color. The case is better when where are some colors with even number a[i]. Firstly we need to find:" }, { "code": null, "e": 1911, "s": 1873, "text": "total = Total number of socks = ∑a[i]" }, { "code": null, "e": 1978, "s": 1911, "text": "even = Number of colors having even number of socks = ∑(1- a[i]%2)" }, { "code": null, "e": 2106, "s": 1978, "text": "The concept is: For the last (even - 1) pairs you only need to pick 1 sock instead of 2. For example when n = 6 and total = 16:" }, { "code": null, "e": 2365, "s": 2106, "text": "n = 6, total = 16\n\t k = 1 2 3 4 5 6 7 8 9\n-------------------------------------------\neven = 0 | 7 9 11 13 15 -1 -1 -1 -1\t\t<-\neven = 2 | 7 9 11 13 15 16 -1 -1 -1\t\t<- ans\neven = 4 | 7 9 11 13 14 15 16 -1 -1\t\t<-\neven = 6 | 7 9 11 12 13 14 15 16 -1\t\t<-" }, { "code": null, "e": 2478, "s": 2365, "text": "We can figure out that ans increases by 1 instead of 2 starting from the value last(sorry for the weird naming):" }, { "code": null, "e": 2625, "s": 2478, "text": "when even = 0, last = ??\nwhen even = 2, last = 15\nwhen even = 4, last = 13\nwhen even = 6, last = 11\n∴ last = total - (even - 1) = total - even + 1" }, { "code": null, "e": 2684, "s": 2625, "text": "So let's “patch” the value of ans with the following code:" }, { "code": null, "e": 2757, "s": 2684, "text": "last = total - even + 1\ndiff = ans - last\nif diff > 0:\n\tans -= diff // 2" }, { "code": null, "e": 2813, "s": 2757, "text": "Finally, don't forget to return -1 in case ans > total:" }, { "code": null, "e": 2848, "s": 2813, "text": "return ans if ans <= total else -1" }, { "code": null, "e": 2875, "s": 2848, "text": "Here is the full solution." }, { "code": null, "e": 2877, "s": 2875, "text": "0" }, { "code": null, "e": 2900, "s": 2877, "text": "malimukesh3 months ago" }, { "code": null, "e": 3029, "s": 2900, "text": "I also had confusion while seeing the examples which is not explained clearly, specially the second example which confuses more." }, { "code": null, "e": 3072, "s": 3029, "text": "Input: N = 2, K = 3\na[] = {4, 6}\nOutput: 7" }, { "code": null, "e": 3107, "s": 3072, "text": "How ans is 7 here, let me explain:" }, { "code": null, "e": 3221, "s": 3107, "text": "You can see that you need 3 pair and you can simply pick 6 socks from index 1 and say I got 3 pair of same color." }, { "code": null, "e": 3407, "s": 3223, "text": "so, there is a catch. you can not see it before so I can say that these 6 socks are 1 from index 0 and 5 are from index 1, which fails to given create 3 pair so socks with same color." }, { "code": null, "e": 3461, "s": 3409, "text": "so if you pick 7 socks, possibility of these to be " }, { "code": null, "e": 3467, "s": 3461, "text": "1 - 6" }, { "code": null, "e": 3473, "s": 3467, "text": "2 - 5" }, { "code": null, "e": 3479, "s": 3473, "text": "3 - 5" }, { "code": null, "e": 3485, "s": 3479, "text": "4 - 3" }, { "code": null, "e": 3543, "s": 3487, "text": "from all sets you can get 3 pairs of socks, so ans is 7" }, { "code": null, "e": 3552, "s": 3549, "text": "-6" }, { "code": null, "e": 3573, "s": 3552, "text": "jbbm81856 months ago" }, { "code": null, "e": 4112, "s": 3573, "text": "class Solution: def find_min(self,a, n, k): SP=0 res=n for i in range(len(a)): if i<n and SP<k: a[i]-=1 while a[i]>=2: SP+=1 if (SP==k): res+=1 break a[i]-=2 res+=2 print(a,res) for j in range(n): if j<n and SP<k: if a[j]>0: SP+=1 res+=1 return res if(SP==k) else -1" }, { "code": null, "e": 4114, "s": 4112, "text": "0" }, { "code": null, "e": 4136, "s": 4114, "text": "ankit31106 months ago" }, { "code": null, "e": 4555, "s": 4136, "text": " int find_min(int a[], int n, int k) { // Your code geos here int p=0;int sum=0; for(int i=0;i<n;i++){ p+=a[i]/2; if(a[i]%2==0){ sum+=(a[i]-2)/2; }else{ sum+=(a[i]-1)/2; } } if(p<k){ return -1; }else if(sum>=k){ return (2*(k-1))+n+1; }else{ return (2*sum)+n+(k-sum); } }" }, { "code": null, "e": 4558, "s": 4555, "text": "-1" }, { "code": null, "e": 4591, "s": 4558, "text": "gowthamreddyuppunuri6 months ago" }, { "code": null, "e": 5430, "s": 4591, "text": "// Your code geos here\n int ans = n;//min n socks are needed as we take one from each color, 0pairs are done till now\n int n_pairs = 0;\n //use odd numbers completely to increase worst cases\n for(int i=0; i<n && n_pairs<k; i++){\n a[i] -= 1;//initially taking one from each color\n while(a[i] >= 2){\n n_pairs += 1;\n if(n_pairs == k){\n ans += 1;\n a[i] -= 1;\n break;\n }\n ans += 2;\n a[i] -= 2;\n }\n }\n //even socks are left\n for(int i=0; i<n && n_pairs<k; i++){\n if(a[i] > 0){\n n_pairs += 1;\n ans += 1;\n a[i] -= 1;\n }\n }\n return (n_pairs==k?ans:-1);" }, { "code": null, "e": 5434, "s": 5430, "text": "+19" }, { "code": null, "e": 5461, "s": 5434, "text": "arpitprasad9286 months ago" }, { "code": null, "e": 5577, "s": 5461, "text": "i cant even understand what the question wants to say? can anyone please explain explain it in a simple way. please" }, { "code": null, "e": 5580, "s": 5577, "text": "+1" }, { "code": null, "e": 5604, "s": 5580, "text": "mastermind_6 months ago" }, { "code": null, "e": 5633, "s": 5604, "text": "C++ Shorter Solution ~ O(N) " }, { "code": null, "e": 5839, "s": 5633, "text": "int find_min(int a[], int n, int k) {\n int cnt = 0, cnt2 = 0;\n for (int i=0;i<n;i++) cnt +=(a[i]+1)/2-1, cnt2+=(a[i]%2==0);\n if (cnt2 + cnt < k)return -1;\n return n + 2 * k - max(1, k - cnt);\n}" }, { "code": null, "e": 6028, "s": 5839, "text": "Idea: Consider choosing the last k'th pair, then we might choose all elements which don't lead to the k'th complete pair at worst. Then finally add element that lead to complete k'th pair." }, { "code": null, "e": 6031, "s": 6028, "text": "+6" }, { "code": null, "e": 6055, "s": 6031, "text": "rohit_iiitl6 months ago" }, { "code": null, "e": 6448, "s": 6055, "text": "Algorithm: We need to find the worst case. Initially take 1 socks of each color and reduce each element by 1. After that just try to keep every element as odd by picking pair of each color (if possible) and res++ accordingly. If socksPair is still less than k, then in another loop, take all remaining socks till we get K pairs. At last if we get K pairs then return res, otherwise return -1." }, { "code": null, "e": 6922, "s": 6450, "text": "int find_min(int a[], int n, int k) {\n int res = n, socksPair = 0;\n for(int i=0; socksPair<k && i<n; i++) {\n a[i]--;\n while(a[i]>=2) {\n socksPair += 1;\n if(socksPair == k) {\n res += 1;\n break;\n }\n res += 2;\n a[i] -= 2;\n }\n }\n for(int i=0; socksPair<k && i<n; i++) {\n if(a[i] > 0) socksPair++, res++;\n }\n return (socksPair == k)? res : -1;\n}" }, { "code": null, "e": 6924, "s": 6922, "text": "0" }, { "code": null, "e": 6950, "s": 6924, "text": "Nitin Sharma10 months ago" }, { "code": null, "e": 6963, "s": 6950, "text": "Nitin Sharma" }, { "code": null, "e": 7014, "s": 6963, "text": "Simple java solutionhttps://github.com/nitinsha..." }, { "code": null, "e": 7016, "s": 7014, "text": "0" }, { "code": null, "e": 7043, "s": 7016, "text": "Mridul Kapoor11 months ago" }, { "code": null, "e": 7057, "s": 7043, "text": "Mridul Kapoor" }, { "code": null, "e": 7137, "s": 7057, "text": "Simple CPP SolutionExpected Time Complexity: O(N)Expected Auxiliary Space: O(1)" }, { "code": null, "e": 7169, "s": 7137, "text": " https://uploads.disquscdn.c..." }, { "code": null, "e": 7315, "s": 7169, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 7351, "s": 7315, "text": " Login to access your submissions. " }, { "code": null, "e": 7361, "s": 7351, "text": "\nProblem\n" }, { "code": null, "e": 7371, "s": 7361, "text": "\nContest\n" }, { "code": null, "e": 7434, "s": 7371, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 7582, "s": 7434, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 7790, "s": 7582, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 7896, "s": 7790, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
How do I put a jQuery code in an external .js file?
Create an external JavaScript file and add the jQuery code in it. Let’s say the name of the external file is demo.js. To add it in the HTML page, include it like the following − <html> <head> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script src="demo.js"></script> </head> <body> <h1>Hello</h1> </body> </html> Above we added jQuery using Google CDN and the external file was included after that.Add jQuery code in demo.js, since you wanted to place jQuery code − $(document).ready(function(){ alert(“amit”) });
[ { "code": null, "e": 1128, "s": 1062, "text": "Create an external JavaScript file and add the jQuery code in it." }, { "code": null, "e": 1240, "s": 1128, "text": "Let’s say the name of the external file is demo.js. To add it in the HTML page, include it like the following −" }, { "code": null, "e": 1454, "s": 1240, "text": "<html>\n <head>\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\"></script>\n <script src=\"demo.js\"></script>\n </head>\n\n <body>\n <h1>Hello</h1>\n </body>\n</html>" }, { "code": null, "e": 1607, "s": 1454, "text": "Above we added jQuery using Google CDN and the external file was included after that.Add jQuery code in demo.js, since you wanted to place jQuery code −" }, { "code": null, "e": 1658, "s": 1607, "text": "$(document).ready(function(){\n alert(“amit”)\n});" } ]
Excel Absolute References
Absolute reference is when a reference has the dollar sign ($). It locks a reference in the formula. Add $ to the formula to use absolute references. The dollar sign has three different states: Absolute for column and row. The reference is absolutely locked. Example =$A$1 Absolute for the column. The reference is locked to that column. The row remains relative. Example =$A1 Absolute for the row. The reference is locked to that row. The column remains relative. Example =A$1 Let's have a look at an example helping the Pokemon trainers to calculate prices for Pokeballs Type or copy the following data: Data explained There are 6 trainers: Iva, Liam, Adora, Jenny, Iben and Kasper. They have different amount of Pokeballs each in their shop cart The price per Pokeball is 2 coins Help them to calculate the prices for the Pokeballs. The price's reference is B11, we do not want the fill function to change this, so we lock it. The reference is absolutely locked by using the formula $B$11. How to do it, step by step: Type C2(=) Select B11 Type ($) before the B and 11 ($B$11) Type (*) Select B2 Hit enter Auto fill C2:C7 Type C2(=) Select B11 Type ($) before the B and 11 ($B$11) Type (*) Select B2 Hit enter Auto fill C2:C7 Congratulations! You successfully calculated the prices for the Pokeballs using an absolute reference. Type reference A1 as absolute: A$1 Start the Exercise We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: [email protected] Your message has been sent to W3Schools.
[ { "code": null, "e": 64, "s": 0, "text": "Absolute reference is when a reference has the dollar sign ($)." }, { "code": null, "e": 102, "s": 64, "text": "It locks a reference in the formula. " }, { "code": null, "e": 151, "s": 102, "text": "Add $ to the formula to use absolute references." }, { "code": null, "e": 195, "s": 151, "text": "The dollar sign has three different states:" }, { "code": null, "e": 275, "s": 195, "text": "Absolute for column and row. The reference is absolutely locked.\n\nExample =$A$1" }, { "code": null, "e": 381, "s": 275, "text": "Absolute for the column. The reference is locked to that column. The row remains relative.\n\nExample =$A1\n" }, { "code": null, "e": 484, "s": 381, "text": "Absolute for the row. The reference is locked to that row. The column remains relative.\n\nExample =A$1\n" }, { "code": null, "e": 579, "s": 484, "text": "Let's have a look at an example helping the Pokemon trainers to calculate prices for Pokeballs" }, { "code": null, "e": 612, "s": 579, "text": "Type or copy the following data:" }, { "code": null, "e": 627, "s": 612, "text": "Data explained" }, { "code": null, "e": 692, "s": 627, "text": "There are 6 trainers: Iva, Liam, Adora, Jenny, Iben and Kasper. " }, { "code": null, "e": 756, "s": 692, "text": "They have different amount of Pokeballs each in their shop cart" }, { "code": null, "e": 790, "s": 756, "text": "The price per Pokeball is 2 coins" }, { "code": null, "e": 843, "s": 790, "text": "Help them to calculate the prices for the Pokeballs." }, { "code": null, "e": 938, "s": 843, "text": "The price's reference is B11, we do not want the fill function to change this, so we lock it. " }, { "code": null, "e": 1001, "s": 938, "text": "The reference is absolutely locked by using the formula $B$11." }, { "code": null, "e": 1029, "s": 1001, "text": "How to do it, step by step:" }, { "code": null, "e": 1135, "s": 1029, "text": "\nType C2(=)\nSelect B11\nType ($) before the B and 11 ($B$11)\nType (*)\nSelect B2\nHit enter\nAuto fill C2:C7\n" }, { "code": null, "e": 1146, "s": 1135, "text": "Type C2(=)" }, { "code": null, "e": 1157, "s": 1146, "text": "Select B11" }, { "code": null, "e": 1194, "s": 1157, "text": "Type ($) before the B and 11 ($B$11)" }, { "code": null, "e": 1203, "s": 1194, "text": "Type (*)" }, { "code": null, "e": 1213, "s": 1203, "text": "Select B2" }, { "code": null, "e": 1223, "s": 1213, "text": "Hit enter" }, { "code": null, "e": 1239, "s": 1223, "text": "Auto fill C2:C7" }, { "code": null, "e": 1344, "s": 1239, "text": "Congratulations! You successfully calculated the prices for the Pokeballs using an absolute reference. \n" }, { "code": null, "e": 1375, "s": 1344, "text": "Type reference A1 as absolute:" }, { "code": null, "e": 1380, "s": 1375, "text": "A$1\n" }, { "code": null, "e": 1399, "s": 1380, "text": "Start the Exercise" }, { "code": null, "e": 1432, "s": 1399, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 1474, "s": 1432, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 1581, "s": 1474, "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": 1600, "s": 1581, "text": "[email protected]" } ]
Python range() built-in-function. Let us understand the basics of range()... | by Tanu N Prabhu | Towards Data Science
Let us understand the basics of range() function in python. Now let us understand the concept of range function() in python, below shown are the concepts along with examples that will help you guys to understand the range() in a clear way. Also, visit my GitHub repository to find more details about the range function below: github.com The range() function is a built-in-function used in python, it is used to generate a sequence of numbers. If the user wants to generate a sequence of numbers given the starting and the ending values then they can give these values as parameters of the range() function. The range() function will then generate a sequence of numbers according to the user's requirement. The syntax of range() function is shown below: range(start, stop, step) There are three parameters inside the range(): start, stop, and step. When you think about these three-parameters, it resembles a real-life scenario that would be discussed down below. Start: Optional — An integer number that specifies where to start (Default value is 0)Stop: Required — An integer number that specifies where to stop.Step: Optional — An integer number that specifies how much to increment the number (Default value is 1) The return value of the range function is a sequence of numbers depending upon the parameters defined. 1. Let us see what happens when we just print the range function with the value 10. x = range(10)print(x)range(0, 10) As seen above the value 10 indicates the stop value for the range function and the 0 value is by default added as the starting value. 2. Let us see what happens when we put the range function in a for loop. x = range(10)for i in x: print(i)0 1 2 3 4 5 6 7 8 9 Now as seen above we can get the values from 0 to 10 but excluding 10 because the stop value of the range function always returns the value -1. Hence the values 0–10. 3. Let us see what happens that we give the start and the stop value to the range function. x = range(1, 10)for i in x: print(i)12 3 4 5 6 7 8 9 As seen above its prints the values from 1–9 because the start value is defined as 1. 4. Let us see what happens when we give the step value to the range function. x = range(1, 10, 2)for i in x: print(i)1 3 5 7 9 As seen above the step is used to increment the numbers, in this case, the step is 2 so the number is incremented by 2. In general, think this way the range function is like a real-life scenario: You start to walk — startYou make your steps (footsteps) — stepYou stop to walk because you have reached your destination — stop. You start to walk — start You make your steps (footsteps) — step You stop to walk because you have reached your destination — stop. Even though you don't declare the step variable in this case you will take one step at a time, Obviously, nobody takes two steps at a time. Yes, the range function is a class because when you check the type of the range function using type() then you get the answer. x = range(10)print(type(x))<class 'range'> The range function does not work for floating-point values, because according to the range function the floating object cannot be interpreted as an integer. Hence make it a common rule that always specify integer values inside a range function. x = range(10.0, 100.5)for i in x: print(i)--------------------------------------------------------------------TypeError Traceback (most recent call last)<ipython-input-23-55e80efae649> in <module>()----> 1 x = range(10.0, 100.5) 2 for i in x: 3 print(i)TypeError: 'float' object cannot be interpreted as an integer If at all you need to solve it you can typecast it to as an integer as shown below: x = range(int(10.0), int(100.5))for i in x: print(i)10 11 12 13 14----99 To support this context I was doing some research on StackOverflow and then I got to see a problem there which was stated as “I want to loop from 0 to 100 but with a step of 1/2” now this is not a simple problem, because the above concept applies for this so you need to use some logic, now I have used some sort of my logic to solve this problem as shown below: x = range(0, 100 * 2)for i in x: print(i * 0.5)0.0 0.5 1.0 1.5 2.0---99.5 You are free to solve the above problem with your logic and provide the solution in the comment section below. This is also a built-in-function in python I think this also works in the same way as the range(), when I tried executing it I got a weird error: x = xrange(1, 5)for i in x: print(i)--------------------------------------------------------------------NameError Traceback (most recent call last)<ipython-input-30-969120b3b060> in <module>()----> 1 x = xrange(1, 5) 2 for i in x: 3 print(i)NameError: name 'xrange' is not defined Then after quite a research, I came to know that the xrange is the incremental version of range according to stack overflow. One of them said that Python2 uses xrange() and Python3 uses range, so you don’ t have to worry about it. The range functions can also be used on the python list. An easy way to do this is as shown below: names = [‘India’, ‘Canada’, ‘United States’, ‘United Kingdom’]for i in range(1, len(names)): print(names[i])Canada United States United Kingdom I think by this time you guys know how to do this. But anyways I would provide the solution to this problem. You got to just play with the step parameter in this case. Incrementing x = range(1, 10, 2)for i in x: print(i)1 3 5 7 9 Decrementing x = range(10, 1, -2)for i in x: print(i)10 8 6 4 2 This is all you need to know about the range function in python, I recommend you to read Python’s official guide: docs.python.org Thank you guys for reading this short tutorial, I hope you enjoyed it, let me know about your opinion, and if you have any doubt then the comment section is all yours.
[ { "code": null, "e": 232, "s": 172, "text": "Let us understand the basics of range() function in python." }, { "code": null, "e": 498, "s": 232, "text": "Now let us understand the concept of range function() in python, below shown are the concepts along with examples that will help you guys to understand the range() in a clear way. Also, visit my GitHub repository to find more details about the range function below:" }, { "code": null, "e": 509, "s": 498, "text": "github.com" }, { "code": null, "e": 878, "s": 509, "text": "The range() function is a built-in-function used in python, it is used to generate a sequence of numbers. If the user wants to generate a sequence of numbers given the starting and the ending values then they can give these values as parameters of the range() function. The range() function will then generate a sequence of numbers according to the user's requirement." }, { "code": null, "e": 925, "s": 878, "text": "The syntax of range() function is shown below:" }, { "code": null, "e": 950, "s": 925, "text": "range(start, stop, step)" }, { "code": null, "e": 1135, "s": 950, "text": "There are three parameters inside the range(): start, stop, and step. When you think about these three-parameters, it resembles a real-life scenario that would be discussed down below." }, { "code": null, "e": 1393, "s": 1135, "text": "Start: Optional — An integer number that specifies where to start (Default value is 0)Stop: Required — An integer number that specifies where to stop.Step: Optional — An integer number that specifies how much to increment the number (Default value is 1)" }, { "code": null, "e": 1496, "s": 1393, "text": "The return value of the range function is a sequence of numbers depending upon the parameters defined." }, { "code": null, "e": 1580, "s": 1496, "text": "1. Let us see what happens when we just print the range function with the value 10." }, { "code": null, "e": 1614, "s": 1580, "text": "x = range(10)print(x)range(0, 10)" }, { "code": null, "e": 1748, "s": 1614, "text": "As seen above the value 10 indicates the stop value for the range function and the 0 value is by default added as the starting value." }, { "code": null, "e": 1821, "s": 1748, "text": "2. Let us see what happens when we put the range function in a for loop." }, { "code": null, "e": 1877, "s": 1821, "text": "x = range(10)for i in x: print(i)0 1 2 3 4 5 6 7 8 9" }, { "code": null, "e": 2044, "s": 1877, "text": "Now as seen above we can get the values from 0 to 10 but excluding 10 because the stop value of the range function always returns the value -1. Hence the values 0–10." }, { "code": null, "e": 2136, "s": 2044, "text": "3. Let us see what happens that we give the start and the stop value to the range function." }, { "code": null, "e": 2192, "s": 2136, "text": "x = range(1, 10)for i in x: print(i)12 3 4 5 6 7 8 9" }, { "code": null, "e": 2278, "s": 2192, "text": "As seen above its prints the values from 1–9 because the start value is defined as 1." }, { "code": null, "e": 2356, "s": 2278, "text": "4. Let us see what happens when we give the step value to the range function." }, { "code": null, "e": 2408, "s": 2356, "text": "x = range(1, 10, 2)for i in x: print(i)1 3 5 7 9" }, { "code": null, "e": 2528, "s": 2408, "text": "As seen above the step is used to increment the numbers, in this case, the step is 2 so the number is incremented by 2." }, { "code": null, "e": 2604, "s": 2528, "text": "In general, think this way the range function is like a real-life scenario:" }, { "code": null, "e": 2734, "s": 2604, "text": "You start to walk — startYou make your steps (footsteps) — stepYou stop to walk because you have reached your destination — stop." }, { "code": null, "e": 2760, "s": 2734, "text": "You start to walk — start" }, { "code": null, "e": 2799, "s": 2760, "text": "You make your steps (footsteps) — step" }, { "code": null, "e": 2866, "s": 2799, "text": "You stop to walk because you have reached your destination — stop." }, { "code": null, "e": 3006, "s": 2866, "text": "Even though you don't declare the step variable in this case you will take one step at a time, Obviously, nobody takes two steps at a time." }, { "code": null, "e": 3133, "s": 3006, "text": "Yes, the range function is a class because when you check the type of the range function using type() then you get the answer." }, { "code": null, "e": 3176, "s": 3133, "text": "x = range(10)print(type(x))<class 'range'>" }, { "code": null, "e": 3421, "s": 3176, "text": "The range function does not work for floating-point values, because according to the range function the floating object cannot be interpreted as an integer. Hence make it a common rule that always specify integer values inside a range function." }, { "code": null, "e": 3777, "s": 3421, "text": "x = range(10.0, 100.5)for i in x: print(i)--------------------------------------------------------------------TypeError Traceback (most recent call last)<ipython-input-23-55e80efae649> in <module>()----> 1 x = range(10.0, 100.5) 2 for i in x: 3 print(i)TypeError: 'float' object cannot be interpreted as an integer" }, { "code": null, "e": 3861, "s": 3777, "text": "If at all you need to solve it you can typecast it to as an integer as shown below:" }, { "code": null, "e": 3937, "s": 3861, "text": "x = range(int(10.0), int(100.5))for i in x: print(i)10 11 12 13 14----99" }, { "code": null, "e": 4300, "s": 3937, "text": "To support this context I was doing some research on StackOverflow and then I got to see a problem there which was stated as “I want to loop from 0 to 100 but with a step of 1/2” now this is not a simple problem, because the above concept applies for this so you need to use some logic, now I have used some sort of my logic to solve this problem as shown below:" }, { "code": null, "e": 4377, "s": 4300, "text": "x = range(0, 100 * 2)for i in x: print(i * 0.5)0.0 0.5 1.0 1.5 2.0---99.5" }, { "code": null, "e": 4488, "s": 4377, "text": "You are free to solve the above problem with your logic and provide the solution in the comment section below." }, { "code": null, "e": 4634, "s": 4488, "text": "This is also a built-in-function in python I think this also works in the same way as the range(), when I tried executing it I got a weird error:" }, { "code": null, "e": 4954, "s": 4634, "text": "x = xrange(1, 5)for i in x: print(i)--------------------------------------------------------------------NameError Traceback (most recent call last)<ipython-input-30-969120b3b060> in <module>()----> 1 x = xrange(1, 5) 2 for i in x: 3 print(i)NameError: name 'xrange' is not defined" }, { "code": null, "e": 5185, "s": 4954, "text": "Then after quite a research, I came to know that the xrange is the incremental version of range according to stack overflow. One of them said that Python2 uses xrange() and Python3 uses range, so you don’ t have to worry about it." }, { "code": null, "e": 5284, "s": 5185, "text": "The range functions can also be used on the python list. An easy way to do this is as shown below:" }, { "code": null, "e": 5431, "s": 5284, "text": "names = [‘India’, ‘Canada’, ‘United States’, ‘United Kingdom’]for i in range(1, len(names)): print(names[i])Canada United States United Kingdom" }, { "code": null, "e": 5599, "s": 5431, "text": "I think by this time you guys know how to do this. But anyways I would provide the solution to this problem. You got to just play with the step parameter in this case." }, { "code": null, "e": 5612, "s": 5599, "text": "Incrementing" }, { "code": null, "e": 5664, "s": 5612, "text": "x = range(1, 10, 2)for i in x: print(i)1 3 5 7 9" }, { "code": null, "e": 5677, "s": 5664, "text": "Decrementing" }, { "code": null, "e": 5731, "s": 5677, "text": "x = range(10, 1, -2)for i in x: print(i)10 8 6 4 2" }, { "code": null, "e": 5845, "s": 5731, "text": "This is all you need to know about the range function in python, I recommend you to read Python’s official guide:" }, { "code": null, "e": 5861, "s": 5845, "text": "docs.python.org" } ]
Calculate the cross-product of a Matrix in R Programming - crossprod() Function - GeeksforGeeks
03 Jun, 2020 crossprod() function in R Language is used to return the cross-product of the specified matrix. Syntax: crossprod(x) Parameters:x: numeric matrix Example 1: # R program to illustrate# crossprod function # Initializing a matrix with# 2 rows and 2 columnsx <- matrix(1:4, 2, 2) # Getting the matrix representationx # Calling the crossprod() functioncrossprod(x) Output: [, 1] [, 2] [1, ] 1 3 [2, ] 2 4 [, 1] [, 2] [1, ] 5 11 [2, ] 11 25 Example 2: # R program to illustrate# crossprod function # Initializing a matrix with# 3 rows and 3 columnsx <- matrix(1:9, 3, 3) # Getting the matrix representationx # Calling the crossprod() functioncrossprod(x) Output: [, 1] [, 2] [, 3] [1, ] 1 4 7 [2, ] 2 5 8 [3, ] 3 6 9 [, 1] [, 2] [, 3] [1, ] 14 32 50 [2, ] 32 77 122 [3, ] 50 122 194 R Matrix-Function R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R How to Change Axis Scales in R Plots? Group by function in R using Dplyr How to Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column? How to import an Excel File into R ? How to filter R dataframe by multiple conditions? Replace Specific Characters in String in R Time Series Analysis in R R - if statement
[ { "code": null, "e": 25242, "s": 25214, "text": "\n03 Jun, 2020" }, { "code": null, "e": 25338, "s": 25242, "text": "crossprod() function in R Language is used to return the cross-product of the specified matrix." }, { "code": null, "e": 25359, "s": 25338, "text": "Syntax: crossprod(x)" }, { "code": null, "e": 25388, "s": 25359, "text": "Parameters:x: numeric matrix" }, { "code": null, "e": 25399, "s": 25388, "text": "Example 1:" }, { "code": "# R program to illustrate# crossprod function # Initializing a matrix with# 2 rows and 2 columnsx <- matrix(1:4, 2, 2) # Getting the matrix representationx # Calling the crossprod() functioncrossprod(x)", "e": 25605, "s": 25399, "text": null }, { "code": null, "e": 25613, "s": 25605, "text": "Output:" }, { "code": null, "e": 25713, "s": 25613, "text": " [, 1] [, 2]\n[1, ] 1 3\n[2, ] 2 4\n\n [, 1] [, 2]\n[1, ] 5 11\n[2, ] 11 25\n" }, { "code": null, "e": 25724, "s": 25713, "text": "Example 2:" }, { "code": "# R program to illustrate# crossprod function # Initializing a matrix with# 3 rows and 3 columnsx <- matrix(1:9, 3, 3) # Getting the matrix representationx # Calling the crossprod() functioncrossprod(x)", "e": 25930, "s": 25724, "text": null }, { "code": null, "e": 25938, "s": 25930, "text": "Output:" }, { "code": null, "e": 26112, "s": 25938, "text": " [, 1] [, 2] [, 3]\n[1, ] 1 4 7\n[2, ] 2 5 8\n[3, ] 3 6 9\n\n [, 1] [, 2] [, 3]\n[1, ] 14 32 50\n[2, ] 32 77 122\n[3, ] 50 122 194\n" }, { "code": null, "e": 26130, "s": 26112, "text": "R Matrix-Function" }, { "code": null, "e": 26141, "s": 26130, "text": "R Language" }, { "code": null, "e": 26239, "s": 26141, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26291, "s": 26239, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 26329, "s": 26291, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 26364, "s": 26329, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 26422, "s": 26364, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 26471, "s": 26422, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 26508, "s": 26471, "text": "How to import an Excel File into R ?" }, { "code": null, "e": 26558, "s": 26508, "text": "How to filter R dataframe by multiple conditions?" }, { "code": null, "e": 26601, "s": 26558, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 26627, "s": 26601, "text": "Time Series Analysis in R" } ]
DAX Information - ISTEXT function
Checks if a value is text, and returns TRUE or FALSE. ISTEXT (<value>) value The value you want to check. TRUE or FALSE. Empty strings are considered as text. Blank cells, BLANK () are considered as non-text. = ISTEXT("") returns TRUE. = ISTEXT("AB") returns TRUE. = ISTEXT(4) returns FALSE. = ISTEXT(TRUE()) returns FALSE. 53 Lectures 5.5 hours Abhay Gadiya 24 Lectures 2 hours Randy Minder 26 Lectures 4.5 hours Randy Minder Print Add Notes Bookmark this page
[ { "code": null, "e": 2055, "s": 2001, "text": "Checks if a value is text, and returns TRUE or FALSE." }, { "code": null, "e": 2074, "s": 2055, "text": "ISTEXT (<value>) \n" }, { "code": null, "e": 2080, "s": 2074, "text": "value" }, { "code": null, "e": 2109, "s": 2080, "text": "The value you want to check." }, { "code": null, "e": 2124, "s": 2109, "text": "TRUE or FALSE." }, { "code": null, "e": 2162, "s": 2124, "text": "Empty strings are considered as text." }, { "code": null, "e": 2212, "s": 2162, "text": "Blank cells, BLANK () are considered as non-text." }, { "code": null, "e": 2331, "s": 2212, "text": "= ISTEXT(\"\") returns TRUE. \n= ISTEXT(\"AB\") returns TRUE. \n= ISTEXT(4) returns FALSE. \n= ISTEXT(TRUE()) returns FALSE. " }, { "code": null, "e": 2366, "s": 2331, "text": "\n 53 Lectures \n 5.5 hours \n" }, { "code": null, "e": 2380, "s": 2366, "text": " Abhay Gadiya" }, { "code": null, "e": 2413, "s": 2380, "text": "\n 24 Lectures \n 2 hours \n" }, { "code": null, "e": 2427, "s": 2413, "text": " Randy Minder" }, { "code": null, "e": 2462, "s": 2427, "text": "\n 26 Lectures \n 4.5 hours \n" }, { "code": null, "e": 2476, "s": 2462, "text": " Randy Minder" }, { "code": null, "e": 2483, "s": 2476, "text": " Print" }, { "code": null, "e": 2494, "s": 2483, "text": " Add Notes" } ]
ES6 - RegExp match()
This method retrieves the matches. str.match(regexp) Regexp − A regular expression object. Regexp − A regular expression object. Returns an array of matches and null if no matches are found. var str = 'Welcome to ES6.We are learning ES6'; var re = new RegExp("We"); var found = str.match(re); console.log(found); We 32 Lectures 3.5 hours Sharad Kumar 40 Lectures 5 hours Richa Maheshwari 16 Lectures 1 hours Anadi Sharma 50 Lectures 6.5 hours Gowthami Swarna 14 Lectures 1 hours Deepti Trivedi 31 Lectures 1.5 hours Shweta Print Add Notes Bookmark this page
[ { "code": null, "e": 2312, "s": 2277, "text": "This method retrieves the matches." }, { "code": null, "e": 2342, "s": 2312, "text": "str.match(regexp) \n" }, { "code": null, "e": 2380, "s": 2342, "text": "Regexp − A regular expression object." }, { "code": null, "e": 2418, "s": 2380, "text": "Regexp − A regular expression object." }, { "code": null, "e": 2480, "s": 2418, "text": "Returns an array of matches and null if no matches are found." }, { "code": null, "e": 2607, "s": 2480, "text": "var str = 'Welcome to ES6.We are learning ES6'; \nvar re = new RegExp(\"We\"); \nvar found = str.match(re); \nconsole.log(found); " }, { "code": null, "e": 2616, "s": 2607, "text": "We \n" }, { "code": null, "e": 2651, "s": 2616, "text": "\n 32 Lectures \n 3.5 hours \n" }, { "code": null, "e": 2665, "s": 2651, "text": " Sharad Kumar" }, { "code": null, "e": 2698, "s": 2665, "text": "\n 40 Lectures \n 5 hours \n" }, { "code": null, "e": 2716, "s": 2698, "text": " Richa Maheshwari" }, { "code": null, "e": 2749, "s": 2716, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 2763, "s": 2749, "text": " Anadi Sharma" }, { "code": null, "e": 2798, "s": 2763, "text": "\n 50 Lectures \n 6.5 hours \n" }, { "code": null, "e": 2815, "s": 2798, "text": " Gowthami Swarna" }, { "code": null, "e": 2848, "s": 2815, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 2864, "s": 2848, "text": " Deepti Trivedi" }, { "code": null, "e": 2899, "s": 2864, "text": "\n 31 Lectures \n 1.5 hours \n" }, { "code": null, "e": 2907, "s": 2899, "text": " Shweta" }, { "code": null, "e": 2914, "s": 2907, "text": " Print" }, { "code": null, "e": 2925, "s": 2914, "text": " Add Notes" } ]
Python MySQL - Update Table
UPDATE Operation on any database updates one or more records, which are already available in the database. You can update the values of existing records in MySQL using the UPDATE statement. To update specific rows, you need to use the WHERE clause along with it. Following is the syntax of the UPDATE statement in MySQL − UPDATE table_name SET column1 = value1, column2 = value2...., columnN = valueN WHERE [condition]; You can combine N number of conditions using the AND or the OR operators. Assume we have created a table in MySQL with name EMPLOYEES as − mysql> CREATE TABLE EMPLOYEE( FIRST_NAME CHAR(20) NOT NULL, LAST_NAME CHAR(20), AGE INT, SEX CHAR(1), INCOME FLOAT ); Query OK, 0 rows affected (0.36 sec) And if we have inserted 4 records in to it using INSERT statements as − mysql> INSERT INTO EMPLOYEE VALUES ('Krishna', 'Sharma', 19, 'M', 2000), ('Raj', 'Kandukuri', 20, 'M', 7000), ('Ramya', 'Ramapriya', 25, 'F', 5000), ('Mac', 'Mohan', 26, 'M', 2000); Following MySQL statement increases the age of all male employees by one year − mysql> UPDATE EMPLOYEE SET AGE = AGE + 1 WHERE SEX = 'M'; Query OK, 3 rows affected (0.06 sec) Rows matched: 3 Changed: 3 Warnings: 0 If you retrieve the contents of the table, you can see the updated values as − mysql> select * from EMPLOYEE; +------------+-----------+------+------+--------+ | FIRST_NAME | LAST_NAME | AGE | SEX | INCOME | +------------+-----------+------+------+--------+ | Krishna | Sharma | 20 | M | 2000 | | Raj | Kandukuri | 21 | M | 7000 | | Ramya | Ramapriya | 25 | F | 5000 | | Mac | Mohan | 27 | M | 2000 | +------------+-----------+------+------+--------+ 4 rows in set (0.00 sec) To update the records in a table in MySQL using python − import mysql.connector package. import mysql.connector package. Create a connection object using the mysql.connector.connect() method, by passing the user name, password, host (optional default: localhost) and, database (optional) as parameters to it. Create a connection object using the mysql.connector.connect() method, by passing the user name, password, host (optional default: localhost) and, database (optional) as parameters to it. Create a cursor object by invoking the cursor() method on the connection object created above. Create a cursor object by invoking the cursor() method on the connection object created above. Then, execute the UPDATE statement by passing it as a parameter to the execute() method. Then, execute the UPDATE statement by passing it as a parameter to the execute() method. The following example increases age of all the males by one year. import mysql.connector #establishing the connection conn = mysql.connector.connect( user='root', password='password', host='127.0.0.1', database='mydb') #Creating a cursor object using the cursor() method cursor = conn.cursor() #Preparing the query to update the records sql = '''UPDATE EMPLOYEE SET AGE = AGE + 1 WHERE SEX = 'M' ''' try: # Execute the SQL command cursor.execute(sql) # Commit your changes in the database conn.commit() except: # Rollback in case there is any error conn.rollback() #Retrieving data sql = '''SELECT * from EMPLOYEE''' #Executing the query cursor.execute(sql) #Displaying the result print(cursor.fetchall()) #Closing the connection conn.close() [('Krishna', 'Sharma', 22, 'M', 2000.0), ('Raj', 'Kandukuri', 23, 'M', 7000.0), ('Ramya', 'Ramapriya', 26, 'F', 5000.0) ] 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": 3468, "s": 3205, "text": "UPDATE Operation on any database updates one or more records, which are already available in the database. You can update the values of existing records in MySQL using the UPDATE statement. To update specific rows, you need to use the WHERE clause along with it." }, { "code": null, "e": 3527, "s": 3468, "text": "Following is the syntax of the UPDATE statement in MySQL −" }, { "code": null, "e": 3626, "s": 3527, "text": "UPDATE table_name\nSET column1 = value1, column2 = value2...., columnN = valueN\nWHERE [condition];\n" }, { "code": null, "e": 3700, "s": 3626, "text": "You can combine N number of conditions using the AND or the OR operators." }, { "code": null, "e": 3765, "s": 3700, "text": "Assume we have created a table in MySQL with name EMPLOYEES as −" }, { "code": null, "e": 3935, "s": 3765, "text": "mysql> CREATE TABLE EMPLOYEE(\n FIRST_NAME CHAR(20) NOT NULL,\n LAST_NAME CHAR(20),\n AGE INT,\n SEX CHAR(1),\n INCOME FLOAT\n);\nQuery OK, 0 rows affected (0.36 sec)" }, { "code": null, "e": 4007, "s": 3935, "text": "And if we have inserted 4 records in to it using INSERT statements as −" }, { "code": null, "e": 4202, "s": 4007, "text": "mysql> INSERT INTO EMPLOYEE VALUES\n ('Krishna', 'Sharma', 19, 'M', 2000),\n ('Raj', 'Kandukuri', 20, 'M', 7000),\n ('Ramya', 'Ramapriya', 25, 'F', 5000),\n ('Mac', 'Mohan', 26, 'M', 2000);\n" }, { "code": null, "e": 4282, "s": 4202, "text": "Following MySQL statement increases the age of all male employees by one year −" }, { "code": null, "e": 4417, "s": 4282, "text": "mysql> UPDATE EMPLOYEE SET AGE = AGE + 1 WHERE SEX = 'M';\nQuery OK, 3 rows affected (0.06 sec)\nRows matched: 3 Changed: 3 Warnings: 0\n" }, { "code": null, "e": 4496, "s": 4417, "text": "If you retrieve the contents of the table, you can see the updated values as −" }, { "code": null, "e": 4953, "s": 4496, "text": "mysql> select * from EMPLOYEE;\n+------------+-----------+------+------+--------+\n| FIRST_NAME | LAST_NAME | AGE | SEX | INCOME |\n+------------+-----------+------+------+--------+\n| Krishna | Sharma | 20 | M | 2000 |\n| Raj | Kandukuri | 21 | M | 7000 |\n| Ramya | Ramapriya | 25 | F | 5000 |\n| Mac | Mohan | 27 | M | 2000 |\n+------------+-----------+------+------+--------+\n4 rows in set (0.00 sec)\n" }, { "code": null, "e": 5010, "s": 4953, "text": "To update the records in a table in MySQL using python −" }, { "code": null, "e": 5042, "s": 5010, "text": "import mysql.connector package." }, { "code": null, "e": 5074, "s": 5042, "text": "import mysql.connector package." }, { "code": null, "e": 5262, "s": 5074, "text": "Create a connection object using the mysql.connector.connect() method, by passing the user name, password, host (optional default: localhost) and, database (optional) as parameters to it." }, { "code": null, "e": 5450, "s": 5262, "text": "Create a connection object using the mysql.connector.connect() method, by passing the user name, password, host (optional default: localhost) and, database (optional) as parameters to it." }, { "code": null, "e": 5545, "s": 5450, "text": "Create a cursor object by invoking the cursor() method on the connection object created above." }, { "code": null, "e": 5640, "s": 5545, "text": "Create a cursor object by invoking the cursor() method on the connection object created above." }, { "code": null, "e": 5729, "s": 5640, "text": "Then, execute the UPDATE statement by passing it as a parameter to the execute() method." }, { "code": null, "e": 5818, "s": 5729, "text": "Then, execute the UPDATE statement by passing it as a parameter to the execute() method." }, { "code": null, "e": 5884, "s": 5818, "text": "The following example increases age of all the males by one year." }, { "code": null, "e": 6596, "s": 5884, "text": "import mysql.connector\n\n#establishing the connection\nconn = mysql.connector.connect(\n user='root', password='password', host='127.0.0.1', database='mydb')\n\n#Creating a cursor object using the cursor() method\ncursor = conn.cursor()\n\n#Preparing the query to update the records\nsql = '''UPDATE EMPLOYEE SET AGE = AGE + 1 WHERE SEX = 'M' '''\ntry:\n # Execute the SQL command\n cursor.execute(sql)\n \n # Commit your changes in the database\n conn.commit()\nexcept:\n # Rollback in case there is any error\n conn.rollback()\n \n#Retrieving data\nsql = '''SELECT * from EMPLOYEE'''\n\n#Executing the query\ncursor.execute(sql)\n\n#Displaying the result\nprint(cursor.fetchall())\n\n#Closing the connection\nconn.close()" }, { "code": null, "e": 6727, "s": 6596, "text": "[('Krishna', 'Sharma', 22, 'M', 2000.0), \n ('Raj', 'Kandukuri', 23, 'M', 7000.0), \n ('Ramya', 'Ramapriya', 26, 'F', 5000.0)\n]\n" }, { "code": null, "e": 6764, "s": 6727, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 6780, "s": 6764, "text": " Malhar Lathkar" }, { "code": null, "e": 6813, "s": 6780, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 6832, "s": 6813, "text": " Arnab Chakraborty" }, { "code": null, "e": 6867, "s": 6832, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 6889, "s": 6867, "text": " In28Minutes Official" }, { "code": null, "e": 6923, "s": 6889, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 6951, "s": 6923, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 6986, "s": 6951, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 7000, "s": 6986, "text": " Lets Kode It" }, { "code": null, "e": 7033, "s": 7000, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 7050, "s": 7033, "text": " Abhilash Nelson" }, { "code": null, "e": 7057, "s": 7050, "text": " Print" }, { "code": null, "e": 7068, "s": 7057, "text": " Add Notes" } ]
Find array elements that are greater than average - GeeksforGeeks
28 Apr, 2021 Given an array of numbers, print all those elements that are greater than average. Examples: Input : 5, 4, 6, 9, 10 Output : 9 10 Explanation: avg = 5 + 4 + 6 + 9 + 10 / 5; avg = 34 / 5 avg = 6.8 Elements greater than 6.8 are 9 and 10 Input : 1, 2, 4, 0, 5 Output : 4 5 1) Find average of elements. 2) Traverse array again and print elements that are greater than average, C++ Java Python3 PHP C# Javascript // A C++ program to print elements which are// greater than avg of array#include <iostream>using namespace std; // Print array elements greater than averagevoid printAboveAvg(int arr[], int n){ // Find average double avg = 0; for (int i = 0; i < n; i++) avg += arr[i]; avg = avg / n; // Print elements greater than average for (int i = 0; i < n; i++) if (arr[i] > avg) cout << arr[i] << " ";} // Driver programint main(){ int arr[] = { 5, 4, 6, 9, 10 }; int a = sizeof(arr) / sizeof(arr[0]); printAboveAvg(arr, a); return 0;} // A Java program to print elements which are// greater than avg of arrayimport java.io.*; class GFG { // Print array elements greater than average static void printAboveAvg(int arr[], int n) { // Find average double avg = 0; for (int i = 0; i < n; i++) avg += arr[i]; avg = avg / n; // Print elements greater than average for (int i = 0; i < n; i++) if (arr[i] > avg) System.out.print(arr[i] + " "); } // Driver program public static void main (String[] args) { int arr[] = { 5, 4, 6, 9, 10 }; int a = arr.length; printAboveAvg(arr, a); }} // This code is contributed by anuj_67. # python program to print elements# which are greater than avg of# array # Print array elements greater# than averagedef printAboveAvg(arr, a): # Find average avg = 0 for i in range(a): avg = avg + arr[i] avg = avg // a # Print elements greater than # average for i in range(a): if arr[i] > avg: print(arr[i], end = " ") # Driver Programarr = [5, 4, 6, 9, 10]a = len(arr)printAboveAvg(arr, a) # This code is contributed# by Shrikant13. <?php// A PHP program to print// elements which are// greater than avg of array // Print array elements// greater than averagefunction printAboveAvg( $arr, $n){ // Find average $avg = 0; for ($i = 0; $i < $n; $i++) $avg += $arr[$i]; $avg = $avg / $n; // Print elements greater // than average for ($i = 0; $i < $n; $i++) if ($arr[$i] > $avg) echo $arr[$i] , " ";} // Driver Code $arr = array(5, 4, 6, 9, 10); $a = count($arr); printAboveAvg($arr, $a); // This code is contributed by anuj_67.?> // A C# program to print elements which are// greater than avg of arrayusing System;using System.Collections.Generic; class GFG { // Print array elements // greater than average static void printAboveAvg(int []arr, int n) { // Find average double avg = 0; for (int i = 0; i < n; i++) avg += arr[i]; avg = avg / n; // Print elements greater // than average for (int i = 0; i < n; i++) if (arr[i] > avg) Console.Write(arr[i] + " "); } // Driver Code public static void Main() { int []arr = {5, 4, 6, 9, 10}; int a = arr.Length; printAboveAvg(arr, a); }} // This code is contributed by// Manish Shaw (manishshaw1) <script> // A Javascript program to print// elements which are greater// than avg of array // Print array elements greater// than averagefunction printAboveAvg(arr, n){ // Find average let avg = 0; for(let i = 0; i < n; i++) avg += arr[i]; avg = avg / n; // Print elements greater than average for(let i = 0; i < n; i++) if (arr[i] > avg) document.write(arr[i] + " ");} // Driver codelet arr = [ 5, 4, 6, 9, 10 ];let a = arr.length; printAboveAvg(arr, a); // This code is contributed by jana_sayantan </script> 9 10 shrikanth13 vt_m manishshaw1 jana_sayantan Articles School Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Time Complexity and Space Complexity Docker - COPY Instruction SQL | Date functions Time complexities of different data structures Difference between Class and Object Python Dictionary Arrays in C/C++ Inheritance in C++ Reverse a string in Java Interfaces in Java
[ { "code": null, "e": 24421, "s": 24393, "text": "\n28 Apr, 2021" }, { "code": null, "e": 24504, "s": 24421, "text": "Given an array of numbers, print all those elements that are greater than average." }, { "code": null, "e": 24515, "s": 24504, "text": "Examples: " }, { "code": null, "e": 24693, "s": 24515, "text": "Input : 5, 4, 6, 9, 10\nOutput : 9 10\nExplanation:\navg = 5 + 4 + 6 + 9 + 10 / 5;\navg = 34 / 5\navg = 6.8\nElements greater than 6.8 are 9 and\n10\n\nInput : 1, 2, 4, 0, 5\nOutput : 4 5" }, { "code": null, "e": 24797, "s": 24693, "text": "1) Find average of elements. 2) Traverse array again and print elements that are greater than average, " }, { "code": null, "e": 24801, "s": 24797, "text": "C++" }, { "code": null, "e": 24806, "s": 24801, "text": "Java" }, { "code": null, "e": 24814, "s": 24806, "text": "Python3" }, { "code": null, "e": 24818, "s": 24814, "text": "PHP" }, { "code": null, "e": 24821, "s": 24818, "text": "C#" }, { "code": null, "e": 24832, "s": 24821, "text": "Javascript" }, { "code": "// A C++ program to print elements which are// greater than avg of array#include <iostream>using namespace std; // Print array elements greater than averagevoid printAboveAvg(int arr[], int n){ // Find average double avg = 0; for (int i = 0; i < n; i++) avg += arr[i]; avg = avg / n; // Print elements greater than average for (int i = 0; i < n; i++) if (arr[i] > avg) cout << arr[i] << \" \";} // Driver programint main(){ int arr[] = { 5, 4, 6, 9, 10 }; int a = sizeof(arr) / sizeof(arr[0]); printAboveAvg(arr, a); return 0;}", "e": 25417, "s": 24832, "text": null }, { "code": "// A Java program to print elements which are// greater than avg of arrayimport java.io.*; class GFG { // Print array elements greater than average static void printAboveAvg(int arr[], int n) { // Find average double avg = 0; for (int i = 0; i < n; i++) avg += arr[i]; avg = avg / n; // Print elements greater than average for (int i = 0; i < n; i++) if (arr[i] > avg) System.out.print(arr[i] + \" \"); } // Driver program public static void main (String[] args) { int arr[] = { 5, 4, 6, 9, 10 }; int a = arr.length; printAboveAvg(arr, a); }} // This code is contributed by anuj_67.", "e": 26143, "s": 25417, "text": null }, { "code": "# python program to print elements# which are greater than avg of# array # Print array elements greater# than averagedef printAboveAvg(arr, a): # Find average avg = 0 for i in range(a): avg = avg + arr[i] avg = avg // a # Print elements greater than # average for i in range(a): if arr[i] > avg: print(arr[i], end = \" \") # Driver Programarr = [5, 4, 6, 9, 10]a = len(arr)printAboveAvg(arr, a) # This code is contributed# by Shrikant13.", "e": 26636, "s": 26143, "text": null }, { "code": "<?php// A PHP program to print// elements which are// greater than avg of array // Print array elements// greater than averagefunction printAboveAvg( $arr, $n){ // Find average $avg = 0; for ($i = 0; $i < $n; $i++) $avg += $arr[$i]; $avg = $avg / $n; // Print elements greater // than average for ($i = 0; $i < $n; $i++) if ($arr[$i] > $avg) echo $arr[$i] , \" \";} // Driver Code $arr = array(5, 4, 6, 9, 10); $a = count($arr); printAboveAvg($arr, $a); // This code is contributed by anuj_67.?>", "e": 27200, "s": 26636, "text": null }, { "code": "// A C# program to print elements which are// greater than avg of arrayusing System;using System.Collections.Generic; class GFG { // Print array elements // greater than average static void printAboveAvg(int []arr, int n) { // Find average double avg = 0; for (int i = 0; i < n; i++) avg += arr[i]; avg = avg / n; // Print elements greater // than average for (int i = 0; i < n; i++) if (arr[i] > avg) Console.Write(arr[i] + \" \"); } // Driver Code public static void Main() { int []arr = {5, 4, 6, 9, 10}; int a = arr.Length; printAboveAvg(arr, a); }} // This code is contributed by// Manish Shaw (manishshaw1)", "e": 27960, "s": 27200, "text": null }, { "code": "<script> // A Javascript program to print// elements which are greater// than avg of array // Print array elements greater// than averagefunction printAboveAvg(arr, n){ // Find average let avg = 0; for(let i = 0; i < n; i++) avg += arr[i]; avg = avg / n; // Print elements greater than average for(let i = 0; i < n; i++) if (arr[i] > avg) document.write(arr[i] + \" \");} // Driver codelet arr = [ 5, 4, 6, 9, 10 ];let a = arr.length; printAboveAvg(arr, a); // This code is contributed by jana_sayantan </script>", "e": 28536, "s": 27960, "text": null }, { "code": null, "e": 28541, "s": 28536, "text": "9 10" }, { "code": null, "e": 28555, "s": 28543, "text": "shrikanth13" }, { "code": null, "e": 28560, "s": 28555, "text": "vt_m" }, { "code": null, "e": 28572, "s": 28560, "text": "manishshaw1" }, { "code": null, "e": 28586, "s": 28572, "text": "jana_sayantan" }, { "code": null, "e": 28595, "s": 28586, "text": "Articles" }, { "code": null, "e": 28614, "s": 28595, "text": "School Programming" }, { "code": null, "e": 28712, "s": 28614, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28721, "s": 28712, "text": "Comments" }, { "code": null, "e": 28734, "s": 28721, "text": "Old Comments" }, { "code": null, "e": 28771, "s": 28734, "text": "Time Complexity and Space Complexity" }, { "code": null, "e": 28797, "s": 28771, "text": "Docker - COPY Instruction" }, { "code": null, "e": 28818, "s": 28797, "text": "SQL | Date functions" }, { "code": null, "e": 28865, "s": 28818, "text": "Time complexities of different data structures" }, { "code": null, "e": 28901, "s": 28865, "text": "Difference between Class and Object" }, { "code": null, "e": 28919, "s": 28901, "text": "Python Dictionary" }, { "code": null, "e": 28935, "s": 28919, "text": "Arrays in C/C++" }, { "code": null, "e": 28954, "s": 28935, "text": "Inheritance in C++" }, { "code": null, "e": 28979, "s": 28954, "text": "Reverse a string in Java" } ]
Geometry - Solved Examples
Q 1 - A line has A - One end point B - Two end points C - Three end points D - No end points Answer - D Explanation A line has no points. Q 2 - A line segment has A - One end point B - Two end points C - Three end points D - No end points Answer - B Explanation A line segment has two end points. Q 3 - A ray has A - One end point B - Two end points C - Three end points D - No end points Answer - A Explanation A ray has one end point. Q 4 - An angle which is greater then 180° but less than 360° is called A - Acute Angle B - Obtuse Angle C - Straight Angle D - Reflex Angle Answer - B Explanation An angle which is greater than 180° but less than 360° is called a reflex angle. Q 5 - The complement of 62° is. A - 118° B - 28° C - 38° D - 48° Answer - B Explanation Complement of 62°= (90° – 62°) = 28°. Q 6 - The supplement of 60° is A - 30° B - 40° C - 120° D - 300° Answer - B Explanation Supplement of 60° = (180°-60°) =120°. Q 7 - The complement of 72° 40' is A - 107°20' B - 27°20' C - 17°20' D - 12°40' Answer - C Explanation Complement of 72° 40' = (90°-72° 40') =17° 20'. Q 8 - An angle is one fifth of its supplement. The measure of the angle is A - 15° B - 30° C - 75° D - 150° Answer - B Explanation x = 1/5 (180 – x )⇒ 5x = 180 – x ⇒ 6x = 180 ⇒ x = 30°. Q 9 - If an angle is its own complementary angle, then its measure is A - 30° B - 45° C - 60° D - 90° Answer - B Explanation x=(90-x) ⇒ 2x = 90 ⇒ x = 45° . Q 10 - How many angles are made by rays shown in the figure? A - 5 B - 6 C - 8 D - 10 Answer - D Explanation The angle are ∠AOB , ∠BOC,∠COD,∠DOE,∠AOC,∠AOD, ∠AOE,∠BOD,∠BOD,∠COE. Thus , 10 angle are formed. Q 11 - An angle is 24° more than its complement.The measure of the angle is A - 57° B - 47° C - 53° D - 66° Answer - A Explanation x – (90-x ) = 24 ⇒ 2x = 114 ⇒ x = 57 ∴ Required angle is 57°. Q 12 -An angle is 32° less than its supplement. The measure of the angle is A - 37° B - 74° C - 48° D - 66° Answer - A Explanation (180 –X) – X = 32 ⇒ 2x = 180 – 32 = 148 ⇒ x = 74. Required angle is 74°. Q 13 - Two Supplementary angles are in th ratio 3:2. The smaller angle measures A - 108° B - 81° C - 72° D - 66° Answer - C Explanation Let the measures of the angle be (3x)° and (2x)°. Then, 3x+2x=180 ⇒ 5x = 180 ⇒ x = 36. Smaller angle = (2x)° = (2*36)° = 72°. Q 14 - In the given figure, AOB is a straight line, ∠AOC = 68° and ∠BOC = x°. The value of the x is A - 120° B - 22° C - 112° D - 132° Answer - A Explanation Since ∠AOB is a straight angle , we have X+ 68 = 180 ⇒ x= (180-68)° = 120° Q 15 - In the given figure , AOB is a straight line, ∠AOC = (3x+20)° and ∠ BOC =(4 x-36)°. The value of the x is A - 32° B - 22° C - 26° D - 24° Answer - B Explanation Since ∠AOB is a straight angle , we have ∠AOC + ∠ BOC =180° ⇒ 3x + 20 +4x – 36 = 180 ⇒ 7x = 164 ⇒ x = 22. Q 16 - In the given figure , AOB is a straight line, ∠ AOC = (3x-8)° and ∠COD =50 and ∠BOD° =(x+10)°. The value of the x is A - 32° B - 42° C - 36° D - 52° Answer - A Explanation Since ∠AOB is a straight angle , we have ∠AOC + ∠ COB + ∠ BOD = 180° ⇒ (3X – 8)° + 50° + (X+ 10)° = 180° ⇒ 4X = 128 ⇒ X = 32. 87 Lectures 22.5 hours Programming Line Print Add Notes Bookmark this page
[ { "code": null, "e": 3909, "s": 3892, "text": "Q 1 - A line has" }, { "code": null, "e": 3927, "s": 3909, "text": "A - One end point" }, { "code": null, "e": 3946, "s": 3927, "text": "B - Two end points" }, { "code": null, "e": 3967, "s": 3946, "text": "C - Three end points" }, { "code": null, "e": 3985, "s": 3967, "text": "D - No end points" }, { "code": null, "e": 3996, "s": 3985, "text": "Answer - D" }, { "code": null, "e": 4008, "s": 3996, "text": "Explanation" }, { "code": null, "e": 4031, "s": 4008, "text": "A line has no points.\n" }, { "code": null, "e": 4056, "s": 4031, "text": "Q 2 - A line segment has" }, { "code": null, "e": 4074, "s": 4056, "text": "A - One end point" }, { "code": null, "e": 4093, "s": 4074, "text": "B - Two end points" }, { "code": null, "e": 4114, "s": 4093, "text": "C - Three end points" }, { "code": null, "e": 4132, "s": 4114, "text": "D - No end points" }, { "code": null, "e": 4143, "s": 4132, "text": "Answer - B" }, { "code": null, "e": 4155, "s": 4143, "text": "Explanation" }, { "code": null, "e": 4191, "s": 4155, "text": "A line segment has two end points.\n" }, { "code": null, "e": 4207, "s": 4191, "text": "Q 3 - A ray has" }, { "code": null, "e": 4225, "s": 4207, "text": "A - One end point" }, { "code": null, "e": 4244, "s": 4225, "text": "B - Two end points" }, { "code": null, "e": 4265, "s": 4244, "text": "C - Three end points" }, { "code": null, "e": 4283, "s": 4265, "text": "D - No end points" }, { "code": null, "e": 4294, "s": 4283, "text": "Answer - A" }, { "code": null, "e": 4306, "s": 4294, "text": "Explanation" }, { "code": null, "e": 4332, "s": 4306, "text": "A ray has one end point.\n" }, { "code": null, "e": 4403, "s": 4332, "text": "Q 4 - An angle which is greater then 180° but less than 360° is called" }, { "code": null, "e": 4419, "s": 4403, "text": "A - Acute Angle" }, { "code": null, "e": 4436, "s": 4419, "text": "B - Obtuse Angle" }, { "code": null, "e": 4455, "s": 4436, "text": "C - Straight Angle" }, { "code": null, "e": 4472, "s": 4455, "text": "D - Reflex Angle" }, { "code": null, "e": 4483, "s": 4472, "text": "Answer - B" }, { "code": null, "e": 4495, "s": 4483, "text": "Explanation" }, { "code": null, "e": 4578, "s": 4495, "text": "An angle which is greater than 180° but less than 360° is called a reflex angle.\n" }, { "code": null, "e": 4611, "s": 4578, "text": "Q 5 - The complement of 62° is." }, { "code": null, "e": 4620, "s": 4611, "text": "A - 118°" }, { "code": null, "e": 4628, "s": 4620, "text": "B - 28°" }, { "code": null, "e": 4636, "s": 4628, "text": "C - 38°" }, { "code": null, "e": 4644, "s": 4636, "text": "D - 48°" }, { "code": null, "e": 4655, "s": 4644, "text": "Answer - B" }, { "code": null, "e": 4667, "s": 4655, "text": "Explanation" }, { "code": null, "e": 4706, "s": 4667, "text": "Complement of 62°= (90° – 62°) = 28°.\n" }, { "code": null, "e": 4737, "s": 4706, "text": "Q 6 - The supplement of 60° is" }, { "code": null, "e": 4745, "s": 4737, "text": "A - 30°" }, { "code": null, "e": 4753, "s": 4745, "text": "B - 40°" }, { "code": null, "e": 4762, "s": 4753, "text": "C - 120°" }, { "code": null, "e": 4771, "s": 4762, "text": "D - 300°" }, { "code": null, "e": 4782, "s": 4771, "text": "Answer - B" }, { "code": null, "e": 4794, "s": 4782, "text": "Explanation" }, { "code": null, "e": 4833, "s": 4794, "text": "Supplement of 60° = (180°-60°) =120°.\n" }, { "code": null, "e": 4870, "s": 4833, "text": "Q 7 - The complement of 72° 40' is " }, { "code": null, "e": 4883, "s": 4870, "text": "A - 107°20' " }, { "code": null, "e": 4895, "s": 4883, "text": "B - 27°20' " }, { "code": null, "e": 4907, "s": 4895, "text": "C - 17°20' " }, { "code": null, "e": 4919, "s": 4907, "text": "D - 12°40' " }, { "code": null, "e": 4930, "s": 4919, "text": "Answer - C" }, { "code": null, "e": 4942, "s": 4930, "text": "Explanation" }, { "code": null, "e": 4991, "s": 4942, "text": "Complement of 72° 40' = (90°-72° 40') =17° 20'.\n" }, { "code": null, "e": 5066, "s": 4991, "text": "Q 8 - An angle is one fifth of its supplement. The measure of the angle is" }, { "code": null, "e": 5074, "s": 5066, "text": "A - 15°" }, { "code": null, "e": 5082, "s": 5074, "text": "B - 30°" }, { "code": null, "e": 5090, "s": 5082, "text": "C - 75°" }, { "code": null, "e": 5099, "s": 5090, "text": "D - 150°" }, { "code": null, "e": 5110, "s": 5099, "text": "Answer - B" }, { "code": null, "e": 5122, "s": 5110, "text": "Explanation" }, { "code": null, "e": 5178, "s": 5122, "text": "x = 1/5 (180 – x )⇒ 5x = 180 – x ⇒ 6x = 180 ⇒ x = 30°.\n" }, { "code": null, "e": 5249, "s": 5178, "text": "Q 9 - If an angle is its own complementary angle, then its measure is " }, { "code": null, "e": 5257, "s": 5249, "text": "A - 30°" }, { "code": null, "e": 5265, "s": 5257, "text": "B - 45°" }, { "code": null, "e": 5273, "s": 5265, "text": "C - 60°" }, { "code": null, "e": 5281, "s": 5273, "text": "D - 90°" }, { "code": null, "e": 5292, "s": 5281, "text": "Answer - B" }, { "code": null, "e": 5304, "s": 5292, "text": "Explanation" }, { "code": null, "e": 5336, "s": 5304, "text": "x=(90-x) ⇒ 2x = 90 ⇒ x = 45° .\n" }, { "code": null, "e": 5398, "s": 5336, "text": "Q 10 - How many angles are made by rays shown in the figure?\n" }, { "code": null, "e": 5404, "s": 5398, "text": "A - 5" }, { "code": null, "e": 5410, "s": 5404, "text": "B - 6" }, { "code": null, "e": 5416, "s": 5410, "text": "C - 8" }, { "code": null, "e": 5423, "s": 5416, "text": "D - 10" }, { "code": null, "e": 5434, "s": 5423, "text": "Answer - D" }, { "code": null, "e": 5446, "s": 5434, "text": "Explanation" }, { "code": null, "e": 5545, "s": 5446, "text": "The angle are ∠AOB , ∠BOC,∠COD,∠DOE,∠AOC,∠AOD, ∠AOE,∠BOD,∠BOD,∠COE. \nThus , 10 angle are formed.\n" }, { "code": null, "e": 5622, "s": 5545, "text": "Q 11 - An angle is 24° more than its complement.The measure of the angle is" }, { "code": null, "e": 5630, "s": 5622, "text": "A - 57°" }, { "code": null, "e": 5638, "s": 5630, "text": "B - 47°" }, { "code": null, "e": 5646, "s": 5638, "text": "C - 53°" }, { "code": null, "e": 5654, "s": 5646, "text": "D - 66°" }, { "code": null, "e": 5665, "s": 5654, "text": "Answer - A" }, { "code": null, "e": 5677, "s": 5665, "text": "Explanation" }, { "code": null, "e": 5740, "s": 5677, "text": "x – (90-x ) = 24 ⇒ 2x = 114 ⇒ x = 57\n∴ Required angle is 57°.\n" }, { "code": null, "e": 5817, "s": 5740, "text": "Q 12 -An angle is 32° less than its supplement. The measure of the angle is" }, { "code": null, "e": 5825, "s": 5817, "text": "A - 37°" }, { "code": null, "e": 5833, "s": 5825, "text": "B - 74°" }, { "code": null, "e": 5841, "s": 5833, "text": "C - 48°" }, { "code": null, "e": 5849, "s": 5841, "text": "D - 66°" }, { "code": null, "e": 5860, "s": 5849, "text": "Answer - A" }, { "code": null, "e": 5872, "s": 5860, "text": "Explanation" }, { "code": null, "e": 5948, "s": 5872, "text": "(180 –X) – X = 32 ⇒ 2x = 180 – 32 = 148 ⇒ x = 74. \nRequired angle is 74°.\n" }, { "code": null, "e": 6030, "s": 5948, "text": "Q 13 - Two Supplementary angles are in th ratio 3:2. The smaller angle measures " }, { "code": null, "e": 6039, "s": 6030, "text": "A - 108°" }, { "code": null, "e": 6047, "s": 6039, "text": "B - 81°" }, { "code": null, "e": 6055, "s": 6047, "text": "C - 72°" }, { "code": null, "e": 6063, "s": 6055, "text": "D - 66°" }, { "code": null, "e": 6074, "s": 6063, "text": "Answer - C" }, { "code": null, "e": 6086, "s": 6074, "text": "Explanation" }, { "code": null, "e": 6215, "s": 6086, "text": "Let the measures of the angle be (3x)° and (2x)°. Then, \n3x+2x=180 ⇒ 5x = 180 ⇒ x = 36.\nSmaller angle = (2x)° = (2*36)° = 72°. \n" }, { "code": null, "e": 6316, "s": 6215, "text": "Q 14 - In the given figure, AOB is a straight line, ∠AOC = 68° and\t∠BOC = x°. The value of the x is " }, { "code": null, "e": 6325, "s": 6316, "text": "A - 120°" }, { "code": null, "e": 6333, "s": 6325, "text": "B - 22°" }, { "code": null, "e": 6342, "s": 6333, "text": "C - 112°" }, { "code": null, "e": 6351, "s": 6342, "text": "D - 132°" }, { "code": null, "e": 6362, "s": 6351, "text": "Answer - A" }, { "code": null, "e": 6374, "s": 6362, "text": "Explanation" }, { "code": null, "e": 6451, "s": 6374, "text": "Since ∠AOB is a straight angle , we have\nX+ 68 = 180 ⇒ x= (180-68)° = 120°\n" }, { "code": null, "e": 6566, "s": 6451, "text": "Q 15 - In the given figure , AOB is a straight line, ∠AOC = (3x+20)° and ∠ BOC =(4 x-36)°. The value of the x is " }, { "code": null, "e": 6574, "s": 6566, "text": "A - 32°" }, { "code": null, "e": 6582, "s": 6574, "text": "B - 22°" }, { "code": null, "e": 6590, "s": 6582, "text": "C - 26°" }, { "code": null, "e": 6598, "s": 6590, "text": "D - 24°" }, { "code": null, "e": 6609, "s": 6598, "text": "Answer - B" }, { "code": null, "e": 6621, "s": 6609, "text": "Explanation" }, { "code": null, "e": 6731, "s": 6621, "text": "Since ∠AOB is a straight angle , we have \n∠AOC + ∠ BOC =180° \n⇒ 3x + 20 +4x – 36 = 180\n⇒ 7x = 164 ⇒ x = 22.\n" }, { "code": null, "e": 6857, "s": 6731, "text": "Q 16 - In the given figure , AOB is a straight line, ∠ AOC = (3x-8)° and ∠COD =50 and ∠BOD° =(x+10)°. The value of the x is " }, { "code": null, "e": 6865, "s": 6857, "text": "A - 32°" }, { "code": null, "e": 6873, "s": 6865, "text": "B - 42°" }, { "code": null, "e": 6881, "s": 6873, "text": "C - 36°" }, { "code": null, "e": 6889, "s": 6881, "text": "D - 52°" }, { "code": null, "e": 6900, "s": 6889, "text": "Answer - A" }, { "code": null, "e": 6912, "s": 6900, "text": "Explanation" }, { "code": null, "e": 7045, "s": 6912, "text": "Since ∠AOB is a straight angle , we have\n∠AOC + ∠ COB + ∠ BOD = 180° \n⇒ (3X – 8)° + 50° + (X+ 10)° = 180° \n⇒ 4X = 128 ⇒ X = 32. \n" }, { "code": null, "e": 7081, "s": 7045, "text": "\n 87 Lectures \n 22.5 hours \n" }, { "code": null, "e": 7099, "s": 7081, "text": " Programming Line" }, { "code": null, "e": 7106, "s": 7099, "text": " Print" }, { "code": null, "e": 7117, "s": 7106, "text": " Add Notes" } ]
MySQL - Insert Query
To insert data into a MySQL table, you would need to use the SQL INSERT INTO command. You can insert data into the MySQL table by using the mysql> prompt or by using any script like PHP. Here is a generic SQL syntax of INSERT INTO command to insert data into the MySQL table − INSERT INTO table_name ( field1, field2,...fieldN ) VALUES ( value1, value2,...valueN ); To insert string data types, it is required to keep all the values into double or single quotes. For example "value". To insert data from the command prompt, we will use SQL INSERT INTO command to insert data into MySQL table tutorials_tbl. The following example will create 3 records into tutorials_tbl table − root@host# mysql -u root -p password; Enter password:******* mysql> use TUTORIALS; Database changed mysql> INSERT INTO tutorials_tbl ->(tutorial_title, tutorial_author, submission_date) ->VALUES ->("Learn PHP", "John Poul", NOW()); Query OK, 1 row affected (0.01 sec) mysql> INSERT INTO tutorials_tbl ->(tutorial_title, tutorial_author, submission_date) ->VALUES ->("Learn MySQL", "Abdul S", NOW()); Query OK, 1 row affected (0.01 sec) mysql> INSERT INTO tutorials_tbl ->(tutorial_title, tutorial_author, submission_date) ->VALUES ->("JAVA Tutorial", "Sanjay", '2007-05-06'); Query OK, 1 row affected (0.01 sec) mysql> NOTE − Please note that all the arrow signs (->) are not a part of the SQL command. They are indicating a new line and they are created automatically by the MySQL prompt while pressing the enter key without giving a semicolon at the end of each line of the command. In the above example, we have not provided a tutorial_id because at the time of table creation, we had given AUTO_INCREMENT option for this field. So MySQL takes care of inserting these IDs automatically. Here, NOW() is a MySQL function, which returns the current date and time. PHP uses mysqli query() or mysql_query() function to insert a record into a MySQL table. This function takes two parameters and returns TRUE on success or FALSE on failure. $mysqli->query($sql,$resultmode) $sql Required - SQL query to insert record into a table. $resultmode Optional - Either the constant MYSQLI_USE_RESULT or MYSQLI_STORE_RESULT depending on the desired behavior. By default, MYSQLI_STORE_RESULT is used. This example will take three parameters from the user and will insert them into the MySQL table − − Copy and paste the following example as mysql_example.php − <html> <head><title>Add New Record in MySQL Database</title></head> <body> <?php if(isset($_POST['add'])) { $dbhost = 'localhost'; $dbuser = 'root'; $dbpass = 'root@123'; $dbname = 'TUTORIALS'; $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname); if($mysqli->connect_errno ) { printf("Connect failed: %s<br />", $mysqli->connect_error); exit(); } printf('Connected successfully.<br />'); if(! get_magic_quotes_gpc() ) { $tutorial_title = addslashes ($_POST['tutorial_title']); $tutorial_author = addslashes ($_POST['tutorial_author']); } else { $tutorial_title = $_POST['tutorial_title']; $tutorial_author = $_POST['tutorial_author']; } $submission_date = $_POST['submission_date']; $sql = "INSERT INTO tutorials_tbl ". "(tutorial_title,tutorial_author, submission_date) "."VALUES ". "('$tutorial_title','$tutorial_author','$submission_date')"; if ($mysqli->query($sql)) { printf("Record inserted successfully.<br />"); } if ($mysqli->errno) { printf("Could not insert record into table: %s<br />", $mysqli->error); } $mysqli->close(); } else { ?> <form method = "post" action = "<?php $_PHP_SELF ?>"> <table width = "600" border = "0" cellspacing = "1" cellpadding = "2"> <tr> <td width = "250">Tutorial Title</td> <td><input name = "tutorial_title" type = "text" id = "tutorial_title"></td> </tr> <tr> <td width = "250">Tutorial Author</td> <td><input name = "tutorial_author" type = "text" id = "tutorial_author"></td> </tr> <tr> <td width = "250">Submission Date [ yyyy-mm-dd ]</td> <td><input name = "submission_date" type = "text" id = "submission_date"></td> </tr> <tr> <td width = "250"> </td> <td></td> </tr> <tr> <td width = "250"> </td> <td><input name = "add" type = "submit" id = "add" value = "Add Tutorial"></td> </tr> </table> </form> <?php } ?> </body> </html> Access the mysql_example.php deployed on apache web server, enter details and verify the output on submitting the form. Record inserted successfully. While doing a data insert, it is best to use the function get_magic_quotes_gpc() to check if the current configuration for magic quote is set or not. If this function returns false, then use the function addslashes() to add slashes before the quotes. You can put many validations around to check if the entered data is correct or not and can take the appropriate action. 31 Lectures 6 hours Eduonix Learning Solutions 84 Lectures 5.5 hours Frahaan Hussain 6 Lectures 3.5 hours DATAhill Solutions Srinivas Reddy 60 Lectures 10 hours Vijay Kumar Parvatha Reddy 10 Lectures 1 hours Harshit Srivastava 25 Lectures 4 hours Trevoir Williams Print Add Notes Bookmark this page
[ { "code": null, "e": 2520, "s": 2333, "text": "To insert data into a MySQL table, you would need to use the SQL INSERT INTO command. You can insert data into the MySQL table by using the mysql> prompt or by using any script like PHP." }, { "code": null, "e": 2611, "s": 2520, "text": "Here is a generic SQL syntax of INSERT INTO command to insert data into the MySQL table −" }, { "code": null, "e": 2707, "s": 2611, "text": "INSERT INTO table_name ( field1, field2,...fieldN )\n VALUES\n ( value1, value2,...valueN );\n" }, { "code": null, "e": 2825, "s": 2707, "text": "To insert string data types, it is required to keep all the values into double or single quotes. For example \"value\"." }, { "code": null, "e": 2948, "s": 2825, "text": "To insert data from the command prompt, we will use SQL INSERT INTO command to insert data into MySQL table tutorials_tbl." }, { "code": null, "e": 3019, "s": 2948, "text": "The following example will create 3 records into tutorials_tbl table −" }, { "code": null, "e": 3669, "s": 3019, "text": "root@host# mysql -u root -p password;\nEnter password:*******\nmysql> use TUTORIALS;\nDatabase changed\n\nmysql> INSERT INTO tutorials_tbl \n ->(tutorial_title, tutorial_author, submission_date)\n ->VALUES\n ->(\"Learn PHP\", \"John Poul\", NOW());\nQuery OK, 1 row affected (0.01 sec)\n\nmysql> INSERT INTO tutorials_tbl\n ->(tutorial_title, tutorial_author, submission_date)\n ->VALUES\n ->(\"Learn MySQL\", \"Abdul S\", NOW());\nQuery OK, 1 row affected (0.01 sec)\n\nmysql> INSERT INTO tutorials_tbl\n ->(tutorial_title, tutorial_author, submission_date)\n ->VALUES\n ->(\"JAVA Tutorial\", \"Sanjay\", '2007-05-06');\nQuery OK, 1 row affected (0.01 sec)\nmysql>" }, { "code": null, "e": 3935, "s": 3669, "text": "NOTE − Please note that all the arrow signs (->) are not a part of the SQL command. They are indicating a new line and they are created automatically by the MySQL prompt while pressing the enter key without giving a semicolon at the end of each line of the command." }, { "code": null, "e": 4214, "s": 3935, "text": "In the above example, we have not provided a tutorial_id because at the time of table creation, we had given AUTO_INCREMENT option for this field. So MySQL takes care of inserting these IDs automatically. Here, NOW() is a MySQL function, which returns the current date and time." }, { "code": null, "e": 4387, "s": 4214, "text": "PHP uses mysqli query() or mysql_query() function to insert a record into a MySQL table. This function takes two parameters and returns TRUE on success or FALSE on failure." }, { "code": null, "e": 4421, "s": 4387, "text": "$mysqli->query($sql,$resultmode)\n" }, { "code": null, "e": 4426, "s": 4421, "text": "$sql" }, { "code": null, "e": 4478, "s": 4426, "text": "Required - SQL query to insert record into a table." }, { "code": null, "e": 4490, "s": 4478, "text": "$resultmode" }, { "code": null, "e": 4638, "s": 4490, "text": "Optional - Either the constant MYSQLI_USE_RESULT or MYSQLI_STORE_RESULT depending on the desired behavior. By default, MYSQLI_STORE_RESULT is used." }, { "code": null, "e": 4738, "s": 4638, "text": "This example will take three parameters from the user and will insert them into the MySQL table − −" }, { "code": null, "e": 4798, "s": 4738, "text": "Copy and paste the following example as mysql_example.php −" }, { "code": null, "e": 7360, "s": 4798, "text": "<html>\n <head><title>Add New Record in MySQL Database</title></head>\n <body>\n <?php\n if(isset($_POST['add'])) {\n $dbhost = 'localhost';\n $dbuser = 'root';\n $dbpass = 'root@123';\n $dbname = 'TUTORIALS';\n $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);\n \n if($mysqli->connect_errno ) {\n printf(\"Connect failed: %s<br />\", $mysqli->connect_error);\n exit();\n }\n printf('Connected successfully.<br />');\n\n if(! get_magic_quotes_gpc() ) {\n $tutorial_title = addslashes ($_POST['tutorial_title']);\n $tutorial_author = addslashes ($_POST['tutorial_author']);\n } else {\n $tutorial_title = $_POST['tutorial_title'];\n $tutorial_author = $_POST['tutorial_author'];\n }\n\n $submission_date = $_POST['submission_date'];\n $sql = \"INSERT INTO tutorials_tbl \".\n \"(tutorial_title,tutorial_author, submission_date) \".\"VALUES \".\n \"('$tutorial_title','$tutorial_author','$submission_date')\";\n \n if ($mysqli->query($sql)) {\n printf(\"Record inserted successfully.<br />\");\n }\n if ($mysqli->errno) {\n printf(\"Could not insert record into table: %s<br />\", $mysqli->error);\n }\n $mysqli->close();\n } else {\n ?> \n <form method = \"post\" action = \"<?php $_PHP_SELF ?>\">\n <table width = \"600\" border = \"0\" cellspacing = \"1\" cellpadding = \"2\">\n <tr>\n <td width = \"250\">Tutorial Title</td>\n <td><input name = \"tutorial_title\" type = \"text\" id = \"tutorial_title\"></td>\n </tr> \n <tr>\n <td width = \"250\">Tutorial Author</td>\n <td><input name = \"tutorial_author\" type = \"text\" id = \"tutorial_author\"></td>\n </tr> \n <tr>\n <td width = \"250\">Submission Date [ yyyy-mm-dd ]</td>\n <td><input name = \"submission_date\" type = \"text\" id = \"submission_date\"></td>\n </tr> \n <tr>\n <td width = \"250\"> </td>\n <td></td>\n </tr> \n <tr>\n <td width = \"250\"> </td>\n <td><input name = \"add\" type = \"submit\" id = \"add\" value = \"Add Tutorial\"></td>\n </tr>\n </table>\n </form>\n <?php\n }\n ?>\n </body>\n</html>" }, { "code": null, "e": 7480, "s": 7360, "text": "Access the mysql_example.php deployed on apache web server, enter details and verify the output on submitting the form." }, { "code": null, "e": 7511, "s": 7480, "text": "Record inserted successfully.\n" }, { "code": null, "e": 7762, "s": 7511, "text": "While doing a data insert, it is best to use the function get_magic_quotes_gpc() to check if the current configuration for magic quote is set or not. If this function returns false, then use the function addslashes() to add slashes before the quotes." }, { "code": null, "e": 7882, "s": 7762, "text": "You can put many validations around to check if the entered data is correct or not and can take the appropriate action." }, { "code": null, "e": 7915, "s": 7882, "text": "\n 31 Lectures \n 6 hours \n" }, { "code": null, "e": 7943, "s": 7915, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 7978, "s": 7943, "text": "\n 84 Lectures \n 5.5 hours \n" }, { "code": null, "e": 7995, "s": 7978, "text": " Frahaan Hussain" }, { "code": null, "e": 8029, "s": 7995, "text": "\n 6 Lectures \n 3.5 hours \n" }, { "code": null, "e": 8064, "s": 8029, "text": " DATAhill Solutions Srinivas Reddy" }, { "code": null, "e": 8098, "s": 8064, "text": "\n 60 Lectures \n 10 hours \n" }, { "code": null, "e": 8126, "s": 8098, "text": " Vijay Kumar Parvatha Reddy" }, { "code": null, "e": 8159, "s": 8126, "text": "\n 10 Lectures \n 1 hours \n" }, { "code": null, "e": 8179, "s": 8159, "text": " Harshit Srivastava" }, { "code": null, "e": 8212, "s": 8179, "text": "\n 25 Lectures \n 4 hours \n" }, { "code": null, "e": 8230, "s": 8212, "text": " Trevoir Williams" }, { "code": null, "e": 8237, "s": 8230, "text": " Print" }, { "code": null, "e": 8248, "s": 8237, "text": " Add Notes" } ]
GATE | GATE-CS-2014-(Set-2) | Question 65 - GeeksforGeeks
28 Jun, 2021 At what time between 6 a.m. and 7 a.m. will the minute hand and hour hand of a clock make an angle closest to 60o(A) 6:22 am(B) 6:27 am(C) 6:38 am(D) 6:45 amAnswer: (A)Explanation: Speed of the Hour hand = ( 360 degree ) / ( 12 * 60 minutes ) = 0.5 degree / minute. Speed of the minute hand = ( 360 degree ) / ( 60 minutes ) = 6 degree / minute. At 6 am, hour hand will point vertically downward to 6 in the clock, and minute hand will point vertically upward to 12 in the clock. ( Hence they are opposite with a gap of 180 degree between them). Now after t minutes , The angle between these two hands will be either of the below two: (180 - 6t) + 0.5t, when the minute hand is behind the hour hand or, 6t - (180 + 0.5t), when the minute hand is ahead of hour hand, Now the the question asks for angle of 60 degree. Hence, (180 - 6t) + 0.5t = 60 , we get t = 21.8 minute and 6t - ( 180 + 0.5t ) = 60, we get t = 48 minutess Hence the closest to answer is 22 minutes, i.e. 6.22 am. Hence answer is A.Quiz of this Question GATE-CS-2014-(Set-2) GATE-GATE-CS-2014-(Set-2) GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments GATE | GATE-IT-2004 | Question 71 GATE | GATE CS 2011 | Question 7 GATE | GATE-CS-2016 (Set 2) | Question 48 GATE | GATE CS 2010 | Question 24 GATE | GATE-CS-2015 (Set 3) | Question 65 GATE | GATE-CS-2016 (Set 1) | Question 65 GATE | GATE-CS-2014-(Set-3) | Question 38 GATE | GATE CS 2018 | Question 37 GATE | GATE-IT-2004 | Question 83 GATE | GATE-CS-2016 (Set 1) | Question 63
[ { "code": null, "e": 24674, "s": 24646, "text": "\n28 Jun, 2021" }, { "code": null, "e": 24855, "s": 24674, "text": "At what time between 6 a.m. and 7 a.m. will the minute hand and hour hand of a clock make an angle closest to 60o(A) 6:22 am(B) 6:27 am(C) 6:38 am(D) 6:45 amAnswer: (A)Explanation:" }, { "code": null, "e": 25070, "s": 24855, "text": "Speed of the Hour hand = ( 360 degree ) / ( 12 * 60 minutes ) \n = 0.5 degree / minute.\nSpeed of the minute hand = ( 360 degree ) / ( 60 minutes ) \n = 6 degree / minute." }, { "code": null, "e": 25270, "s": 25070, "text": "At 6 am, hour hand will point vertically downward to 6 in the clock, and minute hand will point vertically upward to 12 in the clock. ( Hence they are opposite with a gap of 180 degree between them)." }, { "code": null, "e": 25359, "s": 25270, "text": "Now after t minutes , The angle between these two hands will be either of the below two:" }, { "code": null, "e": 25694, "s": 25359, "text": "\n(180 - 6t) + 0.5t, when the minute hand is \n behind the hour hand or,\n\n6t - (180 + 0.5t), when the minute hand is \n ahead of hour hand,\n\nNow the the question asks for angle of 60 degree.\n\nHence, \n(180 - 6t) + 0.5t = 60 , we get t = 21.8 minute\nand\n6t - ( 180 + 0.5t ) = 60, we get t = 48 minutess" }, { "code": null, "e": 25791, "s": 25694, "text": "Hence the closest to answer is 22 minutes, i.e. 6.22 am. Hence answer is A.Quiz of this Question" }, { "code": null, "e": 25812, "s": 25791, "text": "GATE-CS-2014-(Set-2)" }, { "code": null, "e": 25838, "s": 25812, "text": "GATE-GATE-CS-2014-(Set-2)" }, { "code": null, "e": 25843, "s": 25838, "text": "GATE" }, { "code": null, "e": 25941, "s": 25843, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25950, "s": 25941, "text": "Comments" }, { "code": null, "e": 25963, "s": 25950, "text": "Old Comments" }, { "code": null, "e": 25997, "s": 25963, "text": "GATE | GATE-IT-2004 | Question 71" }, { "code": null, "e": 26030, "s": 25997, "text": "GATE | GATE CS 2011 | Question 7" }, { "code": null, "e": 26072, "s": 26030, "text": "GATE | GATE-CS-2016 (Set 2) | Question 48" }, { "code": null, "e": 26106, "s": 26072, "text": "GATE | GATE CS 2010 | Question 24" }, { "code": null, "e": 26148, "s": 26106, "text": "GATE | GATE-CS-2015 (Set 3) | Question 65" }, { "code": null, "e": 26190, "s": 26148, "text": "GATE | GATE-CS-2016 (Set 1) | Question 65" }, { "code": null, "e": 26232, "s": 26190, "text": "GATE | GATE-CS-2014-(Set-3) | Question 38" }, { "code": null, "e": 26266, "s": 26232, "text": "GATE | GATE CS 2018 | Question 37" }, { "code": null, "e": 26300, "s": 26266, "text": "GATE | GATE-IT-2004 | Question 83" } ]
How to Perform a SUMIF Function in Pandas? - GeeksforGeeks
22 Nov, 2021 sumif() function is used to perform sum operation by a group of items in the dataframe, It can be applied on single and multiple columns and we can also use this function with groupby function. This function is used to display sum of all columns with respect to grouped column Syntax: dataframe.groupby(‘group_column’).sum() where dataframe is the input dataframe group_column is the column in dataframe to be grouped sum() function is to perform the sum operation Python3 # import pandas moduleimport pandas as pd # create dataframe with 4 columnsdata = pd.DataFrame({ "name": ['sravan', 'jyothika', 'harsha', 'ramya', 'sravan', 'jyothika', 'harsha', 'ramya', 'sravan', 'jyothika', 'harsha', 'ramya'], "subjects": ['java', 'java', 'java', 'python', 'python', 'python', 'html/php', 'html/php', 'html/php', 'php/js', 'php/js', 'php/js'], "internal marks": [98, 79, 89, 97, 82, 98, 90, 87, 78, 89, 93, 94], "external marks": [88, 71, 89, 97, 82, 98, 80, 87, 71, 89, 92, 64],}) # display dataframeprint(data) Output: Python3 # import pandas moduleimport pandas as pd # create dataframe with 4 columnsdata = pd.DataFrame({ "name": ['sravan', 'jyothika', 'harsha', 'ramya', 'sravan', 'jyothika', 'harsha', 'ramya', 'sravan', 'jyothika', 'harsha', 'ramya'], "subjects": ['java', 'java', 'java', 'python', 'python', 'python', 'html/php', 'html/php', 'html/php', 'php/js', 'php/js', 'php/js'], "internal marks": [98, 79, 89, 97, 82, 98, 90, 87, 78, 89, 93, 94], "external marks": [88, 71, 89, 97, 82, 98, 80, 87, 71, 89, 92, 64],}) # find sum of all columns group by nameprint(data.groupby('name').sum()) # find sum of all columns group by subjectsprint(data.groupby('subjects').sum()) Output: Here we are performing sumif operation on one particular column by grouping it with one column Syntax: dataframe.groupby(‘group_column’)[‘column_name].sum() where dataframe is the input dataframe group_column is the column in dataframe to be grouped column_name is to get sum of this column with respect to grouped column sum() function is to perform the sum operation Python3 # import pandas moduleimport pandas as pd # create dataframe with 4 columnsdata = pd.DataFrame({ "name": ['sravan', 'jyothika', 'harsha', 'ramya', 'sravan', 'jyothika', 'harsha', 'ramya', 'sravan', 'jyothika', 'harsha', 'ramya'], "subjects": ['java', 'java', 'java', 'python', 'python', 'python', 'html/php', 'html/php', 'html/php', 'php/js', 'php/js', 'php/js'], "internal marks": [98, 79, 89, 97, 82, 98, 90, 87, 78, 89, 93, 94], "external marks": [88, 71, 89, 97, 82, 98, 80, 87, 71, 89, 92, 64],}) # find sum of columns group by# name with internal marks columnprint(data.groupby('name')['internal marks'].sum()) print("---------------") # find sum of columns group by# name with external marks columnprint(data.groupby('name')['external marks'].sum()) print("---------------") # find sum of columns group by# subjects with internal marks columnprint(data.groupby('subjects')['internal marks'].sum()) print("---------------") # find sum of columns group by# subjects with external marks columnprint(data.groupby('subjects')['external marks'].sum()) Output: Here we will use sumif operation on multiple columns. Syntax: dataframe.groupby(‘group_column’)[[‘column_names’]].sum() where, dataframe is the input dataframe group_column is the column in dataframe to be grouped column_names are to get sum of these columns with respect to grouped column sum() function is to perform the sum operation Python3 # import pandas moduleimport pandas as pd # create dataframe with 4 columnsdata = pd.DataFrame({ "name": ['sravan', 'jyothika', 'harsha', 'ramya', 'sravan', 'jyothika', 'harsha', 'ramya', 'sravan', 'jyothika', 'harsha', 'ramya'], "subjects": ['java', 'java', 'java', 'python', 'python', 'python', 'html/php', 'html/php', 'html/php', 'php/js', 'php/js', 'php/js'], "internal marks": [98, 79, 89, 97, 82, 98, 90, 87, 78, 89, 93, 94], "external marks": [88, 71, 89, 97, 82, 98, 80, 87, 71, 89, 92, 64],}) # find sum of columns group by name with# external marks and internal marks columnprint(data.groupby('name')[['external marks', 'internal marks']].sum()) print("---------------") # find sum of columns group by subjects# with external marks and internal marks columnprint(data.groupby('subjects')[['external marks', 'internal marks']].sum()) Output: Picked Python pandas-groupby Python-pandas 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 Convert Python Dictionary To JSON? Selecting rows in pandas DataFrame based on conditions How to drop one or multiple columns in Pandas Dataframe Check if element exists in list in Python 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": 24292, "s": 24264, "text": "\n22 Nov, 2021" }, { "code": null, "e": 24486, "s": 24292, "text": "sumif() function is used to perform sum operation by a group of items in the dataframe, It can be applied on single and multiple columns and we can also use this function with groupby function." }, { "code": null, "e": 24569, "s": 24486, "text": "This function is used to display sum of all columns with respect to grouped column" }, { "code": null, "e": 24617, "s": 24569, "text": "Syntax: dataframe.groupby(‘group_column’).sum()" }, { "code": null, "e": 24623, "s": 24617, "text": "where" }, { "code": null, "e": 24656, "s": 24623, "text": "dataframe is the input dataframe" }, { "code": null, "e": 24710, "s": 24656, "text": "group_column is the column in dataframe to be grouped" }, { "code": null, "e": 24757, "s": 24710, "text": "sum() function is to perform the sum operation" }, { "code": null, "e": 24765, "s": 24757, "text": "Python3" }, { "code": "# import pandas moduleimport pandas as pd # create dataframe with 4 columnsdata = pd.DataFrame({ \"name\": ['sravan', 'jyothika', 'harsha', 'ramya', 'sravan', 'jyothika', 'harsha', 'ramya', 'sravan', 'jyothika', 'harsha', 'ramya'], \"subjects\": ['java', 'java', 'java', 'python', 'python', 'python', 'html/php', 'html/php', 'html/php', 'php/js', 'php/js', 'php/js'], \"internal marks\": [98, 79, 89, 97, 82, 98, 90, 87, 78, 89, 93, 94], \"external marks\": [88, 71, 89, 97, 82, 98, 80, 87, 71, 89, 92, 64],}) # display dataframeprint(data)", "e": 25445, "s": 24765, "text": null }, { "code": null, "e": 25453, "s": 25445, "text": "Output:" }, { "code": null, "e": 25461, "s": 25453, "text": "Python3" }, { "code": "# import pandas moduleimport pandas as pd # create dataframe with 4 columnsdata = pd.DataFrame({ \"name\": ['sravan', 'jyothika', 'harsha', 'ramya', 'sravan', 'jyothika', 'harsha', 'ramya', 'sravan', 'jyothika', 'harsha', 'ramya'], \"subjects\": ['java', 'java', 'java', 'python', 'python', 'python', 'html/php', 'html/php', 'html/php', 'php/js', 'php/js', 'php/js'], \"internal marks\": [98, 79, 89, 97, 82, 98, 90, 87, 78, 89, 93, 94], \"external marks\": [88, 71, 89, 97, 82, 98, 80, 87, 71, 89, 92, 64],}) # find sum of all columns group by nameprint(data.groupby('name').sum()) # find sum of all columns group by subjectsprint(data.groupby('subjects').sum())", "e": 26252, "s": 25461, "text": null }, { "code": null, "e": 26260, "s": 26252, "text": "Output:" }, { "code": null, "e": 26355, "s": 26260, "text": "Here we are performing sumif operation on one particular column by grouping it with one column" }, { "code": null, "e": 26417, "s": 26355, "text": "Syntax: dataframe.groupby(‘group_column’)[‘column_name].sum()" }, { "code": null, "e": 26423, "s": 26417, "text": "where" }, { "code": null, "e": 26456, "s": 26423, "text": "dataframe is the input dataframe" }, { "code": null, "e": 26510, "s": 26456, "text": "group_column is the column in dataframe to be grouped" }, { "code": null, "e": 26582, "s": 26510, "text": "column_name is to get sum of this column with respect to grouped column" }, { "code": null, "e": 26629, "s": 26582, "text": "sum() function is to perform the sum operation" }, { "code": null, "e": 26637, "s": 26629, "text": "Python3" }, { "code": "# import pandas moduleimport pandas as pd # create dataframe with 4 columnsdata = pd.DataFrame({ \"name\": ['sravan', 'jyothika', 'harsha', 'ramya', 'sravan', 'jyothika', 'harsha', 'ramya', 'sravan', 'jyothika', 'harsha', 'ramya'], \"subjects\": ['java', 'java', 'java', 'python', 'python', 'python', 'html/php', 'html/php', 'html/php', 'php/js', 'php/js', 'php/js'], \"internal marks\": [98, 79, 89, 97, 82, 98, 90, 87, 78, 89, 93, 94], \"external marks\": [88, 71, 89, 97, 82, 98, 80, 87, 71, 89, 92, 64],}) # find sum of columns group by# name with internal marks columnprint(data.groupby('name')['internal marks'].sum()) print(\"---------------\") # find sum of columns group by# name with external marks columnprint(data.groupby('name')['external marks'].sum()) print(\"---------------\") # find sum of columns group by# subjects with internal marks columnprint(data.groupby('subjects')['internal marks'].sum()) print(\"---------------\") # find sum of columns group by# subjects with external marks columnprint(data.groupby('subjects')['external marks'].sum())", "e": 27834, "s": 26637, "text": null }, { "code": null, "e": 27842, "s": 27834, "text": "Output:" }, { "code": null, "e": 27896, "s": 27842, "text": "Here we will use sumif operation on multiple columns." }, { "code": null, "e": 27962, "s": 27896, "text": "Syntax: dataframe.groupby(‘group_column’)[[‘column_names’]].sum()" }, { "code": null, "e": 27969, "s": 27962, "text": "where," }, { "code": null, "e": 28002, "s": 27969, "text": "dataframe is the input dataframe" }, { "code": null, "e": 28056, "s": 28002, "text": "group_column is the column in dataframe to be grouped" }, { "code": null, "e": 28132, "s": 28056, "text": "column_names are to get sum of these columns with respect to grouped column" }, { "code": null, "e": 28179, "s": 28132, "text": "sum() function is to perform the sum operation" }, { "code": null, "e": 28187, "s": 28179, "text": "Python3" }, { "code": "# import pandas moduleimport pandas as pd # create dataframe with 4 columnsdata = pd.DataFrame({ \"name\": ['sravan', 'jyothika', 'harsha', 'ramya', 'sravan', 'jyothika', 'harsha', 'ramya', 'sravan', 'jyothika', 'harsha', 'ramya'], \"subjects\": ['java', 'java', 'java', 'python', 'python', 'python', 'html/php', 'html/php', 'html/php', 'php/js', 'php/js', 'php/js'], \"internal marks\": [98, 79, 89, 97, 82, 98, 90, 87, 78, 89, 93, 94], \"external marks\": [88, 71, 89, 97, 82, 98, 80, 87, 71, 89, 92, 64],}) # find sum of columns group by name with# external marks and internal marks columnprint(data.groupby('name')[['external marks', 'internal marks']].sum()) print(\"---------------\") # find sum of columns group by subjects# with external marks and internal marks columnprint(data.groupby('subjects')[['external marks', 'internal marks']].sum())", "e": 29227, "s": 28187, "text": null }, { "code": null, "e": 29235, "s": 29227, "text": "Output:" }, { "code": null, "e": 29242, "s": 29235, "text": "Picked" }, { "code": null, "e": 29264, "s": 29242, "text": "Python pandas-groupby" }, { "code": null, "e": 29278, "s": 29264, "text": "Python-pandas" }, { "code": null, "e": 29285, "s": 29278, "text": "Python" }, { "code": null, "e": 29383, "s": 29285, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29392, "s": 29383, "text": "Comments" }, { "code": null, "e": 29405, "s": 29392, "text": "Old Comments" }, { "code": null, "e": 29437, "s": 29405, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29479, "s": 29437, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 29534, "s": 29479, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 29590, "s": 29534, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 29632, "s": 29590, "text": "Check if element exists in list in Python" }, { "code": null, "e": 29654, "s": 29632, "text": "Defaultdict in Python" }, { "code": null, "e": 29693, "s": 29654, "text": "Python | Get unique values from a list" }, { "code": null, "e": 29724, "s": 29693, "text": "Python | os.path.join() method" }, { "code": null, "e": 29753, "s": 29724, "text": "Create a directory in Python" } ]
Speed up your pytest GitHub Actions with Docker | by Emeline Floc'h | Towards Data Science
GitHub introduced Actions in 2018 as a fast and easy to set up CI/CD solution. Because of its recent release date, documentation on the topic is sometimes hard to find and I couldn’t put my hands on something that explained how to set up your Actions that run pytest in a pipenv environment into a Docker container. Here is a quick summary of the method I used on a Mac. To install Docker, download Docker Desktop from the homepage, and follow the instructions on the desktop app. You’ll need to create a Docker Hub account to publish your Docker image and be able to use it in your GitHub Actions. To create a Docker image, create a file called Dockerfile in your python project root folder, at the same level as your Pipfile. In Dockerfile copy the following lines. # Get the python 3.8 base docker imageFROM python:3.8# Install pipenvRUN pip install pipenv# Copy your Pipfile and Pipfile.lock in your containerCOPY Pipfile .COPY Pipfile.lock .# Install all the dependencies from your lock file directly into the # containerRUN pipenv install — system — deploy Once you’ve saved the Dockerfile, run the following commands to update your Pipfile.lock file, build your docker container using your Docker Hub username then push your Docker image to Docker Hub. >> pipenv lock>> docker build -t <hub-username>/<repo-name>>> docker push <hub-username>/<repo-name> You now have a docker image pushed to Docker Hub and it should appear in your account. You are now ready to use it within your Github Actions workflow. The last step is creating a workflow that runs pytest in your container. Follow the following template and copy these lines in a YAML file. name: Pytest with Pipenv & Docker# workflow triggered by any push on any branchon: [push]jobs: build: name: Pytest in Pipenv # runs on the latest Ubuntu runs-on: ubuntu-latest # runs within your Docker container container: image: docker://<hub-username>/<repo-name>:latest # checkout your code from your repository # and runs pytest in your pipenv environment steps: - uses: actions/checkout@v2 - name: Test with pytest run: | pipenv run pytest tests/ Save this file in your .github/workflows/ folder. Once all these steps are done and you push code to your repository with tests in your tests/ folder, you should see on the GitHub Actions page that your container has been initialized and that your tests have been run in the container. You should also see that the setup of the local environment was much faster than by simply installing the dependencies from the pipfile in your workflow. And there you have it, the easiest way to speed up your pytest in Github Actions.
[ { "code": null, "e": 543, "s": 172, "text": "GitHub introduced Actions in 2018 as a fast and easy to set up CI/CD solution. Because of its recent release date, documentation on the topic is sometimes hard to find and I couldn’t put my hands on something that explained how to set up your Actions that run pytest in a pipenv environment into a Docker container. Here is a quick summary of the method I used on a Mac." }, { "code": null, "e": 771, "s": 543, "text": "To install Docker, download Docker Desktop from the homepage, and follow the instructions on the desktop app. You’ll need to create a Docker Hub account to publish your Docker image and be able to use it in your GitHub Actions." }, { "code": null, "e": 900, "s": 771, "text": "To create a Docker image, create a file called Dockerfile in your python project root folder, at the same level as your Pipfile." }, { "code": null, "e": 940, "s": 900, "text": "In Dockerfile copy the following lines." }, { "code": null, "e": 1235, "s": 940, "text": "# Get the python 3.8 base docker imageFROM python:3.8# Install pipenvRUN pip install pipenv# Copy your Pipfile and Pipfile.lock in your containerCOPY Pipfile .COPY Pipfile.lock .# Install all the dependencies from your lock file directly into the # containerRUN pipenv install — system — deploy" }, { "code": null, "e": 1432, "s": 1235, "text": "Once you’ve saved the Dockerfile, run the following commands to update your Pipfile.lock file, build your docker container using your Docker Hub username then push your Docker image to Docker Hub." }, { "code": null, "e": 1533, "s": 1432, "text": ">> pipenv lock>> docker build -t <hub-username>/<repo-name>>> docker push <hub-username>/<repo-name>" }, { "code": null, "e": 1685, "s": 1533, "text": "You now have a docker image pushed to Docker Hub and it should appear in your account. You are now ready to use it within your Github Actions workflow." }, { "code": null, "e": 1825, "s": 1685, "text": "The last step is creating a workflow that runs pytest in your container. Follow the following template and copy these lines in a YAML file." }, { "code": null, "e": 2334, "s": 1825, "text": "name: Pytest with Pipenv & Docker# workflow triggered by any push on any branchon: [push]jobs: build: name: Pytest in Pipenv # runs on the latest Ubuntu runs-on: ubuntu-latest # runs within your Docker container container: image: docker://<hub-username>/<repo-name>:latest # checkout your code from your repository # and runs pytest in your pipenv environment steps: - uses: actions/checkout@v2 - name: Test with pytest run: | pipenv run pytest tests/ " }, { "code": null, "e": 2774, "s": 2334, "text": "Save this file in your .github/workflows/ folder. Once all these steps are done and you push code to your repository with tests in your tests/ folder, you should see on the GitHub Actions page that your container has been initialized and that your tests have been run in the container. You should also see that the setup of the local environment was much faster than by simply installing the dependencies from the pipfile in your workflow." } ]
Perl Assignment Operators Example
Assume variable $a holds 10 and variable $b holds 20, then below are the assignment operators available in Perl and their usage − = Simple assignment operator, Assigns values from right side operands to left side operand Example − $c = $a + $b will assigned value of $a + $b into $c += Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand Example − $c += $a is equivalent to $c = $c + $a -= Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand Example − $c -= $a is equivalent to $c = $c - $a *= Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand Example − $c *= $a is equivalent to $c = $c * $a /= Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand Example − $c /= $a is equivalent to $c = $c / $a %= Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand Example − $c %= $a is equivalent to $c = $c % a **= Exponent AND assignment operator, Performs exponential (power) calculation on operators and assign value to the left operand Example − $c **= $a is equivalent to $c = $c ** $a Try the following example to understand all the assignment operators available in Perl. Copy and paste the following Perl program in test.pl file and execute this program. #!/usr/local/bin/perl $a = 10; $b = 20; print "Value of \$a = $a and value of \$b = $b\n"; $c = $a + $b; print "After assignment value of \$c = $c\n"; $c += $a; print "Value of \$c = $c after statement \$c += \$a\n"; $c -= $a; print "Value of \$c = $c after statement \$c -= \$a\n"; $c *= $a; print "Value of \$c = $c after statement \$c *= \$a\n"; $c /= $a; print "Value of \$c = $c after statement \$c /= \$a\n"; $c %= $a; print "Value of \$c = $c after statement \$c %= \$a\n"; $c = 2; $a = 4; print "Value of \$a = $a and value of \$c = $c\n"; $c **= $a; print "Value of \$c = $c after statement \$c **= \$a\n"; When the above code is executed, it produces the following result − Value of $a = 10 and value of $b = 20 After assignment value of $c = 30 Value of $c = 40 after statement $c += $a Value of $c = 30 after statement $c -= $a Value of $c = 300 after statement $c *= $a Value of $c = 30 after statement $c /= $a Value of $c = 0 after statement $c %= $a Value of $a = 4 and value of $c = 2 Value of $c = 16 after statement $c **= $a 46 Lectures 4.5 hours Devi Killada 11 Lectures 1.5 hours Harshit Srivastava 30 Lectures 6 hours TELCOMA Global 24 Lectures 2 hours Mohammad Nauman 68 Lectures 7 hours Stone River ELearning 58 Lectures 6.5 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 2350, "s": 2220, "text": "Assume variable $a holds 10 and variable $b holds 20, then below are the assignment operators available in Perl and their usage −" }, { "code": null, "e": 2352, "s": 2350, "text": "=" }, { "code": null, "e": 2441, "s": 2352, "text": "Simple assignment operator, Assigns values from right side operands to left side operand" }, { "code": null, "e": 2503, "s": 2441, "text": "Example − $c = $a + $b will assigned value of $a + $b into $c" }, { "code": null, "e": 2506, "s": 2503, "text": "+=" }, { "code": null, "e": 2615, "s": 2506, "text": "Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand" }, { "code": null, "e": 2664, "s": 2615, "text": "Example − $c += $a is equivalent to $c = $c + $a" }, { "code": null, "e": 2667, "s": 2664, "text": "-=" }, { "code": null, "e": 2788, "s": 2667, "text": "Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand" }, { "code": null, "e": 2837, "s": 2788, "text": "Example − $c -= $a is equivalent to $c = $c - $a" }, { "code": null, "e": 2840, "s": 2837, "text": "*=" }, { "code": null, "e": 2962, "s": 2840, "text": "Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand" }, { "code": null, "e": 3011, "s": 2962, "text": "Example − $c *= $a is equivalent to $c = $c * $a" }, { "code": null, "e": 3014, "s": 3011, "text": "/=" }, { "code": null, "e": 3131, "s": 3014, "text": "Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand" }, { "code": null, "e": 3180, "s": 3131, "text": "Example − $c /= $a is equivalent to $c = $c / $a" }, { "code": null, "e": 3183, "s": 3180, "text": "%=" }, { "code": null, "e": 3290, "s": 3183, "text": "Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand" }, { "code": null, "e": 3338, "s": 3290, "text": "Example − $c %= $a is equivalent to $c = $c % a" }, { "code": null, "e": 3342, "s": 3338, "text": "**=" }, { "code": null, "e": 3467, "s": 3342, "text": "Exponent AND assignment operator, Performs exponential (power) calculation on operators and assign value to the left operand" }, { "code": null, "e": 3518, "s": 3467, "text": "Example − $c **= $a is equivalent to $c = $c ** $a" }, { "code": null, "e": 3690, "s": 3518, "text": "Try the following example to understand all the assignment operators available in Perl. Copy and paste the following Perl program in test.pl file and execute this program." }, { "code": null, "e": 4316, "s": 3690, "text": "#!/usr/local/bin/perl\n \n$a = 10;\n$b = 20;\n\nprint \"Value of \\$a = $a and value of \\$b = $b\\n\";\n\n$c = $a + $b;\nprint \"After assignment value of \\$c = $c\\n\";\n\n$c += $a;\nprint \"Value of \\$c = $c after statement \\$c += \\$a\\n\";\n\n$c -= $a;\nprint \"Value of \\$c = $c after statement \\$c -= \\$a\\n\";\n\n$c *= $a;\nprint \"Value of \\$c = $c after statement \\$c *= \\$a\\n\";\n\n$c /= $a;\nprint \"Value of \\$c = $c after statement \\$c /= \\$a\\n\";\n\n$c %= $a;\nprint \"Value of \\$c = $c after statement \\$c %= \\$a\\n\";\n\n$c = 2;\n$a = 4;\nprint \"Value of \\$a = $a and value of \\$c = $c\\n\";\n$c **= $a;\nprint \"Value of \\$c = $c after statement \\$c **= \\$a\\n\";" }, { "code": null, "e": 4384, "s": 4316, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 4746, "s": 4384, "text": "Value of $a = 10 and value of $b = 20\nAfter assignment value of $c = 30\nValue of $c = 40 after statement $c += $a\nValue of $c = 30 after statement $c -= $a\nValue of $c = 300 after statement $c *= $a\nValue of $c = 30 after statement $c /= $a\nValue of $c = 0 after statement $c %= $a\nValue of $a = 4 and value of $c = 2\nValue of $c = 16 after statement $c **= $a\n" }, { "code": null, "e": 4781, "s": 4746, "text": "\n 46 Lectures \n 4.5 hours \n" }, { "code": null, "e": 4795, "s": 4781, "text": " Devi Killada" }, { "code": null, "e": 4830, "s": 4795, "text": "\n 11 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4850, "s": 4830, "text": " Harshit Srivastava" }, { "code": null, "e": 4883, "s": 4850, "text": "\n 30 Lectures \n 6 hours \n" }, { "code": null, "e": 4899, "s": 4883, "text": " TELCOMA Global" }, { "code": null, "e": 4932, "s": 4899, "text": "\n 24 Lectures \n 2 hours \n" }, { "code": null, "e": 4949, "s": 4932, "text": " Mohammad Nauman" }, { "code": null, "e": 4982, "s": 4949, "text": "\n 68 Lectures \n 7 hours \n" }, { "code": null, "e": 5005, "s": 4982, "text": " Stone River ELearning" }, { "code": null, "e": 5040, "s": 5005, "text": "\n 58 Lectures \n 6.5 hours \n" }, { "code": null, "e": 5063, "s": 5040, "text": " Stone River ELearning" }, { "code": null, "e": 5070, "s": 5063, "text": " Print" }, { "code": null, "e": 5081, "s": 5070, "text": " Add Notes" } ]
How to use shared preference in Android between activities?
This example demonstrate about How to use shared preference in Android between activities. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version = "1.0" encoding = "utf-8"?> <LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" xmlns:tools = "http://schemas.android.com/tools" android:layout_width = "match_parent" android:layout_height = "match_parent" android:layout_margin = "16dp" android:orientation = "vertical" tools:context = ".MainActivity"> <EditText android:id = "@+id/edit_text" android:layout_width = "match_parent" android:layout_height = "wrap_content" android:layout_gravity = "center" android:hint = "Enter something to pass" android:inputType = "text" /> <Button android:id = "@+id/button" android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:layout_gravity = "center" android:layout_marginTop = "16dp" android:text = "Next" /> </LinearLayout> Step 3 − Add the following code to src/MainActivity.java package com.example.myapplication; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final EditText editText = findViewById(R.id.edit_text); Button button = findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String value = editText.getText().toString().trim(); SharedPreferences sharedPref = getSharedPreferences("myKey", MODE_PRIVATE); SharedPreferences.Editor editor = sharedPref.edit(); editor.putString("value", value); editor.apply(); Intent intent = new Intent(MainActivity.this, SecondActivity.class); startActivity(intent); } }); } } Step 4 − Add the following code to res/layout/activity_second.xml. <?xml version = "1.0" encoding = "utf-8"?> <LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" xmlns:tools = "http://schemas.android.com/tools" android:layout_width = "match_parent" android:layout_height = "match_parent" android:layout_margin = "16dp" android:orientation = "vertical" tools:context = ".SecondActivity"> <TextView android:id = "@+id/text_view" android:layout_width = "match_parent" android:layout_height = "wrap_content" android:layout_gravity = "center" /> </LinearLayout> Step 5 − Add the following code to src/SecondActivity.java package com.example.myapplication; import android.content.SharedPreferences; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.TextView; public class SecondActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_second); TextView textView = findViewById(R.id.text_view); SharedPreferences sharedPreferences = getSharedPreferences("myKey", MODE_PRIVATE); String value = sharedPreferences.getString("value",""); textView.setText(value); } } Step 6 − 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.myapplication"> <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> <activity android:name = ".SecondActivity"></activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen – Click here to download the project code
[ { "code": null, "e": 1153, "s": 1062, "text": "This example demonstrate about How to use shared preference in Android between activities." }, { "code": null, "e": 1282, "s": 1153, "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": 1347, "s": 1282, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2227, "s": 1347, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<LinearLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n android:layout_margin = \"16dp\"\n android:orientation = \"vertical\"\n tools:context = \".MainActivity\">\n <EditText\n android:id = \"@+id/edit_text\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\"\n android:layout_gravity = \"center\"\n android:hint = \"Enter something to pass\"\n android:inputType = \"text\" />\n <Button\n android:id = \"@+id/button\"\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\"\n android:layout_gravity = \"center\"\n android:layout_marginTop = \"16dp\"\n android:text = \"Next\" />\n</LinearLayout>" }, { "code": null, "e": 2284, "s": 2227, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 3433, "s": 2284, "text": "package com.example.myapplication;\nimport android.content.Intent;\nimport android.content.SharedPreferences;\nimport android.os.Bundle;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.EditText;\n\npublic class MainActivity extends AppCompatActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n final EditText editText = findViewById(R.id.edit_text);\n Button button = findViewById(R.id.button);\n button.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n String value = editText.getText().toString().trim();\n SharedPreferences sharedPref = getSharedPreferences(\"myKey\", MODE_PRIVATE);\n SharedPreferences.Editor editor = sharedPref.edit();\n editor.putString(\"value\", value);\n editor.apply();\n Intent intent = new Intent(MainActivity.this, SecondActivity.class);\n startActivity(intent);\n }\n });\n }\n}" }, { "code": null, "e": 3500, "s": 3433, "text": "Step 4 − Add the following code to res/layout/activity_second.xml." }, { "code": null, "e": 4058, "s": 3500, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<LinearLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n android:layout_margin = \"16dp\"\n android:orientation = \"vertical\"\n tools:context = \".SecondActivity\">\n <TextView\n android:id = \"@+id/text_view\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\"\n android:layout_gravity = \"center\" />\n</LinearLayout>" }, { "code": null, "e": 4117, "s": 4058, "text": "Step 5 − Add the following code to src/SecondActivity.java" }, { "code": null, "e": 4762, "s": 4117, "text": "package com.example.myapplication;\nimport android.content.SharedPreferences;\nimport android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.widget.TextView;\n\npublic class SecondActivity extends AppCompatActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_second);\n TextView textView = findViewById(R.id.text_view);\n SharedPreferences sharedPreferences = getSharedPreferences(\"myKey\", MODE_PRIVATE);\n String value = sharedPreferences.getString(\"value\",\"\");\n textView.setText(value);\n }\n}" }, { "code": null, "e": 4817, "s": 4762, "text": "Step 6 − Add the following code to androidManifest.xml" }, { "code": null, "e": 5585, "s": 4817, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<manifest xmlns:android = \"http://schemas.android.com/apk/res/android\"\n package = \"com.example.myapplication\">\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 <activity android:name = \".SecondActivity\"></activity>\n </application>\n</manifest>" }, { "code": null, "e": 5934, "s": 5585, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –" }, { "code": null, "e": 5974, "s": 5934, "text": "Click here to download the project code" } ]
sort() vs orderBy() in Spark | Towards Data Science
Sorting a Spark DataFrame is probably one of the most commonly used operations. You can use either sort() or orderBy() built-in functions to sort a particular DataFrame in ascending or descending order over at least one column. Even though both functions are supposed to order the data in a Spark DataFrame, they have one significant difference. In today’s article we are going to discuss the difference between sort() and orderBy() and understand when to use one over the other. First let’s create an example DataFrame that will use throughout the article to demonstrate how both sort() and orderBy() work. Note that I’ll be using the Python API but what we discuss today is also applicable for Scala as well. df = spark.createDataFrame( [ ('Andrew', 'Johnson', 'Engineering', 'UK', 34), ('Maria', 'Brown', 'Finance', 'US', 41), ('Michael', 'Stevenson', 'Sales', 'US', 31), ('Mark', 'Anderson', 'Engineering', 'Ireland', 28), ('Jen', 'White', 'Engineering', 'UK', 29) ], ['first_name', 'last_name', 'department', 'country', 'age'])df.show(truncate=False)+----------+---------+-----------+--------+---+|first_name|last_name| department||country|age|+----------+---------+-----------+--------+---+| Andrew| Johnson|Engineering| UK| 34|| Maria| Brown| Finance| US| 41|| Michael|Stevenson| Sales| US| 31|| Mark| Anderson|Engineering| Ireland| 28|| Jen| White|Engineering| UK| 29|+----------+---------+-----------+--------+---+ Now we can use sort() method do sort the DataFrame df based on the country and age of the employees in ascending order. df.sort('country', 'age').show(truncate=False)+----------+---------+-----------+--------+---+|first_name|last_name| department||country|age|+----------+---------+-----------+--------+---+| Mark| Anderson|Engineering| Ireland| 28|| Jen| White|Engineering| UK| 29|| Andrew| Johnson|Engineering| UK| 34|| Michael|Stevenson| Sales| US| 31|| Maria| Brown| Finance| US| 41|+----------+---------+-----------+--------+---+ Note however that sort() method will sort the records in each partition and then return the final output which means that the order of the output data is not guaranteed because the data is ordered on partition-level but your DataFrame may have thousands of partitions distributed across the cluster. Since the data is not collected into a single executor the sort() method is efficient thus more suitable when sorting is not critical for your use-case. For example, if employees Jen and Andrew are stored on a different partition the final order may have been wrong, for instance: +----------+---------+-----------+--------+---+|first_name|last_name| department||country|age|+----------+---------+-----------+--------+---+| Mark| Anderson|Engineering| Ireland| 28|| Andrew| Johnson|Engineering| UK| 34|| Jen| White|Engineering| UK| 29|| Michael|Stevenson| Sales| US| 31|| Maria| Brown| Finance| US| 41|+----------+---------+-----------+--------+---+ In the same way we can use orderBy() to order our DataFrame based on the country and age of the employees in ascending order: df.orderBy('country', 'age').show(truncate=False)+----------+---------+-----------+--------+---+|first_name|last_name| department||country|age|+----------+---------+-----------+--------+---+| Mark| Anderson|Engineering| Ireland| 28|| Jen| White|Engineering| UK| 29|| Andrew| Johnson|Engineering| UK| 34|| Michael|Stevenson| Sales| US| 31|| Maria| Brown| Finance| US| 41|+----------+---------+-----------+--------+---+ Unlike sort(), the orderBy() function guarantees a total order in the output. This happens because the data will be collected into a single executor in order to be sorted. This means that orderBy() is more inefficient compared to sort(). Both sort() and orderBy() functions can be used to sort Spark DataFrames on at least one column and any desired order, namely ascending or descending. sort() is more efficient compared to orderBy() because the data is sorted on each partition individually and this is why the order in the output data is not guaranteed. On the other hand, orderBy() collects all the data into a single executor and then sorts them. This means that the order of the output data is guaranteed but this is probably a very costly operation. Therefore, if you need to sort a DataFrame where the order is not so critical and at the same time you want it to be as fast as possible then sort() is more suitable. In case the order is critical, make sure to use orderBy() that guarantees that the output data is ordered based on the user parameters.
[ { "code": null, "e": 518, "s": 172, "text": "Sorting a Spark DataFrame is probably one of the most commonly used operations. You can use either sort() or orderBy() built-in functions to sort a particular DataFrame in ascending or descending order over at least one column. Even though both functions are supposed to order the data in a Spark DataFrame, they have one significant difference." }, { "code": null, "e": 652, "s": 518, "text": "In today’s article we are going to discuss the difference between sort() and orderBy() and understand when to use one over the other." }, { "code": null, "e": 883, "s": 652, "text": "First let’s create an example DataFrame that will use throughout the article to demonstrate how both sort() and orderBy() work. Note that I’ll be using the Python API but what we discuss today is also applicable for Scala as well." }, { "code": null, "e": 1680, "s": 883, "text": "df = spark.createDataFrame( [ ('Andrew', 'Johnson', 'Engineering', 'UK', 34), ('Maria', 'Brown', 'Finance', 'US', 41), ('Michael', 'Stevenson', 'Sales', 'US', 31), ('Mark', 'Anderson', 'Engineering', 'Ireland', 28), ('Jen', 'White', 'Engineering', 'UK', 29) ], ['first_name', 'last_name', 'department', 'country', 'age'])df.show(truncate=False)+----------+---------+-----------+--------+---+|first_name|last_name| department||country|age|+----------+---------+-----------+--------+---+| Andrew| Johnson|Engineering| UK| 34|| Maria| Brown| Finance| US| 41|| Michael|Stevenson| Sales| US| 31|| Mark| Anderson|Engineering| Ireland| 28|| Jen| White|Engineering| UK| 29|+----------+---------+-----------+--------+---+" }, { "code": null, "e": 1800, "s": 1680, "text": "Now we can use sort() method do sort the DataFrame df based on the country and age of the employees in ascending order." }, { "code": null, "e": 2270, "s": 1800, "text": "df.sort('country', 'age').show(truncate=False)+----------+---------+-----------+--------+---+|first_name|last_name| department||country|age|+----------+---------+-----------+--------+---+| Mark| Anderson|Engineering| Ireland| 28|| Jen| White|Engineering| UK| 29|| Andrew| Johnson|Engineering| UK| 34|| Michael|Stevenson| Sales| US| 31|| Maria| Brown| Finance| US| 41|+----------+---------+-----------+--------+---+" }, { "code": null, "e": 2723, "s": 2270, "text": "Note however that sort() method will sort the records in each partition and then return the final output which means that the order of the output data is not guaranteed because the data is ordered on partition-level but your DataFrame may have thousands of partitions distributed across the cluster. Since the data is not collected into a single executor the sort() method is efficient thus more suitable when sorting is not critical for your use-case." }, { "code": null, "e": 2851, "s": 2723, "text": "For example, if employees Jen and Andrew are stored on a different partition the final order may have been wrong, for instance:" }, { "code": null, "e": 3275, "s": 2851, "text": "+----------+---------+-----------+--------+---+|first_name|last_name| department||country|age|+----------+---------+-----------+--------+---+| Mark| Anderson|Engineering| Ireland| 28|| Andrew| Johnson|Engineering| UK| 34|| Jen| White|Engineering| UK| 29|| Michael|Stevenson| Sales| US| 31|| Maria| Brown| Finance| US| 41|+----------+---------+-----------+--------+---+" }, { "code": null, "e": 3401, "s": 3275, "text": "In the same way we can use orderBy() to order our DataFrame based on the country and age of the employees in ascending order:" }, { "code": null, "e": 3874, "s": 3401, "text": "df.orderBy('country', 'age').show(truncate=False)+----------+---------+-----------+--------+---+|first_name|last_name| department||country|age|+----------+---------+-----------+--------+---+| Mark| Anderson|Engineering| Ireland| 28|| Jen| White|Engineering| UK| 29|| Andrew| Johnson|Engineering| UK| 34|| Michael|Stevenson| Sales| US| 31|| Maria| Brown| Finance| US| 41|+----------+---------+-----------+--------+---+" }, { "code": null, "e": 4112, "s": 3874, "text": "Unlike sort(), the orderBy() function guarantees a total order in the output. This happens because the data will be collected into a single executor in order to be sorted. This means that orderBy() is more inefficient compared to sort()." }, { "code": null, "e": 4263, "s": 4112, "text": "Both sort() and orderBy() functions can be used to sort Spark DataFrames on at least one column and any desired order, namely ascending or descending." }, { "code": null, "e": 4432, "s": 4263, "text": "sort() is more efficient compared to orderBy() because the data is sorted on each partition individually and this is why the order in the output data is not guaranteed." }, { "code": null, "e": 4632, "s": 4432, "text": "On the other hand, orderBy() collects all the data into a single executor and then sorts them. This means that the order of the output data is guaranteed but this is probably a very costly operation." } ]
How to convert an array into a matrix in R?
To convert an array into a matrix in R, we can use apply function. For example, if we have an array called ARRAY that contains 2 array elements then we can convert this array into a single matrix using the command apply(ARRAY,2,c). We need to understand the dimension of the array making the conversion otherwise the output will not be as expected. Consider the below array − Live Demo x1<-array(1:50,dim=c(5,5,2)) x1 , , 1 [,1] [,2] [,3] [,4] [,5] [1,] 1 6 11 16 21 [2,] 2 7 12 17 22 [3,] 3 8 13 18 23 [4,] 4 9 14 19 24 [5,] 5 10 15 20 25 , , 2 [,1] [,2] [,3] [,4] [,5] [1,] 26 31 36 41 46 [2,] 27 32 37 42 47 [3,] 28 33 38 43 48 [4,] 29 34 39 44 49 [5,] 30 35 40 45 50 Converting x1 into a matrix − apply(x1,2,c) [,1] [,2] [,3] [,4] [,5] [1,] 1 6 11 16 21 [2,] 2 7 12 17 22 [3,] 3 8 13 18 23 [4,] 4 9 14 19 24 [5,] 5 10 15 20 25 [6,] 26 31 36 41 46 [7,] 27 32 37 42 47 [8,] 28 33 38 43 48 [9,] 29 34 39 44 49 [10,] 30 35 40 45 50 Live Demo x2<-array(rpois(20,5),dim=c(10,2,2)) x2 , , 1 [,1] [,2] [1,] 8 7 [2,] 8 9 [3,] 6 6 [4,] 5 5 [5,] 5 6 [6,] 5 7 [7,] 1 3 [8,] 8 7 [9,] 6 3 [10,] 3 2 , , 2 [,1] [,2] [1,] 8 7 [2,] 8 9 [3,] 6 6 [4,] 5 5 [5,] 5 6 [6,] 5 7 [7,] 1 3 [8,] 8 7 [9,] 6 3 [10,] 3 2 Converting x2 into a matrix − apply(x2,2,c) [,1] [,2] [1,] 8 7 [2,] 8 9 [3,] 6 6 [4,] 5 5 [5,] 5 6 [6,] 5 7 [7,] 1 3 [8,] 8 7 [9,] 6 3 [10,] 3 2 [11,] 8 7 [12,] 8 9 [13,] 6 6 [14,] 5 5 [15,] 5 6 [16,] 5 7 [17,] 1 3 [18,] 8 7 [19,] 6 3 [20,] 3 2
[ { "code": null, "e": 1411, "s": 1062, "text": "To convert an array into a matrix in R, we can use apply function. For example, if we have an array called ARRAY that contains 2 array elements then we can convert this array into a single matrix using the command apply(ARRAY,2,c). We need to understand the dimension of the array making the conversion otherwise the output will not be as expected." }, { "code": null, "e": 1438, "s": 1411, "text": "Consider the below array −" }, { "code": null, "e": 1449, "s": 1438, "text": " Live Demo" }, { "code": null, "e": 1487, "s": 1449, "text": "x1<-array(1:50,dim=c(5,5,2))\nx1\n, , 1" }, { "code": null, "e": 1832, "s": 1487, "text": " [,1] [,2] [,3] [,4] [,5]\n[1,] 1 6 11 16 21\n[2,] 2 7 12 17 22\n[3,] 3 8 13 18 23\n[4,] 4 9 14 19 24\n[5,] 5 10 15 20 25\n, , 2\n [,1] [,2] [,3] [,4] [,5]\n[1,] 26 31 36 41 46\n[2,] 27 32 37 42 47\n[3,] 28 33 38 43 48\n[4,] 29 34 39 44 49\n[5,] 30 35 40 45 50" }, { "code": null, "e": 1862, "s": 1832, "text": "Converting x1 into a matrix −" }, { "code": null, "e": 1876, "s": 1862, "text": "apply(x1,2,c)" }, { "code": null, "e": 2185, "s": 1876, "text": " [,1] [,2] [,3] [,4] [,5]\n[1,] 1 6 11 16 21\n[2,] 2 7 12 17 22\n[3,] 3 8 13 18 23\n[4,] 4 9 14 19 24\n[5,] 5 10 15 20 25\n[6,] 26 31 36 41 46\n[7,] 27 32 37 42 47\n[8,] 28 33 38 43 48\n[9,] 29 34 39 44 49\n[10,] 30 35 40 45 50" }, { "code": null, "e": 2196, "s": 2185, "text": " Live Demo" }, { "code": null, "e": 2236, "s": 2196, "text": "x2<-array(rpois(20,5),dim=c(10,2,2))\nx2" }, { "code": null, "e": 2526, "s": 2236, "text": ", , 1\n [,1] [,2]\n[1,] 8 7\n[2,] 8 9\n[3,] 6 6\n[4,] 5 5\n[5,] 5 6\n[6,] 5 7\n[7,] 1 3\n[8,] 8 7 \n[9,] 6 3\n[10,] 3 2\n, , 2\n [,1] [,2]\n[1,] 8 7\n[2,] 8 9\n[3,] 6 6\n[4,] 5 5\n[5,] 5 6\n[6,] 5 7\n[7,] 1 3\n[8,] 8 7\n[9,] 6 3\n[10,] 3 2" }, { "code": null, "e": 2556, "s": 2526, "text": "Converting x2 into a matrix −" }, { "code": null, "e": 2570, "s": 2556, "text": "apply(x2,2,c)" }, { "code": null, "e": 2824, "s": 2570, "text": " [,1] [,2]\n[1,] 8 7\n[2,] 8 9\n[3,] 6 6\n[4,] 5 5\n[5,] 5 6\n[6,] 5 7\n[7,] 1 3\n[8,] 8 7\n[9,] 6 3\n[10,] 3 2\n[11,] 8 7\n[12,] 8 9\n[13,] 6 6\n[14,] 5 5\n[15,] 5 6\n[16,] 5 7\n[17,] 1 3\n[18,] 8 7 \n[19,] 6 3\n[20,] 3 2" } ]
Statistical analysis of a stock price | by Gianluca Malato | Towards Data Science
The stock market is always considered a challenge for statistics. Somebody thinks that knowing the statistics of a market lets us beat it and earn money. The reality can be quite different. In this article, I’m going to show you a statistical analysis of Google stock price. In 2008, for my Bachelor’s Degree in Theoretical Physics, I had to analyze stock prices in order to check the validity of a stock market model. In the following part of the article, I’m going to show you some of those analyses applied to Google stock price using Python. The code can be found in my GitHub repository here: https://github.com/gianlucamalato/machinelearning/blob/master/Stock_market_analysis.ipynb First, we need to get stock data. I’m going to use the yfinance library to download the price time series. First, we have to install this library. !pip install yfinance Then we can import some useful libraries. import pandas as pdimport numpy as npimport yfinanceimport matplotlib.pyplot as pltfrom scipy.stats import skew,kurtosis,norm,skewtest,kurtosistestfrom statsmodels.graphics.tsaplots import plot_pacf,plot_acf We can now get Google price data from 2015 to 2020. name = 'GOOG'ticker = yfinance.Ticker(name)df = ticker.history(interval="1d",start="2015-03-15",end="2020-09-10")x = df['Close'] We are now going to work with x object, which contains the daily close price of the stock. Let’s plot the daily close price. As you can see, there’s quite a nice bullish trend. There are some drawdowns, but the drift seems to be quite positive. When you perform the statistical analysis of a stock, it’s very useful to work with its returns and not with the price itself. The return from one day to another one is the percentage change of the closing price between the two days. In Python, series objects have the pct_change method that allows us to calculate this quantity. The argument is the lag to use. In this article, I’ll use a 1-day lag. returns = x.pct_change(1).dropna() The result is this: The first number is (x[1]-x[0])/x[0], the second one is (x[2]-x[1])/x[1] and so on. This is the data we are going to analyze. We are now going to calculate some insights about the probability distribution of returns. Let’s make a first raw histogram of returns. plt.hist(returns,bins="rice",label="Daily close price")plt.legend()plt.show() As you can see, it’s quite centered around zero and it seems symmetric. However, we can see that this histogram has tails that don’t seem to be neglectable. Let’s make a boxplot to better understand the distribution of this dataset. plt.boxplot(returns,labels=["Daily close price"])plt.show() As you can see, it’s full of outliers. The interquartile range (i.e. the height of the box) is quite narrow if compared with the distribution total range. This phenomenon is called fat tails and it’s very common in stock analysis. Let’s calculate some observables of our dataset. The mean value is: It’s quite similar to zero, but the fact that it’s positive explains the positive drift of the price time series. Let’s now take a look at the standard deviation: It’s more than an order of magnitude higher than the mean value. It’s clearly the effect of outliers. In stock price analysis, the standard deviation is a measure of the risk and such a high standard deviation is the reason why stocks are considered risky assets. Let’s take a look at the median: It’s not so different from the mean value, so we might think that the distribution is symmetrical. Let’s check the skewness of the distribution to better assess the symmetry: It’s positive, so we can assume that the distribution is not symmetrical (i.e. null skewness) and that the right tail as a not neglectable weight. If we perform a test on the skewness, we find: The very low p-value suggests that the skewness of the distribution can’t be neglected, so we can’t assume that it’s symmetrical. Finally, we can measure the kurtosis (scipy normalizes the kurtosis so that it is 0 for a normal distribution) It’s very different from zero, so the distribution is quite different from a normal one. A kurtosis test gives us these results: Again, a very small p-value lets us reject the null hypothesis that the kurtosis is the same as a normal distribution (which is 0). Although the statistically significant high values of kurtosis and skewness already tell us that the returns aren’t normally distributed, a Q-Q plot will give us graphically clear information. t = np.linspace(0.01,0.99,1000)q1 = np.quantile(returns,t)q2 = norm.ppf(t,loc=np.mean(returns),scale=np.std(returns))plt.plot(q1,q2)plt.plot([min(q1),max(q1)],[min(q2),max(q2)])plt.xlim((min(q1),max(q1)))plt.ylim((min(q2),max(q2)))plt.xlabel("Daily returns")plt.ylabel("Normal distribution")plt.show() The straight line is what we expect for a normal distribution, while the blue line is what we get from our data. It’s clear that the quantiles of our dataset aren’t comparable with the quantiles of a normal distribution with the same mean and standard deviation. So, returns aren’t normally distributed and this makes models like Geometric Brownian Motion (which assumes normal returns) only an approximation of the reality. Once we have ensured the non-normality of the returns probability distribution, let’s take a look at the raw time series. plt.plot(returns)plt.xlabel("Time")plt.ylabel("Daily returns")plt.show() It’s clear that there are time periods with high volatility and other periods with low volatility. This phenomenon is called volatility clustering and it’s very common in the stock market. Practically speaking, the standard deviation changes during time, making the time series non-stationary. A closer look at the 20-days rolling standard deviation will make everything clear. plt.plot(returns.rolling(20).std())plt.xlabel("Time")plt.ylabel("20-days rolling standard deviation")plt.show() It’s clear that it’s not a constant value, but it has spikes and oscillations. The fat tails of the distribution may be caused by these volatility spikes, which create non-neglectable outliers. Finally, we can plot the partial autocorrelation function, which gives us some ideas about the autocorrelation of the time series and the possibility that this autocorrelation can be used for prediction purposes in some ARIMA model. plot_pacf(returns,lags=20) It’s clear from this plot that there’s no high correlation among all lags. There are some lags between 5 and 10 that show some correlation, but it’s quite small compared with 1. So we can easily understand that using some ARIMA models would be quite useless. In this article, I’ve shown a simple statistical analysis of Google stock price. The returns aren’t normally distributed, since they are skewed and have fat tails. The time series is not stationary because the standard deviation changes over time. The autocorrelation of returns time series is very low at almost any lag, making ARIMA models useless. So, predicting stock prices using statistics and machine learning is a great challenge. Some results have been achieved using LSTM models, but we are very far from clearly modeling a stock market in a money-making way.
[ { "code": null, "e": 362, "s": 172, "text": "The stock market is always considered a challenge for statistics. Somebody thinks that knowing the statistics of a market lets us beat it and earn money. The reality can be quite different." }, { "code": null, "e": 447, "s": 362, "text": "In this article, I’m going to show you a statistical analysis of Google stock price." }, { "code": null, "e": 718, "s": 447, "text": "In 2008, for my Bachelor’s Degree in Theoretical Physics, I had to analyze stock prices in order to check the validity of a stock market model. In the following part of the article, I’m going to show you some of those analyses applied to Google stock price using Python." }, { "code": null, "e": 860, "s": 718, "text": "The code can be found in my GitHub repository here: https://github.com/gianlucamalato/machinelearning/blob/master/Stock_market_analysis.ipynb" }, { "code": null, "e": 967, "s": 860, "text": "First, we need to get stock data. I’m going to use the yfinance library to download the price time series." }, { "code": null, "e": 1007, "s": 967, "text": "First, we have to install this library." }, { "code": null, "e": 1029, "s": 1007, "text": "!pip install yfinance" }, { "code": null, "e": 1071, "s": 1029, "text": "Then we can import some useful libraries." }, { "code": null, "e": 1279, "s": 1071, "text": "import pandas as pdimport numpy as npimport yfinanceimport matplotlib.pyplot as pltfrom scipy.stats import skew,kurtosis,norm,skewtest,kurtosistestfrom statsmodels.graphics.tsaplots import plot_pacf,plot_acf" }, { "code": null, "e": 1331, "s": 1279, "text": "We can now get Google price data from 2015 to 2020." }, { "code": null, "e": 1460, "s": 1331, "text": "name = 'GOOG'ticker = yfinance.Ticker(name)df = ticker.history(interval=\"1d\",start=\"2015-03-15\",end=\"2020-09-10\")x = df['Close']" }, { "code": null, "e": 1551, "s": 1460, "text": "We are now going to work with x object, which contains the daily close price of the stock." }, { "code": null, "e": 1585, "s": 1551, "text": "Let’s plot the daily close price." }, { "code": null, "e": 1705, "s": 1585, "text": "As you can see, there’s quite a nice bullish trend. There are some drawdowns, but the drift seems to be quite positive." }, { "code": null, "e": 1832, "s": 1705, "text": "When you perform the statistical analysis of a stock, it’s very useful to work with its returns and not with the price itself." }, { "code": null, "e": 1939, "s": 1832, "text": "The return from one day to another one is the percentage change of the closing price between the two days." }, { "code": null, "e": 2106, "s": 1939, "text": "In Python, series objects have the pct_change method that allows us to calculate this quantity. The argument is the lag to use. In this article, I’ll use a 1-day lag." }, { "code": null, "e": 2141, "s": 2106, "text": "returns = x.pct_change(1).dropna()" }, { "code": null, "e": 2161, "s": 2141, "text": "The result is this:" }, { "code": null, "e": 2245, "s": 2161, "text": "The first number is (x[1]-x[0])/x[0], the second one is (x[2]-x[1])/x[1] and so on." }, { "code": null, "e": 2287, "s": 2245, "text": "This is the data we are going to analyze." }, { "code": null, "e": 2378, "s": 2287, "text": "We are now going to calculate some insights about the probability distribution of returns." }, { "code": null, "e": 2423, "s": 2378, "text": "Let’s make a first raw histogram of returns." }, { "code": null, "e": 2501, "s": 2423, "text": "plt.hist(returns,bins=\"rice\",label=\"Daily close price\")plt.legend()plt.show()" }, { "code": null, "e": 2658, "s": 2501, "text": "As you can see, it’s quite centered around zero and it seems symmetric. However, we can see that this histogram has tails that don’t seem to be neglectable." }, { "code": null, "e": 2734, "s": 2658, "text": "Let’s make a boxplot to better understand the distribution of this dataset." }, { "code": null, "e": 2794, "s": 2734, "text": "plt.boxplot(returns,labels=[\"Daily close price\"])plt.show()" }, { "code": null, "e": 3025, "s": 2794, "text": "As you can see, it’s full of outliers. The interquartile range (i.e. the height of the box) is quite narrow if compared with the distribution total range. This phenomenon is called fat tails and it’s very common in stock analysis." }, { "code": null, "e": 3074, "s": 3025, "text": "Let’s calculate some observables of our dataset." }, { "code": null, "e": 3093, "s": 3074, "text": "The mean value is:" }, { "code": null, "e": 3207, "s": 3093, "text": "It’s quite similar to zero, but the fact that it’s positive explains the positive drift of the price time series." }, { "code": null, "e": 3256, "s": 3207, "text": "Let’s now take a look at the standard deviation:" }, { "code": null, "e": 3520, "s": 3256, "text": "It’s more than an order of magnitude higher than the mean value. It’s clearly the effect of outliers. In stock price analysis, the standard deviation is a measure of the risk and such a high standard deviation is the reason why stocks are considered risky assets." }, { "code": null, "e": 3553, "s": 3520, "text": "Let’s take a look at the median:" }, { "code": null, "e": 3652, "s": 3553, "text": "It’s not so different from the mean value, so we might think that the distribution is symmetrical." }, { "code": null, "e": 3728, "s": 3652, "text": "Let’s check the skewness of the distribution to better assess the symmetry:" }, { "code": null, "e": 3875, "s": 3728, "text": "It’s positive, so we can assume that the distribution is not symmetrical (i.e. null skewness) and that the right tail as a not neglectable weight." }, { "code": null, "e": 3922, "s": 3875, "text": "If we perform a test on the skewness, we find:" }, { "code": null, "e": 4052, "s": 3922, "text": "The very low p-value suggests that the skewness of the distribution can’t be neglected, so we can’t assume that it’s symmetrical." }, { "code": null, "e": 4163, "s": 4052, "text": "Finally, we can measure the kurtosis (scipy normalizes the kurtosis so that it is 0 for a normal distribution)" }, { "code": null, "e": 4252, "s": 4163, "text": "It’s very different from zero, so the distribution is quite different from a normal one." }, { "code": null, "e": 4292, "s": 4252, "text": "A kurtosis test gives us these results:" }, { "code": null, "e": 4424, "s": 4292, "text": "Again, a very small p-value lets us reject the null hypothesis that the kurtosis is the same as a normal distribution (which is 0)." }, { "code": null, "e": 4617, "s": 4424, "text": "Although the statistically significant high values of kurtosis and skewness already tell us that the returns aren’t normally distributed, a Q-Q plot will give us graphically clear information." }, { "code": null, "e": 4919, "s": 4617, "text": "t = np.linspace(0.01,0.99,1000)q1 = np.quantile(returns,t)q2 = norm.ppf(t,loc=np.mean(returns),scale=np.std(returns))plt.plot(q1,q2)plt.plot([min(q1),max(q1)],[min(q2),max(q2)])plt.xlim((min(q1),max(q1)))plt.ylim((min(q2),max(q2)))plt.xlabel(\"Daily returns\")plt.ylabel(\"Normal distribution\")plt.show()" }, { "code": null, "e": 5182, "s": 4919, "text": "The straight line is what we expect for a normal distribution, while the blue line is what we get from our data. It’s clear that the quantiles of our dataset aren’t comparable with the quantiles of a normal distribution with the same mean and standard deviation." }, { "code": null, "e": 5344, "s": 5182, "text": "So, returns aren’t normally distributed and this makes models like Geometric Brownian Motion (which assumes normal returns) only an approximation of the reality." }, { "code": null, "e": 5466, "s": 5344, "text": "Once we have ensured the non-normality of the returns probability distribution, let’s take a look at the raw time series." }, { "code": null, "e": 5539, "s": 5466, "text": "plt.plot(returns)plt.xlabel(\"Time\")plt.ylabel(\"Daily returns\")plt.show()" }, { "code": null, "e": 5833, "s": 5539, "text": "It’s clear that there are time periods with high volatility and other periods with low volatility. This phenomenon is called volatility clustering and it’s very common in the stock market. Practically speaking, the standard deviation changes during time, making the time series non-stationary." }, { "code": null, "e": 5917, "s": 5833, "text": "A closer look at the 20-days rolling standard deviation will make everything clear." }, { "code": null, "e": 6029, "s": 5917, "text": "plt.plot(returns.rolling(20).std())plt.xlabel(\"Time\")plt.ylabel(\"20-days rolling standard deviation\")plt.show()" }, { "code": null, "e": 6223, "s": 6029, "text": "It’s clear that it’s not a constant value, but it has spikes and oscillations. The fat tails of the distribution may be caused by these volatility spikes, which create non-neglectable outliers." }, { "code": null, "e": 6456, "s": 6223, "text": "Finally, we can plot the partial autocorrelation function, which gives us some ideas about the autocorrelation of the time series and the possibility that this autocorrelation can be used for prediction purposes in some ARIMA model." }, { "code": null, "e": 6483, "s": 6456, "text": "plot_pacf(returns,lags=20)" }, { "code": null, "e": 6661, "s": 6483, "text": "It’s clear from this plot that there’s no high correlation among all lags. There are some lags between 5 and 10 that show some correlation, but it’s quite small compared with 1." }, { "code": null, "e": 6742, "s": 6661, "text": "So we can easily understand that using some ARIMA models would be quite useless." }, { "code": null, "e": 7093, "s": 6742, "text": "In this article, I’ve shown a simple statistical analysis of Google stock price. The returns aren’t normally distributed, since they are skewed and have fat tails. The time series is not stationary because the standard deviation changes over time. The autocorrelation of returns time series is very low at almost any lag, making ARIMA models useless." } ]
Query MongoDB with “like” implementation on name and email field beginning with a specific letter?
For “like” implementation in MongoDB, use / / and set that specific letter in between. For example − /J/ Let us create a collection with documents − > db.demo554.insertOne({"UserName":"John","UserMailId":"[email protected]"});{ "acknowledged" : true, "insertedId" : ObjectId("5e8f1cfed1d72c4545cb8679") } > db.demo554.insertOne({"UserName":"Chris","UserMailId":"[email protected]"});{ "acknowledged" : true, "insertedId" : ObjectId("5e8f1d0cd1d72c4545cb867a") } > db.demo554.insertOne({"UserName":"Jace","UserMailId":"[email protected]"});{ "acknowledged" : true, "insertedId" : ObjectId("5e8f1d1cd1d72c4545cb867b") } Display all documents from a collection with the help of find() method − > db.demo554.find(); This will produce the following output − { "_id" : ObjectId("5e8f1cfed1d72c4545cb8679"), "UserName" : "John", "UserMailId" : "[email protected]" } { "_id" : ObjectId("5e8f1d0cd1d72c4545cb867a"), "UserName" : "Chris", "UserMailId" : "[email protected]" } { "_id" : ObjectId("5e8f1d1cd1d72c4545cb867b"), "UserName" : "Jace", "UserMailId" : "[email protected]" } Following is the query to implementation of “like” − > db.demo554.find({ ... "$or": [ ... { "UserName": /J/ }, ... ... { "UserMailId": /J/ } ... ] ... } ... ); This will produce the following output − { "_id" : ObjectId("5e8f1cfed1d72c4545cb8679"), "UserName" : "John", "UserMailId" : "[email protected]" } { "_id" : ObjectId("5e8f1d1cd1d72c4545cb867b"), "UserName" : "Jace", "UserMailId" : "[email protected]" }
[ { "code": null, "e": 1163, "s": 1062, "text": "For “like” implementation in MongoDB, use / / and set that specific letter in between. For example −" }, { "code": null, "e": 1167, "s": 1163, "text": "/J/" }, { "code": null, "e": 1211, "s": 1167, "text": "Let us create a collection with documents −" }, { "code": null, "e": 1681, "s": 1211, "text": "> db.demo554.insertOne({\"UserName\":\"John\",\"UserMailId\":\"[email protected]\"});{\n \"acknowledged\" : true, \"insertedId\" : ObjectId(\"5e8f1cfed1d72c4545cb8679\")\n}\n> db.demo554.insertOne({\"UserName\":\"Chris\",\"UserMailId\":\"[email protected]\"});{\n \"acknowledged\" : true, \"insertedId\" : ObjectId(\"5e8f1d0cd1d72c4545cb867a\")\n}\n> db.demo554.insertOne({\"UserName\":\"Jace\",\"UserMailId\":\"[email protected]\"});{\n \"acknowledged\" : true, \"insertedId\" : ObjectId(\"5e8f1d1cd1d72c4545cb867b\")\n}" }, { "code": null, "e": 1754, "s": 1681, "text": "Display all documents from a collection with the help of find() method −" }, { "code": null, "e": 1775, "s": 1754, "text": "> db.demo554.find();" }, { "code": null, "e": 1816, "s": 1775, "text": "This will produce the following output −" }, { "code": null, "e": 2127, "s": 1816, "text": "{ \"_id\" : ObjectId(\"5e8f1cfed1d72c4545cb8679\"), \"UserName\" : \"John\", \"UserMailId\" : \"[email protected]\" }\n{ \"_id\" : ObjectId(\"5e8f1d0cd1d72c4545cb867a\"), \"UserName\" : \"Chris\", \"UserMailId\" : \"[email protected]\" }\n{ \"_id\" : ObjectId(\"5e8f1d1cd1d72c4545cb867b\"), \"UserName\" : \"Jace\", \"UserMailId\" : \"[email protected]\" }" }, { "code": null, "e": 2180, "s": 2127, "text": "Following is the query to implementation of “like” −" }, { "code": null, "e": 2305, "s": 2180, "text": "> db.demo554.find({\n... \"$or\": [\n... { \"UserName\": /J/ },\n...\n... { \"UserMailId\": /J/ }\n... ]\n... }\n... );" }, { "code": null, "e": 2346, "s": 2305, "text": "This will produce the following output −" }, { "code": null, "e": 2552, "s": 2346, "text": "{ \"_id\" : ObjectId(\"5e8f1cfed1d72c4545cb8679\"), \"UserName\" : \"John\", \"UserMailId\" : \"[email protected]\" }\n{ \"_id\" : ObjectId(\"5e8f1d1cd1d72c4545cb867b\"), \"UserName\" : \"Jace\", \"UserMailId\" : \"[email protected]\" }" } ]
What are Ordered dictionaries in Python?
An OrderedDict is a dictionary subclass that remembers the order in which its contents are added, supporting the usual dict methods.If a new entry overwrites an existing entry, the original insertion position is left unchanged. Deleting an entry and reinserting it will move it to the end. >>> from collections import OrderedDict >>> d = {'banana': 3, 'apple':4, 'pear': 1, 'mango': 2} >>> od=OrderedDict(d.items()) >>> od OrderedDict([('banana', 3), ('apple', 4), ('pear', 1), ('mango', 2)]) >>> od=OrderedDict(sorted(d.items())) >>> od OrderedDict([('apple', 4), ('banana', 3), ('mango', 2), ('pear', 1)]) >>> t=od.popitem() >>> t ('pear', 1) >>> od=OrderedDict(d.items()) >>> t=od.popitem() >>> t ('mango', 2)
[ { "code": null, "e": 1352, "s": 1062, "text": "An OrderedDict is a dictionary subclass that remembers the order in which its contents are added, supporting the usual dict methods.If a new entry overwrites an existing entry, the original insertion position is left unchanged. Deleting an entry and reinserting it will move it to the end." }, { "code": null, "e": 1775, "s": 1352, "text": ">>> from collections import OrderedDict\n>>> d = {'banana': 3, 'apple':4, 'pear': 1, 'mango': 2}\n>>> od=OrderedDict(d.items())\n>>> od\nOrderedDict([('banana', 3), ('apple', 4), ('pear', 1), ('mango', 2)])\n>>> od=OrderedDict(sorted(d.items()))\n>>> od\nOrderedDict([('apple', 4), ('banana', 3), ('mango', 2), ('pear', 1)])\n>>> t=od.popitem()\n>>> t\n('pear', 1)\n>>> od=OrderedDict(d.items())\n>>> t=od.popitem()\n>>> t\n('mango', 2)" } ]
How to vectorize pairwise (dis)similarity metrics | by Ben Cook | Towards Data Science
You can vectorize a whole class of pairwise (dis)similarity metrics with the same pattern in NumPy, PyTorch and TensorFlow. This is important when a step inside your data science or machine learning algorithm requires you to compute these pairwise metrics because you probably don’t want to waste compute time with expensive nested for loops. This pattern works any time you can break the pairwise calculation up into two distinct steps: expand and reduce. And it works equally well for similarity metrics like intersection over union between two boxes and dissimilarity metrics like Euclidean distance. This post explains the pattern and makes it concrete with two real-world examples. For brevity, I sometimes refer to “similarity” as a shorthand for both similarity and dissimilarity. I also sometimes use “point” to mean any item we might use in pairwise comparisons. For example, in computer vision, a box encoded as (x1, y1, x2, y2) can be treated as a point in 4-dimensional space. Why do we calculate pairwise similarity functions? There are several data science and machine learning algorithms that require pairwise similarity metrics as one of their steps. Indeed, scikit-learn has an entire module dedicated to this type of operation. Here are a few examples where you might want to compute pairwise metrics: Comparing points to centroids. In both clustering and classification, it can be useful to compare individual points to the class means for a set of points. These class mean values are called centroids and they are themselves points, which means the comparison is a pairwise operation. Creating cost matrices for bipartite assignment. In tracking-by-detection, you typically want to assign new detections to existing objects by similarity. The Hungarian algorithm can create these assignments by minimizing total cost while requiring that one object gets assigned to one detection (at most) and vice versa. The input to that algorithm is a cost matrix where each element is the dissimilarity between an object and a new detection. Examples of dissimilarity could be Euclidean distance or the inverse of Intersection over Union. Creating kernels for Gaussian process (GP) regression. The uncertainty in a Gaussian process is defined by a function that parameterizes the covariance between arbitrary pairs of points. Doing inference with a GP requires you to compute a matrix of pairwise covariance for your dataset. The most common covariance function is the squared exponential. Why is pairwise similarity a bottleneck? By “pairwise”, we mean that we have to compute similarity for each pair of points. That means the computation will be O(M*N) where M is the size of the first set of points and N is the size of the second set of points. The naive way to solve this is with a nested for-loop. Don't do this! Nested for loops are notoriously slow in Python. The beauty of NumPy (and its cousins PyTorch and TensorFlow) is that you can use vectorization to send for loops to optimized, low-level implementations. Writing fast, scientific Python code is largely about understanding the APIs of these packages. So how does it work? Typically, if you want to vectorize a pairwise similarity metric between a set of M D-dimensional points with shape (M, D) and a set of N D-dimensional points with shape (N, D), you need to perform two steps: Expand. Use an element-wise operation between two D-dimensional points with broadcasting to produce an expanded array with shape (M, N, D).Reduce. Use an aggregate operation to reduce the last dimension, creating a matrix with shape (M, N). Expand. Use an element-wise operation between two D-dimensional points with broadcasting to produce an expanded array with shape (M, N, D). Reduce. Use an aggregate operation to reduce the last dimension, creating a matrix with shape (M, N). It’s pretty simple. There are just a couple things to be aware of: When you compute pairwise similarity between a matrix of points and itself, M will be the same as N. Sometimes you will want to apply additional element-wise calculations for your similarity metric as well. This can be done anytime without messing up the result. Let’s look at a few examples where we compute pairwise similarity between sets of points and themselves to make the process more concrete. Pairwise Manhattan distance We’ll start with pairwise Manhattan distance, or L1 norm because it’s easy. Then we’ll look at a more interesting similarity function. The Manhattan distance between two points is the sum of the absolute value of the differences. Say we have two 4-dimensional NumPy vectors, x and x_prime. Computing the Manhattan distance between them is easy: import numpy as npx = np.array([1, 2, 3, 4])x_prime = np.array([2, 3, 4, 5])np.abs(x - x_prime).sum()# Expected result# 4 Now, we’ll extend Manhattan distance to a pairwise comparison. Let X be the four corners of a unit square: X = np.array([ [0, 0], [0, 1], [1, 1], [1, 0]]) The Manhattan distance between any pair of these points will be 0 (if they’re the same), 1 (if they share a side) or 2 (if they don’t share a side). A pairwise dissimilarity matrix comparing the set of points with itself will have shape (4, 4). Every point gets a row and every point gets a column. The order of the rows and columns will be the same, which means we should get 0s along the diagonal since the Manhattan distance between a point and itself is 0. Let’s compute pairwise Manhattan distance between each of these points and themselves the naive way, with a nested for-loop: manhattan = np.empty((4, 4))for i, x in enumerate(X): for j, x_prime in enumerate(X): manhattan[i, j] = np.abs(x - x_prime).sum()manhattan# Expected result# array([[0., 1., 2., 1.],# [1., 0., 1., 2.],# [2., 1., 0., 1.],# [1., 2., 1., 0.]]) Every element manhattan[i, j] is now the Manhattan distance between point X[i] and X[j]. Easy enough. Now, let’s vectorize it. The first thing we need is an expand operation that can be broadcast over pairs of points to create a (4, 4, 2) array. Subtraction works with broadcasting so this is where we should start. To expand correctly, we need to insert dimensions so that the operands have shape (4, 1, 2) and (1, 4, 2) respectively. This works because NumPy broadcasting steps backwards through the dimensions and expands axes when necessary. This will result in a distance array that is (4, 4, 2): deltas = X[:, None, :] - X[None, :, :]deltas.shape# Expected result# (4, 4, 2) Now we’ve created a 4x4 set of 2-dimensional points called deltas. The way this result works is that deltas[i, j, k] is the result of X[i, k] - X[j, k]. It would be equivalent to assigning deltas[i, j, :] = x - x_prime in the nested for loop above. At this point, we’re free to apply the element-wise absolute value operation since it doesn’t change the shape: abs_deltas = np.abs(deltas)abs_deltas.min()# Expected result# 0 We still need to perform the reduce step to create (4, 4) L1 distance matrix. We can do this by summing over the last axis: manhattan_distances = abs_deltas.sum(axis=-1)manhattan_distances# Expected result# array([[0, 1, 2, 1],# [1, 0, 1, 2],# [2, 1, 0, 1],# [1, 2, 1, 0]]) Voila! Vectorized pairwise Manhattan distance. By the way, when NumPy operations accept an axis argument, it typically means you have the option to reduce one or more dimensions. So, to go from a (4, 4, 2) array of deltas to a (4, 4) matrix with distances, we sum over the last axis by passing axis=-1 to the sum() method. The -1 is shorthand for "the last axis". Let’s simplify the above snippets to a one-liner that generates pairwise Manhattan distances between all pairs of points on the unit square: np.abs(X[:, None, :] - X[None, :, :]).sum(axis=-1)# Expected result# array([[0, 1, 2, 1],# [1, 0, 1, 2],# [2, 1, 0, 1],# [1, 2, 1, 0]]) Pairwise Intersection over Union Now that you’ve seen how to vectorize pairwise similarity metrics, let’s look at a more interesting example. Intersection over Union (IoU) is a measure of the degree to which two boxes overlap. Assume you have two boxes, each parameterized by its top left corner (x1, y1) and bottom right corner (x2, y2). IoU is the area of the intersection between the two boxes divided by the area of the union between the two boxes. Let’s use boxes generated from the popular YoloV3 model. We’ll use relative coordinates so the maximum possible value for any of the coordinates is 1.0 and the minimum is 0.0: bicycle = np.array([0.129, 0.215, 0.767, 0.778])truck = np.array([0.62 , 0.141, 0.891, 0.292])dog = np.array([0.174, 0.372, 0.408, 0.941]) The area of a box (x1, y1, x2, y2) is (x2 - x1) * (y2 - y1). So if you have two boxes a and b, you can compute IoU by creating an intersection box (when it exists) and then calculating the area of the intersection, and the area of each of the individual boxes. Once you have that, IoU is intersection / (a_area + b_area - intersection). The result will be 0 if the boxes don't overlap (because the intersection box doesn't exist) and 1 when the boxes have perfect overlap. Here’s the code to calculate IoU for the bicycle-dog pair and the dog-truck pair: def iou(a, b): """ Intersection over Union for two boxes a, b parameterized as x1, y1, x2, y2. """ # Define the inner box x1 = max(a[0], b[0]) y1 = max(a[1], b[1]) x2 = min(a[2], b[2]) y2 = min(a[3], b[3]) # Area of a, b separately a_area = (a[2] - a[0]) * (a[3] - a[1]) b_area = (b[2] - b[0]) * (b[3] - b[1]) total_area = a_area + b_area # Area of inner box intersection = max(0, x2 - x1) * max(y2 - y1, 0) # Area of union union = total_area - intersection return intersection / unioniou(bicycle, dog), iou(dog, truck)# Expected result# (0.2391024221313951, 0.0) In order to vectorize IoU, we need to vectorize the intersection and total area separately. Then we can calculate IoU as an element-wise operation between the two mat First, stack the three boxes to create a (3, 4) matrix: X = np.stack([ dog, bicycle, truck])X.shape# Expected result# (3, 4) The np.stack() operation puts multiple NumPy arrays together by adding a new dimension. By default, it adds a dimension at the beginning. Next, compute the coordinates of the intersection boxes for all pairs of boxes: x1 = np.maximum(X[:, None, 0], X[None, :, 0])y1 = np.maximum(X[:, None, 1], X[None, :, 1])x2 = np.minimum(X[:, None, 2], X[None, :, 2])y2 = np.minimum(X[:, None, 3], X[None, :, 3])inner_box = np.stack([x1, y1, x2, y2], -1)inner_box.shape# Expected result# (3, 3, 4) This is the expand step for intersection. We can’t do it in a single step because the inner box is the maximum between corresponding coordinates and the minimum between others. But we stack the result to make it clear that this step indeed expands the result to a (3, 3, 4) array. Each element inner_box[i, j, k] is the kth coordinate of the intersection between box i and box j. Now, calculate the area of the inner box: intersection = ( np.maximum(inner_box[..., 2] - inner_box[..., 0], 0) * np.maximum(inner_box[..., 3] - inner_box[..., 1], 0))intersection.shape# Expected result# (3, 3) The area operation reduces the last dimension. We’re doing that reduction manually by selecting indices, but we are still reducing that dimension, just like we did with sum(axis=-1) above. We need to do another pairwise operation to get total area between pairs of boxes, but this one is a little different. For total area, the “points” are no longer boxes, they are areas. That is, instead of doing a pairwise calculation between two (3, 4) sets of boxes, we will do a pairwise operation between two sets of areas. Although we're stretching the term "point", the pattern is the same as the previous examples. First, we compute the area of each individual box to create our area vectors, then we compute total area with an expand step: a_area = (X[:, 2] - X[:, 0]) * (X[:, 3] - X[:, 1])b_area = (X[:, 2] - X[:, 0]) * (X[:, 3] - X[:, 1])total_area = a_area[:, None] + b_area[None, :]total_area.shape# Expected result# (3, 3) Think of total_area as having shape (3, 3, 1) where each element total_area[i, j, 0] contains the sum of the areas between a pair of boxes. NumPy squeezes the last dimension automatically, so the actual result is (3, 3) and we don't need to explicitly perform the reduce step. The rest of the IoU calculation is element-wise between the intersection and total_area matrices. This is analogous to the single box case above: union = total_area - intersectionintersection / union# Expected result# array([[1. , 0.23910242, 0. ],# [0.23910242, 1. , 0.02911295],# [0. , 0.02911295, 1. ]]) Notice, the diagonal elements are all 1 (perfect IoU) and the non-overlapping elements are all 0. Conclusion That’s it! In this post, we talked about what pairwise similarity is and some use cases where it’s important. We also talked about why it can be such a bottleneck for your machine learning algorithms. Then, we saw a general approach to vectorizing these pairwise similarity computations: 1) expand and 2) reduce. If you can break the pairwise calculation up into these two steps then you can vectorize it. And you’re free to add any additional element-wise operations you might need. All the examples in this post used NumPy, but don’t forget that you can use this trick in PyTorch and TensorFlow as well.
[ { "code": null, "e": 515, "s": 172, "text": "You can vectorize a whole class of pairwise (dis)similarity metrics with the same pattern in NumPy, PyTorch and TensorFlow. This is important when a step inside your data science or machine learning algorithm requires you to compute these pairwise metrics because you probably don’t want to waste compute time with expensive nested for loops." }, { "code": null, "e": 859, "s": 515, "text": "This pattern works any time you can break the pairwise calculation up into two distinct steps: expand and reduce. And it works equally well for similarity metrics like intersection over union between two boxes and dissimilarity metrics like Euclidean distance. This post explains the pattern and makes it concrete with two real-world examples." }, { "code": null, "e": 1161, "s": 859, "text": "For brevity, I sometimes refer to “similarity” as a shorthand for both similarity and dissimilarity. I also sometimes use “point” to mean any item we might use in pairwise comparisons. For example, in computer vision, a box encoded as (x1, y1, x2, y2) can be treated as a point in 4-dimensional space." }, { "code": null, "e": 1212, "s": 1161, "text": "Why do we calculate pairwise similarity functions?" }, { "code": null, "e": 1418, "s": 1212, "text": "There are several data science and machine learning algorithms that require pairwise similarity metrics as one of their steps. Indeed, scikit-learn has an entire module dedicated to this type of operation." }, { "code": null, "e": 1492, "s": 1418, "text": "Here are a few examples where you might want to compute pairwise metrics:" }, { "code": null, "e": 1777, "s": 1492, "text": "Comparing points to centroids. In both clustering and classification, it can be useful to compare individual points to the class means for a set of points. These class mean values are called centroids and they are themselves points, which means the comparison is a pairwise operation." }, { "code": null, "e": 2319, "s": 1777, "text": "Creating cost matrices for bipartite assignment. In tracking-by-detection, you typically want to assign new detections to existing objects by similarity. The Hungarian algorithm can create these assignments by minimizing total cost while requiring that one object gets assigned to one detection (at most) and vice versa. The input to that algorithm is a cost matrix where each element is the dissimilarity between an object and a new detection. Examples of dissimilarity could be Euclidean distance or the inverse of Intersection over Union." }, { "code": null, "e": 2670, "s": 2319, "text": "Creating kernels for Gaussian process (GP) regression. The uncertainty in a Gaussian process is defined by a function that parameterizes the covariance between arbitrary pairs of points. Doing inference with a GP requires you to compute a matrix of pairwise covariance for your dataset. The most common covariance function is the squared exponential." }, { "code": null, "e": 2711, "s": 2670, "text": "Why is pairwise similarity a bottleneck?" }, { "code": null, "e": 3049, "s": 2711, "text": "By “pairwise”, we mean that we have to compute similarity for each pair of points. That means the computation will be O(M*N) where M is the size of the first set of points and N is the size of the second set of points. The naive way to solve this is with a nested for-loop. Don't do this! Nested for loops are notoriously slow in Python." }, { "code": null, "e": 3299, "s": 3049, "text": "The beauty of NumPy (and its cousins PyTorch and TensorFlow) is that you can use vectorization to send for loops to optimized, low-level implementations. Writing fast, scientific Python code is largely about understanding the APIs of these packages." }, { "code": null, "e": 3320, "s": 3299, "text": "So how does it work?" }, { "code": null, "e": 3529, "s": 3320, "text": "Typically, if you want to vectorize a pairwise similarity metric between a set of M D-dimensional points with shape (M, D) and a set of N D-dimensional points with shape (N, D), you need to perform two steps:" }, { "code": null, "e": 3770, "s": 3529, "text": "Expand. Use an element-wise operation between two D-dimensional points with broadcasting to produce an expanded array with shape (M, N, D).Reduce. Use an aggregate operation to reduce the last dimension, creating a matrix with shape (M, N)." }, { "code": null, "e": 3910, "s": 3770, "text": "Expand. Use an element-wise operation between two D-dimensional points with broadcasting to produce an expanded array with shape (M, N, D)." }, { "code": null, "e": 4012, "s": 3910, "text": "Reduce. Use an aggregate operation to reduce the last dimension, creating a matrix with shape (M, N)." }, { "code": null, "e": 4079, "s": 4012, "text": "It’s pretty simple. There are just a couple things to be aware of:" }, { "code": null, "e": 4180, "s": 4079, "text": "When you compute pairwise similarity between a matrix of points and itself, M will be the same as N." }, { "code": null, "e": 4342, "s": 4180, "text": "Sometimes you will want to apply additional element-wise calculations for your similarity metric as well. This can be done anytime without messing up the result." }, { "code": null, "e": 4481, "s": 4342, "text": "Let’s look at a few examples where we compute pairwise similarity between sets of points and themselves to make the process more concrete." }, { "code": null, "e": 4509, "s": 4481, "text": "Pairwise Manhattan distance" }, { "code": null, "e": 4644, "s": 4509, "text": "We’ll start with pairwise Manhattan distance, or L1 norm because it’s easy. Then we’ll look at a more interesting similarity function." }, { "code": null, "e": 4854, "s": 4644, "text": "The Manhattan distance between two points is the sum of the absolute value of the differences. Say we have two 4-dimensional NumPy vectors, x and x_prime. Computing the Manhattan distance between them is easy:" }, { "code": null, "e": 4976, "s": 4854, "text": "import numpy as npx = np.array([1, 2, 3, 4])x_prime = np.array([2, 3, 4, 5])np.abs(x - x_prime).sum()# Expected result# 4" }, { "code": null, "e": 5083, "s": 4976, "text": "Now, we’ll extend Manhattan distance to a pairwise comparison. Let X be the four corners of a unit square:" }, { "code": null, "e": 5143, "s": 5083, "text": "X = np.array([ [0, 0], [0, 1], [1, 1], [1, 0]])" }, { "code": null, "e": 5604, "s": 5143, "text": "The Manhattan distance between any pair of these points will be 0 (if they’re the same), 1 (if they share a side) or 2 (if they don’t share a side). A pairwise dissimilarity matrix comparing the set of points with itself will have shape (4, 4). Every point gets a row and every point gets a column. The order of the rows and columns will be the same, which means we should get 0s along the diagonal since the Manhattan distance between a point and itself is 0." }, { "code": null, "e": 5729, "s": 5604, "text": "Let’s compute pairwise Manhattan distance between each of these points and themselves the naive way, with a nested for-loop:" }, { "code": null, "e": 6000, "s": 5729, "text": "manhattan = np.empty((4, 4))for i, x in enumerate(X): for j, x_prime in enumerate(X): manhattan[i, j] = np.abs(x - x_prime).sum()manhattan# Expected result# array([[0., 1., 2., 1.],# [1., 0., 1., 2.],# [2., 1., 0., 1.],# [1., 2., 1., 0.]])" }, { "code": null, "e": 6102, "s": 6000, "text": "Every element manhattan[i, j] is now the Manhattan distance between point X[i] and X[j]. Easy enough." }, { "code": null, "e": 6316, "s": 6102, "text": "Now, let’s vectorize it. The first thing we need is an expand operation that can be broadcast over pairs of points to create a (4, 4, 2) array. Subtraction works with broadcasting so this is where we should start." }, { "code": null, "e": 6602, "s": 6316, "text": "To expand correctly, we need to insert dimensions so that the operands have shape (4, 1, 2) and (1, 4, 2) respectively. This works because NumPy broadcasting steps backwards through the dimensions and expands axes when necessary. This will result in a distance array that is (4, 4, 2):" }, { "code": null, "e": 6681, "s": 6602, "text": "deltas = X[:, None, :] - X[None, :, :]deltas.shape# Expected result# (4, 4, 2)" }, { "code": null, "e": 6930, "s": 6681, "text": "Now we’ve created a 4x4 set of 2-dimensional points called deltas. The way this result works is that deltas[i, j, k] is the result of X[i, k] - X[j, k]. It would be equivalent to assigning deltas[i, j, :] = x - x_prime in the nested for loop above." }, { "code": null, "e": 7042, "s": 6930, "text": "At this point, we’re free to apply the element-wise absolute value operation since it doesn’t change the shape:" }, { "code": null, "e": 7106, "s": 7042, "text": "abs_deltas = np.abs(deltas)abs_deltas.min()# Expected result# 0" }, { "code": null, "e": 7230, "s": 7106, "text": "We still need to perform the reduce step to create (4, 4) L1 distance matrix. We can do this by summing over the last axis:" }, { "code": null, "e": 7401, "s": 7230, "text": "manhattan_distances = abs_deltas.sum(axis=-1)manhattan_distances# Expected result# array([[0, 1, 2, 1],# [1, 0, 1, 2],# [2, 1, 0, 1],# [1, 2, 1, 0]])" }, { "code": null, "e": 7448, "s": 7401, "text": "Voila! Vectorized pairwise Manhattan distance." }, { "code": null, "e": 7765, "s": 7448, "text": "By the way, when NumPy operations accept an axis argument, it typically means you have the option to reduce one or more dimensions. So, to go from a (4, 4, 2) array of deltas to a (4, 4) matrix with distances, we sum over the last axis by passing axis=-1 to the sum() method. The -1 is shorthand for \"the last axis\"." }, { "code": null, "e": 7906, "s": 7765, "text": "Let’s simplify the above snippets to a one-liner that generates pairwise Manhattan distances between all pairs of points on the unit square:" }, { "code": null, "e": 8063, "s": 7906, "text": "np.abs(X[:, None, :] - X[None, :, :]).sum(axis=-1)# Expected result# array([[0, 1, 2, 1],# [1, 0, 1, 2],# [2, 1, 0, 1],# [1, 2, 1, 0]])" }, { "code": null, "e": 8096, "s": 8063, "text": "Pairwise Intersection over Union" }, { "code": null, "e": 8516, "s": 8096, "text": "Now that you’ve seen how to vectorize pairwise similarity metrics, let’s look at a more interesting example. Intersection over Union (IoU) is a measure of the degree to which two boxes overlap. Assume you have two boxes, each parameterized by its top left corner (x1, y1) and bottom right corner (x2, y2). IoU is the area of the intersection between the two boxes divided by the area of the union between the two boxes." }, { "code": null, "e": 8692, "s": 8516, "text": "Let’s use boxes generated from the popular YoloV3 model. We’ll use relative coordinates so the maximum possible value for any of the coordinates is 1.0 and the minimum is 0.0:" }, { "code": null, "e": 8831, "s": 8692, "text": "bicycle = np.array([0.129, 0.215, 0.767, 0.778])truck = np.array([0.62 , 0.141, 0.891, 0.292])dog = np.array([0.174, 0.372, 0.408, 0.941])" }, { "code": null, "e": 9304, "s": 8831, "text": "The area of a box (x1, y1, x2, y2) is (x2 - x1) * (y2 - y1). So if you have two boxes a and b, you can compute IoU by creating an intersection box (when it exists) and then calculating the area of the intersection, and the area of each of the individual boxes. Once you have that, IoU is intersection / (a_area + b_area - intersection). The result will be 0 if the boxes don't overlap (because the intersection box doesn't exist) and 1 when the boxes have perfect overlap." }, { "code": null, "e": 9386, "s": 9304, "text": "Here’s the code to calculate IoU for the bicycle-dog pair and the dog-truck pair:" }, { "code": null, "e": 10004, "s": 9386, "text": "def iou(a, b): \"\"\" Intersection over Union for two boxes a, b parameterized as x1, y1, x2, y2. \"\"\" # Define the inner box x1 = max(a[0], b[0]) y1 = max(a[1], b[1]) x2 = min(a[2], b[2]) y2 = min(a[3], b[3]) # Area of a, b separately a_area = (a[2] - a[0]) * (a[3] - a[1]) b_area = (b[2] - b[0]) * (b[3] - b[1]) total_area = a_area + b_area # Area of inner box intersection = max(0, x2 - x1) * max(y2 - y1, 0) # Area of union union = total_area - intersection return intersection / unioniou(bicycle, dog), iou(dog, truck)# Expected result# (0.2391024221313951, 0.0)" }, { "code": null, "e": 10171, "s": 10004, "text": "In order to vectorize IoU, we need to vectorize the intersection and total area separately. Then we can calculate IoU as an element-wise operation between the two mat" }, { "code": null, "e": 10227, "s": 10171, "text": "First, stack the three boxes to create a (3, 4) matrix:" }, { "code": null, "e": 10305, "s": 10227, "text": "X = np.stack([ dog, bicycle, truck])X.shape# Expected result# (3, 4)" }, { "code": null, "e": 10443, "s": 10305, "text": "The np.stack() operation puts multiple NumPy arrays together by adding a new dimension. By default, it adds a dimension at the beginning." }, { "code": null, "e": 10523, "s": 10443, "text": "Next, compute the coordinates of the intersection boxes for all pairs of boxes:" }, { "code": null, "e": 10789, "s": 10523, "text": "x1 = np.maximum(X[:, None, 0], X[None, :, 0])y1 = np.maximum(X[:, None, 1], X[None, :, 1])x2 = np.minimum(X[:, None, 2], X[None, :, 2])y2 = np.minimum(X[:, None, 3], X[None, :, 3])inner_box = np.stack([x1, y1, x2, y2], -1)inner_box.shape# Expected result# (3, 3, 4)" }, { "code": null, "e": 11169, "s": 10789, "text": "This is the expand step for intersection. We can’t do it in a single step because the inner box is the maximum between corresponding coordinates and the minimum between others. But we stack the result to make it clear that this step indeed expands the result to a (3, 3, 4) array. Each element inner_box[i, j, k] is the kth coordinate of the intersection between box i and box j." }, { "code": null, "e": 11211, "s": 11169, "text": "Now, calculate the area of the inner box:" }, { "code": null, "e": 11386, "s": 11211, "text": "intersection = ( np.maximum(inner_box[..., 2] - inner_box[..., 0], 0) * np.maximum(inner_box[..., 3] - inner_box[..., 1], 0))intersection.shape# Expected result# (3, 3)" }, { "code": null, "e": 11575, "s": 11386, "text": "The area operation reduces the last dimension. We’re doing that reduction manually by selecting indices, but we are still reducing that dimension, just like we did with sum(axis=-1) above." }, { "code": null, "e": 11996, "s": 11575, "text": "We need to do another pairwise operation to get total area between pairs of boxes, but this one is a little different. For total area, the “points” are no longer boxes, they are areas. That is, instead of doing a pairwise calculation between two (3, 4) sets of boxes, we will do a pairwise operation between two sets of areas. Although we're stretching the term \"point\", the pattern is the same as the previous examples." }, { "code": null, "e": 12122, "s": 11996, "text": "First, we compute the area of each individual box to create our area vectors, then we compute total area with an expand step:" }, { "code": null, "e": 12310, "s": 12122, "text": "a_area = (X[:, 2] - X[:, 0]) * (X[:, 3] - X[:, 1])b_area = (X[:, 2] - X[:, 0]) * (X[:, 3] - X[:, 1])total_area = a_area[:, None] + b_area[None, :]total_area.shape# Expected result# (3, 3)" }, { "code": null, "e": 12587, "s": 12310, "text": "Think of total_area as having shape (3, 3, 1) where each element total_area[i, j, 0] contains the sum of the areas between a pair of boxes. NumPy squeezes the last dimension automatically, so the actual result is (3, 3) and we don't need to explicitly perform the reduce step." }, { "code": null, "e": 12733, "s": 12587, "text": "The rest of the IoU calculation is element-wise between the intersection and total_area matrices. This is analogous to the single box case above:" }, { "code": null, "e": 12943, "s": 12733, "text": "union = total_area - intersectionintersection / union# Expected result# array([[1. , 0.23910242, 0. ],# [0.23910242, 1. , 0.02911295],# [0. , 0.02911295, 1. ]])" }, { "code": null, "e": 13041, "s": 12943, "text": "Notice, the diagonal elements are all 1 (perfect IoU) and the non-overlapping elements are all 0." }, { "code": null, "e": 13052, "s": 13041, "text": "Conclusion" } ]
Find the Number Occurring Odd Number of Times using Lambda expression and reduce function in Python
In this article we are required to find that number from the list which occurs odd number of times in the given list. We are also required to use the Lambda function and the reduce function. We design a function where the reduce function is used by applying the Lambda function to check if the element is present odd number of times. Live Demo from functools import reduce def oddcount(i): print(reduce(lambda x, y: x ^ y, i)) listA = [12,34,12,12,34] print("Given list:\n",listA) print("The element present odd number of times:") oddcount(listA) Running the above code gives us the following result − Given list: [12, 34, 12, 12, 34] The element present odd number of times: 12
[ { "code": null, "e": 1253, "s": 1062, "text": "In this article we are required to find that number from the list which occurs odd number of times in the given list. We are also required to use the Lambda function and the reduce function." }, { "code": null, "e": 1396, "s": 1253, "text": "We design a function where the reduce function is used by applying the Lambda function to check if the element is present odd number of times." }, { "code": null, "e": 1407, "s": 1396, "text": " Live Demo" }, { "code": null, "e": 1613, "s": 1407, "text": "from functools import reduce\ndef oddcount(i):\n print(reduce(lambda x, y: x ^ y, i))\nlistA = [12,34,12,12,34]\nprint(\"Given list:\\n\",listA)\nprint(\"The element present odd number of times:\")\noddcount(listA)" }, { "code": null, "e": 1668, "s": 1613, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 1745, "s": 1668, "text": "Given list:\n[12, 34, 12, 12, 34]\nThe element present odd number of times:\n12" } ]
Bulma Text Color - GeeksforGeeks
01 Dec, 2021 Bulma is a free and open-source CSS framework based on Flexbox. It is component-rich, compatible, and well documented. It is highly responsive in nature. It uses classes to implement its design. Text class accepts lots of value in Bulma which all the properties are covered in class form. By using this class we can color any text. In CSS, we do that by using the CSS Color property. Syntax: <tag class="has-text-*"> Text </tag> Text Color classes We can use any of these colors listed below at the place of * in the above syntax: has-text-white: This class used to set the test color white. has-text-black: This class used to set the test color black. has-text-light: This class used to set the test color cream. has-text-dark: This class used to set the test color dark brown. has-text-primary: This class used to set the test color light cyan. has-text-link: This class used to set the test color blue. has-text-info: This class used to set the test color light blue. has-text-success: This class used to set the test color green. has-text-warning: This class used to set the test color yellow. has-text-danger: This class used to set the test color red. Note: You can set any element to one of the 10 colors or 9 shades of grey. You can use each color in its light and dark versions. Simply append *-light or *-dark. Below example illustrate the text color in Bulma: Example: HTML <!DOCTYPE html><html> <head> <title>Bulma Panel</title> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css'></head> <body> <h1 class="is-size-2"> GeeksforGeeks </h1> <b>Bulma Text Color Class</b> <br> <div> <p class="has-text-white has-background-black"> A Computer Science Portal for Geeks </p> <p class="has-text-black has-background-white"> A Computer Science Portal for Geeks </p> <p class="has-text-light has-background-dark"> A Computer Science Portal for Geeks </p> <p class="has-text-dark has-background-light"> A Computer Science Portal for Geeks </p> <p class="has-text-primary has-background-link"> A Computer Science Portal for Geeks </p> <p class="has-text-link has-background-primary"> A Computer Science Portal for Geeks </p> <p class="has-text-info has-background-success"> A Computer Science Portal for Geeks </p> <p class="has-text-success has-background-info"> A Computer Science Portal for Geeks </p> <p class="has-text-warning has-background-danger"> A Computer Science Portal for Geeks </p> <p class="has-text-danger has-background-warning"> A Computer Science Portal for Geeks </p> </div></body> </html> Output: Reference:https://bulma.io/documentation/helpers/color-helpers/#text-color Bulma CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Design a web page using HTML and CSS Form validation using jQuery How to set space between the flexbox ? Search Bar using HTML, CSS and JavaScript How to Create Time-Table schedule using HTML ? Roadmap to Become a Web Developer in 2022 How to fetch data from an API in ReactJS ? Installation of Node.js on Linux Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 25376, "s": 25348, "text": "\n01 Dec, 2021" }, { "code": null, "e": 25760, "s": 25376, "text": "Bulma is a free and open-source CSS framework based on Flexbox. It is component-rich, compatible, and well documented. It is highly responsive in nature. It uses classes to implement its design. Text class accepts lots of value in Bulma which all the properties are covered in class form. By using this class we can color any text. In CSS, we do that by using the CSS Color property." }, { "code": null, "e": 25768, "s": 25760, "text": "Syntax:" }, { "code": null, "e": 25809, "s": 25768, "text": "<tag class=\"has-text-*\">\n Text\n</tag>" }, { "code": null, "e": 25828, "s": 25809, "text": "Text Color classes" }, { "code": null, "e": 25912, "s": 25828, "text": "We can use any of these colors listed below at the place of * in the above syntax: " }, { "code": null, "e": 25973, "s": 25912, "text": "has-text-white: This class used to set the test color white." }, { "code": null, "e": 26034, "s": 25973, "text": "has-text-black: This class used to set the test color black." }, { "code": null, "e": 26095, "s": 26034, "text": "has-text-light: This class used to set the test color cream." }, { "code": null, "e": 26160, "s": 26095, "text": "has-text-dark: This class used to set the test color dark brown." }, { "code": null, "e": 26228, "s": 26160, "text": "has-text-primary: This class used to set the test color light cyan." }, { "code": null, "e": 26287, "s": 26228, "text": "has-text-link: This class used to set the test color blue." }, { "code": null, "e": 26352, "s": 26287, "text": "has-text-info: This class used to set the test color light blue." }, { "code": null, "e": 26415, "s": 26352, "text": "has-text-success: This class used to set the test color green." }, { "code": null, "e": 26479, "s": 26415, "text": "has-text-warning: This class used to set the test color yellow." }, { "code": null, "e": 26539, "s": 26479, "text": "has-text-danger: This class used to set the test color red." }, { "code": null, "e": 26752, "s": 26539, "text": "Note: You can set any element to one of the 10 colors or 9 shades of grey. You can use each color in its light and dark versions. Simply append *-light or *-dark. Below example illustrate the text color in Bulma:" }, { "code": null, "e": 26761, "s": 26752, "text": "Example:" }, { "code": null, "e": 26766, "s": 26761, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>Bulma Panel</title> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css'></head> <body> <h1 class=\"is-size-2\"> GeeksforGeeks </h1> <b>Bulma Text Color Class</b> <br> <div> <p class=\"has-text-white has-background-black\"> A Computer Science Portal for Geeks </p> <p class=\"has-text-black has-background-white\"> A Computer Science Portal for Geeks </p> <p class=\"has-text-light has-background-dark\"> A Computer Science Portal for Geeks </p> <p class=\"has-text-dark has-background-light\"> A Computer Science Portal for Geeks </p> <p class=\"has-text-primary has-background-link\"> A Computer Science Portal for Geeks </p> <p class=\"has-text-link has-background-primary\"> A Computer Science Portal for Geeks </p> <p class=\"has-text-info has-background-success\"> A Computer Science Portal for Geeks </p> <p class=\"has-text-success has-background-info\"> A Computer Science Portal for Geeks </p> <p class=\"has-text-warning has-background-danger\"> A Computer Science Portal for Geeks </p> <p class=\"has-text-danger has-background-warning\"> A Computer Science Portal for Geeks </p> </div></body> </html>", "e": 28238, "s": 26766, "text": null }, { "code": null, "e": 28246, "s": 28238, "text": "Output:" }, { "code": null, "e": 28321, "s": 28246, "text": "Reference:https://bulma.io/documentation/helpers/color-helpers/#text-color" }, { "code": null, "e": 28327, "s": 28321, "text": "Bulma" }, { "code": null, "e": 28331, "s": 28327, "text": "CSS" }, { "code": null, "e": 28348, "s": 28331, "text": "Web Technologies" }, { "code": null, "e": 28446, "s": 28348, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28483, "s": 28446, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 28512, "s": 28483, "text": "Form validation using jQuery" }, { "code": null, "e": 28551, "s": 28512, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 28593, "s": 28551, "text": "Search Bar using HTML, CSS and JavaScript" }, { "code": null, "e": 28640, "s": 28593, "text": "How to Create Time-Table schedule using HTML ?" }, { "code": null, "e": 28682, "s": 28640, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 28725, "s": 28682, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 28758, "s": 28725, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28803, "s": 28758, "text": "Convert a string to an integer in JavaScript" } ]
PHP $_SERVER
$_SERVER is a superglobal that holds information regarding HTTP headers, path and script location etc. All the server and execution environment related information is available in this associative array. Most of the entries in this array are populated by web server. PHP versions prior to 5.4.0 contained $HTTP_SERVER_VARS contained same information but has now been removed. Following are some prominent members of this array PHP_SELF − stores filename of currently executing script. For example, a script in test folder of document root of a local server returns its path as follows − <?php echo $_SERVER['PHP_SELF']; ?> This results in following output in browser with http://localhost/test/testscript.php URL /test/testscript.php SERVER_ADDR − This property of array returns The IP address of the server under which the current script is executing. SERVER_NAME − Name of server hostunder which the current script is executing.In case of a erver running locally, localhost is returned QUERY_STRING − A query string is the string of key=value pairs separated by & symbol and appended to URL after ? symbol. For example, http://localhost/testscript?name=xyz&age=20 URL returns trailing query string REQUEST_METHOD − HTTP request method used for accessing a URL, such as POST, GET, POST, PUT or DELETE. In above query string example, a URL attached to query string wirh ? symbol requests the page with GET method DOCUMENT_ROOT − returns name of directory on server that is configured as document root. On XAMPP apache server it returns htdocs as name of document root C:/xampp/htdocs DOCUMENT_ROOT − This is a string denoting the user agent (browser) being which is accessing the page. Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36 REMOTE_ADDR − IP address of machine from which the user is viewing the current page. SERVER_PORT − port number on which the web server is listening to incoming request. Default is 80 Following script invoked from document root of XAMPP server lists all server variables <?php foreach ($_SERVER as $k=>$v) echo $k . "=>" . $v . "<br>"; ?> List of all server variables MIBDIRS=>C:/xampp/php/extras/mibs MYSQL_HOME=>\xampp\mysql\bin OPENSSL_CONF=>C:/xampp/apache/bin/openssl.cnf PHP_PEAR_SYSCONF_DIR=>\xampp\php PHPRC=>\xampp\php TMP=>\xampp\tmp HTTP_HOST=>localhost HTTP_CONNECTION=>keep-alive HTTP_CACHE_CONTROL=>max-age=0 HTTP_DNT=>1 HTTP_UPGRADE_INSECURE_REQUESTS=>1 HTTP_USER_AGENT=>Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.135 Safari/537.36 HTTP_ACCEPT=>text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9 HTTP_SEC_FETCH_SITE=>none HTTP_SEC_FETCH_MODE=>navigate HTTP_SEC_FETCH_USER=>?1 HTTP_SEC_FETCH_DEST=>document HTTP_ACCEPT_ENCODING=>gzip, deflate, br HTTP_ACCEPT_LANGUAGE=>en-US,en;q=0.9,mr;q=0.8 PATH=>C:\python37\Scripts\;C:\python37\;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Windows\System32\OpenSSH\;C:\Program Files (x86)\AMD\ATI.ACE\Core-Static;C:\python37\Scripts\;C:\python37\;C:\Users\User\AppData\Local\Microsoft\WindowsApps;C:\Users\User\AppData\Local\Programs\MiKTeX 2.9\miktex\bin\x64\;C:\MicrosoftVSCode\bin SystemRoot=>C:\Windows COMSPEC=>C:\Windows\system32\cmd.exe PATHEXT=>.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC;.PY;.PYW WINDIR=>C:\Windows SERVER_SIGNATURE=> Apache/2.4.41 (Win64) OpenSSL/1.0.2s PHP/7.1.32 Server at localhost Port 80 SERVER_SOFTWARE=>Apache/2.4.41 (Win64) OpenSSL/1.0.2s PHP/7.1.32 SERVER_NAME=>localhost SERVER_ADDR=>::1 SERVER_PORT=>80 REMOTE_ADDR=>::1 DOCUMENT_ROOT=>C:/xampp/htdocs REQUEST_SCHEME=>http CONTEXT_PREFIX=> CONTEXT_DOCUMENT_ROOT=>C:/xampp/htdocs SERVER_ADMIN=>postmaster@localhost SCRIPT_FILENAME=>C:/xampp/htdocs/testscript.php REMOTE_PORT=>49475 GATEWAY_INTERFACE=>CGI/1.1 SERVER_PROTOCOL=>HTTP/1.1 REQUEST_METHOD=>GET QUERY_STRING=> REQUEST_URI=>/testscript.php SCRIPT_NAME=>/testscript.php PHP_SELF=>/testscript.php REQUEST_TIME_FLOAT=>1599118525.327 REQUEST_TIME=>1599118525
[ { "code": null, "e": 1329, "s": 1062, "text": "$_SERVER is a superglobal that holds information regarding HTTP headers, path and script location etc. All the server and execution environment related information is available in this associative array. Most of the entries in this array are populated by web server." }, { "code": null, "e": 1489, "s": 1329, "text": "PHP versions prior to 5.4.0 contained $HTTP_SERVER_VARS contained same information but has now been removed. Following are some prominent members of this array" }, { "code": null, "e": 1649, "s": 1489, "text": "PHP_SELF − stores filename of currently executing script. For example, a script in test folder of document root of a local server returns its path as follows −" }, { "code": null, "e": 1685, "s": 1649, "text": "<?php\necho $_SERVER['PHP_SELF'];\n?>" }, { "code": null, "e": 1775, "s": 1685, "text": "This results in following output in browser with http://localhost/test/testscript.php URL" }, { "code": null, "e": 1796, "s": 1775, "text": "/test/testscript.php" }, { "code": null, "e": 1915, "s": 1796, "text": "SERVER_ADDR − This property of array returns The IP address of the server under which the current script is executing." }, { "code": null, "e": 2050, "s": 1915, "text": "SERVER_NAME − Name of server hostunder which the current script is executing.In case of a erver running locally, localhost is returned" }, { "code": null, "e": 2262, "s": 2050, "text": "QUERY_STRING − A query string is the string of key=value pairs separated by & symbol and appended to URL after ? symbol. For example, http://localhost/testscript?name=xyz&age=20 URL returns trailing query string" }, { "code": null, "e": 2475, "s": 2262, "text": "REQUEST_METHOD − HTTP request method used for accessing a URL, such as POST, GET, POST, PUT or DELETE. In above query string example, a URL attached to query string wirh ? symbol requests the page with GET method" }, { "code": null, "e": 2630, "s": 2475, "text": "DOCUMENT_ROOT − returns name of directory on server that is configured as document root. On XAMPP apache server it returns htdocs as name of document root" }, { "code": null, "e": 2646, "s": 2630, "text": "C:/xampp/htdocs" }, { "code": null, "e": 2748, "s": 2646, "text": "DOCUMENT_ROOT − This is a string denoting the user agent (browser) being which is accessing the page." }, { "code": null, "e": 2865, "s": 2748, "text": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36\n" }, { "code": null, "e": 2950, "s": 2865, "text": "REMOTE_ADDR − IP address of machine from which the user is viewing the current page." }, { "code": null, "e": 3048, "s": 2950, "text": "SERVER_PORT − port number on which the web server is listening to incoming request. Default is 80" }, { "code": null, "e": 3135, "s": 3048, "text": "Following script invoked from document root of XAMPP server lists all server variables" }, { "code": null, "e": 3203, "s": 3135, "text": "<?php\nforeach ($_SERVER as $k=>$v)\necho $k . \"=>\" . $v . \"<br>\";\n?>" }, { "code": null, "e": 3232, "s": 3203, "text": "List of all server variables" }, { "code": null, "e": 5214, "s": 3232, "text": "MIBDIRS=>C:/xampp/php/extras/mibs\nMYSQL_HOME=>\\xampp\\mysql\\bin\nOPENSSL_CONF=>C:/xampp/apache/bin/openssl.cnf\nPHP_PEAR_SYSCONF_DIR=>\\xampp\\php\nPHPRC=>\\xampp\\php\nTMP=>\\xampp\\tmp\nHTTP_HOST=>localhost\nHTTP_CONNECTION=>keep-alive\nHTTP_CACHE_CONTROL=>max-age=0\nHTTP_DNT=>1\nHTTP_UPGRADE_INSECURE_REQUESTS=>1\nHTTP_USER_AGENT=>Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.135 Safari/537.36\nHTTP_ACCEPT=>text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9\nHTTP_SEC_FETCH_SITE=>none\nHTTP_SEC_FETCH_MODE=>navigate\nHTTP_SEC_FETCH_USER=>?1\nHTTP_SEC_FETCH_DEST=>document\nHTTP_ACCEPT_ENCODING=>gzip, deflate, br\nHTTP_ACCEPT_LANGUAGE=>en-US,en;q=0.9,mr;q=0.8\nPATH=>C:\\python37\\Scripts\\;C:\\python37\\;C:\\Windows\\system32;C:\\Windows;C:\\Windows\\System32\\Wbem;C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\;C:\\Windows\\System32\\OpenSSH\\;C:\\Program Files (x86)\\AMD\\ATI.ACE\\Core-Static;C:\\python37\\Scripts\\;C:\\python37\\;C:\\Users\\User\\AppData\\Local\\Microsoft\\WindowsApps;C:\\Users\\User\\AppData\\Local\\Programs\\MiKTeX 2.9\\miktex\\bin\\x64\\;C:\\MicrosoftVSCode\\bin\nSystemRoot=>C:\\Windows\nCOMSPEC=>C:\\Windows\\system32\\cmd.exe\nPATHEXT=>.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC;.PY;.PYW\nWINDIR=>C:\\Windows\nSERVER_SIGNATURE=>\nApache/2.4.41 (Win64) OpenSSL/1.0.2s PHP/7.1.32 Server at localhost Port 80\n\nSERVER_SOFTWARE=>Apache/2.4.41 (Win64) OpenSSL/1.0.2s PHP/7.1.32\nSERVER_NAME=>localhost\nSERVER_ADDR=>::1\nSERVER_PORT=>80\nREMOTE_ADDR=>::1\nDOCUMENT_ROOT=>C:/xampp/htdocs\nREQUEST_SCHEME=>http\nCONTEXT_PREFIX=>\nCONTEXT_DOCUMENT_ROOT=>C:/xampp/htdocs\nSERVER_ADMIN=>postmaster@localhost\nSCRIPT_FILENAME=>C:/xampp/htdocs/testscript.php\nREMOTE_PORT=>49475\nGATEWAY_INTERFACE=>CGI/1.1\nSERVER_PROTOCOL=>HTTP/1.1\nREQUEST_METHOD=>GET\nQUERY_STRING=>\nREQUEST_URI=>/testscript.php\nSCRIPT_NAME=>/testscript.php\nPHP_SELF=>/testscript.php\nREQUEST_TIME_FLOAT=>1599118525.327\nREQUEST_TIME=>1599118525" } ]
Python dictionary with keys having multiple inputs
When it is required to create a dictionary where keys have multiple inputs, an empty dictionary can be created, and the value for a specific key can be specified. Below is the demonstration of the same − Live Demo my_dict = {} a, b, c = 15, 26, 38 my_dict[a, b, c] = a + b - c a, b, c = 5, 4, 11 my_dict[a, b, c] = a + b - c print("The dictionary is :") print(my_dict) The dictionary is : {(15, 26, 38): 3, (5, 4, 11): -2} The required packages are imported. The required packages are imported. An empty dictionary is defined. An empty dictionary is defined. The values for a specific key are specified. The values for a specific key are specified. The output is displayed on the console. The output is displayed on the console.
[ { "code": null, "e": 1225, "s": 1062, "text": "When it is required to create a dictionary where keys have multiple inputs, an empty dictionary can be created, and the value for a specific key can be specified." }, { "code": null, "e": 1266, "s": 1225, "text": "Below is the demonstration of the same −" }, { "code": null, "e": 1277, "s": 1266, "text": " Live Demo" }, { "code": null, "e": 1435, "s": 1277, "text": "my_dict = {}\n\na, b, c = 15, 26, 38\nmy_dict[a, b, c] = a + b - c\n\na, b, c = 5, 4, 11\nmy_dict[a, b, c] = a + b - c\n\nprint(\"The dictionary is :\")\nprint(my_dict)" }, { "code": null, "e": 1489, "s": 1435, "text": "The dictionary is :\n{(15, 26, 38): 3, (5, 4, 11): -2}" }, { "code": null, "e": 1525, "s": 1489, "text": "The required packages are imported." }, { "code": null, "e": 1561, "s": 1525, "text": "The required packages are imported." }, { "code": null, "e": 1593, "s": 1561, "text": "An empty dictionary is defined." }, { "code": null, "e": 1625, "s": 1593, "text": "An empty dictionary is defined." }, { "code": null, "e": 1670, "s": 1625, "text": "The values for a specific key are specified." }, { "code": null, "e": 1715, "s": 1670, "text": "The values for a specific key are specified." }, { "code": null, "e": 1755, "s": 1715, "text": "The output is displayed on the console." }, { "code": null, "e": 1795, "s": 1755, "text": "The output is displayed on the console." } ]
What is the best way to compare two strings in JavaScript?
To compare two strings in JavaScript, use the localeCompare() method. The method returns 0 if both the strings are equal, -1 if string 1 is sorted before string 2 and 1 if string 2 is sorted before string 1. You can try to run the following code to compare two strings Live Demo <!DOCTYPE html> <html> <body> <button onclick="compareStr()">Compare Strings</button> <p id="test"></p> <script> function compareStr() { var string1 = "World"; var string2 = "World"; var result = string1.localeCompare(string2); document.getElementById("test").innerHTML = result; } </script> </body> </html>
[ { "code": null, "e": 1270, "s": 1062, "text": "To compare two strings in JavaScript, use the localeCompare() method. The method returns 0 if both the strings are equal, -1 if string 1 is sorted before string 2 and 1 if string 2 is sorted before string 1." }, { "code": null, "e": 1331, "s": 1270, "text": "You can try to run the following code to compare two strings" }, { "code": null, "e": 1341, "s": 1331, "text": "Live Demo" }, { "code": null, "e": 1746, "s": 1341, "text": "<!DOCTYPE html>\n<html>\n <body>\n <button onclick=\"compareStr()\">Compare Strings</button>\n <p id=\"test\"></p>\n <script>\n function compareStr() {\n var string1 = \"World\";\n var string2 = \"World\";\n var result = string1.localeCompare(string2);\n\n document.getElementById(\"test\").innerHTML = result;\n }\n </script>\n </body>\n</html>" } ]
Getting a Matrix of number of rows in R Programming - row() Function - GeeksforGeeks
04 Jun, 2020 row() function in R Language is used to get the row number of a matrix. Syntax: row(x, as.factor=FALSE) Parameters:x: matrixas.factor: a logical value indicating whether the value should be returned as a factor of column labels (created if necessary) rather than as numbers Example 1: # R program to illustrate# row function # Initializing a matrix with# 2 rows and 2 columnsx <- matrix(c(1, 2, 3, 4), 2, 2) # Getting the matrix representationx # Calling the row() functionrow(x) Output: $Rscript main.r [, 1] [, 2] [1, ] 1 3 [2, ] 2 4 [, 1] [, 2] [1, ] 1 1 [2, ] 2 2 Example 2: # R program to illustrate# row function # Initializing a matrix with# 3 rows and 3 columnsx <- matrix(rep(1:12), 3, 3) # Getting the matrix representationx # Calling the row() functionrow(x) Output: [, 1] [, 2] [, 3] [1, ] 1 4 7 [2, ] 2 5 8 [3, ] 3 6 9 [, 1] [, 2] [, 3] [1, ] 1 1 1 [2, ] 2 2 2 [3, ] 3 3 3 R Matrix-Function R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to change Row Names of DataFrame in R ? Filter data by multiple conditions in R using Dplyr Change Color of Bars in Barchart using ggplot2 in R Loops in R (for, while, repeat) How to Change Axis Scales in R Plots? Group by function in R using Dplyr How to Split Column Into Multiple Columns in R DataFrame? K-Means Clustering in R Programming Remove rows with NA in one column of R DataFrame How to filter R DataFrame by values in a column?
[ { "code": null, "e": 24467, "s": 24439, "text": "\n04 Jun, 2020" }, { "code": null, "e": 24539, "s": 24467, "text": "row() function in R Language is used to get the row number of a matrix." }, { "code": null, "e": 24571, "s": 24539, "text": "Syntax: row(x, as.factor=FALSE)" }, { "code": null, "e": 24741, "s": 24571, "text": "Parameters:x: matrixas.factor: a logical value indicating whether the value should be returned as a factor of column labels (created if necessary) rather than as numbers" }, { "code": null, "e": 24752, "s": 24741, "text": "Example 1:" }, { "code": "# R program to illustrate# row function # Initializing a matrix with# 2 rows and 2 columnsx <- matrix(c(1, 2, 3, 4), 2, 2) # Getting the matrix representationx # Calling the row() functionrow(x)", "e": 24950, "s": 24752, "text": null }, { "code": null, "e": 24958, "s": 24950, "text": "Output:" }, { "code": null, "e": 25074, "s": 24958, "text": "$Rscript main.r\n [, 1] [, 2]\n[1, ] 1 3\n[2, ] 2 4\n\n [, 1] [, 2]\n[1, ] 1 1\n[2, ] 2 2\n" }, { "code": null, "e": 25085, "s": 25074, "text": "Example 2:" }, { "code": "# R program to illustrate# row function # Initializing a matrix with# 3 rows and 3 columnsx <- matrix(rep(1:12), 3, 3) # Getting the matrix representationx # Calling the row() functionrow(x)", "e": 25279, "s": 25085, "text": null }, { "code": null, "e": 25287, "s": 25279, "text": "Output:" }, { "code": null, "e": 25460, "s": 25287, "text": " [, 1] [, 2] [, 3]\n[1, ] 1 4 7\n[2, ] 2 5 8\n[3, ] 3 6 9\n\n [, 1] [, 2] [, 3]\n[1, ] 1 1 1\n[2, ] 2 2 2\n[3, ] 3 3 3\n" }, { "code": null, "e": 25478, "s": 25460, "text": "R Matrix-Function" }, { "code": null, "e": 25489, "s": 25478, "text": "R Language" }, { "code": null, "e": 25587, "s": 25489, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25596, "s": 25587, "text": "Comments" }, { "code": null, "e": 25609, "s": 25596, "text": "Old Comments" }, { "code": null, "e": 25653, "s": 25609, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 25705, "s": 25653, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 25757, "s": 25705, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 25789, "s": 25757, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 25827, "s": 25789, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 25862, "s": 25827, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 25920, "s": 25862, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 25956, "s": 25920, "text": "K-Means Clustering in R Programming" }, { "code": null, "e": 26005, "s": 25956, "text": "Remove rows with NA in one column of R DataFrame" } ]
How to use PyCaret - the library for easy ML | Towards Data Science
When we approach supervised machine learning problems, it can be tempting to just see how a random forest or gradient boosting model performs and stop experimenting if we are satisfied with the results. What if you could compare many different models with just one line of code? What if you could reduce each step of the data science process from feature engineering to model deployment to just a few lines of code? This is exactly where PyCaret comes into play. PyCaret is a high-level, low-code Python library that makes it easy to compare, train, evaluate, tune, and deploy machine learning models with only a few lines of code. At its core, PyCaret is basically just a large wrapper over many data science libraries such as Scikit-learn, Yellowbrick, SHAP, Optuna, and Spacy. Yes, you could use these libraries for the same tasks, but if you don’t want to write a lot of code, PyCaret could save you a lot of time. In this article, I will demonstrate how you can use PyCaret to quickly and easily build a machine learning project and prepare the final model for deployment. PyCaret is a large library with a lot of dependencies. I would recommend creating a virtual environment specifically for PyCaret using Conda so that the installation does not impact any of your existing libraries. To create and activate a virtual environment in Conda, run the following commands: conda create --name pycaret_env python=3.6conda activate pycaret_env To install the default, smaller version of PyCaret with only the required dependencies, you can run the following command. pip install pycaret To install the full version of PyCaret, you should run the following command instead. pip install pycaret[full] Once PyCaret has been installed, deactivate the virtual environment and then add it to Jupyter with the following commands. conda deactivatepython -m ipykernel install --user --name pycaret_env --display-name "pycaret_env" Now, after launching a Jupyter Notebook in your browser, you should be able to see the option to change your environment to the one you just created. You can find the entire code for this article in this GitHub repository. In the code below, I simply imported Numpy and Pandas for handling the data for this demonstration. import numpy as npimport pandas as pd For this example, I used the California Housing Prices Dataset available on Kaggle. In the code below, I read this dataset into a dataframe and displayed the first ten rows of the dataframe. housing_data = pd.read_csv('./data/housing.csv')housing_data.head(10) The output above gives us an idea of what the data looks like. The data contains mostly numerical features with one categorical feature for the proximity of each house to the ocean. The target column that we are trying to predict is the median_house_value column. The entire dataset contains a total of 20,640 observations. Now that we have the data, we can initialize a PyCaret experiment, which will preprocess the data and enable logging for all of the models that we will train on this dataset. from pycaret.regression import *reg_experiment = setup(housing_data, target = 'median_house_value', session_id=123, log_experiment=True, experiment_name='ca_housing') As demonstrated in the GIF below, running the code above preprocesses the data and then produces a dataframe with the options for the experiment. We can compare different baseline models at once to find the model that achieves the best K-fold cross-validation performance with the compare_models function as shown in the code below. I have excluded XGBoost in the example below for demonstration purposes. best_model = compare_models(exclude=['xgboost'], fold=5) The function produces a data frame with the performance statistics for each model and highlights the metrics for the best performing model, which in this case was the CatBoost regressor. We can also train a model in just a single line of code with PyCaret. The create_model function simply requires a string corresponding to the type of model that you want to train. You can find a complete list of acceptable strings and the corresponding regression models on the PyCaret documentation page for this function. catboost = create_model('catboost') The create_model function produces the dataframe above with cross-validation metrics for the trained CatBoost model. Now that we have a trained model, we can optimize it even further with hyperparameter tuning. With just one line of code, we can tune the hyperparameters of this model as demonstrated below. tuned_catboost = tune_model(catboost, n_iter=50, optimize = 'MAE') The most important results, in this case, the average metrics, are highlighted in yellow. There are many plots that we can create with PyCaret to visualize a model’s performance. PyCaret uses another high-level library called Yellowbrick for building these visualizations. The plot_model function will produce a residual plot by default for a regression model as demonstrated below. plot_model(tuned_catboost) We can also visualize the predicted values against the actual target values by creating a prediction error plot. plot_model(tuned_catboost, plot = 'error') The plot above is particularly useful because it gives us a visual representation of the R2 coefficient for the CatBoost model. In a perfect scenario (R2 = 1), where the predicted values exactly matched the actual target values, this plot would simply contain points along the dashed identity line. We can also visualize the feature importances for a model as shown below. plot_model(tuned_catboost, plot = 'feature') Based on the plot above, we can see that the median_income feature is the most important feature when predicting the price of a house. Since this feature corresponds to the median income in the area in which a house was built, this evaluation makes perfect sense. Houses built in higher-income areas are likely more expensive than those in lower-income areas. We can also create multiple plots for evaluating a model with the evaluate_model function. evaluate_model(tuned_catboost) The interpret_model function is a useful tool for explaining the predictions of a model. This function uses a library for explainable machine learning called SHAP that I covered in the article below. towardsdatascience.com With just one line of code, we can create a SHAP beeswarm plot for the model. interpret_model(tuned_catboost) Based on the plot above, we can see that the median_income field has the greatest impact on the predicted house value. PyCaret also has a function for running automated machine learning (AutoML). We can specify the loss function or metric that we want to optimize and then just let the library take over as demonstrated below. automl_model = automl(optimize = 'MAE') In this example, the AutoML model also happens to be a CatBoost regressor, which we can confirm by printing out the model. print(automl_model) Running the print statement above produces the following output: <catboost.core.CatBoostRegressor at 0x7f9f05f4aad0> The predict_model function allows us to generate predictions by either using data from the experiment or new unseen data. pred_holdouts = predict_model(automl_model)pred_holdouts.head() The predict_model function above produces predictions for the holdout datasets used for validating the model during cross-validation. The code also gives us a dataframe with performance statistics for the predictions generated by the AutoML model. In the output above, the Label column represents the predictions generated by the AutoML model. We can also produce predictions on the entire dataset as demonstrated in the code below. new_data = housing_data.copy()new_data.drop(['median_house_value'], axis=1, inplace=True)predictions = predict_model(automl_model, data=new_data)predictions.head() PyCaret also allows us to save trained models with the save_model function. This function saves the transformation pipeline for the model to a pickle file. save_model(automl_model, model_name='automl-model') We can also load the saved AutoML model with the load_model function. loaded_model = load_model('automl-model')print(loaded_model) Printing out the loaded model produces the following output: Pipeline(memory=None, steps=[('dtypes', DataTypes_Auto_infer(categorical_features=[], display_types=True, features_todrop=[], id_columns=[], ml_usecase='regression', numerical_features=[], target='median_house_value', time_features=[])), ('imputer', Simple_Imputer(categorical_strategy='not_available', fill_value_categorical=None, fill_value_numerical=None, numer... ('cluster_all', 'passthrough'), ('dummy', Dummify(target='median_house_value')), ('fix_perfect', Remove_100(target='median_house_value')), ('clean_names', Clean_Colum_Names()), ('feature_select', 'passthrough'), ('fix_multi', 'passthrough'), ('dfs', 'passthrough'), ('pca', 'passthrough'), ['trained_model', <catboost.core.CatBoostRegressor object at 0x7fb750a0aad0>]], verbose=False) As we can see from the output above, PyCaret not only saved the trained model at the end of the pipeline but also the feature engineering and data preprocessing steps at the beginning of the pipeline. Now, we have a production-ready machine learning pipeline in a single file and we don’t have to worry about putting the individual parts of the pipeline together. Now that we have a model pipeline that is ready for production, we can also deploy the model to a cloud platform such as AWS with the deploy_model function. Before running this function, you must run the following command to configure your AWS command-line interface if you plan on deploying the model to an S3 bucket: aws configure Running the code above will trigger a series of prompts for information like your AWS Secret Access Key that you will need to provide. Once this process is complete, you are ready to deploy the model with the deploy_model function. deploy_model(automl_model, model_name = 'automl-model-aws', platform='aws', authentication = {'bucket' : 'pycaret-ca-housing-model'}) In the code above, I deployed the AutoML model to an S3 bucket named pycaret-ca-housing-model in AWS. From here, you can write an AWS Lambda function that pulls the model from S3 and runs in the cloud. PyCaret also allows you to load the model from S3 using the load_model function. Another nice feature of PyCaret is that it can log and track your machine learning experiments with a machine learning lifecycle tool called MLfLow. Running the command below will launch the MLflow user interface in your browser from localhost. !mlflow ui In the dashboard above, we can see that MLflow keeps track of the runs for different models for your PyCaret experiments. You can view the performance metrics as well as the running times for each run in your experiment. If you’ve read this far, you now have a basic understanding of how to use PyCaret. While PyCaret is a great tool, it comes with its own pros and cons that you should be aware of if you plan to use it for your data science projects. Low-code library. Great for simple, standard tasks and general-purpose machine learning. Provides support for regression, classification, natural language processing, clustering, anomaly detection, and association rule mining. Makes it easy to create and save complex transformation pipelines for models. Makes it easy to visualize the performance of your model. As of now, PyCaret is not ideal for text classification because the NLP utilities are limited to topic modeling algorithms. PyCaret is not ideal for deep learning and doesn’t use Keras or PyTorch models. You can’t perform more complex machine learning tasks such as image classification and text generation with PyCaret (at least with version 2.2.0). By using PyCaret, you are sacrificing a certain degree of control for simple and high-level code. In this article, I demonstrated how you can use PyCaret to complete all of the steps in a machine learning project ranging from data preprocessing to model deployment. While PyCaret is a useful tool, you should be aware of its pros and cons if you plan to use it for your data science projects. PyCaret is great for general-purpose machine learning with tabular data but as of version 2.2.0, it is not designed for more complex natural language processing, deep learning, and computer vision tasks. But it is still a time-saving tool and who knows, maybe the developers will add support for more complex tasks in the future? As I mentioned earlier, you can find the full code for this article on GitHub. Do you want to get better at data science and machine learning? Do you want to stay up to date with the latest libraries, developments, and research in the data science and machine learning community? Join my mailing list to get updates on my data science content. You’ll also get my free Step-By-Step Guide to Solving Machine Learning Problems when you sign up! M. Ali, PyCaret: An open-source, low-code machine learning library in Python, (2020), PyCaret.org.S. M. Lundberg, S. Lee, A Unified Approach to Interpreting Model Predictions, (2017), Advances in Neural Information Processing Systems 30 (NIPS 2017). M. Ali, PyCaret: An open-source, low-code machine learning library in Python, (2020), PyCaret.org. S. M. Lundberg, S. Lee, A Unified Approach to Interpreting Model Predictions, (2017), Advances in Neural Information Processing Systems 30 (NIPS 2017).
[ { "code": null, "e": 588, "s": 172, "text": "When we approach supervised machine learning problems, it can be tempting to just see how a random forest or gradient boosting model performs and stop experimenting if we are satisfied with the results. What if you could compare many different models with just one line of code? What if you could reduce each step of the data science process from feature engineering to model deployment to just a few lines of code?" }, { "code": null, "e": 1091, "s": 588, "text": "This is exactly where PyCaret comes into play. PyCaret is a high-level, low-code Python library that makes it easy to compare, train, evaluate, tune, and deploy machine learning models with only a few lines of code. At its core, PyCaret is basically just a large wrapper over many data science libraries such as Scikit-learn, Yellowbrick, SHAP, Optuna, and Spacy. Yes, you could use these libraries for the same tasks, but if you don’t want to write a lot of code, PyCaret could save you a lot of time." }, { "code": null, "e": 1250, "s": 1091, "text": "In this article, I will demonstrate how you can use PyCaret to quickly and easily build a machine learning project and prepare the final model for deployment." }, { "code": null, "e": 1547, "s": 1250, "text": "PyCaret is a large library with a lot of dependencies. I would recommend creating a virtual environment specifically for PyCaret using Conda so that the installation does not impact any of your existing libraries. To create and activate a virtual environment in Conda, run the following commands:" }, { "code": null, "e": 1616, "s": 1547, "text": "conda create --name pycaret_env python=3.6conda activate pycaret_env" }, { "code": null, "e": 1739, "s": 1616, "text": "To install the default, smaller version of PyCaret with only the required dependencies, you can run the following command." }, { "code": null, "e": 1759, "s": 1739, "text": "pip install pycaret" }, { "code": null, "e": 1845, "s": 1759, "text": "To install the full version of PyCaret, you should run the following command instead." }, { "code": null, "e": 1871, "s": 1845, "text": "pip install pycaret[full]" }, { "code": null, "e": 1995, "s": 1871, "text": "Once PyCaret has been installed, deactivate the virtual environment and then add it to Jupyter with the following commands." }, { "code": null, "e": 2094, "s": 1995, "text": "conda deactivatepython -m ipykernel install --user --name pycaret_env --display-name \"pycaret_env\"" }, { "code": null, "e": 2244, "s": 2094, "text": "Now, after launching a Jupyter Notebook in your browser, you should be able to see the option to change your environment to the one you just created." }, { "code": null, "e": 2417, "s": 2244, "text": "You can find the entire code for this article in this GitHub repository. In the code below, I simply imported Numpy and Pandas for handling the data for this demonstration." }, { "code": null, "e": 2455, "s": 2417, "text": "import numpy as npimport pandas as pd" }, { "code": null, "e": 2646, "s": 2455, "text": "For this example, I used the California Housing Prices Dataset available on Kaggle. In the code below, I read this dataset into a dataframe and displayed the first ten rows of the dataframe." }, { "code": null, "e": 2716, "s": 2646, "text": "housing_data = pd.read_csv('./data/housing.csv')housing_data.head(10)" }, { "code": null, "e": 3040, "s": 2716, "text": "The output above gives us an idea of what the data looks like. The data contains mostly numerical features with one categorical feature for the proximity of each house to the ocean. The target column that we are trying to predict is the median_house_value column. The entire dataset contains a total of 20,640 observations." }, { "code": null, "e": 3215, "s": 3040, "text": "Now that we have the data, we can initialize a PyCaret experiment, which will preprocess the data and enable logging for all of the models that we will train on this dataset." }, { "code": null, "e": 3474, "s": 3215, "text": "from pycaret.regression import *reg_experiment = setup(housing_data, target = 'median_house_value', session_id=123, log_experiment=True, experiment_name='ca_housing')" }, { "code": null, "e": 3620, "s": 3474, "text": "As demonstrated in the GIF below, running the code above preprocesses the data and then produces a dataframe with the options for the experiment." }, { "code": null, "e": 3880, "s": 3620, "text": "We can compare different baseline models at once to find the model that achieves the best K-fold cross-validation performance with the compare_models function as shown in the code below. I have excluded XGBoost in the example below for demonstration purposes." }, { "code": null, "e": 3937, "s": 3880, "text": "best_model = compare_models(exclude=['xgboost'], fold=5)" }, { "code": null, "e": 4124, "s": 3937, "text": "The function produces a data frame with the performance statistics for each model and highlights the metrics for the best performing model, which in this case was the CatBoost regressor." }, { "code": null, "e": 4448, "s": 4124, "text": "We can also train a model in just a single line of code with PyCaret. The create_model function simply requires a string corresponding to the type of model that you want to train. You can find a complete list of acceptable strings and the corresponding regression models on the PyCaret documentation page for this function." }, { "code": null, "e": 4484, "s": 4448, "text": "catboost = create_model('catboost')" }, { "code": null, "e": 4601, "s": 4484, "text": "The create_model function produces the dataframe above with cross-validation metrics for the trained CatBoost model." }, { "code": null, "e": 4792, "s": 4601, "text": "Now that we have a trained model, we can optimize it even further with hyperparameter tuning. With just one line of code, we can tune the hyperparameters of this model as demonstrated below." }, { "code": null, "e": 4859, "s": 4792, "text": "tuned_catboost = tune_model(catboost, n_iter=50, optimize = 'MAE')" }, { "code": null, "e": 4949, "s": 4859, "text": "The most important results, in this case, the average metrics, are highlighted in yellow." }, { "code": null, "e": 5132, "s": 4949, "text": "There are many plots that we can create with PyCaret to visualize a model’s performance. PyCaret uses another high-level library called Yellowbrick for building these visualizations." }, { "code": null, "e": 5242, "s": 5132, "text": "The plot_model function will produce a residual plot by default for a regression model as demonstrated below." }, { "code": null, "e": 5269, "s": 5242, "text": "plot_model(tuned_catboost)" }, { "code": null, "e": 5382, "s": 5269, "text": "We can also visualize the predicted values against the actual target values by creating a prediction error plot." }, { "code": null, "e": 5425, "s": 5382, "text": "plot_model(tuned_catboost, plot = 'error')" }, { "code": null, "e": 5724, "s": 5425, "text": "The plot above is particularly useful because it gives us a visual representation of the R2 coefficient for the CatBoost model. In a perfect scenario (R2 = 1), where the predicted values exactly matched the actual target values, this plot would simply contain points along the dashed identity line." }, { "code": null, "e": 5798, "s": 5724, "text": "We can also visualize the feature importances for a model as shown below." }, { "code": null, "e": 5843, "s": 5798, "text": "plot_model(tuned_catboost, plot = 'feature')" }, { "code": null, "e": 6203, "s": 5843, "text": "Based on the plot above, we can see that the median_income feature is the most important feature when predicting the price of a house. Since this feature corresponds to the median income in the area in which a house was built, this evaluation makes perfect sense. Houses built in higher-income areas are likely more expensive than those in lower-income areas." }, { "code": null, "e": 6294, "s": 6203, "text": "We can also create multiple plots for evaluating a model with the evaluate_model function." }, { "code": null, "e": 6325, "s": 6294, "text": "evaluate_model(tuned_catboost)" }, { "code": null, "e": 6525, "s": 6325, "text": "The interpret_model function is a useful tool for explaining the predictions of a model. This function uses a library for explainable machine learning called SHAP that I covered in the article below." }, { "code": null, "e": 6548, "s": 6525, "text": "towardsdatascience.com" }, { "code": null, "e": 6626, "s": 6548, "text": "With just one line of code, we can create a SHAP beeswarm plot for the model." }, { "code": null, "e": 6658, "s": 6626, "text": "interpret_model(tuned_catboost)" }, { "code": null, "e": 6777, "s": 6658, "text": "Based on the plot above, we can see that the median_income field has the greatest impact on the predicted house value." }, { "code": null, "e": 6985, "s": 6777, "text": "PyCaret also has a function for running automated machine learning (AutoML). We can specify the loss function or metric that we want to optimize and then just let the library take over as demonstrated below." }, { "code": null, "e": 7025, "s": 6985, "text": "automl_model = automl(optimize = 'MAE')" }, { "code": null, "e": 7148, "s": 7025, "text": "In this example, the AutoML model also happens to be a CatBoost regressor, which we can confirm by printing out the model." }, { "code": null, "e": 7168, "s": 7148, "text": "print(automl_model)" }, { "code": null, "e": 7233, "s": 7168, "text": "Running the print statement above produces the following output:" }, { "code": null, "e": 7285, "s": 7233, "text": "<catboost.core.CatBoostRegressor at 0x7f9f05f4aad0>" }, { "code": null, "e": 7407, "s": 7285, "text": "The predict_model function allows us to generate predictions by either using data from the experiment or new unseen data." }, { "code": null, "e": 7471, "s": 7407, "text": "pred_holdouts = predict_model(automl_model)pred_holdouts.head()" }, { "code": null, "e": 7719, "s": 7471, "text": "The predict_model function above produces predictions for the holdout datasets used for validating the model during cross-validation. The code also gives us a dataframe with performance statistics for the predictions generated by the AutoML model." }, { "code": null, "e": 7904, "s": 7719, "text": "In the output above, the Label column represents the predictions generated by the AutoML model. We can also produce predictions on the entire dataset as demonstrated in the code below." }, { "code": null, "e": 8068, "s": 7904, "text": "new_data = housing_data.copy()new_data.drop(['median_house_value'], axis=1, inplace=True)predictions = predict_model(automl_model, data=new_data)predictions.head()" }, { "code": null, "e": 8224, "s": 8068, "text": "PyCaret also allows us to save trained models with the save_model function. This function saves the transformation pipeline for the model to a pickle file." }, { "code": null, "e": 8276, "s": 8224, "text": "save_model(automl_model, model_name='automl-model')" }, { "code": null, "e": 8346, "s": 8276, "text": "We can also load the saved AutoML model with the load_model function." }, { "code": null, "e": 8407, "s": 8346, "text": "loaded_model = load_model('automl-model')print(loaded_model)" }, { "code": null, "e": 8468, "s": 8407, "text": "Printing out the loaded model produces the following output:" }, { "code": null, "e": 9683, "s": 8468, "text": "Pipeline(memory=None, steps=[('dtypes', DataTypes_Auto_infer(categorical_features=[], display_types=True, features_todrop=[], id_columns=[], ml_usecase='regression', numerical_features=[], target='median_house_value', time_features=[])), ('imputer', Simple_Imputer(categorical_strategy='not_available', fill_value_categorical=None, fill_value_numerical=None, numer... ('cluster_all', 'passthrough'), ('dummy', Dummify(target='median_house_value')), ('fix_perfect', Remove_100(target='median_house_value')), ('clean_names', Clean_Colum_Names()), ('feature_select', 'passthrough'), ('fix_multi', 'passthrough'), ('dfs', 'passthrough'), ('pca', 'passthrough'), ['trained_model', <catboost.core.CatBoostRegressor object at 0x7fb750a0aad0>]], verbose=False)" }, { "code": null, "e": 10047, "s": 9683, "text": "As we can see from the output above, PyCaret not only saved the trained model at the end of the pipeline but also the feature engineering and data preprocessing steps at the beginning of the pipeline. Now, we have a production-ready machine learning pipeline in a single file and we don’t have to worry about putting the individual parts of the pipeline together." }, { "code": null, "e": 10366, "s": 10047, "text": "Now that we have a model pipeline that is ready for production, we can also deploy the model to a cloud platform such as AWS with the deploy_model function. Before running this function, you must run the following command to configure your AWS command-line interface if you plan on deploying the model to an S3 bucket:" }, { "code": null, "e": 10380, "s": 10366, "text": "aws configure" }, { "code": null, "e": 10612, "s": 10380, "text": "Running the code above will trigger a series of prompts for information like your AWS Secret Access Key that you will need to provide. Once this process is complete, you are ready to deploy the model with the deploy_model function." }, { "code": null, "e": 10771, "s": 10612, "text": "deploy_model(automl_model, model_name = 'automl-model-aws', platform='aws', authentication = {'bucket' : 'pycaret-ca-housing-model'})" }, { "code": null, "e": 11054, "s": 10771, "text": "In the code above, I deployed the AutoML model to an S3 bucket named pycaret-ca-housing-model in AWS. From here, you can write an AWS Lambda function that pulls the model from S3 and runs in the cloud. PyCaret also allows you to load the model from S3 using the load_model function." }, { "code": null, "e": 11299, "s": 11054, "text": "Another nice feature of PyCaret is that it can log and track your machine learning experiments with a machine learning lifecycle tool called MLfLow. Running the command below will launch the MLflow user interface in your browser from localhost." }, { "code": null, "e": 11310, "s": 11299, "text": "!mlflow ui" }, { "code": null, "e": 11531, "s": 11310, "text": "In the dashboard above, we can see that MLflow keeps track of the runs for different models for your PyCaret experiments. You can view the performance metrics as well as the running times for each run in your experiment." }, { "code": null, "e": 11763, "s": 11531, "text": "If you’ve read this far, you now have a basic understanding of how to use PyCaret. While PyCaret is a great tool, it comes with its own pros and cons that you should be aware of if you plan to use it for your data science projects." }, { "code": null, "e": 11781, "s": 11763, "text": "Low-code library." }, { "code": null, "e": 11852, "s": 11781, "text": "Great for simple, standard tasks and general-purpose machine learning." }, { "code": null, "e": 11990, "s": 11852, "text": "Provides support for regression, classification, natural language processing, clustering, anomaly detection, and association rule mining." }, { "code": null, "e": 12068, "s": 11990, "text": "Makes it easy to create and save complex transformation pipelines for models." }, { "code": null, "e": 12126, "s": 12068, "text": "Makes it easy to visualize the performance of your model." }, { "code": null, "e": 12250, "s": 12126, "text": "As of now, PyCaret is not ideal for text classification because the NLP utilities are limited to topic modeling algorithms." }, { "code": null, "e": 12330, "s": 12250, "text": "PyCaret is not ideal for deep learning and doesn’t use Keras or PyTorch models." }, { "code": null, "e": 12477, "s": 12330, "text": "You can’t perform more complex machine learning tasks such as image classification and text generation with PyCaret (at least with version 2.2.0)." }, { "code": null, "e": 12575, "s": 12477, "text": "By using PyCaret, you are sacrificing a certain degree of control for simple and high-level code." }, { "code": null, "e": 13200, "s": 12575, "text": "In this article, I demonstrated how you can use PyCaret to complete all of the steps in a machine learning project ranging from data preprocessing to model deployment. While PyCaret is a useful tool, you should be aware of its pros and cons if you plan to use it for your data science projects. PyCaret is great for general-purpose machine learning with tabular data but as of version 2.2.0, it is not designed for more complex natural language processing, deep learning, and computer vision tasks. But it is still a time-saving tool and who knows, maybe the developers will add support for more complex tasks in the future?" }, { "code": null, "e": 13279, "s": 13200, "text": "As I mentioned earlier, you can find the full code for this article on GitHub." }, { "code": null, "e": 13480, "s": 13279, "text": "Do you want to get better at data science and machine learning? Do you want to stay up to date with the latest libraries, developments, and research in the data science and machine learning community?" }, { "code": null, "e": 13642, "s": 13480, "text": "Join my mailing list to get updates on my data science content. You’ll also get my free Step-By-Step Guide to Solving Machine Learning Problems when you sign up!" }, { "code": null, "e": 13892, "s": 13642, "text": "M. Ali, PyCaret: An open-source, low-code machine learning library in Python, (2020), PyCaret.org.S. M. Lundberg, S. Lee, A Unified Approach to Interpreting Model Predictions, (2017), Advances in Neural Information Processing Systems 30 (NIPS 2017)." }, { "code": null, "e": 13991, "s": 13892, "text": "M. Ali, PyCaret: An open-source, low-code machine learning library in Python, (2020), PyCaret.org." } ]
WPF - Listbox
ListBox is a control that provides a list of items to the user item selection. A user can select one or more items from the predefined list of items at a time. In a ListBox, multiple options are always visible to the user without any user interaction. The hierarchical inheritance of ListBox class is as follows − Below are the commonly used Properties of ListBox class Background Gets or sets a brush that provides the background of the control. (Inherited from Control) BorderThickness Gets or sets the border thickness of a control. (Inherited from Control) FontFamily Gets or sets the font used to display text in the control. (Inherited from Control) FontSize Gets or sets the size of the text in this control. (Inherited from Control) FontStyle Gets or sets the style in which the text is rendered. (Inherited from Control) FontWeight Gets or sets the thickness of the specified font. (Inherited from Control) Foreground Gets or sets a brush that describes the foreground color. (Inherited from Control) GroupStyle Gets a collection of GroupStyle objects that define the appearance of each level of groups. (Inherited from ItemsControl) Height Gets or sets the suggested height of a FrameworkElement. (Inherited from FrameworkElement) HorizontalAlignment Gets or sets the horizontal alignment characteristics that are applied to a FrameworkElement when it is composed in a layout parent, such as a panel or items control. (Inherited from FrameworkElement) IsEnabled Gets or sets a value indicating whether the user can interact with the control. (Inherited from Control) Item Gets the collection used to generate the content of the control. (Inherited from ItemsControl) ItemSource Gets or sets an object source used to generate the content of the ItemsControl. (Inherited from ItemsControl) Margin Gets or sets the outer margin of a FrameworkElement. (Inherited from FrameworkElement) Name Gets or sets the identifying name of the object. When a XAML processor creates the object tree from XAML markup, run-time code can refer to the XAML declared object by this name. (Inherited from FrameworkElement) Opacity Gets or sets the degree of the object's opacity. (Inherited from UIElement) SelectedIndex Gets or sets the index of the selected item. (Inherited from Selector) SelectedItem Gets or sets the selected item. (Inherited from Selector) SelectedValue Gets or sets the value of the selected item, obtained by using the SelectedValuePath. (Inherited from Selector) Style Gets or sets an instance Style that is applied for this object during layout and rendering. (Inherited from FrameworkElement) VerticalAlignment Gets or sets the vertical alignment characteristics that are applied to a FrameworkElement when it is composed in a parent object such as a panel or items control. (Inherited from FrameworkElement) Width Gets or sets the width of a FrameworkElement. (Inherited from FrameworkElement) DragEnter Occurs when the input system reports an underlying drag event with this element as the target. (Inherited from UIElement) DragLeave Occurs when the input system reports an underlying drag event with this element as the origin. (Inherited from UIElement) DragOver Occurs when the input system reports an underlying drag event with this element as the potential drop target. (Inherited from UIElement) DragStarting Occurs when a drag operation is initiated. (Inherited from UIElement) Drop Occurs when the input system reports an underlying drop event with this element as the drop target. (Inherited from UIElement) DropCompleted Occurs when a drag-and-drop operation is ended. (Inherited from UIElement) GotFocus Occurs when a UIElement receives focus. (Inherited from UIElement) IsEnabledChanged Occurs when the IsEnabled property changes. (Inherited from Control) KeyDown Occurs when a keyboard key is pressed while the UIElement has focus. (Inherited from UIElement) KeyUp Occurs when a keyboard key is released while the UIElement has focus. (Inherited from UIElement) LostFocus Occurs when a UIElement loses focus. (Inherited from UIElement) SelectionChanged Occurs when the currently selected item changes. (Inherited from Selector) SizeChanged Occurs when either the ActualHeight or the ActualWidth property changes value on a FrameworkElement. (Inherited from FrameworkElement) Arrange Positions child objects and determines a size for a UIElement. Parent objects that implement custom layout for their child elements should call this method from their layout override implementations to form a recursive layout update. (Inherited from UIElement) FindName Retrieves an object that has the specified identifier name. (Inherited from FrameworkElement) Focus Attempts to set the focus on the control. (Inherited from Control) GetValue Returns the current effective value of a dependency property from a DependencyObject. (Inherited from DependencyObject) IndexFromContainer Returns the index to the item that has the specified, generated container. (Inherited from ItemsControl) OnDragEnter Called before the DragEnter event occurs. (Inherited from Control) OnDragLeave Called before the DragLeave event occurs. (Inherited from Control) OnDragOver Called before the DragOver event occurs. (Inherited from Control) OnDrop Called before the Drop event occurs. (Inherited from Control) OnKeyDown Called before the KeyDown event occurs. (Inherited from Control) OnKeyUp Called before the KeyUp event occurs. (Inherited from Control) OnLostFocus Called before the LostFocus event occurs. (Inherited from Control) ReadLocalValue Returns the local value of a dependency property, if a local value is set. (Inherited from DependencyObject) SetBinding Attaches a binding to a FrameworkElement, using the provided binding object. (Inherited from FrameworkElement) SetValue Sets the local value of a dependency property on a DependencyObject. (Inherited from DependencyObject) Let’s create a new WPF project with the name WPFListBoxControl. Let’s create a new WPF project with the name WPFListBoxControl. Drag one list box and one textbox from the Toolbox. Drag one list box and one textbox from the Toolbox. When the user selects any item from the ListBox, it displayed on the TextBox as well. When the user selects any item from the ListBox, it displayed on the TextBox as well. Here is the XAML code in which a ListBox and a TextBox is created and initialized with some properties. Here is the XAML code in which a ListBox and a TextBox is created and initialized with some properties. <Window x:Class = "WPFListBoxControl.MainWindow" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d = "http://schemas.microsoft.com/expression/blend/2008" xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local = "clr-namespace:WPFListBoxControl" mc:Ignorable = "d" Title = "MainWindow" Height = "350" Width = "604"> <Grid> <ListBox Name = "listbox" Margin = "118,77,293,103"> <ListBoxItem Content = "XAML Tutorials" /> <ListBoxItem Content = "WPF Tutorials" /> <ListBoxItem Content = "Silverlight Tutorials" /> <ListBoxItem Content = "Windows 10 Tutorials" /> <ListBoxItem Content = "iOS Tutorials" /> </ListBox> <TextBox Height = "23" x:Name = "textBox1" Width = "120" Margin = "361,116,0,0" HorizontalAlignment = "Left" VerticalAlignment = "Top" Text="{Binding SelectedItem.Content, ElementName=listbox}" /> </Grid> </Window> When the above code is compiled and executed, it will produce the following output − We recommend that you execute the above example code and try the other properties and events of ListBox control. 31 Lectures 2.5 hours Anadi Sharma 30 Lectures 2.5 hours Taurius Litvinavicius Print Add Notes Bookmark this page
[ { "code": null, "e": 2334, "s": 2020, "text": "ListBox is a control that provides a list of items to the user item selection. A user can select one or more items from the predefined list of items at a time. In a ListBox, multiple options are always visible to the user without any user interaction. The hierarchical inheritance of ListBox class is as follows −" }, { "code": null, "e": 2390, "s": 2334, "text": "Below are the commonly used Properties of ListBox class" }, { "code": null, "e": 2401, "s": 2390, "text": "Background" }, { "code": null, "e": 2492, "s": 2401, "text": "Gets or sets a brush that provides the background of the control. (Inherited from Control)" }, { "code": null, "e": 2508, "s": 2492, "text": "BorderThickness" }, { "code": null, "e": 2581, "s": 2508, "text": "Gets or sets the border thickness of a control. (Inherited from Control)" }, { "code": null, "e": 2592, "s": 2581, "text": "FontFamily" }, { "code": null, "e": 2676, "s": 2592, "text": "Gets or sets the font used to display text in the control. (Inherited from Control)" }, { "code": null, "e": 2685, "s": 2676, "text": "FontSize" }, { "code": null, "e": 2761, "s": 2685, "text": "Gets or sets the size of the text in this control. (Inherited from Control)" }, { "code": null, "e": 2771, "s": 2761, "text": "FontStyle" }, { "code": null, "e": 2850, "s": 2771, "text": "Gets or sets the style in which the text is rendered. (Inherited from Control)" }, { "code": null, "e": 2861, "s": 2850, "text": "FontWeight" }, { "code": null, "e": 2936, "s": 2861, "text": "Gets or sets the thickness of the specified font. (Inherited from Control)" }, { "code": null, "e": 2947, "s": 2936, "text": "Foreground" }, { "code": null, "e": 3030, "s": 2947, "text": "Gets or sets a brush that describes the foreground color. (Inherited from Control)" }, { "code": null, "e": 3041, "s": 3030, "text": "GroupStyle" }, { "code": null, "e": 3163, "s": 3041, "text": "Gets a collection of GroupStyle objects that define the appearance of each level of groups. (Inherited from ItemsControl)" }, { "code": null, "e": 3170, "s": 3163, "text": "Height" }, { "code": null, "e": 3261, "s": 3170, "text": "Gets or sets the suggested height of a FrameworkElement. (Inherited from FrameworkElement)" }, { "code": null, "e": 3281, "s": 3261, "text": "HorizontalAlignment" }, { "code": null, "e": 3482, "s": 3281, "text": "Gets or sets the horizontal alignment characteristics that are applied to a FrameworkElement when it is composed in a layout parent, such as a panel or items control. (Inherited from FrameworkElement)" }, { "code": null, "e": 3492, "s": 3482, "text": "IsEnabled" }, { "code": null, "e": 3597, "s": 3492, "text": "Gets or sets a value indicating whether the user can interact with the control. (Inherited from Control)" }, { "code": null, "e": 3602, "s": 3597, "text": "Item" }, { "code": null, "e": 3697, "s": 3602, "text": "Gets the collection used to generate the content of the control. (Inherited from ItemsControl)" }, { "code": null, "e": 3708, "s": 3697, "text": "ItemSource" }, { "code": null, "e": 3818, "s": 3708, "text": "Gets or sets an object source used to generate the content of the ItemsControl. (Inherited from ItemsControl)" }, { "code": null, "e": 3825, "s": 3818, "text": "Margin" }, { "code": null, "e": 3912, "s": 3825, "text": "Gets or sets the outer margin of a FrameworkElement. (Inherited from FrameworkElement)" }, { "code": null, "e": 3917, "s": 3912, "text": "Name" }, { "code": null, "e": 4130, "s": 3917, "text": "Gets or sets the identifying name of the object. When a XAML processor creates the object tree from XAML markup, run-time code can refer to the XAML declared object by this name. (Inherited from FrameworkElement)" }, { "code": null, "e": 4138, "s": 4130, "text": "Opacity" }, { "code": null, "e": 4214, "s": 4138, "text": "Gets or sets the degree of the object's opacity. (Inherited from UIElement)" }, { "code": null, "e": 4228, "s": 4214, "text": "SelectedIndex" }, { "code": null, "e": 4299, "s": 4228, "text": "Gets or sets the index of the selected item. (Inherited from Selector)" }, { "code": null, "e": 4312, "s": 4299, "text": "SelectedItem" }, { "code": null, "e": 4370, "s": 4312, "text": "Gets or sets the selected item. (Inherited from Selector)" }, { "code": null, "e": 4384, "s": 4370, "text": "SelectedValue" }, { "code": null, "e": 4496, "s": 4384, "text": "Gets or sets the value of the selected item, obtained by using the SelectedValuePath. (Inherited from Selector)" }, { "code": null, "e": 4502, "s": 4496, "text": "Style" }, { "code": null, "e": 4628, "s": 4502, "text": "Gets or sets an instance Style that is applied for this object during layout and rendering. (Inherited from FrameworkElement)" }, { "code": null, "e": 4646, "s": 4628, "text": "VerticalAlignment" }, { "code": null, "e": 4844, "s": 4646, "text": "Gets or sets the vertical alignment characteristics that are applied to a FrameworkElement when it is composed in a parent object such as a panel or items control. (Inherited from FrameworkElement)" }, { "code": null, "e": 4850, "s": 4844, "text": "Width" }, { "code": null, "e": 4930, "s": 4850, "text": "Gets or sets the width of a FrameworkElement. (Inherited from FrameworkElement)" }, { "code": null, "e": 4940, "s": 4930, "text": "DragEnter" }, { "code": null, "e": 5062, "s": 4940, "text": "Occurs when the input system reports an underlying drag event with this element as the target. (Inherited from UIElement)" }, { "code": null, "e": 5072, "s": 5062, "text": "DragLeave" }, { "code": null, "e": 5194, "s": 5072, "text": "Occurs when the input system reports an underlying drag event with this element as the origin. (Inherited from UIElement)" }, { "code": null, "e": 5203, "s": 5194, "text": "DragOver" }, { "code": null, "e": 5340, "s": 5203, "text": "Occurs when the input system reports an underlying drag event with this element as the potential drop target. (Inherited from UIElement)" }, { "code": null, "e": 5353, "s": 5340, "text": "DragStarting" }, { "code": null, "e": 5423, "s": 5353, "text": "Occurs when a drag operation is initiated. (Inherited from UIElement)" }, { "code": null, "e": 5428, "s": 5423, "text": "Drop" }, { "code": null, "e": 5555, "s": 5428, "text": "Occurs when the input system reports an underlying drop event with this element as the drop target. (Inherited from UIElement)" }, { "code": null, "e": 5569, "s": 5555, "text": "DropCompleted" }, { "code": null, "e": 5644, "s": 5569, "text": "Occurs when a drag-and-drop operation is ended. (Inherited from UIElement)" }, { "code": null, "e": 5653, "s": 5644, "text": "GotFocus" }, { "code": null, "e": 5720, "s": 5653, "text": "Occurs when a UIElement receives focus. (Inherited from UIElement)" }, { "code": null, "e": 5737, "s": 5720, "text": "IsEnabledChanged" }, { "code": null, "e": 5806, "s": 5737, "text": "Occurs when the IsEnabled property changes. (Inherited from Control)" }, { "code": null, "e": 5814, "s": 5806, "text": "KeyDown" }, { "code": null, "e": 5910, "s": 5814, "text": "Occurs when a keyboard key is pressed while the UIElement has focus. (Inherited from UIElement)" }, { "code": null, "e": 5916, "s": 5910, "text": "KeyUp" }, { "code": null, "e": 6013, "s": 5916, "text": "Occurs when a keyboard key is released while the UIElement has focus. (Inherited from UIElement)" }, { "code": null, "e": 6023, "s": 6013, "text": "LostFocus" }, { "code": null, "e": 6087, "s": 6023, "text": "Occurs when a UIElement loses focus. (Inherited from UIElement)" }, { "code": null, "e": 6104, "s": 6087, "text": "SelectionChanged" }, { "code": null, "e": 6179, "s": 6104, "text": "Occurs when the currently selected item changes. (Inherited from Selector)" }, { "code": null, "e": 6191, "s": 6179, "text": "SizeChanged" }, { "code": null, "e": 6326, "s": 6191, "text": "Occurs when either the ActualHeight or the ActualWidth property changes value on a FrameworkElement. (Inherited from FrameworkElement)" }, { "code": null, "e": 6334, "s": 6326, "text": "Arrange" }, { "code": null, "e": 6595, "s": 6334, "text": "Positions child objects and determines a size for a UIElement. Parent objects that implement custom layout for their child elements should call this method from their layout override implementations to form a recursive layout update. (Inherited from UIElement)" }, { "code": null, "e": 6604, "s": 6595, "text": "FindName" }, { "code": null, "e": 6698, "s": 6604, "text": "Retrieves an object that has the specified identifier name. (Inherited from FrameworkElement)" }, { "code": null, "e": 6704, "s": 6698, "text": "Focus" }, { "code": null, "e": 6771, "s": 6704, "text": "Attempts to set the focus on the control. (Inherited from Control)" }, { "code": null, "e": 6780, "s": 6771, "text": "GetValue" }, { "code": null, "e": 6900, "s": 6780, "text": "Returns the current effective value of a dependency property from a DependencyObject. (Inherited from DependencyObject)" }, { "code": null, "e": 6919, "s": 6900, "text": "IndexFromContainer" }, { "code": null, "e": 7024, "s": 6919, "text": "Returns the index to the item that has the specified, generated container. (Inherited from ItemsControl)" }, { "code": null, "e": 7036, "s": 7024, "text": "OnDragEnter" }, { "code": null, "e": 7103, "s": 7036, "text": "Called before the DragEnter event occurs. (Inherited from Control)" }, { "code": null, "e": 7115, "s": 7103, "text": "OnDragLeave" }, { "code": null, "e": 7182, "s": 7115, "text": "Called before the DragLeave event occurs. (Inherited from Control)" }, { "code": null, "e": 7193, "s": 7182, "text": "OnDragOver" }, { "code": null, "e": 7259, "s": 7193, "text": "Called before the DragOver event occurs. (Inherited from Control)" }, { "code": null, "e": 7266, "s": 7259, "text": "OnDrop" }, { "code": null, "e": 7328, "s": 7266, "text": "Called before the Drop event occurs. (Inherited from Control)" }, { "code": null, "e": 7338, "s": 7328, "text": "OnKeyDown" }, { "code": null, "e": 7403, "s": 7338, "text": "Called before the KeyDown event occurs. (Inherited from Control)" }, { "code": null, "e": 7411, "s": 7403, "text": "OnKeyUp" }, { "code": null, "e": 7474, "s": 7411, "text": "Called before the KeyUp event occurs. (Inherited from Control)" }, { "code": null, "e": 7486, "s": 7474, "text": "OnLostFocus" }, { "code": null, "e": 7553, "s": 7486, "text": "Called before the LostFocus event occurs. (Inherited from Control)" }, { "code": null, "e": 7568, "s": 7553, "text": "ReadLocalValue" }, { "code": null, "e": 7677, "s": 7568, "text": "Returns the local value of a dependency property, if a local value is set. (Inherited from DependencyObject)" }, { "code": null, "e": 7688, "s": 7677, "text": "SetBinding" }, { "code": null, "e": 7799, "s": 7688, "text": "Attaches a binding to a FrameworkElement, using the provided binding object. (Inherited from FrameworkElement)" }, { "code": null, "e": 7808, "s": 7799, "text": "SetValue" }, { "code": null, "e": 7911, "s": 7808, "text": "Sets the local value of a dependency property on a DependencyObject. (Inherited from DependencyObject)" }, { "code": null, "e": 7975, "s": 7911, "text": "Let’s create a new WPF project with the name WPFListBoxControl." }, { "code": null, "e": 8039, "s": 7975, "text": "Let’s create a new WPF project with the name WPFListBoxControl." }, { "code": null, "e": 8091, "s": 8039, "text": "Drag one list box and one textbox from the Toolbox." }, { "code": null, "e": 8143, "s": 8091, "text": "Drag one list box and one textbox from the Toolbox." }, { "code": null, "e": 8229, "s": 8143, "text": "When the user selects any item from the ListBox, it displayed on the TextBox as well." }, { "code": null, "e": 8315, "s": 8229, "text": "When the user selects any item from the ListBox, it displayed on the TextBox as well." }, { "code": null, "e": 8419, "s": 8315, "text": "Here is the XAML code in which a ListBox and a TextBox is created and initialized with some properties." }, { "code": null, "e": 8523, "s": 8419, "text": "Here is the XAML code in which a ListBox and a TextBox is created and initialized with some properties." }, { "code": null, "e": 9593, "s": 8523, "text": "<Window x:Class = \"WPFListBoxControl.MainWindow\" \n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" \n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\" \n xmlns:d = \"http://schemas.microsoft.com/expression/blend/2008\" \n xmlns:mc = \"http://schemas.openxmlformats.org/markup-compatibility/2006\" \n xmlns:local = \"clr-namespace:WPFListBoxControl\"\n mc:Ignorable = \"d\" Title = \"MainWindow\" Height = \"350\" Width = \"604\">\n\t\n <Grid> \n <ListBox Name = \"listbox\" Margin = \"118,77,293,103\">\n <ListBoxItem Content = \"XAML Tutorials\" /> \n <ListBoxItem Content = \"WPF Tutorials\" /> \n <ListBoxItem Content = \"Silverlight Tutorials\" /> \n <ListBoxItem Content = \"Windows 10 Tutorials\" /> \n <ListBoxItem Content = \"iOS Tutorials\" /> \n </ListBox> \n\t\t\n <TextBox Height = \"23\" x:Name = \"textBox1\" Width = \"120\" Margin = \"361,116,0,0\" \n HorizontalAlignment = \"Left\" VerticalAlignment = \"Top\" \n Text=\"{Binding SelectedItem.Content, ElementName=listbox}\" /> \n </Grid> \n\t\n</Window>" }, { "code": null, "e": 9678, "s": 9593, "text": "When the above code is compiled and executed, it will produce the following output −" }, { "code": null, "e": 9791, "s": 9678, "text": "We recommend that you execute the above example code and try the other properties and events of ListBox control." }, { "code": null, "e": 9826, "s": 9791, "text": "\n 31 Lectures \n 2.5 hours \n" }, { "code": null, "e": 9840, "s": 9826, "text": " Anadi Sharma" }, { "code": null, "e": 9875, "s": 9840, "text": "\n 30 Lectures \n 2.5 hours \n" }, { "code": null, "e": 9898, "s": 9875, "text": " Taurius Litvinavicius" }, { "code": null, "e": 9905, "s": 9898, "text": " Print" }, { "code": null, "e": 9916, "s": 9905, "text": " Add Notes" } ]
Bootstrap well class
A well is a container in <div> that causes the content to appear sunken or an inset effect on the page. To create a well, simply wrap the content that you would like to appear in the well with a <div> containing the class of .well. You can try to run the following code to implement well class in Bootstrap − Live Demo <!DOCTYPE html> <html> <head> <title>Bootstrap Example</title> <link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet"> <script src = "/scripts/jquery.min.js"></script> <script src = "/bootstrap/js/bootstrap.min.js"></script> </head> <body> <div class = "well">This is demo text!</div> </body> </html>
[ { "code": null, "e": 1294, "s": 1062, "text": "A well is a container in <div> that causes the content to appear sunken or an inset effect on the page. To create a well, simply wrap the content that you would like to appear in the well with a <div> containing the class of .well." }, { "code": null, "e": 1371, "s": 1294, "text": "You can try to run the following code to implement well class in Bootstrap −" }, { "code": null, "e": 1381, "s": 1371, "text": "Live Demo" }, { "code": null, "e": 1736, "s": 1381, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Bootstrap Example</title>\n <link href = \"/bootstrap/css/bootstrap.min.css\" rel = \"stylesheet\">\n <script src = \"/scripts/jquery.min.js\"></script>\n <script src = \"/bootstrap/js/bootstrap.min.js\"></script>\n </head>\n <body>\n <div class = \"well\">This is demo text!</div>\n </body>\n</html>" } ]
Plot a Vertical line in Matplotlib - GeeksforGeeks
25 Aug, 2021 Matplotlib is a popular python library used for plotting, It provides an object-oriented API to render GUI plots. Plotting a horizontal line is fairly simple, The following code shows how it can be done. Method #1: Using axvline() This function adds the vertical lines across the axes of the plot Syntax: matplotlib.pyplot.axvline(x, color, xmin, xmax, linestyle) Parameters: x: Position on X axis to plot the line, It accepts integers. xmin and xmax: scalar, optional, default: 0/1. It plots the line in the given range color: color for the line, It accepts a string. eg ‘r’ or ‘b’ . linestyle: Specifies the type of line, It accepts a string. eg ‘-‘, ‘–‘, ‘-.’, ‘:’, ‘None’, ‘ ‘, ”, ‘solid’, ‘dashed’, ‘dashdot’, ‘dotted’ Python3 # importing the modulesimport matplotlib.pyplot as pltimport numpy as np # specifying the plot sizeplt.figure(figsize = (10, 5)) # only one line may be specified; full heightplt.axvline(x = 7, color = 'b', label = 'axvline - full height') # rendering plotplt.show() Output: Method #2: Using vlines() matplotlib.pyplot.vlines() is a function used in the plotting of a dataset. In matplotlib.pyplot.vlines(), vlines is the abbreviation for vertical lines. What this function does is very much clear from the expanded form, which says that function deals with the plotting of the vertical lines across the axes. Syntax: vlines(x, ymin, ymax, colors, linestyles) Parameters: x: Position on X axis to plot the line, It accepts integers. xmin and xmax: scalar, optional, default: 0/1. It plots the line in the given range color: color for the line, It accepts a string. eg ‘r’ or ‘b’ . linestyle: Specifies the type of line, It accepts a string. eg ‘-‘, ‘–‘, ‘-.’, ‘:’, ‘None’, ‘ ‘, ”, ‘solid’, ‘dashed’, ‘dashdot’, ‘dotted’ Python3 # importing necessary librariesimport matplotlib.pyplot as pltimport numpy as np # defining an arrayxs = [1, 100] # defining plot sizeplt.figure(figsize = (10, 7)) # single lineplt.vlines(x = 37, ymin = 0, ymax = max(xs), colors = 'purple', label = 'vline_multiple - full height') plt.show() Output: Method #3: Using plot() The plot() function in pyplot module of matplotlib library is used to make a 2D hexagonal binning plot of points x, y. Syntax : plot(x_points, y_points, scaley = False) Parameters: x_points/y_points: points to plot scalex/scaley: Bool, These parameters determine if the view limits are adapted to the data limits Python3 # importing libraryimport matplotlib.pyplot as plt # defining plot sizeplt.figure(figsize = (10, 5)) # specifying plot coordinatesplt.plot((0, 0), (0, 1), scaley = False) # setting scaley = True will make the line fit# withn the frame, i.e It will appear as a finite lineplt.show() Output: The below methods can be used for plotting multiple lines in Python. Method #1: Using axvline() Python3 # importing the modulesimport matplotlib.pyplot as pltimport numpy as np # specifying the plot sizeplt.figure(figsize = (10, 5)) # only one line may be specified; full heightplt.axvline(x = 7, color = 'b', label = 'axvline - full height') # only one line may be specified; ymin & ymax specified as# a percentage of y-rangeplt.axvline(x = 7.25, ymin = 0.1, ymax = 0.90, color = 'r', label = 'axvline - % of full height') # place legend outsideplt.legend(bbox_to_anchor = (1.0, 1), loc = 'upper left') # rendering plotplt.show() Output: Method #2: Using vlines() Python3 # importing necessary librariesimport matplotlib.pyplot as pltimport numpy as np # defining an arrayxs = [1, 100] # defining plot sizeplt.figure(figsize = (10, 7)) # multiple lines all full heightplt.vlines(x = [37, 37.25, 37.5], ymin = 0, ymax = max(xs), colors = 'purple', label = 'vline_multiple - full height') # multiple lines with varying ymin and ymaxplt.vlines(x = [38, 38.25, 38.5], ymin = [0, 25, 75], ymax = max(xs), colors = 'teal', label = 'vline_multiple - partial height') # single vline with full ymin and ymaxplt.vlines(x = 39, ymin = 0, ymax = max(xs), colors = 'green', label = 'vline_single - full height') # single vline with specific ymin and ymaxplt.vlines(x = 39.25, ymin = 25, ymax = max(xs), colors = 'green', label = 'vline_single - partial height') # place legend outsideplt.legend(bbox_to_anchor = (1.0, 1), loc = 'up')plt.show() Output: akshaysingh98088 saurabh1990aror Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python String | replace() Create a Pandas DataFrame from Lists Python program to convert a list to string Reading and Writing to text files in Python
[ { "code": null, "e": 24592, "s": 24564, "text": "\n25 Aug, 2021" }, { "code": null, "e": 24796, "s": 24592, "text": "Matplotlib is a popular python library used for plotting, It provides an object-oriented API to render GUI plots. Plotting a horizontal line is fairly simple, The following code shows how it can be done." }, { "code": null, "e": 24823, "s": 24796, "text": "Method #1: Using axvline()" }, { "code": null, "e": 24889, "s": 24823, "text": "This function adds the vertical lines across the axes of the plot" }, { "code": null, "e": 24956, "s": 24889, "text": "Syntax: matplotlib.pyplot.axvline(x, color, xmin, xmax, linestyle)" }, { "code": null, "e": 24968, "s": 24956, "text": "Parameters:" }, { "code": null, "e": 25030, "s": 24968, "text": "x: Position on X axis to plot the line, It accepts integers." }, { "code": null, "e": 25115, "s": 25030, "text": "xmin and xmax: scalar, optional, default: 0/1. It plots the line in the given range" }, { "code": null, "e": 25180, "s": 25115, "text": "color: color for the line, It accepts a string. eg ‘r’ or ‘b’ ." }, { "code": null, "e": 25319, "s": 25180, "text": "linestyle: Specifies the type of line, It accepts a string. eg ‘-‘, ‘–‘, ‘-.’, ‘:’, ‘None’, ‘ ‘, ”, ‘solid’, ‘dashed’, ‘dashdot’, ‘dotted’" }, { "code": null, "e": 25327, "s": 25319, "text": "Python3" }, { "code": "# importing the modulesimport matplotlib.pyplot as pltimport numpy as np # specifying the plot sizeplt.figure(figsize = (10, 5)) # only one line may be specified; full heightplt.axvline(x = 7, color = 'b', label = 'axvline - full height') # rendering plotplt.show()", "e": 25593, "s": 25327, "text": null }, { "code": null, "e": 25601, "s": 25593, "text": "Output:" }, { "code": null, "e": 25627, "s": 25601, "text": "Method #2: Using vlines()" }, { "code": null, "e": 25936, "s": 25627, "text": "matplotlib.pyplot.vlines() is a function used in the plotting of a dataset. In matplotlib.pyplot.vlines(), vlines is the abbreviation for vertical lines. What this function does is very much clear from the expanded form, which says that function deals with the plotting of the vertical lines across the axes." }, { "code": null, "e": 25986, "s": 25936, "text": "Syntax: vlines(x, ymin, ymax, colors, linestyles)" }, { "code": null, "e": 25998, "s": 25986, "text": "Parameters:" }, { "code": null, "e": 26060, "s": 25998, "text": "x: Position on X axis to plot the line, It accepts integers." }, { "code": null, "e": 26145, "s": 26060, "text": "xmin and xmax: scalar, optional, default: 0/1. It plots the line in the given range" }, { "code": null, "e": 26210, "s": 26145, "text": "color: color for the line, It accepts a string. eg ‘r’ or ‘b’ ." }, { "code": null, "e": 26349, "s": 26210, "text": "linestyle: Specifies the type of line, It accepts a string. eg ‘-‘, ‘–‘, ‘-.’, ‘:’, ‘None’, ‘ ‘, ”, ‘solid’, ‘dashed’, ‘dashdot’, ‘dotted’" }, { "code": null, "e": 26357, "s": 26349, "text": "Python3" }, { "code": "# importing necessary librariesimport matplotlib.pyplot as pltimport numpy as np # defining an arrayxs = [1, 100] # defining plot sizeplt.figure(figsize = (10, 7)) # single lineplt.vlines(x = 37, ymin = 0, ymax = max(xs), colors = 'purple', label = 'vline_multiple - full height') plt.show()", "e": 26669, "s": 26357, "text": null }, { "code": null, "e": 26679, "s": 26669, "text": " Output:" }, { "code": null, "e": 26704, "s": 26679, "text": "Method #3: Using plot() " }, { "code": null, "e": 26823, "s": 26704, "text": "The plot() function in pyplot module of matplotlib library is used to make a 2D hexagonal binning plot of points x, y." }, { "code": null, "e": 26873, "s": 26823, "text": "Syntax : plot(x_points, y_points, scaley = False)" }, { "code": null, "e": 26885, "s": 26873, "text": "Parameters:" }, { "code": null, "e": 26919, "s": 26885, "text": "x_points/y_points: points to plot" }, { "code": null, "e": 27017, "s": 26919, "text": "scalex/scaley: Bool, These parameters determine if the view limits are adapted to the data limits" }, { "code": null, "e": 27025, "s": 27017, "text": "Python3" }, { "code": "# importing libraryimport matplotlib.pyplot as plt # defining plot sizeplt.figure(figsize = (10, 5)) # specifying plot coordinatesplt.plot((0, 0), (0, 1), scaley = False) # setting scaley = True will make the line fit# withn the frame, i.e It will appear as a finite lineplt.show()", "e": 27307, "s": 27025, "text": null }, { "code": null, "e": 27317, "s": 27307, "text": " Output:" }, { "code": null, "e": 27388, "s": 27319, "text": "The below methods can be used for plotting multiple lines in Python." }, { "code": null, "e": 27416, "s": 27388, "text": "Method #1: Using axvline() " }, { "code": null, "e": 27424, "s": 27416, "text": "Python3" }, { "code": "# importing the modulesimport matplotlib.pyplot as pltimport numpy as np # specifying the plot sizeplt.figure(figsize = (10, 5)) # only one line may be specified; full heightplt.axvline(x = 7, color = 'b', label = 'axvline - full height') # only one line may be specified; ymin & ymax specified as# a percentage of y-rangeplt.axvline(x = 7.25, ymin = 0.1, ymax = 0.90, color = 'r', label = 'axvline - % of full height') # place legend outsideplt.legend(bbox_to_anchor = (1.0, 1), loc = 'upper left') # rendering plotplt.show()", "e": 27962, "s": 27424, "text": null }, { "code": null, "e": 27970, "s": 27962, "text": "Output:" }, { "code": null, "e": 27996, "s": 27970, "text": "Method #2: Using vlines()" }, { "code": null, "e": 28004, "s": 27996, "text": "Python3" }, { "code": "# importing necessary librariesimport matplotlib.pyplot as pltimport numpy as np # defining an arrayxs = [1, 100] # defining plot sizeplt.figure(figsize = (10, 7)) # multiple lines all full heightplt.vlines(x = [37, 37.25, 37.5], ymin = 0, ymax = max(xs), colors = 'purple', label = 'vline_multiple - full height') # multiple lines with varying ymin and ymaxplt.vlines(x = [38, 38.25, 38.5], ymin = [0, 25, 75], ymax = max(xs), colors = 'teal', label = 'vline_multiple - partial height') # single vline with full ymin and ymaxplt.vlines(x = 39, ymin = 0, ymax = max(xs), colors = 'green', label = 'vline_single - full height') # single vline with specific ymin and ymaxplt.vlines(x = 39.25, ymin = 25, ymax = max(xs), colors = 'green', label = 'vline_single - partial height') # place legend outsideplt.legend(bbox_to_anchor = (1.0, 1), loc = 'up')plt.show()", "e": 28923, "s": 28004, "text": null }, { "code": null, "e": 28931, "s": 28923, "text": "Output:" }, { "code": null, "e": 28948, "s": 28931, "text": "akshaysingh98088" }, { "code": null, "e": 28964, "s": 28948, "text": "saurabh1990aror" }, { "code": null, "e": 28982, "s": 28964, "text": "Python-matplotlib" }, { "code": null, "e": 28989, "s": 28982, "text": "Python" }, { "code": null, "e": 29087, "s": 28989, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29105, "s": 29087, "text": "Python Dictionary" }, { "code": null, "e": 29140, "s": 29105, "text": "Read a file line by line in Python" }, { "code": null, "e": 29162, "s": 29140, "text": "Enumerate() in Python" }, { "code": null, "e": 29194, "s": 29162, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29224, "s": 29194, "text": "Iterate over a list in Python" }, { "code": null, "e": 29266, "s": 29224, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 29292, "s": 29266, "text": "Python String | replace()" }, { "code": null, "e": 29329, "s": 29292, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 29372, "s": 29329, "text": "Python program to convert a list to string" } ]
Mahotas - Bernsen local thresholding - GeeksforGeeks
08 Dec, 2021 In this article, we will see how we can implement bernsen local thresholding in mahotas. Bernsen’s method is one of locally adaptive binarization methods developed for image segmentation. In this study, Bernsen’s locally adaptive binarization method is implemented and then tested for different grayscale images. In this tutorial, we will use “luispedro” image, below is the command to load it. mahotas.demos.load('luispedro') Below is the luispedro image In order to do this we will use mahotas.thresholding.bernsen method Syntax : mahotas.thresholding.bernsen(image, contrast_threshold, global_threshold)Argument : It takes image object and two integer as argumentReturn : It returns image object Note: Input image should be filtered or should be loaded as grey In order to filter the image we will take the image object which is numpy.ndarray and filter it with the help of indexing, below is the command to do this image = image[:, :, 0] Example 1: Python3 # importing required librariesimport mahotasimport mahotas.demosimport numpy as npfrom pylab import imshow, gray, showfrom os import path # loading the imagephoto = mahotas.demos.load('luispedro') # loading image as greyphoto = mahotas.demos.load('luispedro', as_grey = True) # converting image type to unit8# because as_grey returns floating valuesphoto = photo.astype(np.uint8) # showing original imageprint("Image")imshow(photo)show() # bernsen thresholdphoto = mahotas.thresholding.bernsen(photo, 7, 200) print("Image with bernsen threshold") # showing imageimshow(photo)show() Output : Example 2: Python3 # importing required librariesimport mahotasimport numpy as npfrom pylab import imshow, showimport os # loading imageimg = mahotas.imread('dog_image.png') # setting filter to the imageimg = img[:, :, 0] print("Image") # showing the imageimshow(img)show() # bernsen thresholdimg = mahotas.thresholding.bernsen(img, 5, 100) print("Image with bernsen threshold") # showing imageimshow(img)show() Output : gabaa406 arorakashish0911 simranarora5sos sumitgumber28 Python-Mahotas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe Selecting rows in pandas DataFrame based on conditions How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | os.path.join() method Python | Get unique values from a list Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24292, "s": 24264, "text": "\n08 Dec, 2021" }, { "code": null, "e": 24605, "s": 24292, "text": "In this article, we will see how we can implement bernsen local thresholding in mahotas. Bernsen’s method is one of locally adaptive binarization methods developed for image segmentation. In this study, Bernsen’s locally adaptive binarization method is implemented and then tested for different grayscale images." }, { "code": null, "e": 24688, "s": 24605, "text": "In this tutorial, we will use “luispedro” image, below is the command to load it. " }, { "code": null, "e": 24720, "s": 24688, "text": "mahotas.demos.load('luispedro')" }, { "code": null, "e": 24751, "s": 24720, "text": "Below is the luispedro image " }, { "code": null, "e": 24821, "s": 24751, "text": "In order to do this we will use mahotas.thresholding.bernsen method " }, { "code": null, "e": 24998, "s": 24821, "text": "Syntax : mahotas.thresholding.bernsen(image, contrast_threshold, global_threshold)Argument : It takes image object and two integer as argumentReturn : It returns image object " }, { "code": null, "e": 25063, "s": 24998, "text": "Note: Input image should be filtered or should be loaded as grey" }, { "code": null, "e": 25219, "s": 25063, "text": "In order to filter the image we will take the image object which is numpy.ndarray and filter it with the help of indexing, below is the command to do this " }, { "code": null, "e": 25242, "s": 25219, "text": "image = image[:, :, 0]" }, { "code": null, "e": 25255, "s": 25242, "text": "Example 1: " }, { "code": null, "e": 25263, "s": 25255, "text": "Python3" }, { "code": "# importing required librariesimport mahotasimport mahotas.demosimport numpy as npfrom pylab import imshow, gray, showfrom os import path # loading the imagephoto = mahotas.demos.load('luispedro') # loading image as greyphoto = mahotas.demos.load('luispedro', as_grey = True) # converting image type to unit8# because as_grey returns floating valuesphoto = photo.astype(np.uint8) # showing original imageprint(\"Image\")imshow(photo)show() # bernsen thresholdphoto = mahotas.thresholding.bernsen(photo, 7, 200) print(\"Image with bernsen threshold\") # showing imageimshow(photo)show()", "e": 25847, "s": 25263, "text": null }, { "code": null, "e": 25857, "s": 25847, "text": "Output : " }, { "code": null, "e": 25869, "s": 25857, "text": "Example 2: " }, { "code": null, "e": 25877, "s": 25869, "text": "Python3" }, { "code": "# importing required librariesimport mahotasimport numpy as npfrom pylab import imshow, showimport os # loading imageimg = mahotas.imread('dog_image.png') # setting filter to the imageimg = img[:, :, 0] print(\"Image\") # showing the imageimshow(img)show() # bernsen thresholdimg = mahotas.thresholding.bernsen(img, 5, 100) print(\"Image with bernsen threshold\") # showing imageimshow(img)show()", "e": 26278, "s": 25877, "text": null }, { "code": null, "e": 26288, "s": 26278, "text": "Output : " }, { "code": null, "e": 26299, "s": 26290, "text": "gabaa406" }, { "code": null, "e": 26316, "s": 26299, "text": "arorakashish0911" }, { "code": null, "e": 26332, "s": 26316, "text": "simranarora5sos" }, { "code": null, "e": 26346, "s": 26332, "text": "sumitgumber28" }, { "code": null, "e": 26361, "s": 26346, "text": "Python-Mahotas" }, { "code": null, "e": 26368, "s": 26361, "text": "Python" }, { "code": null, "e": 26466, "s": 26368, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26475, "s": 26466, "text": "Comments" }, { "code": null, "e": 26488, "s": 26475, "text": "Old Comments" }, { "code": null, "e": 26520, "s": 26488, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26576, "s": 26520, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26631, "s": 26576, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 26673, "s": 26631, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26715, "s": 26673, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26746, "s": 26715, "text": "Python | os.path.join() method" }, { "code": null, "e": 26785, "s": 26746, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26814, "s": 26785, "text": "Create a directory in Python" }, { "code": null, "e": 26836, "s": 26814, "text": "Defaultdict in Python" } ]
Security Testing - Quick Guide
Security testing is very important to keep the system protected from malicious activities on the web. Security testing is a testing technique to determine if an information system protects data and maintains functionality as intended. Security testing does not guarantee complete security of the system, but it is important to include security testing as a part of the testing process. Security testing takes the following six measures to provide a secured environment − Confidentiality − It protects against disclosure of information to unintended recipients. Confidentiality − It protects against disclosure of information to unintended recipients. Integrity − It allows transferring accurate and correct desired information from senders to intended receivers. Integrity − It allows transferring accurate and correct desired information from senders to intended receivers. Authentication − It verifies and confirms the identity of the user. Authentication − It verifies and confirms the identity of the user. Authorization − It specifies access rights to the users and resources. Authorization − It specifies access rights to the users and resources. Availability − It ensures readiness of the information on requirement. Availability − It ensures readiness of the information on requirement. Non-repudiation − It ensures there is no denial from the sender or the receiver for having sent or received the message. Non-repudiation − It ensures there is no denial from the sender or the receiver for having sent or received the message. Spotting a security flaw in a web-based application involves complex steps and creative thinking. At times, a simple test can expose the most severe security risk. You can try this very basic test on any web application − Log into the web application using valid credentials. Log into the web application using valid credentials. Log out of the web application. Log out of the web application. Click the BACK button of the browser. Click the BACK button of the browser. Verify if you are asked to log in again or if you are able go back to the logged in page again. Verify if you are asked to log in again or if you are able go back to the logged in page again. Security testing can be seen as a controlled attack on the system, which uncovers security flaws in a realistic way. Its goal is to evaluate the current status of an IT system. It is also known as penetration test or more popularly as ethical hacking. Penetration test is done in phases and here in this chapter, we will discuss the complete process. Proper documentation should be done in each phase so that all the steps necessary to reproduce the attack are available readily. The documentation also serves as the basis for the detailed report customers receive at the end of a penetration test. Penetration test includes four major phases − Foot Printing Scanning Enumeration Exploitation These four steps are re-iterated multiple times which goes hand in hand with the normal SDLC. Malicious software (malware) is any software that gives partial to full control of the system to the attacker/malware creator. Various forms of malware are listed below − Virus − A virus is a program that creates copies of itself and inserts these copies into other computer programs, data files, or into the boot sector of the hard-disk. Upon successful replication, viruses cause harmful activity on infected hosts such as stealing hard-disk space or CPU time. Virus − A virus is a program that creates copies of itself and inserts these copies into other computer programs, data files, or into the boot sector of the hard-disk. Upon successful replication, viruses cause harmful activity on infected hosts such as stealing hard-disk space or CPU time. Worm − A worm is a type of malware which leaves a copy of itself in the memory of each computer in its path. Worm − A worm is a type of malware which leaves a copy of itself in the memory of each computer in its path. Trojan − Trojan is a non-self-replicating type of malware that contains malicious code, which upon execution results in loss or theft of data or possible system harm. Trojan − Trojan is a non-self-replicating type of malware that contains malicious code, which upon execution results in loss or theft of data or possible system harm. Adware − Adware, also known as freeware or pitchware, is a free computer software that contains commercial advertisements of games, desktop toolbars, and utilities. It is a web-based application and it collects web browser data to target advertisements, especially pop-ups. Adware − Adware, also known as freeware or pitchware, is a free computer software that contains commercial advertisements of games, desktop toolbars, and utilities. It is a web-based application and it collects web browser data to target advertisements, especially pop-ups. Spyware − Spyware is infiltration software that anonymously monitors users which enables a hacker to obtain sensitive information from the user's computer. Spyware exploits users and application vulnerabilities that is quite often attached to free online software downloads or to links that are clicked by users. Spyware − Spyware is infiltration software that anonymously monitors users which enables a hacker to obtain sensitive information from the user's computer. Spyware exploits users and application vulnerabilities that is quite often attached to free online software downloads or to links that are clicked by users. Rootkit − A rootkit is a software used by a hacker to gain admin level access to a computer/network which is installed through a stolen password or by exploiting a system vulnerability without the victim's knowledge. Rootkit − A rootkit is a software used by a hacker to gain admin level access to a computer/network which is installed through a stolen password or by exploiting a system vulnerability without the victim's knowledge. The following measures can be taken to avoid presence of malware in a system − Ensure the operating system and applications are up to date with patches/updates. Ensure the operating system and applications are up to date with patches/updates. Never open strange e-mails, especially ones with attachments. Never open strange e-mails, especially ones with attachments. When you download from the internet, always check what you install. Do not simply click OK to dismiss pop-up windows. Verify the publisher before you install application. When you download from the internet, always check what you install. Do not simply click OK to dismiss pop-up windows. Verify the publisher before you install application. Install anti-virus software. Install anti-virus software. Ensure you scan and update the antivirus programs regularly. Ensure you scan and update the antivirus programs regularly. Install firewall. Install firewall. Always enable and use security features provided by browsers and applications. Always enable and use security features provided by browsers and applications. The following software help remove the malwares from a system − Microsoft Security Essentials Microsoft Windows Defender AVG Internet Security Spybot - Search & Destroy Avast! Home Edition for personal use Panda Internet Security MacScan for Mac OS and Mac OS X Understanding the protocol is very important to get a good grasp on security testing. You will be able to appreciate the importance of the protocol when we intercept the packet data between the webserver and the client. The Hypertext Transfer Protocol (HTTP) is an application-level protocol for distributed, collaborative, hypermedia information systems. This is the foundation for data communication for the World Wide Web since 1990. HTTP is a generic and stateless protocol which can be used for other purposes as well using extension of its request methods, error codes, and headers. Basically, HTTP is a TCP/IP based communication protocol, which is used to deliver data such as HTML files, image files, query results etc. over the web. It provides a standardized way for computers to communicate with each other. HTTP specification specifies how clients’ requested data are sent to the server, and how servers respond to these requests. There are following three basic features which make HTTP a simple yet powerful protocol − HTTP is connectionless − The HTTP client, i.e., the browser initiates an HTTP request. After making a request, the client disconnects from the server and waits for a response. The server processes the request and re-establishes the connection with the client to send the response back. HTTP is connectionless − The HTTP client, i.e., the browser initiates an HTTP request. After making a request, the client disconnects from the server and waits for a response. The server processes the request and re-establishes the connection with the client to send the response back. HTTP is media independent − Any type of data can be sent by HTTP as long as both the client and server know how to handle the data content. This is required for client as well as server to specify the content type using appropriate MIME-type. HTTP is media independent − Any type of data can be sent by HTTP as long as both the client and server know how to handle the data content. This is required for client as well as server to specify the content type using appropriate MIME-type. HTTP is stateless − HTTP is a connectionless and this is a direct result that HTTP is a stateless protocol. The server and client are aware of each other only during a current request. Afterwards, both of them forget about each other. Due to this nature of the protocol, neither the client nor the browser can retain information between different requests across the web pages. HTTP is stateless − HTTP is a connectionless and this is a direct result that HTTP is a stateless protocol. The server and client are aware of each other only during a current request. Afterwards, both of them forget about each other. Due to this nature of the protocol, neither the client nor the browser can retain information between different requests across the web pages. HTTP/1.0 uses a new connection for each request/response exchange whereas HTTP/1.1 connection may be used for one or more request/response exchanges. The following diagram shows a very basic architecture of a web application and depicts where HTTP resides − The HTTP protocol is a request/response protocol based on the client/server architecture where web browser, robots, and search engines etc. act as HTTP clients and the web server acts as a server. Client − The HTTP client sends a request to the server in the form of a request method, URI, and protocol version, followed by a MIME-like message containing request modifiers, client information, and possible body content over a TCP/IP connection. Client − The HTTP client sends a request to the server in the form of a request method, URI, and protocol version, followed by a MIME-like message containing request modifiers, client information, and possible body content over a TCP/IP connection. Server − The HTTP server responds with a status line, including the protocol version of the message and a success or error code, followed by a MIME-like message containing server information, entity meta information, and possible entity-body content. Server − The HTTP server responds with a status line, including the protocol version of the message and a success or error code, followed by a MIME-like message containing server information, entity meta information, and possible entity-body content. HTTP is not a completely secured protocol. HTTP is not a completely secured protocol. HTTP uses port 80 as default port for communication. HTTP uses port 80 as default port for communication. HTTP operates at the application Layer. It needs to create multiple connections for data transfer, which increases administration overheads. HTTP operates at the application Layer. It needs to create multiple connections for data transfer, which increases administration overheads. No encryption/digital certificates are required for using HTTP. No encryption/digital certificates are required for using HTTP. Inorder to understand the HTTP Protocol indepth, click on each on of the below links. HTTP Parameters HTTP Parameters HTTP Messages HTTP Messages HTTP Requests HTTP Requests HTTP Responses HTTP Responses HTTP Methods HTTP Methods HTTP Status Codes HTTP Status Codes HTTP Header Fields HTTP Header Fields HTTP Security HTTP Security HTTPS (Hypertext Transfer Protocol over Secure Socket Layer) or HTTP over SSL is a web protocol developed by Netscape. It is not a protocol but it is just the result of layering the HTTP on top of SSL/TLS (Secure Socket Layer/Transport Layer Security). In short, HTTPS = HTTP + SSL When we browse, we normally send and receive information using HTTP protocol. So this leads anyone to eavesdrop on the conversation between our computer and the web server. Many a times we need to exchange sensitive information which needs to be secured and to prevent unauthorized access. Https protocol used in the following scenarios − Banking Websites Payment Gateway Shopping Websites All Login Pages Email Apps Public key and signed certificates are required for the server in HTTPS Protocol. Public key and signed certificates are required for the server in HTTPS Protocol. Client requests for the https:// page Client requests for the https:// page When using an https connection, the server responds to the initial connection by offering a list of encryption methods the webserver supports. When using an https connection, the server responds to the initial connection by offering a list of encryption methods the webserver supports. In response, the client selects a connection method, and the client and server exchange certificates to authenticate their identities. In response, the client selects a connection method, and the client and server exchange certificates to authenticate their identities. After this is done, both webserver and client exchange the encrypted information after ensuring that both are using the same key, and the connection is closed. After this is done, both webserver and client exchange the encrypted information after ensuring that both are using the same key, and the connection is closed. For hosting https connections, a server must have a public key certificate, which embeds key information with a verification of the key owner's identity. For hosting https connections, a server must have a public key certificate, which embeds key information with a verification of the key owner's identity. Almost all certificates are verified by a third party so that clients are assured that the key is always secure. Almost all certificates are verified by a third party so that clients are assured that the key is always secure. Encoding is the process of putting a sequence of characters such as letters, numbers and other special characters into a specialized format for efficient transmission. Decoding is the process of converting an encoded format back into the original sequence of characters. It is completely different from Encryption which we usually misinterpret. Encoding and decoding are used in data communications and storage. Encoding should NOT be used for transporting sensitive information. URLs can only be sent over the Internet using the ASCII character-set and there are instances when URL contains special characters apart from ASCII characters, it needs to be encoded. URLs do not contain spaces and are replaced with a plus (+) sign or with %20. The Browser (client side) will encode the input according to the character-set used in the web-page and the default character-set in HTML5 is UTF-8. Following table shows ASCII symbol of the character and its equal Symbol and finally its replacement which can be used in URL before passing it to the server − Cryptography is the science to encrypt and decrypt data that enables the users to store sensitive information or transmit it across insecure networks so that it can be read only by the intended recipient. Data which can be read and understood without any special measures is called plaintext, while the method of disguising plaintext in order to hide its substance is called encryption. Encrypted plaintext is known as cipher text and process of reverting the encrypted data back to plain text is known as decryption. The science of analyzing and breaking secure communication is known as cryptanalysis. The people who perform the same also known as attackers. The science of analyzing and breaking secure communication is known as cryptanalysis. The people who perform the same also known as attackers. Cryptography can be either strong or weak and the strength is measured by the time and resources it would require to recover the actual plaintext. Cryptography can be either strong or weak and the strength is measured by the time and resources it would require to recover the actual plaintext. Hence an appropriate decoding tool is required to decipher the strong encrypted messages. Hence an appropriate decoding tool is required to decipher the strong encrypted messages. There are some cryptographic techniques available with which even a billion computers doing a billion checks a second, it is not possible to decipher the text. There are some cryptographic techniques available with which even a billion computers doing a billion checks a second, it is not possible to decipher the text. As the computing power is increasing day by day, one has to make the encryption algorithms very strong in order to protect data and critical information from the attackers. As the computing power is increasing day by day, one has to make the encryption algorithms very strong in order to protect data and critical information from the attackers. A cryptographic algorithm works in combination with a key (can be a word, number, or phrase) to encrypt the plaintext and the same plaintext encrypts to different cipher text with different keys. Hence, the encrypted data is completely dependent couple of parameters such as the strength of the cryptographic algorithm and the secrecy of the key. Symmetric Encryption − Conventional cryptography, also known as conventional encryption, is the technique in which only one key is used for both encryption and decryption. For example, DES, Triple DES algorithms, MARS by IBM, RC2, RC4, RC5, RC6. Asymmetric Encryption − It is Public key cryptography that uses a pair of keys for encryption: a public key to encrypt data and a private key for decryption. Public key is published to the people while keeping the private key secret. For example, RSA, Digital Signature Algorithm (DSA), Elgamal. Hashing − Hashing is ONE-WAY encryption, which creates a scrambled output that cannot be reversed or at least cannot be reversed easily. For example, MD5 algorithm. It is used to create Digital Certificates, Digital signatures, Storage of passwords, Verification of communications, etc. Same Origin Policy (SOP) is an important concept in the web application security model. As per this policy, it permits scripts running on pages originating from the same site which can be a combination of the following − Domain Protocol Port The reason behind this behavior is security. If you have try.com in one window and gmail.com in another window, then you DO NOT want a script from try.com to access or modify the contents of gmail.com or run actions in context of gmail on your behalf. Below are webpages from the same origin. As explained before, the same origin takes domain/protocol/port into consideration. http://website.com http://website.com/ http://website.com/my/contact.html Below are webpages from a different origin. http://www.site.co.uk(another domain) http://site.org (another domain) https://site.com (another protocol) http://site.com:8080 (another port) Internet Explorer has two major exceptions to SOP. The first one is related to 'Trusted Zones'. If both domains are in highly trusted zone then the Same Origin policy is not applicable completely. The first one is related to 'Trusted Zones'. If both domains are in highly trusted zone then the Same Origin policy is not applicable completely. The second exception in IE is related to port. IE does not include port into Same Origin policy, hence the http://website.com and http://wesite.com:4444 are considered from the same origin and no restrictions are applied. The second exception in IE is related to port. IE does not include port into Same Origin policy, hence the http://website.com and http://wesite.com:4444 are considered from the same origin and no restrictions are applied. A cookie is a small piece of information sent by a web server to store on a web browser so that it can later be read by the browser. This way, the browser remembers some specific personal information. If a Hacker gets hold of the cookie information, it can lead to security issues. Here are some important properties of cookies − They are usually small text files, given ID tags that are stored on your computer's browser directory. They are usually small text files, given ID tags that are stored on your computer's browser directory. They are used by web developers to help users navigate their websites efficiently and perform certain functions. They are used by web developers to help users navigate their websites efficiently and perform certain functions. When the user browses the same website again, the data stored in the cookie is sent back to the web server to notify the website of the user’s previous activities. When the user browses the same website again, the data stored in the cookie is sent back to the web server to notify the website of the user’s previous activities. Cookies are unavoidable for websites that have huge databases, need logins, have customizable themes. Cookies are unavoidable for websites that have huge databases, need logins, have customizable themes. The cookie contains the following information − The name of the server the cookie was sent from. The lifetime of the cookie. A value - usually a randomly generated unique number. Session Cookies − These cookies are temporary which are erased when the user closes the browser. Even if the user logs in again, a new cookie for that session is created. Session Cookies − These cookies are temporary which are erased when the user closes the browser. Even if the user logs in again, a new cookie for that session is created. Persistent cookies − These cookies remain on the hard disk drive unless user wipes them off or they expire. The Cookie's expiry is dependent on how long they can last. Persistent cookies − These cookies remain on the hard disk drive unless user wipes them off or they expire. The Cookie's expiry is dependent on how long they can last. Here are the ways to test the cookies − Disabling Cookies − As a tester, we need to verify the access of the website after disabling cookies and to check if the pages are working properly. Navigating to all the pages of the website and watch for app crashes. It is also required to inform the user that cookies are required to use the site. Disabling Cookies − As a tester, we need to verify the access of the website after disabling cookies and to check if the pages are working properly. Navigating to all the pages of the website and watch for app crashes. It is also required to inform the user that cookies are required to use the site. Corrupting Cookies − Another testing to be performed is by corrupting the cookies. In order to do the same, one has to find the location of the site's cookie and manually edit it with fake / invalid data which can be used access internal information from the domain which in turn can then be used to hack the site. Corrupting Cookies − Another testing to be performed is by corrupting the cookies. In order to do the same, one has to find the location of the site's cookie and manually edit it with fake / invalid data which can be used access internal information from the domain which in turn can then be used to hack the site. Removing Cookies − Remove all the cookies for the website and check how the website reacts to it. Removing Cookies − Remove all the cookies for the website and check how the website reacts to it. Cross-Browser Compatibility − It is also important to check that cookies are being written properly on all supported browsers from any page that writes cookies. Cross-Browser Compatibility − It is also important to check that cookies are being written properly on all supported browsers from any page that writes cookies. Editing Cookies − If the application uses cookies to store login information then as a tester we should try changing the user in the cookie or address bar to another valid user. Editing the cookie should not let you log in to a different users account. Editing Cookies − If the application uses cookies to store login information then as a tester we should try changing the user in the cookie or address bar to another valid user. Editing the cookie should not let you log in to a different users account. Modern browsers support viewing/editing of the cookies inform within the Browser itself. There are plugins for mozilla/chrome using which we are able to perform the edit successfully. Edit cookies plugin for Firefox Edit This cookie plugin for chrome The steps should be performed to Edit a cookie − Download the plugin for Chrome from here Download the plugin for Chrome from here Edit the cookie value just by accessing the 'edit this cookie' plugin from chrome as shown below. Edit the cookie value just by accessing the 'edit this cookie' plugin from chrome as shown below. There are various methodologies/approaches which we can make use of as a reference for performing an attack. One can take into account the following standards while developing an attack model. Among the following list, OWASP is the most active and there are a number of contributors. We will focus on OWASP Techniques which each development team takes into consideration before designing a web app. PTES − Penetration Testing Execution Standard PTES − Penetration Testing Execution Standard OSSTMM − Open Source Security Testing Methodology Manual OSSTMM − Open Source Security Testing Methodology Manual OWASP Testing Techniques − Open Web Application Security Protocol OWASP Testing Techniques − Open Web Application Security Protocol The Open Web Application Security Protocol team released the top 10 vulnerabilities that are more prevalent in web in the recent years. Below is the list of security flaws that are more prevalent in a web based application. In order to understand each one of the techniques, let us work with a sample application. We will perform the attack on 'WebGoat', the J2EE application which is developed explicitly with security flaws for learning purposes. The complete details about the webgoat project can be located https://www.owasp.org/index.php/Category:OWASP_WebGoat_Project. To Download the WebGoat Application, Navigate to https://github.com/WebGoat/WebGoat/wiki/Installation-(WebGoat-6.0) and goto downloads section. To install the downloaded application, first ensure that you do not have any application running on Port 8080. It can be installed just using a single command - java -jar WebGoat-6.0.1-war-exec.jar. For more details, visit WebGoat Installation Post Installation, we should be able to access the application by navigating to http://localhost:8080/WebGoat/attack and the page would be displayed as shown below. We can use the credentials of guest or admin as displayed in the login page. In order to intercept the traffic between client (Browser) and Server (System where Webgoat Application is hosted in our case), we need to use a web proxy. We will use Burp Proxy that can be downloaded from https://portswigger.net/burp/download.html It is sufficient if you download the free version of burp suite as shown below. Burp Suite is a web proxy which can intercept each packet of information sent and received by the browser and webserver. This helps us to modify the contents before the client sends the information to the Web-Server. Step 1 − The App is installed on port 8080 and Burp is installed on port 8181 as shown below. Launch Burp suite and make the following settings in order to bring it up in port 8181 as shown below. Step 2 − We should ensure that the Burp is listening to Port#8080 where the application is installed so that Burp suite can intercept the traffic. This settings should be done on the scope tab of the Burp Suite as shown below. Step 3 − Then make your browser proxy settings to listen to the port 8181 (Burp Suite port). Thus we have configured the Web proxy to intercept the traffic between the client (browser) and the server (Webserver) as shown below − Step 4 − The snapshot of the configuration is shown below with a help of a simple workflow diagram as shown below Injection technique consists of injecting a SQL query or a command using the input fields of the application. A successful SQL injection can read, modify sensitive data from the database, and can also delete data from a database. It also enables the hacker to perform administrative operations on the database such as shutdown the DBMS/dropping databases. Let us understand Threat Agents, Attack Vectors, Security Weakness, Technical Impact and Business Impacts of this flaw with the help of simple diagram. The application uses untrusted data in the construction of the following vulnerable SQL call − String query = "SELECT * FROM EMP WHERE EMPID = '" + request.getParameter("id") + "'"; Step 1 − Navigate to the SQL Injection area of the application as shown below. Step 2 − As given in the exercise, we use String SQL Injection to bypass authentication. Use SQL injection to log in as the boss ('Neville') without using the correct password. Verify that Neville's profile can be viewed and that all functions are available (including Search, Create, and Delete). Step 3 − We will Inject a SQL such that we are able to bypass the password by sending the parameter as 'a' = 'a' or 1 = 1 Step 4 − Post Exploitation, we are able to login as Neville who is the Admin as shown below. There are plenty of ways to prevent SQL injection. When developers write the code, they should ensure that they handle special characters accordingly. There are cheat sheets/prevention techniques available from OWASP which is definitely a guide for developers. Using Parameterized Queries Escaping all User Supplied Input Enable Least Privilege for the database for the end users When authentication functions related to the application are not implemented correctly, it allows hackers to compromise passwords or session ID's or to exploit other implementation flaws using other users credentials. Let us understand Threat Agents, Attack Vectors, Security Weakness, Technical Impact and Business Impacts of this flaw with the help of simple diagram. An e-commerce application supports URL rewriting, putting session IDs in the URL − http://example.com/sale/saleitems/jsessionid=2P0OC2JSNDLPSKHCJUN2JV/?item=laptop An authenticated user of the site forwards the URL to their friends to know about the discounted sales. He e-mails the above link without knowing that the user is also giving away the session IDs. When his friends use the link, they use his session and credit card. Step 1 − Login to Webgoat and navigate to 'Session Management Flaws' Section. Let us bypass the authetication by spoofing the cookie. Below is the snapshot of the scenario. Step 2 − When we login using the credentials webgoat/webgoat, we find from Burp Suite that the JSESSION ID is C8F3177CCAFF380441ABF71090748F2E while the AuthCookie = 65432ubphcfx upon successful authentication. Step 3 − When we login using the credentials aspect/aspect, we find from Burp Suite that the JSESSION ID is C8F3177CCAFF380441ABF71090748F2E while the AuthCookie = 65432udfqtb upon successful authentication. Step 4 − Now we need to analyze the AuthCookie Patterns. The first half '65432' is common for both authentications. Hence we are now interested in analyzing the last part of the authcookie values such as - ubphcfx for webgoat user and udfqtb for aspect user respectively. Step 5 − If we take a deep look at the AuthCookie values, the last part is having the same length as that of user name. Hence it is evident that the username is used with some encryption method. Upon trial and errors/brute force mechanisms, we find that after reversing the user name, webgoat; we end up with taogbew and then the before alphabet character is what being used as AuthCookie. i.e ubphcfx. Step 6 − If we pass this cookie value and let us see what happens. Upon authenticating as user webgoat, change the AuthCookie value to mock the user Alice by finding the AuthCookie for the same by performing step#4 and step#5. Develop a strong authentication and session management controls such that it meets all the authentication and session management requirements defined in OWASP's Application Security Verification Standard. Develop a strong authentication and session management controls such that it meets all the authentication and session management requirements defined in OWASP's Application Security Verification Standard. Developers should ensure that they avoid XSS flaws that can be used to steal session IDs. Developers should ensure that they avoid XSS flaws that can be used to steal session IDs. Cross-site Scripting (XSS) happens whenever an application takes untrusted data and sends it to the client (browser) without validation. This allows attackers to execute malicious scripts in the victim's browser which can result in user sessions hijack, defacing web sites or redirect the user to malicious sites. Let us understand Threat Agents, Attack Vectors, Security Weakness, Technical Impact and Business Impacts of this flaw with the help of simple diagram. Stored XSS − Stored XSS also known as persistent XSS occurs when user input is stored on the target server such as database/message forum/comment field etc. Then the victim is able to retrieve the stored data from the web application. Stored XSS − Stored XSS also known as persistent XSS occurs when user input is stored on the target server such as database/message forum/comment field etc. Then the victim is able to retrieve the stored data from the web application. Reflected XSS − Reflected XSS also known as non-persistent XSS occurs when user input is immediately returned by a web application in an error message/search result or the input provided by the user as part of the request and without permanently storing the user provided data. Reflected XSS − Reflected XSS also known as non-persistent XSS occurs when user input is immediately returned by a web application in an error message/search result or the input provided by the user as part of the request and without permanently storing the user provided data. DOM Based XSS − DOM Based XSS is a form of XSS when the source of the data is in the DOM, the sink is also in the DOM, and the data flow never leaves the browser. DOM Based XSS − DOM Based XSS is a form of XSS when the source of the data is in the DOM, the sink is also in the DOM, and the data flow never leaves the browser. The application uses untrusted data in the construction without validation. The special characters ought to be escaped. http://www.webpage.org/task/Rule1?query=try The attacker modifies the query parameter in their browser to − http://www.webpage.org/task/Rule1?query=<h3>Hello from XSS"</h3> Step 1 − Login to Webgoat and navigate to cross-site scripting (XSS) Section. Let us execute a Stored Cross-site Scripting (XSS) attack. Below is the snapshot of the scenario. Step 2 − As per the scenario, let us login as Tom with password 'tom' as mentioned in the scenario itself. Click 'view profile' and get into edit mode. Since tom is the attacker, let us inject Java script into those edit boxes. <script> alert("HACKED") </script> Step 3 − As soon as the update is over, tom receives an alert box with the message "hacked" which means that the app is vulnerable. Step 4 − Now as per the scenario, we need to login as jerry (HR) and check if jerry is affected by the injected script. Step 5 − After logging in as Jerry, select 'Tom' and click 'view profile' as shown below. While viewing tom's profile from Jerry's account, he is able to get the same message box. Step 6 − This message box is just an example, but the actual attacker can perform much more than just displaying a message box. Developers have to ensure that they escape all untrusted data based on the HTML context such as body, attribute, JavaScript, CSS, or URL that the data is placed into. Developers have to ensure that they escape all untrusted data based on the HTML context such as body, attribute, JavaScript, CSS, or URL that the data is placed into. For those applications that need special characters as input, there should be robust validation mechanisms in place before accepting them as valid inputs. For those applications that need special characters as input, there should be robust validation mechanisms in place before accepting them as valid inputs. A direct object reference is likely to occur when a developer exposes a reference to an internal implementation object, such as a file, directory, or database key without any validation mechanism which allows attackers to manipulate these references to access unauthorized data. Let us understand Threat Agents, Attack Vectors, Security Weakness, Technical Impact and Business Impacts of this flaw with the help of simple diagram. The App uses unverified data in a SQL call that is accessing account information. String sqlquery = "SELECT * FROM useraccounts WHERE account = ?"; PreparedStatement st = connection.prepareStatement(sqlquery, ??); st.setString( 1, request.getParameter("acct")); ResultSet results = st.executeQuery( ); The attacker modifies the query parameter in their browser to point to Admin. http://webapp.com/app/accountInfo?acct=admin Step 1 − Login to Webgoat and navigate to access control flaws Section. The goal is to retrieve the tomcat-users.xml by navigating to the path where it is located. Below is the snapshot of the scenario. Step 2 − The path of the file is displayed in 'the current directory is' field - C:\Users\userName$\.extract\webapps\WebGoat\lesson_plans\en and we also know that the tomcat-users.xml file is kept under C:\xampp\tomcat\conf Step 3 − We need to traverse all the way out of the current directory and navigate from C:\ Drive. We can perform the same by intercepting the traffic using Burp Suite. Step 4 − If the attempt is successful, it displays the tomcat-users.xml with the message "Congratulations. You have successfully completed this lesson." Developers can use the following resources/points as a guide to prevent insecure direct object reference during development phase itself. Developers should use only one user or session for indirect object references. Developers should use only one user or session for indirect object references. It is also recommended to check the access before using a direct object reference from an untrusted source. It is also recommended to check the access before using a direct object reference from an untrusted source. Security Misconfiguration arises when Security settings are defined, implemented, and maintained as defaults. Good security requires a secure configuration defined and deployed for the application, web server, database server, and platform. It is equally important to have the software up to date. Some classic examples of security misconfiguration are as given − If Directory listing is not disabled on the server and if attacker discovers the same then the attacker can simply list directories to find any file and execute it. It is also possible to get the actual code base which contains all your custom code and then to find a serious flaws in the application. If Directory listing is not disabled on the server and if attacker discovers the same then the attacker can simply list directories to find any file and execute it. It is also possible to get the actual code base which contains all your custom code and then to find a serious flaws in the application. App server configuration allows stack traces to be returned to users, potentially exposing underlying flaws. Attackers grab those extra information that the error messages provide which is enough for them to penetrate. App server configuration allows stack traces to be returned to users, potentially exposing underlying flaws. Attackers grab those extra information that the error messages provide which is enough for them to penetrate. App servers usually come with sample apps that are not well secured. If not removed from production server would result in compromising your server. App servers usually come with sample apps that are not well secured. If not removed from production server would result in compromising your server. Step 1 − Launch Webgoat and navigate to insecure configuration section and let us try to solve that challenge. Snapshot of the same is provided below − Step 2 − We can try out as many options as we can think of. All we need to find the URL of config file and we know that the developers follow kind of naming convention for config files. It can be anything that is listed below. It is usually done by BRUTE force technique. web.config config appname.config conf Step 3 − Upon trying various options, we find that 'http://localhost:8080/WebGoat/conf' is successful. The following page is displayed if the attempt is successful − All environments such Development, QA, and production environments should be configured identically using different passwords used in each environment that cannot be hacked easily. All environments such Development, QA, and production environments should be configured identically using different passwords used in each environment that cannot be hacked easily. Ensure that a strong application architecture is being adopted that provides effective, secure separation between components. Ensure that a strong application architecture is being adopted that provides effective, secure separation between components. It can also minimize the possibility of this attack by running automated scans and doing audits periodically. It can also minimize the possibility of this attack by running automated scans and doing audits periodically. As the online applications keep flooding the internet in day by day, not all applications are secured. Many web applications do not properly protect sensitive user data such as credit cards information/Bank account info/authentication credentials. Hackers might end up stealing those weakly protected data to conduct credit card fraud, identity theft, or other crimes. Let us understand Threat Agents, Attack Vectors, Security Weakness, Technical Impact and Business Impacts of this flaw with the help of simple diagram. Some of the classic examples of security misconfiguration are as given − A site simply does not use SSL for all authenticated pages. This enables an attacker to monitor network traffic and steal the user’s session cookie to hijack the users session or accessing their private data. A site simply does not use SSL for all authenticated pages. This enables an attacker to monitor network traffic and steal the user’s session cookie to hijack the users session or accessing their private data. An application stores the credit card numbers in an encrypted format in a database. Upon retrieval they are decrypted allowing the hacker to perform a SQL injection attack to retrieve all sensitive info in a clear text. This can be avoided by encrypting the credit card numbers using a public key and allowed back-end applications to decrypt them with the private key. An application stores the credit card numbers in an encrypted format in a database. Upon retrieval they are decrypted allowing the hacker to perform a SQL injection attack to retrieve all sensitive info in a clear text. This can be avoided by encrypting the credit card numbers using a public key and allowed back-end applications to decrypt them with the private key. Step 1 − Launch WebGoat and navigate to "Insecure Storage" Section. Snapshot of the same is displayed below. Step 2 − Enter the username and password. It is time to learn different kind of encoding and encryption methodologies that we discussed previously. It is advised not to store sensitive data unnecessarily and should be scraped as soon as possible if it is no more required. It is advised not to store sensitive data unnecessarily and should be scraped as soon as possible if it is no more required. It is important to ensure that we incorporate strong and standard encryption algorithms are used and proper key management is in place. It is important to ensure that we incorporate strong and standard encryption algorithms are used and proper key management is in place. It can also be avoided by disabling autocomplete on forms that collect sensitive data such as password and disable caching for pages that contain sensitive data. It can also be avoided by disabling autocomplete on forms that collect sensitive data such as password and disable caching for pages that contain sensitive data. Most of the web applications verify function level access rights before making that functionality accessible to the user. However, if the same access control checks are not performed on the server, hackers are able to penetrate into the application without proper authorization. Let us understand Threat Agents, Attack Vectors, Security Weakness, Technical Impact and Business Impacts of this flaw with the help of simple diagram. Here is a classic example of Missing Function Level Access Control − The hacker simply forces target URLs. Usually admin access requires authentication, however, if the application access is not verified, then an unauthenticated user can access admin page. ' Below URL might be accessible to an authenticated user http://website.com/app/standarduserpage ' A NON Admin user is able to access admin page without authorization. http://website.com/app/admin_page Step 1 − Let us login as account manager by first going through the list of users and their access privileges. Step 2 − Upon trying various combinations we can find out that Larry has access to resource account manager. The authentication mechanism should deny all access by default, and provide access to specific roles for every function. The authentication mechanism should deny all access by default, and provide access to specific roles for every function. In a workflow based application, verify the users’ state before allowing them to access any resources. In a workflow based application, verify the users’ state before allowing them to access any resources. A CSRF attack forces an authenticated user (victim) to send a forged HTTP request, including the victim's session cookie to a vulnerable web application, which allows the attacker to force the victim's browser to generate request such that the vulnerable app perceives as legitimate requests from the victim. Let us understand Threat Agents, Attack Vectors, Security Weakness, Technical Impact and Business Impacts of this flaw with the help of simple diagram. Here is a classic example of CSRF − Step 1 − Let us say, the vulnerable application sends a state changing request as a plain text without any encryption. http://bankx.com/app?action=transferFund&amount=3500&destinationAccount=4673243243 Step 2 − Now the hacker constructs a request that transfers money from the victim's account to the attacker's account by embedding the request in an image that is stored on various sites under the attacker's control − <img src = "http://bankx.com/app?action=transferFunds&amount=14000&destinationAccount=attackersAcct#" width = "0" height = "0" /> Step 1 − Let us perform a CSRF forgery by embedding a Java script into an image. The snapshot of the problem is listed below. Step 2 − Now we need to mock up the transfer into a 1x1 image and make the victim to click on the same. Step 3 − Upon submitting the message, the message is displayed as highlighted below. Step 4 − Now if the victim clicks the following URL, the transfer is executed, which can be found intercepting the user action using burp suite. We are able to see the transfer by spotting it in Get message as shown below − Step 5 − Now upon clicking refresh, the lesson completion mark is shown. CSRF can be avoided by creating a unique token in a hidden field which would be sent in the body of the HTTP request rather than in an URL, which is more prone to exposure. CSRF can be avoided by creating a unique token in a hidden field which would be sent in the body of the HTTP request rather than in an URL, which is more prone to exposure. Forcing the user to re-authenticate or proving that they are users in order to protect CSRF. For example, CAPTCHA. Forcing the user to re-authenticate or proving that they are users in order to protect CSRF. For example, CAPTCHA. This kind of threat occurs when the components such as libraries and frameworks used within the app almost always execute with full privileges. If a vulnerable component is exploited, it makes the hacker’s job easier to cause a serious data loss or server takeover. Let us understand Threat Agents, Attack Vectors, Security Weakness, Technical Impact and Business Impacts of this flaw with the help of simple diagram. The following examples are of using components with known vulnerabilities − Attackers can invoke any web service with full permission by failing to provide an identity token. Attackers can invoke any web service with full permission by failing to provide an identity token. Remote-code execution with Expression Language injection vulnerability is introduced through the Spring Framework for Java based apps. Remote-code execution with Expression Language injection vulnerability is introduced through the Spring Framework for Java based apps. Identify all components and the versions that are being used in the webapps not just restricted to database/frameworks. Identify all components and the versions that are being used in the webapps not just restricted to database/frameworks. Keep all the components such as public databases, project mailing lists etc. up to date. Keep all the components such as public databases, project mailing lists etc. up to date. Add security wrappers around components that are vulnerable in nature. Add security wrappers around components that are vulnerable in nature. Most web applications on the internet frequently redirect and forward users to other pages or other external websites. However, without validating the credibility of those pages, hackers can redirect victims to phishing or malware sites, or use forwards to access unauthorized pages. Let us understand Threat Agents, Attack Vectors, Security Weakness, Technical Impact and Business Impacts of this flaw with the help of simple diagram. Some classic examples of Unvalidated Redirects and Forwards are as given − Let us say the application has a page - redirect.jsp, which takes a parameter redirectrul. The hacker adds a malicious URL that redirects users which performs phishing/installs malware. Let us say the application has a page - redirect.jsp, which takes a parameter redirectrul. The hacker adds a malicious URL that redirects users which performs phishing/installs malware. http://www.mywebapp.com/redirect.jsp?redirectrul=hacker.com All web application used to forward users to different parts of the site. In order to achieve the same, some pages use a parameter to indicate where the user should be redirected if an operation is successful. The attacker crafts an URL that passes the application's access control check and then forwards the attacker to administrative functionality for which the attacker has not got the access. All web application used to forward users to different parts of the site. In order to achieve the same, some pages use a parameter to indicate where the user should be redirected if an operation is successful. The attacker crafts an URL that passes the application's access control check and then forwards the attacker to administrative functionality for which the attacker has not got the access. http://www.mywebapp.com/checkstatus.jsp?fwd=appadmin.jsp It is better to avoid using redirects and forwards. It is better to avoid using redirects and forwards. If it is unavoidable, then it should be done without involving user parameters in redirecting the destination. If it is unavoidable, then it should be done without involving user parameters in redirecting the destination. Asynchronous Javascript and XML (AJAX) is one of the latest techniques used to develope web application inorder to give a rich user experience. Since it is a new technology, there are many security issues that are yet to be completed established and below are the few security issues in AJAX. The attack surface is more as there are more inputs to be secured. The attack surface is more as there are more inputs to be secured. It also exposes the internal functions of the applications. It also exposes the internal functions of the applications. Failure to protect authentication information and sessions. Failure to protect authentication information and sessions. There is a very narrow line between client-side and server-side, hence there are possibilities of committing security mistakes. There is a very narrow line between client-side and server-side, hence there are possibilities of committing security mistakes. Here is an example for AJAX Security − In 2006, a worm infected yahoo mail service using XSS and AJAX that took advantage of a vulnerability in Yahoo Mail's onload event handling. When an infected email was opened, the worm executed its JavaScript, sending a copy to all the Yahoo contacts of the infected user. Step 1 − We need to try to add more rewards to your allowed set of reward using XML injection. Below is the snapshot of the scenario. Step 2 − Make sure that we intercept both request and response using Burp Suite. Settings of the same as shown below. Step 3 − Enter the account number as given in the scenario. We will be able to get a list of all rewards that we are eligible for. We are eligible for 3 rewards out of 5. Step 4 − Now let us click 'Submit' and see what we get in the response XML. As shown below the three rewards that are we are eligible are passed to us as XML. Step 5 − Now let us edit those XMLs and add the other two rewards as well. Step 6 − Now all the rewards would be displayed to the user for them to select. Select the ones that we added and click 'Submit'. Step 7 − The following message appears saying, "* Congratulations. You have successfully completed this lesson." Client side − Use .innerText instead of .innerHtml. Do not use eval. Do not rely on client logic for security. Avoid writing serialization code. Avoid building XML dynamically. Never transmit secrets to the client. Do not perform encryption in client side code. Do not perform security impacting logic on client side. Server side − Use CSRF protection. Avoid writing serialization code. Services can be called by users directly. Avoid building XML by hand, use the framework. Avoid building JSON by hand, use an existing framework. In modern web-based applications, the usage of web services is inevitable and they are prone for attacks as well. Since the web services request fetch from multiple websites developers have to take few additional measures in order to avoid any kind of penetration by hackers. Step 1 − Navigate to web services area of Webgoat and go to WSDL Scanning. We need to now get credit card details of some other account number. Snapshot of the scenario is as mentioned below. Step 2 − If we select the first name, the 'getFirstName' function call is made through SOAP request xml. Step 3 − By opening the WSDL, we are can see that there is a method to retrieve credit card information as well 'getCreditCard'. Now let us tamper the inputs using Burp suite as shown below − Step 4 − Now let us modify the inputs using Burp suite as shown below − Step 5 − We can get the credit card information of other users. Since SOAP messages are XML-based, all passed credentials have to be converted to text format. Hence one has to be very careful in passing the sensitive information which has to be always encrypted. Since SOAP messages are XML-based, all passed credentials have to be converted to text format. Hence one has to be very careful in passing the sensitive information which has to be always encrypted. Protecting message integrity by implementing the mechanisms like checksum applied to ensure packet's integrity. Protecting message integrity by implementing the mechanisms like checksum applied to ensure packet's integrity. Protecting message confidentiality - Asymmetric encryption is applied to protect the symmetric session keys, which in many implementations are valid for one communication only and are discarded subsequently. Protecting message confidentiality - Asymmetric encryption is applied to protect the symmetric session keys, which in many implementations are valid for one communication only and are discarded subsequently. A buffer overflow arises when a program tries to store more data in a temporary data storage area (buffer) than it was intended to hold. Since buffers are created to contain a finite amount of data, the extra information can overflow into adjacent buffers, thus corrupting the valid data held in them. Here is a classic examples of buffer overflow. It demonstrates a simple buffer overflow that is caused by the first scenario in which relies on external data to control its behavior. There is no way to limit the amount of data that user has entered and the behavior of the program depends on the how many characters the user has put inside. ... char bufr[BUFSIZE]; gets(bufr); ... Step 1 − We need to login with name and room number to get the internet access. Here is the scenario snapshot. Step 2 − We will also enable "Unhide hidden form fields" in Burp Suite as shown below − Step 3 − Now we send an input in name and room number field. We also try and inject a pretty big number in the room number field. Step 4 − The hidden fields are displayed as shown below. We click accept terms. Step 5 − The attack is successful such that as a result of buffer overflow, it started reading the adjacent memory locations and displayed to the user as shown below. Step 6 − Now let us login using the data displayed. After logging, the following message is displayed − Code Reviewing Developer training Compiler tools Developing Safe functions Periodical Scanning Denial of Service (DoS) attack is an attempt by hackers to make a network resource unavailable. It usually interrupts the host, temporary or indefinitely, which is connected to the internet. These attacks typically target services hosted on mission critical web servers such as banks, credit card payment gateways. Unusually slow network performance. Unavailability of a particular web site. Inability to access any web site. Dramatic increase in the number of spam emails received. Long term denial of access to the web or any internet services. Unavailability of a particular website. Step 1 − Launch WebGoat and navigate to 'Denial of Service' section. The snapshot of the scenario is given below. We need to login multiple times there by breaching maximum DB thread pool size. Step 2 − First we need to get the list of valid logins. We use SQL Injection in this case. Step 3 − If the attempt is successful, then it displays all valid credentials to the user. Step 4 − Now login with each one of these user in at least 3 different sessions in order to make the DoS attack successful. As we know that DB connection can handle only two threads, by using all logins it will create three threads which makes the attack successful. Perform thorough input validations. Perform thorough input validations. Avoid highly CPU consuming operations. Avoid highly CPU consuming operations. It is better to separate data disks from system disks. It is better to separate data disks from system disks. Developers often directly use or concatenate potentially vulnerable input with file or assume that input files are genuine. When the data is not checked properly, this can lead to the vulnerable content being processed or invoked by the web server. Some of the classic examples include − Upload .jsp file into web tree. Upload .gif to be resized. Upload huge files. Upload file containing tags. Upload .exe file into web tree. Step 1 − Launch WebGoat and navigate to Malicious file execution section. The snapshot of the scenario is given below − Step 2 − In order to complete this lesson, we need to upload guest.txt in the above said location. Step 3 − Let us create a jsp file such that the guest.txt file is created on executing the jsp. The Naming of the jsp has no role to play in this context as we are executing the content of the jsp file. <HTML> <% java.io.File file = new java.io.File("C:\\Users\\username$\\.extract\\webapps\\WebGoat\\mfe_target\\guest.txt"); file.createNewFile(); %> </HTML> Step 4 − Now upload the jsp file and copy the link location of the same after upload. The upload is expecting an image, but we are uploading a jsp. Step 5 − By navigating to the jsp file, there will not be any message to the user. Step 6 − Now refresh the session where you have uploaded the jsp file and you will get the message saying, "* Congratulations. You have successfully completed the lesson". Secure websites using website permissions. Adopt countermeasures for web application security. Understand the Built-In user and group accounts in IIS 7.0. There are various tools available to perform security testing of an application. There are few tools that can perform end-to-end security testing while some are dedicated to spot a particular type of flaw in the system. Some open source security testing tools are as given − Zed Attack Proxy Provides Automated Scanners and other tools for spotting security flaws. https://www.owasp.org OWASP WebScarab Developed in Java for Analysing Http and Https requests. https://www.owasp.org/index.php OWASP Mantra Supports multi-lingual security testing framework https://www.owasp.org/index.php/OWASP_Mantra_-_Security_Framework Burp Proxy Tool for Intercepting & Modyfying traffic and works with work with custom SSL certificates. https://www.portswigger.net/Burp/ Firefox Tamper Data Use tamperdata to view and modify HTTP/HTTPS headers and post parameters https://addons.mozilla.org/en-US Firefox Web Developer Tools The Web Developer extension adds various web developer tools to the browser. https://addons.mozilla.org/en-US/firefox Cookie Editor Lets user to add, delete, edit, search, protect and block cookies https://chrome.google.com/webstore The following tools can help us spot a particular type of vulnerability in the system − DOMinator Pro − Testing for DOM XSS https://dominator.mindedsecurity.com/ OWASP SQLiX − SQL Injection https://www.owasp.org/index.php Sqlninja − SQL Injection http://sqlninja.sourceforge.net/ SQLInjector − SQL Injection https://sourceforge.net/projects/safe3si/ sqlpowerinjector − SQL Injection http://www.sqlpowerinjector.com/ SSL Digger − Testing SSL https://www.mcafee.com/us/downloads/free-tools THC-Hydra − Brute Force Password https://www.thc.org/thc-hydra/ Brutus − Brute Force Password http://www.hoobie.net/brutus/ Ncat − Brute Force Password https://nmap.org/ncat/ OllyDbg − Testing Buffer Overflow http://www.ollydbg.de/ Spike − Testing Buffer Overflow https://www.immunitysec.com/downloads/SPIKE2.9.tgz Metasploit − Testing Buffer Overflow https://www.metasploit.com/ Here are some of the commercial black box testing tools that help us spot security issues in the applications that we develop. NGSSQuirreL https://www.nccgroup.com/en/our-services IBM AppScan https://www-01.ibm.com/software/awdtools/appscan/ Acunetix Web Vulnerability Scanner https://www.acunetix.com/ NTOSpider https://www.ntobjectives.com/products/ntospider.php SOAP UI https://www.soapui.org/Security/getting-started.html Netsparker https://www.mavitunasecurity.com/netsparker/ HP WebInspect http://www.hpenterprisesecurity.com/products OWASP Orizon https://www.owasp.org/index.php OWASP O2 https://www.owasp.org/index.php/OWASP_O2_Platform SearchDiggity https://www.bishopfox.com/resources/tools FXCOP https://www.owasp.org/index.php/FxCop Splint http://splint.org/ Boon https://www.cs.berkeley.edu/~daw/boon/ W3af http://w3af.org/ FlawFinder https://www.dwheeler.com/flawfinder/ FindBugs http://findbugs.sourceforge.net/ These analyzers examine, detect, and report the weaknesses in the source code, which are prone to vulnerabilities − Parasoft C/C++ test https://www.parasoft.com/cpptest/ HP Fortify http://www.hpenterprisesecurity.com/products Appscan http://www-01.ibm.com/software/rational/products Veracode https://www.veracode.com Armorize CodeSecure http://www.armorize.com/codesecure/ GrammaTech https://www.grammatech.com/ 36 Lectures 5 hours Sharad Kumar 26 Lectures 2.5 hours Harshit Srivastava 47 Lectures 2 hours Dhabaleshwar Das 14 Lectures 1.5 hours Harshit Srivastava 38 Lectures 3 hours Harshit Srivastava 32 Lectures 3 hours Harshit Srivastava Print Add Notes Bookmark this page
[ { "code": null, "e": 2542, "s": 2440, "text": "Security testing is very important to keep the system protected from malicious activities on the web." }, { "code": null, "e": 2826, "s": 2542, "text": "Security testing is a testing technique to determine if an information system protects data and maintains functionality as intended. Security testing does not guarantee complete security of the system, but it is important to include security testing as a part of the testing process." }, { "code": null, "e": 2911, "s": 2826, "text": "Security testing takes the following six measures to provide a secured environment −" }, { "code": null, "e": 3001, "s": 2911, "text": "Confidentiality − It protects against disclosure of information to unintended recipients." }, { "code": null, "e": 3091, "s": 3001, "text": "Confidentiality − It protects against disclosure of information to unintended recipients." }, { "code": null, "e": 3203, "s": 3091, "text": "Integrity − It allows transferring accurate and correct desired information from senders to intended receivers." }, { "code": null, "e": 3315, "s": 3203, "text": "Integrity − It allows transferring accurate and correct desired information from senders to intended receivers." }, { "code": null, "e": 3383, "s": 3315, "text": "Authentication − It verifies and confirms the identity of the user." }, { "code": null, "e": 3451, "s": 3383, "text": "Authentication − It verifies and confirms the identity of the user." }, { "code": null, "e": 3522, "s": 3451, "text": "Authorization − It specifies access rights to the users and resources." }, { "code": null, "e": 3593, "s": 3522, "text": "Authorization − It specifies access rights to the users and resources." }, { "code": null, "e": 3664, "s": 3593, "text": "Availability − It ensures readiness of the information on requirement." }, { "code": null, "e": 3735, "s": 3664, "text": "Availability − It ensures readiness of the information on requirement." }, { "code": null, "e": 3856, "s": 3735, "text": "Non-repudiation − It ensures there is no denial from the sender or the receiver for having sent or received the message." }, { "code": null, "e": 3977, "s": 3856, "text": "Non-repudiation − It ensures there is no denial from the sender or the receiver for having sent or received the message." }, { "code": null, "e": 4199, "s": 3977, "text": "Spotting a security flaw in a web-based application involves complex steps and creative thinking. At times, a simple test can expose the most severe security risk. You can try this very basic test on any web application −" }, { "code": null, "e": 4253, "s": 4199, "text": "Log into the web application using valid credentials." }, { "code": null, "e": 4307, "s": 4253, "text": "Log into the web application using valid credentials." }, { "code": null, "e": 4339, "s": 4307, "text": "Log out of the web application." }, { "code": null, "e": 4371, "s": 4339, "text": "Log out of the web application." }, { "code": null, "e": 4409, "s": 4371, "text": "Click the BACK button of the browser." }, { "code": null, "e": 4447, "s": 4409, "text": "Click the BACK button of the browser." }, { "code": null, "e": 4543, "s": 4447, "text": "Verify if you are asked to log in again or if you are able go back to the logged in page again." }, { "code": null, "e": 4639, "s": 4543, "text": "Verify if you are asked to log in again or if you are able go back to the logged in page again." }, { "code": null, "e": 4891, "s": 4639, "text": "Security testing can be seen as a controlled attack on the system, which uncovers security flaws in a realistic way. Its goal is to evaluate the current status of an IT system. It is also known as penetration test or more popularly as ethical hacking." }, { "code": null, "e": 5238, "s": 4891, "text": "Penetration test is done in phases and here in this chapter, we will discuss the complete process. Proper documentation should be done in each phase so that all the steps necessary to reproduce the attack are available readily. The documentation also serves as the basis for the detailed report customers receive at the end of a penetration test." }, { "code": null, "e": 5284, "s": 5238, "text": "Penetration test includes four major phases −" }, { "code": null, "e": 5298, "s": 5284, "text": "Foot Printing" }, { "code": null, "e": 5307, "s": 5298, "text": "Scanning" }, { "code": null, "e": 5319, "s": 5307, "text": "Enumeration" }, { "code": null, "e": 5332, "s": 5319, "text": "Exploitation" }, { "code": null, "e": 5426, "s": 5332, "text": "These four steps are re-iterated multiple times which goes hand in hand with the normal SDLC." }, { "code": null, "e": 5553, "s": 5426, "text": "Malicious software (malware) is any software that gives partial to full control of the system to the attacker/malware creator." }, { "code": null, "e": 5597, "s": 5553, "text": "Various forms of malware are listed below −" }, { "code": null, "e": 5889, "s": 5597, "text": "Virus − A virus is a program that creates copies of itself and inserts these copies into other computer programs, data files, or into the boot sector of the hard-disk. Upon successful replication, viruses cause harmful activity on infected hosts such as stealing hard-disk space or CPU time." }, { "code": null, "e": 6181, "s": 5889, "text": "Virus − A virus is a program that creates copies of itself and inserts these copies into other computer programs, data files, or into the boot sector of the hard-disk. Upon successful replication, viruses cause harmful activity on infected hosts such as stealing hard-disk space or CPU time." }, { "code": null, "e": 6290, "s": 6181, "text": "Worm − A worm is a type of malware which leaves a copy of itself in the memory of each computer in its path." }, { "code": null, "e": 6399, "s": 6290, "text": "Worm − A worm is a type of malware which leaves a copy of itself in the memory of each computer in its path." }, { "code": null, "e": 6566, "s": 6399, "text": "Trojan − Trojan is a non-self-replicating type of malware that contains malicious code, which upon execution results in loss or theft of data or possible system harm." }, { "code": null, "e": 6733, "s": 6566, "text": "Trojan − Trojan is a non-self-replicating type of malware that contains malicious code, which upon execution results in loss or theft of data or possible system harm." }, { "code": null, "e": 7007, "s": 6733, "text": "Adware − Adware, also known as freeware or pitchware, is a free computer software that contains commercial advertisements of games, desktop toolbars, and utilities. It is a web-based application and it collects web browser data to target advertisements, especially pop-ups." }, { "code": null, "e": 7281, "s": 7007, "text": "Adware − Adware, also known as freeware or pitchware, is a free computer software that contains commercial advertisements of games, desktop toolbars, and utilities. It is a web-based application and it collects web browser data to target advertisements, especially pop-ups." }, { "code": null, "e": 7594, "s": 7281, "text": "Spyware − Spyware is infiltration software that anonymously monitors users which enables a hacker to obtain sensitive information from the user's computer. Spyware exploits users and application vulnerabilities that is quite often attached to free online software downloads or to links that are clicked by users." }, { "code": null, "e": 7907, "s": 7594, "text": "Spyware − Spyware is infiltration software that anonymously monitors users which enables a hacker to obtain sensitive information from the user's computer. Spyware exploits users and application vulnerabilities that is quite often attached to free online software downloads or to links that are clicked by users." }, { "code": null, "e": 8124, "s": 7907, "text": "Rootkit − A rootkit is a software used by a hacker to gain admin level access to a computer/network which is installed through a stolen password or by exploiting a system vulnerability without the victim's knowledge." }, { "code": null, "e": 8341, "s": 8124, "text": "Rootkit − A rootkit is a software used by a hacker to gain admin level access to a computer/network which is installed through a stolen password or by exploiting a system vulnerability without the victim's knowledge." }, { "code": null, "e": 8420, "s": 8341, "text": "The following measures can be taken to avoid presence of malware in a system −" }, { "code": null, "e": 8502, "s": 8420, "text": "Ensure the operating system and applications are up to date with patches/updates." }, { "code": null, "e": 8584, "s": 8502, "text": "Ensure the operating system and applications are up to date with patches/updates." }, { "code": null, "e": 8646, "s": 8584, "text": "Never open strange e-mails, especially ones with attachments." }, { "code": null, "e": 8708, "s": 8646, "text": "Never open strange e-mails, especially ones with attachments." }, { "code": null, "e": 8879, "s": 8708, "text": "When you download from the internet, always check what you install. Do not simply click OK to dismiss pop-up windows. Verify the publisher before you install application." }, { "code": null, "e": 9050, "s": 8879, "text": "When you download from the internet, always check what you install. Do not simply click OK to dismiss pop-up windows. Verify the publisher before you install application." }, { "code": null, "e": 9079, "s": 9050, "text": "Install anti-virus software." }, { "code": null, "e": 9108, "s": 9079, "text": "Install anti-virus software." }, { "code": null, "e": 9169, "s": 9108, "text": "Ensure you scan and update the antivirus programs regularly." }, { "code": null, "e": 9230, "s": 9169, "text": "Ensure you scan and update the antivirus programs regularly." }, { "code": null, "e": 9248, "s": 9230, "text": "Install firewall." }, { "code": null, "e": 9266, "s": 9248, "text": "Install firewall." }, { "code": null, "e": 9345, "s": 9266, "text": "Always enable and use security features provided by browsers and applications." }, { "code": null, "e": 9424, "s": 9345, "text": "Always enable and use security features provided by browsers and applications." }, { "code": null, "e": 9488, "s": 9424, "text": "The following software help remove the malwares from a system −" }, { "code": null, "e": 9518, "s": 9488, "text": "Microsoft Security Essentials" }, { "code": null, "e": 9545, "s": 9518, "text": "Microsoft Windows Defender" }, { "code": null, "e": 9567, "s": 9545, "text": "AVG Internet Security" }, { "code": null, "e": 9593, "s": 9567, "text": "Spybot - Search & Destroy" }, { "code": null, "e": 9630, "s": 9593, "text": "Avast! Home Edition for personal use" }, { "code": null, "e": 9654, "s": 9630, "text": "Panda Internet Security" }, { "code": null, "e": 9686, "s": 9654, "text": "MacScan for Mac OS and Mac OS X" }, { "code": null, "e": 9906, "s": 9686, "text": "Understanding the protocol is very important to get a good grasp on security testing. You will be able to appreciate the importance of the protocol when we intercept the packet data between the webserver and the client." }, { "code": null, "e": 10275, "s": 9906, "text": "The Hypertext Transfer Protocol (HTTP) is an application-level protocol for distributed, collaborative, hypermedia information systems. This is the foundation for data communication for the World Wide Web since 1990. HTTP is a generic and stateless protocol which can be used for other purposes as well using extension of its request methods, error codes, and headers." }, { "code": null, "e": 10630, "s": 10275, "text": "Basically, HTTP is a TCP/IP based communication protocol, which is used to deliver data such as HTML files, image files, query results etc. over the web. It provides a standardized way for computers to communicate with each other. HTTP specification specifies how clients’ requested data are sent to the server, and how servers respond to these requests." }, { "code": null, "e": 10720, "s": 10630, "text": "There are following three basic features which make HTTP a simple yet powerful protocol −" }, { "code": null, "e": 11006, "s": 10720, "text": "HTTP is connectionless − The HTTP client, i.e., the browser initiates an HTTP request. After making a request, the client disconnects from the server and waits for a response. The server processes the request and re-establishes the connection with the client to send the response back." }, { "code": null, "e": 11292, "s": 11006, "text": "HTTP is connectionless − The HTTP client, i.e., the browser initiates an HTTP request. After making a request, the client disconnects from the server and waits for a response. The server processes the request and re-establishes the connection with the client to send the response back." }, { "code": null, "e": 11535, "s": 11292, "text": "HTTP is media independent − Any type of data can be sent by HTTP as long as both the client and server know how to handle the data content. This is required for client as well as server to specify the content type using appropriate MIME-type." }, { "code": null, "e": 11778, "s": 11535, "text": "HTTP is media independent − Any type of data can be sent by HTTP as long as both the client and server know how to handle the data content. This is required for client as well as server to specify the content type using appropriate MIME-type." }, { "code": null, "e": 12156, "s": 11778, "text": "HTTP is stateless − HTTP is a connectionless and this is a direct result that HTTP is a stateless protocol. The server and client are aware of each other only during a current request. Afterwards, both of them forget about each other. Due to this nature of the protocol, neither the client nor the browser can retain information between different requests across the web pages." }, { "code": null, "e": 12534, "s": 12156, "text": "HTTP is stateless − HTTP is a connectionless and this is a direct result that HTTP is a stateless protocol. The server and client are aware of each other only during a current request. Afterwards, both of them forget about each other. Due to this nature of the protocol, neither the client nor the browser can retain information between different requests across the web pages." }, { "code": null, "e": 12684, "s": 12534, "text": "HTTP/1.0 uses a new connection for each request/response exchange whereas HTTP/1.1 connection may be used for one or more request/response exchanges." }, { "code": null, "e": 12792, "s": 12684, "text": "The following diagram shows a very basic architecture of a web application and depicts where HTTP resides −" }, { "code": null, "e": 12989, "s": 12792, "text": "The HTTP protocol is a request/response protocol based on the client/server architecture where web browser, robots, and search engines etc. act as HTTP clients and the web server acts as a server." }, { "code": null, "e": 13238, "s": 12989, "text": "Client − The HTTP client sends a request to the server in the form of a request method, URI, and protocol version, followed by a MIME-like message containing request modifiers, client information, and possible body content over a TCP/IP connection." }, { "code": null, "e": 13487, "s": 13238, "text": "Client − The HTTP client sends a request to the server in the form of a request method, URI, and protocol version, followed by a MIME-like message containing request modifiers, client information, and possible body content over a TCP/IP connection." }, { "code": null, "e": 13738, "s": 13487, "text": "Server − The HTTP server responds with a status line, including the protocol version of the message and a success or error code, followed by a MIME-like message containing server information, entity meta information, and possible entity-body content." }, { "code": null, "e": 13989, "s": 13738, "text": "Server − The HTTP server responds with a status line, including the protocol version of the message and a success or error code, followed by a MIME-like message containing server information, entity meta information, and possible entity-body content." }, { "code": null, "e": 14032, "s": 13989, "text": "HTTP is not a completely secured protocol." }, { "code": null, "e": 14075, "s": 14032, "text": "HTTP is not a completely secured protocol." }, { "code": null, "e": 14128, "s": 14075, "text": "HTTP uses port 80 as default port for communication." }, { "code": null, "e": 14181, "s": 14128, "text": "HTTP uses port 80 as default port for communication." }, { "code": null, "e": 14322, "s": 14181, "text": "HTTP operates at the application Layer. It needs to create multiple connections for data transfer, which increases administration overheads." }, { "code": null, "e": 14463, "s": 14322, "text": "HTTP operates at the application Layer. It needs to create multiple connections for data transfer, which increases administration overheads." }, { "code": null, "e": 14527, "s": 14463, "text": "No encryption/digital certificates are required for using HTTP." }, { "code": null, "e": 14591, "s": 14527, "text": "No encryption/digital certificates are required for using HTTP." }, { "code": null, "e": 14677, "s": 14591, "text": "Inorder to understand the HTTP Protocol indepth, click on each on of the below links." }, { "code": null, "e": 14693, "s": 14677, "text": "HTTP Parameters" }, { "code": null, "e": 14709, "s": 14693, "text": "HTTP Parameters" }, { "code": null, "e": 14723, "s": 14709, "text": "HTTP Messages" }, { "code": null, "e": 14737, "s": 14723, "text": "HTTP Messages" }, { "code": null, "e": 14751, "s": 14737, "text": "HTTP Requests" }, { "code": null, "e": 14765, "s": 14751, "text": "HTTP Requests" }, { "code": null, "e": 14780, "s": 14765, "text": "HTTP Responses" }, { "code": null, "e": 14795, "s": 14780, "text": "HTTP Responses" }, { "code": null, "e": 14808, "s": 14795, "text": "HTTP Methods" }, { "code": null, "e": 14821, "s": 14808, "text": "HTTP Methods" }, { "code": null, "e": 14839, "s": 14821, "text": "HTTP Status Codes" }, { "code": null, "e": 14857, "s": 14839, "text": "HTTP Status Codes" }, { "code": null, "e": 14876, "s": 14857, "text": "HTTP Header Fields" }, { "code": null, "e": 14895, "s": 14876, "text": "HTTP Header Fields" }, { "code": null, "e": 14909, "s": 14895, "text": "HTTP Security" }, { "code": null, "e": 14923, "s": 14909, "text": "HTTP Security" }, { "code": null, "e": 15176, "s": 14923, "text": "HTTPS (Hypertext Transfer Protocol over Secure Socket Layer) or HTTP over SSL is a web protocol developed by Netscape. It is not a protocol but it is just the result of layering the HTTP on top of SSL/TLS (Secure Socket Layer/Transport Layer Security)." }, { "code": null, "e": 15205, "s": 15176, "text": "In short, HTTPS = HTTP + SSL" }, { "code": null, "e": 15495, "s": 15205, "text": "When we browse, we normally send and receive information using HTTP protocol. So this leads anyone to eavesdrop on the conversation between our computer and the web server. Many a times we need to exchange sensitive information which needs to be secured and to prevent unauthorized access." }, { "code": null, "e": 15544, "s": 15495, "text": "Https protocol used in the following scenarios −" }, { "code": null, "e": 15561, "s": 15544, "text": "Banking Websites" }, { "code": null, "e": 15577, "s": 15561, "text": "Payment Gateway" }, { "code": null, "e": 15595, "s": 15577, "text": "Shopping Websites" }, { "code": null, "e": 15611, "s": 15595, "text": "All Login Pages" }, { "code": null, "e": 15622, "s": 15611, "text": "Email Apps" }, { "code": null, "e": 15704, "s": 15622, "text": "Public key and signed certificates are required for the server in HTTPS Protocol." }, { "code": null, "e": 15786, "s": 15704, "text": "Public key and signed certificates are required for the server in HTTPS Protocol." }, { "code": null, "e": 15824, "s": 15786, "text": "Client requests for the https:// page" }, { "code": null, "e": 15862, "s": 15824, "text": "Client requests for the https:// page" }, { "code": null, "e": 16005, "s": 15862, "text": "When using an https connection, the server responds to the initial connection by offering a list of encryption methods the webserver supports." }, { "code": null, "e": 16148, "s": 16005, "text": "When using an https connection, the server responds to the initial connection by offering a list of encryption methods the webserver supports." }, { "code": null, "e": 16283, "s": 16148, "text": "In response, the client selects a connection method, and the client and server exchange certificates to authenticate their identities." }, { "code": null, "e": 16418, "s": 16283, "text": "In response, the client selects a connection method, and the client and server exchange certificates to authenticate their identities." }, { "code": null, "e": 16578, "s": 16418, "text": "After this is done, both webserver and client exchange the encrypted information after ensuring that both are using the same key, and the connection is closed." }, { "code": null, "e": 16738, "s": 16578, "text": "After this is done, both webserver and client exchange the encrypted information after ensuring that both are using the same key, and the connection is closed." }, { "code": null, "e": 16895, "s": 16738, "text": "For hosting https connections, a server must have a public key certificate, which embeds key information with a verification of the key owner's identity. " }, { "code": null, "e": 17052, "s": 16895, "text": "For hosting https connections, a server must have a public key certificate, which embeds key information with a verification of the key owner's identity. " }, { "code": null, "e": 17165, "s": 17052, "text": "Almost all certificates are verified by a third party so that clients are assured that the key is always secure." }, { "code": null, "e": 17278, "s": 17165, "text": "Almost all certificates are verified by a third party so that clients are assured that the key is always secure." }, { "code": null, "e": 17446, "s": 17278, "text": "Encoding is the process of putting a sequence of characters such as letters, numbers and other special characters into a specialized format for efficient transmission." }, { "code": null, "e": 17623, "s": 17446, "text": "Decoding is the process of converting an encoded format back into the original sequence of characters. It is completely different from Encryption which we usually misinterpret." }, { "code": null, "e": 17758, "s": 17623, "text": "Encoding and decoding are used in data communications and storage. Encoding should NOT be used for transporting sensitive information." }, { "code": null, "e": 18020, "s": 17758, "text": "URLs can only be sent over the Internet using the ASCII character-set and there are instances when URL contains special characters apart from ASCII characters, it needs to be encoded. URLs do not contain spaces and are replaced with a plus (+) sign or with %20." }, { "code": null, "e": 18169, "s": 18020, "text": "The Browser (client side) will encode the input according to the character-set used in the web-page and the default character-set in HTML5 is UTF-8." }, { "code": null, "e": 18329, "s": 18169, "text": "Following table shows ASCII symbol of the character and its equal Symbol and finally its replacement which can be used in URL before passing it to the server −" }, { "code": null, "e": 18534, "s": 18329, "text": "Cryptography is the science to encrypt and decrypt data that enables the users to store sensitive information or transmit it across insecure networks so that it can be read only by the intended recipient." }, { "code": null, "e": 18716, "s": 18534, "text": "Data which can be read and understood without any special measures is called plaintext, while the method of disguising plaintext in order to hide its substance is called encryption." }, { "code": null, "e": 18847, "s": 18716, "text": "Encrypted plaintext is known as cipher text and process of reverting the encrypted data back to plain text is known as decryption." }, { "code": null, "e": 18990, "s": 18847, "text": "The science of analyzing and breaking secure communication is known as cryptanalysis. The people who perform the same also known as attackers." }, { "code": null, "e": 19133, "s": 18990, "text": "The science of analyzing and breaking secure communication is known as cryptanalysis. The people who perform the same also known as attackers." }, { "code": null, "e": 19280, "s": 19133, "text": "Cryptography can be either strong or weak and the strength is measured by the time and resources it would require to recover the actual plaintext." }, { "code": null, "e": 19427, "s": 19280, "text": "Cryptography can be either strong or weak and the strength is measured by the time and resources it would require to recover the actual plaintext." }, { "code": null, "e": 19517, "s": 19427, "text": "Hence an appropriate decoding tool is required to decipher the strong encrypted messages." }, { "code": null, "e": 19607, "s": 19517, "text": "Hence an appropriate decoding tool is required to decipher the strong encrypted messages." }, { "code": null, "e": 19767, "s": 19607, "text": "There are some cryptographic techniques available with which even a billion computers doing a billion checks a second, it is not possible to decipher the text." }, { "code": null, "e": 19927, "s": 19767, "text": "There are some cryptographic techniques available with which even a billion computers doing a billion checks a second, it is not possible to decipher the text." }, { "code": null, "e": 20100, "s": 19927, "text": "As the computing power is increasing day by day, one has to make the encryption algorithms very strong in order to protect data and critical information from the attackers." }, { "code": null, "e": 20273, "s": 20100, "text": "As the computing power is increasing day by day, one has to make the encryption algorithms very strong in order to protect data and critical information from the attackers." }, { "code": null, "e": 20469, "s": 20273, "text": "A cryptographic algorithm works in combination with a key (can be a word, number, or phrase) to encrypt the plaintext and the same plaintext encrypts to different cipher text with different keys." }, { "code": null, "e": 20620, "s": 20469, "text": "Hence, the encrypted data is completely dependent couple of parameters such as the strength of the cryptographic algorithm and the secrecy of the key." }, { "code": null, "e": 20866, "s": 20620, "text": "Symmetric Encryption − Conventional cryptography, also known as conventional encryption, is the technique in which only one key is used for both encryption and decryption. For example, DES, Triple DES algorithms, MARS by IBM, RC2, RC4, RC5, RC6." }, { "code": null, "e": 21162, "s": 20866, "text": "Asymmetric Encryption − It is Public key cryptography that uses a pair of keys for encryption: a public key to encrypt data and a private key for decryption. Public key is published to the people while keeping the private key secret. For example, RSA, Digital Signature Algorithm (DSA), Elgamal." }, { "code": null, "e": 21449, "s": 21162, "text": "Hashing − Hashing is ONE-WAY encryption, which creates a scrambled output that cannot be reversed or at least cannot be reversed easily. For example, MD5 algorithm. It is used to create Digital Certificates, Digital signatures, Storage of passwords, Verification of communications, etc." }, { "code": null, "e": 21537, "s": 21449, "text": "Same Origin Policy (SOP) is an important concept in the web application security model." }, { "code": null, "e": 21670, "s": 21537, "text": "As per this policy, it permits scripts running on pages originating from the same site which can be a combination of the following −" }, { "code": null, "e": 21677, "s": 21670, "text": "Domain" }, { "code": null, "e": 21686, "s": 21677, "text": "Protocol" }, { "code": null, "e": 21691, "s": 21686, "text": "Port" }, { "code": null, "e": 21943, "s": 21691, "text": "The reason behind this behavior is security. If you have try.com in one window and gmail.com in another window, then you DO NOT want a script from try.com to access or modify the contents of gmail.com or run actions in context of gmail on your behalf." }, { "code": null, "e": 22068, "s": 21943, "text": "Below are webpages from the same origin. As explained before, the same origin takes domain/protocol/port into consideration." }, { "code": null, "e": 22087, "s": 22068, "text": "http://website.com" }, { "code": null, "e": 22107, "s": 22087, "text": "http://website.com/" }, { "code": null, "e": 22142, "s": 22107, "text": "http://website.com/my/contact.html" }, { "code": null, "e": 22186, "s": 22142, "text": "Below are webpages from a different origin." }, { "code": null, "e": 22224, "s": 22186, "text": "http://www.site.co.uk(another domain)" }, { "code": null, "e": 22257, "s": 22224, "text": "http://site.org (another domain)" }, { "code": null, "e": 22293, "s": 22257, "text": "https://site.com (another protocol)" }, { "code": null, "e": 22329, "s": 22293, "text": "http://site.com:8080 (another port)" }, { "code": null, "e": 22380, "s": 22329, "text": "Internet Explorer has two major exceptions to SOP." }, { "code": null, "e": 22526, "s": 22380, "text": "The first one is related to 'Trusted Zones'. If both domains are in highly trusted zone then the Same Origin policy is not applicable completely." }, { "code": null, "e": 22672, "s": 22526, "text": "The first one is related to 'Trusted Zones'. If both domains are in highly trusted zone then the Same Origin policy is not applicable completely." }, { "code": null, "e": 22894, "s": 22672, "text": "The second exception in IE is related to port. IE does not include port into Same Origin policy, hence the http://website.com and http://wesite.com:4444 are considered from the same origin and no restrictions are applied." }, { "code": null, "e": 23116, "s": 22894, "text": "The second exception in IE is related to port. IE does not include port into Same Origin policy, hence the http://website.com and http://wesite.com:4444 are considered from the same origin and no restrictions are applied." }, { "code": null, "e": 23398, "s": 23116, "text": "A cookie is a small piece of information sent by a web server to store on a web browser so that it can later be read by the browser. This way, the browser remembers some specific personal information. If a Hacker gets hold of the cookie information, it can lead to security issues." }, { "code": null, "e": 23446, "s": 23398, "text": "Here are some important properties of cookies −" }, { "code": null, "e": 23549, "s": 23446, "text": "They are usually small text files, given ID tags that are stored on your computer's browser directory." }, { "code": null, "e": 23652, "s": 23549, "text": "They are usually small text files, given ID tags that are stored on your computer's browser directory." }, { "code": null, "e": 23765, "s": 23652, "text": "They are used by web developers to help users navigate their websites efficiently and perform certain functions." }, { "code": null, "e": 23878, "s": 23765, "text": "They are used by web developers to help users navigate their websites efficiently and perform certain functions." }, { "code": null, "e": 24042, "s": 23878, "text": "When the user browses the same website again, the data stored in the cookie is sent back to the web server to notify the website of the user’s previous activities." }, { "code": null, "e": 24206, "s": 24042, "text": "When the user browses the same website again, the data stored in the cookie is sent back to the web server to notify the website of the user’s previous activities." }, { "code": null, "e": 24308, "s": 24206, "text": "Cookies are unavoidable for websites that have huge databases, need logins, have customizable themes." }, { "code": null, "e": 24410, "s": 24308, "text": "Cookies are unavoidable for websites that have huge databases, need logins, have customizable themes." }, { "code": null, "e": 24458, "s": 24410, "text": "The cookie contains the following information −" }, { "code": null, "e": 24507, "s": 24458, "text": "The name of the server the cookie was sent from." }, { "code": null, "e": 24535, "s": 24507, "text": "The lifetime of the cookie." }, { "code": null, "e": 24589, "s": 24535, "text": "A value - usually a randomly generated unique number." }, { "code": null, "e": 24760, "s": 24589, "text": "Session Cookies − These cookies are temporary which are erased when the user closes the browser. Even if the user logs in again, a new cookie for that session is created." }, { "code": null, "e": 24931, "s": 24760, "text": "Session Cookies − These cookies are temporary which are erased when the user closes the browser. Even if the user logs in again, a new cookie for that session is created." }, { "code": null, "e": 25099, "s": 24931, "text": "Persistent cookies − These cookies remain on the hard disk drive unless user wipes them off or they expire. The Cookie's expiry is dependent on how long they can last." }, { "code": null, "e": 25267, "s": 25099, "text": "Persistent cookies − These cookies remain on the hard disk drive unless user wipes them off or they expire. The Cookie's expiry is dependent on how long they can last." }, { "code": null, "e": 25307, "s": 25267, "text": "Here are the ways to test the cookies −" }, { "code": null, "e": 25608, "s": 25307, "text": "Disabling Cookies − As a tester, we need to verify the access of the website after disabling cookies and to check if the pages are working properly. Navigating to all the pages of the website and watch for app crashes. It is also required to inform the user that cookies are required to use the site." }, { "code": null, "e": 25909, "s": 25608, "text": "Disabling Cookies − As a tester, we need to verify the access of the website after disabling cookies and to check if the pages are working properly. Navigating to all the pages of the website and watch for app crashes. It is also required to inform the user that cookies are required to use the site." }, { "code": null, "e": 26224, "s": 25909, "text": "Corrupting Cookies − Another testing to be performed is by corrupting the cookies. In order to do the same, one has to find the location of the site's cookie and manually edit it with fake / invalid data which can be used access internal information from the domain which in turn can then be used to hack the site." }, { "code": null, "e": 26539, "s": 26224, "text": "Corrupting Cookies − Another testing to be performed is by corrupting the cookies. In order to do the same, one has to find the location of the site's cookie and manually edit it with fake / invalid data which can be used access internal information from the domain which in turn can then be used to hack the site." }, { "code": null, "e": 26637, "s": 26539, "text": "Removing Cookies − Remove all the cookies for the website and check how the website reacts to it." }, { "code": null, "e": 26735, "s": 26637, "text": "Removing Cookies − Remove all the cookies for the website and check how the website reacts to it." }, { "code": null, "e": 26896, "s": 26735, "text": "Cross-Browser Compatibility − It is also important to check that cookies are being written properly on all supported browsers from any page that writes cookies." }, { "code": null, "e": 27057, "s": 26896, "text": "Cross-Browser Compatibility − It is also important to check that cookies are being written properly on all supported browsers from any page that writes cookies." }, { "code": null, "e": 27310, "s": 27057, "text": "Editing Cookies − If the application uses cookies to store login information then as a tester we should try changing the user in the cookie or address bar to another valid user. Editing the cookie should not let you log in to a different users account." }, { "code": null, "e": 27563, "s": 27310, "text": "Editing Cookies − If the application uses cookies to store login information then as a tester we should try changing the user in the cookie or address bar to another valid user. Editing the cookie should not let you log in to a different users account." }, { "code": null, "e": 27747, "s": 27563, "text": "Modern browsers support viewing/editing of the cookies inform within the Browser itself. There are plugins for mozilla/chrome using which we are able to perform the edit successfully." }, { "code": null, "e": 27779, "s": 27747, "text": "Edit cookies plugin for Firefox" }, { "code": null, "e": 27814, "s": 27779, "text": "Edit This cookie plugin for chrome" }, { "code": null, "e": 27863, "s": 27814, "text": "The steps should be performed to Edit a cookie −" }, { "code": null, "e": 27904, "s": 27863, "text": "Download the plugin for Chrome from here" }, { "code": null, "e": 27945, "s": 27904, "text": "Download the plugin for Chrome from here" }, { "code": null, "e": 28043, "s": 27945, "text": "Edit the cookie value just by accessing the 'edit this cookie' plugin from chrome as shown below." }, { "code": null, "e": 28141, "s": 28043, "text": "Edit the cookie value just by accessing the 'edit this cookie' plugin from chrome as shown below." }, { "code": null, "e": 28250, "s": 28141, "text": "There are various methodologies/approaches which we can make use of as a reference for performing an attack." }, { "code": null, "e": 28334, "s": 28250, "text": "One can take into account the following standards while developing an attack model." }, { "code": null, "e": 28540, "s": 28334, "text": "Among the following list, OWASP is the most active and there are a number of contributors. We will focus on OWASP Techniques which each development team takes into consideration before designing a web app." }, { "code": null, "e": 28586, "s": 28540, "text": "PTES − Penetration Testing Execution Standard" }, { "code": null, "e": 28632, "s": 28586, "text": "PTES − Penetration Testing Execution Standard" }, { "code": null, "e": 28689, "s": 28632, "text": "OSSTMM − Open Source Security Testing Methodology Manual" }, { "code": null, "e": 28746, "s": 28689, "text": "OSSTMM − Open Source Security Testing Methodology Manual" }, { "code": null, "e": 28813, "s": 28746, "text": "OWASP Testing Techniques − Open Web Application Security Protocol " }, { "code": null, "e": 28880, "s": 28813, "text": "OWASP Testing Techniques − Open Web Application Security Protocol " }, { "code": null, "e": 29104, "s": 28880, "text": "The Open Web Application Security Protocol team released the top 10 vulnerabilities that are more prevalent in web in the recent years. Below is the list of security flaws that are more prevalent in a web based application." }, { "code": null, "e": 29329, "s": 29104, "text": "In order to understand each one of the techniques, let us work with a sample application. We will perform the attack on 'WebGoat', the J2EE application which is developed explicitly with security flaws for learning purposes." }, { "code": null, "e": 29599, "s": 29329, "text": "The complete details about the webgoat project can be located https://www.owasp.org/index.php/Category:OWASP_WebGoat_Project. To Download the WebGoat Application, Navigate to https://github.com/WebGoat/WebGoat/wiki/Installation-(WebGoat-6.0) and goto downloads section." }, { "code": null, "e": 29843, "s": 29599, "text": "To install the downloaded application, first ensure that you do not have any application running on Port 8080. It can be installed just using a single command - java -jar WebGoat-6.0.1-war-exec.jar. For more details, visit WebGoat Installation" }, { "code": null, "e": 30008, "s": 29843, "text": "Post Installation, we should be able to access the application by navigating to http://localhost:8080/WebGoat/attack and the page would be displayed as shown below." }, { "code": null, "e": 30085, "s": 30008, "text": "We can use the credentials of guest or admin as displayed in the login page." }, { "code": null, "e": 30335, "s": 30085, "text": "In order to intercept the traffic between client (Browser) and Server (System where Webgoat Application is hosted in our case), we need to use a web proxy. We will use Burp Proxy that can be downloaded from https://portswigger.net/burp/download.html" }, { "code": null, "e": 30415, "s": 30335, "text": "It is sufficient if you download the free version of burp suite as shown below." }, { "code": null, "e": 30632, "s": 30415, "text": "Burp Suite is a web proxy which can intercept each packet of information sent and received by the browser and webserver. This helps us to modify the contents before the client sends the information to the Web-Server." }, { "code": null, "e": 30829, "s": 30632, "text": "Step 1 − The App is installed on port 8080 and Burp is installed on port 8181 as shown below. Launch Burp suite and make the following settings in order to bring it up in port 8181 as shown below." }, { "code": null, "e": 31056, "s": 30829, "text": "Step 2 − We should ensure that the Burp is listening to Port#8080 where the application is installed so that Burp suite can intercept the traffic. This settings should be done on the scope tab of the Burp Suite as shown below." }, { "code": null, "e": 31285, "s": 31056, "text": "Step 3 − Then make your browser proxy settings to listen to the port 8181 (Burp Suite port). Thus we have configured the Web proxy to intercept the traffic between the client (browser) and the server (Webserver) as shown below −" }, { "code": null, "e": 31399, "s": 31285, "text": "Step 4 − The snapshot of the configuration is shown below with a help of a simple workflow diagram as shown below" }, { "code": null, "e": 31509, "s": 31399, "text": "Injection technique consists of injecting a SQL query or a command using the input fields of the application." }, { "code": null, "e": 31755, "s": 31509, "text": "A successful SQL injection can read, modify sensitive data from the database, and can also delete data from a database. It also enables the hacker to perform administrative operations on the database such as shutdown the DBMS/dropping databases." }, { "code": null, "e": 31907, "s": 31755, "text": "Let us understand Threat Agents, Attack Vectors, Security Weakness, Technical Impact and Business Impacts of this flaw with the help of simple diagram." }, { "code": null, "e": 32002, "s": 31907, "text": "The application uses untrusted data in the construction of the following vulnerable SQL call −" }, { "code": null, "e": 32089, "s": 32002, "text": "String query = \"SELECT * FROM EMP WHERE EMPID = '\" + request.getParameter(\"id\") + \"'\";" }, { "code": null, "e": 32168, "s": 32089, "text": "Step 1 − Navigate to the SQL Injection area of the application as shown below." }, { "code": null, "e": 32466, "s": 32168, "text": "Step 2 − As given in the exercise, we use String SQL Injection to bypass authentication. Use SQL injection to log in as the boss ('Neville') without using the correct password. Verify that Neville's profile can be viewed and that all functions are available (including Search, Create, and Delete)." }, { "code": null, "e": 32588, "s": 32466, "text": "Step 3 − We will Inject a SQL such that we are able to bypass the password by sending the parameter as 'a' = 'a' or 1 = 1" }, { "code": null, "e": 32681, "s": 32588, "text": "Step 4 − Post Exploitation, we are able to login as Neville who is the Admin as shown below." }, { "code": null, "e": 32942, "s": 32681, "text": "There are plenty of ways to prevent SQL injection. When developers write the code, they should ensure that they handle special characters accordingly. There are cheat sheets/prevention techniques available from OWASP which is definitely a guide for developers." }, { "code": null, "e": 32970, "s": 32942, "text": "Using Parameterized Queries" }, { "code": null, "e": 33003, "s": 32970, "text": "Escaping all User Supplied Input" }, { "code": null, "e": 33061, "s": 33003, "text": "Enable Least Privilege for the database for the end users" }, { "code": null, "e": 33279, "s": 33061, "text": "When authentication functions related to the application are not implemented correctly, it allows hackers to compromise passwords or session ID's or to exploit other implementation flaws using other users credentials." }, { "code": null, "e": 33431, "s": 33279, "text": "Let us understand Threat Agents, Attack Vectors, Security Weakness, Technical Impact and Business Impacts of this flaw with the help of simple diagram." }, { "code": null, "e": 33597, "s": 33431, "text": "An e-commerce application supports URL rewriting, putting session IDs in the URL −\n\nhttp://example.com/sale/saleitems/jsessionid=2P0OC2JSNDLPSKHCJUN2JV/?item=laptop\n" }, { "code": null, "e": 33863, "s": 33597, "text": "An authenticated user of the site forwards the URL to their friends to know about the discounted sales. He e-mails the above link without knowing that the user is also giving away the session IDs. When his friends use the link, they use his session and credit card." }, { "code": null, "e": 34036, "s": 33863, "text": "Step 1 − Login to Webgoat and navigate to 'Session Management Flaws' Section. Let us bypass the authetication by spoofing the cookie. Below is the snapshot of the scenario." }, { "code": null, "e": 34247, "s": 34036, "text": "Step 2 − When we login using the credentials webgoat/webgoat, we find from Burp Suite that the JSESSION ID is C8F3177CCAFF380441ABF71090748F2E while the AuthCookie = 65432ubphcfx upon successful authentication." }, { "code": null, "e": 34455, "s": 34247, "text": "Step 3 − When we login using the credentials aspect/aspect, we find from Burp Suite that the JSESSION ID is C8F3177CCAFF380441ABF71090748F2E while the AuthCookie = 65432udfqtb upon successful authentication." }, { "code": null, "e": 34727, "s": 34455, "text": "Step 4 − Now we need to analyze the AuthCookie Patterns. The first half '65432' is common for both authentications. Hence we are now interested in analyzing the last part of the authcookie values such as - ubphcfx for webgoat user and udfqtb for aspect user respectively." }, { "code": null, "e": 35130, "s": 34727, "text": "Step 5 − If we take a deep look at the AuthCookie values, the last part is having the same length as that of user name. Hence it is evident that the username is used with some encryption method. Upon trial and errors/brute force mechanisms, we find that after reversing the user name, webgoat; we end up with taogbew and then the before alphabet character is what being used as AuthCookie. i.e ubphcfx." }, { "code": null, "e": 35357, "s": 35130, "text": "Step 6 − If we pass this cookie value and let us see what happens. Upon authenticating as user webgoat, change the AuthCookie value to mock the user Alice by finding the AuthCookie for the same by performing step#4 and step#5." }, { "code": null, "e": 35562, "s": 35357, "text": "Develop a strong authentication and session management controls such that it meets all the authentication and session management requirements defined in OWASP's Application Security Verification Standard." }, { "code": null, "e": 35767, "s": 35562, "text": "Develop a strong authentication and session management controls such that it meets all the authentication and session management requirements defined in OWASP's Application Security Verification Standard." }, { "code": null, "e": 35857, "s": 35767, "text": "Developers should ensure that they avoid XSS flaws that can be used to steal session IDs." }, { "code": null, "e": 35947, "s": 35857, "text": "Developers should ensure that they avoid XSS flaws that can be used to steal session IDs." }, { "code": null, "e": 36261, "s": 35947, "text": "Cross-site Scripting (XSS) happens whenever an application takes untrusted data and sends it to the client (browser) without validation. This allows attackers to execute malicious scripts in the victim's browser which can result in user sessions hijack, defacing web sites or redirect the user to malicious sites." }, { "code": null, "e": 36413, "s": 36261, "text": "Let us understand Threat Agents, Attack Vectors, Security Weakness, Technical Impact and Business Impacts of this flaw with the help of simple diagram." }, { "code": null, "e": 36648, "s": 36413, "text": "Stored XSS − Stored XSS also known as persistent XSS occurs when user input is stored on the target server such as database/message forum/comment field etc. Then the victim is able to retrieve the stored data from the web application." }, { "code": null, "e": 36883, "s": 36648, "text": "Stored XSS − Stored XSS also known as persistent XSS occurs when user input is stored on the target server such as database/message forum/comment field etc. Then the victim is able to retrieve the stored data from the web application." }, { "code": null, "e": 37161, "s": 36883, "text": "Reflected XSS − Reflected XSS also known as non-persistent XSS occurs when user input is immediately returned by a web application in an error message/search result or the input provided by the user as part of the request and without permanently storing the user provided data." }, { "code": null, "e": 37439, "s": 37161, "text": "Reflected XSS − Reflected XSS also known as non-persistent XSS occurs when user input is immediately returned by a web application in an error message/search result or the input provided by the user as part of the request and without permanently storing the user provided data." }, { "code": null, "e": 37602, "s": 37439, "text": "DOM Based XSS − DOM Based XSS is a form of XSS when the source of the data is in the DOM, the sink is also in the DOM, and the data flow never leaves the browser." }, { "code": null, "e": 37765, "s": 37602, "text": "DOM Based XSS − DOM Based XSS is a form of XSS when the source of the data is in the DOM, the sink is also in the DOM, and the data flow never leaves the browser." }, { "code": null, "e": 37885, "s": 37765, "text": "The application uses untrusted data in the construction without validation. The special characters ought to be escaped." }, { "code": null, "e": 37930, "s": 37885, "text": "http://www.webpage.org/task/Rule1?query=try\n" }, { "code": null, "e": 37994, "s": 37930, "text": "The attacker modifies the query parameter in their browser to −" }, { "code": null, "e": 38060, "s": 37994, "text": "http://www.webpage.org/task/Rule1?query=<h3>Hello from XSS\"</h3>\n" }, { "code": null, "e": 38236, "s": 38060, "text": "Step 1 − Login to Webgoat and navigate to cross-site scripting (XSS) Section. Let us execute a Stored Cross-site Scripting (XSS) attack. Below is the snapshot of the scenario." }, { "code": null, "e": 38464, "s": 38236, "text": "Step 2 − As per the scenario, let us login as Tom with password 'tom' as mentioned in the scenario itself. Click 'view profile' and get into edit mode. Since tom is the attacker, let us inject Java script into those edit boxes." }, { "code": null, "e": 38504, "s": 38464, "text": "<script> \n alert(\"HACKED\")\n</script> " }, { "code": null, "e": 38636, "s": 38504, "text": "Step 3 − As soon as the update is over, tom receives an alert box with the message \"hacked\" which means that the app is vulnerable." }, { "code": null, "e": 38756, "s": 38636, "text": "Step 4 − Now as per the scenario, we need to login as jerry (HR) and check if jerry is affected by the injected script." }, { "code": null, "e": 38846, "s": 38756, "text": "Step 5 − After logging in as Jerry, select 'Tom' and click 'view profile' as shown below." }, { "code": null, "e": 38936, "s": 38846, "text": "While viewing tom's profile from Jerry's account, he is able to get the same message box." }, { "code": null, "e": 39064, "s": 38936, "text": "Step 6 − This message box is just an example, but the actual attacker can perform much more than just displaying a message box." }, { "code": null, "e": 39231, "s": 39064, "text": "Developers have to ensure that they escape all untrusted data based on the HTML context such as body, attribute, JavaScript, CSS, or URL that the data is placed into." }, { "code": null, "e": 39398, "s": 39231, "text": "Developers have to ensure that they escape all untrusted data based on the HTML context such as body, attribute, JavaScript, CSS, or URL that the data is placed into." }, { "code": null, "e": 39553, "s": 39398, "text": "For those applications that need special characters as input, there should be robust validation mechanisms in place before accepting them as valid inputs." }, { "code": null, "e": 39708, "s": 39553, "text": "For those applications that need special characters as input, there should be robust validation mechanisms in place before accepting them as valid inputs." }, { "code": null, "e": 39987, "s": 39708, "text": "A direct object reference is likely to occur when a developer exposes a reference to an internal implementation object, such as a file, directory, or database key without any validation mechanism which allows attackers to manipulate these references to access unauthorized data." }, { "code": null, "e": 40139, "s": 39987, "text": "Let us understand Threat Agents, Attack Vectors, Security Weakness, Technical Impact and Business Impacts of this flaw with the help of simple diagram." }, { "code": null, "e": 40221, "s": 40139, "text": "The App uses unverified data in a SQL call that is accessing account information." }, { "code": null, "e": 40441, "s": 40221, "text": "String sqlquery = \"SELECT * FROM useraccounts WHERE account = ?\";\nPreparedStatement st = connection.prepareStatement(sqlquery, ??);\nst.setString( 1, request.getParameter(\"acct\"));\nResultSet results = st.executeQuery( );" }, { "code": null, "e": 40519, "s": 40441, "text": "The attacker modifies the query parameter in their browser to point to Admin." }, { "code": null, "e": 40565, "s": 40519, "text": "http://webapp.com/app/accountInfo?acct=admin\n" }, { "code": null, "e": 40768, "s": 40565, "text": "Step 1 − Login to Webgoat and navigate to access control flaws Section. The goal is to retrieve the tomcat-users.xml by navigating to the path where it is located. Below is the snapshot of the scenario." }, { "code": null, "e": 40992, "s": 40768, "text": "Step 2 − The path of the file is displayed in 'the current directory is' field - C:\\Users\\userName$\\.extract\\webapps\\WebGoat\\lesson_plans\\en and we also know that the tomcat-users.xml file is kept under C:\\xampp\\tomcat\\conf" }, { "code": null, "e": 41161, "s": 40992, "text": "Step 3 − We need to traverse all the way out of the current directory and navigate from C:\\ Drive. We can perform the same by intercepting the traffic using Burp Suite." }, { "code": null, "e": 41314, "s": 41161, "text": "Step 4 − If the attempt is successful, it displays the tomcat-users.xml with the message \"Congratulations. You have successfully completed this lesson.\"" }, { "code": null, "e": 41452, "s": 41314, "text": "Developers can use the following resources/points as a guide to prevent insecure direct object reference during development phase itself." }, { "code": null, "e": 41531, "s": 41452, "text": "Developers should use only one user or session for indirect object references." }, { "code": null, "e": 41610, "s": 41531, "text": "Developers should use only one user or session for indirect object references." }, { "code": null, "e": 41718, "s": 41610, "text": "It is also recommended to check the access before using a direct object reference from an untrusted source." }, { "code": null, "e": 41826, "s": 41718, "text": "It is also recommended to check the access before using a direct object reference from an untrusted source." }, { "code": null, "e": 42124, "s": 41826, "text": "Security Misconfiguration arises when Security settings are defined, implemented, and maintained as defaults. Good security requires a secure configuration defined and deployed for the application, web server, database server, and platform. It is equally important to have the software up to date." }, { "code": null, "e": 42190, "s": 42124, "text": "Some classic examples of security misconfiguration are as given −" }, { "code": null, "e": 42492, "s": 42190, "text": "If Directory listing is not disabled on the server and if attacker discovers the same then the attacker can simply list directories to find any file and execute it. It is also possible to get the actual code base which contains all your custom code and then to find a serious flaws in the application." }, { "code": null, "e": 42794, "s": 42492, "text": "If Directory listing is not disabled on the server and if attacker discovers the same then the attacker can simply list directories to find any file and execute it. It is also possible to get the actual code base which contains all your custom code and then to find a serious flaws in the application." }, { "code": null, "e": 43013, "s": 42794, "text": "App server configuration allows stack traces to be returned to users, potentially exposing underlying flaws. Attackers grab those extra information that the error messages provide which is enough for them to penetrate." }, { "code": null, "e": 43232, "s": 43013, "text": "App server configuration allows stack traces to be returned to users, potentially exposing underlying flaws. Attackers grab those extra information that the error messages provide which is enough for them to penetrate." }, { "code": null, "e": 43381, "s": 43232, "text": "App servers usually come with sample apps that are not well secured. If not removed from production server would result in compromising your server." }, { "code": null, "e": 43530, "s": 43381, "text": "App servers usually come with sample apps that are not well secured. If not removed from production server would result in compromising your server." }, { "code": null, "e": 43682, "s": 43530, "text": "Step 1 − Launch Webgoat and navigate to insecure configuration section and let us try to solve that challenge. Snapshot of the same is provided below −" }, { "code": null, "e": 43954, "s": 43682, "text": "Step 2 − We can try out as many options as we can think of. All we need to find the URL of config file and we know that the developers follow kind of naming convention for config files. It can be anything that is listed below. It is usually done by BRUTE force technique." }, { "code": null, "e": 43965, "s": 43954, "text": "web.config" }, { "code": null, "e": 43972, "s": 43965, "text": "config" }, { "code": null, "e": 43987, "s": 43972, "text": "appname.config" }, { "code": null, "e": 43992, "s": 43987, "text": "conf" }, { "code": null, "e": 44158, "s": 43992, "text": "Step 3 − Upon trying various options, we find that 'http://localhost:8080/WebGoat/conf' is successful. The following page is displayed if the attempt is successful −" }, { "code": null, "e": 44339, "s": 44158, "text": "All environments such Development, QA, and production environments should be configured identically using different passwords used in each environment that cannot be hacked easily." }, { "code": null, "e": 44520, "s": 44339, "text": "All environments such Development, QA, and production environments should be configured identically using different passwords used in each environment that cannot be hacked easily." }, { "code": null, "e": 44646, "s": 44520, "text": "Ensure that a strong application architecture is being adopted that provides effective, secure separation between components." }, { "code": null, "e": 44772, "s": 44646, "text": "Ensure that a strong application architecture is being adopted that provides effective, secure separation between components." }, { "code": null, "e": 44882, "s": 44772, "text": "It can also minimize the possibility of this attack by running automated scans and doing audits periodically." }, { "code": null, "e": 44992, "s": 44882, "text": "It can also minimize the possibility of this attack by running automated scans and doing audits periodically." }, { "code": null, "e": 45361, "s": 44992, "text": "As the online applications keep flooding the internet in day by day, not all applications are secured. Many web applications do not properly protect sensitive user data such as credit cards information/Bank account info/authentication credentials. Hackers might end up stealing those weakly protected data to conduct credit card fraud, identity theft, or other crimes." }, { "code": null, "e": 45513, "s": 45361, "text": "Let us understand Threat Agents, Attack Vectors, Security Weakness, Technical Impact and Business Impacts of this flaw with the help of simple diagram." }, { "code": null, "e": 45586, "s": 45513, "text": "Some of the classic examples of security misconfiguration are as given −" }, { "code": null, "e": 45795, "s": 45586, "text": "A site simply does not use SSL for all authenticated pages. This enables an attacker to monitor network traffic and steal the user’s session cookie to hijack the users session or accessing their private data." }, { "code": null, "e": 46004, "s": 45795, "text": "A site simply does not use SSL for all authenticated pages. This enables an attacker to monitor network traffic and steal the user’s session cookie to hijack the users session or accessing their private data." }, { "code": null, "e": 46373, "s": 46004, "text": "An application stores the credit card numbers in an encrypted format in a database. Upon retrieval they are decrypted allowing the hacker to perform a SQL injection attack to retrieve all sensitive info in a clear text. This can be avoided by encrypting the credit card numbers using a public key and allowed back-end applications to decrypt them with the private key." }, { "code": null, "e": 46742, "s": 46373, "text": "An application stores the credit card numbers in an encrypted format in a database. Upon retrieval they are decrypted allowing the hacker to perform a SQL injection attack to retrieve all sensitive info in a clear text. This can be avoided by encrypting the credit card numbers using a public key and allowed back-end applications to decrypt them with the private key." }, { "code": null, "e": 46851, "s": 46742, "text": "Step 1 − Launch WebGoat and navigate to \"Insecure Storage\" Section. Snapshot of the same is displayed below." }, { "code": null, "e": 46999, "s": 46851, "text": "Step 2 − Enter the username and password. It is time to learn different kind of encoding and encryption methodologies that we discussed previously." }, { "code": null, "e": 47124, "s": 46999, "text": "It is advised not to store sensitive data unnecessarily and should be scraped as soon as possible if it is no more required." }, { "code": null, "e": 47249, "s": 47124, "text": "It is advised not to store sensitive data unnecessarily and should be scraped as soon as possible if it is no more required." }, { "code": null, "e": 47385, "s": 47249, "text": "It is important to ensure that we incorporate strong and standard encryption algorithms are used and proper key management is in place." }, { "code": null, "e": 47521, "s": 47385, "text": "It is important to ensure that we incorporate strong and standard encryption algorithms are used and proper key management is in place." }, { "code": null, "e": 47683, "s": 47521, "text": "It can also be avoided by disabling autocomplete on forms that collect sensitive data such as password and disable caching for pages that contain sensitive data." }, { "code": null, "e": 47845, "s": 47683, "text": "It can also be avoided by disabling autocomplete on forms that collect sensitive data such as password and disable caching for pages that contain sensitive data." }, { "code": null, "e": 48124, "s": 47845, "text": "Most of the web applications verify function level access rights before making that functionality accessible to the user. However, if the same access control checks are not performed on the server, hackers are able to penetrate into the application without proper authorization." }, { "code": null, "e": 48276, "s": 48124, "text": "Let us understand Threat Agents, Attack Vectors, Security Weakness, Technical Impact and Business Impacts of this flaw with the help of simple diagram." }, { "code": null, "e": 48345, "s": 48276, "text": "Here is a classic example of Missing Function Level Access Control −" }, { "code": null, "e": 48533, "s": 48345, "text": "The hacker simply forces target URLs. Usually admin access requires authentication, however, if the application access is not verified, then an unauthenticated user can access admin page." }, { "code": null, "e": 48737, "s": 48533, "text": "' Below URL might be accessible to an authenticated user\nhttp://website.com/app/standarduserpage\n\n' A NON Admin user is able to access admin page without authorization.\nhttp://website.com/app/admin_page\n" }, { "code": null, "e": 48848, "s": 48737, "text": "Step 1 − Let us login as account manager by first going through the list of users and their access privileges." }, { "code": null, "e": 48957, "s": 48848, "text": "Step 2 − Upon trying various combinations we can find out that Larry has access to resource account manager." }, { "code": null, "e": 49078, "s": 48957, "text": "The authentication mechanism should deny all access by default, and provide access to specific roles for every function." }, { "code": null, "e": 49199, "s": 49078, "text": "The authentication mechanism should deny all access by default, and provide access to specific roles for every function." }, { "code": null, "e": 49302, "s": 49199, "text": "In a workflow based application, verify the users’ state before allowing them to access any resources." }, { "code": null, "e": 49405, "s": 49302, "text": "In a workflow based application, verify the users’ state before allowing them to access any resources." }, { "code": null, "e": 49714, "s": 49405, "text": "A CSRF attack forces an authenticated user (victim) to send a forged HTTP request, including the victim's session cookie to a vulnerable web application, which allows the attacker to force the victim's browser to generate request such that the vulnerable app perceives as legitimate requests from the victim." }, { "code": null, "e": 49866, "s": 49714, "text": "Let us understand Threat Agents, Attack Vectors, Security Weakness, Technical Impact and Business Impacts of this flaw with the help of simple diagram." }, { "code": null, "e": 49902, "s": 49866, "text": "Here is a classic example of CSRF −" }, { "code": null, "e": 50021, "s": 49902, "text": "Step 1 − Let us say, the vulnerable application sends a state changing request as a plain text without any encryption." }, { "code": null, "e": 50105, "s": 50021, "text": "http://bankx.com/app?action=transferFund&amount=3500&destinationAccount=4673243243\n" }, { "code": null, "e": 50323, "s": 50105, "text": "Step 2 − Now the hacker constructs a request that transfers money from the victim's account to the attacker's account by embedding the request in an image that is stored on various sites under the attacker's control −" }, { "code": null, "e": 50457, "s": 50323, "text": "<img src = \"http://bankx.com/app?action=transferFunds&amount=14000&destinationAccount=attackersAcct#\" \n width = \"0\" height = \"0\" />" }, { "code": null, "e": 50583, "s": 50457, "text": "Step 1 − Let us perform a CSRF forgery by embedding a Java script into an image. The snapshot of the problem is listed below." }, { "code": null, "e": 50687, "s": 50583, "text": "Step 2 − Now we need to mock up the transfer into a 1x1 image and make the victim to click on the same." }, { "code": null, "e": 50772, "s": 50687, "text": "Step 3 − Upon submitting the message, the message is displayed as highlighted below." }, { "code": null, "e": 50996, "s": 50772, "text": "Step 4 − Now if the victim clicks the following URL, the transfer is executed, which can be found intercepting the user action using burp suite. We are able to see the transfer by spotting it in Get message as shown below −" }, { "code": null, "e": 51069, "s": 50996, "text": "Step 5 − Now upon clicking refresh, the lesson completion mark is shown." }, { "code": null, "e": 51242, "s": 51069, "text": "CSRF can be avoided by creating a unique token in a hidden field which would be sent in the body of the HTTP request rather than in an URL, which is more prone to exposure." }, { "code": null, "e": 51415, "s": 51242, "text": "CSRF can be avoided by creating a unique token in a hidden field which would be sent in the body of the HTTP request rather than in an URL, which is more prone to exposure." }, { "code": null, "e": 51530, "s": 51415, "text": "Forcing the user to re-authenticate or proving that they are users in order to protect CSRF. For example, CAPTCHA." }, { "code": null, "e": 51645, "s": 51530, "text": "Forcing the user to re-authenticate or proving that they are users in order to protect CSRF. For example, CAPTCHA." }, { "code": null, "e": 51911, "s": 51645, "text": "This kind of threat occurs when the components such as libraries and frameworks used within the app almost always execute with full privileges. If a vulnerable component is exploited, it makes the hacker’s job easier to cause a serious data loss or server takeover." }, { "code": null, "e": 52063, "s": 51911, "text": "Let us understand Threat Agents, Attack Vectors, Security Weakness, Technical Impact and Business Impacts of this flaw with the help of simple diagram." }, { "code": null, "e": 52139, "s": 52063, "text": "The following examples are of using components with known vulnerabilities −" }, { "code": null, "e": 52238, "s": 52139, "text": "Attackers can invoke any web service with full permission by failing to provide an identity token." }, { "code": null, "e": 52337, "s": 52238, "text": "Attackers can invoke any web service with full permission by failing to provide an identity token." }, { "code": null, "e": 52472, "s": 52337, "text": "Remote-code execution with Expression Language injection vulnerability is introduced through the Spring Framework for Java based apps." }, { "code": null, "e": 52607, "s": 52472, "text": "Remote-code execution with Expression Language injection vulnerability is introduced through the Spring Framework for Java based apps." }, { "code": null, "e": 52727, "s": 52607, "text": "Identify all components and the versions that are being used in the webapps not just restricted to database/frameworks." }, { "code": null, "e": 52847, "s": 52727, "text": "Identify all components and the versions that are being used in the webapps not just restricted to database/frameworks." }, { "code": null, "e": 52936, "s": 52847, "text": "Keep all the components such as public databases, project mailing lists etc. up to date." }, { "code": null, "e": 53025, "s": 52936, "text": "Keep all the components such as public databases, project mailing lists etc. up to date." }, { "code": null, "e": 53096, "s": 53025, "text": "Add security wrappers around components that are vulnerable in nature." }, { "code": null, "e": 53167, "s": 53096, "text": "Add security wrappers around components that are vulnerable in nature." }, { "code": null, "e": 53451, "s": 53167, "text": "Most web applications on the internet frequently redirect and forward users to other pages or other external websites. However, without validating the credibility of those pages, hackers can redirect victims to phishing or malware sites, or use forwards to access unauthorized pages." }, { "code": null, "e": 53603, "s": 53451, "text": "Let us understand Threat Agents, Attack Vectors, Security Weakness, Technical Impact and Business Impacts of this flaw with the help of simple diagram." }, { "code": null, "e": 53678, "s": 53603, "text": "Some classic examples of Unvalidated Redirects and Forwards are as given −" }, { "code": null, "e": 53864, "s": 53678, "text": "Let us say the application has a page - redirect.jsp, which takes a parameter redirectrul. The hacker adds a malicious URL that redirects users which performs phishing/installs malware." }, { "code": null, "e": 54050, "s": 53864, "text": "Let us say the application has a page - redirect.jsp, which takes a parameter redirectrul. The hacker adds a malicious URL that redirects users which performs phishing/installs malware." }, { "code": null, "e": 54111, "s": 54050, "text": "http://www.mywebapp.com/redirect.jsp?redirectrul=hacker.com\n" }, { "code": null, "e": 54509, "s": 54111, "text": "All web application used to forward users to different parts of the site. In order to achieve the same, some pages use a parameter to indicate where the user should be redirected if an operation is successful. The attacker crafts an URL that passes the application's access control check and then forwards the attacker to administrative functionality for which the attacker has not got the access." }, { "code": null, "e": 54907, "s": 54509, "text": "All web application used to forward users to different parts of the site. In order to achieve the same, some pages use a parameter to indicate where the user should be redirected if an operation is successful. The attacker crafts an URL that passes the application's access control check and then forwards the attacker to administrative functionality for which the attacker has not got the access." }, { "code": null, "e": 54965, "s": 54907, "text": "http://www.mywebapp.com/checkstatus.jsp?fwd=appadmin.jsp\n" }, { "code": null, "e": 55017, "s": 54965, "text": "It is better to avoid using redirects and forwards." }, { "code": null, "e": 55069, "s": 55017, "text": "It is better to avoid using redirects and forwards." }, { "code": null, "e": 55180, "s": 55069, "text": "If it is unavoidable, then it should be done without involving user parameters in redirecting the destination." }, { "code": null, "e": 55291, "s": 55180, "text": "If it is unavoidable, then it should be done without involving user parameters in redirecting the destination." }, { "code": null, "e": 55584, "s": 55291, "text": "Asynchronous Javascript and XML (AJAX) is one of the latest techniques used to develope web application inorder to give a rich user experience. Since it is a new technology, there are many security issues that are yet to be completed established and below are the few security issues in AJAX." }, { "code": null, "e": 55651, "s": 55584, "text": "The attack surface is more as there are more inputs to be secured." }, { "code": null, "e": 55718, "s": 55651, "text": "The attack surface is more as there are more inputs to be secured." }, { "code": null, "e": 55778, "s": 55718, "text": "It also exposes the internal functions of the applications." }, { "code": null, "e": 55838, "s": 55778, "text": "It also exposes the internal functions of the applications." }, { "code": null, "e": 55898, "s": 55838, "text": "Failure to protect authentication information and sessions." }, { "code": null, "e": 55958, "s": 55898, "text": "Failure to protect authentication information and sessions." }, { "code": null, "e": 56086, "s": 55958, "text": "There is a very narrow line between client-side and server-side, hence there are possibilities of committing security mistakes." }, { "code": null, "e": 56214, "s": 56086, "text": "There is a very narrow line between client-side and server-side, hence there are possibilities of committing security mistakes." }, { "code": null, "e": 56253, "s": 56214, "text": "Here is an example for AJAX Security −" }, { "code": null, "e": 56526, "s": 56253, "text": "In 2006, a worm infected yahoo mail service using XSS and AJAX that took advantage of a vulnerability in Yahoo Mail's onload event handling. When an infected email was opened, the worm executed its JavaScript, sending a copy to all the Yahoo contacts of the infected user." }, { "code": null, "e": 56660, "s": 56526, "text": "Step 1 − We need to try to add more rewards to your allowed set of reward using XML injection. Below is the snapshot of the scenario." }, { "code": null, "e": 56778, "s": 56660, "text": "Step 2 − Make sure that we intercept both request and response using Burp Suite. Settings of the same as shown below." }, { "code": null, "e": 56949, "s": 56778, "text": "Step 3 − Enter the account number as given in the scenario. We will be able to get a list of all rewards that we are eligible for. We are eligible for 3 rewards out of 5." }, { "code": null, "e": 57108, "s": 56949, "text": "Step 4 − Now let us click 'Submit' and see what we get in the response XML. As shown below the three rewards that are we are eligible are passed to us as XML." }, { "code": null, "e": 57183, "s": 57108, "text": "Step 5 − Now let us edit those XMLs and add the other two rewards as well." }, { "code": null, "e": 57313, "s": 57183, "text": "Step 6 − Now all the rewards would be displayed to the user for them to select. Select the ones that we added and click 'Submit'." }, { "code": null, "e": 57426, "s": 57313, "text": "Step 7 − The following message appears saying, \"* Congratulations. You have successfully completed this lesson.\"" }, { "code": null, "e": 57440, "s": 57426, "text": "Client side −" }, { "code": null, "e": 57478, "s": 57440, "text": "Use .innerText instead of .innerHtml." }, { "code": null, "e": 57495, "s": 57478, "text": "Do not use eval." }, { "code": null, "e": 57537, "s": 57495, "text": "Do not rely on client logic for security." }, { "code": null, "e": 57571, "s": 57537, "text": "Avoid writing serialization code." }, { "code": null, "e": 57603, "s": 57571, "text": "Avoid building XML dynamically." }, { "code": null, "e": 57641, "s": 57603, "text": "Never transmit secrets to the client." }, { "code": null, "e": 57688, "s": 57641, "text": "Do not perform encryption in client side code." }, { "code": null, "e": 57744, "s": 57688, "text": "Do not perform security impacting logic on client side." }, { "code": null, "e": 57758, "s": 57744, "text": "Server side −" }, { "code": null, "e": 57779, "s": 57758, "text": "Use CSRF protection." }, { "code": null, "e": 57813, "s": 57779, "text": "Avoid writing serialization code." }, { "code": null, "e": 57855, "s": 57813, "text": "Services can be called by users directly." }, { "code": null, "e": 57902, "s": 57855, "text": "Avoid building XML by hand, use the framework." }, { "code": null, "e": 57958, "s": 57902, "text": "Avoid building JSON by hand, use an existing framework." }, { "code": null, "e": 58234, "s": 57958, "text": "In modern web-based applications, the usage of web services is inevitable and they are prone for attacks as well. Since the web services request fetch from multiple websites developers have to take few additional measures in order to avoid any kind of penetration by hackers." }, { "code": null, "e": 58426, "s": 58234, "text": "Step 1 − Navigate to web services area of Webgoat and go to WSDL Scanning. We need to now get credit card details of some other account number. Snapshot of the scenario is as mentioned below." }, { "code": null, "e": 58531, "s": 58426, "text": "Step 2 − If we select the first name, the 'getFirstName' function call is made through SOAP request xml." }, { "code": null, "e": 58723, "s": 58531, "text": "Step 3 − By opening the WSDL, we are can see that there is a method to retrieve credit card information as well 'getCreditCard'. Now let us tamper the inputs using Burp suite as shown below −" }, { "code": null, "e": 58795, "s": 58723, "text": "Step 4 − Now let us modify the inputs using Burp suite as shown below −" }, { "code": null, "e": 58859, "s": 58795, "text": "Step 5 − We can get the credit card information of other users." }, { "code": null, "e": 59058, "s": 58859, "text": "Since SOAP messages are XML-based, all passed credentials have to be converted to text format. Hence one has to be very careful in passing the sensitive information which has to be always encrypted." }, { "code": null, "e": 59257, "s": 59058, "text": "Since SOAP messages are XML-based, all passed credentials have to be converted to text format. Hence one has to be very careful in passing the sensitive information which has to be always encrypted." }, { "code": null, "e": 59369, "s": 59257, "text": "Protecting message integrity by implementing the mechanisms like checksum applied to ensure packet's integrity." }, { "code": null, "e": 59481, "s": 59369, "text": "Protecting message integrity by implementing the mechanisms like checksum applied to ensure packet's integrity." }, { "code": null, "e": 59689, "s": 59481, "text": "Protecting message confidentiality - Asymmetric encryption is applied to protect the symmetric session keys, which in many implementations are valid for one communication only and are discarded subsequently." }, { "code": null, "e": 59897, "s": 59689, "text": "Protecting message confidentiality - Asymmetric encryption is applied to protect the symmetric session keys, which in many implementations are valid for one communication only and are discarded subsequently." }, { "code": null, "e": 60199, "s": 59897, "text": "A buffer overflow arises when a program tries to store more data in a temporary data storage area (buffer) than it was intended to hold. Since buffers are created to contain a finite amount of data, the extra information can overflow into adjacent buffers, thus corrupting the valid data held in them." }, { "code": null, "e": 60540, "s": 60199, "text": "Here is a classic examples of buffer overflow. It demonstrates a simple buffer overflow that is caused by the first scenario in which relies on external data to control its behavior. There is no way to limit the amount of data that user has entered and the behavior of the program depends on the how many characters the user has put inside." }, { "code": null, "e": 60594, "s": 60540, "text": " ...\n char bufr[BUFSIZE]; \n gets(bufr);\n ...\n" }, { "code": null, "e": 60705, "s": 60594, "text": "Step 1 − We need to login with name and room number to get the internet access. Here is the scenario snapshot." }, { "code": null, "e": 60793, "s": 60705, "text": "Step 2 − We will also enable \"Unhide hidden form fields\" in Burp Suite as shown below −" }, { "code": null, "e": 60923, "s": 60793, "text": "Step 3 − Now we send an input in name and room number field. We also try and inject a pretty big number in the room number field." }, { "code": null, "e": 61003, "s": 60923, "text": "Step 4 − The hidden fields are displayed as shown below. We click accept terms." }, { "code": null, "e": 61170, "s": 61003, "text": "Step 5 − The attack is successful such that as a result of buffer overflow, it started reading the adjacent memory locations and displayed to the user as shown below." }, { "code": null, "e": 61274, "s": 61170, "text": "Step 6 − Now let us login using the data displayed. After logging, the following message is displayed −" }, { "code": null, "e": 61289, "s": 61274, "text": "Code Reviewing" }, { "code": null, "e": 61308, "s": 61289, "text": "Developer training" }, { "code": null, "e": 61323, "s": 61308, "text": "Compiler tools" }, { "code": null, "e": 61349, "s": 61323, "text": "Developing Safe functions" }, { "code": null, "e": 61369, "s": 61349, "text": "Periodical Scanning" }, { "code": null, "e": 61684, "s": 61369, "text": "Denial of Service (DoS) attack is an attempt by hackers to make a network resource unavailable. It usually interrupts the host, temporary or indefinitely, which is connected to the internet. These attacks typically target services hosted on mission critical web servers such as banks, credit card payment gateways." }, { "code": null, "e": 61720, "s": 61684, "text": "Unusually slow network performance." }, { "code": null, "e": 61761, "s": 61720, "text": "Unavailability of a particular web site." }, { "code": null, "e": 61795, "s": 61761, "text": "Inability to access any web site." }, { "code": null, "e": 61852, "s": 61795, "text": "Dramatic increase in the number of spam emails received." }, { "code": null, "e": 61916, "s": 61852, "text": "Long term denial of access to the web or any internet services." }, { "code": null, "e": 61956, "s": 61916, "text": "Unavailability of a particular website." }, { "code": null, "e": 62150, "s": 61956, "text": "Step 1 − Launch WebGoat and navigate to 'Denial of Service' section. The snapshot of the scenario is given below. We need to login multiple times there by breaching maximum DB thread pool size." }, { "code": null, "e": 62241, "s": 62150, "text": "Step 2 − First we need to get the list of valid logins. We use SQL Injection in this case." }, { "code": null, "e": 62332, "s": 62241, "text": "Step 3 − If the attempt is successful, then it displays all valid credentials to the user." }, { "code": null, "e": 62599, "s": 62332, "text": "Step 4 − Now login with each one of these user in at least 3 different sessions in order to make the DoS attack successful. As we know that DB connection can handle only two threads, by using all logins it will create three threads which makes the attack successful." }, { "code": null, "e": 62635, "s": 62599, "text": "Perform thorough input validations." }, { "code": null, "e": 62671, "s": 62635, "text": "Perform thorough input validations." }, { "code": null, "e": 62710, "s": 62671, "text": "Avoid highly CPU consuming operations." }, { "code": null, "e": 62749, "s": 62710, "text": "Avoid highly CPU consuming operations." }, { "code": null, "e": 62804, "s": 62749, "text": "It is better to separate data disks from system disks." }, { "code": null, "e": 62859, "s": 62804, "text": "It is better to separate data disks from system disks." }, { "code": null, "e": 63108, "s": 62859, "text": "Developers often directly use or concatenate potentially vulnerable input with file or assume that input files are genuine. When the data is not checked properly, this can lead to the vulnerable content being processed or invoked by the web server." }, { "code": null, "e": 63147, "s": 63108, "text": "Some of the classic examples include −" }, { "code": null, "e": 63179, "s": 63147, "text": "Upload .jsp file into web tree." }, { "code": null, "e": 63206, "s": 63179, "text": "Upload .gif to be resized." }, { "code": null, "e": 63225, "s": 63206, "text": "Upload huge files." }, { "code": null, "e": 63254, "s": 63225, "text": "Upload file containing tags." }, { "code": null, "e": 63286, "s": 63254, "text": "Upload .exe file into web tree." }, { "code": null, "e": 63406, "s": 63286, "text": "Step 1 − Launch WebGoat and navigate to Malicious file execution section. The snapshot of the scenario is given below −" }, { "code": null, "e": 63505, "s": 63406, "text": "Step 2 − In order to complete this lesson, we need to upload guest.txt in the above said location." }, { "code": null, "e": 63708, "s": 63505, "text": "Step 3 − Let us create a jsp file such that the guest.txt file is created on executing the jsp. The Naming of the jsp has no role to play in this context as we are executing the content of the jsp file." }, { "code": null, "e": 63883, "s": 63708, "text": "<HTML> \n <% java.io.File file = new \n java.io.File(\"C:\\\\Users\\\\username$\\\\.extract\\\\webapps\\\\WebGoat\\\\mfe_target\\\\guest.txt\"); \n file.createNewFile(); %> \n</HTML>" }, { "code": null, "e": 64031, "s": 63883, "text": "Step 4 − Now upload the jsp file and copy the link location of the same after upload. The upload is expecting an image, but we are uploading a jsp." }, { "code": null, "e": 64114, "s": 64031, "text": "Step 5 − By navigating to the jsp file, there will not be any message to the user." }, { "code": null, "e": 64286, "s": 64114, "text": "Step 6 − Now refresh the session where you have uploaded the jsp file and you will get the message saying, \"* Congratulations. You have successfully completed the lesson\"." }, { "code": null, "e": 64329, "s": 64286, "text": "Secure websites using website permissions." }, { "code": null, "e": 64381, "s": 64329, "text": "Adopt countermeasures for web application security." }, { "code": null, "e": 64441, "s": 64381, "text": "Understand the Built-In user and group accounts in IIS 7.0." }, { "code": null, "e": 64661, "s": 64441, "text": "There are various tools available to perform security testing of an application. There are few tools that can perform end-to-end security testing while some are dedicated to spot a particular type of flaw in the system." }, { "code": null, "e": 64716, "s": 64661, "text": "Some open source security testing tools are as given −" }, { "code": null, "e": 64733, "s": 64716, "text": "Zed Attack Proxy" }, { "code": null, "e": 64806, "s": 64733, "text": "Provides Automated Scanners and other tools for spotting security flaws." }, { "code": null, "e": 64828, "s": 64806, "text": "https://www.owasp.org" }, { "code": null, "e": 64844, "s": 64828, "text": "OWASP WebScarab" }, { "code": null, "e": 64901, "s": 64844, "text": "Developed in Java for Analysing Http and Https requests." }, { "code": null, "e": 64933, "s": 64901, "text": "https://www.owasp.org/index.php" }, { "code": null, "e": 64946, "s": 64933, "text": "OWASP Mantra" }, { "code": null, "e": 64996, "s": 64946, "text": "Supports multi-lingual security testing framework" }, { "code": null, "e": 65062, "s": 64996, "text": "https://www.owasp.org/index.php/OWASP_Mantra_-_Security_Framework" }, { "code": null, "e": 65073, "s": 65062, "text": "Burp Proxy" }, { "code": null, "e": 65165, "s": 65073, "text": "Tool for Intercepting & Modyfying traffic and works with work with custom SSL certificates." }, { "code": null, "e": 65199, "s": 65165, "text": "https://www.portswigger.net/Burp/" }, { "code": null, "e": 65219, "s": 65199, "text": "Firefox Tamper Data" }, { "code": null, "e": 65292, "s": 65219, "text": "Use tamperdata to view and modify HTTP/HTTPS headers and post parameters" }, { "code": null, "e": 65325, "s": 65292, "text": "https://addons.mozilla.org/en-US" }, { "code": null, "e": 65353, "s": 65325, "text": "Firefox Web Developer Tools" }, { "code": null, "e": 65430, "s": 65353, "text": "The Web Developer extension adds various web developer tools to the browser." }, { "code": null, "e": 65472, "s": 65430, "text": " https://addons.mozilla.org/en-US/firefox" }, { "code": null, "e": 65486, "s": 65472, "text": "Cookie Editor" }, { "code": null, "e": 65552, "s": 65486, "text": "Lets user to add, delete, edit, search, protect and block cookies" }, { "code": null, "e": 65588, "s": 65552, "text": " https://chrome.google.com/webstore" }, { "code": null, "e": 65676, "s": 65588, "text": "The following tools can help us spot a particular type of vulnerability in the system −" }, { "code": null, "e": 65712, "s": 65676, "text": "DOMinator Pro − Testing for DOM XSS" }, { "code": null, "e": 65750, "s": 65712, "text": "https://dominator.mindedsecurity.com/" }, { "code": null, "e": 65778, "s": 65750, "text": "OWASP SQLiX − SQL Injection" }, { "code": null, "e": 65810, "s": 65778, "text": "https://www.owasp.org/index.php" }, { "code": null, "e": 65835, "s": 65810, "text": "Sqlninja − SQL Injection" }, { "code": null, "e": 65868, "s": 65835, "text": "http://sqlninja.sourceforge.net/" }, { "code": null, "e": 65896, "s": 65868, "text": "SQLInjector − SQL Injection" }, { "code": null, "e": 65938, "s": 65896, "text": "https://sourceforge.net/projects/safe3si/" }, { "code": null, "e": 65971, "s": 65938, "text": "sqlpowerinjector − SQL Injection" }, { "code": null, "e": 66004, "s": 65971, "text": "http://www.sqlpowerinjector.com/" }, { "code": null, "e": 66029, "s": 66004, "text": "SSL Digger − Testing SSL" }, { "code": null, "e": 66077, "s": 66029, "text": " https://www.mcafee.com/us/downloads/free-tools" }, { "code": null, "e": 66110, "s": 66077, "text": "THC-Hydra − Brute Force Password" }, { "code": null, "e": 66141, "s": 66110, "text": "https://www.thc.org/thc-hydra/" }, { "code": null, "e": 66171, "s": 66141, "text": "Brutus − Brute Force Password" }, { "code": null, "e": 66201, "s": 66171, "text": "http://www.hoobie.net/brutus/" }, { "code": null, "e": 66229, "s": 66201, "text": "Ncat − Brute Force Password" }, { "code": null, "e": 66252, "s": 66229, "text": "https://nmap.org/ncat/" }, { "code": null, "e": 66286, "s": 66252, "text": "OllyDbg − Testing Buffer Overflow" }, { "code": null, "e": 66309, "s": 66286, "text": "http://www.ollydbg.de/" }, { "code": null, "e": 66341, "s": 66309, "text": "Spike − Testing Buffer Overflow" }, { "code": null, "e": 66392, "s": 66341, "text": "https://www.immunitysec.com/downloads/SPIKE2.9.tgz" }, { "code": null, "e": 66429, "s": 66392, "text": "Metasploit − Testing Buffer Overflow" }, { "code": null, "e": 66457, "s": 66429, "text": "https://www.metasploit.com/" }, { "code": null, "e": 66584, "s": 66457, "text": "Here are some of the commercial black box testing tools that help us spot security issues in the applications that we develop." }, { "code": null, "e": 66596, "s": 66584, "text": "NGSSQuirreL" }, { "code": null, "e": 66637, "s": 66596, "text": "https://www.nccgroup.com/en/our-services" }, { "code": null, "e": 66649, "s": 66637, "text": "IBM AppScan" }, { "code": null, "e": 66699, "s": 66649, "text": "https://www-01.ibm.com/software/awdtools/appscan/" }, { "code": null, "e": 66734, "s": 66699, "text": "Acunetix Web Vulnerability Scanner" }, { "code": null, "e": 66760, "s": 66734, "text": "https://www.acunetix.com/" }, { "code": null, "e": 66770, "s": 66760, "text": "NTOSpider" }, { "code": null, "e": 66822, "s": 66770, "text": "https://www.ntobjectives.com/products/ntospider.php" }, { "code": null, "e": 66830, "s": 66822, "text": "SOAP UI" }, { "code": null, "e": 66883, "s": 66830, "text": "https://www.soapui.org/Security/getting-started.html" }, { "code": null, "e": 66894, "s": 66883, "text": "Netsparker" }, { "code": null, "e": 66939, "s": 66894, "text": "https://www.mavitunasecurity.com/netsparker/" }, { "code": null, "e": 66953, "s": 66939, "text": "HP WebInspect" }, { "code": null, "e": 66999, "s": 66953, "text": " http://www.hpenterprisesecurity.com/products" }, { "code": null, "e": 67012, "s": 66999, "text": "OWASP Orizon" }, { "code": null, "e": 67044, "s": 67012, "text": "https://www.owasp.org/index.php" }, { "code": null, "e": 67053, "s": 67044, "text": "OWASP O2" }, { "code": null, "e": 67103, "s": 67053, "text": "https://www.owasp.org/index.php/OWASP_O2_Platform" }, { "code": null, "e": 67117, "s": 67103, "text": "SearchDiggity" }, { "code": null, "e": 67159, "s": 67117, "text": "https://www.bishopfox.com/resources/tools" }, { "code": null, "e": 67165, "s": 67159, "text": "FXCOP" }, { "code": null, "e": 67203, "s": 67165, "text": "https://www.owasp.org/index.php/FxCop" }, { "code": null, "e": 67210, "s": 67203, "text": "Splint" }, { "code": null, "e": 67231, "s": 67210, "text": "http://splint.org/ " }, { "code": null, "e": 67236, "s": 67231, "text": "Boon" }, { "code": null, "e": 67275, "s": 67236, "text": "https://www.cs.berkeley.edu/~daw/boon/" }, { "code": null, "e": 67280, "s": 67275, "text": "W3af" }, { "code": null, "e": 67298, "s": 67280, "text": "http://w3af.org/ " }, { "code": null, "e": 67309, "s": 67298, "text": "FlawFinder" }, { "code": null, "e": 67346, "s": 67309, "text": "https://www.dwheeler.com/flawfinder/" }, { "code": null, "e": 67355, "s": 67346, "text": "FindBugs" }, { "code": null, "e": 67388, "s": 67355, "text": "http://findbugs.sourceforge.net/" }, { "code": null, "e": 67504, "s": 67388, "text": "These analyzers examine, detect, and report the weaknesses in the source code, which are prone to vulnerabilities −" }, { "code": null, "e": 67524, "s": 67504, "text": "Parasoft C/C++ test" }, { "code": null, "e": 67558, "s": 67524, "text": "https://www.parasoft.com/cpptest/" }, { "code": null, "e": 67569, "s": 67558, "text": "HP Fortify" }, { "code": null, "e": 67614, "s": 67569, "text": "http://www.hpenterprisesecurity.com/products" }, { "code": null, "e": 67622, "s": 67614, "text": "Appscan" }, { "code": null, "e": 67672, "s": 67622, "text": " http://www-01.ibm.com/software/rational/products" }, { "code": null, "e": 67681, "s": 67672, "text": "Veracode" }, { "code": null, "e": 67706, "s": 67681, "text": "https://www.veracode.com" }, { "code": null, "e": 67726, "s": 67706, "text": "Armorize CodeSecure" }, { "code": null, "e": 67763, "s": 67726, "text": " http://www.armorize.com/codesecure/" }, { "code": null, "e": 67774, "s": 67763, "text": "GrammaTech" }, { "code": null, "e": 67802, "s": 67774, "text": "https://www.grammatech.com/" }, { "code": null, "e": 67835, "s": 67802, "text": "\n 36 Lectures \n 5 hours \n" }, { "code": null, "e": 67849, "s": 67835, "text": " Sharad Kumar" }, { "code": null, "e": 67884, "s": 67849, "text": "\n 26 Lectures \n 2.5 hours \n" }, { "code": null, "e": 67904, "s": 67884, "text": " Harshit Srivastava" }, { "code": null, "e": 67937, "s": 67904, "text": "\n 47 Lectures \n 2 hours \n" }, { "code": null, "e": 67955, "s": 67937, "text": " Dhabaleshwar Das" }, { "code": null, "e": 67990, "s": 67955, "text": "\n 14 Lectures \n 1.5 hours \n" }, { "code": null, "e": 68010, "s": 67990, "text": " Harshit Srivastava" }, { "code": null, "e": 68043, "s": 68010, "text": "\n 38 Lectures \n 3 hours \n" }, { "code": null, "e": 68063, "s": 68043, "text": " Harshit Srivastava" }, { "code": null, "e": 68096, "s": 68063, "text": "\n 32 Lectures \n 3 hours \n" }, { "code": null, "e": 68116, "s": 68096, "text": " Harshit Srivastava" }, { "code": null, "e": 68123, "s": 68116, "text": " Print" }, { "code": null, "e": 68134, "s": 68123, "text": " Add Notes" } ]
Have you tried Pylance for VS Code? If not, here’s why you should. | by SJ Porter | Towards Data Science
If you work with Python and Visual Studio Code, go ahead and do yourself a favor: download the Pylance extension (preview) and try it out for yourself. Pylance is an extension for Visual Studio Code. More specifically, Pylance is a Python language server — this means it offers enhancements to IntelliSense, syntax highlighting, package import resolution, and a myriad of other features for an improved development experience in the Python language. You can find the full list of features here. To keep things simple, I’m going to focus on the three most useful features based on my experience with the extension thus far. In Python, understanding how to correctly import dependencies from both internal and external modules is a challenge for newbies and professionals alike. The Pylance extension offers a feature which automatically adds imports to the top of your Python files when you reference a dependency in your environment. It will also show a lightbulb icon with suggestions to add or remove imports depending on the scenario. It’s worth mentioning that you need to have the modules you’re referencing installed in your Python environment for this to work. Pylance’s semantic highlighting means that classes, functions, properties, and other Python object types are colored (i.e. highlighted) on the screen in a much more intuitive and readable fashion. It’s much easier to demonstrate this visually than to attempt to describe it, so here are some screenshots... Type hinting, or the practice of specifying expected data types for variables/functions/classes/etc., is fairly new to Python. Python does not enforce type hinting, so at this point it’s essentially just a best practice for documentation. However, with Pylance, enabling the type checking setting (see below) will help you understand if your code violates any documented type hints. There are two modes for type checking, basic and strict (configured in preferences). At this time I would recommend sticking to the basic setting. { "python.analysis.typeCheckingMode": "basic"} The Pylance extension for Visual Studio Code is still in preview. There’s more work to be done to improve performance, expand upon the documentation, and resolve some bugs. However, it’s already a fantastic extension in my experience. I certainly don’t want to go back to the default language server for Python after enabling Pylance. I recommend you try the extension out for yourself and feel free to leave a comment with your thoughts!
[ { "code": null, "e": 323, "s": 171, "text": "If you work with Python and Visual Studio Code, go ahead and do yourself a favor: download the Pylance extension (preview) and try it out for yourself." }, { "code": null, "e": 621, "s": 323, "text": "Pylance is an extension for Visual Studio Code. More specifically, Pylance is a Python language server — this means it offers enhancements to IntelliSense, syntax highlighting, package import resolution, and a myriad of other features for an improved development experience in the Python language." }, { "code": null, "e": 794, "s": 621, "text": "You can find the full list of features here. To keep things simple, I’m going to focus on the three most useful features based on my experience with the extension thus far." }, { "code": null, "e": 948, "s": 794, "text": "In Python, understanding how to correctly import dependencies from both internal and external modules is a challenge for newbies and professionals alike." }, { "code": null, "e": 1209, "s": 948, "text": "The Pylance extension offers a feature which automatically adds imports to the top of your Python files when you reference a dependency in your environment. It will also show a lightbulb icon with suggestions to add or remove imports depending on the scenario." }, { "code": null, "e": 1339, "s": 1209, "text": "It’s worth mentioning that you need to have the modules you’re referencing installed in your Python environment for this to work." }, { "code": null, "e": 1536, "s": 1339, "text": "Pylance’s semantic highlighting means that classes, functions, properties, and other Python object types are colored (i.e. highlighted) on the screen in a much more intuitive and readable fashion." }, { "code": null, "e": 1646, "s": 1536, "text": "It’s much easier to demonstrate this visually than to attempt to describe it, so here are some screenshots..." }, { "code": null, "e": 1885, "s": 1646, "text": "Type hinting, or the practice of specifying expected data types for variables/functions/classes/etc., is fairly new to Python. Python does not enforce type hinting, so at this point it’s essentially just a best practice for documentation." }, { "code": null, "e": 2176, "s": 1885, "text": "However, with Pylance, enabling the type checking setting (see below) will help you understand if your code violates any documented type hints. There are two modes for type checking, basic and strict (configured in preferences). At this time I would recommend sticking to the basic setting." }, { "code": null, "e": 2226, "s": 2176, "text": "{ \"python.analysis.typeCheckingMode\": \"basic\"}" }, { "code": null, "e": 2561, "s": 2226, "text": "The Pylance extension for Visual Studio Code is still in preview. There’s more work to be done to improve performance, expand upon the documentation, and resolve some bugs. However, it’s already a fantastic extension in my experience. I certainly don’t want to go back to the default language server for Python after enabling Pylance." } ]
Calculate and Plot S&P 500 Daily Returns | by Jose Manu (CodingFun) | Towards Data Science
The majority of investors are always trying to find an answer to a simple question, how the financial market will perform in the future. Obviously, no one knows the answer, and therefore, investors and financial analysts spend hours and hours trying to find out the best possible estimate of future stock prices. Python and Pandas can be a great ally to support us finding the best possible answer to the above mentioned question. In this story, we will write a Python script that will let us: Retrieve market data with Python and Pandas Calculate market daily returns Plot the market daily return in a chart After reading this article, you will be able to analyse the market returns for any company of your interest. Let’s start. First of all, to perform any analysis we need to have data. Luckily for us, with Python we can download hundred of data points within seconds. For our anylsis, we need to retrieve market data in form of stock prices. As a proxy of market data, I will use the S&P 500 index which tracks the performance of the 500 largest companies in the United States. The S&P 500 daily data can be extracted using Pandas and Pandas DataReader. Pandas DataReader is a great package to access data remotely with Pandas. Within Pandas DataReader, we have multiple sources where we can download data to perform multiple financial analysis with Python. We can get for example stock data or economic indicators from reliable providers. Check the Pandas DataReader documentation for more information. For our analysis, we will retrieve data from the FRED datasource. First, we need to import Pandas, datetime and Pandas_datareader packages. Next, we can simply define a date range and use the web.DataReader method to download the data in the form of a Pandas DataFrame and store it in a variable name SP500. We passed as arguments of the DataReader method the name of the dataset that we want to download (i.e. sp500), the provider or source of the data (‘Fred’) and the start and ending dates: import pandas as pd#if you get an error after executing the code, try adding below. pd.core.common.is_list_like = pd.api.types.is_list_likeimport pandas_datareader.data as webimport datetimestart = datetime.datetime(2010, 1, 1)end = datetime.datetime(2020, 1, 27)SP500 = web.DataReader(['sp500'], 'fred', start, end) After running the code, we have below Pandas DataFrame showing the historical S&P 500 daily prices: Great, we have the S&P 500 prices from the last 10 years in a Pandas DataFrame. Now, we are ready to calculate the S&P 500 daily returns from the last 10 years and add them to our DataFrame as a new column that we will call daily_return. To calculate the rate of return, we can use below formula where P1 refers to current price while P0 refers to the initial price or price that we take as reference to calculate the return. SP500['daily_return'] = (SP500['sp500']/ SP500['sp500'].shift(1)) -1#Drop all Not a number values using drop method.SP500.dropna(inplace = True) What shift method does is to shift our index by the number provided as an argument. In our case, we are shifting each of the values in the sp500 column by one. Meaning that we are diving the current day S&P 500 price by the previous day S&P 500 price. Lets print the last five values of our SP500 DataFrame to see what we get: We have our S&P 500 prices and returns ready to plot with Python. Lets plot the daily returns first. Plotting with Python and Matplotlib is super easy, we only need to select the daily_return column from our SP500 DataFrame and use the method plot. SP500['daily_return'].plot(title='S&P 500 daily returns') Nice! We can easily identify in the graph some very useful information. For example, we can see that the worst daily return for the S&P 500 index was in 2011 with a daily return of -7%. Similarly, we can see that the best day for the S&P 500 index was in the middle of 2019 with around 5% daily return. In addition to the daily returns, we can also plot the S&P 500 price evolution for the last 10 years. Here we can observe a clear upward trend. SP500['sp500'].plot(title='S&P 500 Price') In this story on Python for Finance, we have retrieved the S&P 500 historical prices in order to calculate and plot the daily returns for the index. Plotting daily market returns is a great way to visualise stock returns for any given period of time. You can try it out with any other stock or index. I really hope you have enjoyed the story! If you have questions or anything is not clear, feel free to leave a response. I also have a Youtube video explaining step by step the code used in this tutorial: Originally published at https://codingandfun.com on February 8, 2020.
[ { "code": null, "e": 308, "s": 171, "text": "The majority of investors are always trying to find an answer to a simple question, how the financial market will perform in the future." }, { "code": null, "e": 665, "s": 308, "text": "Obviously, no one knows the answer, and therefore, investors and financial analysts spend hours and hours trying to find out the best possible estimate of future stock prices. Python and Pandas can be a great ally to support us finding the best possible answer to the above mentioned question. In this story, we will write a Python script that will let us:" }, { "code": null, "e": 709, "s": 665, "text": "Retrieve market data with Python and Pandas" }, { "code": null, "e": 740, "s": 709, "text": "Calculate market daily returns" }, { "code": null, "e": 780, "s": 740, "text": "Plot the market daily return in a chart" }, { "code": null, "e": 902, "s": 780, "text": "After reading this article, you will be able to analyse the market returns for any company of your interest. Let’s start." }, { "code": null, "e": 1119, "s": 902, "text": "First of all, to perform any analysis we need to have data. Luckily for us, with Python we can download hundred of data points within seconds. For our anylsis, we need to retrieve market data in form of stock prices." }, { "code": null, "e": 1255, "s": 1119, "text": "As a proxy of market data, I will use the S&P 500 index which tracks the performance of the 500 largest companies in the United States." }, { "code": null, "e": 1405, "s": 1255, "text": "The S&P 500 daily data can be extracted using Pandas and Pandas DataReader. Pandas DataReader is a great package to access data remotely with Pandas." }, { "code": null, "e": 1681, "s": 1405, "text": "Within Pandas DataReader, we have multiple sources where we can download data to perform multiple financial analysis with Python. We can get for example stock data or economic indicators from reliable providers. Check the Pandas DataReader documentation for more information." }, { "code": null, "e": 1821, "s": 1681, "text": "For our analysis, we will retrieve data from the FRED datasource. First, we need to import Pandas, datetime and Pandas_datareader packages." }, { "code": null, "e": 1989, "s": 1821, "text": "Next, we can simply define a date range and use the web.DataReader method to download the data in the form of a Pandas DataFrame and store it in a variable name SP500." }, { "code": null, "e": 2176, "s": 1989, "text": "We passed as arguments of the DataReader method the name of the dataset that we want to download (i.e. sp500), the provider or source of the data (‘Fred’) and the start and ending dates:" }, { "code": null, "e": 2493, "s": 2176, "text": "import pandas as pd#if you get an error after executing the code, try adding below. pd.core.common.is_list_like = pd.api.types.is_list_likeimport pandas_datareader.data as webimport datetimestart = datetime.datetime(2010, 1, 1)end = datetime.datetime(2020, 1, 27)SP500 = web.DataReader(['sp500'], 'fred', start, end)" }, { "code": null, "e": 2593, "s": 2493, "text": "After running the code, we have below Pandas DataFrame showing the historical S&P 500 daily prices:" }, { "code": null, "e": 2831, "s": 2593, "text": "Great, we have the S&P 500 prices from the last 10 years in a Pandas DataFrame. Now, we are ready to calculate the S&P 500 daily returns from the last 10 years and add them to our DataFrame as a new column that we will call daily_return." }, { "code": null, "e": 3019, "s": 2831, "text": "To calculate the rate of return, we can use below formula where P1 refers to current price while P0 refers to the initial price or price that we take as reference to calculate the return." }, { "code": null, "e": 3164, "s": 3019, "text": "SP500['daily_return'] = (SP500['sp500']/ SP500['sp500'].shift(1)) -1#Drop all Not a number values using drop method.SP500.dropna(inplace = True)" }, { "code": null, "e": 3416, "s": 3164, "text": "What shift method does is to shift our index by the number provided as an argument. In our case, we are shifting each of the values in the sp500 column by one. Meaning that we are diving the current day S&P 500 price by the previous day S&P 500 price." }, { "code": null, "e": 3491, "s": 3416, "text": "Lets print the last five values of our SP500 DataFrame to see what we get:" }, { "code": null, "e": 3592, "s": 3491, "text": "We have our S&P 500 prices and returns ready to plot with Python. Lets plot the daily returns first." }, { "code": null, "e": 3740, "s": 3592, "text": "Plotting with Python and Matplotlib is super easy, we only need to select the daily_return column from our SP500 DataFrame and use the method plot." }, { "code": null, "e": 3798, "s": 3740, "text": "SP500['daily_return'].plot(title='S&P 500 daily returns')" }, { "code": null, "e": 3984, "s": 3798, "text": "Nice! We can easily identify in the graph some very useful information. For example, we can see that the worst daily return for the S&P 500 index was in 2011 with a daily return of -7%." }, { "code": null, "e": 4101, "s": 3984, "text": "Similarly, we can see that the best day for the S&P 500 index was in the middle of 2019 with around 5% daily return." }, { "code": null, "e": 4245, "s": 4101, "text": "In addition to the daily returns, we can also plot the S&P 500 price evolution for the last 10 years. Here we can observe a clear upward trend." }, { "code": null, "e": 4288, "s": 4245, "text": "SP500['sp500'].plot(title='S&P 500 Price')" }, { "code": null, "e": 4437, "s": 4288, "text": "In this story on Python for Finance, we have retrieved the S&P 500 historical prices in order to calculate and plot the daily returns for the index." }, { "code": null, "e": 4589, "s": 4437, "text": "Plotting daily market returns is a great way to visualise stock returns for any given period of time. You can try it out with any other stock or index." }, { "code": null, "e": 4794, "s": 4589, "text": "I really hope you have enjoyed the story! If you have questions or anything is not clear, feel free to leave a response. I also have a Youtube video explaining step by step the code used in this tutorial:" } ]
Extract the Day / Month / Year from a Timestamp in PHP MySQL?
To extract the Day/Month/Year from a timestamp, you need to use the date_parse() function. The syntax as follows − print_r(date_parse(“anyTimeStampValue”)); The PHP code is as follows − $yourTimeStampValue="2019-02-04 12:56:50"; print_r(date_parse($yourTimeStampValue)); The snapshot of PHP code is as follows − The following is the output − Array ( [year] => 2019 [month] => 2 [day] => 4 [hour] => 12 [minute] => 56 [second] => 50 [fraction] => 0 [warning_count] => 0 [warnings] => Array ( ) [error_count] => 0 [errors] => Array ( ) [is_localtime] => ) The snapshot of the sample output −
[ { "code": null, "e": 1177, "s": 1062, "text": "To extract the Day/Month/Year from a timestamp, you need to use the date_parse() function. The syntax as follows −" }, { "code": null, "e": 1219, "s": 1177, "text": "print_r(date_parse(“anyTimeStampValue”));" }, { "code": null, "e": 1248, "s": 1219, "text": "The PHP code is as follows −" }, { "code": null, "e": 1333, "s": 1248, "text": "$yourTimeStampValue=\"2019-02-04 12:56:50\";\nprint_r(date_parse($yourTimeStampValue));" }, { "code": null, "e": 1374, "s": 1333, "text": "The snapshot of PHP code is as follows −" }, { "code": null, "e": 1404, "s": 1374, "text": "The following is the output −" }, { "code": null, "e": 1616, "s": 1404, "text": "Array ( [year] => 2019 [month] => 2 [day] => 4 [hour] => 12 [minute] => 56 [second] => 50 [fraction] => 0 [warning_count] => 0 [warnings] => Array ( ) [error_count] => 0 [errors] => Array ( ) [is_localtime] => )" }, { "code": null, "e": 1652, "s": 1616, "text": "The snapshot of the sample output −" } ]
Fortran - Reshape Functions
The following table describes the reshape function: Example The following example demonstrates the concept: program arrayReshape implicit none interface subroutine write_matrix(a) real, dimension(:,:) :: a end subroutine write_matrix end interface real, dimension (1:9) :: b = (/ 21, 22, 23, 24, 25, 26, 27, 28, 29 /) real, dimension (1:3, 1:3) :: c, d, e real, dimension (1:4, 1:4) :: f, g, h integer, dimension (1:2) :: order1 = (/ 1, 2 /) integer, dimension (1:2) :: order2 = (/ 2, 1 /) real, dimension (1:16) :: pad1 = (/ -1, -2, -3, -4, -5, -6, -7, -8, & & -9, -10, -11, -12, -13, -14, -15, -16 /) c = reshape( b, (/ 3, 3 /) ) call write_matrix(c) d = reshape( b, (/ 3, 3 /), order = order1) call write_matrix(d) e = reshape( b, (/ 3, 3 /), order = order2) call write_matrix(e) f = reshape( b, (/ 4, 4 /), pad = pad1) call write_matrix(f) g = reshape( b, (/ 4, 4 /), pad = pad1, order = order1) call write_matrix(g) h = reshape( b, (/ 4, 4 /), pad = pad1, order = order2) call write_matrix(h) end program arrayReshape subroutine write_matrix(a) real, dimension(:,:) :: a write(*,*) do i = lbound(a,1), ubound(a,1) write(*,*) (a(i,j), j = lbound(a,2), ubound(a,2)) end do end subroutine write_matrix When the above code is compiled and executed, it produces the following result: 21.0000000 24.0000000 27.0000000 22.0000000 25.0000000 28.0000000 23.0000000 26.0000000 29.0000000 21.0000000 24.0000000 27.0000000 22.0000000 25.0000000 28.0000000 23.0000000 26.0000000 29.0000000 21.0000000 22.0000000 23.0000000 24.0000000 25.0000000 26.0000000 27.0000000 28.0000000 29.0000000 21.0000000 25.0000000 29.0000000 -4.00000000 22.0000000 26.0000000 -1.00000000 -5.00000000 23.0000000 27.0000000 -2.00000000 -6.00000000 24.0000000 28.0000000 -3.00000000 -7.00000000 21.0000000 25.0000000 29.0000000 -4.00000000 22.0000000 26.0000000 -1.00000000 -5.00000000 23.0000000 27.0000000 -2.00000000 -6.00000000 24.0000000 28.0000000 -3.00000000 -7.00000000 21.0000000 22.0000000 23.0000000 24.0000000 25.0000000 26.0000000 27.0000000 28.0000000 29.0000000 -1.00000000 -2.00000000 -3.00000000 -4.00000000 -5.00000000 -6.00000000 -7.00000000 Print Add Notes Bookmark this page
[ { "code": null, "e": 2198, "s": 2146, "text": "The following table describes the reshape function:" }, { "code": null, "e": 2206, "s": 2198, "text": "Example" }, { "code": null, "e": 2254, "s": 2206, "text": "The following example demonstrates the concept:" }, { "code": null, "e": 3483, "s": 2254, "text": "program arrayReshape\nimplicit none\n\ninterface\n subroutine write_matrix(a)\n real, dimension(:,:) :: a\n end subroutine write_matrix\n end interface\n\n real, dimension (1:9) :: b = (/ 21, 22, 23, 24, 25, 26, 27, 28, 29 /)\n real, dimension (1:3, 1:3) :: c, d, e\n real, dimension (1:4, 1:4) :: f, g, h\n\n integer, dimension (1:2) :: order1 = (/ 1, 2 /)\n integer, dimension (1:2) :: order2 = (/ 2, 1 /)\n real, dimension (1:16) :: pad1 = (/ -1, -2, -3, -4, -5, -6, -7, -8, &\n & -9, -10, -11, -12, -13, -14, -15, -16 /)\n\n c = reshape( b, (/ 3, 3 /) )\n call write_matrix(c)\n\n d = reshape( b, (/ 3, 3 /), order = order1)\n call write_matrix(d)\n\n e = reshape( b, (/ 3, 3 /), order = order2)\n call write_matrix(e)\n\n f = reshape( b, (/ 4, 4 /), pad = pad1)\n call write_matrix(f)\n\n g = reshape( b, (/ 4, 4 /), pad = pad1, order = order1)\n call write_matrix(g)\n\n h = reshape( b, (/ 4, 4 /), pad = pad1, order = order2)\n call write_matrix(h)\n\nend program arrayReshape\n\n\nsubroutine write_matrix(a)\n real, dimension(:,:) :: a\n write(*,*)\n \n do i = lbound(a,1), ubound(a,1)\n write(*,*) (a(i,j), j = lbound(a,2), ubound(a,2))\n end do\nend subroutine write_matrix" }, { "code": null, "e": 3563, "s": 3483, "text": "When the above code is compiled and executed, it produces the following result:" }, { "code": null, "e": 4554, "s": 3563, "text": "21.0000000 24.0000000 27.0000000 \n22.0000000 25.0000000 28.0000000 \n23.0000000 26.0000000 29.0000000 \n\n21.0000000 24.0000000 27.0000000 \n22.0000000 25.0000000 28.0000000 \n23.0000000 26.0000000 29.0000000 \n\n21.0000000 22.0000000 23.0000000 \n24.0000000 25.0000000 26.0000000 \n27.0000000 28.0000000 29.0000000 \n\n21.0000000 25.0000000 29.0000000 -4.00000000 \n22.0000000 26.0000000 -1.00000000 -5.00000000 \n23.0000000 27.0000000 -2.00000000 -6.00000000 \n24.0000000 28.0000000 -3.00000000 -7.00000000 \n\n21.0000000 25.0000000 29.0000000 -4.00000000 \n22.0000000 26.0000000 -1.00000000 -5.00000000 \n23.0000000 27.0000000 -2.00000000 -6.00000000 \n24.0000000 28.0000000 -3.00000000 -7.00000000 \n\n21.0000000 22.0000000 23.0000000 24.0000000 \n25.0000000 26.0000000 27.0000000 28.0000000 \n29.0000000 -1.00000000 -2.00000000 -3.00000000 \n-4.00000000 -5.00000000 -6.00000000 -7.00000000 \n" }, { "code": null, "e": 4561, "s": 4554, "text": " Print" }, { "code": null, "e": 4572, "s": 4561, "text": " Add Notes" } ]
Burning Tree | Practice | GeeksforGeeks
Given a binary tree and a node called target. Find the minimum time required to burn the complete binary tree if the target is set on fire. It is known that in 1 second all nodes connected to a given node get burned. That is its left child, right child, and parent. Example 1: Input: 1 / \ 2 3 / \ \ 4 5 6 / \ \ 7 8 9 \ 10 Target Node = 8 Output: 7 Explanation: If leaf with the value 8 is set on fire. After 1 sec: 5 is set on fire. After 2 sec: 2, 7 are set to fire. After 3 sec: 4, 1 are set to fire. After 4 sec: 3 is set to fire. After 5 sec: 6 is set to fire. After 6 sec: 9 is set to fire. After 7 sec: 10 is set to fire. It takes 7s to burn the complete tree. Example 2: Input: 1 / \ 2 3 / \ \ 4 5 7 / / 8 10 Target Node = 10 Output: 5 Your Task: You don't need to read input or print anything. Complete the function minTime() which takes the root of the tree and target as input parameters and returns the minimum time required to burn the complete binary tree if the target is set on fire at the 0th second. Expected Time Complexity: O(N) Expected Auxiliary Space: O(height of tree) Constraints: 1 ≤ N ≤ 104 0 archit232002 days ago Simple Java Solution based on Striver's Approach:- public static int minTime(Node root, int target) { // Your code goes here calcParent(root, target); Queue<Node> q = new LinkedList<>(); Map<Node, Boolean> visited = new LinkedHashMap<>(); q.offer(n); int time = 0; //Only difference between the "Print nodes at a distance k from target" and this is that here we take the variable as time. while (q.isEmpty() == false) { int size = q.size(); time++; for (int i = 0; i < size; i++) { Node node = q.poll(); if (node.left != null && visited.get(node.left) == null) { q.offer(node.left); visited.put(node.left, true); } if (node.right != null && visited.get(node.right) == null) { q.offer(node.right); visited.put(node.right, true); } if (p.containsKey(node) == true && visited.get(p.get(node)) == null) { q.offer(p.get(node)); visited.put(p.get(node), true); } } } return time - 1;//We return time-1 as 1 sec extra time is counted due to the target node being processed first in the Queue } 0 satyamtiwari20163 weeks ago int minTime(Node* root, int target) { // Your code goes here //parents map formation map<Node*,Node*> parent; parent[root]=NULL; Node* curr=NULL; queue<Node*> q; q.push(root); while(!q.empty()){ Node* front = q.front(); q.pop(); if(front->data==target){ curr=front; } if(front->left){ q.push(front->left); parent[front->left]=front; } if(front->right){ q.push(front->right); parent[front->right]=front; } } //parent map completed int time=0; map<Node*,bool> visited; queue<Node*> q1; q1.push(curr); visited[curr]=true; while(!q1.empty()){ int size=q1.size(); bool flag=false; for(int i=0;i<size;i++){ Node* front=q1.front(); q1.pop(); if(parent[front] && !visited[parent[front]]){ visited[parent[front]]=true; q1.push(parent[front]); flag=true; } if(front->left && !visited[front->left]){ visited[front->left]=true; q1.push(front->left); flag=true; } if(front->right && !visited[front->right]){ visited[front->right]=true; q1.push(front->right); flag=true; } } if(flag){ time++; } } return time; } 0 adil033204 weeks ago class Solution { public: void path (Node*root,int target,vector<Node*>temp,vector<Node*>&v){ if(root==NULL) return; if(root->data==target){ temp.push_back(root); v=temp; return; } temp.push_back(root); path(root->left,target,temp,v); path(root->right,target,temp,v); } int maxdis(Node*root,Node*bloc){ if(root==NULL) return -1; if(root->data==bloc->data) return -1; int l=maxdis(root->left,bloc); int r=maxdis(root->right,bloc); return max(l,r)+1; // if(root->left==NULL && root->right==NULL) return 0; } int minTime(Node* root, int target) { vector<Node*>v; vector<Node*>temp; path(root,target,temp,v); int maxi=INT_MIN; for(int i=v.size()-1;i>=0;i--){ if(i==v.size()-1){ Node*tt=new Node(-999999); maxi=max(maxi,maxdis(v[i],tt)); } else{ int dis=maxdis(v[i],v[i+1])+(v.size()-i-1); maxi=max(maxi,dis); } } // Your code goes here return maxi; } }; +1 vipuldawar4 weeks ago BFS approach:Steps:1) Find targetNode and Map for child to parent.2) BFS start with targetNode and keep checking for non-visited left, right or parent of currentNode and add it to q. 3) Keep increasing the time, if any node is burnt in any iteration. public static int minTime(Node root, int target) { // Your code goes here Map<Node, Node> map = new HashMap<>(); Node[] targetNode = new Node[1]; fill(root, target, map, targetNode); if(targetNode[0] == null) { return 0; } return findMinTime(targetNode[0], map);}private static void fill(Node root, int target, Map<Node, Node> map, Node[] targetNode) { if(root == null) { return; } if(root.data == target) { targetNode[0] = root; } if (root.left != null) { map.put(root.left, root); fill(root.left, target, map, targetNode); } if (root.right != null) { map.put(root.right, root); fill(root.right, target, map, targetNode); }}private static int findMinTime(Node targetNode, Map<Node, Node> map) { Map<Node, Boolean> visited = new HashMap<>(); Queue<Node> q = new LinkedList<>(); q.add(targetNode); visited.put(targetNode, true); int result = 0; while(!q.isEmpty()) { int size = q.size(); boolean anyBurnt = false; for (int i = 0; i < size; i++) { Node n = q.remove(); if(n.left != null && !visited.containsKey(n.left)) { q.add(n.left); visited.put(n.left, true); anyBurnt = true; } if(n.right != null && !visited.containsKey(n.right)) { q.add(n.right); visited.put(n.right, true); anyBurnt = true; } if(map.containsKey(n) && !visited.containsKey(map.get(n))) { q.add(map.get(n)); visited.put(map.get(n), true); anyBurnt = true; } } if(anyBurnt) { result++; } } return result;} 0 luffysama11 month ago int burnTree(map<Node*,Node*>mp, Node* target){ map<Node* , int> vis; queue<Node*> q; q.push(target); vis[target] = 1; int maxi = 0; while(!q.empty()){ int n = q.size(); bool f = 0; while(n--){ Node* temp = q.front(); q.pop(); if(temp->left && !vis[temp->left]){ f = 1; q.push(temp->left); vis[temp->left] = 1; } if(temp->right && !vis[temp->right]){ f = 1; q.push(temp->right); vis[temp->right] = 1; } if(mp[temp] && !vis[mp[temp]]){ f = 1; q.push(mp[temp]); vis[mp[temp]] = 1; } } if(f) maxi++; } return maxi; } Node* getNodeAndMap(Node* root , int t , map<Node*,Node*>& mp){ queue<Node*>q; q.push(root); Node* ans; while(!q.empty()){ int n = q.size(); while(n--){ Node* temp = q.front(); q.pop(); if(temp->data==t) ans = temp; if(temp->left){ mp[temp->left] = temp; q.push(temp->left); } if(temp->right){ mp[temp->right] = temp; q.push(temp->right); } } } return ans; } int minTime(Node* root, int target) { // Your code goes here map<Node*,Node*>mp; Node* temp = getNodeAndMap(root,target,mp); return burnTree(mp,temp); } 0 aadityasharmax1 month ago → Using Print nodes k away from target problem logic. class Solution { public: void burnTheTree(Node *root,int maxT,stack<Node *>&st,int &ans,Node* blocker){ if(root==NULL || root==blocker) return; if(root->left!=NULL){ burnTheTree(root->left,maxT+1,st,ans,blocker); } if(root->right!=NULL){ burnTheTree(root->right,maxT+1,st,ans,blocker); } if(st.top() == root){ st.pop(); if(!st.empty()) burnTheTree(st.top(),maxT+1,st,ans,root); } ans = max(maxT,ans); } void rootToNodePath(Node *root,int target,vector<Node*> &v,stack<Node*>&s){ if(root == NULL) return; v.push_back(root); if(root->data==target) { for(int i =0 ;i<v.size() ;i++) s.push(v[i]); return; } rootToNodePath(root->left,target,v,s); rootToNodePath(root->right,target,v,s); v.pop_back(); } int minTime(Node* root, int target) { // Your code goes here int ans = 0; stack<Node*> st; vector<Node*> v; rootToNodePath(root,target,v,st); Node* blocker = NULL; burnTheTree(st.top(),0,st,ans,blocker); return ans; } }; +2 sahilarya20111 month ago public static Node createParentMapping(Node root, int target, HashMap<Node,Node>map){ Node res= null; Queue<Node>q= new LinkedList<>(); q.add(root); map.put(root,null); while(!q.isEmpty()){ Node n= q.peek(); q.remove(); if(n.data==target){ res=n; } if(n.left!=null){ map.put(n.left,n); q.add(n.left); } if(n.right!=null){ map.put(n.right,n); q.add(n.right); } } return res; } public static int burnTree(Node root, HashMap<Node,Node>map ) { HashMap<Node,Boolean>visited= new HashMap<>(); Queue<Node>q= new LinkedList<>(); q.add(root); visited.put(root,true); int time=0; while(!q.isEmpty()){ boolean flag= true; int size= q.size(); for(int i=0; i<size; i++){ Node front= q.peek(); q.remove(); if(front.left!=null && !visited.containsKey(front.left)){ flag=true; q.add(front.left); visited.put(front.left,true); } if(front.right!=null && !visited.containsKey(front.right)){ flag=true; q.add(front.right); visited.put(front.right,true); } if(map.get(front)!=null && !visited.containsKey(map.get(front))){ flag=true; q.add(map.get(front)); visited.put(map.get(front),true); } } if(flag==true) time++; } return time-1; } public static int minTime(Node root, int target) { // Your code goes here HashMap<Node,Node>map= new HashMap<>(); Node targetNode= createParentMapping(root,target,map); int ans= burnTree(targetNode, map); return ans; }} 0 himanshu3198live1 month ago Node *source; unordered_map<Node*,Node*>getParent; void solve(Node *root,int target){ if(!root) return; if(root->data==target) source=root; if(root->left) getParent[root->left]=root; if(root->right) getParent[root->right]=root; solve(root->left,target); solve(root->right,target); } int minTime(Node* root, int target) { // Your code goes here getParent[root]==root; solve(root,target); if(root and !root->left and !root->right) return 0; queue<Node*>q; set<Node*>vis; q.push(source); int time=0; while(!q.empty()){ int size=q.size(); time++; while(size--){ Node *curr=q.front(); q.pop(); if(vis.count(curr)==1) break; vis.insert(curr); if(curr->left){ if((curr->left->left or curr->left->right) and !vis.count(curr->left)){ q.push(curr->left); } } if(curr->right){ if((curr->right->left or curr->right->right) and !vis.count(curr->right)){ q.push(curr->right); } } if(getParent[curr]){ if(vis.count(getParent[curr])==0){ q.push(getParent[curr]); } } } } return time; } +1 creator23031 month ago class Solution { public: int ans=1; unordered_map<Node* , Node*> mp ; Node *T=NULL ; unordered_map<Node*, bool > visited ; void PreOrder(Node *root,int target) { if(!root) return ; if(root->data==target) T = root ; if(root->left) { mp[root->left] =root ; } if(root->right) { mp[root->right] = root ; } PreOrder(root->left,target) ; PreOrder(root->right,target) ; } int minTime(Node* root, int target) { if(!root) return 0 ; mp[root] = NULL ; int t= 0; Node* r=root; PreOrder(root, target); queue<Node* > q ; q.push(T); while(!q.empty()) { int sz=q.size(); while(sz--) { Node *temp = q.front() ; q.pop(); if(temp->left and !visited[temp->left]) { q.push(temp->left) ;visited[temp->left] =1 ; } if(temp->right and !visited[temp->right]) { q.push(temp->right) ; visited[temp->right]=1 ; } if(mp[temp]and !visited[mp[temp]]) { q.push(mp[temp]) ;visited[mp[temp]]=1; } } t++ ; } return t-1; } }; +1 himanshu11042003singh1 month ago class Solution { public: Node* createParentMapping(Node* root,int target,map<Node*,Node*>&nodeToParent){ Node* res= NULL; queue<Node*>q; q.push(root); nodeToParent[root]=NULL; while(!q.empty()){ Node* front= q.front(); q.pop(); if(front->data==target){ res= front; } if(front->left){ nodeToParent[front->left]=front; q.push(front->left); } if(front->right){ nodeToParent[front->right]=front; q.push(front->right); } } return res; } int burnTree(Node* root,map<Node*,Node*>&nodeToParent){ map<Node*,bool>visited; queue<Node*>q; q.push(root); visited[root]=true; int ans=0; while(!q.empty()){ bool flag=0; int size=q.size(); for(int i=0;i<size;i++){ Node* front= q.front(); q.pop(); if(front->left&&!visited[front->left]){ flag=1; q.push(front->left); visited[front->left]=1; } if(front->right&&!visited[front->right]){ flag=1; q.push(front->right); visited[front->right]=1; } if(nodeToParent[front]&&!visited[nodeToParent[front]]){ flag=1; q.push(nodeToParent[front]); visited[nodeToParent[front]]=1; } } if(flag==1){ ans++; } } return ans; } int minTime(Node* root, int target) { // Your code goes here map<Node*,Node*>nodeToParent; Node* targetNode= createParentMapping(root,target,nodeToParent); int ans= burnTree(targetNode,nodeToParent); return ans; }}; We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 556, "s": 290, "text": "Given a binary tree and a node called target. Find the minimum time required to burn the complete binary tree if the target is set on fire. It is known that in 1 second all nodes connected to a given node get burned. That is its left child, right child, and parent." }, { "code": null, "e": 568, "s": 556, "text": "\nExample 1:" }, { "code": null, "e": 1083, "s": 568, "text": "Input: \n 1\n / \\\n 2 3\n / \\ \\\n 4 5 6\n / \\ \\\n 7 8 9\n \\\n 10\nTarget Node = 8\nOutput: 7\nExplanation: If leaf with the value \n8 is set on fire. \nAfter 1 sec: 5 is set on fire.\nAfter 2 sec: 2, 7 are set to fire.\nAfter 3 sec: 4, 1 are set to fire.\nAfter 4 sec: 3 is set to fire.\nAfter 5 sec: 6 is set to fire.\nAfter 6 sec: 9 is set to fire.\nAfter 7 sec: 10 is set to fire.\nIt takes 7s to burn the complete tree.\n" }, { "code": null, "e": 1094, "s": 1083, "text": "Example 2:" }, { "code": null, "e": 1228, "s": 1094, "text": "Input: \n 1\n / \\\n 2 3\n / \\ \\\n 4 5 7\n / / \n 8 10\nTarget Node = 10\nOutput: 5\n" }, { "code": null, "e": 1505, "s": 1228, "text": "\nYour Task: \nYou don't need to read input or print anything. Complete the function minTime() which takes the root of the tree and target as input parameters and returns the minimum time required to burn the complete binary tree if the target is set on fire at the 0th second." }, { "code": null, "e": 1581, "s": 1505, "text": "\nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(height of tree)" }, { "code": null, "e": 1607, "s": 1581, "text": "\nConstraints:\n1 ≤ N ≤ 104" }, { "code": null, "e": 1609, "s": 1607, "text": "0" }, { "code": null, "e": 1631, "s": 1609, "text": "archit232002 days ago" }, { "code": null, "e": 1682, "s": 1631, "text": "Simple Java Solution based on Striver's Approach:-" }, { "code": null, "e": 3084, "s": 1684, "text": "public static int minTime(Node root, int target) {\n // Your code goes here\n calcParent(root, target);\n Queue<Node> q = new LinkedList<>();\n Map<Node, Boolean> visited = new LinkedHashMap<>();\n q.offer(n);\n int time = 0; //Only difference between the \"Print nodes at a distance k from target\" and this is that here we take the variable as time.\n while (q.isEmpty() == false) {\n int size = q.size();\n time++;\n for (int i = 0; i < size; i++) {\n Node node = q.poll();\n if (node.left != null && visited.get(node.left) == null) {\n q.offer(node.left);\n visited.put(node.left, true);\n }\n if (node.right != null && visited.get(node.right) == null) {\n q.offer(node.right);\n visited.put(node.right, true);\n }\n if (p.containsKey(node) == true && visited.get(p.get(node)) == null) {\n q.offer(p.get(node));\n visited.put(p.get(node), true);\n }\n }\n }\n return time - 1;//We return time-1 as 1 sec extra time is counted due to the target node being processed first in the Queue\n }" }, { "code": null, "e": 3086, "s": 3084, "text": "0" }, { "code": null, "e": 3114, "s": 3086, "text": "satyamtiwari20163 weeks ago" }, { "code": null, "e": 5072, "s": 3114, "text": " int minTime(Node* root, int target) \n {\n // Your code goes here\n \n //parents map formation\n map<Node*,Node*> parent;\n parent[root]=NULL;\n Node* curr=NULL;\n queue<Node*> q;\n \n q.push(root);\n \n while(!q.empty()){\n \n Node* front = q.front();\n q.pop();\n \n \n if(front->data==target){\n curr=front;\n }\n \n if(front->left){\n q.push(front->left);\n parent[front->left]=front;\n }\n \n \n if(front->right){\n q.push(front->right);\n parent[front->right]=front;\n }\n \n }\n \n //parent map completed\n \n \n int time=0;\n \n \n map<Node*,bool> visited;\n queue<Node*> q1;\n q1.push(curr);\n \n visited[curr]=true;\n \n \n \n while(!q1.empty()){\n \n int size=q1.size();\n bool flag=false;\n \n for(int i=0;i<size;i++){\n \n Node* front=q1.front();\n q1.pop();\n \n \n if(parent[front] && !visited[parent[front]]){\n visited[parent[front]]=true;\n q1.push(parent[front]);\n flag=true;\n }\n \n \n if(front->left && !visited[front->left]){\n visited[front->left]=true;\n q1.push(front->left);\n flag=true;\n }\n \n if(front->right && !visited[front->right]){\n visited[front->right]=true;\n q1.push(front->right);\n flag=true;\n }\n \n }\n \n \n if(flag){\n time++;\n }\n }\n \n return time;\n }" }, { "code": null, "e": 5074, "s": 5072, "text": "0" }, { "code": null, "e": 5095, "s": 5074, "text": "adil033204 weeks ago" }, { "code": null, "e": 6260, "s": 5095, "text": "class Solution {\n public:\n void path (Node*root,int target,vector<Node*>temp,vector<Node*>&v){\n if(root==NULL) return;\n if(root->data==target){\n temp.push_back(root);\n v=temp;\n return;\n }\n temp.push_back(root);\n path(root->left,target,temp,v);\n path(root->right,target,temp,v);\n }\n int maxdis(Node*root,Node*bloc){\n if(root==NULL) return -1;\n if(root->data==bloc->data) return -1;\n int l=maxdis(root->left,bloc);\n int r=maxdis(root->right,bloc);\n return max(l,r)+1;\n // if(root->left==NULL && root->right==NULL) return 0;\n \n }\n int minTime(Node* root, int target) \n {\n vector<Node*>v;\n vector<Node*>temp;\n path(root,target,temp,v);\n int maxi=INT_MIN;\n for(int i=v.size()-1;i>=0;i--){\n if(i==v.size()-1){\n Node*tt=new Node(-999999);\n maxi=max(maxi,maxdis(v[i],tt));\n }\n else{\n int dis=maxdis(v[i],v[i+1])+(v.size()-i-1);\n maxi=max(maxi,dis);\n }\n }\n // Your code goes here\n return maxi;\n \n }\n};" }, { "code": null, "e": 6263, "s": 6260, "text": "+1" }, { "code": null, "e": 6285, "s": 6263, "text": "vipuldawar4 weeks ago" }, { "code": null, "e": 6470, "s": 6287, "text": "BFS approach:Steps:1) Find targetNode and Map for child to parent.2) BFS start with targetNode and keep checking for non-visited left, right or parent of currentNode and add it to q." }, { "code": null, "e": 6538, "s": 6470, "text": "3) Keep increasing the time, if any node is burnt in any iteration." }, { "code": null, "e": 8302, "s": 6542, "text": "public static int minTime(Node root, int target) { // Your code goes here Map<Node, Node> map = new HashMap<>(); Node[] targetNode = new Node[1]; fill(root, target, map, targetNode); if(targetNode[0] == null) { return 0; } return findMinTime(targetNode[0], map);}private static void fill(Node root, int target, Map<Node, Node> map, Node[] targetNode) { if(root == null) { return; } if(root.data == target) { targetNode[0] = root; } if (root.left != null) { map.put(root.left, root); fill(root.left, target, map, targetNode); } if (root.right != null) { map.put(root.right, root); fill(root.right, target, map, targetNode); }}private static int findMinTime(Node targetNode, Map<Node, Node> map) { Map<Node, Boolean> visited = new HashMap<>(); Queue<Node> q = new LinkedList<>(); q.add(targetNode); visited.put(targetNode, true); int result = 0; while(!q.isEmpty()) { int size = q.size(); boolean anyBurnt = false; for (int i = 0; i < size; i++) { Node n = q.remove(); if(n.left != null && !visited.containsKey(n.left)) { q.add(n.left); visited.put(n.left, true); anyBurnt = true; } if(n.right != null && !visited.containsKey(n.right)) { q.add(n.right); visited.put(n.right, true); anyBurnt = true; } if(map.containsKey(n) && !visited.containsKey(map.get(n))) { q.add(map.get(n)); visited.put(map.get(n), true); anyBurnt = true; } } if(anyBurnt) { result++; } } return result;} " }, { "code": null, "e": 8304, "s": 8302, "text": "0" }, { "code": null, "e": 8326, "s": 8304, "text": "luffysama11 month ago" }, { "code": null, "e": 10026, "s": 8326, "text": "int burnTree(map<Node*,Node*>mp, Node* target){ map<Node* , int> vis; queue<Node*> q; q.push(target); vis[target] = 1; int maxi = 0; while(!q.empty()){ int n = q.size(); bool f = 0; while(n--){ Node* temp = q.front(); q.pop(); if(temp->left && !vis[temp->left]){ f = 1; q.push(temp->left); vis[temp->left] = 1; } if(temp->right && !vis[temp->right]){ f = 1; q.push(temp->right); vis[temp->right] = 1; } if(mp[temp] && !vis[mp[temp]]){ f = 1; q.push(mp[temp]); vis[mp[temp]] = 1; } } if(f) maxi++; } return maxi; } Node* getNodeAndMap(Node* root , int t , map<Node*,Node*>& mp){ queue<Node*>q; q.push(root); Node* ans; while(!q.empty()){ int n = q.size(); while(n--){ Node* temp = q.front(); q.pop(); if(temp->data==t) ans = temp; if(temp->left){ mp[temp->left] = temp; q.push(temp->left); } if(temp->right){ mp[temp->right] = temp; q.push(temp->right); } } } return ans; } int minTime(Node* root, int target) { // Your code goes here map<Node*,Node*>mp; Node* temp = getNodeAndMap(root,target,mp); return burnTree(mp,temp); }" }, { "code": null, "e": 10028, "s": 10026, "text": "0" }, { "code": null, "e": 10054, "s": 10028, "text": "aadityasharmax1 month ago" }, { "code": null, "e": 10108, "s": 10054, "text": "→ Using Print nodes k away from target problem logic." }, { "code": null, "e": 11331, "s": 10108, "text": "class Solution {\n public:\n void burnTheTree(Node *root,int maxT,stack<Node *>&st,int &ans,Node* blocker){\n if(root==NULL || root==blocker) return;\n \n if(root->left!=NULL){\n burnTheTree(root->left,maxT+1,st,ans,blocker);\n }\n if(root->right!=NULL){\n burnTheTree(root->right,maxT+1,st,ans,blocker);\n }\n if(st.top() == root){\n st.pop();\n if(!st.empty()) burnTheTree(st.top(),maxT+1,st,ans,root);\n }\n ans = max(maxT,ans);\n }\n void rootToNodePath(Node *root,int target,vector<Node*> &v,stack<Node*>&s){\n if(root == NULL) return;\n v.push_back(root);\n if(root->data==target)\n {\n for(int i =0 ;i<v.size() ;i++) s.push(v[i]);\n return;\n }\n rootToNodePath(root->left,target,v,s);\n rootToNodePath(root->right,target,v,s);\n v.pop_back();\n }\n int minTime(Node* root, int target) \n {\n // Your code goes here\n int ans = 0;\n stack<Node*> st;\n vector<Node*> v;\n rootToNodePath(root,target,v,st);\n Node* blocker = NULL;\n burnTheTree(st.top(),0,st,ans,blocker);\n return ans;\n }\n};" }, { "code": null, "e": 11334, "s": 11331, "text": "+2" }, { "code": null, "e": 11359, "s": 11334, "text": "sahilarya20111 month ago" }, { "code": null, "e": 13402, "s": 11359, "text": " public static Node createParentMapping(Node root, int target, HashMap<Node,Node>map){ Node res= null; Queue<Node>q= new LinkedList<>(); q.add(root); map.put(root,null); while(!q.isEmpty()){ Node n= q.peek(); q.remove(); if(n.data==target){ res=n; } if(n.left!=null){ map.put(n.left,n); q.add(n.left); } if(n.right!=null){ map.put(n.right,n); q.add(n.right); } } return res; } public static int burnTree(Node root, HashMap<Node,Node>map ) { HashMap<Node,Boolean>visited= new HashMap<>(); Queue<Node>q= new LinkedList<>(); q.add(root); visited.put(root,true); int time=0; while(!q.isEmpty()){ boolean flag= true; int size= q.size(); for(int i=0; i<size; i++){ Node front= q.peek(); q.remove(); if(front.left!=null && !visited.containsKey(front.left)){ flag=true; q.add(front.left); visited.put(front.left,true); } if(front.right!=null && !visited.containsKey(front.right)){ flag=true; q.add(front.right); visited.put(front.right,true); } if(map.get(front)!=null && !visited.containsKey(map.get(front))){ flag=true; q.add(map.get(front)); visited.put(map.get(front),true); } } if(flag==true) time++; } return time-1; } public static int minTime(Node root, int target) { // Your code goes here HashMap<Node,Node>map= new HashMap<>(); Node targetNode= createParentMapping(root,target,map); int ans= burnTree(targetNode, map); return ans; }}" }, { "code": null, "e": 13404, "s": 13402, "text": "0" }, { "code": null, "e": 13432, "s": 13404, "text": "himanshu3198live1 month ago" }, { "code": null, "e": 15511, "s": 13432, "text": " Node *source;\n unordered_map<Node*,Node*>getParent;\n \n void solve(Node *root,int target){\n \n if(!root) return;\n if(root->data==target) source=root;\n \n if(root->left) getParent[root->left]=root;\n if(root->right) getParent[root->right]=root;\n solve(root->left,target);\n solve(root->right,target);\n }\n int minTime(Node* root, int target) \n {\n // Your code goes here\n getParent[root]==root;\n solve(root,target);\n \n if(root and !root->left and !root->right) return 0;\n \n queue<Node*>q;\n set<Node*>vis;\n q.push(source);\n int time=0;\n while(!q.empty()){\n \n int size=q.size();\n time++;\n while(size--){\n \n Node *curr=q.front();\n q.pop();\n \n if(vis.count(curr)==1) break; \n vis.insert(curr);\n \n if(curr->left){\n \n if((curr->left->left or curr->left->right) and !vis.count(curr->left)){\n \n q.push(curr->left);\n }\n }\n if(curr->right){\n if((curr->right->left or curr->right->right) and !vis.count(curr->right)){\n \n q.push(curr->right);\n }\n \n }\n \n if(getParent[curr]){\n \n if(vis.count(getParent[curr])==0){\n q.push(getParent[curr]);\n }\n }\n \n }\n \n \n }\n \n return time;\n \n \n }" }, { "code": null, "e": 15514, "s": 15511, "text": "+1" }, { "code": null, "e": 15537, "s": 15514, "text": "creator23031 month ago" }, { "code": null, "e": 17272, "s": 15537, "text": "\nclass Solution {\n public:\n int ans=1;\n unordered_map<Node* , Node*> mp ;\n \n Node *T=NULL ;\n \n \n unordered_map<Node*, bool > visited ;\n \n void PreOrder(Node *root,int target)\n {\n if(!root)\n return ;\n \n if(root->data==target)\n T = root ;\n if(root->left)\n {\n mp[root->left] =root ;\n }\n if(root->right)\n {\n mp[root->right] = root ;\n }\n \n PreOrder(root->left,target) ;\n PreOrder(root->right,target) ;\n }\n \n \n \n \n \n\n int minTime(Node* root, int target) \n {\n \n if(!root)\n return 0 ;\n \n mp[root] = NULL ;\n int t= 0;\n Node* r=root;\n \n PreOrder(root, target);\n \n \n queue<Node* > q ;\n q.push(T);\n \n while(!q.empty())\n {\n int sz=q.size(); \n \n while(sz--)\n {\n Node *temp = q.front() ;\n q.pop();\n \n \n \n if(temp->left and !visited[temp->left])\n {\n q.push(temp->left) ;visited[temp->left] =1 ;\n \n }\n \n if(temp->right and !visited[temp->right])\n {\n q.push(temp->right) ; visited[temp->right]=1 ;\n \n }\n \n if(mp[temp]and !visited[mp[temp]])\n {\n \n q.push(mp[temp]) ;visited[mp[temp]]=1;\n \n }\n }\n \n t++ ;\n }\n return t-1;\n }\n \n\n};" }, { "code": null, "e": 17277, "s": 17274, "text": "+1" }, { "code": null, "e": 17310, "s": 17277, "text": "himanshu11042003singh1 month ago" }, { "code": null, "e": 19136, "s": 17310, "text": "class Solution { public: Node* createParentMapping(Node* root,int target,map<Node*,Node*>&nodeToParent){ Node* res= NULL; queue<Node*>q; q.push(root); nodeToParent[root]=NULL; while(!q.empty()){ Node* front= q.front(); q.pop(); if(front->data==target){ res= front; } if(front->left){ nodeToParent[front->left]=front; q.push(front->left); } if(front->right){ nodeToParent[front->right]=front; q.push(front->right); } } return res; } int burnTree(Node* root,map<Node*,Node*>&nodeToParent){ map<Node*,bool>visited; queue<Node*>q; q.push(root); visited[root]=true; int ans=0; while(!q.empty()){ bool flag=0; int size=q.size(); for(int i=0;i<size;i++){ Node* front= q.front(); q.pop(); if(front->left&&!visited[front->left]){ flag=1; q.push(front->left); visited[front->left]=1; } if(front->right&&!visited[front->right]){ flag=1; q.push(front->right); visited[front->right]=1; } if(nodeToParent[front]&&!visited[nodeToParent[front]]){ flag=1; q.push(nodeToParent[front]); visited[nodeToParent[front]]=1; } } if(flag==1){ ans++; } } return ans; } int minTime(Node* root, int target) { // Your code goes here map<Node*,Node*>nodeToParent; Node* targetNode= createParentMapping(root,target,nodeToParent); int ans= burnTree(targetNode,nodeToParent); return ans; }};" }, { "code": null, "e": 19282, "s": 19136, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 19318, "s": 19282, "text": " Login to access your submissions. " }, { "code": null, "e": 19328, "s": 19318, "text": "\nProblem\n" }, { "code": null, "e": 19338, "s": 19328, "text": "\nContest\n" }, { "code": null, "e": 19401, "s": 19338, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 19549, "s": 19401, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 19757, "s": 19549, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 19863, "s": 19757, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
D3.js image() Function - GeeksforGeeks
17 Aug, 2020 The d3.image() function in D3.js is a part of the request API that is used to fetch the images from any given image URL. If init is also given in the function then it sets any additional properties on the image before loading the image. Syntax: d3.image(input[, init]); Parameters: This function accepts a single parameter as mentioned above and described below: input: It takes the address of the image to be fetched. Return Values: It returns the image from the image URL. Below examples illustrate the D3.js image() Function in JavaScript. Example1: HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" path1tent="width=device-width, initial-scale=1.0"/> <title>D3.js image() Function</title> </head> <style></style> <body> <script src="https://d3js.org/d3.v4.min.js"> </script> <script src="https://d3js.org/d3-dsv.v1.min.js"> </script> <script src="https://d3js.org/d3-fetch.v1.min.js"> </script> <script> d3.image("https://robohash.org/image", { crossOrigin: "anonymous" }).then((img) => { console.log(img); }); </script> </body></html> Output: Example 2: HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" path1tent="width=device-width, initial-scale=1.0"/> <title>D3.js image() Function</title> </head> <style></style> <body> <script src="https://d3js.org/d3.v4.min.js"> </script> <script src="https://d3js.org/d3-dsv.v1.min.js"> </script> <script src="https://d3js.org/d3-fetch.v1.min.js"> </script> <script> d3.image(`https://pbs.twimg.com/profile_images/1138375574726955008/1fNUyEdv_400x400.png`, { crossOrigin: "anonymous" }).then((img) => { document.body.append("Image using d3.image()"); document.body.append(img); }); </script> </body></html> Output: D3.js JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request Angular File Upload How to get selected value in dropdown list using JavaScript ? How to remove duplicate elements from JavaScript Array ? Installation of Node.js on Linux Roadmap to Become a Web Developer in 2022 How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 25220, "s": 25192, "text": "\n17 Aug, 2020" }, { "code": null, "e": 25459, "s": 25220, "text": "The d3.image() function in D3.js is a part of the request API that is used to fetch the images from any given image URL. If init is also given in the function then it sets any additional properties on the image before loading the image. " }, { "code": null, "e": 25467, "s": 25459, "text": "Syntax:" }, { "code": null, "e": 25493, "s": 25467, "text": "d3.image(input[, init]);\n" }, { "code": null, "e": 25586, "s": 25493, "text": "Parameters: This function accepts a single parameter as mentioned above and described below:" }, { "code": null, "e": 25642, "s": 25586, "text": "input: It takes the address of the image to be fetched." }, { "code": null, "e": 25698, "s": 25642, "text": "Return Values: It returns the image from the image URL." }, { "code": null, "e": 25766, "s": 25698, "text": "Below examples illustrate the D3.js image() Function in JavaScript." }, { "code": null, "e": 25776, "s": 25766, "text": "Example1:" }, { "code": null, "e": 25781, "s": 25776, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" path1tent=\"width=device-width, initial-scale=1.0\"/> <title>D3.js image() Function</title> </head> <style></style> <body> <script src=\"https://d3js.org/d3.v4.min.js\"> </script> <script src=\"https://d3js.org/d3-dsv.v1.min.js\"> </script> <script src=\"https://d3js.org/d3-fetch.v1.min.js\"> </script> <script> d3.image(\"https://robohash.org/image\", { crossOrigin: \"anonymous\" }).then((img) => { console.log(img); }); </script> </body></html>", "e": 26501, "s": 25781, "text": null }, { "code": null, "e": 26509, "s": 26501, "text": "Output:" }, { "code": null, "e": 26520, "s": 26509, "text": "Example 2:" }, { "code": null, "e": 26525, "s": 26520, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" path1tent=\"width=device-width, initial-scale=1.0\"/> <title>D3.js image() Function</title> </head> <style></style> <body> <script src=\"https://d3js.org/d3.v4.min.js\"> </script> <script src=\"https://d3js.org/d3-dsv.v1.min.js\"> </script> <script src=\"https://d3js.org/d3-fetch.v1.min.js\"> </script> <script> d3.image(`https://pbs.twimg.com/profile_images/1138375574726955008/1fNUyEdv_400x400.png`, { crossOrigin: \"anonymous\" }).then((img) => { document.body.append(\"Image using d3.image()\"); document.body.append(img); }); </script> </body></html>", "e": 27361, "s": 26525, "text": null }, { "code": null, "e": 27369, "s": 27361, "text": "Output:" }, { "code": null, "e": 27375, "s": 27369, "text": "D3.js" }, { "code": null, "e": 27386, "s": 27375, "text": "JavaScript" }, { "code": null, "e": 27403, "s": 27386, "text": "Web Technologies" }, { "code": null, "e": 27501, "s": 27403, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27510, "s": 27501, "text": "Comments" }, { "code": null, "e": 27523, "s": 27510, "text": "Old Comments" }, { "code": null, "e": 27584, "s": 27523, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 27625, "s": 27584, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 27645, "s": 27625, "text": "Angular File Upload" }, { "code": null, "e": 27707, "s": 27645, "text": "How to get selected value in dropdown list using JavaScript ?" }, { "code": null, "e": 27764, "s": 27707, "text": "How to remove duplicate elements from JavaScript Array ?" }, { "code": null, "e": 27797, "s": 27764, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27839, "s": 27797, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 27882, "s": 27839, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 27944, "s": 27882, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
Python - Modules
A module allows you to logically organize your Python code. Grouping related code into a module makes the code easier to understand and use. A module is a Python object with arbitrarily named attributes that you can bind and reference. Simply, a module is a file consisting of Python code. A module can define functions, classes and variables. A module can also include runnable code. The Python code for a module named aname normally resides in a file named aname.py. Here's an example of a simple module, support.py def print_func( par ): print "Hello : ", par return You can use any Python source file as a module by executing an import statement in some other Python source file. The import has the following syntax − import module1[, module2[,... moduleN] When the interpreter encounters an import statement, it imports the module if the module is present in the search path. A search path is a list of directories that the interpreter searches before importing a module. For example, to import the module support.py, you need to put the following command at the top of the script − #!/usr/bin/python # Import module support import support # Now you can call defined function that module as follows support.print_func("Zara") When the above code is executed, it produces the following result − Hello : Zara A module is loaded only once, regardless of the number of times it is imported. This prevents the module execution from happening over and over again if multiple imports occur. Python's from statement lets you import specific attributes from a module into the current namespace. The from...import has the following syntax − from modname import name1[, name2[, ... nameN]] For example, to import the function fibonacci from the module fib, use the following statement − from fib import fibonacci This statement does not import the entire module fib into the current namespace; it just introduces the item fibonacci from the module fib into the global symbol table of the importing module. It is also possible to import all names from a module into the current namespace by using the following import statement − from modname import * This provides an easy way to import all the items from a module into the current namespace; however, this statement should be used sparingly. When you import a module, the Python interpreter searches for the module in the following sequences − The current directory. The current directory. If the module isn't found, Python then searches each directory in the shell variable PYTHONPATH. If the module isn't found, Python then searches each directory in the shell variable PYTHONPATH. If all else fails, Python checks the default path. On UNIX, this default path is normally /usr/local/lib/python/. If all else fails, Python checks the default path. On UNIX, this default path is normally /usr/local/lib/python/. The module search path is stored in the system module sys as the sys.path variable. The sys.path variable contains the current directory, PYTHONPATH, and the installation-dependent default. The PYTHONPATH is an environment variable, consisting of a list of directories. The syntax of PYTHONPATH is the same as that of the shell variable PATH. Here is a typical PYTHONPATH from a Windows system − set PYTHONPATH = c:\python20\lib; And here is a typical PYTHONPATH from a UNIX system − set PYTHONPATH = /usr/local/lib/python Variables are names (identifiers) that map to objects. A namespace is a dictionary of variable names (keys) and their corresponding objects (values). A Python statement can access variables in a local namespace and in the global namespace. If a local and a global variable have the same name, the local variable shadows the global variable. Each function has its own local namespace. Class methods follow the same scoping rule as ordinary functions. Python makes educated guesses on whether variables are local or global. It assumes that any variable assigned a value in a function is local. Therefore, in order to assign a value to a global variable within a function, you must first use the global statement. The statement global VarName tells Python that VarName is a global variable. Python stops searching the local namespace for the variable. For example, we define a variable Money in the global namespace. Within the function Money, we assign Money a value, therefore Python assumes Money as a local variable. However, we accessed the value of the local variable Money before setting it, so an UnboundLocalError is the result. Uncommenting the global statement fixes the problem. #!/usr/bin/python Money = 2000 def AddMoney(): # Uncomment the following line to fix the code: # global Money Money = Money + 1 print Money AddMoney() print Money The dir() built-in function returns a sorted list of strings containing the names defined by a module. The list contains the names of all the modules, variables and functions that are defined in a module. Following is a simple example − #!/usr/bin/python # Import built-in module math import math content = dir(math) print content When the above code is executed, it produces the following result − ['__doc__', '__file__', '__name__', 'acos', 'asin', 'atan', 'atan2', 'ceil', 'cos', 'cosh', 'degrees', 'e', 'exp', 'fabs', 'floor', 'fmod', 'frexp', 'hypot', 'ldexp', 'log', 'log10', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh'] Here, the special string variable __name__ is the module's name, and __file__ is the filename from which the module was loaded. The globals() and locals() functions can be used to return the names in the global and local namespaces depending on the location from where they are called. If locals() is called from within a function, it will return all the names that can be accessed locally from that function. If globals() is called from within a function, it will return all the names that can be accessed globally from that function. The return type of both these functions is dictionary. Therefore, names can be extracted using the keys() function. When the module is imported into a script, the code in the top-level portion of a module is executed only once. Therefore, if you want to reexecute the top-level code in a module, you can use the reload() function. The reload() function imports a previously imported module again. The syntax of the reload() function is this − reload(module_name) Here, module_name is the name of the module you want to reload and not the string containing the module name. For example, to reload hello module, do the following − reload(hello) A package is a hierarchical file directory structure that defines a single Python application environment that consists of modules and subpackages and sub-subpackages, and so on. Consider a file Pots.py available in Phone directory. This file has following line of source code − #!/usr/bin/python def Pots(): print "I'm Pots Phone" Similar way, we have another two files having different functions with the same name as above − Phone/Isdn.py file having function Isdn() Phone/Isdn.py file having function Isdn() Phone/G3.py file having function G3() Phone/G3.py file having function G3() Now, create one more file __init__.py in Phone directory − Phone/__init__.py To make all of your functions available when you've imported Phone, you need to put explicit import statements in __init__.py as follows − from Pots import Pots from Isdn import Isdn from G3 import G3 After you add these lines to __init__.py, you have all of these classes available when you import the Phone package. #!/usr/bin/python # Now import your Phone Package. import Phone Phone.Pots() Phone.Isdn() Phone.G3() When the above code is executed, it produces the following result − I'm Pots Phone I'm 3G Phone I'm ISDN Phone In the above example, we have taken example of a single functions in each file, but you can keep multiple functions in your files. You can also define different Python classes in those files and then you can create your packages out of those classes. 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": 2480, "s": 2244, "text": "A module allows you to logically organize your Python code. Grouping related code into a module makes the code easier to understand and use. A module is a Python object with arbitrarily named attributes that you can bind and reference." }, { "code": null, "e": 2629, "s": 2480, "text": "Simply, a module is a file consisting of Python code. A module can define functions, classes and variables. A module can also include runnable code." }, { "code": null, "e": 2762, "s": 2629, "text": "The Python code for a module named aname normally resides in a file named aname.py. Here's an example of a simple module, support.py" }, { "code": null, "e": 2820, "s": 2762, "text": "def print_func( par ):\n print \"Hello : \", par\n return" }, { "code": null, "e": 2972, "s": 2820, "text": "You can use any Python source file as a module by executing an import statement in some other Python source file. The import has the following syntax −" }, { "code": null, "e": 3012, "s": 2972, "text": "import module1[, module2[,... moduleN]\n" }, { "code": null, "e": 3339, "s": 3012, "text": "When the interpreter encounters an import statement, it imports the module if the module is present in the search path. A search path is a list of directories that the interpreter searches before importing a module. For example, to import the module support.py, you need to put the following command at the top of the script −" }, { "code": null, "e": 3484, "s": 3339, "text": "#!/usr/bin/python\n\n# Import module support\nimport support\n\n# Now you can call defined function that module as follows\nsupport.print_func(\"Zara\")" }, { "code": null, "e": 3553, "s": 3484, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 3567, "s": 3553, "text": "Hello : Zara\n" }, { "code": null, "e": 3744, "s": 3567, "text": "A module is loaded only once, regardless of the number of times it is imported. This prevents the module execution from happening over and over again if multiple imports occur." }, { "code": null, "e": 3891, "s": 3744, "text": "Python's from statement lets you import specific attributes from a module into the current namespace. The from...import has the following syntax −" }, { "code": null, "e": 3940, "s": 3891, "text": "from modname import name1[, name2[, ... nameN]]\n" }, { "code": null, "e": 4037, "s": 3940, "text": "For example, to import the function fibonacci from the module fib, use the following statement −" }, { "code": null, "e": 4064, "s": 4037, "text": "from fib import fibonacci\n" }, { "code": null, "e": 4257, "s": 4064, "text": "This statement does not import the entire module fib into the current namespace; it just introduces the item fibonacci from the module fib into the global symbol table of the importing module." }, { "code": null, "e": 4380, "s": 4257, "text": "It is also possible to import all names from a module into the current namespace by using the following import statement −" }, { "code": null, "e": 4403, "s": 4380, "text": "from modname import *\n" }, { "code": null, "e": 4545, "s": 4403, "text": "This provides an easy way to import all the items from a module into the current namespace; however, this statement should be used sparingly." }, { "code": null, "e": 4647, "s": 4545, "text": "When you import a module, the Python interpreter searches for the module in the following sequences −" }, { "code": null, "e": 4670, "s": 4647, "text": "The current directory." }, { "code": null, "e": 4693, "s": 4670, "text": "The current directory." }, { "code": null, "e": 4790, "s": 4693, "text": "If the module isn't found, Python then searches each directory in the shell variable PYTHONPATH." }, { "code": null, "e": 4887, "s": 4790, "text": "If the module isn't found, Python then searches each directory in the shell variable PYTHONPATH." }, { "code": null, "e": 5001, "s": 4887, "text": "If all else fails, Python checks the default path. On UNIX, this default path is normally /usr/local/lib/python/." }, { "code": null, "e": 5115, "s": 5001, "text": "If all else fails, Python checks the default path. On UNIX, this default path is normally /usr/local/lib/python/." }, { "code": null, "e": 5305, "s": 5115, "text": "The module search path is stored in the system module sys as the sys.path variable. The sys.path variable contains the current directory, PYTHONPATH, and the installation-dependent default." }, { "code": null, "e": 5458, "s": 5305, "text": "The PYTHONPATH is an environment variable, consisting of a list of directories. The syntax of PYTHONPATH is the same as that of the shell variable PATH." }, { "code": null, "e": 5511, "s": 5458, "text": "Here is a typical PYTHONPATH from a Windows system −" }, { "code": null, "e": 5546, "s": 5511, "text": "set PYTHONPATH = c:\\python20\\lib;\n" }, { "code": null, "e": 5600, "s": 5546, "text": "And here is a typical PYTHONPATH from a UNIX system −" }, { "code": null, "e": 5640, "s": 5600, "text": "set PYTHONPATH = /usr/local/lib/python\n" }, { "code": null, "e": 5790, "s": 5640, "text": "Variables are names (identifiers) that map to objects. A namespace is a dictionary of variable names (keys) and their corresponding objects (values)." }, { "code": null, "e": 5981, "s": 5790, "text": "A Python statement can access variables in a local namespace and in the global namespace. If a local and a global variable have the same name, the local variable shadows the global variable." }, { "code": null, "e": 6090, "s": 5981, "text": "Each function has its own local namespace. Class methods follow the same scoping rule as ordinary functions." }, { "code": null, "e": 6232, "s": 6090, "text": "Python makes educated guesses on whether variables are local or global. It assumes that any variable assigned a value in a function is local." }, { "code": null, "e": 6351, "s": 6232, "text": "Therefore, in order to assign a value to a global variable within a function, you must first use the global statement." }, { "code": null, "e": 6489, "s": 6351, "text": "The statement global VarName tells Python that VarName is a global variable. Python stops searching the local namespace for the variable." }, { "code": null, "e": 6829, "s": 6489, "text": "For example, we define a variable Money in the global namespace. Within the function Money, we assign Money a value, therefore Python assumes Money as a local variable. However, we accessed the value of the local variable Money before setting it, so an UnboundLocalError is the result. Uncommenting the global statement fixes the problem." }, { "code": null, "e": 7003, "s": 6829, "text": "#!/usr/bin/python\n\nMoney = 2000\ndef AddMoney():\n # Uncomment the following line to fix the code:\n # global Money\n Money = Money + 1\n\nprint Money\nAddMoney()\nprint Money" }, { "code": null, "e": 7106, "s": 7003, "text": "The dir() built-in function returns a sorted list of strings containing the names defined by a module." }, { "code": null, "e": 7240, "s": 7106, "text": "The list contains the names of all the modules, variables and functions that are defined in a module. Following is a simple example −" }, { "code": null, "e": 7336, "s": 7240, "text": "#!/usr/bin/python\n\n# Import built-in module math\nimport math\n\ncontent = dir(math)\nprint content" }, { "code": null, "e": 7405, "s": 7336, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 7662, "s": 7405, "text": "['__doc__', '__file__', '__name__', 'acos', 'asin', 'atan', \n'atan2', 'ceil', 'cos', 'cosh', 'degrees', 'e', 'exp', \n'fabs', 'floor', 'fmod', 'frexp', 'hypot', 'ldexp', 'log',\n'log10', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', \n'sqrt', 'tan', 'tanh']\n" }, { "code": null, "e": 7791, "s": 7662, "text": "Here, the special string variable __name__ is the module's name, and __file__ is the filename from which the module was loaded." }, { "code": null, "e": 7949, "s": 7791, "text": "The globals() and locals() functions can be used to return the names in the global and local namespaces depending on the location from where they are called." }, { "code": null, "e": 8073, "s": 7949, "text": "If locals() is called from within a function, it will return all the names that can be accessed locally from that function." }, { "code": null, "e": 8199, "s": 8073, "text": "If globals() is called from within a function, it will return all the names that can be accessed globally from that function." }, { "code": null, "e": 8315, "s": 8199, "text": "The return type of both these functions is dictionary. Therefore, names can be extracted using the keys() function." }, { "code": null, "e": 8427, "s": 8315, "text": "When the module is imported into a script, the code in the top-level portion of a module is executed only once." }, { "code": null, "e": 8642, "s": 8427, "text": "Therefore, if you want to reexecute the top-level code in a module, you can use the reload() function. The reload() function imports a previously imported module again. The syntax of the reload() function is this −" }, { "code": null, "e": 8663, "s": 8642, "text": "reload(module_name)\n" }, { "code": null, "e": 8829, "s": 8663, "text": "Here, module_name is the name of the module you want to reload and not the string containing the module name. For example, to reload hello module, do the following −" }, { "code": null, "e": 8844, "s": 8829, "text": "reload(hello)\n" }, { "code": null, "e": 9023, "s": 8844, "text": "A package is a hierarchical file directory structure that defines a single Python application environment that consists of modules and subpackages and sub-subpackages, and so on." }, { "code": null, "e": 9124, "s": 9023, "text": "Consider a file Pots.py available in Phone directory. This file has following line of source code −" }, { "code": null, "e": 9181, "s": 9124, "text": "#!/usr/bin/python\n\ndef Pots():\n print \"I'm Pots Phone\"" }, { "code": null, "e": 9277, "s": 9181, "text": "Similar way, we have another two files having different functions with the same name as above −" }, { "code": null, "e": 9319, "s": 9277, "text": "Phone/Isdn.py file having function Isdn()" }, { "code": null, "e": 9361, "s": 9319, "text": "Phone/Isdn.py file having function Isdn()" }, { "code": null, "e": 9399, "s": 9361, "text": "Phone/G3.py file having function G3()" }, { "code": null, "e": 9437, "s": 9399, "text": "Phone/G3.py file having function G3()" }, { "code": null, "e": 9496, "s": 9437, "text": "Now, create one more file __init__.py in Phone directory −" }, { "code": null, "e": 9514, "s": 9496, "text": "Phone/__init__.py" }, { "code": null, "e": 9653, "s": 9514, "text": "To make all of your functions available when you've imported Phone, you need to put explicit import statements in __init__.py as follows −" }, { "code": null, "e": 9716, "s": 9653, "text": "from Pots import Pots\nfrom Isdn import Isdn\nfrom G3 import G3\n" }, { "code": null, "e": 9833, "s": 9716, "text": "After you add these lines to __init__.py, you have all of these classes available when you import the Phone package." }, { "code": null, "e": 9936, "s": 9833, "text": "#!/usr/bin/python\n\n# Now import your Phone Package.\nimport Phone\n\nPhone.Pots()\nPhone.Isdn()\nPhone.G3()" }, { "code": null, "e": 10005, "s": 9936, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 10049, "s": 10005, "text": "I'm Pots Phone\nI'm 3G Phone\nI'm ISDN Phone\n" }, { "code": null, "e": 10300, "s": 10049, "text": "In the above example, we have taken example of a single functions in each file, but you can keep multiple functions in your files. You can also define different Python classes in those files and then you can create your packages out of those classes." }, { "code": null, "e": 10337, "s": 10300, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 10353, "s": 10337, "text": " Malhar Lathkar" }, { "code": null, "e": 10386, "s": 10353, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 10405, "s": 10386, "text": " Arnab Chakraborty" }, { "code": null, "e": 10440, "s": 10405, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 10462, "s": 10440, "text": " In28Minutes Official" }, { "code": null, "e": 10496, "s": 10462, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 10524, "s": 10496, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 10559, "s": 10524, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 10573, "s": 10559, "text": " Lets Kode It" }, { "code": null, "e": 10606, "s": 10573, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 10623, "s": 10606, "text": " Abhilash Nelson" }, { "code": null, "e": 10630, "s": 10623, "text": " Print" }, { "code": null, "e": 10641, "s": 10630, "text": " Add Notes" } ]
Data Manipulation Commands in DBMS
Data manipulation commands are used to manipulate data in the database. Some of the Data Manipulation Commands are- Select statement retrieves the data from database according to the constraints specifies alongside. SELECT <COLUMN NAME> FROM <TABLE NAME> WHERE <CONDITION> GROUP BY <COLUMN LIST> HAVING <CRITERIA FOR FUNCTION RESULTS> ORDER BY <COLUMN LIST> General syntax − Example: select * from employee where e_id>100; Insert statement is used to insert data into database tables. General Syntax − INSERT INTO <TABLE NAME> (<COLUMNS TO INSERT>) VALUES (<VALUES TO INSERT>) Example: insert into Employee (name, dept_id) values (‘ABC’, 3); The update command updates existing data within a table. General syntax − UPDATE <TABLE NAME> SET <COLUMN NAME> = <UPDATED COLUMN VALUE>, <COLUMN NAME> = <UPDATED COLUMN VALUE>, <COLUMN NAME> = <UPDATED COLUMN VALUE>,... WHERE <CONDITION> Example: update Employee set Name=’AMIT’ where E_id=5; Deletes records from the database table according to the given constraints. General Syntax − DELETE FROM <TABLE NAME> WHERE <CONDITION> Example − delete from Employee where e_id=5; To delete all records from the table − Delete * from <TABLE NAME>; Use the MERGE statement to select rows from one table for update or insertion into another table. The decision whether to update or insert into the target table is based on a condition in the ON clause. It is also known as UPSERT i.e. combination of UPDATE and INSERT. General Syntax (SQL) − MERGE <TARGET TABLE> [AS TARGET] USING <SOURCE TABLE> [AS SOURCE] ON <SEARCH CONDITION> [WHEN MATCHED THEN <MERGE MATCHED > ] [WHEN NOT MATCHED [BY TARGET] THEN < MERGE NOT MATCHED >] [WHEN NOT MATCHED BY SOURCE THEN <MERGE MATCHED >]; General Syntax (Oracle) MERGE INTO <TARGET TABLE> USING <SOURCE TABLE> ON <SEARCH CONDITION> [WHEN MATCHED THEN <MERGE MATCHED > ] [WHEN NOT MATCHED THEN < MERGE NOT MATCHED > ];
[ { "code": null, "e": 1134, "s": 1062, "text": "Data manipulation commands are used to manipulate data in the database." }, { "code": null, "e": 1178, "s": 1134, "text": "Some of the Data Manipulation Commands are-" }, { "code": null, "e": 1278, "s": 1178, "text": "Select statement retrieves the data from database according to the constraints specifies alongside." }, { "code": null, "e": 1420, "s": 1278, "text": "SELECT <COLUMN NAME>\nFROM <TABLE NAME>\nWHERE <CONDITION>\nGROUP BY <COLUMN LIST>\nHAVING <CRITERIA FOR FUNCTION RESULTS>\nORDER BY <COLUMN LIST>" }, { "code": null, "e": 1437, "s": 1420, "text": "General syntax −" }, { "code": null, "e": 1485, "s": 1437, "text": "Example: select * from employee where e_id>100;" }, { "code": null, "e": 1547, "s": 1485, "text": "Insert statement is used to insert data into database tables." }, { "code": null, "e": 1565, "s": 1547, "text": "General Syntax − " }, { "code": null, "e": 1640, "s": 1565, "text": "INSERT INTO <TABLE NAME> (<COLUMNS TO INSERT>) VALUES (<VALUES TO INSERT>)" }, { "code": null, "e": 1705, "s": 1640, "text": "Example: insert into Employee (name, dept_id) values (‘ABC’, 3);" }, { "code": null, "e": 1762, "s": 1705, "text": "The update command updates existing data within a table." }, { "code": null, "e": 1779, "s": 1762, "text": "General syntax −" }, { "code": null, "e": 1944, "s": 1779, "text": "UPDATE <TABLE NAME>\nSET <COLUMN NAME> = <UPDATED COLUMN VALUE>,\n<COLUMN NAME> = <UPDATED COLUMN VALUE>,\n<COLUMN NAME> = <UPDATED COLUMN VALUE>,...\nWHERE <CONDITION>" }, { "code": null, "e": 1999, "s": 1944, "text": "Example: update Employee set Name=’AMIT’ where E_id=5;" }, { "code": null, "e": 2075, "s": 1999, "text": "Deletes records from the database table according to the given constraints." }, { "code": null, "e": 2092, "s": 2075, "text": "General Syntax −" }, { "code": null, "e": 2135, "s": 2092, "text": "DELETE FROM <TABLE NAME>\nWHERE <CONDITION>" }, { "code": null, "e": 2145, "s": 2135, "text": "Example −" }, { "code": null, "e": 2180, "s": 2145, "text": "delete from Employee where e_id=5;" }, { "code": null, "e": 2219, "s": 2180, "text": "To delete all records from the table −" }, { "code": null, "e": 2247, "s": 2219, "text": "Delete * from <TABLE NAME>;" }, { "code": null, "e": 2516, "s": 2247, "text": "Use the MERGE statement to select rows from one table for update or insertion into another table. The decision whether to update or insert into the target table is based on a condition in the ON clause. It is also known as UPSERT i.e. combination of UPDATE and INSERT." }, { "code": null, "e": 2539, "s": 2516, "text": "General Syntax (SQL) −" }, { "code": null, "e": 2777, "s": 2539, "text": "MERGE <TARGET TABLE> [AS TARGET]\nUSING <SOURCE TABLE> [AS SOURCE]\nON <SEARCH CONDITION>\n[WHEN MATCHED\nTHEN <MERGE MATCHED > ]\n[WHEN NOT MATCHED [BY TARGET]\nTHEN < MERGE NOT MATCHED >]\n[WHEN NOT MATCHED BY SOURCE\nTHEN <MERGE MATCHED >];" }, { "code": null, "e": 2801, "s": 2777, "text": "General Syntax (Oracle)" }, { "code": null, "e": 2956, "s": 2801, "text": "MERGE INTO <TARGET TABLE>\nUSING <SOURCE TABLE>\nON <SEARCH CONDITION>\n[WHEN MATCHED\nTHEN <MERGE MATCHED > ]\n[WHEN NOT MATCHED\nTHEN < MERGE NOT MATCHED > ];" } ]
Groovy - For Statement
The for statement is used to iterate through a set of values. The for statement is generally used in the following way. for(variable declaration;expression;Increment) { statement #1 statement #2 ... } The classic for statement consists of the following parts − Variable declaration − This step is executed only once for the entire loop and used to declare any variables which will be used within the loop. Variable declaration − This step is executed only once for the entire loop and used to declare any variables which will be used within the loop. Expression − This will consists of an expression which will be evaluated for each iteration of the loop. Expression − This will consists of an expression which will be evaluated for each iteration of the loop. The increment section will contain the logic needed increment the variable declared in the for statement. The increment section will contain the logic needed increment the variable declared in the for statement. The following diagram shows the diagrammatic explanation of this loop. Following is an example of the classic for statement − class Example { static void main(String[] args) { for(int i = 0;i<5;i++) { println(i); } } } In the above example, we are in our for loop doing three things − Declaring a variable i and Initializing the value of i to 0 Declaring a variable i and Initializing the value of i to 0 Putting a conditional expression that the for loop should execute till the value of i is less than 5. Putting a conditional expression that the for loop should execute till the value of i is less than 5. Increment the value of i by 1 for each iteration. Increment the value of i by 1 for each iteration. The output of the above code would be − 0 1 2 3 4 52 Lectures 8 hours Krishna Sakinala 49 Lectures 2.5 hours Packt Publishing Print Add Notes Bookmark this page
[ { "code": null, "e": 2358, "s": 2238, "text": "The for statement is used to iterate through a set of values. The for statement is generally used in the following way." }, { "code": null, "e": 2453, "s": 2358, "text": "for(variable declaration;expression;Increment) { \n statement #1 \n statement #2 \n ... \n}\n" }, { "code": null, "e": 2513, "s": 2453, "text": "The classic for statement consists of the following parts −" }, { "code": null, "e": 2658, "s": 2513, "text": "Variable declaration − This step is executed only once for the entire loop and used to declare any variables which will be used within the loop." }, { "code": null, "e": 2803, "s": 2658, "text": "Variable declaration − This step is executed only once for the entire loop and used to declare any variables which will be used within the loop." }, { "code": null, "e": 2908, "s": 2803, "text": "Expression − This will consists of an expression which will be evaluated for each iteration of the loop." }, { "code": null, "e": 3013, "s": 2908, "text": "Expression − This will consists of an expression which will be evaluated for each iteration of the loop." }, { "code": null, "e": 3119, "s": 3013, "text": "The increment section will contain the logic needed increment the variable declared in the for statement." }, { "code": null, "e": 3225, "s": 3119, "text": "The increment section will contain the logic needed increment the variable declared in the for statement." }, { "code": null, "e": 3296, "s": 3225, "text": "The following diagram shows the diagrammatic explanation of this loop." }, { "code": null, "e": 3351, "s": 3296, "text": "Following is an example of the classic for statement −" }, { "code": null, "e": 3477, "s": 3351, "text": "class Example { \n static void main(String[] args) {\n\t\n for(int i = 0;i<5;i++) {\n println(i);\n }\n\t\t\n }\n}" }, { "code": null, "e": 3543, "s": 3477, "text": "In the above example, we are in our for loop doing three things −" }, { "code": null, "e": 3603, "s": 3543, "text": "Declaring a variable i and Initializing the value of i to 0" }, { "code": null, "e": 3663, "s": 3603, "text": "Declaring a variable i and Initializing the value of i to 0" }, { "code": null, "e": 3765, "s": 3663, "text": "Putting a conditional expression that the for loop should execute till the value of i is less than 5." }, { "code": null, "e": 3867, "s": 3765, "text": "Putting a conditional expression that the for loop should execute till the value of i is less than 5." }, { "code": null, "e": 3917, "s": 3867, "text": "Increment the value of i by 1 for each iteration." }, { "code": null, "e": 3967, "s": 3917, "text": "Increment the value of i by 1 for each iteration." }, { "code": null, "e": 4007, "s": 3967, "text": "The output of the above code would be −" }, { "code": null, "e": 4023, "s": 4007, "text": "0 \n1 \n2 \n3 \n4 \n" }, { "code": null, "e": 4056, "s": 4023, "text": "\n 52 Lectures \n 8 hours \n" }, { "code": null, "e": 4074, "s": 4056, "text": " Krishna Sakinala" }, { "code": null, "e": 4109, "s": 4074, "text": "\n 49 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4127, "s": 4109, "text": " Packt Publishing" }, { "code": null, "e": 4134, "s": 4127, "text": " Print" }, { "code": null, "e": 4145, "s": 4134, "text": " Add Notes" } ]
Procurement Process Optimization with Python | by Samir Saci | Towards Data Science
Procurement management is a strategic approach to acquiring goods or services from preferred vendors, within your determined budget, either on or before a specific deadline. Your target is to balance supply and demand in a manner to ensure a minimum level of inventory to meet your store demand. In this article, we will present a simple methodology using Non-Linear Programming to design an optimal inventory replenishment strategy for a mid-size retail store considering: Transportation Costs from the Supplier Warehouse to the Store Reserve ($/Carton) Costs to finance your inventory (% of inventory value in $) Reserve (Store’s Warehouse) Rental Costs for storage ($/Carton) SUMMARYI. ScenarioAs a Supply Planning manager you need to optimize inventory allocation to reduce transportation costs.II. Build your Model1. Declare your decision variablesWhat are you trying to decide?2. Declare your objective functionWhat do you want to minimize?3. Define the constraintsWhat are the limits in resources?4. Solve the model and prepare the resultsWhat is the suggestion of the model?III. Conclusion & Next Steps As a Store Manager of a mid-size retail location, you are in charge of setting the replenishment quantity in the ERP. For each SKU, when the inventory level is below a certain threshold your ERP is sending an automatic Purchase Order (PO) to your supplier. You need to balance with the constraints of stock capacity, transportation costs and cost of inventory to fix the right quantity for your PO. 1 supplier that receives your orders via EDI connection (with your ERP) and ships them using a 3rd Party Transportation company at your expenseNote: we’ll not consider any lead time in this article 60 active stock-keeping units (SKU) with a purchasing price ($/carton) and a yearly sales quantity (Cartons/year) Transportation using a 3rd party company that operates parcel delivery invoiced per carton ($/Carton) Storage Location (Store’s Reserve) with a capacity of 480 boxes stored on shelves To simplify the comprehension, let’s introduce some notations Annual Demand per SKU Transportation b = 42.250 $A = -0.3975 $/Carton Costs of Capital As a mid-size business, we suppose that your cost of capital is quite high: 12.5%. Storage Costs In this model, we suppose that we have the best landlord in the world. She invoices us by carton occupied taking the average value per year. We will not pay for the empty locations. Imax= 480Rmonth= 2,000 $/Month Question Which Quantity per replenishment Qi should you set in the ERP to minimize the total costs? Unlike the previous article of the series, we won’t use PuLP as we are not in a linear programming problem. We will be using the SciPy optimization functions to solve this non-linear minimization problem. You can find the full code in this Github (Follow Me :D) repository: Link.My portfolio with other projects: Samir Saci What are you trying to decide? We want to set the quantity per replenishment order sent by our ERP to the supplier. However, to simplify our calculation we will use the number of replenishment per year Ri as a decision variable. The replenishment quantity will be calculated using the formula below. Note: We accept to have a replenishment case quantity that is not an integer. What do you want to minimize? The purchasing cost itself is not included in the objective function as it is out of the scope of our optimization targets. Code What are the limits in resources that will determine your feasible region? This is where problems start as we have a non-linear constraint (1/Ri). What are the results of your simulation? Initial Guess Unlike Linear Programming, we need to provide an initial vector of a potential solution to the algorithm for the first iteration to initiate it. Here, we’ll assume that 2 replenishments per year for all SKUs could be a good candidate. $63,206.7 total cost for initial guessingHopefully the optimal solution will be lower Solve Comment I could not find any method to implement Integer Non-Linear Programming using Scipy solvers. If you have a solution, better than this quick-and-dirty rounding, using another library of python, can you please share it in the comment section? For 100 Iterations-> Initial Solution: $28,991.9-> Integer Solution: $29,221.3 with a maximum inventory of 356 cartons This optimized solution is 56% better than the initial guess of 2 replenishment per year for all references. What if we have a stochastic distribution of your demand and we want to avoid stock-outs? In the article below, you can find a simple methodology to build replenishment rules assuming a stochastic distribution of your demand. www.samirsaci.com We can see here that our solution is mainly driven by transportation costs as we have a maximum stock of 356 boxes. In the next article, we will perform an exploratory data analysis to understand the distribution of our decision variables and understand what drove the results for each reference. We’ll also try to understand what is the impact of the transformation from continuous to integer decision variables. Finally, we’ll try several scenarios to see how the model reacts: High rental costs and low transportation costs Non-linear purchasing costs Higher Minimum Order Quantity Please feel free to contact me, I am willing to share and exchange on topics related to Data Science and Supply Chain.My Portfolio: https://samirsaci.com [1] SciPy Optimization Library, Official Documentation, Link [2] Samir Saci, Supply Planning using Linear Programming with Python, Link
[ { "code": null, "e": 345, "s": 171, "text": "Procurement management is a strategic approach to acquiring goods or services from preferred vendors, within your determined budget, either on or before a specific deadline." }, { "code": null, "e": 467, "s": 345, "text": "Your target is to balance supply and demand in a manner to ensure a minimum level of inventory to meet your store demand." }, { "code": null, "e": 645, "s": 467, "text": "In this article, we will present a simple methodology using Non-Linear Programming to design an optimal inventory replenishment strategy for a mid-size retail store considering:" }, { "code": null, "e": 726, "s": 645, "text": "Transportation Costs from the Supplier Warehouse to the Store Reserve ($/Carton)" }, { "code": null, "e": 786, "s": 726, "text": "Costs to finance your inventory (% of inventory value in $)" }, { "code": null, "e": 850, "s": 786, "text": "Reserve (Store’s Warehouse) Rental Costs for storage ($/Carton)" }, { "code": null, "e": 1282, "s": 850, "text": "SUMMARYI. ScenarioAs a Supply Planning manager you need to optimize inventory allocation to reduce transportation costs.II. Build your Model1. Declare your decision variablesWhat are you trying to decide?2. Declare your objective functionWhat do you want to minimize?3. Define the constraintsWhat are the limits in resources?4. Solve the model and prepare the resultsWhat is the suggestion of the model?III. Conclusion & Next Steps" }, { "code": null, "e": 1400, "s": 1282, "text": "As a Store Manager of a mid-size retail location, you are in charge of setting the replenishment quantity in the ERP." }, { "code": null, "e": 1539, "s": 1400, "text": "For each SKU, when the inventory level is below a certain threshold your ERP is sending an automatic Purchase Order (PO) to your supplier." }, { "code": null, "e": 1681, "s": 1539, "text": "You need to balance with the constraints of stock capacity, transportation costs and cost of inventory to fix the right quantity for your PO." }, { "code": null, "e": 1879, "s": 1681, "text": "1 supplier that receives your orders via EDI connection (with your ERP) and ships them using a 3rd Party Transportation company at your expenseNote: we’ll not consider any lead time in this article" }, { "code": null, "e": 1993, "s": 1879, "text": "60 active stock-keeping units (SKU) with a purchasing price ($/carton) and a yearly sales quantity (Cartons/year)" }, { "code": null, "e": 2095, "s": 1993, "text": "Transportation using a 3rd party company that operates parcel delivery invoiced per carton ($/Carton)" }, { "code": null, "e": 2177, "s": 2095, "text": "Storage Location (Store’s Reserve) with a capacity of 480 boxes stored on shelves" }, { "code": null, "e": 2239, "s": 2177, "text": "To simplify the comprehension, let’s introduce some notations" }, { "code": null, "e": 2261, "s": 2239, "text": "Annual Demand per SKU" }, { "code": null, "e": 2276, "s": 2261, "text": "Transportation" }, { "code": null, "e": 2309, "s": 2276, "text": "b = 42.250 $A = -0.3975 $/Carton" }, { "code": null, "e": 2326, "s": 2309, "text": "Costs of Capital" }, { "code": null, "e": 2409, "s": 2326, "text": "As a mid-size business, we suppose that your cost of capital is quite high: 12.5%." }, { "code": null, "e": 2423, "s": 2409, "text": "Storage Costs" }, { "code": null, "e": 2605, "s": 2423, "text": "In this model, we suppose that we have the best landlord in the world. She invoices us by carton occupied taking the average value per year. We will not pay for the empty locations." }, { "code": null, "e": 2636, "s": 2605, "text": "Imax= 480Rmonth= 2,000 $/Month" }, { "code": null, "e": 2645, "s": 2636, "text": "Question" }, { "code": null, "e": 2736, "s": 2645, "text": "Which Quantity per replenishment Qi should you set in the ERP to minimize the total costs?" }, { "code": null, "e": 2941, "s": 2736, "text": "Unlike the previous article of the series, we won’t use PuLP as we are not in a linear programming problem. We will be using the SciPy optimization functions to solve this non-linear minimization problem." }, { "code": null, "e": 3060, "s": 2941, "text": "You can find the full code in this Github (Follow Me :D) repository: Link.My portfolio with other projects: Samir Saci" }, { "code": null, "e": 3091, "s": 3060, "text": "What are you trying to decide?" }, { "code": null, "e": 3176, "s": 3091, "text": "We want to set the quantity per replenishment order sent by our ERP to the supplier." }, { "code": null, "e": 3289, "s": 3176, "text": "However, to simplify our calculation we will use the number of replenishment per year Ri as a decision variable." }, { "code": null, "e": 3360, "s": 3289, "text": "The replenishment quantity will be calculated using the formula below." }, { "code": null, "e": 3438, "s": 3360, "text": "Note: We accept to have a replenishment case quantity that is not an integer." }, { "code": null, "e": 3468, "s": 3438, "text": "What do you want to minimize?" }, { "code": null, "e": 3592, "s": 3468, "text": "The purchasing cost itself is not included in the objective function as it is out of the scope of our optimization targets." }, { "code": null, "e": 3597, "s": 3592, "text": "Code" }, { "code": null, "e": 3672, "s": 3597, "text": "What are the limits in resources that will determine your feasible region?" }, { "code": null, "e": 3744, "s": 3672, "text": "This is where problems start as we have a non-linear constraint (1/Ri)." }, { "code": null, "e": 3785, "s": 3744, "text": "What are the results of your simulation?" }, { "code": null, "e": 3799, "s": 3785, "text": "Initial Guess" }, { "code": null, "e": 3944, "s": 3799, "text": "Unlike Linear Programming, we need to provide an initial vector of a potential solution to the algorithm for the first iteration to initiate it." }, { "code": null, "e": 4034, "s": 3944, "text": "Here, we’ll assume that 2 replenishments per year for all SKUs could be a good candidate." }, { "code": null, "e": 4120, "s": 4034, "text": "$63,206.7 total cost for initial guessingHopefully the optimal solution will be lower" }, { "code": null, "e": 4126, "s": 4120, "text": "Solve" }, { "code": null, "e": 4134, "s": 4126, "text": "Comment" }, { "code": null, "e": 4375, "s": 4134, "text": "I could not find any method to implement Integer Non-Linear Programming using Scipy solvers. If you have a solution, better than this quick-and-dirty rounding, using another library of python, can you please share it in the comment section?" }, { "code": null, "e": 4494, "s": 4375, "text": "For 100 Iterations-> Initial Solution: $28,991.9-> Integer Solution: $29,221.3 with a maximum inventory of 356 cartons" }, { "code": null, "e": 4603, "s": 4494, "text": "This optimized solution is 56% better than the initial guess of 2 replenishment per year for all references." }, { "code": null, "e": 4829, "s": 4603, "text": "What if we have a stochastic distribution of your demand and we want to avoid stock-outs? In the article below, you can find a simple methodology to build replenishment rules assuming a stochastic distribution of your demand." }, { "code": null, "e": 4847, "s": 4829, "text": "www.samirsaci.com" }, { "code": null, "e": 4963, "s": 4847, "text": "We can see here that our solution is mainly driven by transportation costs as we have a maximum stock of 356 boxes." }, { "code": null, "e": 5144, "s": 4963, "text": "In the next article, we will perform an exploratory data analysis to understand the distribution of our decision variables and understand what drove the results for each reference." }, { "code": null, "e": 5261, "s": 5144, "text": "We’ll also try to understand what is the impact of the transformation from continuous to integer decision variables." }, { "code": null, "e": 5327, "s": 5261, "text": "Finally, we’ll try several scenarios to see how the model reacts:" }, { "code": null, "e": 5374, "s": 5327, "text": "High rental costs and low transportation costs" }, { "code": null, "e": 5402, "s": 5374, "text": "Non-linear purchasing costs" }, { "code": null, "e": 5432, "s": 5402, "text": "Higher Minimum Order Quantity" }, { "code": null, "e": 5586, "s": 5432, "text": "Please feel free to contact me, I am willing to share and exchange on topics related to Data Science and Supply Chain.My Portfolio: https://samirsaci.com" }, { "code": null, "e": 5647, "s": 5586, "text": "[1] SciPy Optimization Library, Official Documentation, Link" } ]
Can I retrieve multiple documents from MongoDB by id?
Yes, to retrieve multiple docs from MongoDB by id, use the $in operator. The syntax is as follows db.yourCollectionName.find({_id:{$in:[yourValue1,yourValue2,yourValue3,...N]}}); Let us first create a collection with documents: > db.retrieveMultipleDocsByIdDemo.insertOne({"_id":10,"CustomerName":"John"}); { "acknowledged" : true, "insertedId" : 10 } > db.retrieveMultipleDocsByIdDemo.insertOne({"_id":14,"CustomerName":"Chris"}); { "acknowledged" : true, "insertedId" : 14 } > db.retrieveMultipleDocsByIdDemo.insertOne({"_id":20,"CustomerName":"Robert"}); { "acknowledged" : true, "insertedId" : 20 } > db.retrieveMultipleDocsByIdDemo.insertOne({"_id":25,"CustomerName":"Sam"}); { "acknowledged" : true, "insertedId" : 25 } > db.retrieveMultipleDocsByIdDemo.insertOne({"_id":30,"CustomerName":"Bob"}); { "acknowledged" : true, "insertedId" : 30 } > db.retrieveMultipleDocsByIdDemo.insertOne({"_id":34,"CustomerName":"Carol"}); { "acknowledged" : true, "insertedId" : 34 } Following is the query to display all documents from a collection with the help of find() method > db.retrieveMultipleDocsByIdDemo.find().pretty(); This will produce the following output { "_id" : 10, "CustomerName" : "John" } { "_id" : 14, "CustomerName" : "Chris" } { "_id" : 20, "CustomerName" : "Robert" } { "_id" : 25, "CustomerName" : "Sam" } { "_id" : 30, "CustomerName" : "Bob" } { "_id" : 34, "CustomerName" : "Carol" } Following is the query to retrieve multiple documents from MongoDB by id > db.retrieveMultipleDocsByIdDemo.find({_id:{$in:[10,20,30]}}); This will produce the following output { "_id" : 10, "CustomerName" : "John" } { "_id" : 20, "CustomerName" : "Robert" } { "_id" : 30, "CustomerName" : "Bob" }
[ { "code": null, "e": 1160, "s": 1062, "text": "Yes, to retrieve multiple docs from MongoDB by id, use the $in operator. The syntax is as follows" }, { "code": null, "e": 1241, "s": 1160, "text": "db.yourCollectionName.find({_id:{$in:[yourValue1,yourValue2,yourValue3,...N]}});" }, { "code": null, "e": 1290, "s": 1241, "text": "Let us first create a collection with documents:" }, { "code": null, "e": 2036, "s": 1290, "text": "> db.retrieveMultipleDocsByIdDemo.insertOne({\"_id\":10,\"CustomerName\":\"John\"});\n{ \"acknowledged\" : true, \"insertedId\" : 10 }\n> db.retrieveMultipleDocsByIdDemo.insertOne({\"_id\":14,\"CustomerName\":\"Chris\"});\n{ \"acknowledged\" : true, \"insertedId\" : 14 }\n> db.retrieveMultipleDocsByIdDemo.insertOne({\"_id\":20,\"CustomerName\":\"Robert\"});\n{ \"acknowledged\" : true, \"insertedId\" : 20 }\n> db.retrieveMultipleDocsByIdDemo.insertOne({\"_id\":25,\"CustomerName\":\"Sam\"});\n{ \"acknowledged\" : true, \"insertedId\" : 25 }\n> db.retrieveMultipleDocsByIdDemo.insertOne({\"_id\":30,\"CustomerName\":\"Bob\"});\n{ \"acknowledged\" : true, \"insertedId\" : 30 }\n> db.retrieveMultipleDocsByIdDemo.insertOne({\"_id\":34,\"CustomerName\":\"Carol\"});\n{ \"acknowledged\" : true, \"insertedId\" : 34 }" }, { "code": null, "e": 2133, "s": 2036, "text": "Following is the query to display all documents from a collection with the help of find() method" }, { "code": null, "e": 2184, "s": 2133, "text": "> db.retrieveMultipleDocsByIdDemo.find().pretty();" }, { "code": null, "e": 2223, "s": 2184, "text": "This will produce the following output" }, { "code": null, "e": 2465, "s": 2223, "text": "{ \"_id\" : 10, \"CustomerName\" : \"John\" }\n{ \"_id\" : 14, \"CustomerName\" : \"Chris\" }\n{ \"_id\" : 20, \"CustomerName\" : \"Robert\" }\n{ \"_id\" : 25, \"CustomerName\" : \"Sam\" }\n{ \"_id\" : 30, \"CustomerName\" : \"Bob\" }\n{ \"_id\" : 34, \"CustomerName\" : \"Carol\" }" }, { "code": null, "e": 2538, "s": 2465, "text": "Following is the query to retrieve multiple documents from MongoDB by id" }, { "code": null, "e": 2602, "s": 2538, "text": "> db.retrieveMultipleDocsByIdDemo.find({_id:{$in:[10,20,30]}});" }, { "code": null, "e": 2641, "s": 2602, "text": "This will produce the following output" }, { "code": null, "e": 2762, "s": 2641, "text": "{ \"_id\" : 10, \"CustomerName\" : \"John\" }\n{ \"_id\" : 20, \"CustomerName\" : \"Robert\" }\n{ \"_id\" : 30, \"CustomerName\" : \"Bob\" }" } ]
Ruby Integer times function with example - GeeksforGeeks
17 Mar, 2020 The times function in Ruby returns all the numbers from 0 to one less than the number itself. It iterates the given block, passing in increasing values from 0 up to the limit. If no block is given, an Enumerator is returned instead. Syntax: (number).times Parameter: The function takes the integer till which the numbers are returned. It also takes an block. Return Value: The function returns all the numbers from 0 to one less than the number itself. Example #1: # Ruby program for times function # Initializing the number num1 = 8 # Prints the number from 0 to num1-1 puts num1.times { |i| print i, " " } # Initializing the numbernum2 = 5 # Prints the number from 0 to num2-1puts num2.times { |i| print i, " " } Output : 0 1 2 3 4 5 6 7 0 1 2 3 4 Example #2: # Ruby program for times function # Initializing the number num1 = 4 # Prints the number from 0 to num1-1 puts num1.times { |i| print i, " " } # Initializing the numbernum2 = -2 # Prints the number from 0 to num2puts num2.times { |i| print i, " " } Output: 0 1 2 3 -2 Example #3: # Ruby program for times function # Initializing the numbernum1 = 5 # Prints enumerator as no block is given puts num1.times Output: # timcustard Ruby Integer-class Ruby-Methods Ruby Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Ruby | Array select() function Global Variable in Ruby Ruby | Enumerator each_with_index function Ruby | Numeric round() function Ruby | Decision Making (if, if-else, if-else-if, ternary) | Set - 1 Ruby | Types of Iterators Include v/s Extend in Ruby Ruby | String gsub! Method Ruby | Data Types Ruby | Class Method and Variables
[ { "code": null, "e": 23536, "s": 23508, "text": "\n17 Mar, 2020" }, { "code": null, "e": 23769, "s": 23536, "text": "The times function in Ruby returns all the numbers from 0 to one less than the number itself. It iterates the given block, passing in increasing values from 0 up to the limit. If no block is given, an Enumerator is returned instead." }, { "code": null, "e": 23792, "s": 23769, "text": "Syntax: (number).times" }, { "code": null, "e": 23895, "s": 23792, "text": "Parameter: The function takes the integer till which the numbers are returned. It also takes an block." }, { "code": null, "e": 23989, "s": 23895, "text": "Return Value: The function returns all the numbers from 0 to one less than the number itself." }, { "code": null, "e": 24001, "s": 23989, "text": "Example #1:" }, { "code": "# Ruby program for times function # Initializing the number num1 = 8 # Prints the number from 0 to num1-1 puts num1.times { |i| print i, \" \" } # Initializing the numbernum2 = 5 # Prints the number from 0 to num2-1puts num2.times { |i| print i, \" \" }", "e": 24261, "s": 24001, "text": null }, { "code": null, "e": 24270, "s": 24261, "text": "Output :" }, { "code": null, "e": 24297, "s": 24270, "text": "0 1 2 3 4 5 6 7\n0 1 2 3 4\n" }, { "code": null, "e": 24309, "s": 24297, "text": "Example #2:" }, { "code": "# Ruby program for times function # Initializing the number num1 = 4 # Prints the number from 0 to num1-1 puts num1.times { |i| print i, \" \" } # Initializing the numbernum2 = -2 # Prints the number from 0 to num2puts num2.times { |i| print i, \" \" }", "e": 24567, "s": 24309, "text": null }, { "code": null, "e": 24575, "s": 24567, "text": "Output:" }, { "code": null, "e": 24587, "s": 24575, "text": "0 1 2 3\n-2\n" }, { "code": null, "e": 24599, "s": 24587, "text": "Example #3:" }, { "code": "# Ruby program for times function # Initializing the numbernum1 = 5 # Prints enumerator as no block is given puts num1.times ", "e": 24730, "s": 24599, "text": null }, { "code": null, "e": 24738, "s": 24730, "text": "Output:" }, { "code": null, "e": 24741, "s": 24738, "text": "#\n" }, { "code": null, "e": 24752, "s": 24741, "text": "timcustard" }, { "code": null, "e": 24771, "s": 24752, "text": "Ruby Integer-class" }, { "code": null, "e": 24784, "s": 24771, "text": "Ruby-Methods" }, { "code": null, "e": 24789, "s": 24784, "text": "Ruby" }, { "code": null, "e": 24887, "s": 24789, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 24896, "s": 24887, "text": "Comments" }, { "code": null, "e": 24909, "s": 24896, "text": "Old Comments" }, { "code": null, "e": 24940, "s": 24909, "text": "Ruby | Array select() function" }, { "code": null, "e": 24964, "s": 24940, "text": "Global Variable in Ruby" }, { "code": null, "e": 25007, "s": 24964, "text": "Ruby | Enumerator each_with_index function" }, { "code": null, "e": 25039, "s": 25007, "text": "Ruby | Numeric round() function" }, { "code": null, "e": 25107, "s": 25039, "text": "Ruby | Decision Making (if, if-else, if-else-if, ternary) | Set - 1" }, { "code": null, "e": 25133, "s": 25107, "text": "Ruby | Types of Iterators" }, { "code": null, "e": 25160, "s": 25133, "text": "Include v/s Extend in Ruby" }, { "code": null, "e": 25187, "s": 25160, "text": "Ruby | String gsub! Method" }, { "code": null, "e": 25205, "s": 25187, "text": "Ruby | Data Types" } ]
acos() function in C++ STL - GeeksforGeeks
10 May, 2021 acos() is an inbuilt function in C++ STL and it’s the same as the inverse of cosine in maths. The acos() function returns the values in the range of [0, ?] that is an angle in radian. Syntax : acos(data_type x) Parameters : This function accepts one mandatory parameter x which specifies the value whose inverse of cosine should be computed. x must be in the range of [-1, 1] to find valid output as [0, ?], else acos(x) function returns NaN(Not a Number) . The parameter x can be of double, float or long double datatype. Return : The function returns angles in radians in the range of [0,?]. It is the counterclockwise angle which is measured in radian. Program 1: C++ // C++ program to demonstrate// the acos() function#include <bits/stdc++.h>using namespace std; int main(){ double x = 1.0; // Function call to calculate acos(x) value double result = acos(x); cout << "acos(1.0) = " << result << " radians" << endl; cout << "acos(1.0) = " << result * 180 / 3.141592 << " degrees" << endl; return 0;} acos(1.0) = 0 radians acos(1.0) = 0 degrees Program 2: C++ // C++ program to demonstrate// the acos() function#include <bits/stdc++.h>using namespace std; int main(){ double result; int x = -1; // Function call to calculate acos(x) value result = acos(x); cout << "acos(-1) = " << result << " radians" << endl; cout << "acos(-1) = " << result * 180 / 3.141592 << " degrees" << endl; return 0;} acos(-1) = 3.14159 radians acos(-1) = 180 degrees Errors and Exceptions: The function returns no matching function for call to error when a string or character is passed as an argument. The function returns nan when a out of domain(domain [-1,1]) number is passed as an argument. Below programs illustrate the errors and exceptions of the above method: Program 3: C++ // C++ program to demonstrate the acos()// function errors and exceptions#include <bits/stdc++.h>using namespace std; int main(){ double result; string x = "gfg"; result = acos(x); cout << "acos(x) = " << result << " radians" << endl; cout << "acos(x) = " << result * 180 / 3.141592 << " degrees" << endl; return 0;} Output: prog.cpp:10:17: error: no matching function for call to 'acos(std::__cxx11::string&)' result = acos(x); When argument x >1 or x<-1 it will give nan(not a number). Program 4: C++ // C++ program to demonstrate the// acos() function errors and exceptions#include <bits/stdc++.h>using namespace std; int main(){ double x = 3.7, result; // Function call to calculate acos(x) value result = acos(x); cout << "acos(3.7) = " << result << " radians" << endl; cout << "acos(3.7) = " << result * 180 / 3.141592 << " degrees" << endl; return 0;} Output: acos(3.7) = nan radians acos(3.7) = nan degrees badger_666 Code_Mech CPP-Functions STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Socket Programming in C/C++ Operator Overloading in C++ Multidimensional Arrays in C / C++ Copy Constructor in C++ Templates in C++ with Examples rand() and srand() in C/C++ vector erase() and clear() in C++ unordered_map in C++ STL Left Shift and Right Shift Operators in C/C++ Command line arguments in C/C++
[ { "code": null, "e": 24059, "s": 24031, "text": "\n10 May, 2021" }, { "code": null, "e": 24243, "s": 24059, "text": "acos() is an inbuilt function in C++ STL and it’s the same as the inverse of cosine in maths. The acos() function returns the values in the range of [0, ?] that is an angle in radian." }, { "code": null, "e": 24252, "s": 24243, "text": "Syntax :" }, { "code": null, "e": 24270, "s": 24252, "text": "acos(data_type x)" }, { "code": null, "e": 24582, "s": 24270, "text": "Parameters : This function accepts one mandatory parameter x which specifies the value whose inverse of cosine should be computed. x must be in the range of [-1, 1] to find valid output as [0, ?], else acos(x) function returns NaN(Not a Number) . The parameter x can be of double, float or long double datatype." }, { "code": null, "e": 24716, "s": 24582, "text": "Return : The function returns angles in radians in the range of [0,?]. It is the counterclockwise angle which is measured in radian." }, { "code": null, "e": 24727, "s": 24716, "text": "Program 1:" }, { "code": null, "e": 24731, "s": 24727, "text": "C++" }, { "code": "// C++ program to demonstrate// the acos() function#include <bits/stdc++.h>using namespace std; int main(){ double x = 1.0; // Function call to calculate acos(x) value double result = acos(x); cout << \"acos(1.0) = \" << result << \" radians\" << endl; cout << \"acos(1.0) = \" << result * 180 / 3.141592 << \" degrees\" << endl; return 0;}", "e": 25123, "s": 24731, "text": null }, { "code": null, "e": 25167, "s": 25123, "text": "acos(1.0) = 0 radians\nacos(1.0) = 0 degrees" }, { "code": null, "e": 25178, "s": 25167, "text": "Program 2:" }, { "code": null, "e": 25182, "s": 25178, "text": "C++" }, { "code": "// C++ program to demonstrate// the acos() function#include <bits/stdc++.h>using namespace std; int main(){ double result; int x = -1; // Function call to calculate acos(x) value result = acos(x); cout << \"acos(-1) = \" << result << \" radians\" << endl; cout << \"acos(-1) = \" << result * 180 / 3.141592 << \" degrees\" << endl; return 0;}", "e": 25555, "s": 25182, "text": null }, { "code": null, "e": 25605, "s": 25555, "text": "acos(-1) = 3.14159 radians\nacos(-1) = 180 degrees" }, { "code": null, "e": 25628, "s": 25605, "text": "Errors and Exceptions:" }, { "code": null, "e": 25741, "s": 25628, "text": "The function returns no matching function for call to error when a string or character is passed as an argument." }, { "code": null, "e": 25835, "s": 25741, "text": "The function returns nan when a out of domain(domain [-1,1]) number is passed as an argument." }, { "code": null, "e": 25908, "s": 25835, "text": "Below programs illustrate the errors and exceptions of the above method:" }, { "code": null, "e": 25919, "s": 25908, "text": "Program 3:" }, { "code": null, "e": 25923, "s": 25919, "text": "C++" }, { "code": "// C++ program to demonstrate the acos()// function errors and exceptions#include <bits/stdc++.h>using namespace std; int main(){ double result; string x = \"gfg\"; result = acos(x); cout << \"acos(x) = \" << result << \" radians\" << endl; cout << \"acos(x) = \" << result * 180 / 3.141592 << \" degrees\" << endl; return 0;}", "e": 26274, "s": 25923, "text": null }, { "code": null, "e": 26282, "s": 26274, "text": "Output:" }, { "code": null, "e": 26388, "s": 26282, "text": "prog.cpp:10:17: error: no matching function for call to 'acos(std::__cxx11::string&)'\n result = acos(x);" }, { "code": null, "e": 26447, "s": 26388, "text": "When argument x >1 or x<-1 it will give nan(not a number)." }, { "code": null, "e": 26458, "s": 26447, "text": "Program 4:" }, { "code": null, "e": 26462, "s": 26458, "text": "C++" }, { "code": "// C++ program to demonstrate the// acos() function errors and exceptions#include <bits/stdc++.h>using namespace std; int main(){ double x = 3.7, result; // Function call to calculate acos(x) value result = acos(x); cout << \"acos(3.7) = \" << result << \" radians\" << endl; cout << \"acos(3.7) = \" << result * 180 / 3.141592 << \" degrees\" << endl; return 0;}", "e": 26853, "s": 26462, "text": null }, { "code": null, "e": 26861, "s": 26853, "text": "Output:" }, { "code": null, "e": 26909, "s": 26861, "text": "acos(3.7) = nan radians\nacos(3.7) = nan degrees" }, { "code": null, "e": 26920, "s": 26909, "text": "badger_666" }, { "code": null, "e": 26930, "s": 26920, "text": "Code_Mech" }, { "code": null, "e": 26944, "s": 26930, "text": "CPP-Functions" }, { "code": null, "e": 26948, "s": 26944, "text": "STL" }, { "code": null, "e": 26952, "s": 26948, "text": "C++" }, { "code": null, "e": 26956, "s": 26952, "text": "STL" }, { "code": null, "e": 26960, "s": 26956, "text": "CPP" }, { "code": null, "e": 27058, "s": 26960, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27067, "s": 27058, "text": "Comments" }, { "code": null, "e": 27080, "s": 27067, "text": "Old Comments" }, { "code": null, "e": 27108, "s": 27080, "text": "Socket Programming in C/C++" }, { "code": null, "e": 27136, "s": 27108, "text": "Operator Overloading in C++" }, { "code": null, "e": 27171, "s": 27136, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 27195, "s": 27171, "text": "Copy Constructor in C++" }, { "code": null, "e": 27226, "s": 27195, "text": "Templates in C++ with Examples" }, { "code": null, "e": 27254, "s": 27226, "text": "rand() and srand() in C/C++" }, { "code": null, "e": 27288, "s": 27254, "text": "vector erase() and clear() in C++" }, { "code": null, "e": 27313, "s": 27288, "text": "unordered_map in C++ STL" }, { "code": null, "e": 27359, "s": 27313, "text": "Left Shift and Right Shift Operators in C/C++" } ]
How to add text inside a Tkinter Canvas?
Canvas is undoubtedly one of the most versatile widgets in tkinter. With Canvas, we can create shapes, texts, animate stuff, modeling 3D shapes, modeling simulations, and many more. In order to add text inside a tkinter frame, we can use the create_text() method. We can define create_text() by adding values of font, text, and other options such as create_text(x,y,font, text, options....). #Import the required library from tkinter import * #Create an instance of tkinter frame win= Tk() #Set the geometry win.geometry("750x280") #Create a canvas object canvas= Canvas(win, width= 1000, height= 750, bg="SpringGreen2") #Add a text in Canvas canvas.create_text(300, 50, text="HELLO WORLD", fill="black", font=('Helvetica 15 bold')) canvas.pack() win.mainloop() Running the above code will display a canvas with some text in it.
[ { "code": null, "e": 1244, "s": 1062, "text": "Canvas is undoubtedly one of the most versatile widgets in tkinter. With Canvas, we can create shapes, texts, animate stuff, modeling 3D shapes, modeling simulations, and many more." }, { "code": null, "e": 1454, "s": 1244, "text": "In order to add text inside a tkinter frame, we can use the create_text() method. We can define create_text() by adding values of font, text, and other options such as create_text(x,y,font, text, options....)." }, { "code": null, "e": 1829, "s": 1454, "text": "#Import the required library\nfrom tkinter import *\n\n#Create an instance of tkinter frame\nwin= Tk()\n\n#Set the geometry\nwin.geometry(\"750x280\")\n\n#Create a canvas object\ncanvas= Canvas(win, width= 1000, height= 750, bg=\"SpringGreen2\")\n\n#Add a text in Canvas\ncanvas.create_text(300, 50, text=\"HELLO WORLD\", fill=\"black\", font=('Helvetica 15 bold'))\ncanvas.pack()\n\nwin.mainloop()" }, { "code": null, "e": 1896, "s": 1829, "text": "Running the above code will display a canvas with some text in it." } ]
Link Prediction with Neo4j Part 2: Predicting co-authors using scikit-learn | by Mark Needham | Towards Data Science
In the 1st post we learnt about link prediction measures, how to apply them in Neo4j, and how they can be used as features in a machine learning classifier. We also learnt about the challenge of splitting train and test data sets when working with graphs. In this post we’ll apply the things we learned on a citation dataset. We’re going to predict future co-authorships using scikit-learn and the link prediction algorithms. Amy Hodler and I showed how to apply the approaches described in this post in last week’s Neo4j Online Meetup, so you can also watch the video. If you’re sticking around for the written version, let’s get started! We’re going to use data from the DBLP Citation Network, which includes citation data from various academic sources. I wrote a blog post explaining how to import the full dataset, but in this post we’re going to focus on the data from a few Software Development Conferences. We can import that subset of the data by running the following Cypher statements. You can run them all in one go as long as you have the multi statement editor enabled in the Neo4j Browser: // Create constraintsCREATE CONSTRAINT ON (a:Article) ASSERT a.index IS UNIQUE;CREATE CONSTRAINT ON (a:Author) ASSERT a.name IS UNIQUE;CREATE CONSTRAINT ON (v:Venue) ASSERT v.name IS UNIQUE;// Import data from JSON files using the APOC libraryCALL apoc.periodic.iterate( 'UNWIND ["dblp-ref-0.json", "dblp-ref-1.json", "dblp-ref-2.json", "dblp-ref-3.json"] AS file CALL apoc.load.json("https://github.com/mneedham/link-prediction/raw/master/data/" + file) YIELD value WITH value RETURN value', 'MERGE (a:Article {index:value.id}) SET a += apoc.map.clean(value,["id","authors","references", "venue"],[0]) WITH a, value.authors as authors, value.references AS citations, value.venue AS venue MERGE (v:Venue {name: venue}) MERGE (a)-[:VENUE]->(v) FOREACH(author in authors | MERGE (b:Author{name:author}) MERGE (a)-[:AUTHOR]->(b)) FOREACH(citation in citations | MERGE (cited:Article {index:citation}) MERGE (a)-[:CITED]->(cited))', {batchSize: 1000, iterateList: true}); The following diagram shows what the data looks like once we’ve imported into Neo4j: The dataset doesn’t contain relationships between authors describing their collaborations, but we can infer them based on finding articles authored by multiple people. The following Cypher statement creates aCO_AUTHOR relationship between authors that have collaborated on at least one article: MATCH (a1)<-[:AUTHOR]-(paper)-[:AUTHOR]->(a2:Author)WITH a1, a2, paperORDER BY a1, paper.yearWITH a1, a2, collect(paper)[0].year AS year, count(*) AS collaborationsMERGE (a1)-[coauthor:CO_AUTHOR {year: year}]-(a2)SET coauthor.collaborations = collaborations; We create only one CO_AUTHOR relationship between authors that have collaborated, even if they’ve collaborated on multiple articles. We create a couple of properties on these relationships: a year property that indicates the publication year of the first article on which the authors collaborated a collaborations property that indicates how many articles on which the authors have collaborated Now that we’ve got our co-author graph, we need to figure out how we’re going to predict future collaborations between authors. We’re going to build a binary classifier to do this, so our next step is to create train and test graphs. As mentioned in the 1st post, we can’t just randomly split the data into train and test datasets, as this could lead to data leakage. Data leakage can occur when data outside of your training data is inadvertently used to create your model. This can easily happen when working with graphs because pairs of nodes in our training set may be connected to those in the test set. Instead we need to split our graph into training and test sub graphs, and we are lucky that our citation graph contains time information that we can split on. We will create training and test graphs by splitting the data on a particular year. But which year should we split on? Let’s have a look at the distribution of the first year that co-authors collaborated: It looks like 2006 would act as a good year on which to split the data, because it will give us a reasonable amount of data for each of our sub graphs. We’ll take all the co-authorships from 2005 and earlier as our training graph, and everything from 2006 onwards as the test graph. Let’s create explicit CO_AUTHOR_EARLY and CO_AUTHOR_LATE relationships in our graph based on that year. The following code will create these relationships for us: Train sub graph MATCH (a)-[r:CO_AUTHOR]->(b) WHERE r.year < 2006MERGE (a)-[:CO_AUTHOR_EARLY {year: r.year}]-(b); Test sub graph MATCH (a)-[r:CO_AUTHOR]->(b) WHERE r.year >= 2006MERGE (a)-[:CO_AUTHOR_LATE {year: r.year}]-(b); This split leaves us with 81,096 relationships in the early graph, and 74,128 in the late one. This is a split of 52–48. That’s a higher percentage of values than we’d usually have in our test graph, but it should be ok. The relationships in these sub graphs will act as the positive examples in our train and test sets, but we need some negative examples as well. The negative examples are needed so that our model can learn to distinguish nodes that should have a link between them and nodes that shouldn’t. As is often the case in link prediction problems, there are a lot more negative examples than positive ones. The maximum number of negative examples is equal to : # negative examples = (# nodes)2 - (# relationships) - (# nodes) i.e. the number of nodes squared, minus the relationships that the graph has, minus self relationships. Instead of using almost all possible pairs, we’ll use pairs of nodes that are between 2 and 3 hops away from each other. This will give us a much more manageable amount of data to work with. We can generate these pairs by running the following query: MATCH (author:Author)WHERE (author)-[:CO_AUTHOR_EARLY]-()MATCH (author)-[:CO_AUTHOR_EARLY*2..3]-(other)WHERE not((author)-[:CO_AUTHOR_EARLY]-(other))RETURN id(author) AS node1, id(other) AS node2 This query returns 4,389,478 negative examples compared to 81,096 positive examples, which means we have 54 times as many negative examples. So we still have a big class imbalance, which means that a model that predicts that every pair of nodes will not have a link will be very accurate. To solve this issue we can either up sample the positive examples or down sample the negative examples. We’re going to go with the downsampling approach. For the rest of the post we’re going to be working in Python with the py2neo, pandas, and scikit-learn libraries. The py2neo driver enables data scientists to easily integrate Neo4j with tools in the Python Data Science ecosystem. We’ll be using this library to execute Cypher queries against Neo4j. pandas is an open source, BSD-licensed library providing high-performance, easy-to-use data structures and data analysis tools for the Python programming language scikit-learn is a popular machine learning library. We’ll be using this library to build our machine learning model. We can install these libraries from PyPi: pip install py2neo==4.1.3 pandas sklearn Once we’ve got those libraries installed we’ll import the required packages, and create a database connection: from py2neo import Graphimport pandas as pdgraph = Graph("bolt://localhost", auth=("neo4j", "neo4jPassword")) We can now write the following code to create a test DataFrame containing positive and negative examples based on the early graph: # Find positive examplestrain_existing_links = graph.run("""MATCH (author:Author)-[:CO_AUTHOR_EARLY]->(other:Author)RETURN id(author) AS node1, id(other) AS node2, 1 AS label""").to_data_frame()# Find negative examplestrain_missing_links = graph.run("""MATCH (author:Author)WHERE (author)-[:CO_AUTHOR_EARLY]-()MATCH (author)-[:CO_AUTHOR_EARLY*2..3]-(other)WHERE not((author)-[:CO_AUTHOR_EARLY]-(other))RETURN id(author) AS node1, id(other) AS node2, 0 AS label""").to_data_frame()# Remove duplicatestrain_missing_links = train_missing_links.drop_duplicates()# Down sample negative examplestrain_missing_links = train_missing_links.sample( n=len(train_existing_links))# Create DataFrame from positive and negative examplestraining_df = train_missing_links.append( train_existing_links, ignore_index=True)training_df['label'] = training_df['label'].astype('category') And now we’ll do the same to create a test DataFrame, but this time we only consider relationships in the late graph: # Find positive examplestest_existing_links = graph.run("""MATCH (author:Author)-[:CO_AUTHOR_LATE]->(other:Author)RETURN id(author) AS node1, id(other) AS node2, 1 AS label""").to_data_frame()# Find negative examplestest_missing_links = graph.run("""MATCH (author:Author)WHERE (author)-[:CO_AUTHOR_LATE]-()MATCH (author)-[:CO_AUTHOR_LATE*2..3]-(other)WHERE not((author)-[:CO_AUTHOR_LATE]-(other))RETURN id(author) AS node1, id(other) AS node2, 0 AS label""").to_data_frame()# Remove duplicates test_missing_links = test_missing_links.drop_duplicates()# Down sample negative examplestest_missing_links = test_missing_links.sample(n=len(test_existing_links))# Create DataFrame from positive and negative examplestest_df = test_missing_links.append( test_existing_links, ignore_index=True)test_df['label'] = test_df['label'].astype('category') Now it’s time to create our machine learning model. We’ll create a random forest classifier. This method is well suited as our data set will be comprised of a mix of strong and weak features. While the weak features will sometimes be helpful, the random forest method will ensure we don’t create a model that over fits our training data. We can create this model with the following code: from sklearn.ensemble import RandomForestClassifierclassifier = RandomForestClassifier(n_estimators=30, max_depth=10, random_state=0) Now it’s time to engineer some features which we’ll use to train our model. Feature extraction is a way to distill large volumes of data and attributes down to a set of representative, numerical values, i.e. features.’ This is then used as input data so we can differentiate categories/values for learning tasks. Keep in mind that if you want to try out the code samples in the next part of this post you’ll need to make sure you have your Neo4j development environment setup as described in the 1st post of this series. We’ll start by creating some features using link prediction functions def apply_graphy_features(data, rel_type): query = """ UNWIND $pairs AS pair MATCH (p1) WHERE id(p1) = pair.node1 MATCH (p2) WHERE id(p2) = pair.node2 RETURN pair.node1 AS node1, pair.node2 AS node2, algo.linkprediction.commonNeighbors( p1, p2, {relationshipQuery: $relType}) AS cn, algo.linkprediction.preferentialAttachment( p1, p2, {relationshipQuery: $relType}) AS pa, algo.linkprediction.totalNeighbors( p1, p2, {relationshipQuery: $relType}) AS tn """ pairs = [{"node1": pair[0], "node2": pair[1]} for pair in data[["node1", "node2"]].values.tolist()] params = {"pairs": pairs, "relType": rel_type} features = graph.run(query, params).to_data_frame() return pd.merge(data, features, on = ["node1", "node2"]) This function executes a query that takes each pair of nodes from a provided DataFrame, and computes: common neighbors (cn) preferential attachment (pa), and total neighbors (tn) for each of those pairs. These measures are defined in the first post. We can apply it to our train and test DataFrames like this: training_df = apply_graphy_features(training_df, "CO_AUTHOR_EARLY")test_df = apply_graphy_features(test_df, "CO_AUTHOR") For the training DataFrame we compute these metrics based only on the early graph, whereas for the test DataFrame we’ll compute them across the whole graph. We can still use the whole graph to compute these features, as the evolution of the graph depends on what it looks like across all time, it’s not only based on what happened in 2006 and later. Now we’re ready to train our model. We can do this with the following code: columns = ["cn", "pa", "tn"]X = training_df[columns]y = training_df["label"]classifier.fit(X, y) Our model is now trained, but we need to evaluate it. We’re going to compute its accuracy, precision, and recall. The diagram below, taken from the O’Reilly Graph Algorithms Book, explains how each of these metrics are computed. scikit-learn has built in functions that we can use for this. We can also return the importance of each feature used in our model. The following functions will help with this: from sklearn.metrics import recall_scorefrom sklearn.metrics import precision_scorefrom sklearn.metrics import accuracy_scoredef evaluate_model(predictions, actual): accuracy = accuracy_score(actual, predictions) precision = precision_score(actual, predictions) recall = recall_score(actual, predictions) metrics = ["accuracy", "precision", "recall"] values = [accuracy, precision, recall] return pd.DataFrame(data={'metric': metrics, 'value': values})def feature_importance(columns, classifier): features = list(zip(columns, classifier.feature_importances_)) sorted_features = sorted(features, key = lambda x: x[1]*-1) keys = [value[0] for value in sorted_features] values = [value[1] for value in sorted_features] return pd.DataFrame(data={'feature': keys, 'value': values}) We can evaluate our model by running the following code: predictions = classifier.predict(test_df[columns])y_test = test_df["label"]evaluate_model(predictions, y_test) We have quite high scores across the board. We can now run the following code to see which feature is playing the most prominent role: feature_importance(columns, classifier) We can see above that Common neighbors (cn) is the massively dominant feature in our model. Common neighbors returns us a count of the number of unclosed co-author triangles that an author has, so this perhaps isn’t that surprising. Now we’re going to add some new features that are generated from graph algorithms. We’ll start by running the triangle count algorithm over our test and train sub graphs. This algorithm returns the number of triangles that each node forms, as well as each node’s clustering coefficient. The clustering coefficient of a node indicates the likelihood that its neighbours are also connected. We can run the following Cypher queries in the Neo4j Browser, to run this algorithm on our train graph: CALL algo.triangleCount('Author', 'CO_AUTHOR_EARLY', { write:true, writeProperty:'trianglesTrain', clusteringCoefficientProperty:'coefficientTrain'}); And the following Cypher query to run it on the test graph: CALL algo.triangleCount('Author', 'CO_AUTHOR', { write:true, writeProperty:'trianglesTest', clusteringCoefficientProperty:'coefficientTest'}); We now have 4 new properties on our nodes: trianglesTrain, coefficientTrain, trianglesTest, and coefficientTest. Let’s now add these to our train and test DataFrames, with help from the following function: def apply_triangles_features(data,triangles_prop,coefficient_prop): query = """ UNWIND $pairs AS pair MATCH (p1) WHERE id(p1) = pair.node1 MATCH (p2) WHERE id(p2) = pair.node2 RETURN pair.node1 AS node1, pair.node2 AS node2, apoc.coll.min([p1[$triangles], p2[$triangles]]) AS minTriangles, apoc.coll.max([p1[$triangles], p2[$triangles]]) AS maxTriangles, apoc.coll.min([p1[$coefficient], p2[$coefficient]]) AS minCoeff, apoc.coll.max([p1[$coefficient], p2[$coefficient]]) AS maxCoeff """ pairs = [{"node1": pair[0], "node2": pair[1]} for pair in data[["node1", "node2"]].values.tolist()] params = {"pairs": pairs, "triangles": triangles_prop, "coefficient": coefficient_prop} features = graph.run(query, params).to_data_frame() return pd.merge(data, features, on = ["node1", "node2"]) These measures are different than the ones we’ve used so far, because rather than being computed based on the pair of nodes, they are node specific measures. We can’t simply add these values to our DataFrame as node1Triangles or node1Coeff because we have no guarantee over the order of nodes in the pair. We need to come up with an approach that is agnostic of the order We can do this by taking the average of the values, the product of the values, or by computing the minimum and maximum value, as we do here. We can apply that function to the DataFrame like this: training_df = apply_triangles_features(training_df, "trianglesTrain", "coefficientTrain")test_df = apply_triangles_features(test_df, "trianglesTest", "coefficientTest") And now we can train and evaluate: columns = [ "cn", "pa", "tn", "minTriangles", "maxTriangles", "minCoeff", "maxCoeff"]X = training_df[columns]y = training_df["label"]classifier.fit(X, y)predictions = classifier.predict(test_df[columns])y_test = test_df["label"]display(evaluate_model(predictions, y_test)) Those features have been helpful! Each of our measures have improved by about 4% from the initial model. Which features are most important? display(feature_importance(columns, classifier)) Common neighbors is still the most influential, but the triangles features are adding some value as well. This post has already gone on a lot longer than I intended so we’ll stop there, but there are certainly some exercises left for the reader. Can you think of any other features that we could add that might help us to create a model with even higher accuracy? Perhaps other community detection, or even centrality algorithms might help? At the moment the link prediction algorithms in the Graph Algorithms Library only work for mono-partite graphs. Mono-partite graphs are ones where the label of both nodes are the same. The algorithms are based on the topology of nodes, and if we try to apply them to nodes with different labels, those nodes will likely have different topologies, meaning that the algorithms won’t work so well. We’re looking at adding versions of the link prediction algorithms that work on other graphs. If you have any particular ones that you’d like to see, please let us know on GitHub issues. If you found this blog post interesting, you might enjoy the O’Reilly Graph Algorithms Book that Amy Hodler and I have been working on over the last 9 months. We’re in the final review stage and it should be available in the next few weeks. You can register to get your free digital copy from the Neo4j webisite, at: neo4j.com/graph-algorithms-book Will Lyon and I are also working on a new online training course on Data Science with Neo4j, so keep an eye on the Online Training page for details of that.
[ { "code": null, "e": 428, "s": 172, "text": "In the 1st post we learnt about link prediction measures, how to apply them in Neo4j, and how they can be used as features in a machine learning classifier. We also learnt about the challenge of splitting train and test data sets when working with graphs." }, { "code": null, "e": 598, "s": 428, "text": "In this post we’ll apply the things we learned on a citation dataset. We’re going to predict future co-authorships using scikit-learn and the link prediction algorithms." }, { "code": null, "e": 742, "s": 598, "text": "Amy Hodler and I showed how to apply the approaches described in this post in last week’s Neo4j Online Meetup, so you can also watch the video." }, { "code": null, "e": 812, "s": 742, "text": "If you’re sticking around for the written version, let’s get started!" }, { "code": null, "e": 1086, "s": 812, "text": "We’re going to use data from the DBLP Citation Network, which includes citation data from various academic sources. I wrote a blog post explaining how to import the full dataset, but in this post we’re going to focus on the data from a few Software Development Conferences." }, { "code": null, "e": 1276, "s": 1086, "text": "We can import that subset of the data by running the following Cypher statements. You can run them all in one go as long as you have the multi statement editor enabled in the Neo4j Browser:" }, { "code": null, "e": 2285, "s": 1276, "text": "// Create constraintsCREATE CONSTRAINT ON (a:Article) ASSERT a.index IS UNIQUE;CREATE CONSTRAINT ON (a:Author) ASSERT a.name IS UNIQUE;CREATE CONSTRAINT ON (v:Venue) ASSERT v.name IS UNIQUE;// Import data from JSON files using the APOC libraryCALL apoc.periodic.iterate( 'UNWIND [\"dblp-ref-0.json\", \"dblp-ref-1.json\", \"dblp-ref-2.json\", \"dblp-ref-3.json\"] AS file CALL apoc.load.json(\"https://github.com/mneedham/link-prediction/raw/master/data/\" + file) YIELD value WITH value RETURN value', 'MERGE (a:Article {index:value.id}) SET a += apoc.map.clean(value,[\"id\",\"authors\",\"references\", \"venue\"],[0]) WITH a, value.authors as authors, value.references AS citations, value.venue AS venue MERGE (v:Venue {name: venue}) MERGE (a)-[:VENUE]->(v) FOREACH(author in authors | MERGE (b:Author{name:author}) MERGE (a)-[:AUTHOR]->(b)) FOREACH(citation in citations | MERGE (cited:Article {index:citation}) MERGE (a)-[:CITED]->(cited))', {batchSize: 1000, iterateList: true});" }, { "code": null, "e": 2370, "s": 2285, "text": "The following diagram shows what the data looks like once we’ve imported into Neo4j:" }, { "code": null, "e": 2538, "s": 2370, "text": "The dataset doesn’t contain relationships between authors describing their collaborations, but we can infer them based on finding articles authored by multiple people." }, { "code": null, "e": 2665, "s": 2538, "text": "The following Cypher statement creates aCO_AUTHOR relationship between authors that have collaborated on at least one article:" }, { "code": null, "e": 2929, "s": 2665, "text": "MATCH (a1)<-[:AUTHOR]-(paper)-[:AUTHOR]->(a2:Author)WITH a1, a2, paperORDER BY a1, paper.yearWITH a1, a2, collect(paper)[0].year AS year, count(*) AS collaborationsMERGE (a1)-[coauthor:CO_AUTHOR {year: year}]-(a2)SET coauthor.collaborations = collaborations;" }, { "code": null, "e": 3119, "s": 2929, "text": "We create only one CO_AUTHOR relationship between authors that have collaborated, even if they’ve collaborated on multiple articles. We create a couple of properties on these relationships:" }, { "code": null, "e": 3226, "s": 3119, "text": "a year property that indicates the publication year of the first article on which the authors collaborated" }, { "code": null, "e": 3324, "s": 3226, "text": "a collaborations property that indicates how many articles on which the authors have collaborated" }, { "code": null, "e": 3452, "s": 3324, "text": "Now that we’ve got our co-author graph, we need to figure out how we’re going to predict future collaborations between authors." }, { "code": null, "e": 3558, "s": 3452, "text": "We’re going to build a binary classifier to do this, so our next step is to create train and test graphs." }, { "code": null, "e": 3692, "s": 3558, "text": "As mentioned in the 1st post, we can’t just randomly split the data into train and test datasets, as this could lead to data leakage." }, { "code": null, "e": 3933, "s": 3692, "text": "Data leakage can occur when data outside of your training data is inadvertently used to create your model. This can easily happen when working with graphs because pairs of nodes in our training set may be connected to those in the test set." }, { "code": null, "e": 4176, "s": 3933, "text": "Instead we need to split our graph into training and test sub graphs, and we are lucky that our citation graph contains time information that we can split on. We will create training and test graphs by splitting the data on a particular year." }, { "code": null, "e": 4297, "s": 4176, "text": "But which year should we split on? Let’s have a look at the distribution of the first year that co-authors collaborated:" }, { "code": null, "e": 4580, "s": 4297, "text": "It looks like 2006 would act as a good year on which to split the data, because it will give us a reasonable amount of data for each of our sub graphs. We’ll take all the co-authorships from 2005 and earlier as our training graph, and everything from 2006 onwards as the test graph." }, { "code": null, "e": 4743, "s": 4580, "text": "Let’s create explicit CO_AUTHOR_EARLY and CO_AUTHOR_LATE relationships in our graph based on that year. The following code will create these relationships for us:" }, { "code": null, "e": 4759, "s": 4743, "text": "Train sub graph" }, { "code": null, "e": 4856, "s": 4759, "text": "MATCH (a)-[r:CO_AUTHOR]->(b) WHERE r.year < 2006MERGE (a)-[:CO_AUTHOR_EARLY {year: r.year}]-(b);" }, { "code": null, "e": 4871, "s": 4856, "text": "Test sub graph" }, { "code": null, "e": 4968, "s": 4871, "text": "MATCH (a)-[r:CO_AUTHOR]->(b) WHERE r.year >= 2006MERGE (a)-[:CO_AUTHOR_LATE {year: r.year}]-(b);" }, { "code": null, "e": 5189, "s": 4968, "text": "This split leaves us with 81,096 relationships in the early graph, and 74,128 in the late one. This is a split of 52–48. That’s a higher percentage of values than we’d usually have in our test graph, but it should be ok." }, { "code": null, "e": 5478, "s": 5189, "text": "The relationships in these sub graphs will act as the positive examples in our train and test sets, but we need some negative examples as well. The negative examples are needed so that our model can learn to distinguish nodes that should have a link between them and nodes that shouldn’t." }, { "code": null, "e": 5641, "s": 5478, "text": "As is often the case in link prediction problems, there are a lot more negative examples than positive ones. The maximum number of negative examples is equal to :" }, { "code": null, "e": 5706, "s": 5641, "text": "# negative examples = (# nodes)2 - (# relationships) - (# nodes)" }, { "code": null, "e": 5810, "s": 5706, "text": "i.e. the number of nodes squared, minus the relationships that the graph has, minus self relationships." }, { "code": null, "e": 6001, "s": 5810, "text": "Instead of using almost all possible pairs, we’ll use pairs of nodes that are between 2 and 3 hops away from each other. This will give us a much more manageable amount of data to work with." }, { "code": null, "e": 6061, "s": 6001, "text": "We can generate these pairs by running the following query:" }, { "code": null, "e": 6257, "s": 6061, "text": "MATCH (author:Author)WHERE (author)-[:CO_AUTHOR_EARLY]-()MATCH (author)-[:CO_AUTHOR_EARLY*2..3]-(other)WHERE not((author)-[:CO_AUTHOR_EARLY]-(other))RETURN id(author) AS node1, id(other) AS node2" }, { "code": null, "e": 6398, "s": 6257, "text": "This query returns 4,389,478 negative examples compared to 81,096 positive examples, which means we have 54 times as many negative examples." }, { "code": null, "e": 6546, "s": 6398, "text": "So we still have a big class imbalance, which means that a model that predicts that every pair of nodes will not have a link will be very accurate." }, { "code": null, "e": 6700, "s": 6546, "text": "To solve this issue we can either up sample the positive examples or down sample the negative examples. We’re going to go with the downsampling approach." }, { "code": null, "e": 6814, "s": 6700, "text": "For the rest of the post we’re going to be working in Python with the py2neo, pandas, and scikit-learn libraries." }, { "code": null, "e": 7000, "s": 6814, "text": "The py2neo driver enables data scientists to easily integrate Neo4j with tools in the Python Data Science ecosystem. We’ll be using this library to execute Cypher queries against Neo4j." }, { "code": null, "e": 7163, "s": 7000, "text": "pandas is an open source, BSD-licensed library providing high-performance, easy-to-use data structures and data analysis tools for the Python programming language" }, { "code": null, "e": 7280, "s": 7163, "text": "scikit-learn is a popular machine learning library. We’ll be using this library to build our machine learning model." }, { "code": null, "e": 7322, "s": 7280, "text": "We can install these libraries from PyPi:" }, { "code": null, "e": 7363, "s": 7322, "text": "pip install py2neo==4.1.3 pandas sklearn" }, { "code": null, "e": 7474, "s": 7363, "text": "Once we’ve got those libraries installed we’ll import the required packages, and create a database connection:" }, { "code": null, "e": 7584, "s": 7474, "text": "from py2neo import Graphimport pandas as pdgraph = Graph(\"bolt://localhost\", auth=(\"neo4j\", \"neo4jPassword\"))" }, { "code": null, "e": 7715, "s": 7584, "text": "We can now write the following code to create a test DataFrame containing positive and negative examples based on the early graph:" }, { "code": null, "e": 8587, "s": 7715, "text": "# Find positive examplestrain_existing_links = graph.run(\"\"\"MATCH (author:Author)-[:CO_AUTHOR_EARLY]->(other:Author)RETURN id(author) AS node1, id(other) AS node2, 1 AS label\"\"\").to_data_frame()# Find negative examplestrain_missing_links = graph.run(\"\"\"MATCH (author:Author)WHERE (author)-[:CO_AUTHOR_EARLY]-()MATCH (author)-[:CO_AUTHOR_EARLY*2..3]-(other)WHERE not((author)-[:CO_AUTHOR_EARLY]-(other))RETURN id(author) AS node1, id(other) AS node2, 0 AS label\"\"\").to_data_frame()# Remove duplicatestrain_missing_links = train_missing_links.drop_duplicates()# Down sample negative examplestrain_missing_links = train_missing_links.sample( n=len(train_existing_links))# Create DataFrame from positive and negative examplestraining_df = train_missing_links.append( train_existing_links, ignore_index=True)training_df['label'] = training_df['label'].astype('category')" }, { "code": null, "e": 8705, "s": 8587, "text": "And now we’ll do the same to create a test DataFrame, but this time we only consider relationships in the late graph:" }, { "code": null, "e": 9549, "s": 8705, "text": "# Find positive examplestest_existing_links = graph.run(\"\"\"MATCH (author:Author)-[:CO_AUTHOR_LATE]->(other:Author)RETURN id(author) AS node1, id(other) AS node2, 1 AS label\"\"\").to_data_frame()# Find negative examplestest_missing_links = graph.run(\"\"\"MATCH (author:Author)WHERE (author)-[:CO_AUTHOR_LATE]-()MATCH (author)-[:CO_AUTHOR_LATE*2..3]-(other)WHERE not((author)-[:CO_AUTHOR_LATE]-(other))RETURN id(author) AS node1, id(other) AS node2, 0 AS label\"\"\").to_data_frame()# Remove duplicates test_missing_links = test_missing_links.drop_duplicates()# Down sample negative examplestest_missing_links = test_missing_links.sample(n=len(test_existing_links))# Create DataFrame from positive and negative examplestest_df = test_missing_links.append( test_existing_links, ignore_index=True)test_df['label'] = test_df['label'].astype('category')" }, { "code": null, "e": 9601, "s": 9549, "text": "Now it’s time to create our machine learning model." }, { "code": null, "e": 9887, "s": 9601, "text": "We’ll create a random forest classifier. This method is well suited as our data set will be comprised of a mix of strong and weak features. While the weak features will sometimes be helpful, the random forest method will ensure we don’t create a model that over fits our training data." }, { "code": null, "e": 9937, "s": 9887, "text": "We can create this model with the following code:" }, { "code": null, "e": 10107, "s": 9937, "text": "from sklearn.ensemble import RandomForestClassifierclassifier = RandomForestClassifier(n_estimators=30, max_depth=10, random_state=0)" }, { "code": null, "e": 10183, "s": 10107, "text": "Now it’s time to engineer some features which we’ll use to train our model." }, { "code": null, "e": 10420, "s": 10183, "text": "Feature extraction is a way to distill large volumes of data and attributes down to a set of representative, numerical values, i.e. features.’ This is then used as input data so we can differentiate categories/values for learning tasks." }, { "code": null, "e": 10628, "s": 10420, "text": "Keep in mind that if you want to try out the code samples in the next part of this post you’ll need to make sure you have your Neo4j development environment setup as described in the 1st post of this series." }, { "code": null, "e": 10698, "s": 10628, "text": "We’ll start by creating some features using link prediction functions" }, { "code": null, "e": 11542, "s": 10698, "text": "def apply_graphy_features(data, rel_type): query = \"\"\" UNWIND $pairs AS pair MATCH (p1) WHERE id(p1) = pair.node1 MATCH (p2) WHERE id(p2) = pair.node2 RETURN pair.node1 AS node1, pair.node2 AS node2, algo.linkprediction.commonNeighbors( p1, p2, {relationshipQuery: $relType}) AS cn, algo.linkprediction.preferentialAttachment( p1, p2, {relationshipQuery: $relType}) AS pa, algo.linkprediction.totalNeighbors( p1, p2, {relationshipQuery: $relType}) AS tn \"\"\" pairs = [{\"node1\": pair[0], \"node2\": pair[1]} for pair in data[[\"node1\", \"node2\"]].values.tolist()] params = {\"pairs\": pairs, \"relType\": rel_type} features = graph.run(query, params).to_data_frame() return pd.merge(data, features, on = [\"node1\", \"node2\"])" }, { "code": null, "e": 11644, "s": 11542, "text": "This function executes a query that takes each pair of nodes from a provided DataFrame, and computes:" }, { "code": null, "e": 11666, "s": 11644, "text": "common neighbors (cn)" }, { "code": null, "e": 11700, "s": 11666, "text": "preferential attachment (pa), and" }, { "code": null, "e": 11721, "s": 11700, "text": "total neighbors (tn)" }, { "code": null, "e": 11792, "s": 11721, "text": "for each of those pairs. These measures are defined in the first post." }, { "code": null, "e": 11852, "s": 11792, "text": "We can apply it to our train and test DataFrames like this:" }, { "code": null, "e": 11973, "s": 11852, "text": "training_df = apply_graphy_features(training_df, \"CO_AUTHOR_EARLY\")test_df = apply_graphy_features(test_df, \"CO_AUTHOR\")" }, { "code": null, "e": 12130, "s": 11973, "text": "For the training DataFrame we compute these metrics based only on the early graph, whereas for the test DataFrame we’ll compute them across the whole graph." }, { "code": null, "e": 12323, "s": 12130, "text": "We can still use the whole graph to compute these features, as the evolution of the graph depends on what it looks like across all time, it’s not only based on what happened in 2006 and later." }, { "code": null, "e": 12399, "s": 12323, "text": "Now we’re ready to train our model. We can do this with the following code:" }, { "code": null, "e": 12496, "s": 12399, "text": "columns = [\"cn\", \"pa\", \"tn\"]X = training_df[columns]y = training_df[\"label\"]classifier.fit(X, y)" }, { "code": null, "e": 12550, "s": 12496, "text": "Our model is now trained, but we need to evaluate it." }, { "code": null, "e": 12725, "s": 12550, "text": "We’re going to compute its accuracy, precision, and recall. The diagram below, taken from the O’Reilly Graph Algorithms Book, explains how each of these metrics are computed." }, { "code": null, "e": 12856, "s": 12725, "text": "scikit-learn has built in functions that we can use for this. We can also return the importance of each feature used in our model." }, { "code": null, "e": 12901, "s": 12856, "text": "The following functions will help with this:" }, { "code": null, "e": 13731, "s": 12901, "text": "from sklearn.metrics import recall_scorefrom sklearn.metrics import precision_scorefrom sklearn.metrics import accuracy_scoredef evaluate_model(predictions, actual): accuracy = accuracy_score(actual, predictions) precision = precision_score(actual, predictions) recall = recall_score(actual, predictions) metrics = [\"accuracy\", \"precision\", \"recall\"] values = [accuracy, precision, recall] return pd.DataFrame(data={'metric': metrics, 'value': values})def feature_importance(columns, classifier): features = list(zip(columns, classifier.feature_importances_)) sorted_features = sorted(features, key = lambda x: x[1]*-1) keys = [value[0] for value in sorted_features] values = [value[1] for value in sorted_features] return pd.DataFrame(data={'feature': keys, 'value': values})" }, { "code": null, "e": 13788, "s": 13731, "text": "We can evaluate our model by running the following code:" }, { "code": null, "e": 13899, "s": 13788, "text": "predictions = classifier.predict(test_df[columns])y_test = test_df[\"label\"]evaluate_model(predictions, y_test)" }, { "code": null, "e": 14034, "s": 13899, "text": "We have quite high scores across the board. We can now run the following code to see which feature is playing the most prominent role:" }, { "code": null, "e": 14074, "s": 14034, "text": "feature_importance(columns, classifier)" }, { "code": null, "e": 14307, "s": 14074, "text": "We can see above that Common neighbors (cn) is the massively dominant feature in our model. Common neighbors returns us a count of the number of unclosed co-author triangles that an author has, so this perhaps isn’t that surprising." }, { "code": null, "e": 14390, "s": 14307, "text": "Now we’re going to add some new features that are generated from graph algorithms." }, { "code": null, "e": 14696, "s": 14390, "text": "We’ll start by running the triangle count algorithm over our test and train sub graphs. This algorithm returns the number of triangles that each node forms, as well as each node’s clustering coefficient. The clustering coefficient of a node indicates the likelihood that its neighbours are also connected." }, { "code": null, "e": 14800, "s": 14696, "text": "We can run the following Cypher queries in the Neo4j Browser, to run this algorithm on our train graph:" }, { "code": null, "e": 14956, "s": 14800, "text": "CALL algo.triangleCount('Author', 'CO_AUTHOR_EARLY', { write:true, writeProperty:'trianglesTrain', clusteringCoefficientProperty:'coefficientTrain'});" }, { "code": null, "e": 15016, "s": 14956, "text": "And the following Cypher query to run it on the test graph:" }, { "code": null, "e": 15164, "s": 15016, "text": "CALL algo.triangleCount('Author', 'CO_AUTHOR', { write:true, writeProperty:'trianglesTest', clusteringCoefficientProperty:'coefficientTest'});" }, { "code": null, "e": 15370, "s": 15164, "text": "We now have 4 new properties on our nodes: trianglesTrain, coefficientTrain, trianglesTest, and coefficientTest. Let’s now add these to our train and test DataFrames, with help from the following function:" }, { "code": null, "e": 16245, "s": 15370, "text": "def apply_triangles_features(data,triangles_prop,coefficient_prop): query = \"\"\" UNWIND $pairs AS pair MATCH (p1) WHERE id(p1) = pair.node1 MATCH (p2) WHERE id(p2) = pair.node2 RETURN pair.node1 AS node1, pair.node2 AS node2, apoc.coll.min([p1[$triangles], p2[$triangles]]) AS minTriangles, apoc.coll.max([p1[$triangles], p2[$triangles]]) AS maxTriangles, apoc.coll.min([p1[$coefficient], p2[$coefficient]]) AS minCoeff, apoc.coll.max([p1[$coefficient], p2[$coefficient]]) AS maxCoeff \"\"\" pairs = [{\"node1\": pair[0], \"node2\": pair[1]} for pair in data[[\"node1\", \"node2\"]].values.tolist()] params = {\"pairs\": pairs, \"triangles\": triangles_prop, \"coefficient\": coefficient_prop} features = graph.run(query, params).to_data_frame() return pd.merge(data, features, on = [\"node1\", \"node2\"])" }, { "code": null, "e": 16403, "s": 16245, "text": "These measures are different than the ones we’ve used so far, because rather than being computed based on the pair of nodes, they are node specific measures." }, { "code": null, "e": 16617, "s": 16403, "text": "We can’t simply add these values to our DataFrame as node1Triangles or node1Coeff because we have no guarantee over the order of nodes in the pair. We need to come up with an approach that is agnostic of the order" }, { "code": null, "e": 16758, "s": 16617, "text": "We can do this by taking the average of the values, the product of the values, or by computing the minimum and maximum value, as we do here." }, { "code": null, "e": 16813, "s": 16758, "text": "We can apply that function to the DataFrame like this:" }, { "code": null, "e": 16986, "s": 16813, "text": "training_df = apply_triangles_features(training_df, \"trianglesTrain\", \"coefficientTrain\")test_df = apply_triangles_features(test_df, \"trianglesTest\", \"coefficientTest\")" }, { "code": null, "e": 17021, "s": 16986, "text": "And now we can train and evaluate:" }, { "code": null, "e": 17301, "s": 17021, "text": "columns = [ \"cn\", \"pa\", \"tn\", \"minTriangles\", \"maxTriangles\", \"minCoeff\", \"maxCoeff\"]X = training_df[columns]y = training_df[\"label\"]classifier.fit(X, y)predictions = classifier.predict(test_df[columns])y_test = test_df[\"label\"]display(evaluate_model(predictions, y_test))" }, { "code": null, "e": 17441, "s": 17301, "text": "Those features have been helpful! Each of our measures have improved by about 4% from the initial model. Which features are most important?" }, { "code": null, "e": 17490, "s": 17441, "text": "display(feature_importance(columns, classifier))" }, { "code": null, "e": 17596, "s": 17490, "text": "Common neighbors is still the most influential, but the triangles features are adding some value as well." }, { "code": null, "e": 17736, "s": 17596, "text": "This post has already gone on a lot longer than I intended so we’ll stop there, but there are certainly some exercises left for the reader." }, { "code": null, "e": 17931, "s": 17736, "text": "Can you think of any other features that we could add that might help us to create a model with even higher accuracy? Perhaps other community detection, or even centrality algorithms might help?" }, { "code": null, "e": 18326, "s": 17931, "text": "At the moment the link prediction algorithms in the Graph Algorithms Library only work for mono-partite graphs. Mono-partite graphs are ones where the label of both nodes are the same. The algorithms are based on the topology of nodes, and if we try to apply them to nodes with different labels, those nodes will likely have different topologies, meaning that the algorithms won’t work so well." }, { "code": null, "e": 18513, "s": 18326, "text": "We’re looking at adding versions of the link prediction algorithms that work on other graphs. If you have any particular ones that you’d like to see, please let us know on GitHub issues." }, { "code": null, "e": 18754, "s": 18513, "text": "If you found this blog post interesting, you might enjoy the O’Reilly Graph Algorithms Book that Amy Hodler and I have been working on over the last 9 months. We’re in the final review stage and it should be available in the next few weeks." }, { "code": null, "e": 18862, "s": 18754, "text": "You can register to get your free digital copy from the Neo4j webisite, at: neo4j.com/graph-algorithms-book" } ]
How to import Google Sheets data into a Pandas DataFrame using Google’s API v4 (2020) | by Erik Yan | Towards Data Science
Google Sheets is a useful way to share data and collaborate remotely. But transferring the data to environments such as Python on a regular basis can be burdensome. This post will cover how to set up the latest Google Sheets API, v4 as of June 2020, for Python. We’ll also cover how to extract data from a Google Sheet range (or even an entire sheet) into a Pandas data frame. Before you start you’ll need the following: Python 2.6 or greater (Python 3 recommended) Pip/pip3 package management tool (comes standard with Python 2 >= 2.7.9 or Python 3 >= 3.4) A Google Account (and Google Sheet containing your data-of-interest). First, you’ll need to enable the Google Sheets API on your Gmail account, where the Google Sheet is stored. Login to your Gmail account and visit the Google Sheets API QuickStart Guide for Python. You’ll see a blue “Enable Google Sheets API” button. Click on the button (marked as [1] in the image below): Select “Desktop App” from the dropdown menu (marked as [2] in the image below) and click “Create” (marked as [3] in the image below). This will create a client configuration, which we’ll need to set up the initial connection via the API: Click the blue “DOWNLOAD CLIENT CONFIGURATION” button (marked as [4] in the image below). You should now have a file named “credentials.json” downloaded. You’ll need to move this file to your working directory. Next we’ll need to install Google’s Client Library using pip: pip install — upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib NOTE: Rather than running the sample Python code Google provides in their guide, we’ll be using a modified version of their script. First, we’ll set up our gsheet_api_check() function. It looks for an existing token.pickle file (which stores our user access and refresh tokens). If no token.pickle file is found, the function will prompt you to log into your Google Gmail account. The credentials.json must be present in your working directory to initiate token.pickle creation/refresh. The function generates the credentials we’ll use to make API calls: import pickleimport os.pathfrom google_auth_oauthlib.flow import InstalledAppFlowfrom google.auth.transport.requests import Requestdef gsheet_api_check(SCOPES): creds = None if os.path.exists('token.pickle'): with open('token.pickle', 'rb') as token: creds = pickle.load(token) if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file( 'credentials.json', SCOPES) creds = flow.run_local_server(port=0) with open('token.pickle', 'wb') as token: pickle.dump(creds, token) return creds NOTE: After completing the initial credentials setup we can discard gsheet_api_check() and load our tokens directly during future API calls. Alternatively, it may be beneficial to keep gsheet_api_check() because the function checks if our tokens are expired and/or missing. If the tokens are expired/missing, gsheet_api_check() will then initiate a refresh of the user tokens (by prompting you to re-login to your Google account). You can decide whether you want to continue using gsheet_api_check() or load the tokens directly. Next we’ll define a function that makes the API call and pulls the data we want from Google Sheets. The pull_sheet_data() function establishes the API call and pulls the data we want. If no data is found the function will print “No data found.”, otherwise it will confirm the data has been retrieved by printing “COMPLETE: Data Copied” and return our data: from googleapiclient.discovery import builddef pull_sheet_data(SCOPES,SPREADSHEET_ID,DATA_TO_PULL): creds = gsheet_api_check(SCOPES) service = build('sheets', 'v4', credentials=creds) sheet = service.spreadsheets() result = sheet.values().get( spreadsheetId=SPREADSHEET_ID, range=DATA_TO_PULL).execute() values = result.get('values', []) if not values: print('No data found.') else: rows = sheet.values().get(spreadsheetId=SPREADSHEET_ID, range=DATA_TO_PULL).execute() data = rows.get('values') print("COMPLETE: Data copied") return data NOTE: pull_sheet_data() can be modified to define other API tasks such as appending data to a google sheet, updating existing data, or creating new spreadsheets. Next we will need two pieces of information. First, we need to find and copy the ID of the spreadsheet-of-interest. This can be found in the URL of your Google Spreadsheet (marked as [5] in the image below): Second, we’ll need the name of the spreadsheet tab from which we’ll pull the data from. Alternatively, you can explicitly define the range of cells you want to retrieve if you wish to pull specific sections of data from the spreadsheet (examples provided below): #Pulls data from the entire spreadsheet tab.DATA_TO_PULL = 'spreadsheet_tab_name'or#Pulls data only from the specified range of cells.DATA_TO_PULL = 'spreadsheet_tab_name!A2:C6' Finally, we’ll bring all of our code together by specifying the pull_sheet_data() parameters, running the functions, and then storing the retrieved data into a Pandas DataFrame. Be sure to replace ‘spreadsheet_url_ID ’ with the spreadsheet ID you copied, and replace ‘spreadsheet_tab_name!’ with your spreadsheet tab name (and range if necessary): import pandas as pdSCOPES = ['https://www.googleapis.com/auth/spreadsheets']SPREADSHEET_ID = 'spreadsheet_url_ID'DATA_TO_PULL = 'spreadsheet_tab_name'data = pull_sheet_data(SCOPES,SPREADSHEET_ID,DATA_TO_PULL)df = pd.DataFrame(data[1:], columns=data[0])df And now you’re ready to explore your retrieved data within Python, all without manually downloading or importing the dataset!
[ { "code": null, "e": 549, "s": 172, "text": "Google Sheets is a useful way to share data and collaborate remotely. But transferring the data to environments such as Python on a regular basis can be burdensome. This post will cover how to set up the latest Google Sheets API, v4 as of June 2020, for Python. We’ll also cover how to extract data from a Google Sheet range (or even an entire sheet) into a Pandas data frame." }, { "code": null, "e": 593, "s": 549, "text": "Before you start you’ll need the following:" }, { "code": null, "e": 638, "s": 593, "text": "Python 2.6 or greater (Python 3 recommended)" }, { "code": null, "e": 730, "s": 638, "text": "Pip/pip3 package management tool (comes standard with Python 2 >= 2.7.9 or Python 3 >= 3.4)" }, { "code": null, "e": 800, "s": 730, "text": "A Google Account (and Google Sheet containing your data-of-interest)." }, { "code": null, "e": 1106, "s": 800, "text": "First, you’ll need to enable the Google Sheets API on your Gmail account, where the Google Sheet is stored. Login to your Gmail account and visit the Google Sheets API QuickStart Guide for Python. You’ll see a blue “Enable Google Sheets API” button. Click on the button (marked as [1] in the image below):" }, { "code": null, "e": 1344, "s": 1106, "text": "Select “Desktop App” from the dropdown menu (marked as [2] in the image below) and click “Create” (marked as [3] in the image below). This will create a client configuration, which we’ll need to set up the initial connection via the API:" }, { "code": null, "e": 1434, "s": 1344, "text": "Click the blue “DOWNLOAD CLIENT CONFIGURATION” button (marked as [4] in the image below)." }, { "code": null, "e": 1555, "s": 1434, "text": "You should now have a file named “credentials.json” downloaded. You’ll need to move this file to your working directory." }, { "code": null, "e": 1617, "s": 1555, "text": "Next we’ll need to install Google’s Client Library using pip:" }, { "code": null, "e": 1706, "s": 1617, "text": "pip install — upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib" }, { "code": null, "e": 1838, "s": 1706, "text": "NOTE: Rather than running the sample Python code Google provides in their guide, we’ll be using a modified version of their script." }, { "code": null, "e": 2261, "s": 1838, "text": "First, we’ll set up our gsheet_api_check() function. It looks for an existing token.pickle file (which stores our user access and refresh tokens). If no token.pickle file is found, the function will prompt you to log into your Google Gmail account. The credentials.json must be present in your working directory to initiate token.pickle creation/refresh. The function generates the credentials we’ll use to make API calls:" }, { "code": null, "e": 2962, "s": 2261, "text": "import pickleimport os.pathfrom google_auth_oauthlib.flow import InstalledAppFlowfrom google.auth.transport.requests import Requestdef gsheet_api_check(SCOPES): creds = None if os.path.exists('token.pickle'): with open('token.pickle', 'rb') as token: creds = pickle.load(token) if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file( 'credentials.json', SCOPES) creds = flow.run_local_server(port=0) with open('token.pickle', 'wb') as token: pickle.dump(creds, token) return creds" }, { "code": null, "e": 3491, "s": 2962, "text": "NOTE: After completing the initial credentials setup we can discard gsheet_api_check() and load our tokens directly during future API calls. Alternatively, it may be beneficial to keep gsheet_api_check() because the function checks if our tokens are expired and/or missing. If the tokens are expired/missing, gsheet_api_check() will then initiate a refresh of the user tokens (by prompting you to re-login to your Google account). You can decide whether you want to continue using gsheet_api_check() or load the tokens directly." }, { "code": null, "e": 3848, "s": 3491, "text": "Next we’ll define a function that makes the API call and pulls the data we want from Google Sheets. The pull_sheet_data() function establishes the API call and pulls the data we want. If no data is found the function will print “No data found.”, otherwise it will confirm the data has been retrieved by printing “COMPLETE: Data Copied” and return our data:" }, { "code": null, "e": 4493, "s": 3848, "text": "from googleapiclient.discovery import builddef pull_sheet_data(SCOPES,SPREADSHEET_ID,DATA_TO_PULL): creds = gsheet_api_check(SCOPES) service = build('sheets', 'v4', credentials=creds) sheet = service.spreadsheets() result = sheet.values().get( spreadsheetId=SPREADSHEET_ID, range=DATA_TO_PULL).execute() values = result.get('values', []) if not values: print('No data found.') else: rows = sheet.values().get(spreadsheetId=SPREADSHEET_ID, range=DATA_TO_PULL).execute() data = rows.get('values') print(\"COMPLETE: Data copied\") return data" }, { "code": null, "e": 4655, "s": 4493, "text": "NOTE: pull_sheet_data() can be modified to define other API tasks such as appending data to a google sheet, updating existing data, or creating new spreadsheets." }, { "code": null, "e": 4863, "s": 4655, "text": "Next we will need two pieces of information. First, we need to find and copy the ID of the spreadsheet-of-interest. This can be found in the URL of your Google Spreadsheet (marked as [5] in the image below):" }, { "code": null, "e": 5126, "s": 4863, "text": "Second, we’ll need the name of the spreadsheet tab from which we’ll pull the data from. Alternatively, you can explicitly define the range of cells you want to retrieve if you wish to pull specific sections of data from the spreadsheet (examples provided below):" }, { "code": null, "e": 5304, "s": 5126, "text": "#Pulls data from the entire spreadsheet tab.DATA_TO_PULL = 'spreadsheet_tab_name'or#Pulls data only from the specified range of cells.DATA_TO_PULL = 'spreadsheet_tab_name!A2:C6'" }, { "code": null, "e": 5652, "s": 5304, "text": "Finally, we’ll bring all of our code together by specifying the pull_sheet_data() parameters, running the functions, and then storing the retrieved data into a Pandas DataFrame. Be sure to replace ‘spreadsheet_url_ID ’ with the spreadsheet ID you copied, and replace ‘spreadsheet_tab_name!’ with your spreadsheet tab name (and range if necessary):" }, { "code": null, "e": 5907, "s": 5652, "text": "import pandas as pdSCOPES = ['https://www.googleapis.com/auth/spreadsheets']SPREADSHEET_ID = 'spreadsheet_url_ID'DATA_TO_PULL = 'spreadsheet_tab_name'data = pull_sheet_data(SCOPES,SPREADSHEET_ID,DATA_TO_PULL)df = pd.DataFrame(data[1:], columns=data[0])df" } ]
5 Common SQL Interview Problems for Data Scientists | by Terence Shin | Towards Data Science
While it’s not the sexiest part of the job, having a strong understanding of SQL is essential to succeed in any data-focused job. The truth is that there’s way more to SQL than SELECT FROM WHERE GROUP BY ORDER BY. The more functions you know, the easier it’ll be for you to manipulate and query anything you want. There are two things I hope to learn and communicate in this article: Learn and teach SQL functions beyond the basic fundamentalsGo through a number of SQL interview practice problems Learn and teach SQL functions beyond the basic fundamentals Go through a number of SQL interview practice problems These questions are taken from none other than Leetcode! Go check it out if you haven’t yet! PROBLEM #1: Second Highest Salary PROBLEM #2: Duplicate Emails PROBLEM #3: Rising Temperature PROBLEM #4: Department Highest Salary PROBLEM #5: Exchange Seats Write a SQL query to get the second highest salary from the Employee table. For example, given the Employee table below, the query should return 200 as the second highest salary. If there is no second highest salary, then the query should return null. +----+--------+| Id | Salary |+----+--------+| 1 | 100 || 2 | 200 || 3 | 300 |+----+--------+ IFNULL(expression, alt) : ifnull() returns the specified value if null, otherwise returns the expected value. We’ll use this to return null if there’s no second-highest salary. OFFSET : offset is used with the ORDER BY clause to disregard the top n rows that you specify. This will be useful as you’ll want to get the second row (2nd highest salary) SELECT IFNULL( (SELECT DISTINCT Salary FROM Employee ORDER BY Salary DESC LIMIT 1 OFFSET 1 ), null) as SecondHighestSalaryFROM EmployeeLIMIT 1 This query says to choose the MAX salary that isn’t equal to the MAX salary, which is equivalent to saying to choose the second-highest salary! SELECT MAX(salary) AS SecondHighestSalaryFROM EmployeeWHERE salary != (SELECT MAX(salary) FROM Employee) Write a SQL query to find all duplicate emails in a table named Person. +----+---------+| Id | Email |+----+---------+| 1 | [email protected] || 2 | [email protected] || 3 | [email protected] |+----+---------+ First, a subquery is created to show the count of the frequency of each email. Then the subquery is filtered WHERE the count is greater than 1. SELECT EmailFROM ( SELECT Email, count(Email) AS count FROM Person GROUP BY Email) as email_countWHERE count > 1 HAVING is a clause that essentially allows you to use a WHERE statement in conjunction with aggregates (GROUP BY). SELECT EmailFROM PersonGROUP BY EmailHAVING count(Email) > 1 Given a Weather table, write a SQL query to find all dates' Ids with higher temperature compared to its previous (yesterday's) dates. +---------+------------------+------------------+| Id(INT) | RecordDate(DATE) | Temperature(INT) |+---------+------------------+------------------+| 1 | 2015-01-01 | 10 || 2 | 2015-01-02 | 25 || 3 | 2015-01-03 | 20 || 4 | 2015-01-04 | 30 |+---------+------------------+------------------+ DATEDIFF calculates the difference between two dates and is used to make sure we’re comparing today’s temperature to yesterday’s temperature. In plain English, the query is saying, Select the Ids where the temperature on a given day is greater than the temperature yesterday. SELECT DISTINCT a.IdFROM Weather a, Weather bWHERE a.Temperature > b.TemperatureAND DATEDIFF(a.Recorddate, b.Recorddate) = 1 The Employee table holds all employees. Every employee has an Id, a salary, and there is also a column for the department Id. +----+-------+--------+--------------+| Id | Name | Salary | DepartmentId |+----+-------+--------+--------------+| 1 | Joe | 70000 | 1 || 2 | Jim | 90000 | 1 || 3 | Henry | 80000 | 2 || 4 | Sam | 60000 | 2 || 5 | Max | 90000 | 1 |+----+-------+--------+--------------+ The Department table holds all departments of the company. +----+----------+| Id | Name |+----+----------+| 1 | IT || 2 | Sales |+----+----------+ Write a SQL query to find employees who have the highest salary in each of the departments. For the above tables, your SQL query should return the following rows (order of rows does not matter). +------------+----------+--------+| Department | Employee | Salary |+------------+----------+--------+| IT | Max | 90000 || IT | Jim | 90000 || Sales | Henry | 80000 |+------------+----------+--------+ The IN clause allows you to use multiple OR clauses in a WHERE statement. For example WHERE country = ‘Canada’ or country = ‘USA’ is the same as WHERE country IN (‘Canada’, ’USA’). In this case, we want to filter the Department table to only show the highest Salary per Department (i.e. DepartmentId). Then we can join the two tables WHERE the DepartmentId and Salary is in the filtered Department table. SELECT Department.name AS 'Department', Employee.name AS 'Employee', SalaryFROM EmployeeINNER JOIN Department ON Employee.DepartmentId = Department.IdWHERE (DepartmentId , Salary) IN ( SELECT DepartmentId, MAX(Salary) FROM Employee GROUP BY DepartmentId ) Mary is a teacher in a middle school and she has a table seat storing students' names and their corresponding seat ids. The column id is a continuous increment. Mary wants to change seats for the adjacent students. Can you write a SQL query to output the result for Mary? +---------+---------+| id | student |+---------+---------+| 1 | Abbot || 2 | Doris || 3 | Emerson || 4 | Green || 5 | Jeames |+---------+---------+ For the sample input, the output is: +---------+---------+| id | student |+---------+---------+| 1 | Doris || 2 | Abbot || 3 | Green || 4 | Emerson || 5 | Jeames |+---------+---------+ Note:If the number of students is odd, there is no need to change the last one’s seat. Think of a CASE WHEN THEN statement like an IF statement in coding. The first WHEN statement checks to see if there’s an odd number of rows, and if there is, ensure that the id number does not change. The second WHEN statement adds 1 to each id (eg. 1,3,5 becomes 2,4,6) Similarly, the third WHEN statement subtracts 1 to each id (2,4,6 becomes 1,3,5) SELECT CASE WHEN((SELECT MAX(id) FROM seat)%2 = 1) AND id = (SELECT MAX(id) FROM seat) THEN id WHEN id%2 = 1 THEN id + 1 ELSE id - 1 END AS id, studentFROM seatORDER BY id And that’s it! Please comment below if there is anything unclear and I will do my best to clarify anything to the best of my ability — Thanks! If you like my work and want to support me... The BEST way to support me is by following me on Medium here.Be one of the FIRST to follow me on Twitter here. I’ll be posting lots of updates and interesting stuff here!Also, be one of the FIRST to subscribe to my new YouTube channel here!Follow me on LinkedIn here.Sign up on my email list here.Check out my website, terenceshin.com. The BEST way to support me is by following me on Medium here. Be one of the FIRST to follow me on Twitter here. I’ll be posting lots of updates and interesting stuff here! Also, be one of the FIRST to subscribe to my new YouTube channel here! Follow me on LinkedIn here. Sign up on my email list here. Check out my website, terenceshin.com.
[ { "code": null, "e": 485, "s": 171, "text": "While it’s not the sexiest part of the job, having a strong understanding of SQL is essential to succeed in any data-focused job. The truth is that there’s way more to SQL than SELECT FROM WHERE GROUP BY ORDER BY. The more functions you know, the easier it’ll be for you to manipulate and query anything you want." }, { "code": null, "e": 555, "s": 485, "text": "There are two things I hope to learn and communicate in this article:" }, { "code": null, "e": 669, "s": 555, "text": "Learn and teach SQL functions beyond the basic fundamentalsGo through a number of SQL interview practice problems" }, { "code": null, "e": 729, "s": 669, "text": "Learn and teach SQL functions beyond the basic fundamentals" }, { "code": null, "e": 784, "s": 729, "text": "Go through a number of SQL interview practice problems" }, { "code": null, "e": 877, "s": 784, "text": "These questions are taken from none other than Leetcode! Go check it out if you haven’t yet!" }, { "code": null, "e": 911, "s": 877, "text": "PROBLEM #1: Second Highest Salary" }, { "code": null, "e": 940, "s": 911, "text": "PROBLEM #2: Duplicate Emails" }, { "code": null, "e": 971, "s": 940, "text": "PROBLEM #3: Rising Temperature" }, { "code": null, "e": 1009, "s": 971, "text": "PROBLEM #4: Department Highest Salary" }, { "code": null, "e": 1036, "s": 1009, "text": "PROBLEM #5: Exchange Seats" }, { "code": null, "e": 1288, "s": 1036, "text": "Write a SQL query to get the second highest salary from the Employee table. For example, given the Employee table below, the query should return 200 as the second highest salary. If there is no second highest salary, then the query should return null." }, { "code": null, "e": 1394, "s": 1288, "text": "+----+--------+| Id | Salary |+----+--------+| 1 | 100 || 2 | 200 || 3 | 300 |+----+--------+" }, { "code": null, "e": 1571, "s": 1394, "text": "IFNULL(expression, alt) : ifnull() returns the specified value if null, otherwise returns the expected value. We’ll use this to return null if there’s no second-highest salary." }, { "code": null, "e": 1744, "s": 1571, "text": "OFFSET : offset is used with the ORDER BY clause to disregard the top n rows that you specify. This will be useful as you’ll want to get the second row (2nd highest salary)" }, { "code": null, "e": 1925, "s": 1744, "text": "SELECT IFNULL( (SELECT DISTINCT Salary FROM Employee ORDER BY Salary DESC LIMIT 1 OFFSET 1 ), null) as SecondHighestSalaryFROM EmployeeLIMIT 1" }, { "code": null, "e": 2069, "s": 1925, "text": "This query says to choose the MAX salary that isn’t equal to the MAX salary, which is equivalent to saying to choose the second-highest salary!" }, { "code": null, "e": 2174, "s": 2069, "text": "SELECT MAX(salary) AS SecondHighestSalaryFROM EmployeeWHERE salary != (SELECT MAX(salary) FROM Employee)" }, { "code": null, "e": 2246, "s": 2174, "text": "Write a SQL query to find all duplicate emails in a table named Person." }, { "code": null, "e": 2359, "s": 2246, "text": "+----+---------+| Id | Email |+----+---------+| 1 | [email protected] || 2 | [email protected] || 3 | [email protected] |+----+---------+" }, { "code": null, "e": 2503, "s": 2359, "text": "First, a subquery is created to show the count of the frequency of each email. Then the subquery is filtered WHERE the count is greater than 1." }, { "code": null, "e": 2625, "s": 2503, "text": "SELECT EmailFROM ( SELECT Email, count(Email) AS count FROM Person GROUP BY Email) as email_countWHERE count > 1" }, { "code": null, "e": 2740, "s": 2625, "text": "HAVING is a clause that essentially allows you to use a WHERE statement in conjunction with aggregates (GROUP BY)." }, { "code": null, "e": 2801, "s": 2740, "text": "SELECT EmailFROM PersonGROUP BY EmailHAVING count(Email) > 1" }, { "code": null, "e": 2935, "s": 2801, "text": "Given a Weather table, write a SQL query to find all dates' Ids with higher temperature compared to its previous (yesterday's) dates." }, { "code": null, "e": 3328, "s": 2935, "text": "+---------+------------------+------------------+| Id(INT) | RecordDate(DATE) | Temperature(INT) |+---------+------------------+------------------+| 1 | 2015-01-01 | 10 || 2 | 2015-01-02 | 25 || 3 | 2015-01-03 | 20 || 4 | 2015-01-04 | 30 |+---------+------------------+------------------+" }, { "code": null, "e": 3470, "s": 3328, "text": "DATEDIFF calculates the difference between two dates and is used to make sure we’re comparing today’s temperature to yesterday’s temperature." }, { "code": null, "e": 3604, "s": 3470, "text": "In plain English, the query is saying, Select the Ids where the temperature on a given day is greater than the temperature yesterday." }, { "code": null, "e": 3729, "s": 3604, "text": "SELECT DISTINCT a.IdFROM Weather a, Weather bWHERE a.Temperature > b.TemperatureAND DATEDIFF(a.Recorddate, b.Recorddate) = 1" }, { "code": null, "e": 3855, "s": 3729, "text": "The Employee table holds all employees. Every employee has an Id, a salary, and there is also a column for the department Id." }, { "code": null, "e": 4198, "s": 3855, "text": "+----+-------+--------+--------------+| Id | Name | Salary | DepartmentId |+----+-------+--------+--------------+| 1 | Joe | 70000 | 1 || 2 | Jim | 90000 | 1 || 3 | Henry | 80000 | 2 || 4 | Sam | 60000 | 2 || 5 | Max | 90000 | 1 |+----+-------+--------+--------------+" }, { "code": null, "e": 4257, "s": 4198, "text": "The Department table holds all departments of the company." }, { "code": null, "e": 4360, "s": 4257, "text": "+----+----------+| Id | Name |+----+----------+| 1 | IT || 2 | Sales |+----+----------+" }, { "code": null, "e": 4555, "s": 4360, "text": "Write a SQL query to find employees who have the highest salary in each of the departments. For the above tables, your SQL query should return the following rows (order of rows does not matter)." }, { "code": null, "e": 4794, "s": 4555, "text": "+------------+----------+--------+| Department | Employee | Salary |+------------+----------+--------+| IT | Max | 90000 || IT | Jim | 90000 || Sales | Henry | 80000 |+------------+----------+--------+" }, { "code": null, "e": 4975, "s": 4794, "text": "The IN clause allows you to use multiple OR clauses in a WHERE statement. For example WHERE country = ‘Canada’ or country = ‘USA’ is the same as WHERE country IN (‘Canada’, ’USA’)." }, { "code": null, "e": 5199, "s": 4975, "text": "In this case, we want to filter the Department table to only show the highest Salary per Department (i.e. DepartmentId). Then we can join the two tables WHERE the DepartmentId and Salary is in the filtered Department table." }, { "code": null, "e": 5509, "s": 5199, "text": "SELECT Department.name AS 'Department', Employee.name AS 'Employee', SalaryFROM EmployeeINNER JOIN Department ON Employee.DepartmentId = Department.IdWHERE (DepartmentId , Salary) IN ( SELECT DepartmentId, MAX(Salary) FROM Employee GROUP BY DepartmentId )" }, { "code": null, "e": 5724, "s": 5509, "text": "Mary is a teacher in a middle school and she has a table seat storing students' names and their corresponding seat ids. The column id is a continuous increment. Mary wants to change seats for the adjacent students." }, { "code": null, "e": 5781, "s": 5724, "text": "Can you write a SQL query to output the result for Mary?" }, { "code": null, "e": 5971, "s": 5781, "text": "+---------+---------+| id | student |+---------+---------+| 1 | Abbot || 2 | Doris || 3 | Emerson || 4 | Green || 5 | Jeames |+---------+---------+" }, { "code": null, "e": 6008, "s": 5971, "text": "For the sample input, the output is:" }, { "code": null, "e": 6198, "s": 6008, "text": "+---------+---------+| id | student |+---------+---------+| 1 | Doris || 2 | Abbot || 3 | Green || 4 | Emerson || 5 | Jeames |+---------+---------+" }, { "code": null, "e": 6285, "s": 6198, "text": "Note:If the number of students is odd, there is no need to change the last one’s seat." }, { "code": null, "e": 6353, "s": 6285, "text": "Think of a CASE WHEN THEN statement like an IF statement in coding." }, { "code": null, "e": 6486, "s": 6353, "text": "The first WHEN statement checks to see if there’s an odd number of rows, and if there is, ensure that the id number does not change." }, { "code": null, "e": 6556, "s": 6486, "text": "The second WHEN statement adds 1 to each id (eg. 1,3,5 becomes 2,4,6)" }, { "code": null, "e": 6637, "s": 6556, "text": "Similarly, the third WHEN statement subtracts 1 to each id (2,4,6 becomes 1,3,5)" }, { "code": null, "e": 6838, "s": 6637, "text": "SELECT CASE WHEN((SELECT MAX(id) FROM seat)%2 = 1) AND id = (SELECT MAX(id) FROM seat) THEN id WHEN id%2 = 1 THEN id + 1 ELSE id - 1 END AS id, studentFROM seatORDER BY id" }, { "code": null, "e": 6981, "s": 6838, "text": "And that’s it! Please comment below if there is anything unclear and I will do my best to clarify anything to the best of my ability — Thanks!" }, { "code": null, "e": 7027, "s": 6981, "text": "If you like my work and want to support me..." }, { "code": null, "e": 7363, "s": 7027, "text": "The BEST way to support me is by following me on Medium here.Be one of the FIRST to follow me on Twitter here. I’ll be posting lots of updates and interesting stuff here!Also, be one of the FIRST to subscribe to my new YouTube channel here!Follow me on LinkedIn here.Sign up on my email list here.Check out my website, terenceshin.com." }, { "code": null, "e": 7425, "s": 7363, "text": "The BEST way to support me is by following me on Medium here." }, { "code": null, "e": 7535, "s": 7425, "text": "Be one of the FIRST to follow me on Twitter here. I’ll be posting lots of updates and interesting stuff here!" }, { "code": null, "e": 7606, "s": 7535, "text": "Also, be one of the FIRST to subscribe to my new YouTube channel here!" }, { "code": null, "e": 7634, "s": 7606, "text": "Follow me on LinkedIn here." }, { "code": null, "e": 7665, "s": 7634, "text": "Sign up on my email list here." } ]
Java Examples - Set Background to a Table
How to set background to a table in a PDF using Java. Following is the program to set background to a table in a PDF using Java. import com.itextpdf.kernel.color.Color; import com.itextpdf.kernel.pdf.PdfDocument; import com.itextpdf.kernel.pdf.PdfWriter; import com.itextpdf.layout.Document; import com.itextpdf.layout.border.Border; import com.itextpdf.layout.element.Cell; import com.itextpdf.layout.element.Table; import com.itextpdf.layout.property.TextAlignment; public class BackgroundToTable { public static void main(String args[]) throws Exception { String file = "C:/EXAMPLES/itextExamples/backgroundToTable.pdf"; //Creating a PdfDocument object PdfDocument pdfDoc = new PdfDocument(new PdfWriter(file)); //Creating a Document object Document doc = new Document(pdfDoc); //Creating a table Table table = new Table(2); //Adding row 1 to the table Cell c1 = new Cell(); c1.add("Name"); c1.setBackgroundColor(Color.DARK_GRAY); c1.setBorder(Border.NO_BORDER); c1.setTextAlignment(TextAlignment.CENTER); table.addCell(c1); Cell c2 = new Cell(); c2.add("Raju"); c2.setBackgroundColor(Color.GRAY); c2.setBorder(Border.NO_BORDER); c2.setTextAlignment(TextAlignment.CENTER); table.addCell(c2); //Adding row 2 to the table Cell c3 = new Cell(); c3.add("Id"); c3.setBackgroundColor(Color.WHITE); c3.setBorder(Border.NO_BORDER); c3.setTextAlignment(TextAlignment.CENTER); table.addCell(c3); Cell c4 = new Cell(); c4.add("001"); c4.setBackgroundColor(Color.WHITE); c4.setBorder(Border.NO_BORDER); c4.setTextAlignment(TextAlignment.CENTER); table.addCell(c4); //Adding row 3 to the table Cell c5 = new Cell(); c5.add("Designation"); c5.setBackgroundColor(Color.DARK_GRAY); c5.setBorder(Border.NO_BORDER); c5.setTextAlignment(TextAlignment.CENTER); table.addCell(c5); Cell c6 = new Cell(); c6.add("Programmer"); c6.setBackgroundColor(Color.GRAY); c6.setBorder(Border.NO_BORDER); c6.setTextAlignment(TextAlignment.CENTER); table.addCell(c6); //Adding Table to document doc.add(table); //Closing the document doc.close(); System.out.println("Background added successfully.."); } } Print Add Notes Bookmark this page
[ { "code": null, "e": 2122, "s": 2068, "text": "How to set background to a table in a PDF using Java." }, { "code": null, "e": 2197, "s": 2122, "text": "Following is the program to set background to a table in a PDF using Java." }, { "code": null, "e": 4621, "s": 2197, "text": "import com.itextpdf.kernel.color.Color; \nimport com.itextpdf.kernel.pdf.PdfDocument; \nimport com.itextpdf.kernel.pdf.PdfWriter; \n\nimport com.itextpdf.layout.Document; \nimport com.itextpdf.layout.border.Border; \nimport com.itextpdf.layout.element.Cell; \nimport com.itextpdf.layout.element.Table; \nimport com.itextpdf.layout.property.TextAlignment; \n\npublic class BackgroundToTable { \n public static void main(String args[]) throws Exception {\n String file = \"C:/EXAMPLES/itextExamples/backgroundToTable.pdf\"; \n\n //Creating a PdfDocument object \n PdfDocument pdfDoc = new PdfDocument(new PdfWriter(file)); \n\n //Creating a Document object \n Document doc = new Document(pdfDoc); \n\n //Creating a table \n Table table = new Table(2); \n\n //Adding row 1 to the table \n Cell c1 = new Cell(); \n \n c1.add(\"Name\"); \n c1.setBackgroundColor(Color.DARK_GRAY); \n c1.setBorder(Border.NO_BORDER); \n c1.setTextAlignment(TextAlignment.CENTER); \n table.addCell(c1); \n\n Cell c2 = new Cell(); \n c2.add(\"Raju\"); \n c2.setBackgroundColor(Color.GRAY); \n c2.setBorder(Border.NO_BORDER); \n c2.setTextAlignment(TextAlignment.CENTER); \n table.addCell(c2); \n\n //Adding row 2 to the table \n Cell c3 = new Cell(); \n \n c3.add(\"Id\"); \n c3.setBackgroundColor(Color.WHITE); \n c3.setBorder(Border.NO_BORDER); \n c3.setTextAlignment(TextAlignment.CENTER); \n table.addCell(c3); \n\n Cell c4 = new Cell(); \n c4.add(\"001\");\n c4.setBackgroundColor(Color.WHITE); \n c4.setBorder(Border.NO_BORDER); \n c4.setTextAlignment(TextAlignment.CENTER); \n table.addCell(c4); \n\n //Adding row 3 to the table \n Cell c5 = new Cell(); \n \n c5.add(\"Designation\"); \n c5.setBackgroundColor(Color.DARK_GRAY); \n c5.setBorder(Border.NO_BORDER); \n c5.setTextAlignment(TextAlignment.CENTER); \n table.addCell(c5); \n\n Cell c6 = new Cell(); \n c6.add(\"Programmer\"); \n c6.setBackgroundColor(Color.GRAY); \n c6.setBorder(Border.NO_BORDER); \n c6.setTextAlignment(TextAlignment.CENTER); \n table.addCell(c6); \n\n //Adding Table to document \n doc.add(table); \n\n //Closing the document \n doc.close(); \n System.out.println(\"Background added successfully..\"); \n } \n}" }, { "code": null, "e": 4628, "s": 4621, "text": " Print" }, { "code": null, "e": 4639, "s": 4628, "text": " Add Notes" } ]
Matplotlib.pyplot.hexbin() function in Python - GeeksforGeeks
05 Jun, 2020 Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. There are various plots which can be used in Pyplot are Line Plot, Contour, Histogram, Scatter, 3D Plot, etc. The hexbin() function in pyplot module of matplotlib library is used to make a 2D hexagonal binning plot of points x, y. Syntax: matplotlib.pyplot.hexbin(x, y, C=None, gridsize=100, bins=None, xscale=’linear’, yscale=’linear’, extent=None, cmap=None, norm=None, vmin=None, vmax=None, alpha=None, linewidths=None, edgecolors=’face’, reduce_C_function=, mincnt=None, marginals=False, *, data=None, **kwargs) Parameters: This method accept the following parameters that are described below: x, y: These parameter are the sequence of data. x and y must be of the same length. C : This parameter are the values which are accumulated in the bins. gridsize : This parameter represents the number of hexagons in the x-direction or both direction. xscale : This parameter uses a linear or log10 scale on the horizontal axis. xycale : This parameter uses a linear or log10 scale on the vertical axis. mincnt : This parameter is used to display cells with more than mincnt number of points in the cell. marginals : This parameter is used to plot the marginal density as colormapped rectangles along the bottom of the x-axis and left of the y-axis. extent : This parameter is the limits of the bins. Returns: This returns the following: polycollection : This returns the PolyCollection defining the hexagonal bins. Below examples illustrate the matplotlib.pyplot.hexbin() function in matplotlib.pyplot: Example 1: Python3 # Implementation of matplotlib function import matplotlib.pyplot as plt import numpy as np np.random.seed(19680801) n = 100000x = np.random.standard_normal(n) y = 12 * np.random.standard_normal(n) plt.hexbin(x, y, gridsize = 50, cmap ='Greens') plt.title('matplotlib.pyplot.hexbin() Example') plt.show() Output: Example 2: Python3 # Implementation of matplotlib function import matplotlib.pyplot as plt import numpy as np np.random.seed(19680801) n = 100000x = np.random.standard_normal(n) y = 2 * np.random.standard_normal(n) z =[1, 2, 3, 4] xmin = x.min() xmax = x.max() ymin = y.min() ymax = y.max() hb = plt.hexbin(x, y, gridsize = 50, bins = z, cmap ='BuGn') plt.xlim(xmin, xmax)plt.ylim(ymin, ymax) cb = plt.colorbar(hb) cb.set_label(z)plt.title('matplotlib.pyplot.hexbin()\Example') plt.show() Output: Matplotlib Pyplot-class Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python OOPs Concepts How to Install PIP on Windows ? Bar Plot in Matplotlib Defaultdict in Python Python Classes and Objects Deque in Python Check if element exists in list in Python How to drop one or multiple columns in Pandas Dataframe Python - Ways to remove duplicates from list Class method vs Static method in Python
[ { "code": null, "e": 23901, "s": 23873, "text": "\n05 Jun, 2020" }, { "code": null, "e": 24207, "s": 23901, "text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. There are various plots which can be used in Pyplot are Line Plot, Contour, Histogram, Scatter, 3D Plot, etc. " }, { "code": null, "e": 24330, "s": 24207, "text": "The hexbin() function in pyplot module of matplotlib library is used to make a 2D hexagonal binning plot of points x, y. " }, { "code": null, "e": 24616, "s": 24330, "text": "Syntax: matplotlib.pyplot.hexbin(x, y, C=None, gridsize=100, bins=None, xscale=’linear’, yscale=’linear’, extent=None, cmap=None, norm=None, vmin=None, vmax=None, alpha=None, linewidths=None, edgecolors=’face’, reduce_C_function=, mincnt=None, marginals=False, *, data=None, **kwargs) " }, { "code": null, "e": 24699, "s": 24616, "text": "Parameters: This method accept the following parameters that are described below: " }, { "code": null, "e": 24783, "s": 24699, "text": "x, y: These parameter are the sequence of data. x and y must be of the same length." }, { "code": null, "e": 24852, "s": 24783, "text": "C : This parameter are the values which are accumulated in the bins." }, { "code": null, "e": 24950, "s": 24852, "text": "gridsize : This parameter represents the number of hexagons in the x-direction or both direction." }, { "code": null, "e": 25027, "s": 24950, "text": "xscale : This parameter uses a linear or log10 scale on the horizontal axis." }, { "code": null, "e": 25102, "s": 25027, "text": "xycale : This parameter uses a linear or log10 scale on the vertical axis." }, { "code": null, "e": 25203, "s": 25102, "text": "mincnt : This parameter is used to display cells with more than mincnt number of points in the cell." }, { "code": null, "e": 25348, "s": 25203, "text": "marginals : This parameter is used to plot the marginal density as colormapped rectangles along the bottom of the x-axis and left of the y-axis." }, { "code": null, "e": 25399, "s": 25348, "text": "extent : This parameter is the limits of the bins." }, { "code": null, "e": 25437, "s": 25399, "text": "Returns: This returns the following: " }, { "code": null, "e": 25515, "s": 25437, "text": "polycollection : This returns the PolyCollection defining the hexagonal bins." }, { "code": null, "e": 25605, "s": 25515, "text": "Below examples illustrate the matplotlib.pyplot.hexbin() function in matplotlib.pyplot: " }, { "code": null, "e": 25617, "s": 25605, "text": "Example 1: " }, { "code": null, "e": 25625, "s": 25617, "text": "Python3" }, { "code": "# Implementation of matplotlib function import matplotlib.pyplot as plt import numpy as np np.random.seed(19680801) n = 100000x = np.random.standard_normal(n) y = 12 * np.random.standard_normal(n) plt.hexbin(x, y, gridsize = 50, cmap ='Greens') plt.title('matplotlib.pyplot.hexbin() Example') plt.show() ", "e": 25943, "s": 25625, "text": null }, { "code": null, "e": 25953, "s": 25943, "text": "Output: " }, { "code": null, "e": 25965, "s": 25953, "text": "Example 2: " }, { "code": null, "e": 25973, "s": 25965, "text": "Python3" }, { "code": "# Implementation of matplotlib function import matplotlib.pyplot as plt import numpy as np np.random.seed(19680801) n = 100000x = np.random.standard_normal(n) y = 2 * np.random.standard_normal(n) z =[1, 2, 3, 4] xmin = x.min() xmax = x.max() ymin = y.min() ymax = y.max() hb = plt.hexbin(x, y, gridsize = 50, bins = z, cmap ='BuGn') plt.xlim(xmin, xmax)plt.ylim(ymin, ymax) cb = plt.colorbar(hb) cb.set_label(z)plt.title('matplotlib.pyplot.hexbin()\\Example') plt.show()", "e": 26478, "s": 25973, "text": null }, { "code": null, "e": 26488, "s": 26478, "text": "Output: " }, { "code": null, "e": 26514, "s": 26490, "text": "Matplotlib Pyplot-class" }, { "code": null, "e": 26532, "s": 26514, "text": "Python-matplotlib" }, { "code": null, "e": 26539, "s": 26532, "text": "Python" }, { "code": null, "e": 26637, "s": 26539, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26646, "s": 26637, "text": "Comments" }, { "code": null, "e": 26659, "s": 26646, "text": "Old Comments" }, { "code": null, "e": 26680, "s": 26659, "text": "Python OOPs Concepts" }, { "code": null, "e": 26712, "s": 26680, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26735, "s": 26712, "text": "Bar Plot in Matplotlib" }, { "code": null, "e": 26757, "s": 26735, "text": "Defaultdict in Python" }, { "code": null, "e": 26784, "s": 26757, "text": "Python Classes and Objects" }, { "code": null, "e": 26800, "s": 26784, "text": "Deque in Python" }, { "code": null, "e": 26842, "s": 26800, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26898, "s": 26842, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26943, "s": 26898, "text": "Python - Ways to remove duplicates from list" } ]
Tryit Editor v3.7
Tryit: Events sent form the server
[]
C Program for Binary Search (Recursive and Iterative)?
The binary search algorithm is an algorithm that is based on compare and split mechanism. The binary Search algorithm is also known as half-interval search, logarithmic search, or binary chop. The binary search algorithm, search the position of the target value in a sorted array. It compares the target value with the middle element of the array. If the element is equal to the target element then the algorithm returns the index of the found element. And if they are not equal, the searching algorithm uses a half section of that array, Based on the comparison of the value, the algorithm uses either of the first-half ( when the value is less than the middle ) and the second half ( when the value is greater than the middle ). And does the same for the next array half. Input: A[] = {0,2,6,11,12,18,34,45,55,99} n=55 Output: 55 at Index = 8 For our array - We will compare 55, with the middle element of the array which is 18, which is less than 55 so we will use second-half of the array i.e. the array {24, 45, 55, 99}, again the middle is 55. Check the value of search element with it. And the value matched, then we will return the index of this value with is 8. If the search element would be smaller than the middle than we would have used the first-half and go on until the element is found at the middle of the array. To Implement the binary search we can write the code in two ways. these two ways defer in only the way we call the function that checks for the binary search element. they are: Using iterations− this means using a loop inside the function that checks for the equality of the middle element. Using iterations− this means using a loop inside the function that checks for the equality of the middle element. Using In this method, the function calls itself again and again with a different set of values. Using In this method, the function calls itself again and again with a different set of values. #include<stdio.h> int iterativeBsearch(int A[], int size, int element); int main() { int A[] = {0,12,6,12,12,18,34,45,55,99}; int n=55; printf("%d is found at Index %d \n",n,iterativeBsearch(A,10,n)); return 0; } int iterativeBsearch(int A[], int size, int element) { int start = 0; int end = size-1; while(start<=end) { int mid = (start+end)/2; if( A[mid] == element) { return mid; } else if( element < A[mid] ) { end = mid-1; } else { start = mid+1; } } return -1; } 55 is found at Index 8 #include<stdio.h> int RecursiveBsearch(int A[], int start, int end, int element) { if(start>end) return -1; int mid = (start+end)/2; if( A[mid] == element ) return mid; else if( element < A[mid] ) RecursiveBsearch(A, start, mid-1, element); else RecursiveBsearch(A, mid+1, end, element); } int main() { int A[] = {0,2,6,11,12,18,34,45,55,99}; int n=55; printf("%d is found at Index %d \n",n,RecursiveBsearch(A,0,9,n)); return 0; } 55 is found at Index 8
[ { "code": null, "e": 1836, "s": 1062, "text": "The binary search algorithm is an algorithm that is based on compare and split mechanism. The binary Search algorithm is also known as half-interval search, logarithmic search, or binary chop. The binary search algorithm, search the position of the target value in a sorted array. It compares the target value with the middle element of the array. If the element is equal to the target element then the algorithm returns the index of the found element. And if they are not equal, the searching algorithm uses a half section of that array, Based on the comparison of the value, the algorithm uses either of the first-half ( when the value is less than the middle ) and the second half ( when the value is greater than the middle ). And does the same for the next array half." }, { "code": null, "e": 1907, "s": 1836, "text": "Input:\nA[] = {0,2,6,11,12,18,34,45,55,99}\nn=55\nOutput:\n55 at Index = 8" }, { "code": null, "e": 1923, "s": 1907, "text": "For our array -" }, { "code": null, "e": 2233, "s": 1923, "text": "We will compare 55, with the middle element of the array which is 18, which is less than 55 so we will use second-half of the array i.e. the array {24, 45, 55, 99}, again the middle is 55. Check the value of search element with it. And the value matched, then we will return the index of this value with is 8." }, { "code": null, "e": 2392, "s": 2233, "text": "If the search element would be smaller than the middle than we would have used the first-half and go on until the element is found at the middle of the array." }, { "code": null, "e": 2569, "s": 2392, "text": "To Implement the binary search we can write the code in two ways. these two ways defer in only the way we call the function that checks for the binary search element. they are:" }, { "code": null, "e": 2683, "s": 2569, "text": "Using iterations− this means using a loop inside the function that checks for the equality of the middle element." }, { "code": null, "e": 2797, "s": 2683, "text": "Using iterations− this means using a loop inside the function that checks for the equality of the middle element." }, { "code": null, "e": 2893, "s": 2797, "text": "Using In this method, the function calls itself again and again with a different set of values." }, { "code": null, "e": 2989, "s": 2893, "text": "Using In this method, the function calls itself again and again with a different set of values." }, { "code": null, "e": 3542, "s": 2989, "text": "#include<stdio.h>\nint iterativeBsearch(int A[], int size, int element);\nint main() {\n int A[] = {0,12,6,12,12,18,34,45,55,99};\n int n=55;\n printf(\"%d is found at Index %d \\n\",n,iterativeBsearch(A,10,n));\n return 0;\n}\nint iterativeBsearch(int A[], int size, int element) {\n int start = 0;\n int end = size-1;\n while(start<=end) {\n int mid = (start+end)/2;\n if( A[mid] == element) {\n return mid;\n } else if( element < A[mid] ) {\n end = mid-1;\n } else {\n start = mid+1;\n }\n }\n return -1;\n}" }, { "code": null, "e": 3565, "s": 3542, "text": "55 is found at Index 8" }, { "code": null, "e": 4038, "s": 3565, "text": "#include<stdio.h>\nint RecursiveBsearch(int A[], int start, int end, int element) {\n if(start>end) return -1;\n int mid = (start+end)/2;\n if( A[mid] == element ) return mid;\n else if( element < A[mid] )\n RecursiveBsearch(A, start, mid-1, element);\n else\n RecursiveBsearch(A, mid+1, end, element);\n}\nint main() {\n int A[] = {0,2,6,11,12,18,34,45,55,99};\n int n=55;\n printf(\"%d is found at Index %d \\n\",n,RecursiveBsearch(A,0,9,n));\n return 0;\n}" }, { "code": null, "e": 4061, "s": 4038, "text": "55 is found at Index 8" } ]
Update all the fields in a table with null or non-null values with MySQL
Let us first create a table − mysql> create table DemoTable -> ( -> Id int, -> Name varchar(20) -> ); Query OK, 0 rows affected (0.58 sec) Insert some records in the table using insert command − mysql> insert into DemoTable values(10,NULL); Query OK, 1 row affected (0.32 sec) mysql> insert into DemoTable values(NULL,'David'); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable values(NULL,NULL); Query OK, 1 row affected (0.15 sec) Display all records from the table using select statement − mysql> select * from DemoTable; This will produce the following output− +------+-------+ | Id | Name | +------+-------+ | 10 | NULL | | NULL | David | | NULL | NULL | +------+-------+ 3 rows in set (0.00 sec) Here is the query to update all the fields in a table with null or non-null values − mysql> update DemoTable set Name='Robert' where Id IS NULL or Name IS NULL; Query OK, 3 rows affected (0.22 sec) Rows matched: 3 Changed: 3 Warnings: 0 Let us check the table records once again − mysql> select * from DemoTable; This will produce the following output − +------+--------+ | Id | Name | +------+--------+ | 10 | Robert | | NULL | Robert | | NULL | Robert | +------+--------+ 3 rows in set (0.00 sec)
[ { "code": null, "e": 1092, "s": 1062, "text": "Let us first create a table −" }, { "code": null, "e": 1213, "s": 1092, "text": "mysql> create table DemoTable\n -> (\n -> Id int,\n -> Name varchar(20)\n -> );\nQuery OK, 0 rows affected (0.58 sec)" }, { "code": null, "e": 1269, "s": 1213, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1522, "s": 1269, "text": "mysql> insert into DemoTable values(10,NULL);\nQuery OK, 1 row affected (0.32 sec)\nmysql> insert into DemoTable values(NULL,'David');\nQuery OK, 1 row affected (0.16 sec)\nmysql> insert into DemoTable values(NULL,NULL);\nQuery OK, 1 row affected (0.15 sec)" }, { "code": null, "e": 1582, "s": 1522, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1614, "s": 1582, "text": "mysql> select * from DemoTable;" }, { "code": null, "e": 1654, "s": 1614, "text": "This will produce the following output−" }, { "code": null, "e": 1798, "s": 1654, "text": "+------+-------+\n| Id | Name |\n+------+-------+\n| 10 | NULL |\n| NULL | David |\n| NULL | NULL |\n+------+-------+\n3 rows in set (0.00 sec)" }, { "code": null, "e": 1883, "s": 1798, "text": "Here is the query to update all the fields in a table with null or non-null values −" }, { "code": null, "e": 2035, "s": 1883, "text": "mysql> update DemoTable set Name='Robert' where Id IS NULL or Name IS NULL;\nQuery OK, 3 rows affected (0.22 sec)\nRows matched: 3 Changed: 3 Warnings: 0" }, { "code": null, "e": 2079, "s": 2035, "text": "Let us check the table records once again −" }, { "code": null, "e": 2111, "s": 2079, "text": "mysql> select * from DemoTable;" }, { "code": null, "e": 2152, "s": 2111, "text": "This will produce the following output −" }, { "code": null, "e": 2303, "s": 2152, "text": "+------+--------+\n| Id | Name |\n+------+--------+\n| 10 | Robert |\n| NULL | Robert |\n| NULL | Robert |\n+------+--------+\n3 rows in set (0.00 sec)" } ]
Node.js socket.bind() Method - GeeksforGeeks
02 Jul, 2021 The socket.bind() method is an inbuilt application programming interface of class Socket within dgram module which is used to bind the particular data gram server to a particular port with some required information. Syntax: const socket.bind(options[, callback]) Parameters: This method takes the following parameter: option: It can use the following parameters- port: port value.address: addressexclusive: Boolean value true or false.fd: Integer value. port: port value. address: address exclusive: Boolean value true or false. fd: Integer value. callback: Callback function for further operation. Return Value: This method returns the object which contains the address information for the socket. Example 1: Filename: index.js Javascript // Node.js program to demonstrate the// server.bind() method // Importing dgram modulevar dgram = require('dgram'); // Creating and initializing client// and server socketvar client = dgram.createSocket("udp4");var server = dgram.createSocket("udp4"); // Catching the message eventserver.on("message", function (msg) { // Displaying the client message process.stdout.write("UDP String: " + msg + "\n"); // Exiting process process.exit();}) // Binding server with port .bind(1234, () => { // Getting the address information // for the server by using // address() method const address = server.address() // Display the result console.log(address); }); // Client sending message to serverclient.send("Hello", 0, 7, 1234, "localhost"); Output: { address: '0.0.0.0', family: 'IPv4', port: 1234 } UDP String: Hello Example 2: Filename: index.js Javascript // Node.js program to demonstrate the// server.bind() method // Importing dgram modulevar dgram = require('dgram'); // Creating and initializing client// and server socketvar client = dgram.createSocket("udp4");var server = dgram.createSocket("udp4"); // Catching the message eventserver.on("message", function (msg) { // Displaying the client message process.stdout.write("UDP String: " + msg + "\n"); // Exiting process process.exit(); }); // Catching the listening eventserver.on('listening', () => { // Getting address information for the server const address = server.address(); // Display the result console.log(`server listening ${address.address}:${address.port}`);}); // Binding server with port address// by using bind() methodserver.bind(1234, () => { // Adding a multicast address for others to join server.addMembership('224.0.0.114');}); // Client sending message to serverclient.send("Hello", 0, 7, 1234, "localhost"); Output: server listening 0.0.0.0:1234 UDP String: Hello Run the index.js file using the following command: node index.js Reference:https://nodejs.org/dist/latest-v12.x/docs/api/dgram.html#dgram_socket_bind_options_callback sagartomar9927 Node.js-Methods Node.js Web Technologies 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 ? Node.js fs.readFileSync() Method Node.js fs.writeFile() Method How to update NPM ? Difference between promise and async await in Node.js Remove elements from a JavaScript Array Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 38611, "s": 38583, "text": "\n02 Jul, 2021" }, { "code": null, "e": 38827, "s": 38611, "text": "The socket.bind() method is an inbuilt application programming interface of class Socket within dgram module which is used to bind the particular data gram server to a particular port with some required information." }, { "code": null, "e": 38835, "s": 38827, "text": "Syntax:" }, { "code": null, "e": 38874, "s": 38835, "text": "const socket.bind(options[, callback])" }, { "code": null, "e": 38929, "s": 38874, "text": "Parameters: This method takes the following parameter:" }, { "code": null, "e": 39065, "s": 38929, "text": "option: It can use the following parameters- port: port value.address: addressexclusive: Boolean value true or false.fd: Integer value." }, { "code": null, "e": 39083, "s": 39065, "text": "port: port value." }, { "code": null, "e": 39100, "s": 39083, "text": "address: address" }, { "code": null, "e": 39140, "s": 39100, "text": "exclusive: Boolean value true or false." }, { "code": null, "e": 39159, "s": 39140, "text": "fd: Integer value." }, { "code": null, "e": 39210, "s": 39159, "text": "callback: Callback function for further operation." }, { "code": null, "e": 39310, "s": 39210, "text": "Return Value: This method returns the object which contains the address information for the socket." }, { "code": null, "e": 39340, "s": 39310, "text": "Example 1: Filename: index.js" }, { "code": null, "e": 39351, "s": 39340, "text": "Javascript" }, { "code": "// Node.js program to demonstrate the// server.bind() method // Importing dgram modulevar dgram = require('dgram'); // Creating and initializing client// and server socketvar client = dgram.createSocket(\"udp4\");var server = dgram.createSocket(\"udp4\"); // Catching the message eventserver.on(\"message\", function (msg) { // Displaying the client message process.stdout.write(\"UDP String: \" + msg + \"\\n\"); // Exiting process process.exit();}) // Binding server with port .bind(1234, () => { // Getting the address information // for the server by using // address() method const address = server.address() // Display the result console.log(address); }); // Client sending message to serverclient.send(\"Hello\", 0, 7, 1234, \"localhost\");", "e": 40152, "s": 39351, "text": null }, { "code": null, "e": 40160, "s": 40152, "text": "Output:" }, { "code": null, "e": 40229, "s": 40160, "text": "{ address: '0.0.0.0', family: 'IPv4', port: 1234 }\nUDP String: Hello" }, { "code": null, "e": 40259, "s": 40229, "text": "Example 2: Filename: index.js" }, { "code": null, "e": 40270, "s": 40259, "text": "Javascript" }, { "code": "// Node.js program to demonstrate the// server.bind() method // Importing dgram modulevar dgram = require('dgram'); // Creating and initializing client// and server socketvar client = dgram.createSocket(\"udp4\");var server = dgram.createSocket(\"udp4\"); // Catching the message eventserver.on(\"message\", function (msg) { // Displaying the client message process.stdout.write(\"UDP String: \" + msg + \"\\n\"); // Exiting process process.exit(); }); // Catching the listening eventserver.on('listening', () => { // Getting address information for the server const address = server.address(); // Display the result console.log(`server listening ${address.address}:${address.port}`);}); // Binding server with port address// by using bind() methodserver.bind(1234, () => { // Adding a multicast address for others to join server.addMembership('224.0.0.114');}); // Client sending message to serverclient.send(\"Hello\", 0, 7, 1234, \"localhost\");", "e": 41246, "s": 40270, "text": null }, { "code": null, "e": 41254, "s": 41246, "text": "Output:" }, { "code": null, "e": 41302, "s": 41254, "text": "server listening 0.0.0.0:1234\nUDP String: Hello" }, { "code": null, "e": 41353, "s": 41302, "text": "Run the index.js file using the following command:" }, { "code": null, "e": 41367, "s": 41353, "text": "node index.js" }, { "code": null, "e": 41469, "s": 41367, "text": "Reference:https://nodejs.org/dist/latest-v12.x/docs/api/dgram.html#dgram_socket_bind_options_callback" }, { "code": null, "e": 41484, "s": 41469, "text": "sagartomar9927" }, { "code": null, "e": 41500, "s": 41484, "text": "Node.js-Methods" }, { "code": null, "e": 41508, "s": 41500, "text": "Node.js" }, { "code": null, "e": 41525, "s": 41508, "text": "Web Technologies" }, { "code": null, "e": 41623, "s": 41525, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 41671, "s": 41623, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 41704, "s": 41671, "text": "Node.js fs.readFileSync() Method" }, { "code": null, "e": 41734, "s": 41704, "text": "Node.js fs.writeFile() Method" }, { "code": null, "e": 41754, "s": 41734, "text": "How to update NPM ?" }, { "code": null, "e": 41808, "s": 41754, "text": "Difference between promise and async await in Node.js" }, { "code": null, "e": 41848, "s": 41808, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 41893, "s": 41848, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 41936, "s": 41893, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 41986, "s": 41936, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
join Command in Linux - GeeksforGeeks
22 May, 2019 The join command in UNIX is a command line utility for joining lines of two files on a common field. Suppose you have two files and there is a need to combine these two files in a way that the output makes even more sense.For example, there could be a file containing names and the other containing ID’s and the requirement is to combine both files in such a way that the names and corresponding ID’s appear in the same line. join command is the tool for it. join command is used to join the two files based on a key field present in both the files. The input file can be separated by white space or any delimiter.Syntax: $join [OPTION] FILE1 FILE2 // displaying the contents of first file // $cat file1.txt 1 AAYUSH 2 APAAR 3 HEMANT 4 KARTIK // displaying contents of second file // $cat file2.txt 1 101 2 102 3 103 4 104 Now, in order to combine two files the files must have some common field. In this case, we have the numbering 1, 2... as the common field in both the files. NOTE : When using join command, both the input files should be sorted on the KEY on which we are going to join the files. //..using join command...// $join file1.txt file2.txt 1 AAYUSH 101 2 APAAR 102 3 HEMANT 103 4 KARTIK 104 // by default join command takes the first column as the key to join as in the above case // So, the output contains the key followed by all the matching columns from the first file file1.txt, followed by all the columns of second file file2.txt. Now, if we wanted to create a new file with the joined contents, we could use the following command: $join file1.txt file2.txt > newjoinfile.txt //..this will direct the output of joined files into a new file newjoinfile.txt containing the same output as the example above..// 1. -a FILENUM : Also, print unpairable lines from file FILENUM, where FILENUM is 1 or 2, corresponding to FILE1 or FILE2.2. -e EMPTY : Replace missing input fields with EMPTY.3. -i - -ignore-case : Ignore differences in case when comparing fields.4. -j FIELD : Equivalent to "-1 FIELD -2 FIELD".5. -o FORMAT : Obey FORMAT while constructing output line.6. -t CHAR : Use CHAR as input and output field separator.7. -v FILENUM : Like -a FILENUM, but suppress joined output lines.8. -1 FIELD : Join on this FIELD of file 1.9. -2 FIELD : Join on this FIELD of file 2.10. - -check-order : Check that the input is correctly sorted, even if all input lines are pairable.11. - -nocheck-order : Do not check that the input is correctly sorted.12. - -help : Display a help message and exit.13. - -version : Display version information and exit. Using join with options1. using -a FILENUM option : Now, sometimes it is possible that one of the files contain extra fields so what join command does in that case is that by default, it only prints pairable lines. For example, even if file file1.txt contains an extra field provided that the contents of file2.txt are same then the output produced by join command would be same: //displaying the contents of file1.txt// $cat file1.txt 1 AAYUSH 2 APAAR 3 HEMANT 4 KARTIK 5 DEEPAK //displaying contents of file2.txt// $cat file2.txt 1 101 2 102 3 103 4 104 //using join command// $join file1.txt file2.txt 1 AAYUSH 101 2 APAAR 102 3 HEMANT 103 4 KARTIK 104 // although file1.txt has extra field the output is not affected cause the 5 column in file1.txt was unpairable with any in file2.txt// What if such unpairable lines are important and must be visible after joining the files. In such cases we can use -a option with join command which will help in displaying such unpairable lines. This option requires the user to pass a file number so that the tool knows which file you are talking about. //using join with -a option// //1 is used with -a to display the contents of first file passed// $join file1.txt file2.txt -a 1 1 AAYUSH 101 2 APAAR 102 3 HEMANT 103 4 KARTIK 104 5 DEEPAK //5 column of first file is also displayed with help of -a option although it is unpairable// 2. using -v option : Now, in case you only want to print unpairable lines i.e suppress the paired lines in output then -v option is used with join command.This option works exactly the way -a works(in terms of 1 used with -v in example below). //using -v option with join// $join file1.txt file2.txt -v 1 5 DEEPAK //the output only prints unpairable lines found in first file passed// 3. using -1, -2 and -j option : As we already know that join combines lines of files on a common field, which is first field by default.However, it is not necessary that the common key in the both files always be the first column.join command provides options if the common key is other than the first column.Now, if you want the second field of either file or both the files to be the common field for join, you can do this by using the -1 and -2 command line options. The -1 and -2 here represents he first and second file and these options requires a numeric argument that refers to the joining field for the corresponding file. This will be easily understandable with the example below: //displaying contents of first file// $cat file1.txt AAYUSH 1 APAAR 2 HEMANT 3 KARTIK 4 //displaying contents of second file// $cat file2.txt 101 1 102 2 103 3 104 4 //now using join command // $join -1 2 -2 2 file1.txt file2.txt 1 AAYUSH 101 2 APAAR 102 3 HEMANT 103 4 KARTIK 104 //here -1 2 refers to the use of 2 column of first file as the common field and -2 2 refers to the use of 2 column of second file as the common field for joining// So, this is how we can use different columns other than the first as the common field for joining.In case, we have the position of common field same in both the files(other than first) then we can simply replace the part -1[field] -2[field] in the command with -j[field]. So, in the above case the command could be: //using -j option with join// $join -j2 file1.txt file2.txt 1 AAYUSH 101 2 APAAR 102 3 HEMANT 103 4 KARTIK 104 //displaying contents of file1.txt// $cat file1.txt A AAYUSH B APAAR C HEMANT D KARTIK //displaying contents of file2.txt// $cat file2.txt a 101 b 102 c 103 d 104 Now, if you try joining these two files, using the default (first) common field, nothing will happen. That's because the case of field elements in both files is different. To make join ignore this case issue, use the -i command line option. //using -i option with join// $join -i file1.txt file2.txt A AAYUSH 101 B APAAR 102 C HEMANT 103 D KARTIK 104 5. using - -nocheck-order option : By default, the join command checks whether or not the supplied input is sorted, and reports if not. In order to remove this error/warning then we have to use - -nocheck-order command like: //syntax of join with --nocheck-order option// $join --nocheck-order file1 file2 6. using -t option : Most of the times, files contain some delimiter to separate the columns. Let us update the files with comma delimiter. $cat file1.txt 1, AAYUSH 2, APAAR 3, HEMANT 4, KARTIK 5, DEEPAK //displaying contents of file2.txt// $cat file2.txt 1, 101 2, 102 3, 103 4, 104 Now, -t option is the one we use to specify the delimiterin such cases.Since comma is the delimiter we will specify it along with -t. //using join with -t option// $join -t, file1.txt file2.txt 1, AAYUSH, 101 2, APAAR, 102 3, HEMANT, 103 4, KARTIK, 104 linux-command Linux-text-processing-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 SED command in Linux | Set 2 Docker - COPY Instruction mv command in Linux with examples chown command in Linux with Examples nohup Command in Linux with Examples Named Pipe or FIFO with example C program Thread functions in C/C++ uniq Command in LINUX with examples Basic Operators in Shell Scripting
[ { "code": null, "e": 25787, "s": 25759, "text": "\n22 May, 2019" }, { "code": null, "e": 25888, "s": 25787, "text": "The join command in UNIX is a command line utility for joining lines of two files on a common field." }, { "code": null, "e": 26409, "s": 25888, "text": "Suppose you have two files and there is a need to combine these two files in a way that the output makes even more sense.For example, there could be a file containing names and the other containing ID’s and the requirement is to combine both files in such a way that the names and corresponding ID’s appear in the same line. join command is the tool for it. join command is used to join the two files based on a key field present in both the files. The input file can be separated by white space or any delimiter.Syntax:" }, { "code": null, "e": 26437, "s": 26409, "text": "$join [OPTION] FILE1 FILE2\n" }, { "code": null, "e": 26613, "s": 26437, "text": "// displaying the contents of first file //\n$cat file1.txt\n1 AAYUSH\n2 APAAR\n3 HEMANT\n4 KARTIK\n\n// displaying contents of second file //\n$cat file2.txt\n1 101\n2 102\n3 103\n4 104\n" }, { "code": null, "e": 26770, "s": 26613, "text": "Now, in order to combine two files the files must have some common field. In this case, we have the numbering 1, 2... as the common field in both the files." }, { "code": null, "e": 26892, "s": 26770, "text": "NOTE : When using join command, both the input files should be sorted on the KEY on which we are going to join the files." }, { "code": null, "e": 27094, "s": 26892, "text": "//..using join command...//\n$join file1.txt file2.txt\n1 AAYUSH 101\n2 APAAR 102\n3 HEMANT 103\n4 KARTIK 104\n\n// by default join command takes the \nfirst column as the key to join as \nin the above case //\n" }, { "code": null, "e": 27248, "s": 27094, "text": "So, the output contains the key followed by all the matching columns from the first file file1.txt, followed by all the columns of second file file2.txt." }, { "code": null, "e": 27349, "s": 27248, "text": "Now, if we wanted to create a new file with the joined contents, we could use the following command:" }, { "code": null, "e": 27529, "s": 27349, "text": "$join file1.txt file2.txt > newjoinfile.txt\n\n//..this will direct the output of joined files\ninto a new file newjoinfile.txt \ncontaining the same output as the example \nabove..//\n" }, { "code": null, "e": 28364, "s": 27529, "text": "1. -a FILENUM : Also, print unpairable lines from file FILENUM, where FILENUM is 1 or 2, corresponding to FILE1 or FILE2.2. -e EMPTY : Replace missing input fields with EMPTY.3. -i - -ignore-case : Ignore differences in case when comparing fields.4. -j FIELD : Equivalent to \"-1 FIELD -2 FIELD\".5. -o FORMAT : Obey FORMAT while constructing output line.6. -t CHAR : Use CHAR as input and output field separator.7. -v FILENUM : Like -a FILENUM, but suppress joined output lines.8. -1 FIELD : Join on this FIELD of file 1.9. -2 FIELD : Join on this FIELD of file 2.10. - -check-order : Check that the input is correctly sorted, even if all input lines are pairable.11. - -nocheck-order : Do not check that the input is correctly sorted.12. - -help : Display a help message and exit.13. - -version : Display version information and exit." }, { "code": null, "e": 28744, "s": 28364, "text": "Using join with options1. using -a FILENUM option : Now, sometimes it is possible that one of the files contain extra fields so what join command does in that case is that by default, it only prints pairable lines. For example, even if file file1.txt contains an extra field provided that the contents of file2.txt are same then the output produced by join command would be same:" }, { "code": null, "e": 29162, "s": 28744, "text": "//displaying the contents of file1.txt//\n$cat file1.txt\n1 AAYUSH\n2 APAAR\n3 HEMANT\n4 KARTIK\n5 DEEPAK\n\n//displaying contents of file2.txt//\n$cat file2.txt\n1 101\n2 102\n3 103\n4 104\n\n//using join command//\n$join file1.txt file2.txt\n1 AAYUSH 101\n2 APAAR 102\n3 HEMANT 103\n4 KARTIK 104\n\n// although file1.txt has extra field the \noutput is not affected cause the 5 column in \nfile1.txt was unpairable with any in file2.txt//\n" }, { "code": null, "e": 29466, "s": 29162, "text": "What if such unpairable lines are important and must be visible after joining the files. In such cases we can use -a option with join command which will help in displaying such unpairable lines. This option requires the user to pass a file number so that the tool knows which file you are talking about." }, { "code": null, "e": 29753, "s": 29466, "text": "//using join with -a option//\n\n//1 is used with -a to display the contents of\nfirst file passed//\n\n$join file1.txt file2.txt -a 1\n1 AAYUSH 101\n2 APAAR 102\n3 HEMANT 103\n4 KARTIK 104\n5 DEEPAK\n\n//5 column of first file is \nalso displayed with help of -a option\nalthough it is unpairable//\n" }, { "code": null, "e": 29997, "s": 29753, "text": "2. using -v option : Now, in case you only want to print unpairable lines i.e suppress the paired lines in output then -v option is used with join command.This option works exactly the way -a works(in terms of 1 used with -v in example below)." }, { "code": null, "e": 30142, "s": 29997, "text": "//using -v option with join//\n\n$join file1.txt file2.txt -v 1\n5 DEEPAK \n\n//the output only prints unpairable lines found\nin first file passed//\n" }, { "code": null, "e": 30833, "s": 30142, "text": "3. using -1, -2 and -j option : As we already know that join combines lines of files on a common field, which is first field by default.However, it is not necessary that the common key in the both files always be the first column.join command provides options if the common key is other than the first column.Now, if you want the second field of either file or both the files to be the common field for join, you can do this by using the -1 and -2 command line options. The -1 and -2 here represents he first and second file and these options requires a numeric argument that refers to the joining field for the corresponding file. This will be easily understandable with the example below:" }, { "code": null, "e": 31287, "s": 30833, "text": "//displaying contents of first file//\n$cat file1.txt\nAAYUSH 1\nAPAAR 2\nHEMANT 3\nKARTIK 4\n\n//displaying contents of second file//\n$cat file2.txt\n 101 1\n 102 2\n 103 3\n 104 4\n\n//now using join command //\n\n$join -1 2 -2 2 file1.txt file2.txt\n1 AAYUSH 101\n2 APAAR 102\n3 HEMANT 103\n4 KARTIK 104\n\n//here -1 2 refers to the use of 2 column of\nfirst file as the common field and -2 2\nrefers to the use of 2 column of second\nfile as the common field for joining//\n" }, { "code": null, "e": 31603, "s": 31287, "text": "So, this is how we can use different columns other than the first as the common field for joining.In case, we have the position of common field same in both the files(other than first) then we can simply replace the part -1[field] -2[field] in the command with -j[field]. So, in the above case the command could be:" }, { "code": null, "e": 31716, "s": 31603, "text": "//using -j option with join//\n\n$join -j2 file1.txt file2.txt\n1 AAYUSH 101\n2 APAAR 102\n3 HEMANT 103\n4 KARTIK 104\n" }, { "code": null, "e": 31881, "s": 31716, "text": "//displaying contents of file1.txt//\n$cat file1.txt\nA AAYUSH\nB APAAR\nC HEMANT\nD KARTIK\n\n//displaying contents of file2.txt//\n$cat file2.txt\na 101\nb 102\nc 103\nd 104\n" }, { "code": null, "e": 32122, "s": 31881, "text": "Now, if you try joining these two files, using the default (first) common field, nothing will happen. That's because the case of field elements in both files is different. To make join ignore this case issue, use the -i command line option." }, { "code": null, "e": 32233, "s": 32122, "text": "//using -i option with join//\n$join -i file1.txt file2.txt\nA AAYUSH 101\nB APAAR 102\nC HEMANT 103\nD KARTIK 104\n" }, { "code": null, "e": 32458, "s": 32233, "text": "5. using - -nocheck-order option : By default, the join command checks whether or not the supplied input is sorted, and reports if not. In order to remove this error/warning then we have to use - -nocheck-order command like:" }, { "code": null, "e": 32541, "s": 32458, "text": "//syntax of join with --nocheck-order option//\n\n$join --nocheck-order file1 file2\n" }, { "code": null, "e": 32681, "s": 32541, "text": "6. using -t option : Most of the times, files contain some delimiter to separate the columns. Let us update the files with comma delimiter." }, { "code": null, "e": 32826, "s": 32681, "text": "$cat file1.txt\n1, AAYUSH\n2, APAAR\n3, HEMANT\n4, KARTIK\n5, DEEPAK\n\n//displaying contents of file2.txt//\n$cat file2.txt\n1, 101\n2, 102\n3, 103\n4, 104" }, { "code": null, "e": 32960, "s": 32826, "text": "Now, -t option is the one we use to specify the delimiterin such cases.Since comma is the delimiter we will specify it along with -t." }, { "code": null, "e": 33081, "s": 32960, "text": "//using join with -t option//\n\n$join -t, file1.txt file2.txt\n1, AAYUSH, 101\n2, APAAR, 102\n3, HEMANT, 103\n4, KARTIK, 104\n" }, { "code": null, "e": 33095, "s": 33081, "text": "linux-command" }, { "code": null, "e": 33126, "s": 33095, "text": "Linux-text-processing-commands" }, { "code": null, "e": 33137, "s": 33126, "text": "Linux-Unix" }, { "code": null, "e": 33235, "s": 33137, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33270, "s": 33235, "text": "scp command in Linux with Examples" }, { "code": null, "e": 33299, "s": 33270, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 33325, "s": 33299, "text": "Docker - COPY Instruction" }, { "code": null, "e": 33359, "s": 33325, "text": "mv command in Linux with examples" }, { "code": null, "e": 33396, "s": 33359, "text": "chown command in Linux with Examples" }, { "code": null, "e": 33433, "s": 33396, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 33475, "s": 33433, "text": "Named Pipe or FIFO with example C program" }, { "code": null, "e": 33501, "s": 33475, "text": "Thread functions in C/C++" }, { "code": null, "e": 33537, "s": 33501, "text": "uniq Command in LINUX with examples" } ]
Count the number of currency notes needed - GeeksforGeeks
04 May, 2021 You have an unlimited amount of banknotes worth A and B dollars (A not equals to B). You want to pay a total of S dollars using exactly N notes. The task is to find the number of notes worth A dollars you need. If there is no solution return -1. Examples: Input: A = 1, B = 2, S = 7, N = 5 Output: 3 3 * A + 2 * B = S 3 * 1 + 2 * 2 = 7 Input: A = 2, B = 1, S = 7, N = 5 Output: 2 Input: A = 2, B = 1, S = 4, N = 5 Output: -1 Input: A = 2, B = 3, S = 20, N = 8 Output: 4 Approach: Let x be the number of notes of value A required then the rest of the notes i.e. N – x must of value B. Since, their sum is required be S then the following equation must be satisfied: S = (A * x) + (B * (N – x)) Solving the equation further, S = (A * x) + (B * N) – (B * x) S – (B * N) = (A – B) * x x = (S – (B * N)) / (A – B) After solving for x, it is the number of notes of value A required only if the value of x is an integer else the result is not possible. Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ implementation of the approach#include<bits/stdc++.h>using namespace std; // Function to return the amount of notes// with value A requiredint bankNotes(int A, int B, int S, int N){ int numerator = S - (B * N); int denominator = A - B; // If possible if (numerator % denominator == 0) return (numerator / denominator); return -1;} // Driver codeint main(){ int A = 1, B = 2, S = 7, N = 5; cout << bankNotes(A, B, S, N) << endl;} // This code is contributed by mits // Java implementation of the approachclass GFG { // Function to return the amount of notes // with value A required static int bankNotes(int A, int B, int S, int N) { int numerator = S - (B * N); int denominator = A - B; // If possible if (numerator % denominator == 0) return (numerator / denominator); return -1; } // Driver code public static void main(String[] args) { int A = 1, B = 2, S = 7, N = 5; System.out.print(bankNotes(A, B, S, N)); }} # Python3 implementation of the approach # Function to return the amount of notes# with value A requireddef bankNotes(A, B, S, N): numerator = S - (B * N) denominator = A - B # If possible if (numerator % denominator == 0): return (numerator // denominator) return -1 # Driver codeA, B, S, N = 1, 2, 7, 5print(bankNotes(A, B, S, N)) # This code is contributed# by mohit kumar // C# implementation of the approachusing System; class GFG{ // Function to return the amount of notes // with value A required static int bankNotes(int A, int B, int S, int N) { int numerator = S - (B * N); int denominator = A - B; // If possible if (numerator % denominator == 0) return (numerator / denominator); return -1; } // Driver code public static void Main() { int A = 1, B = 2, S = 7, N = 5; Console.Write(bankNotes(A, B, S, N)); }} // This code is contributed by Akanksha Rai <?php// PHP implementation of the approach // Function to return the amount of notes// with value A requiredfunction bankNotes($A, $B, $S, $N){ $numerator = $S - ($B * $N); $denominator = $A - $B; // If possible if ($numerator % $denominator == 0) return ($numerator / $denominator); return -1;} // Driver code$A = 1; $B= 2; $S = 7; $N = 5;echo(bankNotes($A, $B, $S, $N)); // This code is contributed by Code_Mech?> <script> // Javascript implementation of the approach // Function to return the amount of notes// with value A requiredfunction bankNotes(A, B, S, N){ let numerator = S - (B * N); let denominator = A - B; // If possible if (numerator % denominator == 0) return (Math.floor(numerator / denominator)); return -1;} // Driver Codelet A = 1, B = 2, S = 7, N = 5; document.write(bankNotes(A, B, S, N) + "</br>"); // This code is contributed by jana_sayantan </script> 3 mohit kumar 29 Akanksha_Rai Code_Mech Mithun Kumar jana_sayantan expression-evaluation Greedy Mathematical School Programming Greedy Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Optimal Page Replacement Algorithm Program for Best Fit algorithm in Memory Management Program for First Fit algorithm in Memory Management Bin Packing Problem (Minimize number of used Bins) Program for Worst Fit algorithm in Memory Management Program for Fibonacci numbers C++ Data Types Set in C++ Standard Template Library (STL) Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples
[ { "code": null, "e": 26537, "s": 26509, "text": "\n04 May, 2021" }, { "code": null, "e": 26783, "s": 26537, "text": "You have an unlimited amount of banknotes worth A and B dollars (A not equals to B). You want to pay a total of S dollars using exactly N notes. The task is to find the number of notes worth A dollars you need. If there is no solution return -1." }, { "code": null, "e": 26794, "s": 26783, "text": "Examples: " }, { "code": null, "e": 26874, "s": 26794, "text": "Input: A = 1, B = 2, S = 7, N = 5 Output: 3 3 * A + 2 * B = S 3 * 1 + 2 * 2 = 7" }, { "code": null, "e": 26918, "s": 26874, "text": "Input: A = 2, B = 1, S = 7, N = 5 Output: 2" }, { "code": null, "e": 26963, "s": 26918, "text": "Input: A = 2, B = 1, S = 4, N = 5 Output: -1" }, { "code": null, "e": 27009, "s": 26963, "text": "Input: A = 2, B = 3, S = 20, N = 8 Output: 4 " }, { "code": null, "e": 27206, "s": 27009, "text": "Approach: Let x be the number of notes of value A required then the rest of the notes i.e. N – x must of value B. Since, their sum is required be S then the following equation must be satisfied: " }, { "code": null, "e": 27489, "s": 27206, "text": "S = (A * x) + (B * (N – x)) Solving the equation further, S = (A * x) + (B * N) – (B * x) S – (B * N) = (A – B) * x x = (S – (B * N)) / (A – B) After solving for x, it is the number of notes of value A required only if the value of x is an integer else the result is not possible. " }, { "code": null, "e": 27541, "s": 27489, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 27545, "s": 27541, "text": "C++" }, { "code": null, "e": 27550, "s": 27545, "text": "Java" }, { "code": null, "e": 27558, "s": 27550, "text": "Python3" }, { "code": null, "e": 27561, "s": 27558, "text": "C#" }, { "code": null, "e": 27565, "s": 27561, "text": "PHP" }, { "code": null, "e": 27576, "s": 27565, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include<bits/stdc++.h>using namespace std; // Function to return the amount of notes// with value A requiredint bankNotes(int A, int B, int S, int N){ int numerator = S - (B * N); int denominator = A - B; // If possible if (numerator % denominator == 0) return (numerator / denominator); return -1;} // Driver codeint main(){ int A = 1, B = 2, S = 7, N = 5; cout << bankNotes(A, B, S, N) << endl;} // This code is contributed by mits", "e": 28081, "s": 27576, "text": null }, { "code": "// Java implementation of the approachclass GFG { // Function to return the amount of notes // with value A required static int bankNotes(int A, int B, int S, int N) { int numerator = S - (B * N); int denominator = A - B; // If possible if (numerator % denominator == 0) return (numerator / denominator); return -1; } // Driver code public static void main(String[] args) { int A = 1, B = 2, S = 7, N = 5; System.out.print(bankNotes(A, B, S, N)); }}", "e": 28621, "s": 28081, "text": null }, { "code": "# Python3 implementation of the approach # Function to return the amount of notes# with value A requireddef bankNotes(A, B, S, N): numerator = S - (B * N) denominator = A - B # If possible if (numerator % denominator == 0): return (numerator // denominator) return -1 # Driver codeA, B, S, N = 1, 2, 7, 5print(bankNotes(A, B, S, N)) # This code is contributed# by mohit kumar", "e": 29021, "s": 28621, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ // Function to return the amount of notes // with value A required static int bankNotes(int A, int B, int S, int N) { int numerator = S - (B * N); int denominator = A - B; // If possible if (numerator % denominator == 0) return (numerator / denominator); return -1; } // Driver code public static void Main() { int A = 1, B = 2, S = 7, N = 5; Console.Write(bankNotes(A, B, S, N)); }} // This code is contributed by Akanksha Rai", "e": 29624, "s": 29021, "text": null }, { "code": "<?php// PHP implementation of the approach // Function to return the amount of notes// with value A requiredfunction bankNotes($A, $B, $S, $N){ $numerator = $S - ($B * $N); $denominator = $A - $B; // If possible if ($numerator % $denominator == 0) return ($numerator / $denominator); return -1;} // Driver code$A = 1; $B= 2; $S = 7; $N = 5;echo(bankNotes($A, $B, $S, $N)); // This code is contributed by Code_Mech?>", "e": 30063, "s": 29624, "text": null }, { "code": "<script> // Javascript implementation of the approach // Function to return the amount of notes// with value A requiredfunction bankNotes(A, B, S, N){ let numerator = S - (B * N); let denominator = A - B; // If possible if (numerator % denominator == 0) return (Math.floor(numerator / denominator)); return -1;} // Driver Codelet A = 1, B = 2, S = 7, N = 5; document.write(bankNotes(A, B, S, N) + \"</br>\"); // This code is contributed by jana_sayantan </script>", "e": 30574, "s": 30063, "text": null }, { "code": null, "e": 30576, "s": 30574, "text": "3" }, { "code": null, "e": 30593, "s": 30578, "text": "mohit kumar 29" }, { "code": null, "e": 30606, "s": 30593, "text": "Akanksha_Rai" }, { "code": null, "e": 30616, "s": 30606, "text": "Code_Mech" }, { "code": null, "e": 30629, "s": 30616, "text": "Mithun Kumar" }, { "code": null, "e": 30643, "s": 30629, "text": "jana_sayantan" }, { "code": null, "e": 30665, "s": 30643, "text": "expression-evaluation" }, { "code": null, "e": 30672, "s": 30665, "text": "Greedy" }, { "code": null, "e": 30685, "s": 30672, "text": "Mathematical" }, { "code": null, "e": 30704, "s": 30685, "text": "School Programming" }, { "code": null, "e": 30711, "s": 30704, "text": "Greedy" }, { "code": null, "e": 30724, "s": 30711, "text": "Mathematical" }, { "code": null, "e": 30822, "s": 30724, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30857, "s": 30822, "text": "Optimal Page Replacement Algorithm" }, { "code": null, "e": 30909, "s": 30857, "text": "Program for Best Fit algorithm in Memory Management" }, { "code": null, "e": 30962, "s": 30909, "text": "Program for First Fit algorithm in Memory Management" }, { "code": null, "e": 31013, "s": 30962, "text": "Bin Packing Problem (Minimize number of used Bins)" }, { "code": null, "e": 31066, "s": 31013, "text": "Program for Worst Fit algorithm in Memory Management" }, { "code": null, "e": 31096, "s": 31066, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 31111, "s": 31096, "text": "C++ Data Types" }, { "code": null, "e": 31154, "s": 31111, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 31178, "s": 31154, "text": "Merge two sorted arrays" } ]
SAS - Date & Times
IN SAS dates are a special case of numeric values. Each day is assigned a specific numeric value starting from 1st January 1960. This date is assigned the date value 0 and the next date has a date value of 1 and so on. The previous days to this date are represented by -1 , -2 and so on. With this approach SAS can represent any date in future and any date in past. When SAS reads the data from a source it converts the data read into a specific date format as specified the date format. The variable to store the date value is declared with the proper informat required. The output date is shown by using the output data formats. The source data can be read properly by using specific date informats as shown below. The digit at the end of the informat indicates the minimum width of the date string to be read completely using the informat. A smaller width will give incorrect result. with SAS V9, there is a generic date format anydtdte15. which can process any date input. The below code shows the reading of different date formats. Please note the all the output values are just numbers as we have not applied any format statement to the output values. DATA TEMP; INPUT @1 Date1 date11. @12 Date2 anydtdte15. @23 Date3 mmddyy10. ; DATALINES; 02-mar-2012 3/02/2012 3/02/2012 ; PROC PRINT DATA = TEMP; RUN; When the above code is executed, we get the following output. The dates after being read , can be converted to another format as required by the display. This is achieved using the format statement for the date types. They take the same formats as informats. In the below exampel the date is read in one format but displayed in another format. DATA TEMP; INPUT @1 DOJ1 mmddyy10. @12 DOJ2 mmddyy10.; format DOJ1 date11. DOJ2 worddate20. ; DATALINES; 01/12/2012 02/11/1998 ; PROC PRINT DATA = TEMP; RUN; When the above code is executed, we get the following output. 50 Lectures 5.5 hours Code And Create 124 Lectures 30 hours Juan Galvan 162 Lectures 31.5 hours Yossef Ayman Zedan 35 Lectures 2.5 hours Ermin Dedic 167 Lectures 45.5 hours Muslim Helalee Print Add Notes Bookmark this page
[ { "code": null, "e": 2949, "s": 2583, "text": "IN SAS dates are a special case of numeric values. Each day is assigned a specific numeric value starting from 1st January 1960. This date is assigned the date value 0 and the next date has a date value of 1 and so on. The previous days to this date are represented by -1 , -2 and so on. With this approach SAS can represent any date in future and any date in past." }, { "code": null, "e": 3214, "s": 2949, "text": "When SAS reads the data from a source it converts the data read into a specific date format as specified the date format. The variable to store the date value is declared with the proper informat required. The output date is shown by using the output data formats." }, { "code": null, "e": 3560, "s": 3214, "text": "The source data can be read properly by using specific date informats as shown below. The digit at the end of the informat indicates the minimum width of the date string to be read completely using the informat. A smaller width will give incorrect result. with SAS V9, there is a generic date format anydtdte15. which can process any date input." }, { "code": null, "e": 3741, "s": 3560, "text": "The below code shows the reading of different date formats. Please note the all the output values are just numbers as we have not applied any format statement to the output values." }, { "code": null, "e": 3896, "s": 3741, "text": "DATA TEMP;\nINPUT @1 Date1 date11. @12 Date2 anydtdte15. @23 Date3 mmddyy10. ;\nDATALINES;\n02-mar-2012 3/02/2012 3/02/2012\n;\nPROC PRINT DATA = TEMP;\nRUN;\n" }, { "code": null, "e": 3958, "s": 3896, "text": "When the above code is executed, we get the following output." }, { "code": null, "e": 4155, "s": 3958, "text": "The dates after being read , can be converted to another format as required by the display. This is achieved using the format statement for the date types. They take the same formats as informats." }, { "code": null, "e": 4240, "s": 4155, "text": "In the below exampel the date is read in one format but displayed in another format." }, { "code": null, "e": 4403, "s": 4240, "text": "DATA TEMP;\nINPUT @1 DOJ1 mmddyy10. @12 DOJ2 mmddyy10.;\nformat DOJ1 date11. DOJ2 worddate20. ;\nDATALINES;\n01/12/2012 02/11/1998 \n;\nPROC PRINT DATA = TEMP;\nRUN;\n" }, { "code": null, "e": 4465, "s": 4403, "text": "When the above code is executed, we get the following output." }, { "code": null, "e": 4500, "s": 4465, "text": "\n 50 Lectures \n 5.5 hours \n" }, { "code": null, "e": 4517, "s": 4500, "text": " Code And Create" }, { "code": null, "e": 4552, "s": 4517, "text": "\n 124 Lectures \n 30 hours \n" }, { "code": null, "e": 4565, "s": 4552, "text": " Juan Galvan" }, { "code": null, "e": 4602, "s": 4565, "text": "\n 162 Lectures \n 31.5 hours \n" }, { "code": null, "e": 4622, "s": 4602, "text": " Yossef Ayman Zedan" }, { "code": null, "e": 4657, "s": 4622, "text": "\n 35 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4670, "s": 4657, "text": " Ermin Dedic" }, { "code": null, "e": 4707, "s": 4670, "text": "\n 167 Lectures \n 45.5 hours \n" }, { "code": null, "e": 4723, "s": 4707, "text": " Muslim Helalee" }, { "code": null, "e": 4730, "s": 4723, "text": " Print" }, { "code": null, "e": 4741, "s": 4730, "text": " Add Notes" } ]
What is arrow operator in C++?
The dot and arrow operator are both used in C++ to access the members of a class. They are just used in different scenarios. In C++, types declared as a class, struct, or union are considered "of class type". So the following refers to both of them. a.b is only used if b is a member of the object (or reference[1] to an object) a. So for a.b, a will always be an actual object (or a reference to an object) of a class. a →b is essentially a shorthand notation for (*a).b, ie, if a is a pointer to an object, then a→b is accessing the property b of the object that points to. Note that . is not overloadable. → is an overloadable operator, so we can define our own function(operator→()) that should be called when this operator is used. so if a is an object of a class that overloads operator→ (common such types are smart pointers and iterators), then the meaning is whatever the class designer implemented. [1] References are, semantically, aliases to objects, so I should have added "or reference to a pointer" to the #3 as well. However, I thought this would be more confusing than helpful since references to pointers (T*&) are rarely ever used. #include<iostream> class A { public: int b; A() { b = 5; } }; int main() { A a = A(); A* x = &a; std::cout << "a.b = " << a.b << "\n"; std::cout << "x->b = " << x->b << "\n"; return 0; } This will give the output − 5 5
[ { "code": null, "e": 1312, "s": 1062, "text": "The dot and arrow operator are both used in C++ to access the members of a class. They are just used in different scenarios. In C++, types declared as a class, struct, or union are considered \"of class type\". So the following refers to both of them." }, { "code": null, "e": 1482, "s": 1312, "text": "a.b is only used if b is a member of the object (or reference[1] to an object) a. So for a.b, a will always be an actual object (or a reference to an object) of a class." }, { "code": null, "e": 1638, "s": 1482, "text": "a →b is essentially a shorthand notation for (*a).b, ie, if a is a pointer to an object, then a→b is accessing the property b of the object that points to." }, { "code": null, "e": 1971, "s": 1638, "text": "Note that . is not overloadable. → is an overloadable operator, so we can define our own function(operator→()) that should be called when this operator is used. so if a is an object of a class that overloads operator→ (common such types are smart pointers and iterators), then the meaning is whatever the class designer implemented." }, { "code": null, "e": 2213, "s": 1971, "text": "[1] References are, semantically, aliases to objects, so I should have added \"or reference to a pointer\" to the #3 as well. However, I thought this would be more confusing than helpful since references to pointers (T*&) are rarely ever used." }, { "code": null, "e": 2421, "s": 2213, "text": "#include<iostream>\nclass A {\n public: int b;\n A() { b = 5; }\n};\nint main() {\n A a = A();\n A* x = &a;\n std::cout << \"a.b = \" << a.b << \"\\n\";\n std::cout << \"x->b = \" << x->b << \"\\n\";\n return 0;\n}" }, { "code": null, "e": 2449, "s": 2421, "text": "This will give the output −" }, { "code": null, "e": 2453, "s": 2449, "text": "5\n5" } ]
How to Use Dagger Library in Android App? - GeeksforGeeks
30 Aug, 2021 When we create a new Android Project, eventually we start accumulating different-different dependencies to get certain functionalities, but over time managing them becomes cumbersome, thus an injection framework like Dagger comes into play. However, setting up an injection service like Dagger requires much amount of boilerplate code and has a very steep learning curve. Originally adding raw dependency/version of Dagger without Android Support is a nightmare. But..... Then comes Dagger-Android, which changes this game and satisfies everything which raw Dagger lacked, like reduced pre-made (boiler-plate) code, still it wasn’t successful. In this article, we are going to understand the following by building a simple project. What is Dagger Library, Types of Dependency Injections, and How to Use the Constructor Dependency Injection in Android? We are going to build a very simple app in which we will display text. But we are going to do this by using constructor dependency Injection. Step 1: Create a New Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. Step 2: Add dependencies Copy the following Dagger dependencies and paste them into your App-level build.gradle file. implementation ‘com.google.dagger:dagger:2.38.1’ annotationProcessor ‘com.google.dagger:dagger-compiler:2.38.1’ Keep using the latest dagger version, you can get it from here. Step 3: Working with the activity_main.xml file Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. Add a Simple TextView in the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="30sp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout> Step 4: Create two new Java Classes Make 2 Classes Engine and Wheel with their Empty Constructors like shown below Java Java import java.io.*; class Engine { // Constructor public void Engine() { }} import java.io.*; class Wheel { // Constructor public void Wheel() { }} Step 5: Create another Java class Create a Car Class whose constructor will be taking 2 objects (Engine and Wheel) as arguments. Create a Function drive(), it will be returning a String. Return a simple string “Driving...” in the drive() function. Java import java.io.*; class Car { Engine engine; Wheel wheel; // Constructor public void Car(Engine engine , Wheel wheel) { this.engine = engine; this.wheel = wheel } // method public String drive(){ return "Driving..."; } } Step 6: Working with the MainActivity.java file Now in the MainActivity, Declare the TextView and Define itCreate new objects of Wheel and Engine ClassNow create a car object using the wheel and engine objectsSimply use the drive function we made in the Car class for getting the String Declare the TextView and Define it Create new objects of Wheel and Engine Class Now create a car object using the wheel and engine objects Simply use the drive function we made in the Car class for getting the String Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail. Java import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle; public class MainActivity extends AppCompatActivity { // Declaring TextView text; Wheel wheel; Engine engine; Car car; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Defining text = findViewById(R.id.textView); wheel = new Wheel(); engine = new Engine(); car = new Car(engine, wheel); // Use the drive method from the car object String message = car.drive(); text.setText(message); }} What is a Dependency? Here Dependency Does not mean the Gradle dependency. The car object cannot be created without an engine and wheel object, so the car is dependent on engine and wheel and hence wheel and Engine are dependencies of Car. Why Dagger? For creating a car object whose constructor has arguments, we must pass those arguments (engine and wheel ). while creating the car object. For that, we have to create objects of Wheel and Engine which creates messy boilerplate/reusable code and is a very tedious process. To avoid these we can use Dagger Dependency Injection. Step 7: Make a CarComponent Interface Make a CarComponent Interface and add @Component Annotation to it. The @Component annotation just tells the compiler that this interface is going to be the Component for the car object. Java import java.io.*; @Componentinterface CarComponent { Car getCar();} Step 8: Add @Inject annotation Add @Inject annotation for the constructor of all the classes (Car, Engine, Wheel ). Java Java Java import java.io.*; class Car { Engine engine; Wheel wheel; // Constructor @Inject public void Car(Engine engine , Wheel wheel) { this.engine = engine; this.wheel = wheel } // method public String drive(){ return "Driving..."; } } import java.io.*; class Wheel { // Constructor @Inject public void Wheel(){ }} import java.io.*; class Engine { // Constructor @Inject public void Engine() { }} Step 9: Rebuild the Project Don’t forget to Rebuild the project after Step 8 Step 10: Come again in the MainActivity, as we have used Dagger Dependency Injection (just added annotations). All the boilerplate tedious code is gone. Dagger itself will create a CarComponent class so we don’t have to make Wheel and Engine objects. This way Dagger Dependency Injection makes us work easier removes boilerplate code. Java import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; public class MainActivity extends AppCompatActivity { // Declaration TextView text; Car car; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Defining text = findViewById(R.id.textView); CarComponent carComponent = DaggerCarComponent.create(); car=carComponent.getCar(); String message = car.driving(); text.setText(message); }} Output: Android Java Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Read Data from SQLite Database in Android? How to Delete Data in SQLite Database in Android? MVP (Model View Presenter) Architecture Pattern in Android with Example How to Change the Background Color After Clicking the Button in Android? Android | How to Create/Start a New Project in Android Studio? Arrays in Java Split() String method in Java with examples Arrays.sort() in Java with examples For-each loop in Java Initialize an ArrayList in Java
[ { "code": null, "e": 24751, "s": 24723, "text": "\n30 Aug, 2021" }, { "code": null, "e": 25214, "s": 24751, "text": "When we create a new Android Project, eventually we start accumulating different-different dependencies to get certain functionalities, but over time managing them becomes cumbersome, thus an injection framework like Dagger comes into play. However, setting up an injection service like Dagger requires much amount of boilerplate code and has a very steep learning curve. Originally adding raw dependency/version of Dagger without Android Support is a nightmare." }, { "code": null, "e": 25484, "s": 25214, "text": "But..... Then comes Dagger-Android, which changes this game and satisfies everything which raw Dagger lacked, like reduced pre-made (boiler-plate) code, still it wasn’t successful. In this article, we are going to understand the following by building a simple project. " }, { "code": null, "e": 25508, "s": 25484, "text": "What is Dagger Library," }, { "code": null, "e": 25544, "s": 25508, "text": "Types of Dependency Injections, and" }, { "code": null, "e": 25604, "s": 25544, "text": "How to Use the Constructor Dependency Injection in Android?" }, { "code": null, "e": 25746, "s": 25604, "text": "We are going to build a very simple app in which we will display text. But we are going to do this by using constructor dependency Injection." }, { "code": null, "e": 25775, "s": 25746, "text": "Step 1: Create a New Project" }, { "code": null, "e": 25937, "s": 25775, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language." }, { "code": null, "e": 25962, "s": 25937, "text": "Step 2: Add dependencies" }, { "code": null, "e": 26056, "s": 25962, "text": "Copy the following Dagger dependencies and paste them into your App-level build.gradle file. " }, { "code": null, "e": 26105, "s": 26056, "text": "implementation ‘com.google.dagger:dagger:2.38.1’" }, { "code": null, "e": 26168, "s": 26105, "text": "annotationProcessor ‘com.google.dagger:dagger-compiler:2.38.1’" }, { "code": null, "e": 26232, "s": 26168, "text": "Keep using the latest dagger version, you can get it from here." }, { "code": null, "e": 26280, "s": 26232, "text": "Step 3: Working with the activity_main.xml file" }, { "code": null, "e": 26475, "s": 26280, "text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. Add a Simple TextView in the activity_main.xml file." }, { "code": null, "e": 26479, "s": 26475, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <TextView android:id=\"@+id/textView\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:textSize=\"30sp\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintLeft_toLeftOf=\"parent\" app:layout_constraintRight_toRightOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" /> </androidx.constraintlayout.widget.ConstraintLayout>", "e": 27287, "s": 26479, "text": null }, { "code": null, "e": 27324, "s": 27287, "text": "Step 4: Create two new Java Classes " }, { "code": null, "e": 27403, "s": 27324, "text": "Make 2 Classes Engine and Wheel with their Empty Constructors like shown below" }, { "code": null, "e": 27408, "s": 27403, "text": "Java" }, { "code": null, "e": 27413, "s": 27408, "text": "Java" }, { "code": "import java.io.*; class Engine { // Constructor public void Engine() { }}", "e": 27495, "s": 27413, "text": null }, { "code": "import java.io.*; class Wheel { // Constructor public void Wheel() { }}", "e": 27575, "s": 27495, "text": null }, { "code": null, "e": 27609, "s": 27575, "text": "Step 5: Create another Java class" }, { "code": null, "e": 27704, "s": 27609, "text": "Create a Car Class whose constructor will be taking 2 objects (Engine and Wheel) as arguments." }, { "code": null, "e": 27823, "s": 27704, "text": "Create a Function drive(), it will be returning a String. Return a simple string “Driving...” in the drive() function." }, { "code": null, "e": 27828, "s": 27823, "text": "Java" }, { "code": "import java.io.*; class Car { Engine engine; Wheel wheel; // Constructor public void Car(Engine engine , Wheel wheel) { this.engine = engine; this.wheel = wheel } // method public String drive(){ return \"Driving...\"; } }", "e": 28081, "s": 27828, "text": null }, { "code": null, "e": 28129, "s": 28081, "text": "Step 6: Working with the MainActivity.java file" }, { "code": null, "e": 28155, "s": 28129, "text": "Now in the MainActivity, " }, { "code": null, "e": 28369, "s": 28155, "text": "Declare the TextView and Define itCreate new objects of Wheel and Engine ClassNow create a car object using the wheel and engine objectsSimply use the drive function we made in the Car class for getting the String" }, { "code": null, "e": 28404, "s": 28369, "text": "Declare the TextView and Define it" }, { "code": null, "e": 28449, "s": 28404, "text": "Create new objects of Wheel and Engine Class" }, { "code": null, "e": 28508, "s": 28449, "text": "Now create a car object using the wheel and engine objects" }, { "code": null, "e": 28586, "s": 28508, "text": "Simply use the drive function we made in the Car class for getting the String" }, { "code": null, "e": 28776, "s": 28586, "text": "Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 28781, "s": 28776, "text": "Java" }, { "code": "import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle; public class MainActivity extends AppCompatActivity { // Declaring TextView text; Wheel wheel; Engine engine; Car car; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Defining text = findViewById(R.id.textView); wheel = new Wheel(); engine = new Engine(); car = new Car(engine, wheel); // Use the drive method from the car object String message = car.drive(); text.setText(message); }}", "e": 29454, "s": 28781, "text": null }, { "code": null, "e": 29477, "s": 29454, "text": "What is a Dependency? " }, { "code": null, "e": 29695, "s": 29477, "text": "Here Dependency Does not mean the Gradle dependency. The car object cannot be created without an engine and wheel object, so the car is dependent on engine and wheel and hence wheel and Engine are dependencies of Car." }, { "code": null, "e": 29707, "s": 29695, "text": "Why Dagger?" }, { "code": null, "e": 30035, "s": 29707, "text": "For creating a car object whose constructor has arguments, we must pass those arguments (engine and wheel ). while creating the car object. For that, we have to create objects of Wheel and Engine which creates messy boilerplate/reusable code and is a very tedious process. To avoid these we can use Dagger Dependency Injection." }, { "code": null, "e": 30073, "s": 30035, "text": "Step 7: Make a CarComponent Interface" }, { "code": null, "e": 30259, "s": 30073, "text": "Make a CarComponent Interface and add @Component Annotation to it. The @Component annotation just tells the compiler that this interface is going to be the Component for the car object." }, { "code": null, "e": 30264, "s": 30259, "text": "Java" }, { "code": "import java.io.*; @Componentinterface CarComponent { Car getCar();}", "e": 30334, "s": 30264, "text": null }, { "code": null, "e": 30365, "s": 30334, "text": "Step 8: Add @Inject annotation" }, { "code": null, "e": 30450, "s": 30365, "text": "Add @Inject annotation for the constructor of all the classes (Car, Engine, Wheel )." }, { "code": null, "e": 30455, "s": 30450, "text": "Java" }, { "code": null, "e": 30460, "s": 30455, "text": "Java" }, { "code": null, "e": 30465, "s": 30460, "text": "Java" }, { "code": "import java.io.*; class Car { Engine engine; Wheel wheel; // Constructor @Inject public void Car(Engine engine , Wheel wheel) { this.engine = engine; this.wheel = wheel } // method public String drive(){ return \"Driving...\"; } }", "e": 30729, "s": 30465, "text": null }, { "code": "import java.io.*; class Wheel { // Constructor @Inject public void Wheel(){ }}", "e": 30824, "s": 30729, "text": null }, { "code": "import java.io.*; class Engine { // Constructor @Inject public void Engine() { }}", "e": 30914, "s": 30824, "text": null }, { "code": null, "e": 30942, "s": 30914, "text": "Step 9: Rebuild the Project" }, { "code": null, "e": 30991, "s": 30942, "text": "Don’t forget to Rebuild the project after Step 8" }, { "code": null, "e": 31327, "s": 30991, "text": "Step 10: Come again in the MainActivity, as we have used Dagger Dependency Injection (just added annotations). All the boilerplate tedious code is gone. Dagger itself will create a CarComponent class so we don’t have to make Wheel and Engine objects. This way Dagger Dependency Injection makes us work easier removes boilerplate code." }, { "code": null, "e": 31332, "s": 31327, "text": "Java" }, { "code": "import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; public class MainActivity extends AppCompatActivity { // Declaration TextView text; Car car; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Defining text = findViewById(R.id.textView); CarComponent carComponent = DaggerCarComponent.create(); car=carComponent.getCar(); String message = car.driving(); text.setText(message); }}", "e": 31921, "s": 31332, "text": null }, { "code": null, "e": 31930, "s": 31921, "text": "Output: " }, { "code": null, "e": 31938, "s": 31930, "text": "Android" }, { "code": null, "e": 31943, "s": 31938, "text": "Java" }, { "code": null, "e": 31948, "s": 31943, "text": "Java" }, { "code": null, "e": 31956, "s": 31948, "text": "Android" }, { "code": null, "e": 32054, "s": 31956, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32063, "s": 32054, "text": "Comments" }, { "code": null, "e": 32076, "s": 32063, "text": "Old Comments" }, { "code": null, "e": 32126, "s": 32076, "text": "How to Read Data from SQLite Database in Android?" }, { "code": null, "e": 32176, "s": 32126, "text": "How to Delete Data in SQLite Database in Android?" }, { "code": null, "e": 32248, "s": 32176, "text": "MVP (Model View Presenter) Architecture Pattern in Android with Example" }, { "code": null, "e": 32321, "s": 32248, "text": "How to Change the Background Color After Clicking the Button in Android?" }, { "code": null, "e": 32384, "s": 32321, "text": "Android | How to Create/Start a New Project in Android Studio?" }, { "code": null, "e": 32399, "s": 32384, "text": "Arrays in Java" }, { "code": null, "e": 32443, "s": 32399, "text": "Split() String method in Java with examples" }, { "code": null, "e": 32479, "s": 32443, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 32501, "s": 32479, "text": "For-each loop in Java" } ]
What is the difference between method overloading and method overriding in Java?
Following are the notable differences between overloading and overriding. In method overloading a class have two or more methods in with the same name and different parameters. In overloading return type could vary in both methods. JVM calls the respective method based on the parameters passed to it, at the time of method call. Live Demo public class OverloadingExample { public void display(){ System.out.println("Display method"); } public void display(int a){ System.out.println("Display method "+a); } public static void main(String args[]){ OverloadingExample obj = new OverloadingExample(); obj.display(); obj.display(20); } } Display method Display method 20 In method overriding Super class and subclass have methods with same name including parameters. In overriding return types should also be same. JVM calls the respective method based on the object used to call the method. Live Demo class SuperClass{ public static void sample(){ System.out.println("Method of the super class"); } } public class RuntimePolymorphism extends SuperClass { public static void sample(){ System.out.println("Method of the sub class"); } public static void main(String args[]){ SuperClass obj1 = new RuntimePolymorphism(); RuntimePolymorphism obj2 = new RuntimePolymorphism(); obj1.sample(); obj2.sample(); } } Method of the super class Method of the sub class
[ { "code": null, "e": 1136, "s": 1062, "text": "Following are the notable differences between overloading and overriding." }, { "code": null, "e": 1239, "s": 1136, "text": "In method overloading a class have two or more methods in with the same name and different parameters." }, { "code": null, "e": 1294, "s": 1239, "text": "In overloading return type could vary in both methods." }, { "code": null, "e": 1392, "s": 1294, "text": "JVM calls the respective method based on the parameters passed to it, at the time of method call." }, { "code": null, "e": 1403, "s": 1392, "text": " Live Demo" }, { "code": null, "e": 1746, "s": 1403, "text": "public class OverloadingExample {\n public void display(){\n System.out.println(\"Display method\");\n }\n public void display(int a){\n System.out.println(\"Display method \"+a);\n }\n public static void main(String args[]){\n OverloadingExample obj = new OverloadingExample();\n obj.display();\n obj.display(20);\n }\n}" }, { "code": null, "e": 1780, "s": 1746, "text": "Display method\nDisplay method 20\n" }, { "code": null, "e": 1876, "s": 1780, "text": "In method overriding Super class and subclass have methods with same name including parameters." }, { "code": null, "e": 1924, "s": 1876, "text": "In overriding return types should also be same." }, { "code": null, "e": 2001, "s": 1924, "text": "JVM calls the respective method based on the object used to call the method." }, { "code": null, "e": 2012, "s": 2001, "text": " Live Demo" }, { "code": null, "e": 2478, "s": 2012, "text": "class SuperClass{\n public static void sample(){\n System.out.println(\"Method of the super class\");\n }\n}\npublic class RuntimePolymorphism extends SuperClass {\n public static void sample(){\n System.out.println(\"Method of the sub class\");\n }\n public static void main(String args[]){\n SuperClass obj1 = new RuntimePolymorphism();\n RuntimePolymorphism obj2 = new RuntimePolymorphism();\n \n obj1.sample();\n obj2.sample();\n }\n}" }, { "code": null, "e": 2529, "s": 2478, "text": "Method of the super class\nMethod of the sub class\n" } ]
TF – IDF for Bigrams & Trigrams
27 Sep, 2019 TF-IDF in NLP stands for Term Frequency – Inverse document frequency. It is a very popular topic in Natural Language Processing which generally deals with human languages. During any text processing, cleaning the text (preprocessing) is vital. Further, the cleaned data needs to be converted into a numerical format where each word is represented by a matrix (word vectors). This is also known as word embeddingTerm Frequency (TF) = (Frequency of a term in the document)/(Total number of terms in documents)Inverse Document Frequency(IDF) = log( (total number of documents)/(number of documents with term t))TF.IDF = (TF).(IDF) Bigrams: Bigram is 2 consecutive words in a sentence. E.g. “The boy is playing football”. The bigrams here are: The boy Boy is Is playing Playing football Trigrams: Trigram is 3 consecutive words in a sentence. For the above example trigrams will be: The boy is Boy is playing Is playing football From the above bigrams and trigram, some are relevant while others are discarded which do not contribute value for further processing.Let us say from a document we want to find out the skills required to be a “Data Scientist”. Here, if we consider only unigrams, then the single word cannot convey the details properly. If we have a word like ‘Machine learning developer’, then the word extracted should be ‘Machine learning’ or ‘Machine learning developer’. The words simply ‘Machine’, ‘learning’ or ‘developer’ will not give the expected result. Code – Illustrating the detailed explanation for trigrams # Importing librariesimport nltkimport refrom sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizerfrom nltk.corpus import stopwordsfrom nltk.tokenize import word_tokenizeimport pandas as pd # Input the file txt1 = []with open('C:\\Users\\DELL\\Desktop\\MachineLearning1.txt') as file: txt1 = file.readlines() # Preprocessingdef remove_string_special_characters(s): # removes special characters with ' ' stripped = re.sub('[^a-zA-z\s]', '', s) stripped = re.sub('_', '', stripped) # Change any white space to one space stripped = re.sub('\s+', ' ', stripped) # Remove start and end white spaces stripped = stripped.strip() if stripped != '': return stripped.lower() # Stopword removal stop_words = set(stopwords.words('english'))your_list = ['skills', 'ability', 'job', 'description']for i, line in enumerate(txt1): txt1[i] = ' '.join([x for x in nltk.word_tokenize(line) if ( x not in stop_words ) and ( x not in your_list )]) # Getting trigrams vectorizer = CountVectorizer(ngram_range = (3,3))X1 = vectorizer.fit_transform(txt1) features = (vectorizer.get_feature_names())print("\n\nFeatures : \n", features)print("\n\nX1 : \n", X1.toarray()) # Applying TFIDFvectorizer = TfidfVectorizer(ngram_range = (3,3))X2 = vectorizer.fit_transform(txt1)scores = (X2.toarray())print("\n\nScores : \n", scores) # Getting top ranking featuressums = X2.sum(axis = 0)data1 = []for col, term in enumerate(features): data1.append( (term, sums[0,col] ))ranking = pd.DataFrame(data1, columns = ['term','rank'])words = (ranking.sort_values('rank', ascending = False))print ("\n\nWords head : \n", words.head(7)) Output: Features : ['10 experience working', '11 exposure implementing', 'able work minimal', 'accounts commerce added', 'analysis recognition face', 'analytics contextual image', 'analytics nlp ensemble', 'applying data science', 'bagging boosting text', 'beyond existing learn', 'boosting text analytics', 'building using logistics', 'building using supervised', 'classification facial expression', 'classifier deep learning', 'commerce added advantage', 'complex engineering analysis', 'contextual image processing', 'creative projects work', 'data science problem', 'data science solutions', 'decisions report progress', 'deep learning analytics', 'deep learning framework', 'deep learning neural', 'demonstrated development role', 'demonstrated leadership role', 'description machine learning', 'detection tracking classification', 'development role machine', 'direction project less', 'domains essential position', 'domains like healthcare', 'ensemble classifier deep', 'existing learn quickly', 'experience object detection', 'experience working multiple', 'experienced technical personnel', 'expertise visualizing manipulating', 'exposure implementing data', 'expression analysis recognition', 'extensively worked python', 'face iris finger', 'facial expression analysis', 'finance accounts commerce', 'forest bagging boosting', 'framework tensorflow keras', 'good oral written', 'guidance direction project', 'guidance make decisions', 'healthcare finance accounts', 'implementing data science', 'including provide guidance', 'innovative creative projects', 'iris finger gesture', 'job description machine', 'keras or pytorch', 'leadership role projects', 'learn quickly new', 'learning analytics contextual', 'learning framework tensorflow', 'learning neural networks', 'learning projects including', 'less experienced technical', 'like healthcare finance', 'linear regression svm', 'logistics regression linear', 'machine learning developer', 'machine learning projects', 'make decisions report', 'manipulating big datasets', 'minimal guidance make', 'model building using', 'motivated able work', 'multiple domains like', 'must self motivated', 'new domains essential', 'nlp ensemble classifier', 'object detection tracking', 'oral written communication', 'perform complex engineering', 'problem solving proven', 'problem statements bring', 'proficiency deep learning', 'proficiency problem solving', 'project less experienced', 'projects including provide', 'projects work spare', 'proven perform complex', 'proven record working', 'provide guidance direction', 'quickly new domains', 'random forest bagging', 'recognition face iris', 'record working innovative', 'regression linear regression', 'regression svm random', 'role machine learning', 'role projects including', 'science problem statements', 'science solutions production', 'self motivated able', 'solutions production environments', 'solving proven perform', 'spare time plus', 'statements bring insights', 'supervised unsupervised algorithms', 'svm random forest', 'tensorflow keras or', 'text analytics nlp', 'tracking classification facial', 'using logistics regression', 'using supervised unsupervised', 'visualizing manipulating big', 'work minimal guidance', 'work spare time', 'working innovative creative', 'working multiple domains'] X1 : [[0 0 0 ... 0 0 0] [0 0 0 ... 0 0 0] [0 0 0 ... 0 0 0] ... [0 0 0 ... 0 0 0] [0 0 0 ... 0 0 0] [0 0 0 ... 0 0 0]] Scores : [[0. 0. 0. ... 0. 0. 0.] [0. 0. 0. ... 0. 0. 0.] [0. 0. 0. ... 0. 0. 0.] ... [0. 0. 0. ... 0. 0. 0.] [0. 0. 0. ... 0. 0. 0.] [0. 0. 0. ... 0. 0. 0.]] Words head : term rank 41 extensively worked python 1.000000 79 oral written communication 0.707107 47 good oral written 0.707107 72 model building using 0.673502 27 description machine learning 0.577350 70 manipulating big datasets 0.577350 67 machine learning developer 0.577350 Now, if w do it for bigrams then the initial part of code will remain the same. Only the bigram formation part will change.Code : Python code for implementing bigrams # Getting bigrams vectorizer = CountVectorizer(ngram_range =(2, 2))X1 = vectorizer.fit_transform(txt1) features = (vectorizer.get_feature_names())print("\n\nX1 : \n", X1.toarray()) # Applying TFIDF# You can still get n-grams herevectorizer = TfidfVectorizer(ngram_range = (2, 2))X2 = vectorizer.fit_transform(txt1)scores = (X2.toarray())print("\n\nScores : \n", scores) # Getting top ranking featuressums = X2.sum(axis = 0)data1 = []for col, term in enumerate(features): data1.append( (term, sums[0, col] ))ranking = pd.DataFrame(data1, columns = ['term', 'rank'])words = (ranking.sort_values('rank', ascending = False))print ("\n\nWords : \n", words.head(7)) Output: X1 : [[0 0 0 ... 0 0 0] [0 0 0 ... 0 0 0] [0 0 0 ... 0 0 0] ... [0 0 0 ... 0 0 0] [0 0 0 ... 0 0 0] [0 0 0 ... 0 0 0]] Scores : [[0. 0. 0. ... 0. 0. 0.] [0. 0. 0. ... 0. 0. 0.] [0. 0. 0. ... 0. 0. 0.] ... [0. 0. 0. ... 0. 0. 0.] [0. 0. 0. ... 0. 0. 0.] [0. 0. 0. ... 0. 0. 0.]] Words : term rank 50 great interpersonal 1.000000 110 skills abilities 1.000000 23 deep learning 0.904954 72 machine learning 0.723725 21 data science 0.723724 128 worked python 0.707107 42 extensively worked 0.707107 Likewise, we can obtain the TF IDF scores for bigrams and trigrams as per our use. These can help us get a better outcome without having to process more on data. Machine Learning Python Technical Scripter Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n27 Sep, 2019" }, { "code": null, "e": 682, "s": 54, "text": "TF-IDF in NLP stands for Term Frequency – Inverse document frequency. It is a very popular topic in Natural Language Processing which generally deals with human languages. During any text processing, cleaning the text (preprocessing) is vital. Further, the cleaned data needs to be converted into a numerical format where each word is represented by a matrix (word vectors). This is also known as word embeddingTerm Frequency (TF) = (Frequency of a term in the document)/(Total number of terms in documents)Inverse Document Frequency(IDF) = log( (total number of documents)/(number of documents with term t))TF.IDF = (TF).(IDF)" }, { "code": null, "e": 794, "s": 682, "text": "Bigrams: Bigram is 2 consecutive words in a sentence. E.g. “The boy is playing football”. The bigrams here are:" }, { "code": null, "e": 838, "s": 794, "text": "The boy\nBoy is\nIs playing\nPlaying football\n" }, { "code": null, "e": 934, "s": 838, "text": "Trigrams: Trigram is 3 consecutive words in a sentence. For the above example trigrams will be:" }, { "code": null, "e": 980, "s": 934, "text": "The boy is\nBoy is playing\nIs playing football" }, { "code": null, "e": 1528, "s": 980, "text": "From the above bigrams and trigram, some are relevant while others are discarded which do not contribute value for further processing.Let us say from a document we want to find out the skills required to be a “Data Scientist”. Here, if we consider only unigrams, then the single word cannot convey the details properly. If we have a word like ‘Machine learning developer’, then the word extracted should be ‘Machine learning’ or ‘Machine learning developer’. The words simply ‘Machine’, ‘learning’ or ‘developer’ will not give the expected result." }, { "code": null, "e": 1586, "s": 1528, "text": "Code – Illustrating the detailed explanation for trigrams" }, { "code": "# Importing librariesimport nltkimport refrom sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizerfrom nltk.corpus import stopwordsfrom nltk.tokenize import word_tokenizeimport pandas as pd # Input the file txt1 = []with open('C:\\\\Users\\\\DELL\\\\Desktop\\\\MachineLearning1.txt') as file: txt1 = file.readlines() # Preprocessingdef remove_string_special_characters(s): # removes special characters with ' ' stripped = re.sub('[^a-zA-z\\s]', '', s) stripped = re.sub('_', '', stripped) # Change any white space to one space stripped = re.sub('\\s+', ' ', stripped) # Remove start and end white spaces stripped = stripped.strip() if stripped != '': return stripped.lower() # Stopword removal stop_words = set(stopwords.words('english'))your_list = ['skills', 'ability', 'job', 'description']for i, line in enumerate(txt1): txt1[i] = ' '.join([x for x in nltk.word_tokenize(line) if ( x not in stop_words ) and ( x not in your_list )]) # Getting trigrams vectorizer = CountVectorizer(ngram_range = (3,3))X1 = vectorizer.fit_transform(txt1) features = (vectorizer.get_feature_names())print(\"\\n\\nFeatures : \\n\", features)print(\"\\n\\nX1 : \\n\", X1.toarray()) # Applying TFIDFvectorizer = TfidfVectorizer(ngram_range = (3,3))X2 = vectorizer.fit_transform(txt1)scores = (X2.toarray())print(\"\\n\\nScores : \\n\", scores) # Getting top ranking featuressums = X2.sum(axis = 0)data1 = []for col, term in enumerate(features): data1.append( (term, sums[0,col] ))ranking = pd.DataFrame(data1, columns = ['term','rank'])words = (ranking.sort_values('rank', ascending = False))print (\"\\n\\nWords head : \\n\", words.head(7))", "e": 3295, "s": 1586, "text": null }, { "code": null, "e": 3303, "s": 3295, "text": "Output:" }, { "code": null, "e": 7316, "s": 3303, "text": "Features : \n ['10 experience working', '11 exposure implementing', 'able work minimal',\n 'accounts commerce added', 'analysis recognition face', 'analytics contextual image',\n 'analytics nlp ensemble', 'applying data science', 'bagging boosting text',\n 'beyond existing learn', 'boosting text analytics', 'building using logistics',\n 'building using supervised', 'classification facial expression', \n 'classifier deep learning', 'commerce added advantage',\n 'complex engineering analysis', 'contextual image processing',\n 'creative projects work', 'data science problem', 'data science solutions',\n 'decisions report progress', 'deep learning analytics', 'deep learning framework',\n 'deep learning neural', 'demonstrated development role', 'demonstrated leadership role',\n 'description machine learning', 'detection tracking classification',\n 'development role machine', 'direction project less', 'domains essential position',\n 'domains like healthcare', 'ensemble classifier deep', 'existing learn quickly',\n 'experience object detection', 'experience working multiple',\n 'experienced technical personnel', 'expertise visualizing manipulating',\n 'exposure implementing data', 'expression analysis recognition',\n 'extensively worked python', 'face iris finger', 'facial expression analysis',\n 'finance accounts commerce', 'forest bagging boosting', 'framework tensorflow keras',\n 'good oral written', 'guidance direction project', 'guidance make decisions',\n 'healthcare finance accounts', 'implementing data science', 'including provide guidance',\n 'innovative creative projects', 'iris finger gesture', 'job description machine',\n 'keras or pytorch', 'leadership role projects', 'learn quickly new',\n 'learning analytics contextual', 'learning framework tensorflow',\n 'learning neural networks', 'learning projects including', 'less experienced technical',\n 'like healthcare finance', 'linear regression svm', 'logistics regression linear',\n 'machine learning developer', 'machine learning projects', 'make decisions report',\n 'manipulating big datasets', 'minimal guidance make', 'model building using',\n 'motivated able work', 'multiple domains like', 'must self motivated',\n 'new domains essential', 'nlp ensemble classifier', 'object detection tracking',\n 'oral written communication', 'perform complex engineering', 'problem solving proven',\n 'problem statements bring', 'proficiency deep learning', 'proficiency problem solving',\n 'project less experienced', 'projects including provide', 'projects work spare',\n 'proven perform complex', 'proven record working', 'provide guidance direction',\n 'quickly new domains', 'random forest bagging', 'recognition face iris',\n 'record working innovative', 'regression linear regression', 'regression svm random',\n 'role machine learning', 'role projects including', 'science problem statements',\n 'science solutions production', 'self motivated able', 'solutions production environments',\n 'solving proven perform', 'spare time plus', 'statements bring insights',\n 'supervised unsupervised algorithms', 'svm random forest', 'tensorflow keras or',\n 'text analytics nlp', 'tracking classification facial', 'using logistics regression',\n 'using supervised unsupervised', 'visualizing manipulating big', 'work minimal guidance',\n 'work spare time', 'working innovative creative', 'working multiple domains']\n\n\nX1 : \n [[0 0 0 ... 0 0 0]\n [0 0 0 ... 0 0 0]\n [0 0 0 ... 0 0 0]\n ...\n [0 0 0 ... 0 0 0]\n [0 0 0 ... 0 0 0]\n [0 0 0 ... 0 0 0]]\n\n\nScores : \n [[0. 0. 0. ... 0. 0. 0.]\n [0. 0. 0. ... 0. 0. 0.]\n [0. 0. 0. ... 0. 0. 0.]\n ...\n [0. 0. 0. ... 0. 0. 0.]\n [0. 0. 0. ... 0. 0. 0.]\n [0. 0. 0. ... 0. 0. 0.]]\n\n\nWords head : \n term rank\n41 extensively worked python 1.000000\n79 oral written communication 0.707107\n47 good oral written 0.707107\n72 model building using 0.673502\n27 description machine learning 0.577350\n70 manipulating big datasets 0.577350\n67 machine learning developer 0.577350" }, { "code": null, "e": 7483, "s": 7316, "text": "Now, if w do it for bigrams then the initial part of code will remain the same. Only the bigram formation part will change.Code : Python code for implementing bigrams" }, { "code": "# Getting bigrams vectorizer = CountVectorizer(ngram_range =(2, 2))X1 = vectorizer.fit_transform(txt1) features = (vectorizer.get_feature_names())print(\"\\n\\nX1 : \\n\", X1.toarray()) # Applying TFIDF# You can still get n-grams herevectorizer = TfidfVectorizer(ngram_range = (2, 2))X2 = vectorizer.fit_transform(txt1)scores = (X2.toarray())print(\"\\n\\nScores : \\n\", scores) # Getting top ranking featuressums = X2.sum(axis = 0)data1 = []for col, term in enumerate(features): data1.append( (term, sums[0, col] ))ranking = pd.DataFrame(data1, columns = ['term', 'rank'])words = (ranking.sort_values('rank', ascending = False))print (\"\\n\\nWords : \\n\", words.head(7))", "e": 8148, "s": 7483, "text": null }, { "code": null, "e": 8156, "s": 8148, "text": "Output:" }, { "code": null, "e": 8745, "s": 8156, "text": "X1 : \n [[0 0 0 ... 0 0 0]\n [0 0 0 ... 0 0 0]\n [0 0 0 ... 0 0 0]\n ...\n [0 0 0 ... 0 0 0]\n [0 0 0 ... 0 0 0]\n [0 0 0 ... 0 0 0]]\n\n\nScores : \n [[0. 0. 0. ... 0. 0. 0.]\n [0. 0. 0. ... 0. 0. 0.]\n [0. 0. 0. ... 0. 0. 0.]\n ...\n [0. 0. 0. ... 0. 0. 0.]\n [0. 0. 0. ... 0. 0. 0.]\n [0. 0. 0. ... 0. 0. 0.]]\n\n\nWords : \n term rank\n50 great interpersonal 1.000000\n110 skills abilities 1.000000\n23 deep learning 0.904954\n72 machine learning 0.723725\n21 data science 0.723724\n128 worked python 0.707107\n42 extensively worked 0.707107\n" }, { "code": null, "e": 8907, "s": 8745, "text": "Likewise, we can obtain the TF IDF scores for bigrams and trigrams as per our use. These can help us get a better outcome without having to process more on data." }, { "code": null, "e": 8924, "s": 8907, "text": "Machine Learning" }, { "code": null, "e": 8931, "s": 8924, "text": "Python" }, { "code": null, "e": 8950, "s": 8931, "text": "Technical Scripter" }, { "code": null, "e": 8967, "s": 8950, "text": "Machine Learning" } ]
Golang | Replacing all String which Matches with Regular Expression
05 Sep, 2019 A regular expression is a sequence of characters which define a search pattern. Go language support regular expressions. A regular expression is used for parsing, filtering, validating, and extracting meaningful information from large text, like logs, the output generated from other programs, etc.In Go regexp, you are allowed to replace original string with another string if the specified string matches with the specified regular expression with the help of ReplaceAllString() method. In this method, $ sign means interpreted as in Expand like $1 indicates the text of the first submatch. This method is defined under the regexp package, so for accessing this method you need to import the regexp package in your program. Syntax: func (re *Regexp) ReplaceAllString(str, r string) string Example 1: // Go program to illustrate how to// replace string with the specified regexppackage main import ( "fmt" "regexp") // Main functionfunc main() { // Replace string with the specified regexp // Using ReplaceAllString() method m1 := regexp.MustCompile(`x(p*)y`) fmt.Println(m1.ReplaceAllString("xy--xpppyxxppxy-", "B")) fmt.Println(m1.ReplaceAllString("xy--xpppyxxppxy--", "$1")) fmt.Println(m1.ReplaceAllString("xy--xpppyxxppxy-", "$1P")) fmt.Println(m1.ReplaceAllString("xy--xpppyxxppxy-", "${1}Q")) } Output: B--BxxppB- --pppxxpp-- --xxpp- Q--pppQxxppQ- Example 2: // Go program to illustrate how to replace// string with the specified regexppackage main import ( "fmt" "regexp") // Main functionfunc main() { // Creating and initializing a string // Using shorthand declaration s := "Geeks-for-Geeks-for-Geeks-for-Geeks-gfg" // Replacing all the strings // Using ReplaceAllString() method m := regexp.MustCompile("^(.*?)Geeks(.*)$") Str := "${1}GEEKS$2" res := m.ReplaceAllString(s, Str) fmt.Println(res) } Output: GEEKS-for-Geeks-for-Geeks-for-Geeks-gfg Golang Golang-String Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n05 Sep, 2019" }, { "code": null, "e": 754, "s": 28, "text": "A regular expression is a sequence of characters which define a search pattern. Go language support regular expressions. A regular expression is used for parsing, filtering, validating, and extracting meaningful information from large text, like logs, the output generated from other programs, etc.In Go regexp, you are allowed to replace original string with another string if the specified string matches with the specified regular expression with the help of ReplaceAllString() method. In this method, $ sign means interpreted as in Expand like $1 indicates the text of the first submatch. This method is defined under the regexp package, so for accessing this method you need to import the regexp package in your program." }, { "code": null, "e": 762, "s": 754, "text": "Syntax:" }, { "code": null, "e": 819, "s": 762, "text": "func (re *Regexp) ReplaceAllString(str, r string) string" }, { "code": null, "e": 830, "s": 819, "text": "Example 1:" }, { "code": "// Go program to illustrate how to// replace string with the specified regexppackage main import ( \"fmt\" \"regexp\") // Main functionfunc main() { // Replace string with the specified regexp // Using ReplaceAllString() method m1 := regexp.MustCompile(`x(p*)y`) fmt.Println(m1.ReplaceAllString(\"xy--xpppyxxppxy-\", \"B\")) fmt.Println(m1.ReplaceAllString(\"xy--xpppyxxppxy--\", \"$1\")) fmt.Println(m1.ReplaceAllString(\"xy--xpppyxxppxy-\", \"$1P\")) fmt.Println(m1.ReplaceAllString(\"xy--xpppyxxppxy-\", \"${1}Q\")) }", "e": 1365, "s": 830, "text": null }, { "code": null, "e": 1373, "s": 1365, "text": "Output:" }, { "code": null, "e": 1419, "s": 1373, "text": "B--BxxppB-\n--pppxxpp--\n--xxpp-\nQ--pppQxxppQ-\n" }, { "code": null, "e": 1430, "s": 1419, "text": "Example 2:" }, { "code": "// Go program to illustrate how to replace// string with the specified regexppackage main import ( \"fmt\" \"regexp\") // Main functionfunc main() { // Creating and initializing a string // Using shorthand declaration s := \"Geeks-for-Geeks-for-Geeks-for-Geeks-gfg\" // Replacing all the strings // Using ReplaceAllString() method m := regexp.MustCompile(\"^(.*?)Geeks(.*)$\") Str := \"${1}GEEKS$2\" res := m.ReplaceAllString(s, Str) fmt.Println(res) }", "e": 1913, "s": 1430, "text": null }, { "code": null, "e": 1921, "s": 1913, "text": "Output:" }, { "code": null, "e": 1961, "s": 1921, "text": "GEEKS-for-Geeks-for-Geeks-for-Geeks-gfg" }, { "code": null, "e": 1968, "s": 1961, "text": "Golang" }, { "code": null, "e": 1982, "s": 1968, "text": "Golang-String" }, { "code": null, "e": 1994, "s": 1982, "text": "Go Language" } ]
Zoom into ggplot2 Plot without Removing Data in R
24 Oct, 2021 In this article, we will discuss how to zoom into the ggplot2 plot without removing data using ggplot2 package in the R programming language. The approaches to the zoom into ggplot2 plot without removing data are as follows: Zoom in to ggplot2 plot without Removing data using ylim()/xlim() function Zoom in to ggplot2 plot without Removing data using coord_cartesian() function ylim()/xlim() function: Convenience function to set the limits of the y axis/x-axis. Syntax: ylim(...) xlim(...) Parameters: ...: if numeric, will create a continuous scale, if factor or character, will create a discrete scale. Example: In this, example, we will be using xlim() function to get the zoom into view of the ggplot2 bar plot of the given data without removing any initial data in the R programming language. R # load the packageslibrary("ggplot2") # create the dataframe with letters and numbersgfg < -data.frame( x=c('A', 'B', 'C', 'D', 'E', 'F'), y=c(4, 6, 2, 9, 7, 3)) # plot the given data# with A,B and C as titles to the barsplot < -ggplot(gfg, aes(x, y, fill=x)) +geom_bar(stat="identity")plot+xlim('A', 'B', 'C') Output: The Cartesian coordinate system is the most familiar, and common, type of coordinate system. Setting limits on the coordinate system will zoom the plot (like you’re looking at it with a magnifying glass), and will not change the underlying data like setting limits on a scale will. Syntax: coord_cartesian( xlim = NULL, ylim = NULL,expand = TRUE, default = FALSE, clip = “on”) Parameters: xlim, ylim: Limits for the x and y axes. expand: If TRUE, the default, adds a small expansion factor to the limits to ensure that data and axes don’t overlap. default: Is this the default coordinate system clip: Should drawing be clipped to the extent of the plot panel? Example: In this, example, we will be using the coord_cartesian() function with ylim() function to get the zoom into view of the ggplot2 bar plot of the given data without removing any initial data in the R programming language. R # load the packagelibrary("ggplot2") # create the dataframe with letters# and numbersgfg < -data.frame( x=c('A', 'B', 'C', 'D', 'E', 'F'), y=c(4, 6, 2, 9, 7, 3)) # plot the catrtesian barplot < -ggplot(gfg, aes(x, y, fill=x)) +geom_bar(stat="identity")plot+coord_cartesian(ylim=c(5, 7)) Output: Picked R-ggplot R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Oct, 2021" }, { "code": null, "e": 253, "s": 28, "text": "In this article, we will discuss how to zoom into the ggplot2 plot without removing data using ggplot2 package in the R programming language. The approaches to the zoom into ggplot2 plot without removing data are as follows:" }, { "code": null, "e": 328, "s": 253, "text": "Zoom in to ggplot2 plot without Removing data using ylim()/xlim() function" }, { "code": null, "e": 407, "s": 328, "text": "Zoom in to ggplot2 plot without Removing data using coord_cartesian() function" }, { "code": null, "e": 492, "s": 407, "text": "ylim()/xlim() function: Convenience function to set the limits of the y axis/x-axis." }, { "code": null, "e": 500, "s": 492, "text": "Syntax:" }, { "code": null, "e": 520, "s": 500, "text": "ylim(...)\nxlim(...)" }, { "code": null, "e": 532, "s": 520, "text": "Parameters:" }, { "code": null, "e": 635, "s": 532, "text": "...: if numeric, will create a continuous scale, if factor or character, will create a discrete scale." }, { "code": null, "e": 644, "s": 635, "text": "Example:" }, { "code": null, "e": 829, "s": 644, "text": "In this, example, we will be using xlim() function to get the zoom into view of the ggplot2 bar plot of the given data without removing any initial data in the R programming language. " }, { "code": null, "e": 831, "s": 829, "text": "R" }, { "code": "# load the packageslibrary(\"ggplot2\") # create the dataframe with letters and numbersgfg < -data.frame( x=c('A', 'B', 'C', 'D', 'E', 'F'), y=c(4, 6, 2, 9, 7, 3)) # plot the given data# with A,B and C as titles to the barsplot < -ggplot(gfg, aes(x, y, fill=x)) +geom_bar(stat=\"identity\")plot+xlim('A', 'B', 'C')", "e": 1150, "s": 831, "text": null }, { "code": null, "e": 1158, "s": 1150, "text": "Output:" }, { "code": null, "e": 1440, "s": 1158, "text": "The Cartesian coordinate system is the most familiar, and common, type of coordinate system. Setting limits on the coordinate system will zoom the plot (like you’re looking at it with a magnifying glass), and will not change the underlying data like setting limits on a scale will." }, { "code": null, "e": 1448, "s": 1440, "text": "Syntax:" }, { "code": null, "e": 1535, "s": 1448, "text": "coord_cartesian( xlim = NULL, ylim = NULL,expand = TRUE, default = FALSE, clip = “on”)" }, { "code": null, "e": 1547, "s": 1535, "text": "Parameters:" }, { "code": null, "e": 1588, "s": 1547, "text": "xlim, ylim: Limits for the x and y axes." }, { "code": null, "e": 1706, "s": 1588, "text": "expand: If TRUE, the default, adds a small expansion factor to the limits to ensure that data and axes don’t overlap." }, { "code": null, "e": 1753, "s": 1706, "text": "default: Is this the default coordinate system" }, { "code": null, "e": 1818, "s": 1753, "text": "clip: Should drawing be clipped to the extent of the plot panel?" }, { "code": null, "e": 1827, "s": 1818, "text": "Example:" }, { "code": null, "e": 2048, "s": 1827, "text": "In this, example, we will be using the coord_cartesian() function with ylim() function to get the zoom into view of the ggplot2 bar plot of the given data without removing any initial data in the R programming language. " }, { "code": null, "e": 2050, "s": 2048, "text": "R" }, { "code": "# load the packagelibrary(\"ggplot2\") # create the dataframe with letters# and numbersgfg < -data.frame( x=c('A', 'B', 'C', 'D', 'E', 'F'), y=c(4, 6, 2, 9, 7, 3)) # plot the catrtesian barplot < -ggplot(gfg, aes(x, y, fill=x)) +geom_bar(stat=\"identity\")plot+coord_cartesian(ylim=c(5, 7))", "e": 2345, "s": 2050, "text": null }, { "code": null, "e": 2353, "s": 2345, "text": "Output:" }, { "code": null, "e": 2360, "s": 2353, "text": "Picked" }, { "code": null, "e": 2369, "s": 2360, "text": "R-ggplot" }, { "code": null, "e": 2380, "s": 2369, "text": "R Language" } ]
Design a close button using Pure CSS
19 Jan, 2022 The task is to make the close button using Pure CSS. There are two approaches that are discussed below. Approach 1: Create a <div> inside another <div> which has alphabet ‘X’ in it which helps in displaying the close button. When the “click” event occurs on ‘X’, then perform the operation. In this example the outer <div> has been hidden when the event occurs. Example: This example implements the above approach. html <!DOCTYPE HTML><html> <head> <style> .outer { background: green; height: 60px; display: block; } .button { margin-left: 93%; color: white; font-weight: bold; cursor: pointer; } </style></head> <body style="text-align:center;"> <h1>GeeksForGeeks</h1> <p> Click on the cross to hide the element. </p> <div class="outer"> <div class="button">X</div> </div> <br> <p id="GFG"></p> <script> var down = document.getElementById("GFG"); var el = document.querySelector('.button'); el.addEventListener('click', function () { var el2 = document.querySelector('.outer'); el2.style.display = "none"; }); </script></body> </html> Output: Approach 2: jQuery is used in this approach. Create a <div> inside another <div> that contains the alphabet ‘X’ to display the close button. When the “Click” event occurs on ‘X’ then perform the operation. In this example, the outer <div> has been hidden when the event occurs. Example: This example implements the above approach. html <!DOCTYPE HTML><html> <head> <style> .outer { background: green; height: 60px; display: block; } .button { margin-left: 93%; color: white; font-weight: bold; cursor: pointer; } </style> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script></head> <body style="text-align:center;"> <h1> GeeksForGeeks </h1> <p> Click on the cross to hide the element. </p> <div class="outer"> <div class="button">X</div> </div> <br> <p id="GFG"> </p> <script> var down = document.getElementById("GFG"); $('.button').on('click', function () { $('.outer').hide(); }); </script></body> </html> Output: varshagumber28 CSS-Misc jQuery-Misc JavaScript JQuery 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": "\n19 Jan, 2022" }, { "code": null, "e": 133, "s": 28, "text": "The task is to make the close button using Pure CSS. There are two approaches that are discussed below. " }, { "code": null, "e": 392, "s": 133, "text": "Approach 1: Create a <div> inside another <div> which has alphabet ‘X’ in it which helps in displaying the close button. When the “click” event occurs on ‘X’, then perform the operation. In this example the outer <div> has been hidden when the event occurs. " }, { "code": null, "e": 445, "s": 392, "text": "Example: This example implements the above approach." }, { "code": null, "e": 452, "s": 447, "text": "html" }, { "code": "<!DOCTYPE HTML><html> <head> <style> .outer { background: green; height: 60px; display: block; } .button { margin-left: 93%; color: white; font-weight: bold; cursor: pointer; } </style></head> <body style=\"text-align:center;\"> <h1>GeeksForGeeks</h1> <p> Click on the cross to hide the element. </p> <div class=\"outer\"> <div class=\"button\">X</div> </div> <br> <p id=\"GFG\"></p> <script> var down = document.getElementById(\"GFG\"); var el = document.querySelector('.button'); el.addEventListener('click', function () { var el2 = document.querySelector('.outer'); el2.style.display = \"none\"; }); </script></body> </html>", "e": 1308, "s": 452, "text": null }, { "code": null, "e": 1318, "s": 1308, "text": "Output: " }, { "code": null, "e": 1598, "s": 1320, "text": "Approach 2: jQuery is used in this approach. Create a <div> inside another <div> that contains the alphabet ‘X’ to display the close button. When the “Click” event occurs on ‘X’ then perform the operation. In this example, the outer <div> has been hidden when the event occurs." }, { "code": null, "e": 1653, "s": 1600, "text": "Example: This example implements the above approach." }, { "code": null, "e": 1660, "s": 1655, "text": "html" }, { "code": "<!DOCTYPE HTML><html> <head> <style> .outer { background: green; height: 60px; display: block; } .button { margin-left: 93%; color: white; font-weight: bold; cursor: pointer; } </style> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js\"> </script></head> <body style=\"text-align:center;\"> <h1> GeeksForGeeks </h1> <p> Click on the cross to hide the element. </p> <div class=\"outer\"> <div class=\"button\">X</div> </div> <br> <p id=\"GFG\"> </p> <script> var down = document.getElementById(\"GFG\"); $('.button').on('click', function () { $('.outer').hide(); }); </script></body> </html>", "e": 2481, "s": 1660, "text": null }, { "code": null, "e": 2491, "s": 2481, "text": "Output: " }, { "code": null, "e": 2508, "s": 2493, "text": "varshagumber28" }, { "code": null, "e": 2517, "s": 2508, "text": "CSS-Misc" }, { "code": null, "e": 2529, "s": 2517, "text": "jQuery-Misc" }, { "code": null, "e": 2540, "s": 2529, "text": "JavaScript" }, { "code": null, "e": 2547, "s": 2540, "text": "JQuery" }, { "code": null, "e": 2564, "s": 2547, "text": "Web Technologies" } ]
How to Create a Transparent Activity in Android?
05 May, 2021 Many times we have to display a feature in our app where we have to use transparent activity inside our android app. In this article, we will take a look at creating a Transparent Activity in Android. We will be building a simple application in which we will be displaying a simple TextView inside a transparent activity. For creating a transparent activity we will be adding a different style to our activity. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. Step 1: Create a New Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. Step 2: Working with the activity_main.xml file Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <!--text view for displaying textview--> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="4dp" android:padding="10dp" android:text="Welcome to Geeks for Geeks" android:textAlignment="center" android:textColor="@color/purple_200" android:textSize="25sp" android:textStyle="bold" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout> Step 3: Adding a custom style for this activity Navigate to the app > res > values > themes.xml and add the below code to it. XML <resources xmlns:tools="http://schemas.android.com/tools"> <!-- Base application theme. --> <style name="Theme.TransparentActivity" parent="Theme.MaterialComponents.DayNight.DarkActionBar"> <!-- Primary brand color. --> <item name="colorPrimary">@color/purple_500</item> <item name="colorPrimaryVariant">@color/purple_700</item> <item name="colorOnPrimary">@color/white</item> <!-- Secondary brand color. --> <item name="colorSecondary">@color/teal_200</item> <item name="colorSecondaryVariant">@color/teal_700</item> <item name="colorOnSecondary">@color/black</item> <!-- Status bar color. --> <item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item> <!-- Customize your theme here. --> </style> <!--add below code in themes.xml file--> <!--below is the style for transparent activity and here we are using no action bar.--> <style name="Theme.AppCompat.Translucent" parent="Theme.AppCompat.NoActionBar"> <!--on below line we are setting background as transparent color--> <item name="android:background">@android:color/transparent</item> <!--on below line we are displaying the windowNotitle as true as we are not displaying our status bar--> <item name="android:windowNoTitle">true</item> <!--on below line we are setting our window background as transparent color--> <item name="android:windowBackground">@android:color/transparent</item> <!--on below line we are setting color background cache hint as null--> <item name="android:colorBackgroundCacheHint">@null</item> <!--on below line we are adding a window translucent as true--> <item name="android:windowIsTranslucent">true</item> <!--on below line we are adding a window animationstyle--> <item name="android:windowAnimationStyle">@android:style/Animation</item> </style> </resources> Step 4: Changing the theme in the AndroidManifest.xml file Navigate to the app > AndroidManifest.xml inside application tag in theme tag add this style in it. XML android:theme="@style/Theme.AppCompat.Translucent" Now run your app and see the output of the app. Output: Android Java Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Android SDK and it's Components Flutter - Custom Bottom Navigation Bar Retrofit with Kotlin Coroutine in Android How to Post Data to API using Retrofit in Android? Flutter - Stack Widget Arrays in Java Split() String method in Java with examples Arrays.sort() in Java with examples Object Oriented Programming (OOPs) Concept in Java Reverse a string in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n05 May, 2021" }, { "code": null, "e": 230, "s": 28, "text": "Many times we have to display a feature in our app where we have to use transparent activity inside our android app. In this article, we will take a look at creating a Transparent Activity in Android. " }, { "code": null, "e": 607, "s": 230, "text": "We will be building a simple application in which we will be displaying a simple TextView inside a transparent activity. For creating a transparent activity we will be adding a different style to our activity. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. " }, { "code": null, "e": 636, "s": 607, "text": "Step 1: Create a New Project" }, { "code": null, "e": 798, "s": 636, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language." }, { "code": null, "e": 846, "s": 798, "text": "Step 2: Working with the activity_main.xml file" }, { "code": null, "e": 989, "s": 846, "text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. " }, { "code": null, "e": 993, "s": 989, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <!--text view for displaying textview--> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_margin=\"4dp\" android:padding=\"10dp\" android:text=\"Welcome to Geeks for Geeks\" android:textAlignment=\"center\" android:textColor=\"@color/purple_200\" android:textSize=\"25sp\" android:textStyle=\"bold\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintLeft_toLeftOf=\"parent\" app:layout_constraintRight_toRightOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" /> </androidx.constraintlayout.widget.ConstraintLayout>", "e": 2034, "s": 993, "text": null }, { "code": null, "e": 2083, "s": 2034, "text": "Step 3: Adding a custom style for this activity " }, { "code": null, "e": 2162, "s": 2083, "text": "Navigate to the app > res > values > themes.xml and add the below code to it. " }, { "code": null, "e": 2166, "s": 2162, "text": "XML" }, { "code": "<resources xmlns:tools=\"http://schemas.android.com/tools\"> <!-- Base application theme. --> <style name=\"Theme.TransparentActivity\" parent=\"Theme.MaterialComponents.DayNight.DarkActionBar\"> <!-- Primary brand color. --> <item name=\"colorPrimary\">@color/purple_500</item> <item name=\"colorPrimaryVariant\">@color/purple_700</item> <item name=\"colorOnPrimary\">@color/white</item> <!-- Secondary brand color. --> <item name=\"colorSecondary\">@color/teal_200</item> <item name=\"colorSecondaryVariant\">@color/teal_700</item> <item name=\"colorOnSecondary\">@color/black</item> <!-- Status bar color. --> <item name=\"android:statusBarColor\" tools:targetApi=\"l\">?attr/colorPrimaryVariant</item> <!-- Customize your theme here. --> </style> <!--add below code in themes.xml file--> <!--below is the style for transparent activity and here we are using no action bar.--> <style name=\"Theme.AppCompat.Translucent\" parent=\"Theme.AppCompat.NoActionBar\"> <!--on below line we are setting background as transparent color--> <item name=\"android:background\">@android:color/transparent</item> <!--on below line we are displaying the windowNotitle as true as we are not displaying our status bar--> <item name=\"android:windowNoTitle\">true</item> <!--on below line we are setting our window background as transparent color--> <item name=\"android:windowBackground\">@android:color/transparent</item> <!--on below line we are setting color background cache hint as null--> <item name=\"android:colorBackgroundCacheHint\">@null</item> <!--on below line we are adding a window translucent as true--> <item name=\"android:windowIsTranslucent\">true</item> <!--on below line we are adding a window animationstyle--> <item name=\"android:windowAnimationStyle\">@android:style/Animation</item> </style> </resources>", "e": 4129, "s": 2166, "text": null }, { "code": null, "e": 4189, "s": 4129, "text": "Step 4: Changing the theme in the AndroidManifest.xml file " }, { "code": null, "e": 4290, "s": 4189, "text": "Navigate to the app > AndroidManifest.xml inside application tag in theme tag add this style in it. " }, { "code": null, "e": 4294, "s": 4290, "text": "XML" }, { "code": "android:theme=\"@style/Theme.AppCompat.Translucent\"", "e": 4345, "s": 4294, "text": null }, { "code": null, "e": 4394, "s": 4345, "text": "Now run your app and see the output of the app. " }, { "code": null, "e": 4402, "s": 4394, "text": "Output:" }, { "code": null, "e": 4410, "s": 4402, "text": "Android" }, { "code": null, "e": 4415, "s": 4410, "text": "Java" }, { "code": null, "e": 4420, "s": 4415, "text": "Java" }, { "code": null, "e": 4428, "s": 4420, "text": "Android" }, { "code": null, "e": 4526, "s": 4428, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4558, "s": 4526, "text": "Android SDK and it's Components" }, { "code": null, "e": 4597, "s": 4558, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 4639, "s": 4597, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 4690, "s": 4639, "text": "How to Post Data to API using Retrofit in Android?" }, { "code": null, "e": 4713, "s": 4690, "text": "Flutter - Stack Widget" }, { "code": null, "e": 4728, "s": 4713, "text": "Arrays in Java" }, { "code": null, "e": 4772, "s": 4728, "text": "Split() String method in Java with examples" }, { "code": null, "e": 4808, "s": 4772, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 4859, "s": 4808, "text": "Object Oriented Programming (OOPs) Concept in Java" } ]
Python Django | Google authentication and Fetching mails from scratch
30 Jun, 2020 Google Authentication and Fetching mails from scratch mean without using any module which has already set up this authentication process. We’ll be using Google API python client and oauth2client which is provided by Google. Sometimes, it really hard to implement this Google authentication with these libraries as there was no proper documentation available. But after completing this read, things will be clear completely. Now Let’s create Django 2.0 project and then implement Google authentication services and then extract mails. We are doing extract mail just to show how one can ask for permission after authenticating it. Step #1: Creating Django Project The first step is to create virtual environment and then install the dependencies. So We’ll be using venv: mkdir google-login && cd google-login python3.5 -m venv myvenv source myvenv/bin/activate This command will create one folder myvenv through which we just activated virtual environment. Now type pip freeze Then you must see no dependencies installed in it. Now first thing first let’s install Django: pip install Django==2.0.7 That is Django version which we used but feel free to use any other version. Now next step is to create one project, let’s name it gfglogin: django-admin startproject gfglogin . Since we are inside google-login directory that’s why we want django project to be on that present directory only so for that you need to use ‘ . ‘ at the end for present directory indication. Then create one app to separate logic from main project, so create one app called gfgauth: django-admin startapp gfgauth So overall terminal will look like: Since we created one app. Add that app name into settings.py in INSTALLED_APP list. Now we have Django project up running, so let’s migrate it first and then check if there is any error or not. python manage.py makemigrations python manage.py migrate python manage.py runserver So after migrating, one should be able to run the server and see the starting page of Django on that particular url. Step #2: Installing dependencies Since we have the project up running successfully, let’s install basic requirements. First, we need googleapiclient, this is needed because we have to create one resource object which helps to interact with the API. So to be precise we will make use of `build` method from it. To install: pip install google-api-python-client==1.6.4 Now the second module is oauth2client, this will make sure of all the authentication, credential, flows and many more complex thing so it is important to use this. pip install oauth2client==4.1.2 And at last, install jsonpickle, (just in case if it is not installed) because it will be used by oauth2client while making CredentalsField. pip install jsonpickle==0.9.6 So these are the only dependencies which we need. Now let’s step into the coding part and see how it works. Step #3: Creating models Use models to store the credentials which we get from an API, so there are only 2 main field which needed to take care of. First is id , which will be ForeignKey and second is credential which will be equal to CredentialsField. This field needs to be imported from oauth2client. So our models.py will look like: from django.contrib import adminfrom django.contrib.auth.models import Userfrom django.db import modelsfrom oauth2client.contrib.django_util.models import CredentialsField class CredentialsModel(models.Model): id = models.ForeignKey(User, primary_key = True, on_delete = models.CASCADE) credential = CredentialsField() task = models.CharField(max_length = 80, null = True) updated_time = models.CharField(max_length = 80, null = True) class CredentialsAdmin(admin.ModelAdmin): pass, Currently task and updated_time are simply extra fields added, hence can be removed. So this credential will hold the credential data in the database. Important guideline: When we import CredentialsField, then automatically __init__ method gets executed at back and if you’ll notice the code in path/google-login/myvenv/lib/python3.5/site-packages/oauth2client/contrib/django_util/__init__.py Line 233 They are importing urlresolvers so that they can make use of the reverse method from it. Now the problem is that this urlresolvers has been removed after Django 1.10 or Django 1.11, If you are working on Django 2.0 then it will give an error that urlresolvers cannot be found or not there. Now to overcome this problem we need to change 2 lines, first replace that import from django.core import urlresolvers to from django.urls import reverse And then replace Line 411 urlresolvers.reverse(...) to reverse(...) Now you should be able to run it successfully. After creating these models: python manage.py makemigrations python manage.py migrate Step #4: Creating Views Right now we have only 3 main views to handle requests. First is to show the home page, status, Google button so that we can send requests for Authentication. Second view will get triggered when the google button is clicked, means an AJAX request. Third will be to handle the return request from google so that we can accept the access_token from it and save it in our database. First, let’s do the Google authentication thing: So right now we need to specify the flow to the API that what permissions we need to ask, what is my secret key and redirect url. So to do that enter: FLOW = flow_from_clientsecrets( settings.GOOGLE_OAUTH2_CLIENT_SECRETS_JSON, scope='https://www.googleapis.com/auth/gmail.readonly', redirect_uri='http://127.0.0.1:8000/oauth2callback', prompt='consent') As you can notice settings.GOOGLE_OAUTH2_CLIENT_SECRETS_JSON, so go to settings.py file and type: GOOGLE_OAUTH2_CLIENT_SECRETS_JSON = 'client_secrets.json' This tells Django that where json file is present. We will later download this file. After specifying the flow, let’s start logic. Whenever we need to see if someone is authorized or not we first check our database whether that user credentials is already present or not. If not then we make requests to API url and then get credentials. def gmail_authenticate(request): storage = DjangoORMStorage(CredentialsModel, 'id', request.user, 'credential') credential = storage.get() if credential is None or credential.invalid: FLOW.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY, request.user) authorize_url = FLOW.step1_get_authorize_url() return HttpResponseRedirect(authorize_url) else: http = httplib2.Http() http = credential.authorize(http) service = build('gmail', 'v1', http = http) print('access_token = ', credential.access_token) status = True return render(request, 'index.html', {'status': status}) We use DjangoORMStorage (which is provided by oauth2client) so that we can store and retrieve credentials from Django datastore. So we need to pass 4 parameters for it. First is the model class which has CredientialsField inside it. Second is the unique id that has credentials means key name, third is the key value which has the credentials and last is the name of that CredentialsField which we specified in models.py. Then we get the value from storage and see if it is valid or not. If it is not valid then we create one user token and get one to authorize url, where we redirect the user to the Google login page. After redirecting user will fill up the form and once user is authorized by google then google will send data to callback url with access_token which we will do later. Now in case, if user credentials was already present then it will re-verify the credentials and give you back the access_token or sometimes the refreshed access_token in case if the previous one was expired. Now we need to handle the callback url, to do that: def auth_return(request): get_state = bytes(request.GET.get('state'), 'utf8') if not xsrfutil.validate_token(settings.SECRET_KEY, get_state, request.user): return HttpResponseBadRequest() credential = FLOW.step2_exchange(request.GET.get('code')) storage = DjangoORMStorage(CredentialsModel, 'id', request.user, 'credential') storage.put(credential) print("access_token: % s" % credential.access_token) return HttpResponseRedirect("/") Now inside callback url when we get one response from google then we capture the data and get state from it, state is nothing but the token which we generated by generateToken. So what we do is that we validate the token with secret_key, the token which we generated and with the user who generated it. These things get verified by xsrfutil.validate_token method which make sure that the token is not too old with the time and it was generated at given particular time only. If these things doesn’t work out well then it will give you error else you will go to the next step and share the code from callback response with google so that you can get the access_token. So this was 2 step verification and after successfully getting the credential we save it in Django datastore by using DjangoORMStorage because through that only we can fetch and store credential into CredentialsField. Once we will store it we can redirect the user to any particular page and that’s how you can get access_token. Now let’s create one home page which will tell whether the user is logged in or not. def home(request): status = True if not request.user.is_authenticated: return HttpResponseRedirect('admin') storage = DjangoORMStorage(CredentialsModel, 'id', request.user, 'credential') credential = storage.get() try: access_token = credential.access_token resp, cont = Http().request("https://www.googleapis.com/auth/gmail.readonly", headers ={'Host': 'www.googleapis.com', 'Authorization': access_token}) except: status = False print('Not Found') return render(request, 'index.html', {'status': status}) Right now we are assuming that the user is authenticated in Django, means that user is no more anonymous and has info saved in database. Now to have support for the anonymous user, we can remove the checks for credentials in database or create one temporary user. Coming back to home view, first we will check whether the user is authenticated or not, means that user is not anonymous, if yes then make him do log in else check for credentials first. If user has already logged in from Google then it will show Status as True else it will show False. Now coming to templates let’s create one. First go to root folder and create one folder named as ‘templates’, then inside that create index.html: {% load static %}<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <script src="{% static 'js/main.js' %}"></script> <title>Google Login</title></head><body> <div> <div> {% if not status %} <a href="/gmailAuthenticate" onclick="gmailAuthenticate()" title="Google">Google</a> {% else %} <p>Your are verified</p> {% endif %} </div> </div></body></html> Now this page is very much simplified so no css or styling is there, just one simple link to check. Now you will notice js file also. so again go to root folder and create one directory as static/js/ And inside js create one javascript file main.js: function gmailAuthenticate(){ $.ajax({ type: "GET", url: "ajax/gmailAuthenticate", // data: '', success: function (data) { console.log('Done') } });}; This js file was used to separate the logic from HTML file and also to make one AJAX call to Django. Now we have all the parts done for views. Step #5: Creating urls and basic settings In the main project urls means gfglogin/urls.py edit and put: from django.contrib import adminfrom django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('gfgauth.urls')),] Because we need to test gfgauth app working. Now inside gfgauth/urls.py type: from django.conf.urls import urlfrom . import views urlpatterns = [ url(r'^gmailAuthenticate', views.gmail_authenticate, name ='gmail_authenticate'), url(r'^oauth2callback', views.auth_return), url(r'^$', views.home, name ='home'),] As you can see, gmailAuthenticate is for AJAX calls, oauth2callback is for callback url and the last one is home page url. Now before running there are few settings which we haven’t talked about: In settings.py you need to edit: In TEMPLATES list add ‘templates’ inside DIRS list.At last of settings.py file add:STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) GOOGLE_OAUTH2_CLIENT_SECRETS_JSON = 'client_secrets.json' In TEMPLATES list add ‘templates’ inside DIRS list. At last of settings.py file add:STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) GOOGLE_OAUTH2_CLIENT_SECRETS_JSON = 'client_secrets.json' STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) GOOGLE_OAUTH2_CLIENT_SECRETS_JSON = 'client_secrets.json' So we just specified where templates and static files are present and most importantly where is google oauth2 client secret json file. Now we will download this file. Step #6: Generating Oauth2 Client secret file Head over to Google Developer Console page and create one project and name it anything you like. After creating it, head over to the project dashboard and click on the Navigation menu which is on the top left. Then click on API services and then credentials page. Click on create credentials (you might need to set product name before going ahead so do that first). Now select web application since we are using Django. After this specifies the name and then simply go to redirect URIs and over there type: http://127.0.0.1:8000/oauth2callback And then save it. You need not specify the Authorized Javascript origins so leave it blank for now. After saving it, you will be able to see all your credentials, just download the credentials, it will get saved in some random names so simply reformat the filename and type ‘client_secrets’ and make sure it is of json format. Then save it and paste it on Django project root folder (where manage.py is there). Step #7: Running it Now recheck if everything is correct or not. Make sure you have migrated it. Also before going ahead create one superuser so that you are no more anonymous: python3.5 manage.py createsuperuser Type all the necessary details and then do: python3.5 manage.py runserver And go to http://127.0.0.1:8000 You will see this: Which is perfectly fine, now type your superuser credentials over here and then you will be able to see the admin dashboard. Just avoid that and again go to http://127.0.0.1:8000 Now you should be able to see the Google link, now click on it and you will see: Now as you can see it is saying Sign in to continue to GFG, here GFG is my Project name. So it is working fine. Now enter your credentials and after submitting you will see: Since we are requesting for mails permission that’s why it is asking the user to allow it. In case if it is showing error then in Google console you might need to activate Gmail API into your project. Now once you will allow it you will get the credentials and get saved inside your database. In case if the user clicks on Cancel then you will need to write a few more codes to handle such flow. Now in case if you allowed it then you will be able to see the access_token on your console/database. After getting access_token you can make use of this to fetch user email and all other stuff. See full code in this repository here. nidhi_biet Python Django Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n30 Jun, 2020" }, { "code": null, "e": 476, "s": 52, "text": "Google Authentication and Fetching mails from scratch mean without using any module which has already set up this authentication process. We’ll be using Google API python client and oauth2client which is provided by Google. Sometimes, it really hard to implement this Google authentication with these libraries as there was no proper documentation available. But after completing this read, things will be clear completely." }, { "code": null, "e": 681, "s": 476, "text": "Now Let’s create Django 2.0 project and then implement Google authentication services and then extract mails. We are doing extract mail just to show how one can ask for permission after authenticating it." }, { "code": null, "e": 714, "s": 681, "text": "Step #1: Creating Django Project" }, { "code": null, "e": 821, "s": 714, "text": "The first step is to create virtual environment and then install the dependencies. So We’ll be using venv:" }, { "code": null, "e": 913, "s": 821, "text": "mkdir google-login && cd google-login\n\npython3.5 -m venv myvenv\nsource myvenv/bin/activate\n" }, { "code": null, "e": 1018, "s": 913, "text": "This command will create one folder myvenv through which we just activated virtual environment. Now type" }, { "code": null, "e": 1029, "s": 1018, "text": "pip freeze" }, { "code": null, "e": 1124, "s": 1029, "text": "Then you must see no dependencies installed in it. Now first thing first let’s install Django:" }, { "code": null, "e": 1150, "s": 1124, "text": "pip install Django==2.0.7" }, { "code": null, "e": 1291, "s": 1150, "text": "That is Django version which we used but feel free to use any other version. Now next step is to create one project, let’s name it gfglogin:" }, { "code": null, "e": 1328, "s": 1291, "text": "django-admin startproject gfglogin ." }, { "code": null, "e": 1612, "s": 1328, "text": "Since we are inside google-login directory that’s why we want django project to be on that present directory only so for that you need to use ‘ . ‘ at the end for present directory indication. Then create one app to separate logic from main project, so create one app called gfgauth:" }, { "code": null, "e": 1642, "s": 1612, "text": "django-admin startapp gfgauth" }, { "code": null, "e": 1678, "s": 1642, "text": "So overall terminal will look like:" }, { "code": null, "e": 1872, "s": 1678, "text": "Since we created one app. Add that app name into settings.py in INSTALLED_APP list. Now we have Django project up running, so let’s migrate it first and then check if there is any error or not." }, { "code": null, "e": 1956, "s": 1872, "text": "python manage.py makemigrations\npython manage.py migrate\npython manage.py runserver" }, { "code": null, "e": 2106, "s": 1956, "text": "So after migrating, one should be able to run the server and see the starting page of Django on that particular url. Step #2: Installing dependencies" }, { "code": null, "e": 2383, "s": 2106, "text": "Since we have the project up running successfully, let’s install basic requirements. First, we need googleapiclient, this is needed because we have to create one resource object which helps to interact with the API. So to be precise we will make use of `build` method from it." }, { "code": null, "e": 2395, "s": 2383, "text": "To install:" }, { "code": null, "e": 2439, "s": 2395, "text": "pip install google-api-python-client==1.6.4" }, { "code": null, "e": 2603, "s": 2439, "text": "Now the second module is oauth2client, this will make sure of all the authentication, credential, flows and many more complex thing so it is important to use this." }, { "code": null, "e": 2635, "s": 2603, "text": "pip install oauth2client==4.1.2" }, { "code": null, "e": 2776, "s": 2635, "text": "And at last, install jsonpickle, (just in case if it is not installed) because it will be used by oauth2client while making CredentalsField." }, { "code": null, "e": 2806, "s": 2776, "text": "pip install jsonpickle==0.9.6" }, { "code": null, "e": 2939, "s": 2806, "text": "So these are the only dependencies which we need. Now let’s step into the coding part and see how it works. Step #3: Creating models" }, { "code": null, "e": 3251, "s": 2939, "text": "Use models to store the credentials which we get from an API, so there are only 2 main field which needed to take care of. First is id , which will be ForeignKey and second is credential which will be equal to CredentialsField. This field needs to be imported from oauth2client. So our models.py will look like:" }, { "code": "from django.contrib import adminfrom django.contrib.auth.models import Userfrom django.db import modelsfrom oauth2client.contrib.django_util.models import CredentialsField class CredentialsModel(models.Model): id = models.ForeignKey(User, primary_key = True, on_delete = models.CASCADE) credential = CredentialsField() task = models.CharField(max_length = 80, null = True) updated_time = models.CharField(max_length = 80, null = True) class CredentialsAdmin(admin.ModelAdmin): pass,", "e": 3755, "s": 3251, "text": null }, { "code": null, "e": 3906, "s": 3755, "text": "Currently task and updated_time are simply extra fields added, hence can be removed. So this credential will hold the credential data in the database." }, { "code": null, "e": 3927, "s": 3906, "text": "Important guideline:" }, { "code": null, "e": 4157, "s": 3927, "text": "When we import CredentialsField, then automatically __init__ method gets executed at back and if you’ll notice the code in path/google-login/myvenv/lib/python3.5/site-packages/oauth2client/contrib/django_util/__init__.py Line 233" }, { "code": null, "e": 4447, "s": 4157, "text": "They are importing urlresolvers so that they can make use of the reverse method from it. Now the problem is that this urlresolvers has been removed after Django 1.10 or Django 1.11, If you are working on Django 2.0 then it will give an error that urlresolvers cannot be found or not there." }, { "code": null, "e": 4601, "s": 4447, "text": "Now to overcome this problem we need to change 2 lines, first replace that import from django.core import urlresolvers to from django.urls import reverse" }, { "code": null, "e": 4669, "s": 4601, "text": "And then replace Line 411 urlresolvers.reverse(...) to reverse(...)" }, { "code": null, "e": 4716, "s": 4669, "text": "Now you should be able to run it successfully." }, { "code": null, "e": 4745, "s": 4716, "text": "After creating these models:" }, { "code": null, "e": 4803, "s": 4745, "text": "python manage.py makemigrations\npython manage.py migrate\n" }, { "code": null, "e": 4828, "s": 4803, "text": " Step #4: Creating Views" }, { "code": null, "e": 5207, "s": 4828, "text": "Right now we have only 3 main views to handle requests. First is to show the home page, status, Google button so that we can send requests for Authentication. Second view will get triggered when the google button is clicked, means an AJAX request. Third will be to handle the return request from google so that we can accept the access_token from it and save it in our database." }, { "code": null, "e": 5256, "s": 5207, "text": "First, let’s do the Google authentication thing:" }, { "code": null, "e": 5407, "s": 5256, "text": "So right now we need to specify the flow to the API that what permissions we need to ask, what is my secret key and redirect url. So to do that enter:" }, { "code": null, "e": 5627, "s": 5407, "text": "FLOW = flow_from_clientsecrets(\n settings.GOOGLE_OAUTH2_CLIENT_SECRETS_JSON,\n scope='https://www.googleapis.com/auth/gmail.readonly',\n redirect_uri='http://127.0.0.1:8000/oauth2callback',\n prompt='consent')\n" }, { "code": null, "e": 5725, "s": 5627, "text": "As you can notice settings.GOOGLE_OAUTH2_CLIENT_SECRETS_JSON, so go to settings.py file and type:" }, { "code": null, "e": 5783, "s": 5725, "text": "GOOGLE_OAUTH2_CLIENT_SECRETS_JSON = 'client_secrets.json'" }, { "code": null, "e": 5914, "s": 5783, "text": "This tells Django that where json file is present. We will later download this file. After specifying the flow, let’s start logic." }, { "code": null, "e": 6121, "s": 5914, "text": "Whenever we need to see if someone is authorized or not we first check our database whether that user credentials is already present or not. If not then we make requests to API url and then get credentials." }, { "code": "def gmail_authenticate(request): storage = DjangoORMStorage(CredentialsModel, 'id', request.user, 'credential') credential = storage.get() if credential is None or credential.invalid: FLOW.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY, request.user) authorize_url = FLOW.step1_get_authorize_url() return HttpResponseRedirect(authorize_url) else: http = httplib2.Http() http = credential.authorize(http) service = build('gmail', 'v1', http = http) print('access_token = ', credential.access_token) status = True return render(request, 'index.html', {'status': status})", "e": 6845, "s": 6121, "text": null }, { "code": null, "e": 7267, "s": 6845, "text": "We use DjangoORMStorage (which is provided by oauth2client) so that we can store and retrieve credentials from Django datastore. So we need to pass 4 parameters for it. First is the model class which has CredientialsField inside it. Second is the unique id that has credentials means key name, third is the key value which has the credentials and last is the name of that CredentialsField which we specified in models.py." }, { "code": null, "e": 7841, "s": 7267, "text": "Then we get the value from storage and see if it is valid or not. If it is not valid then we create one user token and get one to authorize url, where we redirect the user to the Google login page. After redirecting user will fill up the form and once user is authorized by google then google will send data to callback url with access_token which we will do later. Now in case, if user credentials was already present then it will re-verify the credentials and give you back the access_token or sometimes the refreshed access_token in case if the previous one was expired." }, { "code": null, "e": 7893, "s": 7841, "text": "Now we need to handle the callback url, to do that:" }, { "code": "def auth_return(request): get_state = bytes(request.GET.get('state'), 'utf8') if not xsrfutil.validate_token(settings.SECRET_KEY, get_state, request.user): return HttpResponseBadRequest() credential = FLOW.step2_exchange(request.GET.get('code')) storage = DjangoORMStorage(CredentialsModel, 'id', request.user, 'credential') storage.put(credential) print(\"access_token: % s\" % credential.access_token) return HttpResponseRedirect(\"/\")", "e": 8394, "s": 7893, "text": null }, { "code": null, "e": 9061, "s": 8394, "text": "Now inside callback url when we get one response from google then we capture the data and get state from it, state is nothing but the token which we generated by generateToken. So what we do is that we validate the token with secret_key, the token which we generated and with the user who generated it. These things get verified by xsrfutil.validate_token method which make sure that the token is not too old with the time and it was generated at given particular time only. If these things doesn’t work out well then it will give you error else you will go to the next step and share the code from callback response with google so that you can get the access_token." }, { "code": null, "e": 9390, "s": 9061, "text": "So this was 2 step verification and after successfully getting the credential we save it in Django datastore by using DjangoORMStorage because through that only we can fetch and store credential into CredentialsField. Once we will store it we can redirect the user to any particular page and that’s how you can get access_token." }, { "code": null, "e": 9475, "s": 9390, "text": "Now let’s create one home page which will tell whether the user is logged in or not." }, { "code": "def home(request): status = True if not request.user.is_authenticated: return HttpResponseRedirect('admin') storage = DjangoORMStorage(CredentialsModel, 'id', request.user, 'credential') credential = storage.get() try: access_token = credential.access_token resp, cont = Http().request(\"https://www.googleapis.com/auth/gmail.readonly\", headers ={'Host': 'www.googleapis.com', 'Authorization': access_token}) except: status = False print('Not Found') return render(request, 'index.html', {'status': status})", "e": 10126, "s": 9475, "text": null }, { "code": null, "e": 10390, "s": 10126, "text": "Right now we are assuming that the user is authenticated in Django, means that user is no more anonymous and has info saved in database. Now to have support for the anonymous user, we can remove the checks for credentials in database or create one temporary user." }, { "code": null, "e": 10677, "s": 10390, "text": "Coming back to home view, first we will check whether the user is authenticated or not, means that user is not anonymous, if yes then make him do log in else check for credentials first. If user has already logged in from Google then it will show Status as True else it will show False." }, { "code": null, "e": 10823, "s": 10677, "text": "Now coming to templates let’s create one. First go to root folder and create one folder named as ‘templates’, then inside that create index.html:" }, { "code": "{% load static %}<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <script src=\"{% static 'js/main.js' %}\"></script> <title>Google Login</title></head><body> <div> <div> {% if not status %} <a href=\"/gmailAuthenticate\" onclick=\"gmailAuthenticate()\" title=\"Google\">Google</a> {% else %} <p>Your are verified</p> {% endif %} </div> </div></body></html>", "e": 11247, "s": 10823, "text": null }, { "code": null, "e": 11447, "s": 11247, "text": "Now this page is very much simplified so no css or styling is there, just one simple link to check. Now you will notice js file also. so again go to root folder and create one directory as static/js/" }, { "code": null, "e": 11497, "s": 11447, "text": "And inside js create one javascript file main.js:" }, { "code": "function gmailAuthenticate(){ $.ajax({ type: \"GET\", url: \"ajax/gmailAuthenticate\", // data: '', success: function (data) { console.log('Done') } });};", "e": 11700, "s": 11497, "text": null }, { "code": null, "e": 11885, "s": 11700, "text": "This js file was used to separate the logic from HTML file and also to make one AJAX call to Django. Now we have all the parts done for views. Step #5: Creating urls and basic settings" }, { "code": null, "e": 11947, "s": 11885, "text": "In the main project urls means gfglogin/urls.py edit and put:" }, { "code": "from django.contrib import adminfrom django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('gfgauth.urls')),]", "e": 12109, "s": 11947, "text": null }, { "code": null, "e": 12187, "s": 12109, "text": "Because we need to test gfgauth app working. Now inside gfgauth/urls.py type:" }, { "code": "from django.conf.urls import urlfrom . import views urlpatterns = [ url(r'^gmailAuthenticate', views.gmail_authenticate, name ='gmail_authenticate'), url(r'^oauth2callback', views.auth_return), url(r'^$', views.home, name ='home'),]", "e": 12430, "s": 12187, "text": null }, { "code": null, "e": 12626, "s": 12430, "text": "As you can see, gmailAuthenticate is for AJAX calls, oauth2callback is for callback url and the last one is home page url. Now before running there are few settings which we haven’t talked about:" }, { "code": null, "e": 12659, "s": 12626, "text": "In settings.py you need to edit:" }, { "code": null, "e": 12887, "s": 12659, "text": "In TEMPLATES list add ‘templates’ inside DIRS list.At last of settings.py file add:STATIC_URL = '/static/'\nSTATICFILES_DIRS = (\n os.path.join(BASE_DIR, 'static'),\n)\n\nGOOGLE_OAUTH2_CLIENT_SECRETS_JSON = 'client_secrets.json'\n" }, { "code": null, "e": 12939, "s": 12887, "text": "In TEMPLATES list add ‘templates’ inside DIRS list." }, { "code": null, "e": 13116, "s": 12939, "text": "At last of settings.py file add:STATIC_URL = '/static/'\nSTATICFILES_DIRS = (\n os.path.join(BASE_DIR, 'static'),\n)\n\nGOOGLE_OAUTH2_CLIENT_SECRETS_JSON = 'client_secrets.json'\n" }, { "code": null, "e": 13261, "s": 13116, "text": "STATIC_URL = '/static/'\nSTATICFILES_DIRS = (\n os.path.join(BASE_DIR, 'static'),\n)\n\nGOOGLE_OAUTH2_CLIENT_SECRETS_JSON = 'client_secrets.json'\n" }, { "code": null, "e": 13474, "s": 13261, "text": "So we just specified where templates and static files are present and most importantly where is google oauth2 client secret json file. Now we will download this file. Step #6: Generating Oauth2 Client secret file" }, { "code": null, "e": 13981, "s": 13474, "text": "Head over to Google Developer Console page and create one project and name it anything you like. After creating it, head over to the project dashboard and click on the Navigation menu which is on the top left. Then click on API services and then credentials page. Click on create credentials (you might need to set product name before going ahead so do that first). Now select web application since we are using Django. After this specifies the name and then simply go to redirect URIs and over there type:" }, { "code": null, "e": 14019, "s": 13981, "text": "http://127.0.0.1:8000/oauth2callback\n" }, { "code": null, "e": 14450, "s": 14019, "text": "And then save it. You need not specify the Authorized Javascript origins so leave it blank for now. After saving it, you will be able to see all your credentials, just download the credentials, it will get saved in some random names so simply reformat the filename and type ‘client_secrets’ and make sure it is of json format. Then save it and paste it on Django project root folder (where manage.py is there). Step #7: Running it" }, { "code": null, "e": 14607, "s": 14450, "text": "Now recheck if everything is correct or not. Make sure you have migrated it. Also before going ahead create one superuser so that you are no more anonymous:" }, { "code": null, "e": 14643, "s": 14607, "text": "python3.5 manage.py createsuperuser" }, { "code": null, "e": 14687, "s": 14643, "text": "Type all the necessary details and then do:" }, { "code": null, "e": 14717, "s": 14687, "text": "python3.5 manage.py runserver" }, { "code": null, "e": 14749, "s": 14717, "text": "And go to http://127.0.0.1:8000" }, { "code": null, "e": 14768, "s": 14749, "text": "You will see this:" }, { "code": null, "e": 14947, "s": 14768, "text": "Which is perfectly fine, now type your superuser credentials over here and then you will be able to see the admin dashboard. Just avoid that and again go to http://127.0.0.1:8000" }, { "code": null, "e": 15028, "s": 14947, "text": "Now you should be able to see the Google link, now click on it and you will see:" }, { "code": null, "e": 15202, "s": 15028, "text": "Now as you can see it is saying Sign in to continue to GFG, here GFG is my Project name. So it is working fine. Now enter your credentials and after submitting you will see:" }, { "code": null, "e": 15598, "s": 15202, "text": "Since we are requesting for mails permission that’s why it is asking the user to allow it. In case if it is showing error then in Google console you might need to activate Gmail API into your project. Now once you will allow it you will get the credentials and get saved inside your database. In case if the user clicks on Cancel then you will need to write a few more codes to handle such flow." }, { "code": null, "e": 15793, "s": 15598, "text": "Now in case if you allowed it then you will be able to see the access_token on your console/database. After getting access_token you can make use of this to fetch user email and all other stuff." }, { "code": null, "e": 15832, "s": 15793, "text": "See full code in this repository here." }, { "code": null, "e": 15843, "s": 15832, "text": "nidhi_biet" }, { "code": null, "e": 15857, "s": 15843, "text": "Python Django" }, { "code": null, "e": 15864, "s": 15857, "text": "Python" }, { "code": null, "e": 15880, "s": 15864, "text": "Python Programs" } ]
Python sympy | Matrix.eigenvects() method
26 Aug, 2019 With the help of sympy.Matrix().eigenvects() method, we can find the Eigenvectors of a matrix. eigenvects() method returns a list of tuples of the form (eigenvalue:algebraic multiplicity, [eigenvectors]). Syntax: Matrix().eigenvects() Returns: Returns a list of tuples of the form (eigenvalue:algebraic multiplicity, [eigenvectors]). Example #1: # import sympy from sympy import * M = Matrix([[3, -2, 4, -2], [5, 3, -3, -2], [5, -2, 2, -2], [5, -2, -3, 3]]) print("Matrix : {} ".format(M)) # Use sympy.eigenvects() method M_eigenvects = M.eigenvects() print("Eigenvects of a matrix : {}".format(M_eigenvects)) Output: Matrix : Matrix([[3, -2, 4, -2], [5, 3, -3, -2], [5, -2, 2, -2], [5, -2, -3, 3]])Eigenvects of a matrix : [(-2, 1, [Matrix([[0],[1],[1],[1]])]), (3, 1, [Matrix([[1],[1],[1],[1]])]), (5, 2, [Matrix([[1],[1],[1],[0]]), Matrix([[ 0],[-1],[ 0],[ 1]])])] Example #2: # import sympy from sympy import * M = Matrix([[1, -3, 3], [3, -5, 3], [6, -6, 4]]) print("Matrix : {} ".format(M)) # Use sympy.eigenvects() method M_eigenvects = M.eigenvects() print("Eigenvects of a matrix : {}".format(M_eigenvects)) Output: Matrix : Matrix([[1, -3, 3], [3, -5, 3], [6, -6, 4]])Eigenvects of a matrix : [(-2, 2, [Matrix([[1],[1],[0]]), Matrix([[-1],[ 0],[ 1]])]), (4, 1, [Matrix([[1/2],[1/2],[ 1]])])] SymPy Python 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": 233, "s": 28, "text": "With the help of sympy.Matrix().eigenvects() method, we can find the Eigenvectors of a matrix. eigenvects() method returns a list of tuples of the form (eigenvalue:algebraic multiplicity, [eigenvectors])." }, { "code": null, "e": 263, "s": 233, "text": "Syntax: Matrix().eigenvects()" }, { "code": null, "e": 362, "s": 263, "text": "Returns: Returns a list of tuples of the form (eigenvalue:algebraic multiplicity, [eigenvectors])." }, { "code": null, "e": 374, "s": 362, "text": "Example #1:" }, { "code": "# import sympy from sympy import * M = Matrix([[3, -2, 4, -2], [5, 3, -3, -2], [5, -2, 2, -2], [5, -2, -3, 3]]) print(\"Matrix : {} \".format(M)) # Use sympy.eigenvects() method M_eigenvects = M.eigenvects() print(\"Eigenvects of a matrix : {}\".format(M_eigenvects)) ", "e": 748, "s": 374, "text": null }, { "code": null, "e": 756, "s": 748, "text": "Output:" }, { "code": null, "e": 1006, "s": 756, "text": "Matrix : Matrix([[3, -2, 4, -2], [5, 3, -3, -2], [5, -2, 2, -2], [5, -2, -3, 3]])Eigenvects of a matrix : [(-2, 1, [Matrix([[0],[1],[1],[1]])]), (3, 1, [Matrix([[1],[1],[1],[1]])]), (5, 2, [Matrix([[1],[1],[1],[0]]), Matrix([[ 0],[-1],[ 0],[ 1]])])]" }, { "code": null, "e": 1018, "s": 1006, "text": "Example #2:" }, { "code": "# import sympy from sympy import * M = Matrix([[1, -3, 3], [3, -5, 3], [6, -6, 4]]) print(\"Matrix : {} \".format(M)) # Use sympy.eigenvects() method M_eigenvects = M.eigenvects() print(\"Eigenvects of a matrix : {}\".format(M_eigenvects))", "e": 1263, "s": 1018, "text": null }, { "code": null, "e": 1271, "s": 1263, "text": "Output:" }, { "code": null, "e": 1448, "s": 1271, "text": "Matrix : Matrix([[1, -3, 3], [3, -5, 3], [6, -6, 4]])Eigenvects of a matrix : [(-2, 2, [Matrix([[1],[1],[0]]), Matrix([[-1],[ 0],[ 1]])]), (4, 1, [Matrix([[1/2],[1/2],[ 1]])])]" }, { "code": null, "e": 1454, "s": 1448, "text": "SymPy" }, { "code": null, "e": 1461, "s": 1454, "text": "Python" } ]
MySQL query to decrease the value of a specific record to zero?
Use SET to decrease the value and WHERE to set the condition for a specific record to be 0. Let us first create a table − mysql> create table DemoTable ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, Number int ); Query OK, 0 rows affected (0.54 sec) Insert some records in the table using insert command &minus mysql> insert into DemoTable(Number) values(10); Query OK, 1 row affected (0.20 sec) mysql> insert into DemoTable(Number) values(20); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable(Number) values(1); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable(Number) values(0); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable(Number) values(-1); Query OK, 1 row affected (0.39 sec) Display all records from the table using select statement − mysql> select *from DemoTable; This will produce the following output − +----+--------+ | Id | Number | +----+--------+ | 1 | 10 | | 2 | 20 | | 3 | 1 | | 4 | 0 | | 5 | -1 | +----+--------+ 5 rows in set (0.00 sec) Following is the query to decrease the value to 0 − mysql> update DemoTable set Number = Number-1 where Id = 3 AND Number > 0; Query OK, 1 row affected (0.20 sec) Rows matched: 1 Changed: 1 Warnings: 0 Let us display table records once again − mysql> select *from DemoTable; This will produce the following output. Now, record with Id 3 is 0 since we decremented it by 1 − +----+--------+ | Id | Number | +----+--------+ | 1 | 10 | | 2 | 20 | | 3 | 0 | | 4 | 0 | | 5 | -1 | +----+--------+ 5 rows in set (0.00 sec)
[ { "code": null, "e": 1184, "s": 1062, "text": "Use SET to decrease the value and WHERE to set the condition for a specific record to be 0. Let us first create a table −" }, { "code": null, "e": 1320, "s": 1184, "text": "mysql> create table DemoTable\n (\n Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, Number int\n );\nQuery OK, 0 rows affected (0.54 sec)" }, { "code": null, "e": 1381, "s": 1320, "text": "Insert some records in the table using insert command &minus" }, { "code": null, "e": 1808, "s": 1381, "text": "mysql> insert into DemoTable(Number) values(10);\nQuery OK, 1 row affected (0.20 sec)\n\nmysql> insert into DemoTable(Number) values(20);\nQuery OK, 1 row affected (0.14 sec)\n\nmysql> insert into DemoTable(Number) values(1);\nQuery OK, 1 row affected (0.10 sec)\n\nmysql> insert into DemoTable(Number) values(0);\nQuery OK, 1 row affected (0.12 sec)\n\nmysql> insert into DemoTable(Number) values(-1);\nQuery OK, 1 row affected (0.39 sec)" }, { "code": null, "e": 1868, "s": 1808, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1899, "s": 1868, "text": "mysql> select *from DemoTable;" }, { "code": null, "e": 1940, "s": 1899, "text": "This will produce the following output −" }, { "code": null, "e": 2109, "s": 1940, "text": "+----+--------+\n| Id | Number |\n+----+--------+\n| 1 | 10 |\n| 2 | 20 |\n| 3 | 1 |\n| 4 | 0 |\n| 5 | -1 |\n+----+--------+\n5 rows in set (0.00 sec)" }, { "code": null, "e": 2161, "s": 2109, "text": "Following is the query to decrease the value to 0 −" }, { "code": null, "e": 2317, "s": 2161, "text": "mysql> update DemoTable\n set Number = Number-1\n where Id = 3 AND Number > 0;\nQuery OK, 1 row affected (0.20 sec)\nRows matched: 1 Changed: 1 Warnings: 0" }, { "code": null, "e": 2359, "s": 2317, "text": "Let us display table records once again −" }, { "code": null, "e": 2390, "s": 2359, "text": "mysql> select *from DemoTable;" }, { "code": null, "e": 2488, "s": 2390, "text": "This will produce the following output. Now, record with Id 3 is 0 since we decremented it by 1 −" }, { "code": null, "e": 2657, "s": 2488, "text": "+----+--------+\n| Id | Number |\n+----+--------+\n| 1 | 10 |\n| 2 | 20 |\n| 3 | 0 |\n| 4 | 0 |\n| 5 | -1 |\n+----+--------+\n5 rows in set (0.00 sec)" } ]
How To Analyze Survey Data With Python | by Benedikt Droste | Towards Data Science
If you work in market research, you probably also have to deal with survey data. Often these are available as SAV or SPSS files. SPSS is great for statistic analysis of survey data because variables, variable labels, values, and value labels are all integrated in one dataset. With SPSS, categorized variables are easy to analyze: Unfortunately, SPSS is slow on larger data sets and the macro system for automation is not intuitive and offers just a few options compared to Python. Therefore I would like to show you how to analyze survey data with Python. First of all, we install the pyreadstat module, which allows us to import SPSS files as DataFrames pip install pyreadstat . If you want to install it manually, you can download the package here: pypi.org Now we import the module into a Jupyter notebook and load the dataset: import numpy as npimport pandas as pdimport pyreadstatdf, meta = pyreadstat.read_sav('...path\\Surveydata.sav')df.head(5) Let’s take a look at the DataFrame: We can not read out much from this, because we do not know what the variables and the numerical information mean. The meta container includes all other data, such as the labels and value labels. With meta.column_labels we can print the variable labels: For the column Sat_overall the matching label is “How satisfied are you overall?”. With a few variables, you can easily assign it from the list. If we had hundreds of variables, the whole thing would be confusing. Therefore, we first create a dictionary so that we can selectively display the correct label for a column if necessary. meta_dict = dict(zip(meta.column_names, meta.column_labels)) With meta_dict['Sat_overall'] we now get the matching label. In surveys, we are often interested in the percentage of respondents who chose a specific answer category: df['Age'].value_counts(normalize=True).sort_index() From the output we can only read that 29% voted for category 1, 33% for category 2 and almost 38% for category 3. However, in the dictionary meta.value_labels we have all value labels: df['Age'].map(meta.variable_value_labels['Age']).value_counts(normalize=True) That looks better! 38% of the respondents are over 50, 33% are between 30 and 50 and the rest is under 30. I personally prefer sorting according to the order of the value labels. Currently, the values ​​are simply sorted by the size of the proportions: df['Age'].map(meta.variable_value_labels['Age']).value_counts(normalize=True).loc[meta.variable_value_labels['Age'].values()] Perfect! That’s what we need and the result pretty much matches the output of an SPSS “Frequency”. Frequently, survey data is evaluated according to sociodemographic characteristics. For example, how does satisfaction differ by age group? For this, we can simply use the crosstab function: pd.crosstab(df['Sat_overall'], df['Age'], dropna=True, normalize='columns') Again, we cannot do much with the output, so let’s first map the value labels: pd.crosstab(df['Sat_overall'].\ map(meta.variable_value_labels['Sat_overall']), \ df['Age'].map(meta.variable_value_labels['Age']), \ dropna=True, normalize='columns'). \ loc[meta.variable_value_labels['Sat_overall'].values()]. \ loc[:,meta.variable_value_labels['Age'].values()]*100 Now, we are able to interpret the output. For those over 50, there are the most completely satisfied customers. By contrast, among the under 30s there are the most dissatisfied customers. With the .loc function we can again specify the order here. In surveys, it is often found out afterwards that the distribution of sociodemographic characteristics does not correspond to the distribution in the customer base. At the beginning we saw that the three groups are almost equally distributed. However, we know that 50% of our customers are under 30, 25% are between 30 and 50 and the rest is over 50. Therefore, we weight our data to reflect this distribution: weight = np.NaNdf.loc[(df['Age'] == 1), 'weight'] = 0.5/(67/230)df.loc[(df['Age'] == 2), 'weight'] = 0.25/(76/230)df.loc[(df['Age'] == 3), 'weight'] = 0.25/(87/230) But how can we now take this weight into account in our calculations? For the frequency distribution, we write a small helper function: def weighted_frequency(x,y): a = pd.Series(df[[x,y]].groupby(x).sum()[y])/df[y].sum() b = a.index.map(meta.variable_value_labels[x]) c = a.values df_temp = pd.DataFrame({'Labels': b, 'Frequency': c}) return df_temp As a result, we get a DataFrame with the respective labels (in the numerical order from small to large) and the corresponding percentage frequency: weighted_frequency('Age','weight') The weighted distribution now corresponds to our customer structure. Let’s take another look at the satisfaction distribution: weighted_frequency('Sat_overall','weight') We see that in the weighted distribution, for example, more customers are dissatisfied. We would have underestimated the oddness in our customer base if we had not weighted. With crosstabs a weight can be easily integrated: pd.crosstab(df['Sat_overall']. \ map(meta.variable_value_labels['Sat_overall']), \ df['Age'].map(meta.variable_value_labels['Age']), df.weight, aggfunc = sum, dropna=True, \ normalize='columns'). \ loc[meta.variable_value_labels['Sat_overall'].values()]. \ loc[:,meta.variable_value_labels['Age'].values()]*100 All we have to do is adding the parameters for the weight (e.g. df.weight) and the function aggfunc=sum. In this example, the weighted corresponds to the unweighted distribution because the ratio of cases within a group does not change. In a first step, we have installed pyreadstat, a module with which we can read sav-files into Python and process them further. After that, we looked at how labels and value labels can be assigned and how the analyzes can be presented in a way that is easy to interpret. We saw that Python handles categorized data very well and that it is easy to use. Respository:https://github.com/bd317/surveydata_with_pythonNotebook:https://github.com/bd317/surveydata_with_python/blob/master/Github_Survey_Data_Upload.ipynbSPSS-Dataset:https://github.com/bd317/surveydata_with_python/blob/master/Surveydata.sav If you enjoy Medium and Towards Data Science and didn’t sign up yet, feel free to use my referral link to join the community.
[ { "code": null, "e": 503, "s": 172, "text": "If you work in market research, you probably also have to deal with survey data. Often these are available as SAV or SPSS files. SPSS is great for statistic analysis of survey data because variables, variable labels, values, and value labels are all integrated in one dataset. With SPSS, categorized variables are easy to analyze:" }, { "code": null, "e": 729, "s": 503, "text": "Unfortunately, SPSS is slow on larger data sets and the macro system for automation is not intuitive and offers just a few options compared to Python. Therefore I would like to show you how to analyze survey data with Python." }, { "code": null, "e": 924, "s": 729, "text": "First of all, we install the pyreadstat module, which allows us to import SPSS files as DataFrames pip install pyreadstat . If you want to install it manually, you can download the package here:" }, { "code": null, "e": 933, "s": 924, "text": "pypi.org" }, { "code": null, "e": 1004, "s": 933, "text": "Now we import the module into a Jupyter notebook and load the dataset:" }, { "code": null, "e": 1126, "s": 1004, "text": "import numpy as npimport pandas as pdimport pyreadstatdf, meta = pyreadstat.read_sav('...path\\\\Surveydata.sav')df.head(5)" }, { "code": null, "e": 1162, "s": 1126, "text": "Let’s take a look at the DataFrame:" }, { "code": null, "e": 1415, "s": 1162, "text": "We can not read out much from this, because we do not know what the variables and the numerical information mean. The meta container includes all other data, such as the labels and value labels. With meta.column_labels we can print the variable labels:" }, { "code": null, "e": 1749, "s": 1415, "text": "For the column Sat_overall the matching label is “How satisfied are you overall?”. With a few variables, you can easily assign it from the list. If we had hundreds of variables, the whole thing would be confusing. Therefore, we first create a dictionary so that we can selectively display the correct label for a column if necessary." }, { "code": null, "e": 1810, "s": 1749, "text": "meta_dict = dict(zip(meta.column_names, meta.column_labels))" }, { "code": null, "e": 1871, "s": 1810, "text": "With meta_dict['Sat_overall'] we now get the matching label." }, { "code": null, "e": 1978, "s": 1871, "text": "In surveys, we are often interested in the percentage of respondents who chose a specific answer category:" }, { "code": null, "e": 2030, "s": 1978, "text": "df['Age'].value_counts(normalize=True).sort_index()" }, { "code": null, "e": 2215, "s": 2030, "text": "From the output we can only read that 29% voted for category 1, 33% for category 2 and almost 38% for category 3. However, in the dictionary meta.value_labels we have all value labels:" }, { "code": null, "e": 2293, "s": 2215, "text": "df['Age'].map(meta.variable_value_labels['Age']).value_counts(normalize=True)" }, { "code": null, "e": 2546, "s": 2293, "text": "That looks better! 38% of the respondents are over 50, 33% are between 30 and 50 and the rest is under 30. I personally prefer sorting according to the order of the value labels. Currently, the values ​​are simply sorted by the size of the proportions:" }, { "code": null, "e": 2672, "s": 2546, "text": "df['Age'].map(meta.variable_value_labels['Age']).value_counts(normalize=True).loc[meta.variable_value_labels['Age'].values()]" }, { "code": null, "e": 2962, "s": 2672, "text": "Perfect! That’s what we need and the result pretty much matches the output of an SPSS “Frequency”. Frequently, survey data is evaluated according to sociodemographic characteristics. For example, how does satisfaction differ by age group? For this, we can simply use the crosstab function:" }, { "code": null, "e": 3038, "s": 2962, "text": "pd.crosstab(df['Sat_overall'], df['Age'], dropna=True, normalize='columns')" }, { "code": null, "e": 3117, "s": 3038, "text": "Again, we cannot do much with the output, so let’s first map the value labels:" }, { "code": null, "e": 3436, "s": 3117, "text": "pd.crosstab(df['Sat_overall'].\\ map(meta.variable_value_labels['Sat_overall']), \\ df['Age'].map(meta.variable_value_labels['Age']), \\ dropna=True, normalize='columns'). \\ loc[meta.variable_value_labels['Sat_overall'].values()]. \\ loc[:,meta.variable_value_labels['Age'].values()]*100" }, { "code": null, "e": 3684, "s": 3436, "text": "Now, we are able to interpret the output. For those over 50, there are the most completely satisfied customers. By contrast, among the under 30s there are the most dissatisfied customers. With the .loc function we can again specify the order here." }, { "code": null, "e": 4095, "s": 3684, "text": "In surveys, it is often found out afterwards that the distribution of sociodemographic characteristics does not correspond to the distribution in the customer base. At the beginning we saw that the three groups are almost equally distributed. However, we know that 50% of our customers are under 30, 25% are between 30 and 50 and the rest is over 50. Therefore, we weight our data to reflect this distribution:" }, { "code": null, "e": 4260, "s": 4095, "text": "weight = np.NaNdf.loc[(df['Age'] == 1), 'weight'] = 0.5/(67/230)df.loc[(df['Age'] == 2), 'weight'] = 0.25/(76/230)df.loc[(df['Age'] == 3), 'weight'] = 0.25/(87/230)" }, { "code": null, "e": 4396, "s": 4260, "text": "But how can we now take this weight into account in our calculations? For the frequency distribution, we write a small helper function:" }, { "code": null, "e": 4626, "s": 4396, "text": "def weighted_frequency(x,y): a = pd.Series(df[[x,y]].groupby(x).sum()[y])/df[y].sum() b = a.index.map(meta.variable_value_labels[x]) c = a.values df_temp = pd.DataFrame({'Labels': b, 'Frequency': c}) return df_temp" }, { "code": null, "e": 4774, "s": 4626, "text": "As a result, we get a DataFrame with the respective labels (in the numerical order from small to large) and the corresponding percentage frequency:" }, { "code": null, "e": 4809, "s": 4774, "text": "weighted_frequency('Age','weight')" }, { "code": null, "e": 4936, "s": 4809, "text": "The weighted distribution now corresponds to our customer structure. Let’s take another look at the satisfaction distribution:" }, { "code": null, "e": 4979, "s": 4936, "text": "weighted_frequency('Sat_overall','weight')" }, { "code": null, "e": 5203, "s": 4979, "text": "We see that in the weighted distribution, for example, more customers are dissatisfied. We would have underestimated the oddness in our customer base if we had not weighted. With crosstabs a weight can be easily integrated:" }, { "code": null, "e": 5557, "s": 5203, "text": "pd.crosstab(df['Sat_overall']. \\ map(meta.variable_value_labels['Sat_overall']), \\ df['Age'].map(meta.variable_value_labels['Age']), df.weight, aggfunc = sum, dropna=True, \\ normalize='columns'). \\ loc[meta.variable_value_labels['Sat_overall'].values()]. \\ loc[:,meta.variable_value_labels['Age'].values()]*100" }, { "code": null, "e": 5794, "s": 5557, "text": "All we have to do is adding the parameters for the weight (e.g. df.weight) and the function aggfunc=sum. In this example, the weighted corresponds to the unweighted distribution because the ratio of cases within a group does not change." }, { "code": null, "e": 6146, "s": 5794, "text": "In a first step, we have installed pyreadstat, a module with which we can read sav-files into Python and process them further. After that, we looked at how labels and value labels can be assigned and how the analyzes can be presented in a way that is easy to interpret. We saw that Python handles categorized data very well and that it is easy to use." }, { "code": null, "e": 6393, "s": 6146, "text": "Respository:https://github.com/bd317/surveydata_with_pythonNotebook:https://github.com/bd317/surveydata_with_python/blob/master/Github_Survey_Data_Upload.ipynbSPSS-Dataset:https://github.com/bd317/surveydata_with_python/blob/master/Surveydata.sav" } ]
ShellSort - GeeksforGeeks
17 Aug, 2021 ShellSort is mainly a variation of Insertion Sort. In insertion sort, we move elements only one position ahead. When an element has to be moved far ahead, many movements are involved. The idea of shellSort is to allow exchange of far items. In shellSort, we make the array h-sorted for a large value of h. We keep reducing the value of h until it becomes 1. An array is said to be h-sorted if all sublists of every h’th element is sorted. Following is the implementation of ShellSort. C++ Java Python3 C# Javascript // C++ implementation of Shell Sort#include <iostream>using namespace std; /* function to sort arr using shellSort */int shellSort(int arr[], int n){ // Start with a big gap, then reduce the gap for (int gap = n/2; gap > 0; gap /= 2) { // Do a gapped insertion sort for this gap size. // The first gap elements a[0..gap-1] are already in gapped order // keep adding one more element until the entire array is // gap sorted for (int i = gap; i < n; i += 1) { // add a[i] to the elements that have been gap sorted // save a[i] in temp and make a hole at position i int temp = arr[i]; // shift earlier gap-sorted elements up until the correct // location for a[i] is found int j; for (j = i; j >= gap && arr[j - gap] > temp; j -= gap) arr[j] = arr[j - gap]; // put temp (the original a[i]) in its correct location arr[j] = temp; } } return 0;} void printArray(int arr[], int n){ for (int i=0; i<n; i++) cout << arr[i] << " ";} int main(){ int arr[] = {12, 34, 54, 2, 3}, i; int n = sizeof(arr)/sizeof(arr[0]); cout << "Array before sorting: \n"; printArray(arr, n); shellSort(arr, n); cout << "\nArray after sorting: \n"; printArray(arr, n); return 0;} // Java implementation of ShellSortclass ShellSort{ /* An utility function to print array of size n*/ static void printArray(int arr[]) { int n = arr.length; for (int i=0; i<n; ++i) System.out.print(arr[i] + " "); System.out.println(); } /* function to sort arr using shellSort */ int sort(int arr[]) { int n = arr.length; // Start with a big gap, then reduce the gap for (int gap = n/2; gap > 0; gap /= 2) { // Do a gapped insertion sort for this gap size. // The first gap elements a[0..gap-1] are already // in gapped order keep adding one more element // until the entire array is gap sorted for (int i = gap; i < n; i += 1) { // add a[i] to the elements that have been gap // sorted save a[i] in temp and make a hole at // position i int temp = arr[i]; // shift earlier gap-sorted elements up until // the correct location for a[i] is found int j; for (j = i; j >= gap && arr[j - gap] > temp; j -= gap) arr[j] = arr[j - gap]; // put temp (the original a[i]) in its correct // location arr[j] = temp; } } return 0; } // Driver method public static void main(String args[]) { int arr[] = {12, 34, 54, 2, 3}; System.out.println("Array before sorting"); printArray(arr); ShellSort ob = new ShellSort(); ob.sort(arr); System.out.println("Array after sorting"); printArray(arr); }}/*This code is contributed by Rajat Mishra */ # Python3 program for implementation of Shell Sort def shellSort(arr): gap = len(arr) // 2 # initialize the gap while gap > 0: i = 0 j = gap # check the array in from left to right # till the last possible index of j while j < len(arr): if arr[i] >arr[j]: arr[i],arr[j] = arr[j],arr[i] i += 1 j += 1 # now, we look back from ith index to the left # we swap the values which are not in the right order. k = i while k - gap > -1: if arr[k - gap] > arr[k]: arr[k-gap],arr[k] = arr[k],arr[k-gap] k -= 1 gap //= 2 # driver to check the codearr2 = [12, 34, 54, 2, 3]print("input array:",arr2) shellSort(arr2)print("sorted array",arr2) # This code is contributed by Shubham Prashar (SirPrashar) // C# implementation of ShellSortusing System; class ShellSort{ /* An utility function to print array of size n*/ static void printArray(int []arr) { int n = arr.Length; for (int i=0; i<n; ++i) Console.Write(arr[i] + " "); Console.WriteLine(); } /* function to sort arr using shellSort */ int sort(int []arr) { int n = arr.Length; // Start with a big gap, // then reduce the gap for (int gap = n/2; gap > 0; gap /= 2) { // Do a gapped insertion sort for this gap size. // The first gap elements a[0..gap-1] are already // in gapped order keep adding one more element // until the entire array is gap sorted for (int i = gap; i < n; i += 1) { // add a[i] to the elements that have // been gap sorted save a[i] in temp and // make a hole at position i int temp = arr[i]; // shift earlier gap-sorted elements up until // the correct location for a[i] is found int j; for (j = i; j >= gap && arr[j - gap] > temp; j -= gap) arr[j] = arr[j - gap]; // put temp (the original a[i]) // in its correct location arr[j] = temp; } } return 0; } // Driver method public static void Main() { int []arr = {12, 34, 54, 2, 3}; Console.Write("Array before sorting :\n"); printArray(arr); ShellSort ob = new ShellSort(); ob.sort(arr); Console.Write("Array after sorting :\n"); printArray(arr); }} // This code is contributed by nitin mittal. <script>// Javascript implementation of ShellSort /* An utility function to print array of size n*/function printArray(arr){ let n = arr.length; for (let i = 0; i < n; ++i) document.write(arr[i] + " "); document.write("<br>");} /* function to sort arr using shellSort */function sort(arr){ let n = arr.length; // Start with a big gap, then reduce the gap for (let gap = Math.floor(n/2); gap > 0; gap = Math.floor(gap/2)) { // Do a gapped insertion sort for this gap size. // The first gap elements a[0..gap-1] are already // in gapped order keep adding one more element // until the entire array is gap sorted for (let i = gap; i < n; i += 1) { // add a[i] to the elements that have been gap // sorted save a[i] in temp and make a hole at // position i let temp = arr[i]; // shift earlier gap-sorted elements up until // the correct location for a[i] is found let j; for (j = i; j >= gap && arr[j - gap] > temp; j -= gap) arr[j] = arr[j - gap]; // put temp (the original a[i]) in its correct // location arr[j] = temp; } } return arr;} // Driver methodlet arr = [12, 34, 54, 2, 3];document.write("Array before sorting<br>");printArray(arr); arr = sort(arr);document.write("Array after sorting<br>");printArray(arr); // This code is contributed by unknown2108</script> Output: Array before sorting: 12 34 54 2 3 Array after sorting: 2 3 12 34 54 Time Complexity: Time complexity of above implementation of shellsort is O(n2). In the above implementation gap is reduce by half in every iteration. There are many other ways to reduce gap which lead to better time complexity. See this for more details. References: https://www.youtube.com/watch?v=pGhazjsFW28 http://en.wikipedia.org/wiki/Shellsort YouTubeGeeksforGeeks500K subscribersShell Sort | 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 / 1:57•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=SHcPqUe2GZM" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> Snapshots: Other Sorting Algorithms on GeeksforGeeks/GeeksQuiz: Selection Sort Bubble Sort Insertion Sort Merge Sort Heap Sort QuickSort Radix Sort Counting Sort Bucket Sort nitin mittal NikitaZakharov shubhamprashar unknown2108 asdhamidi sweetyty Sorting Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Merge two sorted arrays Sort an array of 0s, 1s and 2s k largest(or smallest) elements in an array Count Inversions in an array | Set 1 (Using Merge Sort) Python Program for Bubble Sort sort() in Python Merge Sort for Linked Lists Python List sort() method Python Program for QuickSort Most frequent element in an array
[ { "code": null, "e": 23055, "s": 23027, "text": "\n17 Aug, 2021" }, { "code": null, "e": 23494, "s": 23055, "text": "ShellSort is mainly a variation of Insertion Sort. In insertion sort, we move elements only one position ahead. When an element has to be moved far ahead, many movements are involved. The idea of shellSort is to allow exchange of far items. In shellSort, we make the array h-sorted for a large value of h. We keep reducing the value of h until it becomes 1. An array is said to be h-sorted if all sublists of every h’th element is sorted." }, { "code": null, "e": 23540, "s": 23494, "text": "Following is the implementation of ShellSort." }, { "code": null, "e": 23544, "s": 23540, "text": "C++" }, { "code": null, "e": 23549, "s": 23544, "text": "Java" }, { "code": null, "e": 23557, "s": 23549, "text": "Python3" }, { "code": null, "e": 23560, "s": 23557, "text": "C#" }, { "code": null, "e": 23571, "s": 23560, "text": "Javascript" }, { "code": "// C++ implementation of Shell Sort#include <iostream>using namespace std; /* function to sort arr using shellSort */int shellSort(int arr[], int n){ // Start with a big gap, then reduce the gap for (int gap = n/2; gap > 0; gap /= 2) { // Do a gapped insertion sort for this gap size. // The first gap elements a[0..gap-1] are already in gapped order // keep adding one more element until the entire array is // gap sorted for (int i = gap; i < n; i += 1) { // add a[i] to the elements that have been gap sorted // save a[i] in temp and make a hole at position i int temp = arr[i]; // shift earlier gap-sorted elements up until the correct // location for a[i] is found int j; for (j = i; j >= gap && arr[j - gap] > temp; j -= gap) arr[j] = arr[j - gap]; // put temp (the original a[i]) in its correct location arr[j] = temp; } } return 0;} void printArray(int arr[], int n){ for (int i=0; i<n; i++) cout << arr[i] << \" \";} int main(){ int arr[] = {12, 34, 54, 2, 3}, i; int n = sizeof(arr)/sizeof(arr[0]); cout << \"Array before sorting: \\n\"; printArray(arr, n); shellSort(arr, n); cout << \"\\nArray after sorting: \\n\"; printArray(arr, n); return 0;}", "e": 24964, "s": 23571, "text": null }, { "code": "// Java implementation of ShellSortclass ShellSort{ /* An utility function to print array of size n*/ static void printArray(int arr[]) { int n = arr.length; for (int i=0; i<n; ++i) System.out.print(arr[i] + \" \"); System.out.println(); } /* function to sort arr using shellSort */ int sort(int arr[]) { int n = arr.length; // Start with a big gap, then reduce the gap for (int gap = n/2; gap > 0; gap /= 2) { // Do a gapped insertion sort for this gap size. // The first gap elements a[0..gap-1] are already // in gapped order keep adding one more element // until the entire array is gap sorted for (int i = gap; i < n; i += 1) { // add a[i] to the elements that have been gap // sorted save a[i] in temp and make a hole at // position i int temp = arr[i]; // shift earlier gap-sorted elements up until // the correct location for a[i] is found int j; for (j = i; j >= gap && arr[j - gap] > temp; j -= gap) arr[j] = arr[j - gap]; // put temp (the original a[i]) in its correct // location arr[j] = temp; } } return 0; } // Driver method public static void main(String args[]) { int arr[] = {12, 34, 54, 2, 3}; System.out.println(\"Array before sorting\"); printArray(arr); ShellSort ob = new ShellSort(); ob.sort(arr); System.out.println(\"Array after sorting\"); printArray(arr); }}/*This code is contributed by Rajat Mishra */", "e": 26717, "s": 24964, "text": null }, { "code": "# Python3 program for implementation of Shell Sort def shellSort(arr): gap = len(arr) // 2 # initialize the gap while gap > 0: i = 0 j = gap # check the array in from left to right # till the last possible index of j while j < len(arr): if arr[i] >arr[j]: arr[i],arr[j] = arr[j],arr[i] i += 1 j += 1 # now, we look back from ith index to the left # we swap the values which are not in the right order. k = i while k - gap > -1: if arr[k - gap] > arr[k]: arr[k-gap],arr[k] = arr[k],arr[k-gap] k -= 1 gap //= 2 # driver to check the codearr2 = [12, 34, 54, 2, 3]print(\"input array:\",arr2) shellSort(arr2)print(\"sorted array\",arr2) # This code is contributed by Shubham Prashar (SirPrashar)", "e": 27634, "s": 26717, "text": null }, { "code": "// C# implementation of ShellSortusing System; class ShellSort{ /* An utility function to print array of size n*/ static void printArray(int []arr) { int n = arr.Length; for (int i=0; i<n; ++i) Console.Write(arr[i] + \" \"); Console.WriteLine(); } /* function to sort arr using shellSort */ int sort(int []arr) { int n = arr.Length; // Start with a big gap, // then reduce the gap for (int gap = n/2; gap > 0; gap /= 2) { // Do a gapped insertion sort for this gap size. // The first gap elements a[0..gap-1] are already // in gapped order keep adding one more element // until the entire array is gap sorted for (int i = gap; i < n; i += 1) { // add a[i] to the elements that have // been gap sorted save a[i] in temp and // make a hole at position i int temp = arr[i]; // shift earlier gap-sorted elements up until // the correct location for a[i] is found int j; for (j = i; j >= gap && arr[j - gap] > temp; j -= gap) arr[j] = arr[j - gap]; // put temp (the original a[i]) // in its correct location arr[j] = temp; } } return 0; } // Driver method public static void Main() { int []arr = {12, 34, 54, 2, 3}; Console.Write(\"Array before sorting :\\n\"); printArray(arr); ShellSort ob = new ShellSort(); ob.sort(arr); Console.Write(\"Array after sorting :\\n\"); printArray(arr); }} // This code is contributed by nitin mittal.", "e": 29392, "s": 27634, "text": null }, { "code": "<script>// Javascript implementation of ShellSort /* An utility function to print array of size n*/function printArray(arr){ let n = arr.length; for (let i = 0; i < n; ++i) document.write(arr[i] + \" \"); document.write(\"<br>\");} /* function to sort arr using shellSort */function sort(arr){ let n = arr.length; // Start with a big gap, then reduce the gap for (let gap = Math.floor(n/2); gap > 0; gap = Math.floor(gap/2)) { // Do a gapped insertion sort for this gap size. // The first gap elements a[0..gap-1] are already // in gapped order keep adding one more element // until the entire array is gap sorted for (let i = gap; i < n; i += 1) { // add a[i] to the elements that have been gap // sorted save a[i] in temp and make a hole at // position i let temp = arr[i]; // shift earlier gap-sorted elements up until // the correct location for a[i] is found let j; for (j = i; j >= gap && arr[j - gap] > temp; j -= gap) arr[j] = arr[j - gap]; // put temp (the original a[i]) in its correct // location arr[j] = temp; } } return arr;} // Driver methodlet arr = [12, 34, 54, 2, 3];document.write(\"Array before sorting<br>\");printArray(arr); arr = sort(arr);document.write(\"Array after sorting<br>\");printArray(arr); // This code is contributed by unknown2108</script>", "e": 31015, "s": 29392, "text": null }, { "code": null, "e": 31023, "s": 31015, "text": "Output:" }, { "code": null, "e": 31094, "s": 31023, "text": "Array before sorting:\n12 34 54 2 3\nArray after sorting:\n2 3 12 34 54\n " }, { "code": null, "e": 31349, "s": 31094, "text": "Time Complexity: Time complexity of above implementation of shellsort is O(n2). In the above implementation gap is reduce by half in every iteration. There are many other ways to reduce gap which lead to better time complexity. See this for more details." }, { "code": null, "e": 31444, "s": 31349, "text": "References: https://www.youtube.com/watch?v=pGhazjsFW28 http://en.wikipedia.org/wiki/Shellsort" }, { "code": null, "e": 32253, "s": 31444, "text": "YouTubeGeeksforGeeks500K subscribersShell Sort | 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 / 1:57•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=SHcPqUe2GZM\" 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": 32266, "s": 32253, "text": "Snapshots: " }, { "code": null, "e": 32330, "s": 32276, "text": "Other Sorting Algorithms on GeeksforGeeks/GeeksQuiz: " }, { "code": null, "e": 32345, "s": 32330, "text": "Selection Sort" }, { "code": null, "e": 32357, "s": 32345, "text": "Bubble Sort" }, { "code": null, "e": 32372, "s": 32357, "text": "Insertion Sort" }, { "code": null, "e": 32383, "s": 32372, "text": "Merge Sort" }, { "code": null, "e": 32393, "s": 32383, "text": "Heap Sort" }, { "code": null, "e": 32403, "s": 32393, "text": "QuickSort" }, { "code": null, "e": 32414, "s": 32403, "text": "Radix Sort" }, { "code": null, "e": 32428, "s": 32414, "text": "Counting Sort" }, { "code": null, "e": 32440, "s": 32428, "text": "Bucket Sort" }, { "code": null, "e": 32453, "s": 32440, "text": "nitin mittal" }, { "code": null, "e": 32468, "s": 32453, "text": "NikitaZakharov" }, { "code": null, "e": 32483, "s": 32468, "text": "shubhamprashar" }, { "code": null, "e": 32495, "s": 32483, "text": "unknown2108" }, { "code": null, "e": 32505, "s": 32495, "text": "asdhamidi" }, { "code": null, "e": 32514, "s": 32505, "text": "sweetyty" }, { "code": null, "e": 32522, "s": 32514, "text": "Sorting" }, { "code": null, "e": 32530, "s": 32522, "text": "Sorting" }, { "code": null, "e": 32628, "s": 32530, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32637, "s": 32628, "text": "Comments" }, { "code": null, "e": 32650, "s": 32637, "text": "Old Comments" }, { "code": null, "e": 32674, "s": 32650, "text": "Merge two sorted arrays" }, { "code": null, "e": 32705, "s": 32674, "text": "Sort an array of 0s, 1s and 2s" }, { "code": null, "e": 32749, "s": 32705, "text": "k largest(or smallest) elements in an array" }, { "code": null, "e": 32805, "s": 32749, "text": "Count Inversions in an array | Set 1 (Using Merge Sort)" }, { "code": null, "e": 32836, "s": 32805, "text": "Python Program for Bubble Sort" }, { "code": null, "e": 32853, "s": 32836, "text": "sort() in Python" }, { "code": null, "e": 32881, "s": 32853, "text": "Merge Sort for Linked Lists" }, { "code": null, "e": 32907, "s": 32881, "text": "Python List sort() method" }, { "code": null, "e": 32936, "s": 32907, "text": "Python Program for QuickSort" } ]
Automated Data Quality Testing at Scale using Apache Spark | by Tanmay Deshpande | Towards Data Science
I have been working as a Technology Architect, mainly responsible for the Data Lake/Hub/Platform kind of projects. Every day we ingest data from 100+ business systems so that the data can be made available to the analytics and BI teams for their projects. While ingesting data, we avoid any transformations. The data is replicated as it is from the source. The sources can be of type MySQL, SQL Server, Oracle, DB2, etc. The target systems can be Hadoop/Hive or Big Query. Even though there is no transformation done on the data since the source and target systems are different, sometimes these simple data ingestions could cause data quality issues. Source and target systems can have different data types which might cause more issues. Special characters in data might cause row/column shiftings. In order to solve this problem, most of the developers use a manual approach for data quality testing after they built the data pipelines. This can be done by running some simple tests like Sample data comparison between source and target Null checks on primary key columns Null checks on date columns Count comparison for the categorical columns etc. This approach sometimes works well but it is time-consuming and error-prone. Hence I started looking for some automated options. My search for an open-source data quality testing framework stopped at Deequ library from Amazon. Deequ is being used at Amazon for verifying the quality of many large production datasets. The system keeps on computing data quality metrics on a regular basis. Deequ is built on top of Apache Spark hence it is naturally scalable for the huge amount of data. The best part is, you don’t need to know Spark in detail to use this library. Deequ provides features like — Constraint Suggestions — What to test. Sometimes it might be difficult to find what to test for in a particular object. Deequ provides built-in functionality to identify constraints to be tested. Metrics Computation — Once we know what to test, we can use the suggestion given by the library and run the tests to compute the metrics. Constraint Verification — Using Deequ, we can also put test cases and get results to be used for the reporting. In order to run Deequ, we need to first prepare our workstation. You can try this out on a simple Windows/Linux/Mac machine. Install Scala — You can download and install Scala from — https://www.scala-lang.org/ Install Apache Spark — You can download and install Spark from — https://spark.apache.org/ Download Deequ library — You can download the Deequ JAR as shown below — wget http://repo1.maven.org/maven2/com/amazon/deequ/deequ/1.0.1/deequ-1.0.1.jar Prepare the data to be tested — If you don’t have any data to be tested, you can prepare one. For this tutorial, I have a MySQL instance installed and I have loaded some sample data from — http://www.mysqltutorial.org/mysql-sample-database.aspx Download JDBC Jars — For whichever type of database you want to run these tests, please make sure to add JDBC jars in $SPARK_HOME/jars . Since I am going to run my tests on MySQL & Hive, I have added respective JDBC jars. In order to run tests, we will start Spark in interactive mode using the library downloaded in the previous step as shown below — PS D:\work\DataTesting> spark-shell --conf spark.jars=deequ-1.0.1.jarSpark context Web UI available at http://localhost:4040Spark context available as 'sc' (master = local[*], app id = local-1561783362821).Spark session available as 'spark'.Welcome to ____ __ / __/__ ___ _____/ /__ _\ \/ _ \/ _ `/ __/ '_/ /___/ .__/\_,_/_/ /_/\_\ version 2.4.3 /_/Using Scala version 2.11.12 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_171)Type in expressions to have them evaluated.Type :help for more information.scala> I am planning to run tests on customer table loaded in the earlier steps. You can use MySQL Workbench/CLI to verify the data is loaded properly. In order to run constraint suggestions, we need to first connect to the DB using Spark. Please make a note, with this approach, we are doing a query push down to the underlying databases. So please be careful while running on production systems directly. import org.apache.spark.sql.SQLContextval sqlcontext = new org.apache.spark.sql.SQLContext(sc)val datasource = sqlcontext.read.format("jdbc").option("url", "jdbc:mysql://<IP>:3306/classicmodels").option("driver", "com.mysql.jdbc.Driver").option("dbtable", "customers").option("user", "<username>").option("password", "<password>").option("useSSL", "false").load() On a valid connection, you can check the schema of the table — scala> datasource.printSchema()root |-- customerNumber: integer (nullable = true) |-- customerName: string (nullable = true) |-- contactLastName: string (nullable = true) |-- contactFirstName: string (nullable = true) |-- phone: string (nullable = true) |-- addressLine1: string (nullable = true) |-- addressLine2: string (nullable = true) |-- city: string (nullable = true) |-- state: string (nullable = true) |-- postalCode: string (nullable = true) |-- country: string (nullable = true) |-- salesRepEmployeeNumber: integer (nullable = true) |-- creditLimit: decimal(10,2) (nullable = true)scala> Now, let’s run the constraint suggestions — import com.amazon.deequ.suggestions.{ConstraintSuggestionRunner, Rules}import spark.implicits._ // for toDS method// We ask deequ to compute constraint suggestions for us on the dataval suggestionResult = { ConstraintSuggestionRunner() // data to suggest constraints for .onData(datasource) // default set of rules for constraint suggestion .addConstraintRules(Rules.DEFAULT) // run data profiling and constraint suggestion .run()}// We can now investigate the constraints that Deequ suggested. val suggestionDataFrame = suggestionResult.constraintSuggestions.flatMap { case (column, suggestions) => suggestions.map { constraint => (column, constraint.description, constraint.codeForConstraint) } }.toSeq.toDS() Once the execution is complete, you can print the suggestions as shown below — scala> suggestionDataFrame.toJSON.collect.foreach(println){"_1":"addressLine1","_2":"'addressLine1' is not null","_3":".isComplete(\"addressLine1\")"}{"_1":"city","_2":"'city' is not null","_3":".isComplete(\"city\")"}{"_1":"contactFirstName","_2":"'contactFirstName' is not null","_3":".isComplete(\"contactFirstName\")"}{"_1":"state","_2":"'state' has less than 69% missing values","_3":".hasCompleteness(\"state\", _ >= 0.31, Some(\"It should be above 0.31!\"))"}{"_1":"salesRepEmployeeNumber","_2":"'salesRepEmployeeNumber' has less than 25% missing values","_3":".hasCompleteness(\"salesRepEmployeeNumber\", _ >= 0.75, Some(\"It should be above 0.75!\"))"}{"_1":"salesRepEmployeeNumber","_2":"'salesRepEmployeeNumber' has no negative values","_3":".isNonNegative(\"salesRepEmployeeNumber\")"}{"_1":"customerName","_2":"'customerName' is not null","_3":".isComplete(\"customerName\")"}{"_1":"creditLimit","_2":"'creditLimit' is not null","_3":".isComplete(\"creditLimit\")"}{"_1":"creditLimit","_2":"'creditLimit' has no negative values","_3":".isNonNegative(\"creditLimit\")"}{"_1":"country","_2":"'country' is not null","_3":".isComplete(\"country\")"}{"_1":"country","_2":"'country' has value range 'USA', 'Germany', 'France', 'Spain', 'UK', 'Australia', 'Italy', 'New Zealand', 'Switzerland', 'Singapore', 'Finland', 'Canada', 'Portugal', 'Ireland', 'Norway ', 'Austria', 'Sweden', 'Belgium' for at least 84.0% of values","_3":".isContainedIn(\"country\", Array(\"USA\", \"Germany\", \"France\", \"Spain\", \"UK\", \"Australia\", \"Italy\", \"New Zealand\", \"Switzerland\", \"Singapore\", \"Finland\", \"Canada\", \"Portugal\",\"Ireland\", \"Norway \", \"Austria\", \"Sweden\", \"Belgium\"), _ >= 0.84, Some(\"It should be above 0.84!\"))"}{"_1":"postalCode","_2":"'postalCode' has less than 9% missing values","_3":".hasCompleteness(\"postalCode\", _ >= 0.9,Some(\"It should be above 0.9!\"))"}{"_1":"customerNumber","_2":"'customerNumber' is not null","_3":".isComplete(\"customerNumber\")"}{"_1":"customerNumber","_2":"'customerNumber' has no negative values","_3":".isNonNegative(\"customerNumber\")"}{"_1":"contactLastName","_2":"'contactLastName' is not null","_3":".isComplete(\"contactLastName\")"}{"_1":"phone","_2":"'phone' is not null","_3":".isComplete(\"phone\")"} This means your test cases are ready. Now let’s run the metrics computation. Looking at the columns and suggestions, now I want to run the metrics computations. Here is how you can do so — import com.amazon.deequ.analyzers.runners.{AnalysisRunner, AnalyzerContext}import com.amazon.deequ.analyzers.runners.AnalyzerContext.successMetricsAsDataFrameimport com.amazon.deequ.analyzers.{Compliance, Correlation, Size, Completeness, Mean, ApproxCountDistinct, Maximum, Minimum, Entropy, GroupingAnalyzer}val analysisResult: AnalyzerContext = { AnalysisRunner // data to run the analysis on .onData(datasource) // define analyzers that compute metrics .addAnalyzer(Size()) .addAnalyzer(Completeness("customerNumber")) .addAnalyzer(ApproxCountDistinct("customerNumber")) .addAnalyzer(Minimum("creditLimit")) .addAnalyzer(Mean("creditLimit")) .addAnalyzer(Maximum("creditLimit")) .addAnalyzer(Entropy("creditLimit")) .run()} On a successful run, you can see the results // retrieve successfully computed metrics as a Spark data frameval metrics = successMetricsAsDataFrame(spark, analysisResult)metrics.show()scala> metrics.show()+-------+--------------+-------------------+-----------------+| entity| instance| name| value|+-------+--------------+-------------------+-----------------+| Column| creditLimit| Entropy|4.106362796873961|| Column|customerNumber| Completeness| 1.0|| Column|customerNumber|ApproxCountDistinct| 119.0|| Column| creditLimit| Minimum| 0.0|| Column| creditLimit| Mean|67659.01639344262|| Column| creditLimit| Maximum| 227600.0||Dataset| *| Size| 122.0|+-------+--------------+-------------------+-----------------+ You can also store these numbers for further verifications or to even show trends. In this example, we are running ApproxCountDistinct, this is calculated using the HyperLogLog algorithm. This reduces the burden on the source system by approximating the distinct count. A full list of available Analyzers can be found at — https://github.com/awslabs/deequ/tree/master/src/main/scala/com/amazon/deequ/analyzers Now let’s run test cases using the verification suites. import com.amazon.deequ.{VerificationSuite, VerificationResult}import com.amazon.deequ.VerificationResult.checkResultsAsDataFrameimport com.amazon.deequ.checks.{Check, CheckLevel}val verificationResult: VerificationResult = { VerificationSuite() // data to run the verification on .onData(datasource) // define a data quality check .addCheck( Check(CheckLevel.Error, "Data Validation Check") .hasSize(_ == 122 ) .isComplete("customerNumber") // should never be NULL .isUnique("customerNumber") // should not contain duplicates .isNonNegative("creditLimit")) // should not contain negative values // compute metrics and verify check conditions .run()} Once the run is complete, you can look at the results // convert check results to a Spark data frameval resultDataFrame = checkResultsAsDataFrame(spark, verificationResult)resultDataFrame.show()scala> resultDataFrame.show()+-------------------+-----------+------------+--------------------+-----------------+------------------+| check|check_level|check_status| constraint|constraint_status|constraint_message|+-------------------+-----------+------------+--------------------+-----------------+------------------+|Data Validate Check| Error| Success|SizeConstraint(Si...| Success| ||Data Validate Check| Error| Success|CompletenessConst...| Success| ||Data Validate Check| Error| Success|UniquenessConstra...| Success| ||Data Validate Check| Error| Success|ComplianceConstra...| Success| |+-------------------+-----------+------------+--------------------+-----------------+------------------+ If a particular case is failed, you can take a look at the details as shown below resultDataFrame.filter(resultDataFrame("constraint_status")==="Failure").toJSON.collect.foreach(println) Deequ also provides a way to validate incremental data loads. You can read more about this approach at — https://github.com/awslabs/deequ/blob/master/src/main/scala/com/amazon/deequ/examples/algebraic_states_example.md Deequ also provided an approach to detect anomalies. The GitHub page lists down some approaches and strategies. Details can be found here — https://github.com/awslabs/deequ/tree/master/src/main/scala/com/amazon/deequ/anomalydetection Overall, I see Deequ as a great tool to be used for data validation and quality testing in Data Lakes/ Hub/Data Warehouse kind of use cases. Amazon has even published a research paper about this approach. This can be viewed at — http://www.vldb.org/pvldb/vol11/p1781-schelter.pdf If you try this out, do let me know your experience. If you have some interesting ideas to take this further, please don’t forget to mention those in the comments. Hey, if you enjoyed this story, check out Medium Membership! Just $5/month!Your membership fee directly supports me and other writers you read. You’ll also get full access to every story on Medium.
[ { "code": null, "e": 428, "s": 172, "text": "I have been working as a Technology Architect, mainly responsible for the Data Lake/Hub/Platform kind of projects. Every day we ingest data from 100+ business systems so that the data can be made available to the analytics and BI teams for their projects." }, { "code": null, "e": 972, "s": 428, "text": "While ingesting data, we avoid any transformations. The data is replicated as it is from the source. The sources can be of type MySQL, SQL Server, Oracle, DB2, etc. The target systems can be Hadoop/Hive or Big Query. Even though there is no transformation done on the data since the source and target systems are different, sometimes these simple data ingestions could cause data quality issues. Source and target systems can have different data types which might cause more issues. Special characters in data might cause row/column shiftings." }, { "code": null, "e": 1162, "s": 972, "text": "In order to solve this problem, most of the developers use a manual approach for data quality testing after they built the data pipelines. This can be done by running some simple tests like" }, { "code": null, "e": 1211, "s": 1162, "text": "Sample data comparison between source and target" }, { "code": null, "e": 1246, "s": 1211, "text": "Null checks on primary key columns" }, { "code": null, "e": 1274, "s": 1246, "text": "Null checks on date columns" }, { "code": null, "e": 1319, "s": 1274, "text": "Count comparison for the categorical columns" }, { "code": null, "e": 1324, "s": 1319, "text": "etc." }, { "code": null, "e": 1453, "s": 1324, "text": "This approach sometimes works well but it is time-consuming and error-prone. Hence I started looking for some automated options." }, { "code": null, "e": 1713, "s": 1453, "text": "My search for an open-source data quality testing framework stopped at Deequ library from Amazon. Deequ is being used at Amazon for verifying the quality of many large production datasets. The system keeps on computing data quality metrics on a regular basis." }, { "code": null, "e": 1920, "s": 1713, "text": "Deequ is built on top of Apache Spark hence it is naturally scalable for the huge amount of data. The best part is, you don’t need to know Spark in detail to use this library. Deequ provides features like —" }, { "code": null, "e": 2116, "s": 1920, "text": "Constraint Suggestions — What to test. Sometimes it might be difficult to find what to test for in a particular object. Deequ provides built-in functionality to identify constraints to be tested." }, { "code": null, "e": 2254, "s": 2116, "text": "Metrics Computation — Once we know what to test, we can use the suggestion given by the library and run the tests to compute the metrics." }, { "code": null, "e": 2366, "s": 2254, "text": "Constraint Verification — Using Deequ, we can also put test cases and get results to be used for the reporting." }, { "code": null, "e": 2491, "s": 2366, "text": "In order to run Deequ, we need to first prepare our workstation. You can try this out on a simple Windows/Linux/Mac machine." }, { "code": null, "e": 2577, "s": 2491, "text": "Install Scala — You can download and install Scala from — https://www.scala-lang.org/" }, { "code": null, "e": 2668, "s": 2577, "text": "Install Apache Spark — You can download and install Spark from — https://spark.apache.org/" }, { "code": null, "e": 2741, "s": 2668, "text": "Download Deequ library — You can download the Deequ JAR as shown below —" }, { "code": null, "e": 2821, "s": 2741, "text": "wget http://repo1.maven.org/maven2/com/amazon/deequ/deequ/1.0.1/deequ-1.0.1.jar" }, { "code": null, "e": 3066, "s": 2821, "text": "Prepare the data to be tested — If you don’t have any data to be tested, you can prepare one. For this tutorial, I have a MySQL instance installed and I have loaded some sample data from — http://www.mysqltutorial.org/mysql-sample-database.aspx" }, { "code": null, "e": 3288, "s": 3066, "text": "Download JDBC Jars — For whichever type of database you want to run these tests, please make sure to add JDBC jars in $SPARK_HOME/jars . Since I am going to run my tests on MySQL & Hive, I have added respective JDBC jars." }, { "code": null, "e": 3418, "s": 3288, "text": "In order to run tests, we will start Spark in interactive mode using the library downloaded in the previous step as shown below —" }, { "code": null, "e": 3964, "s": 3418, "text": "PS D:\\work\\DataTesting> spark-shell --conf spark.jars=deequ-1.0.1.jarSpark context Web UI available at http://localhost:4040Spark context available as 'sc' (master = local[*], app id = local-1561783362821).Spark session available as 'spark'.Welcome to ____ __ / __/__ ___ _____/ /__ _\\ \\/ _ \\/ _ `/ __/ '_/ /___/ .__/\\_,_/_/ /_/\\_\\ version 2.4.3 /_/Using Scala version 2.11.12 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_171)Type in expressions to have them evaluated.Type :help for more information.scala>" }, { "code": null, "e": 4109, "s": 3964, "text": "I am planning to run tests on customer table loaded in the earlier steps. You can use MySQL Workbench/CLI to verify the data is loaded properly." }, { "code": null, "e": 4197, "s": 4109, "text": "In order to run constraint suggestions, we need to first connect to the DB using Spark." }, { "code": null, "e": 4364, "s": 4197, "text": "Please make a note, with this approach, we are doing a query push down to the underlying databases. So please be careful while running on production systems directly." }, { "code": null, "e": 4728, "s": 4364, "text": "import org.apache.spark.sql.SQLContextval sqlcontext = new org.apache.spark.sql.SQLContext(sc)val datasource = sqlcontext.read.format(\"jdbc\").option(\"url\", \"jdbc:mysql://<IP>:3306/classicmodels\").option(\"driver\", \"com.mysql.jdbc.Driver\").option(\"dbtable\", \"customers\").option(\"user\", \"<username>\").option(\"password\", \"<password>\").option(\"useSSL\", \"false\").load()" }, { "code": null, "e": 4791, "s": 4728, "text": "On a valid connection, you can check the schema of the table —" }, { "code": null, "e": 5390, "s": 4791, "text": "scala> datasource.printSchema()root |-- customerNumber: integer (nullable = true) |-- customerName: string (nullable = true) |-- contactLastName: string (nullable = true) |-- contactFirstName: string (nullable = true) |-- phone: string (nullable = true) |-- addressLine1: string (nullable = true) |-- addressLine2: string (nullable = true) |-- city: string (nullable = true) |-- state: string (nullable = true) |-- postalCode: string (nullable = true) |-- country: string (nullable = true) |-- salesRepEmployeeNumber: integer (nullable = true) |-- creditLimit: decimal(10,2) (nullable = true)scala>" }, { "code": null, "e": 5434, "s": 5390, "text": "Now, let’s run the constraint suggestions —" }, { "code": null, "e": 6166, "s": 5434, "text": "import com.amazon.deequ.suggestions.{ConstraintSuggestionRunner, Rules}import spark.implicits._ // for toDS method// We ask deequ to compute constraint suggestions for us on the dataval suggestionResult = { ConstraintSuggestionRunner() // data to suggest constraints for .onData(datasource) // default set of rules for constraint suggestion .addConstraintRules(Rules.DEFAULT) // run data profiling and constraint suggestion .run()}// We can now investigate the constraints that Deequ suggested. val suggestionDataFrame = suggestionResult.constraintSuggestions.flatMap { case (column, suggestions) => suggestions.map { constraint => (column, constraint.description, constraint.codeForConstraint) } }.toSeq.toDS()" }, { "code": null, "e": 6245, "s": 6166, "text": "Once the execution is complete, you can print the suggestions as shown below —" }, { "code": null, "e": 8534, "s": 6245, "text": "scala> suggestionDataFrame.toJSON.collect.foreach(println){\"_1\":\"addressLine1\",\"_2\":\"'addressLine1' is not null\",\"_3\":\".isComplete(\\\"addressLine1\\\")\"}{\"_1\":\"city\",\"_2\":\"'city' is not null\",\"_3\":\".isComplete(\\\"city\\\")\"}{\"_1\":\"contactFirstName\",\"_2\":\"'contactFirstName' is not null\",\"_3\":\".isComplete(\\\"contactFirstName\\\")\"}{\"_1\":\"state\",\"_2\":\"'state' has less than 69% missing values\",\"_3\":\".hasCompleteness(\\\"state\\\", _ >= 0.31, Some(\\\"It should be above 0.31!\\\"))\"}{\"_1\":\"salesRepEmployeeNumber\",\"_2\":\"'salesRepEmployeeNumber' has less than 25% missing values\",\"_3\":\".hasCompleteness(\\\"salesRepEmployeeNumber\\\", _ >= 0.75, Some(\\\"It should be above 0.75!\\\"))\"}{\"_1\":\"salesRepEmployeeNumber\",\"_2\":\"'salesRepEmployeeNumber' has no negative values\",\"_3\":\".isNonNegative(\\\"salesRepEmployeeNumber\\\")\"}{\"_1\":\"customerName\",\"_2\":\"'customerName' is not null\",\"_3\":\".isComplete(\\\"customerName\\\")\"}{\"_1\":\"creditLimit\",\"_2\":\"'creditLimit' is not null\",\"_3\":\".isComplete(\\\"creditLimit\\\")\"}{\"_1\":\"creditLimit\",\"_2\":\"'creditLimit' has no negative values\",\"_3\":\".isNonNegative(\\\"creditLimit\\\")\"}{\"_1\":\"country\",\"_2\":\"'country' is not null\",\"_3\":\".isComplete(\\\"country\\\")\"}{\"_1\":\"country\",\"_2\":\"'country' has value range 'USA', 'Germany', 'France', 'Spain', 'UK', 'Australia', 'Italy', 'New Zealand', 'Switzerland', 'Singapore', 'Finland', 'Canada', 'Portugal', 'Ireland', 'Norway ', 'Austria', 'Sweden', 'Belgium' for at least 84.0% of values\",\"_3\":\".isContainedIn(\\\"country\\\", Array(\\\"USA\\\", \\\"Germany\\\", \\\"France\\\", \\\"Spain\\\", \\\"UK\\\", \\\"Australia\\\", \\\"Italy\\\", \\\"New Zealand\\\", \\\"Switzerland\\\", \\\"Singapore\\\", \\\"Finland\\\", \\\"Canada\\\", \\\"Portugal\\\",\\\"Ireland\\\", \\\"Norway \\\", \\\"Austria\\\", \\\"Sweden\\\", \\\"Belgium\\\"), _ >= 0.84, Some(\\\"It should be above 0.84!\\\"))\"}{\"_1\":\"postalCode\",\"_2\":\"'postalCode' has less than 9% missing values\",\"_3\":\".hasCompleteness(\\\"postalCode\\\", _ >= 0.9,Some(\\\"It should be above 0.9!\\\"))\"}{\"_1\":\"customerNumber\",\"_2\":\"'customerNumber' is not null\",\"_3\":\".isComplete(\\\"customerNumber\\\")\"}{\"_1\":\"customerNumber\",\"_2\":\"'customerNumber' has no negative values\",\"_3\":\".isNonNegative(\\\"customerNumber\\\")\"}{\"_1\":\"contactLastName\",\"_2\":\"'contactLastName' is not null\",\"_3\":\".isComplete(\\\"contactLastName\\\")\"}{\"_1\":\"phone\",\"_2\":\"'phone' is not null\",\"_3\":\".isComplete(\\\"phone\\\")\"}" }, { "code": null, "e": 8611, "s": 8534, "text": "This means your test cases are ready. Now let’s run the metrics computation." }, { "code": null, "e": 8723, "s": 8611, "text": "Looking at the columns and suggestions, now I want to run the metrics computations. Here is how you can do so —" }, { "code": null, "e": 9461, "s": 8723, "text": "import com.amazon.deequ.analyzers.runners.{AnalysisRunner, AnalyzerContext}import com.amazon.deequ.analyzers.runners.AnalyzerContext.successMetricsAsDataFrameimport com.amazon.deequ.analyzers.{Compliance, Correlation, Size, Completeness, Mean, ApproxCountDistinct, Maximum, Minimum, Entropy, GroupingAnalyzer}val analysisResult: AnalyzerContext = { AnalysisRunner // data to run the analysis on .onData(datasource) // define analyzers that compute metrics .addAnalyzer(Size()) .addAnalyzer(Completeness(\"customerNumber\")) .addAnalyzer(ApproxCountDistinct(\"customerNumber\")) .addAnalyzer(Minimum(\"creditLimit\")) .addAnalyzer(Mean(\"creditLimit\")) .addAnalyzer(Maximum(\"creditLimit\")) .addAnalyzer(Entropy(\"creditLimit\")) .run()}" }, { "code": null, "e": 9506, "s": 9461, "text": "On a successful run, you can see the results" }, { "code": null, "e": 10349, "s": 9506, "text": "// retrieve successfully computed metrics as a Spark data frameval metrics = successMetricsAsDataFrame(spark, analysisResult)metrics.show()scala> metrics.show()+-------+--------------+-------------------+-----------------+| entity| instance| name| value|+-------+--------------+-------------------+-----------------+| Column| creditLimit| Entropy|4.106362796873961|| Column|customerNumber| Completeness| 1.0|| Column|customerNumber|ApproxCountDistinct| 119.0|| Column| creditLimit| Minimum| 0.0|| Column| creditLimit| Mean|67659.01639344262|| Column| creditLimit| Maximum| 227600.0||Dataset| *| Size| 122.0|+-------+--------------+-------------------+-----------------+" }, { "code": null, "e": 10619, "s": 10349, "text": "You can also store these numbers for further verifications or to even show trends. In this example, we are running ApproxCountDistinct, this is calculated using the HyperLogLog algorithm. This reduces the burden on the source system by approximating the distinct count." }, { "code": null, "e": 10759, "s": 10619, "text": "A full list of available Analyzers can be found at — https://github.com/awslabs/deequ/tree/master/src/main/scala/com/amazon/deequ/analyzers" }, { "code": null, "e": 10815, "s": 10759, "text": "Now let’s run test cases using the verification suites." }, { "code": null, "e": 11497, "s": 10815, "text": "import com.amazon.deequ.{VerificationSuite, VerificationResult}import com.amazon.deequ.VerificationResult.checkResultsAsDataFrameimport com.amazon.deequ.checks.{Check, CheckLevel}val verificationResult: VerificationResult = { VerificationSuite() // data to run the verification on .onData(datasource) // define a data quality check .addCheck( Check(CheckLevel.Error, \"Data Validation Check\") .hasSize(_ == 122 ) .isComplete(\"customerNumber\") // should never be NULL .isUnique(\"customerNumber\") // should not contain duplicates .isNonNegative(\"creditLimit\")) // should not contain negative values // compute metrics and verify check conditions .run()}" }, { "code": null, "e": 11551, "s": 11497, "text": "Once the run is complete, you can look at the results" }, { "code": null, "e": 12553, "s": 11551, "text": "// convert check results to a Spark data frameval resultDataFrame = checkResultsAsDataFrame(spark, verificationResult)resultDataFrame.show()scala> resultDataFrame.show()+-------------------+-----------+------------+--------------------+-----------------+------------------+| check|check_level|check_status| constraint|constraint_status|constraint_message|+-------------------+-----------+------------+--------------------+-----------------+------------------+|Data Validate Check| Error| Success|SizeConstraint(Si...| Success| ||Data Validate Check| Error| Success|CompletenessConst...| Success| ||Data Validate Check| Error| Success|UniquenessConstra...| Success| ||Data Validate Check| Error| Success|ComplianceConstra...| Success| |+-------------------+-----------+------------+--------------------+-----------------+------------------+" }, { "code": null, "e": 12635, "s": 12553, "text": "If a particular case is failed, you can take a look at the details as shown below" }, { "code": null, "e": 12740, "s": 12635, "text": "resultDataFrame.filter(resultDataFrame(\"constraint_status\")===\"Failure\").toJSON.collect.foreach(println)" }, { "code": null, "e": 12959, "s": 12740, "text": "Deequ also provides a way to validate incremental data loads. You can read more about this approach at — https://github.com/awslabs/deequ/blob/master/src/main/scala/com/amazon/deequ/examples/algebraic_states_example.md" }, { "code": null, "e": 13193, "s": 12959, "text": "Deequ also provided an approach to detect anomalies. The GitHub page lists down some approaches and strategies. Details can be found here — https://github.com/awslabs/deequ/tree/master/src/main/scala/com/amazon/deequ/anomalydetection" }, { "code": null, "e": 13473, "s": 13193, "text": "Overall, I see Deequ as a great tool to be used for data validation and quality testing in Data Lakes/ Hub/Data Warehouse kind of use cases. Amazon has even published a research paper about this approach. This can be viewed at — http://www.vldb.org/pvldb/vol11/p1781-schelter.pdf" }, { "code": null, "e": 13637, "s": 13473, "text": "If you try this out, do let me know your experience. If you have some interesting ideas to take this further, please don’t forget to mention those in the comments." } ]
How do I plot a step function with Matplotlib in Python?
To plot a step function with matplotlib in Python, we can take the following steps − Create data points for x and y. Create data points for x and y. Make a step plot using step() method. Make a step plot using step() method. To display the figure, use show() method. To display the figure, use show() method. import matplotlib.pyplot as plt import numpy as np plt.rcParams["figure.figsize"] = [7.00, 3.50] plt.rcParams["figure.autolayout"] = True x = np.array([1, 3, 4, 5, 7]) y = np.array([1, 9, 16, 25, 49]) plt.step(x, y, 'r*') plt.show()
[ { "code": null, "e": 1147, "s": 1062, "text": "To plot a step function with matplotlib in Python, we can take the following steps −" }, { "code": null, "e": 1179, "s": 1147, "text": "Create data points for x and y." }, { "code": null, "e": 1211, "s": 1179, "text": "Create data points for x and y." }, { "code": null, "e": 1249, "s": 1211, "text": "Make a step plot using step() method." }, { "code": null, "e": 1287, "s": 1249, "text": "Make a step plot using step() method." }, { "code": null, "e": 1329, "s": 1287, "text": "To display the figure, use show() method." }, { "code": null, "e": 1371, "s": 1329, "text": "To display the figure, use show() method." }, { "code": null, "e": 1604, "s": 1371, "text": "import matplotlib.pyplot as plt\nimport numpy as np\nplt.rcParams[\"figure.figsize\"] = [7.00, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\nx = np.array([1, 3, 4, 5, 7])\ny = np.array([1, 9, 16, 25, 49])\nplt.step(x, y, 'r*')\nplt.show()" } ]
Python | Pandas Series.repeat() - GeeksforGeeks
10 Feb, 2019 Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index. Pandas Series.repeat() function repeat elements of a Series. It returns a new Series where each element of the current Series is repeated consecutively a given number of times. Syntax: Series.repeat(repeats, axis=None) Parameter :repeats : The number of repetitions for each element.axis : None Returns : repeated_series Example #1: Use Series.repeat() function to repeat each value in the given Series object 2 times. # importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([10, 25, 3, 11, 24, 6]) # Create the Indexindex_ = ['Coca Cola', 'Sprite', 'Coke', 'Fanta', 'Dew', 'ThumbsUp'] # set the indexsr.index = index_ # Print the seriesprint(sr) Output : Now we will use Series.repeat() function to repeat each value of the given series object 2 times. # repeat twiceresult = sr.repeat(repeats = 2) # Print the resultprint(result) Output : As we can see in the output, the Series.repeat() function has returned a new series object where each values are repeated the specified number of times. Example #2 : Use Series.repeat() function to repeat each value in the given Series object 3 times. # importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon', 'Rio']) # Create the Indexindex_ = ['City 1', 'City 2', 'City 3', 'City 4', 'City 5'] # set the indexsr.index = index_ # Print the seriesprint(sr) Output : Now we will use Series.repeat() function to repeat each value of the given series object 3 times. # repeat twiceresult = sr.repeat(repeats = 3) # Print the resultprint(result) Output :As we can see in the output, the Series.repeat() function has returned a new series object where each values are repeated the specified number of times. Python pandas-series Python pandas-series-methods Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Different ways to create Pandas Dataframe Python String | replace() Reading and Writing to text files in Python sum() function in Python Create a Pandas DataFrame from Lists How to drop one or multiple columns in Pandas Dataframe
[ { "code": null, "e": 24449, "s": 24421, "text": "\n10 Feb, 2019" }, { "code": null, "e": 24706, "s": 24449, "text": "Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index." }, { "code": null, "e": 24883, "s": 24706, "text": "Pandas Series.repeat() function repeat elements of a Series. It returns a new Series where each element of the current Series is repeated consecutively a given number of times." }, { "code": null, "e": 24925, "s": 24883, "text": "Syntax: Series.repeat(repeats, axis=None)" }, { "code": null, "e": 25001, "s": 24925, "text": "Parameter :repeats : The number of repetitions for each element.axis : None" }, { "code": null, "e": 25027, "s": 25001, "text": "Returns : repeated_series" }, { "code": null, "e": 25125, "s": 25027, "text": "Example #1: Use Series.repeat() function to repeat each value in the given Series object 2 times." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([10, 25, 3, 11, 24, 6]) # Create the Indexindex_ = ['Coca Cola', 'Sprite', 'Coke', 'Fanta', 'Dew', 'ThumbsUp'] # set the indexsr.index = index_ # Print the seriesprint(sr)", "e": 25381, "s": 25125, "text": null }, { "code": null, "e": 25390, "s": 25381, "text": "Output :" }, { "code": null, "e": 25488, "s": 25390, "text": "Now we will use Series.repeat() function to repeat each value of the given series object 2 times." }, { "code": "# repeat twiceresult = sr.repeat(repeats = 2) # Print the resultprint(result)", "e": 25567, "s": 25488, "text": null }, { "code": null, "e": 25576, "s": 25567, "text": "Output :" }, { "code": null, "e": 25828, "s": 25576, "text": "As we can see in the output, the Series.repeat() function has returned a new series object where each values are repeated the specified number of times. Example #2 : Use Series.repeat() function to repeat each value in the given Series object 3 times." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon', 'Rio']) # Create the Indexindex_ = ['City 1', 'City 2', 'City 3', 'City 4', 'City 5'] # set the indexsr.index = index_ # Print the seriesprint(sr)", "e": 26105, "s": 25828, "text": null }, { "code": null, "e": 26114, "s": 26105, "text": "Output :" }, { "code": null, "e": 26212, "s": 26114, "text": "Now we will use Series.repeat() function to repeat each value of the given series object 3 times." }, { "code": "# repeat twiceresult = sr.repeat(repeats = 3) # Print the resultprint(result)", "e": 26291, "s": 26212, "text": null }, { "code": null, "e": 26452, "s": 26291, "text": "Output :As we can see in the output, the Series.repeat() function has returned a new series object where each values are repeated the specified number of times." }, { "code": null, "e": 26473, "s": 26452, "text": "Python pandas-series" }, { "code": null, "e": 26502, "s": 26473, "text": "Python pandas-series-methods" }, { "code": null, "e": 26516, "s": 26502, "text": "Python-pandas" }, { "code": null, "e": 26523, "s": 26516, "text": "Python" }, { "code": null, "e": 26621, "s": 26523, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26630, "s": 26621, "text": "Comments" }, { "code": null, "e": 26643, "s": 26630, "text": "Old Comments" }, { "code": null, "e": 26661, "s": 26643, "text": "Python Dictionary" }, { "code": null, "e": 26696, "s": 26661, "text": "Read a file line by line in Python" }, { "code": null, "e": 26718, "s": 26696, "text": "Enumerate() in Python" }, { "code": null, "e": 26750, "s": 26718, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26792, "s": 26750, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26818, "s": 26792, "text": "Python String | replace()" }, { "code": null, "e": 26862, "s": 26818, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 26887, "s": 26862, "text": "sum() function in Python" }, { "code": null, "e": 26924, "s": 26887, "text": "Create a Pandas DataFrame from Lists" } ]
Program to remove vowels from Linked List
03 Jun, 2021 Given a singly linked list, the task is to remove the vowels from the given linked list. Examples: Input: g -> e -> e -> k -> s -> f -> o -> r -> g -> e -> e -> k -> s Output: g -> k -> s -> f -> r -> g -> k -> s Explanation: After removing vowels {e, e}, {o}, {e, e}. The linked list becomes g -> k -> s -> f -> r -> g -> k -> s Input: a -> a -> a -> g -> e -> e -> k -> s -> i -> i -> i -> m Output: g -> k -> s -> m Explanation: After removing vowels {a, a, a}, {e, e}, {i, i, i}. The linked list becomes g -> k -> s -> f -> r -> g -> k -> s Approach: There are three cases where we can find the vowels in the given linked list: At the starting of the linked list: For removing vowels from the start of the linked list, move the head Node to the first consonant that occurs in the linked list. For Example: For Linked List: a -> e -> i -> a -> c -> r -> d -> NULL After moving the head Node from Node a to Node c, We have c -> r -> d -> NULL In the between of the linked list: For removing vowels from the between of the linked list, the idea is to keep a marker of the last consonant found in the linked list before the vowel Nodes and change the next link of that Node with the next consonant Node found in the linked list after vowel Nodes. For Example: For Linked List: c -> r -> d -> a -> e -> i -> a -> c -> r -> z -> NULL last consonant before vowels {a, e, i, a} is d and next consonant after vowels {a, e, i, a} is r After linking next pointer of Node d to Node r, We have c -> r -> d -> r -> z -> NULL At the end of the linked list: For removing vowels from the end of the linked list, the idea is to keep a marker of the last consonant found in the linked list before the vowel Nodes and change the next link of that Node with NULL. For Example: For Linked List: c -> r -> d -> a -> e -> i -> a -> NULL last consonant before vowels {a, e, i, a} is d After changing the next link of Node to NULL, We have c -> r -> d -> NULL Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to remove vowels// Nodes in a linked list#include <bits/stdc++.h>using namespace std; // A linked list nodestruct Node { char data; struct Node* next;}; // Head Nodestruct Node* head; // Function to add new node to the// ListNode* newNode(char key){ Node* temp = new Node; temp->data = key; temp->next = NULL; return temp;} // Utility function to print the// linked listvoid printlist(Node* head){ if (!head) { cout << "Empty List\n"; return; } while (head != NULL) { cout << head->data << " "; if (head->next) cout << "-> "; head = head->next; } cout << endl;} // Utility function for checking vowelbool isVowel(char x){ return (x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u' || x == 'A' || x == 'E' || x == 'I' || x == 'O' || x == 'U');} // Function to remove the vowels Nodevoid removeVowels(){ // Node pointing to head Node struct Node* ptr = head; // Case 1 : Remove the trailing // vowels while (ptr != NULL) { // If current Node is a vowel // node then move the pointer // to next node if (isVowel(ptr->data)) ptr = ptr->next; // Else break if a consonant // node is found else break; } // This prev node used to link // prev consonant to next // consonant after vowels struct Node* prev = ptr; // Head points to the first // consonant of the linked list head = ptr; ptr = ptr->next; // Case 2: If vowels found in // between of the linked list while (ptr != NULL) { // If current node is vowel if (isVowel(ptr->data)) { // Move ptr to the next // node ptr = ptr->next; // Check for vowels // occurring continuously while (ptr != NULL) { // If ptr is a vowel // move to next pointer if (isVowel(ptr->data)) { ptr = ptr->next; } // Else break if // consonant found else break; } // Case 3: If we have ending // vowels then link the prev // consonant to NULL if (ptr == NULL) { prev->next = NULL; break; } // Case 2: change the next // link of prev to current // consonant pointing to // ptr else { prev->next = ptr; } } // Move prev and ptr to next // for next iteration prev = prev->next; ptr = ptr->next; }} // Driver codeint main(){ // Initialise the Linked List head = newNode('a'); head->next = newNode('b'); head->next->next = newNode('c'); head->next->next->next = newNode('e'); head->next->next->next->next = newNode('f'); head->next->next->next->next->next = newNode('g'); head->next->next->next->next->next->next = newNode('i'); head->next->next->next->next->next->next->next = newNode('o'); // Print the given Linked List printf("Linked list before :\n"); printlist(head); removeVowels(); // Print the Linked List after // removing vowels printf("Linked list after :\n"); printlist(head); return 0;} // Java program to remove vowels// Nodes in a linked listimport java.io.*; // A linked list nodeclass Node{ char data; Node next; // Function to add new node to the // List Node(char item) { data = item; next = null; }}class GFG{ // Head Node public static Node head; // Utility function to print the // linked list static void printlist(Node head) { if(head == null) { System.out.println("Empty List"); } while(head != null) { System.out.print(head.data + " "); if(head.next != null) { System.out.print("-> "); } head = head.next; } System.out.println(); } // Utility function for checking vowel static boolean isVowel(char x) { return (x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u' || x == 'A' || x == 'E' || x == 'I' || x == 'O' || x == 'U'); } // Function to remove the vowels Node static void removeVowels() { // Node pointing to head Node Node ptr = head; // Case 1 : Remove the trailing // vowels while(ptr != null) { // If current Node is a vowel // node then move the pointer // to next node if(isVowel(ptr.data)) { ptr = ptr.next; } // Else break if a consonant // node is found else { break; } } // This prev node used to link // prev consonant to next // consonant after vowels Node prev = ptr; // Head points to the first // consonant of the linked list head = ptr; ptr = ptr.next; // Case 2: If vowels found in // between of the linked list while(ptr != null) { // If current node is vowel if(isVowel(ptr.data)) { // Move ptr to the next // node ptr = ptr.next; // Check for vowels // occurring continuously while(ptr != null) { // If ptr is a vowel // move to next pointer if(isVowel(ptr.data)) { ptr = ptr.next; } // Else break if // consonant found else { break; } } // Case 3: If we have ending // vowels then link the prev // consonant to NULL if(ptr == null) { prev.next = null; break; } // Case 2: change the next // link of prev to current // consonant pointing to // ptr else { prev.next = ptr; } } // Move prev and ptr to next // for next iteration prev = prev.next; ptr = ptr.next; } } // Driver code public static void main (String[] args) { // Initialise the Linked List GFG tree = new GFG(); tree.head = new Node('a'); tree.head.next = new Node('b'); tree.head.next.next = new Node('c'); tree.head.next.next.next = new Node('e'); tree.head.next.next.next.next = new Node('f'); tree.head.next.next.next.next.next = new Node('g'); tree.head.next.next.next.next.next.next = new Node('i'); tree.head.next.next.next.next.next.next.next = new Node('o'); // Print the given Linked List System.out.println("Linked list before :"); printlist(head); removeVowels(); // Print the Linked List after // removing vowels System.out.println("Linked list after :"); printlist(head); }} // This code is contributed by avanitrachhadiya2155 # Python3 program to remove vowels# Nodes in a linked list # A linked list nodeclass Node: def __init__(self, x): self.data = x self.next = None # Head Nodehead = None # Utility function to print the# linked listdef printlist(head): if (not head): print("Empty List") return while (head != None): print(head.data, end = " ") if (head.next): print(end="-> ") head = head.next print() # Utility function for checking voweldef isVowel(x): return (x == 'a' or x == 'e' or x == 'i' or x == 'o' or x == 'u' or x == 'A' or x == 'E' or x == 'I' or x == 'O' or x == 'U') # Function to remove the vowels Nodedef removeVowels(): global head # Node pointing to head Node ptr = head # Case 1 : Remove the trailing # vowels while (ptr != None): # If current Node is a vowel # node then move the pointer # to next node if (isVowel(ptr.data)): ptr = ptr.next # Else break if a consonant # node is found else: break # This prev node used to link # prev consonant to next # consonant after vowels prev = ptr # Head points to the first # consonant of the linked list head = ptr ptr = ptr.next # Case 2: If vowels found in # between of the linked list while (ptr != None): # If current node is vowel if (isVowel(ptr.data)): # Move ptr to the next # node ptr = ptr.next # Check for vowels # occurring continuously while (ptr != None): # If ptr is a vowel # move to next pointer if (isVowel(ptr.data)): ptr = ptr.next # Else break if # consonant found else: break # Case 3: If we have ending # vowels then link the prev # consonant to NULL if (ptr == None): prev.next = None break # Case 2: change the next # link of prev to current # consonant pointing to # ptr else: prev.next = ptr # Move prev and ptr to next # for next iteration prev = prev.next ptr = ptr.next # Driver codeif __name__ == '__main__': # Initialise the Linked List head = Node('a') head.next = Node('b') head.next.next = Node('c') head.next.next.next = Node('e') head.next.next.next.next = Node('f') head.next.next.next.next.next = Node('g') head.next.next.next.next.next.next = Node('i') head.next.next.next.next.next.next.next = Node('o') # Print the given Linked List print("Linked list before :") printlist(head) removeVowels() # Print the Linked List after # removing vowels print("Linked list after :") printlist(head) # This code is contributed by mohit kumar 29 // C# program to remove vowels// Nodes in a linked listusing System; // A linked list nodeclass Node{ public char data; public Node next; // Function to add new node to the // List public Node(char item) { data = item; next = null; }} class GFG{ // Head Nodestatic Node head; // Utility function to print the// linked liststatic void printlist(Node head){ if (head == null) { Console.WriteLine("Empty List"); } while (head != null) { Console.Write(head.data + " "); if (head.next != null) { Console.Write("-> "); } head = head.next; } Console.WriteLine();} // Utility function for checking vowelstatic bool isVowel(char x){ return (x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u' || x == 'A' || x == 'E' || x == 'I' || x == 'O' || x == 'U');} // Function to remove the vowels Nodestatic void removeVowels(){ // Node pointing to head Node Node ptr = head; // Case 1 : Remove the trailing // vowels while (ptr != null) { // If current Node is a vowel // node then move the pointer // to next node if (isVowel(ptr.data)) { ptr = ptr.next; } // Else break if a consonant // node is found else { break; } } // This prev node used to link // prev consonant to next // consonant after vowels Node prev = ptr; // Head points to the first // consonant of the linked list head = ptr; ptr = ptr.next; // Case 2: If vowels found in // between of the linked list while (ptr != null) { // If current node is vowel if (isVowel(ptr.data)) { // Move ptr to the next // node ptr = ptr.next; // Check for vowels // occurring continuously while (ptr != null) { // If ptr is a vowel // move to next pointer if (isVowel(ptr.data)) { ptr = ptr.next; } // Else break if // consonant found else { break; } } // Case 3: If we have ending // vowels then link the prev // consonant to NULL if (ptr == null) { prev.next = null; break; } // Case 2: change the next // link of prev to current // consonant pointing to // ptr else { prev.next = ptr; } } // Move prev and ptr to next // for next iteration prev = prev.next; ptr = ptr.next; }} // Driver codestatic public void Main(){ // Initialise the Linked List GFG.head = new Node('a'); GFG.head.next = new Node('b'); GFG.head.next.next = new Node('c'); GFG.head.next.next.next = new Node('e'); GFG.head.next.next.next.next = new Node('f'); GFG.head.next.next.next.next.next = new Node('g'); GFG.head.next.next.next.next.next.next = new Node('i'); GFG.head.next.next.next.next.next.next.next = new Node('o'); // Print the given Linked List Console.WriteLine("Linked list before :"); printlist(head); removeVowels(); // Print the Linked List after // removing vowels Console.WriteLine("Linked list after :"); printlist(head);}} // This code is contributed by rag2127 <script>// javascript program to remove vowels// Nodes in a linked list// A linked list nodeclass Node { // Function to add new node to the // List constructor( item) { this.data = item; this.next = null; }} // Head Node var head; // Utility function to print the // linked list function printlist(head) { if (head == null) { document.write("Empty List"); } while (head != null) { document.write(head.data + " "); if (head.next != null) { document.write("-> "); } head = head.next; } document.write("<br/>"); } // Utility function for checking vowel function isVowel( x) { return (x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u' || x == 'A' || x == 'E' || x == 'I' || x == 'O'|| x == 'U'); } // Function to remove the vowels Node function removeVowels() { // Node pointing to head Node var ptr = head; // Case 1 : Remove the trailing // vowels while (ptr != null) { // If current Node is a vowel // node then move the pointer // to next node if (isVowel(ptr.data)) { ptr = ptr.next; } // Else break if a consonant // node is found else { break; } } // This prev node used to link // prev consonant to next // consonant after vowels var prev = ptr; // Head points to the first // consonant of the linked list head = ptr; ptr = ptr.next; // Case 2: If vowels found in // between of the linked list while (ptr != null) { // If current node is vowel if (isVowel(ptr.data)) { // Move ptr to the next // node ptr = ptr.next; // Check for vowels // occurring continuously while (ptr != null) { // If ptr is a vowel // move to next pointer if (isVowel(ptr.data)) { ptr = ptr.next; } // Else break if // consonant found else { break; } } // Case 3: If we have ending // vowels then link the prev // consonant to NULL if (ptr == null) { prev.next = null; break; } // Case 2: change the next // link of prev to current // consonant pointing to // ptr else { prev.next = ptr; } } // Move prev and ptr to next // for next iteration prev = prev.next; ptr = ptr.next; } } // Driver code // Initialise the Linked List head = new Node('a'); head.next = new Node('b'); head.next.next = new Node('c'); head.next.next.next = new Node('e'); head.next.next.next.next = new Node('f'); head.next.next.next.next.next = new Node('g'); head.next.next.next.next.next.next = new Node('i'); head.next.next.next.next.next.next.next = new Node('o'); // Print the given Linked List document.write("Linked list before :<br/>"); printlist(head); removeVowels(); // Print the Linked List after // removing vowels document.write("Linked list after :<br/>"); printlist(head); // This code is contributed by Rajput-Ji</script> Linked list before : a -> b -> c -> e -> f -> g -> i -> o Linked list after : b -> c -> f -> g Time Complexity: O(N) where N is the number of nodes in the linked list. nidhi_biet mohit kumar 29 avanitrachhadiya2155 rag2127 Rajput-Ji Kirti_Mangal Linked List Linked List Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Data Structures What is Data Structure: Types, Classifications and Applications Types of Linked List Circular Singly Linked List | Insertion Find first node of loop in a linked list Add two numbers represented by linked lists | Set 2 Flattening a Linked List Real-time application of Data Structures Insert a node at a specific position in a linked list Clone a linked list with next and random pointer | Set 1
[ { "code": null, "e": 54, "s": 26, "text": "\n03 Jun, 2021" }, { "code": null, "e": 143, "s": 54, "text": "Given a singly linked list, the task is to remove the vowels from the given linked list." }, { "code": null, "e": 154, "s": 143, "text": "Examples: " }, { "code": null, "e": 385, "s": 154, "text": "Input: g -> e -> e -> k -> s -> f -> o -> r -> g -> e -> e -> k -> s Output: g -> k -> s -> f -> r -> g -> k -> s Explanation: After removing vowels {e, e}, {o}, {e, e}. The linked list becomes g -> k -> s -> f -> r -> g -> k -> s" }, { "code": null, "e": 601, "s": 385, "text": "Input: a -> a -> a -> g -> e -> e -> k -> s -> i -> i -> i -> m Output: g -> k -> s -> m Explanation: After removing vowels {a, a, a}, {e, e}, {i, i, i}. The linked list becomes g -> k -> s -> f -> r -> g -> k -> s " }, { "code": null, "e": 690, "s": 601, "text": "Approach: There are three cases where we can find the vowels in the given linked list: " }, { "code": null, "e": 868, "s": 690, "text": "At the starting of the linked list: For removing vowels from the start of the linked list, move the head Node to the first consonant that occurs in the linked list. For Example:" }, { "code": null, "e": 1005, "s": 868, "text": "For Linked List:\na -> e -> i -> a -> c -> r -> d -> NULL\nAfter moving the head Node from Node a to Node c, We have \nc -> r -> d -> NULL" }, { "code": null, "e": 1320, "s": 1005, "text": "In the between of the linked list: For removing vowels from the between of the linked list, the idea is to keep a marker of the last consonant found in the linked list before the vowel Nodes and change the next link of that Node with the next consonant Node found in the linked list after vowel Nodes. For Example:" }, { "code": null, "e": 1576, "s": 1320, "text": "For Linked List:\nc -> r -> d -> a -> e -> i -> a -> c -> r -> z -> NULL\nlast consonant before vowels {a, e, i, a} is d\nand next consonant after vowels {a, e, i, a} is r\nAfter linking next pointer of Node d to Node r, We have \nc -> r -> d -> r -> z -> NULL" }, { "code": null, "e": 1821, "s": 1576, "text": "At the end of the linked list: For removing vowels from the end of the linked list, the idea is to keep a marker of the last consonant found in the linked list before the vowel Nodes and change the next link of that Node with NULL. For Example:" }, { "code": null, "e": 2001, "s": 1821, "text": "For Linked List:\nc -> r -> d -> a -> e -> i -> a -> NULL\nlast consonant before vowels {a, e, i, a} is d\nAfter changing the next link of Node to NULL, We have \nc -> r -> d -> NULL" }, { "code": null, "e": 2052, "s": 2001, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 2056, "s": 2052, "text": "C++" }, { "code": null, "e": 2061, "s": 2056, "text": "Java" }, { "code": null, "e": 2069, "s": 2061, "text": "Python3" }, { "code": null, "e": 2072, "s": 2069, "text": "C#" }, { "code": null, "e": 2083, "s": 2072, "text": "Javascript" }, { "code": "// C++ program to remove vowels// Nodes in a linked list#include <bits/stdc++.h>using namespace std; // A linked list nodestruct Node { char data; struct Node* next;}; // Head Nodestruct Node* head; // Function to add new node to the// ListNode* newNode(char key){ Node* temp = new Node; temp->data = key; temp->next = NULL; return temp;} // Utility function to print the// linked listvoid printlist(Node* head){ if (!head) { cout << \"Empty List\\n\"; return; } while (head != NULL) { cout << head->data << \" \"; if (head->next) cout << \"-> \"; head = head->next; } cout << endl;} // Utility function for checking vowelbool isVowel(char x){ return (x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u' || x == 'A' || x == 'E' || x == 'I' || x == 'O' || x == 'U');} // Function to remove the vowels Nodevoid removeVowels(){ // Node pointing to head Node struct Node* ptr = head; // Case 1 : Remove the trailing // vowels while (ptr != NULL) { // If current Node is a vowel // node then move the pointer // to next node if (isVowel(ptr->data)) ptr = ptr->next; // Else break if a consonant // node is found else break; } // This prev node used to link // prev consonant to next // consonant after vowels struct Node* prev = ptr; // Head points to the first // consonant of the linked list head = ptr; ptr = ptr->next; // Case 2: If vowels found in // between of the linked list while (ptr != NULL) { // If current node is vowel if (isVowel(ptr->data)) { // Move ptr to the next // node ptr = ptr->next; // Check for vowels // occurring continuously while (ptr != NULL) { // If ptr is a vowel // move to next pointer if (isVowel(ptr->data)) { ptr = ptr->next; } // Else break if // consonant found else break; } // Case 3: If we have ending // vowels then link the prev // consonant to NULL if (ptr == NULL) { prev->next = NULL; break; } // Case 2: change the next // link of prev to current // consonant pointing to // ptr else { prev->next = ptr; } } // Move prev and ptr to next // for next iteration prev = prev->next; ptr = ptr->next; }} // Driver codeint main(){ // Initialise the Linked List head = newNode('a'); head->next = newNode('b'); head->next->next = newNode('c'); head->next->next->next = newNode('e'); head->next->next->next->next = newNode('f'); head->next->next->next->next->next = newNode('g'); head->next->next->next->next->next->next = newNode('i'); head->next->next->next->next->next->next->next = newNode('o'); // Print the given Linked List printf(\"Linked list before :\\n\"); printlist(head); removeVowels(); // Print the Linked List after // removing vowels printf(\"Linked list after :\\n\"); printlist(head); return 0;}", "e": 5471, "s": 2083, "text": null }, { "code": "// Java program to remove vowels// Nodes in a linked listimport java.io.*; // A linked list nodeclass Node{ char data; Node next; // Function to add new node to the // List Node(char item) { data = item; next = null; }}class GFG{ // Head Node public static Node head; // Utility function to print the // linked list static void printlist(Node head) { if(head == null) { System.out.println(\"Empty List\"); } while(head != null) { System.out.print(head.data + \" \"); if(head.next != null) { System.out.print(\"-> \"); } head = head.next; } System.out.println(); } // Utility function for checking vowel static boolean isVowel(char x) { return (x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u' || x == 'A' || x == 'E' || x == 'I' || x == 'O' || x == 'U'); } // Function to remove the vowels Node static void removeVowels() { // Node pointing to head Node Node ptr = head; // Case 1 : Remove the trailing // vowels while(ptr != null) { // If current Node is a vowel // node then move the pointer // to next node if(isVowel(ptr.data)) { ptr = ptr.next; } // Else break if a consonant // node is found else { break; } } // This prev node used to link // prev consonant to next // consonant after vowels Node prev = ptr; // Head points to the first // consonant of the linked list head = ptr; ptr = ptr.next; // Case 2: If vowels found in // between of the linked list while(ptr != null) { // If current node is vowel if(isVowel(ptr.data)) { // Move ptr to the next // node ptr = ptr.next; // Check for vowels // occurring continuously while(ptr != null) { // If ptr is a vowel // move to next pointer if(isVowel(ptr.data)) { ptr = ptr.next; } // Else break if // consonant found else { break; } } // Case 3: If we have ending // vowels then link the prev // consonant to NULL if(ptr == null) { prev.next = null; break; } // Case 2: change the next // link of prev to current // consonant pointing to // ptr else { prev.next = ptr; } } // Move prev and ptr to next // for next iteration prev = prev.next; ptr = ptr.next; } } // Driver code public static void main (String[] args) { // Initialise the Linked List GFG tree = new GFG(); tree.head = new Node('a'); tree.head.next = new Node('b'); tree.head.next.next = new Node('c'); tree.head.next.next.next = new Node('e'); tree.head.next.next.next.next = new Node('f'); tree.head.next.next.next.next.next = new Node('g'); tree.head.next.next.next.next.next.next = new Node('i'); tree.head.next.next.next.next.next.next.next = new Node('o'); // Print the given Linked List System.out.println(\"Linked list before :\"); printlist(head); removeVowels(); // Print the Linked List after // removing vowels System.out.println(\"Linked list after :\"); printlist(head); }} // This code is contributed by avanitrachhadiya2155", "e": 8883, "s": 5471, "text": null }, { "code": "# Python3 program to remove vowels# Nodes in a linked list # A linked list nodeclass Node: def __init__(self, x): self.data = x self.next = None # Head Nodehead = None # Utility function to print the# linked listdef printlist(head): if (not head): print(\"Empty List\") return while (head != None): print(head.data, end = \" \") if (head.next): print(end=\"-> \") head = head.next print() # Utility function for checking voweldef isVowel(x): return (x == 'a' or x == 'e' or x == 'i' or x == 'o' or x == 'u' or x == 'A' or x == 'E' or x == 'I' or x == 'O' or x == 'U') # Function to remove the vowels Nodedef removeVowels(): global head # Node pointing to head Node ptr = head # Case 1 : Remove the trailing # vowels while (ptr != None): # If current Node is a vowel # node then move the pointer # to next node if (isVowel(ptr.data)): ptr = ptr.next # Else break if a consonant # node is found else: break # This prev node used to link # prev consonant to next # consonant after vowels prev = ptr # Head points to the first # consonant of the linked list head = ptr ptr = ptr.next # Case 2: If vowels found in # between of the linked list while (ptr != None): # If current node is vowel if (isVowel(ptr.data)): # Move ptr to the next # node ptr = ptr.next # Check for vowels # occurring continuously while (ptr != None): # If ptr is a vowel # move to next pointer if (isVowel(ptr.data)): ptr = ptr.next # Else break if # consonant found else: break # Case 3: If we have ending # vowels then link the prev # consonant to NULL if (ptr == None): prev.next = None break # Case 2: change the next # link of prev to current # consonant pointing to # ptr else: prev.next = ptr # Move prev and ptr to next # for next iteration prev = prev.next ptr = ptr.next # Driver codeif __name__ == '__main__': # Initialise the Linked List head = Node('a') head.next = Node('b') head.next.next = Node('c') head.next.next.next = Node('e') head.next.next.next.next = Node('f') head.next.next.next.next.next = Node('g') head.next.next.next.next.next.next = Node('i') head.next.next.next.next.next.next.next = Node('o') # Print the given Linked List print(\"Linked list before :\") printlist(head) removeVowels() # Print the Linked List after # removing vowels print(\"Linked list after :\") printlist(head) # This code is contributed by mohit kumar 29", "e": 11911, "s": 8883, "text": null }, { "code": "// C# program to remove vowels// Nodes in a linked listusing System; // A linked list nodeclass Node{ public char data; public Node next; // Function to add new node to the // List public Node(char item) { data = item; next = null; }} class GFG{ // Head Nodestatic Node head; // Utility function to print the// linked liststatic void printlist(Node head){ if (head == null) { Console.WriteLine(\"Empty List\"); } while (head != null) { Console.Write(head.data + \" \"); if (head.next != null) { Console.Write(\"-> \"); } head = head.next; } Console.WriteLine();} // Utility function for checking vowelstatic bool isVowel(char x){ return (x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u' || x == 'A' || x == 'E' || x == 'I' || x == 'O' || x == 'U');} // Function to remove the vowels Nodestatic void removeVowels(){ // Node pointing to head Node Node ptr = head; // Case 1 : Remove the trailing // vowels while (ptr != null) { // If current Node is a vowel // node then move the pointer // to next node if (isVowel(ptr.data)) { ptr = ptr.next; } // Else break if a consonant // node is found else { break; } } // This prev node used to link // prev consonant to next // consonant after vowels Node prev = ptr; // Head points to the first // consonant of the linked list head = ptr; ptr = ptr.next; // Case 2: If vowels found in // between of the linked list while (ptr != null) { // If current node is vowel if (isVowel(ptr.data)) { // Move ptr to the next // node ptr = ptr.next; // Check for vowels // occurring continuously while (ptr != null) { // If ptr is a vowel // move to next pointer if (isVowel(ptr.data)) { ptr = ptr.next; } // Else break if // consonant found else { break; } } // Case 3: If we have ending // vowels then link the prev // consonant to NULL if (ptr == null) { prev.next = null; break; } // Case 2: change the next // link of prev to current // consonant pointing to // ptr else { prev.next = ptr; } } // Move prev and ptr to next // for next iteration prev = prev.next; ptr = ptr.next; }} // Driver codestatic public void Main(){ // Initialise the Linked List GFG.head = new Node('a'); GFG.head.next = new Node('b'); GFG.head.next.next = new Node('c'); GFG.head.next.next.next = new Node('e'); GFG.head.next.next.next.next = new Node('f'); GFG.head.next.next.next.next.next = new Node('g'); GFG.head.next.next.next.next.next.next = new Node('i'); GFG.head.next.next.next.next.next.next.next = new Node('o'); // Print the given Linked List Console.WriteLine(\"Linked list before :\"); printlist(head); removeVowels(); // Print the Linked List after // removing vowels Console.WriteLine(\"Linked list after :\"); printlist(head);}} // This code is contributed by rag2127", "e": 15674, "s": 11911, "text": null }, { "code": "<script>// javascript program to remove vowels// Nodes in a linked list// A linked list nodeclass Node { // Function to add new node to the // List constructor( item) { this.data = item; this.next = null; }} // Head Node var head; // Utility function to print the // linked list function printlist(head) { if (head == null) { document.write(\"Empty List\"); } while (head != null) { document.write(head.data + \" \"); if (head.next != null) { document.write(\"-> \"); } head = head.next; } document.write(\"<br/>\"); } // Utility function for checking vowel function isVowel( x) { return (x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u' || x == 'A' || x == 'E' || x == 'I' || x == 'O'|| x == 'U'); } // Function to remove the vowels Node function removeVowels() { // Node pointing to head Node var ptr = head; // Case 1 : Remove the trailing // vowels while (ptr != null) { // If current Node is a vowel // node then move the pointer // to next node if (isVowel(ptr.data)) { ptr = ptr.next; } // Else break if a consonant // node is found else { break; } } // This prev node used to link // prev consonant to next // consonant after vowels var prev = ptr; // Head points to the first // consonant of the linked list head = ptr; ptr = ptr.next; // Case 2: If vowels found in // between of the linked list while (ptr != null) { // If current node is vowel if (isVowel(ptr.data)) { // Move ptr to the next // node ptr = ptr.next; // Check for vowels // occurring continuously while (ptr != null) { // If ptr is a vowel // move to next pointer if (isVowel(ptr.data)) { ptr = ptr.next; } // Else break if // consonant found else { break; } } // Case 3: If we have ending // vowels then link the prev // consonant to NULL if (ptr == null) { prev.next = null; break; } // Case 2: change the next // link of prev to current // consonant pointing to // ptr else { prev.next = ptr; } } // Move prev and ptr to next // for next iteration prev = prev.next; ptr = ptr.next; } } // Driver code // Initialise the Linked List head = new Node('a'); head.next = new Node('b'); head.next.next = new Node('c'); head.next.next.next = new Node('e'); head.next.next.next.next = new Node('f'); head.next.next.next.next.next = new Node('g'); head.next.next.next.next.next.next = new Node('i'); head.next.next.next.next.next.next.next = new Node('o'); // Print the given Linked List document.write(\"Linked list before :<br/>\"); printlist(head); removeVowels(); // Print the Linked List after // removing vowels document.write(\"Linked list after :<br/>\"); printlist(head); // This code is contributed by Rajput-Ji</script>", "e": 19471, "s": 15674, "text": null }, { "code": null, "e": 19567, "s": 19471, "text": "Linked list before :\na -> b -> c -> e -> f -> g -> i -> o \nLinked list after :\nb -> c -> f -> g" }, { "code": null, "e": 19643, "s": 19569, "text": "Time Complexity: O(N) where N is the number of nodes in the linked list. " }, { "code": null, "e": 19654, "s": 19643, "text": "nidhi_biet" }, { "code": null, "e": 19669, "s": 19654, "text": "mohit kumar 29" }, { "code": null, "e": 19690, "s": 19669, "text": "avanitrachhadiya2155" }, { "code": null, "e": 19698, "s": 19690, "text": "rag2127" }, { "code": null, "e": 19708, "s": 19698, "text": "Rajput-Ji" }, { "code": null, "e": 19721, "s": 19708, "text": "Kirti_Mangal" }, { "code": null, "e": 19733, "s": 19721, "text": "Linked List" }, { "code": null, "e": 19745, "s": 19733, "text": "Linked List" }, { "code": null, "e": 19843, "s": 19745, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 19875, "s": 19843, "text": "Introduction to Data Structures" }, { "code": null, "e": 19939, "s": 19875, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 19960, "s": 19939, "text": "Types of Linked List" }, { "code": null, "e": 20000, "s": 19960, "text": "Circular Singly Linked List | Insertion" }, { "code": null, "e": 20041, "s": 20000, "text": "Find first node of loop in a linked list" }, { "code": null, "e": 20093, "s": 20041, "text": "Add two numbers represented by linked lists | Set 2" }, { "code": null, "e": 20118, "s": 20093, "text": "Flattening a Linked List" }, { "code": null, "e": 20159, "s": 20118, "text": "Real-time application of Data Structures" }, { "code": null, "e": 20213, "s": 20159, "text": "Insert a node at a specific position in a linked list" } ]
Review Rating Prediction: A Combined Approach | by Yereya Berdugo | Towards Data Science
The rise in E — commerce, has brought a significant rise in the importance of customer reviews. There are hundreds of review sites online and massive amounts of reviews for every product. Customers have changed their way of shopping and according to a recent survey, 70 percent of customers say that they use rating filters to filter out low rated items in their searches. The ability to successfully decide whether a review will be helpful to other customers and thus give the product more exposure is vital to companies that support these reviews, companies like Google, Amazon and Yelp!. There are two main methods to approach this problem. The first one is based on review text content analysis and uses the principles of natural language process (the NLP method). This method lacks the insights that can be drawn from the relationship between costumers and items. The second one is based on recommender systems, specifically on collaborative filtering, and focuses on the reviewer’s point of view. Use of the user’s similarity matrix and applying neighbors analysis are all part of this method. This method ignores any information from the review text content analysis. In an effort to obtain more information and to improve the prediction of the review rating, the researchers in this article proposed a framework combining review text content with previous user’s similarity matrix analysis. They then did some experiments on two movie review datasets to examine the efficiency of their hypothesis. The results that they got showed that their framework indeed improved prediction of the review rating. This article will describe my attempt of following the work done in their research through examples from the Amazon reviews dataset. The notebook documenting this work is available here and I encourage running the code on your computer and report the results. The dataset used here was made available by Dr. Julian McAuley from the UCSD. It contains product reviews and metadata from Amazon, including 142.8 million reviews spanning May 1996 — July 2014. The product reviews dataset contains user ID, product ID, rating, helpfulness votes, and review text for each review. The data can be found here. In this work my goal was to check the researchers’ thesis. It was not to find the best model for the problem. I will try to prove that combining formerly known data about each user’s similarity to other users, with the sentiment analysis of the review text itself, will help us improve the model prediction of what rating the user’s review will get. As a first step, I will perform the RRP based on RTC analysis. The next step will be to apply a neighbors analysis to perform RRP based on the similarity between users. The final step will be to compare the three methods (RRP based on RTC, RRP based on neighbors analysis and the combination of the two) and to check the hypothesis. Preprocessing is a key step in any analysis and in this project as well. The head of the primary table is as follows: First, I deleted rows with no review text, duplicate lines and extra columns that I will not be used.The second step was to create a column that contains the results from the division of helpful numerator and helpful denominator and then to segment these values into bins. It looked like this: reviews_df = reviews_df[~pd.isnull(reviews_df['reviewText'])]reviews_df.drop_duplicates(subset=['reviewerID', 'asin', 'unixReviewTime'], inplace=True)reviews_df.drop('Unnamed: 0', axis=1, inplace=True)reviews_df.reset_index(inplace=True)reviews_df['helpful_numerator'] = reviews_df['helpful'].apply(lambda x: eval(x)[0])reviews_df['helpful_denominator'] = reviews_df['helpful'].apply(lambda x: eval(x)[1])reviews_df['helpful%'] = np.where(reviews_df['helpful_denominator'] > 0, reviews_df['helpful_numerator'] / reviews_df['helpful_denominator'], -1)reviews_df['helpfulness_range'] = pd.cut(x=reviews_df['helpful%'], bins=[-1, 0, 0.2, 0.4, 0.6, 0.8, 1.0], labels=['empty', '1', '2', '3', '4', '5'], include_lowest=True) The last step was to create a text processor that extracted the meaningful words from the messy review text. def text_process(reviewText): nopunc = [i for i in reviewText if i not in string.punctuation] nopunc = nopunc.lower() nopunc_text = ''.join(nopunc) return [i for i in nopunc_text.split() if i not in stopwords.words('english')] After being applied this had -1. Removed punctuation2. Converted to lowercase3. Removed Stop words (non-relevant words in the context of training the model) The head of the primary table, after all the preprocessing, looks like this: The figures below shows how the users helpfulness range is distributed over the product rating: One can easily see the bias towards the higher ratings. This phenomenon is well known, and it is also supported in the same survey from above. According to that survey: “Reviews are increasingly shifting from being a place where consumers air their grievances to being a place to recommend items after a positive experience”. Later on, I will explain how the problem of the skewed data was solved (resampling methods). In order to check and choose the best model, I constructed a pipeline that did the following steps. The pipeline will first perform a TF-IDF term weighting and vectorizing and will then run the classification algorithm. In general, TF-IDF will process the text using my “text_process” function from above, and then convert the processed text to a count vector. Afterwards, it will apply a calculation that will assign a higher weight to words of more importance. pipeline = Pipeline([ ('Tf-Idf', TfidfVectorizer(ngram_range=(1,2), analyzer=text_process)), ('classifier', MultinomialNB())])X = reviews_df['reviewText']y = reviews_df['helpfulness_range']review_train, review_test, label_train, label_test = train_test_split(X, y, test_size=0.5)pipeline.fit(review_train, label_train)pip_pred = pipeline.predict(review_test)print(metrics.classification_report(label_test, pip_pred)) Note that I chose ngram_range = (1, 2) and that the algorithm was Multinomial Naïve Bayes. Those decisions were taken according to the results of a cross-validation test. The cross-validation test that I did is beyond the scope of this article, but you can find it in the notebook. The models checked were: 1. Multinomial logistic regression, as a benchmark 2. Multinomial Naïve Bayes 3. Decision Tree 4. Random forest Multinomial Naïve Bayes gave the best accuracy score1 (0.61) and therefore the predictions made by it were chosen to represent the RRP based on RTC. The final part in this step is to export the predictions made by the chosen model to a csv file: rev_test_pred_NB_df = pd.DataFrame(data={'review_test': review_test2, 'prediction': pip_pred2})rev_test_pred_NB_df.to_csv('rev_test_pred_NB_df.csv') In this step is the user similarity matrix is constructed and is the basis on which I will calculate the cosine similarity between each user. Some problems occurred when I constructed the matrix using the names of the items but were solved by converting to a unique integers sequence (same as IDENTITY property in SQL). temp_df = pd.DataFrame(np.unique(reviewers_rating_df['reviewerID']), columns=['unique_ID'])temp_df['unique_asin'] = pd.Series(np.unique(reviewers_rating_df['asin']))temp_df['unique_ID_int'] = range(20000, 35998)temp_df['unique_asin_int'] = range(1, 15999)reviewers_rating_df = pd.merge(reviewers_rating_df, temp_df.drop(['unique_asin', 'unique_asin_int'], axis=1), left_on='reviewerID', right_on='unique_ID')reviewers_rating_df = pd.merge(reviewers_rating_df, temp_df.drop(['unique_ID', 'unique_ID_int'], axis=1),left_on='asin', right_on='unique_asin')reviewers_rating_df['overall_rating'] = reviewers_rating_df['overall']id_asin_helpfulness_df = reviewers_rating_df[['reviewerID', 'unique_ID_int', 'helpfulness_range']].copy()# Delete the not in use columns:reviewers_rating_df.drop(['asin', 'unique_asin', 'reviewerID', 'unique_ID', 'overall', 'helpfulness_range'], axis=1, inplace=True) Construct the matrix: I used pivot to bring the data to the proper shape and then “csr_matrix” to convert it to sparse matrix in order to save processing time. matrix = reviewers_rating_df.pivot(index='unique_ID_int', columns='unique_asin_int', values='overall_rating')matrix = matrix.fillna(0)user_item_matrix = sparse.csr_matrix(matrix.values) I used the K-Nearest Neighbors algorithm to produce the neighbors analysis. The KNN model is easy to implement and to interpret. The similarity measure was cosine similarity and the number of the desired neighbors was ten. model_knn = neighbors.NearestNeighbors(metric='cosine', algorithm='brute', n_neighbors=10)model_knn.fit(user_item_matrix) After the training stage I extracted the list of the neighbors and stored it as a NumPy array. That yielded a 2-d array of users and the ten users that are most similar to them. neighbors = np.asarray(model_knn.kneighbors(user_item_matrix, return_distance=False)) The next step was to grab the ten closest neighbors and store them in a dataframe: unique_id = []k_neigh = []for i in range(15998): unique_id.append(i + 20000) k_neigh.append(list(neighbors[i][1:10])) #Grabbing the ten closest neighborsneighbors_df = pd.DataFrame(data={'unique_ID_int': unique_id, 'k_neigh': k_neigh})id_asin_helpfulness_df = pd.merge(id_asin_helpfulness_df, neighbors_df, on='unique_ID_int')id_asin_helpfulness_df['neigh_based_helpf'] = id_asin_helpfulness_df['unique_ID_int'] Finally, to calculate the mean score of the reviews that the ten closest reviewers wrote I coded a nested loop that would iterate through each row. The loop would then iterate through every one of the user’s ten neighbors and calculate the mean score that their reviews got. for index, row in id_asin_helpfulness_df.iterrows(): row = row['k_neigh'] lista = [] for i in row: p = id_asin_helpfulness_df.loc[i]['helpfulness_range'] lista.append(p) id_asin_helpfulness_df.loc[index, 'neigh_based_helpf'] = np.nanmean(lista) As a third step I exported the results from the calculation above and merged them with the predictions from the chosen model. I then had a file that consisted of four columns: 1) The original reviews 2) The scores they got (the ground truth) 3) The predictions from the first step (NLP approach) 4) The predictions from the second step (users similarity approach)The combination of the two methods can be done in many different ways. In this paper I chose the simple arithmetic average, but other methods would work as well.In addition to the four columns above, I now have a fifth column: 5) The arithmetic average of each row in columns 3) and 4) The metric used for comparing the models was Root Mean Squared Error (RMSE). It is a very common and good measure for comparing models. In addition, I chose to present the Mean Absolute Error (MAE) because it uses the same scale as the data being measured and therefor can be easily explained. The results2 are shown below: RMSE for neigh_based_helpf: 1.0338002581383618RMSE for NBprediction: 1.074619472976386RMSE for the combination of the two methods: 0.9920521481819871MAE for the combined prediction: 0.6618020568763793 The RMSE for the combined method was lower than the RMSE of each method alone. In conclusion, my thesis was proven to be correct. Combining the formerly known data about each user’s similarity to other users with the sentiment analysis of the review text itself, does help improve the model prediction of what rate the user’s review will get 1 This paper goal is to compare the methods and to see if the framework offered by the researchers will improve the predictions accuracy. It was not to find the most accurate model for RRP based on RTC. 2 Although MAE of 0.66 is not good, the main aim of this work was to check the hypothesis and not necessarily to seek the best RRP model.
[ { "code": null, "e": 544, "s": 171, "text": "The rise in E — commerce, has brought a significant rise in the importance of customer reviews. There are hundreds of review sites online and massive amounts of reviews for every product. Customers have changed their way of shopping and according to a recent survey, 70 percent of customers say that they use rating filters to filter out low rated items in their searches." }, { "code": null, "e": 762, "s": 544, "text": "The ability to successfully decide whether a review will be helpful to other customers and thus give the product more exposure is vital to companies that support these reviews, companies like Google, Amazon and Yelp!." }, { "code": null, "e": 1346, "s": 762, "text": "There are two main methods to approach this problem. The first one is based on review text content analysis and uses the principles of natural language process (the NLP method). This method lacks the insights that can be drawn from the relationship between costumers and items. The second one is based on recommender systems, specifically on collaborative filtering, and focuses on the reviewer’s point of view. Use of the user’s similarity matrix and applying neighbors analysis are all part of this method. This method ignores any information from the review text content analysis." }, { "code": null, "e": 2040, "s": 1346, "text": "In an effort to obtain more information and to improve the prediction of the review rating, the researchers in this article proposed a framework combining review text content with previous user’s similarity matrix analysis. They then did some experiments on two movie review datasets to examine the efficiency of their hypothesis. The results that they got showed that their framework indeed improved prediction of the review rating. This article will describe my attempt of following the work done in their research through examples from the Amazon reviews dataset. The notebook documenting this work is available here and I encourage running the code on your computer and report the results." }, { "code": null, "e": 2381, "s": 2040, "text": "The dataset used here was made available by Dr. Julian McAuley from the UCSD. It contains product reviews and metadata from Amazon, including 142.8 million reviews spanning May 1996 — July 2014. The product reviews dataset contains user ID, product ID, rating, helpfulness votes, and review text for each review. The data can be found here." }, { "code": null, "e": 2731, "s": 2381, "text": "In this work my goal was to check the researchers’ thesis. It was not to find the best model for the problem. I will try to prove that combining formerly known data about each user’s similarity to other users, with the sentiment analysis of the review text itself, will help us improve the model prediction of what rating the user’s review will get." }, { "code": null, "e": 3064, "s": 2731, "text": "As a first step, I will perform the RRP based on RTC analysis. The next step will be to apply a neighbors analysis to perform RRP based on the similarity between users. The final step will be to compare the three methods (RRP based on RTC, RRP based on neighbors analysis and the combination of the two) and to check the hypothesis." }, { "code": null, "e": 3182, "s": 3064, "text": "Preprocessing is a key step in any analysis and in this project as well. The head of the primary table is as follows:" }, { "code": null, "e": 3476, "s": 3182, "text": "First, I deleted rows with no review text, duplicate lines and extra columns that I will not be used.The second step was to create a column that contains the results from the division of helpful numerator and helpful denominator and then to segment these values into bins. It looked like this:" }, { "code": null, "e": 4269, "s": 3476, "text": "reviews_df = reviews_df[~pd.isnull(reviews_df['reviewText'])]reviews_df.drop_duplicates(subset=['reviewerID', 'asin', 'unixReviewTime'], inplace=True)reviews_df.drop('Unnamed: 0', axis=1, inplace=True)reviews_df.reset_index(inplace=True)reviews_df['helpful_numerator'] = reviews_df['helpful'].apply(lambda x: eval(x)[0])reviews_df['helpful_denominator'] = reviews_df['helpful'].apply(lambda x: eval(x)[1])reviews_df['helpful%'] = np.where(reviews_df['helpful_denominator'] > 0, reviews_df['helpful_numerator'] / reviews_df['helpful_denominator'], -1)reviews_df['helpfulness_range'] = pd.cut(x=reviews_df['helpful%'], bins=[-1, 0, 0.2, 0.4, 0.6, 0.8, 1.0], labels=['empty', '1', '2', '3', '4', '5'], include_lowest=True)" }, { "code": null, "e": 4378, "s": 4269, "text": "The last step was to create a text processor that extracted the meaningful words from the messy review text." }, { "code": null, "e": 4617, "s": 4378, "text": "def text_process(reviewText): nopunc = [i for i in reviewText if i not in string.punctuation] nopunc = nopunc.lower() nopunc_text = ''.join(nopunc) return [i for i in nopunc_text.split() if i not in stopwords.words('english')]" }, { "code": null, "e": 4774, "s": 4617, "text": "After being applied this had -1. Removed punctuation2. Converted to lowercase3. Removed Stop words (non-relevant words in the context of training the model)" }, { "code": null, "e": 4851, "s": 4774, "text": "The head of the primary table, after all the preprocessing, looks like this:" }, { "code": null, "e": 4947, "s": 4851, "text": "The figures below shows how the users helpfulness range is distributed over the product rating:" }, { "code": null, "e": 5116, "s": 4947, "text": "One can easily see the bias towards the higher ratings. This phenomenon is well known, and it is also supported in the same survey from above. According to that survey:" }, { "code": null, "e": 5273, "s": 5116, "text": "“Reviews are increasingly shifting from being a place where consumers air their grievances to being a place to recommend items after a positive experience”." }, { "code": null, "e": 5366, "s": 5273, "text": "Later on, I will explain how the problem of the skewed data was solved (resampling methods)." }, { "code": null, "e": 5829, "s": 5366, "text": "In order to check and choose the best model, I constructed a pipeline that did the following steps. The pipeline will first perform a TF-IDF term weighting and vectorizing and will then run the classification algorithm. In general, TF-IDF will process the text using my “text_process” function from above, and then convert the processed text to a count vector. Afterwards, it will apply a calculation that will assign a higher weight to words of more importance." }, { "code": null, "e": 6252, "s": 5829, "text": "pipeline = Pipeline([ ('Tf-Idf', TfidfVectorizer(ngram_range=(1,2), analyzer=text_process)), ('classifier', MultinomialNB())])X = reviews_df['reviewText']y = reviews_df['helpfulness_range']review_train, review_test, label_train, label_test = train_test_split(X, y, test_size=0.5)pipeline.fit(review_train, label_train)pip_pred = pipeline.predict(review_test)print(metrics.classification_report(label_test, pip_pred))" }, { "code": null, "e": 6674, "s": 6252, "text": "Note that I chose ngram_range = (1, 2) and that the algorithm was Multinomial Naïve Bayes. Those decisions were taken according to the results of a cross-validation test. The cross-validation test that I did is beyond the scope of this article, but you can find it in the notebook. The models checked were: 1. Multinomial logistic regression, as a benchmark 2. Multinomial Naïve Bayes 3. Decision Tree 4. Random forest" }, { "code": null, "e": 6824, "s": 6674, "text": "Multinomial Naïve Bayes gave the best accuracy score1 (0.61) and therefore the predictions made by it were chosen to represent the RRP based on RTC." }, { "code": null, "e": 6921, "s": 6824, "text": "The final part in this step is to export the predictions made by the chosen model to a csv file:" }, { "code": null, "e": 7070, "s": 6921, "text": "rev_test_pred_NB_df = pd.DataFrame(data={'review_test': review_test2, 'prediction': pip_pred2})rev_test_pred_NB_df.to_csv('rev_test_pred_NB_df.csv')" }, { "code": null, "e": 7390, "s": 7070, "text": "In this step is the user similarity matrix is constructed and is the basis on which I will calculate the cosine similarity between each user. Some problems occurred when I constructed the matrix using the names of the items but were solved by converting to a unique integers sequence (same as IDENTITY property in SQL)." }, { "code": null, "e": 8280, "s": 7390, "text": "temp_df = pd.DataFrame(np.unique(reviewers_rating_df['reviewerID']), columns=['unique_ID'])temp_df['unique_asin'] = pd.Series(np.unique(reviewers_rating_df['asin']))temp_df['unique_ID_int'] = range(20000, 35998)temp_df['unique_asin_int'] = range(1, 15999)reviewers_rating_df = pd.merge(reviewers_rating_df, temp_df.drop(['unique_asin', 'unique_asin_int'], axis=1), left_on='reviewerID', right_on='unique_ID')reviewers_rating_df = pd.merge(reviewers_rating_df, temp_df.drop(['unique_ID', 'unique_ID_int'], axis=1),left_on='asin', right_on='unique_asin')reviewers_rating_df['overall_rating'] = reviewers_rating_df['overall']id_asin_helpfulness_df = reviewers_rating_df[['reviewerID', 'unique_ID_int', 'helpfulness_range']].copy()# Delete the not in use columns:reviewers_rating_df.drop(['asin', 'unique_asin', 'reviewerID', 'unique_ID', 'overall', 'helpfulness_range'], axis=1, inplace=True)" }, { "code": null, "e": 8440, "s": 8280, "text": "Construct the matrix: I used pivot to bring the data to the proper shape and then “csr_matrix” to convert it to sparse matrix in order to save processing time." }, { "code": null, "e": 8626, "s": 8440, "text": "matrix = reviewers_rating_df.pivot(index='unique_ID_int', columns='unique_asin_int', values='overall_rating')matrix = matrix.fillna(0)user_item_matrix = sparse.csr_matrix(matrix.values)" }, { "code": null, "e": 8849, "s": 8626, "text": "I used the K-Nearest Neighbors algorithm to produce the neighbors analysis. The KNN model is easy to implement and to interpret. The similarity measure was cosine similarity and the number of the desired neighbors was ten." }, { "code": null, "e": 8971, "s": 8849, "text": "model_knn = neighbors.NearestNeighbors(metric='cosine', algorithm='brute', n_neighbors=10)model_knn.fit(user_item_matrix)" }, { "code": null, "e": 9149, "s": 8971, "text": "After the training stage I extracted the list of the neighbors and stored it as a NumPy array. That yielded a 2-d array of users and the ten users that are most similar to them." }, { "code": null, "e": 9235, "s": 9149, "text": "neighbors = np.asarray(model_knn.kneighbors(user_item_matrix, return_distance=False))" }, { "code": null, "e": 9318, "s": 9235, "text": "The next step was to grab the ten closest neighbors and store them in a dataframe:" }, { "code": null, "e": 9769, "s": 9318, "text": "unique_id = []k_neigh = []for i in range(15998): unique_id.append(i + 20000) k_neigh.append(list(neighbors[i][1:10])) #Grabbing the ten closest neighborsneighbors_df = pd.DataFrame(data={'unique_ID_int': unique_id, 'k_neigh': k_neigh})id_asin_helpfulness_df = pd.merge(id_asin_helpfulness_df, neighbors_df, on='unique_ID_int')id_asin_helpfulness_df['neigh_based_helpf'] = id_asin_helpfulness_df['unique_ID_int']" }, { "code": null, "e": 10044, "s": 9769, "text": "Finally, to calculate the mean score of the reviews that the ten closest reviewers wrote I coded a nested loop that would iterate through each row. The loop would then iterate through every one of the user’s ten neighbors and calculate the mean score that their reviews got." }, { "code": null, "e": 10315, "s": 10044, "text": "for index, row in id_asin_helpfulness_df.iterrows(): row = row['k_neigh'] lista = [] for i in row: p = id_asin_helpfulness_df.loc[i]['helpfulness_range'] lista.append(p) id_asin_helpfulness_df.loc[index, 'neigh_based_helpf'] = np.nanmean(lista)" }, { "code": null, "e": 10967, "s": 10315, "text": "As a third step I exported the results from the calculation above and merged them with the predictions from the chosen model. I then had a file that consisted of four columns: 1) The original reviews 2) The scores they got (the ground truth) 3) The predictions from the first step (NLP approach) 4) The predictions from the second step (users similarity approach)The combination of the two methods can be done in many different ways. In this paper I chose the simple arithmetic average, but other methods would work as well.In addition to the four columns above, I now have a fifth column: 5) The arithmetic average of each row in columns 3) and 4)" }, { "code": null, "e": 11291, "s": 10967, "text": "The metric used for comparing the models was Root Mean Squared Error (RMSE). It is a very common and good measure for comparing models. In addition, I chose to present the Mean Absolute Error (MAE) because it uses the same scale as the data being measured and therefor can be easily explained. The results2 are shown below:" }, { "code": null, "e": 11492, "s": 11291, "text": "RMSE for neigh_based_helpf: 1.0338002581383618RMSE for NBprediction: 1.074619472976386RMSE for the combination of the two methods: 0.9920521481819871MAE for the combined prediction: 0.6618020568763793" }, { "code": null, "e": 11571, "s": 11492, "text": "The RMSE for the combined method was lower than the RMSE of each method alone." }, { "code": null, "e": 11834, "s": 11571, "text": "In conclusion, my thesis was proven to be correct. Combining the formerly known data about each user’s similarity to other users with the sentiment analysis of the review text itself, does help improve the model prediction of what rate the user’s review will get" }, { "code": null, "e": 12037, "s": 11834, "text": "1 This paper goal is to compare the methods and to see if the framework offered by the researchers will improve the predictions accuracy. It was not to find the most accurate model for RRP based on RTC." } ]
RequireJS - Loading jQuery from CDN
jQuery uses CDN (Content Delivery Network) to define the dependencies for jQuery plugins by calling the define() function. define(["jquery", "jquery.load_js1", "jquery.load_js2"], function($) { $(function() { //code here }); }); The following example uses CDN to define the dependencies for jQuery plugins. Create a html file with the name index.html and place the following code in it − <!DOCTYPE html> <html> <head> <title>Load jQuery from a CDN</title> <script data-main = "app" src = "lib/require.js"></script> </head> <body> <h2>Load jQuery from a CDN</h2> <p>Welcome to Tutorialspoint!!!</p> </body> </html> Create a js file with the name app.js and add the following code in it − // you can configure loading modules from the lib directory requirejs.config ({ "baseUrl": "lib", "paths": { "app": "../app", //loading jquery from CDN "jquery": "//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min" } }); //to start the application, load the main module from app folder requirejs(["app/main"]); Create a folder called app and load the main.js module from this folder − define(["jquery", "jquery.load_js1", "jquery.load_js2"], function($) { //loading the jquery.load_js1.js and jquery.load_js2.js plugins $(function() { $('body').load_js1().load_js2(); }); }); Create one more folder called lib to store the require.js file and other js files as shown below − define(["jquery"], function($) { $.fn.load_js1 = function() { return this.append('<p>Loading from first js file!</p>'); }; }); define(["jquery"], function($) { $.fn.load_js2 = function() { return this.append('<p>Loading from second js file!</p>'); }; }); Open the HTML file in a browser; you will receive the following output − Print Add Notes Bookmark this page
[ { "code": null, "e": 1965, "s": 1842, "text": "jQuery uses CDN (Content Delivery Network) to define the dependencies for jQuery plugins by calling the define() function." }, { "code": null, "e": 2083, "s": 1965, "text": "define([\"jquery\", \"jquery.load_js1\", \"jquery.load_js2\"], function($) {\n $(function() {\n //code here\n });\n});" }, { "code": null, "e": 2242, "s": 2083, "text": "The following example uses CDN to define the dependencies for jQuery plugins. Create a html file with the name index.html and place the following code in it −" }, { "code": null, "e": 2508, "s": 2242, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Load jQuery from a CDN</title>\n <script data-main = \"app\" src = \"lib/require.js\"></script>\n </head>\n \n <body>\n <h2>Load jQuery from a CDN</h2>\n <p>Welcome to Tutorialspoint!!!</p>\n </body>\n</html>" }, { "code": null, "e": 2581, "s": 2508, "text": "Create a js file with the name app.js and add the following code in it −" }, { "code": null, "e": 2933, "s": 2581, "text": "// you can configure loading modules from the lib directory\nrequirejs.config ({\n \"baseUrl\": \"lib\",\n \n \"paths\": {\n \"app\": \"../app\",\n\t \n //loading jquery from CDN\n \"jquery\": \"//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min\"\n }\n});\n\n//to start the application, load the main module from app folder\nrequirejs([\"app/main\"]);" }, { "code": null, "e": 3007, "s": 2933, "text": "Create a folder called app and load the main.js module from this folder −" }, { "code": null, "e": 3218, "s": 3007, "text": "define([\"jquery\", \"jquery.load_js1\", \"jquery.load_js2\"], function($) {\n \n //loading the jquery.load_js1.js and jquery.load_js2.js plugins \n $(function() {\n $('body').load_js1().load_js2();\n });\n});" }, { "code": null, "e": 3317, "s": 3218, "text": "Create one more folder called lib to store the require.js file and other js files as shown below −" }, { "code": null, "e": 3460, "s": 3317, "text": "define([\"jquery\"], function($) {\n \n $.fn.load_js1 = function() {\n return this.append('<p>Loading from first js file!</p>');\n };\n});" }, { "code": null, "e": 3604, "s": 3460, "text": "define([\"jquery\"], function($) {\n \n $.fn.load_js2 = function() {\n return this.append('<p>Loading from second js file!</p>');\n };\n});" }, { "code": null, "e": 3677, "s": 3604, "text": "Open the HTML file in a browser; you will receive the following output −" }, { "code": null, "e": 3684, "s": 3677, "text": " Print" }, { "code": null, "e": 3695, "s": 3684, "text": " Add Notes" } ]
Prototyping a Recommendation System | by Ben Weber | Towards Data Science
Hello World in R, Java, Scala, and SQL Twitch has many products powered by recommendation systems including VOD recommendations, Clips recommendations, and similar channels. Before productizing a recommendation system at Twitch, the science team first prototypes a recommendation system to see if the output is useful for one of our products. Prototyping a recommendation can be low cost, and this post provides examples of building a recommendation system in four different programming languages. Each of the examples uses a different library to prototype a recommendation system using collaborative filtering. An introduction to the collaborative filtering approach used on Amazon.com is available in this paper, and a good overview of the different algorithms and similarity measures used in recommendations systems is covered in Mahout in Action. I also provide an overview of recommendation systems in my GDC Talk on the marketplace in EverQuest Landmark. User-based collaborative filtering is used in all of the examples below, except for the Scala example which uses alternating least squares (ALS). The examples load a data set and then recommend five items for the user with ID 101. The synthetic data set used in these examples is a collection of user purchases of games, where each line includes a user ID and a game ID. The example data set and source code for all examples is available on GitHub. R: Recommender Lab If R is your programming language of choice, the recommenderlab package makes it easy to prototype different recommendation systems. The package is available on the CRAN repository and can be installed using the standard install.packages function. Once loaded, the package provides a Recommender function which takes a data matrix and recommendation method as inputs. In this script, the data matrix is loaded from a CSV file, and the method used is user-based collaborative filtering. The predict function is then used to retrieve five items for user 101. install.packages("recommenderlab")library(recommenderlab)matrix <- as(read.csv("Games.csv"),"realRatingMatrix")model <-Recommender(matrix, method = "UBCF")games <- predict(model, matrix["101",], n=5)as(games, "list") Java: Apache MahoutMahout is a machine learning library implemented in Java that provides a variety of collaborative filtering algorithms. Mahout implements user-based collaborative filtering with a UserNeighborhood class that specifies how similar a user needs to be in order to provide feedback for item recommendations. This example uses the Tanimoto similarity measure to find the similarity between users, which computes the ratio of the number of shared games (intersection) over the total number of games owned by the players (union). This CSV file is used as input to a data model which is then passed to the recommender object. Once a recommender object has been instantiated, the recommend method can be used to create a list of game recommendations for a specific user. import org.apache.mahout.cf.taste.*;DataModel model = new FileDataModel(new File("Games.csv"));UserSimilarity similarity = new TanimotoCoefficientSimilarity(model);UserNeighborhood neighborhood = new ThresholdUserNeighborhood(0.1, similarity, model);UserBasedRecommender recommender = new GenericUserBasedRecommender(model, neighborhood, similarity);List recommendations = recommender.recommend(101, 5);System.out.println(recommendations); Scala: MLlib One of the tools becoming more popular for building recommendation systems is Apache Spark, which provides a built-in library called MLlib that includes a collection of machine learning algorithms. This example first runs a query to retrieve game purchases in a UserID, GameID tuple format, and then transforms the data frame into a collection of ratings that can be used by the ALS model. Implicit data feedback is being used in this example, which is why the trainImplicit method is used instead of the train method. The input parameters to the train method are the game ratings, the number of latent features to use, the number of iterations to perform for matrix factorization, the lambda parameter which is used for regularization, and the alpha parameter which specifies how implicit ratings are measured. Once the model is trained, the recommendProducts method can be used to retrieve a recommended list of games for a user. import org.apache.spark.mllib.recommendation._val games = sqlContext.read .format("com.databricks.spark.csv") .option("header", "false") .option("inferSchema", "true") .load("/Users/bgweber/spark/Games.csv")val ratings = games.rdd.map(row => Rating(row.getInt(0), row.getInt(1), 1))val rank = 10val model = ALS.trainImplicit(ratings, rank, 5, 0.01, 1)val recommendations = model.recommendProducts(101, 5)recommendations.foreach(println) SQL: Spark SQL In situations where pulling data to a machine running Spark or R is too slow or expensive, you can use SQL to prototype a recommendation system. This approach may be computationally expensive to use, but can be useful for spot-checking a few results. The example below uses Spark SQL, because I wanted to make the example reproducible for the provided data set. The first part of the code loads the table from a CSV file and registers the loaded data frame as a temporary table. The second part of the example includes SQL CTAs that prepare the data and then scores games for a single user. The inner query computes the Tanimoto coefficient between users by finding the ratio in overlapping games divided by total number of games purchased, and the outer query returns an overall score for each retrieved game. val games = sqlContext.read .format("com.databricks.spark.csv") .option("header", "false") .option("inferSchema", "true") .load("/Users/bgweber/spark/Games.csv") games.registerTempTable("games")val result = sqlContext.sql("""with users as ( select _c0 as User_ID, sum(1) as NumGames from games group by 1 ), purchases as ( select _c0 as User_ID, _c1 as Game_ID, NumGames from games g join users u on g._c0 = u.User_ID)select u.User_ID, v.Game_ID, sum(Tanimoto) as GameWeightfrom ( select u.User_ID, v.User_ID as Other_User_ID, count(u.Game_ID)/(u.NumGames + v.NumGames - count(u.Game_ID)) as Tanimoto from purchases u Join purchases v on u.Game_ID = v.Game_ID where u.User_ID = 101 group by u.User_ID, v.User_ID, u.NumGames, v.NumGames) uJoin purchases v on Other_User_ID = v.User_IDgroup by u.User_ID, v.Game_IDorder by GameWeight desc""")result.show(5) EvaluationThese scripts have provided examples for how to retrieve game suggestions for a specific user. One of the ways to evaluate the quality of a recommender is to use a qualitative approach, in which the output of the recommender is manually examined for a small group of users. Another approach is to use the built-in evaluation metrics included in the different libraries. For example, recommenderlab and MLlib provide functions for computing ROC curves which can be used to evaluate different system configurations. When evaluating a recommender, it is also a good practice to compare the performance of the recommendation system to other handcrafted approaches, such as a top sellers list.
[ { "code": null, "e": 211, "s": 172, "text": "Hello World in R, Java, Scala, and SQL" }, { "code": null, "e": 670, "s": 211, "text": "Twitch has many products powered by recommendation systems including VOD recommendations, Clips recommendations, and similar channels. Before productizing a recommendation system at Twitch, the science team first prototypes a recommendation system to see if the output is useful for one of our products. Prototyping a recommendation can be low cost, and this post provides examples of building a recommendation system in four different programming languages." }, { "code": null, "e": 1279, "s": 670, "text": "Each of the examples uses a different library to prototype a recommendation system using collaborative filtering. An introduction to the collaborative filtering approach used on Amazon.com is available in this paper, and a good overview of the different algorithms and similarity measures used in recommendations systems is covered in Mahout in Action. I also provide an overview of recommendation systems in my GDC Talk on the marketplace in EverQuest Landmark. User-based collaborative filtering is used in all of the examples below, except for the Scala example which uses alternating least squares (ALS)." }, { "code": null, "e": 1582, "s": 1279, "text": "The examples load a data set and then recommend five items for the user with ID 101. The synthetic data set used in these examples is a collection of user purchases of games, where each line includes a user ID and a game ID. The example data set and source code for all examples is available on GitHub." }, { "code": null, "e": 2158, "s": 1582, "text": "R: Recommender Lab If R is your programming language of choice, the recommenderlab package makes it easy to prototype different recommendation systems. The package is available on the CRAN repository and can be installed using the standard install.packages function. Once loaded, the package provides a Recommender function which takes a data matrix and recommendation method as inputs. In this script, the data matrix is loaded from a CSV file, and the method used is user-based collaborative filtering. The predict function is then used to retrieve five items for user 101." }, { "code": null, "e": 2375, "s": 2158, "text": "install.packages(\"recommenderlab\")library(recommenderlab)matrix <- as(read.csv(\"Games.csv\"),\"realRatingMatrix\")model <-Recommender(matrix, method = \"UBCF\")games <- predict(model, matrix[\"101\",], n=5)as(games, \"list\")" }, { "code": null, "e": 3156, "s": 2375, "text": "Java: Apache MahoutMahout is a machine learning library implemented in Java that provides a variety of collaborative filtering algorithms. Mahout implements user-based collaborative filtering with a UserNeighborhood class that specifies how similar a user needs to be in order to provide feedback for item recommendations. This example uses the Tanimoto similarity measure to find the similarity between users, which computes the ratio of the number of shared games (intersection) over the total number of games owned by the players (union). This CSV file is used as input to a data model which is then passed to the recommender object. Once a recommender object has been instantiated, the recommend method can be used to create a list of game recommendations for a specific user." }, { "code": null, "e": 3601, "s": 3156, "text": "import org.apache.mahout.cf.taste.*;DataModel model = new FileDataModel(new File(\"Games.csv\"));UserSimilarity similarity = new TanimotoCoefficientSimilarity(model);UserNeighborhood neighborhood = new ThresholdUserNeighborhood(0.1, similarity, model);UserBasedRecommender recommender = new GenericUserBasedRecommender(model, neighborhood, similarity);List recommendations = recommender.recommend(101, 5);System.out.println(recommendations);" }, { "code": null, "e": 4546, "s": 3601, "text": "Scala: MLlib One of the tools becoming more popular for building recommendation systems is Apache Spark, which provides a built-in library called MLlib that includes a collection of machine learning algorithms. This example first runs a query to retrieve game purchases in a UserID, GameID tuple format, and then transforms the data frame into a collection of ratings that can be used by the ALS model. Implicit data feedback is being used in this example, which is why the trainImplicit method is used instead of the train method. The input parameters to the train method are the game ratings, the number of latent features to use, the number of iterations to perform for matrix factorization, the lambda parameter which is used for regularization, and the alpha parameter which specifies how implicit ratings are measured. Once the model is trained, the recommendProducts method can be used to retrieve a recommended list of games for a user." }, { "code": null, "e": 5000, "s": 4546, "text": "import org.apache.spark.mllib.recommendation._val games = sqlContext.read .format(\"com.databricks.spark.csv\") .option(\"header\", \"false\") .option(\"inferSchema\", \"true\") .load(\"/Users/bgweber/spark/Games.csv\")val ratings = games.rdd.map(row => Rating(row.getInt(0), row.getInt(1), 1))val rank = 10val model = ALS.trainImplicit(ratings, rank, 5, 0.01, 1)val recommendations = model.recommendProducts(101, 5)recommendations.foreach(println)" }, { "code": null, "e": 5826, "s": 5000, "text": "SQL: Spark SQL In situations where pulling data to a machine running Spark or R is too slow or expensive, you can use SQL to prototype a recommendation system. This approach may be computationally expensive to use, but can be useful for spot-checking a few results. The example below uses Spark SQL, because I wanted to make the example reproducible for the provided data set. The first part of the code loads the table from a CSV file and registers the loaded data frame as a temporary table. The second part of the example includes SQL CTAs that prepare the data and then scores games for a single user. The inner query computes the Tanimoto coefficient between users by finding the ratio in overlapping games divided by total number of games purchased, and the outer query returns an overall score for each retrieved game." }, { "code": null, "e": 6760, "s": 5826, "text": "val games = sqlContext.read .format(\"com.databricks.spark.csv\") .option(\"header\", \"false\") .option(\"inferSchema\", \"true\") .load(\"/Users/bgweber/spark/Games.csv\") games.registerTempTable(\"games\")val result = sqlContext.sql(\"\"\"with users as ( select _c0 as User_ID, sum(1) as NumGames from games group by 1 ), purchases as ( select _c0 as User_ID, _c1 as Game_ID, NumGames from games g join users u on g._c0 = u.User_ID)select u.User_ID, v.Game_ID, sum(Tanimoto) as GameWeightfrom ( select u.User_ID, v.User_ID as Other_User_ID, count(u.Game_ID)/(u.NumGames + v.NumGames - count(u.Game_ID)) as Tanimoto from purchases u Join purchases v on u.Game_ID = v.Game_ID where u.User_ID = 101 group by u.User_ID, v.User_ID, u.NumGames, v.NumGames) uJoin purchases v on Other_User_ID = v.User_IDgroup by u.User_ID, v.Game_IDorder by GameWeight desc\"\"\")result.show(5)" } ]
Ramanujan Prime - GeeksforGeeks
11 May, 2021 The Nth Ramanujan prime is the least integer Rn for which where π(x) is a prime-counting functionNote that the integer Rn is necessarily a prime number: π(x) – π(x/2) and, hence, π(x) must increase by obtaining another prime at x = Rn. Since π(x) – π(x/2) can increase by at most 1, Range of Rn is (2n log(2n), 4n log(4n)). Ramanujan primes: 2, 11, 17, 29, 41, 47, 59, 67, 71, 97 For a given N, the task is to print first N Ramanujan primesExamples: Input : N = 5 Output : 2, 11, 17, 29, 41Input : N = 10 Output : 2, 11, 17, 29, 41, 47, 59, 67, 71, 97 Approach: Let us divide our solution into parts, First, we will use sieve of Eratosthenes to get all the primes less than 10^6Now we will have to find the value of π(x), π(x) is the count of primes which are less than or equal to x. Primes are stored in increasing order. So we can perform a binary search to find all the primes less than x, which can be done in O(log n). Now we have the range Rn lies between : 2n log(2n) < Rn < 4n log(4n) So, we will take the upper bound and iterate from upper bound to the lower bound until π(i) – π(i/2) < n, i+1 is the nth Ramanujan prime.Below is the implementation of the above approach : C++ Java Python3 C# Javascript // CPP program to find Ramanujan numbers#include <bits/stdc++.h>using namespace std;#define MAX 1000000 // FUnction to return a vector of primesvector<int> addPrimes(){ int n = MAX; // Create a boolean array "prime[0..n]" and initialize // all entries it as true. A value in prime[i] will // finally be false if i is Not a prime, else true. bool prime[n + 1]; memset(prime, true, sizeof(prime)); for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed, then it is a prime if (prime[p] == true) { // Update all multiples of p greater than or // equal to the square of it // numbers which are multiple of p and are // less than p^2 are already been marked. for (int i = p * p; i <= n; i += p) prime[i] = false; } } vector<int> ans; // Print all prime numbers for (int p = 2; p <= n; p++) if (prime[p]) ans.push_back(p); return ans;}// Function to find number of primes// less than or equal to xint pi(int x, vector<int> v){ int l = 0, r = v.size() - 1, m, in = -1; // Binary search to find out number of // primes less than or equal to x while (l <= r) { m = (l + r) / 2; if (v[m] <= x) { in = m; l = m + 1; } else { r = m - 1; } } return in + 1;} // Function to find the nth ramanujan primeint Ramanujan(int n, vector<int> v){ // For n>=1, a(n)<4*n*log(4n) int upperbound = 4 * n * (log(4 * n) / log(2)); // We start from upperbound and find where // pi(i)-pi(i/2)<n the previous number being // the nth ramanujan prime for (int i = upperbound;; i--) { if (pi(i, v) - pi(i / 2, v) < n) return 1 + i; }} // Function to find first n Ramanujan numbersvoid Ramanujan_Numbers(int n){ int c = 1; // Get the prime numbers vector<int> v = addPrimes(); for (int i = 1; i <= n; i++) { cout << Ramanujan(i, v); if(i!=n) cout << ", "; }} // Driver codeint main(){ int n = 10; Ramanujan_Numbers(n); return 0;} // Java program to find Ramanujan numbersimport java.util.*;class GFG{ static int MAX = 1000000; // FUnction to return a vector of primesstatic Vector<Integer> addPrimes(){ int n = MAX; // Create a boolean array "prime[0..n]" and // initialize all entries it as true. // A value in prime[i] will finally be false // if i is Not a prime, else true. boolean []prime= new boolean[n + 1]; Arrays.fill(prime, true); for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == true) { // Update all multiples of p greater than or // equal to the square of it // numbers which are multiple of p and are // less than p^2 are already been marked. for (int i = p * p; i <= n; i += p) prime[i] = false; } } Vector<Integer> ans = new Vector<Integer>(); // Print all prime numbers for (int p = 2; p <= n; p++) if (prime[p]) ans.add(p); return ans;} // Function to find number of primes// less than or equal to xstatic int pi(int x, Vector<Integer> v){ int l = 0, r = v.size() - 1, m, in = -1; // Binary search to find out number of // primes less than or equal to x while (l <= r) { m = (l + r) / 2; if (v.get(m) <= x) { in = m; l = m + 1; } else { r = m - 1; } } return in + 1;} // Function to find the nth ramanujan primestatic int Ramanujan(int n, Vector<Integer> v){ // For n>=1, a(n)<4*n*log(4n) int upperbound = (int) (4 * n * (Math.log(4 * n) / Math.log(2))); // We start from upperbound and find where // pi(i)-pi(i/2)<n the previous number being // the nth ramanujan prime for (int i = upperbound;; i--) { if (pi(i, v) - pi(i / 2, v) < n) return 1 + i; }} // Function to find first n Ramanujan numbersstatic void Ramanujan_Numbers(int n){ int c = 1; // Get the prime numbers Vector<Integer> v = addPrimes(); for (int i = 1; i <= n; i++) { System.out.print(Ramanujan(i, v)); if(i != n) System.out.print(", "); }} // Driver codepublic static void main(String[] args){ int n = 10; Ramanujan_Numbers(n);}} // This code is contributed by 29AjayKumar # Python3 program to find Ramanujan numbersfrom math import log, ceilMAX = 1000000 # FUnction to return a vector of primesdef addPrimes(): n = MAX # Create a boolean array "prime[0..n]" # and initialize all entries it as true. # A value in prime[i] will finally be # false if i is Not a prime, else true. prime = [True for i in range(n + 1)] for p in range(2, n + 1): if p * p > n: break # If prime[p] is not changed, # then it is a prime if (prime[p] == True): # Update all multiples of p # greater than or equal to the # square of it. numbers which are # multiple of p and are less than p^2 # are already been marked. for i in range(2 * p, n + 1, p): prime[i] = False ans = [] # Print all prime numbers for p in range(2, n + 1): if (prime[p]): ans.append(p) return ans # Function to find number of primes# less than or equal to xdef pi(x, v): l, r = 0, len(v) - 1 # Binary search to find out number of # primes less than or equal to x m, i = 0, -1 while (l <= r): m = (l + r) // 2 if (v[m] <= x): i = m l = m + 1 else: r = m - 1 return i + 1 # Function to find the nth ramanujan primedef Ramanujan(n, v): # For n>=1, a(n)<4*n*log(4n) upperbound = ceil(4 * n * (log(4 * n) / log(2))) # We start from upperbound and find where # pi(i)-pi(i/2)<n the previous number being # the nth ramanujan prime for i in range(upperbound, -1, -1): if (pi(i, v) - pi(i / 2, v) < n): return 1 + i # Function to find first n Ramanujan numbersdef Ramanujan_Numbers(n): c = 1 # Get the prime numbers v = addPrimes() for i in range(1, n + 1): print(Ramanujan(i, v), end = "") if(i != n): print(end = ", ") # Driver coden = 10 Ramanujan_Numbers(n) # This code is contributed# by Mohit Kumar // C# program to find Ramanujan numbersusing System;using System.Collections.Generic; class GFG{static int MAX = 1000000; // FUnction to return a vector of primesstatic List<int> addPrimes(){ int n = MAX; // Create a boolean array "prime[0..n]" and // initialize all entries it as true. // A value in prime[i] will finally be false // if i is Not a prime, else true. Boolean []prime = new Boolean[n + 1]; for(int i = 0; i < n + 1; i++) prime[i] = true; for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == true) { // Update all multiples of p greater than // or equal to the square of it // numbers which are multiple of p and are // less than p^2 are already been marked. for (int i = p * p; i <= n; i += p) prime[i] = false; } } List<int> ans = new List<int>(); // Print all prime numbers for (int p = 2; p <= n; p++) if (prime[p]) ans.Add(p); return ans;} // Function to find number of primes// less than or equal to xstatic int pi(int x, List<int> v){ int l = 0, r = v.Count - 1, m, i = -1; // Binary search to find out number of // primes less than or equal to x while (l <= r) { m = (l + r) / 2; if (v[m] <= x) { i = m; l = m + 1; } else { r = m - 1; } } return i + 1;} // Function to find the nth ramanujan primestatic int Ramanujan(int n, List<int> v){ // For n>=1, a(n)<4*n*log(4n) int upperbound = (int) (4 * n * (Math.Log(4 * n) / Math.Log(2))); // We start from upperbound and find where // pi(i)-pi(i/2)<n the previous number being // the nth ramanujan prime for (int i = upperbound;; i--) { if (pi(i, v) - pi(i / 2, v) < n) return 1 + i; }} // Function to find first n Ramanujan numbersstatic void Ramanujan_Numbers(int n){ int c = 1; // Get the prime numbers List<int> v = addPrimes(); for (int i = 1; i <= n; i++) { Console.Write(Ramanujan(i, v)); if(i != n) Console.Write(", "); }} // Driver codepublic static void Main(String[] args){ int n = 10; Ramanujan_Numbers(n);}} // This code is contributed by 29AjayKumar <script>// Javascript program to find Ramanujan numbers const MAX = 1000000; // FUnction to return a vector of primesfunction addPrimes(){ let n = MAX; // Create a boolean array "prime[0..n]" and initialize // all entries it as true. A value in prime[i] will // finally be false if i is Not a prime, else true. let prime = new Array(n + 1).fill(true); for (let p = 2; p * p <= n; p++) { // If prime[p] is not changed, then it is a prime if (prime[p] == true) { // Update all multiples of p greater than or // equal to the square of it // numbers which are multiple of p and are // less than p^2 are already been marked. for (let i = p * p; i <= n; i += p) prime[i] = false; } } let ans = []; // Print all prime numbers for (let p = 2; p <= n; p++) if (prime[p]) ans.push(p); return ans;}// Function to find number of primes// less than or equal to xfunction pi(x, v){ let l = 0, r = v.length - 1, m, inn = -1; // Binary search to find out number of // primes less than or equal to x while (l <= r) { m = parseInt((l + r) / 2); if (v[m] <= x) { inn = m; l = m + 1; } else { r = m - 1; } } return inn + 1;} // Function to find the nth ramanujan primefunction Ramanujan(n, v){ // For n>=1, a(n)<4*n*log(4n) let upperbound = 4 * n * parseInt((Math.log(4 * n) / Math.log(2))); // We start from upperbound and find where // pi(i)-pi(i/2)<n the previous number being // the nth ramanujan prime for (let i = upperbound;; i--) { if (pi(i, v) - pi(parseInt(i / 2), v) < n) return 1 + i; }} // Function to find first n Ramanujan numbersfunction Ramanujan_Numbers(n){ let c = 1; // Get the prime numbers let v = addPrimes(); for (let i = 1; i <= n; i++) { document.write(Ramanujan(i, v)); if(i!=n) document.write(", "); }} // Driver code let n = 10; Ramanujan_Numbers(n); </script> Output: 2, 11, 17, 29, 41, 47, 59, 67, 71, 97 mohit kumar 29 29AjayKumar Akanksha_Rai souravmahato348 Prime Number Mathematical Mathematical Prime Number 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 Print all possible combinations of r elements in a given array of size n Sieve of Eratosthenes Operators in C / C++ Program for factorial of a number Find minimum number of coins that make a given value The Knight's tour problem | Backtracking-1
[ { "code": null, "e": 26897, "s": 26869, "text": "\n11 May, 2021" }, { "code": null, "e": 26956, "s": 26897, "text": "The Nth Ramanujan prime is the least integer Rn for which " }, { "code": null, "e": 27223, "s": 26956, "text": "where π(x) is a prime-counting functionNote that the integer Rn is necessarily a prime number: π(x) – π(x/2) and, hence, π(x) must increase by obtaining another prime at x = Rn. Since π(x) – π(x/2) can increase by at most 1, Range of Rn is (2n log(2n), 4n log(4n)). " }, { "code": null, "e": 27243, "s": 27223, "text": "Ramanujan primes: " }, { "code": null, "e": 27283, "s": 27243, "text": "2, 11, 17, 29, 41, 47, 59, 67, 71, 97 " }, { "code": null, "e": 27355, "s": 27283, "text": "For a given N, the task is to print first N Ramanujan primesExamples: " }, { "code": null, "e": 27459, "s": 27355, "text": "Input : N = 5 Output : 2, 11, 17, 29, 41Input : N = 10 Output : 2, 11, 17, 29, 41, 47, 59, 67, 71, 97 " }, { "code": null, "e": 28094, "s": 27461, "text": "Approach: Let us divide our solution into parts, First, we will use sieve of Eratosthenes to get all the primes less than 10^6Now we will have to find the value of π(x), π(x) is the count of primes which are less than or equal to x. Primes are stored in increasing order. So we can perform a binary search to find all the primes less than x, which can be done in O(log n). Now we have the range Rn lies between : 2n log(2n) < Rn < 4n log(4n) So, we will take the upper bound and iterate from upper bound to the lower bound until π(i) – π(i/2) < n, i+1 is the nth Ramanujan prime.Below is the implementation of the above approach : " }, { "code": null, "e": 28098, "s": 28094, "text": "C++" }, { "code": null, "e": 28103, "s": 28098, "text": "Java" }, { "code": null, "e": 28111, "s": 28103, "text": "Python3" }, { "code": null, "e": 28114, "s": 28111, "text": "C#" }, { "code": null, "e": 28125, "s": 28114, "text": "Javascript" }, { "code": "// CPP program to find Ramanujan numbers#include <bits/stdc++.h>using namespace std;#define MAX 1000000 // FUnction to return a vector of primesvector<int> addPrimes(){ int n = MAX; // Create a boolean array \"prime[0..n]\" and initialize // all entries it as true. A value in prime[i] will // finally be false if i is Not a prime, else true. bool prime[n + 1]; memset(prime, true, sizeof(prime)); for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed, then it is a prime if (prime[p] == true) { // Update all multiples of p greater than or // equal to the square of it // numbers which are multiple of p and are // less than p^2 are already been marked. for (int i = p * p; i <= n; i += p) prime[i] = false; } } vector<int> ans; // Print all prime numbers for (int p = 2; p <= n; p++) if (prime[p]) ans.push_back(p); return ans;}// Function to find number of primes// less than or equal to xint pi(int x, vector<int> v){ int l = 0, r = v.size() - 1, m, in = -1; // Binary search to find out number of // primes less than or equal to x while (l <= r) { m = (l + r) / 2; if (v[m] <= x) { in = m; l = m + 1; } else { r = m - 1; } } return in + 1;} // Function to find the nth ramanujan primeint Ramanujan(int n, vector<int> v){ // For n>=1, a(n)<4*n*log(4n) int upperbound = 4 * n * (log(4 * n) / log(2)); // We start from upperbound and find where // pi(i)-pi(i/2)<n the previous number being // the nth ramanujan prime for (int i = upperbound;; i--) { if (pi(i, v) - pi(i / 2, v) < n) return 1 + i; }} // Function to find first n Ramanujan numbersvoid Ramanujan_Numbers(int n){ int c = 1; // Get the prime numbers vector<int> v = addPrimes(); for (int i = 1; i <= n; i++) { cout << Ramanujan(i, v); if(i!=n) cout << \", \"; }} // Driver codeint main(){ int n = 10; Ramanujan_Numbers(n); return 0;}", "e": 30269, "s": 28125, "text": null }, { "code": "// Java program to find Ramanujan numbersimport java.util.*;class GFG{ static int MAX = 1000000; // FUnction to return a vector of primesstatic Vector<Integer> addPrimes(){ int n = MAX; // Create a boolean array \"prime[0..n]\" and // initialize all entries it as true. // A value in prime[i] will finally be false // if i is Not a prime, else true. boolean []prime= new boolean[n + 1]; Arrays.fill(prime, true); for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == true) { // Update all multiples of p greater than or // equal to the square of it // numbers which are multiple of p and are // less than p^2 are already been marked. for (int i = p * p; i <= n; i += p) prime[i] = false; } } Vector<Integer> ans = new Vector<Integer>(); // Print all prime numbers for (int p = 2; p <= n; p++) if (prime[p]) ans.add(p); return ans;} // Function to find number of primes// less than or equal to xstatic int pi(int x, Vector<Integer> v){ int l = 0, r = v.size() - 1, m, in = -1; // Binary search to find out number of // primes less than or equal to x while (l <= r) { m = (l + r) / 2; if (v.get(m) <= x) { in = m; l = m + 1; } else { r = m - 1; } } return in + 1;} // Function to find the nth ramanujan primestatic int Ramanujan(int n, Vector<Integer> v){ // For n>=1, a(n)<4*n*log(4n) int upperbound = (int) (4 * n * (Math.log(4 * n) / Math.log(2))); // We start from upperbound and find where // pi(i)-pi(i/2)<n the previous number being // the nth ramanujan prime for (int i = upperbound;; i--) { if (pi(i, v) - pi(i / 2, v) < n) return 1 + i; }} // Function to find first n Ramanujan numbersstatic void Ramanujan_Numbers(int n){ int c = 1; // Get the prime numbers Vector<Integer> v = addPrimes(); for (int i = 1; i <= n; i++) { System.out.print(Ramanujan(i, v)); if(i != n) System.out.print(\", \"); }} // Driver codepublic static void main(String[] args){ int n = 10; Ramanujan_Numbers(n);}} // This code is contributed by 29AjayKumar", "e": 32667, "s": 30269, "text": null }, { "code": "# Python3 program to find Ramanujan numbersfrom math import log, ceilMAX = 1000000 # FUnction to return a vector of primesdef addPrimes(): n = MAX # Create a boolean array \"prime[0..n]\" # and initialize all entries it as true. # A value in prime[i] will finally be # false if i is Not a prime, else true. prime = [True for i in range(n + 1)] for p in range(2, n + 1): if p * p > n: break # If prime[p] is not changed, # then it is a prime if (prime[p] == True): # Update all multiples of p # greater than or equal to the # square of it. numbers which are # multiple of p and are less than p^2 # are already been marked. for i in range(2 * p, n + 1, p): prime[i] = False ans = [] # Print all prime numbers for p in range(2, n + 1): if (prime[p]): ans.append(p) return ans # Function to find number of primes# less than or equal to xdef pi(x, v): l, r = 0, len(v) - 1 # Binary search to find out number of # primes less than or equal to x m, i = 0, -1 while (l <= r): m = (l + r) // 2 if (v[m] <= x): i = m l = m + 1 else: r = m - 1 return i + 1 # Function to find the nth ramanujan primedef Ramanujan(n, v): # For n>=1, a(n)<4*n*log(4n) upperbound = ceil(4 * n * (log(4 * n) / log(2))) # We start from upperbound and find where # pi(i)-pi(i/2)<n the previous number being # the nth ramanujan prime for i in range(upperbound, -1, -1): if (pi(i, v) - pi(i / 2, v) < n): return 1 + i # Function to find first n Ramanujan numbersdef Ramanujan_Numbers(n): c = 1 # Get the prime numbers v = addPrimes() for i in range(1, n + 1): print(Ramanujan(i, v), end = \"\") if(i != n): print(end = \", \") # Driver coden = 10 Ramanujan_Numbers(n) # This code is contributed# by Mohit Kumar", "e": 34687, "s": 32667, "text": null }, { "code": "// C# program to find Ramanujan numbersusing System;using System.Collections.Generic; class GFG{static int MAX = 1000000; // FUnction to return a vector of primesstatic List<int> addPrimes(){ int n = MAX; // Create a boolean array \"prime[0..n]\" and // initialize all entries it as true. // A value in prime[i] will finally be false // if i is Not a prime, else true. Boolean []prime = new Boolean[n + 1]; for(int i = 0; i < n + 1; i++) prime[i] = true; for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == true) { // Update all multiples of p greater than // or equal to the square of it // numbers which are multiple of p and are // less than p^2 are already been marked. for (int i = p * p; i <= n; i += p) prime[i] = false; } } List<int> ans = new List<int>(); // Print all prime numbers for (int p = 2; p <= n; p++) if (prime[p]) ans.Add(p); return ans;} // Function to find number of primes// less than or equal to xstatic int pi(int x, List<int> v){ int l = 0, r = v.Count - 1, m, i = -1; // Binary search to find out number of // primes less than or equal to x while (l <= r) { m = (l + r) / 2; if (v[m] <= x) { i = m; l = m + 1; } else { r = m - 1; } } return i + 1;} // Function to find the nth ramanujan primestatic int Ramanujan(int n, List<int> v){ // For n>=1, a(n)<4*n*log(4n) int upperbound = (int) (4 * n * (Math.Log(4 * n) / Math.Log(2))); // We start from upperbound and find where // pi(i)-pi(i/2)<n the previous number being // the nth ramanujan prime for (int i = upperbound;; i--) { if (pi(i, v) - pi(i / 2, v) < n) return 1 + i; }} // Function to find first n Ramanujan numbersstatic void Ramanujan_Numbers(int n){ int c = 1; // Get the prime numbers List<int> v = addPrimes(); for (int i = 1; i <= n; i++) { Console.Write(Ramanujan(i, v)); if(i != n) Console.Write(\", \"); }} // Driver codepublic static void Main(String[] args){ int n = 10; Ramanujan_Numbers(n);}} // This code is contributed by 29AjayKumar", "e": 37086, "s": 34687, "text": null }, { "code": "<script>// Javascript program to find Ramanujan numbers const MAX = 1000000; // FUnction to return a vector of primesfunction addPrimes(){ let n = MAX; // Create a boolean array \"prime[0..n]\" and initialize // all entries it as true. A value in prime[i] will // finally be false if i is Not a prime, else true. let prime = new Array(n + 1).fill(true); for (let p = 2; p * p <= n; p++) { // If prime[p] is not changed, then it is a prime if (prime[p] == true) { // Update all multiples of p greater than or // equal to the square of it // numbers which are multiple of p and are // less than p^2 are already been marked. for (let i = p * p; i <= n; i += p) prime[i] = false; } } let ans = []; // Print all prime numbers for (let p = 2; p <= n; p++) if (prime[p]) ans.push(p); return ans;}// Function to find number of primes// less than or equal to xfunction pi(x, v){ let l = 0, r = v.length - 1, m, inn = -1; // Binary search to find out number of // primes less than or equal to x while (l <= r) { m = parseInt((l + r) / 2); if (v[m] <= x) { inn = m; l = m + 1; } else { r = m - 1; } } return inn + 1;} // Function to find the nth ramanujan primefunction Ramanujan(n, v){ // For n>=1, a(n)<4*n*log(4n) let upperbound = 4 * n * parseInt((Math.log(4 * n) / Math.log(2))); // We start from upperbound and find where // pi(i)-pi(i/2)<n the previous number being // the nth ramanujan prime for (let i = upperbound;; i--) { if (pi(i, v) - pi(parseInt(i / 2), v) < n) return 1 + i; }} // Function to find first n Ramanujan numbersfunction Ramanujan_Numbers(n){ let c = 1; // Get the prime numbers let v = addPrimes(); for (let i = 1; i <= n; i++) { document.write(Ramanujan(i, v)); if(i!=n) document.write(\", \"); }} // Driver code let n = 10; Ramanujan_Numbers(n); </script>", "e": 39192, "s": 37086, "text": null }, { "code": null, "e": 39202, "s": 39192, "text": "Output: " }, { "code": null, "e": 39240, "s": 39202, "text": "2, 11, 17, 29, 41, 47, 59, 67, 71, 97" }, { "code": null, "e": 39257, "s": 39242, "text": "mohit kumar 29" }, { "code": null, "e": 39269, "s": 39257, "text": "29AjayKumar" }, { "code": null, "e": 39282, "s": 39269, "text": "Akanksha_Rai" }, { "code": null, "e": 39298, "s": 39282, "text": "souravmahato348" }, { "code": null, "e": 39311, "s": 39298, "text": "Prime Number" }, { "code": null, "e": 39324, "s": 39311, "text": "Mathematical" }, { "code": null, "e": 39337, "s": 39324, "text": "Mathematical" }, { "code": null, "e": 39350, "s": 39337, "text": "Prime Number" }, { "code": null, "e": 39448, "s": 39350, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 39472, "s": 39448, "text": "Merge two sorted arrays" }, { "code": null, "e": 39515, "s": 39472, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 39529, "s": 39515, "text": "Prime Numbers" }, { "code": null, "e": 39571, "s": 39529, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 39644, "s": 39571, "text": "Print all possible combinations of r elements in a given array of size n" }, { "code": null, "e": 39666, "s": 39644, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 39687, "s": 39666, "text": "Operators in C / C++" }, { "code": null, "e": 39721, "s": 39687, "text": "Program for factorial of a number" }, { "code": null, "e": 39774, "s": 39721, "text": "Find minimum number of coins that make a given value" } ]
How to check if a number evaluates to Infinity using JavaScript ? - GeeksforGeeks
18 Oct, 2019 The task is to check whether number evaluates to infinity or not with the help of JavaScript. Here are few techniques discussed.Approach 1: Checking if number is equal to Number.POSITIVE_INFINITY or Number.NEGATIVE_INFINITY . Example 1: This example uses the approach as discussed above. <!DOCTYPE HTML><html> <head> <title> Check if a Number evaluates to Infinity. </title></head> <body style="text-align:center;" id="body"> <h1 style="color:green;" id="h1"> GeeksForGeeks </h1> <p id="GFG_UP" style="font-size: 15px; font-weight: bold;"> </p> <button onclick="GFG_Fun()"> click here </button> <p id="GFG_DOWN" style="color:green; font-size: 20px; font-weight: bold;"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); var n = 1 / 0; up.innerHTML = "Click on the button to check if"+ " Number evaluates to Infinity.<br> Number = 1/0"; function GFG_Fun() { if (n == Number.POSITIVE_INFINITY || n == Number.NEGATIVE_INFINITY) { down.innerHTML = "Infinity"; } else { down.innerHTML = "Not Infinity"; } } </script></body> </html> Output: Before clicking on the button: After clicking on the button: Approach 2: Using Number.isFinite() method to check if the number is finite or not. Example 2: This example uses the approach as discussed above. <!DOCTYPE HTML><html> <head> <title> Check if a Number evaluates to Infinity. </title></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP" style="font-size: 15px; font-weight: bold;"> </p> <button onclick="GFG_Fun()"> click here </button> <p id="GFG_DOWN" style="color:green; font-size: 20px; font-weight: bold;"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); var n = 1 / 4; up.innerHTML = "Click on the button to check if"+ " Number evaluates to Infinity.<br> Number = 1/4"; function GFG_Fun() { if (!Number.isFinite(n)) { down.innerHTML = "Infinity"; } else { down.innerHTML = "Not Infinity"; } } </script></body> </html> Output: Before clicking on the button: After clicking on the button: JavaScript-Misc JavaScript Web Technologies Web technologies Questions 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 How to Open URL in New Tab using JavaScript ? Remove elements from a JavaScript Array Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 25953, "s": 25925, "text": "\n18 Oct, 2019" }, { "code": null, "e": 26093, "s": 25953, "text": "The task is to check whether number evaluates to infinity or not with the help of JavaScript. Here are few techniques discussed.Approach 1:" }, { "code": null, "e": 26179, "s": 26093, "text": "Checking if number is equal to Number.POSITIVE_INFINITY or Number.NEGATIVE_INFINITY ." }, { "code": null, "e": 26241, "s": 26179, "text": "Example 1: This example uses the approach as discussed above." }, { "code": "<!DOCTYPE HTML><html> <head> <title> Check if a Number evaluates to Infinity. </title></head> <body style=\"text-align:center;\" id=\"body\"> <h1 style=\"color:green;\" id=\"h1\"> GeeksForGeeks </h1> <p id=\"GFG_UP\" style=\"font-size: 15px; font-weight: bold;\"> </p> <button onclick=\"GFG_Fun()\"> click here </button> <p id=\"GFG_DOWN\" style=\"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); var n = 1 / 0; up.innerHTML = \"Click on the button to check if\"+ \" Number evaluates to Infinity.<br> Number = 1/0\"; function GFG_Fun() { if (n == Number.POSITIVE_INFINITY || n == Number.NEGATIVE_INFINITY) { down.innerHTML = \"Infinity\"; } else { down.innerHTML = \"Not Infinity\"; } } </script></body> </html>", "e": 27292, "s": 26241, "text": null }, { "code": null, "e": 27300, "s": 27292, "text": "Output:" }, { "code": null, "e": 27331, "s": 27300, "text": "Before clicking on the button:" }, { "code": null, "e": 27361, "s": 27331, "text": "After clicking on the button:" }, { "code": null, "e": 27373, "s": 27361, "text": "Approach 2:" }, { "code": null, "e": 27445, "s": 27373, "text": "Using Number.isFinite() method to check if the number is finite or not." }, { "code": null, "e": 27507, "s": 27445, "text": "Example 2: This example uses the approach as discussed above." }, { "code": "<!DOCTYPE HTML><html> <head> <title> Check if a Number evaluates to Infinity. </title></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\" style=\"font-size: 15px; font-weight: bold;\"> </p> <button onclick=\"GFG_Fun()\"> click here </button> <p id=\"GFG_DOWN\" style=\"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); var n = 1 / 4; up.innerHTML = \"Click on the button to check if\"+ \" Number evaluates to Infinity.<br> Number = 1/4\"; function GFG_Fun() { if (!Number.isFinite(n)) { down.innerHTML = \"Infinity\"; } else { down.innerHTML = \"Not Infinity\"; } } </script></body> </html>", "e": 28484, "s": 27507, "text": null }, { "code": null, "e": 28492, "s": 28484, "text": "Output:" }, { "code": null, "e": 28523, "s": 28492, "text": "Before clicking on the button:" }, { "code": null, "e": 28553, "s": 28523, "text": "After clicking on the button:" }, { "code": null, "e": 28569, "s": 28553, "text": "JavaScript-Misc" }, { "code": null, "e": 28580, "s": 28569, "text": "JavaScript" }, { "code": null, "e": 28597, "s": 28580, "text": "Web Technologies" }, { "code": null, "e": 28624, "s": 28597, "text": "Web technologies Questions" }, { "code": null, "e": 28722, "s": 28624, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28762, "s": 28722, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28807, "s": 28762, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28868, "s": 28807, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 28940, "s": 28868, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 28986, "s": 28940, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 29026, "s": 28986, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29071, "s": 29026, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29114, "s": 29071, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 29164, "s": 29114, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Recursive lambda expressions in C++
21 Jun, 2022 A recursive lambda expression is the process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. Using a recursive algorithm, certain problems can be solved quite easily. Examples of such problems are Towers of Hanoi (TOH), Inorder/Preorder/Postorder Tree Traversals, DFS of Graph, etc. A recursive function is a kind of loop structure only. The difference is it maintains a memory stack on its own. Obviously, it must have a break condition like for and while loop. Hence, the recursive function has the following structure- function name(arguments) { a base case (a breaking condition) recursive code (the actual logic) } int fact(int n) { // Base Case if (n < = 1) return 1; else return n * fact(n - 1); } C++ 11 introduced lambda expressions to allow us to write an inline function that can be used for short snippets of code that are not going to be reused and not worth naming. In its simplest form, the lambda expression can be defined as follows: [ capture clause ] (parameters) -> return-type { definition of method } Program 1: Below is the program for the lambda expressions in the sort() method in C++: C++14 // C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Driver codeint main(){ int arr[] = { 5, 2, 1, 4, 3 }; sort(arr, arr + 5, [](int& a, int& b) { // Instant lambda function return a > b; }); for (int i = 0; i < 5; i++) cout << arr[i] << " "; return 0;} 5 4 3 2 1 Time complexity: O(nlogn) Auxiliary Space: O(1) Explanation: Here, the instant lambda function is used, which cannot be used in another sorting method, i.e., the same code needs to be written again. This lambda expression exists only during the execution of the sort() method. But it is possible to store the lambda expression in a variable (better to call it a function) as well, like below. By storing it, it can be used further, and of course, perform recursion also. Program 2: C++14 // C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Stored lambda expressionauto cmp = [](int& a, int& b) { return a > b;}; // Driver codeint main(){ int arr[] = { 5, 2, 3, 1, 4 }; sort(arr, arr + 5, cmp); for (int i = 0; i < 5; i++) cout << arr[i] << " "; return 0;} 5 4 3 2 1 Time complexity: O(nlogn) Auxiliary Space: O(1) Explanation: Here, auto cmp is the lambda stored function that can be used in as many sorting methods. Recursion Using Lambda: Let’s discuss the concept of recursion and lambda expressions together by considering the recursive function below: Program 3: C++14 // C++ program to implement// the above approach#include <iostream>using namespace std; // Recursive function to print// the digits of a numbervoid printReverse(int n){ if (n == 0) return; cout << n % 10 << " "; printReverse(n / 10);} // Driver codeint main(){ int n = 12345; printReverse(n); return 0;} 5 4 3 2 1 Time complexity: O(logn) Auxiliary Space: O(logn) Explanation: Above is the function which prints the digits of a number in reverse order, using recursion. The same can be done using the lambda expression. Program 4: Below is the C++ program to implement the above code using lambda expressions: C++14 // C++ program to implement// the above approach#include <iostream>using namespace std; // Driver codeint main(){ int n = 12345; // Recursive lambda function to // print the digits of a number auto printReverse = [&]() { if (n == 0) return; cout << n % 10; n = n / 10; printReverse(); // As it is a part of main body, // semicolon is must }; printReverse(); return 0;} Output: Oops, the function, defined using auto return type, must be deducted first (Compiler must be able to determine whether the return type auto can be converted into void or int or something else) Explanation: Here, how the function is going to recognize the variable n, even if it is not passed as an argument. A lambda with an empty capture clause [ ] can access only those variables which are local to it. Here, the capture close [&] is used, which allows the function to access the variable n ( The actual value of variable n is being changed). There are two ways to resolve the error above: 1. By passing the function itself, to the function argument: Below is the C++ program to implement the above concept: Program 5: C++14 // C++ program to implement// the above approach#include <iostream>using namespace std; // Driver codeint main(){ int n = 12345; // Function itself as a parameter auto printReverse = [&](auto&& printReverse) { if (n == 0) return; cout << n % 10 << " "; n = n / 10; printReverse(printReverse); }; // Function as an argument printReverse(printReverse); return 0;} 5 4 3 2 1 Time complexity: O(logn) Auxiliary Space: O(logn) 2. By declaring the function first: Declaring a function means declaring its name and parameters type in order to inform a compiler that there is a function named xyz, which will write its body later. Program 6: Below is the C++ program to implement the above concept: C++ // C++ program to implement// the above approach#include <iostream>using namespace std; // Declaring of a functionvoid declaringFunction(string s); // Driver codeint main(){ declaringFunction("Hello I am learning how to declare a function"); return 0;} // Body of a functionvoid declaringFunction(string s){ cout << s;} Hello I am learning how to declare a function Time complexity: O(1) Auxiliary Space: O(1) Program 7: Since it is a lambda function, there must be some unique way of declaring the function. Below is the C++ program for the same: C++14 // C++ program to implement// the above approach#include <functional>#include <iostream>using namespace std; // Driver codeint main(){ int n = 12345; // Function < return type (parameter // types) > functionName // Don't forget to include functional // header // Declaration function<void()> printReverse; printReverse = [&]() { if (n == 0) return; // Defination cout << n % 10 << " "; n /= 10; printReverse(); }; printReverse();} 5 4 3 2 1 Time complexity: O(logn) Auxiliary Space: O(logn) Explanation: In the above code, first, the function printReverse is declared, then we have defined its body. Instead of that, we can directly declare the function and its body along with, which is known as defining a function. Below is the C++ program to implement the above approach: Program 8: C++14 // C++ program to implement// the above approach#include <functional>#include <iostream>using namespace std; // Driver codeint main(){ int n = 12345; // Function < return type (parameter // types) > functionName function<void()> printReverse = [&]() { if (n == 0) return; // Declaration + Body cout << n % 10 << " "; n /= 10; printReverse(); }; printReverse();} 5 4 3 2 1 Time complexity: O(logn) Auxiliary Space: O(logn) Examples: Below are some examples of recursive functions using lambda expressions. Program 9: C++14 // C++ program to implement// the above approach#include <iostream>using namespace std; // Driver codeint main(){ int n = 6; // Recursive Lambda function to // find the factorial of a number auto factorial = [&](auto&& factorial) { if (n == 1) return n; return n-- * factorial(factorial); }; auto factorial2 = [](int n, auto&& factorial2) { if (n == 1) return n; return n * factorial2(n - 1, factorial2); }; // Given n = 6 cout << factorial(factorial) << endl; // Given n = 5 cout << factorial2(5, factorial2);} 720 120 Time complexity: O(2n) Auxiliary Space: O(n) Explanation: In the factorial function, n is directly accessed using the [&] capture clause. In the factorial2 function, n is passed as an argument. Hence, there is no need for the [&] clause. Program 10: C++14 // C++ program to implement// the above approach#include <iostream>using namespace std; // Driver codeint main(){ // Sorted array int arr[] = { 1, 2, 5, 7, 10, 12, 15 }; int size = 7; // Item to be searched int key = 10; auto binarySearch = [&](int startIndex, int endIndex, auto&& binarySearch) { if (startIndex > endIndex) return -1; int midIndex = (startIndex + endIndex) / 2; if (arr[midIndex] == key) return midIndex; if (arr[midIndex] > key) return binarySearch(startIndex, midIndex - 1, binarySearch); if (arr[midIndex] < key) return binarySearch(midIndex + 1, endIndex, binarySearch); // Not found return -1; }; int index = binarySearch(0, size - 1, binarySearch); if (index == -1) cout << "Not found"; else cout << "Found on index " << index; return 0;} Found on index 4 Time complexity: O(logn) Auxiliary Space: O(1) raviparmar5532 jayanth_mkv CPP-Basics CPP-Functions C++ C++ Programs Recursion Recursion CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Jun, 2022" }, { "code": null, "e": 402, "s": 28, "text": "A recursive lambda expression is the process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. Using a recursive algorithm, certain problems can be solved quite easily. Examples of such problems are Towers of Hanoi (TOH), Inorder/Preorder/Postorder Tree Traversals, DFS of Graph, etc." }, { "code": null, "e": 641, "s": 402, "text": "A recursive function is a kind of loop structure only. The difference is it maintains a memory stack on its own. Obviously, it must have a break condition like for and while loop. Hence, the recursive function has the following structure-" }, { "code": null, "e": 750, "s": 641, "text": "function name(arguments)\n{\n a base case (a breaking condition) \n recursive code (the actual logic)\n}" }, { "code": null, "e": 871, "s": 750, "text": "int fact(int n)\n{\n // Base Case\n if (n < = 1)\n return 1;\n else \n return n * fact(n - 1); \n}" }, { "code": null, "e": 1117, "s": 871, "text": "C++ 11 introduced lambda expressions to allow us to write an inline function that can be used for short snippets of code that are not going to be reused and not worth naming. In its simplest form, the lambda expression can be defined as follows:" }, { "code": null, "e": 1201, "s": 1117, "text": "[ capture clause ] (parameters) -> return-type \n{ \n definition of method \n} " }, { "code": null, "e": 1212, "s": 1201, "text": "Program 1:" }, { "code": null, "e": 1289, "s": 1212, "text": "Below is the program for the lambda expressions in the sort() method in C++:" }, { "code": null, "e": 1295, "s": 1289, "text": "C++14" }, { "code": "// C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Driver codeint main(){ int arr[] = { 5, 2, 1, 4, 3 }; sort(arr, arr + 5, [](int& a, int& b) { // Instant lambda function return a > b; }); for (int i = 0; i < 5; i++) cout << arr[i] << \" \"; return 0;}", "e": 1654, "s": 1295, "text": null }, { "code": null, "e": 1665, "s": 1654, "text": "5 4 3 2 1 " }, { "code": null, "e": 1691, "s": 1665, "text": "Time complexity: O(nlogn)" }, { "code": null, "e": 1713, "s": 1691, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 2138, "s": 1713, "text": "Explanation: Here, the instant lambda function is used, which cannot be used in another sorting method, i.e., the same code needs to be written again. This lambda expression exists only during the execution of the sort() method. But it is possible to store the lambda expression in a variable (better to call it a function) as well, like below. By storing it, it can be used further, and of course, perform recursion also. " }, { "code": null, "e": 2149, "s": 2138, "text": "Program 2:" }, { "code": null, "e": 2155, "s": 2149, "text": "C++14" }, { "code": "// C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Stored lambda expressionauto cmp = [](int& a, int& b) { return a > b;}; // Driver codeint main(){ int arr[] = { 5, 2, 3, 1, 4 }; sort(arr, arr + 5, cmp); for (int i = 0; i < 5; i++) cout << arr[i] << \" \"; return 0;}", "e": 2491, "s": 2155, "text": null }, { "code": null, "e": 2502, "s": 2491, "text": "5 4 3 2 1 " }, { "code": null, "e": 2528, "s": 2502, "text": "Time complexity: O(nlogn)" }, { "code": null, "e": 2550, "s": 2528, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 2653, "s": 2550, "text": "Explanation: Here, auto cmp is the lambda stored function that can be used in as many sorting methods." }, { "code": null, "e": 2793, "s": 2653, "text": "Recursion Using Lambda: Let’s discuss the concept of recursion and lambda expressions together by considering the recursive function below:" }, { "code": null, "e": 2804, "s": 2793, "text": "Program 3:" }, { "code": null, "e": 2810, "s": 2804, "text": "C++14" }, { "code": "// C++ program to implement// the above approach#include <iostream>using namespace std; // Recursive function to print// the digits of a numbervoid printReverse(int n){ if (n == 0) return; cout << n % 10 << \" \"; printReverse(n / 10);} // Driver codeint main(){ int n = 12345; printReverse(n); return 0;}", "e": 3139, "s": 2810, "text": null }, { "code": null, "e": 3150, "s": 3139, "text": "5 4 3 2 1 " }, { "code": null, "e": 3175, "s": 3150, "text": "Time complexity: O(logn)" }, { "code": null, "e": 3200, "s": 3175, "text": "Auxiliary Space: O(logn)" }, { "code": null, "e": 3356, "s": 3200, "text": "Explanation: Above is the function which prints the digits of a number in reverse order, using recursion. The same can be done using the lambda expression." }, { "code": null, "e": 3367, "s": 3356, "text": "Program 4:" }, { "code": null, "e": 3447, "s": 3367, "text": "Below is the C++ program to implement the above code using lambda expressions: " }, { "code": null, "e": 3453, "s": 3447, "text": "C++14" }, { "code": "// C++ program to implement// the above approach#include <iostream>using namespace std; // Driver codeint main(){ int n = 12345; // Recursive lambda function to // print the digits of a number auto printReverse = [&]() { if (n == 0) return; cout << n % 10; n = n / 10; printReverse(); // As it is a part of main body, // semicolon is must }; printReverse(); return 0;}", "e": 3899, "s": 3453, "text": null }, { "code": null, "e": 3908, "s": 3899, "text": "Output: " }, { "code": null, "e": 4102, "s": 3908, "text": "Oops, the function, defined using auto return type, must be deducted first (Compiler must be able to determine whether the return type auto can be converted into void or int or something else) " }, { "code": null, "e": 4501, "s": 4102, "text": "Explanation: Here, how the function is going to recognize the variable n, even if it is not passed as an argument. A lambda with an empty capture clause [ ] can access only those variables which are local to it. Here, the capture close [&] is used, which allows the function to access the variable n ( The actual value of variable n is being changed). There are two ways to resolve the error above:" }, { "code": null, "e": 4562, "s": 4501, "text": "1. By passing the function itself, to the function argument:" }, { "code": null, "e": 4619, "s": 4562, "text": "Below is the C++ program to implement the above concept:" }, { "code": null, "e": 4631, "s": 4619, "text": "Program 5: " }, { "code": null, "e": 4637, "s": 4631, "text": "C++14" }, { "code": "// C++ program to implement// the above approach#include <iostream>using namespace std; // Driver codeint main(){ int n = 12345; // Function itself as a parameter auto printReverse = [&](auto&& printReverse) { if (n == 0) return; cout << n % 10 << \" \"; n = n / 10; printReverse(printReverse); }; // Function as an argument printReverse(printReverse); return 0;}", "e": 5061, "s": 4637, "text": null }, { "code": null, "e": 5072, "s": 5061, "text": "5 4 3 2 1 " }, { "code": null, "e": 5097, "s": 5072, "text": "Time complexity: O(logn)" }, { "code": null, "e": 5122, "s": 5097, "text": "Auxiliary Space: O(logn)" }, { "code": null, "e": 5158, "s": 5122, "text": "2. By declaring the function first:" }, { "code": null, "e": 5323, "s": 5158, "text": "Declaring a function means declaring its name and parameters type in order to inform a compiler that there is a function named xyz, which will write its body later." }, { "code": null, "e": 5334, "s": 5323, "text": "Program 6:" }, { "code": null, "e": 5392, "s": 5334, "text": "Below is the C++ program to implement the above concept: " }, { "code": null, "e": 5396, "s": 5392, "text": "C++" }, { "code": "// C++ program to implement// the above approach#include <iostream>using namespace std; // Declaring of a functionvoid declaringFunction(string s); // Driver codeint main(){ declaringFunction(\"Hello I am learning how to declare a function\"); return 0;} // Body of a functionvoid declaringFunction(string s){ cout << s;}", "e": 5725, "s": 5396, "text": null }, { "code": null, "e": 5771, "s": 5725, "text": "Hello I am learning how to declare a function" }, { "code": null, "e": 5793, "s": 5771, "text": "Time complexity: O(1)" }, { "code": null, "e": 5815, "s": 5793, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 5826, "s": 5815, "text": "Program 7:" }, { "code": null, "e": 5954, "s": 5826, "text": "Since it is a lambda function, there must be some unique way of declaring the function. Below is the C++ program for the same: " }, { "code": null, "e": 5960, "s": 5954, "text": "C++14" }, { "code": "// C++ program to implement// the above approach#include <functional>#include <iostream>using namespace std; // Driver codeint main(){ int n = 12345; // Function < return type (parameter // types) > functionName // Don't forget to include functional // header // Declaration function<void()> printReverse; printReverse = [&]() { if (n == 0) return; // Defination cout << n % 10 << \" \"; n /= 10; printReverse(); }; printReverse();}", "e": 6473, "s": 5960, "text": null }, { "code": null, "e": 6484, "s": 6473, "text": "5 4 3 2 1 " }, { "code": null, "e": 6509, "s": 6484, "text": "Time complexity: O(logn)" }, { "code": null, "e": 6534, "s": 6509, "text": "Auxiliary Space: O(logn)" }, { "code": null, "e": 6819, "s": 6534, "text": "Explanation: In the above code, first, the function printReverse is declared, then we have defined its body. Instead of that, we can directly declare the function and its body along with, which is known as defining a function. Below is the C++ program to implement the above approach:" }, { "code": null, "e": 6830, "s": 6819, "text": "Program 8:" }, { "code": null, "e": 6836, "s": 6830, "text": "C++14" }, { "code": "// C++ program to implement// the above approach#include <functional>#include <iostream>using namespace std; // Driver codeint main(){ int n = 12345; // Function < return type (parameter // types) > functionName function<void()> printReverse = [&]() { if (n == 0) return; // Declaration + Body cout << n % 10 << \" \"; n /= 10; printReverse(); }; printReverse();}", "e": 7265, "s": 6836, "text": null }, { "code": null, "e": 7276, "s": 7265, "text": "5 4 3 2 1 " }, { "code": null, "e": 7301, "s": 7276, "text": "Time complexity: O(logn)" }, { "code": null, "e": 7326, "s": 7301, "text": "Auxiliary Space: O(logn)" }, { "code": null, "e": 7409, "s": 7326, "text": "Examples: Below are some examples of recursive functions using lambda expressions." }, { "code": null, "e": 7421, "s": 7409, "text": "Program 9: " }, { "code": null, "e": 7427, "s": 7421, "text": "C++14" }, { "code": "// C++ program to implement// the above approach#include <iostream>using namespace std; // Driver codeint main(){ int n = 6; // Recursive Lambda function to // find the factorial of a number auto factorial = [&](auto&& factorial) { if (n == 1) return n; return n-- * factorial(factorial); }; auto factorial2 = [](int n, auto&& factorial2) { if (n == 1) return n; return n * factorial2(n - 1, factorial2); }; // Given n = 6 cout << factorial(factorial) << endl; // Given n = 5 cout << factorial2(5, factorial2);}", "e": 8026, "s": 7427, "text": null }, { "code": null, "e": 8034, "s": 8026, "text": "720\n120" }, { "code": null, "e": 8057, "s": 8034, "text": "Time complexity: O(2n)" }, { "code": null, "e": 8079, "s": 8057, "text": "Auxiliary Space: O(n)" }, { "code": null, "e": 8272, "s": 8079, "text": "Explanation: In the factorial function, n is directly accessed using the [&] capture clause. In the factorial2 function, n is passed as an argument. Hence, there is no need for the [&] clause." }, { "code": null, "e": 8284, "s": 8272, "text": "Program 10:" }, { "code": null, "e": 8290, "s": 8284, "text": "C++14" }, { "code": "// C++ program to implement// the above approach#include <iostream>using namespace std; // Driver codeint main(){ // Sorted array int arr[] = { 1, 2, 5, 7, 10, 12, 15 }; int size = 7; // Item to be searched int key = 10; auto binarySearch = [&](int startIndex, int endIndex, auto&& binarySearch) { if (startIndex > endIndex) return -1; int midIndex = (startIndex + endIndex) / 2; if (arr[midIndex] == key) return midIndex; if (arr[midIndex] > key) return binarySearch(startIndex, midIndex - 1, binarySearch); if (arr[midIndex] < key) return binarySearch(midIndex + 1, endIndex, binarySearch); // Not found return -1; }; int index = binarySearch(0, size - 1, binarySearch); if (index == -1) cout << \"Not found\"; else cout << \"Found on index \" << index; return 0;}", "e": 9403, "s": 8290, "text": null }, { "code": null, "e": 9420, "s": 9403, "text": "Found on index 4" }, { "code": null, "e": 9445, "s": 9420, "text": "Time complexity: O(logn)" }, { "code": null, "e": 9467, "s": 9445, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 9482, "s": 9467, "text": "raviparmar5532" }, { "code": null, "e": 9494, "s": 9482, "text": "jayanth_mkv" }, { "code": null, "e": 9505, "s": 9494, "text": "CPP-Basics" }, { "code": null, "e": 9519, "s": 9505, "text": "CPP-Functions" }, { "code": null, "e": 9523, "s": 9519, "text": "C++" }, { "code": null, "e": 9536, "s": 9523, "text": "C++ Programs" }, { "code": null, "e": 9546, "s": 9536, "text": "Recursion" }, { "code": null, "e": 9556, "s": 9546, "text": "Recursion" }, { "code": null, "e": 9560, "s": 9556, "text": "CPP" } ]
Python | Pandas Series.str.decode()
27 Mar, 2019 Series.str can be used to access the values of the series as strings and apply several methods to it. Pandas Series.str.decode() function is used to decode character string in the Series/Index using indicated encoding. This function is equivalent to str.decode() in python2 and bytes.decode() in python3. Syntax: Series.str.decode(encoding, errors=’strict’) Parameter :encoding : strerrors : str, optional Returns : decoded Series/Index of objects Example #1: Use Series.str.decode() function to decode the character strings in the underlying data of the given series object. Use ‘UTF-8’ encoding method. # importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([b"b'New_York'", b"b'Lisbon'", b"b'Tokyo'", b"b'Paris'", b"b'Munich'"]) # Creating the indexidx = ['City 1', 'City 2', 'City 3', 'City 4', 'City 5'] # set the indexsr.index = idx # Print the seriesprint(sr) Output : Now we will use Series.str.decode() function to decode the character strings in the underlying data of the given series object. # use 'UTF-8' encodingresult = sr.str.decode(encoding = 'UTF-8') # print the resultprint(result) Output : As we can see in the output, the Series.str.decode() function has successfully decodes the strings in the underlying data of the given series object. Example #2 : Use Series.str.decode() function to decode the character strings in the underlying data of the given series object. Use ‘ASCII’ encoding method. # importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([b'Mike-', b'Alessa-', b'Nick-', b'Kim-', b'Britney-']) # Creating the indexidx = ['Name 1', 'Name 2', 'Name 3', 'Name 4', 'Name 5'] # set the indexsr.index = idx # Print the seriesprint(sr) Output : Now we will use Series.str.decode() function to decode the character strings in the underlying data of the given series object. # use 'ASCII' encodingresult = sr.str.decode(encoding = 'ASCII') # print the resultprint(result) Output : As we can see in the output, the Series.str.decode() function has successfully decodes the strings in the underlying data of the given series object. Python-pandas Python-pandas-series-str Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Different ways to create Pandas Dataframe Enumerate() in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Iterate over a list in Python Introduction To PYTHON Convert integer to string in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n27 Mar, 2019" }, { "code": null, "e": 333, "s": 28, "text": "Series.str can be used to access the values of the series as strings and apply several methods to it. Pandas Series.str.decode() function is used to decode character string in the Series/Index using indicated encoding. This function is equivalent to str.decode() in python2 and bytes.decode() in python3." }, { "code": null, "e": 386, "s": 333, "text": "Syntax: Series.str.decode(encoding, errors=’strict’)" }, { "code": null, "e": 434, "s": 386, "text": "Parameter :encoding : strerrors : str, optional" }, { "code": null, "e": 476, "s": 434, "text": "Returns : decoded Series/Index of objects" }, { "code": null, "e": 633, "s": 476, "text": "Example #1: Use Series.str.decode() function to decode the character strings in the underlying data of the given series object. Use ‘UTF-8’ encoding method." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([b\"b'New_York'\", b\"b'Lisbon'\", b\"b'Tokyo'\", b\"b'Paris'\", b\"b'Munich'\"]) # Creating the indexidx = ['City 1', 'City 2', 'City 3', 'City 4', 'City 5'] # set the indexsr.index = idx # Print the seriesprint(sr)", "e": 924, "s": 633, "text": null }, { "code": null, "e": 933, "s": 924, "text": "Output :" }, { "code": null, "e": 1061, "s": 933, "text": "Now we will use Series.str.decode() function to decode the character strings in the underlying data of the given series object." }, { "code": "# use 'UTF-8' encodingresult = sr.str.decode(encoding = 'UTF-8') # print the resultprint(result)", "e": 1159, "s": 1061, "text": null }, { "code": null, "e": 1168, "s": 1159, "text": "Output :" }, { "code": null, "e": 1318, "s": 1168, "text": "As we can see in the output, the Series.str.decode() function has successfully decodes the strings in the underlying data of the given series object." }, { "code": null, "e": 1476, "s": 1318, "text": "Example #2 : Use Series.str.decode() function to decode the character strings in the underlying data of the given series object. Use ‘ASCII’ encoding method." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([b'Mike-', b'Alessa-', b'Nick-', b'Kim-', b'Britney-']) # Creating the indexidx = ['Name 1', 'Name 2', 'Name 3', 'Name 4', 'Name 5'] # set the indexsr.index = idx # Print the seriesprint(sr)", "e": 1751, "s": 1476, "text": null }, { "code": null, "e": 1760, "s": 1751, "text": "Output :" }, { "code": null, "e": 1888, "s": 1760, "text": "Now we will use Series.str.decode() function to decode the character strings in the underlying data of the given series object." }, { "code": "# use 'ASCII' encodingresult = sr.str.decode(encoding = 'ASCII') # print the resultprint(result)", "e": 1986, "s": 1888, "text": null }, { "code": null, "e": 1995, "s": 1986, "text": "Output :" }, { "code": null, "e": 2145, "s": 1995, "text": "As we can see in the output, the Series.str.decode() function has successfully decodes the strings in the underlying data of the given series object." }, { "code": null, "e": 2159, "s": 2145, "text": "Python-pandas" }, { "code": null, "e": 2184, "s": 2159, "text": "Python-pandas-series-str" }, { "code": null, "e": 2191, "s": 2184, "text": "Python" }, { "code": null, "e": 2289, "s": 2191, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2331, "s": 2289, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2353, "s": 2331, "text": "Enumerate() in Python" }, { "code": null, "e": 2379, "s": 2353, "text": "Python String | replace()" }, { "code": null, "e": 2411, "s": 2379, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2440, "s": 2411, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2467, "s": 2440, "text": "Python Classes and Objects" }, { "code": null, "e": 2488, "s": 2467, "text": "Python OOPs Concepts" }, { "code": null, "e": 2518, "s": 2488, "text": "Iterate over a list in Python" }, { "code": null, "e": 2541, "s": 2518, "text": "Introduction To PYTHON" } ]