title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Generate n-bit Gray Codes
08 Jul, 2022 Given a number N, generate bit patterns from 0 to 2^N-1 such that successive patterns differ by one bit. Examples: Input: N = 2 Output: 00 01 11 10 Input: N = 3 Output: 000 001 011 010 110 111 101 100 Method-1 The above sequences are Gray Codes of different widths. Following is an interesting pattern in Gray Codes.n-bit Gray Codes can be generated from list of (n-1)-bit Gray codes using following steps. Let the list of (n-1)-bit Gray codes be L1. Create another list L2 which is reverse of L1.Modify the list L1 by prefixing a β€˜0’ in all codes of L1.Modify the list L2 by prefixing a β€˜1’ in all codes of L2.Concatenate L1 and L2. The concatenated list is required list of n-bit Gray codes Let the list of (n-1)-bit Gray codes be L1. Create another list L2 which is reverse of L1. Modify the list L1 by prefixing a β€˜0’ in all codes of L1. Modify the list L2 by prefixing a β€˜1’ in all codes of L2. Concatenate L1 and L2. The concatenated list is required list of n-bit Gray codes For example, following are steps for generating the 3-bit Gray code list from the list of 2-bit Gray code list. L1 = {00, 01, 11, 10} (List of 2-bit Gray Codes) L2 = {10, 11, 01, 00} (Reverse of L1) Prefix all entries of L1 with β€˜0’, L1 becomes {000, 001, 011, 010} Prefix all entries of L2 with β€˜1’, L2 becomes {110, 111, 101, 100} Concatenate L1 and L2, we get {000, 001, 011, 010, 110, 111, 101, 100} To generate n-bit Gray codes, we start from list of 1 bit Gray codes. The list of 1 bit Gray code is {0, 1}. We repeat above steps to generate 2 bit Gray codes from 1 bit Gray codes, then 3-bit Gray codes from 2-bit Gray codes till the number of bits becomes equal to n. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to generate n-bit Gray codes#include <iostream>#include <string>#include <vector>using namespace std; // This function generates all n bit Gray codes and prints the// generated codesvoid generateGrayarr(int n){ // base case if (n <= 0) return; // 'arr' will store all generated codes vector<string> arr; // start with one-bit pattern arr.push_back("0"); arr.push_back("1"); // Every iteration of this loop generates 2*i codes from previously // generated i codes. int i, j; for (i = 2; i < (1<<n); i = i<<1) { // Enter the previously generated codes again in arr[] in reverse // order. Nor arr[] has double number of codes. for (j = i-1 ; j >= 0 ; j--) arr.push_back(arr[j]); // append 0 to the first half for (j = 0 ; j < i ; j++) arr[j] = "0" + arr[j]; // append 1 to the second half for (j = i ; j < 2*i ; j++) arr[j] = "1" + arr[j]; } // print contents of arr[] for (i = 0 ; i < arr.size() ; i++ ) cout << arr[i] << endl;} // Driver program to test above functionint main(){ generateGrayarr(3); return 0;} // Java program to generate n-bit Gray codesimport java.util.*;class GfG { // This function generates all n bit Gray codes and prints the// generated codesstatic void generateGrayarr(int n){ // base case if (n <= 0) return; // 'arr' will store all generated codes ArrayList<String> arr = new ArrayList<String> (); // start with one-bit pattern arr.add("0"); arr.add("1"); // Every iteration of this loop generates 2*i codes from previously // generated i codes. int i, j; for (i = 2; i < (1<<n); i = i<<1) { // Enter the previously generated codes again in arr[] in reverse // order. Nor arr[] has double number of codes. for (j = i-1 ; j >= 0 ; j--) arr.add(arr.get(j)); // append 0 to the first half for (j = 0 ; j < i ; j++) arr.set(j, "0" + arr.get(j)); // append 1 to the second half for (j = i ; j < 2*i ; j++) arr.set(j, "1" + arr.get(j)); } // print contents of arr[] for (i = 0 ; i < arr.size() ; i++ ) System.out.println(arr.get(i));} // Driver program to test above functionpublic static void main(String[] args){ generateGrayarr(3);}} # Python3 program to generate n-bit Gray codesimport math as mt # This function generates all n bit Gray# codes and prints the generated codesdef generateGrayarr(n): # base case if (n <= 0): return # 'arr' will store all generated codes arr = list() # start with one-bit pattern arr.append("0") arr.append("1") # Every iteration of this loop generates # 2*i codes from previously generated i codes. i = 2 j = 0 while(True): if i >= 1 << n: break # Enter the previously generated codes # again in arr[] in reverse order. # Nor arr[] has double number of codes. for j in range(i - 1, -1, -1): arr.append(arr[j]) # append 0 to the first half for j in range(i): arr[j] = "0" + arr[j] # append 1 to the second half for j in range(i, 2 * i): arr[j] = "1" + arr[j] i = i << 1 # print contents of arr[] for i in range(len(arr)): print(arr[i]) # Driver CodegenerateGrayarr(3) # This code is contributed# by Mohit kumar 29 using System;using System.Collections.Generic; // C# program to generate n-bit Gray codes public class GfG{ // This function generates all n bit Gray codes and prints the // generated codes public static void generateGrayarr(int n){ // base case if (n <= 0) { return; } // 'arr' will store all generated codes List<string> arr = new List<string> (); // start with one-bit pattern arr.Add("0"); arr.Add("1"); // Every iteration of this loop generates 2*i codes from previously // generated i codes. int i, j; for (i = 2; i < (1 << n); i = i << 1) { // Enter the previously generated codes again in arr[] in reverse // order. Nor arr[] has double number of codes. for (j = i - 1 ; j >= 0 ; j--) { arr.Add(arr[j]); } // append 0 to the first half for (j = 0 ; j < i ; j++) { arr[j] = "0" + arr[j]; } // append 1 to the second half for (j = i ; j < 2 * i ; j++) { arr[j] = "1" + arr[j]; } } // print contents of arr[] for (i = 0 ; i < arr.Count ; i++) { Console.WriteLine(arr[i]); }} // Driver program to test above function public static void Main(string[] args){ generateGrayarr(3);}} // This code is contributed by Shrikant13 <script>// Javascript program to generate n-bit Gray codes // This function generates all n bit Gray codes and prints the // generated codes function generateGrayarr(n) { // base case if (n <= 0) return; // 'arr' will store all generated codes let arr = []; // start with one-bit pattern arr.push("0"); arr.push("1"); // Every iteration of this loop generates 2*i codes from previously // generated i codes. let i, j; for (i = 2; i < (1<<n); i = i<<1) { // Enter the previously generated codes again in arr[] in reverse // order. Nor arr[] has double number of codes. for (j = i-1 ; j >= 0 ; j--) arr.push(arr[j]); // append 0 to the first half for (j = 0 ; j < i ; j++) arr[j]= "0" + arr[j]; // append 1 to the second half for (j = i ; j < 2*i ; j++) arr[j]= "1" + arr[j]; } // print contents of arr[] for (i = 0 ; i < arr.length ; i++ ) document.write(arr[i]+"<br>"); } // Driver program to test above function generateGrayarr(3); // This code is contributed by unknown2108</script> 000 001 011 010 110 111 101 100 Time Complexity: O(2N)Auxiliary Space: O(2N) Method 2: Recursive Approach The idea is to recursively append the bit 0 and 1 each time until the number of bits is not equal to N. Base Condition: The base case for this problem will be when the value of N = 0 or 1. If (N == 0)return {β€œ0”}if (N == 1)return {β€œ0”, β€œ1”} Recursive Condition: Otherwise, for any value greater than 1, recursively generate the gray codes of the N – 1 bits and then for each of the gray code generated add the prefix 0 and 1. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to generate// n-bit Gray codes #include <bits/stdc++.h>using namespace std; // This function generates all n// bit Gray codes and prints the// generated codesvector<string> generateGray(int n){ // Base case if (n <= 0) return {"0"}; if (n == 1) { return {"0","1"}; } //Recursive case vector<string> recAns= generateGray(n-1); vector<string> mainAns; // Append 0 to the first half for(int i=0;i<recAns.size();i++) { string s=recAns[i]; mainAns.push_back("0"+s); } // Append 1 to the second half for(int i=recAns.size()-1;i>=0;i--) { string s=recAns[i]; mainAns.push_back("1"+s); } return mainAns;} // Function to generate the// Gray code of N bitsvoid generateGrayarr(int n){ vector<string> arr; arr=generateGray(n); // print contents of arr for (int i = 0 ; i < arr.size(); i++ ) cout << arr[i] << endl;} // Driver Codeint main(){ generateGrayarr(3); return 0;} // Java program to generate// n-bit Gray codesimport java.io.*;import java.util.*;class GFG{ // This function generates all n // bit Gray codes and prints the // generated codes static ArrayList<String> generateGray(int n) { // Base case if (n <= 0) { ArrayList<String> temp = new ArrayList<String>(){{add("0");}}; return temp; } if(n == 1) { ArrayList<String> temp = new ArrayList<String>(){{add("0");add("1");}}; return temp; } // Recursive case ArrayList<String> recAns = generateGray(n - 1); ArrayList<String> mainAns = new ArrayList<String>(); // Append 0 to the first half for(int i = 0; i < recAns.size(); i++) { String s = recAns.get(i); mainAns.add("0" + s); } // Append 1 to the second half for(int i = recAns.size() - 1; i >= 0; i--) { String s = recAns.get(i); mainAns.add("1" + s); } return mainAns; } // Function to generate the // Gray code of N bits static void generateGrayarr(int n) { ArrayList<String> arr = new ArrayList<String>(); arr = generateGray(n); // print contents of arr for (int i = 0 ; i < arr.size(); i++) { System.out.println(arr.get(i)); } } // Driver Code public static void main (String[] args) { generateGrayarr(3); }} // This code is contributed by rag2127. # Python3 program to generate# n-bit Gray codes # This function generates all n# bit Gray codes and prints the# generated codesdef generateGray(n): # Base case if (n <= 0): return ["0"] if (n == 1): return [ "0", "1" ] # Recursive case recAns = generateGray(n - 1) mainAns = [] # Append 0 to the first half for i in range(len(recAns)): s = recAns[i] mainAns.append("0" + s) # Append 1 to the second half for i in range(len(recAns) - 1, -1, -1): s = recAns[i] mainAns.append("1" + s) return mainAns # Function to generate the# Gray code of N bitsdef generateGrayarr(n): arr = generateGray(n) # Print contents of arr print(*arr, sep = "\n") # Driver CodegenerateGrayarr(3) # This code is contributed by avanitrachhadiya2155 // Java program to generate// n-bit Gray codesusing System;using System.Collections.Generic;class GFG { // This function generates all n // bit Gray codes and prints the // generated codes static List<String> generateGray(int n) { // Base case if (n <= 0) { List<String> temp = new List<String>(); temp.Add("0"); return temp; } if (n == 1) { List<String> temp = new List<String>(); temp.Add("0"); temp.Add("1"); return temp; } // Recursive case List<String> recAns = generateGray(n - 1); List<String> mainAns = new List<String>(); // Append 0 to the first half for (int i = 0; i < recAns.Count; i++) { String s = recAns[i]; mainAns.Add("0" + s); } // Append 1 to the second half for (int i = recAns.Count - 1; i >= 0; i--) { String s = recAns[i]; mainAns.Add("1" + s); } return mainAns; } // Function to generate the // Gray code of N bits static void generateGrayarr(int n) { List<String> arr = new List<String>(); arr = generateGray(n); // print contents of arr for (int i = 0; i < arr.Count; i++) { Console.WriteLine(arr[i]); } } // Driver Code public static void Main(String[] args) { generateGrayarr(3); }} // This code is contributed by grand_master. <script>// Javascript program to generate// n-bit Gray codes // This function generates all n // bit Gray codes and prints the // generated codesfunction generateGray(n){ // Base case if (n <= 0) { let temp =["0"]; return temp; } if(n == 1) { let temp =["0","1"]; return temp; } // Recursive case let recAns = generateGray(n - 1); let mainAns = []; // Append 0 to the first half for(let i = 0; i < recAns.length; i++) { let s = recAns[i]; mainAns.push("0" + s); } // Append 1 to the second half for(let i = recAns.length - 1; i >= 0; i--) { let s = recAns[i]; mainAns.push("1" + s); } return mainAns;} // Function to generate the // Gray code of N bitsfunction generateGrayarr(n){ let arr = []; arr = generateGray(n); // print contents of arr for (let i = 0 ; i < arr.length; i++) { document.write(arr[i]+"<br>"); }} // Driver CodegenerateGrayarr(3); // This code is contributed by ab2127</script> 000 001 011 010 110 111 101 100 Time Complexity: O(2N)Auxiliary Space: O(2N) Method3: (Using bitset) We should first find binary no from 1 to n and then convert it into string and then print it using substring function of string. Below is the implementation of the above idea: C++ Java Python3 Javascript C# // C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; void GreyCode(int n){ // power of 2 for (int i = 0; i < (1 << n); i++) { // Generating the decimal // values of gray code then using // bitset to convert them to binary form int val = (i ^ (i >> 1)); // Using bitset bitset<32> r(val); // Converting to string string s = r.to_string(); cout << s.substr(32 - n) << " "; }} // Driver Codeint main(){ int n; n = 4; // Function call GreyCode(n); return 0;} // Java implementation of the above approachimport java.lang.Math; class GFG { static void GreyCode(int n) { // power of 2 for (int i = 0; i < (1 << n); i++) { // Generating the decimal // values of gray code then using // bitset to convert them to binary form int val = (i ^ (i >> 1)); // Converting to binary string String s = Integer.toBinaryString(val); System.out.print( String.format("%1$" + 4 + "s", s) .replace(' ', '0') + " "); } } // Driver Code public static void main(String[] args) { int n = 4; // Function call GreyCode(n); }} // This code is contributed by phasing17 # Python3 implementation of the above approachdef GreyCode(n): # power of 2 for i in range(1 << n): # Generating the decimal # values of gray code then using # bitset to convert them to binary form val = (i ^ (i >> 1)) # Converting to binary string s = bin(val)[2::] print(s.zfill(4), end = " ") # Driver Coden = 4 # Function callGreyCode(n) # This code is contributed by phasing17 // JavaScript implementation of the above approachfunction GreyCode(n){ // power of 2 for (var i = 0; i < (1 << n); i++) { // Generating the decimal // values of gray code then using // bitset to convert them to binary form var val = (i ^ (i >> 1)); // Converting to binary string s = val.toString(2); process.stdout.write(s.padStart(4, '0') + " "); }} // Driver Codelet n = 4; // Function callGreyCode(n); // This code is contributed by phasing17 // C# implementation of the above approach using System; class GFG { static void GreyCode(int n) { // power of 2 for (int i = 0; i < (1 << n); i++) { // Generating the decimal // values of gray code then using // bitset to convert them to binary form int val = (i ^ (i >> 1)); // Converting to binary string string s = Convert.ToString(val, 2); Console.Write(s.PadLeft(4, '0') + " "); } } // Driver Code public static void Main(string[] args) { int n = 4; // Function call GreyCode(n); }} // This code is contributed by phasing17 0000 0001 0011 0010 0110 0111 0101 0100 1100 1101 1111 1110 1010 1011 1001 1000 Time Complexity: O(2N)Auxiliary Space: O(N) prerna saini shrikanth13 mohit kumar 29 aryan_a biturobin187 avanitrachhadiya2155 gouravrj9654 rag2127 grand_master unknown2108 ab2127 simmytarika5 surinderdawra388 phasing17 hardikkoriintern Amazon gray-code Microsoft Bit Magic Strings Amazon Microsoft Strings Bit Magic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Bitwise Operators in C/C++ Left Shift and Right Shift Operators in C/C++ Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Count set bits in an integer How to swap two numbers without using a temporary variable? Write a program to reverse an array or string Reverse a string in Java Write a program to print all permutations of a given string C++ Data Types Check for Balanced Brackets in an expression (well-formedness) using Stack
[ { "code": null, "e": 54, "s": 26, "text": "\n08 Jul, 2022" }, { "code": null, "e": 159, "s": 54, "text": "Given a number N, generate bit patterns from 0 to 2^N-1 such that successive patterns differ by one bit." }, { "code": null, "e": 169, "s": 159, "text": "Examples:" }, { "code": null, "e": 256, "s": 169, "text": "Input: N = 2\nOutput: 00 01 11 10\n\nInput: N = 3\nOutput: 000 001 011 010 110 111 101 100" }, { "code": null, "e": 265, "s": 256, "text": "Method-1" }, { "code": null, "e": 462, "s": 265, "text": "The above sequences are Gray Codes of different widths. Following is an interesting pattern in Gray Codes.n-bit Gray Codes can be generated from list of (n-1)-bit Gray codes using following steps." }, { "code": null, "e": 748, "s": 462, "text": "Let the list of (n-1)-bit Gray codes be L1. Create another list L2 which is reverse of L1.Modify the list L1 by prefixing a β€˜0’ in all codes of L1.Modify the list L2 by prefixing a β€˜1’ in all codes of L2.Concatenate L1 and L2. The concatenated list is required list of n-bit Gray codes" }, { "code": null, "e": 839, "s": 748, "text": "Let the list of (n-1)-bit Gray codes be L1. Create another list L2 which is reverse of L1." }, { "code": null, "e": 897, "s": 839, "text": "Modify the list L1 by prefixing a β€˜0’ in all codes of L1." }, { "code": null, "e": 955, "s": 897, "text": "Modify the list L2 by prefixing a β€˜1’ in all codes of L2." }, { "code": null, "e": 1037, "s": 955, "text": "Concatenate L1 and L2. The concatenated list is required list of n-bit Gray codes" }, { "code": null, "e": 1712, "s": 1037, "text": "For example, following are steps for generating the 3-bit Gray code list from the list of 2-bit Gray code list. L1 = {00, 01, 11, 10} (List of 2-bit Gray Codes) L2 = {10, 11, 01, 00} (Reverse of L1) Prefix all entries of L1 with β€˜0’, L1 becomes {000, 001, 011, 010} Prefix all entries of L2 with β€˜1’, L2 becomes {110, 111, 101, 100} Concatenate L1 and L2, we get {000, 001, 011, 010, 110, 111, 101, 100} To generate n-bit Gray codes, we start from list of 1 bit Gray codes. The list of 1 bit Gray code is {0, 1}. We repeat above steps to generate 2 bit Gray codes from 1 bit Gray codes, then 3-bit Gray codes from 2-bit Gray codes till the number of bits becomes equal to n." }, { "code": null, "e": 1763, "s": 1712, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 1767, "s": 1763, "text": "C++" }, { "code": null, "e": 1772, "s": 1767, "text": "Java" }, { "code": null, "e": 1780, "s": 1772, "text": "Python3" }, { "code": null, "e": 1783, "s": 1780, "text": "C#" }, { "code": null, "e": 1794, "s": 1783, "text": "Javascript" }, { "code": "// C++ program to generate n-bit Gray codes#include <iostream>#include <string>#include <vector>using namespace std; // This function generates all n bit Gray codes and prints the// generated codesvoid generateGrayarr(int n){ // base case if (n <= 0) return; // 'arr' will store all generated codes vector<string> arr; // start with one-bit pattern arr.push_back(\"0\"); arr.push_back(\"1\"); // Every iteration of this loop generates 2*i codes from previously // generated i codes. int i, j; for (i = 2; i < (1<<n); i = i<<1) { // Enter the previously generated codes again in arr[] in reverse // order. Nor arr[] has double number of codes. for (j = i-1 ; j >= 0 ; j--) arr.push_back(arr[j]); // append 0 to the first half for (j = 0 ; j < i ; j++) arr[j] = \"0\" + arr[j]; // append 1 to the second half for (j = i ; j < 2*i ; j++) arr[j] = \"1\" + arr[j]; } // print contents of arr[] for (i = 0 ; i < arr.size() ; i++ ) cout << arr[i] << endl;} // Driver program to test above functionint main(){ generateGrayarr(3); return 0;}", "e": 2972, "s": 1794, "text": null }, { "code": "// Java program to generate n-bit Gray codesimport java.util.*;class GfG { // This function generates all n bit Gray codes and prints the// generated codesstatic void generateGrayarr(int n){ // base case if (n <= 0) return; // 'arr' will store all generated codes ArrayList<String> arr = new ArrayList<String> (); // start with one-bit pattern arr.add(\"0\"); arr.add(\"1\"); // Every iteration of this loop generates 2*i codes from previously // generated i codes. int i, j; for (i = 2; i < (1<<n); i = i<<1) { // Enter the previously generated codes again in arr[] in reverse // order. Nor arr[] has double number of codes. for (j = i-1 ; j >= 0 ; j--) arr.add(arr.get(j)); // append 0 to the first half for (j = 0 ; j < i ; j++) arr.set(j, \"0\" + arr.get(j)); // append 1 to the second half for (j = i ; j < 2*i ; j++) arr.set(j, \"1\" + arr.get(j)); } // print contents of arr[] for (i = 0 ; i < arr.size() ; i++ ) System.out.println(arr.get(i));} // Driver program to test above functionpublic static void main(String[] args){ generateGrayarr(3);}}", "e": 4169, "s": 2972, "text": null }, { "code": "# Python3 program to generate n-bit Gray codesimport math as mt # This function generates all n bit Gray# codes and prints the generated codesdef generateGrayarr(n): # base case if (n <= 0): return # 'arr' will store all generated codes arr = list() # start with one-bit pattern arr.append(\"0\") arr.append(\"1\") # Every iteration of this loop generates # 2*i codes from previously generated i codes. i = 2 j = 0 while(True): if i >= 1 << n: break # Enter the previously generated codes # again in arr[] in reverse order. # Nor arr[] has double number of codes. for j in range(i - 1, -1, -1): arr.append(arr[j]) # append 0 to the first half for j in range(i): arr[j] = \"0\" + arr[j] # append 1 to the second half for j in range(i, 2 * i): arr[j] = \"1\" + arr[j] i = i << 1 # print contents of arr[] for i in range(len(arr)): print(arr[i]) # Driver CodegenerateGrayarr(3) # This code is contributed# by Mohit kumar 29", "e": 5265, "s": 4169, "text": null }, { "code": "using System;using System.Collections.Generic; // C# program to generate n-bit Gray codes public class GfG{ // This function generates all n bit Gray codes and prints the // generated codes public static void generateGrayarr(int n){ // base case if (n <= 0) { return; } // 'arr' will store all generated codes List<string> arr = new List<string> (); // start with one-bit pattern arr.Add(\"0\"); arr.Add(\"1\"); // Every iteration of this loop generates 2*i codes from previously // generated i codes. int i, j; for (i = 2; i < (1 << n); i = i << 1) { // Enter the previously generated codes again in arr[] in reverse // order. Nor arr[] has double number of codes. for (j = i - 1 ; j >= 0 ; j--) { arr.Add(arr[j]); } // append 0 to the first half for (j = 0 ; j < i ; j++) { arr[j] = \"0\" + arr[j]; } // append 1 to the second half for (j = i ; j < 2 * i ; j++) { arr[j] = \"1\" + arr[j]; } } // print contents of arr[] for (i = 0 ; i < arr.Count ; i++) { Console.WriteLine(arr[i]); }} // Driver program to test above function public static void Main(string[] args){ generateGrayarr(3);}} // This code is contributed by Shrikant13", "e": 6606, "s": 5265, "text": null }, { "code": "<script>// Javascript program to generate n-bit Gray codes // This function generates all n bit Gray codes and prints the // generated codes function generateGrayarr(n) { // base case if (n <= 0) return; // 'arr' will store all generated codes let arr = []; // start with one-bit pattern arr.push(\"0\"); arr.push(\"1\"); // Every iteration of this loop generates 2*i codes from previously // generated i codes. let i, j; for (i = 2; i < (1<<n); i = i<<1) { // Enter the previously generated codes again in arr[] in reverse // order. Nor arr[] has double number of codes. for (j = i-1 ; j >= 0 ; j--) arr.push(arr[j]); // append 0 to the first half for (j = 0 ; j < i ; j++) arr[j]= \"0\" + arr[j]; // append 1 to the second half for (j = i ; j < 2*i ; j++) arr[j]= \"1\" + arr[j]; } // print contents of arr[] for (i = 0 ; i < arr.length ; i++ ) document.write(arr[i]+\"<br>\"); } // Driver program to test above function generateGrayarr(3); // This code is contributed by unknown2108</script>", "e": 7793, "s": 6606, "text": null }, { "code": null, "e": 7825, "s": 7793, "text": "000\n001\n011\n010\n110\n111\n101\n100" }, { "code": null, "e": 7870, "s": 7825, "text": "Time Complexity: O(2N)Auxiliary Space: O(2N)" }, { "code": null, "e": 7899, "s": 7870, "text": "Method 2: Recursive Approach" }, { "code": null, "e": 8003, "s": 7899, "text": "The idea is to recursively append the bit 0 and 1 each time until the number of bits is not equal to N." }, { "code": null, "e": 8088, "s": 8003, "text": "Base Condition: The base case for this problem will be when the value of N = 0 or 1." }, { "code": null, "e": 8140, "s": 8088, "text": "If (N == 0)return {β€œ0”}if (N == 1)return {β€œ0”, β€œ1”}" }, { "code": null, "e": 8325, "s": 8140, "text": "Recursive Condition: Otherwise, for any value greater than 1, recursively generate the gray codes of the N – 1 bits and then for each of the gray code generated add the prefix 0 and 1." }, { "code": null, "e": 8376, "s": 8325, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 8380, "s": 8376, "text": "C++" }, { "code": null, "e": 8385, "s": 8380, "text": "Java" }, { "code": null, "e": 8393, "s": 8385, "text": "Python3" }, { "code": null, "e": 8396, "s": 8393, "text": "C#" }, { "code": null, "e": 8407, "s": 8396, "text": "Javascript" }, { "code": "// C++ program to generate// n-bit Gray codes #include <bits/stdc++.h>using namespace std; // This function generates all n// bit Gray codes and prints the// generated codesvector<string> generateGray(int n){ // Base case if (n <= 0) return {\"0\"}; if (n == 1) { return {\"0\",\"1\"}; } //Recursive case vector<string> recAns= generateGray(n-1); vector<string> mainAns; // Append 0 to the first half for(int i=0;i<recAns.size();i++) { string s=recAns[i]; mainAns.push_back(\"0\"+s); } // Append 1 to the second half for(int i=recAns.size()-1;i>=0;i--) { string s=recAns[i]; mainAns.push_back(\"1\"+s); } return mainAns;} // Function to generate the// Gray code of N bitsvoid generateGrayarr(int n){ vector<string> arr; arr=generateGray(n); // print contents of arr for (int i = 0 ; i < arr.size(); i++ ) cout << arr[i] << endl;} // Driver Codeint main(){ generateGrayarr(3); return 0;}", "e": 9424, "s": 8407, "text": null }, { "code": "// Java program to generate// n-bit Gray codesimport java.io.*;import java.util.*;class GFG{ // This function generates all n // bit Gray codes and prints the // generated codes static ArrayList<String> generateGray(int n) { // Base case if (n <= 0) { ArrayList<String> temp = new ArrayList<String>(){{add(\"0\");}}; return temp; } if(n == 1) { ArrayList<String> temp = new ArrayList<String>(){{add(\"0\");add(\"1\");}}; return temp; } // Recursive case ArrayList<String> recAns = generateGray(n - 1); ArrayList<String> mainAns = new ArrayList<String>(); // Append 0 to the first half for(int i = 0; i < recAns.size(); i++) { String s = recAns.get(i); mainAns.add(\"0\" + s); } // Append 1 to the second half for(int i = recAns.size() - 1; i >= 0; i--) { String s = recAns.get(i); mainAns.add(\"1\" + s); } return mainAns; } // Function to generate the // Gray code of N bits static void generateGrayarr(int n) { ArrayList<String> arr = new ArrayList<String>(); arr = generateGray(n); // print contents of arr for (int i = 0 ; i < arr.size(); i++) { System.out.println(arr.get(i)); } } // Driver Code public static void main (String[] args) { generateGrayarr(3); }} // This code is contributed by rag2127.", "e": 10784, "s": 9424, "text": null }, { "code": "# Python3 program to generate# n-bit Gray codes # This function generates all n# bit Gray codes and prints the# generated codesdef generateGray(n): # Base case if (n <= 0): return [\"0\"] if (n == 1): return [ \"0\", \"1\" ] # Recursive case recAns = generateGray(n - 1) mainAns = [] # Append 0 to the first half for i in range(len(recAns)): s = recAns[i] mainAns.append(\"0\" + s) # Append 1 to the second half for i in range(len(recAns) - 1, -1, -1): s = recAns[i] mainAns.append(\"1\" + s) return mainAns # Function to generate the# Gray code of N bitsdef generateGrayarr(n): arr = generateGray(n) # Print contents of arr print(*arr, sep = \"\\n\") # Driver CodegenerateGrayarr(3) # This code is contributed by avanitrachhadiya2155", "e": 11610, "s": 10784, "text": null }, { "code": "// Java program to generate// n-bit Gray codesusing System;using System.Collections.Generic;class GFG { // This function generates all n // bit Gray codes and prints the // generated codes static List<String> generateGray(int n) { // Base case if (n <= 0) { List<String> temp = new List<String>(); temp.Add(\"0\"); return temp; } if (n == 1) { List<String> temp = new List<String>(); temp.Add(\"0\"); temp.Add(\"1\"); return temp; } // Recursive case List<String> recAns = generateGray(n - 1); List<String> mainAns = new List<String>(); // Append 0 to the first half for (int i = 0; i < recAns.Count; i++) { String s = recAns[i]; mainAns.Add(\"0\" + s); } // Append 1 to the second half for (int i = recAns.Count - 1; i >= 0; i--) { String s = recAns[i]; mainAns.Add(\"1\" + s); } return mainAns; } // Function to generate the // Gray code of N bits static void generateGrayarr(int n) { List<String> arr = new List<String>(); arr = generateGray(n); // print contents of arr for (int i = 0; i < arr.Count; i++) { Console.WriteLine(arr[i]); } } // Driver Code public static void Main(String[] args) { generateGrayarr(3); }} // This code is contributed by grand_master.", "e": 12916, "s": 11610, "text": null }, { "code": "<script>// Javascript program to generate// n-bit Gray codes // This function generates all n // bit Gray codes and prints the // generated codesfunction generateGray(n){ // Base case if (n <= 0) { let temp =[\"0\"]; return temp; } if(n == 1) { let temp =[\"0\",\"1\"]; return temp; } // Recursive case let recAns = generateGray(n - 1); let mainAns = []; // Append 0 to the first half for(let i = 0; i < recAns.length; i++) { let s = recAns[i]; mainAns.push(\"0\" + s); } // Append 1 to the second half for(let i = recAns.length - 1; i >= 0; i--) { let s = recAns[i]; mainAns.push(\"1\" + s); } return mainAns;} // Function to generate the // Gray code of N bitsfunction generateGrayarr(n){ let arr = []; arr = generateGray(n); // print contents of arr for (let i = 0 ; i < arr.length; i++) { document.write(arr[i]+\"<br>\"); }} // Driver CodegenerateGrayarr(3); // This code is contributed by ab2127</script>", "e": 13958, "s": 12916, "text": null }, { "code": null, "e": 13990, "s": 13958, "text": "000\n001\n011\n010\n110\n111\n101\n100" }, { "code": null, "e": 14035, "s": 13990, "text": "Time Complexity: O(2N)Auxiliary Space: O(2N)" }, { "code": null, "e": 14059, "s": 14035, "text": "Method3: (Using bitset)" }, { "code": null, "e": 14188, "s": 14059, "text": "We should first find binary no from 1 to n and then convert it into string and then print it using substring function of string." }, { "code": null, "e": 14235, "s": 14188, "text": "Below is the implementation of the above idea:" }, { "code": null, "e": 14239, "s": 14235, "text": "C++" }, { "code": null, "e": 14244, "s": 14239, "text": "Java" }, { "code": null, "e": 14252, "s": 14244, "text": "Python3" }, { "code": null, "e": 14263, "s": 14252, "text": "Javascript" }, { "code": null, "e": 14266, "s": 14263, "text": "C#" }, { "code": "// C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; void GreyCode(int n){ // power of 2 for (int i = 0; i < (1 << n); i++) { // Generating the decimal // values of gray code then using // bitset to convert them to binary form int val = (i ^ (i >> 1)); // Using bitset bitset<32> r(val); // Converting to string string s = r.to_string(); cout << s.substr(32 - n) << \" \"; }} // Driver Codeint main(){ int n; n = 4; // Function call GreyCode(n); return 0;}", "e": 14873, "s": 14266, "text": null }, { "code": "// Java implementation of the above approachimport java.lang.Math; class GFG { static void GreyCode(int n) { // power of 2 for (int i = 0; i < (1 << n); i++) { // Generating the decimal // values of gray code then using // bitset to convert them to binary form int val = (i ^ (i >> 1)); // Converting to binary string String s = Integer.toBinaryString(val); System.out.print( String.format(\"%1$\" + 4 + \"s\", s) .replace(' ', '0') + \" \"); } } // Driver Code public static void main(String[] args) { int n = 4; // Function call GreyCode(n); }} // This code is contributed by phasing17", "e": 15545, "s": 14873, "text": null }, { "code": "# Python3 implementation of the above approachdef GreyCode(n): # power of 2 for i in range(1 << n): # Generating the decimal # values of gray code then using # bitset to convert them to binary form val = (i ^ (i >> 1)) # Converting to binary string s = bin(val)[2::] print(s.zfill(4), end = \" \") # Driver Coden = 4 # Function callGreyCode(n) # This code is contributed by phasing17", "e": 16001, "s": 15545, "text": null }, { "code": "// JavaScript implementation of the above approachfunction GreyCode(n){ // power of 2 for (var i = 0; i < (1 << n); i++) { // Generating the decimal // values of gray code then using // bitset to convert them to binary form var val = (i ^ (i >> 1)); // Converting to binary string s = val.toString(2); process.stdout.write(s.padStart(4, '0') + \" \"); }} // Driver Codelet n = 4; // Function callGreyCode(n); // This code is contributed by phasing17", "e": 16522, "s": 16001, "text": null }, { "code": "// C# implementation of the above approach using System; class GFG { static void GreyCode(int n) { // power of 2 for (int i = 0; i < (1 << n); i++) { // Generating the decimal // values of gray code then using // bitset to convert them to binary form int val = (i ^ (i >> 1)); // Converting to binary string string s = Convert.ToString(val, 2); Console.Write(s.PadLeft(4, '0') + \" \"); } } // Driver Code public static void Main(string[] args) { int n = 4; // Function call GreyCode(n); }} // This code is contributed by phasing17", "e": 17197, "s": 16522, "text": null }, { "code": null, "e": 17278, "s": 17197, "text": "0000 0001 0011 0010 0110 0111 0101 0100 1100 1101 1111 1110 1010 1011 1001 1000 " }, { "code": null, "e": 17322, "s": 17278, "text": "Time Complexity: O(2N)Auxiliary Space: O(N)" }, { "code": null, "e": 17335, "s": 17322, "text": "prerna saini" }, { "code": null, "e": 17347, "s": 17335, "text": "shrikanth13" }, { "code": null, "e": 17362, "s": 17347, "text": "mohit kumar 29" }, { "code": null, "e": 17370, "s": 17362, "text": "aryan_a" }, { "code": null, "e": 17383, "s": 17370, "text": "biturobin187" }, { "code": null, "e": 17404, "s": 17383, "text": "avanitrachhadiya2155" }, { "code": null, "e": 17417, "s": 17404, "text": "gouravrj9654" }, { "code": null, "e": 17425, "s": 17417, "text": "rag2127" }, { "code": null, "e": 17438, "s": 17425, "text": "grand_master" }, { "code": null, "e": 17450, "s": 17438, "text": "unknown2108" }, { "code": null, "e": 17457, "s": 17450, "text": "ab2127" }, { "code": null, "e": 17470, "s": 17457, "text": "simmytarika5" }, { "code": null, "e": 17487, "s": 17470, "text": "surinderdawra388" }, { "code": null, "e": 17497, "s": 17487, "text": "phasing17" }, { "code": null, "e": 17514, "s": 17497, "text": "hardikkoriintern" }, { "code": null, "e": 17521, "s": 17514, "text": "Amazon" }, { "code": null, "e": 17531, "s": 17521, "text": "gray-code" }, { "code": null, "e": 17541, "s": 17531, "text": "Microsoft" }, { "code": null, "e": 17551, "s": 17541, "text": "Bit Magic" }, { "code": null, "e": 17559, "s": 17551, "text": "Strings" }, { "code": null, "e": 17566, "s": 17559, "text": "Amazon" }, { "code": null, "e": 17576, "s": 17566, "text": "Microsoft" }, { "code": null, "e": 17584, "s": 17576, "text": "Strings" }, { "code": null, "e": 17594, "s": 17584, "text": "Bit Magic" }, { "code": null, "e": 17692, "s": 17594, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 17719, "s": 17692, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 17765, "s": 17719, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 17833, "s": 17765, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 17862, "s": 17833, "text": "Count set bits in an integer" }, { "code": null, "e": 17922, "s": 17862, "text": "How to swap two numbers without using a temporary variable?" }, { "code": null, "e": 17968, "s": 17922, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 17993, "s": 17968, "text": "Reverse a string in Java" }, { "code": null, "e": 18053, "s": 17993, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 18068, "s": 18053, "text": "C++ Data Types" } ]
Difference between Method and Function in Python
06 Jul, 2022 Here, key differences between Method and Function in Python are explained. Java is also an OOP language, but there is no concept of Function in it. But Python has both concept of Method and Function. Python Method Method is called by its name, but it is associated to an object (dependent).A method definition always includes β€˜self’ as its first parameter.A method is implicitly passed the object on which it is invoked.It may or may not return any data.A method can operate on the data (instance variables) that is contained by the corresponding class Method is called by its name, but it is associated to an object (dependent). A method definition always includes β€˜self’ as its first parameter. A method is implicitly passed the object on which it is invoked. It may or may not return any data. A method can operate on the data (instance variables) that is contained by the corresponding class Basic Method Structure in Python : Python # Basic Python methodclass class_name def method_name () : ...... # method body ...... Python 3 User-Defined Method : Python3 # Python 3 User-Defined Methodclass ABC : def method_abc (self): print("I am in method_abc of ABC class. ") class_ref = ABC() # object of ABC classclass_ref.method_abc() Output: I am in method_abc of ABC class Python 3 Inbuilt method : Python3 import math ceil_val = math.ceil(15.25)print( "Ceiling value of 15.25 is : ", ceil_val) Output: Ceiling value of 15.25 is : 16 Know more about Python ceil() and floor() method. Functions Function is block of code that is also called by its name. (independent)The function can have different parameters or may not have any at all. If any data (parameters) are passed, they are passed explicitly.It may or may not return any data.Function does not deal with Class and its instance concept. Function is block of code that is also called by its name. (independent) The function can have different parameters or may not have any at all. If any data (parameters) are passed, they are passed explicitly. It may or may not return any data. Function does not deal with Class and its instance concept. Basic Function Structure in Python : Python3 def function_name ( arg1, arg2, ...) : ...... # function body ...... Python 3 User-Defined Function : Python3 def Subtract (a, b): return (a-b) print( Subtract(10, 12) ) # prints -2 print( Subtract(15, 6) ) # prints 9 Output: -2 9 Python 3 Inbuilt Function : Python3 s = sum([5, 15, 2])print( s ) # prints 22 mx = max(15, 6)print( mx ) # prints 15 Output: 22 15 Know more about Python sum() function. Know more about Python min() or max() function. Difference between method and function Simply, function and method both look similar as they perform in almost similar way, but the key difference is the concept of β€˜Class and its Objectβ€˜.Functions can be called only by its name, as it is defined independently. But methods can’t be called by its name only, we need to invoke the class by a reference of that class in which it is defined, i.e. method is defined within a class and hence they are dependent on that class. Simply, function and method both look similar as they perform in almost similar way, but the key difference is the concept of β€˜Class and its Objectβ€˜. Functions can be called only by its name, as it is defined independently. But methods can’t be called by its name only, we need to invoke the class by a reference of that class in which it is defined, i.e. method is defined within a class and hence they are dependent on that class. getsrikar mitalibhola94 Python-Functions Difference Between Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Difference Between Method Overloading and Method Overriding in Java Differences between JDK, JRE and JVM Stack vs Heap Memory Allocation Difference between Process and Thread Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function Python Dictionary How to get column names in Pandas dataframe
[ { "code": null, "e": 52, "s": 24, "text": "\n06 Jul, 2022" }, { "code": null, "e": 252, "s": 52, "text": "Here, key differences between Method and Function in Python are explained. Java is also an OOP language, but there is no concept of Function in it. But Python has both concept of Method and Function." }, { "code": null, "e": 266, "s": 252, "text": "Python Method" }, { "code": null, "e": 605, "s": 266, "text": "Method is called by its name, but it is associated to an object (dependent).A method definition always includes β€˜self’ as its first parameter.A method is implicitly passed the object on which it is invoked.It may or may not return any data.A method can operate on the data (instance variables) that is contained by the corresponding class" }, { "code": null, "e": 682, "s": 605, "text": "Method is called by its name, but it is associated to an object (dependent)." }, { "code": null, "e": 749, "s": 682, "text": "A method definition always includes β€˜self’ as its first parameter." }, { "code": null, "e": 814, "s": 749, "text": "A method is implicitly passed the object on which it is invoked." }, { "code": null, "e": 849, "s": 814, "text": "It may or may not return any data." }, { "code": null, "e": 948, "s": 849, "text": "A method can operate on the data (instance variables) that is contained by the corresponding class" }, { "code": null, "e": 984, "s": 948, "text": "Basic Method Structure in Python : " }, { "code": null, "e": 991, "s": 984, "text": "Python" }, { "code": "# Basic Python methodclass class_name def method_name () : ...... # method body ...... ", "e": 1104, "s": 991, "text": null }, { "code": null, "e": 1136, "s": 1104, "text": "Python 3 User-Defined Method : " }, { "code": null, "e": 1144, "s": 1136, "text": "Python3" }, { "code": "# Python 3 User-Defined Methodclass ABC : def method_abc (self): print(\"I am in method_abc of ABC class. \") class_ref = ABC() # object of ABC classclass_ref.method_abc()", "e": 1326, "s": 1144, "text": null }, { "code": null, "e": 1334, "s": 1326, "text": "Output:" }, { "code": null, "e": 1367, "s": 1334, "text": " I am in method_abc of ABC class" }, { "code": null, "e": 1394, "s": 1367, "text": "Python 3 Inbuilt method : " }, { "code": null, "e": 1402, "s": 1394, "text": "Python3" }, { "code": "import math ceil_val = math.ceil(15.25)print( \"Ceiling value of 15.25 is : \", ceil_val)", "e": 1490, "s": 1402, "text": null }, { "code": null, "e": 1498, "s": 1490, "text": "Output:" }, { "code": null, "e": 1530, "s": 1498, "text": "Ceiling value of 15.25 is : 16" }, { "code": null, "e": 1580, "s": 1530, "text": "Know more about Python ceil() and floor() method." }, { "code": null, "e": 1590, "s": 1580, "text": "Functions" }, { "code": null, "e": 1891, "s": 1590, "text": "Function is block of code that is also called by its name. (independent)The function can have different parameters or may not have any at all. If any data (parameters) are passed, they are passed explicitly.It may or may not return any data.Function does not deal with Class and its instance concept." }, { "code": null, "e": 1964, "s": 1891, "text": "Function is block of code that is also called by its name. (independent)" }, { "code": null, "e": 2100, "s": 1964, "text": "The function can have different parameters or may not have any at all. If any data (parameters) are passed, they are passed explicitly." }, { "code": null, "e": 2135, "s": 2100, "text": "It may or may not return any data." }, { "code": null, "e": 2195, "s": 2135, "text": "Function does not deal with Class and its instance concept." }, { "code": null, "e": 2233, "s": 2195, "text": "Basic Function Structure in Python : " }, { "code": null, "e": 2241, "s": 2233, "text": "Python3" }, { "code": "def function_name ( arg1, arg2, ...) : ...... # function body ...... ", "e": 2321, "s": 2241, "text": null }, { "code": null, "e": 2355, "s": 2321, "text": "Python 3 User-Defined Function : " }, { "code": null, "e": 2363, "s": 2355, "text": "Python3" }, { "code": "def Subtract (a, b): return (a-b) print( Subtract(10, 12) ) # prints -2 print( Subtract(15, 6) ) # prints 9", "e": 2474, "s": 2363, "text": null }, { "code": null, "e": 2482, "s": 2474, "text": "Output:" }, { "code": null, "e": 2487, "s": 2482, "text": "-2\n9" }, { "code": null, "e": 2516, "s": 2487, "text": "Python 3 Inbuilt Function : " }, { "code": null, "e": 2524, "s": 2516, "text": "Python3" }, { "code": "s = sum([5, 15, 2])print( s ) # prints 22 mx = max(15, 6)print( mx ) # prints 15", "e": 2605, "s": 2524, "text": null }, { "code": null, "e": 2613, "s": 2605, "text": "Output:" }, { "code": null, "e": 2619, "s": 2613, "text": "22\n15" }, { "code": null, "e": 2706, "s": 2619, "text": "Know more about Python sum() function. Know more about Python min() or max() function." }, { "code": null, "e": 2745, "s": 2706, "text": "Difference between method and function" }, { "code": null, "e": 3177, "s": 2745, "text": "Simply, function and method both look similar as they perform in almost similar way, but the key difference is the concept of β€˜Class and its Objectβ€˜.Functions can be called only by its name, as it is defined independently. But methods can’t be called by its name only, we need to invoke the class by a reference of that class in which it is defined, i.e. method is defined within a class and hence they are dependent on that class." }, { "code": null, "e": 3327, "s": 3177, "text": "Simply, function and method both look similar as they perform in almost similar way, but the key difference is the concept of β€˜Class and its Objectβ€˜." }, { "code": null, "e": 3610, "s": 3327, "text": "Functions can be called only by its name, as it is defined independently. But methods can’t be called by its name only, we need to invoke the class by a reference of that class in which it is defined, i.e. method is defined within a class and hence they are dependent on that class." }, { "code": null, "e": 3620, "s": 3610, "text": "getsrikar" }, { "code": null, "e": 3634, "s": 3620, "text": "mitalibhola94" }, { "code": null, "e": 3651, "s": 3634, "text": "Python-Functions" }, { "code": null, "e": 3670, "s": 3651, "text": "Difference Between" }, { "code": null, "e": 3677, "s": 3670, "text": "Python" }, { "code": null, "e": 3696, "s": 3677, "text": "Technical Scripter" }, { "code": null, "e": 3794, "s": 3696, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3855, "s": 3794, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3923, "s": 3855, "text": "Difference Between Method Overloading and Method Overriding in Java" }, { "code": null, "e": 3960, "s": 3923, "text": "Differences between JDK, JRE and JVM" }, { "code": null, "e": 3992, "s": 3960, "text": "Stack vs Heap Memory Allocation" }, { "code": null, "e": 4030, "s": 3992, "text": "Difference between Process and Thread" }, { "code": null, "e": 4058, "s": 4030, "text": "Read JSON file using Python" }, { "code": null, "e": 4108, "s": 4058, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 4130, "s": 4108, "text": "Python map() function" }, { "code": null, "e": 4148, "s": 4130, "text": "Python Dictionary" } ]
Humanize Package in Python
23 May, 2020 Humanize is a package in python which contains various humanization utilities like turning a number into a human-readable size or throughput or number. In this article, we will discuss how to install this package and what are the different utilities present in this package. Installation: To install this package, we will use pip a command. Python pip is the package manager for Python packages. pip comes pre-installed on 3.4 or older versions of Python, pip commands are used in the command prompt. The following command is used to install the package: pip install humanize Usage: This package offers various utilities which can be used on the numbers to make the numbers easily readable for the humans. The utilities of the package are: File Size Utility: This utility can convert large integers of file sizes to human-readable form. The default unit of the size it accepts is bytes. For example:# Program to demonstrate the# File Size Utilityimport humanize size = humanize.naturalsize(1024000)Output:1.0 MB Scientific Notation: This utility is used to add scientific notation to the program. This utility also gives an option to add precision to the number. Precision here means the number of digits needed in the number. For example:# Program to demonstrate the# scientific notation utilityimport humanize # Scientific notation using # integer without precisiongfg = humanize.scientific(2000)print('Without Precision: '+gfg) # Scientific notation using # integer with precisiongfg = humanize.scientific(2**10, precision = 5)print('With Precision: '+gfg)Output:Without Precision: 2.00 x 103 With Precision: 1.02400 x 103 Floating Point to Fractions: This utility is used to convert a floating-point to fractions. For example:# Program to demonstrate the# floating point to fraction # utilityimport humanize gfg = humanize.fractional(0.5269)print(gfg)Output:333/632 Date & Time Utility: Many a times, we encounter few scenarios where the date or time is returned in the form of numbers. This utility is used to convert the date into a human understandable format. For example:# Program to demonstrate the# date time utilityimport humanizeimport datetime as dt # Converting the date represented# as a numbergfg = humanize.naturaldate(dt.date(2020, 5, 3))print(gfg) # Converting seconds to a # better representationgfg = humanize.naturaldelta(dt.timedelta(seconds = 900))print(gfg)Output:May 03 2020 15 minutes Integer Utility: This utility is used to make integer values more presentable. For Example:# Python program to demonstrate # the integer utilityimport humanize # Adding commas to integer valuesgfg = humanize.intcomma(14523689)print(gfg) # Converts the integer to # long and short scalesgfg = humanize.intword(1562345640)print(gfg) # Converts numbers (0-9) to their # english formatgfg = humanize.apnumber(5)print(gfg)Output:14, 523, 689 1.6 billion five File Size Utility: This utility can convert large integers of file sizes to human-readable form. The default unit of the size it accepts is bytes. For example:# Program to demonstrate the# File Size Utilityimport humanize size = humanize.naturalsize(1024000)Output:1.0 MB # Program to demonstrate the# File Size Utilityimport humanize size = humanize.naturalsize(1024000) Output: 1.0 MB Scientific Notation: This utility is used to add scientific notation to the program. This utility also gives an option to add precision to the number. Precision here means the number of digits needed in the number. For example:# Program to demonstrate the# scientific notation utilityimport humanize # Scientific notation using # integer without precisiongfg = humanize.scientific(2000)print('Without Precision: '+gfg) # Scientific notation using # integer with precisiongfg = humanize.scientific(2**10, precision = 5)print('With Precision: '+gfg)Output:Without Precision: 2.00 x 103 With Precision: 1.02400 x 103 # Program to demonstrate the# scientific notation utilityimport humanize # Scientific notation using # integer without precisiongfg = humanize.scientific(2000)print('Without Precision: '+gfg) # Scientific notation using # integer with precisiongfg = humanize.scientific(2**10, precision = 5)print('With Precision: '+gfg) Output: Without Precision: 2.00 x 103 With Precision: 1.02400 x 103 Floating Point to Fractions: This utility is used to convert a floating-point to fractions. For example:# Program to demonstrate the# floating point to fraction # utilityimport humanize gfg = humanize.fractional(0.5269)print(gfg)Output:333/632 # Program to demonstrate the# floating point to fraction # utilityimport humanize gfg = humanize.fractional(0.5269)print(gfg) Output: 333/632 Date & Time Utility: Many a times, we encounter few scenarios where the date or time is returned in the form of numbers. This utility is used to convert the date into a human understandable format. For example:# Program to demonstrate the# date time utilityimport humanizeimport datetime as dt # Converting the date represented# as a numbergfg = humanize.naturaldate(dt.date(2020, 5, 3))print(gfg) # Converting seconds to a # better representationgfg = humanize.naturaldelta(dt.timedelta(seconds = 900))print(gfg)Output:May 03 2020 15 minutes # Program to demonstrate the# date time utilityimport humanizeimport datetime as dt # Converting the date represented# as a numbergfg = humanize.naturaldate(dt.date(2020, 5, 3))print(gfg) # Converting seconds to a # better representationgfg = humanize.naturaldelta(dt.timedelta(seconds = 900))print(gfg) Output: May 03 2020 15 minutes Integer Utility: This utility is used to make integer values more presentable. For Example:# Python program to demonstrate # the integer utilityimport humanize # Adding commas to integer valuesgfg = humanize.intcomma(14523689)print(gfg) # Converts the integer to # long and short scalesgfg = humanize.intword(1562345640)print(gfg) # Converts numbers (0-9) to their # english formatgfg = humanize.apnumber(5)print(gfg)Output:14, 523, 689 1.6 billion five # Python program to demonstrate # the integer utilityimport humanize # Adding commas to integer valuesgfg = humanize.intcomma(14523689)print(gfg) # Converts the integer to # long and short scalesgfg = humanize.intword(1562345640)print(gfg) # Converts numbers (0-9) to their # english formatgfg = humanize.apnumber(5)print(gfg) Output: 14, 523, 689 1.6 billion five References: https://pypi.org/project/humanize/ python-modules Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n23 May, 2020" }, { "code": null, "e": 329, "s": 54, "text": "Humanize is a package in python which contains various humanization utilities like turning a number into a human-readable size or throughput or number. In this article, we will discuss how to install this package and what are the different utilities present in this package." }, { "code": null, "e": 609, "s": 329, "text": "Installation: To install this package, we will use pip a command. Python pip is the package manager for Python packages. pip comes pre-installed on 3.4 or older versions of Python, pip commands are used in the command prompt. The following command is used to install the package:" }, { "code": null, "e": 630, "s": 609, "text": "pip install humanize" }, { "code": null, "e": 794, "s": 630, "text": "Usage: This package offers various utilities which can be used on the numbers to make the numbers easily readable for the humans. The utilities of the package are:" }, { "code": null, "e": 2931, "s": 794, "text": "File Size Utility: This utility can convert large integers of file sizes to human-readable form. The default unit of the size it accepts is bytes. For example:# Program to demonstrate the# File Size Utilityimport humanize size = humanize.naturalsize(1024000)Output:1.0 MB\nScientific Notation: This utility is used to add scientific notation to the program. This utility also gives an option to add precision to the number. Precision here means the number of digits needed in the number. For example:# Program to demonstrate the# scientific notation utilityimport humanize # Scientific notation using # integer without precisiongfg = humanize.scientific(2000)print('Without Precision: '+gfg) # Scientific notation using # integer with precisiongfg = humanize.scientific(2**10, precision = 5)print('With Precision: '+gfg)Output:Without Precision: 2.00 x 103\nWith Precision: 1.02400 x 103\nFloating Point to Fractions: This utility is used to convert a floating-point to fractions. For example:# Program to demonstrate the# floating point to fraction # utilityimport humanize gfg = humanize.fractional(0.5269)print(gfg)Output:333/632\nDate & Time Utility: Many a times, we encounter few scenarios where the date or time is returned in the form of numbers. This utility is used to convert the date into a human understandable format. For example:# Program to demonstrate the# date time utilityimport humanizeimport datetime as dt # Converting the date represented# as a numbergfg = humanize.naturaldate(dt.date(2020, 5, 3))print(gfg) # Converting seconds to a # better representationgfg = humanize.naturaldelta(dt.timedelta(seconds = 900))print(gfg)Output:May 03 2020\n15 minutes\nInteger Utility: This utility is used to make integer values more presentable. For Example:# Python program to demonstrate # the integer utilityimport humanize # Adding commas to integer valuesgfg = humanize.intcomma(14523689)print(gfg) # Converts the integer to # long and short scalesgfg = humanize.intword(1562345640)print(gfg) # Converts numbers (0-9) to their # english formatgfg = humanize.apnumber(5)print(gfg)Output:14, 523, 689\n1.6 billion\nfive\n" }, { "code": null, "e": 3205, "s": 2931, "text": "File Size Utility: This utility can convert large integers of file sizes to human-readable form. The default unit of the size it accepts is bytes. For example:# Program to demonstrate the# File Size Utilityimport humanize size = humanize.naturalsize(1024000)Output:1.0 MB\n" }, { "code": "# Program to demonstrate the# File Size Utilityimport humanize size = humanize.naturalsize(1024000)", "e": 3306, "s": 3205, "text": null }, { "code": null, "e": 3314, "s": 3306, "text": "Output:" }, { "code": null, "e": 3322, "s": 3314, "text": "1.0 MB\n" }, { "code": null, "e": 3939, "s": 3322, "text": "Scientific Notation: This utility is used to add scientific notation to the program. This utility also gives an option to add precision to the number. Precision here means the number of digits needed in the number. For example:# Program to demonstrate the# scientific notation utilityimport humanize # Scientific notation using # integer without precisiongfg = humanize.scientific(2000)print('Without Precision: '+gfg) # Scientific notation using # integer with precisiongfg = humanize.scientific(2**10, precision = 5)print('With Precision: '+gfg)Output:Without Precision: 2.00 x 103\nWith Precision: 1.02400 x 103\n" }, { "code": "# Program to demonstrate the# scientific notation utilityimport humanize # Scientific notation using # integer without precisiongfg = humanize.scientific(2000)print('Without Precision: '+gfg) # Scientific notation using # integer with precisiongfg = humanize.scientific(2**10, precision = 5)print('With Precision: '+gfg)", "e": 4262, "s": 3939, "text": null }, { "code": null, "e": 4270, "s": 4262, "text": "Output:" }, { "code": null, "e": 4331, "s": 4270, "text": "Without Precision: 2.00 x 103\nWith Precision: 1.02400 x 103\n" }, { "code": null, "e": 4577, "s": 4331, "text": "Floating Point to Fractions: This utility is used to convert a floating-point to fractions. For example:# Program to demonstrate the# floating point to fraction # utilityimport humanize gfg = humanize.fractional(0.5269)print(gfg)Output:333/632\n" }, { "code": "# Program to demonstrate the# floating point to fraction # utilityimport humanize gfg = humanize.fractional(0.5269)print(gfg)", "e": 4704, "s": 4577, "text": null }, { "code": null, "e": 4712, "s": 4704, "text": "Output:" }, { "code": null, "e": 4721, "s": 4712, "text": "333/632\n" }, { "code": null, "e": 5267, "s": 4721, "text": "Date & Time Utility: Many a times, we encounter few scenarios where the date or time is returned in the form of numbers. This utility is used to convert the date into a human understandable format. For example:# Program to demonstrate the# date time utilityimport humanizeimport datetime as dt # Converting the date represented# as a numbergfg = humanize.naturaldate(dt.date(2020, 5, 3))print(gfg) # Converting seconds to a # better representationgfg = humanize.naturaldelta(dt.timedelta(seconds = 900))print(gfg)Output:May 03 2020\n15 minutes\n" }, { "code": "# Program to demonstrate the# date time utilityimport humanizeimport datetime as dt # Converting the date represented# as a numbergfg = humanize.naturaldate(dt.date(2020, 5, 3))print(gfg) # Converting seconds to a # better representationgfg = humanize.naturaldelta(dt.timedelta(seconds = 900))print(gfg)", "e": 5573, "s": 5267, "text": null }, { "code": null, "e": 5581, "s": 5573, "text": "Output:" }, { "code": null, "e": 5605, "s": 5581, "text": "May 03 2020\n15 minutes\n" }, { "code": null, "e": 6063, "s": 5605, "text": "Integer Utility: This utility is used to make integer values more presentable. For Example:# Python program to demonstrate # the integer utilityimport humanize # Adding commas to integer valuesgfg = humanize.intcomma(14523689)print(gfg) # Converts the integer to # long and short scalesgfg = humanize.intword(1562345640)print(gfg) # Converts numbers (0-9) to their # english formatgfg = humanize.apnumber(5)print(gfg)Output:14, 523, 689\n1.6 billion\nfive\n" }, { "code": "# Python program to demonstrate # the integer utilityimport humanize # Adding commas to integer valuesgfg = humanize.intcomma(14523689)print(gfg) # Converts the integer to # long and short scalesgfg = humanize.intword(1562345640)print(gfg) # Converts numbers (0-9) to their # english formatgfg = humanize.apnumber(5)print(gfg)", "e": 6393, "s": 6063, "text": null }, { "code": null, "e": 6401, "s": 6393, "text": "Output:" }, { "code": null, "e": 6432, "s": 6401, "text": "14, 523, 689\n1.6 billion\nfive\n" }, { "code": null, "e": 6479, "s": 6432, "text": "References: https://pypi.org/project/humanize/" }, { "code": null, "e": 6494, "s": 6479, "text": "python-modules" }, { "code": null, "e": 6501, "s": 6494, "text": "Python" } ]
Program for finding the Integral of a given function using Boole’s Rule
19 May, 2021 Given a function, f(x), tabulated at points equally spaced by such that [Tex]f_2=f(x_2)[/Tex] .....and so on The upper and lower limits a, b correspond to which the integral needs to be found, the task is to find the integral value of the given equation f(x).Examples: Input: a = 0, b = 4, Output: 1.6178 Explanation: Integral of (1 / (1 + x)) is 4ln(|1 + x|)0 + c. On substituting the limits, ln(|5|) + ln(|1|) = 1.6178.Input: a = 0.2, b = 0.6, Output: 0.3430 Approach: In this article, Boole’s rule is discussed to compute the approximate integral value of the given function f(x). Boole’s rule is a numerical integration technique to find the approximate value of the integral. It is named after a largely self-taught mathematician, philosopher, and logician George Boole. The idea of the Boole’s technique is to approximate the integral using the values of β€˜fkβ€˜ at some equally spaced values(h in the given image). The following illustration shows how various fk’s are considered: The integral value of Boole’s rule is given by the formula: In the above formula, an error term which comes when integration is of order 6. The error term is [Tex]f_1, f_2, f_3, f_4, f_5, [/Tex] Are the values of f(x) at their respective intervals of x. Therefore, the following steps can be followed to compute the integral of some function f(x) in the interval (a, b): The value of n=6, which is the number of parts the interval is divided into.Calculate the width, h = (b – a)/4.Calculate the values of x1 to x5 as The value of n=6, which is the number of parts the interval is divided into.Calculate the width, h = (b – a)/4.Calculate the values of x1 to x5 as The value of n=6, which is the number of parts the interval is divided into. Calculate the width, h = (b – a)/4. Calculate the values of x1 to x5 as Consider y = f(x). Now find the values for the corresponding values. Substitute all the values in Boole’s rule to calculate the integral value. Below is the implementation of the above approach: C++ C Java Python3 C# Javascript // C++ program to implement Boole's Rule// on the given function#include <bits/stdc++.h>using namespace std; // In order to represent the implementation,// a function f(x) = 1/(1 + x) is considered// in this program // Function to return the value of f(x)// for the given value of xfloat y(float x){ return (1 / (1 + x));} // Function to computes the integrand of y// at the given intervals of x with// step size h and the initial limit a// and final limit bfloat BooleRule(float a, float b){ // Number of intervals int n = 4; int h; // Computing the step size h = ((b - a) / n); float sum = 0; // Substituing a = 0, b = 4 and h = 1 float bl = ((7 * y(a) + 32 * y(a + h) + 12 * y(a + 2 * h) + 32 * y(a + 3 * h) + 7 * y(a + 4 * h)) * 2 * h / 45); sum = sum + bl; return sum;} // Driver codeint main(){ float lowlimit = 0; float upplimit = 4; cout << fixed << setprecision(4) << "f(x) = " << BooleRule(0, 4); return 0;} // This code is contributed by shivanisinghss2110 // C program to implement Boole's Rule// on the given function #include <math.h>#include <stdio.h> // In order to represent the implementation,// a function f(x) = 1/(1 + x) is considered// in this program // Function to return the value of f(x)// for the given value of xfloat y(float x){ return (1 / (1 + x));} // Function to computes the integrand of y// at the given intervals of x with// step size h and the initial limit a// and final limit bfloat BooleRule(float a, float b){ // Number of intervals int n = 4; int h; // Computing the step size h = ((b - a) / n); float sum = 0; // Substituing a = 0, b = 4 and h = 1 float bl = (7 * y(a) + 32 * y(a + h) + 12 * y(a + 2 * h) + 32 * y(a + 3 * h) + 7 * y(a + 4 * h)) * 2 * h / 45; sum = sum + bl; return sum;} // Driver codeint main(){ float lowlimit = 0; float upplimit = 4; printf("f(x) = %.4f", BooleRule(0, 4)); return 0;} // Java program to implement Boole's Rule// on the given functionclass GFG{ // In order to represent the implementation,// a function f(x) = 1/(1 + x) is considered// in this program // Function to return the value of f(x)// for the given value of xstatic float y(float x){ return (1 / (1 + x));} // Function to computes the integrand of y// at the given intervals of x with// step size h and the initial limit a// and final limit bstatic float BooleRule(float a, float b){ // Number of intervals int n = 4; int h; // Computing the step size h = (int) ((b - a) / n); float sum = 0; // Substituing a = 0, b = 4 and h = 1 float bl = (7 * y(a) + 32 * y(a + h) + 12 * y(a + 2 * h) + 32 * y(a + 3 * h) + 7 * y(a + 4 * h)) * 2 * h / 45; sum = sum + bl; return sum;} // Driver codepublic static void main(String[] args){ System.out.printf(("f(x) = %.4f"), BooleRule(0, 4));}} // This code is contributed by 29AjayKumar # Python3 program to implement Boole's Rule# on the given function # In order to represent the implementation,# a function f(x) = 1/(1 + x) is considered# in this program # Function to return the value of f(x)# for the given value of xdef y(x): return (1 / (1 + x)) # Function to computes the integrand of y# at the given intervals of x with# step size h and the initial limit a# and final limit bdef BooleRule(a, b): # Number of intervals n = 4 # Computing the step size h = ((b - a) / n) sum = 0 # Substituing a = 0, b = 4 and h = 1 bl = (7 * y(a) + 32 * y(a + h) + 12 * y(a + 2 * h)+32 * y(a + 3 * h)+7 * y(a + 4 * h))* 2 * h / 45 sum = sum + bl return sum # Driver codeif __name__ == '__main__': lowlimit = 0 upplimit = 4 print("f(x) =",round(BooleRule(0, 4),4)) # This code is contributed by Surendra_Gangwar // C# program to implement Boole's// Rule on the given functionusing System;class GFG{ // In order to represent the// implementation, a function// f(x) = 1/(1 + x) is considered// in this program // Function to return the value of// f(x) for the given value of xstatic float y(float x){ return (1 / (1 + x));} // Function to computes the integrand// of y at the given intervals of x// with step size h and the initial// limit a and final limit bstatic float BooleRule(float a, float b){ // Number of intervals int n = 4; int h; // Computing the step size h = (int)((b - a) / n); float sum = 0; // Substituing a = 0, b = 4 // and h = 1 float bl = (7 * y(a) + 32 * y(a + h) + 12 * y(a + 2 * h) + 32 * y(a + 3 * h) + 7 * y(a + 4 * h)) * 2 * h / 45; sum = sum + bl; return sum;} // Driver codepublic static void Main(string[] args){ Console.Write(("f(x) = " + System.Math.Round( BooleRule(0, 4), 4)));}} // This code is contributed by Chitranayal <script> // JavaScript program to implement Boole's Rule// on the given function // In order to represent the implementation,// a function f(x) = 1/(1 + x) is considered// in this program // Function to return the value of f(x)// for the given value of xfunction y(x){ return (1 / (1 + x));} // Function to computes the integrand of y// at the given intervals of x with// step size h and the initial limit a// and final limit bfunction BooleRule(a, b){ // Number of intervals let n = 4; let h; // Computing the step size h = ((b - a) / n); let sum = 0; // Substituing a = 0, b = 4 and h = 1 let bl = (7 * y(a) + 32 * y(a + h) + 12 * y(a + 2 * h) + 32 * y(a + 3 * h) + 7 * y(a + 4 * h)) * 2 * h / 45; sum = sum + bl; return sum;} // Driver Code document.write("f(x) = " + BooleRule(0, 4).toFixed(4)); </script> f(x) = 1.6178 SURENDRA_GANGWAR 29AjayKumar shivanisinghss2110 ukasp susmitakundugoaldanga Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n19 May, 2021" }, { "code": null, "e": 73, "s": 28, "text": "Given a function, f(x), tabulated at points " }, { "code": null, "e": 94, "s": 75, "text": "equally spaced by " }, { "code": null, "e": 108, "s": 96, "text": "such that " }, { "code": null, "e": 130, "s": 108, "text": "[Tex]f_2=f(x_2)[/Tex]" }, { "code": null, "e": 145, "s": 130, "text": ".....and so on" }, { "code": null, "e": 309, "s": 147, "text": "The upper and lower limits a, b correspond to which the integral needs to be found, the task is to find the integral value of the given equation f(x).Examples: " }, { "code": null, "e": 333, "s": 311, "text": "Input: a = 0, b = 4, " }, { "code": null, "e": 492, "s": 335, "text": "Output: 1.6178 Explanation: Integral of (1 / (1 + x)) is 4ln(|1 + x|)0 + c. On substituting the limits, ln(|5|) + ln(|1|) = 1.6178.Input: a = 0.2, b = 0.6, " }, { "code": null, "e": 509, "s": 494, "text": "Output: 0.3430" }, { "code": null, "e": 1038, "s": 513, "text": "Approach: In this article, Boole’s rule is discussed to compute the approximate integral value of the given function f(x). Boole’s rule is a numerical integration technique to find the approximate value of the integral. It is named after a largely self-taught mathematician, philosopher, and logician George Boole. The idea of the Boole’s technique is to approximate the integral using the values of β€˜fkβ€˜ at some equally spaced values(h in the given image). The following illustration shows how various fk’s are considered: " }, { "code": null, "e": 1102, "s": 1042, "text": "The integral value of Boole’s rule is given by the formula:" }, { "code": null, "e": 1202, "s": 1104, "text": "In the above formula, an error term which comes when integration is of order 6. The error term is" }, { "code": null, "e": 1239, "s": 1202, "text": "[Tex]f_1, f_2, f_3, f_4, f_5, [/Tex]" }, { "code": null, "e": 1298, "s": 1239, "text": "Are the values of f(x) at their respective intervals of x." }, { "code": null, "e": 1562, "s": 1298, "text": "Therefore, the following steps can be followed to compute the integral of some function f(x) in the interval (a, b): The value of n=6, which is the number of parts the interval is divided into.Calculate the width, h = (b – a)/4.Calculate the values of x1 to x5 as" }, { "code": null, "e": 1709, "s": 1562, "text": "The value of n=6, which is the number of parts the interval is divided into.Calculate the width, h = (b – a)/4.Calculate the values of x1 to x5 as" }, { "code": null, "e": 1786, "s": 1709, "text": "The value of n=6, which is the number of parts the interval is divided into." }, { "code": null, "e": 1822, "s": 1786, "text": "Calculate the width, h = (b – a)/4." }, { "code": null, "e": 1858, "s": 1822, "text": "Calculate the values of x1 to x5 as" }, { "code": null, "e": 1897, "s": 1858, "text": "Consider y = f(x). Now find the values" }, { "code": null, "e": 1919, "s": 1897, "text": "for the corresponding" }, { "code": null, "e": 1927, "s": 1919, "text": "values." }, { "code": null, "e": 2002, "s": 1927, "text": "Substitute all the values in Boole’s rule to calculate the integral value." }, { "code": null, "e": 2057, "s": 2004, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 2063, "s": 2059, "text": "C++" }, { "code": null, "e": 2065, "s": 2063, "text": "C" }, { "code": null, "e": 2070, "s": 2065, "text": "Java" }, { "code": null, "e": 2078, "s": 2070, "text": "Python3" }, { "code": null, "e": 2081, "s": 2078, "text": "C#" }, { "code": null, "e": 2092, "s": 2081, "text": "Javascript" }, { "code": "// C++ program to implement Boole's Rule// on the given function#include <bits/stdc++.h>using namespace std; // In order to represent the implementation,// a function f(x) = 1/(1 + x) is considered// in this program // Function to return the value of f(x)// for the given value of xfloat y(float x){ return (1 / (1 + x));} // Function to computes the integrand of y// at the given intervals of x with// step size h and the initial limit a// and final limit bfloat BooleRule(float a, float b){ // Number of intervals int n = 4; int h; // Computing the step size h = ((b - a) / n); float sum = 0; // Substituing a = 0, b = 4 and h = 1 float bl = ((7 * y(a) + 32 * y(a + h) + 12 * y(a + 2 * h) + 32 * y(a + 3 * h) + 7 * y(a + 4 * h)) * 2 * h / 45); sum = sum + bl; return sum;} // Driver codeint main(){ float lowlimit = 0; float upplimit = 4; cout << fixed << setprecision(4) << \"f(x) = \" << BooleRule(0, 4); return 0;} // This code is contributed by shivanisinghss2110", "e": 3207, "s": 2092, "text": null }, { "code": "// C program to implement Boole's Rule// on the given function #include <math.h>#include <stdio.h> // In order to represent the implementation,// a function f(x) = 1/(1 + x) is considered// in this program // Function to return the value of f(x)// for the given value of xfloat y(float x){ return (1 / (1 + x));} // Function to computes the integrand of y// at the given intervals of x with// step size h and the initial limit a// and final limit bfloat BooleRule(float a, float b){ // Number of intervals int n = 4; int h; // Computing the step size h = ((b - a) / n); float sum = 0; // Substituing a = 0, b = 4 and h = 1 float bl = (7 * y(a) + 32 * y(a + h) + 12 * y(a + 2 * h) + 32 * y(a + 3 * h) + 7 * y(a + 4 * h)) * 2 * h / 45; sum = sum + bl; return sum;} // Driver codeint main(){ float lowlimit = 0; float upplimit = 4; printf(\"f(x) = %.4f\", BooleRule(0, 4)); return 0;}", "e": 4205, "s": 3207, "text": null }, { "code": "// Java program to implement Boole's Rule// on the given functionclass GFG{ // In order to represent the implementation,// a function f(x) = 1/(1 + x) is considered// in this program // Function to return the value of f(x)// for the given value of xstatic float y(float x){ return (1 / (1 + x));} // Function to computes the integrand of y// at the given intervals of x with// step size h and the initial limit a// and final limit bstatic float BooleRule(float a, float b){ // Number of intervals int n = 4; int h; // Computing the step size h = (int) ((b - a) / n); float sum = 0; // Substituing a = 0, b = 4 and h = 1 float bl = (7 * y(a) + 32 * y(a + h) + 12 * y(a + 2 * h) + 32 * y(a + 3 * h) + 7 * y(a + 4 * h)) * 2 * h / 45; sum = sum + bl; return sum;} // Driver codepublic static void main(String[] args){ System.out.printf((\"f(x) = %.4f\"), BooleRule(0, 4));}} // This code is contributed by 29AjayKumar", "e": 5237, "s": 4205, "text": null }, { "code": "# Python3 program to implement Boole's Rule# on the given function # In order to represent the implementation,# a function f(x) = 1/(1 + x) is considered# in this program # Function to return the value of f(x)# for the given value of xdef y(x): return (1 / (1 + x)) # Function to computes the integrand of y# at the given intervals of x with# step size h and the initial limit a# and final limit bdef BooleRule(a, b): # Number of intervals n = 4 # Computing the step size h = ((b - a) / n) sum = 0 # Substituing a = 0, b = 4 and h = 1 bl = (7 * y(a) + 32 * y(a + h) + 12 * y(a + 2 * h)+32 * y(a + 3 * h)+7 * y(a + 4 * h))* 2 * h / 45 sum = sum + bl return sum # Driver codeif __name__ == '__main__': lowlimit = 0 upplimit = 4 print(\"f(x) =\",round(BooleRule(0, 4),4)) # This code is contributed by Surendra_Gangwar", "e": 6112, "s": 5237, "text": null }, { "code": "// C# program to implement Boole's// Rule on the given functionusing System;class GFG{ // In order to represent the// implementation, a function// f(x) = 1/(1 + x) is considered// in this program // Function to return the value of// f(x) for the given value of xstatic float y(float x){ return (1 / (1 + x));} // Function to computes the integrand// of y at the given intervals of x// with step size h and the initial// limit a and final limit bstatic float BooleRule(float a, float b){ // Number of intervals int n = 4; int h; // Computing the step size h = (int)((b - a) / n); float sum = 0; // Substituing a = 0, b = 4 // and h = 1 float bl = (7 * y(a) + 32 * y(a + h) + 12 * y(a + 2 * h) + 32 * y(a + 3 * h) + 7 * y(a + 4 * h)) * 2 * h / 45; sum = sum + bl; return sum;} // Driver codepublic static void Main(string[] args){ Console.Write((\"f(x) = \" + System.Math.Round( BooleRule(0, 4), 4)));}} // This code is contributed by Chitranayal", "e": 7206, "s": 6112, "text": null }, { "code": "<script> // JavaScript program to implement Boole's Rule// on the given function // In order to represent the implementation,// a function f(x) = 1/(1 + x) is considered// in this program // Function to return the value of f(x)// for the given value of xfunction y(x){ return (1 / (1 + x));} // Function to computes the integrand of y// at the given intervals of x with// step size h and the initial limit a// and final limit bfunction BooleRule(a, b){ // Number of intervals let n = 4; let h; // Computing the step size h = ((b - a) / n); let sum = 0; // Substituing a = 0, b = 4 and h = 1 let bl = (7 * y(a) + 32 * y(a + h) + 12 * y(a + 2 * h) + 32 * y(a + 3 * h) + 7 * y(a + 4 * h)) * 2 * h / 45; sum = sum + bl; return sum;} // Driver Code document.write(\"f(x) = \" + BooleRule(0, 4).toFixed(4)); </script>", "e": 8147, "s": 7206, "text": null }, { "code": null, "e": 8161, "s": 8147, "text": "f(x) = 1.6178" }, { "code": null, "e": 8180, "s": 8163, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 8192, "s": 8180, "text": "29AjayKumar" }, { "code": null, "e": 8211, "s": 8192, "text": "shivanisinghss2110" }, { "code": null, "e": 8217, "s": 8211, "text": "ukasp" }, { "code": null, "e": 8239, "s": 8217, "text": "susmitakundugoaldanga" }, { "code": null, "e": 8252, "s": 8239, "text": "Mathematical" }, { "code": null, "e": 8265, "s": 8252, "text": "Mathematical" } ]
Restoring Division Algorithm For Unsigned Integer
22 Apr, 2020 A division algorithm provides a quotient and a remainder when we divide two number. They are generally of two type slow algorithm and fast algorithm. Slow division algorithm are restoring, non-restoring, non-performing restoring, SRT algorithm and under fast comes Newton–Raphson and Goldschmidt. In this article, will be performing restoring algorithm for unsigned integer. Restoring term is due to fact that value of register A is restored after each iteration. Here, register Q contain quotient and register A contain remainder. Here, n-bit dividend is loaded in Q and divisor is loaded in M. Value of Register is initially kept 0 and this is the register whose value is restored during iteration due to which it is named Restoring. Let’s pick the step involved: Step-1: First the registers are initialized with corresponding values (Q = Dividend, M = Divisor, A = 0, n = number of bits in dividend) Step-2: Then the content of register A and Q is shifted left as if they are a single unit Step-3: Then content of register M is subtracted from A and result is stored in A Step-4: Then the most significant bit of the A is checked if it is 0 the least significant bit of Q is set to 1 otherwise if it is 1 the least significant bit of Q is set to 0 and value of register A is restored i.e the value of A before the subtraction with M Step-5: The value of counter n is decremented Step-6: If the value of n becomes zero we get of the loop otherwise we repeat from step 2 Step-7: Finally, the register Q contain the quotient and A contain remainder Examples: Perform Division Restoring Algorithm Dividend = 11 Divisor = 3 Remember to restore the value of A most significant bit of A is 1. As that register Q contain the quotient, i.e. 3 and register A contain remainder 2. ShubhamMaurya3 subhendu17620 Computer Organization & Architecture Digital Electronics & Logic Design GATE CS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n22 Apr, 2020" }, { "code": null, "e": 351, "s": 54, "text": "A division algorithm provides a quotient and a remainder when we divide two number. They are generally of two type slow algorithm and fast algorithm. Slow division algorithm are restoring, non-restoring, non-performing restoring, SRT algorithm and under fast comes Newton–Raphson and Goldschmidt." }, { "code": null, "e": 518, "s": 351, "text": "In this article, will be performing restoring algorithm for unsigned integer. Restoring term is due to fact that value of register A is restored after each iteration." }, { "code": null, "e": 790, "s": 518, "text": "Here, register Q contain quotient and register A contain remainder. Here, n-bit dividend is loaded in Q and divisor is loaded in M. Value of Register is initially kept 0 and this is the register whose value is restored during iteration due to which it is named Restoring." }, { "code": null, "e": 820, "s": 790, "text": "Let’s pick the step involved:" }, { "code": null, "e": 957, "s": 820, "text": "Step-1: First the registers are initialized with corresponding values (Q = Dividend, M = Divisor, A = 0, n = number of bits in dividend)" }, { "code": null, "e": 1047, "s": 957, "text": "Step-2: Then the content of register A and Q is shifted left as if they are a single unit" }, { "code": null, "e": 1129, "s": 1047, "text": "Step-3: Then content of register M is subtracted from A and result is stored in A" }, { "code": null, "e": 1390, "s": 1129, "text": "Step-4: Then the most significant bit of the A is checked if it is 0 the least significant bit of Q is set to 1 otherwise if it is 1 the least significant bit of Q is set to 0 and value of register A is restored i.e the value of A before the subtraction with M" }, { "code": null, "e": 1436, "s": 1390, "text": "Step-5: The value of counter n is decremented" }, { "code": null, "e": 1526, "s": 1436, "text": "Step-6: If the value of n becomes zero we get of the loop otherwise we repeat from step 2" }, { "code": null, "e": 1603, "s": 1526, "text": "Step-7: Finally, the register Q contain the quotient and A contain remainder" }, { "code": null, "e": 1613, "s": 1603, "text": "Examples:" }, { "code": null, "e": 1678, "s": 1613, "text": "Perform Division Restoring Algorithm \nDividend = 11\nDivisor = 3" }, { "code": null, "e": 1829, "s": 1678, "text": "Remember to restore the value of A most significant bit of A is 1. As that register Q contain the quotient, i.e. 3 and register A contain remainder 2." }, { "code": null, "e": 1844, "s": 1829, "text": "ShubhamMaurya3" }, { "code": null, "e": 1858, "s": 1844, "text": "subhendu17620" }, { "code": null, "e": 1895, "s": 1858, "text": "Computer Organization & Architecture" }, { "code": null, "e": 1930, "s": 1895, "text": "Digital Electronics & Logic Design" }, { "code": null, "e": 1938, "s": 1930, "text": "GATE CS" } ]
CSS scroll-margin-top property
07 Sep, 2020 The scroll-margin-top property is used to set all the scroll margins to the top of an element at once. The value specified for the scroll-margin-top determines how much of the page that is primarily outside the support should remain visible. Hence, the scroll-margin-top values represent outsets that define the scroll snap area that is used for snapping this box to the support. Syntax: scroll-margin-top: length /* Or */ scroll-margin-top: Global_Values Property values: This property accepts two-properties mentioned above and described below: length: This property refers to the values defined with length units: px, em, rem, vh, etc. Global_Values: This property refers to the global values like initial, inherit, unset, etc. Note: scroll-margin-top doesn’t accept percentage value as the length. Example: In this example, you can see the effect of scroll-margin-top by scrolling to a point partway between two of the β€œinterfaces” of the example’s content. <!DOCTYPE html><html> <head> <style> .page { width:278px; height:296px; color: white; font-size: 50px; display: flex; box-sizing: border-box; align-items: center; justify-content: center; scroll-snap-align: end none; } .Container { width: 300px; height:300px; overflow-x: hidden; overflow-y: auto; white-space: nowrap; scroll-snap-type:y mandatory; } </style> </head> <body> <div class="Container"> <div class="page" style= "background-color: rgb(20, 240, 38); scroll-margin-top: 0px;"> Geeks </div> <div class="page" style= "background-color: green; scroll-margin-top: 20px;"> for </div> <div class="page" style="color: black; scroll-margin-top: 40px;"> Geeks </div> <div class="page" style= "background-color: rgb(10, 207, 43); scroll-margin-top: 30px;"> for </div> </div> </body></html> Output: Supported Browsers: Chrome Firefox Opera Edge Internet Explorer (Not Supported) Safari(partially supported) CSS-Properties CSS 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": "\n07 Sep, 2020" }, { "code": null, "e": 270, "s": 28, "text": "The scroll-margin-top property is used to set all the scroll margins to the top of an element at once. The value specified for the scroll-margin-top determines how much of the page that is primarily outside the support should remain visible." }, { "code": null, "e": 408, "s": 270, "text": "Hence, the scroll-margin-top values represent outsets that define the scroll snap area that is used for snapping this box to the support." }, { "code": null, "e": 416, "s": 408, "text": "Syntax:" }, { "code": null, "e": 485, "s": 416, "text": "scroll-margin-top: length\n/* Or */\nscroll-margin-top: Global_Values\n" }, { "code": null, "e": 576, "s": 485, "text": "Property values: This property accepts two-properties mentioned above and described below:" }, { "code": null, "e": 668, "s": 576, "text": "length: This property refers to the values defined with length units: px, em, rem, vh, etc." }, { "code": null, "e": 760, "s": 668, "text": "Global_Values: This property refers to the global values like initial, inherit, unset, etc." }, { "code": null, "e": 831, "s": 760, "text": "Note: scroll-margin-top doesn’t accept percentage value as the length." }, { "code": null, "e": 991, "s": 831, "text": "Example: In this example, you can see the effect of scroll-margin-top by scrolling to a point partway between two of the β€œinterfaces” of the example’s content." }, { "code": "<!DOCTYPE html><html> <head> <style> .page { width:278px; height:296px; color: white; font-size: 50px; display: flex; box-sizing: border-box; align-items: center; justify-content: center; scroll-snap-align: end none; } .Container { width: 300px; height:300px; overflow-x: hidden; overflow-y: auto; white-space: nowrap; scroll-snap-type:y mandatory; } </style> </head> <body> <div class=\"Container\"> <div class=\"page\" style= \"background-color: rgb(20, 240, 38); scroll-margin-top: 0px;\"> Geeks </div> <div class=\"page\" style= \"background-color: green; scroll-margin-top: 20px;\"> for </div> <div class=\"page\" style=\"color: black; scroll-margin-top: 40px;\"> Geeks </div> <div class=\"page\" style= \"background-color: rgb(10, 207, 43); scroll-margin-top: 30px;\"> for </div> </div> </body></html>", "e": 2376, "s": 991, "text": null }, { "code": null, "e": 2384, "s": 2376, "text": "Output:" }, { "code": null, "e": 2404, "s": 2384, "text": "Supported Browsers:" }, { "code": null, "e": 2411, "s": 2404, "text": "Chrome" }, { "code": null, "e": 2419, "s": 2411, "text": "Firefox" }, { "code": null, "e": 2425, "s": 2419, "text": "Opera" }, { "code": null, "e": 2430, "s": 2425, "text": "Edge" }, { "code": null, "e": 2464, "s": 2430, "text": "Internet Explorer (Not Supported)" }, { "code": null, "e": 2492, "s": 2464, "text": "Safari(partially supported)" }, { "code": null, "e": 2507, "s": 2492, "text": "CSS-Properties" }, { "code": null, "e": 2511, "s": 2507, "text": "CSS" }, { "code": null, "e": 2528, "s": 2511, "text": "Web Technologies" } ]
jQuery | keyup() with Examples
13 Feb, 2019 The keyup() is an inbuilt method in jQuery which is used to trigger the keyup event whenever User releases a key from the keyboard. So, Using keyup() method we can detect if any key is released from the keyboard. Syntax: $(selector).keyup(function) Here selector is the selected element. Parameters: It accepts an optional parameter as a function which gives the idea whether any key is pressed or not. Return values: It returns whether any key is pressed or not and accordingly change the background color. <html> <head> <title>Jquery | Keyup() </title> <scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script></head><script> $(document).keyup(function(event) { alert('You released a key'); });</script> <body> <br> <br> <center> <h1>Press and release a key from the keyboard </h1> </center></body> </html> Output:After running the code: After pressing any key from the keyboard- Code: #2Below code is used to change background color of the page whenever a key is released from the keyboard <html> <head> <title>Jquery | Keyup() </title> <scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script></head><script> var colors = ['red', 'blue', 'green', 'grey', 'black', 'white', 'teal', 'yellow']; var i = 0; $(document).keyup(function(event) { $('body').css('background-color', colors[i]); i++; i = i % 9; });</script> <body> <br> <br> <center> <h3> Press any key from the keyboard and then release it <br> to change the background color of the page</h3> </center></body> </html> Output:Before pressing a key:Every time When any key is pressed and released from the keyboard, The background colour of the page changes to a new colour- After pressing and releasing any key: jQuery-Events JavaScript JQuery Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Remove elements from a JavaScript Array Roadmap to Learn JavaScript For Beginners Difference Between PUT and PATCH Request JavaScript | Promises JQuery | Set the value of an input text field How to change selected value of a drop-down list using jQuery? Form validation using jQuery How to add options to a select element using jQuery? jQuery | children() with Examples
[ { "code": null, "e": 28, "s": 0, "text": "\n13 Feb, 2019" }, { "code": null, "e": 241, "s": 28, "text": "The keyup() is an inbuilt method in jQuery which is used to trigger the keyup event whenever User releases a key from the keyboard. So, Using keyup() method we can detect if any key is released from the keyboard." }, { "code": null, "e": 249, "s": 241, "text": "Syntax:" }, { "code": null, "e": 279, "s": 249, "text": "$(selector).keyup(function) \n" }, { "code": null, "e": 318, "s": 279, "text": "Here selector is the selected element." }, { "code": null, "e": 433, "s": 318, "text": "Parameters: It accepts an optional parameter as a function which gives the idea whether any key is pressed or not." }, { "code": null, "e": 538, "s": 433, "text": "Return values: It returns whether any key is pressed or not and accordingly change the background color." }, { "code": "<html> <head> <title>Jquery | Keyup() </title> <scriptsrc=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js\"> </script></head><script> $(document).keyup(function(event) { alert('You released a key'); });</script> <body> <br> <br> <center> <h1>Press and release a key from the keyboard </h1> </center></body> </html>", "e": 917, "s": 538, "text": null }, { "code": null, "e": 948, "s": 917, "text": "Output:After running the code:" }, { "code": null, "e": 990, "s": 948, "text": "After pressing any key from the keyboard-" }, { "code": null, "e": 1101, "s": 990, "text": "Code: #2Below code is used to change background color of the page whenever a key is released from the keyboard" }, { "code": "<html> <head> <title>Jquery | Keyup() </title> <scriptsrc=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js\"> </script></head><script> var colors = ['red', 'blue', 'green', 'grey', 'black', 'white', 'teal', 'yellow']; var i = 0; $(document).keyup(function(event) { $('body').css('background-color', colors[i]); i++; i = i % 9; });</script> <body> <br> <br> <center> <h3> Press any key from the keyboard and then release it <br> to change the background color of the page</h3> </center></body> </html> ", "e": 1750, "s": 1101, "text": null }, { "code": null, "e": 1905, "s": 1750, "text": "Output:Before pressing a key:Every time When any key is pressed and released from the keyboard, The background colour of the page changes to a new colour-" }, { "code": null, "e": 1943, "s": 1905, "text": "After pressing and releasing any key:" }, { "code": null, "e": 1957, "s": 1943, "text": "jQuery-Events" }, { "code": null, "e": 1968, "s": 1957, "text": "JavaScript" }, { "code": null, "e": 1975, "s": 1968, "text": "JQuery" }, { "code": null, "e": 2073, "s": 1975, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2134, "s": 2073, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2174, "s": 2134, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 2216, "s": 2174, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 2257, "s": 2216, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 2279, "s": 2257, "text": "JavaScript | Promises" }, { "code": null, "e": 2325, "s": 2279, "text": "JQuery | Set the value of an input text field" }, { "code": null, "e": 2388, "s": 2325, "text": "How to change selected value of a drop-down list using jQuery?" }, { "code": null, "e": 2417, "s": 2388, "text": "Form validation using jQuery" }, { "code": null, "e": 2470, "s": 2417, "text": "How to add options to a select element using jQuery?" } ]
Python | Corner detection with Harris Corner Detection method using OpenCV
08 Feb, 2022 Harris Corner detection algorithm was developed to identify the internal corners of an image. The corners of an image are basically identified as the regions in which there are variations in large intensity of the gradient in all possible dimensions and directions. Corners extracted can be a part of the image features, which can be matched with features of other images, and can be used to extract accurate information. Harris Corner Detection is a method to extract the corners from the input image and to extract features from the input image. About the function used: Syntax: cv2.cornerHarris(src, dest, blockSize, kSize, freeParameter, borderType)Parameters: src – Input Image (Single-channel, 8-bit or floating-point) dest – Image to store the Harris detector responses. Size is same as source image blockSize – Neighborhood size ( for each pixel value blockSize * blockSize neighbourhood is considered ) ksize – Aperture parameter for the Sobel() operator freeParameter – Harris detector free parameter borderType – Pixel extrapolation method ( the extrapolation mode used returns the coordinate of the pixel corresponding to the specified extrapolated pixel ) Below is the Python implementation : Python3 # Python program to illustrate# corner detection with# Harris Corner Detection Method # organizing importsimport cv2import numpy as np # path to input image specified and# image is loaded with imread commandimage = cv2.imread('GeekforGeeks.jpg') # convert the input image into# grayscale color spaceoperatedImage = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # modify the data type# setting to 32-bit floating pointoperatedImage = np.float32(operatedImage) # apply the cv2.cornerHarris method# to detect the corners with appropriate# values as input parametersdest = cv2.cornerHarris(operatedImage, 2, 5, 0.07) # Results are marked through the dilated cornersdest = cv2.dilate(dest, None) # Reverting back to the original image,# with optimal threshold valueimage[dest > 0.01 * dest.max()]=[0, 0, 255] # the window showing output image with cornerscv2.imshow('Image with Borders', image) # De-allocate any associated memory usageif cv2.waitKey(0) & 0xff == 27: cv2.destroyAllWindows() Input: Output: sweetyty Image-Processing OpenCV Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Feb, 2022" }, { "code": null, "e": 603, "s": 28, "text": "Harris Corner detection algorithm was developed to identify the internal corners of an image. The corners of an image are basically identified as the regions in which there are variations in large intensity of the gradient in all possible dimensions and directions. Corners extracted can be a part of the image features, which can be matched with features of other images, and can be used to extract accurate information. Harris Corner Detection is a method to extract the corners from the input image and to extract features from the input image. About the function used: " }, { "code": null, "e": 1199, "s": 603, "text": "Syntax: cv2.cornerHarris(src, dest, blockSize, kSize, freeParameter, borderType)Parameters: src – Input Image (Single-channel, 8-bit or floating-point) dest – Image to store the Harris detector responses. Size is same as source image blockSize – Neighborhood size ( for each pixel value blockSize * blockSize neighbourhood is considered ) ksize – Aperture parameter for the Sobel() operator freeParameter – Harris detector free parameter borderType – Pixel extrapolation method ( the extrapolation mode used returns the coordinate of the pixel corresponding to the specified extrapolated pixel )" }, { "code": null, "e": 1238, "s": 1199, "text": "Below is the Python implementation : " }, { "code": null, "e": 1246, "s": 1238, "text": "Python3" }, { "code": "# Python program to illustrate# corner detection with# Harris Corner Detection Method # organizing importsimport cv2import numpy as np # path to input image specified and# image is loaded with imread commandimage = cv2.imread('GeekforGeeks.jpg') # convert the input image into# grayscale color spaceoperatedImage = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # modify the data type# setting to 32-bit floating pointoperatedImage = np.float32(operatedImage) # apply the cv2.cornerHarris method# to detect the corners with appropriate# values as input parametersdest = cv2.cornerHarris(operatedImage, 2, 5, 0.07) # Results are marked through the dilated cornersdest = cv2.dilate(dest, None) # Reverting back to the original image,# with optimal threshold valueimage[dest > 0.01 * dest.max()]=[0, 0, 255] # the window showing output image with cornerscv2.imshow('Image with Borders', image) # De-allocate any associated memory usageif cv2.waitKey(0) & 0xff == 27: cv2.destroyAllWindows()", "e": 2230, "s": 1246, "text": null }, { "code": null, "e": 2239, "s": 2230, "text": "Input: " }, { "code": null, "e": 2249, "s": 2239, "text": "Output: " }, { "code": null, "e": 2260, "s": 2251, "text": "sweetyty" }, { "code": null, "e": 2277, "s": 2260, "text": "Image-Processing" }, { "code": null, "e": 2284, "s": 2277, "text": "OpenCV" }, { "code": null, "e": 2291, "s": 2284, "text": "Python" } ]
Express.js res.sendFile() Function
03 Sep, 2021 The res.sendFile() function basically transfers the file at the given path and it sets the Content-Type response HTTP header field based on the filename extension. Syntax: res.sendFile(path [, options] [, fn]) Parameter: The path parameter describes the path and the options parameter contains various properties like maxAge, root, etc and fn is the callback function.Returns: It returns an Object.Installation of express module: You can visit the link to Install express module. You can install this package by using this command. npm install express After installing the express module, you can check your express version in command prompt using the command. npm version express After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command. node index.js Example 1: Filename: index.js javascript var express = require('express');var app = express();var path = require('path');var PORT = 3000; // Without middlewareapp.get('/', function(req, res){ var options = { root: path.join(__dirname) }; var fileName = 'Hello.txt'; res.sendFile(fileName, options, function (err) { if (err) { next(err); } else { console.log('Sent:', fileName); } });}); app.listen(PORT, function(err){ if (err) console.log(err); console.log("Server listening on PORT", PORT);}); Now, create a .txt file like here we have created Hello.txt in the root directory of project with the following text: Greetings from GeeksforGeeks Steps to run the program: Make sure you have installed express module using the following command: npm install express Run index.js file using below command: node index.js Output: Server listening on PORT 3000 Now open browser and go to http://localhost:3000/, now check your console and you will see the following output: Server listening on PORT 3000 Sent: Hello.txt And on screen you will see the following output: Greetings from GeeksforGeeks Example 2: Filename: index.js javascript var express = require('express');const path = require('path');var app = express();var PORT = 3000; // With middlewareapp.use('/', function(req, res, next){ var options = { root: path.join(__dirname) }; var fileName = 'GeeksforGeeks.txt'; res.sendFile(fileName, options, function (err) { if (err) { next(err); } else { console.log('Sent:', fileName); next(); } });}); app.get('/', function(req, res){ console.log("File Sent") res.send();}); app.listen(PORT, function(err){ if (err) console.log(err); console.log("Server listening on PORT", PORT);}); Make sure you create a .txt file like here we have created GeeksforGeeks.txt in the root directory of project with the following text: Welcome from GeeksforGeeks Run index.js file using below command: node index.js Now open the browser and go to http://localhost:3000/, now check your console and you will see the following output: Server listening on PORT 3000 Sent: GeeksforGeeks.txt File Sent And you will see the following output on your browser screen: Welcome from GeeksforGeeks Reference: https://expressjs.com/en/5x/api.html#res.sendFile kapoorsagar226 Express.js Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Node.js fs.writeFile() Method How to install the previous version of node.js and npm ? Difference between promise and async await in Node.js Mongoose | findByIdAndUpdate() Function Installation of Node.js on Windows Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React
[ { "code": null, "e": 53, "s": 25, "text": "\n03 Sep, 2021" }, { "code": null, "e": 226, "s": 53, "text": "The res.sendFile() function basically transfers the file at the given path and it sets the Content-Type response HTTP header field based on the filename extension. Syntax: " }, { "code": null, "e": 264, "s": 226, "text": "res.sendFile(path [, options] [, fn])" }, { "code": null, "e": 485, "s": 264, "text": "Parameter: The path parameter describes the path and the options parameter contains various properties like maxAge, root, etc and fn is the callback function.Returns: It returns an Object.Installation of express module: " }, { "code": null, "e": 588, "s": 485, "text": "You can visit the link to Install express module. You can install this package by using this command. " }, { "code": null, "e": 608, "s": 588, "text": "npm install express" }, { "code": null, "e": 718, "s": 608, "text": "After installing the express module, you can check your express version in command prompt using the command. " }, { "code": null, "e": 738, "s": 718, "text": "npm version express" }, { "code": null, "e": 874, "s": 738, "text": "After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command. " }, { "code": null, "e": 888, "s": 874, "text": "node index.js" }, { "code": null, "e": 919, "s": 888, "text": "Example 1: Filename: index.js " }, { "code": null, "e": 930, "s": 919, "text": "javascript" }, { "code": "var express = require('express');var app = express();var path = require('path');var PORT = 3000; // Without middlewareapp.get('/', function(req, res){ var options = { root: path.join(__dirname) }; var fileName = 'Hello.txt'; res.sendFile(fileName, options, function (err) { if (err) { next(err); } else { console.log('Sent:', fileName); } });}); app.listen(PORT, function(err){ if (err) console.log(err); console.log(\"Server listening on PORT\", PORT);});", "e": 1461, "s": 930, "text": null }, { "code": null, "e": 1581, "s": 1461, "text": "Now, create a .txt file like here we have created Hello.txt in the root directory of project with the following text: " }, { "code": null, "e": 1610, "s": 1581, "text": "Greetings from GeeksforGeeks" }, { "code": null, "e": 1637, "s": 1610, "text": "Steps to run the program: " }, { "code": null, "e": 1711, "s": 1637, "text": "Make sure you have installed express module using the following command: " }, { "code": null, "e": 1731, "s": 1711, "text": "npm install express" }, { "code": null, "e": 1771, "s": 1731, "text": "Run index.js file using below command: " }, { "code": null, "e": 1785, "s": 1771, "text": "node index.js" }, { "code": null, "e": 1794, "s": 1785, "text": "Output: " }, { "code": null, "e": 1824, "s": 1794, "text": "Server listening on PORT 3000" }, { "code": null, "e": 1938, "s": 1824, "text": "Now open browser and go to http://localhost:3000/, now check your console and you will see the following output: " }, { "code": null, "e": 1984, "s": 1938, "text": "Server listening on PORT 3000\nSent: Hello.txt" }, { "code": null, "e": 2034, "s": 1984, "text": "And on screen you will see the following output: " }, { "code": null, "e": 2063, "s": 2034, "text": "Greetings from GeeksforGeeks" }, { "code": null, "e": 2094, "s": 2063, "text": "Example 2: Filename: index.js " }, { "code": null, "e": 2105, "s": 2094, "text": "javascript" }, { "code": "var express = require('express');const path = require('path');var app = express();var PORT = 3000; // With middlewareapp.use('/', function(req, res, next){ var options = { root: path.join(__dirname) }; var fileName = 'GeeksforGeeks.txt'; res.sendFile(fileName, options, function (err) { if (err) { next(err); } else { console.log('Sent:', fileName); next(); } });}); app.get('/', function(req, res){ console.log(\"File Sent\") res.send();}); app.listen(PORT, function(err){ if (err) console.log(err); console.log(\"Server listening on PORT\", PORT);});", "e": 2751, "s": 2105, "text": null }, { "code": null, "e": 2888, "s": 2751, "text": "Make sure you create a .txt file like here we have created GeeksforGeeks.txt in the root directory of project with the following text: " }, { "code": null, "e": 2915, "s": 2888, "text": "Welcome from GeeksforGeeks" }, { "code": null, "e": 2956, "s": 2915, "text": "Run index.js file using below command: " }, { "code": null, "e": 2970, "s": 2956, "text": "node index.js" }, { "code": null, "e": 3089, "s": 2970, "text": "Now open the browser and go to http://localhost:3000/, now check your console and you will see the following output: " }, { "code": null, "e": 3153, "s": 3089, "text": "Server listening on PORT 3000\nSent: GeeksforGeeks.txt\nFile Sent" }, { "code": null, "e": 3217, "s": 3153, "text": "And you will see the following output on your browser screen: " }, { "code": null, "e": 3244, "s": 3217, "text": "Welcome from GeeksforGeeks" }, { "code": null, "e": 3305, "s": 3244, "text": "Reference: https://expressjs.com/en/5x/api.html#res.sendFile" }, { "code": null, "e": 3320, "s": 3305, "text": "kapoorsagar226" }, { "code": null, "e": 3331, "s": 3320, "text": "Express.js" }, { "code": null, "e": 3339, "s": 3331, "text": "Node.js" }, { "code": null, "e": 3356, "s": 3339, "text": "Web Technologies" }, { "code": null, "e": 3454, "s": 3356, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3484, "s": 3454, "text": "Node.js fs.writeFile() Method" }, { "code": null, "e": 3541, "s": 3484, "text": "How to install the previous version of node.js and npm ?" }, { "code": null, "e": 3595, "s": 3541, "text": "Difference between promise and async await in Node.js" }, { "code": null, "e": 3635, "s": 3595, "text": "Mongoose | findByIdAndUpdate() Function" }, { "code": null, "e": 3670, "s": 3635, "text": "Installation of Node.js on Windows" }, { "code": null, "e": 3732, "s": 3670, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3793, "s": 3732, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3843, "s": 3793, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 3886, "s": 3843, "text": "How to fetch data from an API in ReactJS ?" } ]
VSAM - RRDS
RRDS is known as Relative Record Data Set. RRDS cluster is similar to an ESDS cluster. The only difference is that RRDS records are accessed by Relative Record Number (RRN), we must code NUMBERED inside the DEFINE CLUSTER command. Following are the key features of RRDS βˆ’ A Relative record dataset has records that are identified by the Relative Record Number (RRN), which is the sequence number relative to the first record. A Relative record dataset has records that are identified by the Relative Record Number (RRN), which is the sequence number relative to the first record. RRDS allows access of records by number like record 1, record 2, and so on. This provides random access and assumes the application program has a way to get the desired record numbers. RRDS allows access of records by number like record 1, record 2, and so on. This provides random access and assumes the application program has a way to get the desired record numbers. The records in an RRDS dataset can be accessed sequentially, in relative record number order, or directly, by supplying the relative record number of the desired record. The records in an RRDS dataset can be accessed sequentially, in relative record number order, or directly, by supplying the relative record number of the desired record. The records in a RRDS dataset are stored in fixed length slots. Each record is referenced by the number of its slot, number can vary from 1 to the maximum number of records in the dataset. The records in a RRDS dataset are stored in fixed length slots. Each record is referenced by the number of its slot, number can vary from 1 to the maximum number of records in the dataset. Records in a RRDS can be written by inserting new record into an empty slot. Records in a RRDS can be written by inserting new record into an empty slot. Records can be deleted from an RRDS cluster, thereby leaving an empty slot. Records can be deleted from an RRDS cluster, thereby leaving an empty slot. Applications which use fixed-length records or a record number with contextual meaning that can use RRDS datasets. Applications which use fixed-length records or a record number with contextual meaning that can use RRDS datasets. RRDS can be used in COBOL programs like any other file. We will specify the file name in JCL and we can use the KSDS file for processing inside program. In COBOL program specify file organization as RELATIVE and you can use any access mode (Sequential, Random or Dynamic) with RRDS dataset. RRDS can be used in COBOL programs like any other file. We will specify the file name in JCL and we can use the KSDS file for processing inside program. In COBOL program specify file organization as RELATIVE and you can use any access mode (Sequential, Random or Dynamic) with RRDS dataset. Space is divided into fixed length slots in RRDS file structure. A slot can be either completely vacant or completely full. Thus, new records can be added to empty slots and existing records can be deleted from slots which are filled. We can access any record directly by giving Relative Record Number. Following example shows the basic structure of data file βˆ’ The following syntax shows which parameters we can use while creating RRDS cluster. The parameter description remains the same as mentioned in VSAM - Cluster module. DEFINE CLUSTER (NAME(rrds-file-name) - BLOCKS(number) - VOLUMES(volume-serial) - NUMBERED - RECSZ(average maximum) - [FREESPACE(CI-Percentage,CA-Percentage)] - CISZ(number) - [READPW(password)] - [FOR(days)|TO(date)] - [UPDATEPW(password)] - [REUSE / NOREUSE]) - DATA - (NAME(rrds-file-name.data)) Following example shows how to create an RRDS cluster in JCL using IDCAMS utility βˆ’ //SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C //STEP1 EXEC PGM = IDCAMS //SYSPRINT DD SYSOUT = * //SYSIN DD * DEFINE CLUSTER (NAME(MY.VSAM.RRDSFILE) - NUMBERED - RECSZ(80 80) - TRACKS(1,1) - REUSE - FREESPACE(3 3) ) - DATA (NAME(MY.VSAM.RRDSFILE.DATA)) /* If you will execute the above JCL on Mainframes server. It should execute with MAXCC = 0 and it will create MY.VSAM.RRDSFILE VSAM file. RRDS cluster is deleted using IDCAMS utility. DELETE command removes the entry of the VSAM cluster from the catalog and optionally removes the file, thereby freeing up the space occupied by the object. DELETE data-set-name CLUSTER [ERASE / NOERASE] [FORCE / NOFORCE] [PURGE / NOPURGE] [SCRATCH / NOSCRATCH] Above syntax shows which parameters we can use while deleting RRDS cluster. The parameter description remains the same as mentioned in VSAM - Cluster module. Following example shows how to delete an RRDS cluster in JCL using IDCAMS utility βˆ’ //SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C //STEPNAME EXEC PGM = IDCAMS //SYSPRINT DD SYSOUT = * //SYSIN DD * DELETE MY.VSAM.RRDSFILE CLUSTER /* If you will execute the above JCL on Mainframes server. It should execute with MAXCC = 0 and it will delete MY.VSAM.RRDSFILE VSAM Cluster.
[ { "code": null, "e": 2171, "s": 1899, "text": "RRDS is known as Relative Record Data Set. RRDS cluster is similar to an ESDS cluster. The only difference is that RRDS records are accessed by Relative Record Number (RRN), we must code NUMBERED inside the DEFINE CLUSTER command. Following are the key features of RRDS βˆ’" }, { "code": null, "e": 2325, "s": 2171, "text": "A Relative record dataset has records that are identified by the Relative Record Number (RRN), which is the sequence number relative to the first record." }, { "code": null, "e": 2479, "s": 2325, "text": "A Relative record dataset has records that are identified by the Relative Record Number (RRN), which is the sequence number relative to the first record." }, { "code": null, "e": 2665, "s": 2479, "text": "RRDS allows access of records by number like record 1, record 2, and so on. This provides random access and assumes the application program has a way to get the desired record numbers." }, { "code": null, "e": 2851, "s": 2665, "text": "RRDS allows access of records by number like record 1, record 2, and so on. This provides random access and assumes the application program has a way to get the desired record numbers." }, { "code": null, "e": 3021, "s": 2851, "text": "The records in an RRDS dataset can be accessed sequentially, in relative record number order, or directly, by supplying the relative record number of the desired record." }, { "code": null, "e": 3191, "s": 3021, "text": "The records in an RRDS dataset can be accessed sequentially, in relative record number order, or directly, by supplying the relative record number of the desired record." }, { "code": null, "e": 3380, "s": 3191, "text": "The records in a RRDS dataset are stored in fixed length slots. Each record is referenced by the number of its slot, number can vary from 1 to the maximum number of records in the dataset." }, { "code": null, "e": 3569, "s": 3380, "text": "The records in a RRDS dataset are stored in fixed length slots. Each record is referenced by the number of its slot, number can vary from 1 to the maximum number of records in the dataset." }, { "code": null, "e": 3646, "s": 3569, "text": "Records in a RRDS can be written by inserting new record into an empty slot." }, { "code": null, "e": 3723, "s": 3646, "text": "Records in a RRDS can be written by inserting new record into an empty slot." }, { "code": null, "e": 3799, "s": 3723, "text": "Records can be deleted from an RRDS cluster, thereby leaving an empty slot." }, { "code": null, "e": 3875, "s": 3799, "text": "Records can be deleted from an RRDS cluster, thereby leaving an empty slot." }, { "code": null, "e": 3990, "s": 3875, "text": "Applications which use fixed-length records or a record number with contextual meaning that can use RRDS datasets." }, { "code": null, "e": 4105, "s": 3990, "text": "Applications which use fixed-length records or a record number with contextual meaning that can use RRDS datasets." }, { "code": null, "e": 4396, "s": 4105, "text": "RRDS can be used in COBOL programs like any other file. We will specify the file name in JCL and we can use the KSDS file for processing inside program. In COBOL program specify file organization as RELATIVE and you can use any access mode (Sequential, Random or Dynamic) with RRDS dataset." }, { "code": null, "e": 4687, "s": 4396, "text": "RRDS can be used in COBOL programs like any other file. We will specify the file name in JCL and we can use the KSDS file for processing inside program. In COBOL program specify file organization as RELATIVE and you can use any access mode (Sequential, Random or Dynamic) with RRDS dataset." }, { "code": null, "e": 5049, "s": 4687, "text": "Space is divided into fixed length slots in RRDS file structure. A slot can be either completely vacant or completely full. Thus, new records can be added to empty slots and existing records can be deleted from slots which are filled. We can access any record directly by giving Relative Record Number. Following example shows the basic structure of data file βˆ’" }, { "code": null, "e": 5133, "s": 5049, "text": "The following syntax shows which parameters we can use while creating RRDS cluster." }, { "code": null, "e": 5215, "s": 5133, "text": "The parameter description remains the same as mentioned in VSAM - Cluster module." }, { "code": null, "e": 5774, "s": 5215, "text": "DEFINE CLUSTER (NAME(rrds-file-name) -\nBLOCKS(number) -\nVOLUMES(volume-serial) -\nNUMBERED -\nRECSZ(average maximum) -\n[FREESPACE(CI-Percentage,CA-Percentage)] -\nCISZ(number) -\n[READPW(password)] -\n[FOR(days)|TO(date)] -\n[UPDATEPW(password)] -\n[REUSE / NOREUSE]) -\nDATA -\n (NAME(rrds-file-name.data)) \n" }, { "code": null, "e": 5858, "s": 5774, "text": "Following example shows how to create an RRDS cluster in JCL using IDCAMS utility βˆ’" }, { "code": null, "e": 6298, "s": 5858, "text": "//SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C\n//STEP1 EXEC PGM = IDCAMS\n//SYSPRINT DD SYSOUT = *\n//SYSIN DD *\n DEFINE CLUSTER (NAME(MY.VSAM.RRDSFILE) -\n NUMBERED -\n RECSZ(80 80) -\n TRACKS(1,1) -\n REUSE - \n FREESPACE(3 3) ) -\n DATA (NAME(MY.VSAM.RRDSFILE.DATA)) \n/*" }, { "code": null, "e": 6434, "s": 6298, "text": "If you will execute the above JCL on Mainframes server. It should execute with MAXCC = 0 and it will create MY.VSAM.RRDSFILE VSAM file." }, { "code": null, "e": 6636, "s": 6434, "text": "RRDS cluster is deleted using IDCAMS utility. DELETE command removes the entry of the VSAM cluster from the catalog and optionally removes the file, thereby freeing up the space occupied by the object." }, { "code": null, "e": 6747, "s": 6636, "text": "DELETE data-set-name CLUSTER \n[ERASE / NOERASE] \n[FORCE / NOFORCE] \n[PURGE / NOPURGE] \n[SCRATCH / NOSCRATCH]\n" }, { "code": null, "e": 6906, "s": 6747, "text": "Above syntax shows which parameters we can use while deleting RRDS cluster. The parameter description remains the same as mentioned in VSAM - Cluster module. " }, { "code": null, "e": 6990, "s": 6906, "text": "Following example shows how to delete an RRDS cluster in JCL using IDCAMS utility βˆ’" }, { "code": null, "e": 7152, "s": 6990, "text": "//SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C\n//STEPNAME EXEC PGM = IDCAMS\n//SYSPRINT DD SYSOUT = *\n//SYSIN DD *\n DELETE MY.VSAM.RRDSFILE CLUSTER\n/*" } ]
Render HTML Forms (GET & POST) in Django
16 Aug, 2021 Django is often called β€œBatteries Included Framework” because it has a default setting for everything and has features that can help anyone develop a website rapidly. Talking about forms, In HTML, a form is a collection of elements inside <form>...</form> that allow a visitor to do things like entering text, select options, manipulate objects or controls, and so on, and then send that information back to the server. Basically, it is a collection of data for processing it for any purpose including saving it in the database or fetching data from the database. Django supports all types of HTML forms and rendering data from them to a view for processing using various logical operations. To know more about HTML forms, visit HTML | form Tag. Django also provides a built-in feature of Django Forms just like Django Models. One can create forms in Django and use them to fetch data from the user in a convenient manner.To begin with forms, one needs to be familiar with GET and POST requests in forms. GET: GET, by contrast, bundles the submitted data into a string, and uses this to compose a URL. The URL contains the address where the data must be sent, as well as the data keys and values. You can see this in action if you do a search in the Django documentation, which will produce a URL of the form https://docs.djangoproject.com/search/?q=forms&release=1. POST: Any request that could be used to change the state of the system – for example, a request that makes changes in the database – should use POST. Illustration of Django Forms using an Example. Consider a project named geeksforgeeks having an app named geeks. Refer to the following articles to check how to create a project and an app in Django. How to Create a Basic Project using MVT in Django? How to Create an App in Django ? Let’s create a simple HTML form to show how can you input the data from a user and use it in your view. Enter following code in geeks > templates > home.html HTML <form action = "" method = "get"> <label for="your_name">Your name: </label> <input id="your_name" type="text" name="your_name"> <input type="submit" value="OK"></form> Now to render it in our view we need to modify urls.py for geeks app.Enter the following code in geeksforgeeks > urls.py Python3 from django.urls import path # importing views from views..pyfrom .views import geeks_view urlpatterns = [ path('', home_view ),] Now, let’s move to our home_view and start checking how are we going to get the data. Entire data from an HTML form in Django is transferred as a JSON object called a request. Let’s create a view first and then we will try all methods to fetch data from the form. Python3 from django.shortcuts import render # Create your views here.def home_view(request): # logic of view will be implemented here return render(request, "home.html") As we have everything set up let us run Python manage.py run server and check if the form is there on the home page. By default every form ever written in HTML makes a GET request to the back end of an application, a GET request normally works using queries in the URL. Let’s demonstrate it using the above form, Fill up the form using your name, and let’s check what happens. The above URL is appended with a name attribute of the input tag and the name entered in the form. This is how the GET request works whatever be the number of inputs they would be appended to the URL to send the data to the back end of an application. Let’s check how to finally get this data in our view so that logic could be applied based on input. In views.py Python3 from django.shortcuts import render # Create your views here.def home_view(request): print(request.GET) return render(request, "home.html") Now when we fill the form we can see the output in the terminal as below: request.GET returns a query dictionary that one can access like any other python dictionary and finally use its data for applying some logic. Similarly, if the method of transmission is POST, you can use request.POST as query dictionary for rendering the data from the form into views. In home.html HTML <form action = "" method = "POST"> {% csrf_token %} <label for="your_name">Your name: </label> <input id="your_name" type="text" name="your_name"> <input type="submit" value="OK"></form> Note that whenever we create a form request, Django requires you to add {% csrf_token %} in form for security purposes Now, in views.py let’s check what request.POST has got. Python3 from django.shortcuts import render # Create your views here.def home_view(request): print(request.POST) return render(request, "home.html") Now when we submit the form it shows the data as below. This way one can use this data for querying into the database or for processing using some logical operation and pass using the context dictionary to the template. yuvraj_chandra ddeevviissaavviittaa Django-forms Python Django Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read JSON file using Python Python map() function Adding new column to existing DataFrame in Pandas How to get column names in Pandas dataframe Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? Iterate over a list in Python
[ { "code": null, "e": 54, "s": 26, "text": "\n16 Aug, 2021" }, { "code": null, "e": 746, "s": 54, "text": "Django is often called β€œBatteries Included Framework” because it has a default setting for everything and has features that can help anyone develop a website rapidly. Talking about forms, In HTML, a form is a collection of elements inside <form>...</form> that allow a visitor to do things like entering text, select options, manipulate objects or controls, and so on, and then send that information back to the server. Basically, it is a collection of data for processing it for any purpose including saving it in the database or fetching data from the database. Django supports all types of HTML forms and rendering data from them to a view for processing using various logical operations." }, { "code": null, "e": 800, "s": 746, "text": "To know more about HTML forms, visit HTML | form Tag." }, { "code": null, "e": 1059, "s": 800, "text": "Django also provides a built-in feature of Django Forms just like Django Models. One can create forms in Django and use them to fetch data from the user in a convenient manner.To begin with forms, one needs to be familiar with GET and POST requests in forms." }, { "code": null, "e": 1421, "s": 1059, "text": "GET: GET, by contrast, bundles the submitted data into a string, and uses this to compose a URL. The URL contains the address where the data must be sent, as well as the data keys and values. You can see this in action if you do a search in the Django documentation, which will produce a URL of the form https://docs.djangoproject.com/search/?q=forms&release=1." }, { "code": null, "e": 1571, "s": 1421, "text": "POST: Any request that could be used to change the state of the system – for example, a request that makes changes in the database – should use POST." }, { "code": null, "e": 1684, "s": 1571, "text": "Illustration of Django Forms using an Example. Consider a project named geeksforgeeks having an app named geeks." }, { "code": null, "e": 1771, "s": 1684, "text": "Refer to the following articles to check how to create a project and an app in Django." }, { "code": null, "e": 1822, "s": 1771, "text": "How to Create a Basic Project using MVT in Django?" }, { "code": null, "e": 1855, "s": 1822, "text": "How to Create an App in Django ?" }, { "code": null, "e": 2013, "s": 1855, "text": "Let’s create a simple HTML form to show how can you input the data from a user and use it in your view. Enter following code in geeks > templates > home.html" }, { "code": null, "e": 2018, "s": 2013, "text": "HTML" }, { "code": "<form action = \"\" method = \"get\"> <label for=\"your_name\">Your name: </label> <input id=\"your_name\" type=\"text\" name=\"your_name\"> <input type=\"submit\" value=\"OK\"></form>", "e": 2196, "s": 2018, "text": null }, { "code": null, "e": 2317, "s": 2196, "text": "Now to render it in our view we need to modify urls.py for geeks app.Enter the following code in geeksforgeeks > urls.py" }, { "code": null, "e": 2325, "s": 2317, "text": "Python3" }, { "code": "from django.urls import path # importing views from views..pyfrom .views import geeks_view urlpatterns = [ path('', home_view ),]", "e": 2458, "s": 2325, "text": null }, { "code": null, "e": 2722, "s": 2458, "text": "Now, let’s move to our home_view and start checking how are we going to get the data. Entire data from an HTML form in Django is transferred as a JSON object called a request. Let’s create a view first and then we will try all methods to fetch data from the form." }, { "code": null, "e": 2730, "s": 2722, "text": "Python3" }, { "code": "from django.shortcuts import render # Create your views here.def home_view(request): # logic of view will be implemented here return render(request, \"home.html\")", "e": 2899, "s": 2730, "text": null }, { "code": null, "e": 3016, "s": 2899, "text": "As we have everything set up let us run Python manage.py run server and check if the form is there on the home page." }, { "code": null, "e": 3276, "s": 3016, "text": "By default every form ever written in HTML makes a GET request to the back end of an application, a GET request normally works using queries in the URL. Let’s demonstrate it using the above form, Fill up the form using your name, and let’s check what happens." }, { "code": null, "e": 3640, "s": 3276, "text": "The above URL is appended with a name attribute of the input tag and the name entered in the form. This is how the GET request works whatever be the number of inputs they would be appended to the URL to send the data to the back end of an application. Let’s check how to finally get this data in our view so that logic could be applied based on input. In views.py" }, { "code": null, "e": 3648, "s": 3640, "text": "Python3" }, { "code": "from django.shortcuts import render # Create your views here.def home_view(request): print(request.GET) return render(request, \"home.html\")", "e": 3794, "s": 3648, "text": null }, { "code": null, "e": 3868, "s": 3794, "text": "Now when we fill the form we can see the output in the terminal as below:" }, { "code": null, "e": 4154, "s": 3868, "text": "request.GET returns a query dictionary that one can access like any other python dictionary and finally use its data for applying some logic. Similarly, if the method of transmission is POST, you can use request.POST as query dictionary for rendering the data from the form into views." }, { "code": null, "e": 4167, "s": 4154, "text": "In home.html" }, { "code": null, "e": 4172, "s": 4167, "text": "HTML" }, { "code": "<form action = \"\" method = \"POST\"> {% csrf_token %} <label for=\"your_name\">Your name: </label> <input id=\"your_name\" type=\"text\" name=\"your_name\"> <input type=\"submit\" value=\"OK\"></form>", "e": 4371, "s": 4172, "text": null }, { "code": null, "e": 4546, "s": 4371, "text": "Note that whenever we create a form request, Django requires you to add {% csrf_token %} in form for security purposes Now, in views.py let’s check what request.POST has got." }, { "code": null, "e": 4554, "s": 4546, "text": "Python3" }, { "code": "from django.shortcuts import render # Create your views here.def home_view(request): print(request.POST) return render(request, \"home.html\")", "e": 4701, "s": 4554, "text": null }, { "code": null, "e": 4757, "s": 4701, "text": "Now when we submit the form it shows the data as below." }, { "code": null, "e": 4921, "s": 4757, "text": "This way one can use this data for querying into the database or for processing using some logical operation and pass using the context dictionary to the template." }, { "code": null, "e": 4936, "s": 4921, "text": "yuvraj_chandra" }, { "code": null, "e": 4957, "s": 4936, "text": "ddeevviissaavviittaa" }, { "code": null, "e": 4970, "s": 4957, "text": "Django-forms" }, { "code": null, "e": 4984, "s": 4970, "text": "Python Django" }, { "code": null, "e": 4991, "s": 4984, "text": "Python" }, { "code": null, "e": 5089, "s": 4991, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5117, "s": 5089, "text": "Read JSON file using Python" }, { "code": null, "e": 5139, "s": 5117, "text": "Python map() function" }, { "code": null, "e": 5189, "s": 5139, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 5233, "s": 5189, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 5275, "s": 5233, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 5297, "s": 5275, "text": "Enumerate() in Python" }, { "code": null, "e": 5332, "s": 5297, "text": "Read a file line by line in Python" }, { "code": null, "e": 5358, "s": 5332, "text": "Python String | replace()" }, { "code": null, "e": 5390, "s": 5358, "text": "How to Install PIP on Windows ?" } ]
How to validate Email Address in Android on EditText using Kotlin?
This example demonstrates how to validate Email Address in Android on EditText using Kotlin. Step 1 βˆ’ Create a new project in Android Studio, go to File β‡’ New Project and fill all required details to create a new project Step 2 βˆ’ Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/relativeLayout" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_marginTop="70dp" android:background="#008080" android:padding="5dp" android:text="TutorialsPoint" android:textColor="#fff" android:textSize="24sp" android:textStyle="bold" /> <EditText android:id="@+id/editText" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerInParent="true" android:layout_margin="20dp" android:hint="Enter Email id" /> <Button android:id="@+id/text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/editText" android:layout_centerInParent="true" android:text="Check validation" android:textAlignment="center" android:textColor="#000" android:textSize="18sp" /> </RelativeLayout> Step 3 βˆ’ Add the following code to src/MainActivity.kt import android.os.Bundle import android.widget.Button import android.widget.EditText import android.widget.Toast import androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { lateinit var button: Button lateinit var emailId: EditText var emailPattern = "[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) title = "KotlinApp" button = findViewById(R.id.text) emailId = findViewById(R.id.editText) button.setOnClickListener { if (emailId.text.toString().isEmpty()) { Toast.makeText(applicationContext, "enter email address", Toast.LENGTH_SHORT).show() } else { if (emailId.text.toString().trim { it <= ' ' }.matches(emailPattern.toRegex())) { Toast.makeText(applicationContext, "valid email address", Toast.LENGTH_SHORT).show() } else { Toast.makeText(applicationContext, "Invalid email address", Toast.LENGTH_SHORT).show() } } } } } Step 4 βˆ’ Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.q11"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen
[ { "code": null, "e": 1155, "s": 1062, "text": "This example demonstrates how to validate Email Address in Android on EditText using Kotlin." }, { "code": null, "e": 1283, "s": 1155, "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": 1348, "s": 1283, "text": "Step 2 βˆ’ Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2602, "s": 1348, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:id=\"@+id/relativeLayout\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\">\n <TextView\n android:id=\"@+id/textView\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginTop=\"70dp\"\n android:background=\"#008080\"\n android:padding=\"5dp\"\n android:text=\"TutorialsPoint\"\n android:textColor=\"#fff\"\n android:textSize=\"24sp\"\n android:textStyle=\"bold\" />\n <EditText\n android:id=\"@+id/editText\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"\n android:layout_margin=\"20dp\"\n android:hint=\"Enter Email id\" />\n <Button\n android:id=\"@+id/text\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_below=\"@+id/editText\"\n android:layout_centerInParent=\"true\"\n android:text=\"Check validation\"\n android:textAlignment=\"center\"\n android:textColor=\"#000\"\n android:textSize=\"18sp\" />\n</RelativeLayout>" }, { "code": null, "e": 2657, "s": 2602, "text": "Step 3 βˆ’ Add the following code to src/MainActivity.kt" }, { "code": null, "e": 3811, "s": 2657, "text": "import android.os.Bundle\nimport android.widget.Button\nimport android.widget.EditText\nimport android.widget.Toast\nimport androidx.appcompat.app.AppCompatActivity\nclass MainActivity : AppCompatActivity() {\n lateinit var button: Button\n lateinit var emailId: EditText\n var emailPattern = \"[a-zA-Z0-9._-]+@[a-z]+\\\\.+[a-z]+\"\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n button = findViewById(R.id.text)\n emailId = findViewById(R.id.editText)\n button.setOnClickListener {\n if (emailId.text.toString().isEmpty()) {\n Toast.makeText(applicationContext, \"enter email address\", Toast.LENGTH_SHORT).show()\n }\n else {\n if (emailId.text.toString().trim { it <= ' ' }.matches(emailPattern.toRegex())) {\n Toast.makeText(applicationContext, \"valid email address\", Toast.LENGTH_SHORT).show()\n }\n else {\n Toast.makeText(applicationContext, \"Invalid email address\", Toast.LENGTH_SHORT).show()\n }\n }\n }\n }\n}" }, { "code": null, "e": 3866, "s": 3811, "text": "Step 4 βˆ’ Add the following code to androidManifest.xml" }, { "code": null, "e": 4540, "s": 3866, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"com.example.q11\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 4889, "s": 4540, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen" } ]
How to group data by time intervals in Python Pandas? - GeeksforGeeks
26 Dec, 2020 Prerequisites: Pandas Grouping data by time intervals is very obvious when you come across Time-Series Analysis. A time series is a series of data points indexed (or listed or graphed) in time order. Most commonly, a time series is a sequence taken at successive equally spaced points in time. Pandas provide two very useful functions that we can use to group our data. resample()β€” This function is primarily used for time series data. It is a Convenience method for frequency conversion and resampling of time series. Object must have a datetime-like index (DatetimeIndex, PeriodIndex, or TimedeltaIndex), or pass datetime-like values to the on or level keyword. Resampling generates a unique sampling distribution on the basis of the actual data. Syntax : DataFrame.resample(rule, how=None, axis=0, fill_method=None, closed=None, label=None, convention=’start’, kind=None, loffset=None, limit=None, base=0, on=None, level=None) Parameters : rule : the offset string or object representing target conversion axis : int, optional, default 0 closed : {β€˜right’, β€˜left’} label : {β€˜right’, β€˜left’} convention : For PeriodIndex only, controls whether to use the start or end of rule loffset : Adjust the resampled time labels base : For frequencies that evenly subdivide 1 day, the β€œorigin” of the aggregated intervals. For example, for β€˜5min’ frequency, base could range from 0 through 4. Defaults to 0. on : For a DataFrame, column to use instead of index for resampling. Column must be datetime-like. level : For a MultiIndex, level (name or number) to use for resampling. Level must be datetime-like. Example: quantity added each month, total amount added each year. Grouper β€” Grouper allows the user to specify on what basis the user wants to analyze the data. Syntax: dataframe.groupby(pd.Grouper(key, level, freq, axis, sort, label, convention, base, Ioffset, origin, offset)) Parameters: key: selects the target column to be grouped level: level of the target index freq: groupby a specified frequency if a target column is a datetime-like object axis: name or number of axis sort: to enable sorting label: interval boundary to be used for labeling, valid only when freq parameter is passed. convention: If grouper is PeriodIndex and freq parameter is passed base: works only when freq is passed Ioffset: works only when freq is passed origin: timestamp to adjust grouping on the basis of offset: offset timedelta added to the origin Import module Load or create data Resample the data as required Grouping the data Implementation using this approach is given below: Dataframe in use: timeseries.csv Link: here. Program : Aggregating using resampling Python3 import numpy as npimport pandas as pd # loading datasetdata = pd.read_csv('path of dataset') # setting the index for the datadata = data.set_index(['created_at']) # converting index to datetime indexdata.index = pd.to_datetime(data.index) # Changing start time for each hour, by default start time is at 0th minutedata.resample('W', loffset='30Min30s').price.sum().head(2)data.resample('W', loffset='30Min30s').price.sum().head(2) # we can also aggregate it will show quantity added in each week# as well as the total amount added in each weekdata.resample('W', loffset='30Min30s').agg( {'price': 'sum', 'quantity': 'sum'}).head(5) Output: Program : Grouping the data based on different time intervals In the first part we are grouping like the way we did in resampling (on the basis of days, months, etc.) then we group the data on the basis of store type over a month Then aggregating as we did in resample It will give the quantity added in each week as well as the total amount added in each week. Python3 import numpy as np import pandas as pd # loading dataset data = pd.read_csv(r'path of dataset')# setting the index for the datadata = data.set_index(['created_at'])# converting index to datetime indexdata.index = pd.to_datetime(data.index) # Changing start time for each hour, by default start time is at 0th minutedata.resample('W', loffset='30Min30s').price.sum().head(2)data.resample('W', loffset='30Min30s').price.sum().head(2) data.groupby([pd.Grouper(freq='M'), 'store_type']).agg(total_quantity=('quantity', 'sum'), total_amount=('price', 'sum')).head(5) Output: Picked Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? 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": 24292, "s": 24264, "text": "\n26 Dec, 2020" }, { "code": null, "e": 24314, "s": 24292, "text": "Prerequisites: Pandas" }, { "code": null, "e": 24586, "s": 24314, "text": "Grouping data by time intervals is very obvious when you come across Time-Series Analysis. A time series is a series of data points indexed (or listed or graphed) in time order. Most commonly, a time series is a sequence taken at successive equally spaced points in time." }, { "code": null, "e": 24662, "s": 24586, "text": "Pandas provide two very useful functions that we can use to group our data." }, { "code": null, "e": 25041, "s": 24662, "text": "resample()β€” This function is primarily used for time series data. It is a Convenience method for frequency conversion and resampling of time series. Object must have a datetime-like index (DatetimeIndex, PeriodIndex, or TimedeltaIndex), or pass datetime-like values to the on or level keyword. Resampling generates a unique sampling distribution on the basis of the actual data." }, { "code": null, "e": 25222, "s": 25041, "text": "Syntax : DataFrame.resample(rule, how=None, axis=0, fill_method=None, closed=None, label=None, convention=’start’, kind=None, loffset=None, limit=None, base=0, on=None, level=None)" }, { "code": null, "e": 25235, "s": 25222, "text": "Parameters :" }, { "code": null, "e": 25301, "s": 25235, "text": "rule : the offset string or object representing target conversion" }, { "code": null, "e": 25333, "s": 25301, "text": "axis : int, optional, default 0" }, { "code": null, "e": 25360, "s": 25333, "text": "closed : {β€˜right’, β€˜left’}" }, { "code": null, "e": 25386, "s": 25360, "text": "label : {β€˜right’, β€˜left’}" }, { "code": null, "e": 25470, "s": 25386, "text": "convention : For PeriodIndex only, controls whether to use the start or end of rule" }, { "code": null, "e": 25513, "s": 25470, "text": "loffset : Adjust the resampled time labels" }, { "code": null, "e": 25692, "s": 25513, "text": "base : For frequencies that evenly subdivide 1 day, the β€œorigin” of the aggregated intervals. For example, for β€˜5min’ frequency, base could range from 0 through 4. Defaults to 0." }, { "code": null, "e": 25791, "s": 25692, "text": "on : For a DataFrame, column to use instead of index for resampling. Column must be datetime-like." }, { "code": null, "e": 25892, "s": 25791, "text": "level : For a MultiIndex, level (name or number) to use for resampling. Level must be datetime-like." }, { "code": null, "e": 25958, "s": 25892, "text": "Example: quantity added each month, total amount added each year." }, { "code": null, "e": 26053, "s": 25958, "text": "Grouper β€” Grouper allows the user to specify on what basis the user wants to analyze the data." }, { "code": null, "e": 26171, "s": 26053, "text": "Syntax: dataframe.groupby(pd.Grouper(key, level, freq, axis, sort, label, convention, base, Ioffset, origin, offset))" }, { "code": null, "e": 26183, "s": 26171, "text": "Parameters:" }, { "code": null, "e": 26228, "s": 26183, "text": "key: selects the target column to be grouped" }, { "code": null, "e": 26261, "s": 26228, "text": "level: level of the target index" }, { "code": null, "e": 26342, "s": 26261, "text": "freq: groupby a specified frequency if a target column is a datetime-like object" }, { "code": null, "e": 26371, "s": 26342, "text": "axis: name or number of axis" }, { "code": null, "e": 26395, "s": 26371, "text": "sort: to enable sorting" }, { "code": null, "e": 26487, "s": 26395, "text": "label: interval boundary to be used for labeling, valid only when freq parameter is passed." }, { "code": null, "e": 26554, "s": 26487, "text": "convention: If grouper is PeriodIndex and freq parameter is passed" }, { "code": null, "e": 26591, "s": 26554, "text": "base: works only when freq is passed" }, { "code": null, "e": 26631, "s": 26591, "text": "Ioffset: works only when freq is passed" }, { "code": null, "e": 26684, "s": 26631, "text": "origin: timestamp to adjust grouping on the basis of" }, { "code": null, "e": 26729, "s": 26684, "text": "offset: offset timedelta added to the origin" }, { "code": null, "e": 26743, "s": 26729, "text": "Import module" }, { "code": null, "e": 26763, "s": 26743, "text": "Load or create data" }, { "code": null, "e": 26793, "s": 26763, "text": "Resample the data as required" }, { "code": null, "e": 26811, "s": 26793, "text": "Grouping the data" }, { "code": null, "e": 26862, "s": 26811, "text": "Implementation using this approach is given below:" }, { "code": null, "e": 26895, "s": 26862, "text": "Dataframe in use: timeseries.csv" }, { "code": null, "e": 26907, "s": 26895, "text": "Link: here." }, { "code": null, "e": 26947, "s": 26907, "text": "Program : Aggregating using resampling " }, { "code": null, "e": 26955, "s": 26947, "text": "Python3" }, { "code": "import numpy as npimport pandas as pd # loading datasetdata = pd.read_csv('path of dataset') # setting the index for the datadata = data.set_index(['created_at']) # converting index to datetime indexdata.index = pd.to_datetime(data.index) # Changing start time for each hour, by default start time is at 0th minutedata.resample('W', loffset='30Min30s').price.sum().head(2)data.resample('W', loffset='30Min30s').price.sum().head(2) # we can also aggregate it will show quantity added in each week# as well as the total amount added in each weekdata.resample('W', loffset='30Min30s').agg( {'price': 'sum', 'quantity': 'sum'}).head(5)", "e": 27596, "s": 26955, "text": null }, { "code": null, "e": 27604, "s": 27596, "text": "Output:" }, { "code": null, "e": 27666, "s": 27604, "text": "Program : Grouping the data based on different time intervals" }, { "code": null, "e": 27966, "s": 27666, "text": "In the first part we are grouping like the way we did in resampling (on the basis of days, months, etc.) then we group the data on the basis of store type over a month Then aggregating as we did in resample It will give the quantity added in each week as well as the total amount added in each week." }, { "code": null, "e": 27974, "s": 27966, "text": "Python3" }, { "code": "import numpy as np import pandas as pd # loading dataset data = pd.read_csv(r'path of dataset')# setting the index for the datadata = data.set_index(['created_at'])# converting index to datetime indexdata.index = pd.to_datetime(data.index) # Changing start time for each hour, by default start time is at 0th minutedata.resample('W', loffset='30Min30s').price.sum().head(2)data.resample('W', loffset='30Min30s').price.sum().head(2) data.groupby([pd.Grouper(freq='M'), 'store_type']).agg(total_quantity=('quantity', 'sum'), total_amount=('price', 'sum')).head(5)", "e": 28596, "s": 27974, "text": null }, { "code": null, "e": 28604, "s": 28596, "text": "Output:" }, { "code": null, "e": 28611, "s": 28604, "text": "Picked" }, { "code": null, "e": 28625, "s": 28611, "text": "Python-pandas" }, { "code": null, "e": 28632, "s": 28625, "text": "Python" }, { "code": null, "e": 28730, "s": 28632, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28762, "s": 28730, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28804, "s": 28762, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28860, "s": 28804, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28902, "s": 28860, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28933, "s": 28902, "text": "Python | os.path.join() method" }, { "code": null, "e": 28988, "s": 28933, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 29010, "s": 28988, "text": "Defaultdict in Python" }, { "code": null, "e": 29049, "s": 29010, "text": "Python | Get unique values from a list" }, { "code": null, "e": 29078, "s": 29049, "text": "Create a directory in Python" } ]
Tryit Editor v3.7
CSS Math Functions Tryit: Using the max() function
[ { "code": null, "e": 28, "s": 9, "text": "CSS Math Functions" } ]
The netrc file processing using Python
The netrc class in python is used to read the data from the .netrc file presnt in unix systems in user’s home firectory. These are hidden files containing user’s login credential details. This is helpful for tool slike ftp, curl etc to successfully read the ,netrc file and use it for their actions. The below program shows how we can read the .netrc file using python’s netrc module. import netrc netrc = netrc.netrc() remoteHostName = "hostname" authTokens = netrc.authenticators(remoteHostName) # Print the access tokens print("Remote Host Name:%s" % (remoteHostName)) print("User Name at remote host:%s" % (authTokens[0])) print("Account Password:%s" % (authTokens[1])) print("Password for the user name at remote host:%s" % (authTokens[2])) # print the macros macroDictionary = netrc.macros print(macroDictionary) Running the above code gives us the following result βˆ’ Remote Host Name:hostname User Name at remote host:xxx Account Password: XXX Password for the user name at remote host:XXXXXX
[ { "code": null, "e": 1362, "s": 1062, "text": "The netrc class in python is used to read the data from the .netrc file presnt in unix systems in user’s home firectory. These are hidden files containing user’s login credential details. This is helpful for tool slike ftp, curl etc to successfully read the ,netrc file and use it for their actions." }, { "code": null, "e": 1447, "s": 1362, "text": "The below program shows how we can read the .netrc file using python’s netrc module." }, { "code": null, "e": 1881, "s": 1447, "text": "import netrc\nnetrc = netrc.netrc()\nremoteHostName = \"hostname\"\nauthTokens = netrc.authenticators(remoteHostName)\n# Print the access tokens\nprint(\"Remote Host Name:%s\" % (remoteHostName))\nprint(\"User Name at remote host:%s\" % (authTokens[0]))\nprint(\"Account Password:%s\" % (authTokens[1]))\nprint(\"Password for the user name at remote host:%s\" % (authTokens[2]))\n# print the macros\nmacroDictionary = netrc.macros\nprint(macroDictionary)" }, { "code": null, "e": 1936, "s": 1881, "text": "Running the above code gives us the following result βˆ’" }, { "code": null, "e": 2062, "s": 1936, "text": "Remote Host Name:hostname\nUser Name at remote host:xxx\nAccount Password: XXX\nPassword for the user name at remote host:XXXXXX" } ]
Data Structure and Algorithms - Shell Sort
Shell sort is a highly efficient sorting algorithm and is based on insertion sort algorithm. This algorithm avoids large shifts as in case of insertion sort, if the smaller value is to the far right and has to be moved to the far left. This algorithm uses insertion sort on a widely spread elements, first to sort them and then sorts the less widely spaced elements. This spacing is termed as interval. This interval is calculated based on Knuth's formula as βˆ’ h = h * 3 + 1 where βˆ’ h is interval with initial value 1 This algorithm is quite efficient for medium-sized data sets as its average and worst-case complexity of this algorithm depends on the gap sequence the best known is Ο(n), where n is the number of items. And the worst case space complexity is O(n). Let us consider the following example to have an idea of how shell sort works. We take the same array we have used in our previous examples. For our example and ease of understanding, we take the interval of 4. Make a virtual sub-list of all values located at the interval of 4 positions. Here these values are {35, 14}, {33, 19}, {42, 27} and {10, 44} We compare values in each sub-list and swap them (if necessary) in the original array. After this step, the new array should look like this βˆ’ Then, we take interval of 1 and this gap generates two sub-lists - {14, 27, 35, 42}, {19, 10, 33, 44} We compare and swap the values, if required, in the original array. After this step, the array should look like this βˆ’ Finally, we sort the rest of the array using interval of value 1. Shell sort uses insertion sort to sort the array. Following is the step-by-step depiction βˆ’ We see that it required only four swaps to sort the rest of the array. Following is the algorithm for shell sort. Step 1 βˆ’ Initialize the value of h Step 2 βˆ’ Divide the list into smaller sub-list of equal interval h Step 3 βˆ’ Sort these sub-lists using insertion sort Step 3 βˆ’ Repeat until complete list is sorted Following is the pseudocode for shell sort. procedure shellSort() A : array of items /* calculate interval*/ while interval < A.length /3 do: interval = interval * 3 + 1 end while while interval > 0 do: for outer = interval; outer < A.length; outer ++ do: /* select value to be inserted */ valueToInsert = A[outer] inner = outer; /*shift element towards right*/ while inner > interval -1 && A[inner - interval] >= valueToInsert do: A[inner] = A[inner - interval] inner = inner - interval end while /* insert the number at hole position */ A[inner] = valueToInsert end for /* calculate interval*/ interval = (interval -1) /3; end while end procedure To know about shell sort implementation in C programming language, please click here. 42 Lectures 1.5 hours Ravi Kiran 141 Lectures 13 hours Arnab Chakraborty 26 Lectures 8.5 hours Parth Panjabi 65 Lectures 6 hours Arnab Chakraborty 75 Lectures 13 hours Eduonix Learning Solutions 64 Lectures 10.5 hours Eduonix Learning Solutions Print Add Notes Bookmark this page
[ { "code": null, "e": 2816, "s": 2580, "text": "Shell sort is a highly efficient sorting algorithm and is based on insertion sort algorithm. This algorithm avoids large shifts as in case of insertion sort, if the smaller value is to the far right and has to be moved to the far left." }, { "code": null, "e": 3041, "s": 2816, "text": "This algorithm uses insertion sort on a widely spread elements, first to sort them and then sorts the less widely spaced elements. This spacing is termed as interval. This interval is calculated based on Knuth's formula as βˆ’" }, { "code": null, "e": 3102, "s": 3041, "text": "h = h * 3 + 1\nwhere βˆ’\n h is interval with initial value 1\n" }, { "code": null, "e": 3351, "s": 3102, "text": "This algorithm is quite efficient for medium-sized data sets as its average and worst-case complexity of this algorithm depends on the gap sequence the best known is Ο(n), where n is the number of items. And the worst case space complexity is O(n)." }, { "code": null, "e": 3704, "s": 3351, "text": "Let us consider the following example to have an idea of how shell sort works. We take the same array we have used in our previous examples. For our example and ease of understanding, we take the interval of 4. Make a virtual sub-list of all values located at the interval of 4 positions. Here these values are {35, 14}, {33, 19}, {42, 27} and {10, 44}" }, { "code": null, "e": 3846, "s": 3704, "text": "We compare values in each sub-list and swap them (if necessary) in the original array. After this step, the new array should look like this βˆ’" }, { "code": null, "e": 3948, "s": 3846, "text": "Then, we take interval of 1 and this gap generates two sub-lists - {14, 27, 35, 42}, {19, 10, 33, 44}" }, { "code": null, "e": 4067, "s": 3948, "text": "We compare and swap the values, if required, in the original array. After this step, the array should look like this βˆ’" }, { "code": null, "e": 4183, "s": 4067, "text": "Finally, we sort the rest of the array using interval of value 1. Shell sort uses insertion sort to sort the array." }, { "code": null, "e": 4225, "s": 4183, "text": "Following is the step-by-step depiction βˆ’" }, { "code": null, "e": 4296, "s": 4225, "text": "We see that it required only four swaps to sort the rest of the array." }, { "code": null, "e": 4339, "s": 4296, "text": "Following is the algorithm for shell sort." }, { "code": null, "e": 4539, "s": 4339, "text": "Step 1 βˆ’ Initialize the value of h\nStep 2 βˆ’ Divide the list into smaller sub-list of equal interval h\nStep 3 βˆ’ Sort these sub-lists using insertion sort\nStep 3 βˆ’ Repeat until complete list is sorted\n" }, { "code": null, "e": 4583, "s": 4539, "text": "Following is the pseudocode for shell sort." }, { "code": null, "e": 5337, "s": 4583, "text": "procedure shellSort()\n A : array of items \n\t\n /* calculate interval*/\n while interval < A.length /3 do:\n interval = interval * 3 + 1\t \n end while\n \n while interval > 0 do:\n\n for outer = interval; outer < A.length; outer ++ do:\n\n /* select value to be inserted */\n valueToInsert = A[outer]\n inner = outer;\n\n /*shift element towards right*/\n while inner > interval -1 && A[inner - interval] >= valueToInsert do:\n A[inner] = A[inner - interval]\n inner = inner - interval\n end while\n\n /* insert the number at hole position */\n A[inner] = valueToInsert\n\n end for\n\n /* calculate interval*/\n interval = (interval -1) /3;\t \n\n end while\n \nend procedure" }, { "code": null, "e": 5423, "s": 5337, "text": "To know about shell sort implementation in C programming language, please click here." }, { "code": null, "e": 5458, "s": 5423, "text": "\n 42 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5470, "s": 5458, "text": " Ravi Kiran" }, { "code": null, "e": 5505, "s": 5470, "text": "\n 141 Lectures \n 13 hours \n" }, { "code": null, "e": 5524, "s": 5505, "text": " Arnab Chakraborty" }, { "code": null, "e": 5559, "s": 5524, "text": "\n 26 Lectures \n 8.5 hours \n" }, { "code": null, "e": 5574, "s": 5559, "text": " Parth Panjabi" }, { "code": null, "e": 5607, "s": 5574, "text": "\n 65 Lectures \n 6 hours \n" }, { "code": null, "e": 5626, "s": 5607, "text": " Arnab Chakraborty" }, { "code": null, "e": 5660, "s": 5626, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 5688, "s": 5660, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 5724, "s": 5688, "text": "\n 64 Lectures \n 10.5 hours \n" }, { "code": null, "e": 5752, "s": 5724, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 5759, "s": 5752, "text": " Print" }, { "code": null, "e": 5770, "s": 5759, "text": " Add Notes" } ]
Creating Deep Neural Networks from Scratch, an Introduction to Reinforcement Learning | by Abhav Kedia | Towards Data Science
This post is the first of a three part series that will give a detailed walk-through of a solution to the Cartpole-v1 problem on OpenAI gym β€” using only numpy from the python libraries. This solution is far from an optimal solution (you can find those on the gym website), but rather is focused on doing it from first principles. Pre-requisites for running the code in this article are python (3.x), with gym and numpy modules installed. When I first started looking at reinforcement learning in the OpenAI gym, I was unable to find any good resources on how to begin building the solution myself. There are very powerful libraries (like Tensorflow and Pytorch) that allow you to build incredibly complex neural networks and solve the cartpole problem easily, but I wanted to create the neural networks from scratch, as I believe there is value in understanding the core building blocks of modern machine learning techniques. I’m writing what I wish I had been able to find when I was trying to work on this. So let’s get started. First, what is OpenAI gym? There is a good, short intro on their website, β€œGym is a toolkit for developing and comparing reinforcement learning algorithms.” β€œThe gym library is a collection of test problems β€” environments β€” that you can use to work out your reinforcement learning algorithms. These environments have a shared interface, allowing you to write general algorithms.” What this means is that the engineering around building and rendering models that simulate real world scenarios is already done for us, so we can just focus on teaching an agent to play the game well. The description above also mentions reinforcement learning. What is that? Here’s a wikipedia summaryβ€” β€œReinforcement learning is an area of machine learning concerned with how software agents ought to take actions in an environment in order to maximize some notion of cumulative reward.” To give you an analogy, think about how a dog is trained β€” favorable actions are positively reinforced (in the form of a treat) and negative actions are negatively reinforced. In a way even we, humans, are complex reinforcement learning agents trying to maximize the chance of achieving our goals by selecting actions that we think will β€˜benefit’ us (in the form of greater reward) in the future. Here’s a figure that illustrates the cycle in reinforcement learning, The above figure shows an agent (the program that we will build) taking as inputs the state of the environment and reward from the previous action, selecting a subsequent action and feeding that back to the environment, before observing the environment once again. Great, now that we have an understanding of the basic concepts in reinforcement learning, let’s go back the problem we are trying to solve β€” Cartpole. To begin with, take a look at the documentation for the Cartpole problem specifically. The documentation gives a good overview of what we are trying to achieve. In a nutshell, we are in control of the base of a slider with a pole balanced vertically on top. Our goal is to prevent the pole from falling off for as long as possible. If the pole falls (in terms of its angle) below a certain point, the environment is reset. Below is a random agent working on the cartpole problem. As you can see, it’s not very good! But that is expected, since this agent disregards the current state of the environment and selects a random action at every time step. Let’s see if we can do better. Time for some code! We’ll start by importing the libraries that we will be using. We will need gym for the OpenAI environments as discussed above, and numpy for some math and matrix manipulations. import gymimport numpy as np Next, we need to import the environment that gym provides for the cartpole problem. Here’s how this is done: env=gym.make('CartPole-v1') We can also observe some of the features of this particular environment space by printing them: print(env.action_space) # Discrete(2)print(env.observation_space) # Box(4,) There is much more information about environments and their workings in the docs, but the values above capture the basic elements that define this environment β€” the actions that can be performed, and the observations at every time step. The action space is discrete and contains 2 values: 0 and 1. These correspond with the two actions that the agent is able to perform, i.e. push the slider towards the left or towards the right. The observation space on the other hand is continuous and has four components (not to be thrown off with the data structure Box(4,) , for our purposes it just means an array containing four values). What do the four values mean? They are numbers that represent the state of the environment at that time β€” namely, the position of cart, the velocity of cart, the angle of pole, and the rotation rate of the pole. [https://github.com/openai/gym/issues/238#issuecomment-231129955] A fundamental thing to understand here is that the meaning of the numbers in the observation and action spaces is explained only for completeness and our goal is not to interpret the values (of either the action space or the observation space) but let the agent learn the meaning of these values in context. Let us get back to our program and add code to get a basic loop running. # Global variablesNUM_EPISODES = 10MAX_TIMESTEPS = 1000# The main program loopfor i_episode in range(NUM_EPISODES): observation = env.reset() # Iterating through time steps within an episode for t in range(MAX_TIMESTEPS): env.render() action = env.action_space.sample() observation, reward, done, info = env.step(action) if done: # If the pole has tipped over, end this episode break The code above declares a main program loop for the episodes and iterates through the time steps within an episode. In the internal loop, the program takes an action, observes the result and then checks if the episode has concluded (either the pole has fallen over or the slider has gone off the edge). If it has, the environment is reset and the internal loop starts over. The line that selects the action is randomly sampling it from the available actions; in fact, it behaves exactly like the random agent shown earlier. Let’s change that to define a custom method for selecting the action given the observation. Now, we will define an agent that is (hopefully!) going to learn to be smarter in picking its actions given a state. We will model this agent in a class: class RLAgent: env = None def __init__(self, env): self.env = env def select_action(self, observation): return env.action_space.sample() We also need to add an instance of RLAgent to our global variables and change the action selection to call this function from the instantiated class. Note that at present the select_action function does the same thing as before, but we will change that later. We will now create the elements of our neural net. A quick primer on neural networks: β€œAn ANN (Artificial Neural Network) is a collection of connected units or nodes called artificial neurons, which loosely model the neurons in a biological brain. Each connection, like the synapses in a biological brain, can transmit a signal to other neurons. An artificial neuron that receives a signal then processes it and can signal neurons connected to it.” This is what ours will look like, The above picture captures a neural network that has one input layer, two β€˜hidden’ layers (layers 2 & 3) and an output layer. The model provides inputs from the observation space to the input layer, these are β€˜fed forward’ to subsequent layers until the output layer, where the values in the output layer are used to select the action. For instance, every node in layer 3 is a linear combination (weighted sum) of layer 2 passed through an activation function. The weights used to calculate layer 3 are initialized randomly in a matrix and gradually tuned through a process called stochastic gradient descent to better predict the outputs. The activation function is a simple non-linear function that allows the classifier to learn non-linear rules in the underlying observation space. In our CartPole problem, there are 5 inputs (the elements of the observation space + a bias term) and 2 outputs (the two directions in which we can push the cart). The neural net layers are going to be encapsulated in an NNLayer class, class NNLayer: # class representing a neural net layer def __init__(self, input_size, output_size, activation=None, lr = 0.001): self.input_size = input_size self.output_size = output_size self.weights = np.random.uniform(low=-0.5, high=0.5, size=(input_size, output_size)) self.activation_function = activation self.lr = lr This class captures three major things: The dimensions (input and output sizes) of the layer.The weights that connect the input layer to the output layer.The activation function for the output (the default activation is None, aka Linear). The dimensions (input and output sizes) of the layer. The weights that connect the input layer to the output layer. The activation function for the output (the default activation is None, aka Linear). We will now add the usage of this class to our RLAgent. First, we’ll edit the select action function, def select_action(self, observation): values = self.forward(observation) if (np.random.random() > self.epsilon): return np.argmax(values) else: return np.random.randint(self.env.action_space.n) Instead of randomly selecting a value every time, this function passes the information about the state of the environment to our neural network and calculates the β€˜expected reward’ for each action (values is a function that takes in a (1,nin) array and returns a (1,nout) array). It then selects the action that will lead to the greatest expected reward. Note that this function still selects a random value with probability epsilon. Epsilon, also known as the β€˜rate of exploration’ is the implementation of an important concept in reinforcement learning: the tradeoff between exploration and exploitation. Exploration helps the model to not get stuck in a local minimum, by exploring apparently sub-optimal actions from time to time that may reveal greater rewards further down the road. Exploitation on the other hand allows the agent to use its knowledge of the current state to select the most profitable action. In most RL agents, epsilon starts out high (near 1.0) in the beginning and is gradually reduced to 0 over time as the agent becomes more confident in the learnt values of actions in a given state. The select_action function also calls self.forward (RLAgent.Forward), and here’s the code for that function, def forward(self, observation, remember_for_backprop=True): vals = np.copy(observation) index = 0 for layer in self.layers: vals = layer.forward(vals, remember_for_backprop) index = index + 1 return vals The RLAgent.forward function above has a simple loop. It passes the input (the observation for which we are trying to decide on a course of action) to the network and obtains a set of values for each action. It internally calls the NNLayer.forward function, collecting the output from each layer and passing it to the next layer. To complete the implementation of the select action function, here is the last piece β€” the NNLayer.forward function. The remember_for_backprop parameter is a boolean that specifies whether or not certain calculated values need to be stored in order to prevent double calculation during the weight updates (this will be explained in more detail in the section on backpropagation). # Compute the forward pass for this layerdef forward(self, inputs, remember_for_backprop=True): input_with_bias = np.append(np.ones((len(inputs),1)),inputs, axis=1) unactivated = np.dot(input_with_bias, self.weights) output = unactivated if self.activation_function != None: output = self.activation_function(output) if remember_for_backprop: # store variables for backward pass self.backward_store_in = input_with_bias self.backward_store_out = np.copy(unactivated) return output This function β€” Appends a bias term to the input.Calculates the product of the input and the weight matrix at this layer.Takes the output of step 2, and sends this through an activation function if one has been defined for this layer (which in our case will be ReLU). Appends a bias term to the input. Calculates the product of the input and the weight matrix at this layer. Takes the output of step 2, and sends this through an activation function if one has been defined for this layer (which in our case will be ReLU). Let’s also add the instantiation for these layers in the RLAgent’s init function, def __init__(self, env): self.env = env self.hidden_size = 24 self.input_size = env.observation_space.shape[0] self.output_size = env.action_space.n self.num_hidden_layers = 2 self.epsilon = 1.0 self.layers = [NNLayer(self.input_size + 1, self.hidden_size, activation=relu)] for i in range(self.num_hidden_layers-1): self.layers.append(NNLayer(self.hidden_size+1, self.hidden_size, activation=relu)) self.layers.append(NNLayer(self.hidden_size+1, self.output_size)) You can see above that we have a total of 2 hidden layers and 1 output layer. Also, in all but the output layer we are using an activation function called Rectified Linear Unit (ReLU). This function is an extremely simple function that introduces sufficient non-linearity to our neural network. Here is the implementation for it, def relu(mat): return np.multiply(mat,(mat>0)) This function takes in a matrix and returns another matrix that has identical values where the original matrix was greater than 0, and 0 in all other values. Finally, let’s add the initialization of our agent and epsilon decay to our main program loop. This is what the new main program looks like: # Global variablesNUM_EPISODES = 10MAX_TIMESTEPS = 1000model = RLAgent(env)# The main program loopfor i_episode in range(NUM_EPISODES): observation = env.reset() # Iterating through time steps within an episode for t in range(MAX_TIMESTEPS): env.render() action = model.select_action(observation) observation, reward, done, info = env.step(action) # epsilon decay model.epsilon = model.epsilon if model.epsilon < 0.01 else model.epsilon*0.995 if done: # If the pole has tipped over, end this episode print('Episode {} ended after {} timesteps, current exploration is {}'.format(i_episode, t+1,model.epsilon)) break What does this model do currently? It initializes the weights for the neural network randomly and calculates values for actions in any given state based on these weights. However, we need a way for the function to improve the values of the weights in the network such that the agent is able to take the best action in any given state. As alluded to earlier, this is achieved through stochastic gradient descent and implemented via a technique called backpropagation. I will go into detail about backpropagation along with relevant theory of reinforcement learning in the next post. To summarize, this is what we have accomplished so far: Wrote the main program components for interacting with the environment space of CartPole in OpenAI gym.Encapsulated the Reinforcement Learning agent and its component Neural Net layers in their respective classes.Coded and initialized the neural network architecture for our deep learning reinforcement learning agent.Implemented the β€˜feed forward’ computation to propagate an observation of the environment through the neural network to calculate action values. Wrote the main program components for interacting with the environment space of CartPole in OpenAI gym. Encapsulated the Reinforcement Learning agent and its component Neural Net layers in their respective classes. Coded and initialized the neural network architecture for our deep learning reinforcement learning agent. Implemented the β€˜feed forward’ computation to propagate an observation of the environment through the neural network to calculate action values. In the next post, we will aim to achieve the following: Examine and formalize a notion of the β€˜cumulative reward’ that an agent expects to receive in a particular state for the Cartpole problem.Understand how an agent should update the weights in the neural network to get closer to its idea the correct cumulative rewards expected from taking a particular action in a particular state.Implement backpropagation β€” the algorithm that achieves the goal mentioned in 2 above. Examine and formalize a notion of the β€˜cumulative reward’ that an agent expects to receive in a particular state for the Cartpole problem. Understand how an agent should update the weights in the neural network to get closer to its idea the correct cumulative rewards expected from taking a particular action in a particular state. Implement backpropagation β€” the algorithm that achieves the goal mentioned in 2 above. See you next time!
[ { "code": null, "e": 609, "s": 171, "text": "This post is the first of a three part series that will give a detailed walk-through of a solution to the Cartpole-v1 problem on OpenAI gym β€” using only numpy from the python libraries. This solution is far from an optimal solution (you can find those on the gym website), but rather is focused on doing it from first principles. Pre-requisites for running the code in this article are python (3.x), with gym and numpy modules installed." }, { "code": null, "e": 1202, "s": 609, "text": "When I first started looking at reinforcement learning in the OpenAI gym, I was unable to find any good resources on how to begin building the solution myself. There are very powerful libraries (like Tensorflow and Pytorch) that allow you to build incredibly complex neural networks and solve the cartpole problem easily, but I wanted to create the neural networks from scratch, as I believe there is value in understanding the core building blocks of modern machine learning techniques. I’m writing what I wish I had been able to find when I was trying to work on this. So let’s get started." }, { "code": null, "e": 1783, "s": 1202, "text": "First, what is OpenAI gym? There is a good, short intro on their website, β€œGym is a toolkit for developing and comparing reinforcement learning algorithms.” β€œThe gym library is a collection of test problems β€” environments β€” that you can use to work out your reinforcement learning algorithms. These environments have a shared interface, allowing you to write general algorithms.” What this means is that the engineering around building and rendering models that simulate real world scenarios is already done for us, so we can just focus on teaching an agent to play the game well." }, { "code": null, "e": 2071, "s": 1783, "text": "The description above also mentions reinforcement learning. What is that? Here’s a wikipedia summaryβ€” β€œReinforcement learning is an area of machine learning concerned with how software agents ought to take actions in an environment in order to maximize some notion of cumulative reward.”" }, { "code": null, "e": 2538, "s": 2071, "text": "To give you an analogy, think about how a dog is trained β€” favorable actions are positively reinforced (in the form of a treat) and negative actions are negatively reinforced. In a way even we, humans, are complex reinforcement learning agents trying to maximize the chance of achieving our goals by selecting actions that we think will β€˜benefit’ us (in the form of greater reward) in the future. Here’s a figure that illustrates the cycle in reinforcement learning," }, { "code": null, "e": 2803, "s": 2538, "text": "The above figure shows an agent (the program that we will build) taking as inputs the state of the environment and reward from the previous action, selecting a subsequent action and feeding that back to the environment, before observing the environment once again." }, { "code": null, "e": 3434, "s": 2803, "text": "Great, now that we have an understanding of the basic concepts in reinforcement learning, let’s go back the problem we are trying to solve β€” Cartpole. To begin with, take a look at the documentation for the Cartpole problem specifically. The documentation gives a good overview of what we are trying to achieve. In a nutshell, we are in control of the base of a slider with a pole balanced vertically on top. Our goal is to prevent the pole from falling off for as long as possible. If the pole falls (in terms of its angle) below a certain point, the environment is reset. Below is a random agent working on the cartpole problem." }, { "code": null, "e": 3636, "s": 3434, "text": "As you can see, it’s not very good! But that is expected, since this agent disregards the current state of the environment and selects a random action at every time step. Let’s see if we can do better." }, { "code": null, "e": 3833, "s": 3636, "text": "Time for some code! We’ll start by importing the libraries that we will be using. We will need gym for the OpenAI environments as discussed above, and numpy for some math and matrix manipulations." }, { "code": null, "e": 3862, "s": 3833, "text": "import gymimport numpy as np" }, { "code": null, "e": 3971, "s": 3862, "text": "Next, we need to import the environment that gym provides for the cartpole problem. Here’s how this is done:" }, { "code": null, "e": 3999, "s": 3971, "text": "env=gym.make('CartPole-v1')" }, { "code": null, "e": 4095, "s": 3999, "text": "We can also observe some of the features of this particular environment space by printing them:" }, { "code": null, "e": 4171, "s": 4095, "text": "print(env.action_space) # Discrete(2)print(env.observation_space) # Box(4,)" }, { "code": null, "e": 4408, "s": 4171, "text": "There is much more information about environments and their workings in the docs, but the values above capture the basic elements that define this environment β€” the actions that can be performed, and the observations at every time step." }, { "code": null, "e": 4602, "s": 4408, "text": "The action space is discrete and contains 2 values: 0 and 1. These correspond with the two actions that the agent is able to perform, i.e. push the slider towards the left or towards the right." }, { "code": null, "e": 5079, "s": 4602, "text": "The observation space on the other hand is continuous and has four components (not to be thrown off with the data structure Box(4,) , for our purposes it just means an array containing four values). What do the four values mean? They are numbers that represent the state of the environment at that time β€” namely, the position of cart, the velocity of cart, the angle of pole, and the rotation rate of the pole. [https://github.com/openai/gym/issues/238#issuecomment-231129955]" }, { "code": null, "e": 5460, "s": 5079, "text": "A fundamental thing to understand here is that the meaning of the numbers in the observation and action spaces is explained only for completeness and our goal is not to interpret the values (of either the action space or the observation space) but let the agent learn the meaning of these values in context. Let us get back to our program and add code to get a basic loop running." }, { "code": null, "e": 5903, "s": 5460, "text": "# Global variablesNUM_EPISODES = 10MAX_TIMESTEPS = 1000# The main program loopfor i_episode in range(NUM_EPISODES): observation = env.reset() # Iterating through time steps within an episode for t in range(MAX_TIMESTEPS): env.render() action = env.action_space.sample() observation, reward, done, info = env.step(action) if done: # If the pole has tipped over, end this episode break" }, { "code": null, "e": 6277, "s": 5903, "text": "The code above declares a main program loop for the episodes and iterates through the time steps within an episode. In the internal loop, the program takes an action, observes the result and then checks if the episode has concluded (either the pole has fallen over or the slider has gone off the edge). If it has, the environment is reset and the internal loop starts over." }, { "code": null, "e": 6519, "s": 6277, "text": "The line that selects the action is randomly sampling it from the available actions; in fact, it behaves exactly like the random agent shown earlier. Let’s change that to define a custom method for selecting the action given the observation." }, { "code": null, "e": 6673, "s": 6519, "text": "Now, we will define an agent that is (hopefully!) going to learn to be smarter in picking its actions given a state. We will model this agent in a class:" }, { "code": null, "e": 6841, "s": 6673, "text": "class RLAgent: env = None def __init__(self, env): self.env = env def select_action(self, observation): return env.action_space.sample()" }, { "code": null, "e": 7101, "s": 6841, "text": "We also need to add an instance of RLAgent to our global variables and change the action selection to call this function from the instantiated class. Note that at present the select_action function does the same thing as before, but we will change that later." }, { "code": null, "e": 7550, "s": 7101, "text": "We will now create the elements of our neural net. A quick primer on neural networks: β€œAn ANN (Artificial Neural Network) is a collection of connected units or nodes called artificial neurons, which loosely model the neurons in a biological brain. Each connection, like the synapses in a biological brain, can transmit a signal to other neurons. An artificial neuron that receives a signal then processes it and can signal neurons connected to it.”" }, { "code": null, "e": 7584, "s": 7550, "text": "This is what ours will look like," }, { "code": null, "e": 7920, "s": 7584, "text": "The above picture captures a neural network that has one input layer, two β€˜hidden’ layers (layers 2 & 3) and an output layer. The model provides inputs from the observation space to the input layer, these are β€˜fed forward’ to subsequent layers until the output layer, where the values in the output layer are used to select the action." }, { "code": null, "e": 8370, "s": 7920, "text": "For instance, every node in layer 3 is a linear combination (weighted sum) of layer 2 passed through an activation function. The weights used to calculate layer 3 are initialized randomly in a matrix and gradually tuned through a process called stochastic gradient descent to better predict the outputs. The activation function is a simple non-linear function that allows the classifier to learn non-linear rules in the underlying observation space." }, { "code": null, "e": 8534, "s": 8370, "text": "In our CartPole problem, there are 5 inputs (the elements of the observation space + a bias term) and 2 outputs (the two directions in which we can push the cart)." }, { "code": null, "e": 8606, "s": 8534, "text": "The neural net layers are going to be encapsulated in an NNLayer class," }, { "code": null, "e": 8978, "s": 8606, "text": "class NNLayer: # class representing a neural net layer def __init__(self, input_size, output_size, activation=None, lr = 0.001): self.input_size = input_size self.output_size = output_size self.weights = np.random.uniform(low=-0.5, high=0.5, size=(input_size, output_size)) self.activation_function = activation self.lr = lr" }, { "code": null, "e": 9018, "s": 8978, "text": "This class captures three major things:" }, { "code": null, "e": 9217, "s": 9018, "text": "The dimensions (input and output sizes) of the layer.The weights that connect the input layer to the output layer.The activation function for the output (the default activation is None, aka Linear)." }, { "code": null, "e": 9271, "s": 9217, "text": "The dimensions (input and output sizes) of the layer." }, { "code": null, "e": 9333, "s": 9271, "text": "The weights that connect the input layer to the output layer." }, { "code": null, "e": 9418, "s": 9333, "text": "The activation function for the output (the default activation is None, aka Linear)." }, { "code": null, "e": 9520, "s": 9418, "text": "We will now add the usage of this class to our RLAgent. First, we’ll edit the select action function," }, { "code": null, "e": 9757, "s": 9520, "text": "def select_action(self, observation): values = self.forward(observation) if (np.random.random() > self.epsilon): return np.argmax(values) else: return np.random.randint(self.env.action_space.n)" }, { "code": null, "e": 10871, "s": 9757, "text": "Instead of randomly selecting a value every time, this function passes the information about the state of the environment to our neural network and calculates the β€˜expected reward’ for each action (values is a function that takes in a (1,nin) array and returns a (1,nout) array). It then selects the action that will lead to the greatest expected reward. Note that this function still selects a random value with probability epsilon. Epsilon, also known as the β€˜rate of exploration’ is the implementation of an important concept in reinforcement learning: the tradeoff between exploration and exploitation. Exploration helps the model to not get stuck in a local minimum, by exploring apparently sub-optimal actions from time to time that may reveal greater rewards further down the road. Exploitation on the other hand allows the agent to use its knowledge of the current state to select the most profitable action. In most RL agents, epsilon starts out high (near 1.0) in the beginning and is gradually reduced to 0 over time as the agent becomes more confident in the learnt values of actions in a given state." }, { "code": null, "e": 10980, "s": 10871, "text": "The select_action function also calls self.forward (RLAgent.Forward), and here’s the code for that function," }, { "code": null, "e": 11234, "s": 10980, "text": "def forward(self, observation, remember_for_backprop=True): vals = np.copy(observation) index = 0 for layer in self.layers: vals = layer.forward(vals, remember_for_backprop) index = index + 1 return vals" }, { "code": null, "e": 11944, "s": 11234, "text": "The RLAgent.forward function above has a simple loop. It passes the input (the observation for which we are trying to decide on a course of action) to the network and obtains a set of values for each action. It internally calls the NNLayer.forward function, collecting the output from each layer and passing it to the next layer. To complete the implementation of the select action function, here is the last piece β€” the NNLayer.forward function. The remember_for_backprop parameter is a boolean that specifies whether or not certain calculated values need to be stored in order to prevent double calculation during the weight updates (this will be explained in more detail in the section on backpropagation)." }, { "code": null, "e": 12528, "s": 11944, "text": "# Compute the forward pass for this layerdef forward(self, inputs, remember_for_backprop=True): input_with_bias = np.append(np.ones((len(inputs),1)),inputs, axis=1) unactivated = np.dot(input_with_bias, self.weights) output = unactivated if self.activation_function != None: output = self.activation_function(output) if remember_for_backprop: # store variables for backward pass self.backward_store_in = input_with_bias self.backward_store_out = np.copy(unactivated) return output" }, { "code": null, "e": 12544, "s": 12528, "text": "This function β€”" }, { "code": null, "e": 12796, "s": 12544, "text": "Appends a bias term to the input.Calculates the product of the input and the weight matrix at this layer.Takes the output of step 2, and sends this through an activation function if one has been defined for this layer (which in our case will be ReLU)." }, { "code": null, "e": 12830, "s": 12796, "text": "Appends a bias term to the input." }, { "code": null, "e": 12903, "s": 12830, "text": "Calculates the product of the input and the weight matrix at this layer." }, { "code": null, "e": 13050, "s": 12903, "text": "Takes the output of step 2, and sends this through an activation function if one has been defined for this layer (which in our case will be ReLU)." }, { "code": null, "e": 13132, "s": 13050, "text": "Let’s also add the instantiation for these layers in the RLAgent’s init function," }, { "code": null, "e": 13628, "s": 13132, "text": "def __init__(self, env): self.env = env self.hidden_size = 24 self.input_size = env.observation_space.shape[0] self.output_size = env.action_space.n self.num_hidden_layers = 2 self.epsilon = 1.0 self.layers = [NNLayer(self.input_size + 1, self.hidden_size, activation=relu)] for i in range(self.num_hidden_layers-1): self.layers.append(NNLayer(self.hidden_size+1, self.hidden_size, activation=relu)) self.layers.append(NNLayer(self.hidden_size+1, self.output_size))" }, { "code": null, "e": 13958, "s": 13628, "text": "You can see above that we have a total of 2 hidden layers and 1 output layer. Also, in all but the output layer we are using an activation function called Rectified Linear Unit (ReLU). This function is an extremely simple function that introduces sufficient non-linearity to our neural network. Here is the implementation for it," }, { "code": null, "e": 14008, "s": 13958, "text": "def relu(mat): return np.multiply(mat,(mat>0))" }, { "code": null, "e": 14307, "s": 14008, "text": "This function takes in a matrix and returns another matrix that has identical values where the original matrix was greater than 0, and 0 in all other values. Finally, let’s add the initialization of our agent and epsilon decay to our main program loop. This is what the new main program looks like:" }, { "code": null, "e": 15006, "s": 14307, "text": "# Global variablesNUM_EPISODES = 10MAX_TIMESTEPS = 1000model = RLAgent(env)# The main program loopfor i_episode in range(NUM_EPISODES): observation = env.reset() # Iterating through time steps within an episode for t in range(MAX_TIMESTEPS): env.render() action = model.select_action(observation) observation, reward, done, info = env.step(action) # epsilon decay model.epsilon = model.epsilon if model.epsilon < 0.01 else model.epsilon*0.995 if done: # If the pole has tipped over, end this episode print('Episode {} ended after {} timesteps, current exploration is {}'.format(i_episode, t+1,model.epsilon)) break" }, { "code": null, "e": 15588, "s": 15006, "text": "What does this model do currently? It initializes the weights for the neural network randomly and calculates values for actions in any given state based on these weights. However, we need a way for the function to improve the values of the weights in the network such that the agent is able to take the best action in any given state. As alluded to earlier, this is achieved through stochastic gradient descent and implemented via a technique called backpropagation. I will go into detail about backpropagation along with relevant theory of reinforcement learning in the next post." }, { "code": null, "e": 15644, "s": 15588, "text": "To summarize, this is what we have accomplished so far:" }, { "code": null, "e": 16107, "s": 15644, "text": "Wrote the main program components for interacting with the environment space of CartPole in OpenAI gym.Encapsulated the Reinforcement Learning agent and its component Neural Net layers in their respective classes.Coded and initialized the neural network architecture for our deep learning reinforcement learning agent.Implemented the β€˜feed forward’ computation to propagate an observation of the environment through the neural network to calculate action values." }, { "code": null, "e": 16211, "s": 16107, "text": "Wrote the main program components for interacting with the environment space of CartPole in OpenAI gym." }, { "code": null, "e": 16322, "s": 16211, "text": "Encapsulated the Reinforcement Learning agent and its component Neural Net layers in their respective classes." }, { "code": null, "e": 16428, "s": 16322, "text": "Coded and initialized the neural network architecture for our deep learning reinforcement learning agent." }, { "code": null, "e": 16573, "s": 16428, "text": "Implemented the β€˜feed forward’ computation to propagate an observation of the environment through the neural network to calculate action values." }, { "code": null, "e": 16629, "s": 16573, "text": "In the next post, we will aim to achieve the following:" }, { "code": null, "e": 17046, "s": 16629, "text": "Examine and formalize a notion of the β€˜cumulative reward’ that an agent expects to receive in a particular state for the Cartpole problem.Understand how an agent should update the weights in the neural network to get closer to its idea the correct cumulative rewards expected from taking a particular action in a particular state.Implement backpropagation β€” the algorithm that achieves the goal mentioned in 2 above." }, { "code": null, "e": 17185, "s": 17046, "text": "Examine and formalize a notion of the β€˜cumulative reward’ that an agent expects to receive in a particular state for the Cartpole problem." }, { "code": null, "e": 17378, "s": 17185, "text": "Understand how an agent should update the weights in the neural network to get closer to its idea the correct cumulative rewards expected from taking a particular action in a particular state." }, { "code": null, "e": 17465, "s": 17378, "text": "Implement backpropagation β€” the algorithm that achieves the goal mentioned in 2 above." } ]
Git Ignore and .gitignore
When sharing your code with others, there are often files or parts of your project, you do not want to share. Examples log files temporary files hidden files personal files etc. Git can specify which files or parts of your project should be ignored by Git using a .gitignore file. Git will not track files and folders specified in .gitignore. However, the .gitignore file itself IS tracked by Git. To create a .gitignore file, go to the root of your local Git, and create it: touch .gitignore Now open the file using a text editor. We are just going to add two simple rules: Ignore any files with the .log extension Ignore everything in any directory named temp Now all .log files and anything in temp folders will be ignored by Git. Note: In this case, we use a single .gitignore which applies to the entire repository. It is also possible to have additional .gitignore files in subdirectories. These only apply to files or folders within that directory. Here are the general rules for matching patterns in .gitignore files: It is also possible to ignore files or folders but not show it in the distubuted .gitignore file. These kinds of ignores are specified in the .git/info/exclude file. It works the same way as .gitignore but are not shown to anyone else. In .gitignore add a line to ignore all .temp files: 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": 110, "s": 0, "text": "When sharing your code with others, there are often files or parts of your project, you do not want to share." }, { "code": null, "e": 119, "s": 110, "text": "Examples" }, { "code": null, "e": 129, "s": 119, "text": "log files" }, { "code": null, "e": 145, "s": 129, "text": "temporary files" }, { "code": null, "e": 158, "s": 145, "text": "hidden files" }, { "code": null, "e": 173, "s": 158, "text": "personal files" }, { "code": null, "e": 178, "s": 173, "text": "etc." }, { "code": null, "e": 282, "s": 178, "text": "Git can specify which files or parts of your project should be \nignored by Git using a .gitignore file." }, { "code": null, "e": 400, "s": 282, "text": "Git will not track files and folders specified in .gitignore. However, the .gitignore \nfile itself IS tracked by Git." }, { "code": null, "e": 478, "s": 400, "text": "To create a .gitignore file, go to the root of your local Git, and create it:" }, { "code": null, "e": 495, "s": 478, "text": "touch .gitignore" }, { "code": null, "e": 534, "s": 495, "text": "Now open the file using a text editor." }, { "code": null, "e": 577, "s": 534, "text": "We are just going to add two simple rules:" }, { "code": null, "e": 618, "s": 577, "text": "Ignore any files with the .log extension" }, { "code": null, "e": 664, "s": 618, "text": "Ignore everything in any directory named temp" }, { "code": null, "e": 737, "s": 664, "text": "Now all .log files and anything in \ntemp folders will be ignored by Git." }, { "code": null, "e": 824, "s": 737, "text": "Note: In this case, we use a single .gitignore which applies to the entire repository." }, { "code": null, "e": 960, "s": 824, "text": " It is also possible to have additional .gitignore files in subdirectories. These only apply to files or folders within that directory." }, { "code": null, "e": 1032, "s": 960, "text": "Here are the general rules for matching patterns in .gitignore \nfiles: " }, { "code": null, "e": 1131, "s": 1032, "text": "It is also possible to ignore files or folders but not show it in the \ndistubuted .gitignore file." }, { "code": null, "e": 1270, "s": 1131, "text": "These kinds of ignores are specified in the \n.git/info/exclude file. It works the same way as\n.gitignore but are not shown to anyone else." }, { "code": null, "e": 1322, "s": 1270, "text": "In .gitignore add a line to ignore all .temp files:" }, { "code": null, "e": 1344, "s": 1324, "text": "\nStart the Exercise" }, { "code": null, "e": 1377, "s": 1344, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 1419, "s": 1377, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 1526, "s": 1419, "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": 1545, "s": 1526, "text": "[email protected]" } ]
Set file attributes in Java
One of the file attribute that can be set is to make the file read-only. This can be done by using the method java.io.File.setReadOnly(). This method requires no parameters and it returns true if the file is set to read-only and false otherwise. The java.io.File.canRead() and java.io.File.canWrite() methods are used to check whether the file can be read or written to respectively. A program that demonstrates this is given as follows βˆ’ Live Demo import java.io.File; public class Demo { public static void main(String[] args) { try { File file = new File("demo1.txt"); file.createNewFile(); if (file.canRead()) System.out.println("Readable"); else System.out.println("Not Readable"); if (file.canWrite()) System.out.println("Writable"); else System.out.println("Not Writable"); file.setReadOnly(); if (file.canRead()) System.out.println("\nReadable"); else System.out.println("\nNot Readable"); if (file.canWrite()) System.out.println("Writable"); else System.out.println("Not Writable"); } catch(Exception e) { e.printStackTrace(); } } } The output of the above program is as follows βˆ’ Readable Writable Readable Not Writable
[ { "code": null, "e": 1308, "s": 1062, "text": "One of the file attribute that can be set is to make the file read-only. This can be done by using the method java.io.File.setReadOnly(). This method requires no parameters and it returns true if the file is set to read-only and false otherwise." }, { "code": null, "e": 1446, "s": 1308, "text": "The java.io.File.canRead() and java.io.File.canWrite() methods are used to check whether the file can be read or written to respectively." }, { "code": null, "e": 1501, "s": 1446, "text": "A program that demonstrates this is given as follows βˆ’" }, { "code": null, "e": 1512, "s": 1501, "text": " Live Demo" }, { "code": null, "e": 2336, "s": 1512, "text": "import java.io.File;\npublic class Demo {\n public static void main(String[] args) {\n try {\n File file = new File(\"demo1.txt\");\n file.createNewFile();\n if (file.canRead())\n System.out.println(\"Readable\");\n else\n System.out.println(\"Not Readable\");\n if (file.canWrite())\n System.out.println(\"Writable\");\n else\n System.out.println(\"Not Writable\");\n file.setReadOnly();\n if (file.canRead())\n System.out.println(\"\\nReadable\");\n else\n System.out.println(\"\\nNot Readable\");\n if (file.canWrite())\n System.out.println(\"Writable\");\n else\n System.out.println(\"Not Writable\");\n } catch(Exception e) {\n e.printStackTrace();\n }\n }\n}" }, { "code": null, "e": 2384, "s": 2336, "text": "The output of the above program is as follows βˆ’" }, { "code": null, "e": 2424, "s": 2384, "text": "Readable\nWritable\nReadable\nNot Writable" } ]
endDrawer Widget in Flutter - GeeksforGeeks
13 Nov, 2020 The endDrawer is the panel displayed to the side of the body (Scaffold Widget). It is generally hidden in mobile devices. We can open it by swiping in from right to left, or we can customise it to open on-press of an icon or a button. This widget is similar to the already present Drawer widget in flutter except for the fact the Drawer by default open from left-to-right and the endDrawer by default opens from right-to-left. However, this direction can be changed by using textDirection property. Constructor of Drawer class: Drawer({Key key, double elevation, Widget child, String semanticLabel}) child: This property takes in a widget as a parameter to show below endDrawer widget in the tree. hashCode: This property takes an int as the parameter. The hash code represents the state of the object that effects operator== comparison. elevation: This property takes in a double value as a parameter to control the z-coordinate at which to place this drawer relative to its parent. semanticLabel: This property takes in a string value a the parameter to create the semantic label of the dialog used by accessibility frameworks to announce screen transitions when the drawer is opened and closed. main.dart Dart import 'package:flutter/material.dart'; void main() { runApp(MyApp());}class MyApp extends StatelessWidget { // This widget is the // root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(), debugShowCheckedModeBanner: false, ); }} class MyHomePage extends StatefulWidget { @override _MyHomePageState createState() => _MyHomePageState();}class _MyHomePageState extends State<MyHomePage> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title:Text("GeeksforGeeks"), backgroundColor: Colors.green, ), endDrawer: Drawer( child: ListView.builder( itemBuilder: ( BuildContext context,int index){ return ListTile( leading:Icon(Icons.list), title: Text("GFG item $index"), trailing: Icon(Icons.done), ); }), //elevation: 20.0, //semanticLabel: 'endDrawer', ), ); }} We create a Scaffold that contains an AppBar and Drawer. Let’s add the endDrawer in our app. Child of Drawer is ListView.builder to build the list of items. Create a List of items as shown above in the code. Run the app and see the output. Output: ankit_kumar_ Flutter Dart Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Flutter - DropDownButton Widget Flutter - Custom Bottom Navigation Bar Flutter - Checkbox Widget Flutter - BoxShadow Widget ListView Class in Flutter Flutter - Flexible Widget Operators in Dart Flutter - Stack Widget What is widgets in Flutter? Android Studio Setup for Flutter Development
[ { "code": null, "e": 23936, "s": 23908, "text": "\n13 Nov, 2020" }, { "code": null, "e": 24436, "s": 23936, "text": "The endDrawer is the panel displayed to the side of the body (Scaffold Widget). It is generally hidden in mobile devices. We can open it by swiping in from right to left, or we can customise it to open on-press of an icon or a button. This widget is similar to the already present Drawer widget in flutter except for the fact the Drawer by default open from left-to-right and the endDrawer by default opens from right-to-left. However, this direction can be changed by using textDirection property. " }, { "code": null, "e": 24465, "s": 24436, "text": "Constructor of Drawer class:" }, { "code": null, "e": 24544, "s": 24465, "text": "Drawer({Key key,\ndouble elevation, \nWidget child, \nString semanticLabel})\n\n\n\n\n" }, { "code": null, "e": 24642, "s": 24544, "text": "child: This property takes in a widget as a parameter to show below endDrawer widget in the tree." }, { "code": null, "e": 24782, "s": 24642, "text": "hashCode: This property takes an int as the parameter. The hash code represents the state of the object that effects operator== comparison." }, { "code": null, "e": 24928, "s": 24782, "text": "elevation: This property takes in a double value as a parameter to control the z-coordinate at which to place this drawer relative to its parent." }, { "code": null, "e": 25142, "s": 24928, "text": "semanticLabel: This property takes in a string value a the parameter to create the semantic label of the dialog used by accessibility frameworks to announce screen transitions when the drawer is opened and closed." }, { "code": null, "e": 25152, "s": 25142, "text": "main.dart" }, { "code": null, "e": 25157, "s": 25152, "text": "Dart" }, { "code": "import 'package:flutter/material.dart'; void main() { runApp(MyApp());}class MyApp extends StatelessWidget { // This widget is the // root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(), debugShowCheckedModeBanner: false, ); }} class MyHomePage extends StatefulWidget { @override _MyHomePageState createState() => _MyHomePageState();}class _MyHomePageState extends State<MyHomePage> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title:Text(\"GeeksforGeeks\"), backgroundColor: Colors.green, ), endDrawer: Drawer( child: ListView.builder( itemBuilder: ( BuildContext context,int index){ return ListTile( leading:Icon(Icons.list), title: Text(\"GFG item $index\"), trailing: Icon(Icons.done), ); }), //elevation: 20.0, //semanticLabel: 'endDrawer', ), ); }}", "e": 26268, "s": 25157, "text": null }, { "code": null, "e": 26328, "s": 26271, "text": "We create a Scaffold that contains an AppBar and Drawer." }, { "code": null, "e": 26428, "s": 26328, "text": "Let’s add the endDrawer in our app. Child of Drawer is ListView.builder to build the list of items." }, { "code": null, "e": 26479, "s": 26428, "text": "Create a List of items as shown above in the code." }, { "code": null, "e": 26511, "s": 26479, "text": "Run the app and see the output." }, { "code": null, "e": 26521, "s": 26513, "text": "Output:" }, { "code": null, "e": 26538, "s": 26525, "text": "ankit_kumar_" }, { "code": null, "e": 26546, "s": 26538, "text": "Flutter" }, { "code": null, "e": 26551, "s": 26546, "text": "Dart" }, { "code": null, "e": 26649, "s": 26551, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26681, "s": 26649, "text": "Flutter - DropDownButton Widget" }, { "code": null, "e": 26720, "s": 26681, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 26746, "s": 26720, "text": "Flutter - Checkbox Widget" }, { "code": null, "e": 26773, "s": 26746, "text": "Flutter - BoxShadow Widget" }, { "code": null, "e": 26799, "s": 26773, "text": "ListView Class in Flutter" }, { "code": null, "e": 26825, "s": 26799, "text": "Flutter - Flexible Widget" }, { "code": null, "e": 26843, "s": 26825, "text": "Operators in Dart" }, { "code": null, "e": 26866, "s": 26843, "text": "Flutter - Stack Widget" }, { "code": null, "e": 26894, "s": 26866, "text": "What is widgets in Flutter?" } ]
Is there any alternative for CONCAT() in MySQL?
Yes, an alternative is CONCAT_WS(). Let us first create a table βˆ’ mysql> create table DemoTable ( StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY, StudentName varchar(100) ); Query OK, 0 rows affected (0.74 sec) Insert some records in the table using insert command βˆ’ mysql> insert into DemoTable(StudentName) values('Chris'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable(StudentName) values('Robert'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable(StudentName) values('Bob'); Query OK, 1 row affected (0.12 sec) Display all records from the table using select statement βˆ’ mysql> select *from DemoTable; +-----------+-------------+ | StudentId | StudentName | +-----------+-------------+ | 1 | Chris | | 2 | Robert | | 3 | Bob | +-----------+-------------+ 3 rows in set (0.00 sec) Let us see how to work with an alternative of CONCAT() in MySQL βˆ’ mysql> select concat_ws(SPACE(2), 'Student Name is:',StudentName) from DemoTable; +-----------------------------------------------------+ | concat_ws(SPACE(2), 'Student Name is:',StudentName) | +-----------------------------------------------------+ | Student Name is: Chris | | Student Name is: Robert | | Student Name is: Bob | +-----------------------------------------------------+ 3 rows in set (0.04 sec)
[ { "code": null, "e": 1128, "s": 1062, "text": "Yes, an alternative is CONCAT_WS(). Let us first create a table βˆ’" }, { "code": null, "e": 1288, "s": 1128, "text": "mysql> create table DemoTable\n (\n StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n StudentName varchar(100)\n );\nQuery OK, 0 rows affected (0.74 sec)" }, { "code": null, "e": 1344, "s": 1288, "text": "Insert some records in the table using insert command βˆ’" }, { "code": null, "e": 1628, "s": 1344, "text": "mysql> insert into DemoTable(StudentName) values('Chris');\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into DemoTable(StudentName) values('Robert');\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into DemoTable(StudentName) values('Bob');\nQuery OK, 1 row affected (0.12 sec)" }, { "code": null, "e": 1688, "s": 1628, "text": "Display all records from the table using select statement βˆ’" }, { "code": null, "e": 1719, "s": 1688, "text": "mysql> select *from DemoTable;" }, { "code": null, "e": 1940, "s": 1719, "text": "+-----------+-------------+\n| StudentId | StudentName |\n+-----------+-------------+\n| 1 | Chris |\n| 2 | Robert |\n| 3 | Bob |\n+-----------+-------------+\n3 rows in set (0.00 sec)" }, { "code": null, "e": 2006, "s": 1940, "text": "Let us see how to work with an alternative of CONCAT() in MySQL βˆ’" }, { "code": null, "e": 2088, "s": 2006, "text": "mysql> select concat_ws(SPACE(2), 'Student Name is:',StudentName) from DemoTable;" }, { "code": null, "e": 2505, "s": 2088, "text": "+-----------------------------------------------------+\n| concat_ws(SPACE(2), 'Student Name is:',StudentName) |\n+-----------------------------------------------------+\n| Student Name is: Chris |\n| Student Name is: Robert |\n| Student Name is: Bob |\n+-----------------------------------------------------+\n3 rows in set (0.04 sec)" } ]
scipy stats.mode() function | Python
11 Feb, 2019 scipy.stats.mode(array, axis=0) function calculates the mode of the array elements along the specified axis of the array (list in python). Its formula – where, l : Lower Boundary of modal class h : Size of modal class fm : Frequency corresponding to modal class f1 : Frequency preceding to modal class f2 : Frequency proceeding to modal class Parameters :array : Input array or object having the elements to calculate the mode.axis : Axis along which the mode is to be computed. By default axis = 0 Returns : Modal values of the array elements based on the set parameters. Code #1: # Arithmetic mode from scipy import statsimport numpy as np arr1 = np.array([[1, 3, 27, 13, 21, 9], [8, 12, 8, 4, 7, 10]]) print("Arithmetic mode is : \n", stats.mode(arr1)) Output : Arithmetic mode is : ModeResult(mode=array([[1, 3, 8, 4, 7, 9]]), count=array([[1, 1, 1, 1, 1, 1]])) Code #2: With multi-dimensional data # Arithmetic mode from scipy import statsimport numpy as np arr1 = [[1, 3, 27], [3, 4, 6], [7, 6, 3], [3, 6, 8]] print("Arithmetic mode is : \n", stats.mode(arr1)) print("\nArithmetic mode is : \n", stats.mode(arr1, axis = None)) print("\nArithmetic mode is : \n", stats.mode(arr1, axis = 0)) print("\nArithmetic mode is : \n", stats.mode(arr1, axis = 1)) Output : Arithmetic mode is : ModeResult(mode=array([[3, 6, 3]]), count=array([[2, 2, 1]])) Arithmetic mode is : ModeResult(mode=array([3]), count=array([4])) Arithmetic mode is : ModeResult(mode=array([[3, 6, 3]]), count=array([[2, 2, 1]])) Arithmetic mode is : ModeResult(mode=array([[1], [3], [3], [3]]), count=array([[1], [1], [1], [1]])) Python scipy-stats-functions Python-scipy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Feb, 2019" }, { "code": null, "e": 167, "s": 28, "text": "scipy.stats.mode(array, axis=0) function calculates the mode of the array elements along the specified axis of the array (list in python)." }, { "code": null, "e": 181, "s": 167, "text": "Its formula –" }, { "code": null, "e": 372, "s": 181, "text": "where,\nl : Lower Boundary of modal class\nh : Size of modal class\nfm : Frequency corresponding to modal class\nf1 : Frequency preceding to modal class\nf2 : Frequency proceeding to modal class" }, { "code": null, "e": 528, "s": 372, "text": "Parameters :array : Input array or object having the elements to calculate the mode.axis : Axis along which the mode is to be computed. By default axis = 0" }, { "code": null, "e": 602, "s": 528, "text": "Returns : Modal values of the array elements based on the set parameters." }, { "code": null, "e": 611, "s": 602, "text": "Code #1:" }, { "code": "# Arithmetic mode from scipy import statsimport numpy as np arr1 = np.array([[1, 3, 27, 13, 21, 9], [8, 12, 8, 4, 7, 10]]) print(\"Arithmetic mode is : \\n\", stats.mode(arr1)) ", "e": 809, "s": 611, "text": null }, { "code": null, "e": 818, "s": 809, "text": "Output :" }, { "code": null, "e": 921, "s": 818, "text": "Arithmetic mode is : \n ModeResult(mode=array([[1, 3, 8, 4, 7, 9]]), count=array([[1, 1, 1, 1, 1, 1]]))" }, { "code": null, "e": 959, "s": 921, "text": " Code #2: With multi-dimensional data" }, { "code": "# Arithmetic mode from scipy import statsimport numpy as np arr1 = [[1, 3, 27], [3, 4, 6], [7, 6, 3], [3, 6, 8]] print(\"Arithmetic mode is : \\n\", stats.mode(arr1)) print(\"\\nArithmetic mode is : \\n\", stats.mode(arr1, axis = None)) print(\"\\nArithmetic mode is : \\n\", stats.mode(arr1, axis = 0)) print(\"\\nArithmetic mode is : \\n\", stats.mode(arr1, axis = 1)) ", "e": 1352, "s": 959, "text": null }, { "code": null, "e": 1361, "s": 1352, "text": "Output :" }, { "code": null, "e": 1748, "s": 1361, "text": "Arithmetic mode is : \n ModeResult(mode=array([[3, 6, 3]]), count=array([[2, 2, 1]]))\n\nArithmetic mode is : \n ModeResult(mode=array([3]), count=array([4]))\n\nArithmetic mode is : \n ModeResult(mode=array([[3, 6, 3]]), count=array([[2, 2, 1]]))\n\nArithmetic mode is : \n ModeResult(mode=array([[1],\n [3],\n [3],\n [3]]), count=array([[1],\n [1],\n [1],\n [1]]))" }, { "code": null, "e": 1777, "s": 1748, "text": "Python scipy-stats-functions" }, { "code": null, "e": 1790, "s": 1777, "text": "Python-scipy" }, { "code": null, "e": 1797, "s": 1790, "text": "Python" }, { "code": null, "e": 1895, "s": 1797, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1927, "s": 1895, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1954, "s": 1927, "text": "Python Classes and Objects" }, { "code": null, "e": 1975, "s": 1954, "text": "Python OOPs Concepts" }, { "code": null, "e": 1998, "s": 1975, "text": "Introduction To PYTHON" }, { "code": null, "e": 2054, "s": 1998, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2085, "s": 2054, "text": "Python | os.path.join() method" }, { "code": null, "e": 2127, "s": 2085, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2169, "s": 2127, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2208, "s": 2169, "text": "Python | Get unique values from a list" } ]
Java - valueOf() Method
The valueOf method returns the relevant Number Object holding the value of the argument passed. The argument can be a primitive data type, String, etc. This method is a static method. The method can take two arguments, where one is a String and the other is a radix. Following are all the variants of this method βˆ’ static Integer valueOf(int i) static Integer valueOf(String s) static Integer valueOf(String s, int radix) Here is the detail of parameters βˆ’ i βˆ’ An int for which Integer representation would be returned. i βˆ’ An int for which Integer representation would be returned. s βˆ’ A String for which Integer representation would be returned. s βˆ’ A String for which Integer representation would be returned. radix βˆ’ This would be used to decide the value of returned Integer based on the passed String. radix βˆ’ This would be used to decide the value of returned Integer based on the passed String. valueOf(int i) βˆ’ This returns an Integer object holding the value of the specified primitive. valueOf(int i) βˆ’ This returns an Integer object holding the value of the specified primitive. valueOf(String s) βˆ’ This returns an Integer object holding the value of the specified string representation. valueOf(String s) βˆ’ This returns an Integer object holding the value of the specified string representation. valueOf(String s, int radix) βˆ’ This returns an Integer object holding the integer value of the specified string representation, parsed with the value of radix. valueOf(String s, int radix) βˆ’ This returns an Integer object holding the integer value of the specified string representation, parsed with the value of radix. public class Test { public static void main(String args[]) { Integer x =Integer.valueOf(9); Double c = Double.valueOf(5); Float a = Float.valueOf("80"); Integer b = Integer.valueOf("444",16); System.out.println(x); System.out.println(c); System.out.println(a); System.out.println(b); } } This will produce the following result βˆ’
[ { "code": null, "e": 2663, "s": 2511, "text": "The valueOf method returns the relevant Number Object holding the value of the argument passed. The argument can be a primitive data type, String, etc." }, { "code": null, "e": 2778, "s": 2663, "text": "This method is a static method. The method can take two arguments, where one is a String and the other is a radix." }, { "code": null, "e": 2826, "s": 2778, "text": "Following are all the variants of this method βˆ’" }, { "code": null, "e": 2934, "s": 2826, "text": "static Integer valueOf(int i)\nstatic Integer valueOf(String s)\nstatic Integer valueOf(String s, int radix)\n" }, { "code": null, "e": 2969, "s": 2934, "text": "Here is the detail of parameters βˆ’" }, { "code": null, "e": 3032, "s": 2969, "text": "i βˆ’ An int for which Integer representation would be returned." }, { "code": null, "e": 3095, "s": 3032, "text": "i βˆ’ An int for which Integer representation would be returned." }, { "code": null, "e": 3160, "s": 3095, "text": "s βˆ’ A String for which Integer representation would be returned." }, { "code": null, "e": 3225, "s": 3160, "text": "s βˆ’ A String for which Integer representation would be returned." }, { "code": null, "e": 3320, "s": 3225, "text": "radix βˆ’ This would be used to decide the value of returned Integer based on the passed String." }, { "code": null, "e": 3415, "s": 3320, "text": "radix βˆ’ This would be used to decide the value of returned Integer based on the passed String." }, { "code": null, "e": 3509, "s": 3415, "text": "valueOf(int i) βˆ’ This returns an Integer object holding the value of the specified primitive." }, { "code": null, "e": 3603, "s": 3509, "text": "valueOf(int i) βˆ’ This returns an Integer object holding the value of the specified primitive." }, { "code": null, "e": 3712, "s": 3603, "text": "valueOf(String s) βˆ’ This returns an Integer object holding the value of the specified string representation." }, { "code": null, "e": 3821, "s": 3712, "text": "valueOf(String s) βˆ’ This returns an Integer object holding the value of the specified string representation." }, { "code": null, "e": 3982, "s": 3821, "text": "valueOf(String s, int radix) βˆ’ This returns an Integer object holding the integer value of the specified string representation, parsed with the value of radix." }, { "code": null, "e": 4143, "s": 3982, "text": "valueOf(String s, int radix) βˆ’ This returns an Integer object holding the integer value of the specified string representation, parsed with the value of radix." }, { "code": null, "e": 4504, "s": 4143, "text": "public class Test { \n\n public static void main(String args[]) {\n Integer x =Integer.valueOf(9);\n Double c = Double.valueOf(5);\n Float a = Float.valueOf(\"80\"); \n Integer b = Integer.valueOf(\"444\",16);\n\n System.out.println(x); \n System.out.println(c);\n System.out.println(a);\n System.out.println(b);\n }\n}" } ]
Calling Python from C | Set 1
27 Mar, 2019 In this article, we will mainly focus on safe execution of a Python callable from C, returning a result back to C and writing C code that needs to access a Python function as a callback. The code below focuses on the tricky parts that are involved in calling Python from C. Code #1 : [Step 1 and 2] Own the GIL and Verify that function is a proper callable #include <Python.h> /* Execute func(x, y) in the Python interpreter. Thearguments and return result of the function mustbe Python floats */ double call_func(PyObject *func, double x, double y){ PyObject *args; PyObject *kwargs; PyObject *result = 0; double retval; // Make sure we own the GIL PyGILState_STATE state = PyGILState_Ensure(); // Verify that func is a proper callable if (!PyCallable_Check(func)) { fprintf(stderr, "call_func: expected a callable\n"); goto fail; } Code #2 : Building Arguments, calling function, Check for Python exceptions Create the return value, Restore previous GIL state and return. // Step3 args = Py_BuildValue("(dd)", x, y); kwargs = NULL; // Step 4 result = PyObject_Call(func, args, kwargs); Py_DECREF(args); Py_XDECREF(kwargs); // Step 5 if (PyErr_Occurred()) { PyErr_Print(); goto fail; } // Verify the result is a float object if (!PyFloat_Check(result)) { fprintf(stderr, "call_func: callable didn't return a float\n"); goto fail; } // Step 6 retval = PyFloat_AsDouble(result); Py_DECREF(result); // Step 7 PyGILState_Release(state); return retval; fail: Py_XDECREF(result); PyGILState_Release(state); abort(); } A reference to an existing Python callable needs to be passed in, to use this function. To do that there are many ways like – simply writing C code to extract a symbol from an existing module or having a callable object passed into an extension module. The code given below shows calling a function from an embedded Python interpreter. Code #3 : Loading a symbol from a module #include <Python.h>/* Definition of call_func() same as above */ /* Load a symbol from a module */PyObject *import_name(const char *modname, const char *symbol){ PyObject *u_name, *module; u_name = PyUnicode_FromString(modname); module = PyImport_Import(u_name); Py_DECREF(u_name); return PyObject_GetAttrString(module, symbol);} Python-ctype Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? Python Classes and Objects Iterate over a list in Python Python OOPs Concepts Introduction To PYTHON
[ { "code": null, "e": 28, "s": 0, "text": "\n27 Mar, 2019" }, { "code": null, "e": 215, "s": 28, "text": "In this article, we will mainly focus on safe execution of a Python callable from C, returning a result back to C and writing C code that needs to access a Python function as a callback." }, { "code": null, "e": 302, "s": 215, "text": "The code below focuses on the tricky parts that are involved in calling Python from C." }, { "code": null, "e": 385, "s": 302, "text": "Code #1 : [Step 1 and 2] Own the GIL and Verify that function is a proper callable" }, { "code": "#include <Python.h> /* Execute func(x, y) in the Python interpreter. Thearguments and return result of the function mustbe Python floats */ double call_func(PyObject *func, double x, double y){ PyObject *args; PyObject *kwargs; PyObject *result = 0; double retval; // Make sure we own the GIL PyGILState_STATE state = PyGILState_Ensure(); // Verify that func is a proper callable if (!PyCallable_Check(func)) { fprintf(stderr, \"call_func: expected a callable\\n\"); goto fail; }", "e": 926, "s": 385, "text": null }, { "code": null, "e": 1003, "s": 926, "text": " Code #2 : Building Arguments, calling function, Check for Python exceptions" }, { "code": null, "e": 1067, "s": 1003, "text": "Create the return value, Restore previous GIL state and return." }, { "code": " // Step3 args = Py_BuildValue(\"(dd)\", x, y); kwargs = NULL; // Step 4 result = PyObject_Call(func, args, kwargs); Py_DECREF(args); Py_XDECREF(kwargs); // Step 5 if (PyErr_Occurred()) { PyErr_Print(); goto fail; } // Verify the result is a float object if (!PyFloat_Check(result)) { fprintf(stderr, \"call_func: callable didn't return a float\\n\"); goto fail; } // Step 6 retval = PyFloat_AsDouble(result); Py_DECREF(result); // Step 7 PyGILState_Release(state); return retval; fail: Py_XDECREF(result); PyGILState_Release(state); abort(); }", "e": 1753, "s": 1067, "text": null }, { "code": null, "e": 2089, "s": 1753, "text": "A reference to an existing Python callable needs to be passed in, to use this function. To do that there are many ways like – simply writing C code to extract a symbol from an existing module or having a callable object passed into an extension module. The code given below shows calling a function from an embedded Python interpreter." }, { "code": null, "e": 2130, "s": 2089, "text": "Code #3 : Loading a symbol from a module" }, { "code": "#include <Python.h>/* Definition of call_func() same as above */ /* Load a symbol from a module */PyObject *import_name(const char *modname, const char *symbol){ PyObject *u_name, *module; u_name = PyUnicode_FromString(modname); module = PyImport_Import(u_name); Py_DECREF(u_name); return PyObject_GetAttrString(module, symbol);}", "e": 2482, "s": 2130, "text": null }, { "code": null, "e": 2495, "s": 2482, "text": "Python-ctype" }, { "code": null, "e": 2502, "s": 2495, "text": "Python" }, { "code": null, "e": 2600, "s": 2502, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2618, "s": 2600, "text": "Python Dictionary" }, { "code": null, "e": 2660, "s": 2618, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2682, "s": 2660, "text": "Enumerate() in Python" }, { "code": null, "e": 2717, "s": 2682, "text": "Read a file line by line in Python" }, { "code": null, "e": 2743, "s": 2717, "text": "Python String | replace()" }, { "code": null, "e": 2775, "s": 2743, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2802, "s": 2775, "text": "Python Classes and Objects" }, { "code": null, "e": 2832, "s": 2802, "text": "Iterate over a list in Python" }, { "code": null, "e": 2853, "s": 2832, "text": "Python OOPs Concepts" } ]
void pointer in C
The void pointer in C is a pointer which is not associated with any data types. It points to some data location in the storage means points to the address of variables. It is also called general purpose pointer. In C, malloc() and calloc() functions return void * or generic pointers. It has some limitations βˆ’ 1) Pointer arithmetic is not possible with void pointer due to its concrete size. 2) It can’t be used as dereferenced. Begin Declare a of the integer datatype. Initialize a = 7. Declare b of the float datatype. Initialize b = 7.6. Declare a pointer p as void. Initialize p pointer to a. Print β€œInteger variable is”. Print the value of a using pointer p. Initialize p pointer to b. Print β€œFloat variable is”. Print the value of b using pointer p End. Here is a simple example βˆ’ Live Demo #include<stdlib.h> int main() { int a = 7; float b = 7.6; void *p; p = &a; printf("Integer variable is = %d", *( (int*) p) ); p = &b; printf("\nFloat variable is = %f", *( (float*) p) ); return 0; } Integer variable is = 7 Float variable is = 7.600000
[ { "code": null, "e": 1472, "s": 1187, "text": "The void pointer in C is a pointer which is not associated with any data types. It points to some data location in the storage means points to the address of variables. It is also called general purpose pointer. In C, malloc() and calloc() functions return void * or generic pointers." }, { "code": null, "e": 1498, "s": 1472, "text": "It has some limitations βˆ’" }, { "code": null, "e": 1580, "s": 1498, "text": "1) Pointer arithmetic is not possible with void pointer due to its concrete size." }, { "code": null, "e": 1617, "s": 1580, "text": "2) It can’t be used as dereferenced." }, { "code": null, "e": 1993, "s": 1617, "text": "Begin\n Declare a of the integer datatype.\n Initialize a = 7.\n Declare b of the float datatype.\n Initialize b = 7.6.\n Declare a pointer p as void.\n Initialize p pointer to a.\n Print β€œInteger variable is”.\n Print the value of a using pointer p.\n Initialize p pointer to b.\n Print β€œFloat variable is”.\n Print the value of b using pointer p\nEnd." }, { "code": null, "e": 2020, "s": 1993, "text": "Here is a simple example βˆ’" }, { "code": null, "e": 2031, "s": 2020, "text": " Live Demo" }, { "code": null, "e": 2254, "s": 2031, "text": "#include<stdlib.h>\nint main() {\n int a = 7;\n float b = 7.6;\n void *p;\n p = &a;\n printf(\"Integer variable is = %d\", *( (int*) p) );\n p = &b;\n printf(\"\\nFloat variable is = %f\", *( (float*) p) );\n return 0;\n}" }, { "code": null, "e": 2307, "s": 2254, "text": "Integer variable is = 7\nFloat variable is = 7.600000" } ]
How to Change Date Format in jQuery UI DatePicker ?
10 Nov, 2021 In this article, we are going to learn about the Datepicker in jQuery. jQuery is the fastest and lightweight JavaScript library that is used to simplify the interactions between an HTML/CSS document, or more precisely the Document Object Model (DOM), and JavaScript. jQuery is widely famous for its motto of β€œWrite less, do more.” It simply means that you can achieve your goal by just writing a few lines of code. In many forms, you can select the date and year from the calendar. Datepicker is a standard form of the input field that is used to select the date and year by just seeing the calendar. It is an interactive calendar in a specified overlay. When you click on any date that is mentioned in the calendar then the feedback will appear on the input text. Approach: Create an HTML file and import the jQuery library. The jQuery datepicker() method is used to create an overlay of an interactive calendar. Apply CSS to your application as per the need. Syntax 1: <script type="text/javascript"> $(function() { $("#txtDate").datepicker({ dateFormat: 'dd/mm/yy' }); }); </script> Example: HTML <!DOCTYPE html><html> <head> <title> jQuery UI datepicker format dd/mm/yyyy </title> <link type="text/css" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet" /> <script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.js"> </script> <script type="text/javascript" src= "https://code.jquery.com/ui/1.12.1/jquery-ui.js"> </script> <style type="text/css"> .ui-datepicker { font-size: 8pt !important } body { text-align: center; background-color: lightgray; } </style></head> <body> <h2 style="color:green"> GeeksforGeeks </h2> <form id="form1" runat="server"> <div class="demo"> <b>Date:</b> <input type="" name="" id="txtDate" runat="server" /> </div> <script type="text/javascript"> $(function () { $("#txtDate").datepicker({ dateFormat: 'dd/mm/yy' }); }); </script> </form></body> </html> Output: Syntax 2: <script type="text/javascript"> $(function() { $("#txtDate").datepicker({ dateFormat: 'yy/mm/dd' }); }); </script> Example: HTML <!DOCTYPE html><html> <head> <title> jQuery ui datepicker format dd/mm/yyyy </title> <link type="text/css" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet" /> <script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.js"> </script> <script type="text/javascript" src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"> </script> <style type="text/css"> .ui-datepicker { font-size: 8pt !important } body { text-align: center; background-color: lightgray; } </style></head> <body> <h2 style="color:green"> GeeksforGeeks </h2> <form id="form1" runat="server"> <div class="demo"> <b>Date:</b> <input type="" name="" id="txtDate" runat="server" /> </div> <script type="text/javascript"> $(function () { $("#txtDate").datepicker({ dateFormat: 'yy/mm/dd' }); }); </script> </form></body> </html> Output: jQuery-Questions jQuery-UI Picked JQuery Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. jQuery | children() with Examples How to get the value in an input text box using jQuery ? jQuery | ajax() Method How to prevent Body from scrolling when a modal is opened using jQuery ? How to redirect to a particular section of a page using HTML or jQuery? Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 53, "s": 25, "text": "\n10 Nov, 2021" }, { "code": null, "e": 320, "s": 53, "text": "In this article, we are going to learn about the Datepicker in jQuery. jQuery is the fastest and lightweight JavaScript library that is used to simplify the interactions between an HTML/CSS document, or more precisely the Document Object Model (DOM), and JavaScript." }, { "code": null, "e": 468, "s": 320, "text": "jQuery is widely famous for its motto of β€œWrite less, do more.” It simply means that you can achieve your goal by just writing a few lines of code." }, { "code": null, "e": 708, "s": 468, "text": "In many forms, you can select the date and year from the calendar. Datepicker is a standard form of the input field that is used to select the date and year by just seeing the calendar. It is an interactive calendar in a specified overlay." }, { "code": null, "e": 818, "s": 708, "text": "When you click on any date that is mentioned in the calendar then the feedback will appear on the input text." }, { "code": null, "e": 830, "s": 820, "text": "Approach:" }, { "code": null, "e": 881, "s": 830, "text": "Create an HTML file and import the jQuery library." }, { "code": null, "e": 970, "s": 881, "text": "The jQuery datepicker() method is used to create an overlay of an interactive calendar." }, { "code": null, "e": 1017, "s": 970, "text": "Apply CSS to your application as per the need." }, { "code": null, "e": 1027, "s": 1017, "text": "Syntax 1:" }, { "code": null, "e": 1180, "s": 1027, "text": "<script type=\"text/javascript\">\n $(function() {\n $(\"#txtDate\").datepicker({ \n dateFormat: 'dd/mm/yy' \n });\n });\n</script>" }, { "code": null, "e": 1189, "s": 1180, "text": "Example:" }, { "code": null, "e": 1194, "s": 1189, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title> jQuery UI datepicker format dd/mm/yyyy </title> <link type=\"text/css\" href=\"https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css\" rel=\"stylesheet\" /> <script type=\"text/javascript\" src=\"https://code.jquery.com/jquery-1.12.4.js\"> </script> <script type=\"text/javascript\" src= \"https://code.jquery.com/ui/1.12.1/jquery-ui.js\"> </script> <style type=\"text/css\"> .ui-datepicker { font-size: 8pt !important } body { text-align: center; background-color: lightgray; } </style></head> <body> <h2 style=\"color:green\"> GeeksforGeeks </h2> <form id=\"form1\" runat=\"server\"> <div class=\"demo\"> <b>Date:</b> <input type=\"\" name=\"\" id=\"txtDate\" runat=\"server\" /> </div> <script type=\"text/javascript\"> $(function () { $(\"#txtDate\").datepicker({ dateFormat: 'dd/mm/yy' }); }); </script> </form></body> </html>", "e": 2312, "s": 1194, "text": null }, { "code": null, "e": 2320, "s": 2312, "text": "Output:" }, { "code": null, "e": 2330, "s": 2320, "text": "Syntax 2:" }, { "code": null, "e": 2483, "s": 2330, "text": "<script type=\"text/javascript\">\n $(function() {\n $(\"#txtDate\").datepicker({ \n dateFormat: 'yy/mm/dd' \n });\n });\n</script>" }, { "code": null, "e": 2492, "s": 2483, "text": "Example:" }, { "code": null, "e": 2497, "s": 2492, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title> jQuery ui datepicker format dd/mm/yyyy </title> <link type=\"text/css\" href=\"https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css\" rel=\"stylesheet\" /> <script type=\"text/javascript\" src=\"https://code.jquery.com/jquery-1.12.4.js\"> </script> <script type=\"text/javascript\" src=\"https://code.jquery.com/ui/1.12.1/jquery-ui.js\"> </script> <style type=\"text/css\"> .ui-datepicker { font-size: 8pt !important } body { text-align: center; background-color: lightgray; } </style></head> <body> <h2 style=\"color:green\"> GeeksforGeeks </h2> <form id=\"form1\" runat=\"server\"> <div class=\"demo\"> <b>Date:</b> <input type=\"\" name=\"\" id=\"txtDate\" runat=\"server\" /> </div> <script type=\"text/javascript\"> $(function () { $(\"#txtDate\").datepicker({ dateFormat: 'yy/mm/dd' }); }); </script> </form></body> </html>", "e": 3615, "s": 2497, "text": null }, { "code": null, "e": 3623, "s": 3615, "text": "Output:" }, { "code": null, "e": 3640, "s": 3623, "text": "jQuery-Questions" }, { "code": null, "e": 3650, "s": 3640, "text": "jQuery-UI" }, { "code": null, "e": 3657, "s": 3650, "text": "Picked" }, { "code": null, "e": 3664, "s": 3657, "text": "JQuery" }, { "code": null, "e": 3681, "s": 3664, "text": "Web Technologies" }, { "code": null, "e": 3779, "s": 3681, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3813, "s": 3779, "text": "jQuery | children() with Examples" }, { "code": null, "e": 3870, "s": 3813, "text": "How to get the value in an input text box using jQuery ?" }, { "code": null, "e": 3893, "s": 3870, "text": "jQuery | ajax() Method" }, { "code": null, "e": 3966, "s": 3893, "text": "How to prevent Body from scrolling when a modal is opened using jQuery ?" }, { "code": null, "e": 4038, "s": 3966, "text": "How to redirect to a particular section of a page using HTML or jQuery?" }, { "code": null, "e": 4071, "s": 4038, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 4133, "s": 4071, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 4194, "s": 4133, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 4244, "s": 4194, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Design Snake Game
06 Oct, 2020 Let us see how to design a basic Snake Game which provides the following functionalities:β€’ Snake can move in a given direction and when it eats the food, the length of snake increases. β€’ When snake crosses itself, the game will over. β€’ Food will be generated at a given interval.Asked In: Amazon, Microsoft, and many more interviews This question is asked in interviews to Judge the Object-Oriented Design skill of a candidate. So, first of all, we should think about the classes. The main classes will be:1. Snake 2. Cell 3. Board 4. Game The class Game represents the body of our program. It stores information about the snake and the board.The Cell class represents the one point of display/board. It contains the row no, column no and the information about it i.e. it is empty or there is food on it or is it a part of snake body? Java // To represent a cell of display board.public class Cell { private final int row, col; private CellType cellType; public Cell(int row, int col) { this.row = row; this.col = col; } public CellType getCellType() { return cellType; } public void setCellType(CellType cellType) { this.cellType = cellType; } public int getRow() { return row; } public int getCol() { return col; }} Java // Enum for different cell types public enum CellType { EMPTY, FOOD, SNAKE_NODE;} Now, the Snake class, which contains the body and head. We have used Linked List to store the body because we can add a cell in O(1). Grow method will be called when it eats the food. Other methods are self-explanatory. Java // To represent a snakeimport java.util.LinkedList; public class Snake { private LinkedList<Cell> snakePartList = new LinkedList<>(); private Cell head; public Snake(Cell initPos) { head = initPos; snakePartList.add(head); head.setCellType(CellType.SNAKE_NODE); } public void grow() { snakePartList.add(head); } public void move(Cell nextCell) { System.out.println("Snake is moving to " + nextCell.getRow() + " " + nextCell.getCol()); Cell tail = snakePartList.removeLast(); tail.setCellType(CellType.EMPTY); head = nextCell; head.setCellType(CellType.SNAKE_NODE); snakePartList.addFirst(head); } public boolean checkCrash(Cell nextCell) { System.out.println("Going to check for Crash"); for (Cell cell : snakePartList) { if (cell == nextCell) { return true; } } return false; } public LinkedList<Cell> getSnakePartList() { return snakePartList; } public void setSnakePartList(LinkedList<Cell> snakePartList) { this.snakePartList = snakePartList; } public Cell getHead() { return head; } public void setHead(Cell head) { this.head = head; }} The Board class represents the display. It is a matrix of Cells. It has a method generate Food which generates the the food at a random position. Java public class Board { final int ROW_COUNT, COL_COUNT; private Cell[][] cells; public Board(int rowCount, int columnCount) { ROW_COUNT = rowCount; COL_COUNT = columnCount; cells = new Cell[ROW_COUNT][COL_COUNT]; for (int row = 0; row < ROW_COUNT; row++) { for (int column = 0; column < COL_COUNT; column++) { cells[row][column] = new Cell(row, column); } } } public Cell[][] getCells() { return cells; } public void setCells(Cell[][] cells) { this.cells = cells; } public void generateFood() { System.out.println("Going to generate food"); while(true){ int row = (int)(Math.random() * ROW_COUNT); int column = (int)(Math.random() * COL_COUNT); if(cells[row][column].getCellType()!=CellType.SNAKE_NODE) break; } cells[row][column].setCellType(CellType.FOOD); System.out.println("Food is generated at: " + row + " " + column); }} The main class (Game) which keeps the instance of Snake and Board. It’s method β€œupdate” needs to be called at a fixed interval (with the help of user input). Java // To represent Snake Gamepublic class Game { public static final int DIRECTION_NONE = 0, DIRECTION_RIGHT = 1, DIRECTION_LEFT = -1, DIRECTION_UP = 2, DIRECTION_DOWN = -2; private Snake snake; private Board board; private int direction; private boolean gameOver; public Game(Snake snake, Board board) { this.snake = snake; this.board = board; } public Snake getSnake() { return snake; } public void setSnake(Snake snake) { this.snake = snake; } public Board getBoard() { return board; } public void setBoard(Board board) { this.board = board; } public boolean isGameOver() { return gameOver; } public void setGameOver(boolean gameOver) { this.gameOver = gameOver; } public int getDirection() { return direction; } public void setDirection(int direction) { this.direction = direction; } // We need to update the game at regular intervals, // and accept user input from the Keyboard. public void update() { System.out.println("Going to update the game"); if (!gameOver) { if (direction != DIRECTION_NONE) { Cell nextCell = getNextCell(snake.getHead()); if (snake.checkCrash(nextCell)) { setDirection(DIRECTION_NONE); gameOver = true; } else { snake.move(nextCell); if (nextCell.getCellType() == CellType.FOOD) { snake.grow(); board.generateFood(); } } } } } private Cell getNextCell(Cell currentPosition) { System.out.println("Going to find next cell"); int row = currentPosition.getRow(); int col = currentPosition.getCol(); if (direction == DIRECTION_RIGHT) { col++; } else if (direction == DIRECTION_LEFT) { col--; } else if (direction == DIRECTION_UP) { row--; } else if (direction == DIRECTION_DOWN) { row++; } Cell nextCell = board.getCells()[row][col]; return nextCell; } public static void main(String[] args) { System.out.println("Going to start game"); Cell initPos = new Cell(0, 0); Snake initSnake = new Snake(initPos); Board board = new Board(10, 10); Game newGame = new Game(initSnake, board); newGame.gameOver = false; newGame.direction = DIRECTION_RIGHT; // We need to update the game at regular intervals, // and accept user input from the Keyboard. // here I have just called the different methods // to show the functionality for (int i = 0; i < 5; i++) { if (i == 2) newGame.board.generateFood(); newGame.update(); if (i == 3) newGame.direction = DIRECTION_RIGHT; if (newGame.gameOver == true) break; } }} Reference: http://massivetechinterview.blogspot.com/2015/10/snake-game-design.html shubham_singh Akanksha_Rai secret_giggle Object-Oriented-Design Technical Scripter 2018 Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n06 Oct, 2020" }, { "code": null, "e": 890, "s": 54, "text": "Let us see how to design a basic Snake Game which provides the following functionalities:β€’ Snake can move in a given direction and when it eats the food, the length of snake increases. β€’ When snake crosses itself, the game will over. β€’ Food will be generated at a given interval.Asked In: Amazon, Microsoft, and many more interviews This question is asked in interviews to Judge the Object-Oriented Design skill of a candidate. So, first of all, we should think about the classes. The main classes will be:1. Snake 2. Cell 3. Board 4. Game The class Game represents the body of our program. It stores information about the snake and the board.The Cell class represents the one point of display/board. It contains the row no, column no and the information about it i.e. it is empty or there is food on it or is it a part of snake body? " }, { "code": null, "e": 895, "s": 890, "text": "Java" }, { "code": "// To represent a cell of display board.public class Cell { private final int row, col; private CellType cellType; public Cell(int row, int col) { this.row = row; this.col = col; } public CellType getCellType() { return cellType; } public void setCellType(CellType cellType) { this.cellType = cellType; } public int getRow() { return row; } public int getCol() { return col; }}", "e": 1372, "s": 895, "text": null }, { "code": null, "e": 1377, "s": 1372, "text": "Java" }, { "code": "// Enum for different cell types public enum CellType { EMPTY, FOOD, SNAKE_NODE;}", "e": 1469, "s": 1377, "text": null }, { "code": null, "e": 1690, "s": 1469, "text": "Now, the Snake class, which contains the body and head. We have used Linked List to store the body because we can add a cell in O(1). Grow method will be called when it eats the food. Other methods are self-explanatory. " }, { "code": null, "e": 1695, "s": 1690, "text": "Java" }, { "code": "// To represent a snakeimport java.util.LinkedList; public class Snake { private LinkedList<Cell> snakePartList = new LinkedList<>(); private Cell head; public Snake(Cell initPos) { head = initPos; snakePartList.add(head); head.setCellType(CellType.SNAKE_NODE); } public void grow() { snakePartList.add(head); } public void move(Cell nextCell) { System.out.println(\"Snake is moving to \" + nextCell.getRow() + \" \" + nextCell.getCol()); Cell tail = snakePartList.removeLast(); tail.setCellType(CellType.EMPTY); head = nextCell; head.setCellType(CellType.SNAKE_NODE); snakePartList.addFirst(head); } public boolean checkCrash(Cell nextCell) { System.out.println(\"Going to check for Crash\"); for (Cell cell : snakePartList) { if (cell == nextCell) { return true; } } return false; } public LinkedList<Cell> getSnakePartList() { return snakePartList; } public void setSnakePartList(LinkedList<Cell> snakePartList) { this.snakePartList = snakePartList; } public Cell getHead() { return head; } public void setHead(Cell head) { this.head = head; }}", "e": 3012, "s": 1695, "text": null }, { "code": null, "e": 3159, "s": 3012, "text": "The Board class represents the display. It is a matrix of Cells. It has a method generate Food which generates the the food at a random position. " }, { "code": null, "e": 3164, "s": 3159, "text": "Java" }, { "code": "public class Board { final int ROW_COUNT, COL_COUNT; private Cell[][] cells; public Board(int rowCount, int columnCount) { ROW_COUNT = rowCount; COL_COUNT = columnCount; cells = new Cell[ROW_COUNT][COL_COUNT]; for (int row = 0; row < ROW_COUNT; row++) { for (int column = 0; column < COL_COUNT; column++) { cells[row][column] = new Cell(row, column); } } } public Cell[][] getCells() { return cells; } public void setCells(Cell[][] cells) { this.cells = cells; } public void generateFood() { System.out.println(\"Going to generate food\"); while(true){ int row = (int)(Math.random() * ROW_COUNT); int column = (int)(Math.random() * COL_COUNT); if(cells[row][column].getCellType()!=CellType.SNAKE_NODE) break; } cells[row][column].setCellType(CellType.FOOD); System.out.println(\"Food is generated at: \" + row + \" \" + column); }}", "e": 4208, "s": 3164, "text": null }, { "code": null, "e": 4367, "s": 4208, "text": "The main class (Game) which keeps the instance of Snake and Board. It’s method β€œupdate” needs to be called at a fixed interval (with the help of user input). " }, { "code": null, "e": 4372, "s": 4367, "text": "Java" }, { "code": "// To represent Snake Gamepublic class Game { public static final int DIRECTION_NONE = 0, DIRECTION_RIGHT = 1, DIRECTION_LEFT = -1, DIRECTION_UP = 2, DIRECTION_DOWN = -2; private Snake snake; private Board board; private int direction; private boolean gameOver; public Game(Snake snake, Board board) { this.snake = snake; this.board = board; } public Snake getSnake() { return snake; } public void setSnake(Snake snake) { this.snake = snake; } public Board getBoard() { return board; } public void setBoard(Board board) { this.board = board; } public boolean isGameOver() { return gameOver; } public void setGameOver(boolean gameOver) { this.gameOver = gameOver; } public int getDirection() { return direction; } public void setDirection(int direction) { this.direction = direction; } // We need to update the game at regular intervals, // and accept user input from the Keyboard. public void update() { System.out.println(\"Going to update the game\"); if (!gameOver) { if (direction != DIRECTION_NONE) { Cell nextCell = getNextCell(snake.getHead()); if (snake.checkCrash(nextCell)) { setDirection(DIRECTION_NONE); gameOver = true; } else { snake.move(nextCell); if (nextCell.getCellType() == CellType.FOOD) { snake.grow(); board.generateFood(); } } } } } private Cell getNextCell(Cell currentPosition) { System.out.println(\"Going to find next cell\"); int row = currentPosition.getRow(); int col = currentPosition.getCol(); if (direction == DIRECTION_RIGHT) { col++; } else if (direction == DIRECTION_LEFT) { col--; } else if (direction == DIRECTION_UP) { row--; } else if (direction == DIRECTION_DOWN) { row++; } Cell nextCell = board.getCells()[row][col]; return nextCell; } public static void main(String[] args) { System.out.println(\"Going to start game\"); Cell initPos = new Cell(0, 0); Snake initSnake = new Snake(initPos); Board board = new Board(10, 10); Game newGame = new Game(initSnake, board); newGame.gameOver = false; newGame.direction = DIRECTION_RIGHT; // We need to update the game at regular intervals, // and accept user input from the Keyboard. // here I have just called the different methods // to show the functionality for (int i = 0; i < 5; i++) { if (i == 2) newGame.board.generateFood(); newGame.update(); if (i == 3) newGame.direction = DIRECTION_RIGHT; if (newGame.gameOver == true) break; } }}", "e": 7492, "s": 4372, "text": null }, { "code": null, "e": 7576, "s": 7492, "text": "Reference: http://massivetechinterview.blogspot.com/2015/10/snake-game-design.html " }, { "code": null, "e": 7590, "s": 7576, "text": "shubham_singh" }, { "code": null, "e": 7603, "s": 7590, "text": "Akanksha_Rai" }, { "code": null, "e": 7617, "s": 7603, "text": "secret_giggle" }, { "code": null, "e": 7640, "s": 7617, "text": "Object-Oriented-Design" }, { "code": null, "e": 7664, "s": 7640, "text": "Technical Scripter 2018" }, { "code": null, "e": 7683, "s": 7664, "text": "Technical Scripter" } ]
PostgreSQL – ROW_NUMBER Function
10 Feb, 2021 In PostgreSQL, the ROW_NUMBER() function is used to assign a unique integer to every row that is returned by a query. Syntax: ROW_NUMBER() OVER( [PARTITION BY column_1, column_2, ...] [ORDER BY column_3, column_4, ...] ) Let’s analyze the above syntax: The set of rows on which the ROW_NUMBER() function operates is called a window. The PARTITION BY clause is used to divide the query set results. The ORDER BY clause inside the OVER clause is used to set the order in which the query result will be displayed. Example 1: First, create two tables named mammals and Animal_groups: CREATE TABLE Animal_groups ( animal_id serial PRIMARY KEY, animal_name VARCHAR (255) NOT NULL ); CREATE TABLE Mammals ( mammal_id serial PRIMARY KEY, mammal_name VARCHAR (255) NOT NULL, lifespan DECIMAL (11, 2), animal_id INT NOT NULL, FOREIGN KEY (animal_id) REFERENCES Animal_groups (animal_id) ); Now add some data to it: INSERT INTO Animal_groups (animal_name) VALUES ('Terrestrial'), ('Aquatic'), ('Winged'); INSERT INTO Mammals(mammal_name, animal_id, lifespan) VALUES ('Cow', 1, 10), ('Dog', 1, 7), ('Ox', 1, 13), ('Wolf', 1, 11), ('Blue Whale', 2, 80), ('Dolphin', 2, 5), ('Sea Horse', 2, 3), ('Octopus', 2, 8), ('Bat', 3, 4), ('Flying Squirrels', 3, 1), ('Petaurus', 3, 2); In the following query, we change the column in the ORDER BY clause to product_name, the ROW_NUMBER() function assigns the integer values to each row based on the product name order SELECT mammal_id, mammal_name, animal_id, ROW_NUMBER () OVER ( ORDER BY mammal_name ) FROM Mammals; Output: Example 2: The following query uses the ROW_NUMBER() function to assign integers to the distinct prices from the products table: SELECT DISTINCT lifespan, ROW_NUMBER () OVER (ORDER BY lifespan) FROM Mammals ORDER BY lifespan; Output: PostgreSQL-function PostgreSQL-Window-function PostgreSQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n10 Feb, 2021" }, { "code": null, "e": 171, "s": 53, "text": "In PostgreSQL, the ROW_NUMBER() function is used to assign a unique integer to every row that is returned by a query." }, { "code": null, "e": 282, "s": 171, "text": "Syntax:\nROW_NUMBER() OVER(\n [PARTITION BY column_1, column_2, ...]\n [ORDER BY column_3, column_4, ...]\n)" }, { "code": null, "e": 314, "s": 282, "text": "Let’s analyze the above syntax:" }, { "code": null, "e": 394, "s": 314, "text": "The set of rows on which the ROW_NUMBER() function operates is called a window." }, { "code": null, "e": 460, "s": 394, "text": "The PARTITION BY clause is used to divide the query set results. " }, { "code": null, "e": 573, "s": 460, "text": "The ORDER BY clause inside the OVER clause is used to set the order in which the query result will be displayed." }, { "code": null, "e": 584, "s": 573, "text": "Example 1:" }, { "code": null, "e": 642, "s": 584, "text": "First, create two tables named mammals and Animal_groups:" }, { "code": null, "e": 972, "s": 642, "text": "CREATE TABLE Animal_groups (\n animal_id serial PRIMARY KEY,\n animal_name VARCHAR (255) NOT NULL\n);\n\nCREATE TABLE Mammals (\n mammal_id serial PRIMARY KEY,\n mammal_name VARCHAR (255) NOT NULL,\n lifespan DECIMAL (11, 2),\n animal_id INT NOT NULL,\n FOREIGN KEY (animal_id) REFERENCES Animal_groups (animal_id)\n);\n" }, { "code": null, "e": 997, "s": 972, "text": "Now add some data to it:" }, { "code": null, "e": 1412, "s": 997, "text": "INSERT INTO Animal_groups (animal_name)\nVALUES\n ('Terrestrial'),\n ('Aquatic'),\n ('Winged');\n\nINSERT INTO Mammals(mammal_name, animal_id, lifespan)\nVALUES\n ('Cow', 1, 10),\n ('Dog', 1, 7),\n ('Ox', 1, 13),\n ('Wolf', 1, 11),\n ('Blue Whale', 2, 80),\n ('Dolphin', 2, 5),\n ('Sea Horse', 2, 3),\n ('Octopus', 2, 8),\n ('Bat', 3, 4),\n ('Flying Squirrels', 3, 1),\n ('Petaurus', 3, 2);" }, { "code": null, "e": 1594, "s": 1412, "text": "In the following query, we change the column in the ORDER BY clause to product_name, the ROW_NUMBER() function assigns the integer values to each row based on the product name order" }, { "code": null, "e": 1733, "s": 1594, "text": "SELECT\n mammal_id,\n mammal_name,\n animal_id,\n ROW_NUMBER () OVER (\n ORDER BY mammal_name\n )\nFROM\n Mammals;" }, { "code": null, "e": 1741, "s": 1733, "text": "Output:" }, { "code": null, "e": 1752, "s": 1741, "text": "Example 2:" }, { "code": null, "e": 1870, "s": 1752, "text": "The following query uses the ROW_NUMBER() function to assign integers to the distinct prices from the products table:" }, { "code": null, "e": 1983, "s": 1870, "text": "SELECT DISTINCT\n lifespan,\n ROW_NUMBER () OVER (ORDER BY lifespan)\nFROM\n Mammals\nORDER BY\n lifespan;" }, { "code": null, "e": 1991, "s": 1983, "text": "Output:" }, { "code": null, "e": 2011, "s": 1991, "text": "PostgreSQL-function" }, { "code": null, "e": 2038, "s": 2011, "text": "PostgreSQL-Window-function" }, { "code": null, "e": 2049, "s": 2038, "text": "PostgreSQL" } ]
Python | Check for Descending Sorted List
11 May, 2020 The sorted operation of list is essential operation in many application. But it takes best of O(nlogn) time complexity, hence one hopes to avoid this. So, to check if this is required or not, knowing if list is by default reverse sorted or not, one can check if list is sorted or not. Lets discuss various ways this can be achieved. Method #1 : Naive methodThe simplest way to check this is run a loop for first element and check if we could find any larger element than it after that element, if yes, the list is not reverse sorted. # Python3 code to demonstrate # Check for Descending Sorted List# using naive method # initializing listtest_list = [10, 8, 4, 3, 1] # printing original list print ("Original list : " + str(test_list)) # using naive method to # Check for Descending Sorted Listflag = 0i = 1while i < len(test_list): if(test_list[i] > test_list[i - 1]): flag = 1 i += 1 # printing resultif (not flag) : print ("Yes, List is reverse sorted.")else : print ("No, List is not reverse sorted.") Original list : [10, 8, 4, 3, 1] Yes, List is reverse sorted. Method #2 : Using sort() + reverseThe new list can be made as a copy of the original list, sorting the new list and comparing with the old list will give us the result if sorting was required to get reverse sorted list or not. # Python3 code to demonstrate # Check for Descending Sorted List# using sort() + reverse # initializing listtest_list = [10, 5, 4, 3, 1] # printing original list print ("Original list : " + str(test_list)) # using sort() + reverse to # Check for Descending Sorted Listflag = 0test_list1 = test_list[:]test_list1.sort(reverse = True)if (test_list1 == test_list): flag = 1 # printing resultif (flag) : print ("Yes, List is reverse sorted.")else : print ("No, List is not reverse sorted.") Original list : [10, 8, 4, 3, 1] Yes, List is reverse sorted. Python list-programs Python-Sorted Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python | Convert string dictionary to dictionary Python Program for Fibonacci numbers
[ { "code": null, "e": 28, "s": 0, "text": "\n11 May, 2020" }, { "code": null, "e": 361, "s": 28, "text": "The sorted operation of list is essential operation in many application. But it takes best of O(nlogn) time complexity, hence one hopes to avoid this. So, to check if this is required or not, knowing if list is by default reverse sorted or not, one can check if list is sorted or not. Lets discuss various ways this can be achieved." }, { "code": null, "e": 562, "s": 361, "text": "Method #1 : Naive methodThe simplest way to check this is run a loop for first element and check if we could find any larger element than it after that element, if yes, the list is not reverse sorted." }, { "code": "# Python3 code to demonstrate # Check for Descending Sorted List# using naive method # initializing listtest_list = [10, 8, 4, 3, 1] # printing original list print (\"Original list : \" + str(test_list)) # using naive method to # Check for Descending Sorted Listflag = 0i = 1while i < len(test_list): if(test_list[i] > test_list[i - 1]): flag = 1 i += 1 # printing resultif (not flag) : print (\"Yes, List is reverse sorted.\")else : print (\"No, List is not reverse sorted.\")", "e": 1062, "s": 562, "text": null }, { "code": null, "e": 1125, "s": 1062, "text": "Original list : [10, 8, 4, 3, 1]\nYes, List is reverse sorted.\n" }, { "code": null, "e": 1354, "s": 1127, "text": "Method #2 : Using sort() + reverseThe new list can be made as a copy of the original list, sorting the new list and comparing with the old list will give us the result if sorting was required to get reverse sorted list or not." }, { "code": "# Python3 code to demonstrate # Check for Descending Sorted List# using sort() + reverse # initializing listtest_list = [10, 5, 4, 3, 1] # printing original list print (\"Original list : \" + str(test_list)) # using sort() + reverse to # Check for Descending Sorted Listflag = 0test_list1 = test_list[:]test_list1.sort(reverse = True)if (test_list1 == test_list): flag = 1 # printing resultif (flag) : print (\"Yes, List is reverse sorted.\")else : print (\"No, List is not reverse sorted.\")", "e": 1858, "s": 1354, "text": null }, { "code": null, "e": 1921, "s": 1858, "text": "Original list : [10, 8, 4, 3, 1]\nYes, List is reverse sorted.\n" }, { "code": null, "e": 1942, "s": 1921, "text": "Python list-programs" }, { "code": null, "e": 1956, "s": 1942, "text": "Python-Sorted" }, { "code": null, "e": 1963, "s": 1956, "text": "Python" }, { "code": null, "e": 1979, "s": 1963, "text": "Python Programs" }, { "code": null, "e": 2077, "s": 1979, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2109, "s": 2077, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2136, "s": 2109, "text": "Python Classes and Objects" }, { "code": null, "e": 2157, "s": 2136, "text": "Python OOPs Concepts" }, { "code": null, "e": 2180, "s": 2157, "text": "Introduction To PYTHON" }, { "code": null, "e": 2236, "s": 2180, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2258, "s": 2236, "text": "Defaultdict in Python" }, { "code": null, "e": 2297, "s": 2258, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2335, "s": 2297, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 2384, "s": 2335, "text": "Python | Convert string dictionary to dictionary" } ]
How to write to an HTML file in Python ?
26 Mar, 2021 Python language has great uses today in almost every field, it can be used along with other technologies to make our lives easier. One such use of python is getting the data output in an HTML file. We can save any amount of our input data into an HTML file in python using the following examples in two ways. Example 1: Creating an HTML file and saving the input data into it. Approach: Creating an HTML file. Function_Name = open("Complete_File_Name","File_operation") Adding input data in HTML format into the file. Function_Name.write("Adding_Input_data_using_HTML_Synatx_separted_by_/n") Saving the HTML file. Function_Name.close() Opening the HTML file from the saved location. Below is the implementation: Python3 # Creating an HTML fileFunc = open("GFG-1.html","w") # Adding input data to the HTML fileFunc.write("<html>\n<head>\n<title> \nOutput Data in an HTML file \ </title>\n</head> <body><h1>Welcome to <u>GeeksforGeeks</u></h1>\ \n<h2>A <u>CS</u> Portal for Everyone</h2> \n</body></html>") # Saving the data into the HTML fileFunc.close() Output: GFG-1.html file is created in the folder Checking the Output data of the GFG-1.html file Example 2: Creating and Saving an HTML file and then adding input data to it. Approach: Creating an HTML file and saving it. Function_Name = open("Complete_File_Name","File_operation") Function_Name.close() Opening the HTML file from the saved location. Now adding input data into the created HTML file. Function_Name = open(File_Location,"File_operation") Function_Name.write("Adding_Input_data_using_HTML_Synatx_separted_by_/n") Saving the HTML file. Function_Name.close() Opening the HTML file from the saved location again to check the output data. Below is the implementation: Python3 # Opening the existing HTML fileFunc = open("GFG-2.html","w") # Adding input data to the HTML fileFunc.write("<html>\n<head>\n<title> \nOutput Data in an HTML file\n \ </title>\n</head> <body> <h1>Welcome to \ <font color = #00b300>GeeksforGeeks</font></h1>\n \ <h2>A CS Portal for Everyone</h2>\n</body></html>") # Saving the data into the HTML fileFunc.close() Output: Input data is saved into the GFG-2.html file Checking the Output data of the GFG-2.html file We’ve successfully saved and output data into an HTML file using a simple function in python. Any one of the above methods can be used to get the desired result. Picked python-file-handling 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 Mar, 2021" }, { "code": null, "e": 226, "s": 28, "text": "Python language has great uses today in almost every field, it can be used along with other technologies to make our lives easier. One such use of python is getting the data output in an HTML file." }, { "code": null, "e": 337, "s": 226, "text": "We can save any amount of our input data into an HTML file in python using the following examples in two ways." }, { "code": null, "e": 405, "s": 337, "text": "Example 1: Creating an HTML file and saving the input data into it." }, { "code": null, "e": 415, "s": 405, "text": "Approach:" }, { "code": null, "e": 438, "s": 415, "text": "Creating an HTML file." }, { "code": null, "e": 498, "s": 438, "text": "Function_Name = open(\"Complete_File_Name\",\"File_operation\")" }, { "code": null, "e": 546, "s": 498, "text": "Adding input data in HTML format into the file." }, { "code": null, "e": 620, "s": 546, "text": "Function_Name.write(\"Adding_Input_data_using_HTML_Synatx_separted_by_/n\")" }, { "code": null, "e": 642, "s": 620, "text": "Saving the HTML file." }, { "code": null, "e": 664, "s": 642, "text": "Function_Name.close()" }, { "code": null, "e": 711, "s": 664, "text": "Opening the HTML file from the saved location." }, { "code": null, "e": 740, "s": 711, "text": "Below is the implementation:" }, { "code": null, "e": 748, "s": 740, "text": "Python3" }, { "code": "# Creating an HTML fileFunc = open(\"GFG-1.html\",\"w\") # Adding input data to the HTML fileFunc.write(\"<html>\\n<head>\\n<title> \\nOutput Data in an HTML file \\ </title>\\n</head> <body><h1>Welcome to <u>GeeksforGeeks</u></h1>\\ \\n<h2>A <u>CS</u> Portal for Everyone</h2> \\n</body></html>\") # Saving the data into the HTML fileFunc.close()", "e": 1117, "s": 748, "text": null }, { "code": null, "e": 1125, "s": 1117, "text": "Output:" }, { "code": null, "e": 1166, "s": 1125, "text": "GFG-1.html file is created in the folder" }, { "code": null, "e": 1214, "s": 1166, "text": "Checking the Output data of the GFG-1.html file" }, { "code": null, "e": 1292, "s": 1214, "text": "Example 2: Creating and Saving an HTML file and then adding input data to it." }, { "code": null, "e": 1302, "s": 1292, "text": "Approach:" }, { "code": null, "e": 1339, "s": 1302, "text": "Creating an HTML file and saving it." }, { "code": null, "e": 1421, "s": 1339, "text": "Function_Name = open(\"Complete_File_Name\",\"File_operation\")\nFunction_Name.close()" }, { "code": null, "e": 1468, "s": 1421, "text": "Opening the HTML file from the saved location." }, { "code": null, "e": 1518, "s": 1468, "text": "Now adding input data into the created HTML file." }, { "code": null, "e": 1645, "s": 1518, "text": "Function_Name = open(File_Location,\"File_operation\")\nFunction_Name.write(\"Adding_Input_data_using_HTML_Synatx_separted_by_/n\")" }, { "code": null, "e": 1667, "s": 1645, "text": "Saving the HTML file." }, { "code": null, "e": 1689, "s": 1667, "text": "Function_Name.close()" }, { "code": null, "e": 1767, "s": 1689, "text": "Opening the HTML file from the saved location again to check the output data." }, { "code": null, "e": 1796, "s": 1767, "text": "Below is the implementation:" }, { "code": null, "e": 1804, "s": 1796, "text": "Python3" }, { "code": "# Opening the existing HTML fileFunc = open(\"GFG-2.html\",\"w\") # Adding input data to the HTML fileFunc.write(\"<html>\\n<head>\\n<title> \\nOutput Data in an HTML file\\n \\ </title>\\n</head> <body> <h1>Welcome to \\ <font color = #00b300>GeeksforGeeks</font></h1>\\n \\ <h2>A CS Portal for Everyone</h2>\\n</body></html>\") # Saving the data into the HTML fileFunc.close()", "e": 2199, "s": 1804, "text": null }, { "code": null, "e": 2207, "s": 2199, "text": "Output:" }, { "code": null, "e": 2252, "s": 2207, "text": "Input data is saved into the GFG-2.html file" }, { "code": null, "e": 2300, "s": 2252, "text": "Checking the Output data of the GFG-2.html file" }, { "code": null, "e": 2462, "s": 2300, "text": "We’ve successfully saved and output data into an HTML file using a simple function in python. Any one of the above methods can be used to get the desired result." }, { "code": null, "e": 2469, "s": 2462, "text": "Picked" }, { "code": null, "e": 2490, "s": 2469, "text": "python-file-handling" }, { "code": null, "e": 2497, "s": 2490, "text": "Python" } ]
Node.js Buffer.writeUInt8() Method
13 Oct, 2021 The Buffer.writeUInt8() method is an inbuilt application programming interface of class Buffer within Buffer module which is used to write values to buffer at the specified offset. The value should be a valid unsigned 8-bit integer otherwise behavior is undefined. Syntax: Buffer.writeUInt8( value, offset ) Parameters: This method accepts two parameters as mentioned above and described below: value: The unsigned integer value that to be written into buffer. offset: It denotes the number of bytes to skipped before starting to write to buffer. The offset can be in range 0 <= offset <= buf.length – 1. The default value of offset is 0. Return value: It returns the buffer with the value inserted at the specified offset. Below examples illustrate the use of Buffer.writeUInt8() Method in Node.js: Example 1: // Node.js program to demonstrate the // Buffer.writeUInt8() method // Creating a buffer const buf = Buffer.allocUnsafe(5); // Using Buffer.writeUInt8() methodbuf.writeUInt8(0x14, 0); // Display the bufferconsole.log(buf); // Using Buffer.writeUInt8() methodbuf.writeUInt8(0x15, 1); // Display the bufferconsole.log(buf); // Using Buffer.writeUInt8() methodbuf.writeUInt8(0x16, 4); // Display the bufferconsole.log(buf); // Using Buffer.writeUInt8() methodbuf.writeUInt8(0x17, 3); // Display the bufferconsole.log(buf); // Using Buffer.writeUInt8() methodbuf.writeUInt8(0x18, 2); // Display the result console.log(buf); Output: <Buffer 14 00 00 00 d6> <Buffer 14 15 00 00 d6> <Buffer 14 15 00 00 16> <Buffer 14 15 00 17 16> <Buffer 14 15 18 17 16> Example 2: // Node.js program to demonstrate the // Buffer.writeUInt8() method // Creating a buffer const buf = Buffer.allocUnsafe(3); // Using Buffer.writeUInt8() methodbuf.writeUInt8(0x11, 0); // Display the bufferconsole.log(buf); // Using Buffer.writeUInt8() methodbuf.writeUInt8(0x22, 1); // Display the bufferconsole.log(buf); // Using Buffer.writeUInt8() methodbuf.writeUInt8(0x33, 2); // Display the bufferconsole.log(buf); Output: <Buffer 11 e7 31> <Buffer 11 22 31> <Buffer 11 22 33> Note: The above program will compile and run by using the node index.js command. Reference: https://nodejs.org/dist/latest-v13.x/docs/api/buffer.html#buffer_buf_writeuint8_value_offset Node.js-Buffer-module Picked Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n13 Oct, 2021" }, { "code": null, "e": 293, "s": 28, "text": "The Buffer.writeUInt8() method is an inbuilt application programming interface of class Buffer within Buffer module which is used to write values to buffer at the specified offset. The value should be a valid unsigned 8-bit integer otherwise behavior is undefined." }, { "code": null, "e": 301, "s": 293, "text": "Syntax:" }, { "code": null, "e": 336, "s": 301, "text": "Buffer.writeUInt8( value, offset )" }, { "code": null, "e": 423, "s": 336, "text": "Parameters: This method accepts two parameters as mentioned above and described below:" }, { "code": null, "e": 489, "s": 423, "text": "value: The unsigned integer value that to be written into buffer." }, { "code": null, "e": 667, "s": 489, "text": "offset: It denotes the number of bytes to skipped before starting to write to buffer. The offset can be in range 0 <= offset <= buf.length – 1. The default value of offset is 0." }, { "code": null, "e": 752, "s": 667, "text": "Return value: It returns the buffer with the value inserted at the specified offset." }, { "code": null, "e": 828, "s": 752, "text": "Below examples illustrate the use of Buffer.writeUInt8() Method in Node.js:" }, { "code": null, "e": 839, "s": 828, "text": "Example 1:" }, { "code": "// Node.js program to demonstrate the // Buffer.writeUInt8() method // Creating a buffer const buf = Buffer.allocUnsafe(5); // Using Buffer.writeUInt8() methodbuf.writeUInt8(0x14, 0); // Display the bufferconsole.log(buf); // Using Buffer.writeUInt8() methodbuf.writeUInt8(0x15, 1); // Display the bufferconsole.log(buf); // Using Buffer.writeUInt8() methodbuf.writeUInt8(0x16, 4); // Display the bufferconsole.log(buf); // Using Buffer.writeUInt8() methodbuf.writeUInt8(0x17, 3); // Display the bufferconsole.log(buf); // Using Buffer.writeUInt8() methodbuf.writeUInt8(0x18, 2); // Display the result console.log(buf); ", "e": 1484, "s": 839, "text": null }, { "code": null, "e": 1492, "s": 1484, "text": "Output:" }, { "code": null, "e": 1613, "s": 1492, "text": "<Buffer 14 00 00 00 d6>\n<Buffer 14 15 00 00 d6>\n<Buffer 14 15 00 00 16>\n<Buffer 14 15 00 17 16>\n<Buffer 14 15 18 17 16>\n" }, { "code": null, "e": 1624, "s": 1613, "text": "Example 2:" }, { "code": "// Node.js program to demonstrate the // Buffer.writeUInt8() method // Creating a buffer const buf = Buffer.allocUnsafe(3); // Using Buffer.writeUInt8() methodbuf.writeUInt8(0x11, 0); // Display the bufferconsole.log(buf); // Using Buffer.writeUInt8() methodbuf.writeUInt8(0x22, 1); // Display the bufferconsole.log(buf); // Using Buffer.writeUInt8() methodbuf.writeUInt8(0x33, 2); // Display the bufferconsole.log(buf); ", "e": 2060, "s": 1624, "text": null }, { "code": null, "e": 2068, "s": 2060, "text": "Output:" }, { "code": null, "e": 2123, "s": 2068, "text": "<Buffer 11 e7 31>\n<Buffer 11 22 31>\n<Buffer 11 22 33>\n" }, { "code": null, "e": 2204, "s": 2123, "text": "Note: The above program will compile and run by using the node index.js command." }, { "code": null, "e": 2308, "s": 2204, "text": "Reference: https://nodejs.org/dist/latest-v13.x/docs/api/buffer.html#buffer_buf_writeuint8_value_offset" }, { "code": null, "e": 2330, "s": 2308, "text": "Node.js-Buffer-module" }, { "code": null, "e": 2337, "s": 2330, "text": "Picked" }, { "code": null, "e": 2345, "s": 2337, "text": "Node.js" }, { "code": null, "e": 2362, "s": 2345, "text": "Web Technologies" } ]
How to get title of current HTML page using jQuery ?
02 Mar, 2020 Suppose you have given an HTML page and the task is to get the title of an HTML page with the help of only jQuery. There are two approaches that are discussed below: Approach 1: The $(β€˜title’) jQuery selector is used to select the title element of the document and we can use text() method on the selector to get the title of the document. Example:<!DOCTYPE HTML> <html> <head> <title> Get title of current HTML page </title> <script src= "https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <style> body { text-align:center; } #gfg{ color: green; font-size: 24px; font-weight: bold; } </style></head> <body> <h1 style="color:green;"> GeeksforGeeks </h1> <b> Click on button to get HTML document's title </b> <br><br> <button onClick="GFG_Fun()"> click here</button> <p id="gfg"> </p> <script> var down = document.getElementById('gfg'); // Main function function GFG_Fun() { down.innerHTML = $('title').text(); } </script> </body> </html> <!DOCTYPE HTML> <html> <head> <title> Get title of current HTML page </title> <script src= "https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <style> body { text-align:center; } #gfg{ color: green; font-size: 24px; font-weight: bold; } </style></head> <body> <h1 style="color:green;"> GeeksforGeeks </h1> <b> Click on button to get HTML document's title </b> <br><br> <button onClick="GFG_Fun()"> click here</button> <p id="gfg"> </p> <script> var down = document.getElementById('gfg'); // Main function function GFG_Fun() { down.innerHTML = $('title').text(); } </script> </body> </html> Output: Approach 2: The $(document) jQuery selector is used to select the HTML document and we can use attr() method on the selector to get the title of the document by passing β€˜title’ as argument. Example:<!DOCTYPE HTML> <html> <head> <title> Get title of current HTML page </title> <script src= "https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <style> body { text-align:center; } #gfg{ color: green; font-size: 24px; font-weight: bold; } </style></head> <body> <h1 style="color:green;"> GeeksforGeeks </h1> <b> Click on button to get HTML document's title </b> <br><br> <button onClick="GFG_Fun()"> click here</button> <p id="gfg"> </p> <script> var down = document.getElementById('gfg'); // Main function function GFG_Fun() { down.innerHTML = $(document).attr('title'); } </script> </body> </html> <!DOCTYPE HTML> <html> <head> <title> Get title of current HTML page </title> <script src= "https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <style> body { text-align:center; } #gfg{ color: green; font-size: 24px; font-weight: bold; } </style></head> <body> <h1 style="color:green;"> GeeksforGeeks </h1> <b> Click on button to get HTML document's title </b> <br><br> <button onClick="GFG_Fun()"> click here</button> <p id="gfg"> </p> <script> var down = document.getElementById('gfg'); // Main function function GFG_Fun() { down.innerHTML = $(document).attr('title'); } </script> </body> </html> Output: CSS-Misc HTML-Misc jQuery-Misc CSS HTML JQuery Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n02 Mar, 2020" }, { "code": null, "e": 194, "s": 28, "text": "Suppose you have given an HTML page and the task is to get the title of an HTML page with the help of only jQuery. There are two approaches that are discussed below:" }, { "code": null, "e": 368, "s": 194, "text": "Approach 1: The $(β€˜title’) jQuery selector is used to select the title element of the document and we can use text() method on the selector to get the title of the document." }, { "code": null, "e": 1239, "s": 368, "text": "Example:<!DOCTYPE HTML> <html> <head> <title> Get title of current HTML page </title> <script src= \"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <style> body { text-align:center; } #gfg{ color: green; font-size: 24px; font-weight: bold; } </style></head> <body> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <b> Click on button to get HTML document's title </b> <br><br> <button onClick=\"GFG_Fun()\"> click here</button> <p id=\"gfg\"> </p> <script> var down = document.getElementById('gfg'); // Main function function GFG_Fun() { down.innerHTML = $('title').text(); } </script> </body> </html> " }, { "code": "<!DOCTYPE HTML> <html> <head> <title> Get title of current HTML page </title> <script src= \"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <style> body { text-align:center; } #gfg{ color: green; font-size: 24px; font-weight: bold; } </style></head> <body> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <b> Click on button to get HTML document's title </b> <br><br> <button onClick=\"GFG_Fun()\"> click here</button> <p id=\"gfg\"> </p> <script> var down = document.getElementById('gfg'); // Main function function GFG_Fun() { down.innerHTML = $('title').text(); } </script> </body> </html> ", "e": 2102, "s": 1239, "text": null }, { "code": null, "e": 2110, "s": 2102, "text": "Output:" }, { "code": null, "e": 2300, "s": 2110, "text": "Approach 2: The $(document) jQuery selector is used to select the HTML document and we can use attr() method on the selector to get the title of the document by passing β€˜title’ as argument." }, { "code": null, "e": 3179, "s": 2300, "text": "Example:<!DOCTYPE HTML> <html> <head> <title> Get title of current HTML page </title> <script src= \"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <style> body { text-align:center; } #gfg{ color: green; font-size: 24px; font-weight: bold; } </style></head> <body> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <b> Click on button to get HTML document's title </b> <br><br> <button onClick=\"GFG_Fun()\"> click here</button> <p id=\"gfg\"> </p> <script> var down = document.getElementById('gfg'); // Main function function GFG_Fun() { down.innerHTML = $(document).attr('title'); } </script> </body> </html> " }, { "code": "<!DOCTYPE HTML> <html> <head> <title> Get title of current HTML page </title> <script src= \"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <style> body { text-align:center; } #gfg{ color: green; font-size: 24px; font-weight: bold; } </style></head> <body> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <b> Click on button to get HTML document's title </b> <br><br> <button onClick=\"GFG_Fun()\"> click here</button> <p id=\"gfg\"> </p> <script> var down = document.getElementById('gfg'); // Main function function GFG_Fun() { down.innerHTML = $(document).attr('title'); } </script> </body> </html> ", "e": 4050, "s": 3179, "text": null }, { "code": null, "e": 4058, "s": 4050, "text": "Output:" }, { "code": null, "e": 4067, "s": 4058, "text": "CSS-Misc" }, { "code": null, "e": 4077, "s": 4067, "text": "HTML-Misc" }, { "code": null, "e": 4089, "s": 4077, "text": "jQuery-Misc" }, { "code": null, "e": 4093, "s": 4089, "text": "CSS" }, { "code": null, "e": 4098, "s": 4093, "text": "HTML" }, { "code": null, "e": 4105, "s": 4098, "text": "JQuery" }, { "code": null, "e": 4122, "s": 4105, "text": "Web Technologies" }, { "code": null, "e": 4149, "s": 4122, "text": "Web technologies Questions" }, { "code": null, "e": 4154, "s": 4149, "text": "HTML" } ]
Simplify Calculus for Machine Learning with SymPy | by Jeremiah Lutes | Towards Data Science
Machine learning requires some calculus. Many of the online Machine learning courses don’t always cover the basics of calculus assuming the user already has a foundation. If you are anything like me, you might need a bit of a refresher. Let’s take a look at a few basic calculus concepts and how to write them in your code using SymPy. Most of the time, we need calculus to find the derivatives in optimization problems. This helps us to decide whether to increase or decrease weights. Our end goal is to find an extreme point(s) that will be the local minimum or maximum point(s) in a function. Let’s go through the process of finding an extreme point by taking the following steps. Installing and learning the basics of Sympy.Finding the slope of a linear function.Discovering tangent and secant lines.Using our slope and tangent line knowledge to find limits.Understanding what the derivative of a function is.Using the derivative to find the extreme point.Deciding whether the extreme point is a local minimum or a maximum point. Installing and learning the basics of Sympy. Finding the slope of a linear function. Discovering tangent and secant lines. Using our slope and tangent line knowledge to find limits. Understanding what the derivative of a function is. Using the derivative to find the extreme point. Deciding whether the extreme point is a local minimum or a maximum point. SymPy is a Python library that lets you use symbols to compute various mathematic equations. It includes functions to calculate calculus equations. It also includes many other functions for some higher-level mathematics. Installing SymPy is simple you can find full installation instructions here. If you are already using Anaconda, SymPy is included. With Anacona you can make sure your SymPy is up to date with a simple: conda update sympy If you aren’t using Anaconda, pip is a great way to install new Python libraries. pip install sympy SymPy depends on the mpmath library so you’ll need that installed too. conda install mpmath#orpip install mpmath With SymPy we can create variables like we would in a math equation. We need to set these variables as symbols so SymPy knows to treat them differently than regular Python variables. This is simple and accomplished using the symbols() function. import sympyx2, y = sympy.symbols('x2 y') Now that we have SymPy installed let’s take a step back and look at the foundations of calculus. As mentioned above one of the main reasons we need calculus is to find the extreme point(s). To illustrate this, let’s pretend every year you enter the Annual Potato Cannon Contest. Every year you lose to the terrible Danny MacDougal. This year you hire a coach to help you beat Danny. To beat Danny, the coach needs you to give him three things. 1. When Danny’s potato is at it’s highest point. 2. How long it takes the potato to get to the highest point. 3. The slope of the potato at its highest point. Let’s talk first about the slope. If Danny built a magic cannon where the potato ascended forever finding the slope would be easy but there wouldn’t be a maximum height. This type of potato flight path is would be a linear equation like y = 3x + 2 (in y-intercept form). We can visualize this linear function potato flight using NumPy and Matplotlib. If you don’t have NumPy and Matplotlib installed the process is like the SymPy installation above. See here and here for more details. import matplotlib.pyplot as pltimport numpy as np#create 100 values for x ranging from 0 to 6x = np.linspace(0,6,100)#our linear functiony = 3*x + 2#add some aesthetics to out plotplt.grid(color='b', linestyle='--', linewidth=.5)plt.plot(x,y, label="potato flight")plt.xlim(0, 6)plt.ylim(0,20)plt.legend(loc='best')plt.xlabel("Seconds")plt.ylabel("Feet(x10)")#show the plot we createdplt.show() We want to examine the slope so we will add to marks on two random points: (1,5) and (4,14). plt.plot(1, 5, 'x', color='red')plt.plot(4, 14, 'x', color='red') When we have a linear function our slope is constant and we can calculate it by looking at any two points and calculating the change in y divided by the change x. Let’s look at the two points we marked earlier. In y-intercept form (y = mx + b) the m is always the slope. This checks out from our previous function of y = 3x + 2. The slope of a linear function is easy but the potato must come down. We need a way to calculate a slope that changes with each point. Let’s start by visualizing a more realistic potato flight path. Our coach is amazing and he knows the function that represents the flight of the potato is f(x) = -(x2) +4x. Once again let’s visualize this potato flight path with Matplotlib. x = np.linspace(0,5,100)y = -(x**2) + 4*xplt.xlim(0, 4.5)plt.ylim(0,4.5)plt.xlabel("Seconds")plt.ylabel("Height in Feet(x10)")plt.grid(color='b', linestyle='--', linewidth=.5)plt.plot(x, y, label="potato")plt.legend(loc='best')plt.show() From the visualization of the function, we see that in around 2 seconds the potato is at its height of around 40 feet. The graph is helpful but we still need the slope of the maximum height. Plus we need some hard evidence to bring back to the coach. Let’s move forward proving this height and time with calculus. A secant of a curve is a line that intersects the curve at a minimum of two distinct points. When we have nonlinear functions we can still find the slope between two points, or a secant line. Since (2,4) looks like the top of our potato path, let’s look at 2 points on our new nonlinear potato path: (1,3) and (2,4). #adding this code to our above plotx2 = np.linspace(1,2,100)y2 = x2 + 2plt.plot(x2,y2, color='green') We can see that the slope from (1,3) and (2,4) is 1. Let’s take this a step further and see what happens when we try to find the slope of just the point(2,4). To do so we need a line that will be able to represent going through one point. Let’s see what happens to the slope of our lines the closer we get to (2,4). To so we’ll draw a few more secant lines. We’ll keep the endpoint at (2,4) but one line will start at (1.5, 3,75) and the other one at (1.95, 3.9975). This gives us two more secant lines y3 = .5x + 3 and y4 = .05x + 3.9. When we finally reach (2,4) as our starting point, a line that forms, which is y = 0x +4. This is the tangent line for (2,4). The tangent line is calculated by solving the limit and plugging it into the y-intercept linear equation. More on the limit in a little bit. Every point in a function has a tangent line, which is how we can calculate the slope for every point in a function. Remember, our main goal is to find an extreme point, the maximum height of the potato. Extreme points will be when the slope of the tangent line is zero as this will signify when a function changes directions. For instance, let’s look at the slope for the tangent line going through (1,3) and one going through (3,3). Let’s look at what happened to the slope of the tangent line for these three points. point (1,3), the tangent line is y = 2x + 1, slope is 2 point (2,4), the tangent line is y = 0x + 4, slope is 0 point (3,3), the tangent line is y = -2x + 9, slope is -2 After 0 the slope changes directions. Perfect, we need to find the point or points that have a tangent line with a slope of zero. These points will tell us the maximum or minimum points as the direction of the tangent line slopes will always change after 0. Great! So we need to find a point on a function where the slope is zero. If only there was a to create a function that would give us the slope of any point in our original function. There is, and that is what the derivative is! Before we jump into derivatives let’s look at Limits. Limits allow us to find the slope of a function as it approaches a certain x value. If we are solving the limit as a secant line it’s easy. We plug in our two x values and two y values and we can solve the slope equation. This sort of limit defined. But, we want to find an undefined limit because we want the slope of the tangent line to the point (2,4). As we approach (2,4) we need the slope. We can’t get the slope of the secant line from (2,4) to (2,4) because if we plug those numbers into our slope equation we get 0/0. This won’t work because as a math teacher once said: β€œ There are two things in life you can’t do, nail jello to a wall and divide by zero”. Since we can’t divide by zero we need to find the undefined limit. Limits are solved by plugging our function into the slope equation and factoring it out. We can use our slope formula from before and substitute our point(2,4) for the x1/y1 values and then substitute the f(x) and x for the x2/y2 values. Our limit value is the x value we are approaching, which in this case is 2. Our new slope equation for limit 2 of the function -(x2) +4x is : Our goal is to get rid of the x on the denominator, so let’s expand the -(x2) and cancel out the x on the denominator. And now that we have removed the x from the denominator we can put plug 2 back into x. Now that we know how a limit is solved let’s fire up SymPy so we can solve the limit in our code. SymPy has a function named limit() which has 3 parameters. the function we’re finding the limit for the input variable the number the input variable is approaching Since our limit is undefined we need to substitute our x and y values as we did above. import sympyx2, y = sympy.symbols('x2 y')#store our substituted function as a y variabley = (-(x2**2) + 4 * x2 -4) / (x2 -2)limit = sympy.limit(y, x2, 2)// 0 Our limit is 0! The derivative is a function that will give us the slope of a tangent for any point in our function. Now we understand what the limit and tangent lines are we can head towards our end goal of using derivatives to find the extreme point(s) in the function. The process of finding a function’s derivative is differentiation. Solving the derivative uses some algebra and our slope formula from above. Because we aren’t solving for a specific point we won’t substitute any values. For this example let’s also replace x1 and x2 with the more common form, which is to use x and x +h. This will give us the following formula to solve for the derivative with fβ€²(x) meaning the derivative of the function of x: If we plug our function into this we get: We can then solve this similarly to how we solved for the limit. We can also use the power rule to solve to easily find our derivative using the following equation. Using that rule we can see the derivative of our function -(x2) +4x is -2x +4. Instead of going through the steps to find the derivative by hand let’s find the derivative using SymPy. SymPy gives us a function called diff() which will perform the differentiation process and returns the derivative. The diff function takes two parameters: the function we’re finding the derivative for the input variable Let’s give this function a try using our original function, -(x2) +4x. # set x as the variablex = sympy.symbols('x')#help make the out easier to readsympy.init_printing(use_unicode=True)#enter the our argumnets to th diff funtiond= sympy.diff(-(x**2) + 4*x, x)#print our derivativeprint(d)//-2*x + 4 Our extreme points in a function will be where our derivative is equal to zero. This is because when the derivative is equal to 0 the direction of the function has changed, as we explored above. To find the x value we set our derivative to equal 0 and solve for x, -2x + 4 = 0. This is solved with SymPy by using the function solveset(). Solvest takes two parameters: the Eq function which takes two parameters: the equation and the value the equation needs to equal the variable we are trying to solve Solvset will return a set for all numbers that solve the equation. Using solvset to find the x value when the derivative is equal to 0 will look like this: answer = sympy.solveset(sympy.Eq(d, 0),x)print(answer)//{2} Perfect! Our x value is 2 and if we plug that into the original function we get 4 as our y value. Now we are certain that at 2 seconds MacDougal’s potato is exactly 40 feet in the air and the slope at that point is 0! We can take that to the coach and we are sure to win the next potato cannon contest! We know our potato’s extreme point must be a max point because these potato cannons aren’t designed to shoot the potato down. But if we didn’t have a graph or know the direction of the function, how would we see if the extreme point(s) is a local minimum value or a local maximum. We already know that setting the x value of the derivative to 2 results in a slope of 0. What happens if we plug two more numbers into our derivative function, one number will be larger than 2 and the other will be less than 2. We will try this with 1 and 3. test1 = -2*1 + 4test2 = -2*3 + 4print(test1)//2print(test2)//-2 We see that before our extreme point the slope is positive and then after the extreme point our slope is negative. A change in slope from positive to negative tells us the extreme point is a maximum value. If the slope had gone from negative to positive we would know the extreme point is a minimum point. If there are multiple extreme points we would want to choose a value between each of the points. For instance, if we had extreme points 1 and 5, we would repeat this process three times: choose a random number less than 1 choose a random number greater than 1 but less than 5 choose a random number greater than 5 Most likely nonlinear functions won’t have only one extreme point. In this case, all of the steps are the same but when we solve for the derivative being equal to zero we get multiple solutions. SymPy vast library and is a great way to find the derivative and the local extreme point(s) in a function. SymPy is easy to use and simple to read adding simplicity and readability to any Machine learning project that requires calculus. We’ve only touched on a few of the many functions available with this library. I encourage you to explore it further and see what else can be used to incorporate mathematics into your data science projects.
[ { "code": null, "e": 507, "s": 171, "text": "Machine learning requires some calculus. Many of the online Machine learning courses don’t always cover the basics of calculus assuming the user already has a foundation. If you are anything like me, you might need a bit of a refresher. Let’s take a look at a few basic calculus concepts and how to write them in your code using SymPy." }, { "code": null, "e": 767, "s": 507, "text": "Most of the time, we need calculus to find the derivatives in optimization problems. This helps us to decide whether to increase or decrease weights. Our end goal is to find an extreme point(s) that will be the local minimum or maximum point(s) in a function." }, { "code": null, "e": 855, "s": 767, "text": "Let’s go through the process of finding an extreme point by taking the following steps." }, { "code": null, "e": 1205, "s": 855, "text": "Installing and learning the basics of Sympy.Finding the slope of a linear function.Discovering tangent and secant lines.Using our slope and tangent line knowledge to find limits.Understanding what the derivative of a function is.Using the derivative to find the extreme point.Deciding whether the extreme point is a local minimum or a maximum point." }, { "code": null, "e": 1250, "s": 1205, "text": "Installing and learning the basics of Sympy." }, { "code": null, "e": 1290, "s": 1250, "text": "Finding the slope of a linear function." }, { "code": null, "e": 1328, "s": 1290, "text": "Discovering tangent and secant lines." }, { "code": null, "e": 1387, "s": 1328, "text": "Using our slope and tangent line knowledge to find limits." }, { "code": null, "e": 1439, "s": 1387, "text": "Understanding what the derivative of a function is." }, { "code": null, "e": 1487, "s": 1439, "text": "Using the derivative to find the extreme point." }, { "code": null, "e": 1561, "s": 1487, "text": "Deciding whether the extreme point is a local minimum or a maximum point." }, { "code": null, "e": 1782, "s": 1561, "text": "SymPy is a Python library that lets you use symbols to compute various mathematic equations. It includes functions to calculate calculus equations. It also includes many other functions for some higher-level mathematics." }, { "code": null, "e": 1984, "s": 1782, "text": "Installing SymPy is simple you can find full installation instructions here. If you are already using Anaconda, SymPy is included. With Anacona you can make sure your SymPy is up to date with a simple:" }, { "code": null, "e": 2003, "s": 1984, "text": "conda update sympy" }, { "code": null, "e": 2085, "s": 2003, "text": "If you aren’t using Anaconda, pip is a great way to install new Python libraries." }, { "code": null, "e": 2103, "s": 2085, "text": "pip install sympy" }, { "code": null, "e": 2174, "s": 2103, "text": "SymPy depends on the mpmath library so you’ll need that installed too." }, { "code": null, "e": 2216, "s": 2174, "text": "conda install mpmath#orpip install mpmath" }, { "code": null, "e": 2461, "s": 2216, "text": "With SymPy we can create variables like we would in a math equation. We need to set these variables as symbols so SymPy knows to treat them differently than regular Python variables. This is simple and accomplished using the symbols() function." }, { "code": null, "e": 2503, "s": 2461, "text": "import sympyx2, y = sympy.symbols('x2 y')" }, { "code": null, "e": 2600, "s": 2503, "text": "Now that we have SymPy installed let’s take a step back and look at the foundations of calculus." }, { "code": null, "e": 2947, "s": 2600, "text": "As mentioned above one of the main reasons we need calculus is to find the extreme point(s). To illustrate this, let’s pretend every year you enter the Annual Potato Cannon Contest. Every year you lose to the terrible Danny MacDougal. This year you hire a coach to help you beat Danny. To beat Danny, the coach needs you to give him three things." }, { "code": null, "e": 2996, "s": 2947, "text": "1. When Danny’s potato is at it’s highest point." }, { "code": null, "e": 3057, "s": 2996, "text": "2. How long it takes the potato to get to the highest point." }, { "code": null, "e": 3106, "s": 3057, "text": "3. The slope of the potato at its highest point." }, { "code": null, "e": 3140, "s": 3106, "text": "Let’s talk first about the slope." }, { "code": null, "e": 3377, "s": 3140, "text": "If Danny built a magic cannon where the potato ascended forever finding the slope would be easy but there wouldn’t be a maximum height. This type of potato flight path is would be a linear equation like y = 3x + 2 (in y-intercept form)." }, { "code": null, "e": 3592, "s": 3377, "text": "We can visualize this linear function potato flight using NumPy and Matplotlib. If you don’t have NumPy and Matplotlib installed the process is like the SymPy installation above. See here and here for more details." }, { "code": null, "e": 3987, "s": 3592, "text": "import matplotlib.pyplot as pltimport numpy as np#create 100 values for x ranging from 0 to 6x = np.linspace(0,6,100)#our linear functiony = 3*x + 2#add some aesthetics to out plotplt.grid(color='b', linestyle='--', linewidth=.5)plt.plot(x,y, label=\"potato flight\")plt.xlim(0, 6)plt.ylim(0,20)plt.legend(loc='best')plt.xlabel(\"Seconds\")plt.ylabel(\"Feet(x10)\")#show the plot we createdplt.show()" }, { "code": null, "e": 4080, "s": 3987, "text": "We want to examine the slope so we will add to marks on two random points: (1,5) and (4,14)." }, { "code": null, "e": 4146, "s": 4080, "text": "plt.plot(1, 5, 'x', color='red')plt.plot(4, 14, 'x', color='red')" }, { "code": null, "e": 4357, "s": 4146, "text": "When we have a linear function our slope is constant and we can calculate it by looking at any two points and calculating the change in y divided by the change x. Let’s look at the two points we marked earlier." }, { "code": null, "e": 4475, "s": 4357, "text": "In y-intercept form (y = mx + b) the m is always the slope. This checks out from our previous function of y = 3x + 2." }, { "code": null, "e": 4674, "s": 4475, "text": "The slope of a linear function is easy but the potato must come down. We need a way to calculate a slope that changes with each point. Let’s start by visualizing a more realistic potato flight path." }, { "code": null, "e": 4783, "s": 4674, "text": "Our coach is amazing and he knows the function that represents the flight of the potato is f(x) = -(x2) +4x." }, { "code": null, "e": 4851, "s": 4783, "text": "Once again let’s visualize this potato flight path with Matplotlib." }, { "code": null, "e": 5089, "s": 4851, "text": "x = np.linspace(0,5,100)y = -(x**2) + 4*xplt.xlim(0, 4.5)plt.ylim(0,4.5)plt.xlabel(\"Seconds\")plt.ylabel(\"Height in Feet(x10)\")plt.grid(color='b', linestyle='--', linewidth=.5)plt.plot(x, y, label=\"potato\")plt.legend(loc='best')plt.show()" }, { "code": null, "e": 5403, "s": 5089, "text": "From the visualization of the function, we see that in around 2 seconds the potato is at its height of around 40 feet. The graph is helpful but we still need the slope of the maximum height. Plus we need some hard evidence to bring back to the coach. Let’s move forward proving this height and time with calculus." }, { "code": null, "e": 5720, "s": 5403, "text": "A secant of a curve is a line that intersects the curve at a minimum of two distinct points. When we have nonlinear functions we can still find the slope between two points, or a secant line. Since (2,4) looks like the top of our potato path, let’s look at 2 points on our new nonlinear potato path: (1,3) and (2,4)." }, { "code": null, "e": 5822, "s": 5720, "text": "#adding this code to our above plotx2 = np.linspace(1,2,100)y2 = x2 + 2plt.plot(x2,y2, color='green')" }, { "code": null, "e": 6061, "s": 5822, "text": "We can see that the slope from (1,3) and (2,4) is 1. Let’s take this a step further and see what happens when we try to find the slope of just the point(2,4). To do so we need a line that will be able to represent going through one point." }, { "code": null, "e": 6359, "s": 6061, "text": "Let’s see what happens to the slope of our lines the closer we get to (2,4). To so we’ll draw a few more secant lines. We’ll keep the endpoint at (2,4) but one line will start at (1.5, 3,75) and the other one at (1.95, 3.9975). This gives us two more secant lines y3 = .5x + 3 and y4 = .05x + 3.9." }, { "code": null, "e": 6743, "s": 6359, "text": "When we finally reach (2,4) as our starting point, a line that forms, which is y = 0x +4. This is the tangent line for (2,4). The tangent line is calculated by solving the limit and plugging it into the y-intercept linear equation. More on the limit in a little bit. Every point in a function has a tangent line, which is how we can calculate the slope for every point in a function." }, { "code": null, "e": 7061, "s": 6743, "text": "Remember, our main goal is to find an extreme point, the maximum height of the potato. Extreme points will be when the slope of the tangent line is zero as this will signify when a function changes directions. For instance, let’s look at the slope for the tangent line going through (1,3) and one going through (3,3)." }, { "code": null, "e": 7146, "s": 7061, "text": "Let’s look at what happened to the slope of the tangent line for these three points." }, { "code": null, "e": 7202, "s": 7146, "text": "point (1,3), the tangent line is y = 2x + 1, slope is 2" }, { "code": null, "e": 7258, "s": 7202, "text": "point (2,4), the tangent line is y = 0x + 4, slope is 0" }, { "code": null, "e": 7316, "s": 7258, "text": "point (3,3), the tangent line is y = -2x + 9, slope is -2" }, { "code": null, "e": 7574, "s": 7316, "text": "After 0 the slope changes directions. Perfect, we need to find the point or points that have a tangent line with a slope of zero. These points will tell us the maximum or minimum points as the direction of the tangent line slopes will always change after 0." }, { "code": null, "e": 7856, "s": 7574, "text": "Great! So we need to find a point on a function where the slope is zero. If only there was a to create a function that would give us the slope of any point in our original function. There is, and that is what the derivative is! Before we jump into derivatives let’s look at Limits." }, { "code": null, "e": 8212, "s": 7856, "text": "Limits allow us to find the slope of a function as it approaches a certain x value. If we are solving the limit as a secant line it’s easy. We plug in our two x values and two y values and we can solve the slope equation. This sort of limit defined. But, we want to find an undefined limit because we want the slope of the tangent line to the point (2,4)." }, { "code": null, "e": 8590, "s": 8212, "text": "As we approach (2,4) we need the slope. We can’t get the slope of the secant line from (2,4) to (2,4) because if we plug those numbers into our slope equation we get 0/0. This won’t work because as a math teacher once said: β€œ There are two things in life you can’t do, nail jello to a wall and divide by zero”. Since we can’t divide by zero we need to find the undefined limit." }, { "code": null, "e": 8970, "s": 8590, "text": "Limits are solved by plugging our function into the slope equation and factoring it out. We can use our slope formula from before and substitute our point(2,4) for the x1/y1 values and then substitute the f(x) and x for the x2/y2 values. Our limit value is the x value we are approaching, which in this case is 2. Our new slope equation for limit 2 of the function -(x2) +4x is :" }, { "code": null, "e": 9089, "s": 8970, "text": "Our goal is to get rid of the x on the denominator, so let’s expand the -(x2) and cancel out the x on the denominator." }, { "code": null, "e": 9176, "s": 9089, "text": "And now that we have removed the x from the denominator we can put plug 2 back into x." }, { "code": null, "e": 9274, "s": 9176, "text": "Now that we know how a limit is solved let’s fire up SymPy so we can solve the limit in our code." }, { "code": null, "e": 9333, "s": 9274, "text": "SymPy has a function named limit() which has 3 parameters." }, { "code": null, "e": 9374, "s": 9333, "text": "the function we’re finding the limit for" }, { "code": null, "e": 9393, "s": 9374, "text": "the input variable" }, { "code": null, "e": 9438, "s": 9393, "text": "the number the input variable is approaching" }, { "code": null, "e": 9525, "s": 9438, "text": "Since our limit is undefined we need to substitute our x and y values as we did above." }, { "code": null, "e": 9683, "s": 9525, "text": "import sympyx2, y = sympy.symbols('x2 y')#store our substituted function as a y variabley = (-(x2**2) + 4 * x2 -4) / (x2 -2)limit = sympy.limit(y, x2, 2)// 0" }, { "code": null, "e": 9699, "s": 9683, "text": "Our limit is 0!" }, { "code": null, "e": 9800, "s": 9699, "text": "The derivative is a function that will give us the slope of a tangent for any point in our function." }, { "code": null, "e": 10022, "s": 9800, "text": "Now we understand what the limit and tangent lines are we can head towards our end goal of using derivatives to find the extreme point(s) in the function. The process of finding a function’s derivative is differentiation." }, { "code": null, "e": 10401, "s": 10022, "text": "Solving the derivative uses some algebra and our slope formula from above. Because we aren’t solving for a specific point we won’t substitute any values. For this example let’s also replace x1 and x2 with the more common form, which is to use x and x +h. This will give us the following formula to solve for the derivative with fβ€²(x) meaning the derivative of the function of x:" }, { "code": null, "e": 10443, "s": 10401, "text": "If we plug our function into this we get:" }, { "code": null, "e": 10608, "s": 10443, "text": "We can then solve this similarly to how we solved for the limit. We can also use the power rule to solve to easily find our derivative using the following equation." }, { "code": null, "e": 10687, "s": 10608, "text": "Using that rule we can see the derivative of our function -(x2) +4x is -2x +4." }, { "code": null, "e": 10792, "s": 10687, "text": "Instead of going through the steps to find the derivative by hand let’s find the derivative using SymPy." }, { "code": null, "e": 10907, "s": 10792, "text": "SymPy gives us a function called diff() which will perform the differentiation process and returns the derivative." }, { "code": null, "e": 10947, "s": 10907, "text": "The diff function takes two parameters:" }, { "code": null, "e": 10993, "s": 10947, "text": "the function we’re finding the derivative for" }, { "code": null, "e": 11012, "s": 10993, "text": "the input variable" }, { "code": null, "e": 11083, "s": 11012, "text": "Let’s give this function a try using our original function, -(x2) +4x." }, { "code": null, "e": 11312, "s": 11083, "text": "# set x as the variablex = sympy.symbols('x')#help make the out easier to readsympy.init_printing(use_unicode=True)#enter the our argumnets to th diff funtiond= sympy.diff(-(x**2) + 4*x, x)#print our derivativeprint(d)//-2*x + 4" }, { "code": null, "e": 11507, "s": 11312, "text": "Our extreme points in a function will be where our derivative is equal to zero. This is because when the derivative is equal to 0 the direction of the function has changed, as we explored above." }, { "code": null, "e": 11590, "s": 11507, "text": "To find the x value we set our derivative to equal 0 and solve for x, -2x + 4 = 0." }, { "code": null, "e": 11680, "s": 11590, "text": "This is solved with SymPy by using the function solveset(). Solvest takes two parameters:" }, { "code": null, "e": 11779, "s": 11680, "text": "the Eq function which takes two parameters: the equation and the value the equation needs to equal" }, { "code": null, "e": 11815, "s": 11779, "text": "the variable we are trying to solve" }, { "code": null, "e": 11882, "s": 11815, "text": "Solvset will return a set for all numbers that solve the equation." }, { "code": null, "e": 11971, "s": 11882, "text": "Using solvset to find the x value when the derivative is equal to 0 will look like this:" }, { "code": null, "e": 12031, "s": 11971, "text": "answer = sympy.solveset(sympy.Eq(d, 0),x)print(answer)//{2}" }, { "code": null, "e": 12129, "s": 12031, "text": "Perfect! Our x value is 2 and if we plug that into the original function we get 4 as our y value." }, { "code": null, "e": 12334, "s": 12129, "text": "Now we are certain that at 2 seconds MacDougal’s potato is exactly 40 feet in the air and the slope at that point is 0! We can take that to the coach and we are sure to win the next potato cannon contest!" }, { "code": null, "e": 12874, "s": 12334, "text": "We know our potato’s extreme point must be a max point because these potato cannons aren’t designed to shoot the potato down. But if we didn’t have a graph or know the direction of the function, how would we see if the extreme point(s) is a local minimum value or a local maximum. We already know that setting the x value of the derivative to 2 results in a slope of 0. What happens if we plug two more numbers into our derivative function, one number will be larger than 2 and the other will be less than 2. We will try this with 1 and 3." }, { "code": null, "e": 12938, "s": 12874, "text": "test1 = -2*1 + 4test2 = -2*3 + 4print(test1)//2print(test2)//-2" }, { "code": null, "e": 13431, "s": 12938, "text": "We see that before our extreme point the slope is positive and then after the extreme point our slope is negative. A change in slope from positive to negative tells us the extreme point is a maximum value. If the slope had gone from negative to positive we would know the extreme point is a minimum point. If there are multiple extreme points we would want to choose a value between each of the points. For instance, if we had extreme points 1 and 5, we would repeat this process three times:" }, { "code": null, "e": 13466, "s": 13431, "text": "choose a random number less than 1" }, { "code": null, "e": 13520, "s": 13466, "text": "choose a random number greater than 1 but less than 5" }, { "code": null, "e": 13558, "s": 13520, "text": "choose a random number greater than 5" }, { "code": null, "e": 13753, "s": 13558, "text": "Most likely nonlinear functions won’t have only one extreme point. In this case, all of the steps are the same but when we solve for the derivative being equal to zero we get multiple solutions." } ]
Cryptography - Quick Guide
Human being from ages had two inherent needs βˆ’ (a) to communicate and share information and (b) to communicate selectively. These two needs gave rise to the art of coding the messages in such a way that only the intended people could have access to the information. Unauthorized people could not extract any information, even if the scrambled messages fell in their hand. The art and science of concealing the messages to introduce secrecy in information security is recognized as cryptography. The word β€˜cryptography’ was coined by combining two Greek words, β€˜Krypto’ meaning hidden and β€˜graphene’ meaning writing. The art of cryptography is considered to be born along with the art of writing. As civilizations evolved, human beings got organized in tribes, groups, and kingdoms. This led to the emergence of ideas such as power, battles, supremacy, and politics. These ideas further fueled the natural need of people to communicate secretly with selective recipient which in turn ensured the continuous evolution of cryptography as well. The roots of cryptography are found in Roman and Egyptian civilizations. The first known evidence of cryptography can be traced to the use of β€˜hieroglyph’. Some 4000 years ago, the Egyptians used to communicate by messages written in hieroglyph. This code was the secret known only to the scribes who used to transmit messages on behalf of the kings. One such hieroglyph is shown below. Later, the scholars moved on to using simple mono-alphabetic substitution ciphers during 500 to 600 BC. This involved replacing alphabets of message with other alphabets with some secret rule. This rule became a key to retrieve the message back from the garbled message. The earlier Roman method of cryptography, popularly known as the Caesar Shift Cipher, relies on shifting the letters of a message by an agreed number (three was a common choice), the recipient of this message would then shift the letters back by the same number and obtain the original message. Steganography is similar but adds another dimension to Cryptography. In this method, people not only want to protect the secrecy of an information by concealing it, but they also want to make sure any unauthorized person gets no evidence that the information even exists. For example, invisible watermarking. In steganography, an unintended recipient or an intruder is unaware of the fact that observed data contains hidden information. In cryptography, an intruder is normally aware that data is being communicated, because they can see the coded/scrambled message. It is during and after the European Renaissance, various Italian and Papal states led the rapid proliferation of cryptographic techniques. Various analysis and attack techniques were researched in this era to break the secret codes. Improved coding techniques such as Vigenere Coding came into existence in the 15th century, which offered moving letters in the message with a number of variable places instead of moving them the same number of places. Improved coding techniques such as Vigenere Coding came into existence in the 15th century, which offered moving letters in the message with a number of variable places instead of moving them the same number of places. Only after the 19th century, cryptography evolved from the ad hoc approaches to encryption to the more sophisticated art and science of information security. Only after the 19th century, cryptography evolved from the ad hoc approaches to encryption to the more sophisticated art and science of information security. In the early 20th century, the invention of mechanical and electromechanical machines, such as the Enigma rotor machine, provided more advanced and efficient means of coding the information. In the early 20th century, the invention of mechanical and electromechanical machines, such as the Enigma rotor machine, provided more advanced and efficient means of coding the information. During the period of World War II, both cryptography and cryptanalysis became excessively mathematical. During the period of World War II, both cryptography and cryptanalysis became excessively mathematical. With the advances taking place in this field, government organizations, military units, and some corporate houses started adopting the applications of cryptography. They used cryptography to guard their secrets from others. Now, the arrival of computers and the Internet has brought effective cryptography within the reach of common people. Modern cryptography is the cornerstone of computer and communications security. Its foundation is based on various concepts of mathematics such as number theory, computational-complexity theory, and probability theory. There are three major characteristics that separate modern cryptography from the classical approach. Cryptology, the study of cryptosystems, can be subdivided into two branches βˆ’ Cryptography Cryptanalysis Cryptography is the art and science of making a cryptosystem that is capable of providing information security. Cryptography deals with the actual securing of digital data. It refers to the design of mechanisms based on mathematical algorithms that provide fundamental information security services. You can think of cryptography as the establishment of a large toolkit containing different techniques in security applications. The art and science of breaking the cipher text is known as cryptanalysis. Cryptanalysis is the sister branch of cryptography and they both co-exist. The cryptographic process results in the cipher text for transmission or storage. It involves the study of cryptographic mechanism with the intention to break them. Cryptanalysis is also used during the design of the new cryptographic techniques to test their security strengths. Note βˆ’ Cryptography concerns with the design of cryptosystems, while cryptanalysis studies the breaking of cryptosystems. The primary objective of using cryptography is to provide the following four fundamental information security services. Let us now see the possible goals intended to be fulfilled by cryptography. Confidentiality is the fundamental security service provided by cryptography. It is a security service that keeps the information from an unauthorized person. It is sometimes referred to as privacy or secrecy. Confidentiality can be achieved through numerous means starting from physical securing to the use of mathematical algorithms for data encryption. It is security service that deals with identifying any alteration to the data. The data may get modified by an unauthorized entity intentionally or accidently. Integrity service confirms that whether data is intact or not since it was last created, transmitted, or stored by an authorized user. Data integrity cannot prevent the alteration of data, but provides a means for detecting whether data has been manipulated in an unauthorized manner. Authentication provides the identification of the originator. It confirms to the receiver that the data received has been sent only by an identified and verified sender. Authentication service has two variants βˆ’ Message authentication identifies the originator of the message without any regard router or system that has sent the message. Message authentication identifies the originator of the message without any regard router or system that has sent the message. Entity authentication is assurance that data has been received from a specific entity, say a particular website. Entity authentication is assurance that data has been received from a specific entity, say a particular website. Apart from the originator, authentication may also provide assurance about other parameters related to data such as the date and time of creation/transmission. It is a security service that ensures that an entity cannot refuse the ownership of a previous commitment or an action. It is an assurance that the original creator of the data cannot deny the creation or transmission of the said data to a recipient or third party. Non-repudiation is a property that is most desirable in situations where there are chances of a dispute over the exchange of data. For example, once an order is placed electronically, a purchaser cannot deny the purchase order, if non-repudiation service was enabled in this transaction. Cryptography primitives are nothing but the tools and techniques in Cryptography that can be selectively used to provide a set of desired security services βˆ’ Encryption Hash functions Message Authentication codes (MAC) Digital Signatures The following table shows the primitives that can achieve a particular security service on their own. Note βˆ’ Cryptographic primitives are intricately related and they are often combined to achieve a set of desired security services from a cryptosystem. A cryptosystem is an implementation of cryptographic techniques and their accompanying infrastructure to provide information security services. A cryptosystem is also referred to as a cipher system. Let us discuss a simple model of a cryptosystem that provides confidentiality to the information being transmitted. This basic model is depicted in the illustration below βˆ’ The illustration shows a sender who wants to transfer some sensitive data to a receiver in such a way that any party intercepting or eavesdropping on the communication channel cannot extract the data. The objective of this simple cryptosystem is that at the end of the process, only the sender and the receiver will know the plaintext. The various components of a basic cryptosystem are as follows βˆ’ Plaintext. It is the data to be protected during transmission. Plaintext. It is the data to be protected during transmission. Encryption Algorithm. It is a mathematical process that produces a ciphertext for any given plaintext and encryption key. It is a cryptographic algorithm that takes plaintext and an encryption key as input and produces a ciphertext. Encryption Algorithm. It is a mathematical process that produces a ciphertext for any given plaintext and encryption key. It is a cryptographic algorithm that takes plaintext and an encryption key as input and produces a ciphertext. Ciphertext. It is the scrambled version of the plaintext produced by the encryption algorithm using a specific the encryption key. The ciphertext is not guarded. It flows on public channel. It can be intercepted or compromised by anyone who has access to the communication channel. Ciphertext. It is the scrambled version of the plaintext produced by the encryption algorithm using a specific the encryption key. The ciphertext is not guarded. It flows on public channel. It can be intercepted or compromised by anyone who has access to the communication channel. Decryption Algorithm, It is a mathematical process, that produces a unique plaintext for any given ciphertext and decryption key. It is a cryptographic algorithm that takes a ciphertext and a decryption key as input, and outputs a plaintext. The decryption algorithm essentially reverses the encryption algorithm and is thus closely related to it. Decryption Algorithm, It is a mathematical process, that produces a unique plaintext for any given ciphertext and decryption key. It is a cryptographic algorithm that takes a ciphertext and a decryption key as input, and outputs a plaintext. The decryption algorithm essentially reverses the encryption algorithm and is thus closely related to it. Encryption Key. It is a value that is known to the sender. The sender inputs the encryption key into the encryption algorithm along with the plaintext in order to compute the ciphertext. Encryption Key. It is a value that is known to the sender. The sender inputs the encryption key into the encryption algorithm along with the plaintext in order to compute the ciphertext. Decryption Key. It is a value that is known to the receiver. The decryption key is related to the encryption key, but is not always identical to it. The receiver inputs the decryption key into the decryption algorithm along with the ciphertext in order to compute the plaintext. Decryption Key. It is a value that is known to the receiver. The decryption key is related to the encryption key, but is not always identical to it. The receiver inputs the decryption key into the decryption algorithm along with the ciphertext in order to compute the plaintext. For a given cryptosystem, a collection of all possible decryption keys is called a key space. An interceptor (an attacker) is an unauthorized entity who attempts to determine the plaintext. He can see the ciphertext and may know the decryption algorithm. He, however, must never know the decryption key. Fundamentally, there are two types of cryptosystems based on the manner in which encryption-decryption is carried out in the system βˆ’ Symmetric Key Encryption Asymmetric Key Encryption The main difference between these cryptosystems is the relationship between the encryption and the decryption key. Logically, in any cryptosystem, both the keys are closely associated. It is practically impossible to decrypt the ciphertext with the key that is unrelated to the encryption key. The encryption process where same keys are used for encrypting and decrypting the information is known as Symmetric Key Encryption. The study of symmetric cryptosystems is referred to as symmetric cryptography. Symmetric cryptosystems are also sometimes referred to as secret key cryptosystems. A few well-known examples of symmetric key encryption methods are βˆ’ Digital Encryption Standard (DES), Triple-DES (3DES), IDEA, and BLOWFISH. Prior to 1970, all cryptosystems employed symmetric key encryption. Even today, its relevance is very high and it is being used extensively in many cryptosystems. It is very unlikely that this encryption will fade away, as it has certain advantages over asymmetric key encryption. The salient features of cryptosystem based on symmetric key encryption are βˆ’ Persons using symmetric key encryption must share a common key prior to exchange of information. Persons using symmetric key encryption must share a common key prior to exchange of information. Keys are recommended to be changed regularly to prevent any attack on the system. Keys are recommended to be changed regularly to prevent any attack on the system. A robust mechanism needs to exist to exchange the key between the communicating parties. As keys are required to be changed regularly, this mechanism becomes expensive and cumbersome. A robust mechanism needs to exist to exchange the key between the communicating parties. As keys are required to be changed regularly, this mechanism becomes expensive and cumbersome. In a group of n people, to enable two-party communication between any two persons, the number of keys required for group is n Γ— (n – 1)/2. In a group of n people, to enable two-party communication between any two persons, the number of keys required for group is n Γ— (n – 1)/2. Length of Key (number of bits) in this encryption is smaller and hence, process of encryption-decryption is faster than asymmetric key encryption. Length of Key (number of bits) in this encryption is smaller and hence, process of encryption-decryption is faster than asymmetric key encryption. Processing power of computer system required to run symmetric algorithm is less. Processing power of computer system required to run symmetric algorithm is less. There are two restrictive challenges of employing symmetric key cryptography. Key establishment βˆ’ Before any communication, both the sender and the receiver need to agree on a secret symmetric key. It requires a secure key establishment mechanism in place. Key establishment βˆ’ Before any communication, both the sender and the receiver need to agree on a secret symmetric key. It requires a secure key establishment mechanism in place. Trust Issue βˆ’ Since the sender and the receiver use the same symmetric key, there is an implicit requirement that the sender and the receiver β€˜trust’ each other. For example, it may happen that the receiver has lost the key to an attacker and the sender is not informed. Trust Issue βˆ’ Since the sender and the receiver use the same symmetric key, there is an implicit requirement that the sender and the receiver β€˜trust’ each other. For example, it may happen that the receiver has lost the key to an attacker and the sender is not informed. These two challenges are highly restraining for modern day communication. Today, people need to exchange information with non-familiar and non-trusted parties. For example, a communication between online seller and customer. These limitations of symmetric key encryption gave rise to asymmetric key encryption schemes. The encryption process where different keys are used for encrypting and decrypting the information is known as Asymmetric Key Encryption. Though the keys are different, they are mathematically related and hence, retrieving the plaintext by decrypting ciphertext is feasible. The process is depicted in the following illustration βˆ’ Asymmetric Key Encryption was invented in the 20th century to come over the necessity of pre-shared secret key between communicating persons. The salient features of this encryption scheme are as follows βˆ’ Every user in this system needs to have a pair of dissimilar keys, private key and public key. These keys are mathematically related βˆ’ when one key is used for encryption, the other can decrypt the ciphertext back to the original plaintext. Every user in this system needs to have a pair of dissimilar keys, private key and public key. These keys are mathematically related βˆ’ when one key is used for encryption, the other can decrypt the ciphertext back to the original plaintext. It requires to put the public key in public repository and the private key as a well-guarded secret. Hence, this scheme of encryption is also called Public Key Encryption. It requires to put the public key in public repository and the private key as a well-guarded secret. Hence, this scheme of encryption is also called Public Key Encryption. Though public and private keys of the user are related, it is computationally not feasible to find one from another. This is a strength of this scheme. Though public and private keys of the user are related, it is computationally not feasible to find one from another. This is a strength of this scheme. When Host1 needs to send data to Host2, he obtains the public key of Host2 from repository, encrypts the data, and transmits. When Host1 needs to send data to Host2, he obtains the public key of Host2 from repository, encrypts the data, and transmits. Host2 uses his private key to extract the plaintext. Host2 uses his private key to extract the plaintext. Length of Keys (number of bits) in this encryption is large and hence, the process of encryption-decryption is slower than symmetric key encryption. Length of Keys (number of bits) in this encryption is large and hence, the process of encryption-decryption is slower than symmetric key encryption. Processing power of computer system required to run asymmetric algorithm is higher. Processing power of computer system required to run asymmetric algorithm is higher. Symmetric cryptosystems are a natural concept. In contrast, public-key cryptosystems are quite difficult to comprehend. You may think, how can the encryption key and the decryption key are β€˜related’, and yet it is impossible to determine the decryption key from the encryption key? The answer lies in the mathematical concepts. It is possible to design a cryptosystem whose keys have this property. The concept of public-key cryptography is relatively new. There are fewer public-key algorithms known than symmetric algorithms. Public-key cryptosystems have one significant challenge βˆ’ the user needs to trust that the public key that he is using in communications with a person really is the public key of that person and has not been spoofed by a malicious third party. This is usually accomplished through a Public Key Infrastructure (PKI) consisting a trusted third party. The third party securely manages and attests to the authenticity of public keys. When the third party is requested to provide the public key for any communicating person X, they are trusted to provide the correct public key. The third party satisfies itself about user identity by the process of attestation, notarization, or some other process βˆ’ that X is the one and only, or globally unique, X. The most common method of making the verified public keys available is to embed them in a certificate which is digitally signed by the trusted third party. A summary of basic key properties of two types of cryptosystems is given below βˆ’ Due to the advantages and disadvantage of both the systems, symmetric key and public-key cryptosystems are often used together in the practical information security systems. In the 19th century, a Dutch cryptographer A. Kerckhoff furnished the requirements of a good cryptosystem. Kerckhoff stated that a cryptographic system should be secure even if everything about the system, except the key, is public knowledge. The six design principles defined by Kerckhoff for cryptosystem are βˆ’ The cryptosystem should be unbreakable practically, if not mathematically. The cryptosystem should be unbreakable practically, if not mathematically. Falling of the cryptosystem in the hands of an intruder should not lead to any compromise of the system, preventing any inconvenience to the user. Falling of the cryptosystem in the hands of an intruder should not lead to any compromise of the system, preventing any inconvenience to the user. The key should be easily communicable, memorable, and changeable. The key should be easily communicable, memorable, and changeable. The ciphertext should be transmissible by telegraph, an unsecure channel. The ciphertext should be transmissible by telegraph, an unsecure channel. The encryption apparatus and documents should be portable and operable by a single person. The encryption apparatus and documents should be portable and operable by a single person. Finally, it is necessary that the system be easy to use, requiring neither mental strain nor the knowledge of a long series of rules to observe. Finally, it is necessary that the system be easy to use, requiring neither mental strain nor the knowledge of a long series of rules to observe. The second rule is currently known as Kerckhoff principle. It is applied in virtually all the contemporary encryption algorithms such as DES, AES, etc. These public algorithms are considered to be thoroughly secure. The security of the encrypted message depends solely on the security of the secret encryption key. Keeping the algorithms secret may act as a significant barrier to cryptanalysis. However, keeping the algorithms secret is possible only when they are used in a strictly limited circle. In modern era, cryptography needs to cater to users who are connected to the Internet. In such cases, using a secret algorithm is not feasible, hence Kerckhoff principles became essential guidelines for designing algorithms in modern cryptography. In the present era, not only business but almost all the aspects of human life are driven by information. Hence, it has become imperative to protect useful information from malicious activities such as attacks. Let us consider the types of attacks to which information is typically subjected to. Attacks are typically categorized based on the action performed by the attacker. An attack, thus, can be passive or active. The main goal of a passive attack is to obtain unauthorized access to the information. For example, actions such as intercepting and eavesdropping on the communication channel can be regarded as passive attack. These actions are passive in nature, as they neither affect information nor disrupt the communication channel. A passive attack is often seen as stealing information. The only difference in stealing physical goods and stealing information is that theft of data still leaves the owner in possession of that data. Passive information attack is thus more dangerous than stealing of goods, as information theft may go unnoticed by the owner. An active attack involves changing the information in some way by conducting some process on the information. For example, Modifying the information in an unauthorized manner. Modifying the information in an unauthorized manner. Initiating unintended or unauthorized transmission of information. Initiating unintended or unauthorized transmission of information. Alteration of authentication data such as originator name or timestamp associated with information Alteration of authentication data such as originator name or timestamp associated with information Unauthorized deletion of data. Unauthorized deletion of data. Denial of access to information for legitimate users (denial of service). Denial of access to information for legitimate users (denial of service). Cryptography provides many tools and techniques for implementing cryptosystems capable of preventing most of the attacks described above. Let us see the prevailing environment around cryptosystems followed by the types of attacks employed to break these systems βˆ’ While considering possible attacks on the cryptosystem, it is necessary to know the cryptosystems environment. The attacker’s assumptions and knowledge about the environment decides his capabilities. In cryptography, the following three assumptions are made about the security environment and attacker’s capabilities. The design of a cryptosystem is based on the following two cryptography algorithms βˆ’ Public Algorithms βˆ’ With this option, all the details of the algorithm are in the public domain, known to everyone. Public Algorithms βˆ’ With this option, all the details of the algorithm are in the public domain, known to everyone. Proprietary algorithms βˆ’ The details of the algorithm are only known by the system designers and users. Proprietary algorithms βˆ’ The details of the algorithm are only known by the system designers and users. In case of proprietary algorithms, security is ensured through obscurity. Private algorithms may not be the strongest algorithms as they are developed in-house and may not be extensively investigated for weakness. Secondly, they allow communication among closed group only. Hence they are not suitable for modern communication where people communicate with large number of known or unknown entities. Also, according to Kerckhoff’s principle, the algorithm is preferred to be public with strength of encryption lying in the key. Thus, the first assumption about security environment is that the encryption algorithm is known to the attacker. We know that once the plaintext is encrypted into ciphertext, it is put on unsecure public channel (say email) for transmission. Thus, the attacker can obviously assume that it has access to the ciphertext generated by the cryptosystem. This assumption is not as obvious as other. However, there may be situations where an attacker can have access to plaintext and corresponding ciphertext. Some such possible circumstances are βˆ’ The attacker influences the sender to convert plaintext of his choice and obtains the ciphertext. The attacker influences the sender to convert plaintext of his choice and obtains the ciphertext. The receiver may divulge the plaintext to the attacker inadvertently. The attacker has access to corresponding ciphertext gathered from open channel. The receiver may divulge the plaintext to the attacker inadvertently. The attacker has access to corresponding ciphertext gathered from open channel. In a public-key cryptosystem, the encryption key is in open domain and is known to any potential attacker. Using this key, he can generate pairs of corresponding plaintexts and ciphertexts. In a public-key cryptosystem, the encryption key is in open domain and is known to any potential attacker. Using this key, he can generate pairs of corresponding plaintexts and ciphertexts. The basic intention of an attacker is to break a cryptosystem and to find the plaintext from the ciphertext. To obtain the plaintext, the attacker only needs to find out the secret decryption key, as the algorithm is already in public domain. Hence, he applies maximum effort towards finding out the secret key used in the cryptosystem. Once the attacker is able to determine the key, the attacked system is considered as broken or compromised. Based on the methodology used, attacks on cryptosystems are categorized as follows βˆ’ Ciphertext Only Attacks (COA) βˆ’ In this method, the attacker has access to a set of ciphertext(s). He does not have access to corresponding plaintext. COA is said to be successful when the corresponding plaintext can be determined from a given set of ciphertext. Occasionally, the encryption key can be determined from this attack. Modern cryptosystems are guarded against ciphertext-only attacks. Ciphertext Only Attacks (COA) βˆ’ In this method, the attacker has access to a set of ciphertext(s). He does not have access to corresponding plaintext. COA is said to be successful when the corresponding plaintext can be determined from a given set of ciphertext. Occasionally, the encryption key can be determined from this attack. Modern cryptosystems are guarded against ciphertext-only attacks. Known Plaintext Attack (KPA) βˆ’ In this method, the attacker knows the plaintext for some parts of the ciphertext. The task is to decrypt the rest of the ciphertext using this information. This may be done by determining the key or via some other method. The best example of this attack is linear cryptanalysis against block ciphers. Known Plaintext Attack (KPA) βˆ’ In this method, the attacker knows the plaintext for some parts of the ciphertext. The task is to decrypt the rest of the ciphertext using this information. This may be done by determining the key or via some other method. The best example of this attack is linear cryptanalysis against block ciphers. Chosen Plaintext Attack (CPA) βˆ’ In this method, the attacker has the text of his choice encrypted. So he has the ciphertext-plaintext pair of his choice. This simplifies his task of determining the encryption key. An example of this attack is differential cryptanalysis applied against block ciphers as well as hash functions. A popular public key cryptosystem, RSA is also vulnerable to chosen-plaintext attacks. Chosen Plaintext Attack (CPA) βˆ’ In this method, the attacker has the text of his choice encrypted. So he has the ciphertext-plaintext pair of his choice. This simplifies his task of determining the encryption key. An example of this attack is differential cryptanalysis applied against block ciphers as well as hash functions. A popular public key cryptosystem, RSA is also vulnerable to chosen-plaintext attacks. Dictionary Attack βˆ’ This attack has many variants, all of which involve compiling a β€˜dictionary’. In simplest method of this attack, attacker builds a dictionary of ciphertexts and corresponding plaintexts that he has learnt over a period of time. In future, when an attacker gets the ciphertext, he refers the dictionary to find the corresponding plaintext. Dictionary Attack βˆ’ This attack has many variants, all of which involve compiling a β€˜dictionary’. In simplest method of this attack, attacker builds a dictionary of ciphertexts and corresponding plaintexts that he has learnt over a period of time. In future, when an attacker gets the ciphertext, he refers the dictionary to find the corresponding plaintext. Brute Force Attack (BFA) βˆ’ In this method, the attacker tries to determine the key by attempting all possible keys. If the key is 8 bits long, then the number of possible keys is 28 = 256. The attacker knows the ciphertext and the algorithm, now he attempts all the 256 keys one by one for decryption. The time to complete the attack would be very high if the key is long. Brute Force Attack (BFA) βˆ’ In this method, the attacker tries to determine the key by attempting all possible keys. If the key is 8 bits long, then the number of possible keys is 28 = 256. The attacker knows the ciphertext and the algorithm, now he attempts all the 256 keys one by one for decryption. The time to complete the attack would be very high if the key is long. Birthday Attack βˆ’ This attack is a variant of brute-force technique. It is used against the cryptographic hash function. When students in a class are asked about their birthdays, the answer is one of the possible 365 dates. Let us assume the first student's birthdate is 3rd Aug. Then to find the next student whose birthdate is 3rd Aug, we need to enquire 1.25*√365 β‰ˆ 25 students. Similarly, if the hash function produces 64 bit hash values, the possible hash values are 1.8x1019. By repeatedly evaluating the function for different inputs, the same output is expected to be obtained after about 5.1x109 random inputs. If the attacker is able to find two different inputs that give the same hash value, it is a collision and that hash function is said to be broken. Birthday Attack βˆ’ This attack is a variant of brute-force technique. It is used against the cryptographic hash function. When students in a class are asked about their birthdays, the answer is one of the possible 365 dates. Let us assume the first student's birthdate is 3rd Aug. Then to find the next student whose birthdate is 3rd Aug, we need to enquire 1.25*√365 β‰ˆ 25 students. Similarly, if the hash function produces 64 bit hash values, the possible hash values are 1.8x1019. By repeatedly evaluating the function for different inputs, the same output is expected to be obtained after about 5.1x109 random inputs. If the attacker is able to find two different inputs that give the same hash value, it is a collision and that hash function is said to be broken. Man in Middle Attack (MIM) βˆ’ The targets of this attack are mostly public key cryptosystems where key exchange is involved before communication takes place. Host A wants to communicate to host B, hence requests public key of B. An attacker intercepts this request and sends his public key instead. Thus, whatever host A sends to host B, the attacker is able to read. In order to maintain communication, the attacker re-encrypts the data after reading with his public key and sends to B. The attacker sends his public key as A’s public key so that B takes it as if it is taking it from A. Man in Middle Attack (MIM) βˆ’ The targets of this attack are mostly public key cryptosystems where key exchange is involved before communication takes place. Host A wants to communicate to host B, hence requests public key of B. Host A wants to communicate to host B, hence requests public key of B. An attacker intercepts this request and sends his public key instead. An attacker intercepts this request and sends his public key instead. Thus, whatever host A sends to host B, the attacker is able to read. Thus, whatever host A sends to host B, the attacker is able to read. In order to maintain communication, the attacker re-encrypts the data after reading with his public key and sends to B. In order to maintain communication, the attacker re-encrypts the data after reading with his public key and sends to B. The attacker sends his public key as A’s public key so that B takes it as if it is taking it from A. The attacker sends his public key as A’s public key so that B takes it as if it is taking it from A. Side Channel Attack (SCA) βˆ’ This type of attack is not against any particular type of cryptosystem or algorithm. Instead, it is launched to exploit the weakness in physical implementation of the cryptosystem. Side Channel Attack (SCA) βˆ’ This type of attack is not against any particular type of cryptosystem or algorithm. Instead, it is launched to exploit the weakness in physical implementation of the cryptosystem. Timing Attacks βˆ’ They exploit the fact that different computations take different times to compute on processor. By measuring such timings, it is be possible to know about a particular computation the processor is carrying out. For example, if the encryption takes a longer time, it indicates that the secret key is long. Timing Attacks βˆ’ They exploit the fact that different computations take different times to compute on processor. By measuring such timings, it is be possible to know about a particular computation the processor is carrying out. For example, if the encryption takes a longer time, it indicates that the secret key is long. Power Analysis Attacks βˆ’ These attacks are similar to timing attacks except that the amount of power consumption is used to obtain information about the nature of the underlying computations. Power Analysis Attacks βˆ’ These attacks are similar to timing attacks except that the amount of power consumption is used to obtain information about the nature of the underlying computations. Fault analysis Attacks βˆ’ In these attacks, errors are induced in the cryptosystem and the attacker studies the resulting output for useful information. Fault analysis Attacks βˆ’ In these attacks, errors are induced in the cryptosystem and the attacker studies the resulting output for useful information. The attacks on cryptosystems described here are highly academic, as majority of them come from the academic community. In fact, many academic attacks involve quite unrealistic assumptions about environment as well as the capabilities of the attacker. For example, in chosen-ciphertext attack, the attacker requires an impractical number of deliberately chosen plaintext-ciphertext pairs. It may not be practical altogether. Nonetheless, the fact that any attack exists should be a cause of concern, particularly if the attack technique has the potential for improvement. In the second chapter, we discussed the fundamentals of modern cryptography. We equated cryptography with a toolkit where various cryptographic techniques are considered as the basic tools. One of these tools is the Symmetric Key Encryption where the key used for encryption and decryption is the same. In this chapter, we discuss this technique further and its applications to develop various cryptosystems. Before proceeding further, you need to know some facts about historical cryptosystems βˆ’ All of these systems are based on symmetric key encryption scheme. All of these systems are based on symmetric key encryption scheme. The only security service these systems provide is confidentiality of information. The only security service these systems provide is confidentiality of information. Unlike modern systems which are digital and treat data as binary numbers, the earlier systems worked on alphabets as basic element. Unlike modern systems which are digital and treat data as binary numbers, the earlier systems worked on alphabets as basic element. These earlier cryptographic systems are also referred to as Ciphers. In general, a cipher is simply just a set of steps (an algorithm) for performing both an encryption, and the corresponding decryption. It is a mono-alphabetic cipher wherein each letter of the plaintext is substituted by another letter to form the ciphertext. It is a simplest form of substitution cipher scheme. This cryptosystem is generally referred to as the Shift Cipher. The concept is to replace each alphabet by another alphabet which is β€˜shifted’ by some fixed number between 0 and 25. For this type of scheme, both sender and receiver agree on a β€˜secret shift number’ for shifting the alphabet. This number which is between 0 and 25 becomes the key of encryption. The name β€˜Caesar Cipher’ is occasionally used to describe the Shift Cipher when the β€˜shift of three’ is used. In order to encrypt a plaintext letter, the sender positions the sliding ruler underneath the first set of plaintext letters and slides it to LEFT by the number of positions of the secret shift. In order to encrypt a plaintext letter, the sender positions the sliding ruler underneath the first set of plaintext letters and slides it to LEFT by the number of positions of the secret shift. The plaintext letter is then encrypted to the ciphertext letter on the sliding ruler underneath. The result of this process is depicted in the following illustration for an agreed shift of three positions. In this case, the plaintext β€˜tutorial’ is encrypted to the ciphertext β€˜WXWRULDO’. Here is the ciphertext alphabet for a Shift of 3 βˆ’ The plaintext letter is then encrypted to the ciphertext letter on the sliding ruler underneath. The result of this process is depicted in the following illustration for an agreed shift of three positions. In this case, the plaintext β€˜tutorial’ is encrypted to the ciphertext β€˜WXWRULDO’. Here is the ciphertext alphabet for a Shift of 3 βˆ’ On receiving the ciphertext, the receiver who also knows the secret shift, positions his sliding ruler underneath the ciphertext alphabet and slides it to RIGHT by the agreed shift number, 3 in this case. On receiving the ciphertext, the receiver who also knows the secret shift, positions his sliding ruler underneath the ciphertext alphabet and slides it to RIGHT by the agreed shift number, 3 in this case. He then replaces the ciphertext letter by the plaintext letter on the sliding ruler underneath. Hence the ciphertext β€˜WXWRULDO’ is decrypted to β€˜tutorial’. To decrypt a message encoded with a Shift of 3, generate the plaintext alphabet using a shift of β€˜-3’ as shown below βˆ’ He then replaces the ciphertext letter by the plaintext letter on the sliding ruler underneath. Hence the ciphertext β€˜WXWRULDO’ is decrypted to β€˜tutorial’. To decrypt a message encoded with a Shift of 3, generate the plaintext alphabet using a shift of β€˜-3’ as shown below βˆ’ Caesar Cipher is not a secure cryptosystem because there are only 26 possible keys to try out. An attacker can carry out an exhaustive key search with available limited computing resources. It is an improvement to the Caesar Cipher. Instead of shifting the alphabets by some number, this scheme uses some permutation of the letters in alphabet. For example, A.B.....Y.Z and Z.Y......B.A are two obvious permutation of all the letters in alphabet. Permutation is nothing but a jumbled up set of alphabets. With 26 letters in alphabet, the possible permutations are 26! (Factorial of 26) which is equal to 4x1026. The sender and the receiver may choose any one of these possible permutation as a ciphertext alphabet. This permutation is the secret key of the scheme. Write the alphabets A, B, C,...,Z in the natural order. Write the alphabets A, B, C,...,Z in the natural order. The sender and the receiver decide on a randomly selected permutation of the letters of the alphabet. The sender and the receiver decide on a randomly selected permutation of the letters of the alphabet. Underneath the natural order alphabets, write out the chosen permutation of the letters of the alphabet. For encryption, sender replaces each plaintext letters by substituting the permutation letter that is directly beneath it in the table. This process is shown in the following illustration. In this example, the chosen permutation is K,D, G, ..., O. The plaintext β€˜point’ is encrypted to β€˜MJBXZ’. Underneath the natural order alphabets, write out the chosen permutation of the letters of the alphabet. For encryption, sender replaces each plaintext letters by substituting the permutation letter that is directly beneath it in the table. This process is shown in the following illustration. In this example, the chosen permutation is K,D, G, ..., O. The plaintext β€˜point’ is encrypted to β€˜MJBXZ’. Here is a jumbled Ciphertext alphabet, where the order of the ciphertext letters is a key. On receiving the ciphertext, the receiver, who also knows the randomly chosen permutation, replaces each ciphertext letter on the bottom row with the corresponding plaintext letter in the top row. The ciphertext β€˜MJBXZ’ is decrypted to β€˜point’. On receiving the ciphertext, the receiver, who also knows the randomly chosen permutation, replaces each ciphertext letter on the bottom row with the corresponding plaintext letter in the top row. The ciphertext β€˜MJBXZ’ is decrypted to β€˜point’. Simple Substitution Cipher is a considerable improvement over the Caesar Cipher. The possible number of keys is large (26!) and even the modern computing systems are not yet powerful enough to comfortably launch a brute force attack to break the system. However, the Simple Substitution Cipher has a simple design and it is prone to design flaws, say choosing obvious permutation, this cryptosystem can be easily broken. Monoalphabetic cipher is a substitution cipher in which for a given key, the cipher alphabet for each plain alphabet is fixed throughout the encryption process. For example, if β€˜A’ is encrypted as β€˜D’, for any number of occurrence in that plaintext, β€˜A’ will always get encrypted to β€˜D’. All of the substitution ciphers we have discussed earlier in this chapter are monoalphabetic; these ciphers are highly susceptible to cryptanalysis. Polyalphabetic Cipher is a substitution cipher in which the cipher alphabet for the plain alphabet may be different at different places during the encryption process. The next two examples, playfair and Vigenere Cipher are polyalphabetic ciphers. In this scheme, pairs of letters are encrypted, instead of single letters as in the case of simple substitution cipher. In playfair cipher, initially a key table is created. The key table is a 5Γ—5 grid of alphabets that acts as the key for encrypting the plaintext. Each of the 25 alphabets must be unique and one letter of the alphabet (usually J) is omitted from the table as we need only 25 alphabets instead of 26. If the plaintext contains J, then it is replaced by I. The sender and the receiver deicide on a particular key, say β€˜tutorials’. In a key table, the first characters (going left to right) in the table is the phrase, excluding the duplicate letters. The rest of the table will be filled with the remaining letters of the alphabet, in natural order. The key table works out to be βˆ’ First, a plaintext message is split into pairs of two letters (digraphs). If there is an odd number of letters, a Z is added to the last letter. Let us say we want to encrypt the message β€œhide money”. It will be written as βˆ’ HI DE MO NE YZ First, a plaintext message is split into pairs of two letters (digraphs). If there is an odd number of letters, a Z is added to the last letter. Let us say we want to encrypt the message β€œhide money”. It will be written as βˆ’ HI DE MO NE YZ The rules of encryption are βˆ’ If both the letters are in the same column, take the letter below each one (going back to the top if at the bottom) The rules of encryption are βˆ’ If both the letters are in the same column, take the letter below each one (going back to the top if at the bottom) If both the letters are in the same column, take the letter below each one (going back to the top if at the bottom) If both letters are in the same row, take the letter to the right of each one (going back to the left if at the farthest right) If both letters are in the same row, take the letter to the right of each one (going back to the left if at the farthest right) If neither of the preceding two rules are true, form a rectangle with the two letters and take the letters on the horizontal opposite corner of the rectangle. If neither of the preceding two rules are true, form a rectangle with the two letters and take the letters on the horizontal opposite corner of the rectangle. Using these rules, the result of the encryption of β€˜hide money’ with the key of β€˜tutorials’ would be βˆ’ QC EF NU MF ZV Decrypting the Playfair cipher is as simple as doing the same process in reverse. Receiver has the same key and can create the same key table, and then decrypt any messages made using that key. It is also a substitution cipher and is difficult to break compared to the simple substitution cipher. As in case of substitution cipher, cryptanalysis is possible on the Playfair cipher as well, however it would be against 625 possible pairs of letters (25x25 alphabets) instead of 26 different possible alphabets. The Playfair cipher was used mainly to protect important, yet non-critical secrets, as it is quick to use and requires no special equipment. This scheme of cipher uses a text string (say, a word) as a key, which is then used for doing a number of shifts on the plaintext. For example, let’s assume the key is β€˜point’. Each alphabet of the key is converted to its respective numeric value: In this case, p β†’ 16, o β†’ 15, i β†’ 9, n β†’ 14, and t β†’ 20. Thus, the key is: 16 15 9 14 20. The sender and the receiver decide on a key. Say β€˜point’ is the key. Numeric representation of this key is β€˜16 15 9 14 20’. The sender and the receiver decide on a key. Say β€˜point’ is the key. Numeric representation of this key is β€˜16 15 9 14 20’. The sender wants to encrypt the message, say β€˜attack from south east’. He will arrange plaintext and numeric key as follows βˆ’ The sender wants to encrypt the message, say β€˜attack from south east’. He will arrange plaintext and numeric key as follows βˆ’ He now shifts each plaintext alphabet by the number written below it to create ciphertext as shown below βˆ’ He now shifts each plaintext alphabet by the number written below it to create ciphertext as shown below βˆ’ Here, each plaintext character has been shifted by a different amount – and that amount is determined by the key. The key must be less than or equal to the size of the message. Here, each plaintext character has been shifted by a different amount – and that amount is determined by the key. The key must be less than or equal to the size of the message. For decryption, the receiver uses the same key and shifts received ciphertext in reverse order to obtain the plaintext. For decryption, the receiver uses the same key and shifts received ciphertext in reverse order to obtain the plaintext. Vigenere Cipher was designed by tweaking the standard Caesar cipher to reduce the effectiveness of cryptanalysis on the ciphertext and make a cryptosystem more robust. It is significantly more secure than a regular Caesar Cipher. In the history, it was regularly used for protecting sensitive political and military information. It was referred to as the unbreakable cipher due to the difficulty it posed to the cryptanalysis. There are two special cases of Vigenere cipher βˆ’ The keyword length is same as plaintect message. This case is called Vernam Cipher. It is more secure than typical Vigenere cipher. The keyword length is same as plaintect message. This case is called Vernam Cipher. It is more secure than typical Vigenere cipher. Vigenere cipher becomes a cryptosystem with perfect secrecy, which is called One-time pad. Vigenere cipher becomes a cryptosystem with perfect secrecy, which is called One-time pad. The circumstances are βˆ’ The length of the keyword is same as the length of the plaintext. The keyword is a randomly generated string of alphabets. The keyword is used only once. Let us compare Shift cipher with one-time pad. In case of Shift cipher, the entire message could have had a shift between 1 and 25. This is a very small size, and very easy to brute force. However, with each character now having its own individual shift between 1 and 26, the possible keys grow exponentially for the message. Let us say, we encrypt the name β€œpoint” with a one-time pad. It is a 5 letter text. To break the ciphertext by brute force, you need to try all possibilities of keys and conduct computation for (26 x 26 x 26 x 26 x 26) = 265 = 11881376 times. That’s for a message with 5 alphabets. Thus, for a longer message, the computation grows exponentially with every additional alphabet. This makes it computationally impossible to break the ciphertext by brute force. It is another type of cipher where the order of the alphabets in the plaintext is rearranged to create the ciphertext. The actual plaintext alphabets are not replaced. An example is a β€˜simple columnar transposition’ cipher where the plaintext is written horizontally with a certain alphabet width. Then the ciphertext is read vertically as shown. For example, the plaintext is β€œgolden statue is in eleventh cave” and the secret random key chosen is β€œfive”. We arrange this text horizontally in table with number of column equal to key value. The resulting text is shown below. The ciphertext is obtained by reading column vertically downward from first to last column. The ciphertext is β€˜gnuneaoseenvltiltedasehetivc’. To decrypt, the receiver prepares similar table. The number of columns is equal to key number. The number of rows is obtained by dividing number of total ciphertext alphabets by key value and rounding of the quotient to next integer value. The receiver then writes the received ciphertext vertically down and from left to right column. To obtain the text, he reads horizontally left to right and from top to bottom row. Digital data is represented in strings of binary digits (bits) unlike alphabets. Modern cryptosystems need to process this binary strings to convert in to another binary string. Based on how these binary strings are processed, a symmetric encryption schemes can be classified in to βˆ’ In this scheme, the plain binary text is processed in blocks (groups) of bits at a time; i.e. a block of plaintext bits is selected, a series of operations is performed on this block to generate a block of ciphertext bits. The number of bits in a block is fixed. For example, the schemes DES and AES have block sizes of 64 and 128, respectively. In this scheme, the plaintext is processed one bit at a time i.e. one bit of plaintext is taken, and a series of operations is performed on it to generate one bit of ciphertext. Technically, stream ciphers are block ciphers with a block size of one bit. The basic scheme of a block cipher is depicted as follows βˆ’ A block cipher takes a block of plaintext bits and generates a block of ciphertext bits, generally of same size. The size of block is fixed in the given scheme. The choice of block size does not directly affect to the strength of encryption scheme. The strength of cipher depends up on the key length. Though any size of block is acceptable, following aspects are borne in mind while selecting a size of a block. Avoid very small block size βˆ’ Say a block size is m bits. Then the possible plaintext bits combinations are then 2m. If the attacker discovers the plain text blocks corresponding to some previously sent ciphertext blocks, then the attacker can launch a type of β€˜dictionary attack’ by building up a dictionary of plaintext/ciphertext pairs sent using that encryption key. A larger block size makes attack harder as the dictionary needs to be larger. Avoid very small block size βˆ’ Say a block size is m bits. Then the possible plaintext bits combinations are then 2m. If the attacker discovers the plain text blocks corresponding to some previously sent ciphertext blocks, then the attacker can launch a type of β€˜dictionary attack’ by building up a dictionary of plaintext/ciphertext pairs sent using that encryption key. A larger block size makes attack harder as the dictionary needs to be larger. Do not have very large block size βˆ’ With very large block size, the cipher becomes inefficient to operate. Such plaintexts will need to be padded before being encrypted. Do not have very large block size βˆ’ With very large block size, the cipher becomes inefficient to operate. Such plaintexts will need to be padded before being encrypted. Multiples of 8 bit βˆ’ A preferred block size is a multiple of 8 as it is easy for implementation as most computer processor handle data in multiple of 8 bits. Multiples of 8 bit βˆ’ A preferred block size is a multiple of 8 as it is easy for implementation as most computer processor handle data in multiple of 8 bits. Block ciphers process blocks of fixed sizes (say 64 bits). The length of plaintexts is mostly not a multiple of the block size. For example, a 150-bit plaintext provides two blocks of 64 bits each with third block of balance 22 bits. The last block of bits needs to be padded up with redundant information so that the length of the final block equal to block size of the scheme. In our example, the remaining 22 bits need to have additional 42 redundant bits added to provide a complete block. The process of adding bits to the last block is referred to as padding. Too much padding makes the system inefficient. Also, padding may render the system insecure at times, if the padding is done with same bits always. There is a vast number of block ciphers schemes that are in use. Many of them are publically known. Most popular and prominent block ciphers are listed below. Digital Encryption Standard (DES) βˆ’ The popular block cipher of the 1990s. It is now considered as a β€˜broken’ block cipher, due primarily to its small key size. Digital Encryption Standard (DES) βˆ’ The popular block cipher of the 1990s. It is now considered as a β€˜broken’ block cipher, due primarily to its small key size. Triple DES βˆ’ It is a variant scheme based on repeated DES applications. It is still a respected block ciphers but inefficient compared to the new faster block ciphers available. Triple DES βˆ’ It is a variant scheme based on repeated DES applications. It is still a respected block ciphers but inefficient compared to the new faster block ciphers available. Advanced Encryption Standard (AES) βˆ’ It is a relatively new block cipher based on the encryption algorithm Rijndael that won the AES design competition. Advanced Encryption Standard (AES) βˆ’ It is a relatively new block cipher based on the encryption algorithm Rijndael that won the AES design competition. IDEA βˆ’ It is a sufficiently strong block cipher with a block size of 64 and a key size of 128 bits. A number of applications use IDEA encryption, including early versions of Pretty Good Privacy (PGP) protocol. The use of IDEA scheme has a restricted adoption due to patent issues. IDEA βˆ’ It is a sufficiently strong block cipher with a block size of 64 and a key size of 128 bits. A number of applications use IDEA encryption, including early versions of Pretty Good Privacy (PGP) protocol. The use of IDEA scheme has a restricted adoption due to patent issues. Twofish βˆ’ This scheme of block cipher uses block size of 128 bits and a key of variable length. It was one of the AES finalists. It is based on the earlier block cipher Blowfish with a block size of 64 bits. Twofish βˆ’ This scheme of block cipher uses block size of 128 bits and a key of variable length. It was one of the AES finalists. It is based on the earlier block cipher Blowfish with a block size of 64 bits. Serpent βˆ’ A block cipher with a block size of 128 bits and key lengths of 128, 192, or 256 bits, which was also an AES competition finalist. It is a slower but has more secure design than other block cipher. Serpent βˆ’ A block cipher with a block size of 128 bits and key lengths of 128, 192, or 256 bits, which was also an AES competition finalist. It is a slower but has more secure design than other block cipher. In the next sections, we will first discuss the model of block cipher followed by DES and AES, two of the most influential modern block ciphers. Feistel Cipher is not a specific scheme of block cipher. It is a design model from which many different block ciphers are derived. DES is just one example of a Feistel Cipher. A cryptographic system based on Feistel cipher structure uses the same algorithm for both encryption and decryption. The encryption process uses the Feistel structure consisting multiple rounds of processing of the plaintext, each round consisting of a β€œsubstitution” step followed by a permutation step. Feistel Structure is shown in the following illustration βˆ’ The input block to each round is divided into two halves that can be denoted as L and R for the left half and the right half. The input block to each round is divided into two halves that can be denoted as L and R for the left half and the right half. In each round, the right half of the block, R, goes through unchanged. But the left half, L, goes through an operation that depends on R and the encryption key. First, we apply an encrypting function β€˜f’ that takes two input βˆ’ the key K and R. The function produces the output f(R,K). Then, we XOR the output of the mathematical function with L. In each round, the right half of the block, R, goes through unchanged. But the left half, L, goes through an operation that depends on R and the encryption key. First, we apply an encrypting function β€˜f’ that takes two input βˆ’ the key K and R. The function produces the output f(R,K). Then, we XOR the output of the mathematical function with L. In real implementation of the Feistel Cipher, such as DES, instead of using the whole encryption key during each round, a round-dependent key (a subkey) is derived from the encryption key. This means that each round uses a different key, although all these subkeys are related to the original key. In real implementation of the Feistel Cipher, such as DES, instead of using the whole encryption key during each round, a round-dependent key (a subkey) is derived from the encryption key. This means that each round uses a different key, although all these subkeys are related to the original key. The permutation step at the end of each round swaps the modified L and unmodified R. Therefore, the L for the next round would be R of the current round. And R for the next round be the output L of the current round. The permutation step at the end of each round swaps the modified L and unmodified R. Therefore, the L for the next round would be R of the current round. And R for the next round be the output L of the current round. Above substitution and permutation steps form a β€˜round’. The number of rounds are specified by the algorithm design. Above substitution and permutation steps form a β€˜round’. The number of rounds are specified by the algorithm design. Once the last round is completed then the two sub blocks, β€˜R’ and β€˜L’ are concatenated in this order to form the ciphertext block. Once the last round is completed then the two sub blocks, β€˜R’ and β€˜L’ are concatenated in this order to form the ciphertext block. The difficult part of designing a Feistel Cipher is selection of round function β€˜f’. In order to be unbreakable scheme, this function needs to have several important properties that are beyond the scope of our discussion. The process of decryption in Feistel cipher is almost similar. Instead of starting with a block of plaintext, the ciphertext block is fed into the start of the Feistel structure and then the process thereafter is exactly the same as described in the given illustration. The process is said to be almost similar and not exactly same. In the case of decryption, the only difference is that the subkeys used in encryption are used in the reverse order. The final swapping of β€˜L’ and β€˜R’ in last step of the Feistel Cipher is essential. If these are not swapped then the resulting ciphertext could not be decrypted using the same algorithm. The number of rounds used in a Feistel Cipher depends on desired security from the system. More number of rounds provide more secure system. But at the same time, more rounds mean the inefficient slow encryption and decryption processes. Number of rounds in the systems thus depend upon efficiency–security tradeoff. The Data Encryption Standard (DES) is a symmetric-key block cipher published by the National Institute of Standards and Technology (NIST). DES is an implementation of a Feistel Cipher. It uses 16 round Feistel structure. The block size is 64-bit. Though, key length is 64-bit, DES has an effective key length of 56 bits, since 8 of the 64 bits of the key are not used by the encryption algorithm (function as check bits only). General Structure of DES is depicted in the following illustration βˆ’ Since DES is based on the Feistel Cipher, all that is required to specify DES is βˆ’ Round function Key schedule Any additional processing βˆ’ Initial and final permutation The initial and final permutations are straight Permutation boxes (P-boxes) that are inverses of each other. They have no cryptography significance in DES. The initial and final permutations are shown as follows βˆ’ The heart of this cipher is the DES function, f. The DES function applies a 48-bit key to the rightmost 32 bits to produce a 32-bit output. Expansion Permutation Box βˆ’ Since right input is 32-bit and round key is a 48-bit, we first need to expand right input to 48 bits. Permutation logic is graphically depicted in the following illustration βˆ’ Expansion Permutation Box βˆ’ Since right input is 32-bit and round key is a 48-bit, we first need to expand right input to 48 bits. Permutation logic is graphically depicted in the following illustration βˆ’ The graphically depicted permutation logic is generally described as table in DES specification illustrated as shown βˆ’ The graphically depicted permutation logic is generally described as table in DES specification illustrated as shown βˆ’ XOR (Whitener). βˆ’ After the expansion permutation, DES does XOR operation on the expanded right section and the round key. The round key is used only in this operation. XOR (Whitener). βˆ’ After the expansion permutation, DES does XOR operation on the expanded right section and the round key. The round key is used only in this operation. Substitution Boxes. βˆ’ The S-boxes carry out the real mixing (confusion). DES uses 8 S-boxes, each with a 6-bit input and a 4-bit output. Refer the following illustration βˆ’ Substitution Boxes. βˆ’ The S-boxes carry out the real mixing (confusion). DES uses 8 S-boxes, each with a 6-bit input and a 4-bit output. Refer the following illustration βˆ’ The S-box rule is illustrated below βˆ’ The S-box rule is illustrated below βˆ’ There are a total of eight S-box tables. The output of all eight s-boxes is then combined in to 32 bit section. There are a total of eight S-box tables. The output of all eight s-boxes is then combined in to 32 bit section. Straight Permutation βˆ’ The 32 bit output of S-boxes is then subjected to the straight permutation with rule shown in the following illustration: Straight Permutation βˆ’ The 32 bit output of S-boxes is then subjected to the straight permutation with rule shown in the following illustration: The round-key generator creates sixteen 48-bit keys out of a 56-bit cipher key. The process of key generation is depicted in the following illustration βˆ’ The logic for Parity drop, shifting, and Compression P-box is given in the DES description. The DES satisfies both the desired properties of block cipher. These two properties make cipher very strong. Avalanche effect βˆ’ A small change in plaintext results in the very great change in the ciphertext. Avalanche effect βˆ’ A small change in plaintext results in the very great change in the ciphertext. Completeness βˆ’ Each bit of ciphertext depends on many bits of plaintext. Completeness βˆ’ Each bit of ciphertext depends on many bits of plaintext. During the last few years, cryptanalysis have found some weaknesses in DES when key selected are weak keys. These keys shall be avoided. DES has proved to be a very well designed block cipher. There have been no significant cryptanalytic attacks on DES other than exhaustive key search. The speed of exhaustive key searches against DES after 1990 began to cause discomfort amongst users of DES. However, users did not want to replace DES as it takes an enormous amount of time and money to change encryption algorithms that are widely adopted and embedded in large security architectures. The pragmatic approach was not to abandon the DES completely, but to change the manner in which DES is used. This led to the modified schemes of Triple DES (sometimes known as 3DES). Incidentally, there are two variants of Triple DES known as 3-key Triple DES (3TDES) and 2-key Triple DES (2TDES). Before using 3TDES, user first generate and distribute a 3TDES key K, which consists of three different DES keys K1, K2 and K3. This means that the actual 3TDES key has length 3Γ—56 = 168 bits. The encryption scheme is illustrated as follows βˆ’ The encryption-decryption process is as follows βˆ’ Encrypt the plaintext blocks using single DES with key K1. Encrypt the plaintext blocks using single DES with key K1. Now decrypt the output of step 1 using single DES with key K2. Now decrypt the output of step 1 using single DES with key K2. Finally, encrypt the output of step 2 using single DES with key K3. Finally, encrypt the output of step 2 using single DES with key K3. The output of step 3 is the ciphertext. The output of step 3 is the ciphertext. Decryption of a ciphertext is a reverse process. User first decrypt using K3, then encrypt with K2, and finally decrypt with K1. Decryption of a ciphertext is a reverse process. User first decrypt using K3, then encrypt with K2, and finally decrypt with K1. Due to this design of Triple DES as an encrypt–decrypt–encrypt process, it is possible to use a 3TDES (hardware) implementation for single DES by setting K1, K2, and K3 to be the same value. This provides backwards compatibility with DES. Second variant of Triple DES (2TDES) is identical to 3TDES except that K3is replaced by K1. In other words, user encrypt plaintext blocks with key K1, then decrypt with key K2, and finally encrypt with K1 again. Therefore, 2TDES has a key length of 112 bits. Triple DES systems are significantly more secure than single DES, but these are clearly a much slower process than encryption using single DES. The more popular and widely adopted symmetric encryption algorithm likely to be encountered nowadays is the Advanced Encryption Standard (AES). It is found at least six time faster than triple DES. A replacement for DES was needed as its key size was too small. With increasing computing power, it was considered vulnerable against exhaustive key search attack. Triple DES was designed to overcome this drawback but it was found slow. The features of AES are as follows βˆ’ Symmetric key symmetric block cipher 128-bit data, 128/192/256-bit keys Stronger and faster than Triple-DES Provide full specification and design details Software implementable in C and Java AES is an iterative rather than Feistel cipher. It is based on β€˜substitution–permutation network’. It comprises of a series of linked operations, some of which involve replacing inputs by specific outputs (substitutions) and others involve shuffling bits around (permutations). Interestingly, AES performs all its computations on bytes rather than bits. Hence, AES treats the 128 bits of a plaintext block as 16 bytes. These 16 bytes are arranged in four columns and four rows for processing as a matrix βˆ’ Unlike DES, the number of rounds in AES is variable and depends on the length of the key. AES uses 10 rounds for 128-bit keys, 12 rounds for 192-bit keys and 14 rounds for 256-bit keys. Each of these rounds uses a different 128-bit round key, which is calculated from the original AES key. The schematic of AES structure is given in the following illustration βˆ’ Here, we restrict to description of a typical round of AES encryption. Each round comprise of four sub-processes. The first round process is depicted below βˆ’ The 16 input bytes are substituted by looking up a fixed table (S-box) given in design. The result is in a matrix of four rows and four columns. Each of the four rows of the matrix is shifted to the left. Any entries that β€˜fall off’ are re-inserted on the right side of row. Shift is carried out as follows βˆ’ First row is not shifted. First row is not shifted. Second row is shifted one (byte) position to the left. Second row is shifted one (byte) position to the left. Third row is shifted two positions to the left. Third row is shifted two positions to the left. Fourth row is shifted three positions to the left. Fourth row is shifted three positions to the left. The result is a new matrix consisting of the same 16 bytes but shifted with respect to each other. The result is a new matrix consisting of the same 16 bytes but shifted with respect to each other. Each column of four bytes is now transformed using a special mathematical function. This function takes as input the four bytes of one column and outputs four completely new bytes, which replace the original column. The result is another new matrix consisting of 16 new bytes. It should be noted that this step is not performed in the last round. The 16 bytes of the matrix are now considered as 128 bits and are XORed to the 128 bits of the round key. If this is the last round then the output is the ciphertext. Otherwise, the resulting 128 bits are interpreted as 16 bytes and we begin another similar round. The process of decryption of an AES ciphertext is similar to the encryption process in the reverse order. Each round consists of the four processes conducted in the reverse order βˆ’ Add round key Mix columns Shift rows Byte substitution Since sub-processes in each round are in reverse manner, unlike for a Feistel Cipher, the encryption and decryption algorithms needs to be separately implemented, although they are very closely related. In present day cryptography, AES is widely adopted and supported in both hardware and software. Till date, no practical cryptanalytic attacks against AES has been discovered. Additionally, AES has built-in flexibility of key length, which allows a degree of β€˜future-proofing’ against progress in the ability to perform exhaustive key searches. However, just as for DES, the AES security is assured only if it is correctly implemented and good key management is employed. In this chapter, we will discuss the different modes of operation of a block cipher. These are procedural rules for a generic block cipher. Interestingly, the different modes result in different properties being achieved which add to the security of the underlying block cipher. A block cipher processes the data blocks of fixed size. Usually, the size of a message is larger than the block size. Hence, the long message is divided into a series of sequential message blocks, and the cipher operates on these blocks one at a time. This mode is a most straightforward way of processing a series of sequentially listed message blocks. The user takes the first block of plaintext and encrypts it with the key to produce the first block of ciphertext. The user takes the first block of plaintext and encrypts it with the key to produce the first block of ciphertext. He then takes the second block of plaintext and follows the same process with same key and so on so forth. He then takes the second block of plaintext and follows the same process with same key and so on so forth. The ECB mode is deterministic, that is, if plaintext block P1, P2,..., Pm are encrypted twice under the same key, the output ciphertext blocks will be the same. In fact, for a given key technically we can create a codebook of ciphertexts for all possible plaintext blocks. Encryption would then entail only looking up for required plaintext and select the corresponding ciphertext. Thus, the operation is analogous to the assignment of code words in a codebook, and hence gets an official name βˆ’ Electronic Codebook mode of operation (ECB). It is illustrated as follows βˆ’ In reality, any application data usually have partial information which can be guessed. For example, the range of salary can be guessed. A ciphertext from ECB can allow an attacker to guess the plaintext by trial-and-error if the plaintext message is within predictable. For example, if a ciphertext from the ECB mode is known to encrypt a salary figure, then a small number of trials will allow an attacker to recover the figure. In general, we do not wish to use a deterministic cipher, and hence the ECB mode should not be used in most applications. CBC mode of operation provides message dependence for generating ciphertext and makes the system non-deterministic. The operation of CBC mode is depicted in the following illustration. The steps are as follows βˆ’ Load the n-bit Initialization Vector (IV) in the top register. Load the n-bit Initialization Vector (IV) in the top register. XOR the n-bit plaintext block with data value in top register. XOR the n-bit plaintext block with data value in top register. Encrypt the result of XOR operation with underlying block cipher with key K. Encrypt the result of XOR operation with underlying block cipher with key K. Feed ciphertext block into top register and continue the operation till all plaintext blocks are processed. Feed ciphertext block into top register and continue the operation till all plaintext blocks are processed. For decryption, IV data is XORed with first ciphertext block decrypted. The first ciphertext block is also fed into to register replacing IV for decrypting next ciphertext block. For decryption, IV data is XORed with first ciphertext block decrypted. The first ciphertext block is also fed into to register replacing IV for decrypting next ciphertext block. In CBC mode, the current plaintext block is added to the previous ciphertext block, and then the result is encrypted with the key. Decryption is thus the reverse process, which involves decrypting the current ciphertext and then adding the previous ciphertext block to the result. Advantage of CBC over ECB is that changing IV results in different ciphertext for identical message. On the drawback side, the error in transmission gets propagated to few further block during decryption due to chaining effect. It is worth mentioning that CBC mode forms the basis for a well-known data origin authentication mechanism. Thus, it has an advantage for those applications that require both symmetric encryption and data origin authentication. In this mode, each ciphertext block gets β€˜fed back’ into the encryption process in order to encrypt the next plaintext block. The operation of CFB mode is depicted in the following illustration. For example, in the present system, a message block has a size β€˜s’ bits where 1 < s < n. The CFB mode requires an initialization vector (IV) as the initial random n-bit input block. The IV need not be secret. Steps of operation are βˆ’ Load the IV in the top register. Load the IV in the top register. Encrypt the data value in top register with underlying block cipher with key K. Encrypt the data value in top register with underlying block cipher with key K. Take only β€˜s’ number of most significant bits (left bits) of output of encryption process and XOR them with β€˜s’ bit plaintext message block to generate ciphertext block. Take only β€˜s’ number of most significant bits (left bits) of output of encryption process and XOR them with β€˜s’ bit plaintext message block to generate ciphertext block. Feed ciphertext block into top register by shifting already present data to the left and continue the operation till all plaintext blocks are processed. Feed ciphertext block into top register by shifting already present data to the left and continue the operation till all plaintext blocks are processed. Essentially, the previous ciphertext block is encrypted with the key, and then the result is XORed to the current plaintext block. Essentially, the previous ciphertext block is encrypted with the key, and then the result is XORed to the current plaintext block. Similar steps are followed for decryption. Pre-decided IV is initially loaded at the start of decryption. Similar steps are followed for decryption. Pre-decided IV is initially loaded at the start of decryption. CFB mode differs significantly from ECB mode, the ciphertext corresponding to a given plaintext block depends not just on that plaintext block and the key, but also on the previous ciphertext block. In other words, the ciphertext block is dependent of message. CFB has a very strange feature. In this mode, user decrypts the ciphertext using only the encryption process of the block cipher. The decryption algorithm of the underlying block cipher is never used. Apparently, CFB mode is converting a block cipher into a type of stream cipher. The encryption algorithm is used as a key-stream generator to produce key-stream that is placed in the bottom register. This key stream is then XORed with the plaintext as in case of stream cipher. By converting a block cipher into a stream cipher, CFB mode provides some of the advantageous properties of a stream cipher while retaining the advantageous properties of a block cipher. On the flip side, the error of transmission gets propagated due to changing of blocks. It involves feeding the successive output blocks from the underlying block cipher back to it. These feedback blocks provide string of bits to feed the encryption algorithm which act as the key-stream generator as in case of CFB mode. The key stream generated is XOR-ed with the plaintext blocks. The OFB mode requires an IV as the initial random n-bit input block. The IV need not be secret. The operation is depicted in the following illustration βˆ’ It can be considered as a counter-based version of CFB mode without the feedback. In this mode, both the sender and receiver need to access to a reliable counter, which computes a new shared value each time a ciphertext block is exchanged. This shared counter is not necessarily a secret value, but challenge is that both sides must keep the counter synchronized. Both encryption and decryption in CTR mode are depicted in the following illustration. Steps in operation are βˆ’ Load the initial counter value in the top register is the same for both the sender and the receiver. It plays the same role as the IV in CFB (and CBC) mode. Load the initial counter value in the top register is the same for both the sender and the receiver. It plays the same role as the IV in CFB (and CBC) mode. Encrypt the contents of the counter with the key and place the result in the bottom register. Encrypt the contents of the counter with the key and place the result in the bottom register. Take the first plaintext block P1 and XOR this to the contents of the bottom register. The result of this is C1. Send C1 to the receiver and update the counter. The counter update replaces the ciphertext feedback in CFB mode. Take the first plaintext block P1 and XOR this to the contents of the bottom register. The result of this is C1. Send C1 to the receiver and update the counter. The counter update replaces the ciphertext feedback in CFB mode. Continue in this manner until the last plaintext block has been encrypted. Continue in this manner until the last plaintext block has been encrypted. The decryption is the reverse process. The ciphertext block is XORed with the output of encrypted contents of counter value. After decryption of each ciphertext block counter is updated as in case of encryption. The decryption is the reverse process. The ciphertext block is XORed with the output of encrypted contents of counter value. After decryption of each ciphertext block counter is updated as in case of encryption. It does not have message dependency and hence a ciphertext block does not depend on the previous plaintext blocks. Like CFB mode, CTR mode does not involve the decryption process of the block cipher. This is because the CTR mode is really using the block cipher to generate a key-stream, which is encrypted using the XOR function. In other words, CTR mode also converts a block cipher to a stream cipher. The serious disadvantage of CTR mode is that it requires a synchronous counter at sender and receiver. Loss of synchronization leads to incorrect recovery of plaintext. However, CTR mode has almost all advantages of CFB mode. In addition, it does not propagate error of transmission at all. Unlike symmetric key cryptography, we do not find historical use of public-key cryptography. It is a relatively new concept. Symmetric cryptography was well suited for organizations such as governments, military, and big financial corporations were involved in the classified communication. With the spread of more unsecure computer networks in last few decades, a genuine need was felt to use cryptography at larger scale. The symmetric key was found to be non-practical due to challenges it faced for key management. This gave rise to the public key cryptosystems. The process of encryption and decryption is depicted in the following illustration βˆ’ The most important properties of public key encryption scheme are βˆ’ Different keys are used for encryption and decryption. This is a property which set this scheme different than symmetric encryption scheme. Different keys are used for encryption and decryption. This is a property which set this scheme different than symmetric encryption scheme. Each receiver possesses a unique decryption key, generally referred to as his private key. Each receiver possesses a unique decryption key, generally referred to as his private key. Receiver needs to publish an encryption key, referred to as his public key. Receiver needs to publish an encryption key, referred to as his public key. Some assurance of the authenticity of a public key is needed in this scheme to avoid spoofing by adversary as the receiver. Generally, this type of cryptosystem involves trusted third party which certifies that a particular public key belongs to a specific person or entity only. Some assurance of the authenticity of a public key is needed in this scheme to avoid spoofing by adversary as the receiver. Generally, this type of cryptosystem involves trusted third party which certifies that a particular public key belongs to a specific person or entity only. Encryption algorithm is complex enough to prohibit attacker from deducing the plaintext from the ciphertext and the encryption (public) key. Encryption algorithm is complex enough to prohibit attacker from deducing the plaintext from the ciphertext and the encryption (public) key. Though private and public keys are related mathematically, it is not be feasible to calculate the private key from the public key. In fact, intelligent part of any public-key cryptosystem is in designing a relationship between two keys. Though private and public keys are related mathematically, it is not be feasible to calculate the private key from the public key. In fact, intelligent part of any public-key cryptosystem is in designing a relationship between two keys. There are three types of Public Key Encryption schemes. We discuss them in following sections βˆ’ This cryptosystem is one the initial system. It remains most employed cryptosystem even today. The system was invented by three scholars Ron Rivest, Adi Shamir, and Len Adleman and hence, it is termed as RSA cryptosystem. We will see two aspects of the RSA cryptosystem, firstly generation of key pair and secondly encryption-decryption algorithms. Each person or a party who desires to participate in communication using encryption needs to generate a pair of keys, namely public key and private key. The process followed in the generation of keys is described below βˆ’ Generate the RSA modulus (n) Select two large primes, p and q. Calculate n=p*q. For strong unbreakable encryption, let n be a large number, typically a minimum of 512 bits. Generate the RSA modulus (n) Select two large primes, p and q. Select two large primes, p and q. Calculate n=p*q. For strong unbreakable encryption, let n be a large number, typically a minimum of 512 bits. Calculate n=p*q. For strong unbreakable encryption, let n be a large number, typically a minimum of 512 bits. Find Derived Number (e) Number e must be greater than 1 and less than (p βˆ’ 1)(q βˆ’ 1). There must be no common factor for e and (p βˆ’ 1)(q βˆ’ 1) except for 1. In other words two numbers e and (p – 1)(q – 1) are coprime. Find Derived Number (e) Number e must be greater than 1 and less than (p βˆ’ 1)(q βˆ’ 1). Number e must be greater than 1 and less than (p βˆ’ 1)(q βˆ’ 1). There must be no common factor for e and (p βˆ’ 1)(q βˆ’ 1) except for 1. In other words two numbers e and (p – 1)(q – 1) are coprime. There must be no common factor for e and (p βˆ’ 1)(q βˆ’ 1) except for 1. In other words two numbers e and (p – 1)(q – 1) are coprime. Form the public key The pair of numbers (n, e) form the RSA public key and is made public. Interestingly, though n is part of the public key, difficulty in factorizing a large prime number ensures that attacker cannot find in finite time the two primes (p & q) used to obtain n. This is strength of RSA. Form the public key The pair of numbers (n, e) form the RSA public key and is made public. The pair of numbers (n, e) form the RSA public key and is made public. Interestingly, though n is part of the public key, difficulty in factorizing a large prime number ensures that attacker cannot find in finite time the two primes (p & q) used to obtain n. This is strength of RSA. Interestingly, though n is part of the public key, difficulty in factorizing a large prime number ensures that attacker cannot find in finite time the two primes (p & q) used to obtain n. This is strength of RSA. Generate the private key Private Key d is calculated from p, q, and e. For given n and e, there is unique number d. Number d is the inverse of e modulo (p - 1)(q – 1). This means that d is the number less than (p - 1)(q - 1) such that when multiplied by e, it is equal to 1 modulo (p - 1)(q - 1). This relationship is written mathematically as follows βˆ’ Generate the private key Private Key d is calculated from p, q, and e. For given n and e, there is unique number d. Private Key d is calculated from p, q, and e. For given n and e, there is unique number d. Number d is the inverse of e modulo (p - 1)(q – 1). This means that d is the number less than (p - 1)(q - 1) such that when multiplied by e, it is equal to 1 modulo (p - 1)(q - 1). Number d is the inverse of e modulo (p - 1)(q – 1). This means that d is the number less than (p - 1)(q - 1) such that when multiplied by e, it is equal to 1 modulo (p - 1)(q - 1). This relationship is written mathematically as follows βˆ’ This relationship is written mathematically as follows βˆ’ ed = 1 mod (p βˆ’ 1)(q βˆ’ 1) The Extended Euclidean Algorithm takes p, q, and e as input and gives d as output. An example of generating RSA Key pair is given below. (For ease of understanding, the primes p & q taken here are small values. Practically, these values are very high). Let two primes be p = 7 and q = 13. Thus, modulus n = pq = 7 x 13 = 91. Let two primes be p = 7 and q = 13. Thus, modulus n = pq = 7 x 13 = 91. Select e = 5, which is a valid choice since there is no number that is common factor of 5 and (p βˆ’ 1)(q βˆ’ 1) = 6 Γ— 12 = 72, except for 1. Select e = 5, which is a valid choice since there is no number that is common factor of 5 and (p βˆ’ 1)(q βˆ’ 1) = 6 Γ— 12 = 72, except for 1. The pair of numbers (n, e) = (91, 5) forms the public key and can be made available to anyone whom we wish to be able to send us encrypted messages. The pair of numbers (n, e) = (91, 5) forms the public key and can be made available to anyone whom we wish to be able to send us encrypted messages. Input p = 7, q = 13, and e = 5 to the Extended Euclidean Algorithm. The output will be d = 29. Input p = 7, q = 13, and e = 5 to the Extended Euclidean Algorithm. The output will be d = 29. Check that the d calculated is correct by computing βˆ’ Check that the d calculated is correct by computing βˆ’ de = 29 Γ— 5 = 145 = 1 mod 72 Hence, public key is (91, 5) and private keys is (91, 29). Hence, public key is (91, 5) and private keys is (91, 29). Once the key pair has been generated, the process of encryption and decryption are relatively straightforward and computationally easy. Interestingly, RSA does not directly operate on strings of bits as in case of symmetric key encryption. It operates on numbers modulo n. Hence, it is necessary to represent the plaintext as a series of numbers less than n. Suppose the sender wish to send some text message to someone whose public key is (n, e). Suppose the sender wish to send some text message to someone whose public key is (n, e). The sender then represents the plaintext as a series of numbers less than n. The sender then represents the plaintext as a series of numbers less than n. To encrypt the first plaintext P, which is a number modulo n. The encryption process is simple mathematical step as βˆ’ To encrypt the first plaintext P, which is a number modulo n. The encryption process is simple mathematical step as βˆ’ C = Pe mod n In other words, the ciphertext C is equal to the plaintext P multiplied by itself e times and then reduced modulo n. This means that C is also a number less than n. In other words, the ciphertext C is equal to the plaintext P multiplied by itself e times and then reduced modulo n. This means that C is also a number less than n. Returning to our Key Generation example with plaintext P = 10, we get ciphertext C βˆ’ Returning to our Key Generation example with plaintext P = 10, we get ciphertext C βˆ’ C = 105 mod 91 The decryption process for RSA is also very straightforward. Suppose that the receiver of public-key pair (n, e) has received a ciphertext C. The decryption process for RSA is also very straightforward. Suppose that the receiver of public-key pair (n, e) has received a ciphertext C. Receiver raises C to the power of his private key d. The result modulo n will be the plaintext P. Receiver raises C to the power of his private key d. The result modulo n will be the plaintext P. Plaintext = Cd mod n Returning again to our numerical example, the ciphertext C = 82 would get decrypted to number 10 using private key 29 βˆ’ Returning again to our numerical example, the ciphertext C = 82 would get decrypted to number 10 using private key 29 βˆ’ Plaintext = 8229 mod 91 = 10 The security of RSA depends on the strengths of two separate functions. The RSA cryptosystem is most popular public-key cryptosystem strength of which is based on the practical difficulty of factoring the very large numbers. Encryption Function βˆ’ It is considered as a one-way function of converting plaintext into ciphertext and it can be reversed only with the knowledge of private key d. Encryption Function βˆ’ It is considered as a one-way function of converting plaintext into ciphertext and it can be reversed only with the knowledge of private key d. Key Generation βˆ’ The difficulty of determining a private key from an RSA public key is equivalent to factoring the modulus n. An attacker thus cannot use knowledge of an RSA public key to determine an RSA private key unless he can factor n. It is also a one way function, going from p & q values to modulus n is easy but reverse is not possible. Key Generation βˆ’ The difficulty of determining a private key from an RSA public key is equivalent to factoring the modulus n. An attacker thus cannot use knowledge of an RSA public key to determine an RSA private key unless he can factor n. It is also a one way function, going from p & q values to modulus n is easy but reverse is not possible. If either of these two functions are proved non one-way, then RSA will be broken. In fact, if a technique for factoring efficiently is developed then RSA will no longer be safe. The strength of RSA encryption drastically goes down against attacks if the number p and q are not large primes and/ or chosen public key e is a small number. Along with RSA, there are other public-key cryptosystems proposed. Many of them are based on different versions of the Discrete Logarithm Problem. ElGamal cryptosystem, called Elliptic Curve Variant, is based on the Discrete Logarithm Problem. It derives the strength from the assumption that the discrete logarithms cannot be found in practical time frame for a given number, while the inverse operation of the power can be computed efficiently. Let us go through a simple version of ElGamal that works with numbers modulo p. In the case of elliptic curve variants, it is based on quite different number systems. Each user of ElGamal cryptosystem generates the key pair through as follows βˆ’ Choosing a large prime p. Generally a prime number of 1024 to 2048 bits length is chosen. Choosing a large prime p. Generally a prime number of 1024 to 2048 bits length is chosen. Choosing a generator element g. This number must be between 1 and p βˆ’ 1, but cannot be any number. It is a generator of the multiplicative group of integers modulo p. This means for every integer m co-prime to p, there is an integer k such that gk=a mod n. For example, 3 is generator of group 5 (Z5 = {1, 2, 3, 4}). Choosing a generator element g. This number must be between 1 and p βˆ’ 1, but cannot be any number. This number must be between 1 and p βˆ’ 1, but cannot be any number. It is a generator of the multiplicative group of integers modulo p. This means for every integer m co-prime to p, there is an integer k such that gk=a mod n. For example, 3 is generator of group 5 (Z5 = {1, 2, 3, 4}). It is a generator of the multiplicative group of integers modulo p. This means for every integer m co-prime to p, there is an integer k such that gk=a mod n. For example, 3 is generator of group 5 (Z5 = {1, 2, 3, 4}). Choosing the private key. The private key x is any number bigger than 1 and smaller than pβˆ’1. Choosing the private key. The private key x is any number bigger than 1 and smaller than pβˆ’1. Computing part of the public key. The value y is computed from the parameters p, g and the private key x as follows βˆ’ Computing part of the public key. The value y is computed from the parameters p, g and the private key x as follows βˆ’ y = gx mod p Obtaining Public key. The ElGamal public key consists of the three parameters (p, g, y). For example, suppose that p = 17 and that g = 6 (It can be confirmed that 6 is a generator of group Z17). The private key x can be any number bigger than 1 and smaller than 71, so we choose x = 5. The value y is then computed as follows βˆ’ Obtaining Public key. The ElGamal public key consists of the three parameters (p, g, y). For example, suppose that p = 17 and that g = 6 (It can be confirmed that 6 is a generator of group Z17). The private key x can be any number bigger than 1 and smaller than 71, so we choose x = 5. The value y is then computed as follows βˆ’ y = 65 mod 17 = 7 Thus the private key is 62 and the public key is (17, 6, 7). Thus the private key is 62 and the public key is (17, 6, 7). The generation of an ElGamal key pair is comparatively simpler than the equivalent process for RSA. But the encryption and decryption are slightly more complex than RSA. Suppose sender wishes to send a plaintext to someone whose ElGamal public key is (p, g, y), then βˆ’ Sender represents the plaintext as a series of numbers modulo p. Sender represents the plaintext as a series of numbers modulo p. To encrypt the first plaintext P, which is represented as a number modulo p. The encryption process to obtain the ciphertext C is as follows βˆ’ Randomly generate a number k; Compute two values C1 and C2, where βˆ’ To encrypt the first plaintext P, which is represented as a number modulo p. The encryption process to obtain the ciphertext C is as follows βˆ’ Randomly generate a number k; Compute two values C1 and C2, where βˆ’ C1 = gk mod p C2 = (P*yk) mod p Send the ciphertext C, consisting of the two separate values (C1, C2), sent together. Send the ciphertext C, consisting of the two separate values (C1, C2), sent together. Referring to our ElGamal key generation example given above, the plaintext P = 13 is encrypted as follows βˆ’ Randomly generate a number, say k = 10 Compute the two values C1 and C2, where βˆ’ Referring to our ElGamal key generation example given above, the plaintext P = 13 is encrypted as follows βˆ’ Randomly generate a number, say k = 10 Compute the two values C1 and C2, where βˆ’ C1 = 610 mod 17 C2 = (13*710) mod 17 = 9 Send the ciphertext C = (C1, C2) = (15, 9). Send the ciphertext C = (C1, C2) = (15, 9). To decrypt the ciphertext (C1, C2) using private key x, the following two steps are taken βˆ’ Compute the modular inverse of (C1)x modulo p, which is (C1)-x , generally referred to as decryption factor. Obtain the plaintext by using the following formula βˆ’ To decrypt the ciphertext (C1, C2) using private key x, the following two steps are taken βˆ’ Compute the modular inverse of (C1)x modulo p, which is (C1)-x , generally referred to as decryption factor. Compute the modular inverse of (C1)x modulo p, which is (C1)-x , generally referred to as decryption factor. Obtain the plaintext by using the following formula βˆ’ Obtain the plaintext by using the following formula βˆ’ C2 Γ— (C1)-x mod p = Plaintext In our example, to decrypt the ciphertext C = (C1, C2) = (15, 9) using private key x = 5, the decryption factor is In our example, to decrypt the ciphertext C = (C1, C2) = (15, 9) using private key x = 5, the decryption factor is 15-5 mod 17 = 9 Extract plaintext P = (9 Γ— 9) mod 17 = 13. Extract plaintext P = (9 Γ— 9) mod 17 = 13. In ElGamal system, each user has a private key x. and has three components of public key βˆ’ prime modulus p, generator g, and public Y = gx mod p. The strength of the ElGamal is based on the difficulty of discrete logarithm problem. The secure key size is generally > 1024 bits. Today even 2048 bits long key are used. On the processing speed front, Elgamal is quite slow, it is used mainly for key authentication protocols. Due to higher processing efficiency, Elliptic Curve variants of ElGamal are becoming increasingly popular. Elliptic Curve Cryptography (ECC) is a term used to describe a suite of cryptographic tools and protocols whose security is based on special versions of the discrete logarithm problem. It does not use numbers modulo p. ECC is based on sets of numbers that are associated with mathematical objects called elliptic curves. There are rules for adding and computing multiples of these numbers, just as there are for numbers modulo p. ECC includes a variants of many cryptographic schemes that were initially designed for modular numbers such as ElGamal encryption and Digital Signature Algorithm. It is believed that the discrete logarithm problem is much harder when applied to points on an elliptic curve. This prompts switching from numbers modulo p to points on an elliptic curve. Also an equivalent security level can be obtained with shorter keys if we use elliptic curve-based variants. The shorter keys result in two benefits βˆ’ Ease of key management Efficient computation These benefits make elliptic-curve-based variants of encryption scheme highly attractive for application where computing resources are constrained. Let us briefly compare the RSA and ElGamal schemes on the various aspects. Until now, we discussed the use of symmetric and public key schemes to achieve the confidentiality of information. With this chapter, we begin our discussion on different cryptographic techniques designed to provide other security services. The focus of this chapter is on data integrity and cryptographic tools used to achieve the same. When sensitive information is exchanged, the receiver must have the assurance that the message has come intact from the intended sender and is not modified inadvertently or otherwise. There are two different types of data integrity threats, namely passive and active. This type of threats exists due to accidental changes in data. These data errors are likely to occur due to noise in a communication channel. Also, the data may get corrupted while the file is stored on a disk. These data errors are likely to occur due to noise in a communication channel. Also, the data may get corrupted while the file is stored on a disk. Error-correcting codes and simple checksums like Cyclic Redundancy Checks (CRCs) are used to detect the loss of data integrity. In these techniques, a digest of data is computed mathematically and appended to the data. Error-correcting codes and simple checksums like Cyclic Redundancy Checks (CRCs) are used to detect the loss of data integrity. In these techniques, a digest of data is computed mathematically and appended to the data. In this type of threats, an attacker can manipulate the data with malicious intent. At simplest level, if data is without digest, it can be modified without detection. The system can use techniques of appending CRC to data for detecting any active modification. At simplest level, if data is without digest, it can be modified without detection. The system can use techniques of appending CRC to data for detecting any active modification. At higher level of threat, attacker may modify data and try to derive new digest for modified data from exiting digest. This is possible if the digest is computed using simple mechanisms such as CRC. At higher level of threat, attacker may modify data and try to derive new digest for modified data from exiting digest. This is possible if the digest is computed using simple mechanisms such as CRC. Security mechanism such as Hash functions are used to tackle the active modification threats. Security mechanism such as Hash functions are used to tackle the active modification threats. Hash functions are extremely useful and appear in almost all information security applications. A hash function is a mathematical function that converts a numerical input value into another compressed numerical value. The input to the hash function is of arbitrary length but output is always of fixed length. Values returned by a hash function are called message digest or simply hash values. The following picture illustrated hash function βˆ’ The typical features of hash functions are βˆ’ Fixed Length Output (Hash Value) Hash function coverts data of arbitrary length to a fixed length. This process is often referred to as hashing the data. In general, the hash is much smaller than the input data, hence hash functions are sometimes called compression functions. Since a hash is a smaller representation of a larger data, it is also referred to as a digest. Hash function with n bit output is referred to as an n-bit hash function. Popular hash functions generate values between 160 and 512 bits. Fixed Length Output (Hash Value) Hash function coverts data of arbitrary length to a fixed length. This process is often referred to as hashing the data. Hash function coverts data of arbitrary length to a fixed length. This process is often referred to as hashing the data. In general, the hash is much smaller than the input data, hence hash functions are sometimes called compression functions. In general, the hash is much smaller than the input data, hence hash functions are sometimes called compression functions. Since a hash is a smaller representation of a larger data, it is also referred to as a digest. Since a hash is a smaller representation of a larger data, it is also referred to as a digest. Hash function with n bit output is referred to as an n-bit hash function. Popular hash functions generate values between 160 and 512 bits. Hash function with n bit output is referred to as an n-bit hash function. Popular hash functions generate values between 160 and 512 bits. Efficiency of Operation Generally for any hash function h with input x, computation of h(x) is a fast operation. Computationally hash functions are much faster than a symmetric encryption. Efficiency of Operation Generally for any hash function h with input x, computation of h(x) is a fast operation. Generally for any hash function h with input x, computation of h(x) is a fast operation. Computationally hash functions are much faster than a symmetric encryption. Computationally hash functions are much faster than a symmetric encryption. In order to be an effective cryptographic tool, the hash function is desired to possess following properties βˆ’ Pre-Image Resistance This property means that it should be computationally hard to reverse a hash function. In other words, if a hash function h produced a hash value z, then it should be a difficult process to find any input value x that hashes to z. This property protects against an attacker who only has a hash value and is trying to find the input. Pre-Image Resistance This property means that it should be computationally hard to reverse a hash function. This property means that it should be computationally hard to reverse a hash function. In other words, if a hash function h produced a hash value z, then it should be a difficult process to find any input value x that hashes to z. In other words, if a hash function h produced a hash value z, then it should be a difficult process to find any input value x that hashes to z. This property protects against an attacker who only has a hash value and is trying to find the input. This property protects against an attacker who only has a hash value and is trying to find the input. Second Pre-Image Resistance This property means given an input and its hash, it should be hard to find a different input with the same hash. In other words, if a hash function h for an input x produces hash value h(x), then it should be difficult to find any other input value y such that h(y) = h(x). This property of hash function protects against an attacker who has an input value and its hash, and wants to substitute different value as legitimate value in place of original input value. Second Pre-Image Resistance This property means given an input and its hash, it should be hard to find a different input with the same hash. This property means given an input and its hash, it should be hard to find a different input with the same hash. In other words, if a hash function h for an input x produces hash value h(x), then it should be difficult to find any other input value y such that h(y) = h(x). In other words, if a hash function h for an input x produces hash value h(x), then it should be difficult to find any other input value y such that h(y) = h(x). This property of hash function protects against an attacker who has an input value and its hash, and wants to substitute different value as legitimate value in place of original input value. This property of hash function protects against an attacker who has an input value and its hash, and wants to substitute different value as legitimate value in place of original input value. Collision Resistance This property means it should be hard to find two different inputs of any length that result in the same hash. This property is also referred to as collision free hash function. In other words, for a hash function h, it is hard to find any two different inputs x and y such that h(x) = h(y). Since, hash function is compressing function with fixed hash length, it is impossible for a hash function not to have collisions. This property of collision free only confirms that these collisions should be hard to find. This property makes it very difficult for an attacker to find two input values with the same hash. Also, if a hash function is collision-resistant then it is second pre-image resistant. Collision Resistance This property means it should be hard to find two different inputs of any length that result in the same hash. This property is also referred to as collision free hash function. This property means it should be hard to find two different inputs of any length that result in the same hash. This property is also referred to as collision free hash function. In other words, for a hash function h, it is hard to find any two different inputs x and y such that h(x) = h(y). In other words, for a hash function h, it is hard to find any two different inputs x and y such that h(x) = h(y). Since, hash function is compressing function with fixed hash length, it is impossible for a hash function not to have collisions. This property of collision free only confirms that these collisions should be hard to find. Since, hash function is compressing function with fixed hash length, it is impossible for a hash function not to have collisions. This property of collision free only confirms that these collisions should be hard to find. This property makes it very difficult for an attacker to find two input values with the same hash. This property makes it very difficult for an attacker to find two input values with the same hash. Also, if a hash function is collision-resistant then it is second pre-image resistant. Also, if a hash function is collision-resistant then it is second pre-image resistant. At the heart of a hashing is a mathematical function that operates on two fixed-size blocks of data to create a hash code. This hash function forms the part of the hashing algorithm. The size of each data block varies depending on the algorithm. Typically the block sizes are from 128 bits to 512 bits. The following illustration demonstrates hash function βˆ’ Hashing algorithm involves rounds of above hash function like a block cipher. Each round takes an input of a fixed size, typically a combination of the most recent message block and the output of the last round. This process is repeated for as many rounds as are required to hash the entire message. Schematic of hashing algorithm is depicted in the following illustration βˆ’ Since, the hash value of first message block becomes an input to the second hash operation, output of which alters the result of the third operation, and so on. This effect, known as an avalanche effect of hashing. Avalanche effect results in substantially different hash values for two messages that differ by even a single bit of data. Understand the difference between hash function and algorithm correctly. The hash function generates a hash code by operating on two blocks of fixed-length binary data. Hashing algorithm is a process for using the hash function, specifying how the message will be broken up and how the results from previous message blocks are chained together. Let us briefly see some popular hash functions βˆ’ MD5 was most popular and widely used hash function for quite some years. The MD family comprises of hash functions MD2, MD4, MD5 and MD6. It was adopted as Internet Standard RFC 1321. It is a 128-bit hash function. The MD family comprises of hash functions MD2, MD4, MD5 and MD6. It was adopted as Internet Standard RFC 1321. It is a 128-bit hash function. MD5 digests have been widely used in the software world to provide assurance about integrity of transferred file. For example, file servers often provide a pre-computed MD5 checksum for the files, so that a user can compare the checksum of the downloaded file to it. MD5 digests have been widely used in the software world to provide assurance about integrity of transferred file. For example, file servers often provide a pre-computed MD5 checksum for the files, so that a user can compare the checksum of the downloaded file to it. In 2004, collisions were found in MD5. An analytical attack was reported to be successful only in an hour by using computer cluster. This collision attack resulted in compromised MD5 and hence it is no longer recommended for use. In 2004, collisions were found in MD5. An analytical attack was reported to be successful only in an hour by using computer cluster. This collision attack resulted in compromised MD5 and hence it is no longer recommended for use. Family of SHA comprise of four SHA algorithms; SHA-0, SHA-1, SHA-2, and SHA-3. Though from same family, there are structurally different. The original version is SHA-0, a 160-bit hash function, was published by the National Institute of Standards and Technology (NIST) in 1993. It had few weaknesses and did not become very popular. Later in 1995, SHA-1 was designed to correct alleged weaknesses of SHA-0. The original version is SHA-0, a 160-bit hash function, was published by the National Institute of Standards and Technology (NIST) in 1993. It had few weaknesses and did not become very popular. Later in 1995, SHA-1 was designed to correct alleged weaknesses of SHA-0. SHA-1 is the most widely used of the existing SHA hash functions. It is employed in several widely used applications and protocols including Secure Socket Layer (SSL) security. SHA-1 is the most widely used of the existing SHA hash functions. It is employed in several widely used applications and protocols including Secure Socket Layer (SSL) security. In 2005, a method was found for uncovering collisions for SHA-1 within practical time frame making long-term employability of SHA-1 doubtful. In 2005, a method was found for uncovering collisions for SHA-1 within practical time frame making long-term employability of SHA-1 doubtful. SHA-2 family has four further SHA variants, SHA-224, SHA-256, SHA-384, and SHA-512 depending up on number of bits in their hash value. No successful attacks have yet been reported on SHA-2 hash function. SHA-2 family has four further SHA variants, SHA-224, SHA-256, SHA-384, and SHA-512 depending up on number of bits in their hash value. No successful attacks have yet been reported on SHA-2 hash function. Though SHA-2 is a strong hash function. Though significantly different, its basic design is still follows design of SHA-1. Hence, NIST called for new competitive hash function designs. Though SHA-2 is a strong hash function. Though significantly different, its basic design is still follows design of SHA-1. Hence, NIST called for new competitive hash function designs. In October 2012, the NIST chose the Keccak algorithm as the new SHA-3 standard. Keccak offers many benefits, such as efficient performance and good resistance for attacks. In October 2012, the NIST chose the Keccak algorithm as the new SHA-3 standard. Keccak offers many benefits, such as efficient performance and good resistance for attacks. The RIPEMD is an acronym for RACE Integrity Primitives Evaluation Message Digest. This set of hash functions was designed by open research community and generally known as a family of European hash functions. The set includes RIPEMD, RIPEMD-128, and RIPEMD-160. There also exist 256, and 320-bit versions of this algorithm. The set includes RIPEMD, RIPEMD-128, and RIPEMD-160. There also exist 256, and 320-bit versions of this algorithm. Original RIPEMD (128 bit) is based upon the design principles used in MD4 and found to provide questionable security. RIPEMD 128-bit version came as a quick fix replacement to overcome vulnerabilities on the original RIPEMD. Original RIPEMD (128 bit) is based upon the design principles used in MD4 and found to provide questionable security. RIPEMD 128-bit version came as a quick fix replacement to overcome vulnerabilities on the original RIPEMD. RIPEMD-160 is an improved version and the most widely used version in the family. The 256 and 320-bit versions reduce the chance of accidental collision, but do not have higher levels of security as compared to RIPEMD-128 and RIPEMD-160 respectively. RIPEMD-160 is an improved version and the most widely used version in the family. The 256 and 320-bit versions reduce the chance of accidental collision, but do not have higher levels of security as compared to RIPEMD-128 and RIPEMD-160 respectively. This is a 512-bit hash function. It is derived from the modified version of Advanced Encryption Standard (AES). One of the designer was Vincent Rijmen, a co-creator of the AES. It is derived from the modified version of Advanced Encryption Standard (AES). One of the designer was Vincent Rijmen, a co-creator of the AES. Three versions of Whirlpool have been released; namely WHIRLPOOL-0, WHIRLPOOL-T, and WHIRLPOOL. Three versions of Whirlpool have been released; namely WHIRLPOOL-0, WHIRLPOOL-T, and WHIRLPOOL. There are two direct applications of hash function based on its cryptographic properties. Hash functions provide protection to password storage. Instead of storing password in clear, mostly all logon processes store the hash values of passwords in the file. Instead of storing password in clear, mostly all logon processes store the hash values of passwords in the file. The Password file consists of a table of pairs which are in the form (user id, h(P)). The Password file consists of a table of pairs which are in the form (user id, h(P)). The process of logon is depicted in the following illustration βˆ’ The process of logon is depicted in the following illustration βˆ’ An intruder can only see the hashes of passwords, even if he accessed the password. He can neither logon using hash nor can he derive the password from hash value since hash function possesses the property of pre-image resistance. An intruder can only see the hashes of passwords, even if he accessed the password. He can neither logon using hash nor can he derive the password from hash value since hash function possesses the property of pre-image resistance. Data integrity check is a most common application of the hash functions. It is used to generate the checksums on data files. This application provides assurance to the user about correctness of the data. The process is depicted in the following illustration βˆ’ The integrity check helps the user to detect any changes made to original file. It however, does not provide any assurance about originality. The attacker, instead of modifying file data, can change the entire file and compute all together new hash and send to the receiver. This integrity check application is useful only if the user is sure about the originality of file. In the last chapter, we discussed the data integrity threats and the use of hashing technique to detect if any modification attacks have taken place on the data. Another type of threat that exist for data is the lack of message authentication. In this threat, the user is not sure about the originator of the message. Message authentication can be provided using the cryptographic techniques that use secret keys as done in case of encryption. MAC algorithm is a symmetric key cryptographic technique to provide message authentication. For establishing MAC process, the sender and receiver share a symmetric key K. Essentially, a MAC is an encrypted checksum generated on the underlying message that is sent along with a message to ensure message authentication. The process of using MAC for authentication is depicted in the following illustration βˆ’ Let us now try to understand the entire process in detail βˆ’ The sender uses some publicly known MAC algorithm, inputs the message and the secret key K and produces a MAC value. The sender uses some publicly known MAC algorithm, inputs the message and the secret key K and produces a MAC value. Similar to hash, MAC function also compresses an arbitrary long input into a fixed length output. The major difference between hash and MAC is that MAC uses secret key during the compression. Similar to hash, MAC function also compresses an arbitrary long input into a fixed length output. The major difference between hash and MAC is that MAC uses secret key during the compression. The sender forwards the message along with the MAC. Here, we assume that the message is sent in the clear, as we are concerned of providing message origin authentication, not confidentiality. If confidentiality is required then the message needs encryption. The sender forwards the message along with the MAC. Here, we assume that the message is sent in the clear, as we are concerned of providing message origin authentication, not confidentiality. If confidentiality is required then the message needs encryption. On receipt of the message and the MAC, the receiver feeds the received message and the shared secret key K into the MAC algorithm and re-computes the MAC value. On receipt of the message and the MAC, the receiver feeds the received message and the shared secret key K into the MAC algorithm and re-computes the MAC value. The receiver now checks equality of freshly computed MAC with the MAC received from the sender. If they match, then the receiver accepts the message and assures himself that the message has been sent by the intended sender. The receiver now checks equality of freshly computed MAC with the MAC received from the sender. If they match, then the receiver accepts the message and assures himself that the message has been sent by the intended sender. If the computed MAC does not match the MAC sent by the sender, the receiver cannot determine whether it is the message that has been altered or it is the origin that has been falsified. As a bottom-line, a receiver safely assumes that the message is not the genuine. If the computed MAC does not match the MAC sent by the sender, the receiver cannot determine whether it is the message that has been altered or it is the origin that has been falsified. As a bottom-line, a receiver safely assumes that the message is not the genuine. There are two major limitations of MAC, both due to its symmetric nature of operation βˆ’ Establishment of Shared Secret. It can provide message authentication among pre-decided legitimate users who have shared key. This requires establishment of shared secret prior to use of MAC. Establishment of Shared Secret. It can provide message authentication among pre-decided legitimate users who have shared key. It can provide message authentication among pre-decided legitimate users who have shared key. This requires establishment of shared secret prior to use of MAC. This requires establishment of shared secret prior to use of MAC. Inability to Provide Non-Repudiation Non-repudiation is the assurance that a message originator cannot deny any previously sent messages and commitments or actions. MAC technique does not provide a non-repudiation service. If the sender and receiver get involved in a dispute over message origination, MACs cannot provide a proof that a message was indeed sent by the sender. Though no third party can compute the MAC, still sender could deny having sent the message and claim that the receiver forged it, as it is impossible to determine which of the two parties computed the MAC. Inability to Provide Non-Repudiation Non-repudiation is the assurance that a message originator cannot deny any previously sent messages and commitments or actions. Non-repudiation is the assurance that a message originator cannot deny any previously sent messages and commitments or actions. MAC technique does not provide a non-repudiation service. If the sender and receiver get involved in a dispute over message origination, MACs cannot provide a proof that a message was indeed sent by the sender. MAC technique does not provide a non-repudiation service. If the sender and receiver get involved in a dispute over message origination, MACs cannot provide a proof that a message was indeed sent by the sender. Though no third party can compute the MAC, still sender could deny having sent the message and claim that the receiver forged it, as it is impossible to determine which of the two parties computed the MAC. Though no third party can compute the MAC, still sender could deny having sent the message and claim that the receiver forged it, as it is impossible to determine which of the two parties computed the MAC. Both these limitations can be overcome by using the public key based digital signatures discussed in following section. Digital signatures are the public-key primitives of message authentication. In the physical world, it is common to use handwritten signatures on handwritten or typed messages. They are used to bind signatory to the message. Similarly, a digital signature is a technique that binds a person/entity to the digital data. This binding can be independently verified by receiver as well as any third party. Digital signature is a cryptographic value that is calculated from the data and a secret key known only by the signer. In real world, the receiver of message needs assurance that the message belongs to the sender and he should not be able to repudiate the origination of that message. This requirement is very crucial in business applications, since likelihood of a dispute over exchanged data is very high. As mentioned earlier, the digital signature scheme is based on public key cryptography. The model of digital signature scheme is depicted in the following illustration βˆ’ The following points explain the entire process in detail βˆ’ Each person adopting this scheme has a public-private key pair. Each person adopting this scheme has a public-private key pair. Generally, the key pairs used for encryption/decryption and signing/verifying are different. The private key used for signing is referred to as the signature key and the public key as the verification key. Generally, the key pairs used for encryption/decryption and signing/verifying are different. The private key used for signing is referred to as the signature key and the public key as the verification key. Signer feeds data to the hash function and generates hash of data. Signer feeds data to the hash function and generates hash of data. Hash value and signature key are then fed to the signature algorithm which produces the digital signature on given hash. Signature is appended to the data and then both are sent to the verifier. Hash value and signature key are then fed to the signature algorithm which produces the digital signature on given hash. Signature is appended to the data and then both are sent to the verifier. Verifier feeds the digital signature and the verification key into the verification algorithm. The verification algorithm gives some value as output. Verifier feeds the digital signature and the verification key into the verification algorithm. The verification algorithm gives some value as output. Verifier also runs same hash function on received data to generate hash value. Verifier also runs same hash function on received data to generate hash value. For verification, this hash value and output of verification algorithm are compared. Based on the comparison result, verifier decides whether the digital signature is valid. For verification, this hash value and output of verification algorithm are compared. Based on the comparison result, verifier decides whether the digital signature is valid. Since digital signature is created by β€˜private’ key of signer and no one else can have this key; the signer cannot repudiate signing the data in future. Since digital signature is created by β€˜private’ key of signer and no one else can have this key; the signer cannot repudiate signing the data in future. It should be noticed that instead of signing data directly by signing algorithm, usually a hash of data is created. Since the hash of data is a unique representation of data, it is sufficient to sign the hash in place of data. The most important reason of using hash instead of data directly for signing is efficiency of the scheme. Let us assume RSA is used as the signing algorithm. As discussed in public key encryption chapter, the encryption/signing process using RSA involves modular exponentiation. Signing large data through modular exponentiation is computationally expensive and time consuming. The hash of the data is a relatively small digest of the data, hence signing a hash is more efficient than signing the entire data. Out of all cryptographic primitives, the digital signature using public key cryptography is considered as very important and useful tool to achieve information security. Apart from ability to provide non-repudiation of message, the digital signature also provides message authentication and data integrity. Let us briefly see how this is achieved by the digital signature βˆ’ Message authentication βˆ’ When the verifier validates the digital signature using public key of a sender, he is assured that signature has been created only by sender who possess the corresponding secret private key and no one else. Message authentication βˆ’ When the verifier validates the digital signature using public key of a sender, he is assured that signature has been created only by sender who possess the corresponding secret private key and no one else. Data Integrity βˆ’ In case an attacker has access to the data and modifies it, the digital signature verification at receiver end fails. The hash of modified data and the output provided by the verification algorithm will not match. Hence, receiver can safely deny the message assuming that data integrity has been breached. Data Integrity βˆ’ In case an attacker has access to the data and modifies it, the digital signature verification at receiver end fails. The hash of modified data and the output provided by the verification algorithm will not match. Hence, receiver can safely deny the message assuming that data integrity has been breached. Non-repudiation βˆ’ Since it is assumed that only the signer has the knowledge of the signature key, he can only create unique signature on a given data. Thus the receiver can present data and the digital signature to a third party as evidence if any dispute arises in the future. Non-repudiation βˆ’ Since it is assumed that only the signer has the knowledge of the signature key, he can only create unique signature on a given data. Thus the receiver can present data and the digital signature to a third party as evidence if any dispute arises in the future. By adding public-key encryption to digital signature scheme, we can create a cryptosystem that can provide the four essential elements of security namely βˆ’ Privacy, Authentication, Integrity, and Non-repudiation. In many digital communications, it is desirable to exchange an encrypted messages than plaintext to achieve confidentiality. In public key encryption scheme, a public (encryption) key of sender is available in open domain, and hence anyone can spoof his identity and send any encrypted message to the receiver. This makes it essential for users employing PKC for encryption to seek digital signatures along with encrypted data to be assured of message authentication and non-repudiation. This can archived by combining digital signatures with encryption scheme. Let us briefly discuss how to achieve this requirement. There are two possibilities, sign-then-encrypt and encrypt-then-sign. However, the crypto system based on sign-then-encrypt can be exploited by receiver to spoof identity of sender and sent that data to third party. Hence, this method is not preferred. The process of encrypt-then-sign is more reliable and widely adopted. This is depicted in the following illustration βˆ’ The receiver after receiving the encrypted data and signature on it, first verifies the signature using sender’s public key. After ensuring the validity of the signature, he then retrieves the data through decryption using his private key. The most distinct feature of Public Key Infrastructure (PKI) is that it uses a pair of keys to achieve the underlying security service. The key pair comprises of private key and public key. Since the public keys are in open domain, they are likely to be abused. It is, thus, necessary to establish and maintain some kind of trusted infrastructure to manage these keys. It goes without saying that the security of any cryptosystem depends upon how securely its keys are managed. Without secure procedures for the handling of cryptographic keys, the benefits of the use of strong cryptographic schemes are potentially lost. It is observed that cryptographic schemes are rarely compromised through weaknesses in their design. However, they are often compromised through poor key management. There are some important aspects of key management which are as follows βˆ’ Cryptographic keys are nothing but special pieces of data. Key management refers to the secure administration of cryptographic keys. Cryptographic keys are nothing but special pieces of data. Key management refers to the secure administration of cryptographic keys. Key management deals with entire key lifecycle as depicted in the following illustration βˆ’ Key management deals with entire key lifecycle as depicted in the following illustration βˆ’ There are two specific requirements of key management for public key cryptography. Secrecy of private keys. Throughout the key lifecycle, secret keys must remain secret from all parties except those who are owner and are authorized to use them. Assurance of public keys. In public key cryptography, the public keys are in open domain and seen as public pieces of data. By default there are no assurances of whether a public key is correct, with whom it can be associated, or what it can be used for. Thus key management of public keys needs to focus much more explicitly on assurance of purpose of public keys. There are two specific requirements of key management for public key cryptography. Secrecy of private keys. Throughout the key lifecycle, secret keys must remain secret from all parties except those who are owner and are authorized to use them. Secrecy of private keys. Throughout the key lifecycle, secret keys must remain secret from all parties except those who are owner and are authorized to use them. Assurance of public keys. In public key cryptography, the public keys are in open domain and seen as public pieces of data. By default there are no assurances of whether a public key is correct, with whom it can be associated, or what it can be used for. Thus key management of public keys needs to focus much more explicitly on assurance of purpose of public keys. Assurance of public keys. In public key cryptography, the public keys are in open domain and seen as public pieces of data. By default there are no assurances of whether a public key is correct, with whom it can be associated, or what it can be used for. Thus key management of public keys needs to focus much more explicitly on assurance of purpose of public keys. The most crucial requirement of β€˜assurance of public key’ can be achieved through the public-key infrastructure (PKI), a key management systems for supporting public-key cryptography. PKI provides assurance of public key. It provides the identification of public keys and their distribution. An anatomy of PKI comprises of the following components. Public Key Certificate, commonly referred to as β€˜digital certificate’. Private Key tokens. Certification Authority. Registration Authority. Certificate Management System. For analogy, a certificate can be considered as the ID card issued to the person. People use ID cards such as a driver's license, passport to prove their identity. A digital certificate does the same basic thing in the electronic world, but with one difference. Digital Certificates are not only issued to people but they can be issued to computers, software packages or anything else that need to prove the identity in the electronic world. Digital certificates are based on the ITU standard X.509 which defines a standard certificate format for public key certificates and certification validation. Hence digital certificates are sometimes also referred to as X.509 certificates. Public key pertaining to the user client is stored in digital certificates by The Certification Authority (CA) along with other relevant information such as client information, expiration date, usage, issuer etc. Digital certificates are based on the ITU standard X.509 which defines a standard certificate format for public key certificates and certification validation. Hence digital certificates are sometimes also referred to as X.509 certificates. Public key pertaining to the user client is stored in digital certificates by The Certification Authority (CA) along with other relevant information such as client information, expiration date, usage, issuer etc. CA digitally signs this entire information and includes digital signature in the certificate. CA digitally signs this entire information and includes digital signature in the certificate. Anyone who needs the assurance about the public key and associated information of client, he carries out the signature validation process using CA’s public key. Successful validation assures that the public key given in the certificate belongs to the person whose details are given in the certificate. Anyone who needs the assurance about the public key and associated information of client, he carries out the signature validation process using CA’s public key. Successful validation assures that the public key given in the certificate belongs to the person whose details are given in the certificate. The process of obtaining Digital Certificate by a person/entity is depicted in the following illustration. As shown in the illustration, the CA accepts the application from a client to certify his public key. The CA, after duly verifying identity of client, issues a digital certificate to that client. As discussed above, the CA issues certificate to a client and assist other users to verify the certificate. The CA takes responsibility for identifying correctly the identity of the client asking for a certificate to be issued, and ensures that the information contained within the certificate is correct and digitally signs it. The key functions of a CA are as follows βˆ’ Generating key pairs βˆ’ The CA may generate a key pair independently or jointly with the client. Generating key pairs βˆ’ The CA may generate a key pair independently or jointly with the client. Issuing digital certificates βˆ’ The CA could be thought of as the PKI equivalent of a passport agency βˆ’ the CA issues a certificate after client provides the credentials to confirm his identity. The CA then signs the certificate to prevent modification of the details contained in the certificate. Issuing digital certificates βˆ’ The CA could be thought of as the PKI equivalent of a passport agency βˆ’ the CA issues a certificate after client provides the credentials to confirm his identity. The CA then signs the certificate to prevent modification of the details contained in the certificate. Publishing Certificates βˆ’ The CA need to publish certificates so that users can find them. There are two ways of achieving this. One is to publish certificates in the equivalent of an electronic telephone directory. The other is to send your certificate out to those people you think might need it by one means or another. Publishing Certificates βˆ’ The CA need to publish certificates so that users can find them. There are two ways of achieving this. One is to publish certificates in the equivalent of an electronic telephone directory. The other is to send your certificate out to those people you think might need it by one means or another. Verifying Certificates βˆ’ The CA makes its public key available in environment to assist verification of his signature on clients’ digital certificate. Verifying Certificates βˆ’ The CA makes its public key available in environment to assist verification of his signature on clients’ digital certificate. Revocation of Certificates βˆ’ At times, CA revokes the certificate issued due to some reason such as compromise of private key by user or loss of trust in the client. After revocation, CA maintains the list of all revoked certificate that is available to the environment. Revocation of Certificates βˆ’ At times, CA revokes the certificate issued due to some reason such as compromise of private key by user or loss of trust in the client. After revocation, CA maintains the list of all revoked certificate that is available to the environment. There are four typical classes of certificate βˆ’ Class 1 βˆ’ These certificates can be easily acquired by supplying an email address. Class 1 βˆ’ These certificates can be easily acquired by supplying an email address. Class 2 βˆ’ These certificates require additional personal information to be supplied. Class 2 βˆ’ These certificates require additional personal information to be supplied. Class 3 βˆ’ These certificates can only be purchased after checks have been made about the requestor’s identity. Class 3 βˆ’ These certificates can only be purchased after checks have been made about the requestor’s identity. Class 4 βˆ’ They may be used by governments and financial organizations needing very high levels of trust. Class 4 βˆ’ They may be used by governments and financial organizations needing very high levels of trust. CA may use a third-party Registration Authority (RA) to perform the necessary checks on the person or company requesting the certificate to confirm their identity. The RA may appear to the client as a CA, but they do not actually sign the certificate that is issued. It is the management system through which certificates are published, temporarily or permanently suspended, renewed, or revoked. Certificate management systems do not normally delete certificates because it may be necessary to prove their status at a point in time, perhaps for legal reasons. A CA along with associated RA runs certificate management systems to be able to track their responsibilities and liabilities. While the public key of a client is stored on the certificate, the associated secret private key can be stored on the key owner’s computer. This method is generally not adopted. If an attacker gains access to the computer, he can easily gain access to private key. For this reason, a private key is stored on secure removable storage token access to which is protected through a password. Different vendors often use different and sometimes proprietary storage formats for storing keys. For example, Entrust uses the proprietary .epf format, while Verisign, GlobalSign, and Baltimore use the standard .p12 format. With vast networks and requirements of global communications, it is practically not feasible to have only one trusted CA from whom all users obtain their certificates. Secondly, availability of only one CA may lead to difficulties if CA is compromised. In such case, the hierarchical certification model is of interest since it allows public key certificates to be used in environments where two communicating parties do not have trust relationships with the same CA. The root CA is at the top of the CA hierarchy and the root CA's certificate is a self-signed certificate. The root CA is at the top of the CA hierarchy and the root CA's certificate is a self-signed certificate. The CAs, which are directly subordinate to the root CA (For example, CA1 and CA2) have CA certificates that are signed by the root CA. The CAs, which are directly subordinate to the root CA (For example, CA1 and CA2) have CA certificates that are signed by the root CA. The CAs under the subordinate CAs in the hierarchy (For example, CA5 and CA6) have their CA certificates signed by the higher-level subordinate CAs. The CAs under the subordinate CAs in the hierarchy (For example, CA5 and CA6) have their CA certificates signed by the higher-level subordinate CAs. Certificate authority (CA) hierarchies are reflected in certificate chains. A certificate chain traces a path of certificates from a branch in the hierarchy to the root of the hierarchy. The following illustration shows a CA hierarchy with a certificate chain leading from an entity certificate through two subordinate CA certificates (CA6 and CA3) to the CA certificate for the root CA. Verifying a certificate chain is the process of ensuring that a specific certificate chain is valid, correctly signed, and trustworthy. The following procedure verifies a certificate chain, beginning with the certificate that is presented for authentication βˆ’ A client whose authenticity is being verified supplies his certificate, generally along with the chain of certificates up to Root CA. A client whose authenticity is being verified supplies his certificate, generally along with the chain of certificates up to Root CA. Verifier takes the certificate and validates by using public key of issuer. The issuer’s public key is found in the issuer’s certificate which is in the chain next to client’s certificate. Verifier takes the certificate and validates by using public key of issuer. The issuer’s public key is found in the issuer’s certificate which is in the chain next to client’s certificate. Now if the higher CA who has signed the issuer’s certificate, is trusted by the verifier, verification is successful and stops here. Now if the higher CA who has signed the issuer’s certificate, is trusted by the verifier, verification is successful and stops here. Else, the issuer's certificate is verified in a similar manner as done for client in above steps. This process continues till either trusted CA is found in between or else it continues till Root CA. Else, the issuer's certificate is verified in a similar manner as done for client in above steps. This process continues till either trusted CA is found in between or else it continues till Root CA. Nowadays, the networks have gone global and information has taken the digital form of bits and bytes. Critical information now gets stored, processed and transmitted in digital form on computer systems and open communication channels. Since information plays such a vital role, adversaries are targeting the computer systems and open communication channels to either steal the sensitive information or to disrupt the critical information system. Modern cryptography provides a robust set of techniques to ensure that the malevolent intentions of the adversary are thwarted while ensuring the legitimate users get access to information. Here in this chapter, we will discuss the benefits that we draw from cryptography, its limitations, as well as the future of cryptography. Cryptography is an essential information security tool. It provides the four most basic services of information security βˆ’ Confidentiality βˆ’ Encryption technique can guard the information and communication from unauthorized revelation and access of information. Confidentiality βˆ’ Encryption technique can guard the information and communication from unauthorized revelation and access of information. Authentication βˆ’ The cryptographic techniques such as MAC and digital signatures can protect information against spoofing and forgeries. Authentication βˆ’ The cryptographic techniques such as MAC and digital signatures can protect information against spoofing and forgeries. Data Integrity βˆ’ The cryptographic hash functions are playing vital role in assuring the users about the data integrity. Data Integrity βˆ’ The cryptographic hash functions are playing vital role in assuring the users about the data integrity. Non-repudiation βˆ’ The digital signature provides the non-repudiation service to guard against the dispute that may arise due to denial of passing message by the sender. Non-repudiation βˆ’ The digital signature provides the non-repudiation service to guard against the dispute that may arise due to denial of passing message by the sender. All these fundamental services offered by cryptography has enabled the conduct of business over the networks using the computer systems in extremely efficient and effective manner. Apart from the four fundamental elements of information security, there are other issues that affect the effective use of information βˆ’ A strongly encrypted, authentic, and digitally signed information can be difficult to access even for a legitimate user at a crucial time of decision-making. The network or the computer system can be attacked and rendered non-functional by an intruder. A strongly encrypted, authentic, and digitally signed information can be difficult to access even for a legitimate user at a crucial time of decision-making. The network or the computer system can be attacked and rendered non-functional by an intruder. High availability, one of the fundamental aspects of information security, cannot be ensured through the use of cryptography. Other methods are needed to guard against the threats such as denial of service or complete breakdown of information system. High availability, one of the fundamental aspects of information security, cannot be ensured through the use of cryptography. Other methods are needed to guard against the threats such as denial of service or complete breakdown of information system. Another fundamental need of information security of selective access control also cannot be realized through the use of cryptography. Administrative controls and procedures are required to be exercised for the same. Another fundamental need of information security of selective access control also cannot be realized through the use of cryptography. Administrative controls and procedures are required to be exercised for the same. Cryptography does not guard against the vulnerabilities and threats that emerge from the poor design of systems, protocols, and procedures. These need to be fixed through proper design and setting up of a defensive infrastructure. Cryptography does not guard against the vulnerabilities and threats that emerge from the poor design of systems, protocols, and procedures. These need to be fixed through proper design and setting up of a defensive infrastructure. Cryptography comes at cost. The cost is in terms of time and money βˆ’ Addition of cryptographic techniques in the information processing leads to delay. The use of public key cryptography requires setting up and maintenance of public key infrastructure requiring the handsome financial budget. Cryptography comes at cost. The cost is in terms of time and money βˆ’ Addition of cryptographic techniques in the information processing leads to delay. Addition of cryptographic techniques in the information processing leads to delay. The use of public key cryptography requires setting up and maintenance of public key infrastructure requiring the handsome financial budget. The use of public key cryptography requires setting up and maintenance of public key infrastructure requiring the handsome financial budget. The security of cryptographic technique is based on the computational difficulty of mathematical problems. Any breakthrough in solving such mathematical problems or increasing the computing power can render a cryptographic technique vulnerable. The security of cryptographic technique is based on the computational difficulty of mathematical problems. Any breakthrough in solving such mathematical problems or increasing the computing power can render a cryptographic technique vulnerable. Elliptic Curve Cryptography (ECC) has already been invented but its advantages and disadvantages are not yet fully understood. ECC allows to perform encryption and decryption in a drastically lesser time, thus allowing a higher amount of data to be passed with equal security. However, as other methods of encryption, ECC must also be tested and proven secure before it is accepted for governmental, commercial, and private use. Quantum computation is the new phenomenon. While modern computers store data using a binary format called a "bit" in which a "1" or a "0" can be stored; a quantum computer stores data using a quantum superposition of multiple states. These multiple valued states are stored in "quantum bits" or "qubits". This allows the computation of numbers to be several orders of magnitude faster than traditional transistor processors. To comprehend the power of quantum computer, consider RSA-640, a number with 193 digits, which can be factored by eighty 2.2GHz computers over the span of 5 months, one quantum computer would factor in less than 17 seconds. Numbers that would typically take billions of years to compute could only take a matter of hours or even minutes with a fully developed quantum computer. In view of these facts, modern cryptography will have to look for computationally harder problems or devise completely new techniques of archiving the goals presently served by modern cryptography. 10 Lectures 2 hours Total Seminars 10 Lectures 2 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 2405, "s": 2033, "text": "Human being from ages had two inherent needs βˆ’ (a) to communicate and share information and (b) to communicate selectively. These two needs gave rise to the art of coding the messages in such a way that only the intended people could have access to the information. Unauthorized people could not extract any information, even if the scrambled messages fell in their hand." }, { "code": null, "e": 2528, "s": 2405, "text": "The art and science of concealing the messages to introduce secrecy in information security is recognized as cryptography." }, { "code": null, "e": 2649, "s": 2528, "text": "The word β€˜cryptography’ was coined by combining two Greek words, β€˜Krypto’ meaning hidden and β€˜graphene’ meaning writing." }, { "code": null, "e": 3074, "s": 2649, "text": "The art of cryptography is considered to be born along with the art of writing. As civilizations evolved, human beings got organized in tribes, groups, and kingdoms. This led to the emergence of ideas such as power, battles, supremacy, and politics. These ideas further fueled the natural need of people to communicate secretly with selective recipient which in turn ensured the continuous evolution of cryptography as well." }, { "code": null, "e": 3147, "s": 3074, "text": "The roots of cryptography are found in Roman and Egyptian civilizations." }, { "code": null, "e": 3461, "s": 3147, "text": "The first known evidence of cryptography can be traced to the use of β€˜hieroglyph’. Some 4000 years ago, the Egyptians used to communicate by messages written in hieroglyph. This code was the secret known only to the scribes who used to transmit messages on behalf of the kings. One such hieroglyph is shown below." }, { "code": null, "e": 3732, "s": 3461, "text": "Later, the scholars moved on to using simple mono-alphabetic substitution ciphers during 500 to 600 BC. This involved replacing alphabets of message with other alphabets with some secret rule. This rule became a key to retrieve the message back from the garbled message." }, { "code": null, "e": 4027, "s": 3732, "text": "The earlier Roman method of cryptography, popularly known as the Caesar Shift Cipher, relies on shifting the letters of a message by an agreed number (three was a common choice), the recipient of this message would then shift the letters back by the same number and obtain the original message." }, { "code": null, "e": 4336, "s": 4027, "text": "Steganography is similar but adds another dimension to Cryptography. In this method, people not only want to protect the secrecy of an information by concealing it, but they also want to make sure any unauthorized person gets no evidence that the information even exists. For example, invisible watermarking." }, { "code": null, "e": 4594, "s": 4336, "text": "In steganography, an unintended recipient or an intruder is unaware of the fact that observed data contains hidden information. In cryptography, an intruder is normally aware that data is being communicated, because they can see the coded/scrambled message." }, { "code": null, "e": 4827, "s": 4594, "text": "It is during and after the European Renaissance, various Italian and Papal states led the rapid proliferation of cryptographic techniques. Various analysis and attack techniques were researched in this era to break the secret codes." }, { "code": null, "e": 5046, "s": 4827, "text": "Improved coding techniques such as Vigenere Coding came into existence in the 15th century, which offered moving letters in the message with a number of variable places instead of moving them the same number of places." }, { "code": null, "e": 5265, "s": 5046, "text": "Improved coding techniques such as Vigenere Coding came into existence in the 15th century, which offered moving letters in the message with a number of variable places instead of moving them the same number of places." }, { "code": null, "e": 5423, "s": 5265, "text": "Only after the 19th century, cryptography evolved from the ad hoc approaches to encryption to the more sophisticated art and science of information security." }, { "code": null, "e": 5581, "s": 5423, "text": "Only after the 19th century, cryptography evolved from the ad hoc approaches to encryption to the more sophisticated art and science of information security." }, { "code": null, "e": 5772, "s": 5581, "text": "In the early 20th century, the invention of mechanical and electromechanical machines, such as the Enigma rotor machine, provided more advanced and efficient means of coding the information." }, { "code": null, "e": 5963, "s": 5772, "text": "In the early 20th century, the invention of mechanical and electromechanical machines, such as the Enigma rotor machine, provided more advanced and efficient means of coding the information." }, { "code": null, "e": 6067, "s": 5963, "text": "During the period of World War II, both cryptography and cryptanalysis became excessively mathematical." }, { "code": null, "e": 6171, "s": 6067, "text": "During the period of World War II, both cryptography and cryptanalysis became excessively mathematical." }, { "code": null, "e": 6512, "s": 6171, "text": "With the advances taking place in this field, government organizations, military units, and some corporate houses started adopting the applications of cryptography. They used cryptography to guard their secrets from others. Now, the arrival of computers and the Internet has brought effective cryptography within the reach of common people." }, { "code": null, "e": 6731, "s": 6512, "text": "Modern cryptography is the cornerstone of computer and communications security. Its foundation is based on various concepts of mathematics such as number theory, computational-complexity theory, and probability theory." }, { "code": null, "e": 6832, "s": 6731, "text": "There are three major characteristics that separate modern cryptography from the classical approach." }, { "code": null, "e": 6910, "s": 6832, "text": "Cryptology, the study of cryptosystems, can be subdivided into two branches βˆ’" }, { "code": null, "e": 6923, "s": 6910, "text": "Cryptography" }, { "code": null, "e": 6937, "s": 6923, "text": "Cryptanalysis" }, { "code": null, "e": 7049, "s": 6937, "text": "Cryptography is the art and science of making a cryptosystem that is capable of providing information security." }, { "code": null, "e": 7365, "s": 7049, "text": "Cryptography deals with the actual securing of digital data. It refers to the design of mechanisms based on mathematical algorithms that provide fundamental information security services. You can think of cryptography as the establishment of a large toolkit containing different techniques in security applications." }, { "code": null, "e": 7440, "s": 7365, "text": "The art and science of breaking the cipher text is known as cryptanalysis." }, { "code": null, "e": 7795, "s": 7440, "text": "Cryptanalysis is the sister branch of cryptography and they both co-exist. The cryptographic process results in the cipher text for transmission or storage. It involves the study of cryptographic mechanism with the intention to break them. Cryptanalysis is also used during the design of the new cryptographic techniques to test their security strengths." }, { "code": null, "e": 7917, "s": 7795, "text": "Note βˆ’ Cryptography concerns with the design of cryptosystems, while cryptanalysis studies the breaking of cryptosystems." }, { "code": null, "e": 8113, "s": 7917, "text": "The primary objective of using cryptography is to provide the following four fundamental information security services. Let us now see the possible goals intended to be fulfilled by cryptography." }, { "code": null, "e": 8323, "s": 8113, "text": "Confidentiality is the fundamental security service provided by cryptography. It is a security service that keeps the information from an unauthorized person. It is sometimes referred to as privacy or secrecy." }, { "code": null, "e": 8469, "s": 8323, "text": "Confidentiality can be achieved through numerous means starting from physical securing to the use of mathematical algorithms for data encryption." }, { "code": null, "e": 8764, "s": 8469, "text": "It is security service that deals with identifying any alteration to the data. The data may get modified by an unauthorized entity intentionally or accidently. Integrity service confirms that whether data is intact or not since it was last created, transmitted, or stored by an authorized user." }, { "code": null, "e": 8914, "s": 8764, "text": "Data integrity cannot prevent the alteration of data, but provides a means for detecting whether data has been manipulated in an unauthorized manner." }, { "code": null, "e": 9084, "s": 8914, "text": "Authentication provides the identification of the originator. It confirms to the receiver that the data received has been sent only by an identified and verified sender." }, { "code": null, "e": 9126, "s": 9084, "text": "Authentication service has two variants βˆ’" }, { "code": null, "e": 9253, "s": 9126, "text": "Message authentication identifies the originator of the message without any regard router or system that has sent the message." }, { "code": null, "e": 9380, "s": 9253, "text": "Message authentication identifies the originator of the message without any regard router or system that has sent the message." }, { "code": null, "e": 9493, "s": 9380, "text": "Entity authentication is assurance that data has been received from a specific entity, say a particular website." }, { "code": null, "e": 9606, "s": 9493, "text": "Entity authentication is assurance that data has been received from a specific entity, say a particular website." }, { "code": null, "e": 9766, "s": 9606, "text": "Apart from the originator, authentication may also provide assurance about other parameters related to data such as the date and time of creation/transmission." }, { "code": null, "e": 10032, "s": 9766, "text": "It is a security service that ensures that an entity cannot refuse the ownership of a previous commitment or an action. It is an assurance that the original creator of the data cannot deny the creation or transmission of the said data to a recipient or third party." }, { "code": null, "e": 10320, "s": 10032, "text": "Non-repudiation is a property that is most desirable in situations where there are chances of a dispute over the exchange of data. For example, once an order is placed electronically, a purchaser cannot deny the purchase order, if non-repudiation service was enabled in this transaction." }, { "code": null, "e": 10478, "s": 10320, "text": "Cryptography primitives are nothing but the tools and techniques in Cryptography that can be selectively used to provide a set of desired security services βˆ’" }, { "code": null, "e": 10489, "s": 10478, "text": "Encryption" }, { "code": null, "e": 10504, "s": 10489, "text": "Hash functions" }, { "code": null, "e": 10539, "s": 10504, "text": "Message Authentication codes (MAC)" }, { "code": null, "e": 10558, "s": 10539, "text": "Digital Signatures" }, { "code": null, "e": 10660, "s": 10558, "text": "The following table shows the primitives that can achieve a particular security service on their own." }, { "code": null, "e": 10811, "s": 10660, "text": "Note βˆ’ Cryptographic primitives are intricately related and they are often combined to achieve a set of desired security services from a cryptosystem." }, { "code": null, "e": 11010, "s": 10811, "text": "A cryptosystem is an implementation of cryptographic techniques and their accompanying infrastructure to provide information security services. A cryptosystem is also referred to as a cipher system." }, { "code": null, "e": 11183, "s": 11010, "text": "Let us discuss a simple model of a cryptosystem that provides confidentiality to the information being transmitted. This basic model is depicted in the illustration\nbelow βˆ’" }, { "code": null, "e": 11384, "s": 11183, "text": "The illustration shows a sender who wants to transfer some sensitive data to a receiver in such a way that any party intercepting or eavesdropping on the communication channel cannot extract the data." }, { "code": null, "e": 11519, "s": 11384, "text": "The objective of this simple cryptosystem is that at the end of the process, only the sender and the receiver will know the plaintext." }, { "code": null, "e": 11583, "s": 11519, "text": "The various components of a basic cryptosystem are as follows βˆ’" }, { "code": null, "e": 11646, "s": 11583, "text": "Plaintext. It is the data to be protected during transmission." }, { "code": null, "e": 11709, "s": 11646, "text": "Plaintext. It is the data to be protected during transmission." }, { "code": null, "e": 11942, "s": 11709, "text": "Encryption Algorithm. It is a mathematical process that produces a ciphertext for any given plaintext and encryption key. It is a cryptographic algorithm that takes plaintext and an encryption key as input and produces a ciphertext." }, { "code": null, "e": 12175, "s": 11942, "text": "Encryption Algorithm. It is a mathematical process that produces a ciphertext for any given plaintext and encryption key. It is a cryptographic algorithm that takes plaintext and an encryption key as input and produces a ciphertext." }, { "code": null, "e": 12457, "s": 12175, "text": "Ciphertext. It is the scrambled version of the plaintext produced by the encryption algorithm using a specific the encryption key. The ciphertext is not guarded. It flows on public channel. It can be intercepted or compromised by anyone who has access to the communication channel." }, { "code": null, "e": 12739, "s": 12457, "text": "Ciphertext. It is the scrambled version of the plaintext produced by the encryption algorithm using a specific the encryption key. The ciphertext is not guarded. It flows on public channel. It can be intercepted or compromised by anyone who has access to the communication channel." }, { "code": null, "e": 13087, "s": 12739, "text": "Decryption Algorithm, It is a mathematical process, that produces a unique plaintext for any given ciphertext and decryption key. It is a cryptographic algorithm that takes a ciphertext and a decryption key as input, and outputs a plaintext. The decryption algorithm essentially reverses the encryption algorithm and is thus closely related to it." }, { "code": null, "e": 13435, "s": 13087, "text": "Decryption Algorithm, It is a mathematical process, that produces a unique plaintext for any given ciphertext and decryption key. It is a cryptographic algorithm that takes a ciphertext and a decryption key as input, and outputs a plaintext. The decryption algorithm essentially reverses the encryption algorithm and is thus closely related to it." }, { "code": null, "e": 13622, "s": 13435, "text": "Encryption Key. It is a value that is known to the sender. The sender inputs the encryption key into the encryption algorithm along with the plaintext in order to compute the ciphertext." }, { "code": null, "e": 13809, "s": 13622, "text": "Encryption Key. It is a value that is known to the sender. The sender inputs the encryption key into the encryption algorithm along with the plaintext in order to compute the ciphertext." }, { "code": null, "e": 14088, "s": 13809, "text": "Decryption Key. It is a value that is known to the receiver. The decryption key is related to the encryption key, but is not always identical to it. The receiver inputs the decryption key into the decryption algorithm along with the ciphertext in order to compute the plaintext." }, { "code": null, "e": 14367, "s": 14088, "text": "Decryption Key. It is a value that is known to the receiver. The decryption key is related to the encryption key, but is not always identical to it. The receiver inputs the decryption key into the decryption algorithm along with the ciphertext in order to compute the plaintext." }, { "code": null, "e": 14461, "s": 14367, "text": "For a given cryptosystem, a collection of all possible decryption keys is called a key space." }, { "code": null, "e": 14671, "s": 14461, "text": "An interceptor (an attacker) is an unauthorized entity who attempts to determine the plaintext. He can see the ciphertext and may know the decryption algorithm. He, however, must never know the decryption key." }, { "code": null, "e": 14805, "s": 14671, "text": "Fundamentally, there are two types of cryptosystems based on the manner in which encryption-decryption is carried out in the system βˆ’" }, { "code": null, "e": 14830, "s": 14805, "text": "Symmetric Key Encryption" }, { "code": null, "e": 14856, "s": 14830, "text": "Asymmetric Key Encryption" }, { "code": null, "e": 15150, "s": 14856, "text": "The main difference between these cryptosystems is the relationship between the encryption and the decryption key. Logically, in any cryptosystem, both the keys are closely associated. It is practically impossible to decrypt the ciphertext with the key that is unrelated to the encryption key." }, { "code": null, "e": 15282, "s": 15150, "text": "The encryption process where same keys are used for encrypting and decrypting the information is known as Symmetric Key Encryption." }, { "code": null, "e": 15445, "s": 15282, "text": "The study of symmetric cryptosystems is referred to as symmetric cryptography. Symmetric cryptosystems are also sometimes referred to as secret key cryptosystems." }, { "code": null, "e": 15587, "s": 15445, "text": "A few well-known examples of symmetric key encryption methods are βˆ’ Digital Encryption Standard (DES), Triple-DES (3DES), IDEA, and BLOWFISH." }, { "code": null, "e": 15868, "s": 15587, "text": "Prior to 1970, all cryptosystems employed symmetric key encryption. Even today, its relevance is very high and it is being used extensively in many cryptosystems. It is very unlikely that this encryption will fade away, as it has certain advantages over asymmetric key encryption." }, { "code": null, "e": 15945, "s": 15868, "text": "The salient features of cryptosystem based on symmetric key encryption are βˆ’" }, { "code": null, "e": 16042, "s": 15945, "text": "Persons using symmetric key encryption must share a common key prior to exchange of information." }, { "code": null, "e": 16139, "s": 16042, "text": "Persons using symmetric key encryption must share a common key prior to exchange of information." }, { "code": null, "e": 16221, "s": 16139, "text": "Keys are recommended to be changed regularly to prevent any attack on the system." }, { "code": null, "e": 16303, "s": 16221, "text": "Keys are recommended to be changed regularly to prevent any attack on the system." }, { "code": null, "e": 16487, "s": 16303, "text": "A robust mechanism needs to exist to exchange the key between the communicating parties. As keys are required to be changed regularly, this mechanism becomes expensive and cumbersome." }, { "code": null, "e": 16671, "s": 16487, "text": "A robust mechanism needs to exist to exchange the key between the communicating parties. As keys are required to be changed regularly, this mechanism becomes expensive and cumbersome." }, { "code": null, "e": 16810, "s": 16671, "text": "In a group of n people, to enable two-party communication between any two persons, the number of keys required for group is n Γ— (n – 1)/2." }, { "code": null, "e": 16949, "s": 16810, "text": "In a group of n people, to enable two-party communication between any two persons, the number of keys required for group is n Γ— (n – 1)/2." }, { "code": null, "e": 17096, "s": 16949, "text": "Length of Key (number of bits) in this encryption is smaller and hence, process of encryption-decryption is faster than asymmetric key encryption." }, { "code": null, "e": 17243, "s": 17096, "text": "Length of Key (number of bits) in this encryption is smaller and hence, process of encryption-decryption is faster than asymmetric key encryption." }, { "code": null, "e": 17324, "s": 17243, "text": "Processing power of computer system required to run symmetric algorithm is less." }, { "code": null, "e": 17405, "s": 17324, "text": "Processing power of computer system required to run symmetric algorithm is less." }, { "code": null, "e": 17483, "s": 17405, "text": "There are two restrictive challenges of employing symmetric key cryptography." }, { "code": null, "e": 17662, "s": 17483, "text": "Key establishment βˆ’ Before any communication, both the sender and the receiver need to agree on a secret symmetric key. It requires a secure key establishment mechanism in place." }, { "code": null, "e": 17841, "s": 17662, "text": "Key establishment βˆ’ Before any communication, both the sender and the receiver need to agree on a secret symmetric key. It requires a secure key establishment mechanism in place." }, { "code": null, "e": 18112, "s": 17841, "text": "Trust Issue βˆ’ Since the sender and the receiver use the same symmetric key, there is an implicit requirement that the sender and the receiver β€˜trust’ each other. For example, it may happen that the receiver has lost the key to an attacker and the sender is not informed." }, { "code": null, "e": 18383, "s": 18112, "text": "Trust Issue βˆ’ Since the sender and the receiver use the same symmetric key, there is an implicit requirement that the sender and the receiver β€˜trust’ each other. For example, it may happen that the receiver has lost the key to an attacker and the sender is not informed." }, { "code": null, "e": 18702, "s": 18383, "text": "These two challenges are highly restraining for modern day communication. Today, people need to exchange information with non-familiar and non-trusted parties. For example, a communication between online seller and customer. These limitations of symmetric key encryption gave rise to asymmetric key encryption schemes." }, { "code": null, "e": 19033, "s": 18702, "text": "The encryption process where different keys are used for encrypting and decrypting the information is known as Asymmetric Key Encryption. Though the keys are different, they are mathematically related and hence, retrieving the plaintext by decrypting ciphertext is feasible. The process is depicted in the following illustration βˆ’" }, { "code": null, "e": 19239, "s": 19033, "text": "Asymmetric Key Encryption was invented in the 20th century to come over the necessity of pre-shared secret key between communicating persons. The salient features of this encryption scheme are as follows βˆ’" }, { "code": null, "e": 19480, "s": 19239, "text": "Every user in this system needs to have a pair of dissimilar keys, private key and public key. These keys are mathematically related βˆ’ when one key is used for encryption, the other can decrypt the ciphertext back to the original plaintext." }, { "code": null, "e": 19721, "s": 19480, "text": "Every user in this system needs to have a pair of dissimilar keys, private key and public key. These keys are mathematically related βˆ’ when one key is used for encryption, the other can decrypt the ciphertext back to the original plaintext." }, { "code": null, "e": 19893, "s": 19721, "text": "It requires to put the public key in public repository and the private key as a well-guarded secret. Hence, this scheme of encryption is also called Public Key Encryption." }, { "code": null, "e": 20065, "s": 19893, "text": "It requires to put the public key in public repository and the private key as a well-guarded secret. Hence, this scheme of encryption is also called Public Key Encryption." }, { "code": null, "e": 20217, "s": 20065, "text": "Though public and private keys of the user are related, it is computationally not feasible to find one from another. This is a strength of this scheme." }, { "code": null, "e": 20369, "s": 20217, "text": "Though public and private keys of the user are related, it is computationally not feasible to find one from another. This is a strength of this scheme." }, { "code": null, "e": 20495, "s": 20369, "text": "When Host1 needs to send data to Host2, he obtains the public key of Host2 from repository, encrypts the data, and transmits." }, { "code": null, "e": 20621, "s": 20495, "text": "When Host1 needs to send data to Host2, he obtains the public key of Host2 from repository, encrypts the data, and transmits." }, { "code": null, "e": 20674, "s": 20621, "text": "Host2 uses his private key to extract the plaintext." }, { "code": null, "e": 20727, "s": 20674, "text": "Host2 uses his private key to extract the plaintext." }, { "code": null, "e": 20876, "s": 20727, "text": "Length of Keys (number of bits) in this encryption is large and hence, the process of encryption-decryption is slower than symmetric key encryption." }, { "code": null, "e": 21025, "s": 20876, "text": "Length of Keys (number of bits) in this encryption is large and hence, the process of encryption-decryption is slower than symmetric key encryption." }, { "code": null, "e": 21109, "s": 21025, "text": "Processing power of computer system required to run asymmetric algorithm is higher." }, { "code": null, "e": 21193, "s": 21109, "text": "Processing power of computer system required to run asymmetric algorithm is higher." }, { "code": null, "e": 21313, "s": 21193, "text": "Symmetric cryptosystems are a natural concept. In contrast, public-key cryptosystems are quite difficult to comprehend." }, { "code": null, "e": 21721, "s": 21313, "text": "You may think, how can the encryption key and the decryption key are β€˜related’, and yet it is impossible to determine the decryption key from the encryption key? The answer lies in the mathematical concepts. It is possible to design a cryptosystem whose keys have this property. The concept of public-key cryptography is relatively new. There are fewer public-key algorithms known than symmetric algorithms." }, { "code": null, "e": 21965, "s": 21721, "text": "Public-key cryptosystems have one significant challenge βˆ’ the user needs to trust that the public key that he is using in communications with a person really is the public key of that person and has not been spoofed by a malicious third party." }, { "code": null, "e": 22295, "s": 21965, "text": "This is usually accomplished through a Public Key Infrastructure (PKI) consisting a trusted third party. The third party securely manages and attests to the authenticity of public keys. When the third party is requested to provide the public key for any communicating person X, they are trusted to provide the correct public key." }, { "code": null, "e": 22624, "s": 22295, "text": "The third party satisfies itself about user identity by the process of attestation, notarization, or some other process βˆ’ that X is the one and only, or globally unique, X. The most common method of making the verified public keys available is to embed them in a certificate which is digitally signed by the trusted third party." }, { "code": null, "e": 22705, "s": 22624, "text": "A summary of basic key properties of two types of cryptosystems is given below βˆ’" }, { "code": null, "e": 22879, "s": 22705, "text": "Due to the advantages and disadvantage of both the systems, symmetric key and public-key cryptosystems are often used together in the practical information security systems." }, { "code": null, "e": 23192, "s": 22879, "text": "In the 19th century, a Dutch cryptographer A. Kerckhoff furnished the requirements of a good cryptosystem. Kerckhoff stated that a cryptographic system should be secure even if everything about the system, except the key, is public knowledge. The six design principles defined by Kerckhoff for cryptosystem are βˆ’" }, { "code": null, "e": 23267, "s": 23192, "text": "The cryptosystem should be unbreakable practically, if not mathematically." }, { "code": null, "e": 23342, "s": 23267, "text": "The cryptosystem should be unbreakable practically, if not mathematically." }, { "code": null, "e": 23489, "s": 23342, "text": "Falling of the cryptosystem in the hands of an intruder should not lead to any compromise of the system, preventing any inconvenience to the user." }, { "code": null, "e": 23636, "s": 23489, "text": "Falling of the cryptosystem in the hands of an intruder should not lead to any compromise of the system, preventing any inconvenience to the user." }, { "code": null, "e": 23702, "s": 23636, "text": "The key should be easily communicable, memorable, and changeable." }, { "code": null, "e": 23768, "s": 23702, "text": "The key should be easily communicable, memorable, and changeable." }, { "code": null, "e": 23842, "s": 23768, "text": "The ciphertext should be transmissible by telegraph, an unsecure channel." }, { "code": null, "e": 23916, "s": 23842, "text": "The ciphertext should be transmissible by telegraph, an unsecure channel." }, { "code": null, "e": 24007, "s": 23916, "text": "The encryption apparatus and documents should be portable and operable by a single person." }, { "code": null, "e": 24098, "s": 24007, "text": "The encryption apparatus and documents should be portable and operable by a single person." }, { "code": null, "e": 24243, "s": 24098, "text": "Finally, it is necessary that the system be easy to use, requiring neither mental strain nor the knowledge of a long series of rules to observe." }, { "code": null, "e": 24388, "s": 24243, "text": "Finally, it is necessary that the system be easy to use, requiring neither mental strain nor the knowledge of a long series of rules to observe." }, { "code": null, "e": 24703, "s": 24388, "text": "The second rule is currently known as Kerckhoff principle. It is applied in virtually all the contemporary encryption algorithms such as DES, AES, etc. These public algorithms are considered to be thoroughly secure. The security of the encrypted message depends solely on the security of the secret encryption key." }, { "code": null, "e": 24889, "s": 24703, "text": "Keeping the algorithms secret may act as a significant barrier to cryptanalysis. However, keeping the algorithms secret is possible only when they are used in a strictly limited circle." }, { "code": null, "e": 25137, "s": 24889, "text": "In modern era, cryptography needs to cater to users who are connected to the Internet. In such cases, using a secret algorithm is not feasible, hence Kerckhoff principles became essential guidelines for designing algorithms in modern cryptography." }, { "code": null, "e": 25433, "s": 25137, "text": "In the present era, not only business but almost all the aspects of human life are driven by information. Hence, it has become imperative to protect useful information from malicious activities such as attacks. Let us consider the types of attacks to which information is typically subjected to." }, { "code": null, "e": 25557, "s": 25433, "text": "Attacks are typically categorized based on the action performed by the attacker. An attack, thus, can be passive or active." }, { "code": null, "e": 25768, "s": 25557, "text": "The main goal of a passive attack is to obtain unauthorized access to the information. For example, actions such as intercepting and eavesdropping on the communication channel can be regarded as passive attack." }, { "code": null, "e": 26206, "s": 25768, "text": "These actions are passive in nature, as they neither affect information nor disrupt the communication channel. A passive attack is often seen as stealing information. The only difference in stealing physical goods and stealing information is that theft of data still leaves the owner in possession of that data. Passive information attack is thus more dangerous than stealing of goods, as information theft may go unnoticed by the owner." }, { "code": null, "e": 26329, "s": 26206, "text": "An active attack involves changing the information in some way by conducting some process on the information. For example," }, { "code": null, "e": 26382, "s": 26329, "text": "Modifying the information in an unauthorized manner." }, { "code": null, "e": 26435, "s": 26382, "text": "Modifying the information in an unauthorized manner." }, { "code": null, "e": 26502, "s": 26435, "text": "Initiating unintended or unauthorized transmission of information." }, { "code": null, "e": 26569, "s": 26502, "text": "Initiating unintended or unauthorized transmission of information." }, { "code": null, "e": 26668, "s": 26569, "text": "Alteration of authentication data such as originator name or timestamp associated with information" }, { "code": null, "e": 26767, "s": 26668, "text": "Alteration of authentication data such as originator name or timestamp associated with information" }, { "code": null, "e": 26798, "s": 26767, "text": "Unauthorized deletion of data." }, { "code": null, "e": 26829, "s": 26798, "text": "Unauthorized deletion of data." }, { "code": null, "e": 26903, "s": 26829, "text": "Denial of access to information for legitimate users (denial of service)." }, { "code": null, "e": 26977, "s": 26903, "text": "Denial of access to information for legitimate users (denial of service)." }, { "code": null, "e": 27115, "s": 26977, "text": "Cryptography provides many tools and techniques for implementing cryptosystems capable of preventing most of the attacks described above." }, { "code": null, "e": 27241, "s": 27115, "text": "Let us see the prevailing environment around cryptosystems followed by the types of attacks employed to break these systems βˆ’" }, { "code": null, "e": 27441, "s": 27241, "text": "While considering possible attacks on the cryptosystem, it is necessary to know the cryptosystems environment. The attacker’s assumptions and knowledge about the environment decides his capabilities." }, { "code": null, "e": 27559, "s": 27441, "text": "In cryptography, the following three assumptions are made about the security environment and attacker’s capabilities." }, { "code": null, "e": 27644, "s": 27559, "text": "The design of a cryptosystem is based on the following two cryptography algorithms βˆ’" }, { "code": null, "e": 27760, "s": 27644, "text": "Public Algorithms βˆ’ With this option, all the details of the algorithm are in the public domain, known to everyone." }, { "code": null, "e": 27876, "s": 27760, "text": "Public Algorithms βˆ’ With this option, all the details of the algorithm are in the public domain, known to everyone." }, { "code": null, "e": 27980, "s": 27876, "text": "Proprietary algorithms βˆ’ The details of the algorithm are only known by the system designers and users." }, { "code": null, "e": 28084, "s": 27980, "text": "Proprietary algorithms βˆ’ The details of the algorithm are only known by the system designers and users." }, { "code": null, "e": 28298, "s": 28084, "text": "In case of proprietary algorithms, security is ensured through obscurity. Private algorithms may not be the strongest algorithms as they are developed in-house and may not be extensively investigated for weakness." }, { "code": null, "e": 28612, "s": 28298, "text": "Secondly, they allow communication among closed group only. Hence they are not suitable for modern communication where people communicate with large number of known or unknown entities. Also, according to Kerckhoff’s principle, the algorithm is preferred to be public with strength of encryption lying in the key." }, { "code": null, "e": 28725, "s": 28612, "text": "Thus, the first assumption about security environment is that the encryption algorithm is known to the attacker." }, { "code": null, "e": 28962, "s": 28725, "text": "We know that once the plaintext is encrypted into ciphertext, it is put on unsecure public channel (say email) for transmission. Thus, the attacker can obviously assume that it has access to the ciphertext generated by the cryptosystem." }, { "code": null, "e": 29155, "s": 28962, "text": "This assumption is not as obvious as other. However, there may be situations where an attacker can have access to plaintext and corresponding ciphertext. Some such possible circumstances are βˆ’" }, { "code": null, "e": 29253, "s": 29155, "text": "The attacker influences the sender to convert plaintext of his choice and obtains the ciphertext." }, { "code": null, "e": 29351, "s": 29253, "text": "The attacker influences the sender to convert plaintext of his choice and obtains the ciphertext." }, { "code": null, "e": 29501, "s": 29351, "text": "The receiver may divulge the plaintext to the attacker inadvertently. The attacker has access to corresponding ciphertext gathered from open channel." }, { "code": null, "e": 29651, "s": 29501, "text": "The receiver may divulge the plaintext to the attacker inadvertently. The attacker has access to corresponding ciphertext gathered from open channel." }, { "code": null, "e": 29841, "s": 29651, "text": "In a public-key cryptosystem, the encryption key is in open domain and is known to any potential attacker. Using this key, he can generate pairs of corresponding plaintexts and ciphertexts." }, { "code": null, "e": 30031, "s": 29841, "text": "In a public-key cryptosystem, the encryption key is in open domain and is known to any potential attacker. Using this key, he can generate pairs of corresponding plaintexts and ciphertexts." }, { "code": null, "e": 30274, "s": 30031, "text": "The basic intention of an attacker is to break a cryptosystem and to find the plaintext from the ciphertext. To obtain the plaintext, the attacker only needs to find out the secret decryption key, as the algorithm is already in public domain." }, { "code": null, "e": 30476, "s": 30274, "text": "Hence, he applies maximum effort towards finding out the secret key used in the cryptosystem. Once the attacker is able to determine the key, the attacked system is considered as broken or compromised." }, { "code": null, "e": 30561, "s": 30476, "text": "Based on the methodology used, attacks on cryptosystems are categorized as follows βˆ’" }, { "code": null, "e": 30959, "s": 30561, "text": "Ciphertext Only Attacks (COA) βˆ’ In this method, the attacker has access to a set of ciphertext(s). He does not have access to corresponding plaintext. COA is said to be successful when the corresponding plaintext can be determined from a given set of ciphertext. Occasionally, the encryption key can be determined from this attack. Modern cryptosystems are guarded against ciphertext-only attacks." }, { "code": null, "e": 31357, "s": 30959, "text": "Ciphertext Only Attacks (COA) βˆ’ In this method, the attacker has access to a set of ciphertext(s). He does not have access to corresponding plaintext. COA is said to be successful when the corresponding plaintext can be determined from a given set of ciphertext. Occasionally, the encryption key can be determined from this attack. Modern cryptosystems are guarded against ciphertext-only attacks." }, { "code": null, "e": 31690, "s": 31357, "text": "Known Plaintext Attack (KPA) βˆ’ In this method, the attacker knows the plaintext for some parts of the ciphertext. The task is to decrypt the rest of the ciphertext using this information. This may be done by determining the key or via some other method. The best example of this attack is linear cryptanalysis against block ciphers." }, { "code": null, "e": 32023, "s": 31690, "text": "Known Plaintext Attack (KPA) βˆ’ In this method, the attacker knows the plaintext for some parts of the ciphertext. The task is to decrypt the rest of the ciphertext using this information. This may be done by determining the key or via some other method. The best example of this attack is linear cryptanalysis against block ciphers." }, { "code": null, "e": 32437, "s": 32023, "text": "Chosen Plaintext Attack (CPA) βˆ’ In this method, the attacker has the text of his choice encrypted. So he has the ciphertext-plaintext pair of his choice. This simplifies his task of determining the encryption key. An example of this attack is differential cryptanalysis applied against block ciphers as well as hash functions. A popular public key cryptosystem, RSA is also vulnerable to chosen-plaintext attacks." }, { "code": null, "e": 32851, "s": 32437, "text": "Chosen Plaintext Attack (CPA) βˆ’ In this method, the attacker has the text of his choice encrypted. So he has the ciphertext-plaintext pair of his choice. This simplifies his task of determining the encryption key. An example of this attack is differential cryptanalysis applied against block ciphers as well as hash functions. A popular public key cryptosystem, RSA is also vulnerable to chosen-plaintext attacks." }, { "code": null, "e": 33210, "s": 32851, "text": "Dictionary Attack βˆ’ This attack has many variants, all of which involve compiling a β€˜dictionary’. In simplest method of this attack, attacker builds a dictionary of ciphertexts and corresponding plaintexts that he has learnt over a period of time. In future, when an attacker gets the ciphertext, he refers the dictionary to find the corresponding plaintext." }, { "code": null, "e": 33569, "s": 33210, "text": "Dictionary Attack βˆ’ This attack has many variants, all of which involve compiling a β€˜dictionary’. In simplest method of this attack, attacker builds a dictionary of ciphertexts and corresponding plaintexts that he has learnt over a period of time. In future, when an attacker gets the ciphertext, he refers the dictionary to find the corresponding plaintext." }, { "code": null, "e": 33942, "s": 33569, "text": "Brute Force Attack (BFA) βˆ’ In this method, the attacker tries to determine the key by attempting all possible keys. If the key is 8 bits long, then the number of possible keys is 28 = 256. The attacker knows the ciphertext and the algorithm, now he attempts all the 256 keys one by one for decryption. The time to complete the attack would be very high if the key is long." }, { "code": null, "e": 34315, "s": 33942, "text": "Brute Force Attack (BFA) βˆ’ In this method, the attacker tries to determine the key by attempting all possible keys. If the key is 8 bits long, then the number of possible keys is 28 = 256. The attacker knows the ciphertext and the algorithm, now he attempts all the 256 keys one by one for decryption. The time to complete the attack would be very high if the key is long." }, { "code": null, "e": 35083, "s": 34315, "text": "Birthday Attack βˆ’ This attack is a variant of brute-force technique. It is used against the cryptographic hash function. When students in a class are asked about their birthdays, the answer is one of the possible 365 dates. Let us assume the first student's birthdate is 3rd Aug. Then to find the next student whose birthdate is 3rd Aug, we need to enquire 1.25*√365 β‰ˆ 25 students.\nSimilarly, if the hash function produces 64 bit hash values, the possible hash values are 1.8x1019. By repeatedly evaluating the function for different inputs, the same output is expected to be obtained after about 5.1x109 random inputs.\nIf the attacker is able to find two different inputs that give the same hash value, it is a collision and that hash function is said to be broken." }, { "code": null, "e": 35466, "s": 35083, "text": "Birthday Attack βˆ’ This attack is a variant of brute-force technique. It is used against the cryptographic hash function. When students in a class are asked about their birthdays, the answer is one of the possible 365 dates. Let us assume the first student's birthdate is 3rd Aug. Then to find the next student whose birthdate is 3rd Aug, we need to enquire 1.25*√365 β‰ˆ 25 students." }, { "code": null, "e": 35704, "s": 35466, "text": "Similarly, if the hash function produces 64 bit hash values, the possible hash values are 1.8x1019. By repeatedly evaluating the function for different inputs, the same output is expected to be obtained after about 5.1x109 random inputs." }, { "code": null, "e": 35851, "s": 35704, "text": "If the attacker is able to find two different inputs that give the same hash value, it is a collision and that hash function is said to be broken." }, { "code": null, "e": 36442, "s": 35851, "text": "Man in Middle Attack (MIM) βˆ’ The targets of this attack are mostly public key cryptosystems where key exchange is involved before communication takes place.\n\nHost A wants to communicate to host B, hence requests public key of B.\nAn attacker intercepts this request and sends his public key instead.\nThus, whatever host A sends to host B, the attacker is able to read.\nIn order to maintain communication, the attacker re-encrypts the data after reading with his public key and sends to B.\nThe attacker sends his public key as A’s public key so that B takes it as if it is taking it from A.\n\n" }, { "code": null, "e": 36599, "s": 36442, "text": "Man in Middle Attack (MIM) βˆ’ The targets of this attack are mostly public key cryptosystems where key exchange is involved before communication takes place." }, { "code": null, "e": 36670, "s": 36599, "text": "Host A wants to communicate to host B, hence requests public key of B." }, { "code": null, "e": 36741, "s": 36670, "text": "Host A wants to communicate to host B, hence requests public key of B." }, { "code": null, "e": 36811, "s": 36741, "text": "An attacker intercepts this request and sends his public key instead." }, { "code": null, "e": 36881, "s": 36811, "text": "An attacker intercepts this request and sends his public key instead." }, { "code": null, "e": 36950, "s": 36881, "text": "Thus, whatever host A sends to host B, the attacker is able to read." }, { "code": null, "e": 37019, "s": 36950, "text": "Thus, whatever host A sends to host B, the attacker is able to read." }, { "code": null, "e": 37139, "s": 37019, "text": "In order to maintain communication, the attacker re-encrypts the data after reading with his public key and sends to B." }, { "code": null, "e": 37259, "s": 37139, "text": "In order to maintain communication, the attacker re-encrypts the data after reading with his public key and sends to B." }, { "code": null, "e": 37360, "s": 37259, "text": "The attacker sends his public key as A’s public key so that B takes it as if it is taking it from A." }, { "code": null, "e": 37461, "s": 37360, "text": "The attacker sends his public key as A’s public key so that B takes it as if it is taking it from A." }, { "code": null, "e": 37670, "s": 37461, "text": "Side Channel Attack (SCA) βˆ’ This type of attack is not against any particular type of cryptosystem or algorithm. Instead, it is launched to exploit the weakness in physical implementation of the cryptosystem." }, { "code": null, "e": 37879, "s": 37670, "text": "Side Channel Attack (SCA) βˆ’ This type of attack is not against any particular type of cryptosystem or algorithm. Instead, it is launched to exploit the weakness in physical implementation of the cryptosystem." }, { "code": null, "e": 38201, "s": 37879, "text": "Timing Attacks βˆ’ They exploit the fact that different computations take different times to compute on processor. By measuring such timings, it is be possible to know about a particular computation the processor is carrying out. For example, if the encryption takes a longer time, it indicates that the secret key is long." }, { "code": null, "e": 38523, "s": 38201, "text": "Timing Attacks βˆ’ They exploit the fact that different computations take different times to compute on processor. By measuring such timings, it is be possible to know about a particular computation the processor is carrying out. For example, if the encryption takes a longer time, it indicates that the secret key is long." }, { "code": null, "e": 38715, "s": 38523, "text": "Power Analysis Attacks βˆ’ These attacks are similar to timing attacks except that the amount of power consumption is used to obtain information about the nature of the underlying computations." }, { "code": null, "e": 38907, "s": 38715, "text": "Power Analysis Attacks βˆ’ These attacks are similar to timing attacks except that the amount of power consumption is used to obtain information about the nature of the underlying computations." }, { "code": null, "e": 39059, "s": 38907, "text": "Fault analysis Attacks βˆ’ In these attacks, errors are induced in the cryptosystem and the attacker studies the resulting output for useful information." }, { "code": null, "e": 39211, "s": 39059, "text": "Fault analysis Attacks βˆ’ In these attacks, errors are induced in the cryptosystem and the attacker studies the resulting output for useful information." }, { "code": null, "e": 39635, "s": 39211, "text": "The attacks on cryptosystems described here are highly academic, as majority of them come from the academic community. In fact, many academic attacks involve quite unrealistic assumptions about environment as well as the capabilities of the attacker. For example, in chosen-ciphertext attack, the attacker requires an impractical number of deliberately chosen plaintext-ciphertext pairs. It may not be practical altogether." }, { "code": null, "e": 39782, "s": 39635, "text": "Nonetheless, the fact that any attack exists should be a cause of concern, particularly if the attack technique has the potential for improvement." }, { "code": null, "e": 40085, "s": 39782, "text": "In the second chapter, we discussed the fundamentals of modern cryptography. We equated cryptography with a toolkit where various cryptographic techniques are considered as the basic tools. One of these tools is the Symmetric Key Encryption where the key used for encryption and decryption is the same." }, { "code": null, "e": 40191, "s": 40085, "text": "In this chapter, we discuss this technique further and its applications to develop various cryptosystems." }, { "code": null, "e": 40279, "s": 40191, "text": "Before proceeding further, you need to know some facts about historical cryptosystems βˆ’" }, { "code": null, "e": 40346, "s": 40279, "text": "All of these systems are based on symmetric key encryption scheme." }, { "code": null, "e": 40413, "s": 40346, "text": "All of these systems are based on symmetric key encryption scheme." }, { "code": null, "e": 40496, "s": 40413, "text": "The only security service these systems provide is confidentiality of information." }, { "code": null, "e": 40579, "s": 40496, "text": "The only security service these systems provide is confidentiality of information." }, { "code": null, "e": 40711, "s": 40579, "text": "Unlike modern systems which are digital and treat data as binary numbers, the earlier systems worked on alphabets as basic element." }, { "code": null, "e": 40843, "s": 40711, "text": "Unlike modern systems which are digital and treat data as binary numbers, the earlier systems worked on alphabets as basic element." }, { "code": null, "e": 41047, "s": 40843, "text": "These earlier cryptographic systems are also referred to as Ciphers. In general, a cipher is simply just a set of steps (an algorithm) for performing both an encryption, and the corresponding decryption." }, { "code": null, "e": 41225, "s": 41047, "text": "It is a mono-alphabetic cipher wherein each letter of the plaintext is substituted by another letter to form the ciphertext. It is a simplest form of substitution cipher scheme." }, { "code": null, "e": 41407, "s": 41225, "text": "This cryptosystem is generally referred to as the Shift Cipher. The concept is to replace each alphabet by another alphabet which is β€˜shifted’ by some fixed number between 0 and 25." }, { "code": null, "e": 41586, "s": 41407, "text": "For this type of scheme, both sender and receiver agree on a β€˜secret shift number’ for shifting the alphabet. This number which is between 0 and 25 becomes the key of encryption." }, { "code": null, "e": 41696, "s": 41586, "text": "The name β€˜Caesar Cipher’ is occasionally used to describe the Shift Cipher when the β€˜shift of three’ is used." }, { "code": null, "e": 41891, "s": 41696, "text": "In order to encrypt a plaintext letter, the sender positions the sliding ruler underneath the first set of plaintext letters and slides it to LEFT by the number of positions of the secret shift." }, { "code": null, "e": 42086, "s": 41891, "text": "In order to encrypt a plaintext letter, the sender positions the sliding ruler underneath the first set of plaintext letters and slides it to LEFT by the number of positions of the secret shift." }, { "code": null, "e": 42425, "s": 42086, "text": "The plaintext letter is then encrypted to the ciphertext letter on the sliding ruler underneath. The result of this process is depicted in the following illustration for an agreed shift of three positions. In this case, the plaintext β€˜tutorial’ is encrypted to the ciphertext β€˜WXWRULDO’. Here is the ciphertext alphabet for a Shift of 3 βˆ’" }, { "code": null, "e": 42764, "s": 42425, "text": "The plaintext letter is then encrypted to the ciphertext letter on the sliding ruler underneath. The result of this process is depicted in the following illustration for an agreed shift of three positions. In this case, the plaintext β€˜tutorial’ is encrypted to the ciphertext β€˜WXWRULDO’. Here is the ciphertext alphabet for a Shift of 3 βˆ’" }, { "code": null, "e": 42969, "s": 42764, "text": "On receiving the ciphertext, the receiver who also knows the secret shift, positions his sliding ruler underneath the ciphertext alphabet and slides it to RIGHT by the agreed shift number, 3 in this case." }, { "code": null, "e": 43174, "s": 42969, "text": "On receiving the ciphertext, the receiver who also knows the secret shift, positions his sliding ruler underneath the ciphertext alphabet and slides it to RIGHT by the agreed shift number, 3 in this case." }, { "code": null, "e": 43449, "s": 43174, "text": "He then replaces the ciphertext letter by the plaintext letter on the sliding ruler underneath. Hence the ciphertext β€˜WXWRULDO’ is decrypted to β€˜tutorial’. To decrypt a message encoded with a Shift of 3, generate the plaintext alphabet using a shift of β€˜-3’ as shown below βˆ’" }, { "code": null, "e": 43724, "s": 43449, "text": "He then replaces the ciphertext letter by the plaintext letter on the sliding ruler underneath. Hence the ciphertext β€˜WXWRULDO’ is decrypted to β€˜tutorial’. To decrypt a message encoded with a Shift of 3, generate the plaintext alphabet using a shift of β€˜-3’ as shown below βˆ’" }, { "code": null, "e": 43914, "s": 43724, "text": "Caesar Cipher is not a secure cryptosystem because there are only 26 possible keys to try out. An attacker can carry out an exhaustive key search with available limited computing resources." }, { "code": null, "e": 44069, "s": 43914, "text": "It is an improvement to the Caesar Cipher. Instead of shifting the alphabets by some number, this scheme uses some permutation of the letters in alphabet." }, { "code": null, "e": 44229, "s": 44069, "text": "For example, A.B.....Y.Z and Z.Y......B.A are two obvious permutation of all the letters in alphabet. Permutation is nothing but a jumbled up set of alphabets." }, { "code": null, "e": 44489, "s": 44229, "text": "With 26 letters in alphabet, the possible permutations are 26! (Factorial of 26) which is equal to 4x1026. The sender and the receiver may choose any one of these possible permutation as a ciphertext alphabet. This permutation is the secret key of the scheme." }, { "code": null, "e": 44545, "s": 44489, "text": "Write the alphabets A, B, C,...,Z in the natural order." }, { "code": null, "e": 44601, "s": 44545, "text": "Write the alphabets A, B, C,...,Z in the natural order." }, { "code": null, "e": 44703, "s": 44601, "text": "The sender and the receiver decide on a randomly selected permutation of the letters of the alphabet." }, { "code": null, "e": 44805, "s": 44703, "text": "The sender and the receiver decide on a randomly selected permutation of the letters of the alphabet." }, { "code": null, "e": 45205, "s": 44805, "text": "Underneath the natural order alphabets, write out the chosen permutation of the letters of the alphabet. For encryption, sender replaces each plaintext letters by substituting the permutation letter that is directly beneath it in the table. This process is shown in the following illustration. In this example, the chosen permutation is K,D, G, ..., O. The plaintext β€˜point’ is encrypted to β€˜MJBXZ’." }, { "code": null, "e": 45605, "s": 45205, "text": "Underneath the natural order alphabets, write out the chosen permutation of the letters of the alphabet. For encryption, sender replaces each plaintext letters by substituting the permutation letter that is directly beneath it in the table. This process is shown in the following illustration. In this example, the chosen permutation is K,D, G, ..., O. The plaintext β€˜point’ is encrypted to β€˜MJBXZ’." }, { "code": null, "e": 45696, "s": 45605, "text": "Here is a jumbled Ciphertext alphabet, where the order of the ciphertext letters is a key." }, { "code": null, "e": 45941, "s": 45696, "text": "On receiving the ciphertext, the receiver, who also knows the randomly chosen permutation, replaces each ciphertext letter on the bottom row with the corresponding plaintext letter in the top row. The ciphertext β€˜MJBXZ’ is decrypted to β€˜point’." }, { "code": null, "e": 46186, "s": 45941, "text": "On receiving the ciphertext, the receiver, who also knows the randomly chosen permutation, replaces each ciphertext letter on the bottom row with the corresponding plaintext letter in the top row. The ciphertext β€˜MJBXZ’ is decrypted to β€˜point’." }, { "code": null, "e": 46607, "s": 46186, "text": "Simple Substitution Cipher is a considerable improvement over the Caesar Cipher. The possible number of keys is large (26!) and even the modern computing systems are not yet powerful enough to comfortably launch a brute force attack to break the system. However, the Simple Substitution Cipher has a simple design and it is prone to design flaws, say choosing obvious permutation, this cryptosystem can be easily broken." }, { "code": null, "e": 46895, "s": 46607, "text": "Monoalphabetic cipher is a substitution cipher in which for a given key, the cipher alphabet for each plain alphabet is fixed throughout the encryption process. For example, if β€˜A’ is encrypted as β€˜D’, for any number of occurrence in that plaintext, β€˜A’ will always get encrypted to β€˜D’." }, { "code": null, "e": 47044, "s": 46895, "text": "All of the substitution ciphers we have discussed earlier in this chapter are monoalphabetic; these ciphers are highly susceptible to cryptanalysis." }, { "code": null, "e": 47291, "s": 47044, "text": "Polyalphabetic Cipher is a substitution cipher in which the cipher alphabet for the plain alphabet may be different at different places during the encryption process. The next two examples, playfair and Vigenere Cipher are polyalphabetic ciphers." }, { "code": null, "e": 47411, "s": 47291, "text": "In this scheme, pairs of letters are encrypted, instead of single letters as in the case of simple substitution cipher." }, { "code": null, "e": 47765, "s": 47411, "text": "In playfair cipher, initially a key table is created. The key table is a 5Γ—5 grid of alphabets that acts as the key for encrypting the plaintext. Each of the 25 alphabets must be unique and one letter of the alphabet (usually J) is omitted from the table as we need only 25 alphabets instead of 26. If the plaintext contains J, then it is replaced by I." }, { "code": null, "e": 48090, "s": 47765, "text": "The sender and the receiver deicide on a particular key, say β€˜tutorials’. In a key table, the first characters (going left to right) in the table is the phrase, excluding the duplicate letters. The rest of the table will be filled with the remaining letters of the alphabet, in natural order. The key table works out to be βˆ’" }, { "code": null, "e": 48330, "s": 48090, "text": "First, a plaintext message is split into pairs of two letters (digraphs). If there is an odd number of letters, a Z is added to the last letter. Let us say we want to encrypt the message β€œhide money”. It will be written as βˆ’\nHI DE MO NE YZ" }, { "code": null, "e": 48555, "s": 48330, "text": "First, a plaintext message is split into pairs of two letters (digraphs). If there is an odd number of letters, a Z is added to the last letter. Let us say we want to encrypt the message β€œhide money”. It will be written as βˆ’" }, { "code": null, "e": 48570, "s": 48555, "text": "HI DE MO NE YZ" }, { "code": null, "e": 48719, "s": 48570, "text": "The rules of encryption are βˆ’\n\nIf both the letters are in the same column, take the letter below each one (going back to the top if at the bottom)\n\n" }, { "code": null, "e": 48749, "s": 48719, "text": "The rules of encryption are βˆ’" }, { "code": null, "e": 48865, "s": 48749, "text": "If both the letters are in the same column, take the letter below each one (going back to the top if at the bottom)" }, { "code": null, "e": 48981, "s": 48865, "text": "If both the letters are in the same column, take the letter below each one (going back to the top if at the bottom)" }, { "code": null, "e": 49109, "s": 48981, "text": "If both letters are in the same row, take the letter to the right of each one (going back to the left if at the farthest right)" }, { "code": null, "e": 49237, "s": 49109, "text": "If both letters are in the same row, take the letter to the right of each one (going back to the left if at the farthest right)" }, { "code": null, "e": 49396, "s": 49237, "text": "If neither of the preceding two rules are true, form a rectangle with the two letters and take the letters on the horizontal opposite corner of the rectangle." }, { "code": null, "e": 49555, "s": 49396, "text": "If neither of the preceding two rules are true, form a rectangle with the two letters and take the letters on the horizontal opposite corner of the rectangle." }, { "code": null, "e": 49658, "s": 49555, "text": "Using these rules, the result of the encryption of β€˜hide money’ with the key of β€˜tutorials’ would be βˆ’" }, { "code": null, "e": 49673, "s": 49658, "text": "QC EF NU MF ZV" }, { "code": null, "e": 49867, "s": 49673, "text": "Decrypting the Playfair cipher is as simple as doing the same process in reverse. Receiver has the same key and can create the same key table, and then decrypt any messages made using that key." }, { "code": null, "e": 50183, "s": 49867, "text": "It is also a substitution cipher and is difficult to break compared to the simple substitution cipher. As in case of substitution cipher, cryptanalysis is possible on the Playfair cipher as well, however it would be against 625 possible pairs of letters (25x25 alphabets) instead of 26 different possible alphabets." }, { "code": null, "e": 50324, "s": 50183, "text": "The Playfair cipher was used mainly to protect important, yet non-critical secrets, as it is quick to use and requires no special equipment." }, { "code": null, "e": 50455, "s": 50324, "text": "This scheme of cipher uses a text string (say, a word) as a key, which is then used for doing a number of shifts on the plaintext." }, { "code": null, "e": 50586, "s": 50455, "text": "For example, let’s assume the key is β€˜point’. Each alphabet of the key is converted to its respective numeric value: In this case," }, { "code": null, "e": 50629, "s": 50586, "text": "p β†’ 16, o β†’ 15, i β†’ 9, n β†’ 14, and t β†’ 20." }, { "code": null, "e": 50662, "s": 50629, "text": "Thus, the key is: 16 15 9 14 20." }, { "code": null, "e": 50786, "s": 50662, "text": "The sender and the receiver decide on a key. Say β€˜point’ is the key. Numeric representation of this key is β€˜16 15 9 14 20’." }, { "code": null, "e": 50910, "s": 50786, "text": "The sender and the receiver decide on a key. Say β€˜point’ is the key. Numeric representation of this key is β€˜16 15 9 14 20’." }, { "code": null, "e": 51036, "s": 50910, "text": "The sender wants to encrypt the message, say β€˜attack from south east’. He will arrange plaintext and numeric key as follows βˆ’" }, { "code": null, "e": 51162, "s": 51036, "text": "The sender wants to encrypt the message, say β€˜attack from south east’. He will arrange plaintext and numeric key as follows βˆ’" }, { "code": null, "e": 51269, "s": 51162, "text": "He now shifts each plaintext alphabet by the number written below it to create ciphertext as shown below βˆ’" }, { "code": null, "e": 51376, "s": 51269, "text": "He now shifts each plaintext alphabet by the number written below it to create ciphertext as shown below βˆ’" }, { "code": null, "e": 51553, "s": 51376, "text": "Here, each plaintext character has been shifted by a different amount – and that amount is determined by the key. The key must be less than or equal to the size of the message." }, { "code": null, "e": 51730, "s": 51553, "text": "Here, each plaintext character has been shifted by a different amount – and that amount is determined by the key. The key must be less than or equal to the size of the message." }, { "code": null, "e": 51850, "s": 51730, "text": "For decryption, the receiver uses the same key and shifts received ciphertext in reverse order to obtain the plaintext." }, { "code": null, "e": 51970, "s": 51850, "text": "For decryption, the receiver uses the same key and shifts received ciphertext in reverse order to obtain the plaintext." }, { "code": null, "e": 52200, "s": 51970, "text": "Vigenere Cipher was designed by tweaking the standard Caesar cipher to reduce the effectiveness of cryptanalysis on the ciphertext and make a cryptosystem more robust. It is significantly more secure than a regular Caesar Cipher." }, { "code": null, "e": 52397, "s": 52200, "text": "In the history, it was regularly used for protecting sensitive political and military information. It was referred to as the unbreakable cipher due to the difficulty it posed to the cryptanalysis." }, { "code": null, "e": 52446, "s": 52397, "text": "There are two special cases of Vigenere cipher βˆ’" }, { "code": null, "e": 52578, "s": 52446, "text": "The keyword length is same as plaintect message. This case is called Vernam Cipher. It is more secure than typical Vigenere cipher." }, { "code": null, "e": 52710, "s": 52578, "text": "The keyword length is same as plaintect message. This case is called Vernam Cipher. It is more secure than typical Vigenere cipher." }, { "code": null, "e": 52801, "s": 52710, "text": "Vigenere cipher becomes a cryptosystem with perfect secrecy, which is called One-time pad." }, { "code": null, "e": 52892, "s": 52801, "text": "Vigenere cipher becomes a cryptosystem with perfect secrecy, which is called One-time pad." }, { "code": null, "e": 52916, "s": 52892, "text": "The circumstances are βˆ’" }, { "code": null, "e": 52982, "s": 52916, "text": "The length of the keyword is same as the length of the plaintext." }, { "code": null, "e": 53039, "s": 52982, "text": "The keyword is a randomly generated string of alphabets." }, { "code": null, "e": 53070, "s": 53039, "text": "The keyword is used only once." }, { "code": null, "e": 53117, "s": 53070, "text": "Let us compare Shift cipher with one-time pad." }, { "code": null, "e": 53396, "s": 53117, "text": "In case of Shift cipher, the entire message could have had a shift between 1 and 25. This is a very small size, and very easy to brute force. However, with each character now having its own individual shift between 1 and 26, the possible keys grow exponentially for the message." }, { "code": null, "e": 53855, "s": 53396, "text": "Let us say, we encrypt the name β€œpoint” with a one-time pad. It is a 5 letter text. To break the ciphertext by brute force, you need to try all possibilities of keys and conduct computation for (26 x 26 x 26 x 26 x 26) = 265 = 11881376 times. That’s for a message with 5 alphabets. Thus, for a longer message, the computation grows exponentially with every additional alphabet. This makes it computationally impossible to break the ciphertext by brute force." }, { "code": null, "e": 54023, "s": 53855, "text": "It is another type of cipher where the order of the alphabets in the plaintext is rearranged to create the ciphertext. The actual plaintext alphabets are not replaced." }, { "code": null, "e": 54202, "s": 54023, "text": "An example is a β€˜simple columnar transposition’ cipher where the plaintext is written horizontally with a certain alphabet width. Then the ciphertext is read vertically as shown." }, { "code": null, "e": 54432, "s": 54202, "text": "For example, the plaintext is β€œgolden statue is in eleventh cave” and the secret random key chosen is β€œfive”. We arrange this text horizontally in table with number of column equal to key value. The resulting text is shown below." }, { "code": null, "e": 54574, "s": 54432, "text": "The ciphertext is obtained by reading column vertically downward from first to last column. The ciphertext is β€˜gnuneaoseenvltiltedasehetivc’." }, { "code": null, "e": 54814, "s": 54574, "text": "To decrypt, the receiver prepares similar table. The number of columns is equal to key number. The number of rows is obtained by dividing number of total ciphertext alphabets by key value and rounding of the quotient to next integer value." }, { "code": null, "e": 54994, "s": 54814, "text": "The receiver then writes the received ciphertext vertically down and from left to right column. To obtain the text, he reads horizontally left to right and from top to bottom row." }, { "code": null, "e": 55278, "s": 54994, "text": "Digital data is represented in strings of binary digits (bits) unlike alphabets. Modern cryptosystems need to process this binary strings to convert in to another binary string. Based on how these binary strings are processed, a symmetric encryption schemes can be classified in to βˆ’" }, { "code": null, "e": 55624, "s": 55278, "text": "In this scheme, the plain binary text is processed in blocks (groups) of bits at a time; i.e. a block of plaintext bits is selected, a series of operations is performed on this block to generate a block of ciphertext bits. The number of bits in a block is fixed. For example, the schemes DES and AES have block sizes of 64 and 128, respectively." }, { "code": null, "e": 55878, "s": 55624, "text": "In this scheme, the plaintext is processed one bit at a time i.e. one bit of plaintext is taken, and a series of operations is performed on it to generate one bit of ciphertext. Technically, stream ciphers are block ciphers with a block size of one bit." }, { "code": null, "e": 55938, "s": 55878, "text": "The basic scheme of a block cipher is depicted as follows βˆ’" }, { "code": null, "e": 56240, "s": 55938, "text": "A block cipher takes a block of plaintext bits and generates a block of ciphertext bits, generally of same size. The size of block is fixed in the given scheme. The choice of block size does not directly affect to the strength of encryption scheme. The strength of cipher depends up on the key length." }, { "code": null, "e": 56351, "s": 56240, "text": "Though any size of block is acceptable, following aspects are borne in mind while selecting a size of a block." }, { "code": null, "e": 56800, "s": 56351, "text": "Avoid very small block size βˆ’ Say a block size is m bits. Then the possible plaintext bits combinations are then 2m. If the attacker discovers the plain text blocks corresponding to some previously sent ciphertext blocks, then the attacker can launch a type of β€˜dictionary attack’ by building up a dictionary of plaintext/ciphertext pairs sent using that encryption key. A larger block size makes attack harder as the dictionary needs to be larger." }, { "code": null, "e": 57249, "s": 56800, "text": "Avoid very small block size βˆ’ Say a block size is m bits. Then the possible plaintext bits combinations are then 2m. If the attacker discovers the plain text blocks corresponding to some previously sent ciphertext blocks, then the attacker can launch a type of β€˜dictionary attack’ by building up a dictionary of plaintext/ciphertext pairs sent using that encryption key. A larger block size makes attack harder as the dictionary needs to be larger." }, { "code": null, "e": 57419, "s": 57249, "text": "Do not have very large block size βˆ’ With very large block size, the cipher becomes inefficient to operate. Such plaintexts will need to be padded before being encrypted." }, { "code": null, "e": 57589, "s": 57419, "text": "Do not have very large block size βˆ’ With very large block size, the cipher becomes inefficient to operate. Such plaintexts will need to be padded before being encrypted." }, { "code": null, "e": 57747, "s": 57589, "text": "Multiples of 8 bit βˆ’ A preferred block size is a multiple of 8 as it is easy for implementation as most computer processor handle data in multiple of 8 bits." }, { "code": null, "e": 57905, "s": 57747, "text": "Multiples of 8 bit βˆ’ A preferred block size is a multiple of 8 as it is easy for implementation as most computer processor handle data in multiple of 8 bits." }, { "code": null, "e": 58471, "s": 57905, "text": "Block ciphers process blocks of fixed sizes (say 64 bits). The length of plaintexts is mostly not a multiple of the block size. For example, a 150-bit plaintext provides two blocks of 64 bits each with third block of balance 22 bits. The last block of bits needs to be padded up with redundant information so that the length of the final block equal to block size of the scheme. In our example, the remaining 22 bits need to have additional 42 redundant bits added to provide a complete block. The process of adding bits to the last block is referred to as padding." }, { "code": null, "e": 58619, "s": 58471, "text": "Too much padding makes the system inefficient. Also, padding may render the system insecure at times, if the padding is done with same bits always." }, { "code": null, "e": 58778, "s": 58619, "text": "There is a vast number of block ciphers schemes that are in use. Many of them are publically known. Most popular and prominent block ciphers are listed below." }, { "code": null, "e": 58939, "s": 58778, "text": "Digital Encryption Standard (DES) βˆ’ The popular block cipher of the 1990s. It is now considered as a β€˜broken’ block cipher, due primarily to its small key size." }, { "code": null, "e": 59100, "s": 58939, "text": "Digital Encryption Standard (DES) βˆ’ The popular block cipher of the 1990s. It is now considered as a β€˜broken’ block cipher, due primarily to its small key size." }, { "code": null, "e": 59278, "s": 59100, "text": "Triple DES βˆ’ It is a variant scheme based on repeated DES applications. It is still a respected block ciphers but inefficient compared to the new faster block ciphers available." }, { "code": null, "e": 59456, "s": 59278, "text": "Triple DES βˆ’ It is a variant scheme based on repeated DES applications. It is still a respected block ciphers but inefficient compared to the new faster block ciphers available." }, { "code": null, "e": 59609, "s": 59456, "text": "Advanced Encryption Standard (AES) βˆ’ It is a relatively new block cipher based on the encryption algorithm Rijndael that won the AES design competition." }, { "code": null, "e": 59762, "s": 59609, "text": "Advanced Encryption Standard (AES) βˆ’ It is a relatively new block cipher based on the encryption algorithm Rijndael that won the AES design competition." }, { "code": null, "e": 60043, "s": 59762, "text": "IDEA βˆ’ It is a sufficiently strong block cipher with a block size of 64 and a key size of 128 bits. A number of applications use IDEA encryption, including early versions of Pretty Good Privacy (PGP) protocol. The use of IDEA scheme has a restricted adoption due to patent issues." }, { "code": null, "e": 60324, "s": 60043, "text": "IDEA βˆ’ It is a sufficiently strong block cipher with a block size of 64 and a key size of 128 bits. A number of applications use IDEA encryption, including early versions of Pretty Good Privacy (PGP) protocol. The use of IDEA scheme has a restricted adoption due to patent issues." }, { "code": null, "e": 60532, "s": 60324, "text": "Twofish βˆ’ This scheme of block cipher uses block size of 128 bits and a key of variable length. It was one of the AES finalists. It is based on the earlier block cipher Blowfish with a block size of 64 bits." }, { "code": null, "e": 60740, "s": 60532, "text": "Twofish βˆ’ This scheme of block cipher uses block size of 128 bits and a key of variable length. It was one of the AES finalists. It is based on the earlier block cipher Blowfish with a block size of 64 bits." }, { "code": null, "e": 60948, "s": 60740, "text": "Serpent βˆ’ A block cipher with a block size of 128 bits and key lengths of 128, 192, or 256 bits, which was also an AES competition finalist. It is a slower but has more secure design than other block cipher." }, { "code": null, "e": 61156, "s": 60948, "text": "Serpent βˆ’ A block cipher with a block size of 128 bits and key lengths of 128, 192, or 256 bits, which was also an AES competition finalist. It is a slower but has more secure design than other block cipher." }, { "code": null, "e": 61301, "s": 61156, "text": "In the next sections, we will first discuss the model of block cipher followed by DES and AES, two of the most influential modern block ciphers." }, { "code": null, "e": 61594, "s": 61301, "text": "Feistel Cipher is not a specific scheme of block cipher. It is a design model from which many different block ciphers are derived. DES is just one example of a Feistel Cipher. A cryptographic system based on Feistel cipher structure uses the same algorithm for both encryption and decryption." }, { "code": null, "e": 61782, "s": 61594, "text": "The encryption process uses the Feistel structure consisting multiple rounds of\nprocessing of the plaintext, each round consisting of a β€œsubstitution” step followed by a permutation step." }, { "code": null, "e": 61841, "s": 61782, "text": "Feistel Structure is shown in the following illustration βˆ’" }, { "code": null, "e": 61967, "s": 61841, "text": "The input block to each round is divided into two halves that can be denoted as L and R for the left half and the right half." }, { "code": null, "e": 62093, "s": 61967, "text": "The input block to each round is divided into two halves that can be denoted as L and R for the left half and the right half." }, { "code": null, "e": 62439, "s": 62093, "text": "In each round, the right half of the block, R, goes through unchanged. But the left half, L, goes through an operation that depends on R and the encryption key. First, we apply an encrypting function β€˜f’ that takes two input βˆ’ the key K and R. The function produces the output f(R,K). Then, we XOR the output of the mathematical function with L." }, { "code": null, "e": 62785, "s": 62439, "text": "In each round, the right half of the block, R, goes through unchanged. But the left half, L, goes through an operation that depends on R and the encryption key. First, we apply an encrypting function β€˜f’ that takes two input βˆ’ the key K and R. The function produces the output f(R,K). Then, we XOR the output of the mathematical function with L." }, { "code": null, "e": 63083, "s": 62785, "text": "In real implementation of the Feistel Cipher, such as DES, instead of using the whole encryption key during each round, a round-dependent key (a subkey) is derived from the encryption key. This means that each round uses a different key, although all these subkeys are related to the original key." }, { "code": null, "e": 63381, "s": 63083, "text": "In real implementation of the Feistel Cipher, such as DES, instead of using the whole encryption key during each round, a round-dependent key (a subkey) is derived from the encryption key. This means that each round uses a different key, although all these subkeys are related to the original key." }, { "code": null, "e": 63598, "s": 63381, "text": "The permutation step at the end of each round swaps the modified L and unmodified R. Therefore, the L for the next round would be R of the current round. And R for the next round be the output L of the current round." }, { "code": null, "e": 63815, "s": 63598, "text": "The permutation step at the end of each round swaps the modified L and unmodified R. Therefore, the L for the next round would be R of the current round. And R for the next round be the output L of the current round." }, { "code": null, "e": 63932, "s": 63815, "text": "Above substitution and permutation steps form a β€˜round’. The number of rounds are specified by the algorithm design." }, { "code": null, "e": 64049, "s": 63932, "text": "Above substitution and permutation steps form a β€˜round’. The number of rounds are specified by the algorithm design." }, { "code": null, "e": 64180, "s": 64049, "text": "Once the last round is completed then the two sub blocks, β€˜R’ and β€˜L’ are concatenated in this order to form the ciphertext block." }, { "code": null, "e": 64311, "s": 64180, "text": "Once the last round is completed then the two sub blocks, β€˜R’ and β€˜L’ are concatenated in this order to form the ciphertext block." }, { "code": null, "e": 64533, "s": 64311, "text": "The difficult part of designing a Feistel Cipher is selection of round function β€˜f’. In order to be unbreakable scheme, this function needs to have several important properties that are beyond the scope of our discussion." }, { "code": null, "e": 64803, "s": 64533, "text": "The process of decryption in Feistel cipher is almost similar. Instead of starting with a block of plaintext, the ciphertext block is fed into the start of the Feistel structure and then the process thereafter is exactly the same as described in the given illustration." }, { "code": null, "e": 64983, "s": 64803, "text": "The process is said to be almost similar and not exactly same. In the case of decryption, the only difference is that the subkeys used in encryption are used in the reverse order." }, { "code": null, "e": 65170, "s": 64983, "text": "The final swapping of β€˜L’ and β€˜R’ in last step of the Feistel Cipher is essential. If these are not swapped then the resulting ciphertext could not be decrypted using the same algorithm." }, { "code": null, "e": 65487, "s": 65170, "text": "The number of rounds used in a Feistel Cipher depends on desired security from the system. More number of rounds provide more secure system. But at the same time, more rounds mean the inefficient slow encryption and decryption processes. Number of rounds in the systems thus depend upon efficiency–security tradeoff." }, { "code": null, "e": 65626, "s": 65487, "text": "The Data Encryption Standard (DES) is a symmetric-key block cipher published by the National Institute of Standards and Technology (NIST)." }, { "code": null, "e": 65983, "s": 65626, "text": "DES is an implementation of a Feistel Cipher. It uses 16 round Feistel structure. The block size is 64-bit. Though, key length is 64-bit, DES has an effective key length of 56 bits, since 8 of the 64 bits of the key are not used by the encryption algorithm (function as check bits only). General Structure of DES is depicted in the following illustration βˆ’" }, { "code": null, "e": 66066, "s": 65983, "text": "Since DES is based on the Feistel Cipher, all that is required to specify DES is βˆ’" }, { "code": null, "e": 66081, "s": 66066, "text": "Round function" }, { "code": null, "e": 66094, "s": 66081, "text": "Key schedule" }, { "code": null, "e": 66152, "s": 66094, "text": "Any additional processing βˆ’ Initial and final permutation" }, { "code": null, "e": 66366, "s": 66152, "text": "The initial and final permutations are straight Permutation boxes (P-boxes) that are inverses of each other. They have no cryptography significance in DES. The initial and final permutations are shown as follows βˆ’" }, { "code": null, "e": 66506, "s": 66366, "text": "The heart of this cipher is the DES function, f. The DES function applies a 48-bit key to the rightmost 32 bits to produce a 32-bit output." }, { "code": null, "e": 66711, "s": 66506, "text": "Expansion Permutation Box βˆ’ Since right input is 32-bit and round key is a 48-bit, we first need to expand right input to 48 bits. Permutation logic is graphically depicted in the following illustration βˆ’" }, { "code": null, "e": 66916, "s": 66711, "text": "Expansion Permutation Box βˆ’ Since right input is 32-bit and round key is a 48-bit, we first need to expand right input to 48 bits. Permutation logic is graphically depicted in the following illustration βˆ’" }, { "code": null, "e": 67035, "s": 66916, "text": "The graphically depicted permutation logic is generally described as table in DES specification illustrated as shown βˆ’" }, { "code": null, "e": 67154, "s": 67035, "text": "The graphically depicted permutation logic is generally described as table in DES specification illustrated as shown βˆ’" }, { "code": null, "e": 67323, "s": 67154, "text": "XOR (Whitener). βˆ’ After the expansion permutation, DES does XOR operation on the expanded right section and the round key. The round key is used only in this operation." }, { "code": null, "e": 67492, "s": 67323, "text": "XOR (Whitener). βˆ’ After the expansion permutation, DES does XOR operation on the expanded right section and the round key. The round key is used only in this operation." }, { "code": null, "e": 67664, "s": 67492, "text": "Substitution Boxes. βˆ’ The S-boxes carry out the real mixing (confusion). DES uses 8 S-boxes, each with a 6-bit input and a 4-bit output. Refer the following illustration βˆ’" }, { "code": null, "e": 67836, "s": 67664, "text": "Substitution Boxes. βˆ’ The S-boxes carry out the real mixing (confusion). DES uses 8 S-boxes, each with a 6-bit input and a 4-bit output. Refer the following illustration βˆ’" }, { "code": null, "e": 67874, "s": 67836, "text": "The S-box rule is illustrated below βˆ’" }, { "code": null, "e": 67912, "s": 67874, "text": "The S-box rule is illustrated below βˆ’" }, { "code": null, "e": 68024, "s": 67912, "text": "There are a total of eight S-box tables. The output of all eight s-boxes is then combined in to 32 bit section." }, { "code": null, "e": 68136, "s": 68024, "text": "There are a total of eight S-box tables. The output of all eight s-boxes is then combined in to 32 bit section." }, { "code": null, "e": 68281, "s": 68136, "text": "Straight Permutation βˆ’ The 32 bit output of S-boxes is then subjected to the straight permutation with rule shown in the following illustration:" }, { "code": null, "e": 68426, "s": 68281, "text": "Straight Permutation βˆ’ The 32 bit output of S-boxes is then subjected to the straight permutation with rule shown in the following illustration:" }, { "code": null, "e": 68580, "s": 68426, "text": "The round-key generator creates sixteen 48-bit keys out of a 56-bit cipher key. The process of key generation is depicted in the following illustration βˆ’" }, { "code": null, "e": 68672, "s": 68580, "text": "The logic for Parity drop, shifting, and Compression P-box is given in the DES description." }, { "code": null, "e": 68781, "s": 68672, "text": "The DES satisfies both the desired properties of block cipher. These two properties make cipher very strong." }, { "code": null, "e": 68880, "s": 68781, "text": "Avalanche effect βˆ’ A small change in plaintext results in the very great change in the ciphertext." }, { "code": null, "e": 68979, "s": 68880, "text": "Avalanche effect βˆ’ A small change in plaintext results in the very great change in the ciphertext." }, { "code": null, "e": 69052, "s": 68979, "text": "Completeness βˆ’ Each bit of ciphertext depends on many bits of plaintext." }, { "code": null, "e": 69125, "s": 69052, "text": "Completeness βˆ’ Each bit of ciphertext depends on many bits of plaintext." }, { "code": null, "e": 69262, "s": 69125, "text": "During the last few years, cryptanalysis have found some weaknesses in DES when key selected are weak keys. These keys shall be avoided." }, { "code": null, "e": 69412, "s": 69262, "text": "DES has proved to be a very well designed block cipher. There have been no significant cryptanalytic attacks on DES other than exhaustive key search." }, { "code": null, "e": 69714, "s": 69412, "text": "The speed of exhaustive key searches against DES after 1990 began to cause discomfort amongst users of DES. However, users did not want to replace DES as it takes an enormous amount of time and money to change encryption algorithms that are widely adopted and embedded in large security architectures." }, { "code": null, "e": 69897, "s": 69714, "text": "The pragmatic approach was not to abandon the DES completely, but to change the manner in which DES is used. This led to the modified schemes of Triple DES (sometimes known as 3DES)." }, { "code": null, "e": 70012, "s": 69897, "text": "Incidentally, there are two variants of Triple DES known as 3-key Triple DES (3TDES) and 2-key Triple DES (2TDES)." }, { "code": null, "e": 70255, "s": 70012, "text": "Before using 3TDES, user first generate and distribute a 3TDES key K, which consists of three different DES keys K1, K2 and K3. This means that the actual 3TDES key has length 3Γ—56 = 168 bits. The encryption scheme is illustrated as follows βˆ’" }, { "code": null, "e": 70305, "s": 70255, "text": "The encryption-decryption process is as follows βˆ’" }, { "code": null, "e": 70364, "s": 70305, "text": "Encrypt the plaintext blocks using single DES with key K1." }, { "code": null, "e": 70423, "s": 70364, "text": "Encrypt the plaintext blocks using single DES with key K1." }, { "code": null, "e": 70486, "s": 70423, "text": "Now decrypt the output of step 1 using single DES with key K2." }, { "code": null, "e": 70549, "s": 70486, "text": "Now decrypt the output of step 1 using single DES with key K2." }, { "code": null, "e": 70617, "s": 70549, "text": "Finally, encrypt the output of step 2 using single DES with key K3." }, { "code": null, "e": 70685, "s": 70617, "text": "Finally, encrypt the output of step 2 using single DES with key K3." }, { "code": null, "e": 70725, "s": 70685, "text": "The output of step 3 is the ciphertext." }, { "code": null, "e": 70765, "s": 70725, "text": "The output of step 3 is the ciphertext." }, { "code": null, "e": 70894, "s": 70765, "text": "Decryption of a ciphertext is a reverse process. User first decrypt using K3, then encrypt with K2, and finally decrypt with K1." }, { "code": null, "e": 71023, "s": 70894, "text": "Decryption of a ciphertext is a reverse process. User first decrypt using K3, then encrypt with K2, and finally decrypt with K1." }, { "code": null, "e": 71262, "s": 71023, "text": "Due to this design of Triple DES as an encrypt–decrypt–encrypt process, it is possible to use a 3TDES (hardware) implementation for single DES by setting K1, K2, and K3 to be the same value. This provides backwards compatibility with DES." }, { "code": null, "e": 71521, "s": 71262, "text": "Second variant of Triple DES (2TDES) is identical to 3TDES except that K3is replaced by K1. In other words, user encrypt plaintext blocks with key K1, then decrypt with key K2, and finally encrypt with K1 again. Therefore, 2TDES has a key length of 112 bits." }, { "code": null, "e": 71665, "s": 71521, "text": "Triple DES systems are significantly more secure than single DES, but these are clearly a much slower process than encryption using single DES." }, { "code": null, "e": 71863, "s": 71665, "text": "The more popular and widely adopted symmetric encryption algorithm likely to be encountered nowadays is the Advanced Encryption Standard (AES). It is found at least six time faster than triple DES." }, { "code": null, "e": 72100, "s": 71863, "text": "A replacement for DES was needed as its key size was too small. With increasing computing power, it was considered vulnerable against exhaustive key search attack. Triple DES was designed to overcome this drawback but it was found slow." }, { "code": null, "e": 72137, "s": 72100, "text": "The features of AES are as follows βˆ’" }, { "code": null, "e": 72174, "s": 72137, "text": "Symmetric key symmetric block cipher" }, { "code": null, "e": 72209, "s": 72174, "text": "128-bit data, 128/192/256-bit keys" }, { "code": null, "e": 72245, "s": 72209, "text": "Stronger and faster than Triple-DES" }, { "code": null, "e": 72291, "s": 72245, "text": "Provide full specification and design details" }, { "code": null, "e": 72328, "s": 72291, "text": "Software implementable in C and Java" }, { "code": null, "e": 72606, "s": 72328, "text": "AES is an iterative rather than Feistel cipher. It is based on β€˜substitution–permutation network’. It comprises of a series of linked operations, some of which involve replacing inputs by specific outputs (substitutions) and others involve shuffling bits around (permutations)." }, { "code": null, "e": 72834, "s": 72606, "text": "Interestingly, AES performs all its computations on bytes rather than bits. Hence, AES treats the 128 bits of a plaintext block as 16 bytes. These 16 bytes are arranged in four columns and four rows for processing as a matrix βˆ’" }, { "code": null, "e": 73124, "s": 72834, "text": "Unlike DES, the number of rounds in AES is variable and depends on the length of the key. AES uses 10 rounds for 128-bit keys, 12 rounds for 192-bit keys and 14 rounds for 256-bit keys. Each of these rounds uses a different 128-bit round key, which is calculated from the original AES key." }, { "code": null, "e": 73196, "s": 73124, "text": "The schematic of AES structure is given in the following illustration βˆ’" }, { "code": null, "e": 73354, "s": 73196, "text": "Here, we restrict to description of a typical round of AES encryption. Each round comprise of four sub-processes. The first round process is depicted below βˆ’" }, { "code": null, "e": 73499, "s": 73354, "text": "The 16 input bytes are substituted by looking up a fixed table (S-box) given in design. The result is in a matrix of four rows and four columns." }, { "code": null, "e": 73663, "s": 73499, "text": "Each of the four rows of the matrix is shifted to the left. Any entries that β€˜fall off’ are re-inserted on the right side of row. Shift is carried out as follows βˆ’" }, { "code": null, "e": 73689, "s": 73663, "text": "First row is not shifted." }, { "code": null, "e": 73715, "s": 73689, "text": "First row is not shifted." }, { "code": null, "e": 73770, "s": 73715, "text": "Second row is shifted one (byte) position to the left." }, { "code": null, "e": 73825, "s": 73770, "text": "Second row is shifted one (byte) position to the left." }, { "code": null, "e": 73873, "s": 73825, "text": "Third row is shifted two positions to the left." }, { "code": null, "e": 73921, "s": 73873, "text": "Third row is shifted two positions to the left." }, { "code": null, "e": 73972, "s": 73921, "text": "Fourth row is shifted three positions to the left." }, { "code": null, "e": 74023, "s": 73972, "text": "Fourth row is shifted three positions to the left." }, { "code": null, "e": 74122, "s": 74023, "text": "The result is a new matrix consisting of the same 16 bytes but shifted with respect to each other." }, { "code": null, "e": 74221, "s": 74122, "text": "The result is a new matrix consisting of the same 16 bytes but shifted with respect to each other." }, { "code": null, "e": 74568, "s": 74221, "text": "Each column of four bytes is now transformed using a special mathematical function. This function takes as input the four bytes of one column and outputs four completely new bytes, which replace the original column. The result is another new matrix consisting of 16 new bytes. It should be noted that this step is not performed in the last round." }, { "code": null, "e": 74833, "s": 74568, "text": "The 16 bytes of the matrix are now considered as 128 bits and are XORed to the 128 bits of the round key. If this is the last round then the output is the ciphertext. Otherwise, the resulting 128 bits are interpreted as 16 bytes and we begin another similar round." }, { "code": null, "e": 75014, "s": 74833, "text": "The process of decryption of an AES ciphertext is similar to the encryption process in the reverse order. Each round consists of the four processes conducted in the reverse order βˆ’" }, { "code": null, "e": 75028, "s": 75014, "text": "Add round key" }, { "code": null, "e": 75040, "s": 75028, "text": "Mix columns" }, { "code": null, "e": 75051, "s": 75040, "text": "Shift rows" }, { "code": null, "e": 75069, "s": 75051, "text": "Byte substitution" }, { "code": null, "e": 75272, "s": 75069, "text": "Since sub-processes in each round are in reverse manner, unlike for a Feistel Cipher, the encryption and decryption algorithms needs to be separately implemented, although they are very closely related." }, { "code": null, "e": 75616, "s": 75272, "text": "In present day cryptography, AES is widely adopted and supported in both hardware and software. Till date, no practical cryptanalytic attacks against AES has been discovered. Additionally, AES has built-in flexibility of key length, which allows a degree of β€˜future-proofing’ against progress in the ability to perform exhaustive key searches." }, { "code": null, "e": 75743, "s": 75616, "text": "However, just as for DES, the AES security is assured only if it is correctly implemented and good key management is employed." }, { "code": null, "e": 76022, "s": 75743, "text": "In this chapter, we will discuss the different modes of operation of a block cipher. These are procedural rules for a generic block cipher. Interestingly, the different modes result in different properties being achieved which add to the security of the underlying block cipher." }, { "code": null, "e": 76274, "s": 76022, "text": "A block cipher processes the data blocks of fixed size. Usually, the size of a message is larger than the block size. Hence, the long message is divided into a series of sequential message blocks, and the cipher operates on these blocks one at a time." }, { "code": null, "e": 76376, "s": 76274, "text": "This mode is a most straightforward way of processing a series of sequentially listed message blocks." }, { "code": null, "e": 76491, "s": 76376, "text": "The user takes the first block of plaintext and encrypts it with the key to produce the first block of ciphertext." }, { "code": null, "e": 76606, "s": 76491, "text": "The user takes the first block of plaintext and encrypts it with the key to produce the first block of ciphertext." }, { "code": null, "e": 76713, "s": 76606, "text": "He then takes the second block of plaintext and follows the same process with same key and so on so forth." }, { "code": null, "e": 76820, "s": 76713, "text": "He then takes the second block of plaintext and follows the same process with same key and so on so forth." }, { "code": null, "e": 76981, "s": 76820, "text": "The ECB mode is deterministic, that is, if plaintext block P1, P2,..., Pm are encrypted twice under the same key, the output ciphertext blocks will be the same." }, { "code": null, "e": 77392, "s": 76981, "text": "In fact, for a given key technically we can create a codebook of ciphertexts for all possible plaintext blocks. Encryption would then entail only looking up for required plaintext and select the corresponding ciphertext. Thus, the operation is analogous to the assignment of code words in a codebook, and hence gets an official name βˆ’ Electronic Codebook mode of operation (ECB). It is illustrated as follows βˆ’" }, { "code": null, "e": 77663, "s": 77392, "text": "In reality, any application data usually have partial information which can be guessed. For example, the range of salary can be guessed. A ciphertext from ECB can allow an attacker to guess the plaintext by trial-and-error if the plaintext message is within predictable." }, { "code": null, "e": 77945, "s": 77663, "text": "For example, if a ciphertext from the ECB mode is known to encrypt a salary figure, then a small number of trials will allow an attacker to recover the figure. In general, we do not wish to use a deterministic cipher, and hence the ECB mode should not be used in most applications." }, { "code": null, "e": 78061, "s": 77945, "text": "CBC mode of operation provides message dependence for generating ciphertext and makes the system non-deterministic." }, { "code": null, "e": 78157, "s": 78061, "text": "The operation of CBC mode is depicted in the following illustration. The steps are as follows βˆ’" }, { "code": null, "e": 78220, "s": 78157, "text": "Load the n-bit Initialization Vector (IV) in the top register." }, { "code": null, "e": 78283, "s": 78220, "text": "Load the n-bit Initialization Vector (IV) in the top register." }, { "code": null, "e": 78346, "s": 78283, "text": "XOR the n-bit plaintext block with data value in top register." }, { "code": null, "e": 78409, "s": 78346, "text": "XOR the n-bit plaintext block with data value in top register." }, { "code": null, "e": 78486, "s": 78409, "text": "Encrypt the result of XOR operation with underlying block cipher with key K." }, { "code": null, "e": 78563, "s": 78486, "text": "Encrypt the result of XOR operation with underlying block cipher with key K." }, { "code": null, "e": 78671, "s": 78563, "text": "Feed ciphertext block into top register and continue the operation till all plaintext blocks are processed." }, { "code": null, "e": 78779, "s": 78671, "text": "Feed ciphertext block into top register and continue the operation till all plaintext blocks are processed." }, { "code": null, "e": 78958, "s": 78779, "text": "For decryption, IV data is XORed with first ciphertext block decrypted. The first ciphertext block is also fed into to register replacing IV for decrypting next ciphertext block." }, { "code": null, "e": 79137, "s": 78958, "text": "For decryption, IV data is XORed with first ciphertext block decrypted. The first ciphertext block is also fed into to register replacing IV for decrypting next ciphertext block." }, { "code": null, "e": 79418, "s": 79137, "text": "In CBC mode, the current plaintext block is added to the previous ciphertext block, and then the result is encrypted with the key. Decryption is thus the reverse process, which involves decrypting the current ciphertext and then adding the previous ciphertext block to the result." }, { "code": null, "e": 79646, "s": 79418, "text": "Advantage of CBC over ECB is that changing IV results in different ciphertext for identical message. On the drawback side, the error in transmission gets propagated to few further block during decryption due to chaining effect." }, { "code": null, "e": 79874, "s": 79646, "text": "It is worth mentioning that CBC mode forms the basis for a well-known data origin authentication mechanism. Thus, it has an advantage for those applications that require both symmetric encryption and data origin authentication." }, { "code": null, "e": 80000, "s": 79874, "text": "In this mode, each ciphertext block gets β€˜fed back’ into the encryption process in order to encrypt the next plaintext block." }, { "code": null, "e": 80303, "s": 80000, "text": "The operation of CFB mode is depicted in the following illustration. For example, in the present system, a message block has a size β€˜s’ bits where 1 < s < n. The CFB mode requires an initialization vector (IV) as the initial random n-bit input block. The IV need not be secret. Steps of operation are βˆ’" }, { "code": null, "e": 80336, "s": 80303, "text": "Load the IV in the top register." }, { "code": null, "e": 80369, "s": 80336, "text": "Load the IV in the top register." }, { "code": null, "e": 80449, "s": 80369, "text": "Encrypt the data value in top register with underlying block cipher with key K." }, { "code": null, "e": 80529, "s": 80449, "text": "Encrypt the data value in top register with underlying block cipher with key K." }, { "code": null, "e": 80699, "s": 80529, "text": "Take only β€˜s’ number of most significant bits (left bits) of output of encryption process and XOR them with β€˜s’ bit plaintext message block to generate ciphertext block." }, { "code": null, "e": 80869, "s": 80699, "text": "Take only β€˜s’ number of most significant bits (left bits) of output of encryption process and XOR them with β€˜s’ bit plaintext message block to generate ciphertext block." }, { "code": null, "e": 81022, "s": 80869, "text": "Feed ciphertext block into top register by shifting already present data to the left and continue the operation till all plaintext blocks are processed." }, { "code": null, "e": 81175, "s": 81022, "text": "Feed ciphertext block into top register by shifting already present data to the left and continue the operation till all plaintext blocks are processed." }, { "code": null, "e": 81306, "s": 81175, "text": "Essentially, the previous ciphertext block is encrypted with the key, and then the result is XORed to the current plaintext block." }, { "code": null, "e": 81437, "s": 81306, "text": "Essentially, the previous ciphertext block is encrypted with the key, and then the result is XORed to the current plaintext block." }, { "code": null, "e": 81543, "s": 81437, "text": "Similar steps are followed for decryption. Pre-decided IV is initially loaded at the start of decryption." }, { "code": null, "e": 81649, "s": 81543, "text": "Similar steps are followed for decryption. Pre-decided IV is initially loaded at the start of decryption." }, { "code": null, "e": 81910, "s": 81649, "text": "CFB mode differs significantly from ECB mode, the ciphertext corresponding to a given plaintext block depends not just on that plaintext block and the key, but also on the previous ciphertext block. In other words, the ciphertext block is dependent of message." }, { "code": null, "e": 82111, "s": 81910, "text": "CFB has a very strange feature. In this mode, user decrypts the ciphertext using only the encryption process of the block cipher. The decryption algorithm of the underlying block cipher is never used." }, { "code": null, "e": 82389, "s": 82111, "text": "Apparently, CFB mode is converting a block cipher into a type of stream cipher. The encryption algorithm is used as a key-stream generator to produce key-stream that is placed in the bottom register. This key stream is then XORed with the plaintext as in case of stream cipher." }, { "code": null, "e": 82576, "s": 82389, "text": "By converting a block cipher into a stream cipher, CFB mode provides some of the advantageous properties of a stream cipher while retaining the advantageous properties of a block cipher." }, { "code": null, "e": 82663, "s": 82576, "text": "On the flip side, the error of transmission gets propagated due to changing of blocks." }, { "code": null, "e": 82897, "s": 82663, "text": "It involves feeding the successive output blocks from the underlying block cipher back to it. These feedback blocks provide string of bits to feed the encryption algorithm which act as the key-stream generator as in case of CFB mode." }, { "code": null, "e": 83055, "s": 82897, "text": "The key stream generated is XOR-ed with the plaintext blocks. The OFB mode requires an IV as the initial random n-bit input block. The IV need not be secret." }, { "code": null, "e": 83113, "s": 83055, "text": "The operation is depicted in the following illustration βˆ’" }, { "code": null, "e": 83477, "s": 83113, "text": "It can be considered as a counter-based version of CFB mode without the feedback. In this mode, both the sender and receiver need to access to a reliable counter, which computes a new shared value each time a ciphertext block is exchanged. This shared counter is not necessarily a secret value, but challenge is that both sides must keep the counter synchronized." }, { "code": null, "e": 83589, "s": 83477, "text": "Both encryption and decryption in CTR mode are depicted in the following illustration. Steps in operation are βˆ’" }, { "code": null, "e": 83746, "s": 83589, "text": "Load the initial counter value in the top register is the same for both the sender and the receiver. It plays the same role as the IV in CFB (and CBC) mode." }, { "code": null, "e": 83903, "s": 83746, "text": "Load the initial counter value in the top register is the same for both the sender and the receiver. It plays the same role as the IV in CFB (and CBC) mode." }, { "code": null, "e": 83997, "s": 83903, "text": "Encrypt the contents of the counter with the key and place the result in the bottom register." }, { "code": null, "e": 84091, "s": 83997, "text": "Encrypt the contents of the counter with the key and place the result in the bottom register." }, { "code": null, "e": 84317, "s": 84091, "text": "Take the first plaintext block P1 and XOR this to the contents of the bottom register. The result of this is C1. Send C1 to the receiver and update the counter. The counter update replaces the ciphertext feedback in CFB mode." }, { "code": null, "e": 84543, "s": 84317, "text": "Take the first plaintext block P1 and XOR this to the contents of the bottom register. The result of this is C1. Send C1 to the receiver and update the counter. The counter update replaces the ciphertext feedback in CFB mode." }, { "code": null, "e": 84618, "s": 84543, "text": "Continue in this manner until the last plaintext block has been encrypted." }, { "code": null, "e": 84693, "s": 84618, "text": "Continue in this manner until the last plaintext block has been encrypted." }, { "code": null, "e": 84905, "s": 84693, "text": "The decryption is the reverse process. The ciphertext block is XORed with the output of encrypted contents of counter value. After decryption of each ciphertext block counter is updated as in case of encryption." }, { "code": null, "e": 85117, "s": 84905, "text": "The decryption is the reverse process. The ciphertext block is XORed with the output of encrypted contents of counter value. After decryption of each ciphertext block counter is updated as in case of encryption." }, { "code": null, "e": 85232, "s": 85117, "text": "It does not have message dependency and hence a ciphertext block does not depend on the previous plaintext blocks." }, { "code": null, "e": 85522, "s": 85232, "text": "Like CFB mode, CTR mode does not involve the decryption process of the block cipher. This is because the CTR mode is really using the block cipher to generate a key-stream, which is encrypted using the XOR function. In other words, CTR mode also converts a block cipher to a stream cipher." }, { "code": null, "e": 85691, "s": 85522, "text": "The serious disadvantage of CTR mode is that it requires a synchronous counter at sender and receiver. Loss of synchronization leads to incorrect recovery of plaintext." }, { "code": null, "e": 85813, "s": 85691, "text": "However, CTR mode has almost all advantages of CFB mode. In addition, it does not propagate error of transmission at all." }, { "code": null, "e": 85938, "s": 85813, "text": "Unlike symmetric key cryptography, we do not find historical use of public-key cryptography. It is a relatively new concept." }, { "code": null, "e": 86104, "s": 85938, "text": "Symmetric cryptography was well suited for organizations such as governments, military, and big financial corporations were involved in the classified communication." }, { "code": null, "e": 86380, "s": 86104, "text": "With the spread of more unsecure computer networks in last few decades, a genuine need was felt to use cryptography at larger scale. The symmetric key was found to be non-practical due to challenges it faced for key management. This gave rise to the public key cryptosystems." }, { "code": null, "e": 86465, "s": 86380, "text": "The process of encryption and decryption is depicted in the following illustration βˆ’" }, { "code": null, "e": 86533, "s": 86465, "text": "The most important properties of public key encryption scheme are βˆ’" }, { "code": null, "e": 86673, "s": 86533, "text": "Different keys are used for encryption and decryption. This is a property which set this scheme different than symmetric encryption scheme." }, { "code": null, "e": 86813, "s": 86673, "text": "Different keys are used for encryption and decryption. This is a property which set this scheme different than symmetric encryption scheme." }, { "code": null, "e": 86904, "s": 86813, "text": "Each receiver possesses a unique decryption key, generally referred to as his private key." }, { "code": null, "e": 86995, "s": 86904, "text": "Each receiver possesses a unique decryption key, generally referred to as his private key." }, { "code": null, "e": 87071, "s": 86995, "text": "Receiver needs to publish an encryption key, referred to as his public key." }, { "code": null, "e": 87147, "s": 87071, "text": "Receiver needs to publish an encryption key, referred to as his public key." }, { "code": null, "e": 87427, "s": 87147, "text": "Some assurance of the authenticity of a public key is needed in this scheme to avoid spoofing by adversary as the receiver. Generally, this type of cryptosystem involves trusted third party which certifies that a particular public key belongs to a specific person or entity only." }, { "code": null, "e": 87707, "s": 87427, "text": "Some assurance of the authenticity of a public key is needed in this scheme to avoid spoofing by adversary as the receiver. Generally, this type of cryptosystem involves trusted third party which certifies that a particular public key belongs to a specific person or entity only." }, { "code": null, "e": 87848, "s": 87707, "text": "Encryption algorithm is complex enough to prohibit attacker from deducing the plaintext from the ciphertext and the encryption (public) key." }, { "code": null, "e": 87989, "s": 87848, "text": "Encryption algorithm is complex enough to prohibit attacker from deducing the plaintext from the ciphertext and the encryption (public) key." }, { "code": null, "e": 88226, "s": 87989, "text": "Though private and public keys are related mathematically, it is not be feasible to calculate the private key from the public key. In fact, intelligent part of any public-key cryptosystem is in designing a relationship between two keys." }, { "code": null, "e": 88463, "s": 88226, "text": "Though private and public keys are related mathematically, it is not be feasible to calculate the private key from the public key. In fact, intelligent part of any public-key cryptosystem is in designing a relationship between two keys." }, { "code": null, "e": 88559, "s": 88463, "text": "There are three types of Public Key Encryption schemes. We discuss them in following sections βˆ’" }, { "code": null, "e": 88781, "s": 88559, "text": "This cryptosystem is one the initial system. It remains most employed cryptosystem even today. The system was invented by three scholars Ron Rivest, Adi Shamir, and Len Adleman and hence, it is termed as RSA cryptosystem." }, { "code": null, "e": 88908, "s": 88781, "text": "We will see two aspects of the RSA cryptosystem, firstly generation of key pair and secondly encryption-decryption algorithms." }, { "code": null, "e": 89129, "s": 88908, "text": "Each person or a party who desires to participate in communication using encryption needs to generate a pair of keys, namely public key and private key. The process followed in the generation of keys is described below βˆ’" }, { "code": null, "e": 89305, "s": 89129, "text": "Generate the RSA modulus (n)\n\nSelect two large primes, p and q.\nCalculate n=p*q. For strong unbreakable encryption, let n be a large number, typically a minimum of 512 bits.\n\n" }, { "code": null, "e": 89334, "s": 89305, "text": "Generate the RSA modulus (n)" }, { "code": null, "e": 89368, "s": 89334, "text": "Select two large primes, p and q." }, { "code": null, "e": 89402, "s": 89368, "text": "Select two large primes, p and q." }, { "code": null, "e": 89512, "s": 89402, "text": "Calculate n=p*q. For strong unbreakable encryption, let n be a large number, typically a minimum of 512 bits." }, { "code": null, "e": 89622, "s": 89512, "text": "Calculate n=p*q. For strong unbreakable encryption, let n be a large number, typically a minimum of 512 bits." }, { "code": null, "e": 89842, "s": 89622, "text": "Find Derived Number (e)\n\nNumber e must be greater than 1 and less than (p βˆ’ 1)(q βˆ’ 1).\nThere must be no common factor for e and (p βˆ’ 1)(q βˆ’ 1) except for 1. In other words two numbers e and (p – 1)(q – 1) are coprime.\n\n" }, { "code": null, "e": 89866, "s": 89842, "text": "Find Derived Number (e)" }, { "code": null, "e": 89928, "s": 89866, "text": "Number e must be greater than 1 and less than (p βˆ’ 1)(q βˆ’ 1)." }, { "code": null, "e": 89990, "s": 89928, "text": "Number e must be greater than 1 and less than (p βˆ’ 1)(q βˆ’ 1)." }, { "code": null, "e": 90121, "s": 89990, "text": "There must be no common factor for e and (p βˆ’ 1)(q βˆ’ 1) except for 1. In other words two numbers e and (p – 1)(q – 1) are coprime." }, { "code": null, "e": 90252, "s": 90121, "text": "There must be no common factor for e and (p βˆ’ 1)(q βˆ’ 1) except for 1. In other words two numbers e and (p – 1)(q – 1) are coprime." }, { "code": null, "e": 90559, "s": 90252, "text": "Form the public key\n\nThe pair of numbers (n, e) form the RSA public key and is made public.\nInterestingly, though n is part of the public key, difficulty in factorizing a large prime number ensures that attacker cannot find in finite time the two primes (p & q) used to obtain n. This is strength of RSA.\n\n" }, { "code": null, "e": 90579, "s": 90559, "text": "Form the public key" }, { "code": null, "e": 90650, "s": 90579, "text": "The pair of numbers (n, e) form the RSA public key and is made public." }, { "code": null, "e": 90721, "s": 90650, "text": "The pair of numbers (n, e) form the RSA public key and is made public." }, { "code": null, "e": 90934, "s": 90721, "text": "Interestingly, though n is part of the public key, difficulty in factorizing a large prime number ensures that attacker cannot find in finite time the two primes (p & q) used to obtain n. This is strength of RSA." }, { "code": null, "e": 91147, "s": 90934, "text": "Interestingly, though n is part of the public key, difficulty in factorizing a large prime number ensures that attacker cannot find in finite time the two primes (p & q) used to obtain n. This is strength of RSA." }, { "code": null, "e": 91504, "s": 91147, "text": "Generate the private key\n\nPrivate Key d is calculated from p, q, and e. For given n and e, there is unique number d.\nNumber d is the inverse of e modulo (p - 1)(q – 1). This means that d is the number less than (p - 1)(q - 1) such that when multiplied by e, it is equal to 1 modulo (p - 1)(q - 1).\nThis relationship is written mathematically as follows βˆ’\n\n" }, { "code": null, "e": 91529, "s": 91504, "text": "Generate the private key" }, { "code": null, "e": 91620, "s": 91529, "text": "Private Key d is calculated from p, q, and e. For given n and e, there is unique number d." }, { "code": null, "e": 91711, "s": 91620, "text": "Private Key d is calculated from p, q, and e. For given n and e, there is unique number d." }, { "code": null, "e": 91892, "s": 91711, "text": "Number d is the inverse of e modulo (p - 1)(q – 1). This means that d is the number less than (p - 1)(q - 1) such that when multiplied by e, it is equal to 1 modulo (p - 1)(q - 1)." }, { "code": null, "e": 92073, "s": 91892, "text": "Number d is the inverse of e modulo (p - 1)(q – 1). This means that d is the number less than (p - 1)(q - 1) such that when multiplied by e, it is equal to 1 modulo (p - 1)(q - 1)." }, { "code": null, "e": 92130, "s": 92073, "text": "This relationship is written mathematically as follows βˆ’" }, { "code": null, "e": 92187, "s": 92130, "text": "This relationship is written mathematically as follows βˆ’" }, { "code": null, "e": 92214, "s": 92187, "text": "ed = 1 mod (p βˆ’ 1)(q βˆ’ 1)\n" }, { "code": null, "e": 92297, "s": 92214, "text": "The Extended Euclidean Algorithm takes p, q, and e as input and gives d as output." }, { "code": null, "e": 92467, "s": 92297, "text": "An example of generating RSA Key pair is given below. (For ease of understanding, the primes p & q taken here are small values. Practically, these values are very high)." }, { "code": null, "e": 92539, "s": 92467, "text": "Let two primes be p = 7 and q = 13. Thus, modulus n = pq = 7 x 13 = 91." }, { "code": null, "e": 92611, "s": 92539, "text": "Let two primes be p = 7 and q = 13. Thus, modulus n = pq = 7 x 13 = 91." }, { "code": null, "e": 92749, "s": 92611, "text": "Select e = 5, which is a valid choice since there is no number that is common factor of 5 and (p βˆ’ 1)(q βˆ’ 1) = 6 Γ— 12 = 72, except for 1." }, { "code": null, "e": 92887, "s": 92749, "text": "Select e = 5, which is a valid choice since there is no number that is common factor of 5 and (p βˆ’ 1)(q βˆ’ 1) = 6 Γ— 12 = 72, except for 1." }, { "code": null, "e": 93036, "s": 92887, "text": "The pair of numbers (n, e) = (91, 5) forms the public key and can be made available to anyone whom we wish to be able to send us encrypted messages." }, { "code": null, "e": 93185, "s": 93036, "text": "The pair of numbers (n, e) = (91, 5) forms the public key and can be made available to anyone whom we wish to be able to send us encrypted messages." }, { "code": null, "e": 93280, "s": 93185, "text": "Input p = 7, q = 13, and e = 5 to the Extended Euclidean Algorithm. The output will be d = 29." }, { "code": null, "e": 93375, "s": 93280, "text": "Input p = 7, q = 13, and e = 5 to the Extended Euclidean Algorithm. The output will be d = 29." }, { "code": null, "e": 93429, "s": 93375, "text": "Check that the d calculated is correct by computing βˆ’" }, { "code": null, "e": 93483, "s": 93429, "text": "Check that the d calculated is correct by computing βˆ’" }, { "code": null, "e": 93513, "s": 93483, "text": "de = 29 Γ— 5 = 145 = 1 mod 72\n" }, { "code": null, "e": 93572, "s": 93513, "text": "Hence, public key is (91, 5) and private keys is (91, 29)." }, { "code": null, "e": 93631, "s": 93572, "text": "Hence, public key is (91, 5) and private keys is (91, 29)." }, { "code": null, "e": 93767, "s": 93631, "text": "Once the key pair has been generated, the process of encryption and decryption are relatively straightforward and computationally easy." }, { "code": null, "e": 93990, "s": 93767, "text": "Interestingly, RSA does not directly operate on strings of bits as in case of symmetric key encryption. It operates on numbers modulo n. Hence, it is necessary to represent the plaintext as a series of numbers less than n." }, { "code": null, "e": 94079, "s": 93990, "text": "Suppose the sender wish to send some text message to someone whose public key is (n, e)." }, { "code": null, "e": 94168, "s": 94079, "text": "Suppose the sender wish to send some text message to someone whose public key is (n, e)." }, { "code": null, "e": 94245, "s": 94168, "text": "The sender then represents the plaintext as a series of numbers less than n." }, { "code": null, "e": 94322, "s": 94245, "text": "The sender then represents the plaintext as a series of numbers less than n." }, { "code": null, "e": 94440, "s": 94322, "text": "To encrypt the first plaintext P, which is a number modulo n. The encryption process is simple mathematical step as βˆ’" }, { "code": null, "e": 94558, "s": 94440, "text": "To encrypt the first plaintext P, which is a number modulo n. The encryption process is simple mathematical step as βˆ’" }, { "code": null, "e": 94572, "s": 94558, "text": "C = Pe mod n\n" }, { "code": null, "e": 94737, "s": 94572, "text": "In other words, the ciphertext C is equal to the plaintext P multiplied by itself e times and then reduced modulo n. This means that C is also a number less than n." }, { "code": null, "e": 94902, "s": 94737, "text": "In other words, the ciphertext C is equal to the plaintext P multiplied by itself e times and then reduced modulo n. This means that C is also a number less than n." }, { "code": null, "e": 94987, "s": 94902, "text": "Returning to our Key Generation example with plaintext P = 10, we get ciphertext C βˆ’" }, { "code": null, "e": 95072, "s": 94987, "text": "Returning to our Key Generation example with plaintext P = 10, we get ciphertext C βˆ’" }, { "code": null, "e": 95088, "s": 95072, "text": "C = 105 mod 91\n" }, { "code": null, "e": 95230, "s": 95088, "text": "The decryption process for RSA is also very straightforward. Suppose that the receiver of public-key pair (n, e) has received a ciphertext C." }, { "code": null, "e": 95372, "s": 95230, "text": "The decryption process for RSA is also very straightforward. Suppose that the receiver of public-key pair (n, e) has received a ciphertext C." }, { "code": null, "e": 95470, "s": 95372, "text": "Receiver raises C to the power of his private key d. The result modulo n will be the plaintext P." }, { "code": null, "e": 95568, "s": 95470, "text": "Receiver raises C to the power of his private key d. The result modulo n will be the plaintext P." }, { "code": null, "e": 95590, "s": 95568, "text": "Plaintext = Cd mod n\n" }, { "code": null, "e": 95710, "s": 95590, "text": "Returning again to our numerical example, the ciphertext C = 82 would get decrypted to number 10 using private key 29 βˆ’" }, { "code": null, "e": 95830, "s": 95710, "text": "Returning again to our numerical example, the ciphertext C = 82 would get decrypted to number 10 using private key 29 βˆ’" }, { "code": null, "e": 95860, "s": 95830, "text": "Plaintext = 8229 mod 91 = 10\n" }, { "code": null, "e": 96085, "s": 95860, "text": "The security of RSA depends on the strengths of two separate functions. The RSA cryptosystem is most popular public-key cryptosystem strength of which is based on the practical difficulty of factoring the very large numbers." }, { "code": null, "e": 96251, "s": 96085, "text": "Encryption Function βˆ’ It is considered as a one-way function of converting plaintext into ciphertext and it can be reversed only with the knowledge of private key d." }, { "code": null, "e": 96417, "s": 96251, "text": "Encryption Function βˆ’ It is considered as a one-way function of converting plaintext into ciphertext and it can be reversed only with the knowledge of private key d." }, { "code": null, "e": 96763, "s": 96417, "text": "Key Generation βˆ’ The difficulty of determining a private key from an RSA public key is equivalent to factoring the modulus n. An attacker thus cannot use knowledge of an RSA public key to determine an RSA private key unless he can factor n. It is also a one way function, going from p & q values to modulus n is easy but reverse is not possible." }, { "code": null, "e": 97109, "s": 96763, "text": "Key Generation βˆ’ The difficulty of determining a private key from an RSA public key is equivalent to factoring the modulus n. An attacker thus cannot use knowledge of an RSA public key to determine an RSA private key unless he can factor n. It is also a one way function, going from p & q values to modulus n is easy but reverse is not possible." }, { "code": null, "e": 97287, "s": 97109, "text": "If either of these two functions are proved non one-way, then RSA will be broken. In fact, if a technique for factoring efficiently is developed then RSA will no longer be safe." }, { "code": null, "e": 97446, "s": 97287, "text": "The strength of RSA encryption drastically goes down against attacks if the number p and q are not large primes and/ or chosen public key e is a small number." }, { "code": null, "e": 97593, "s": 97446, "text": "Along with RSA, there are other public-key cryptosystems proposed. Many of them are based on different versions of the Discrete Logarithm Problem." }, { "code": null, "e": 97893, "s": 97593, "text": "ElGamal cryptosystem, called Elliptic Curve Variant, is based on the Discrete Logarithm Problem. It derives the strength from the assumption that the discrete logarithms cannot be found in practical time frame for a given number, while the inverse operation of the power can be computed efficiently." }, { "code": null, "e": 98060, "s": 97893, "text": "Let us go through a simple version of ElGamal that works with numbers modulo p. In the case of elliptic curve variants, it is based on quite different number systems." }, { "code": null, "e": 98138, "s": 98060, "text": "Each user of ElGamal cryptosystem generates the key pair through as follows βˆ’" }, { "code": null, "e": 98228, "s": 98138, "text": "Choosing a large prime p. Generally a prime number of 1024 to 2048 bits length is chosen." }, { "code": null, "e": 98318, "s": 98228, "text": "Choosing a large prime p. Generally a prime number of 1024 to 2048 bits length is chosen." }, { "code": null, "e": 98639, "s": 98318, "text": "Choosing a generator element g.\n\nThis number must be between 1 and p βˆ’ 1, but cannot be any number.\nIt is a generator of the multiplicative group of integers modulo p. This means for every integer m co-prime to p, there is an integer k such that gk=a mod n.\nFor example, 3 is generator of group 5 (Z5 = {1, 2, 3, 4}).\n\n\n" }, { "code": null, "e": 98671, "s": 98639, "text": "Choosing a generator element g." }, { "code": null, "e": 98738, "s": 98671, "text": "This number must be between 1 and p βˆ’ 1, but cannot be any number." }, { "code": null, "e": 98805, "s": 98738, "text": "This number must be between 1 and p βˆ’ 1, but cannot be any number." }, { "code": null, "e": 99024, "s": 98805, "text": "It is a generator of the multiplicative group of integers modulo p. This means for every integer m co-prime to p, there is an integer k such that gk=a mod n.\nFor example, 3 is generator of group 5 (Z5 = {1, 2, 3, 4}).\n" }, { "code": null, "e": 99182, "s": 99024, "text": "It is a generator of the multiplicative group of integers modulo p. This means for every integer m co-prime to p, there is an integer k such that gk=a mod n." }, { "code": null, "e": 99242, "s": 99182, "text": "For example, 3 is generator of group 5 (Z5 = {1, 2, 3, 4})." }, { "code": null, "e": 99336, "s": 99242, "text": "Choosing the private key. The private key x is any number bigger than 1 and smaller than pβˆ’1." }, { "code": null, "e": 99430, "s": 99336, "text": "Choosing the private key. The private key x is any number bigger than 1 and smaller than pβˆ’1." }, { "code": null, "e": 99548, "s": 99430, "text": "Computing part of the public key. The value y is computed from the parameters p, g and the private key x as follows βˆ’" }, { "code": null, "e": 99666, "s": 99548, "text": "Computing part of the public key. The value y is computed from the parameters p, g and the private key x as follows βˆ’" }, { "code": null, "e": 99680, "s": 99666, "text": "y = gx mod p\n" }, { "code": null, "e": 100008, "s": 99680, "text": "Obtaining Public key. The ElGamal public key consists of the three parameters (p, g, y).\nFor example, suppose that p = 17 and that g = 6 (It can be confirmed that 6 is a generator of group Z17). The private key x can be any number bigger than 1 and smaller than 71, so we choose x = 5. The value y is then computed as follows βˆ’" }, { "code": null, "e": 100097, "s": 100008, "text": "Obtaining Public key. The ElGamal public key consists of the three parameters (p, g, y)." }, { "code": null, "e": 100336, "s": 100097, "text": "For example, suppose that p = 17 and that g = 6 (It can be confirmed that 6 is a generator of group Z17). The private key x can be any number bigger than 1 and smaller than 71, so we choose x = 5. The value y is then computed as follows βˆ’" }, { "code": null, "e": 100355, "s": 100336, "text": "y = 65 mod 17 = 7\n" }, { "code": null, "e": 100416, "s": 100355, "text": "Thus the private key is 62 and the public key is (17, 6, 7)." }, { "code": null, "e": 100477, "s": 100416, "text": "Thus the private key is 62 and the public key is (17, 6, 7)." }, { "code": null, "e": 100647, "s": 100477, "text": "The generation of an ElGamal key pair is comparatively simpler than the equivalent process for RSA. But the encryption and decryption are slightly more complex than RSA." }, { "code": null, "e": 100746, "s": 100647, "text": "Suppose sender wishes to send a plaintext to someone whose ElGamal public key is (p, g, y), then βˆ’" }, { "code": null, "e": 100811, "s": 100746, "text": "Sender represents the plaintext as a series of numbers modulo p." }, { "code": null, "e": 100876, "s": 100811, "text": "Sender represents the plaintext as a series of numbers modulo p." }, { "code": null, "e": 101090, "s": 100876, "text": "To encrypt the first plaintext P, which is represented as a number modulo p. The encryption process to obtain the ciphertext C is as follows βˆ’\n\nRandomly generate a number k;\nCompute two values C1 and C2, where βˆ’\n\n" }, { "code": null, "e": 101233, "s": 101090, "text": "To encrypt the first plaintext P, which is represented as a number modulo p. The encryption process to obtain the ciphertext C is as follows βˆ’" }, { "code": null, "e": 101263, "s": 101233, "text": "Randomly generate a number k;" }, { "code": null, "e": 101301, "s": 101263, "text": "Compute two values C1 and C2, where βˆ’" }, { "code": null, "e": 101334, "s": 101301, "text": "C1 = gk mod p\nC2 = (P*yk) mod p\n" }, { "code": null, "e": 101420, "s": 101334, "text": "Send the ciphertext C, consisting of the two separate values (C1, C2), sent together." }, { "code": null, "e": 101506, "s": 101420, "text": "Send the ciphertext C, consisting of the two separate values (C1, C2), sent together." }, { "code": null, "e": 101698, "s": 101506, "text": "Referring to our ElGamal key generation example given above, the plaintext P = 13 is encrypted as follows βˆ’\n\nRandomly generate a number, say k = 10\nCompute the two values C1 and C2, where βˆ’\n\n" }, { "code": null, "e": 101806, "s": 101698, "text": "Referring to our ElGamal key generation example given above, the plaintext P = 13 is encrypted as follows βˆ’" }, { "code": null, "e": 101845, "s": 101806, "text": "Randomly generate a number, say k = 10" }, { "code": null, "e": 101887, "s": 101845, "text": "Compute the two values C1 and C2, where βˆ’" }, { "code": null, "e": 101929, "s": 101887, "text": "C1 = 610 mod 17\nC2 = (13*710) mod 17 = 9\n" }, { "code": null, "e": 101973, "s": 101929, "text": "Send the ciphertext C = (C1, C2) = (15, 9)." }, { "code": null, "e": 102017, "s": 101973, "text": "Send the ciphertext C = (C1, C2) = (15, 9)." }, { "code": null, "e": 102275, "s": 102017, "text": "To decrypt the ciphertext (C1, C2) using private key x, the following two steps are taken βˆ’\n\nCompute the modular inverse of (C1)x modulo p, which is (C1)-x , generally referred to as decryption factor.\nObtain the plaintext by using the following formula βˆ’\n\n" }, { "code": null, "e": 102367, "s": 102275, "text": "To decrypt the ciphertext (C1, C2) using private key x, the following two steps are taken βˆ’" }, { "code": null, "e": 102476, "s": 102367, "text": "Compute the modular inverse of (C1)x modulo p, which is (C1)-x , generally referred to as decryption factor." }, { "code": null, "e": 102585, "s": 102476, "text": "Compute the modular inverse of (C1)x modulo p, which is (C1)-x , generally referred to as decryption factor." }, { "code": null, "e": 102639, "s": 102585, "text": "Obtain the plaintext by using the following formula βˆ’" }, { "code": null, "e": 102693, "s": 102639, "text": "Obtain the plaintext by using the following formula βˆ’" }, { "code": null, "e": 102725, "s": 102693, "text": "C2 Γ— (C1)-x mod p = Plaintext\n" }, { "code": null, "e": 102840, "s": 102725, "text": "In our example, to decrypt the ciphertext C = (C1, C2) = (15, 9) using private key x = 5, the decryption factor is" }, { "code": null, "e": 102955, "s": 102840, "text": "In our example, to decrypt the ciphertext C = (C1, C2) = (15, 9) using private key x = 5, the decryption factor is" }, { "code": null, "e": 102973, "s": 102955, "text": "15-5 mod 17 = 9\n" }, { "code": null, "e": 103016, "s": 102973, "text": "Extract plaintext P = (9 Γ— 9) mod 17 = 13." }, { "code": null, "e": 103059, "s": 103016, "text": "Extract plaintext P = (9 Γ— 9) mod 17 = 13." }, { "code": null, "e": 103291, "s": 103059, "text": "In ElGamal system, each user has a private key x. and has three components of public key βˆ’ prime modulus p, generator g, and public Y = gx mod p. The strength of the ElGamal is based on the difficulty of discrete logarithm problem." }, { "code": null, "e": 103590, "s": 103291, "text": "The secure key size is generally > 1024 bits. Today even 2048 bits long key are used. On the processing speed front, Elgamal is quite slow, it is used mainly for key authentication protocols. Due to higher processing efficiency, Elliptic Curve variants of ElGamal are becoming increasingly popular." }, { "code": null, "e": 103809, "s": 103590, "text": "Elliptic Curve Cryptography (ECC) is a term used to describe a suite of cryptographic tools and protocols whose security is based on special versions of the discrete logarithm problem. It does not use numbers modulo p." }, { "code": null, "e": 104020, "s": 103809, "text": "ECC is based on sets of numbers that are associated with mathematical objects called elliptic curves. There are rules for adding and computing multiples of these numbers, just as there are for numbers modulo p." }, { "code": null, "e": 104183, "s": 104020, "text": "ECC includes a variants of many cryptographic schemes that were initially designed for modular numbers such as ElGamal encryption and Digital Signature Algorithm." }, { "code": null, "e": 104480, "s": 104183, "text": "It is believed that the discrete logarithm problem is much harder when applied to points on an elliptic curve. This prompts switching from numbers modulo p to points on an elliptic curve. Also an equivalent security level can be obtained with shorter keys if we use elliptic curve-based variants." }, { "code": null, "e": 104522, "s": 104480, "text": "The shorter keys result in two benefits βˆ’" }, { "code": null, "e": 104545, "s": 104522, "text": "Ease of key management" }, { "code": null, "e": 104567, "s": 104545, "text": "Efficient computation" }, { "code": null, "e": 104715, "s": 104567, "text": "These benefits make elliptic-curve-based variants of encryption scheme highly attractive for application where computing resources are constrained." }, { "code": null, "e": 104790, "s": 104715, "text": "Let us briefly compare the RSA and ElGamal schemes on the various aspects." }, { "code": null, "e": 105031, "s": 104790, "text": "Until now, we discussed the use of symmetric and public key schemes to achieve the confidentiality of information. With this chapter, we begin our discussion on different cryptographic techniques designed to provide other security services." }, { "code": null, "e": 105128, "s": 105031, "text": "The focus of this chapter is on data integrity and cryptographic tools used to achieve the same." }, { "code": null, "e": 105396, "s": 105128, "text": "When sensitive information is exchanged, the receiver must have the assurance that the message has come intact from the intended sender and is not modified inadvertently or otherwise. There are two different types of data integrity threats, namely passive and active." }, { "code": null, "e": 105459, "s": 105396, "text": "This type of threats exists due to accidental changes in data." }, { "code": null, "e": 105607, "s": 105459, "text": "These data errors are likely to occur due to noise in a communication channel. Also, the data may get corrupted while the file is stored on a disk." }, { "code": null, "e": 105755, "s": 105607, "text": "These data errors are likely to occur due to noise in a communication channel. Also, the data may get corrupted while the file is stored on a disk." }, { "code": null, "e": 105974, "s": 105755, "text": "Error-correcting codes and simple checksums like Cyclic Redundancy Checks (CRCs) are used to detect the loss of data integrity. In these techniques, a digest of data is computed mathematically and appended to the data." }, { "code": null, "e": 106193, "s": 105974, "text": "Error-correcting codes and simple checksums like Cyclic Redundancy Checks (CRCs) are used to detect the loss of data integrity. In these techniques, a digest of data is computed mathematically and appended to the data." }, { "code": null, "e": 106277, "s": 106193, "text": "In this type of threats, an attacker can manipulate the data with malicious intent." }, { "code": null, "e": 106455, "s": 106277, "text": "At simplest level, if data is without digest, it can be modified without detection. The system can use techniques of appending CRC to data for detecting any active modification." }, { "code": null, "e": 106633, "s": 106455, "text": "At simplest level, if data is without digest, it can be modified without detection. The system can use techniques of appending CRC to data for detecting any active modification." }, { "code": null, "e": 106833, "s": 106633, "text": "At higher level of threat, attacker may modify data and try to derive new digest for modified data from exiting digest. This is possible if the digest is computed using simple mechanisms such as CRC." }, { "code": null, "e": 107033, "s": 106833, "text": "At higher level of threat, attacker may modify data and try to derive new digest for modified data from exiting digest. This is possible if the digest is computed using simple mechanisms such as CRC." }, { "code": null, "e": 107127, "s": 107033, "text": "Security mechanism such as Hash functions are used to tackle the active modification threats." }, { "code": null, "e": 107221, "s": 107127, "text": "Security mechanism such as Hash functions are used to tackle the active modification threats." }, { "code": null, "e": 107317, "s": 107221, "text": "Hash functions are extremely useful and appear in almost all information security applications." }, { "code": null, "e": 107531, "s": 107317, "text": "A hash function is a mathematical function that converts a numerical input value into another compressed numerical value. The input to the hash function is of arbitrary length but output is always of fixed length." }, { "code": null, "e": 107665, "s": 107531, "text": "Values returned by a hash function are called message digest or simply hash values. The following picture illustrated hash function βˆ’" }, { "code": null, "e": 107710, "s": 107665, "text": "The typical features of hash functions are βˆ’" }, { "code": null, "e": 108224, "s": 107710, "text": "Fixed Length Output (Hash Value)\n\nHash function coverts data of arbitrary length to a fixed length. This process is often referred to as hashing the data.\nIn general, the hash is much smaller than the input data, hence hash functions are sometimes called compression functions.\nSince a hash is a smaller representation of a larger data, it is also referred to as a digest.\nHash function with n bit output is referred to as an n-bit hash function. Popular hash functions generate values between 160 and 512 bits.\n\n" }, { "code": null, "e": 108257, "s": 108224, "text": "Fixed Length Output (Hash Value)" }, { "code": null, "e": 108378, "s": 108257, "text": "Hash function coverts data of arbitrary length to a fixed length. This process is often referred to as hashing the data." }, { "code": null, "e": 108499, "s": 108378, "text": "Hash function coverts data of arbitrary length to a fixed length. This process is often referred to as hashing the data." }, { "code": null, "e": 108622, "s": 108499, "text": "In general, the hash is much smaller than the input data, hence hash functions are sometimes called compression functions." }, { "code": null, "e": 108745, "s": 108622, "text": "In general, the hash is much smaller than the input data, hence hash functions are sometimes called compression functions." }, { "code": null, "e": 108840, "s": 108745, "text": "Since a hash is a smaller representation of a larger data, it is also referred to as a digest." }, { "code": null, "e": 108935, "s": 108840, "text": "Since a hash is a smaller representation of a larger data, it is also referred to as a digest." }, { "code": null, "e": 109074, "s": 108935, "text": "Hash function with n bit output is referred to as an n-bit hash function. Popular hash functions generate values between 160 and 512 bits." }, { "code": null, "e": 109213, "s": 109074, "text": "Hash function with n bit output is referred to as an n-bit hash function. Popular hash functions generate values between 160 and 512 bits." }, { "code": null, "e": 109405, "s": 109213, "text": "Efficiency of Operation\n\nGenerally for any hash function h with input x, computation of h(x) is a fast operation.\nComputationally hash functions are much faster than a symmetric encryption.\n\n" }, { "code": null, "e": 109429, "s": 109405, "text": "Efficiency of Operation" }, { "code": null, "e": 109518, "s": 109429, "text": "Generally for any hash function h with input x, computation of h(x) is a fast operation." }, { "code": null, "e": 109607, "s": 109518, "text": "Generally for any hash function h with input x, computation of h(x) is a fast operation." }, { "code": null, "e": 109683, "s": 109607, "text": "Computationally hash functions are much faster than a symmetric encryption." }, { "code": null, "e": 109759, "s": 109683, "text": "Computationally hash functions are much faster than a symmetric encryption." }, { "code": null, "e": 109870, "s": 109759, "text": "In order to be an effective cryptographic tool, the hash function is desired to possess following properties βˆ’" }, { "code": null, "e": 110227, "s": 109870, "text": "Pre-Image Resistance\n\nThis property means that it should be computationally hard to reverse a hash function.\nIn other words, if a hash function h produced a hash value z, then it should be a difficult process to find any input value x that hashes to z.\nThis property protects against an attacker who only has a hash value and is trying to find the input.\n\n" }, { "code": null, "e": 110248, "s": 110227, "text": "Pre-Image Resistance" }, { "code": null, "e": 110335, "s": 110248, "text": "This property means that it should be computationally hard to reverse a hash function." }, { "code": null, "e": 110422, "s": 110335, "text": "This property means that it should be computationally hard to reverse a hash function." }, { "code": null, "e": 110566, "s": 110422, "text": "In other words, if a hash function h produced a hash value z, then it should be a difficult process to find any input value x that hashes to z." }, { "code": null, "e": 110710, "s": 110566, "text": "In other words, if a hash function h produced a hash value z, then it should be a difficult process to find any input value x that hashes to z." }, { "code": null, "e": 110812, "s": 110710, "text": "This property protects against an attacker who only has a hash value and is trying to find the input." }, { "code": null, "e": 110914, "s": 110812, "text": "This property protects against an attacker who only has a hash value and is trying to find the input." }, { "code": null, "e": 111410, "s": 110914, "text": "Second Pre-Image Resistance\n\nThis property means given an input and its hash, it should be hard to find a different input with the same hash.\nIn other words, if a hash function h for an input x produces hash value h(x), then it should be difficult to find any other input value y such that h(y) = h(x).\nThis property of hash function protects against an attacker who has an input value and its hash, and wants to substitute different value as legitimate value in place of original input value.\n\n" }, { "code": null, "e": 111438, "s": 111410, "text": "Second Pre-Image Resistance" }, { "code": null, "e": 111551, "s": 111438, "text": "This property means given an input and its hash, it should be hard to find a different input with the same hash." }, { "code": null, "e": 111664, "s": 111551, "text": "This property means given an input and its hash, it should be hard to find a different input with the same hash." }, { "code": null, "e": 111825, "s": 111664, "text": "In other words, if a hash function h for an input x produces hash value h(x), then it should be difficult to find any other input value y such that h(y) = h(x)." }, { "code": null, "e": 111986, "s": 111825, "text": "In other words, if a hash function h for an input x produces hash value h(x), then it should be difficult to find any other input value y such that h(y) = h(x)." }, { "code": null, "e": 112177, "s": 111986, "text": "This property of hash function protects against an attacker who has an input value and its hash, and wants to substitute different value as legitimate value in place of original input value." }, { "code": null, "e": 112368, "s": 112177, "text": "This property of hash function protects against an attacker who has an input value and its hash, and wants to substitute different value as legitimate value in place of original input value." }, { "code": null, "e": 113092, "s": 112368, "text": "Collision Resistance\n\nThis property means it should be hard to find two different inputs of any length that result in the same hash. This property is also referred to as collision free hash function.\nIn other words, for a hash function h, it is hard to find any two different inputs x and y such that h(x) = h(y).\nSince, hash function is compressing function with fixed hash length, it is impossible for a hash function not to have collisions. This property of collision free only confirms that these collisions should be hard to find.\nThis property makes it very difficult for an attacker to find two input values with the same hash.\nAlso, if a hash function is collision-resistant then it is second pre-image resistant.\n\n" }, { "code": null, "e": 113113, "s": 113092, "text": "Collision Resistance" }, { "code": null, "e": 113291, "s": 113113, "text": "This property means it should be hard to find two different inputs of any length that result in the same hash. This property is also referred to as collision free hash function." }, { "code": null, "e": 113469, "s": 113291, "text": "This property means it should be hard to find two different inputs of any length that result in the same hash. This property is also referred to as collision free hash function." }, { "code": null, "e": 113583, "s": 113469, "text": "In other words, for a hash function h, it is hard to find any two different inputs x and y such that h(x) = h(y)." }, { "code": null, "e": 113697, "s": 113583, "text": "In other words, for a hash function h, it is hard to find any two different inputs x and y such that h(x) = h(y)." }, { "code": null, "e": 113919, "s": 113697, "text": "Since, hash function is compressing function with fixed hash length, it is impossible for a hash function not to have collisions. This property of collision free only confirms that these collisions should be hard to find." }, { "code": null, "e": 114141, "s": 113919, "text": "Since, hash function is compressing function with fixed hash length, it is impossible for a hash function not to have collisions. This property of collision free only confirms that these collisions should be hard to find." }, { "code": null, "e": 114240, "s": 114141, "text": "This property makes it very difficult for an attacker to find two input values with the same hash." }, { "code": null, "e": 114339, "s": 114240, "text": "This property makes it very difficult for an attacker to find two input values with the same hash." }, { "code": null, "e": 114426, "s": 114339, "text": "Also, if a hash function is collision-resistant then it is second pre-image resistant." }, { "code": null, "e": 114513, "s": 114426, "text": "Also, if a hash function is collision-resistant then it is second pre-image resistant." }, { "code": null, "e": 114696, "s": 114513, "text": "At the heart of a hashing is a mathematical function that operates on two fixed-size blocks of data to create a hash code. This hash function forms the part of the hashing algorithm." }, { "code": null, "e": 114872, "s": 114696, "text": "The size of each data block varies depending on the algorithm. Typically the block sizes are from 128 bits to 512 bits. The following illustration demonstrates hash function βˆ’" }, { "code": null, "e": 115084, "s": 114872, "text": "Hashing algorithm involves rounds of above hash function like a block cipher. Each round takes an input of a fixed size, typically a combination of the most recent message block and the output of the last round." }, { "code": null, "e": 115247, "s": 115084, "text": "This process is repeated for as many rounds as are required to hash the entire message. Schematic of hashing algorithm is depicted in the following illustration βˆ’" }, { "code": null, "e": 115462, "s": 115247, "text": "Since, the hash value of first message block becomes an input to the second hash operation, output of which alters the result of the third operation, and so on. This effect, known as an avalanche effect of hashing." }, { "code": null, "e": 115585, "s": 115462, "text": "Avalanche effect results in substantially different hash values for two messages that differ by even a single bit of data." }, { "code": null, "e": 115754, "s": 115585, "text": "Understand the difference between hash function and algorithm correctly. The hash function generates a hash code by operating on two blocks of fixed-length binary data." }, { "code": null, "e": 115930, "s": 115754, "text": "Hashing algorithm is a process for using the hash function, specifying how the message will be broken up and how the results from previous message blocks are chained together." }, { "code": null, "e": 115979, "s": 115930, "text": "Let us briefly see some popular hash functions βˆ’" }, { "code": null, "e": 116052, "s": 115979, "text": "MD5 was most popular and widely used hash function for quite some years." }, { "code": null, "e": 116194, "s": 116052, "text": "The MD family comprises of hash functions MD2, MD4, MD5 and MD6. It was adopted as Internet Standard RFC 1321. It is a 128-bit hash function." }, { "code": null, "e": 116336, "s": 116194, "text": "The MD family comprises of hash functions MD2, MD4, MD5 and MD6. It was adopted as Internet Standard RFC 1321. It is a 128-bit hash function." }, { "code": null, "e": 116603, "s": 116336, "text": "MD5 digests have been widely used in the software world to provide assurance about integrity of transferred file. For example, file servers often provide a pre-computed MD5 checksum for the files, so that a user can compare the checksum of the downloaded file to it." }, { "code": null, "e": 116870, "s": 116603, "text": "MD5 digests have been widely used in the software world to provide assurance about integrity of transferred file. For example, file servers often provide a pre-computed MD5 checksum for the files, so that a user can compare the checksum of the downloaded file to it." }, { "code": null, "e": 117100, "s": 116870, "text": "In 2004, collisions were found in MD5. An analytical attack was reported to be successful only in an hour by using computer cluster. This collision attack resulted in compromised MD5 and hence it is no longer recommended for use." }, { "code": null, "e": 117330, "s": 117100, "text": "In 2004, collisions were found in MD5. An analytical attack was reported to be successful only in an hour by using computer cluster. This collision attack resulted in compromised MD5 and hence it is no longer recommended for use." }, { "code": null, "e": 117468, "s": 117330, "text": "Family of SHA comprise of four SHA algorithms; SHA-0, SHA-1, SHA-2, and SHA-3. Though from same family, there are structurally different." }, { "code": null, "e": 117737, "s": 117468, "text": "The original version is SHA-0, a 160-bit hash function, was published by the National Institute of Standards and Technology (NIST) in 1993. It had few weaknesses and did not become very popular. Later in 1995, SHA-1 was designed to correct alleged weaknesses of SHA-0." }, { "code": null, "e": 118006, "s": 117737, "text": "The original version is SHA-0, a 160-bit hash function, was published by the National Institute of Standards and Technology (NIST) in 1993. It had few weaknesses and did not become very popular. Later in 1995, SHA-1 was designed to correct alleged weaknesses of SHA-0." }, { "code": null, "e": 118183, "s": 118006, "text": "SHA-1 is the most widely used of the existing SHA hash functions. It is employed in several widely used applications and protocols including Secure Socket Layer (SSL) security." }, { "code": null, "e": 118360, "s": 118183, "text": "SHA-1 is the most widely used of the existing SHA hash functions. It is employed in several widely used applications and protocols including Secure Socket Layer (SSL) security." }, { "code": null, "e": 118502, "s": 118360, "text": "In 2005, a method was found for uncovering collisions for SHA-1 within practical time frame making long-term employability of SHA-1 doubtful." }, { "code": null, "e": 118644, "s": 118502, "text": "In 2005, a method was found for uncovering collisions for SHA-1 within practical time frame making long-term employability of SHA-1 doubtful." }, { "code": null, "e": 118848, "s": 118644, "text": "SHA-2 family has four further SHA variants, SHA-224, SHA-256, SHA-384, and SHA-512 depending up on number of bits in their hash value. No successful attacks have yet been reported on SHA-2 hash function." }, { "code": null, "e": 119052, "s": 118848, "text": "SHA-2 family has four further SHA variants, SHA-224, SHA-256, SHA-384, and SHA-512 depending up on number of bits in their hash value. No successful attacks have yet been reported on SHA-2 hash function." }, { "code": null, "e": 119237, "s": 119052, "text": "Though SHA-2 is a strong hash function. Though significantly different, its basic design is still follows design of SHA-1. Hence, NIST called for new competitive hash function designs." }, { "code": null, "e": 119422, "s": 119237, "text": "Though SHA-2 is a strong hash function. Though significantly different, its basic design is still follows design of SHA-1. Hence, NIST called for new competitive hash function designs." }, { "code": null, "e": 119594, "s": 119422, "text": "In October 2012, the NIST chose the Keccak algorithm as the new SHA-3 standard. Keccak offers many benefits, such as efficient performance and good resistance for attacks." }, { "code": null, "e": 119766, "s": 119594, "text": "In October 2012, the NIST chose the Keccak algorithm as the new SHA-3 standard. Keccak offers many benefits, such as efficient performance and good resistance for attacks." }, { "code": null, "e": 119975, "s": 119766, "text": "The RIPEMD is an acronym for RACE Integrity Primitives Evaluation Message Digest. This set of hash functions was designed by open research community and generally known as a family of European hash functions." }, { "code": null, "e": 120090, "s": 119975, "text": "The set includes RIPEMD, RIPEMD-128, and RIPEMD-160. There also exist 256, and 320-bit versions of this algorithm." }, { "code": null, "e": 120205, "s": 120090, "text": "The set includes RIPEMD, RIPEMD-128, and RIPEMD-160. There also exist 256, and 320-bit versions of this algorithm." }, { "code": null, "e": 120430, "s": 120205, "text": "Original RIPEMD (128 bit) is based upon the design principles used in MD4 and found to provide questionable security. RIPEMD 128-bit version came as a quick fix replacement to overcome vulnerabilities on the original RIPEMD." }, { "code": null, "e": 120655, "s": 120430, "text": "Original RIPEMD (128 bit) is based upon the design principles used in MD4 and found to provide questionable security. RIPEMD 128-bit version came as a quick fix replacement to overcome vulnerabilities on the original RIPEMD." }, { "code": null, "e": 120906, "s": 120655, "text": "RIPEMD-160 is an improved version and the most widely used version in the family. The 256 and 320-bit versions reduce the chance of accidental collision, but do not have higher levels of security as compared to RIPEMD-128 and RIPEMD-160 respectively." }, { "code": null, "e": 121157, "s": 120906, "text": "RIPEMD-160 is an improved version and the most widely used version in the family. The 256 and 320-bit versions reduce the chance of accidental collision, but do not have higher levels of security as compared to RIPEMD-128 and RIPEMD-160 respectively." }, { "code": null, "e": 121190, "s": 121157, "text": "This is a 512-bit hash function." }, { "code": null, "e": 121334, "s": 121190, "text": "It is derived from the modified version of Advanced Encryption Standard (AES). One of the designer was Vincent Rijmen, a co-creator of the AES." }, { "code": null, "e": 121478, "s": 121334, "text": "It is derived from the modified version of Advanced Encryption Standard (AES). One of the designer was Vincent Rijmen, a co-creator of the AES." }, { "code": null, "e": 121574, "s": 121478, "text": "Three versions of Whirlpool have been released; namely WHIRLPOOL-0, WHIRLPOOL-T, and WHIRLPOOL." }, { "code": null, "e": 121670, "s": 121574, "text": "Three versions of Whirlpool have been released; namely WHIRLPOOL-0, WHIRLPOOL-T, and WHIRLPOOL." }, { "code": null, "e": 121760, "s": 121670, "text": "There are two direct applications of hash function based on its cryptographic properties." }, { "code": null, "e": 121815, "s": 121760, "text": "Hash functions provide protection to password storage." }, { "code": null, "e": 121928, "s": 121815, "text": "Instead of storing password in clear, mostly all logon processes store the hash values of passwords in the file." }, { "code": null, "e": 122041, "s": 121928, "text": "Instead of storing password in clear, mostly all logon processes store the hash values of passwords in the file." }, { "code": null, "e": 122127, "s": 122041, "text": "The Password file consists of a table of pairs which are in the form (user id, h(P))." }, { "code": null, "e": 122213, "s": 122127, "text": "The Password file consists of a table of pairs which are in the form (user id, h(P))." }, { "code": null, "e": 122278, "s": 122213, "text": "The process of logon is depicted in the following illustration βˆ’" }, { "code": null, "e": 122343, "s": 122278, "text": "The process of logon is depicted in the following illustration βˆ’" }, { "code": null, "e": 122574, "s": 122343, "text": "An intruder can only see the hashes of passwords, even if he accessed the password. He can neither logon using hash nor can he derive the password from hash value since hash function possesses the property of pre-image resistance." }, { "code": null, "e": 122805, "s": 122574, "text": "An intruder can only see the hashes of passwords, even if he accessed the password. He can neither logon using hash nor can he derive the password from hash value since hash function possesses the property of pre-image resistance." }, { "code": null, "e": 123009, "s": 122805, "text": "Data integrity check is a most common application of the hash functions. It is used to generate the checksums on data files. This application provides assurance to the user about correctness of the data." }, { "code": null, "e": 123065, "s": 123009, "text": "The process is depicted in the following illustration βˆ’" }, { "code": null, "e": 123439, "s": 123065, "text": "The integrity check helps the user to detect any changes made to original file. It however, does not provide any assurance about originality. The attacker, instead of modifying file data, can change the entire file and compute all together new hash and send to the receiver. This integrity check application is useful only if the user is sure about the originality of file." }, { "code": null, "e": 123601, "s": 123439, "text": "In the last chapter, we discussed the data integrity threats and the use of hashing technique to detect if any modification attacks have taken place on the data." }, { "code": null, "e": 123883, "s": 123601, "text": "Another type of threat that exist for data is the lack of message authentication. In this threat, the user is not sure about the originator of the message. Message authentication can be provided using the cryptographic techniques that use secret keys as done in case of encryption." }, { "code": null, "e": 124054, "s": 123883, "text": "MAC algorithm is a symmetric key cryptographic technique to provide message authentication. For establishing MAC process, the sender and receiver share a symmetric key K." }, { "code": null, "e": 124202, "s": 124054, "text": "Essentially, a MAC is an encrypted checksum generated on the underlying message that is sent along with a message to ensure message authentication." }, { "code": null, "e": 124290, "s": 124202, "text": "The process of using MAC for authentication is depicted in the following illustration βˆ’" }, { "code": null, "e": 124350, "s": 124290, "text": "Let us now try to understand the entire process in detail βˆ’" }, { "code": null, "e": 124467, "s": 124350, "text": "The sender uses some publicly known MAC algorithm, inputs the message and the secret key K and produces a MAC value." }, { "code": null, "e": 124584, "s": 124467, "text": "The sender uses some publicly known MAC algorithm, inputs the message and the secret key K and produces a MAC value." }, { "code": null, "e": 124776, "s": 124584, "text": "Similar to hash, MAC function also compresses an arbitrary long input into a fixed length output. The major difference between hash and MAC is that MAC uses secret key during the compression." }, { "code": null, "e": 124968, "s": 124776, "text": "Similar to hash, MAC function also compresses an arbitrary long input into a fixed length output. The major difference between hash and MAC is that MAC uses secret key during the compression." }, { "code": null, "e": 125226, "s": 124968, "text": "The sender forwards the message along with the MAC. Here, we assume that the message is sent in the clear, as we are concerned of providing message origin authentication, not confidentiality. If confidentiality is required then the message needs encryption." }, { "code": null, "e": 125484, "s": 125226, "text": "The sender forwards the message along with the MAC. Here, we assume that the message is sent in the clear, as we are concerned of providing message origin authentication, not confidentiality. If confidentiality is required then the message needs encryption." }, { "code": null, "e": 125645, "s": 125484, "text": "On receipt of the message and the MAC, the receiver feeds the received message and the shared secret key K into the MAC algorithm and re-computes the MAC value." }, { "code": null, "e": 125806, "s": 125645, "text": "On receipt of the message and the MAC, the receiver feeds the received message and the shared secret key K into the MAC algorithm and re-computes the MAC value." }, { "code": null, "e": 126030, "s": 125806, "text": "The receiver now checks equality of freshly computed MAC with the MAC received from the sender. If they match, then the receiver accepts the message and assures himself that the message has been sent by the intended sender." }, { "code": null, "e": 126254, "s": 126030, "text": "The receiver now checks equality of freshly computed MAC with the MAC received from the sender. If they match, then the receiver accepts the message and assures himself that the message has been sent by the intended sender." }, { "code": null, "e": 126521, "s": 126254, "text": "If the computed MAC does not match the MAC sent by the sender, the receiver cannot determine whether it is the message that has been altered or it is the origin that has been falsified. As a bottom-line, a receiver safely assumes that the message is not the genuine." }, { "code": null, "e": 126788, "s": 126521, "text": "If the computed MAC does not match the MAC sent by the sender, the receiver cannot determine whether it is the message that has been altered or it is the origin that has been falsified. As a bottom-line, a receiver safely assumes that the message is not the genuine." }, { "code": null, "e": 126876, "s": 126788, "text": "There are two major limitations of MAC, both due to its symmetric nature of operation βˆ’" }, { "code": null, "e": 127071, "s": 126876, "text": "Establishment of Shared Secret.\n\nIt can provide message authentication among pre-decided legitimate users who have shared key.\nThis requires establishment of shared secret prior to use of MAC.\n\n" }, { "code": null, "e": 127103, "s": 127071, "text": "Establishment of Shared Secret." }, { "code": null, "e": 127197, "s": 127103, "text": "It can provide message authentication among pre-decided legitimate users who have shared key." }, { "code": null, "e": 127291, "s": 127197, "text": "It can provide message authentication among pre-decided legitimate users who have shared key." }, { "code": null, "e": 127357, "s": 127291, "text": "This requires establishment of shared secret prior to use of MAC." }, { "code": null, "e": 127423, "s": 127357, "text": "This requires establishment of shared secret prior to use of MAC." }, { "code": null, "e": 128008, "s": 127423, "text": "Inability to Provide Non-Repudiation\n\nNon-repudiation is the assurance that a message originator cannot deny any previously sent messages and commitments or actions.\nMAC technique does not provide a non-repudiation service. If the sender and receiver get involved in a dispute over message origination, MACs cannot provide a proof that a message was indeed sent by the sender.\nThough no third party can compute the MAC, still sender could deny having sent the message and claim that the receiver forged it, as it is impossible to determine which of the two parties computed the MAC.\n\n" }, { "code": null, "e": 128045, "s": 128008, "text": "Inability to Provide Non-Repudiation" }, { "code": null, "e": 128173, "s": 128045, "text": "Non-repudiation is the assurance that a message originator cannot deny any previously sent messages and commitments or actions." }, { "code": null, "e": 128301, "s": 128173, "text": "Non-repudiation is the assurance that a message originator cannot deny any previously sent messages and commitments or actions." }, { "code": null, "e": 128512, "s": 128301, "text": "MAC technique does not provide a non-repudiation service. If the sender and receiver get involved in a dispute over message origination, MACs cannot provide a proof that a message was indeed sent by the sender." }, { "code": null, "e": 128723, "s": 128512, "text": "MAC technique does not provide a non-repudiation service. If the sender and receiver get involved in a dispute over message origination, MACs cannot provide a proof that a message was indeed sent by the sender." }, { "code": null, "e": 128929, "s": 128723, "text": "Though no third party can compute the MAC, still sender could deny having sent the message and claim that the receiver forged it, as it is impossible to determine which of the two parties computed the MAC." }, { "code": null, "e": 129135, "s": 128929, "text": "Though no third party can compute the MAC, still sender could deny having sent the message and claim that the receiver forged it, as it is impossible to determine which of the two parties computed the MAC." }, { "code": null, "e": 129255, "s": 129135, "text": "Both these limitations can be overcome by using the public key based digital signatures discussed in following section." }, { "code": null, "e": 129479, "s": 129255, "text": "Digital signatures are the public-key primitives of message authentication. In the physical world, it is common to use handwritten signatures on handwritten or typed messages. They are used to bind signatory to the message." }, { "code": null, "e": 129656, "s": 129479, "text": "Similarly, a digital signature is a technique that binds a person/entity to the digital data. This binding can be independently verified by receiver as well as any third party." }, { "code": null, "e": 129775, "s": 129656, "text": "Digital signature is a cryptographic value that is calculated from the data and a secret key known only by the signer." }, { "code": null, "e": 130064, "s": 129775, "text": "In real world, the receiver of message needs assurance that the message belongs to the sender and he should not be able to repudiate the origination of that message. This requirement is very crucial in business applications, since likelihood of a dispute over exchanged data is very high." }, { "code": null, "e": 130234, "s": 130064, "text": "As mentioned earlier, the digital signature scheme is based on public key cryptography. The model of digital signature scheme is depicted in the following illustration βˆ’" }, { "code": null, "e": 130294, "s": 130234, "text": "The following points explain the entire process in detail βˆ’" }, { "code": null, "e": 130358, "s": 130294, "text": "Each person adopting this scheme has a public-private key pair." }, { "code": null, "e": 130422, "s": 130358, "text": "Each person adopting this scheme has a public-private key pair." }, { "code": null, "e": 130628, "s": 130422, "text": "Generally, the key pairs used for encryption/decryption and signing/verifying are different. The private key used for signing is referred to as the signature key and the public key as the verification key." }, { "code": null, "e": 130834, "s": 130628, "text": "Generally, the key pairs used for encryption/decryption and signing/verifying are different. The private key used for signing is referred to as the signature key and the public key as the verification key." }, { "code": null, "e": 130901, "s": 130834, "text": "Signer feeds data to the hash function and generates hash of data." }, { "code": null, "e": 130968, "s": 130901, "text": "Signer feeds data to the hash function and generates hash of data." }, { "code": null, "e": 131163, "s": 130968, "text": "Hash value and signature key are then fed to the signature algorithm which produces the digital signature on given hash. Signature is appended to the data and then both are sent to the verifier." }, { "code": null, "e": 131358, "s": 131163, "text": "Hash value and signature key are then fed to the signature algorithm which produces the digital signature on given hash. Signature is appended to the data and then both are sent to the verifier." }, { "code": null, "e": 131508, "s": 131358, "text": "Verifier feeds the digital signature and the verification key into the verification algorithm. The verification algorithm gives some value as output." }, { "code": null, "e": 131658, "s": 131508, "text": "Verifier feeds the digital signature and the verification key into the verification algorithm. The verification algorithm gives some value as output." }, { "code": null, "e": 131737, "s": 131658, "text": "Verifier also runs same hash function on received data to generate hash value." }, { "code": null, "e": 131816, "s": 131737, "text": "Verifier also runs same hash function on received data to generate hash value." }, { "code": null, "e": 131990, "s": 131816, "text": "For verification, this hash value and output of verification algorithm are compared. Based on the comparison result, verifier decides whether the digital signature is valid." }, { "code": null, "e": 132164, "s": 131990, "text": "For verification, this hash value and output of verification algorithm are compared. Based on the comparison result, verifier decides whether the digital signature is valid." }, { "code": null, "e": 132317, "s": 132164, "text": "Since digital signature is created by β€˜private’ key of signer and no one else can have this key; the signer cannot repudiate signing the data in future." }, { "code": null, "e": 132470, "s": 132317, "text": "Since digital signature is created by β€˜private’ key of signer and no one else can have this key; the signer cannot repudiate signing the data in future." }, { "code": null, "e": 132803, "s": 132470, "text": "It should be noticed that instead of signing data directly by signing algorithm, usually a hash of data is created. Since the hash of data is a unique representation of data, it is sufficient to sign the hash in place of data. The most important reason of using hash instead of data directly for signing is efficiency of the scheme." }, { "code": null, "e": 132976, "s": 132803, "text": "Let us assume RSA is used as the signing algorithm. As discussed in public key encryption chapter, the encryption/signing process using RSA involves modular exponentiation." }, { "code": null, "e": 133207, "s": 132976, "text": "Signing large data through modular exponentiation is computationally expensive and time consuming. The hash of the data is a relatively small digest of the data, hence signing a hash is more efficient than signing the entire data." }, { "code": null, "e": 133377, "s": 133207, "text": "Out of all cryptographic primitives, the digital signature using public key cryptography is considered as very important and useful tool to achieve information security." }, { "code": null, "e": 133581, "s": 133377, "text": "Apart from ability to provide non-repudiation of message, the digital signature also provides message authentication and data integrity. Let us briefly see how this is achieved by the digital signature βˆ’" }, { "code": null, "e": 133813, "s": 133581, "text": "Message authentication βˆ’ When the verifier validates the digital signature using public key of a sender, he is assured that signature has been created only by sender who possess the corresponding secret private key and no one else." }, { "code": null, "e": 134045, "s": 133813, "text": "Message authentication βˆ’ When the verifier validates the digital signature using public key of a sender, he is assured that signature has been created only by sender who possess the corresponding secret private key and no one else." }, { "code": null, "e": 134368, "s": 134045, "text": "Data Integrity βˆ’ In case an attacker has access to the data and modifies it, the digital signature verification at receiver end fails. The hash of modified data and the output provided by the verification algorithm will not match. Hence, receiver can safely deny the message assuming that data integrity has been breached." }, { "code": null, "e": 134691, "s": 134368, "text": "Data Integrity βˆ’ In case an attacker has access to the data and modifies it, the digital signature verification at receiver end fails. The hash of modified data and the output provided by the verification algorithm will not match. Hence, receiver can safely deny the message assuming that data integrity has been breached." }, { "code": null, "e": 134970, "s": 134691, "text": "Non-repudiation βˆ’ Since it is assumed that only the signer has the knowledge of the signature key, he can only create unique signature on a given data. Thus the receiver can present data and the digital signature to a third party as evidence if any dispute arises in the future." }, { "code": null, "e": 135249, "s": 134970, "text": "Non-repudiation βˆ’ Since it is assumed that only the signer has the knowledge of the signature key, he can only create unique signature on a given data. Thus the receiver can present data and the digital signature to a third party as evidence if any dispute arises in the future." }, { "code": null, "e": 135462, "s": 135249, "text": "By adding public-key encryption to digital signature scheme, we can create a cryptosystem that can provide the four essential elements of security namely βˆ’ Privacy, Authentication, Integrity, and Non-repudiation." }, { "code": null, "e": 135773, "s": 135462, "text": "In many digital communications, it is desirable to exchange an encrypted messages than plaintext to achieve confidentiality. In public key encryption scheme, a public (encryption) key of sender is available in open domain, and hence anyone can spoof his identity and send any encrypted message to the receiver." }, { "code": null, "e": 135950, "s": 135773, "text": "This makes it essential for users employing PKC for encryption to seek digital signatures along with encrypted data to be assured of message authentication and non-repudiation." }, { "code": null, "e": 136150, "s": 135950, "text": "This can archived by combining digital signatures with encryption scheme. Let us briefly discuss how to achieve this requirement. There are two possibilities, sign-then-encrypt and encrypt-then-sign." }, { "code": null, "e": 136452, "s": 136150, "text": "However, the crypto system based on sign-then-encrypt can be exploited by receiver to spoof identity of sender and sent that data to third party. Hence, this method is not preferred. The process of encrypt-then-sign is more reliable and widely adopted. This is depicted in the following illustration βˆ’" }, { "code": null, "e": 136692, "s": 136452, "text": "The receiver after receiving the encrypted data and signature on it, first verifies the signature using sender’s public key. After ensuring the validity of the signature, he then retrieves the data through decryption using his private key." }, { "code": null, "e": 136882, "s": 136692, "text": "The most distinct feature of Public Key Infrastructure (PKI) is that it uses a pair of keys to achieve the underlying security service. The key pair comprises of private key and public key." }, { "code": null, "e": 137061, "s": 136882, "text": "Since the public keys are in open domain, they are likely to be abused. It is, thus, necessary to establish and maintain some kind of trusted infrastructure to manage these keys." }, { "code": null, "e": 137314, "s": 137061, "text": "It goes without saying that the security of any cryptosystem depends upon how securely its keys are managed. Without secure procedures for the handling of cryptographic keys, the benefits of the use of strong cryptographic schemes are potentially lost." }, { "code": null, "e": 137480, "s": 137314, "text": "It is observed that cryptographic schemes are rarely compromised through weaknesses in their design. However, they are often compromised through poor key management." }, { "code": null, "e": 137554, "s": 137480, "text": "There are some important aspects of key management which are as follows βˆ’" }, { "code": null, "e": 137687, "s": 137554, "text": "Cryptographic keys are nothing but special pieces of data. Key management refers to the secure administration of cryptographic keys." }, { "code": null, "e": 137820, "s": 137687, "text": "Cryptographic keys are nothing but special pieces of data. Key management refers to the secure administration of cryptographic keys." }, { "code": null, "e": 137911, "s": 137820, "text": "Key management deals with entire key lifecycle as depicted in the following illustration βˆ’" }, { "code": null, "e": 138002, "s": 137911, "text": "Key management deals with entire key lifecycle as depicted in the following illustration βˆ’" }, { "code": null, "e": 138616, "s": 138002, "text": "There are two specific requirements of key management for public key cryptography.\n\nSecrecy of private keys. Throughout the key lifecycle, secret keys must remain secret from all parties except those who are owner and are authorized to use them.\nAssurance of public keys. In public key cryptography, the public keys are in open domain and seen as public pieces of data. By default there are no assurances of whether a public key is correct, with whom it can be associated, or what it can be used for. Thus key management of public keys needs to focus much more explicitly on assurance of purpose of public keys.\n\n" }, { "code": null, "e": 138699, "s": 138616, "text": "There are two specific requirements of key management for public key cryptography." }, { "code": null, "e": 138861, "s": 138699, "text": "Secrecy of private keys. Throughout the key lifecycle, secret keys must remain secret from all parties except those who are owner and are authorized to use them." }, { "code": null, "e": 139023, "s": 138861, "text": "Secrecy of private keys. Throughout the key lifecycle, secret keys must remain secret from all parties except those who are owner and are authorized to use them." }, { "code": null, "e": 139389, "s": 139023, "text": "Assurance of public keys. In public key cryptography, the public keys are in open domain and seen as public pieces of data. By default there are no assurances of whether a public key is correct, with whom it can be associated, or what it can be used for. Thus key management of public keys needs to focus much more explicitly on assurance of purpose of public keys." }, { "code": null, "e": 139755, "s": 139389, "text": "Assurance of public keys. In public key cryptography, the public keys are in open domain and seen as public pieces of data. By default there are no assurances of whether a public key is correct, with whom it can be associated, or what it can be used for. Thus key management of public keys needs to focus much more explicitly on assurance of purpose of public keys." }, { "code": null, "e": 139939, "s": 139755, "text": "The most crucial requirement of β€˜assurance of public key’ can be achieved through the public-key infrastructure (PKI), a key management systems for supporting public-key cryptography." }, { "code": null, "e": 140104, "s": 139939, "text": "PKI provides assurance of public key. It provides the identification of public keys and their distribution. An anatomy of PKI comprises of the following components." }, { "code": null, "e": 140175, "s": 140104, "text": "Public Key Certificate, commonly referred to as β€˜digital certificate’." }, { "code": null, "e": 140195, "s": 140175, "text": "Private Key tokens." }, { "code": null, "e": 140220, "s": 140195, "text": "Certification Authority." }, { "code": null, "e": 140244, "s": 140220, "text": "Registration Authority." }, { "code": null, "e": 140275, "s": 140244, "text": "Certificate Management System." }, { "code": null, "e": 140537, "s": 140275, "text": "For analogy, a certificate can be considered as the ID card issued to the person. People use ID cards such as a driver's license, passport to prove their identity. A digital certificate does the same basic thing in the electronic world, but with one difference." }, { "code": null, "e": 140717, "s": 140537, "text": "Digital Certificates are not only issued to people but they can be issued to computers, software packages or anything else that need to prove the identity in the electronic world." }, { "code": null, "e": 141170, "s": 140717, "text": "Digital certificates are based on the ITU standard X.509 which defines a standard certificate format for public key certificates and certification validation. Hence digital certificates are sometimes also referred to as X.509 certificates.\nPublic key pertaining to the user client is stored in digital certificates by The Certification Authority (CA) along with other relevant information such as client information, expiration date, usage, issuer etc." }, { "code": null, "e": 141410, "s": 141170, "text": "Digital certificates are based on the ITU standard X.509 which defines a standard certificate format for public key certificates and certification validation. Hence digital certificates are sometimes also referred to as X.509 certificates." }, { "code": null, "e": 141623, "s": 141410, "text": "Public key pertaining to the user client is stored in digital certificates by The Certification Authority (CA) along with other relevant information such as client information, expiration date, usage, issuer etc." }, { "code": null, "e": 141717, "s": 141623, "text": "CA digitally signs this entire information and includes digital signature in the certificate." }, { "code": null, "e": 141811, "s": 141717, "text": "CA digitally signs this entire information and includes digital signature in the certificate." }, { "code": null, "e": 142113, "s": 141811, "text": "Anyone who needs the assurance about the public key and associated information of client, he carries out the signature validation process using CA’s public key. Successful validation assures that the public key given in the certificate belongs to the person whose details are given in the certificate." }, { "code": null, "e": 142415, "s": 142113, "text": "Anyone who needs the assurance about the public key and associated information of client, he carries out the signature validation process using CA’s public key. Successful validation assures that the public key given in the certificate belongs to the person whose details are given in the certificate." }, { "code": null, "e": 142522, "s": 142415, "text": "The process of obtaining Digital Certificate by a person/entity is depicted in the following illustration." }, { "code": null, "e": 142718, "s": 142522, "text": "As shown in the illustration, the CA accepts the application from a client to certify his public key. The CA, after duly verifying identity of client, issues a digital certificate to that client." }, { "code": null, "e": 143047, "s": 142718, "text": "As discussed above, the CA issues certificate to a client and assist other users to verify the certificate. The CA takes responsibility for identifying correctly the identity of the client asking for a certificate to be issued, and ensures that the information contained within the certificate is correct and digitally signs it." }, { "code": null, "e": 143090, "s": 143047, "text": "The key functions of a CA are as follows βˆ’" }, { "code": null, "e": 143186, "s": 143090, "text": "Generating key pairs βˆ’ The CA may generate a key pair independently or jointly with the client." }, { "code": null, "e": 143282, "s": 143186, "text": "Generating key pairs βˆ’ The CA may generate a key pair independently or jointly with the client." }, { "code": null, "e": 143579, "s": 143282, "text": "Issuing digital certificates βˆ’ The CA could be thought of as the PKI equivalent of a passport agency βˆ’ the CA issues a certificate after client provides the credentials to confirm his identity. The CA then signs the certificate to prevent modification of the details contained in the certificate." }, { "code": null, "e": 143876, "s": 143579, "text": "Issuing digital certificates βˆ’ The CA could be thought of as the PKI equivalent of a passport agency βˆ’ the CA issues a certificate after client provides the credentials to confirm his identity. The CA then signs the certificate to prevent modification of the details contained in the certificate." }, { "code": null, "e": 144199, "s": 143876, "text": "Publishing Certificates βˆ’ The CA need to publish certificates so that users can find them. There are two ways of achieving this. One is to publish certificates in the equivalent of an electronic telephone directory. The other is to send your certificate out to those people you think might need it by one means or another." }, { "code": null, "e": 144522, "s": 144199, "text": "Publishing Certificates βˆ’ The CA need to publish certificates so that users can find them. There are two ways of achieving this. One is to publish certificates in the equivalent of an electronic telephone directory. The other is to send your certificate out to those people you think might need it by one means or another." }, { "code": null, "e": 144673, "s": 144522, "text": "Verifying Certificates βˆ’ The CA makes its public key available in environment to assist verification of his signature on clients’ digital certificate." }, { "code": null, "e": 144824, "s": 144673, "text": "Verifying Certificates βˆ’ The CA makes its public key available in environment to assist verification of his signature on clients’ digital certificate." }, { "code": null, "e": 145095, "s": 144824, "text": "Revocation of Certificates βˆ’ At times, CA revokes the certificate issued due to some reason such as compromise of private key by user or loss of trust in the client. After revocation, CA maintains the list of all revoked certificate that is available to the environment." }, { "code": null, "e": 145366, "s": 145095, "text": "Revocation of Certificates βˆ’ At times, CA revokes the certificate issued due to some reason such as compromise of private key by user or loss of trust in the client. After revocation, CA maintains the list of all revoked certificate that is available to the environment." }, { "code": null, "e": 145414, "s": 145366, "text": "There are four typical classes of certificate βˆ’" }, { "code": null, "e": 145497, "s": 145414, "text": "Class 1 βˆ’ These certificates can be easily acquired by supplying an email address." }, { "code": null, "e": 145580, "s": 145497, "text": "Class 1 βˆ’ These certificates can be easily acquired by supplying an email address." }, { "code": null, "e": 145665, "s": 145580, "text": "Class 2 βˆ’ These certificates require additional personal information to be supplied." }, { "code": null, "e": 145750, "s": 145665, "text": "Class 2 βˆ’ These certificates require additional personal information to be supplied." }, { "code": null, "e": 145861, "s": 145750, "text": "Class 3 βˆ’ These certificates can only be purchased after checks have been made about the requestor’s identity." }, { "code": null, "e": 145972, "s": 145861, "text": "Class 3 βˆ’ These certificates can only be purchased after checks have been made about the requestor’s identity." }, { "code": null, "e": 146077, "s": 145972, "text": "Class 4 βˆ’ They may be used by governments and financial organizations needing very high levels of trust." }, { "code": null, "e": 146182, "s": 146077, "text": "Class 4 βˆ’ They may be used by governments and financial organizations needing very high levels of trust." }, { "code": null, "e": 146449, "s": 146182, "text": "CA may use a third-party Registration Authority (RA) to perform the necessary checks on the person or company requesting the certificate to confirm their identity. The RA may appear to the client as a CA, but they do not actually sign the certificate that is issued." }, { "code": null, "e": 146868, "s": 146449, "text": "It is the management system through which certificates are published, temporarily or permanently suspended, renewed, or revoked. Certificate management systems do not normally delete certificates because it may be necessary to prove their status at a point in time, perhaps for legal reasons. A CA along with associated RA runs certificate management systems to be able to track their responsibilities and liabilities." }, { "code": null, "e": 147257, "s": 146868, "text": "While the public key of a client is stored on the certificate, the associated secret private key can be stored on the key owner’s computer. This method is generally not adopted. If an attacker gains access to the computer, he can easily gain access to private key. For this reason, a private key is stored on secure removable storage token access to which is protected through a password." }, { "code": null, "e": 147482, "s": 147257, "text": "Different vendors often use different and sometimes proprietary storage formats for storing keys. For example, Entrust uses the proprietary .epf format, while Verisign, GlobalSign, and Baltimore use the standard .p12 format." }, { "code": null, "e": 147735, "s": 147482, "text": "With vast networks and requirements of global communications, it is practically not feasible to have only one trusted CA from whom all users obtain their certificates. Secondly, availability of only one CA may lead to difficulties if CA is compromised." }, { "code": null, "e": 147950, "s": 147735, "text": "In such case, the hierarchical certification model is of interest since it allows public key certificates to be used in environments where two communicating parties do not have trust relationships with the same CA." }, { "code": null, "e": 148056, "s": 147950, "text": "The root CA is at the top of the CA hierarchy and the root CA's certificate is a self-signed certificate." }, { "code": null, "e": 148162, "s": 148056, "text": "The root CA is at the top of the CA hierarchy and the root CA's certificate is a self-signed certificate." }, { "code": null, "e": 148297, "s": 148162, "text": "The CAs, which are directly subordinate to the root CA (For example, CA1 and CA2) have CA certificates that are signed by the root CA." }, { "code": null, "e": 148432, "s": 148297, "text": "The CAs, which are directly subordinate to the root CA (For example, CA1 and CA2) have CA certificates that are signed by the root CA." }, { "code": null, "e": 148581, "s": 148432, "text": "The CAs under the subordinate CAs in the hierarchy (For example, CA5 and CA6) have their CA certificates signed by the higher-level subordinate CAs." }, { "code": null, "e": 148730, "s": 148581, "text": "The CAs under the subordinate CAs in the hierarchy (For example, CA5 and CA6) have their CA certificates signed by the higher-level subordinate CAs." }, { "code": null, "e": 148917, "s": 148730, "text": "Certificate authority (CA) hierarchies are reflected in certificate chains. A certificate chain traces a path of certificates from a branch in the hierarchy to the root of the hierarchy." }, { "code": null, "e": 149118, "s": 148917, "text": "The following illustration shows a CA hierarchy with a certificate chain leading from an entity certificate through two subordinate CA certificates (CA6 and CA3) to the CA certificate for the root CA." }, { "code": null, "e": 149378, "s": 149118, "text": "Verifying a certificate chain is the process of ensuring that a specific certificate chain is valid, correctly signed, and trustworthy. The following procedure verifies a certificate chain, beginning with the certificate that is presented for authentication βˆ’" }, { "code": null, "e": 149512, "s": 149378, "text": "A client whose authenticity is being verified supplies his certificate, generally along with the chain of certificates up to Root CA." }, { "code": null, "e": 149646, "s": 149512, "text": "A client whose authenticity is being verified supplies his certificate, generally along with the chain of certificates up to Root CA." }, { "code": null, "e": 149835, "s": 149646, "text": "Verifier takes the certificate and validates by using public key of issuer. The issuer’s public key is found in the issuer’s certificate which is in the chain next to client’s certificate." }, { "code": null, "e": 150024, "s": 149835, "text": "Verifier takes the certificate and validates by using public key of issuer. The issuer’s public key is found in the issuer’s certificate which is in the chain next to client’s certificate." }, { "code": null, "e": 150157, "s": 150024, "text": "Now if the higher CA who has signed the issuer’s certificate, is trusted by the verifier, verification is successful and stops here." }, { "code": null, "e": 150290, "s": 150157, "text": "Now if the higher CA who has signed the issuer’s certificate, is trusted by the verifier, verification is successful and stops here." }, { "code": null, "e": 150489, "s": 150290, "text": "Else, the issuer's certificate is verified in a similar manner as done for client in above steps. This process continues till either trusted CA is found in between or else it continues till Root CA." }, { "code": null, "e": 150688, "s": 150489, "text": "Else, the issuer's certificate is verified in a similar manner as done for client in above steps. This process continues till either trusted CA is found in between or else it continues till Root CA." }, { "code": null, "e": 150923, "s": 150688, "text": "Nowadays, the networks have gone global and information has taken the digital form of bits and bytes. Critical information now gets stored, processed and transmitted in digital form on computer systems and open communication channels." }, { "code": null, "e": 151134, "s": 150923, "text": "Since information plays such a vital role, adversaries are targeting the computer systems and open communication channels to either steal the sensitive information or to disrupt the critical information system." }, { "code": null, "e": 151463, "s": 151134, "text": "Modern cryptography provides a robust set of techniques to ensure that the malevolent intentions of the adversary are thwarted while ensuring the legitimate users get access to information. Here in this chapter, we will discuss the benefits that we draw from cryptography, its limitations, as well as the future of cryptography." }, { "code": null, "e": 151586, "s": 151463, "text": "Cryptography is an essential information security tool. It provides the four most basic services of information security βˆ’" }, { "code": null, "e": 151725, "s": 151586, "text": "Confidentiality βˆ’ Encryption technique can guard the information and communication from unauthorized revelation and access of information." }, { "code": null, "e": 151864, "s": 151725, "text": "Confidentiality βˆ’ Encryption technique can guard the information and communication from unauthorized revelation and access of information." }, { "code": null, "e": 152001, "s": 151864, "text": "Authentication βˆ’ The cryptographic techniques such as MAC and digital signatures can protect information against spoofing and forgeries." }, { "code": null, "e": 152138, "s": 152001, "text": "Authentication βˆ’ The cryptographic techniques such as MAC and digital signatures can protect information against spoofing and forgeries." }, { "code": null, "e": 152259, "s": 152138, "text": "Data Integrity βˆ’ The cryptographic hash functions are playing vital role in assuring the users about the data integrity." }, { "code": null, "e": 152380, "s": 152259, "text": "Data Integrity βˆ’ The cryptographic hash functions are playing vital role in assuring the users about the data integrity." }, { "code": null, "e": 152549, "s": 152380, "text": "Non-repudiation βˆ’ The digital signature provides the non-repudiation service to guard against the dispute that may arise due to denial of passing message by the sender." }, { "code": null, "e": 152718, "s": 152549, "text": "Non-repudiation βˆ’ The digital signature provides the non-repudiation service to guard against the dispute that may arise due to denial of passing message by the sender." }, { "code": null, "e": 152899, "s": 152718, "text": "All these fundamental services offered by cryptography has enabled the conduct of business over the networks using the computer systems in extremely efficient and effective manner." }, { "code": null, "e": 153035, "s": 152899, "text": "Apart from the four fundamental elements of information security, there are other issues that affect the effective use of information βˆ’" }, { "code": null, "e": 153288, "s": 153035, "text": "A strongly encrypted, authentic, and digitally signed information can be difficult to access even for a legitimate user at a crucial time of decision-making. The network or the computer system can be attacked and rendered non-functional by an intruder." }, { "code": null, "e": 153541, "s": 153288, "text": "A strongly encrypted, authentic, and digitally signed information can be difficult to access even for a legitimate user at a crucial time of decision-making. The network or the computer system can be attacked and rendered non-functional by an intruder." }, { "code": null, "e": 153792, "s": 153541, "text": "High availability, one of the fundamental aspects of information security, cannot be ensured through the use of cryptography. Other methods are needed to guard against the threats such as denial of service or complete breakdown of information system." }, { "code": null, "e": 154043, "s": 153792, "text": "High availability, one of the fundamental aspects of information security, cannot be ensured through the use of cryptography. Other methods are needed to guard against the threats such as denial of service or complete breakdown of information system." }, { "code": null, "e": 154259, "s": 154043, "text": "Another fundamental need of information security of selective access control also cannot be realized through the use of cryptography. Administrative controls and procedures are required to be exercised for the same." }, { "code": null, "e": 154475, "s": 154259, "text": "Another fundamental need of information security of selective access control also cannot be realized through the use of cryptography. Administrative controls and procedures are required to be exercised for the same." }, { "code": null, "e": 154706, "s": 154475, "text": "Cryptography does not guard against the vulnerabilities and threats that emerge from the poor design of systems, protocols, and procedures. These need to be fixed through proper design and setting up of a defensive infrastructure." }, { "code": null, "e": 154937, "s": 154706, "text": "Cryptography does not guard against the vulnerabilities and threats that emerge from the poor design of systems, protocols, and procedures. These need to be fixed through proper design and setting up of a defensive infrastructure." }, { "code": null, "e": 155233, "s": 154937, "text": "Cryptography comes at cost. The cost is in terms of time and money βˆ’\n\nAddition of cryptographic techniques in the information processing leads to delay.\nThe use of public key cryptography requires setting up and maintenance of public key infrastructure requiring the handsome financial budget.\n\n" }, { "code": null, "e": 155302, "s": 155233, "text": "Cryptography comes at cost. The cost is in terms of time and money βˆ’" }, { "code": null, "e": 155385, "s": 155302, "text": "Addition of cryptographic techniques in the information processing leads to delay." }, { "code": null, "e": 155468, "s": 155385, "text": "Addition of cryptographic techniques in the information processing leads to delay." }, { "code": null, "e": 155609, "s": 155468, "text": "The use of public key cryptography requires setting up and maintenance of public key infrastructure requiring the handsome financial budget." }, { "code": null, "e": 155750, "s": 155609, "text": "The use of public key cryptography requires setting up and maintenance of public key infrastructure requiring the handsome financial budget." }, { "code": null, "e": 155995, "s": 155750, "text": "The security of cryptographic technique is based on the computational difficulty of mathematical problems. Any breakthrough in solving such mathematical problems or increasing the computing power can render a cryptographic technique vulnerable." }, { "code": null, "e": 156240, "s": 155995, "text": "The security of cryptographic technique is based on the computational difficulty of mathematical problems. Any breakthrough in solving such mathematical problems or increasing the computing power can render a cryptographic technique vulnerable." }, { "code": null, "e": 156669, "s": 156240, "text": "Elliptic Curve Cryptography (ECC) has already been invented but its advantages and disadvantages are not yet fully understood. ECC allows to perform encryption and decryption in a drastically lesser time, thus allowing a higher amount of data to be passed with equal security. However, as other methods of encryption, ECC must also be tested and proven secure before it is accepted for governmental, commercial, and private use." }, { "code": null, "e": 157094, "s": 156669, "text": "Quantum computation is the new phenomenon. While modern computers store data using a binary format called a \"bit\" in which a \"1\" or a \"0\" can be stored; a quantum computer stores data using a quantum superposition of multiple states. These multiple valued states are stored in \"quantum bits\" or \"qubits\". This allows the computation of numbers to be several orders of magnitude faster than traditional transistor processors." }, { "code": null, "e": 157472, "s": 157094, "text": "To comprehend the power of quantum computer, consider RSA-640, a number with 193 digits, which can be factored by eighty 2.2GHz computers over the span of 5 months, one quantum computer would factor in less than 17 seconds. Numbers that would typically take billions of years to compute could only take a matter of hours or even minutes with a fully developed quantum computer." }, { "code": null, "e": 157670, "s": 157472, "text": "In view of these facts, modern cryptography will have to look for computationally harder problems or devise completely new techniques of archiving the goals presently served by modern cryptography." }, { "code": null, "e": 157703, "s": 157670, "text": "\n 10 Lectures \n 2 hours \n" }, { "code": null, "e": 157719, "s": 157703, "text": " Total Seminars" }, { "code": null, "e": 157752, "s": 157719, "text": "\n 10 Lectures \n 2 hours \n" }, { "code": null, "e": 157775, "s": 157752, "text": " Stone River ELearning" }, { "code": null, "e": 157782, "s": 157775, "text": " Print" }, { "code": null, "e": 157793, "s": 157782, "text": " Add Notes" } ]
C# | Arrays of Strings - GeeksforGeeks
19 Nov, 2019 An array is a collection of the same type variable. Whereas a string is a sequence of Unicode characters or array of characters. Therefore arrays of strings is an array of arrays of characters. Here, string array and arrays of strings both are same term. For Example, if you want to store the name of students of a class then you can use the arrays of strings. Arrays of strings can be one dimensional or multidimensional. Declaring the string array: There are two ways to declare the arrays of strings as follows Declaration without size:Syntax:String[] variable_name;orstring[] variable_name; Syntax: String[] variable_name; or string[] variable_name; Declaration with size:Syntax:String[] variable_name = new String[provide_size_here];orstring[] variable_name = new string[provide_size_here]; Syntax: String[] variable_name = new String[provide_size_here]; or string[] variable_name = new string[provide_size_here]; Example: // declaration using string keywordstring[] s1; // declaration using String class object// by giving its size 4String[] s2 = new String[4]; Initialization of Arrays of Strings: Arrays can be initialized after the declaration. It is not necessary to declare and initialize at the same time using the new keyword. However, Initializing an Array after the declaration, it must be initialized with the new keyword. It can’t be initialized by only assigning values. Example: // Declaration of the arraystring[] str1, str2; // Initialization of arraystr1 = new string[5]{ β€œElement 1”, β€œElement 2”, β€œElement 3”, β€œElement 4”, β€œElement 5” }; str2 = new string[]{ β€œElement 1”, β€œElement 2”, β€œElement 3”, β€œElement 4”, β€œElement 5” }; Note: Initialization without giving size is not valid in C#. It will give compile time error. Example: Wrong Declaration for initializing an array // compile-time error: must give size of an arrayString[] str = new String[]; // error : wrong initialization of an arraystring[] str1;str1 = {β€œElement 1”, β€œElement 2”, β€œElement 3”, β€œElement 4” }; Accessing Arrays of Strings Elements: At the time of initialization, we can assign the value. But, we can also assign the value of array using its index randomly after the declaration and initialization. We can access an array value through indexing, placed index of the element within square brackets with the array name. Example: // declares & initializes string array String[] s1 = new String[2]; // assign the value "Geeks" in array on its index 0 s1[0] = 10; // assign the value "GFG" in array on its index 1 s1[1] = 30; // assign the value "Noida" in array on its index 2 s1[2] = 20; // Accessing array elements using index s1[0]; // returns Geeks s1[2]; // returns Noida Declaration and initialization of string array in a single line: String array can also be declared and initialized in a single line. This method is more recommended as it reduces the line of code. Example: String[] weekDays = new string[3] {"Sun", "Mon", "Tue", "Wed"}; Code#1: String array declaration, initialization and accessing its elements // C# program to illustrate the String array // declaration, initialization and accessing // its elementsusing System; class Geeks { // Main Method public static void Main() { // Step 1: Array Declaration string[] stringarr; // Step 2:Array Initialization stringarr = new string[3] {"Element 1", "Element 2", "Element 3"}; // Step 3:Accessing Array Elements Console.WriteLine(stringarr[0]); Console.WriteLine(stringarr[1]); Console.WriteLine(stringarr[2]); }} Output: Element 1 Element 2 Element 3 Code#2: Array declaration and initialization in single line // C# code to illustrate Array declaration// and initialization in single lineusing System; class Geeks { // Main Method public static void Main() { // array initialization and declaration String[] stringarr = new String[] {"Geeks", "GFG", "Noida"}; // accessing array elements Console.WriteLine(stringarr[0]); Console.WriteLine(stringarr[1]); Console.WriteLine(stringarr[2]); }} Output: Geeks GFG Noida Note: In the public static void main(String[] args), String[] args is also an array of string.Example: To show String[] args is an array of string.// C# program to get the type of "args"using System; class GFG { // Main Method static public void Main (String[] args) { // using GetType() method to // get type at runtime Console.WriteLine(args.GetType()); }}Output:System.String[] Example: To show String[] args is an array of string. // C# program to get the type of "args"using System; class GFG { // Main Method static public void Main (String[] args) { // using GetType() method to // get type at runtime Console.WriteLine(args.GetType()); }} Output: System.String[] C# string array is basically an array of objects. It doesn’t matter whether you are creating an array of string using string keyword or String class object. Both are same.Example:// C# program to get the type of arrays of // strings which are declared using 'string'// keyword and 'String class object'using System; class GFG { // Main Method static public void Main (String[] args) { // declaring array of string // using string keyword string[] s1 = {"GFG", "Noida"}; // declaring array of string // using String class object String[] s2 = new String[2]{"Geeks", "C#"}; // using GetType() method to // get type at runtime Console.WriteLine(s1.GetType()); Console.WriteLine(s2.GetType()); }}Output:System.String[] System.String[] Example: // C# program to get the type of arrays of // strings which are declared using 'string'// keyword and 'String class object'using System; class GFG { // Main Method static public void Main (String[] args) { // declaring array of string // using string keyword string[] s1 = {"GFG", "Noida"}; // declaring array of string // using String class object String[] s2 = new String[2]{"Geeks", "C#"}; // using GetType() method to // get type at runtime Console.WriteLine(s1.GetType()); Console.WriteLine(s2.GetType()); }} Output: System.String[] System.String[] shubham_singh CSharp-Arrays CSharp-string Picked C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments C# | Constructors C# | Class and Object C# | Delegates Extension Method in C# Introduction to .NET Framework Partial Classes in C# Top 50 C# Interview Questions & Answers C# | Data Types Basic CRUD (Create, Read, Update, Delete) in ASP.NET MVC Using C# and Entity Framework C# | Encapsulation
[ { "code": null, "e": 24440, "s": 24412, "text": "\n19 Nov, 2019" }, { "code": null, "e": 24695, "s": 24440, "text": "An array is a collection of the same type variable. Whereas a string is a sequence of Unicode characters or array of characters. Therefore arrays of strings is an array of arrays of characters. Here, string array and arrays of strings both are same term." }, { "code": null, "e": 24863, "s": 24695, "text": "For Example, if you want to store the name of students of a class then you can use the arrays of strings. Arrays of strings can be one dimensional or multidimensional." }, { "code": null, "e": 24954, "s": 24863, "text": "Declaring the string array: There are two ways to declare the arrays of strings as follows" }, { "code": null, "e": 25035, "s": 24954, "text": "Declaration without size:Syntax:String[] variable_name;orstring[] variable_name;" }, { "code": null, "e": 25043, "s": 25035, "text": "Syntax:" }, { "code": null, "e": 25067, "s": 25043, "text": "String[] variable_name;" }, { "code": null, "e": 25070, "s": 25067, "text": "or" }, { "code": null, "e": 25094, "s": 25070, "text": "string[] variable_name;" }, { "code": null, "e": 25236, "s": 25094, "text": "Declaration with size:Syntax:String[] variable_name = new String[provide_size_here];orstring[] variable_name = new string[provide_size_here];" }, { "code": null, "e": 25244, "s": 25236, "text": "Syntax:" }, { "code": null, "e": 25300, "s": 25244, "text": "String[] variable_name = new String[provide_size_here];" }, { "code": null, "e": 25303, "s": 25300, "text": "or" }, { "code": null, "e": 25359, "s": 25303, "text": "string[] variable_name = new string[provide_size_here];" }, { "code": null, "e": 25368, "s": 25359, "text": "Example:" }, { "code": null, "e": 25416, "s": 25368, "text": "// declaration using string keywordstring[] s1;" }, { "code": null, "e": 25508, "s": 25416, "text": "// declaration using String class object// by giving its size 4String[] s2 = new String[4];" }, { "code": null, "e": 25829, "s": 25508, "text": "Initialization of Arrays of Strings: Arrays can be initialized after the declaration. It is not necessary to declare and initialize at the same time using the new keyword. However, Initializing an Array after the declaration, it must be initialized with the new keyword. It can’t be initialized by only assigning values." }, { "code": null, "e": 25838, "s": 25829, "text": "Example:" }, { "code": null, "e": 25886, "s": 25838, "text": "// Declaration of the arraystring[] str1, str2;" }, { "code": null, "e": 26001, "s": 25886, "text": "// Initialization of arraystr1 = new string[5]{ β€œElement 1”, β€œElement 2”, β€œElement 3”, β€œElement 4”, β€œElement 5” };" }, { "code": null, "e": 26089, "s": 26001, "text": "str2 = new string[]{ β€œElement 1”, β€œElement 2”, β€œElement 3”, β€œElement 4”, β€œElement 5” };" }, { "code": null, "e": 26183, "s": 26089, "text": "Note: Initialization without giving size is not valid in C#. It will give compile time error." }, { "code": null, "e": 26236, "s": 26183, "text": "Example: Wrong Declaration for initializing an array" }, { "code": null, "e": 26314, "s": 26236, "text": "// compile-time error: must give size of an arrayString[] str = new String[];" }, { "code": null, "e": 26433, "s": 26314, "text": "// error : wrong initialization of an arraystring[] str1;str1 = {β€œElement 1”, β€œElement 2”, β€œElement 3”, β€œElement 4” };" }, { "code": null, "e": 26756, "s": 26433, "text": "Accessing Arrays of Strings Elements: At the time of initialization, we can assign the value. But, we can also assign the value of array using its index randomly after the declaration and initialization. We can access an array value through indexing, placed index of the element within square brackets with the array name." }, { "code": null, "e": 26765, "s": 26756, "text": "Example:" }, { "code": null, "e": 27120, "s": 26765, "text": "// declares & initializes string array\nString[] s1 = new String[2];\n\n// assign the value \"Geeks\" in array on its index 0\ns1[0] = 10; \n\n// assign the value \"GFG\" in array on its index 1\ns1[1] = 30;\n\n// assign the value \"Noida\" in array on its index 2\ns1[2] = 20;\n\n\n// Accessing array elements using index\ns1[0]; // returns Geeks\ns1[2]; // returns Noida\n" }, { "code": null, "e": 27317, "s": 27120, "text": "Declaration and initialization of string array in a single line: String array can also be declared and initialized in a single line. This method is more recommended as it reduces the line of code." }, { "code": null, "e": 27326, "s": 27317, "text": "Example:" }, { "code": null, "e": 27392, "s": 27326, "text": "String[] weekDays = new string[3] {\"Sun\", \"Mon\", \"Tue\", \"Wed\"}; \n" }, { "code": null, "e": 27468, "s": 27392, "text": "Code#1: String array declaration, initialization and accessing its elements" }, { "code": "// C# program to illustrate the String array // declaration, initialization and accessing // its elementsusing System; class Geeks { // Main Method public static void Main() { // Step 1: Array Declaration string[] stringarr; // Step 2:Array Initialization stringarr = new string[3] {\"Element 1\", \"Element 2\", \"Element 3\"}; // Step 3:Accessing Array Elements Console.WriteLine(stringarr[0]); Console.WriteLine(stringarr[1]); Console.WriteLine(stringarr[2]); }}", "e": 28028, "s": 27468, "text": null }, { "code": null, "e": 28036, "s": 28028, "text": "Output:" }, { "code": null, "e": 28067, "s": 28036, "text": "Element 1\nElement 2\nElement 3\n" }, { "code": null, "e": 28127, "s": 28067, "text": "Code#2: Array declaration and initialization in single line" }, { "code": "// C# code to illustrate Array declaration// and initialization in single lineusing System; class Geeks { // Main Method public static void Main() { // array initialization and declaration String[] stringarr = new String[] {\"Geeks\", \"GFG\", \"Noida\"}; // accessing array elements Console.WriteLine(stringarr[0]); Console.WriteLine(stringarr[1]); Console.WriteLine(stringarr[2]); }}", "e": 28567, "s": 28127, "text": null }, { "code": null, "e": 28575, "s": 28567, "text": "Output:" }, { "code": null, "e": 28592, "s": 28575, "text": "Geeks\nGFG\nNoida\n" }, { "code": null, "e": 28598, "s": 28592, "text": "Note:" }, { "code": null, "e": 29017, "s": 28598, "text": "In the public static void main(String[] args), String[] args is also an array of string.Example: To show String[] args is an array of string.// C# program to get the type of \"args\"using System; class GFG { // Main Method static public void Main (String[] args) { // using GetType() method to // get type at runtime Console.WriteLine(args.GetType()); }}Output:System.String[]\n" }, { "code": null, "e": 29071, "s": 29017, "text": "Example: To show String[] args is an array of string." }, { "code": "// C# program to get the type of \"args\"using System; class GFG { // Main Method static public void Main (String[] args) { // using GetType() method to // get type at runtime Console.WriteLine(args.GetType()); }}", "e": 29326, "s": 29071, "text": null }, { "code": null, "e": 29334, "s": 29326, "text": "Output:" }, { "code": null, "e": 29351, "s": 29334, "text": "System.String[]\n" }, { "code": null, "e": 29401, "s": 29351, "text": "C# string array is basically an array of objects." }, { "code": null, "e": 30174, "s": 29401, "text": "It doesn’t matter whether you are creating an array of string using string keyword or String class object. Both are same.Example:// C# program to get the type of arrays of // strings which are declared using 'string'// keyword and 'String class object'using System; class GFG { // Main Method static public void Main (String[] args) { // declaring array of string // using string keyword string[] s1 = {\"GFG\", \"Noida\"}; // declaring array of string // using String class object String[] s2 = new String[2]{\"Geeks\", \"C#\"}; // using GetType() method to // get type at runtime Console.WriteLine(s1.GetType()); Console.WriteLine(s2.GetType()); }}Output:System.String[]\nSystem.String[]\n" }, { "code": null, "e": 30183, "s": 30174, "text": "Example:" }, { "code": "// C# program to get the type of arrays of // strings which are declared using 'string'// keyword and 'String class object'using System; class GFG { // Main Method static public void Main (String[] args) { // declaring array of string // using string keyword string[] s1 = {\"GFG\", \"Noida\"}; // declaring array of string // using String class object String[] s2 = new String[2]{\"Geeks\", \"C#\"}; // using GetType() method to // get type at runtime Console.WriteLine(s1.GetType()); Console.WriteLine(s2.GetType()); }}", "e": 30788, "s": 30183, "text": null }, { "code": null, "e": 30796, "s": 30788, "text": "Output:" }, { "code": null, "e": 30829, "s": 30796, "text": "System.String[]\nSystem.String[]\n" }, { "code": null, "e": 30843, "s": 30829, "text": "shubham_singh" }, { "code": null, "e": 30857, "s": 30843, "text": "CSharp-Arrays" }, { "code": null, "e": 30871, "s": 30857, "text": "CSharp-string" }, { "code": null, "e": 30878, "s": 30871, "text": "Picked" }, { "code": null, "e": 30881, "s": 30878, "text": "C#" }, { "code": null, "e": 30979, "s": 30881, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30988, "s": 30979, "text": "Comments" }, { "code": null, "e": 31001, "s": 30988, "text": "Old Comments" }, { "code": null, "e": 31019, "s": 31001, "text": "C# | Constructors" }, { "code": null, "e": 31041, "s": 31019, "text": "C# | Class and Object" }, { "code": null, "e": 31056, "s": 31041, "text": "C# | Delegates" }, { "code": null, "e": 31079, "s": 31056, "text": "Extension Method in C#" }, { "code": null, "e": 31110, "s": 31079, "text": "Introduction to .NET Framework" }, { "code": null, "e": 31132, "s": 31110, "text": "Partial Classes in C#" }, { "code": null, "e": 31172, "s": 31132, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 31188, "s": 31172, "text": "C# | Data Types" }, { "code": null, "e": 31275, "s": 31188, "text": "Basic CRUD (Create, Read, Update, Delete) in ASP.NET MVC Using C# and Entity Framework" } ]
A NumPy affair: Broadcasting. This article explores the concept of... | by Richmond Alake | Towards Data Science
This article explores the concept of Broadcasting that is utilized in the scientific computing package that is NumPy. We will introduce the concept of Broadcasting by giving a simple definition, along with some examples to illustrate how Broadcasting is implemented in Python by leveraging NumPy arrays. A further detailed explanation will be provided along with a more in-depth definition of what Broadcasting is, its rules, benefits, and limitations. Broadcasting is the methodology adopted in NumPy used to perform arithmetic operations on arrays with differing dimensions. General arithmetic operations such as addition, multiplication, subtraction, etc. tend to broadcast arrays before performing the operations on arrays with variations in size. To provide a context of reasoning for the definition above, the code below depicts how an arithmetic operation would work without broadcasting example #1 and the same arithmetic operation is shown in examples #2, but this time with broadcasting. Example #1 β€” A world without broadcasting import numpy as npa = np.array([1,2,3], dtype=float)b = 5c = np.empty([3])for idx, i in enumerate(a): c[idx] = i * bprint(c)>> [5. 10. 15.] In example #1 we have a NumPy array containing three elements: 1, 2, and 3; this array is assigned to the variable β€˜a’. Variable β€˜b’ is assigned to the scalar 5, and β€˜c’ is initialized as an empty array that has 3 elements. The shape of β€˜c’ is the predetermined expected shape of the result of an arithmetic operation between β€˜a’ and β€˜b’. The arithmetic operation performed is a multiplication. In this operation, the scalar β€˜b’ is multiplied by each element in the array β€˜a’. In more technical terms, we are performing an element-wise operation between the values held in the variables β€˜a’ and β€˜b’. To perform an element-wise operation, we iterate through the array β€˜a’ and multiply each element with the scalar held in β€˜b’. The operation result is placed in the variable β€˜c’ at a corresponding index position of the element within β€˜a’. So a multiplication of the element in index 0 in β€˜a’ (a[0] = 2) and the scalar held in β€˜b’ will be placed at index 1 in β€˜c’ (c[0] = 1* 5 = 5). Example #2 β€” A world with Broadcasting import numpy as npa = np.array([1,2,3], dtype=float)b = 5c = a * bprint(c)>> [5. 10. 15.] In example #2 we can see that we have less written code, and also we do not require a loop to achieve the same operation result as example #1. This is due to the utilization of broadcasting to perform the arithmetic operation. The diagram above depicts visually what is occurring in example #2. An arithmetic operation between an array and a scalar is the simplest method of explaining how broadcasting works. In example #2, the scalar value 5 assigned to variable β€˜b’ has been β€˜broadcast’ to all the elements in the array in variable β€˜a’. In layman terms, the value 5 has been duplicated several times to match the dimensions of the shape of the array β€˜a’, to enable suitable conditions for the execution of the operations. Redefining broadcasting more purposefully and intuitively, we can come up with a description that is as follows: Broadcasting is a method used in python that provides a wrapper for array operations that enables the optimization of loop-based operations through vectorization. β€˜Wrapper’ refers to the fact that the operation carried out through broadcasting is one that is abstracted through python, as the actual executing occurs in a lower-level language, namely C. β€˜Vectorization’ refers to an operation that is performed over several elements without any modification to the operation. This operation could be a multiplication arithmetic operation shown in example #2. Earlier on, we stated that the scalar value in example #2 is β€˜duplicated’ to match the dimensions of the array in variable β€˜a’ for the objective of both data having the same dimensions to enable suitable element-wise operation. This is not entirely correct. What’s happening is not duplication, but instead, the iterator over the extended dimension does not actually move, or rather iterate. To give a more simplistic description of what is occurring, the scalar β€˜5’ or any data value, be it an array, that is extended to meet the dimensions of another array, has an iterator that simply does not move during the broadcasting operation. This occurs because the stride of the iterator of the scalar 5 in variable β€˜b’ is set to 0 in NumPy core. The following images below show the time sequence of the iteration operation between the data values held in variable β€˜a’ and β€˜b’, and also, the operation result at each time step is shown. Now we understand at some level how broadcasting works in NumPy. To further hone in on what broadcasting is and how it is utilized, we will explore rules and conditions that enable suitable broadcasting, along with practical examples of how broadcasting can be leveraged. Broadcasting rules and conditions: For a set of arrays to be deemed β€˜broadcastable’, there are a set of conditions that are met. The shape of the arrays are the same or the ending dimensions for both arrays matchIf an array has a different number of dimension to the another array, then the array with the lesser dimension is extended by 1 until the number of dimension of both arrays are equalIf two arrays are to be broadcastable, then the array with dimension size of 1 is to behave in a manner that enables the array with lesser dimension to be expanded by duplication to the length of the second array. The shape of the arrays are the same or the ending dimensions for both arrays match If an array has a different number of dimension to the another array, then the array with the lesser dimension is extended by 1 until the number of dimension of both arrays are equal If two arrays are to be broadcastable, then the array with dimension size of 1 is to behave in a manner that enables the array with lesser dimension to be expanded by duplication to the length of the second array. Condition #1 # Condition 1: The shape of the arrays are the same or the ending dimensions for both arrays matchx = np.array([3,2,1])y = np.array([6,5,2])z = x * yprint(x.shape)>> (3,)print(y.shape)>> (3,)print(x.shape == y.shape)>> Trueprint(z)>> [18 10 2] Condition #2 x = np.random.randn(4,3)y = np.arange(4).reshape((4,1))print(x.shape)>> (4,3)print(y.shape)>> (4,1)z = x * yprint(z)>>[[-0. -0. 0. ] [ 2.2984589 0.27385878 -1.17348763] [-1.96979462 -4.9748125 0.65956746] [-1.24697399 0.80710713 1.61002339]] Condition #3 x = np.random.randn(5,4)y = np.random.randn(1,4)# The array 'x' has a length of 5 and the array 'y' has length of 1, by following condition 3, the array 'y' has been stretched 5 times to match the array 'x' during broadcasting.print(len(x))>> 5print(len(y))>> 1print(x + y)>>[[-0.99329397 -0.98391026 0.85963453 0.28137122] [-2.17210589 0.99278479 1.98294275 1.11116366] [ 0.92228273 -0.39603659 1.99637842 2.31311734] [-1.29068518 0.22292541 1.56178367 2.07585643] [ 2.42435639 -0.07977165 0.28020364 1.42663066]] Lastly, broadcasting provides some benefits in terms of efficiency as the looping that occurs in broadcasting happens in C as opposed to Python; this means that instructions are not interpreted before execution in the CPU, thus increasing efficiency. Also, as shown in the diagram earlier that illustrates how broadcasting works, we can observe the memory efficiency provided by broadcasting as we do not make needless copies of data. Broadcasting can be useful in practice, especially in data analysis. An example is when tasked with demeaning data, we can leverage broadcasting. Demeaning data is making the mean of a group of dataset zero, by subtracting each element of the dataset by the mean of the grouped of the dataset. The code snippet provides how this is implemented. # Broadcasting can be used for demeaning data.# Demeaning is the process of making the mean of a group of data zero by subtracting each element of the data by the mean of the grouped data.arr = np.array([[1,2,3], [4,5,6], [7,8,9], [10,11,12]])# Take the mean of each column within the arrayarr_mean = arr.mean(0)# Now we use broadcasting to perform element wise subtraction between the array and the meandemeaned_data = arr - arr_mean# To prove that array has been demeaned, we should get a mean of zero for each column when computing the meandemeaned_data.mean(0)>> array([0., 0., 0.]) Feel free to learn more about broadcasting from the links provided below.
[ { "code": null, "e": 290, "s": 172, "text": "This article explores the concept of Broadcasting that is utilized in the scientific computing package that is NumPy." }, { "code": null, "e": 625, "s": 290, "text": "We will introduce the concept of Broadcasting by giving a simple definition, along with some examples to illustrate how Broadcasting is implemented in Python by leveraging NumPy arrays. A further detailed explanation will be provided along with a more in-depth definition of what Broadcasting is, its rules, benefits, and limitations." }, { "code": null, "e": 924, "s": 625, "text": "Broadcasting is the methodology adopted in NumPy used to perform arithmetic operations on arrays with differing dimensions. General arithmetic operations such as addition, multiplication, subtraction, etc. tend to broadcast arrays before performing the operations on arrays with variations in size." }, { "code": null, "e": 1170, "s": 924, "text": "To provide a context of reasoning for the definition above, the code below depicts how an arithmetic operation would work without broadcasting example #1 and the same arithmetic operation is shown in examples #2, but this time with broadcasting." }, { "code": null, "e": 1212, "s": 1170, "text": "Example #1 β€” A world without broadcasting" }, { "code": null, "e": 1355, "s": 1212, "text": "import numpy as npa = np.array([1,2,3], dtype=float)b = 5c = np.empty([3])for idx, i in enumerate(a): c[idx] = i * bprint(c)>> [5. 10. 15.]" }, { "code": null, "e": 1694, "s": 1355, "text": "In example #1 we have a NumPy array containing three elements: 1, 2, and 3; this array is assigned to the variable β€˜a’. Variable β€˜b’ is assigned to the scalar 5, and β€˜c’ is initialized as an empty array that has 3 elements. The shape of β€˜c’ is the predetermined expected shape of the result of an arithmetic operation between β€˜a’ and β€˜b’." }, { "code": null, "e": 1955, "s": 1694, "text": "The arithmetic operation performed is a multiplication. In this operation, the scalar β€˜b’ is multiplied by each element in the array β€˜a’. In more technical terms, we are performing an element-wise operation between the values held in the variables β€˜a’ and β€˜b’." }, { "code": null, "e": 2336, "s": 1955, "text": "To perform an element-wise operation, we iterate through the array β€˜a’ and multiply each element with the scalar held in β€˜b’. The operation result is placed in the variable β€˜c’ at a corresponding index position of the element within β€˜a’. So a multiplication of the element in index 0 in β€˜a’ (a[0] = 2) and the scalar held in β€˜b’ will be placed at index 1 in β€˜c’ (c[0] = 1* 5 = 5)." }, { "code": null, "e": 2375, "s": 2336, "text": "Example #2 β€” A world with Broadcasting" }, { "code": null, "e": 2465, "s": 2375, "text": "import numpy as npa = np.array([1,2,3], dtype=float)b = 5c = a * bprint(c)>> [5. 10. 15.]" }, { "code": null, "e": 2692, "s": 2465, "text": "In example #2 we can see that we have less written code, and also we do not require a loop to achieve the same operation result as example #1. This is due to the utilization of broadcasting to perform the arithmetic operation." }, { "code": null, "e": 3190, "s": 2692, "text": "The diagram above depicts visually what is occurring in example #2. An arithmetic operation between an array and a scalar is the simplest method of explaining how broadcasting works. In example #2, the scalar value 5 assigned to variable β€˜b’ has been β€˜broadcast’ to all the elements in the array in variable β€˜a’. In layman terms, the value 5 has been duplicated several times to match the dimensions of the shape of the array β€˜a’, to enable suitable conditions for the execution of the operations." }, { "code": null, "e": 3466, "s": 3190, "text": "Redefining broadcasting more purposefully and intuitively, we can come up with a description that is as follows: Broadcasting is a method used in python that provides a wrapper for array operations that enables the optimization of loop-based operations through vectorization." }, { "code": null, "e": 3657, "s": 3466, "text": "β€˜Wrapper’ refers to the fact that the operation carried out through broadcasting is one that is abstracted through python, as the actual executing occurs in a lower-level language, namely C." }, { "code": null, "e": 3862, "s": 3657, "text": "β€˜Vectorization’ refers to an operation that is performed over several elements without any modification to the operation. This operation could be a multiplication arithmetic operation shown in example #2." }, { "code": null, "e": 4120, "s": 3862, "text": "Earlier on, we stated that the scalar value in example #2 is β€˜duplicated’ to match the dimensions of the array in variable β€˜a’ for the objective of both data having the same dimensions to enable suitable element-wise operation. This is not entirely correct." }, { "code": null, "e": 4795, "s": 4120, "text": "What’s happening is not duplication, but instead, the iterator over the extended dimension does not actually move, or rather iterate. To give a more simplistic description of what is occurring, the scalar β€˜5’ or any data value, be it an array, that is extended to meet the dimensions of another array, has an iterator that simply does not move during the broadcasting operation. This occurs because the stride of the iterator of the scalar 5 in variable β€˜b’ is set to 0 in NumPy core. The following images below show the time sequence of the iteration operation between the data values held in variable β€˜a’ and β€˜b’, and also, the operation result at each time step is shown." }, { "code": null, "e": 5067, "s": 4795, "text": "Now we understand at some level how broadcasting works in NumPy. To further hone in on what broadcasting is and how it is utilized, we will explore rules and conditions that enable suitable broadcasting, along with practical examples of how broadcasting can be leveraged." }, { "code": null, "e": 5102, "s": 5067, "text": "Broadcasting rules and conditions:" }, { "code": null, "e": 5196, "s": 5102, "text": "For a set of arrays to be deemed β€˜broadcastable’, there are a set of conditions that are met." }, { "code": null, "e": 5675, "s": 5196, "text": "The shape of the arrays are the same or the ending dimensions for both arrays matchIf an array has a different number of dimension to the another array, then the array with the lesser dimension is extended by 1 until the number of dimension of both arrays are equalIf two arrays are to be broadcastable, then the array with dimension size of 1 is to behave in a manner that enables the array with lesser dimension to be expanded by duplication to the length of the second array." }, { "code": null, "e": 5759, "s": 5675, "text": "The shape of the arrays are the same or the ending dimensions for both arrays match" }, { "code": null, "e": 5942, "s": 5759, "text": "If an array has a different number of dimension to the another array, then the array with the lesser dimension is extended by 1 until the number of dimension of both arrays are equal" }, { "code": null, "e": 6156, "s": 5942, "text": "If two arrays are to be broadcastable, then the array with dimension size of 1 is to behave in a manner that enables the array with lesser dimension to be expanded by duplication to the length of the second array." }, { "code": null, "e": 6169, "s": 6156, "text": "Condition #1" }, { "code": null, "e": 6413, "s": 6169, "text": "# Condition 1: The shape of the arrays are the same or the ending dimensions for both arrays matchx = np.array([3,2,1])y = np.array([6,5,2])z = x * yprint(x.shape)>> (3,)print(y.shape)>> (3,)print(x.shape == y.shape)>> Trueprint(z)>> [18 10 2]" }, { "code": null, "e": 6426, "s": 6413, "text": "Condition #2" }, { "code": null, "e": 6698, "s": 6426, "text": "x = np.random.randn(4,3)y = np.arange(4).reshape((4,1))print(x.shape)>> (4,3)print(y.shape)>> (4,1)z = x * yprint(z)>>[[-0. -0. 0. ] [ 2.2984589 0.27385878 -1.17348763] [-1.96979462 -4.9748125 0.65956746] [-1.24697399 0.80710713 1.61002339]]" }, { "code": null, "e": 6711, "s": 6698, "text": "Condition #3" }, { "code": null, "e": 7238, "s": 6711, "text": "x = np.random.randn(5,4)y = np.random.randn(1,4)# The array 'x' has a length of 5 and the array 'y' has length of 1, by following condition 3, the array 'y' has been stretched 5 times to match the array 'x' during broadcasting.print(len(x))>> 5print(len(y))>> 1print(x + y)>>[[-0.99329397 -0.98391026 0.85963453 0.28137122] [-2.17210589 0.99278479 1.98294275 1.11116366] [ 0.92228273 -0.39603659 1.99637842 2.31311734] [-1.29068518 0.22292541 1.56178367 2.07585643] [ 2.42435639 -0.07977165 0.28020364 1.42663066]]" }, { "code": null, "e": 7673, "s": 7238, "text": "Lastly, broadcasting provides some benefits in terms of efficiency as the looping that occurs in broadcasting happens in C as opposed to Python; this means that instructions are not interpreted before execution in the CPU, thus increasing efficiency. Also, as shown in the diagram earlier that illustrates how broadcasting works, we can observe the memory efficiency provided by broadcasting as we do not make needless copies of data." }, { "code": null, "e": 8018, "s": 7673, "text": "Broadcasting can be useful in practice, especially in data analysis. An example is when tasked with demeaning data, we can leverage broadcasting. Demeaning data is making the mean of a group of dataset zero, by subtracting each element of the dataset by the mean of the grouped of the dataset. The code snippet provides how this is implemented." }, { "code": null, "e": 8650, "s": 8018, "text": "# Broadcasting can be used for demeaning data.# Demeaning is the process of making the mean of a group of data zero by subtracting each element of the data by the mean of the grouped data.arr = np.array([[1,2,3], [4,5,6], [7,8,9], [10,11,12]])# Take the mean of each column within the arrayarr_mean = arr.mean(0)# Now we use broadcasting to perform element wise subtraction between the array and the meandemeaned_data = arr - arr_mean# To prove that array has been demeaned, we should get a mean of zero for each column when computing the meandemeaned_data.mean(0)>> array([0., 0., 0.])" } ]
Protractor - Writing the First Test
In this chapter, let us understand how to write the first test in Protractor. Protractor needs the following two files to run βˆ’ It is one of the important files to run Protractor. In this file, we will write our actual test code. The test code is written by using the syntax of our testing framework. For example, if we are using Jasmine framework, then the test code will be written by using the syntax of Jasmine. This file will contain all the functional flows and assertions of the test. In simple words, we can say that this file contains the logic and locators to interact with the application. The following is a simple script, TestSpecification.js, having the test case to navigate to an URL and check for the page title βˆ’ //TestSpecification.js describe('Protractor Demo', function() { it('to check the page title', function() { browser.ignoreSynchronization = true; browser.get('https://www.tutorialspoint.com/tutorialslibrary.htm'); browser.driver.getTitle().then(function(pageTitle) { expect(pageTitle).toEqual('Free Online Tutorials and Courses'); }); }); }); The code of above specification file can be explained as follows βˆ’ It is the global variable created by Protractor to handle all the browser level commands. It is basically a wrapper around an instance of WebDriver. browser.get() is a simple Selenium method that will tell Protractor to load a particular page. describe and it βˆ’ Both are the syntaxes of Jasmine test framework. The ’Describe’ is used to contain the end to end flow of our test case whereas β€˜it’ contains some of the test scenarios. We can have multiple β€˜it’ blocks in our test case program. describe and it βˆ’ Both are the syntaxes of Jasmine test framework. The ’Describe’ is used to contain the end to end flow of our test case whereas β€˜it’ contains some of the test scenarios. We can have multiple β€˜it’ blocks in our test case program. Expect βˆ’ It is an assertion where we are comparing the web page title with some predefined data. Expect βˆ’ It is an assertion where we are comparing the web page title with some predefined data. ignoreSynchronization βˆ’ It is a tag of browser which is used when we will try to test non-angular websites. Protractor expects to work with angular websites only but if we want to work with non-angular websites, then this tag must be set to β€œtrue”. ignoreSynchronization βˆ’ It is a tag of browser which is used when we will try to test non-angular websites. Protractor expects to work with angular websites only but if we want to work with non-angular websites, then this tag must be set to β€œtrue”. As the name suggests, this file provides explanations for all the Protractor configuration options. It basically tells Protractor the following βˆ’ Where to find the test or specs files Which browser to pick Which testing framework to use Where to talk with the Selenium Server The following is the simple script, config.js, having the test // config.js exports.config = { directConnect: true, // Capabilities to be passed to the webdriver instance. capabilities: { 'browserName': 'chrome' }, // Framework to use. Jasmine is recommended. framework: 'jasmine', // Spec patterns are relative to the current working directory when // protractor is called. specs: ['TestSpecification.js'], The code of above configuration file having three basic parameters, can be explained as follows βˆ’ This parameter is used to specify the name of the browser. It can be seen in the following code block of conf.js file βˆ’ exports.config = { directConnect: true, // Capabilities to be passed to the webdriver instance. capabilities: { 'browserName': 'chrome' }, As seen above, the name of the browser given here is β€˜chrome’ which is by default browser for Protractor. We can also change the name of the browser. This parameter is used to specify the name of the testing framework. It can be seen in the following code block of config.js file βˆ’ exports.config = { directConnect: true, // Framework to use. Jasmine is recommended. framework: 'jasmine', Here we are using β€˜jasmine’ test framework. This parameter is used to specify the name of the source file declaration. It can be seen in the following code block of conf.js file βˆ’ exports.config = { directConnect: true, // Spec patterns are relative to the current working directory when protractor is called. specs: ['TsetSpecification.js'], As seen above, the name of the source file declaration given here is β€˜TestSpecification.js’. It is because, for this example we have created the specification file with name TestSpecification.js. As we have got basic understanding about the necessary files and their coding for running Protractor, let us try to run the example. We can follow the following steps to execute this example βˆ’ Step 1 βˆ’ First, open command prompt. Step 1 βˆ’ First, open command prompt. Step 2 βˆ’ Next, we need go to the directory where we have saved our files namely config.js and TestSpecification.js. Step 2 βˆ’ Next, we need go to the directory where we have saved our files namely config.js and TestSpecification.js. Step 3 βˆ’ Now, execute the config.js file by running the command Protrcator config.js. Step 3 βˆ’ Now, execute the config.js file by running the command Protrcator config.js. The screen shot shown below will explain the above steps for executing the example βˆ’ It is seen in the screen shot that the test has been passed. Now, suppose if we are testing non-angular websites and not putting the ignoreSynchronization tag to true then after executing the code we will get the error” Angular could not be found on the page”. It can be seen in the following screen shot βˆ’ Till now, we have discussed about the necessary files and their coding for running test cases. Protractor is also able to generate the report for test cases. For this purpose, it supports Jasmine. JunitXMLReporter can be used to generate test execution reports automatically. But before that, we need to install Jasmine reporter with the help of following command βˆ’ npm install -g jasmine-reporters As you can see, -g option is used while installing Jasmine Reporters, it is because we have installed Protractor globally, with -g option. After successfully installing jasmine-reporters, we need to add the following code into our previously used config.js file βˆ’ onPrepare: function(){ //configure junit xml report var jasmineReporters = require('jasmine-reporters'); jasmine.getEnv().addReporter(new jasmineReporters.JUnitXmlReporter({ consolidateAll: true, filePrefix: 'guitest-xmloutput', savePath: 'test/reports' })); Now, our new config.js file would be as follows βˆ’ // An example configuration file. exports.config = { directConnect: true, // Capabilities to be passed to the webdriver instance. capabilities: { 'browserName': 'chrome' }, // Framework to use. Jasmine is recommended. framework: 'jasmine', // Spec patterns are relative to the current working directory when // protractor is called. specs: ['TestSpecification.js'], //framework: "jasmine2", //must set it if you use JUnitXmlReporter onPrepare: function(){ //configure junit xml report var jasmineReporters = require('jasmine-reporters'); jasmine.getEnv().addReporter(new jasmineReporters.JUnitXmlReporter({ consolidateAll: true, filePrefix: 'guitest-xmloutput', savePath: 'reports' })); }, }; After running the above config file in the same way, we have run previously, it will generate an XML file containing the report under the root directory in reports folder. If the test got successful, the report will look like below βˆ’ But, if the test failed, the report will look as shown below βˆ’ 35 Lectures 3.5 hours SAYANTAN TARAFDAR 18 Lectures 3 hours LuckyTrainings Print Add Notes Bookmark this page
[ { "code": null, "e": 1969, "s": 1891, "text": "In this chapter, let us understand how to write the first test in Protractor." }, { "code": null, "e": 2019, "s": 1969, "text": "Protractor needs the following two files to run βˆ’" }, { "code": null, "e": 2192, "s": 2019, "text": "It is one of the important files to run Protractor. In this file, we will write our actual test code. The test code is written by using the syntax of our testing framework." }, { "code": null, "e": 2383, "s": 2192, "text": "For example, if we are using Jasmine framework, then the test code will be written by using the syntax of Jasmine. This file will contain all the functional flows and assertions of the test." }, { "code": null, "e": 2492, "s": 2383, "text": "In simple words, we can say that this file contains the logic and locators to interact with the application." }, { "code": null, "e": 2622, "s": 2492, "text": "The following is a simple script, TestSpecification.js, having the test case to navigate to an URL and check for the page title βˆ’" }, { "code": null, "e": 3003, "s": 2622, "text": "//TestSpecification.js\ndescribe('Protractor Demo', function() {\n it('to check the page title', function() {\n browser.ignoreSynchronization = true;\n browser.get('https://www.tutorialspoint.com/tutorialslibrary.htm');\n browser.driver.getTitle().then(function(pageTitle) {\n expect(pageTitle).toEqual('Free Online Tutorials and Courses');\n });\n });\n});" }, { "code": null, "e": 3070, "s": 3003, "text": "The code of above specification file can be explained as follows βˆ’" }, { "code": null, "e": 3314, "s": 3070, "text": "It is the global variable created by Protractor to handle all the browser level commands. It is basically a wrapper around an instance of WebDriver. browser.get() is a simple Selenium method that will tell Protractor to load a particular page." }, { "code": null, "e": 3561, "s": 3314, "text": "describe and it βˆ’ Both are the syntaxes of Jasmine test framework. The ’Describe’ is used to contain the end to end flow of our test case whereas β€˜it’ contains some of the test scenarios. We can have multiple β€˜it’ blocks in our test case program." }, { "code": null, "e": 3808, "s": 3561, "text": "describe and it βˆ’ Both are the syntaxes of Jasmine test framework. The ’Describe’ is used to contain the end to end flow of our test case whereas β€˜it’ contains some of the test scenarios. We can have multiple β€˜it’ blocks in our test case program." }, { "code": null, "e": 3905, "s": 3808, "text": "Expect βˆ’ It is an assertion where we are comparing the web page title with some predefined data." }, { "code": null, "e": 4002, "s": 3905, "text": "Expect βˆ’ It is an assertion where we are comparing the web page title with some predefined data." }, { "code": null, "e": 4251, "s": 4002, "text": "ignoreSynchronization βˆ’ It is a tag of browser which is used when we will try to test non-angular websites. Protractor expects to work with angular websites only but if we want to work with non-angular websites, then this tag must be set to β€œtrue”." }, { "code": null, "e": 4500, "s": 4251, "text": "ignoreSynchronization βˆ’ It is a tag of browser which is used when we will try to test non-angular websites. Protractor expects to work with angular websites only but if we want to work with non-angular websites, then this tag must be set to β€œtrue”." }, { "code": null, "e": 4646, "s": 4500, "text": "As the name suggests, this file provides explanations for all the Protractor configuration options. It basically tells Protractor the following βˆ’" }, { "code": null, "e": 4684, "s": 4646, "text": "Where to find the test or specs files" }, { "code": null, "e": 4706, "s": 4684, "text": "Which browser to pick" }, { "code": null, "e": 4737, "s": 4706, "text": "Which testing framework to use" }, { "code": null, "e": 4776, "s": 4737, "text": "Where to talk with the Selenium Server" }, { "code": null, "e": 4839, "s": 4776, "text": "The following is the simple script, config.js, having the test" }, { "code": null, "e": 5220, "s": 4839, "text": "// config.js\nexports.config = {\n directConnect: true,\n\n // Capabilities to be passed to the webdriver instance.\n capabilities: {\n 'browserName': 'chrome'\n },\n\n // Framework to use. Jasmine is recommended.\n framework: 'jasmine',\n\n // Spec patterns are relative to the current working directory when\n // protractor is called.\n specs: ['TestSpecification.js']," }, { "code": null, "e": 5318, "s": 5220, "text": "The code of above configuration file having three basic parameters, can be explained as follows βˆ’" }, { "code": null, "e": 5438, "s": 5318, "text": "This parameter is used to specify the name of the browser. It can be seen in the following code block of conf.js file βˆ’" }, { "code": null, "e": 5594, "s": 5438, "text": "exports.config = {\n directConnect: true,\n\n // Capabilities to be passed to the webdriver instance.\n capabilities: {\n 'browserName': 'chrome'\n},\n" }, { "code": null, "e": 5744, "s": 5594, "text": "As seen above, the name of the browser given here is β€˜chrome’ which is by default browser for Protractor. We can also change the name of the browser." }, { "code": null, "e": 5876, "s": 5744, "text": "This parameter is used to specify the name of the testing framework. It can be seen in the following code block of config.js file βˆ’" }, { "code": null, "e": 5994, "s": 5876, "text": "exports.config = {\n directConnect: true,\n\n // Framework to use. Jasmine is recommended.\n framework: 'jasmine',\n" }, { "code": null, "e": 6038, "s": 5994, "text": "Here we are using β€˜jasmine’ test framework." }, { "code": null, "e": 6174, "s": 6038, "text": "This parameter is used to specify the name of the source file declaration. It can be seen in the following code block of conf.js file βˆ’" }, { "code": null, "e": 6351, "s": 6174, "text": "exports.config = {\n directConnect: true,\n // Spec patterns are relative to the current working \n directory when protractor is called.\n specs: ['TsetSpecification.js'],\n" }, { "code": null, "e": 6547, "s": 6351, "text": "As seen above, the name of the source file declaration given here is β€˜TestSpecification.js’. It is because, for this example we have created the specification file with name TestSpecification.js." }, { "code": null, "e": 6740, "s": 6547, "text": "As we have got basic understanding about the necessary files and their coding for running Protractor, let us try to run the example. We can follow the following steps to execute this example βˆ’" }, { "code": null, "e": 6777, "s": 6740, "text": "Step 1 βˆ’ First, open command prompt." }, { "code": null, "e": 6814, "s": 6777, "text": "Step 1 βˆ’ First, open command prompt." }, { "code": null, "e": 6930, "s": 6814, "text": "Step 2 βˆ’ Next, we need go to the directory where we have saved our files namely config.js and TestSpecification.js." }, { "code": null, "e": 7046, "s": 6930, "text": "Step 2 βˆ’ Next, we need go to the directory where we have saved our files namely config.js and TestSpecification.js." }, { "code": null, "e": 7133, "s": 7046, "text": "Step 3 βˆ’ Now, execute the config.js file by running the command Protrcator config.js.\n" }, { "code": null, "e": 7220, "s": 7133, "text": "Step 3 βˆ’ Now, execute the config.js file by running the command Protrcator config.js.\n" }, { "code": null, "e": 7305, "s": 7220, "text": "The screen shot shown below will explain the above steps for executing the example βˆ’" }, { "code": null, "e": 7366, "s": 7305, "text": "It is seen in the screen shot that the test has been passed." }, { "code": null, "e": 7566, "s": 7366, "text": "Now, suppose if we are testing non-angular websites and not putting the ignoreSynchronization tag to true then after executing the code we will get the error” Angular could not be found on the page”." }, { "code": null, "e": 7612, "s": 7566, "text": "It can be seen in the following screen shot βˆ’" }, { "code": null, "e": 7888, "s": 7612, "text": "Till now, we have discussed about the necessary files and their coding for running test cases. Protractor is also able to generate the report for test cases. For this purpose, it supports Jasmine. JunitXMLReporter can be used to generate test execution reports automatically." }, { "code": null, "e": 7978, "s": 7888, "text": "But before that, we need to install Jasmine reporter with the help of following command βˆ’" }, { "code": null, "e": 8012, "s": 7978, "text": "npm install -g jasmine-reporters\n" }, { "code": null, "e": 8151, "s": 8012, "text": "As you can see, -g option is used while installing Jasmine Reporters, it is because we have installed Protractor globally, with -g option." }, { "code": null, "e": 8276, "s": 8151, "text": "After successfully installing jasmine-reporters, we need to add the following code into our previously used config.js file βˆ’" }, { "code": null, "e": 8563, "s": 8276, "text": "onPrepare: function(){ //configure junit xml report\n\n var jasmineReporters = require('jasmine-reporters');\n jasmine.getEnv().addReporter(new jasmineReporters.JUnitXmlReporter({\n consolidateAll: true,\n filePrefix: 'guitest-xmloutput',\n savePath: 'test/reports'\n }));" }, { "code": null, "e": 8613, "s": 8563, "text": "Now, our new config.js file would be as follows βˆ’" }, { "code": null, "e": 9398, "s": 8613, "text": "// An example configuration file.\nexports.config = {\n directConnect: true,\n\n // Capabilities to be passed to the webdriver instance.\n capabilities: {\n 'browserName': 'chrome'\n },\n\n // Framework to use. Jasmine is recommended.\n framework: 'jasmine',\n\n // Spec patterns are relative to the current working directory when\n // protractor is called.\n specs: ['TestSpecification.js'],\n //framework: \"jasmine2\", //must set it if you use JUnitXmlReporter\n\n onPrepare: function(){ //configure junit xml report\n\n var jasmineReporters = require('jasmine-reporters');\n jasmine.getEnv().addReporter(new jasmineReporters.JUnitXmlReporter({\n consolidateAll: true,\n filePrefix: 'guitest-xmloutput',\n savePath: 'reports'\n }));\n },\n};" }, { "code": null, "e": 9632, "s": 9398, "text": "After running the above config file in the same way, we have run previously, it will generate an XML file containing the report under the root directory in reports folder. If the test got successful, the report will look like below βˆ’" }, { "code": null, "e": 9695, "s": 9632, "text": "But, if the test failed, the report will look as shown below βˆ’" }, { "code": null, "e": 9730, "s": 9695, "text": "\n 35 Lectures \n 3.5 hours \n" }, { "code": null, "e": 9749, "s": 9730, "text": " SAYANTAN TARAFDAR" }, { "code": null, "e": 9782, "s": 9749, "text": "\n 18 Lectures \n 3 hours \n" }, { "code": null, "e": 9798, "s": 9782, "text": " LuckyTrainings" }, { "code": null, "e": 9805, "s": 9798, "text": " Print" }, { "code": null, "e": 9816, "s": 9805, "text": " Add Notes" } ]
Predict Customer Churn with PySpark and Machine Learning | by Ke Chen | Towards Data Science
Customer churn refers to when a customer ceases his/her relationship with a company. It has a considerable impact on the business’ health and long-term success, as it could significantly lower revenues and profits. According to the statistics by Forrester research, it costs 5 times more to acquire new customers than it does to keep the existing ones. Therefore, it is always worth investing time and resources for companies to identify certain customers who are likely to churn, and addressing those customers before they make the decision of stop using the companies’ services. In this article, we will explore the user logs data of a fictitious music streaming services called Sparkify, and build supervised machine learning models to predict whether a customer is potentially going to churn. We have two datasets for this project: the full dataset with a size of 12GB, and a small subset of the full dataset with a size of 128MB. We will use the 128MB version of the dataset which is small enough to fit into the memory of a local machine as the example in this article. In other to use the full dataset for model training, we may need to deploy a cluster on cloud services like AWS. Let’s take a quick look at all the fields in the dataset: df.printSchema()root |-- artist: string (nullable = true) |-- auth: string (nullable = true) |-- firstName: string (nullable = true) |-- gender: string (nullable = true) |-- itemInSession: long (nullable = true) |-- lastName: string (nullable = true) |-- length: double (nullable = true) |-- level: string (nullable = true) |-- location: string (nullable = true) |-- method: string (nullable = true) |-- page: string (nullable = true) |-- registration: long (nullable = true) |-- sessionId: long (nullable = true) |-- song: string (nullable = true) |-- status: long (nullable = true) |-- ts: long (nullable = true) |-- userAgent: string (nullable = true) |-- userId: string (nullable = true) The page field gives us more details about user behaviors: df.select('page').dropDuplicates().sort('page').show()+--------------------+| page|+--------------------+| About|| Add Friend|| Add to Playlist|| Cancel||Cancellation Conf...|| Downgrade|| Error|| Help|| Home|| Logout|| NextSong|| Roll Advert|| Save Settings|| Settings|| Submit Downgrade|| Submit Upgrade|| Thumbs Down|| Thumbs Up|| Upgrade|+--------------------+ Since userId is our target variable that helps us uniquely identify users, logs with empty userId are not helpful for us to make predictions about which customer would churn. We will drop those records with missing userId from our dataset. df = df.where(col('userId').isNotNull())df.count()278154 Before we can move on to comparing users who churned and those who did not, we first need to think about what we would define as churn. A narrow definition would probably only include people who have deleted their account,which is captured in our data as cases where the page feature takes on the value β€œCancellation Confirmation”. We will use the Cancellation Confirmation event of pages to define churn. We will create a new column β€œChurned” to label churned users for our model. Number of users who have churned 52Number of users who have not churned 173 We can see that we have an imbalanced amount of churn and non-churn class in this dataset. In this case, we will use F1 score for evaluating our model later, as it is less sensitive to a class imbalance compared with Accuracy and Precision. Impact of gender there were 19 percent female users churnedthere were 26 percent male users churned Impact of level (paid/free) there were 23 percent free users churnedthere were 21 percent paid users churned Impact of time users spent on listening songs Impact of number of songs played Impact of number of days since registration Impact of pages viewed Now we are familiarized with the data, we build the features we find promising, combined with the page events to train the model on: user_df.printSchema()root |-- userId: string (nullable = true) |-- churn: long (nullable = true) |-- n_act: long (nullable = false) |-- n_about: long (nullable = true) |-- n_addFriend: long (nullable = true) |-- n_addToPlaylist: long (nullable = true) |-- n_cancel: long (nullable = true) |-- n_downgrade: long (nullable = true) |-- n_error: long (nullable = true) |-- n_help: long (nullable = true) |-- n_home: long (nullable = true) |-- n_logout: long (nullable = true) |-- n_rollAdvert: long (nullable = true) |-- n_saveSettings: long (nullable = true) |-- n_settings: long (nullable = true) |-- n_submitDowngrade: long (nullable = true) |-- n_submitUpgrade: long (nullable = true) |-- n_thumbsDown: long (nullable = true) |-- n_thumbsUp: long (nullable = true) |-- n_upgrade: long (nullable = true) |-- playTime: double (nullable = true) |-- numSongs: long (nullable = false) |-- numArtist: long (nullable = false) |-- active_days: double (nullable = true) |-- numSession: long (nullable = false) |-- encoded_level: double (nullable = true) |-- encoded_gender: double (nullable = true) Multicollinearity increases the standard errors of the coefficients. Increased standard errors, in turn, means that coefficients for some independent variables may be found not to be significantly different from 0. In other words, by over-inflating the standard errors, multicollinearity makes some variables statistically insignificant when they should be significant. Without multicollinearity (and thus, with lower standard errors), those coefficients might be significant. We can see that there are some variable pairs with correlation coefficient over 0.8, which means that those variables are highly correlated. in order to deal with the multicollinearity, we will try two approaches here : Remove correlated features manually PCA Remove correlated feature manually We manually remove those variables with high correlation coefficients in the last heat map, and retain the rest of the features: user_df_m.printSchema()root |-- userId: string (nullable = true) |-- churn: long (nullable = true) |-- n_about: long (nullable = true) |-- n_error: long (nullable = true) |-- n_rollAdvert: long (nullable = true) |-- n_saveSettings: long (nullable = true) |-- n_settings: long (nullable = true) |-- n_submitDowngrade: long (nullable = true) |-- n_submitUpgrade: long (nullable = true) |-- n_thumbsDown: long (nullable = true) |-- n_upgrade: long (nullable = true) |-- active_days: double (nullable = true) |-- numSession: long (nullable = false) |-- encoded_level: double (nullable = true) |-- encoded_gender: double (nullable = true) Transform features with PCA Principal component analysis (PCA) is a statistical analysis technique that transforms possibly correlated variables to orthogonal linearly uncorrelated values. We can use it for applications such as data compression, to get dominant physical processes and to get important features for machine learning. Without losing much information, it reduces the number of features in the original data. When applying PCA, we need to first combine features into a vector, and standardize our data: # Vector Assembleruser_df_pca = user_dfcols = user_df_pca.drop('userId','churn').columnsassembler = VectorAssembler(inputCols=cols, outputCol='Features')user_df_pca = assembler.transform(user_df).select('userId', 'churn','Features')# Standard Scalerscaler= FT.StandardScaler(inputCol='Features', outputCol='scaled_features_1', withStd=True)scalerModel = scaler.fit(user_df_pca)user_df_pca = scalerModel.transform(user_df_pca)user_df_pca.select(['userId','churn', 'scaled_features_1']).show(5, truncate = False)pca = PCA(k=10, inputCol = scaler.getOutputCol(), outputCol="pcaFeatures")pca = pca.fit(user_df_pca)pca_result = pca.transform(user_df_pca).select("userId","churn","pcaFeatures") In order to select a good model for the final tuning, we will compare three different classifier models in Spark’s ML: Logistic Regression Decision Tree Random Forest Split Data into Train and Test sets From the distribution of churn shown in the previous session, we know that this is an imbalanced dataset with only 1/4 of users labeled as churn. To avoid imbalanced results in random split, we first make a train set with sampling by label, then subtract them from the whole dataset to get the test set. # prepare training and test data, sample by labelratio = 0.7train_m = m_features_df.sampleBy('churn', fractions={0:ratio, 1:ratio}, seed=123)test_m = m_features_df.subtract(train_m)train_pca = pca_features_df.sampleBy('churn', fractions={0:ratio, 1:ratio}, seed=123)test_pca = pca_features_df.subtract(train_pca) Logistic Regression # initialize classifierlr = LogisticRegression(maxIter=10)# evaluatorevaluator_1 = MulticlassClassificationEvaluator(metricName='f1')# paramGridparamGrid = ParamGridBuilder() \ .build()crossval_lr = CrossValidator(estimator=lr, evaluator=evaluator_1, estimatorParamMaps=paramGrid, numFolds=3) Evaluate with test dataset: Decision Tree # initialize classifierdtc = DecisionTreeClassifier()# evaluatorevaluator_2 = MulticlassClassificationEvaluator(metricName='f1')# paramGridparamGrid = ParamGridBuilder() \ .build()crossval_dtc = CrossValidator(estimator=dtc, evaluator=evaluator_2, estimatorParamMaps=paramGrid, numFolds=3) Evaluate with test dataset: Random Forest # initialize classifierrfc = RandomForestClassifier()# evaluatorevaluator_3 = MulticlassClassificationEvaluator(metricName='f1')# paramGridparamGrid = ParamGridBuilder() \ .build()crossval_rfc = CrossValidator(estimator=rfc, evaluator=evaluator_3, estimatorParamMaps=paramGrid, numFolds=3) Evaluate with test dataset: Among all three models, the result of PCA outperforms the features after manual dimension reduction. Although the Logistic Regression model gave us a perfect F1 score and accuracy for test dataset, it performs much less satisfying with the training dataset. As the Logistic Regression model also performs not as satisfying with the full dataset, this perfect F1 score could due to chance or simplicity of the model. Therefore, I would chose Random Forest classifier for future implementation, of which both the test and train F1 Score are around 97%. Although there are many other models we could try out in the future, such as Naive Bayes and Linear SVM, the Random Forest model performs pretty well in this case (with 97% F1 score with the small dataset, and with 99.992% F1 score with the full dataset). There are some other improvements that we could work on in the future: A more automatic and robust approach to train and evaluate models Take account of those users who downgraded their services More focus on user behavior features Thanks for reading!
[ { "code": null, "e": 753, "s": 172, "text": "Customer churn refers to when a customer ceases his/her relationship with a company. It has a considerable impact on the business’ health and long-term success, as it could significantly lower revenues and profits. According to the statistics by Forrester research, it costs 5 times more to acquire new customers than it does to keep the existing ones. Therefore, it is always worth investing time and resources for companies to identify certain customers who are likely to churn, and addressing those customers before they make the decision of stop using the companies’ services." }, { "code": null, "e": 969, "s": 753, "text": "In this article, we will explore the user logs data of a fictitious music streaming services called Sparkify, and build supervised machine learning models to predict whether a customer is potentially going to churn." }, { "code": null, "e": 1361, "s": 969, "text": "We have two datasets for this project: the full dataset with a size of 12GB, and a small subset of the full dataset with a size of 128MB. We will use the 128MB version of the dataset which is small enough to fit into the memory of a local machine as the example in this article. In other to use the full dataset for model training, we may need to deploy a cluster on cloud services like AWS." }, { "code": null, "e": 1419, "s": 1361, "text": "Let’s take a quick look at all the fields in the dataset:" }, { "code": null, "e": 2111, "s": 1419, "text": "df.printSchema()root |-- artist: string (nullable = true) |-- auth: string (nullable = true) |-- firstName: string (nullable = true) |-- gender: string (nullable = true) |-- itemInSession: long (nullable = true) |-- lastName: string (nullable = true) |-- length: double (nullable = true) |-- level: string (nullable = true) |-- location: string (nullable = true) |-- method: string (nullable = true) |-- page: string (nullable = true) |-- registration: long (nullable = true) |-- sessionId: long (nullable = true) |-- song: string (nullable = true) |-- status: long (nullable = true) |-- ts: long (nullable = true) |-- userAgent: string (nullable = true) |-- userId: string (nullable = true)" }, { "code": null, "e": 2170, "s": 2111, "text": "The page field gives us more details about user behaviors:" }, { "code": null, "e": 2731, "s": 2170, "text": "df.select('page').dropDuplicates().sort('page').show()+--------------------+| page|+--------------------+| About|| Add Friend|| Add to Playlist|| Cancel||Cancellation Conf...|| Downgrade|| Error|| Help|| Home|| Logout|| NextSong|| Roll Advert|| Save Settings|| Settings|| Submit Downgrade|| Submit Upgrade|| Thumbs Down|| Thumbs Up|| Upgrade|+--------------------+" }, { "code": null, "e": 2971, "s": 2731, "text": "Since userId is our target variable that helps us uniquely identify users, logs with empty userId are not helpful for us to make predictions about which customer would churn. We will drop those records with missing userId from our dataset." }, { "code": null, "e": 3028, "s": 2971, "text": "df = df.where(col('userId').isNotNull())df.count()278154" }, { "code": null, "e": 3360, "s": 3028, "text": "Before we can move on to comparing users who churned and those who did not, we first need to think about what we would define as churn. A narrow definition would probably only include people who have deleted their account,which is captured in our data as cases where the page feature takes on the value β€œCancellation Confirmation”." }, { "code": null, "e": 3510, "s": 3360, "text": "We will use the Cancellation Confirmation event of pages to define churn. We will create a new column β€œChurned” to label churned users for our model." }, { "code": null, "e": 3586, "s": 3510, "text": "Number of users who have churned 52Number of users who have not churned 173" }, { "code": null, "e": 3827, "s": 3586, "text": "We can see that we have an imbalanced amount of churn and non-churn class in this dataset. In this case, we will use F1 score for evaluating our model later, as it is less sensitive to a class imbalance compared with Accuracy and Precision." }, { "code": null, "e": 3844, "s": 3827, "text": "Impact of gender" }, { "code": null, "e": 3927, "s": 3844, "text": "there were 19 percent female users churnedthere were 26 percent male users churned" }, { "code": null, "e": 3955, "s": 3927, "text": "Impact of level (paid/free)" }, { "code": null, "e": 4036, "s": 3955, "text": "there were 23 percent free users churnedthere were 21 percent paid users churned" }, { "code": null, "e": 4082, "s": 4036, "text": "Impact of time users spent on listening songs" }, { "code": null, "e": 4115, "s": 4082, "text": "Impact of number of songs played" }, { "code": null, "e": 4159, "s": 4115, "text": "Impact of number of days since registration" }, { "code": null, "e": 4182, "s": 4159, "text": "Impact of pages viewed" }, { "code": null, "e": 4315, "s": 4182, "text": "Now we are familiarized with the data, we build the features we find promising, combined with the page events to train the model on:" }, { "code": null, "e": 5405, "s": 4315, "text": "user_df.printSchema()root |-- userId: string (nullable = true) |-- churn: long (nullable = true) |-- n_act: long (nullable = false) |-- n_about: long (nullable = true) |-- n_addFriend: long (nullable = true) |-- n_addToPlaylist: long (nullable = true) |-- n_cancel: long (nullable = true) |-- n_downgrade: long (nullable = true) |-- n_error: long (nullable = true) |-- n_help: long (nullable = true) |-- n_home: long (nullable = true) |-- n_logout: long (nullable = true) |-- n_rollAdvert: long (nullable = true) |-- n_saveSettings: long (nullable = true) |-- n_settings: long (nullable = true) |-- n_submitDowngrade: long (nullable = true) |-- n_submitUpgrade: long (nullable = true) |-- n_thumbsDown: long (nullable = true) |-- n_thumbsUp: long (nullable = true) |-- n_upgrade: long (nullable = true) |-- playTime: double (nullable = true) |-- numSongs: long (nullable = false) |-- numArtist: long (nullable = false) |-- active_days: double (nullable = true) |-- numSession: long (nullable = false) |-- encoded_level: double (nullable = true) |-- encoded_gender: double (nullable = true)" }, { "code": null, "e": 5882, "s": 5405, "text": "Multicollinearity increases the standard errors of the coefficients. Increased standard errors, in turn, means that coefficients for some independent variables may be found not to be significantly different from 0. In other words, by over-inflating the standard errors, multicollinearity makes some variables statistically insignificant when they should be significant. Without multicollinearity (and thus, with lower standard errors), those coefficients might be significant." }, { "code": null, "e": 6102, "s": 5882, "text": "We can see that there are some variable pairs with correlation coefficient over 0.8, which means that those variables are highly correlated. in order to deal with the multicollinearity, we will try two approaches here :" }, { "code": null, "e": 6138, "s": 6102, "text": "Remove correlated features manually" }, { "code": null, "e": 6142, "s": 6138, "text": "PCA" }, { "code": null, "e": 6177, "s": 6142, "text": "Remove correlated feature manually" }, { "code": null, "e": 6306, "s": 6177, "text": "We manually remove those variables with high correlation coefficients in the last heat map, and retain the rest of the features:" }, { "code": null, "e": 6940, "s": 6306, "text": "user_df_m.printSchema()root |-- userId: string (nullable = true) |-- churn: long (nullable = true) |-- n_about: long (nullable = true) |-- n_error: long (nullable = true) |-- n_rollAdvert: long (nullable = true) |-- n_saveSettings: long (nullable = true) |-- n_settings: long (nullable = true) |-- n_submitDowngrade: long (nullable = true) |-- n_submitUpgrade: long (nullable = true) |-- n_thumbsDown: long (nullable = true) |-- n_upgrade: long (nullable = true) |-- active_days: double (nullable = true) |-- numSession: long (nullable = false) |-- encoded_level: double (nullable = true) |-- encoded_gender: double (nullable = true)" }, { "code": null, "e": 6968, "s": 6940, "text": "Transform features with PCA" }, { "code": null, "e": 7362, "s": 6968, "text": "Principal component analysis (PCA) is a statistical analysis technique that transforms possibly correlated variables to orthogonal linearly uncorrelated values. We can use it for applications such as data compression, to get dominant physical processes and to get important features for machine learning. Without losing much information, it reduces the number of features in the original data." }, { "code": null, "e": 7456, "s": 7362, "text": "When applying PCA, we need to first combine features into a vector, and standardize our data:" }, { "code": null, "e": 8145, "s": 7456, "text": "# Vector Assembleruser_df_pca = user_dfcols = user_df_pca.drop('userId','churn').columnsassembler = VectorAssembler(inputCols=cols, outputCol='Features')user_df_pca = assembler.transform(user_df).select('userId', 'churn','Features')# Standard Scalerscaler= FT.StandardScaler(inputCol='Features', outputCol='scaled_features_1', withStd=True)scalerModel = scaler.fit(user_df_pca)user_df_pca = scalerModel.transform(user_df_pca)user_df_pca.select(['userId','churn', 'scaled_features_1']).show(5, truncate = False)pca = PCA(k=10, inputCol = scaler.getOutputCol(), outputCol=\"pcaFeatures\")pca = pca.fit(user_df_pca)pca_result = pca.transform(user_df_pca).select(\"userId\",\"churn\",\"pcaFeatures\")" }, { "code": null, "e": 8264, "s": 8145, "text": "In order to select a good model for the final tuning, we will compare three different classifier models in Spark’s ML:" }, { "code": null, "e": 8284, "s": 8264, "text": "Logistic Regression" }, { "code": null, "e": 8298, "s": 8284, "text": "Decision Tree" }, { "code": null, "e": 8312, "s": 8298, "text": "Random Forest" }, { "code": null, "e": 8348, "s": 8312, "text": "Split Data into Train and Test sets" }, { "code": null, "e": 8652, "s": 8348, "text": "From the distribution of churn shown in the previous session, we know that this is an imbalanced dataset with only 1/4 of users labeled as churn. To avoid imbalanced results in random split, we first make a train set with sampling by label, then subtract them from the whole dataset to get the test set." }, { "code": null, "e": 8965, "s": 8652, "text": "# prepare training and test data, sample by labelratio = 0.7train_m = m_features_df.sampleBy('churn', fractions={0:ratio, 1:ratio}, seed=123)test_m = m_features_df.subtract(train_m)train_pca = pca_features_df.sampleBy('churn', fractions={0:ratio, 1:ratio}, seed=123)test_pca = pca_features_df.subtract(train_pca)" }, { "code": null, "e": 8985, "s": 8965, "text": "Logistic Regression" }, { "code": null, "e": 9357, "s": 8985, "text": "# initialize classifierlr = LogisticRegression(maxIter=10)# evaluatorevaluator_1 = MulticlassClassificationEvaluator(metricName='f1')# paramGridparamGrid = ParamGridBuilder() \\ .build()crossval_lr = CrossValidator(estimator=lr, evaluator=evaluator_1, estimatorParamMaps=paramGrid, numFolds=3)" }, { "code": null, "e": 9385, "s": 9357, "text": "Evaluate with test dataset:" }, { "code": null, "e": 9399, "s": 9385, "text": "Decision Tree" }, { "code": null, "e": 9768, "s": 9399, "text": "# initialize classifierdtc = DecisionTreeClassifier()# evaluatorevaluator_2 = MulticlassClassificationEvaluator(metricName='f1')# paramGridparamGrid = ParamGridBuilder() \\ .build()crossval_dtc = CrossValidator(estimator=dtc, evaluator=evaluator_2, estimatorParamMaps=paramGrid, numFolds=3)" }, { "code": null, "e": 9796, "s": 9768, "text": "Evaluate with test dataset:" }, { "code": null, "e": 9810, "s": 9796, "text": "Random Forest" }, { "code": null, "e": 10179, "s": 9810, "text": "# initialize classifierrfc = RandomForestClassifier()# evaluatorevaluator_3 = MulticlassClassificationEvaluator(metricName='f1')# paramGridparamGrid = ParamGridBuilder() \\ .build()crossval_rfc = CrossValidator(estimator=rfc, evaluator=evaluator_3, estimatorParamMaps=paramGrid, numFolds=3)" }, { "code": null, "e": 10207, "s": 10179, "text": "Evaluate with test dataset:" }, { "code": null, "e": 10758, "s": 10207, "text": "Among all three models, the result of PCA outperforms the features after manual dimension reduction. Although the Logistic Regression model gave us a perfect F1 score and accuracy for test dataset, it performs much less satisfying with the training dataset. As the Logistic Regression model also performs not as satisfying with the full dataset, this perfect F1 score could due to chance or simplicity of the model. Therefore, I would chose Random Forest classifier for future implementation, of which both the test and train F1 Score are around 97%." }, { "code": null, "e": 11014, "s": 10758, "text": "Although there are many other models we could try out in the future, such as Naive Bayes and Linear SVM, the Random Forest model performs pretty well in this case (with 97% F1 score with the small dataset, and with 99.992% F1 score with the full dataset)." }, { "code": null, "e": 11085, "s": 11014, "text": "There are some other improvements that we could work on in the future:" }, { "code": null, "e": 11151, "s": 11085, "text": "A more automatic and robust approach to train and evaluate models" }, { "code": null, "e": 11209, "s": 11151, "text": "Take account of those users who downgraded their services" }, { "code": null, "e": 11246, "s": 11209, "text": "More focus on user behavior features" } ]
Predictive Modeling and Multiclass Classification: Tackling the Taarifa Challenge | by Antonio Stark | Towards Data Science
Classification predictive problems are one of the most encountered problems in data science. In this article, we’re going to solve a multiclass classification problem using three main classification families: Nearest Neighbors, Decision Trees, and Support Vector Machines (SVMs). The dataset and original code can be accessed through this GitHub link. This article tackles the same challenge introduced in this article. While this article is a standalone for predictive modeling and multiclass classification, if you are wondering how I cleaned the dataset for use in modeling, you can check out that article as well! (also, if you came straight from that article, feel free to skip this section!) The challenge I’ll use for this article is taken from Drivendata.org. You can think of it as a Kaggle for social impact challenges. You still get the same perks for winning and pretty well-formatted datasets, with the additional benefit that you’ll be making a positive impact on the world! The particular challenge that we’re using for this article is called β€œPump it Up: Data Mining the Water Table.” The challenge is to create a model that will predict the condition of a particular water pump (β€œwaterpoint”) given its many attributes. The data is provided by Taarifa, an open-source API that gathers this data and presents it to the world. If you’re curious about their work and what their datapoints represent, make sure to check out their website (and GitHub!) Our original dataset (as provided by the challenge) had 74,000 data points of 42 features. In the previous article about data preprocessing and exploratory data analysis, we converted that into a dataset of 74,000 data points of 114 features. The increased number of features is mainly from one-hot encoding where we expanded categorical features into multiple features per category. We’ve actually eliminated more than half of the features before one-hot encoding, from 42 features to just 20. One-hot encoding on the remaining 20 features led us to the 114 features we have here. Currently, our test dataset has no labels associated with them. In order to see the accuracy of our models, we need labels for our test dataset as well. So as painful as it is, we’re going to discard the test dataset for now. We can re-use this after we’ve trained all of our models and decided which model we want to use for the final submission. train = df[df.train==True].drop(columns=['train'])X = train.drop(columns=['status_group'])y = train.status_group We’ll create an artificial test dataset from our training data as the train data all have labels. Let’s take a one-third random sample from our training dataset and designate that as our testing set for our models. We can use the train_test_split package from scikit-learn (or, β€œsklearn”). X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.33, random_state=1) Let’s quickly re-check our label balances here. It seems like our random splitting did pretty well! Our output balance is pretty identical to both our training and testing dataset. The output classes are a bit imbalanced, we’ll get to that later. While there are many types of classifiers we can use, they are generally put into these three families: nearest neighbors, decision trees, and support vector machines. We’re going to look at one example model from each family of models. Do note that our task is a multi-class classification problem. While there are ways to do multi-class logistic regression, we’re not doing it here. There are also a lot of relationships between our features. This is either because they correspond to similar aspects (e.g. latitude and longitude), or are results of one-hot encoding. That’s why we won’t be doing a Naive Bayes model here as well. The metric employed by Taarifa is the β€œclassification rate” β€” the percentage of correct classification by the model. Let’s look at the classification rate and run time of each model. # packages required for metricsimport time, mathfrom sklearn.metrics import accuracy_scorecols_results=['family','model','classification_rate','runtime']results = pd.DataFrame(columns=cols_results)results For our Nearest Neighbors classifier, we’ll employ a K-Nearest Neighbor (KNN) model. A KNN is a β€œlazy classifier” β€” it does not build any internal models, but simply β€œstores” all the instances in the training dataset. Therefore, a KNN has no β€œtraining time” β€” instead, it takes a lot of time in prediction. It is especially awful when we have a large dataset and the KNN has to evaluate the distance between the new data point and existing data points. Let’s see how a KNN does in accuracy and time for k = 1 to 9. (Remember a KNN of k=1 is just the nearest neighbor classifier) from sklearn.neighbors import KNeighborsClassifierkVals = range(1,10)knn_names = ['KNN-'+str(k) for k in kVals]for k in kVals: knn = KNeighborsClassifier(n_neighbors=k) knn.fit(X_train, y_train) time_start = time.time() y_pred = knn.predict(X_test) time_run = time.time()-time_start results = results.append(pd.DataFrame([['KNN',knn_names[k-1],accuracy_score(y_test,y_pred),time_run]],columns=cols_results),ignore_index=True)results[results.family=='KNN'] Okay, so we have our KNNs here. Let’s visualize how well they’ve done and how much time they’ve took fig, ax = plt.subplots()ax.plot(kVals,results[results.family=='KNN'].classification_rate,color='blue',marker='o')ax.set_xlabel('k-value for KNN models')ax.set_ylabel('classification rate (blue)')ax2=ax.twinx()ax2.plot(kVals,results[results.family=='KNN'].runtime,color='red',marker='o')ax2.set_ylabel('runtime (seconds; red)')plt.show() The accuracy does fluctuate a bit at first but gradually stabilizes around 67% as we take more neighbors into account. The runtime generally increases linearly with k-value. For our Decision-Tree based model, we’ll create a random forest. Random forest is a method of creating multiple decision trees over a subset of the training dataset and taking the consensus result. Because of this random subsetting method, random forests are resilient to overfitting but takes longer time to train than a single decision tree. Let’s see how random forests of 1 (this is just a single decision tree), 10, 100, and 1,000 trees fare. from sklearn.ensemble import RandomForestClassifierrVals = range(1,4)rf_names = ['RF-'+str(int(math.pow(10,r))) for r in rVals]for r in rVals: clf = RandomForestClassifier(n_estimators=int(math.pow(10,r)),random_state=0) time_start = time.time() clf.fit(X_train,y_train) time_run = time.time()-time_start y_pred=clf.predict(X_test) results = results.append(pd.DataFrame([['RF',rf_names[r-1],accuracy_score(y_test,y_pred),time_run]],columns=cols_results),ignore_index=True) results[results.family=='RF'] Let’s see how they visualize. The runtime increases almost exactly linearly with the number of decision trees in the random forest, as to be expected. The accuracy, however, does not increase much and is in the 80% ballpark. SVMs utilize what’s known as a β€œkernel trick” to create hyperplane separators for your data (i.e. linear separators for non-linear problems). While SVMs β€œcould” overfit in theory, the generalizability of kernels usually makes it resistant from small overfitting. SVMs do tend to take a lot of time, and its success is highly dependent on its kernel. A pure SVM on this dataset (40k data points of 100 features) will take forever to run, so we’ll create a β€œbagged classifier” using the BaggingClassifier library offered by sklearn. The BaggingClassifier will take a base model (for us, the SVM), and train multiple of it on multiple random subsets of the dataset. For us, let’s train 10 SVM models per kernel on 1% of the data (about 400 data points) each time. Let’s see how well our model works for three different kernels: linear, RBF, and sigmoid. The Sklearn SVC library also gives us the poly kernel, but it was taking forever to train even in the reduced dataset, so we’re not doing it here. Let’s also visualize the accuracy and run time of these SVM models. The linear kernel does show the highest accuracy, but it has a horrible training time. Considering that we took a bagging approach that will take at maximum 10% of the data (=10 SVMs of 1% of the dataset each), the accuracy is actually pretty impressive. Let’s compare the accuracy and runtime of all of our models! It seems like random forests give the best results β€” nearly 80% accuracy! A random forest with just 100 trees already achieves one of the best results with only nominal training time. Linear SVMs and KNN models give the next best level of results. But apart from comparing models against each other, how can we β€œobjectively” know how well our models have done? For any classification task, the base case is a random classification scheme. One way to do this is to create a random classifier that will classify the input randomly and compare the results. The random assignment of labels will follow the β€œbase” proportion of the labels given to it at training. from sklearn.dummy import DummyClassifierclf = DummyClassifier(strategy='stratified',random_state=0)clf.fit(X_train,y_train)y_pred = clf.predict(X_test)print('Accuracy of a random classifier is: %.2f%%'%(accuracy_score(y_test,y_pred)*100)) It seems like for a base accuracy of 45%, all of our models have done pretty well in terms of accuracy. Lastly, we come back to the class imbalance problem that we’ve mentioned at the beginning. The imbalance in labels leads classifiers to bias towards the majority label. For our case, it’s towards the β€˜functional’ label. We’ve already seen that a classifier that predicts the β€˜functional’ label for half the time (β€˜functional’ label takes up 54.3% of the dataset) will already achieve 45% accuracy. This is already far better than a uniform random guess of 33% (1/3). Class imbalance may not affect classifiers if the classes are clearly separate from each other, but in most cases, they aren’t. To see whether or not class imbalance affected our models, we can undersample the data. Balanced undersampling means that we take a random sample of our data where the classes are β€˜balanced.’ This can be done using the imblearn library’s RandomUnderSampler class. Think of imblearn as a sklearn library for imbalanced datasets. from imblearn.under_sampling import RandomUnderSamplerrus = RandomUnderSampler(random_state=0)X_rus_train,y_rus_train = rus.fit_resample(X_train,y_train)X_rus_test,y_rus_test = rus.fit_resample(X_test,y_test) While our original X_train had almost 40,000 data points, our undersampled dataset only has about 8,700 data points. Let’s run it through our most successful model β€” random forests β€” and see if undersampling affects our model accuracy. Let’s retrain our most successful models β€” our random forests β€” on this undersampled dataset. rf_rus_names = ['RF_rus-'+str(int(math.pow(10,r))) for r in rVals]for r in rVals: clf = RandomForestClassifier(n_estimators=int(math.pow(10,r)),random_state=0) time_start = time.time() clf.fit(X_rus_train,y_rus_train) time_run = time.time()-time_start y_rus_pred=clf.predict(X_rus_test) results = results.append(pd.DataFrame([['RF',rf_rus_names[r-1],accuracy_score(y_rus_test,y_rus_pred),time_run]],columns=cols_results),ignore_index=True) results[results.family=='RF'] So our model accuracy has decreased from close to 80% to under 70%. A part of this is from the fact that the model has had a reduced dataset to work with. But another factor is that our original Random Forest models were getting a falsely β€œinflated” accuracy due to the majority class bias, which is now gone after classes have been imbalanced. At the same time, balancing of classes does lead to an objectively more accurate model, albeit not a more effective one. The ultimate decision is yours to make β€” would you care about β€œinflated” accuracy, or would these β€œfalse positives” deter you from using the original models? As our β€œfalse positives” may lead us to declare non-functional or in-need-of-repair waterpoints to go unaddressed, we might want to err the other way, but the choice is up to you.
[ { "code": null, "e": 452, "s": 172, "text": "Classification predictive problems are one of the most encountered problems in data science. In this article, we’re going to solve a multiclass classification problem using three main classification families: Nearest Neighbors, Decision Trees, and Support Vector Machines (SVMs)." }, { "code": null, "e": 524, "s": 452, "text": "The dataset and original code can be accessed through this GitHub link." }, { "code": null, "e": 870, "s": 524, "text": "This article tackles the same challenge introduced in this article. While this article is a standalone for predictive modeling and multiclass classification, if you are wondering how I cleaned the dataset for use in modeling, you can check out that article as well! (also, if you came straight from that article, feel free to skip this section!)" }, { "code": null, "e": 1161, "s": 870, "text": "The challenge I’ll use for this article is taken from Drivendata.org. You can think of it as a Kaggle for social impact challenges. You still get the same perks for winning and pretty well-formatted datasets, with the additional benefit that you’ll be making a positive impact on the world!" }, { "code": null, "e": 1409, "s": 1161, "text": "The particular challenge that we’re using for this article is called β€œPump it Up: Data Mining the Water Table.” The challenge is to create a model that will predict the condition of a particular water pump (β€œwaterpoint”) given its many attributes." }, { "code": null, "e": 1637, "s": 1409, "text": "The data is provided by Taarifa, an open-source API that gathers this data and presents it to the world. If you’re curious about their work and what their datapoints represent, make sure to check out their website (and GitHub!)" }, { "code": null, "e": 2219, "s": 1637, "text": "Our original dataset (as provided by the challenge) had 74,000 data points of 42 features. In the previous article about data preprocessing and exploratory data analysis, we converted that into a dataset of 74,000 data points of 114 features. The increased number of features is mainly from one-hot encoding where we expanded categorical features into multiple features per category. We’ve actually eliminated more than half of the features before one-hot encoding, from 42 features to just 20. One-hot encoding on the remaining 20 features led us to the 114 features we have here." }, { "code": null, "e": 2567, "s": 2219, "text": "Currently, our test dataset has no labels associated with them. In order to see the accuracy of our models, we need labels for our test dataset as well. So as painful as it is, we’re going to discard the test dataset for now. We can re-use this after we’ve trained all of our models and decided which model we want to use for the final submission." }, { "code": null, "e": 2680, "s": 2567, "text": "train = df[df.train==True].drop(columns=['train'])X = train.drop(columns=['status_group'])y = train.status_group" }, { "code": null, "e": 2970, "s": 2680, "text": "We’ll create an artificial test dataset from our training data as the train data all have labels. Let’s take a one-third random sample from our training dataset and designate that as our testing set for our models. We can use the train_test_split package from scikit-learn (or, β€œsklearn”)." }, { "code": null, "e": 3058, "s": 2970, "text": "X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.33, random_state=1)" }, { "code": null, "e": 3106, "s": 3058, "text": "Let’s quickly re-check our label balances here." }, { "code": null, "e": 3305, "s": 3106, "text": "It seems like our random splitting did pretty well! Our output balance is pretty identical to both our training and testing dataset. The output classes are a bit imbalanced, we’ll get to that later." }, { "code": null, "e": 3542, "s": 3305, "text": "While there are many types of classifiers we can use, they are generally put into these three families: nearest neighbors, decision trees, and support vector machines. We’re going to look at one example model from each family of models." }, { "code": null, "e": 3690, "s": 3542, "text": "Do note that our task is a multi-class classification problem. While there are ways to do multi-class logistic regression, we’re not doing it here." }, { "code": null, "e": 3938, "s": 3690, "text": "There are also a lot of relationships between our features. This is either because they correspond to similar aspects (e.g. latitude and longitude), or are results of one-hot encoding. That’s why we won’t be doing a Naive Bayes model here as well." }, { "code": null, "e": 4121, "s": 3938, "text": "The metric employed by Taarifa is the β€œclassification rate” β€” the percentage of correct classification by the model. Let’s look at the classification rate and run time of each model." }, { "code": null, "e": 4326, "s": 4121, "text": "# packages required for metricsimport time, mathfrom sklearn.metrics import accuracy_scorecols_results=['family','model','classification_rate','runtime']results = pd.DataFrame(columns=cols_results)results" }, { "code": null, "e": 4544, "s": 4326, "text": "For our Nearest Neighbors classifier, we’ll employ a K-Nearest Neighbor (KNN) model. A KNN is a β€œlazy classifier” β€” it does not build any internal models, but simply β€œstores” all the instances in the training dataset." }, { "code": null, "e": 4779, "s": 4544, "text": "Therefore, a KNN has no β€œtraining time” β€” instead, it takes a lot of time in prediction. It is especially awful when we have a large dataset and the KNN has to evaluate the distance between the new data point and existing data points." }, { "code": null, "e": 4905, "s": 4779, "text": "Let’s see how a KNN does in accuracy and time for k = 1 to 9. (Remember a KNN of k=1 is just the nearest neighbor classifier)" }, { "code": null, "e": 5387, "s": 4905, "text": "from sklearn.neighbors import KNeighborsClassifierkVals = range(1,10)knn_names = ['KNN-'+str(k) for k in kVals]for k in kVals: knn = KNeighborsClassifier(n_neighbors=k) knn.fit(X_train, y_train) time_start = time.time() y_pred = knn.predict(X_test) time_run = time.time()-time_start results = results.append(pd.DataFrame([['KNN',knn_names[k-1],accuracy_score(y_test,y_pred),time_run]],columns=cols_results),ignore_index=True)results[results.family=='KNN']" }, { "code": null, "e": 5488, "s": 5387, "text": "Okay, so we have our KNNs here. Let’s visualize how well they’ve done and how much time they’ve took" }, { "code": null, "e": 5825, "s": 5488, "text": "fig, ax = plt.subplots()ax.plot(kVals,results[results.family=='KNN'].classification_rate,color='blue',marker='o')ax.set_xlabel('k-value for KNN models')ax.set_ylabel('classification rate (blue)')ax2=ax.twinx()ax2.plot(kVals,results[results.family=='KNN'].runtime,color='red',marker='o')ax2.set_ylabel('runtime (seconds; red)')plt.show()" }, { "code": null, "e": 5999, "s": 5825, "text": "The accuracy does fluctuate a bit at first but gradually stabilizes around 67% as we take more neighbors into account. The runtime generally increases linearly with k-value." }, { "code": null, "e": 6343, "s": 5999, "text": "For our Decision-Tree based model, we’ll create a random forest. Random forest is a method of creating multiple decision trees over a subset of the training dataset and taking the consensus result. Because of this random subsetting method, random forests are resilient to overfitting but takes longer time to train than a single decision tree." }, { "code": null, "e": 6447, "s": 6343, "text": "Let’s see how random forests of 1 (this is just a single decision tree), 10, 100, and 1,000 trees fare." }, { "code": null, "e": 6975, "s": 6447, "text": "from sklearn.ensemble import RandomForestClassifierrVals = range(1,4)rf_names = ['RF-'+str(int(math.pow(10,r))) for r in rVals]for r in rVals: clf = RandomForestClassifier(n_estimators=int(math.pow(10,r)),random_state=0) time_start = time.time() clf.fit(X_train,y_train) time_run = time.time()-time_start y_pred=clf.predict(X_test) results = results.append(pd.DataFrame([['RF',rf_names[r-1],accuracy_score(y_test,y_pred),time_run]],columns=cols_results),ignore_index=True) results[results.family=='RF']" }, { "code": null, "e": 7005, "s": 6975, "text": "Let’s see how they visualize." }, { "code": null, "e": 7200, "s": 7005, "text": "The runtime increases almost exactly linearly with the number of decision trees in the random forest, as to be expected. The accuracy, however, does not increase much and is in the 80% ballpark." }, { "code": null, "e": 7463, "s": 7200, "text": "SVMs utilize what’s known as a β€œkernel trick” to create hyperplane separators for your data (i.e. linear separators for non-linear problems). While SVMs β€œcould” overfit in theory, the generalizability of kernels usually makes it resistant from small overfitting." }, { "code": null, "e": 7961, "s": 7463, "text": "SVMs do tend to take a lot of time, and its success is highly dependent on its kernel. A pure SVM on this dataset (40k data points of 100 features) will take forever to run, so we’ll create a β€œbagged classifier” using the BaggingClassifier library offered by sklearn. The BaggingClassifier will take a base model (for us, the SVM), and train multiple of it on multiple random subsets of the dataset. For us, let’s train 10 SVM models per kernel on 1% of the data (about 400 data points) each time." }, { "code": null, "e": 8198, "s": 7961, "text": "Let’s see how well our model works for three different kernels: linear, RBF, and sigmoid. The Sklearn SVC library also gives us the poly kernel, but it was taking forever to train even in the reduced dataset, so we’re not doing it here." }, { "code": null, "e": 8266, "s": 8198, "text": "Let’s also visualize the accuracy and run time of these SVM models." }, { "code": null, "e": 8521, "s": 8266, "text": "The linear kernel does show the highest accuracy, but it has a horrible training time. Considering that we took a bagging approach that will take at maximum 10% of the data (=10 SVMs of 1% of the dataset each), the accuracy is actually pretty impressive." }, { "code": null, "e": 8582, "s": 8521, "text": "Let’s compare the accuracy and runtime of all of our models!" }, { "code": null, "e": 8943, "s": 8582, "text": "It seems like random forests give the best results β€” nearly 80% accuracy! A random forest with just 100 trees already achieves one of the best results with only nominal training time. Linear SVMs and KNN models give the next best level of results. But apart from comparing models against each other, how can we β€œobjectively” know how well our models have done?" }, { "code": null, "e": 9241, "s": 8943, "text": "For any classification task, the base case is a random classification scheme. One way to do this is to create a random classifier that will classify the input randomly and compare the results. The random assignment of labels will follow the β€œbase” proportion of the labels given to it at training." }, { "code": null, "e": 9481, "s": 9241, "text": "from sklearn.dummy import DummyClassifierclf = DummyClassifier(strategy='stratified',random_state=0)clf.fit(X_train,y_train)y_pred = clf.predict(X_test)print('Accuracy of a random classifier is: %.2f%%'%(accuracy_score(y_test,y_pred)*100))" }, { "code": null, "e": 9585, "s": 9481, "text": "It seems like for a base accuracy of 45%, all of our models have done pretty well in terms of accuracy." }, { "code": null, "e": 9805, "s": 9585, "text": "Lastly, we come back to the class imbalance problem that we’ve mentioned at the beginning. The imbalance in labels leads classifiers to bias towards the majority label. For our case, it’s towards the β€˜functional’ label." }, { "code": null, "e": 10052, "s": 9805, "text": "We’ve already seen that a classifier that predicts the β€˜functional’ label for half the time (β€˜functional’ label takes up 54.3% of the dataset) will already achieve 45% accuracy. This is already far better than a uniform random guess of 33% (1/3)." }, { "code": null, "e": 10268, "s": 10052, "text": "Class imbalance may not affect classifiers if the classes are clearly separate from each other, but in most cases, they aren’t. To see whether or not class imbalance affected our models, we can undersample the data." }, { "code": null, "e": 10508, "s": 10268, "text": "Balanced undersampling means that we take a random sample of our data where the classes are β€˜balanced.’ This can be done using the imblearn library’s RandomUnderSampler class. Think of imblearn as a sklearn library for imbalanced datasets." }, { "code": null, "e": 10717, "s": 10508, "text": "from imblearn.under_sampling import RandomUnderSamplerrus = RandomUnderSampler(random_state=0)X_rus_train,y_rus_train = rus.fit_resample(X_train,y_train)X_rus_test,y_rus_test = rus.fit_resample(X_test,y_test)" }, { "code": null, "e": 10953, "s": 10717, "text": "While our original X_train had almost 40,000 data points, our undersampled dataset only has about 8,700 data points. Let’s run it through our most successful model β€” random forests β€” and see if undersampling affects our model accuracy." }, { "code": null, "e": 11047, "s": 10953, "text": "Let’s retrain our most successful models β€” our random forests β€” on this undersampled dataset." }, { "code": null, "e": 11542, "s": 11047, "text": "rf_rus_names = ['RF_rus-'+str(int(math.pow(10,r))) for r in rVals]for r in rVals: clf = RandomForestClassifier(n_estimators=int(math.pow(10,r)),random_state=0) time_start = time.time() clf.fit(X_rus_train,y_rus_train) time_run = time.time()-time_start y_rus_pred=clf.predict(X_rus_test) results = results.append(pd.DataFrame([['RF',rf_rus_names[r-1],accuracy_score(y_rus_test,y_rus_pred),time_run]],columns=cols_results),ignore_index=True) results[results.family=='RF']" }, { "code": null, "e": 12166, "s": 11542, "text": "So our model accuracy has decreased from close to 80% to under 70%. A part of this is from the fact that the model has had a reduced dataset to work with. But another factor is that our original Random Forest models were getting a falsely β€œinflated” accuracy due to the majority class bias, which is now gone after classes have been imbalanced. At the same time, balancing of classes does lead to an objectively more accurate model, albeit not a more effective one. The ultimate decision is yours to make β€” would you care about β€œinflated” accuracy, or would these β€œfalse positives” deter you from using the original models?" } ]
Moving a file from one directory to another using Java
We can use Files.move() API to move file from one directory to another. Following is the syntax of the move method. public static Path move(Path source,Path target,CopyOption... options) throws IOException Where source βˆ’ Source path of file to be moved source βˆ’ Source path of file to be moved target βˆ’ Target path of file to be moved target βˆ’ Target path of file to be moved options βˆ’ options like REPLACE_EXISTING, ATOMIC_MOVE options βˆ’ options like REPLACE_EXISTING, ATOMIC_MOVE import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class Tester { public static void main(String[] args) { //move file from D:/temp/test.txt to D:/temp1/test.txt //make sure that temp1 folder exists moveFile("D:/temp/test.txt", "D:/temp1/test.txt"); } private static void moveFile(String src, String dest ) { Path result = null; try { result = Files.move(Paths.get(src), Paths.get(dest)); } catch (IOException e) { System.out.println("Exception while moving file: " + e.getMessage()); } if(result != null) { System.out.println("File moved successfully."); }else{ System.out.println("File movement failed."); } } } File moved successfully.
[ { "code": null, "e": 1178, "s": 1062, "text": "We can use Files.move() API to move file from one directory to another. Following is the syntax of the move method." }, { "code": null, "e": 1268, "s": 1178, "text": "public static Path move(Path source,Path target,CopyOption... options) throws IOException" }, { "code": null, "e": 1274, "s": 1268, "text": "Where" }, { "code": null, "e": 1315, "s": 1274, "text": "source βˆ’ Source path of file to be moved" }, { "code": null, "e": 1356, "s": 1315, "text": "source βˆ’ Source path of file to be moved" }, { "code": null, "e": 1397, "s": 1356, "text": "target βˆ’ Target path of file to be moved" }, { "code": null, "e": 1438, "s": 1397, "text": "target βˆ’ Target path of file to be moved" }, { "code": null, "e": 1491, "s": 1438, "text": "options βˆ’ options like REPLACE_EXISTING, ATOMIC_MOVE" }, { "code": null, "e": 1544, "s": 1491, "text": "options βˆ’ options like REPLACE_EXISTING, ATOMIC_MOVE" }, { "code": null, "e": 2333, "s": 1544, "text": "import java.io.IOException;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\npublic class Tester {\n public static void main(String[] args) {\n //move file from D:/temp/test.txt to D:/temp1/test.txt\n //make sure that temp1 folder exists\n moveFile(\"D:/temp/test.txt\", \"D:/temp1/test.txt\");\n }\n private static void moveFile(String src, String dest ) {\n Path result = null;\n try {\n result = Files.move(Paths.get(src), Paths.get(dest));\n } catch (IOException e) {\n System.out.println(\"Exception while moving file: \" + e.getMessage());\n }\n if(result != null) {\n System.out.println(\"File moved successfully.\");\n }else{\n System.out.println(\"File movement failed.\");\n }\n }\n}" }, { "code": null, "e": 2358, "s": 2333, "text": "File moved successfully." } ]
Natural Language Processing Workflow | by Jason Wong | Towards Data Science
Natural Language Processing (NLP) is the study of how computers interact (i.e. understand, interpret, manipulate) with humans through language, (e.g. speech, text). NLP got its start from the field of Linguistics, the study of language, primarily focusing on its semantics, phonetics, and grammar. Before machine learning began to show success with NLP tasks, it was mainly programming algorithms with rule-based methods from linguistics. The machine learning methods provided better accuracy, faster processing times, and dependability, resulting in the rule-based approaches taking the back seat. I will be going through the NLP process from data preprocessing to model evaluation and selection. The NLP libraries used for this tutorial are: Scikit-Learn β€” Documentation NLTK (Natural Language Toolkit) β€” Documentation The concepts that will be covered are as follows: Exploratory Data Analysis (Frequency Distribution | Parse Trees) Text Preprocessing (Tokenize, Stem, Lemmatize, Vectorize) Feature Engineering (Bigrams, POS-Tags, TF-IDF) Modeling Model Evaluation As with all data science projects, I will be following the CRISP-DM workflow. I have labelled steps for NLP to the right side of the CRISP-DM model in the image below. When working with text data, one of the first steps is to vectorize the text to create a Bag of Words (BoW). This bag will hold information about the individual words, e.g., a count of how many times each word appears in a corpus. The words in the bag are not in any specific order and if we have a large enough corpus, we may begin to notice patterns. Before creating a BoW, the text data needs to be cleaned and tokenized. This will prevent the words with different punctuation and/or capitalization being counted separately. By removing punctuation and lowercasing everything, we’re creating word tokens. Regular Expressions, β€œregex” for short, is a pattern describing a certain amount of text (Goyvaerts). This tool allows us to filter through and pull information from a text document without having to physically read it. Regex is especially helpful when tokenizing text by defining the rules for where strings will be split into tokens. The regular expressions library contains many useful tools: Ranges β€” [A-Z] [A-Za-z0-9] Instead of typing every letter in the alphabet, we can use a range from a-z. The left pattern above, [A-Z], will match on any uppercase letter. The pattern on the right, [A-Za-z0-9], will match on any uppercase letter, lowercase letter, and digit. Character Classes β€” \w \W \d Character classes, in a way, are similar to ranges. Think of these as a shortcut to ranges. The \w class would find any lowercase word and the \d class would match on any digit. Groups β€” (A-Z0-9) Also similar to ranges, but require more specificity to match. The pattern above (A-Z0-9) can only match on that exact sequence. Quantifiers β€” {*} {+} {?} Work hand in hand with groups, giving us the ability to specify the amount of times a group need to appear in order to match. The {*} will match on a group that occurs 0 or more times, {+}, 1 or more times, and {?} 0 or 1 times. Installing NLTK !pip install nltkconda install -c anaconda nltk For this tutorial I will be using a dataset containing satirical and real news articles. The satirical articles were obtained from The Onion and the real news articles were obtained from Reuters. The satirical and real news articles as a whole can be referred to as the corpus. Loading in the dataset (Corpus) import pandas as pdcorpus = pd.read_csv('data/satire_nosatire.csv') Now that the corpus has been loaded in, it’s always a good idea to check how many documents there are, as well as, the class balance of the target variable. corpus.head() #Checking to how many documents are in the corpuscorpus.shape#Output:(1000, 2) This corpus contains 1000 documents in the body column and 2 classes in the target column. #Checking the class balancecorpus.target.value_counts()#Output:1 5000 500Name: target, dtype: int64 This is a balanced dataset containing 500 documents of each class. Class 1 referring to a satirical article, and class 2, a real news article. Manually removing capitals Even though the NLTK library provides tokenizers to perform text preprocessing, manually tokenizing provides some freedom during preprocessing. first_doc = corpus.iloc[0].body#Removing Capitalsmanual_clean = [x.lower() for x in first_doc.split(' ')]manual_clean[:10]#Output:['noting', 'that', 'the', 'resignation', 'of', 'james', 'mattis', 'as', 'secretary', 'of'] Manually removing punctuation Next, we need to remove the punctuation. We can manually do this with the String library. First, I am importing the String library and calling the punctuation function. Then I am using list comprehension to join each character together as long as the character is not a punctuation character. import stringstring.punctuation#Output:'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'#Removing punctuation#s > Sentence#c > Charactermanual_clean = [''.join(c for c in s if c not in string.punctuation) for s in manual_clean] Checking the frequency distribution with the FreqDist function from NLTK #Checking the frequency distribution before stopword removalfrom nltk.probability import FreqDistimport matplotlib.pyplot as pltfdist = FreqDist(manual_clean)plt.figure(figsize=(8,8))fdist.plot(25) As you can see, the plot above is showing the highest frequency with stopwords. Since these words have low semantic value, they will be removed. Removing stopwords Stopwords are basically filler words, e.g., prepositions and conjunctions. These words hold a low semantic value and should be removed so they aren’t counted when we vectorize. We can make use of the list of stopwords provided by NLTK. Something to note, if the stopword list doesn’t contain a stopword in a document, we can just add to the list. from nltk.corpus import stopwordsmanual_clean = [x for x in manual_clean if x not in stopwords.words('english')]#Checking the frequency distribution with the stopwords removedfdist = FreqDist(manual_clean)plt.figure(figsize=(8,8))fdist.plot(25) From the frequency distribution plot above, we can see there are still a few filler words we can add to our stopwords list. Let’s go ahead and add could and one to the list. #Adding to the list of stopwordsstopwords_list = stopwords.words('english')stopwords_list.extend(['could', 'one'])manual_clean = [x for x in manual_clean if x not in stopwords_list] Removing numbers with regex Numbers, like stopwords, usually have a low semantic value. This is the case for the text data we’re using so let’s go ahead and remove them. Removing numbers from the first document for example purposes. Preview of first_doc β€˜Noting that the resignation of James Mattis as Secretary of Defense marked the ouster of the third top administration official in less than three weeks, a worried populace told reporters Friday that it was unsure how many former Trump staffers it could safely reabsorb. β€œJesus, we can’t just take back these assholes all at once β€” we need time to process one before we get the next,” said 53-year-old Gregory Birch of Naperville, IL echoing the concerns of 323 million Americans in also noting that the country was only now truly beginning to reintegrate former national security advisor Michael Flynn. β€œThis is just not sustainable. I’d say we can handle maybe one or two more former members of Trump’s inner circle over the remainder of the year, but that’s it. This country has its limits.” The U.S. populace confirmed that they could not handle all of these pieces of shit trying to rejoin society at once.’ (Retrieved from https://www.theonion.com/) import repattern = '\d+'first_doc = corpus.iloc[0].bodynum = re.findall(pattern, first_doc)num#Output:['53', '323'] Stemming is a method where the end of words are removed if it shows a derivational change to the word. Basically just reducing a word tokens down to its root word. This is helpful because most of the semantic meaning of a word is in the root, and a majority of the time, the beginning of a word is the root. from nltk.stem import *porter_stemmer = PorterStemmer()snowball_stemmer = SnowballStemmer(language="english") To see the difference between these two stemmers, let’s stem the first_doc with them both. #Looping through each word in the document and stem it with both stemmersfor word in first_doc: porter_word = p_stemmer.stem(word) snowball_word = s_stemmer.stem(word) if porter_word != snowball_word: print(porter_word, snowball_word)#Output:jesu jesuscan’t can'tnapervil napervilli’d i'dtrump’ trumpthat’ that Lemming is similar to stemming but instead of just chopping off the end, uses part of speech tags when determining how to transform a word. Lemmatization reduces words showing sort of inflection in order to return a root word that belongs to the language. For example, stemming the word mice would not return mouse but lemming would. from nltk.stem import WordNetLemmatizer lemmatizer = WordNetLemmatizer()print(f'knives becomes: {lemmatizer.lemmatize("knives")}')print(f'Noting becomes: {lemmatizer.lemmatize(first_doc[0])}')#Output:knives becomes: knifeNoting becomes: noting If we wanted to PoS tag the text ourselves, we can make use of the pos_tag function from NLTK. This function will tag each word in a document and return the word along with its PoS tag. We can then, transform the NLTK tags to the tags of the WordNetLemmatizer. from nltk import pos_tagfirst_doc_tagged = pos_tag(first_doc)first_doc_tagged[:10]#Output:[('noting', 'VBG'), ('resignation', 'NN'), ('james', 'NNS'), ('mattis', 'VBP'), ('secretary', 'NN'), ('defense', 'NN'), ('marked', 'VBD'), ('ouster', 'JJ'), ('third', 'JJ'), ('top', 'JJ')] We can make a function to transform the tags to match the WordNetLemmatizer tags. from nltk.corpus import wordnetdef wordnet_tags(tag): if tag.startswith('J'): return wordnet.ADJ elif tag.startswith('V'): return wordnet.VERB elif tag.startswith('N'): return wordnet.NOUN elif tag.startswith('R'): return wordnet.ADV else: return wordnet.NOUN Transforming part of speech tags first_doc_tagged = [(x[0], wordnet_tags(x[1])) for x in first_doc_tagged Lemmatizing first_doc_tagged with the tags we obtained with the wordnet_tags function above first_doc_lemmed = [lemmatizer.lemmatize(x[0], x[1]) for x in first_doc_tagged] When performing NLP, the features can be extracted from the text by making a Bag-of-words (BoW). The BoW method will create a Document Term Matrix, a matrix where each column is a unique word and each row is a document. We can use Scikit-Learn’s CountVectorizer to do this on our first_doc_lemmed. import pandas as pdfrom sklearn.feature_extraction.text import CountVectorizer#Transform text documents to a matrix with token countsvec = CountVectorizer()X = vec.fit_transform([" ".join(first_doc_lemmed)])#Casting results as a Pandas DataFramedf = pd.DataFrame(X.toarray(), columns = vec.get_feature_names())df.head() Instead of tokenizing the text we could also create Bigrams. A bigram is two adjacent words that are treated as one. Bigrams are helpful when performing sentiment analysis on text data, e.g., upset, barely upset. With bigrams we can apply a frequency filter to remove the bigrams that occur due to random chance. If a bigram occurs multiple times, it must have some meaning. The minimum frequency filter depends on the number of factors in the data, a normal starting value is 5 but should also be experimented with to get the most optimal value. Bigrams can also be created by calculating their Pointwise Mutual Information Score (PMI). This measures the mutual dependence between a pair of words. The bigram β€œsocial media” would most likely return a high PMI score, the pair are more than likely appear together than not. vec = CountVectorizer(token_pattern=r"([a-zA-Z]+(?:'[a-z]+)?)", stop_words=stopwords_list, ngram_range=[1,2]) #<- Allowing bigramsX = vec.fit_transform(corpus.body[0:5])df = pd.DataFrame(X.toarray(), columns = vec.get_feature_names())df.head() TF-IDF scales down the frequencies of tokens to represent how important a word is. TF (Term Frequency) β€” frequency of the word in a single document divided by the total number of words in the document. IDF (Inverse Document Frequency) β€” measure of how much information is provided by a term. IDF can be calculated by taking the total number of documents in the corpus, dividing by the number of documents the term appears in, and taking the logarithm of the result. TF-IDF β€” Term Frequency and the Inverse Document Frequency multiplied together from sklearn.feature_extraction.text import TfidfVectorizertf_vec = TfidfVectorizer(token_pattern=r"([a-zA-Z]+(?:'[a-z]+)?)", stop_words=stopwords_list)X = tf_vec.fit_transform(corpus.body)df = pd.DataFrame(X.toarray(), columns = tf_vec.get_feature_names())df.head() Instead of manually going through and performing the preprocessing steps above, let’s just make a function to perform these steps up until count vectorizing. from nltk.corpus import wordnetfrom nltk import pos_tagfrom nltk.stem import WordNetLemmatizerdef prepare_doc(doc, stopwords=stopwords_list): regex_tokenizer = RegexpTokenizer(r"([a-zA-Z]+(?:’[a-z]+)?)") doc = regex_tokenizer.tokenize(doc) doc = [x.lower() for x in doc] doc = [x for x in doc if x not in stopwords_list] doc = pos_tag(doc) doc = [(x[0], wordnet_pos(x[1])) for x in doc] #Could stem here instead of lemmatizing lemma = WordNetLemmatizer() doc = [lemma.lemmatize(x[0], x[1]) for x in doc] return ' '.join(doc) Below, I will import the necessary libraries and use the prepare_doc function above to clean the text. Next, I will perform a train test split and create a pipeline for the remaining preprocessing steps (TF-IDF Vectorizing, TF-IDF Normalisation). I will then fit the pipeline to the train split and predict on the test split. #Importsimport pandas as pdimport numpy as npimport matplotlib.pyplot as plt%matplotlib inlineimport seaborn as snsimport nltkfrom nltk import pos_tagfrom nltk.corpus import stopwordsfrom nltk.tokenize import regexp_tokenize, word_tokenize, RegexpTokenizerimport sklearn.feature_extraction.text from sklearn.feature_extraction.text import TfidfVectorizer, TfidfTransformer, CountVectorizerfrom sklearn.model_selection import train_test_splitfrom sklearn.pipeline import Pipelinefrom sklearn.ensemble import RandomForestClassifierfrom sklearn.metrics import confusion_matrix, mean_squared_error, classification_reportfrom sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, roc_auc_score Loading in the corpus df = pd.read_csv('../data/satire_nosatire.csv')df.head(10) #Defining stopwordsstopwords_list = stopwords.words('english')X = df.body#Preprocessing function to remove numbers, stopwords, lowercase the #capitals, generate PoS tags, and lemmatize the textX = [doc_preparer(x, stopwords_list) for x in X]y = df.targetX[:2] Performing train test split X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42) Creating preprocess pipeline and the full pipeline with a Random Forest Classifier tfidf_vec = Pipeline([('tfidf_vec', TfidfVectorizer())])tfidf = Pipeline([('tfidf', TfidfTransformer())])preprocess = Pipeline([ ('tfidf_vec', tfidf_vec), ('tfidf', tfidf)])pipe = Pipeline([ ('preprocess', preprocess), ('clf', RandomForestClassifier())]) Fitting the pipeline to X_train and y_train pipe.fit(X_train, y_train) Predicting on X_test y_hat = pipe.predict(X_test) Defining evaluation function to plot a confusion matrix and return the accuracy, precision, recall, and f1 scores def evaluation(y, y_hat, title = 'Confusion Matrix'): cm = confusion_matrix(y, y_hat) precision = precision_score(y, y_hat) recall = recall_score(y, y_hat) accuracy = accuracy_score(y,y_hat) f1 = f1_score(y,y_hat) print('Recall: ', recall) print('Accuracy: ', accuracy) print('Precision: ', precision) print('F1: ', f1) sns.heatmap(cm, cmap= 'PuBu', annot=True, fmt='g', annot_kws= {'size':20}) plt.xlabel('predicted', fontsize=18) plt.ylabel('actual', fontsize=18) plt.title(title, fontsize=18) plt.show(); Evaluating the classifier evaluation(y_test, y_hat) With NLP there are many different tools and methods you can use. It is worth taking the time to understand how the NLP libraries preprocess text in different ways, ensuring you choose the best method for your task. Making use of pipelines with the preprocessing and modeling steps help to streamline the workflow while cleaning up the code. I hope the concepts covered in this post can serve as a helpful resource when performing NLP. Natural Language Toolkit. (n.d.). Retrieved from https://www.nltk.org/ Learn. (n.d.). Retrieved from https://scikit-learn.org/stable/ Goyvaerts, J. (n.d.). Regular Expressions TutorialLearn How to Use and Get The Most out of Regular Expressions. Retrieved November 20, 2020, from https://www.regular-expressions.info/tutorial.html Brownlee, J. (2019, August 07). What Is Natural Language Processing? Retrieved from https://machinelearningmastery.com/natural-language-processing/ Re β€” Regular expression operations. (n.d.). Retrieved from https://docs.python.org/3/library/re.html Saurav Jain Enthusiastic Coder Developer and always a learner, Jain, S., & Enthusiastic Coder Developer and always a learner. (2020, September 17). Introduction to Stemming. Retrieved from https://www.geeksforgeeks.org/introduction-to-stemming/ Stemming and Lemmatization in Python. (n.d.). Retrieved from https://www.datacamp.com/community/tutorials/stemming-lemmatization-python Document-Term Matrix. (n.d.). Retrieved from https://shorttext.readthedocs.io/en/latest/tutorial_dtm.html Business & Financial News, U.S & International Breaking News. (n.d.). Retrieved from https://www.Reuters.com/ America’s Finest News Source. (n.d.). Retrieved from https://www.theonion.com/
[ { "code": null, "e": 771, "s": 172, "text": "Natural Language Processing (NLP) is the study of how computers interact (i.e. understand, interpret, manipulate) with humans through language, (e.g. speech, text). NLP got its start from the field of Linguistics, the study of language, primarily focusing on its semantics, phonetics, and grammar. Before machine learning began to show success with NLP tasks, it was mainly programming algorithms with rule-based methods from linguistics. The machine learning methods provided better accuracy, faster processing times, and dependability, resulting in the rule-based approaches taking the back seat." }, { "code": null, "e": 916, "s": 771, "text": "I will be going through the NLP process from data preprocessing to model evaluation and selection. The NLP libraries used for this tutorial are:" }, { "code": null, "e": 945, "s": 916, "text": "Scikit-Learn β€” Documentation" }, { "code": null, "e": 993, "s": 945, "text": "NLTK (Natural Language Toolkit) β€” Documentation" }, { "code": null, "e": 1043, "s": 993, "text": "The concepts that will be covered are as follows:" }, { "code": null, "e": 1108, "s": 1043, "text": "Exploratory Data Analysis (Frequency Distribution | Parse Trees)" }, { "code": null, "e": 1166, "s": 1108, "text": "Text Preprocessing (Tokenize, Stem, Lemmatize, Vectorize)" }, { "code": null, "e": 1214, "s": 1166, "text": "Feature Engineering (Bigrams, POS-Tags, TF-IDF)" }, { "code": null, "e": 1223, "s": 1214, "text": "Modeling" }, { "code": null, "e": 1240, "s": 1223, "text": "Model Evaluation" }, { "code": null, "e": 1408, "s": 1240, "text": "As with all data science projects, I will be following the CRISP-DM workflow. I have labelled steps for NLP to the right side of the CRISP-DM model in the image below." }, { "code": null, "e": 1761, "s": 1408, "text": "When working with text data, one of the first steps is to vectorize the text to create a Bag of Words (BoW). This bag will hold information about the individual words, e.g., a count of how many times each word appears in a corpus. The words in the bag are not in any specific order and if we have a large enough corpus, we may begin to notice patterns." }, { "code": null, "e": 2016, "s": 1761, "text": "Before creating a BoW, the text data needs to be cleaned and tokenized. This will prevent the words with different punctuation and/or capitalization being counted separately. By removing punctuation and lowercasing everything, we’re creating word tokens." }, { "code": null, "e": 2412, "s": 2016, "text": "Regular Expressions, β€œregex” for short, is a pattern describing a certain amount of text (Goyvaerts). This tool allows us to filter through and pull information from a text document without having to physically read it. Regex is especially helpful when tokenizing text by defining the rules for where strings will be split into tokens. The regular expressions library contains many useful tools:" }, { "code": null, "e": 2439, "s": 2412, "text": "Ranges β€” [A-Z] [A-Za-z0-9]" }, { "code": null, "e": 2687, "s": 2439, "text": "Instead of typing every letter in the alphabet, we can use a range from a-z. The left pattern above, [A-Z], will match on any uppercase letter. The pattern on the right, [A-Za-z0-9], will match on any uppercase letter, lowercase letter, and digit." }, { "code": null, "e": 2716, "s": 2687, "text": "Character Classes β€” \\w \\W \\d" }, { "code": null, "e": 2894, "s": 2716, "text": "Character classes, in a way, are similar to ranges. Think of these as a shortcut to ranges. The \\w class would find any lowercase word and the \\d class would match on any digit." }, { "code": null, "e": 2912, "s": 2894, "text": "Groups β€” (A-Z0-9)" }, { "code": null, "e": 3041, "s": 2912, "text": "Also similar to ranges, but require more specificity to match. The pattern above (A-Z0-9) can only match on that exact sequence." }, { "code": null, "e": 3067, "s": 3041, "text": "Quantifiers β€” {*} {+} {?}" }, { "code": null, "e": 3296, "s": 3067, "text": "Work hand in hand with groups, giving us the ability to specify the amount of times a group need to appear in order to match. The {*} will match on a group that occurs 0 or more times, {+}, 1 or more times, and {?} 0 or 1 times." }, { "code": null, "e": 3312, "s": 3296, "text": "Installing NLTK" }, { "code": null, "e": 3360, "s": 3312, "text": "!pip install nltkconda install -c anaconda nltk" }, { "code": null, "e": 3638, "s": 3360, "text": "For this tutorial I will be using a dataset containing satirical and real news articles. The satirical articles were obtained from The Onion and the real news articles were obtained from Reuters. The satirical and real news articles as a whole can be referred to as the corpus." }, { "code": null, "e": 3670, "s": 3638, "text": "Loading in the dataset (Corpus)" }, { "code": null, "e": 3738, "s": 3670, "text": "import pandas as pdcorpus = pd.read_csv('data/satire_nosatire.csv')" }, { "code": null, "e": 3895, "s": 3738, "text": "Now that the corpus has been loaded in, it’s always a good idea to check how many documents there are, as well as, the class balance of the target variable." }, { "code": null, "e": 3909, "s": 3895, "text": "corpus.head()" }, { "code": null, "e": 3988, "s": 3909, "text": "#Checking to how many documents are in the corpuscorpus.shape#Output:(1000, 2)" }, { "code": null, "e": 4079, "s": 3988, "text": "This corpus contains 1000 documents in the body column and 2 classes in the target column." }, { "code": null, "e": 4185, "s": 4079, "text": "#Checking the class balancecorpus.target.value_counts()#Output:1 5000 500Name: target, dtype: int64" }, { "code": null, "e": 4328, "s": 4185, "text": "This is a balanced dataset containing 500 documents of each class. Class 1 referring to a satirical article, and class 2, a real news article." }, { "code": null, "e": 4355, "s": 4328, "text": "Manually removing capitals" }, { "code": null, "e": 4499, "s": 4355, "text": "Even though the NLTK library provides tokenizers to perform text preprocessing, manually tokenizing provides some freedom during preprocessing." }, { "code": null, "e": 4720, "s": 4499, "text": "first_doc = corpus.iloc[0].body#Removing Capitalsmanual_clean = [x.lower() for x in first_doc.split(' ')]manual_clean[:10]#Output:['noting', 'that', 'the', 'resignation', 'of', 'james', 'mattis', 'as', 'secretary', 'of']" }, { "code": null, "e": 4750, "s": 4720, "text": "Manually removing punctuation" }, { "code": null, "e": 5043, "s": 4750, "text": "Next, we need to remove the punctuation. We can manually do this with the String library. First, I am importing the String library and calling the punctuation function. Then I am using list comprehension to join each character together as long as the character is not a punctuation character." }, { "code": null, "e": 5258, "s": 5043, "text": "import stringstring.punctuation#Output:'!\"#$%&\\'()*+,-./:;<=>?@[\\\\]^_`{|}~'#Removing punctuation#s > Sentence#c > Charactermanual_clean = [''.join(c for c in s if c not in string.punctuation) for s in manual_clean]" }, { "code": null, "e": 5331, "s": 5258, "text": "Checking the frequency distribution with the FreqDist function from NLTK" }, { "code": null, "e": 5529, "s": 5331, "text": "#Checking the frequency distribution before stopword removalfrom nltk.probability import FreqDistimport matplotlib.pyplot as pltfdist = FreqDist(manual_clean)plt.figure(figsize=(8,8))fdist.plot(25)" }, { "code": null, "e": 5674, "s": 5529, "text": "As you can see, the plot above is showing the highest frequency with stopwords. Since these words have low semantic value, they will be removed." }, { "code": null, "e": 5693, "s": 5674, "text": "Removing stopwords" }, { "code": null, "e": 6040, "s": 5693, "text": "Stopwords are basically filler words, e.g., prepositions and conjunctions. These words hold a low semantic value and should be removed so they aren’t counted when we vectorize. We can make use of the list of stopwords provided by NLTK. Something to note, if the stopword list doesn’t contain a stopword in a document, we can just add to the list." }, { "code": null, "e": 6285, "s": 6040, "text": "from nltk.corpus import stopwordsmanual_clean = [x for x in manual_clean if x not in stopwords.words('english')]#Checking the frequency distribution with the stopwords removedfdist = FreqDist(manual_clean)plt.figure(figsize=(8,8))fdist.plot(25)" }, { "code": null, "e": 6459, "s": 6285, "text": "From the frequency distribution plot above, we can see there are still a few filler words we can add to our stopwords list. Let’s go ahead and add could and one to the list." }, { "code": null, "e": 6641, "s": 6459, "text": "#Adding to the list of stopwordsstopwords_list = stopwords.words('english')stopwords_list.extend(['could', 'one'])manual_clean = [x for x in manual_clean if x not in stopwords_list]" }, { "code": null, "e": 6669, "s": 6641, "text": "Removing numbers with regex" }, { "code": null, "e": 6874, "s": 6669, "text": "Numbers, like stopwords, usually have a low semantic value. This is the case for the text data we’re using so let’s go ahead and remove them. Removing numbers from the first document for example purposes." }, { "code": null, "e": 6895, "s": 6874, "text": "Preview of first_doc" }, { "code": null, "e": 7808, "s": 6895, "text": "β€˜Noting that the resignation of James Mattis as Secretary of Defense marked the ouster of the third top administration official in less than three weeks, a worried populace told reporters Friday that it was unsure how many former Trump staffers it could safely reabsorb. β€œJesus, we can’t just take back these assholes all at once β€” we need time to process one before we get the next,” said 53-year-old Gregory Birch of Naperville, IL echoing the concerns of 323 million Americans in also noting that the country was only now truly beginning to reintegrate former national security advisor Michael Flynn. β€œThis is just not sustainable. I’d say we can handle maybe one or two more former members of Trump’s inner circle over the remainder of the year, but that’s it. This country has its limits.” The U.S. populace confirmed that they could not handle all of these pieces of shit trying to rejoin society at once.’" }, { "code": null, "e": 7851, "s": 7808, "text": "(Retrieved from https://www.theonion.com/)" }, { "code": null, "e": 7967, "s": 7851, "text": "import repattern = '\\d+'first_doc = corpus.iloc[0].bodynum = re.findall(pattern, first_doc)num#Output:['53', '323']" }, { "code": null, "e": 8275, "s": 7967, "text": "Stemming is a method where the end of words are removed if it shows a derivational change to the word. Basically just reducing a word tokens down to its root word. This is helpful because most of the semantic meaning of a word is in the root, and a majority of the time, the beginning of a word is the root." }, { "code": null, "e": 8385, "s": 8275, "text": "from nltk.stem import *porter_stemmer = PorterStemmer()snowball_stemmer = SnowballStemmer(language=\"english\")" }, { "code": null, "e": 8476, "s": 8385, "text": "To see the difference between these two stemmers, let’s stem the first_doc with them both." }, { "code": null, "e": 8807, "s": 8476, "text": "#Looping through each word in the document and stem it with both stemmersfor word in first_doc: porter_word = p_stemmer.stem(word) snowball_word = s_stemmer.stem(word) if porter_word != snowball_word: print(porter_word, snowball_word)#Output:jesu jesuscan’t can'tnapervil napervilli’d i'dtrump’ trumpthat’ that" }, { "code": null, "e": 9141, "s": 8807, "text": "Lemming is similar to stemming but instead of just chopping off the end, uses part of speech tags when determining how to transform a word. Lemmatization reduces words showing sort of inflection in order to return a root word that belongs to the language. For example, stemming the word mice would not return mouse but lemming would." }, { "code": null, "e": 9387, "s": 9141, "text": "from nltk.stem import WordNetLemmatizer lemmatizer = WordNetLemmatizer()print(f'knives becomes: {lemmatizer.lemmatize(\"knives\")}')print(f'Noting becomes: {lemmatizer.lemmatize(first_doc[0])}')#Output:knives becomes: knifeNoting becomes: noting" }, { "code": null, "e": 9648, "s": 9387, "text": "If we wanted to PoS tag the text ourselves, we can make use of the pos_tag function from NLTK. This function will tag each word in a document and return the word along with its PoS tag. We can then, transform the NLTK tags to the tags of the WordNetLemmatizer." }, { "code": null, "e": 9927, "s": 9648, "text": "from nltk import pos_tagfirst_doc_tagged = pos_tag(first_doc)first_doc_tagged[:10]#Output:[('noting', 'VBG'), ('resignation', 'NN'), ('james', 'NNS'), ('mattis', 'VBP'), ('secretary', 'NN'), ('defense', 'NN'), ('marked', 'VBD'), ('ouster', 'JJ'), ('third', 'JJ'), ('top', 'JJ')]" }, { "code": null, "e": 10009, "s": 9927, "text": "We can make a function to transform the tags to match the WordNetLemmatizer tags." }, { "code": null, "e": 10319, "s": 10009, "text": "from nltk.corpus import wordnetdef wordnet_tags(tag): if tag.startswith('J'): return wordnet.ADJ elif tag.startswith('V'): return wordnet.VERB elif tag.startswith('N'): return wordnet.NOUN elif tag.startswith('R'): return wordnet.ADV else: return wordnet.NOUN" }, { "code": null, "e": 10352, "s": 10319, "text": "Transforming part of speech tags" }, { "code": null, "e": 10425, "s": 10352, "text": "first_doc_tagged = [(x[0], wordnet_tags(x[1])) for x in first_doc_tagged" }, { "code": null, "e": 10517, "s": 10425, "text": "Lemmatizing first_doc_tagged with the tags we obtained with the wordnet_tags function above" }, { "code": null, "e": 10597, "s": 10517, "text": "first_doc_lemmed = [lemmatizer.lemmatize(x[0], x[1]) for x in first_doc_tagged]" }, { "code": null, "e": 10895, "s": 10597, "text": "When performing NLP, the features can be extracted from the text by making a Bag-of-words (BoW). The BoW method will create a Document Term Matrix, a matrix where each column is a unique word and each row is a document. We can use Scikit-Learn’s CountVectorizer to do this on our first_doc_lemmed." }, { "code": null, "e": 11215, "s": 10895, "text": "import pandas as pdfrom sklearn.feature_extraction.text import CountVectorizer#Transform text documents to a matrix with token countsvec = CountVectorizer()X = vec.fit_transform([\" \".join(first_doc_lemmed)])#Casting results as a Pandas DataFramedf = pd.DataFrame(X.toarray(), columns = vec.get_feature_names())df.head()" }, { "code": null, "e": 11762, "s": 11215, "text": "Instead of tokenizing the text we could also create Bigrams. A bigram is two adjacent words that are treated as one. Bigrams are helpful when performing sentiment analysis on text data, e.g., upset, barely upset. With bigrams we can apply a frequency filter to remove the bigrams that occur due to random chance. If a bigram occurs multiple times, it must have some meaning. The minimum frequency filter depends on the number of factors in the data, a normal starting value is 5 but should also be experimented with to get the most optimal value." }, { "code": null, "e": 12039, "s": 11762, "text": "Bigrams can also be created by calculating their Pointwise Mutual Information Score (PMI). This measures the mutual dependence between a pair of words. The bigram β€œsocial media” would most likely return a high PMI score, the pair are more than likely appear together than not." }, { "code": null, "e": 12283, "s": 12039, "text": "vec = CountVectorizer(token_pattern=r\"([a-zA-Z]+(?:'[a-z]+)?)\", stop_words=stopwords_list, ngram_range=[1,2]) #<- Allowing bigramsX = vec.fit_transform(corpus.body[0:5])df = pd.DataFrame(X.toarray(), columns = vec.get_feature_names())df.head()" }, { "code": null, "e": 12366, "s": 12283, "text": "TF-IDF scales down the frequencies of tokens to represent how important a word is." }, { "code": null, "e": 12485, "s": 12366, "text": "TF (Term Frequency) β€” frequency of the word in a single document divided by the total number of words in the document." }, { "code": null, "e": 12749, "s": 12485, "text": "IDF (Inverse Document Frequency) β€” measure of how much information is provided by a term. IDF can be calculated by taking the total number of documents in the corpus, dividing by the number of documents the term appears in, and taking the logarithm of the result." }, { "code": null, "e": 12828, "s": 12749, "text": "TF-IDF β€” Term Frequency and the Inverse Document Frequency multiplied together" }, { "code": null, "e": 13098, "s": 12828, "text": "from sklearn.feature_extraction.text import TfidfVectorizertf_vec = TfidfVectorizer(token_pattern=r\"([a-zA-Z]+(?:'[a-z]+)?)\", stop_words=stopwords_list)X = tf_vec.fit_transform(corpus.body)df = pd.DataFrame(X.toarray(), columns = tf_vec.get_feature_names())df.head()" }, { "code": null, "e": 13256, "s": 13098, "text": "Instead of manually going through and performing the preprocessing steps above, let’s just make a function to perform these steps up until count vectorizing." }, { "code": null, "e": 13812, "s": 13256, "text": "from nltk.corpus import wordnetfrom nltk import pos_tagfrom nltk.stem import WordNetLemmatizerdef prepare_doc(doc, stopwords=stopwords_list): regex_tokenizer = RegexpTokenizer(r\"([a-zA-Z]+(?:’[a-z]+)?)\") doc = regex_tokenizer.tokenize(doc) doc = [x.lower() for x in doc] doc = [x for x in doc if x not in stopwords_list] doc = pos_tag(doc) doc = [(x[0], wordnet_pos(x[1])) for x in doc] #Could stem here instead of lemmatizing lemma = WordNetLemmatizer() doc = [lemma.lemmatize(x[0], x[1]) for x in doc] return ' '.join(doc)" }, { "code": null, "e": 14138, "s": 13812, "text": "Below, I will import the necessary libraries and use the prepare_doc function above to clean the text. Next, I will perform a train test split and create a pipeline for the remaining preprocessing steps (TF-IDF Vectorizing, TF-IDF Normalisation). I will then fit the pipeline to the train split and predict on the test split." }, { "code": null, "e": 14853, "s": 14138, "text": "#Importsimport pandas as pdimport numpy as npimport matplotlib.pyplot as plt%matplotlib inlineimport seaborn as snsimport nltkfrom nltk import pos_tagfrom nltk.corpus import stopwordsfrom nltk.tokenize import regexp_tokenize, word_tokenize, RegexpTokenizerimport sklearn.feature_extraction.text from sklearn.feature_extraction.text import TfidfVectorizer, TfidfTransformer, CountVectorizerfrom sklearn.model_selection import train_test_splitfrom sklearn.pipeline import Pipelinefrom sklearn.ensemble import RandomForestClassifierfrom sklearn.metrics import confusion_matrix, mean_squared_error, classification_reportfrom sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, roc_auc_score" }, { "code": null, "e": 14875, "s": 14853, "text": "Loading in the corpus" }, { "code": null, "e": 14934, "s": 14875, "text": "df = pd.read_csv('../data/satire_nosatire.csv')df.head(10)" }, { "code": null, "e": 15194, "s": 14934, "text": "#Defining stopwordsstopwords_list = stopwords.words('english')X = df.body#Preprocessing function to remove numbers, stopwords, lowercase the #capitals, generate PoS tags, and lemmatize the textX = [doc_preparer(x, stopwords_list) for x in X]y = df.targetX[:2]" }, { "code": null, "e": 15222, "s": 15194, "text": "Performing train test split" }, { "code": null, "e": 15297, "s": 15222, "text": "X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)" }, { "code": null, "e": 15380, "s": 15297, "text": "Creating preprocess pipeline and the full pipeline with a Random Forest Classifier" }, { "code": null, "e": 15647, "s": 15380, "text": "tfidf_vec = Pipeline([('tfidf_vec', TfidfVectorizer())])tfidf = Pipeline([('tfidf', TfidfTransformer())])preprocess = Pipeline([ ('tfidf_vec', tfidf_vec), ('tfidf', tfidf)])pipe = Pipeline([ ('preprocess', preprocess), ('clf', RandomForestClassifier())])" }, { "code": null, "e": 15691, "s": 15647, "text": "Fitting the pipeline to X_train and y_train" }, { "code": null, "e": 15718, "s": 15691, "text": "pipe.fit(X_train, y_train)" }, { "code": null, "e": 15739, "s": 15718, "text": "Predicting on X_test" }, { "code": null, "e": 15768, "s": 15739, "text": "y_hat = pipe.predict(X_test)" }, { "code": null, "e": 15882, "s": 15768, "text": "Defining evaluation function to plot a confusion matrix and return the accuracy, precision, recall, and f1 scores" }, { "code": null, "e": 16440, "s": 15882, "text": "def evaluation(y, y_hat, title = 'Confusion Matrix'): cm = confusion_matrix(y, y_hat) precision = precision_score(y, y_hat) recall = recall_score(y, y_hat) accuracy = accuracy_score(y,y_hat) f1 = f1_score(y,y_hat) print('Recall: ', recall) print('Accuracy: ', accuracy) print('Precision: ', precision) print('F1: ', f1) sns.heatmap(cm, cmap= 'PuBu', annot=True, fmt='g', annot_kws= {'size':20}) plt.xlabel('predicted', fontsize=18) plt.ylabel('actual', fontsize=18) plt.title(title, fontsize=18) plt.show();" }, { "code": null, "e": 16466, "s": 16440, "text": "Evaluating the classifier" }, { "code": null, "e": 16492, "s": 16466, "text": "evaluation(y_test, y_hat)" }, { "code": null, "e": 16927, "s": 16492, "text": "With NLP there are many different tools and methods you can use. It is worth taking the time to understand how the NLP libraries preprocess text in different ways, ensuring you choose the best method for your task. Making use of pipelines with the preprocessing and modeling steps help to streamline the workflow while cleaning up the code. I hope the concepts covered in this post can serve as a helpful resource when performing NLP." }, { "code": null, "e": 16998, "s": 16927, "text": "Natural Language Toolkit. (n.d.). Retrieved from https://www.nltk.org/" }, { "code": null, "e": 17061, "s": 16998, "text": "Learn. (n.d.). Retrieved from https://scikit-learn.org/stable/" }, { "code": null, "e": 17258, "s": 17061, "text": "Goyvaerts, J. (n.d.). Regular Expressions TutorialLearn How to Use and Get The Most out of Regular Expressions. Retrieved November 20, 2020, from https://www.regular-expressions.info/tutorial.html" }, { "code": null, "e": 17406, "s": 17258, "text": "Brownlee, J. (2019, August 07). What Is Natural Language Processing? Retrieved from https://machinelearningmastery.com/natural-language-processing/" }, { "code": null, "e": 17507, "s": 17406, "text": "Re β€” Regular expression operations. (n.d.). Retrieved from https://docs.python.org/3/library/re.html" }, { "code": null, "e": 17752, "s": 17507, "text": "Saurav Jain Enthusiastic Coder Developer and always a learner, Jain, S., & Enthusiastic Coder Developer and always a learner. (2020, September 17). Introduction to Stemming. Retrieved from https://www.geeksforgeeks.org/introduction-to-stemming/" }, { "code": null, "e": 17888, "s": 17752, "text": "Stemming and Lemmatization in Python. (n.d.). Retrieved from https://www.datacamp.com/community/tutorials/stemming-lemmatization-python" }, { "code": null, "e": 17994, "s": 17888, "text": "Document-Term Matrix. (n.d.). Retrieved from https://shorttext.readthedocs.io/en/latest/tutorial_dtm.html" }, { "code": null, "e": 18104, "s": 17994, "text": "Business & Financial News, U.S & International Breaking News. (n.d.). Retrieved from https://www.Reuters.com/" } ]
How to change each column width of a JTable in Java?
A JTable is a subclass of JComponent for displaying complex data structures. A JTable can follow the Model View Controller (MVC) design pattern for displaying the data in rows and columns. The DefaultTableModel class can extend AbstractTableModel and it can be used to add the rows and columns to a JTable dynamically. The DefaultTableCellRenderer class can extend JLabel class and it can be used to add images, colored text and etc. inside the JTable cell. A JTable can generate TableModelListener, TableColumnModelListener, ListSelectionListener, CellEditorListener, RowSorterListener interfaces. By default the width of a JTable is fixed, we can also change the width of each column by using table.getColumnModel().getColumn().setPreferredWidth() method of JTable class. import java.awt.*; import javax.swing.*; import javax.swing.table.*; public class JTableTest extends JFrame { private JTable table; private JScrollPane scrollPane; private DefaultTableModel model; private DefaultTableCellRenderer cellRenderer; public JTableTest() { setTitle("JTable Test"); setLayout(new FlowLayout()); scrollPane = new JScrollPane(); JTable table = new JTable(); scrollPane.setViewportView(table); model = (DefaultTableModel)table.getModel(); model.addColumn("S.No"); model.addColumn("First Name"); model.addColumn("Last Name"); model.addColumn("Email"); model.addColumn("Contact"); for(int i = 0;i < 4; i++) { model.addRow(new Object[0]); model.setValueAt(i+1, i, 0); model.setValueAt("Tutorials", i, 1); model.setValueAt("Point", i, 2); model.setValueAt("@tutorialspoint.com", i, 3); model.setValueAt("123456789", i, 4); } // set the column width for each column table.getColumnModel().getColumn(0).setPreferredWidth(5); table.getColumnModel().getColumn(3).setPreferredWidth(100); cellRenderer = new DefaultTableCellRenderer(); cellRenderer.setHorizontalAlignment(JLabel.CENTER); table.getColumnModel().getColumn(0).setCellRenderer(cellRenderer); add(scrollPane); setSize(475, 250); setResizable(false); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); setVisible(true); } public static void main(String[] args) { new JTableTest(); } }
[ { "code": null, "e": 1139, "s": 1062, "text": "A JTable is a subclass of JComponent for displaying complex data structures." }, { "code": null, "e": 1251, "s": 1139, "text": "A JTable can follow the Model View Controller (MVC) design pattern for displaying the data in rows and columns." }, { "code": null, "e": 1381, "s": 1251, "text": "The DefaultTableModel class can extend AbstractTableModel and it can be used to add the rows and columns to a JTable dynamically." }, { "code": null, "e": 1520, "s": 1381, "text": "The DefaultTableCellRenderer class can extend JLabel class and it can be used to add images, colored text and etc. inside the JTable cell." }, { "code": null, "e": 1661, "s": 1520, "text": "A JTable can generate TableModelListener, TableColumnModelListener, ListSelectionListener, CellEditorListener, RowSorterListener interfaces." }, { "code": null, "e": 1836, "s": 1661, "text": "By default the width of a JTable is fixed, we can also change the width of each column by using table.getColumnModel().getColumn().setPreferredWidth() method of JTable class." }, { "code": null, "e": 3454, "s": 1836, "text": "import java.awt.*;\nimport javax.swing.*;\nimport javax.swing.table.*;\npublic class JTableTest extends JFrame {\n private JTable table;\n private JScrollPane scrollPane;\n private DefaultTableModel model;\n private DefaultTableCellRenderer cellRenderer;\n public JTableTest() {\n setTitle(\"JTable Test\");\n setLayout(new FlowLayout());\n scrollPane = new JScrollPane();\n JTable table = new JTable();\n scrollPane.setViewportView(table);\n model = (DefaultTableModel)table.getModel();\n model.addColumn(\"S.No\");\n model.addColumn(\"First Name\");\n model.addColumn(\"Last Name\");\n model.addColumn(\"Email\");\n model.addColumn(\"Contact\");\n for(int i = 0;i < 4; i++) {\n model.addRow(new Object[0]);\n model.setValueAt(i+1, i, 0);\n model.setValueAt(\"Tutorials\", i, 1);\n model.setValueAt(\"Point\", i, 2);\n model.setValueAt(\"@tutorialspoint.com\", i, 3);\n model.setValueAt(\"123456789\", i, 4);\n }\n // set the column width for each column\n table.getColumnModel().getColumn(0).setPreferredWidth(5);\n table.getColumnModel().getColumn(3).setPreferredWidth(100);\n cellRenderer = new DefaultTableCellRenderer();\n cellRenderer.setHorizontalAlignment(JLabel.CENTER);\n table.getColumnModel().getColumn(0).setCellRenderer(cellRenderer);\n add(scrollPane);\n setSize(475, 250);\n setResizable(false);\n setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n setLocationRelativeTo(null);\n setVisible(true);\n }\n public static void main(String[] args) {\n new JTableTest();\n }\n}" } ]
How to get the number of seconds between two Dates in JavaScript?
To get the number of seconds between two dates, use the Maths.abs() method. You can try to run the following code to get seconds between two dates βˆ’ Live Demo <html> <head> <title>JavaScript Get Seconds</title> </head> <body> <script> var date1, date2; date1 = new Date(); document.write(""+date1); date2 = new Date( "Dec 10, 2015 20:15:10" ); document.write("<br>"+date2); // get total seconds between two dates var seconds = Math.abs(date1 - date2) / 1000; document.write("<br>Difference between 2 dates: "+seconds); </script> </body> </html> Mon May 28 2018 09:35:25 GMT+0530 (India Standard Time) Thu Dec 10 2015 20:15:10 GMT+0530 (India Standard Time) Difference between 2 dates: 77721615.573
[ { "code": null, "e": 1138, "s": 1062, "text": "To get the number of seconds between two dates, use the Maths.abs() method." }, { "code": null, "e": 1211, "s": 1138, "text": "You can try to run the following code to get seconds between two dates βˆ’" }, { "code": null, "e": 1221, "s": 1211, "text": "Live Demo" }, { "code": null, "e": 1709, "s": 1221, "text": "<html>\n <head>\n <title>JavaScript Get Seconds</title>\n </head>\n <body>\n <script>\n var date1, date2;\n date1 = new Date();\n document.write(\"\"+date1);\n date2 = new Date( \"Dec 10, 2015 20:15:10\" );\n document.write(\"<br>\"+date2);\n // get total seconds between two dates\n var seconds = Math.abs(date1 - date2) / 1000;\n document.write(\"<br>Difference between 2 dates: \"+seconds);\n </script>\n </body>\n</html>" }, { "code": null, "e": 1862, "s": 1709, "text": "Mon May 28 2018 09:35:25 GMT+0530 (India Standard Time)\nThu Dec 10 2015 20:15:10 GMT+0530 (India Standard Time)\nDifference between 2 dates: 77721615.573" } ]
Tic Tac Toe | Practice | GeeksforGeeks
A Tic-Tac-Toe board is given after some moves are played. Find out if the given board is valid, i.e., is it possible to reach this board position after some moves or not. Note that every arbitrary filled grid of 9 spaces isn’t valid e.g. a grid filled with 3 X and 6 O isn’t valid situation because each player needs to take alternate turns. Note : The game starts with X Example 1: Input: board[] = {'X', 'X', 'O', 'O', 'O', 'X', 'X', 'O', 'X'}; Output: Valid Explanation: This is a valid board. Example 2: Input: board[] = {'O', 'X', 'X', 'O', 'X', 'X', 'O', 'O', 'X'}; Output: Invalid Explanation: Both X and O cannot win. Your Task: You don't need to read input or print anything. Your task is to complete the function isValid() which takes a character array of size 9 representing the board as input parameter and returns a boolean value denoting if it is valid or not. Expected Time Complexity: O(1) Expected Auxiliary Space: O(1) Constraints: Every character on the board can either be 'X' or 'O'. 0 lindan1232 months ago public: bool solve(char ar[9],char n) { if(ar[0]==ar[1] && ar[1]==ar[2] && ar[2]==n) { return true; } if(ar[0]==ar[3] && ar[3]==ar[6] && ar[6]==n) { return true; } if(ar[0]==ar[4] && ar[4]==ar[8] && ar[8]==n) { return true; } if(ar[1]==ar[4] && ar[4]==ar[7] && ar[7]==n) { return true; } if(ar[2]==ar[4] && ar[4]==ar[6] && ar[6]==n) { return true; } if(ar[2]==ar[5] && ar[5]==ar[8] && ar[8]==n) { return true; } if(ar[3]==ar[4] && ar[4]==ar[5] && ar[5]==n) { return true; } if(ar[6]==ar[7] && ar[7]==ar[8] && ar[8]==n) { return true; } return false; } bool isValid(char board[9]){ int co=0; int cx=0; for(int i=0;i<9;i++) { if(board[i]=='O') { co++; } else if(board[i]=='X') { cx++; } } if(abs(co-cx)>=2) { return false; } else if(abs(co-cx)==1) { char o = 'O'; char x = 'X'; bool a = solve(board,o); bool b = solve(board,x); if(a==true && b==true) { return false; } else if(a==false && b==false) { if(co<cx) { return true; } else { return false; } } else if(a==true && b==false) { return false; } else if(a==false && b==true) { if(co<cx){ return true; } else { return false; } } } } Time Taken : 0.0sec Cpp 0 gaurav79163 months ago bool isValid(char board[9]){ bool oo=false, xx=true; int cnto = 0, cntx = 0; for(int i=0; i<9; i++){ if(board[i] == 'O') cnto += 1; else cntx +=1; } int win[8][3]= {{0,1,2}, {3,4,5}, {6,7,8}, {0,3,6}, {1,4,7}, {2,5,8}, {0,4,8}, {2,4,6}}; for(int i=0; i<8; i++){ if(board[win[i][0]]=='O' && board[win[i][1]]=='O' && board[win[i][2]]=='O') oo=true; } if(oo == true || cntx-cnto != 1) return false; return true; } +1 noob14prosometime4 months ago bool iswin(char x,char a[]){ if(a[0]==a[1]&&a[1]==a[2]&&a[1]==x){ return 1; } if(a[3]==a[4]&&a[4]==a[5]&&a[5]==x){ return 1; } if(a[6]==a[7]&&a[7]==a[8]&&a[7]==x){ return 1; } if(a[0]==a[3]&&a[3]==a[6]&&a[6]==x){ return 1; } if(a[1]==a[4]&&a[4]==a[7]&&a[7]==x){ return 1; } if(a[2]==a[5]&&a[8]==a[5]&&a[5]==x){ return 1; } if(a[0]==a[4]&&a[4]==a[8]&&a[8]==x){ return 1; } if(a[2]==a[4]&&a[4]==a[6]&&a[6]==x){ return 1; } return 0; } bool isValid(char board[9]){ // code here int xcount=0; int ocount=0; for(int i=0;i<9;i++){ if(board[i]=='X'){ xcount++; } if(board[i]=='O'){ ocount++; } } if(xcount==ocount || xcount==ocount+1){ if(iswin('O',board)){ if(iswin('X',board)){ return 0; } return 0; } if(iswin('X',board)&&xcount!=ocount+1){ return 0; }else{ return 1; } }else{ return 0; } } 0 chamoliabhishek0077 months ago Python 0.0 soln def isValid(self, board): oo=False xx=True xcount=0 ycount=0 for i in range(9): if board[i]=='X': xcount+=1 if board[i]=='O': ycount+=1 if xcount-ycount!=1: return False win=[[0,1,2], [3,4,5], [6,7,8], [0,3,6], [1,4,7], [2,5,8], [0,4,8], [2,4,6]] for i in range(8): if board[win[i][0]]=='O' and board[win[i][1]]=='O' and board[win[i][2]]=='O': oo=True if board[win[i][0]]=='X' and board[win[i][1]]=='X' and board[win[i][2]]=='X': xx=True if (oo): return False return True 0 shadyboy7 months ago class Solution{ public: bool isValid(char board[9]){ bool oo = false; bool xx = false; int x = 0, y = 0; for(int i = 0; i < 9 ;i++){ if(board[i]=='O')x++; else y++; } if(y-x != 1)return false; for(int i = 0; i < 9 ;i+=3){ if(board[i] =='O' && board[i+1] =='O' && board[i+2]=='O'){ oo = true; } if(board[i] =='X' && board[i+1] =='X' && board[i+2]=='X'){ xx = true; } } for(int i = 0; i < 3 ;i++){ if(board[i] =='O' && board[i+3] =='O' && board[i+6]=='O'){ oo = true; } if(board[i] =='X' && board[i+3] =='X' && board[i+6]=='X'){ xx = true; } } if(board[0] =='O' && board[4] =='O' && board[8]=='O'){ oo = true; } if(board[0] =='X' && board[4] =='X' && board[8]=='X'){ xx = true; } if(board[2] =='O' && board[4] =='O' && board[6]=='O'){ oo = true; } if(board[2] =='X' && board[4] =='X' && board[6]=='X'){ xx = true; } if(oo)return false; return true; }}; 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": 409, "s": 238, "text": "A Tic-Tac-Toe board is given after some moves are played. Find out if the given board is valid, i.e., is it possible to reach this board position after some moves or not." }, { "code": null, "e": 580, "s": 409, "text": "Note that every arbitrary filled grid of 9 spaces isn’t valid e.g. a grid filled with 3 X and 6 O isn’t valid situation because each player needs to take alternate turns." }, { "code": null, "e": 611, "s": 580, "text": "Note : The game starts with X" }, { "code": null, "e": 623, "s": 611, "text": "\nExample 1:" }, { "code": null, "e": 761, "s": 623, "text": "Input:\nboard[] = {'X', 'X', 'O', \n 'O', 'O', 'X',\n 'X', 'O', 'X'};\nOutput: Valid\nExplanation: This is a valid board.\n" }, { "code": null, "e": 773, "s": 761, "text": "\nExample 2:" }, { "code": null, "e": 914, "s": 773, "text": "Input:\nboard[] = {'O', 'X', 'X', \n 'O', 'X', 'X',\n 'O', 'O', 'X'};\nOutput: Invalid\nExplanation: Both X and O cannot win." }, { "code": null, "e": 1164, "s": 914, "text": "\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function isValid() which takes a character array of size 9 representing the board as input parameter and returns a boolean value denoting if it is valid or not." }, { "code": null, "e": 1227, "s": 1164, "text": "\nExpected Time Complexity: O(1)\nExpected Auxiliary Space: O(1)" }, { "code": null, "e": 1296, "s": 1227, "text": "\nConstraints:\nEvery character on the board can either be 'X' or 'O'." }, { "code": null, "e": 1300, "s": 1298, "text": "0" }, { "code": null, "e": 1322, "s": 1300, "text": "lindan1232 months ago" }, { "code": null, "e": 3431, "s": 1322, "text": "public:\n bool solve(char ar[9],char n)\n {\n if(ar[0]==ar[1] && ar[1]==ar[2] && ar[2]==n)\n {\n return true;\n }\n if(ar[0]==ar[3] && ar[3]==ar[6] && ar[6]==n)\n {\n return true;\n }\n if(ar[0]==ar[4] && ar[4]==ar[8] && ar[8]==n)\n {\n return true;\n }\n if(ar[1]==ar[4] && ar[4]==ar[7] && ar[7]==n)\n {\n return true;\n }\n if(ar[2]==ar[4] && ar[4]==ar[6] && ar[6]==n)\n {\n return true;\n }\n if(ar[2]==ar[5] && ar[5]==ar[8] && ar[8]==n)\n {\n return true;\n }\n if(ar[3]==ar[4] && ar[4]==ar[5] && ar[5]==n)\n {\n return true;\n }\n if(ar[6]==ar[7] && ar[7]==ar[8] && ar[8]==n)\n {\n return true;\n }\n return false;\n }\n bool isValid(char board[9]){\n \n int co=0;\n int cx=0;\n for(int i=0;i<9;i++)\n {\n if(board[i]=='O')\n {\n co++;\n }\n else if(board[i]=='X')\n {\n cx++;\n }\n }\n if(abs(co-cx)>=2)\n {\n return false;\n }\n else if(abs(co-cx)==1)\n {\n char o = 'O';\n char x = 'X';\n bool a = solve(board,o);\n bool b = solve(board,x);\n if(a==true && b==true)\n {\n return false;\n }\n else if(a==false && b==false)\n {\n if(co<cx)\n {\n return true;\n }\n else\n {\n return false;\n }\n }\n else if(a==true && b==false)\n {\n return false;\n \n }\n else if(a==false && b==true)\n {\n if(co<cx){\n return true;\n }\n else\n {\n return false;\n }\n }\n }\n }" }, { "code": null, "e": 3451, "s": 3431, "text": "Time Taken : 0.0sec" }, { "code": null, "e": 3455, "s": 3451, "text": "Cpp" }, { "code": null, "e": 3457, "s": 3455, "text": "0" }, { "code": null, "e": 3480, "s": 3457, "text": "gaurav79163 months ago" }, { "code": null, "e": 4060, "s": 3480, "text": " bool isValid(char board[9]){\n bool oo=false, xx=true;\n int cnto = 0, cntx = 0;\n for(int i=0; i<9; i++){\n if(board[i] == 'O')\n cnto += 1;\n else \n cntx +=1;\n }\n int win[8][3]= {{0,1,2}, {3,4,5}, {6,7,8}, {0,3,6}, {1,4,7}, {2,5,8}, {0,4,8}, {2,4,6}};\n for(int i=0; i<8; i++){\n if(board[win[i][0]]=='O' && board[win[i][1]]=='O' && board[win[i][2]]=='O')\n oo=true;\n }\n if(oo == true || cntx-cnto != 1)\n return false;\n return true;\n }" }, { "code": null, "e": 4063, "s": 4060, "text": "+1" }, { "code": null, "e": 4093, "s": 4063, "text": "noob14prosometime4 months ago" }, { "code": null, "e": 5450, "s": 4093, "text": "bool iswin(char x,char a[]){\n if(a[0]==a[1]&&a[1]==a[2]&&a[1]==x){\n return 1;\n }\n if(a[3]==a[4]&&a[4]==a[5]&&a[5]==x){\n return 1;\n }\n if(a[6]==a[7]&&a[7]==a[8]&&a[7]==x){\n return 1;\n }\n if(a[0]==a[3]&&a[3]==a[6]&&a[6]==x){\n return 1;\n }\n if(a[1]==a[4]&&a[4]==a[7]&&a[7]==x){\n return 1;\n }\n if(a[2]==a[5]&&a[8]==a[5]&&a[5]==x){\n return 1;\n }\n if(a[0]==a[4]&&a[4]==a[8]&&a[8]==x){\n return 1;\n }\n if(a[2]==a[4]&&a[4]==a[6]&&a[6]==x){\n return 1;\n }\n return 0;\n }\n bool isValid(char board[9]){\n // code here\n int xcount=0;\n int ocount=0;\n for(int i=0;i<9;i++){\n if(board[i]=='X'){\n xcount++;\n }\n if(board[i]=='O'){\n ocount++;\n }\n }\n if(xcount==ocount || xcount==ocount+1){\n if(iswin('O',board)){\n if(iswin('X',board)){\n return 0;\n }\n return 0;\n \n }\n if(iswin('X',board)&&xcount!=ocount+1){\n return 0;\n }else{\n return 1;\n }\n }else{\n return 0;\n }\n \n }" }, { "code": null, "e": 5452, "s": 5450, "text": "0" }, { "code": null, "e": 5483, "s": 5452, "text": "chamoliabhishek0077 months ago" }, { "code": null, "e": 5499, "s": 5483, "text": "Python 0.0 soln" }, { "code": null, "e": 6292, "s": 5499, "text": " def isValid(self, board): oo=False xx=True xcount=0 ycount=0 for i in range(9): if board[i]=='X': xcount+=1 if board[i]=='O': ycount+=1 if xcount-ycount!=1: return False win=[[0,1,2], [3,4,5], [6,7,8], [0,3,6], [1,4,7], [2,5,8], [0,4,8], [2,4,6]] for i in range(8): if board[win[i][0]]=='O' and board[win[i][1]]=='O' and board[win[i][2]]=='O': oo=True if board[win[i][0]]=='X' and board[win[i][1]]=='X' and board[win[i][2]]=='X': xx=True if (oo): return False return True" }, { "code": null, "e": 6294, "s": 6292, "text": "0" }, { "code": null, "e": 6315, "s": 6294, "text": "shadyboy7 months ago" }, { "code": null, "e": 7572, "s": 6315, "text": "class Solution{ public: bool isValid(char board[9]){ bool oo = false; bool xx = false; int x = 0, y = 0; for(int i = 0; i < 9 ;i++){ if(board[i]=='O')x++; else y++; } if(y-x != 1)return false; for(int i = 0; i < 9 ;i+=3){ if(board[i] =='O' && board[i+1] =='O' && board[i+2]=='O'){ oo = true; } if(board[i] =='X' && board[i+1] =='X' && board[i+2]=='X'){ xx = true; } } for(int i = 0; i < 3 ;i++){ if(board[i] =='O' && board[i+3] =='O' && board[i+6]=='O'){ oo = true; } if(board[i] =='X' && board[i+3] =='X' && board[i+6]=='X'){ xx = true; } } if(board[0] =='O' && board[4] =='O' && board[8]=='O'){ oo = true; } if(board[0] =='X' && board[4] =='X' && board[8]=='X'){ xx = true; } if(board[2] =='O' && board[4] =='O' && board[6]=='O'){ oo = true; } if(board[2] =='X' && board[4] =='X' && board[6]=='X'){ xx = true; } if(oo)return false; return true; }};" }, { "code": null, "e": 7718, "s": 7572, "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": 7754, "s": 7718, "text": " Login to access your submissions. " }, { "code": null, "e": 7764, "s": 7754, "text": "\nProblem\n" }, { "code": null, "e": 7774, "s": 7764, "text": "\nContest\n" }, { "code": null, "e": 7837, "s": 7774, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 7985, "s": 7837, "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": 8193, "s": 7985, "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": 8299, "s": 8193, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
C++ Library - <map>
Map is dictionary like data structure. It is a sequence of (key, value) pair, where only single value is associated with each unique key. It is often referred as associative array. In map key values generally used to sort the elements. For map data type of key and value can differ and it is represented as typedef pair<const Key, T> value_type; Maps are typically implemented as Binary Search Tree. Zero sized maps are also valid. In that case map.begin() and map.end() points to same location. Below is definition of std::map from <map> header file template < class Key, class T, class Compare = less<Key>, class Alloc = allocator<pair<const Key,T> > > class map; Key βˆ’ Type of the key. Key βˆ’ Type of the key. T βˆ’ Type of the mapped values. T βˆ’ Type of the mapped values. Compare βˆ’ A binary predicate that takes two element keys as arguments and returns a bool. Compare βˆ’ A binary predicate that takes two element keys as arguments and returns a bool. Alloc βˆ’ Type of the allocator object. Alloc βˆ’ Type of the allocator object. T may be substituted by any other data type including user-defined type. Following member types can be used as parameters or return type by member functions. Below is list of all methods from <map> header. Constructs an empty map with zero elements. Constructs a map with as many elements as in range of first to last. Constructs a map with copy of each elements present in existing map. Constructs a map with the contents of other using move semantics. Constructs a map from initialize list. Destroys map object by deallocating it's memory. Returns a reference to the mapped value associated with key k. Returns a iterator which refers to the first element of the map. Returns a constant iterator which refers to the first element of the map. Returns a constant iterator which points to past-the-end element of the map. Destroys the map by removing all elements and sets size of map to zero. Returns number of mapped values associated with key k. Returns a constant reverse iterator which points to the last element of the container i. Returns a constant reverse iterator which points to the theoretical element preceding the first element in the container i. Extends container by inserting new element. Inserts a new element in a map using hint as a position for element. Tests whether map is empty or not. Returns an iterator which points to past-the-end element in the map. Returns range of elements that matches specific key. Removes single element of the map from position. Removes single element of the map from position. Removes mapped value associated with key k. Removes range of element from the the map. Removes range of element from the the map. Finds an element associated with key k. Returns an allocator associated with map. Extends container by inserting new element in map. Extends container by inserting new element in map. Extends container by inserting new elements in the map. Extends map by inserting new element. Extends map by inserting new element from initializer list. Returns a function object that compares the keys, which is a copy of this container's constructor argument comp. Returns an iterator pointing to the first element which is not less than key k. Returns the maximum number of elements can be held by map. Assign new contents to the map by replacing old ones and modifies size if necessary. Move the contents of one map into another and modifies size if necessary. Copy elements from initializer list to map. If key k matches an element in the container, then method returns a reference to the element. If key k matches an element in the container, then method returns a reference to the element. Returns a reverse iterator which points to the last element of the map. Returns a reverse iterator which points to the reverse end of the map i. Returns the number of elements present in the map. Exchanges the content of map with contents of map x. Returns an iterator pointing to the first element which is greater than key k. Returns a function object that compares objects of type std::map::value_type. Tests whether two maps are equal or not. Tests whether two maps are equal or not. Tests whether first map is less than other or not. Tests whether first map is less than or equal to other or not. Tests whether first map is greater than other or not. Tests whether first map is greater than or equal to other or not. Exchanges the content of map with contents of map x. Multimap is dictionary like data structure. It is a sequence of (key, value) pair, where multiple values can be associate with equivalent keys. It is often referred as associative array. In multimap key values generally used to sort the elements. For multimap data type of key and value can differ and it is represented as typedef pair<const Key, T> value_type; Multimaps are typically implemented as Binary Search Tree. Zero sized multimaps are also valid. In that case multimap.begin() and multimap.end() points to same location. Below is definition of std::multimap from <multimap> header file template < class Key, class T, class Compare = less<Key>, class Alloc = allocator<pair<const Key,T> > > class multimap; Key βˆ’ Type of the key. Key βˆ’ Type of the key. T βˆ’ Type of the mapped values. T βˆ’ Type of the mapped values. Compare βˆ’ A binary predicate that takes two element keys as arguments and returns a bool. Compare βˆ’ A binary predicate that takes two element keys as arguments and returns a bool. Alloc βˆ’ Type of the allocator object. Alloc βˆ’ Type of the allocator object. T may be substituted by any other data type including user-defined type. Following member types can be used as parameters or return type by member functions. Below is list of all methods from <multimap> header. Constructs an empty multimap with zero elements. Constructs a multimap with as many elements as in range of first to last. Constructs a multimap with copy of each elements present in existing multimap. Constructs a multimap with the contents of other using move semantics. Constructs a multimap from initialize list. Destroys multimap object by deallocating it's memory. Returns a iterator which refers to the first element of the multimap. Returns a constant iterator which refers to the first element of the multimap. Returns a constant iterator which points to past-the-end element of the multimap. Destroys the multimap by removing all elements and sets size of multimap to zero. Returns number of multimapped values associated with key k. Returns a constant reverse iterator which points to the last element of the container. Returns a constant reverse iterator which points to the theoretical element preceding the first element in the container. Extends container by inserting new element. Inserts a new element in a multimap using hint as a position for element. Tests whether multimap is empty or not. Returns an iterator which points to past-the-end element in the multimap. Returns range of elements that matches specific key. Removes single element of the multimap from position. Removes single element of the multimap from position. Removes mapped value associated with key k. Removes range of element from the the multimap. Removes range of element from the the multimap. Finds an element associated with key k. Returns an allocator associated with multimap. Extends container by inserting new element in multimap. Extends container by inserting new element in multimap. Extends container by inserting new elements in the multimap. Extends multimap by inserting new element. Extends multimap by inserting new element from initializer list. Returns a function object that compares the keys, which is a copy of this container's constructor argument comp. Returns an iterator pointing to the first element which is not less than key k. Returns the maximum number of elements can be held by multimap. Assign new contents to the multimap by replacing old ones and modifies size if necessary. Move the contents of one multimap into another and modifies size if necessary. Copy elements from initializer list to multimap. Returns a reverse iterator which points to the last element of the multimap. Returns a reverse iterator which points to the reverse end of the multimap. Returns the number of elements present in the multimap. Exchanges the content of multimap with contents of multimap x. Returns an iterator pointing to the first element which is greater than key k. Returns a function object that compares objects of type std::multimap::value_type. Tests whether two multimaps are equal or not. Tests whether two multimaps are equal or not. Tests whether first multimap is less than other or not. Tests whether first multimap is less than or equal to other or not. Tests whether first multimap is greater than other or not. Tests whether first multimap is greater than or equal to other or not. Exchanges the content of multimap with contents of multimap x. Print Add Notes Bookmark this page
[ { "code": null, "e": 2784, "s": 2603, "text": "Map is dictionary like data structure. It is a sequence of (key, value) pair, where only single value is associated with each unique key. It is often referred as associative array." }, { "code": null, "e": 2910, "s": 2784, "text": "In map key values generally used to sort the elements. For map data type of key and value can differ and it is represented as" }, { "code": null, "e": 2950, "s": 2910, "text": "typedef pair<const Key, T> value_type;\n" }, { "code": null, "e": 3004, "s": 2950, "text": "Maps are typically implemented as Binary Search Tree." }, { "code": null, "e": 3100, "s": 3004, "text": "Zero sized maps are also valid. In that case map.begin() and map.end() points to same location." }, { "code": null, "e": 3155, "s": 3100, "text": "Below is definition of std::map from <map> header file" }, { "code": null, "e": 3315, "s": 3155, "text": "template < class Key,\n class T,\n class Compare = less<Key>,\n class Alloc = allocator<pair<const Key,T> >\n > class map;\n" }, { "code": null, "e": 3338, "s": 3315, "text": "Key βˆ’ Type of the key." }, { "code": null, "e": 3361, "s": 3338, "text": "Key βˆ’ Type of the key." }, { "code": null, "e": 3392, "s": 3361, "text": "T βˆ’ Type of the mapped values." }, { "code": null, "e": 3423, "s": 3392, "text": "T βˆ’ Type of the mapped values." }, { "code": null, "e": 3513, "s": 3423, "text": "Compare βˆ’ A binary predicate that takes two element keys as arguments and returns a bool." }, { "code": null, "e": 3603, "s": 3513, "text": "Compare βˆ’ A binary predicate that takes two element keys as arguments and returns a bool." }, { "code": null, "e": 3641, "s": 3603, "text": "Alloc βˆ’ Type of the allocator object." }, { "code": null, "e": 3679, "s": 3641, "text": "Alloc βˆ’ Type of the allocator object." }, { "code": null, "e": 3752, "s": 3679, "text": "T may be substituted by any other data type including user-defined type." }, { "code": null, "e": 3837, "s": 3752, "text": "Following member types can be used as parameters or return type by member functions." }, { "code": null, "e": 3885, "s": 3837, "text": "Below is list of all methods from <map> header." }, { "code": null, "e": 3929, "s": 3885, "text": "Constructs an empty map with zero elements." }, { "code": null, "e": 3998, "s": 3929, "text": "Constructs a map with as many elements as in range of first to last." }, { "code": null, "e": 4067, "s": 3998, "text": "Constructs a map with copy of each elements present in existing map." }, { "code": null, "e": 4133, "s": 4067, "text": "Constructs a map with the contents of other using move semantics." }, { "code": null, "e": 4172, "s": 4133, "text": "Constructs a map from initialize list." }, { "code": null, "e": 4221, "s": 4172, "text": "Destroys map object by deallocating it's memory." }, { "code": null, "e": 4284, "s": 4221, "text": "Returns a reference to the mapped value associated with key k." }, { "code": null, "e": 4349, "s": 4284, "text": "Returns a iterator which refers to the first element of the map." }, { "code": null, "e": 4423, "s": 4349, "text": "Returns a constant iterator which refers to the first element of the map." }, { "code": null, "e": 4500, "s": 4423, "text": "Returns a constant iterator which points to past-the-end element of the map." }, { "code": null, "e": 4572, "s": 4500, "text": "Destroys the map by removing all elements and sets size of map to zero." }, { "code": null, "e": 4627, "s": 4572, "text": "Returns number of mapped values associated with key k." }, { "code": null, "e": 4716, "s": 4627, "text": "Returns a constant reverse iterator which points to the last element of the container i." }, { "code": null, "e": 4840, "s": 4716, "text": "Returns a constant reverse iterator which points to the theoretical element preceding the first element in the container i." }, { "code": null, "e": 4884, "s": 4840, "text": "Extends container by inserting new element." }, { "code": null, "e": 4953, "s": 4884, "text": "Inserts a new element in a map using hint as a position for element." }, { "code": null, "e": 4988, "s": 4953, "text": "Tests whether map is empty or not." }, { "code": null, "e": 5057, "s": 4988, "text": "Returns an iterator which points to past-the-end element in the map." }, { "code": null, "e": 5110, "s": 5057, "text": "Returns range of elements that matches specific key." }, { "code": null, "e": 5159, "s": 5110, "text": "Removes single element of the map from position." }, { "code": null, "e": 5208, "s": 5159, "text": "Removes single element of the map from position." }, { "code": null, "e": 5252, "s": 5208, "text": "Removes mapped value associated with key k." }, { "code": null, "e": 5295, "s": 5252, "text": "Removes range of element from the the map." }, { "code": null, "e": 5338, "s": 5295, "text": "Removes range of element from the the map." }, { "code": null, "e": 5378, "s": 5338, "text": "Finds an element associated with key k." }, { "code": null, "e": 5420, "s": 5378, "text": "Returns an allocator associated with map." }, { "code": null, "e": 5471, "s": 5420, "text": "Extends container by inserting new element in map." }, { "code": null, "e": 5522, "s": 5471, "text": "Extends container by inserting new element in map." }, { "code": null, "e": 5578, "s": 5522, "text": "Extends container by inserting new elements in the map." }, { "code": null, "e": 5616, "s": 5578, "text": "Extends map by inserting new element." }, { "code": null, "e": 5676, "s": 5616, "text": "Extends map by inserting new element from initializer list." }, { "code": null, "e": 5789, "s": 5676, "text": "Returns a function object that compares the keys, which is a copy of this container's constructor argument comp." }, { "code": null, "e": 5869, "s": 5789, "text": "Returns an iterator pointing to the first element which is not less than key k." }, { "code": null, "e": 5928, "s": 5869, "text": "Returns the maximum number of elements can be held by map." }, { "code": null, "e": 6013, "s": 5928, "text": "Assign new contents to the map by replacing old ones and modifies size if necessary." }, { "code": null, "e": 6087, "s": 6013, "text": "Move the contents of one map into another and modifies size if necessary." }, { "code": null, "e": 6131, "s": 6087, "text": "Copy elements from initializer list to map." }, { "code": null, "e": 6225, "s": 6131, "text": "If key k matches an element in the container, then method returns a reference to the element." }, { "code": null, "e": 6319, "s": 6225, "text": "If key k matches an element in the container, then method returns a reference to the element." }, { "code": null, "e": 6391, "s": 6319, "text": "Returns a reverse iterator which points to the last element of the map." }, { "code": null, "e": 6464, "s": 6391, "text": "Returns a reverse iterator which points to the reverse end of the map i." }, { "code": null, "e": 6515, "s": 6464, "text": "Returns the number of elements present in the map." }, { "code": null, "e": 6568, "s": 6515, "text": "Exchanges the content of map with contents of map x." }, { "code": null, "e": 6647, "s": 6568, "text": "Returns an iterator pointing to the first element which is greater than key k." }, { "code": null, "e": 6725, "s": 6647, "text": "Returns a function object that compares objects of type std::map::value_type." }, { "code": null, "e": 6766, "s": 6725, "text": "Tests whether two maps are equal or not." }, { "code": null, "e": 6807, "s": 6766, "text": "Tests whether two maps are equal or not." }, { "code": null, "e": 6858, "s": 6807, "text": "Tests whether first map is less than other or not." }, { "code": null, "e": 6921, "s": 6858, "text": "Tests whether first map is less than or equal to other or not." }, { "code": null, "e": 6975, "s": 6921, "text": "Tests whether first map is greater than other or not." }, { "code": null, "e": 7041, "s": 6975, "text": "Tests whether first map is greater than or equal to other or not." }, { "code": null, "e": 7094, "s": 7041, "text": "Exchanges the content of map with contents of map x." }, { "code": null, "e": 7281, "s": 7094, "text": "Multimap is dictionary like data structure. It is a sequence of (key, value) pair, where multiple values can be associate with equivalent keys. It is often referred as associative array." }, { "code": null, "e": 7417, "s": 7281, "text": "In multimap key values generally used to sort the elements. For multimap data type of key and value can differ and it is represented as" }, { "code": null, "e": 7457, "s": 7417, "text": "typedef pair<const Key, T> value_type;\n" }, { "code": null, "e": 7516, "s": 7457, "text": "Multimaps are typically implemented as Binary Search Tree." }, { "code": null, "e": 7627, "s": 7516, "text": "Zero sized multimaps are also valid. In that case multimap.begin() and multimap.end() points to same location." }, { "code": null, "e": 7692, "s": 7627, "text": "Below is definition of std::multimap from <multimap> header file" }, { "code": null, "e": 7857, "s": 7692, "text": "template < class Key,\n class T,\n class Compare = less<Key>,\n class Alloc = allocator<pair<const Key,T> >\n > class multimap;\n" }, { "code": null, "e": 7880, "s": 7857, "text": "Key βˆ’ Type of the key." }, { "code": null, "e": 7903, "s": 7880, "text": "Key βˆ’ Type of the key." }, { "code": null, "e": 7934, "s": 7903, "text": "T βˆ’ Type of the mapped values." }, { "code": null, "e": 7965, "s": 7934, "text": "T βˆ’ Type of the mapped values." }, { "code": null, "e": 8055, "s": 7965, "text": "Compare βˆ’ A binary predicate that takes two element keys as arguments and returns a bool." }, { "code": null, "e": 8145, "s": 8055, "text": "Compare βˆ’ A binary predicate that takes two element keys as arguments and returns a bool." }, { "code": null, "e": 8183, "s": 8145, "text": "Alloc βˆ’ Type of the allocator object." }, { "code": null, "e": 8221, "s": 8183, "text": "Alloc βˆ’ Type of the allocator object." }, { "code": null, "e": 8294, "s": 8221, "text": "T may be substituted by any other data type including user-defined type." }, { "code": null, "e": 8379, "s": 8294, "text": "Following member types can be used as parameters or return type by member functions." }, { "code": null, "e": 8432, "s": 8379, "text": "Below is list of all methods from <multimap> header." }, { "code": null, "e": 8481, "s": 8432, "text": "Constructs an empty multimap with zero elements." }, { "code": null, "e": 8555, "s": 8481, "text": "Constructs a multimap with as many elements as in range of first to last." }, { "code": null, "e": 8634, "s": 8555, "text": "Constructs a multimap with copy of each elements present in existing multimap." }, { "code": null, "e": 8705, "s": 8634, "text": "Constructs a multimap with the contents of other using move semantics." }, { "code": null, "e": 8749, "s": 8705, "text": "Constructs a multimap from initialize list." }, { "code": null, "e": 8803, "s": 8749, "text": "Destroys multimap object by deallocating it's memory." }, { "code": null, "e": 8873, "s": 8803, "text": "Returns a iterator which refers to the first element of the multimap." }, { "code": null, "e": 8952, "s": 8873, "text": "Returns a constant iterator which refers to the first element of the multimap." }, { "code": null, "e": 9034, "s": 8952, "text": "Returns a constant iterator which points to past-the-end element of the multimap." }, { "code": null, "e": 9116, "s": 9034, "text": "Destroys the multimap by removing all elements and sets size of multimap to zero." }, { "code": null, "e": 9176, "s": 9116, "text": "Returns number of multimapped values associated with key k." }, { "code": null, "e": 9263, "s": 9176, "text": "Returns a constant reverse iterator which points to the last element of the container." }, { "code": null, "e": 9385, "s": 9263, "text": "Returns a constant reverse iterator which points to the theoretical element preceding the first element in the container." }, { "code": null, "e": 9429, "s": 9385, "text": "Extends container by inserting new element." }, { "code": null, "e": 9503, "s": 9429, "text": "Inserts a new element in a multimap using hint as a position for element." }, { "code": null, "e": 9543, "s": 9503, "text": "Tests whether multimap is empty or not." }, { "code": null, "e": 9617, "s": 9543, "text": "Returns an iterator which points to past-the-end element in the multimap." }, { "code": null, "e": 9670, "s": 9617, "text": "Returns range of elements that matches specific key." }, { "code": null, "e": 9724, "s": 9670, "text": "Removes single element of the multimap from position." }, { "code": null, "e": 9778, "s": 9724, "text": "Removes single element of the multimap from position." }, { "code": null, "e": 9822, "s": 9778, "text": "Removes mapped value associated with key k." }, { "code": null, "e": 9870, "s": 9822, "text": "Removes range of element from the the multimap." }, { "code": null, "e": 9918, "s": 9870, "text": "Removes range of element from the the multimap." }, { "code": null, "e": 9958, "s": 9918, "text": "Finds an element associated with key k." }, { "code": null, "e": 10005, "s": 9958, "text": "Returns an allocator associated with multimap." }, { "code": null, "e": 10061, "s": 10005, "text": "Extends container by inserting new element in multimap." }, { "code": null, "e": 10117, "s": 10061, "text": "Extends container by inserting new element in multimap." }, { "code": null, "e": 10178, "s": 10117, "text": "Extends container by inserting new elements in the multimap." }, { "code": null, "e": 10221, "s": 10178, "text": "Extends multimap by inserting new element." }, { "code": null, "e": 10286, "s": 10221, "text": "Extends multimap by inserting new element from initializer list." }, { "code": null, "e": 10399, "s": 10286, "text": "Returns a function object that compares the keys, which is a copy of this container's constructor argument comp." }, { "code": null, "e": 10479, "s": 10399, "text": "Returns an iterator pointing to the first element which is not less than key k." }, { "code": null, "e": 10543, "s": 10479, "text": "Returns the maximum number of elements can be held by multimap." }, { "code": null, "e": 10633, "s": 10543, "text": "Assign new contents to the multimap by replacing old ones and modifies size if necessary." }, { "code": null, "e": 10712, "s": 10633, "text": "Move the contents of one multimap into another and modifies size if necessary." }, { "code": null, "e": 10761, "s": 10712, "text": "Copy elements from initializer list to multimap." }, { "code": null, "e": 10838, "s": 10761, "text": "Returns a reverse iterator which points to the last element of the multimap." }, { "code": null, "e": 10914, "s": 10838, "text": "Returns a reverse iterator which points to the reverse end of the multimap." }, { "code": null, "e": 10970, "s": 10914, "text": "Returns the number of elements present in the multimap." }, { "code": null, "e": 11033, "s": 10970, "text": "Exchanges the content of multimap with contents of multimap x." }, { "code": null, "e": 11112, "s": 11033, "text": "Returns an iterator pointing to the first element which is greater than key k." }, { "code": null, "e": 11195, "s": 11112, "text": "Returns a function object that compares objects of type std::multimap::value_type." }, { "code": null, "e": 11241, "s": 11195, "text": "Tests whether two multimaps are equal or not." }, { "code": null, "e": 11287, "s": 11241, "text": "Tests whether two multimaps are equal or not." }, { "code": null, "e": 11343, "s": 11287, "text": "Tests whether first multimap is less than other or not." }, { "code": null, "e": 11411, "s": 11343, "text": "Tests whether first multimap is less than or equal to other or not." }, { "code": null, "e": 11470, "s": 11411, "text": "Tests whether first multimap is greater than other or not." }, { "code": null, "e": 11541, "s": 11470, "text": "Tests whether first multimap is greater than or equal to other or not." }, { "code": null, "e": 11604, "s": 11541, "text": "Exchanges the content of multimap with contents of multimap x." }, { "code": null, "e": 11611, "s": 11604, "text": " Print" }, { "code": null, "e": 11622, "s": 11611, "text": " Add Notes" } ]
MATLAB - Data Import
Importing data in MATLAB means loading data from an external file. The importdata function allows loading various data files of different formats. It has the following five forms βˆ’ A = importdata(filename) Loads data into array A from the file denoted by filename. A = importdata('-pastespecial') Loads data from the system clipboard rather than from a file. A = importdata(___, delimiterIn) Interprets delimiterIn as the column separator in ASCII file, filename, or the clipboard data. You can use delimiterIn with any of the input arguments in the above syntaxes. A = importdata(___, delimiterIn, headerlinesIn) Loads data from ASCII file, filename, or the clipboard, reading numeric data starting from line headerlinesIn+1. [A, delimiterOut, headerlinesOut] = importdata(___) Returns the detected delimiter character for the input ASCII file in delimiterOut and the detected number of header lines in headerlinesOut, using any of the input arguments in the previous syntaxes. Let us load and display an image file. Create a script file and type the following code in it βˆ’ filename = 'smile.jpg'; A = importdata(filename); image(A); When you run the file, MATLAB displays the image file. However, you must store it in the current directory. In this example, we import a text file and specify Delimiter and Column Header. Let us create a space-delimited ASCII file with column headers, named weeklydata.txt. Our text file weeklydata.txt looks like this βˆ’ SunDay MonDay TuesDay WednesDay ThursDay FriDay SaturDay 95.01 76.21 61.54 40.57 55.79 70.28 81.53 73.11 45.65 79.19 93.55 75.29 69.87 74.68 60.68 41.85 92.18 91.69 81.32 90.38 74.51 48.60 82.14 73.82 41.03 0.99 67.22 93.18 89.13 44.47 57.63 89.36 13.89 19.88 46.60 Create a script file and type the following code in it βˆ’ filename = 'weeklydata.txt'; delimiterIn = ' '; headerlinesIn = 1; A = importdata(filename,delimiterIn,headerlinesIn); % View data for k = [1:7] disp(A.colheaders{1, k}) disp(A.data(:, k)) disp(' ') end When you run the file, it displays the following result βˆ’ SunDay 95.0100 73.1100 60.6800 48.6000 89.1300 MonDay 76.2100 45.6500 41.8500 82.1400 44.4700 TuesDay 61.5400 79.1900 92.1800 73.8200 57.6300 WednesDay 40.5700 93.5500 91.6900 41.0300 89.3600 ThursDay 55.7900 75.2900 81.3200 0.9900 13.8900 FriDay 70.2800 69.8700 90.3800 67.2200 19.8800 SaturDay 81.5300 74.6800 74.5100 93.1800 46.6000 In this example, let us import data from clipboard. Copy the following lines to the clipboard βˆ’ Mathematics is simple Create a script file and type the following code βˆ’ A = importdata('-pastespecial') When you run the file, it displays the following result βˆ’ A = 'Mathematics is simple' The importdata function is a high-level function. The low-level file I/O functions in MATLAB allow the most control over reading or writing data to a file. However, these functions need more detailed information about your file to work efficiently. MATLAB provides the following functions for read and write operations at the byte or character level βˆ’ MATLAB provides the following functions for low-level import of text data files βˆ’ The fscanf function reads formatted data in a text or ASCII file. The fscanf function reads formatted data in a text or ASCII file. The fgetl and fgets functions read one line of a file at a time, where a newline character separates each line. The fgetl and fgets functions read one line of a file at a time, where a newline character separates each line. The fread function reads a stream of data at the byte or bit level. The fread function reads a stream of data at the byte or bit level. We have a text data file 'myfile.txt' saved in our working directory. The file stores rainfall data for three months; June, July and August for the year 2012. The data in myfile.txt contains repeated sets of time, month and rainfall measurements at five places. The header data stores the number of months M; so we have M sets of measurements. The file looks like this βˆ’ Rainfall Data Months: June, July, August M = 3 12:00:00 June-2012 17.21 28.52 39.78 16.55 23.67 19.15 0.35 17.57 NaN 12.01 17.92 28.49 17.40 17.06 11.09 9.59 9.33 NaN 0.31 0.23 10.46 13.17 NaN 14.89 19.33 20.97 19.50 17.65 14.45 14.00 18.23 10.34 17.95 16.46 19.34 09:10:02 July-2012 12.76 16.94 14.38 11.86 16.89 20.46 23.17 NaN 24.89 19.33 30.97 49.50 47.65 24.45 34.00 18.23 30.34 27.95 16.46 19.34 30.46 33.17 NaN 34.89 29.33 30.97 49.50 47.65 24.45 34.00 28.67 30.34 27.95 36.46 29.34 15:03:40 August-2012 17.09 16.55 19.59 17.25 19.22 17.54 11.45 13.48 22.55 24.01 NaN 21.19 25.85 25.05 27.21 26.79 24.98 12.23 16.99 18.67 17.54 11.45 13.48 22.55 24.01 NaN 21.19 25.85 25.05 27.21 26.79 24.98 12.23 16.99 18.67 We will import data from this file and display this data. Take the following steps βˆ’ Open the file with fopen function and get the file identifier. Open the file with fopen function and get the file identifier. Describe the data in the file with format specifiers, such as '%s' for a string, '%d' for an integer, or '%f' for a floating-point number. Describe the data in the file with format specifiers, such as '%s' for a string, '%d' for an integer, or '%f' for a floating-point number. To skip literal characters in the file, include them in the format description. To skip a data field, use an asterisk ('*') in the specifier. For example, to read the headers and return the single value for M, we write βˆ’ M = fscanf(fid, '%*s %*s\n%*s %*s %*s %*s\nM=%d\n\n', 1); To skip literal characters in the file, include them in the format description. To skip a data field, use an asterisk ('*') in the specifier. For example, to read the headers and return the single value for M, we write βˆ’ M = fscanf(fid, '%*s %*s\n%*s %*s %*s %*s\nM=%d\n\n', 1); By default, fscanf reads data according to our format description until it does not find any match for the data, or it reaches the end of the file. Here we will use for loop for reading 3 sets of data and each time, it will read 7 rows and 5 columns. By default, fscanf reads data according to our format description until it does not find any match for the data, or it reaches the end of the file. Here we will use for loop for reading 3 sets of data and each time, it will read 7 rows and 5 columns. We will create a structure named mydata in the workspace to store data read from the file. This structure has three fields - time, month, and raindata array. We will create a structure named mydata in the workspace to store data read from the file. This structure has three fields - time, month, and raindata array. Create a script file and type the following code in it βˆ’ filename = '/data/myfile.txt'; rows = 7; cols = 5; % open the file fid = fopen(filename); % read the file headers, find M (number of months) M = fscanf(fid, '%*s %*s\n%*s %*s %*s %*s\nM=%d\n\n', 1); % read each set of measurements for n = 1:M mydata(n).time = fscanf(fid, '%s', 1); mydata(n).month = fscanf(fid, '%s', 1); % fscanf fills the array in column order, % so transpose the results mydata(n).raindata = ... fscanf(fid, '%f', [rows, cols]); end for n = 1:M disp(mydata(n).time), disp(mydata(n).month) disp(mydata(n).raindata) end % close the file fclose(fid); When you run the file, it displays the following result βˆ’ 12:00:00 June-2012 17.2100 17.5700 11.0900 13.1700 14.4500 28.5200 NaN 9.5900 NaN 14.0000 39.7800 12.0100 9.3300 14.8900 18.2300 16.5500 17.9200 NaN 19.3300 10.3400 23.6700 28.4900 0.3100 20.9700 17.9500 19.1500 17.4000 0.2300 19.5000 16.4600 0.3500 17.0600 10.4600 17.6500 19.3400 09:10:02 July-2012 12.7600 NaN 34.0000 33.1700 24.4500 16.9400 24.8900 18.2300 NaN 34.0000 14.3800 19.3300 30.3400 34.8900 28.6700 11.8600 30.9700 27.9500 29.3300 30.3400 16.8900 49.5000 16.4600 30.9700 27.9500 20.4600 47.6500 19.3400 49.5000 36.4600 23.1700 24.4500 30.4600 47.6500 29.3400 15:03:40 August-2012 17.0900 13.4800 27.2100 11.4500 25.0500 16.5500 22.5500 26.7900 13.4800 27.2100 19.5900 24.0100 24.9800 22.5500 26.7900 17.2500 NaN 12.2300 24.0100 24.9800 19.2200 21.1900 16.9900 NaN 12.2300 17.5400 25.8500 18.6700 21.1900 16.9900 11.4500 25.0500 17.5400 25.8500 18.6700 30 Lectures 4 hours Nouman Azam 127 Lectures 12 hours Nouman Azam 17 Lectures 3 hours Sanjeev 37 Lectures 5 hours TELCOMA Global 22 Lectures 4 hours TELCOMA Global 18 Lectures 3 hours Phinite Academy Print Add Notes Bookmark this page
[ { "code": null, "e": 2322, "s": 2141, "text": "Importing data in MATLAB means loading data from an external file. The importdata function allows loading various data files of different formats. It has the following five forms βˆ’" }, { "code": null, "e": 2347, "s": 2322, "text": "A = importdata(filename)" }, { "code": null, "e": 2406, "s": 2347, "text": "Loads data into array A from the file denoted by filename." }, { "code": null, "e": 2438, "s": 2406, "text": "A = importdata('-pastespecial')" }, { "code": null, "e": 2500, "s": 2438, "text": "Loads data from the system clipboard rather than from a file." }, { "code": null, "e": 2533, "s": 2500, "text": "A = importdata(___, delimiterIn)" }, { "code": null, "e": 2707, "s": 2533, "text": "Interprets delimiterIn as the column separator in ASCII file, filename, or the clipboard data. You can use delimiterIn with any of the input arguments in the above syntaxes." }, { "code": null, "e": 2755, "s": 2707, "text": "A = importdata(___, delimiterIn, headerlinesIn)" }, { "code": null, "e": 2868, "s": 2755, "text": "Loads data from ASCII file, filename, or the clipboard, reading numeric data starting from line headerlinesIn+1." }, { "code": null, "e": 2920, "s": 2868, "text": "[A, delimiterOut, headerlinesOut] = importdata(___)" }, { "code": null, "e": 3120, "s": 2920, "text": "Returns the detected delimiter character for the input ASCII file in delimiterOut and the detected number of header lines in headerlinesOut, using any of the input arguments in the previous syntaxes." }, { "code": null, "e": 3216, "s": 3120, "text": "Let us load and display an image file. Create a script file and type the following code in it βˆ’" }, { "code": null, "e": 3276, "s": 3216, "text": "filename = 'smile.jpg';\nA = importdata(filename);\nimage(A);" }, { "code": null, "e": 3384, "s": 3276, "text": "When you run the file, MATLAB displays the image file. However, you must store it in the current directory." }, { "code": null, "e": 3550, "s": 3384, "text": "In this example, we import a text file and specify Delimiter and Column Header. Let us create a space-delimited ASCII file with column headers, named weeklydata.txt." }, { "code": null, "e": 3597, "s": 3550, "text": "Our text file weeklydata.txt looks like this βˆ’" }, { "code": null, "e": 3961, "s": 3597, "text": "SunDay MonDay TuesDay WednesDay ThursDay FriDay SaturDay\n95.01 76.21 61.54 40.57 55.79 70.28 81.53\n73.11 45.65 79.19 93.55 75.29 69.87 74.68\n60.68 41.85 92.18 91.69 81.32 90.38 74.51\n48.60 82.14 73.82 41.03 0.99 67.22 93.18\n89.13 44.47 57.63 89.36 13.89 19.88 46.60\n" }, { "code": null, "e": 4018, "s": 3961, "text": "Create a script file and type the following code in it βˆ’" }, { "code": null, "e": 4231, "s": 4018, "text": "filename = 'weeklydata.txt';\ndelimiterIn = ' ';\nheaderlinesIn = 1;\nA = importdata(filename,delimiterIn,headerlinesIn);\n\n% View data\nfor k = [1:7]\n disp(A.colheaders{1, k})\n disp(A.data(:, k))\n disp(' ')\nend" }, { "code": null, "e": 4289, "s": 4231, "text": "When you run the file, it displays the following result βˆ’" }, { "code": null, "e": 4741, "s": 4289, "text": "SunDay\n 95.0100\n 73.1100\n 60.6800\n 48.6000\n 89.1300\n \nMonDay\n 76.2100\n 45.6500\n 41.8500\n 82.1400\n 44.4700\n \nTuesDay\n 61.5400\n 79.1900\n 92.1800\n 73.8200\n 57.6300\n\nWednesDay\n 40.5700\n 93.5500\n 91.6900\n 41.0300\n 89.3600\n \nThursDay\n 55.7900\n 75.2900\n 81.3200\n 0.9900\n 13.8900\n \nFriDay\n 70.2800\n 69.8700\n 90.3800\n 67.2200\n 19.8800\n\nSaturDay\n 81.5300\n 74.6800\n 74.5100\n 93.1800\n 46.6000\n" }, { "code": null, "e": 4793, "s": 4741, "text": "In this example, let us import data from clipboard." }, { "code": null, "e": 4837, "s": 4793, "text": "Copy the following lines to the clipboard βˆ’" }, { "code": null, "e": 4859, "s": 4837, "text": "Mathematics is simple" }, { "code": null, "e": 4910, "s": 4859, "text": "Create a script file and type the following code βˆ’" }, { "code": null, "e": 4943, "s": 4910, "text": "A = importdata('-pastespecial')\n" }, { "code": null, "e": 5001, "s": 4943, "text": "When you run the file, it displays the following result βˆ’" }, { "code": null, "e": 5034, "s": 5001, "text": "A = \n 'Mathematics is simple'\n" }, { "code": null, "e": 5283, "s": 5034, "text": "The importdata function is a high-level function. The low-level file I/O functions in MATLAB allow the most control over reading or writing data to a file. However, these functions need more detailed information about your file to work efficiently." }, { "code": null, "e": 5386, "s": 5283, "text": "MATLAB provides the following functions for read and write operations at the byte or character level βˆ’" }, { "code": null, "e": 5468, "s": 5386, "text": "MATLAB provides the following functions for low-level import of text data files βˆ’" }, { "code": null, "e": 5534, "s": 5468, "text": "The fscanf function reads formatted data in a text or ASCII file." }, { "code": null, "e": 5600, "s": 5534, "text": "The fscanf function reads formatted data in a text or ASCII file." }, { "code": null, "e": 5712, "s": 5600, "text": "The fgetl and fgets functions read one line of a file at a time, where a newline character separates each line." }, { "code": null, "e": 5824, "s": 5712, "text": "The fgetl and fgets functions read one line of a file at a time, where a newline character separates each line." }, { "code": null, "e": 5893, "s": 5824, "text": "The fread function reads a stream of data at the byte or bit level. " }, { "code": null, "e": 5962, "s": 5893, "text": "The fread function reads a stream of data at the byte or bit level. " }, { "code": null, "e": 6122, "s": 5962, "text": "We have a text data file 'myfile.txt' saved in our working directory. The file stores rainfall data for three months; June, July and August for the year 2012. " }, { "code": null, "e": 6307, "s": 6122, "text": "The data in myfile.txt contains repeated sets of time, month and rainfall measurements at five places. The header data stores the number of months M; so we have M sets of measurements." }, { "code": null, "e": 6334, "s": 6307, "text": "The file looks like this βˆ’" }, { "code": null, "e": 7137, "s": 6334, "text": "Rainfall Data\nMonths: June, July, August\n \nM = 3\n12:00:00\nJune-2012\n17.21 28.52 39.78 16.55 23.67\n19.15 0.35 17.57 NaN 12.01\n17.92 28.49 17.40 17.06 11.09\n9.59 9.33 NaN 0.31 0.23 \n10.46 13.17 NaN 14.89 19.33\n20.97 19.50 17.65 14.45 14.00\n18.23 10.34 17.95 16.46 19.34\n09:10:02\nJuly-2012\n12.76 16.94 14.38 11.86 16.89\n20.46 23.17 NaN 24.89 19.33\n30.97 49.50 47.65 24.45 34.00\n18.23 30.34 27.95 16.46 19.34\n30.46 33.17 NaN 34.89 29.33\n30.97 49.50 47.65 24.45 34.00\n28.67 30.34 27.95 36.46 29.34\n15:03:40\nAugust-2012\n17.09 16.55 19.59 17.25 19.22\n17.54 11.45 13.48 22.55 24.01\nNaN 21.19 25.85 25.05 27.21\n26.79 24.98 12.23 16.99 18.67\n17.54 11.45 13.48 22.55 24.01\nNaN 21.19 25.85 25.05 27.21\n26.79 24.98 12.23 16.99 18.67\n" }, { "code": null, "e": 7222, "s": 7137, "text": "We will import data from this file and display this data. Take the following steps βˆ’" }, { "code": null, "e": 7286, "s": 7222, "text": "Open the file with fopen function and get the file identifier. " }, { "code": null, "e": 7350, "s": 7286, "text": "Open the file with fopen function and get the file identifier. " }, { "code": null, "e": 7489, "s": 7350, "text": "Describe the data in the file with format specifiers, such as '%s' for a string, '%d' for an integer, or '%f' for a floating-point number." }, { "code": null, "e": 7628, "s": 7489, "text": "Describe the data in the file with format specifiers, such as '%s' for a string, '%d' for an integer, or '%f' for a floating-point number." }, { "code": null, "e": 7908, "s": 7628, "text": "To skip literal characters in the file, include them in the format description. To skip a data field, use an asterisk ('*') in the specifier.\nFor example, to read the headers and return the single value for M, we write βˆ’\nM = fscanf(fid, '%*s %*s\\n%*s %*s %*s %*s\\nM=%d\\n\\n', 1);\n" }, { "code": null, "e": 8050, "s": 7908, "text": "To skip literal characters in the file, include them in the format description. To skip a data field, use an asterisk ('*') in the specifier." }, { "code": null, "e": 8129, "s": 8050, "text": "For example, to read the headers and return the single value for M, we write βˆ’" }, { "code": null, "e": 8187, "s": 8129, "text": "M = fscanf(fid, '%*s %*s\\n%*s %*s %*s %*s\\nM=%d\\n\\n', 1);" }, { "code": null, "e": 8438, "s": 8187, "text": "By default, fscanf reads data according to our format description until it does not find any match for the data, or it reaches the end of the file. Here we will use for loop for reading 3 sets of data and each time, it will read 7 rows and 5 columns." }, { "code": null, "e": 8689, "s": 8438, "text": "By default, fscanf reads data according to our format description until it does not find any match for the data, or it reaches the end of the file. Here we will use for loop for reading 3 sets of data and each time, it will read 7 rows and 5 columns." }, { "code": null, "e": 8847, "s": 8689, "text": "We will create a structure named mydata in the workspace to store data read from the file. This structure has three fields - time, month, and raindata array." }, { "code": null, "e": 9005, "s": 8847, "text": "We will create a structure named mydata in the workspace to store data read from the file. This structure has three fields - time, month, and raindata array." }, { "code": null, "e": 9062, "s": 9005, "text": "Create a script file and type the following code in it βˆ’" }, { "code": null, "e": 9668, "s": 9062, "text": "filename = '/data/myfile.txt';\nrows = 7;\ncols = 5;\n \n% open the file\nfid = fopen(filename);\n \n% read the file headers, find M (number of months)\nM = fscanf(fid, '%*s %*s\\n%*s %*s %*s %*s\\nM=%d\\n\\n', 1);\n \n% read each set of measurements\nfor n = 1:M\n mydata(n).time = fscanf(fid, '%s', 1);\n mydata(n).month = fscanf(fid, '%s', 1);\n \n % fscanf fills the array in column order,\n % so transpose the results\n mydata(n).raindata = ...\n fscanf(fid, '%f', [rows, cols]);\nend\nfor n = 1:M\n disp(mydata(n).time), disp(mydata(n).month)\n disp(mydata(n).raindata)\nend\n \n% close the file\nfclose(fid);" }, { "code": null, "e": 9726, "s": 9668, "text": "When you run the file, it displays the following result βˆ’" }, { "code": null, "e": 10858, "s": 9726, "text": "12:00:00\nJune-2012\n 17.2100 17.5700 11.0900 13.1700 14.4500\n 28.5200 NaN 9.5900 NaN 14.0000\n 39.7800 12.0100 9.3300 14.8900 18.2300\n 16.5500 17.9200 NaN 19.3300 10.3400\n 23.6700 28.4900 0.3100 20.9700 17.9500\n 19.1500 17.4000 0.2300 19.5000 16.4600\n 0.3500 17.0600 10.4600 17.6500 19.3400\n\n09:10:02\nJuly-2012\n 12.7600 NaN 34.0000 33.1700 24.4500\n 16.9400 24.8900 18.2300 NaN 34.0000\n 14.3800 19.3300 30.3400 34.8900 28.6700\n 11.8600 30.9700 27.9500 29.3300 30.3400\n 16.8900 49.5000 16.4600 30.9700 27.9500\n 20.4600 47.6500 19.3400 49.5000 36.4600\n 23.1700 24.4500 30.4600 47.6500 29.3400\n\n15:03:40\nAugust-2012\n 17.0900 13.4800 27.2100 11.4500 25.0500\n 16.5500 22.5500 26.7900 13.4800 27.2100\n 19.5900 24.0100 24.9800 22.5500 26.7900\n 17.2500 NaN 12.2300 24.0100 24.9800\n 19.2200 21.1900 16.9900 NaN 12.2300\n 17.5400 25.8500 18.6700 21.1900 16.9900\n 11.4500 25.0500 17.5400 25.8500 18.6700\n" }, { "code": null, "e": 10891, "s": 10858, "text": "\n 30 Lectures \n 4 hours \n" }, { "code": null, "e": 10904, "s": 10891, "text": " Nouman Azam" }, { "code": null, "e": 10939, "s": 10904, "text": "\n 127 Lectures \n 12 hours \n" }, { "code": null, "e": 10952, "s": 10939, "text": " Nouman Azam" }, { "code": null, "e": 10985, "s": 10952, "text": "\n 17 Lectures \n 3 hours \n" }, { "code": null, "e": 10994, "s": 10985, "text": " Sanjeev" }, { "code": null, "e": 11027, "s": 10994, "text": "\n 37 Lectures \n 5 hours \n" }, { "code": null, "e": 11043, "s": 11027, "text": " TELCOMA Global" }, { "code": null, "e": 11076, "s": 11043, "text": "\n 22 Lectures \n 4 hours \n" }, { "code": null, "e": 11092, "s": 11076, "text": " TELCOMA Global" }, { "code": null, "e": 11125, "s": 11092, "text": "\n 18 Lectures \n 3 hours \n" }, { "code": null, "e": 11142, "s": 11125, "text": " Phinite Academy" }, { "code": null, "e": 11149, "s": 11142, "text": " Print" }, { "code": null, "e": 11160, "s": 11149, "text": " Add Notes" } ]
Setting the Image Brightness using CSS3
To set image brightness in CSS, use filter brightness(%). Remember, the value 0 makes the image black, 100% is for original image and default. Rest, you can set any value of your choice, but values above 100% would make the image brighter. Let us now see an example βˆ’ Live Demo <!DOCTYPE html> <html> <head> <style> img.demo { filter: brightness(120%); } </style> </head> <body> <h1>Learn MySQL</h1> <img src="https://www.tutorialspoint.com/mysql/images/mysql-mini-logo.jpg" alt="MySQL" width="160" height="150"> <h1>Learn MySQL</h1> <p>Below image is brighter than the original image above.</p> <img class="demo" src="https://www.tutorialspoint.com/mysql/images/mysql-mini-logo.jpg" alt="MySQL" width="160" height="150"> </body> </html>
[ { "code": null, "e": 1302, "s": 1062, "text": "To set image brightness in CSS, use filter brightness(%). Remember, the value 0 makes the image black, 100% is for original image and default. Rest, you can set any value of your choice, but values above 100% would make the image brighter." }, { "code": null, "e": 1330, "s": 1302, "text": "Let us now see an example βˆ’" }, { "code": null, "e": 1341, "s": 1330, "text": " Live Demo" }, { "code": null, "e": 1804, "s": 1341, "text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\nimg.demo {\n filter: brightness(120%);\n}\n</style>\n</head>\n<body>\n<h1>Learn MySQL</h1>\n<img src=\"https://www.tutorialspoint.com/mysql/images/mysql-mini-logo.jpg\" alt=\"MySQL\" width=\"160\" height=\"150\">\n<h1>Learn MySQL</h1>\n<p>Below image is brighter than the original image above.</p>\n<img class=\"demo\" src=\"https://www.tutorialspoint.com/mysql/images/mysql-mini-logo.jpg\" alt=\"MySQL\" width=\"160\" height=\"150\">\n</body>\n</html>" } ]
Estimating Parameters of Compartmental Models from Observed Data | by Abhay Shukla | Towards Data Science
In this post, we will define SEIR and SEIRD models and minimize nonlinear least squares to estimate their parameters from observed data of coronavirus cases. To perform well, nonlinear optimization techniques such as Levenberg–Marquardt (LM) algorithm need good initial guess to solve Nonlinear least squares optimization. We will use SEIR and SEIRD model simulation to guess parameter estimates and use these values in the optimization. Note that this is purely a programming and data science exercise, so refrain from drawing conclusions based on the simulations or parameter estimates. It’s best left to the experts in epidemiology and medicine. Before we get into the thick of things, let's familiarize ourselves with the type of models to which SEIR and SEIRD belong. However, if you want to jump right into code, the Jupyter notebooks with complete codes are available at Simulation & Parameter Estimation of SEIR Model and Simulation & Parameter Estimation of SEIRD Model. Mechanistic models are used to model and predict the spread of diseases and infections such as flu, Ebola or even coronavirus. A distinguishing feature of mechanistic models over machine learning models is their ability to encode hypothesized causal nature of disease transmission. This typically involves constructing mathematical formulations of causal mechanism and using analytical tools to validate these hypotheses with observed data [R. Baker et al., 2018]. In short, mechanistic models are interpretable while machine learning models, more often than not, are not. Because of this, a mechanistic model which explains the phenomenon well can give insightful information about how a disease spreads and possibly how it can be dealt with. The differences in types of data and information these two models provide are listed in Table 1 below. Compartmental models are a type of mechanistic models which divide the population into groups referred to as compartments. They are based on a system of ordinary differential equations which express the dynamics between different epidemiological states of a population (aka compartments). They are useful for short and long-term forecast of the spread of a phenomenon, e.g. a disease, and can also be used to study the effect of different interventions [Chowell, 2017]. The compartments and progression between epidemiological states in SEIR and SEIRD models are shown in Figure 1 and Figure 2 below. To check more details on dynamical systems of these models and how to simulate them in python, please refer to Simulating Compartmental Models in Epidemiology using Python & Jupyter Widgets. In this section, we will discuss data, models and minimizing nonlinear least squares for parameter estimation. We will use the data of coronavirus cases in India available at the COVID-19 REST API for India. The structure of JSON returned from the API is as follows, {'success': boolean, 'data': [ {'day': 'YYYY-MM-DD', 'summary': { 'total': int, 'confirmedCasesIndian': int, 'confirmedCasesForeign': int, 'discharged': int, 'deaths': int, 'confirmedButLocationUnidentified': int }, 'regional': [ { 'loc': string, 'confirmedCasesIndian': int, 'discharged': int, 'deaths': int, 'confirmedCasesForeign': int, 'totalConfirmed': int } ] } ], 'lastRefreshed': timestamp, 'lastOriginUpdate': timestamp} Sample of the data looks as below, { 'success': True, 'data': [ {'day': '2020-03-10', 'summary': { 'total': 47, 'confirmedCasesIndian': 31, 'confirmedCasesForeign': 16, 'discharged': 0, 'deaths': 0, 'confirmedButLocationUnidentified': 0 }, 'regional': [ { 'loc': 'Delhi', 'confirmedCasesIndian': 4, 'confirmedCasesForeign': 0, 'discharged': 0, 'deaths': 0, 'totalConfirmed': 4}, { 'loc': 'Haryana', 'confirmedCasesIndian': 0, 'confirmedCasesForeign': 14, 'discharged': 0, ... } ... ] } ... ], 'lastRefreshed': '2020-04-27T04:30:02.090Z', 'lastOriginUpdate': '2020-04-27T02:30:00.000Z'} This data can easily be transformed into a pandas data frame, we are familiar with using the following piece of code Let's see first 5 rows of the pandas data frame in Table 2 below, The total positive cases for coronavirus are still rising in India due to daily new non-zero positive cases. The trend of cases is shown in Figure 3 below. Now, let’s define the models in python. SEIR and SEIRD models are defined by a system of ordinary differential equations (ODEs). Let’s see what these ODEs are and how to code and solve them in python, SEIR Mathematical Model Python Code SEIRD Mathematical Model Python Code We will use odeint module in scipy to solve these systems of equations. Like the system of ODE’s, the function for solving the ODE’s is also very similar. Let’s see how it can be coded in Python for SEIRD model. To solve a system of ordinary differential equations, you need initial conditions and the parameters characterizing your ODE’s. You can observe these in the python code above. Next, we proceed to optimizing parameters of ODE’s using nonlinear least squares minimization. A nonlinear model is one where the relationship between output and input(s) is not linear in parameters of the model. E.g. Michaelis–Menten model cannot be expressed as a linear combination of the two betas. Now, nonlinear least squares can be defined as, β€œNon-linear least squares is the form of least squares analysis used to fit a set of m observations with a model that is non-linear in n unknown parameters (m β‰₯ n).” β€” Wikipedia Algorithms (such as LM) minimizing nonlinear least squares require a good initial parameter estimates which are closer to the optimal value. Next, we will use a simulation of the models to arrive at a good initial estimate. Simulation We will use a simulator of SEIR and SEIRD model built in the post Simulating Compartmental Models in Epidemiology using Python & Jupyter Widgets with some modifications for this purpose. Upon trying various combinations of parameters, beta (infection rate) = 1.14, sigma (incubation rate) = 0.02, gamma (recovery rate) = 0.02, mu (mortality rate) = 0.01, seems to be a reasonable initial estimates for SEIRD model. The simulator settings can be seen in Figure 7 below. A similar method can be used for SEIR model. Now, let's use the initial guess to further optimize the parameters using LM algorithm. Optimization Without going into too many details, in Levenberg–Marquardt algorithm, also known as the Damped least-squares (DLS) method, the change in weights in successive epochs is given by, We will use minimize module from lmfit library in python for minimization of nonlinear least squares using LM algorithm. minimize requires residuals as input along with other parameters of the model for optimization. Let's code the residuals and pass it to minimize as shown below, Now, minimization of nonlinear least squares with LM algorithm (leastsq) is straightforward, as shown in code below, After the optimization is complete, you can print the optimized model parameters and visualize the fit. Metrics We can also compute metrics like MAE and RMSE by using optimized parameters and calling ode_solver defined above. At the time of writing this post I found these values to be, Fitted MAEInfected: 587.5587793520101Recovered: 216.5347633701369Dead: 21.532532235433454Fitted RMSEInfected: 702.1643902204037Recovered: 284.9841911847741Dead: 26.4463792416788 You can also feed the optimized parameter values in the simulator to view what the epidemiological state curves look like, as shown in Figure 9. The jupyter notebooks with complete code are available at Simulation & Parameter Estimation of SEIR Model and Simulation & Parameter Estimation of SEIRD Model. In this post, we learned about, Mechanistic, compartmental, SEIR and SEIRD modelsCoding ODE’s in Python and solving themNonlinear models and nonlinear least squaresOptimizing parameters of ODE using SEIR/SEIRD simulator and minimize module in lmfit libraryUsing optimized parameters in a simulator to visualize epidemiological state curves Mechanistic, compartmental, SEIR and SEIRD models Coding ODE’s in Python and solving them Nonlinear models and nonlinear least squares Optimizing parameters of ODE using SEIR/SEIRD simulator and minimize module in lmfit library Using optimized parameters in a simulator to visualize epidemiological state curves *Note that the same approach can also be used to code and optimize any system of ODEs. Things we didn’t learn (a conscious choice) How to interpret the results of these epidemiological models.When will the curve flatten? How many will infect, recover, die etc? When can we re-start the economy? How to interpret the results of these epidemiological models. When will the curve flatten? How many will infect, recover, die etc? When can we re-start the economy? Let’s leave these important questions for experts to answer. Baker RE, PenΜƒa J-M, Jayamohan J and Jérusalem A., 2018, Mechanistic models versus machine learning, a fight worth fighting for the biological community? Biol. Lett.1420170660http://doi.org/10.1098/rsbl.2017.0660Chowell G., Fitting dynamic models to epidemic outbreaks with quantified uncertainty: A primer for parameter uncertainty, identifiability, and forecasts (2017), Infectious Disease Modelling Volume 2, Issue 3, August 2017, Pages 379–398Non-linear least squares (Wikipedia)Nonlinear regression (Wikipedia)Samarasinghe S., 2007, Neural Networks for Applied Sciences and Engineering Baker RE, PenΜƒa J-M, Jayamohan J and Jérusalem A., 2018, Mechanistic models versus machine learning, a fight worth fighting for the biological community? Biol. Lett.1420170660http://doi.org/10.1098/rsbl.2017.0660 Chowell G., Fitting dynamic models to epidemic outbreaks with quantified uncertainty: A primer for parameter uncertainty, identifiability, and forecasts (2017), Infectious Disease Modelling Volume 2, Issue 3, August 2017, Pages 379–398 Non-linear least squares (Wikipedia) Nonlinear regression (Wikipedia) Samarasinghe S., 2007, Neural Networks for Applied Sciences and Engineering
[ { "code": null, "e": 610, "s": 172, "text": "In this post, we will define SEIR and SEIRD models and minimize nonlinear least squares to estimate their parameters from observed data of coronavirus cases. To perform well, nonlinear optimization techniques such as Levenberg–Marquardt (LM) algorithm need good initial guess to solve Nonlinear least squares optimization. We will use SEIR and SEIRD model simulation to guess parameter estimates and use these values in the optimization." }, { "code": null, "e": 821, "s": 610, "text": "Note that this is purely a programming and data science exercise, so refrain from drawing conclusions based on the simulations or parameter estimates. It’s best left to the experts in epidemiology and medicine." }, { "code": null, "e": 945, "s": 821, "text": "Before we get into the thick of things, let's familiarize ourselves with the type of models to which SEIR and SEIRD belong." }, { "code": null, "e": 1152, "s": 945, "text": "However, if you want to jump right into code, the Jupyter notebooks with complete codes are available at Simulation & Parameter Estimation of SEIR Model and Simulation & Parameter Estimation of SEIRD Model." }, { "code": null, "e": 1617, "s": 1152, "text": "Mechanistic models are used to model and predict the spread of diseases and infections such as flu, Ebola or even coronavirus. A distinguishing feature of mechanistic models over machine learning models is their ability to encode hypothesized causal nature of disease transmission. This typically involves constructing mathematical formulations of causal mechanism and using analytical tools to validate these hypotheses with observed data [R. Baker et al., 2018]." }, { "code": null, "e": 1999, "s": 1617, "text": "In short, mechanistic models are interpretable while machine learning models, more often than not, are not. Because of this, a mechanistic model which explains the phenomenon well can give insightful information about how a disease spreads and possibly how it can be dealt with. The differences in types of data and information these two models provide are listed in Table 1 below." }, { "code": null, "e": 2469, "s": 1999, "text": "Compartmental models are a type of mechanistic models which divide the population into groups referred to as compartments. They are based on a system of ordinary differential equations which express the dynamics between different epidemiological states of a population (aka compartments). They are useful for short and long-term forecast of the spread of a phenomenon, e.g. a disease, and can also be used to study the effect of different interventions [Chowell, 2017]." }, { "code": null, "e": 2600, "s": 2469, "text": "The compartments and progression between epidemiological states in SEIR and SEIRD models are shown in Figure 1 and Figure 2 below." }, { "code": null, "e": 2791, "s": 2600, "text": "To check more details on dynamical systems of these models and how to simulate them in python, please refer to Simulating Compartmental Models in Epidemiology using Python & Jupyter Widgets." }, { "code": null, "e": 2902, "s": 2791, "text": "In this section, we will discuss data, models and minimizing nonlinear least squares for parameter estimation." }, { "code": null, "e": 3058, "s": 2902, "text": "We will use the data of coronavirus cases in India available at the COVID-19 REST API for India. The structure of JSON returned from the API is as follows," }, { "code": null, "e": 3891, "s": 3058, "text": "{'success': boolean, 'data': [ {'day': 'YYYY-MM-DD', 'summary': { 'total': int, 'confirmedCasesIndian': int, 'confirmedCasesForeign': int, 'discharged': int, 'deaths': int, 'confirmedButLocationUnidentified': int }, 'regional': [ { 'loc': string, 'confirmedCasesIndian': int, 'discharged': int, 'deaths': int, 'confirmedCasesForeign': int, 'totalConfirmed': int } ] } ], 'lastRefreshed': timestamp, 'lastOriginUpdate': timestamp}" }, { "code": null, "e": 3926, "s": 3891, "text": "Sample of the data looks as below," }, { "code": null, "e": 5054, "s": 3926, "text": "{ 'success': True, 'data': [ {'day': '2020-03-10', 'summary': { 'total': 47, 'confirmedCasesIndian': 31, 'confirmedCasesForeign': 16, 'discharged': 0, 'deaths': 0, 'confirmedButLocationUnidentified': 0 }, 'regional': [ { 'loc': 'Delhi', 'confirmedCasesIndian': 4, 'confirmedCasesForeign': 0, 'discharged': 0, 'deaths': 0, 'totalConfirmed': 4}, { 'loc': 'Haryana', 'confirmedCasesIndian': 0, 'confirmedCasesForeign': 14, 'discharged': 0, ... } ... ] } ... ], 'lastRefreshed': '2020-04-27T04:30:02.090Z', 'lastOriginUpdate': '2020-04-27T02:30:00.000Z'}" }, { "code": null, "e": 5171, "s": 5054, "text": "This data can easily be transformed into a pandas data frame, we are familiar with using the following piece of code" }, { "code": null, "e": 5237, "s": 5171, "text": "Let's see first 5 rows of the pandas data frame in Table 2 below," }, { "code": null, "e": 5393, "s": 5237, "text": "The total positive cases for coronavirus are still rising in India due to daily new non-zero positive cases. The trend of cases is shown in Figure 3 below." }, { "code": null, "e": 5433, "s": 5393, "text": "Now, let’s define the models in python." }, { "code": null, "e": 5594, "s": 5433, "text": "SEIR and SEIRD models are defined by a system of ordinary differential equations (ODEs). Let’s see what these ODEs are and how to code and solve them in python," }, { "code": null, "e": 5599, "s": 5594, "text": "SEIR" }, { "code": null, "e": 5618, "s": 5599, "text": "Mathematical Model" }, { "code": null, "e": 5630, "s": 5618, "text": "Python Code" }, { "code": null, "e": 5636, "s": 5630, "text": "SEIRD" }, { "code": null, "e": 5655, "s": 5636, "text": "Mathematical Model" }, { "code": null, "e": 5667, "s": 5655, "text": "Python Code" }, { "code": null, "e": 5879, "s": 5667, "text": "We will use odeint module in scipy to solve these systems of equations. Like the system of ODE’s, the function for solving the ODE’s is also very similar. Let’s see how it can be coded in Python for SEIRD model." }, { "code": null, "e": 6055, "s": 5879, "text": "To solve a system of ordinary differential equations, you need initial conditions and the parameters characterizing your ODE’s. You can observe these in the python code above." }, { "code": null, "e": 6150, "s": 6055, "text": "Next, we proceed to optimizing parameters of ODE’s using nonlinear least squares minimization." }, { "code": null, "e": 6273, "s": 6150, "text": "A nonlinear model is one where the relationship between output and input(s) is not linear in parameters of the model. E.g." }, { "code": null, "e": 6358, "s": 6273, "text": "Michaelis–Menten model cannot be expressed as a linear combination of the two betas." }, { "code": null, "e": 6584, "s": 6358, "text": "Now, nonlinear least squares can be defined as, β€œNon-linear least squares is the form of least squares analysis used to fit a set of m observations with a model that is non-linear in n unknown parameters (m β‰₯ n).” β€” Wikipedia" }, { "code": null, "e": 6808, "s": 6584, "text": "Algorithms (such as LM) minimizing nonlinear least squares require a good initial parameter estimates which are closer to the optimal value. Next, we will use a simulation of the models to arrive at a good initial estimate." }, { "code": null, "e": 6819, "s": 6808, "text": "Simulation" }, { "code": null, "e": 7006, "s": 6819, "text": "We will use a simulator of SEIR and SEIRD model built in the post Simulating Compartmental Models in Epidemiology using Python & Jupyter Widgets with some modifications for this purpose." }, { "code": null, "e": 7288, "s": 7006, "text": "Upon trying various combinations of parameters, beta (infection rate) = 1.14, sigma (incubation rate) = 0.02, gamma (recovery rate) = 0.02, mu (mortality rate) = 0.01, seems to be a reasonable initial estimates for SEIRD model. The simulator settings can be seen in Figure 7 below." }, { "code": null, "e": 7421, "s": 7288, "text": "A similar method can be used for SEIR model. Now, let's use the initial guess to further optimize the parameters using LM algorithm." }, { "code": null, "e": 7434, "s": 7421, "text": "Optimization" }, { "code": null, "e": 7614, "s": 7434, "text": "Without going into too many details, in Levenberg–Marquardt algorithm, also known as the Damped least-squares (DLS) method, the change in weights in successive epochs is given by," }, { "code": null, "e": 7896, "s": 7614, "text": "We will use minimize module from lmfit library in python for minimization of nonlinear least squares using LM algorithm. minimize requires residuals as input along with other parameters of the model for optimization. Let's code the residuals and pass it to minimize as shown below," }, { "code": null, "e": 8013, "s": 7896, "text": "Now, minimization of nonlinear least squares with LM algorithm (leastsq) is straightforward, as shown in code below," }, { "code": null, "e": 8117, "s": 8013, "text": "After the optimization is complete, you can print the optimized model parameters and visualize the fit." }, { "code": null, "e": 8125, "s": 8117, "text": "Metrics" }, { "code": null, "e": 8300, "s": 8125, "text": "We can also compute metrics like MAE and RMSE by using optimized parameters and calling ode_solver defined above. At the time of writing this post I found these values to be," }, { "code": null, "e": 8490, "s": 8300, "text": "Fitted MAEInfected: 587.5587793520101Recovered: 216.5347633701369Dead: 21.532532235433454Fitted RMSEInfected: 702.1643902204037Recovered: 284.9841911847741Dead: 26.4463792416788" }, { "code": null, "e": 8635, "s": 8490, "text": "You can also feed the optimized parameter values in the simulator to view what the epidemiological state curves look like, as shown in Figure 9." }, { "code": null, "e": 8795, "s": 8635, "text": "The jupyter notebooks with complete code are available at Simulation & Parameter Estimation of SEIR Model and Simulation & Parameter Estimation of SEIRD Model." }, { "code": null, "e": 8827, "s": 8795, "text": "In this post, we learned about," }, { "code": null, "e": 9135, "s": 8827, "text": "Mechanistic, compartmental, SEIR and SEIRD modelsCoding ODE’s in Python and solving themNonlinear models and nonlinear least squaresOptimizing parameters of ODE using SEIR/SEIRD simulator and minimize module in lmfit libraryUsing optimized parameters in a simulator to visualize epidemiological state curves" }, { "code": null, "e": 9185, "s": 9135, "text": "Mechanistic, compartmental, SEIR and SEIRD models" }, { "code": null, "e": 9225, "s": 9185, "text": "Coding ODE’s in Python and solving them" }, { "code": null, "e": 9270, "s": 9225, "text": "Nonlinear models and nonlinear least squares" }, { "code": null, "e": 9363, "s": 9270, "text": "Optimizing parameters of ODE using SEIR/SEIRD simulator and minimize module in lmfit library" }, { "code": null, "e": 9447, "s": 9363, "text": "Using optimized parameters in a simulator to visualize epidemiological state curves" }, { "code": null, "e": 9534, "s": 9447, "text": "*Note that the same approach can also be used to code and optimize any system of ODEs." }, { "code": null, "e": 9578, "s": 9534, "text": "Things we didn’t learn (a conscious choice)" }, { "code": null, "e": 9742, "s": 9578, "text": "How to interpret the results of these epidemiological models.When will the curve flatten? How many will infect, recover, die etc? When can we re-start the economy?" }, { "code": null, "e": 9804, "s": 9742, "text": "How to interpret the results of these epidemiological models." }, { "code": null, "e": 9907, "s": 9804, "text": "When will the curve flatten? How many will infect, recover, die etc? When can we re-start the economy?" }, { "code": null, "e": 9968, "s": 9907, "text": "Let’s leave these important questions for experts to answer." }, { "code": null, "e": 10560, "s": 9968, "text": "Baker RE, PenΜƒa J-M, Jayamohan J and Jérusalem A., 2018, Mechanistic models versus machine learning, a fight worth fighting for the biological community? Biol. Lett.1420170660http://doi.org/10.1098/rsbl.2017.0660Chowell G., Fitting dynamic models to epidemic outbreaks with quantified uncertainty: A primer for parameter uncertainty, identifiability, and forecasts (2017), Infectious Disease Modelling Volume 2, Issue 3, August 2017, Pages 379–398Non-linear least squares (Wikipedia)Nonlinear regression (Wikipedia)Samarasinghe S., 2007, Neural Networks for Applied Sciences and Engineering" }, { "code": null, "e": 10774, "s": 10560, "text": "Baker RE, PenΜƒa J-M, Jayamohan J and Jérusalem A., 2018, Mechanistic models versus machine learning, a fight worth fighting for the biological community? Biol. Lett.1420170660http://doi.org/10.1098/rsbl.2017.0660" }, { "code": null, "e": 11010, "s": 10774, "text": "Chowell G., Fitting dynamic models to epidemic outbreaks with quantified uncertainty: A primer for parameter uncertainty, identifiability, and forecasts (2017), Infectious Disease Modelling Volume 2, Issue 3, August 2017, Pages 379–398" }, { "code": null, "e": 11047, "s": 11010, "text": "Non-linear least squares (Wikipedia)" }, { "code": null, "e": 11080, "s": 11047, "text": "Nonlinear regression (Wikipedia)" } ]
How to count number of columns in a table with jQuery
To count number of columns in a table with jQuery, use the each() function with attr(). You can try to run the following code to learn how to count column in a table: Live Demo <html> <head> <title>jQuery Example</title> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script> $(document).ready(function(){ var num = 0; $('tr:nth-child(1) td').each(function () { if ($(this).attr('colspan')) { num += +$(this).attr('colspan'); } else { num++; } }); alert("Total Columns= "+num); }); </script> </head> <body> <table> <tr> <td>-1st column-</td> <td colspan="1">-2nd column-</td> <td colspan="1">-3rd column-</td> <tr> </table> </body> </html
[ { "code": null, "e": 1229, "s": 1062, "text": "To count number of columns in a table with jQuery, use the each() function with attr(). You can try to run the following code to learn how to count column in a table:" }, { "code": null, "e": 1239, "s": 1229, "text": "Live Demo" }, { "code": null, "e": 1843, "s": 1239, "text": "<html>\n <head>\n <title>jQuery Example</title>\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\"></script>\n <script>\n $(document).ready(function(){\n var num = 0;\n $('tr:nth-child(1) td').each(function () {\n if ($(this).attr('colspan')) {\n num += +$(this).attr('colspan');\n } else {\n num++;\n }\n });\n alert(\"Total Columns= \"+num);\n});\n</script>\n</head>\n<body>\n <table>\n <tr>\n <td>-1st column-</td>\n <td colspan=\"1\">-2nd column-</td>\n <td colspan=\"1\">-3rd column-</td>\n <tr>\n </table>\n</body>\n</html" } ]
Powerful Text Augmentation Using NLPAUG | by Raj Sangani | Towards Data Science
Data Augmentation is the practice of synthesizing new data from data at hand. This could be applied to any form of data from numbers to images. Usually, the augmented data is similar to the data that is already available. In all Machine Learning problems the dataset determines how well the problem can be solved. Sometimes we don’t have enough data to build robust models, and what’s even more common is having data with a palpable class imbalance. Say we are building a model which predicts one of two classes but we have 5000 samples of one class to train on and only 200 of the other class. In such a case our model will almost always predict the class with more samples since it has not been given enough data to discern between the two classes. We must then turn to collecting more data, but what if we can’t? One way is to generate exact copies of the 200 data samples that we have and decrease the imbalance. Although this does provide some improvement, the model is still learning from the same set of features! Perhaps a few artful tweaks can improve the quality of data we have. Think about it, to augment images we can just rotate , sharpen, or crop different areas of the images and the new data would still make some sense. However, augmenting text data is very difficult. For instance changing the order of words may at first seem plausible but sometimes this can completely alter the meaning of the sentence, say, for instance, I had my car cleaned is different from I had cleaned my car. Luckily, Edward Ma’s nlpaug gives us some amazing tools to augment text quickly. Let’s talk about some of them. Replace a few words with their synonyms.Replace a few words with words that have similar (based on cosine similarity) word embeddings (like word2vec or GloVe) to those words.Replace words based on the context using powerful transformer models (BERT).Use Back Translation , that is translate a sentence to another language and then translate it back to the original language which sometimes modifies a few words. Replace a few words with their synonyms. Replace a few words with words that have similar (based on cosine similarity) word embeddings (like word2vec or GloVe) to those words. Replace words based on the context using powerful transformer models (BERT). Use Back Translation , that is translate a sentence to another language and then translate it back to the original language which sometimes modifies a few words. I am going to be analysing a sentiment analysis problem which uses the Yelp Coffee reviews dataset from Kaggle. The dataset contains close to 7000 user reviews and ratings. The users have rated the coffee stores from 1 to 5, the higher the better. To create some imbalance I have discarded the neutral ratings (3) and have labelled all ratings greater than three as positive and all those lesser than 3 as negative. Here is an example review before preprocessing I am not a big fan of the accuracy metric when it comes to imbalanced classification and will hence mainly look at the area under the ROC curve as the evaluation metric. I have used a Random Forest Classifier with 10 estimators after some text preprocessing and cleaning. The text was vectorized using the Tfidf Vectorizer and the best 3000 feature vectors based on term frequency were chosen as input features to the classifier. The model is pretty straightforward and I have linked the entire code below. For eager readers who would like to first refer to the code, here it is! First, let’s have a look at the class imbalance. As you can see, the imbalance between positives and negatives is almost in the ratio 6.5 : 1 . So here are the results after training the RandomForest Classifier on the dataset. As you can see the Area Under Curve is 0.85 and to prove that the model only performing badly on the class with the lesser number of samples have a closer look at the classification report. The model’s recall and f1-score on the negative class (labelled 0) is absolutely terrible! This explains why the AUC is 0.85. Now, with minimal effort, we will improve on this AUC and f1-score through nlpaug. Please install nlpaug using pip. Please refer to my notebook to see the entire code. The following is just a small snippet. pip install nlpaug After this, I will be using the wordnet library to help with synonyms. Let’s pick a sentence from the dataset β€” β€œMisleading reviews. Worst coffee ever had, and sorely disappointing vibe.” import nlpaugimport nlpaug.augmenter.word as nawaug = naw.SynonymAug(aug_src='wordnet',aug_max=2)aug.augment("Misleading reviews. Worst coffee ever had, and sorely disappointing vibe.",n=2) In the above code aug_max indicates the maximum number of words we want to replace with their corresponding synonyms. In the last line n=2 indicates that we want to generate 2 augmented sentences. Here are the amazing results! β€˜Misleading review article. Worst coffee ever get, and sorely disappointing vibe.’ β€˜Lead astray reviews. Worst coffee ever had, and sorely dissatisfactory vibe.’ The augmenter replaced reviews with review article and had with get in the first sentence and in the second sentence misleading and disappointing were replaced with lead astray and dissatisfactory respectively . I decided to introduce 2 new augmented sentences for each sentence in the training set with the label 0 (negative reviews belonging to the minority class). In each of these augmented sentences I decided to replace a maximum of 3 words by their synonyms. You can play around with these parameters yourself and have some fun. Here is the distribution after augmenting the data. The minority class has tripled in size with some new meaningful data! WOW! We improved the AUC from 0.85 to 0.88 and improved the f1-score from 0.7 to 0.76. Although slightly, the ROC curve on the right covers more area and is better. What’s even better is that the augmentation only took 57 seconds on a CPU. This shows how beneficial Text Augmentation can be. At no point during the experiment did we change the model or tune it, all the improvement in performance was solely due to data augmentation.The nlpaug library provides even more powerful augmentation options using word embeddings, BERT Transformers, and Back Translation. The one we used is the cheapest option in terms of storage and execution speed!The augmentation took under a minute on the CPU which is pretty rapid.Please explore the link in the references for more ways to augment data.Finally we improved the AUC from 0.85 to 0.88 with very little effort (in terms of time) and less than 5 lines of code. At no point during the experiment did we change the model or tune it, all the improvement in performance was solely due to data augmentation. The nlpaug library provides even more powerful augmentation options using word embeddings, BERT Transformers, and Back Translation. The one we used is the cheapest option in terms of storage and execution speed! The augmentation took under a minute on the CPU which is pretty rapid. Please explore the link in the references for more ways to augment data. Finally we improved the AUC from 0.85 to 0.88 with very little effort (in terms of time) and less than 5 lines of code. The official Github Library of nlpaug which contains example notebooks The official Github Library of nlpaug which contains example notebooks Check out my GitHub for some other projects and the entire code. You can contact me on my website. I would love some feedback in the comments. Thank you for your time!
[ { "code": null, "e": 1262, "s": 172, "text": "Data Augmentation is the practice of synthesizing new data from data at hand. This could be applied to any form of data from numbers to images. Usually, the augmented data is similar to the data that is already available. In all Machine Learning problems the dataset determines how well the problem can be solved. Sometimes we don’t have enough data to build robust models, and what’s even more common is having data with a palpable class imbalance. Say we are building a model which predicts one of two classes but we have 5000 samples of one class to train on and only 200 of the other class. In such a case our model will almost always predict the class with more samples since it has not been given enough data to discern between the two classes. We must then turn to collecting more data, but what if we can’t? One way is to generate exact copies of the 200 data samples that we have and decrease the imbalance. Although this does provide some improvement, the model is still learning from the same set of features! Perhaps a few artful tweaks can improve the quality of data we have." }, { "code": null, "e": 1410, "s": 1262, "text": "Think about it, to augment images we can just rotate , sharpen, or crop different areas of the images and the new data would still make some sense." }, { "code": null, "e": 1677, "s": 1410, "text": "However, augmenting text data is very difficult. For instance changing the order of words may at first seem plausible but sometimes this can completely alter the meaning of the sentence, say, for instance, I had my car cleaned is different from I had cleaned my car." }, { "code": null, "e": 1789, "s": 1677, "text": "Luckily, Edward Ma’s nlpaug gives us some amazing tools to augment text quickly. Let’s talk about some of them." }, { "code": null, "e": 2201, "s": 1789, "text": "Replace a few words with their synonyms.Replace a few words with words that have similar (based on cosine similarity) word embeddings (like word2vec or GloVe) to those words.Replace words based on the context using powerful transformer models (BERT).Use Back Translation , that is translate a sentence to another language and then translate it back to the original language which sometimes modifies a few words." }, { "code": null, "e": 2242, "s": 2201, "text": "Replace a few words with their synonyms." }, { "code": null, "e": 2377, "s": 2242, "text": "Replace a few words with words that have similar (based on cosine similarity) word embeddings (like word2vec or GloVe) to those words." }, { "code": null, "e": 2454, "s": 2377, "text": "Replace words based on the context using powerful transformer models (BERT)." }, { "code": null, "e": 2616, "s": 2454, "text": "Use Back Translation , that is translate a sentence to another language and then translate it back to the original language which sometimes modifies a few words." }, { "code": null, "e": 3079, "s": 2616, "text": "I am going to be analysing a sentiment analysis problem which uses the Yelp Coffee reviews dataset from Kaggle. The dataset contains close to 7000 user reviews and ratings. The users have rated the coffee stores from 1 to 5, the higher the better. To create some imbalance I have discarded the neutral ratings (3) and have labelled all ratings greater than three as positive and all those lesser than 3 as negative. Here is an example review before preprocessing" }, { "code": null, "e": 3249, "s": 3079, "text": "I am not a big fan of the accuracy metric when it comes to imbalanced classification and will hence mainly look at the area under the ROC curve as the evaluation metric." }, { "code": null, "e": 3659, "s": 3249, "text": "I have used a Random Forest Classifier with 10 estimators after some text preprocessing and cleaning. The text was vectorized using the Tfidf Vectorizer and the best 3000 feature vectors based on term frequency were chosen as input features to the classifier. The model is pretty straightforward and I have linked the entire code below. For eager readers who would like to first refer to the code, here it is!" }, { "code": null, "e": 3803, "s": 3659, "text": "First, let’s have a look at the class imbalance. As you can see, the imbalance between positives and negatives is almost in the ratio 6.5 : 1 ." }, { "code": null, "e": 3886, "s": 3803, "text": "So here are the results after training the RandomForest Classifier on the dataset." }, { "code": null, "e": 4076, "s": 3886, "text": "As you can see the Area Under Curve is 0.85 and to prove that the model only performing badly on the class with the lesser number of samples have a closer look at the classification report." }, { "code": null, "e": 4285, "s": 4076, "text": "The model’s recall and f1-score on the negative class (labelled 0) is absolutely terrible! This explains why the AUC is 0.85. Now, with minimal effort, we will improve on this AUC and f1-score through nlpaug." }, { "code": null, "e": 4409, "s": 4285, "text": "Please install nlpaug using pip. Please refer to my notebook to see the entire code. The following is just a small snippet." }, { "code": null, "e": 4428, "s": 4409, "text": "pip install nlpaug" }, { "code": null, "e": 4499, "s": 4428, "text": "After this, I will be using the wordnet library to help with synonyms." }, { "code": null, "e": 4616, "s": 4499, "text": "Let’s pick a sentence from the dataset β€” β€œMisleading reviews. Worst coffee ever had, and sorely disappointing vibe.”" }, { "code": null, "e": 4806, "s": 4616, "text": "import nlpaugimport nlpaug.augmenter.word as nawaug = naw.SynonymAug(aug_src='wordnet',aug_max=2)aug.augment(\"Misleading reviews. Worst coffee ever had, and sorely disappointing vibe.\",n=2)" }, { "code": null, "e": 5003, "s": 4806, "text": "In the above code aug_max indicates the maximum number of words we want to replace with their corresponding synonyms. In the last line n=2 indicates that we want to generate 2 augmented sentences." }, { "code": null, "e": 5033, "s": 5003, "text": "Here are the amazing results!" }, { "code": null, "e": 5195, "s": 5033, "text": "β€˜Misleading review article. Worst coffee ever get, and sorely disappointing vibe.’ β€˜Lead astray reviews. Worst coffee ever had, and sorely dissatisfactory vibe.’" }, { "code": null, "e": 5407, "s": 5195, "text": "The augmenter replaced reviews with review article and had with get in the first sentence and in the second sentence misleading and disappointing were replaced with lead astray and dissatisfactory respectively ." }, { "code": null, "e": 5731, "s": 5407, "text": "I decided to introduce 2 new augmented sentences for each sentence in the training set with the label 0 (negative reviews belonging to the minority class). In each of these augmented sentences I decided to replace a maximum of 3 words by their synonyms. You can play around with these parameters yourself and have some fun." }, { "code": null, "e": 5853, "s": 5731, "text": "Here is the distribution after augmenting the data. The minority class has tripled in size with some new meaningful data!" }, { "code": null, "e": 5940, "s": 5853, "text": "WOW! We improved the AUC from 0.85 to 0.88 and improved the f1-score from 0.7 to 0.76." }, { "code": null, "e": 6145, "s": 5940, "text": "Although slightly, the ROC curve on the right covers more area and is better. What’s even better is that the augmentation only took 57 seconds on a CPU. This shows how beneficial Text Augmentation can be." }, { "code": null, "e": 6759, "s": 6145, "text": "At no point during the experiment did we change the model or tune it, all the improvement in performance was solely due to data augmentation.The nlpaug library provides even more powerful augmentation options using word embeddings, BERT Transformers, and Back Translation. The one we used is the cheapest option in terms of storage and execution speed!The augmentation took under a minute on the CPU which is pretty rapid.Please explore the link in the references for more ways to augment data.Finally we improved the AUC from 0.85 to 0.88 with very little effort (in terms of time) and less than 5 lines of code." }, { "code": null, "e": 6901, "s": 6759, "text": "At no point during the experiment did we change the model or tune it, all the improvement in performance was solely due to data augmentation." }, { "code": null, "e": 7113, "s": 6901, "text": "The nlpaug library provides even more powerful augmentation options using word embeddings, BERT Transformers, and Back Translation. The one we used is the cheapest option in terms of storage and execution speed!" }, { "code": null, "e": 7184, "s": 7113, "text": "The augmentation took under a minute on the CPU which is pretty rapid." }, { "code": null, "e": 7257, "s": 7184, "text": "Please explore the link in the references for more ways to augment data." }, { "code": null, "e": 7377, "s": 7257, "text": "Finally we improved the AUC from 0.85 to 0.88 with very little effort (in terms of time) and less than 5 lines of code." }, { "code": null, "e": 7448, "s": 7377, "text": "The official Github Library of nlpaug which contains example notebooks" }, { "code": null, "e": 7519, "s": 7448, "text": "The official Github Library of nlpaug which contains example notebooks" } ]
Bootstrap - Navbar
The navbar is one of the prominent features of Bootstrap sites. Navbars are responsive 'meta' components that serve as navigation headers for your application or site. Navbars collapse in mobile views and become horizontal as the available viewport width increases. At its core, the navbar includes styling for site names and basic navigation. To create a default navbar βˆ’ Add the classes .navbar, .navbar-default to the <nav> tag. Add the classes .navbar, .navbar-default to the <nav> tag. Add role = "navigation" to the above element, to help with accessibility. Add role = "navigation" to the above element, to help with accessibility. Add a header class .navbar-header to the <div> element. Include an <a> element with class navbar-brand. This will give the text a slightly larger size. Add a header class .navbar-header to the <div> element. Include an <a> element with class navbar-brand. This will give the text a slightly larger size. To add links to the navbar, simply add an unordered list with the classes of .nav, .navbar-nav. To add links to the navbar, simply add an unordered list with the classes of .nav, .navbar-nav. The following example demonstrates this βˆ’ <nav class = "navbar navbar-default" role = "navigation"> <div class = "navbar-header"> <a class = "navbar-brand" href = "#">TutorialsPoint</a> </div> <div> <ul class = "nav navbar-nav"> <li class = "active"><a href = "#">iOS</a></li> <li><a href = "#">SVN</a></li> <li class = "dropdown"> <a href = "#" class = "dropdown-toggle" data-toggle = "dropdown"> Java <b class = "caret"></b> </a> <ul class = "dropdown-menu"> <li><a href = "#">jmeter</a></li> <li><a href = "#">EJB</a></li> <li><a href = "#">Jasper Report</a></li> <li class = "divider"></li> <li><a href = "#">Separated link</a></li> <li class = "divider"></li> <li><a href = "#">One more separated link</a></li> </ul> </li> </ul> </div> </nav> iOS SVN Java jmeter EJB Jasper Report Separated link One more separated link jmeter EJB Jasper Report Separated link One more separated link To add responsive features to the navbar, the content that you want to be collapsed needs to be wrapped in a <div> with classes .collapse, .navbar-collapse. The collapsing nature is tripped by a button that has the class of .navbar-toggle and then features two data- elements. The first, data-toggle, is used to tell the JavaScript what to do with the button, and the second, data-target, indicates which element to toggle. Then with a class .icon-bar create what we like to call the hamburger button. This will toggle the elements that are in the .nav-collapse <div>. For this feature to work, you need to include the Bootstrap Collapse Plugin. The following example demonstrates this βˆ’ <nav class = "navbar navbar-default" role = "navigation"> <div class = "navbar-header"> <button type = "button" class = "navbar-toggle" data-toggle = "collapse" data-target = "#example-navbar-collapse"> <span class = "sr-only">Toggle navigation</span> <span class = "icon-bar"></span> <span class = "icon-bar"></span> <span class = "icon-bar"></span> </button> <a class = "navbar-brand" href = "#">TutorialsPoint</a> </div> <div class = "collapse navbar-collapse" id = "example-navbar-collapse"> <ul class = "nav navbar-nav"> <li class = "active"><a href = "#">iOS</a></li> <li><a href = "#">SVN</a></li> <li class = "dropdown"> <a href = "#" class = "dropdown-toggle" data-toggle = "dropdown"> Java <b class = "caret"></b> </a> <ul class = "dropdown-menu"> <li><a href = "#">jmeter</a></li> <li><a href = "#">EJB</a></li> <li><a href = "#">Jasper Report</a></li> <li class = "divider"></li> <li><a href = "#">Separated link</a></li> <li class = "divider"></li> <li><a href = "#">One more separated link</a></li> </ul> </li> </ul> </div> </nav> iOS SVN Java jmeter EJB Jasper Report Separated link One more separated link jmeter EJB Jasper Report Separated link One more separated link Instead of using the default class-based forms from Chapter Bootstrap Forms, forms that are in the navbar, use the .navbar-form class. This ensures that the form’s proper vertical alignment and collapsed behavior in narrow viewports. Use the alignment options (explained in Component alignment section) to decide where it resides within the navbar content. The following example demonstrates this βˆ’ <nav class = "navbar navbar-default" role = "navigation"> <div class = "navbar-header"> <a class = "navbar-brand" href = "#">TutorialsPoint</a> </div> <div> <form class = "navbar-form navbar-left" role = "search"> <div class = "form-group"> <input type = "text" class = "form-control" placeholder = "Search"> </div> <button type = "submit" class = "btn btn-default">Submit</button> </form> </div> </nav> You can add buttons using class .navbar-btn to <button> elements not residing in a <form> to vertically center them in the navbar. .navbar-btn can be used on <a> and <input> elements. The following example demonstrates this βˆ’ <nav class = "navbar navbar-default" role = "navigation"> <div class = "navbar-header"> <a class = "navbar-brand" href = "#">TutorialsPoint</a> </div> <div> <form class = "navbar-form navbar-left" role = "search"> <div class = "form-group"> <input type = "text" class = "form-control" placeholder = "Search"> </div> <button type = "submit" class = "btn btn-default">Submit Button</button> </form> <button type = "button" class = "btn btn-default navbar-btn">Navbar Button</button> </div> </nav> To wrap strings of text in an element use the class .navbar-text. This is usually used with <p> tag for proper leading and color. The following example demonstrates this βˆ’ <nav class = "navbar navbar-default" role = "navigation"> <div class = "navbar-header"> <a class = "navbar-brand" href = "#">TutorialsPoint</a> </div> <div> <p class = "navbar-text">Signed in as Thomas</p> </div> </nav> Signed in as Thomas If you want to use the standard links that are not within the regular navbar navigation component, then use the class navbar-link to add proper colors for the default and inverse navbar options as shown in the following example βˆ’ <nav class = "navbar navbar-default" role = "navigation"> <div class = "navbar-header"> <a class = "navbar-brand" href = "#">TutorialsPoint</a> </div> <div> <p class = "navbar-text navbar-right"> Signed in as <a href = "#" class = "navbar-link">Thomas</a> </p> </div> </nav> Signed in as Thomas You can align the components like nav links, forms, buttons, or text to left or right in a navbar using the utility classes .navbar-left or .navbar-right. Both classes will add a CSS float in the specified direction. The following example demonstrates this βˆ’ <nav class = "navbar navbar-default" role = "navigation"> <div class = "navbar-header"> <a class = "navbar-brand" href = "#">TutorialsPoint</a> </div> <div> <!--Left Align--> <ul class = "nav navbar-nav navbar-left"> <li class = "dropdown"> <a href = "#" class = "dropdown-toggle" data-toggle = "dropdown"> Java <b class = "caret"></b> </a> <ul class = "dropdown-menu"> <li><a href = "#">jmeter</a></li> <li><a href = "#">EJB</a></li> <li><a href = "#">Jasper Report</a></li> <li class = "divider"></li> <li><a href = "#">Separated link</a></li> <li class = "divider"></li> <li><a href = "#">One more separated link</a></li> </ul> </li> </ul> <form class = "navbar-form navbar-left" role = "search"> <button type = "submit" class = "btn btn-default">Left align-Submit Button</button> </form> <p class = "navbar-text navbar-left">Left align-Text</p> <!--Right Align--> <ul class = "nav navbar-nav navbar-right"> <li class = "dropdown"> <a href = "#" class = "dropdown-toggle" data-toggle = "dropdown"> Java <b class = "caret"></b> </a> <ul class = "dropdown-menu"> <li><a href = "#">jmeter</a></li> <li><a href = "#">EJB</a></li> <li><a href = "#">Jasper Report</a></li> <li class = "divider"></li> <li><a href = "#">Separated link</a></li> <li class = "divider"></li> <li><a href = "#">One more separated link</a></li> </ul> </li> </ul> <form class = "navbar-form navbar-right" role = "search"> <button type = "submit" class = "btn btn-default"> Right align-Submit Button </button> </form> <p class = "navbar-text navbar-right">Right align-Text</p> </div> </nav> Java jmeter EJB Jasper Report Separated link One more separated link jmeter EJB Jasper Report Separated link One more separated link Left align-Text Java jmeter EJB Jasper Report Separated link One more separated link jmeter EJB Jasper Report Separated link One more separated link Right align-Text The Bootstrap navbar can be dynamic in its positioning. By default, it is a block-level element that takes its positioning based on its placement in the HTML. With a few helper classes, you can place it either on the top or bottom of the page, or you can make it scroll statically with the page. If you want the navbar fixed to the top, add class .navbar-fixed-top to the .navbar class. The following example demonstrates this βˆ’ <nav class = "navbar navbar-default navbar-fixed-top" role = "navigation"> <div class = "navbar-header"> <a class = "navbar-brand" href = "#">TutorialsPoint</a> </div> <div> <ul class = "nav navbar-nav"> <li class = "active"><a href = "#">iOS</a></li> <li><a href = "#">SVN</a></li> <li class = "dropdown"> <a href = "#" class = "dropdown-toggle" data-toggle = "dropdown"> Java <b class = "caret"></b> </a> <ul class = "dropdown-menu"> <li><a href = "#">jmeter</a></li> <li><a href = "#">EJB</a></li> <li><a href = "#">Jasper Report</a></li> <li class = "divider"></li> <li><a href = "#">Separated link</a></li> <li class = "divider"></li> <li><a href = "#">One more separated link</a></li> </ul> </li> </ul> </div> </nav> If you want the navbar fixed to the bottom of the page, add class .navbar-fixed-bottom to the .navbar class. The following example demonstrates this βˆ’ <nav class = "navbar navbar-default navbar-fixed-bottom" role = "navigation"> <div class = "navbar-header"> <a class = "navbar-brand" href = "#">TutorialsPoint</a> </div> <div> <ul class = "nav navbar-nav"> <li class = "active"><a href = "#">iOS</a></li> <li><a href="#">SVN</a></li> <li class = "dropdown"> <a href = "#" class = "dropdown-toggle" data-toggle = "dropdown"> Java <b class ="caret"></b> </a> <ul class = "dropdown-menu"> <li><a href = "#">jmeter</a></li> <li><a href = "#">EJB</a></li> <li><a href = "#">Jasper Report</a></li> <li class = "divider"></li> <li><a href = "#">Separated link</a></li> <li class = "divider"></li> <li><a href = "#">One more separated link</a></li> </ul> </li> </ul> </div> </nav> iOS SVN Java jmeter EJB Jasper Report Separated link One more separated link jmeter EJB Jasper Report Separated link One more separated link To create a navbar that scrolls with the page, add the .navbar-static-top class. This class does not require adding the padding to the <body>. <nav class = "navbar navbar-default navbar-static-top" role = "navigation"> <div class = "navbar-header"> <a class = "navbar-brand" href = "#">TutorialsPoint</a> </div> <div> <ul class = "nav navbar-nav"> <li class = "active"><a href = "#">iOS</a></li> <li><a href = "#">SVN</a></li> <li class = "dropdown"> <a href = "#" class = "dropdown-toggle" data-toggle = "dropdown"> Java <b class = "caret"></b> </a> <ul class = "dropdown-menu"> <li><a href = "#">jmeter</a></li> <li><a href = "#">EJB</a></li> <li><a href = "#">Jasper Report</a></li> <li class = "divider"></li> <li><a href = "#">Separated link</a></li> <li class = "divider"></li> <li><a href = "#">One more separated link</a></li> </ul> </li> </ul> </div> </nav> iOS SVN Java jmeter EJB Jasper Report Separated link One more separated link jmeter EJB Jasper Report Separated link One more separated link To create an inverted navbar with a black background and with white text, simply add the .navbar-inverse class to the .navbar class as demonstrated in the following example βˆ’ <nav class = "navbar navbar-inverse" role = "navigation"> <div class = "navbar-header"> <a class = "navbar-brand" href = "#">TutorialsPoint</a> </div> <div> <ul class = "nav navbar-nav"> <li class = "active"><a href = "#">iOS</a></li> <li><a href = "#">SVN</a></li> <li class = "dropdown"> <a href = "#" class = "dropdown-toggle" data-toggle = "dropdown"> Java <b class = "caret"></b> </a> <ul class = "dropdown-menu"> <li><a href = "#">jmeter</a></li> <li><a href = "#">EJB</a></li> <li><a href = "#">Jasper Report</a></li> <li class = "divider"></li> <li><a href = "#">Separated link</a></li> <li class = "divider"></li> <li><a href = "#">One more separated link</a></li> </ul> </li> </ul> </div> </nav> iOS SVN Java jmeter EJB Jasper Report Separated link One more separated link jmeter EJB Jasper Report Separated link One more separated link 26 Lectures 2 hours Anadi Sharma 54 Lectures 4.5 hours Frahaan Hussain 161 Lectures 14.5 hours Eduonix Learning Solutions 20 Lectures 4 hours Azaz Patel 15 Lectures 1.5 hours Muhammad Ismail 62 Lectures 8 hours Yossef Ayman Zedan Print Add Notes Bookmark this page
[ { "code": null, "e": 3675, "s": 3331, "text": "The navbar is one of the prominent features of Bootstrap sites. Navbars are responsive 'meta' components that serve as navigation headers for your application or site. Navbars collapse in mobile views and become horizontal as the available viewport width increases. At its core, the navbar includes styling for site names and basic navigation." }, { "code": null, "e": 3704, "s": 3675, "text": "To create a default navbar βˆ’" }, { "code": null, "e": 3763, "s": 3704, "text": "Add the classes .navbar, .navbar-default to the <nav> tag." }, { "code": null, "e": 3822, "s": 3763, "text": "Add the classes .navbar, .navbar-default to the <nav> tag." }, { "code": null, "e": 3896, "s": 3822, "text": "Add role = \"navigation\" to the above element, to help with accessibility." }, { "code": null, "e": 3970, "s": 3896, "text": "Add role = \"navigation\" to the above element, to help with accessibility." }, { "code": null, "e": 4122, "s": 3970, "text": "Add a header class .navbar-header to the <div> element. Include an <a> element with class navbar-brand. This will give the text a slightly larger size." }, { "code": null, "e": 4274, "s": 4122, "text": "Add a header class .navbar-header to the <div> element. Include an <a> element with class navbar-brand. This will give the text a slightly larger size." }, { "code": null, "e": 4370, "s": 4274, "text": "To add links to the navbar, simply add an unordered list with the classes of .nav, .navbar-nav." }, { "code": null, "e": 4466, "s": 4370, "text": "To add links to the navbar, simply add an unordered list with the classes of .nav, .navbar-nav." }, { "code": null, "e": 4508, "s": 4466, "text": "The following example demonstrates this βˆ’" }, { "code": null, "e": 5518, "s": 4508, "text": "<nav class = \"navbar navbar-default\" role = \"navigation\">\n\n <div class = \"navbar-header\">\n <a class = \"navbar-brand\" href = \"#\">TutorialsPoint</a>\n </div>\n \n <div>\n <ul class = \"nav navbar-nav\">\n <li class = \"active\"><a href = \"#\">iOS</a></li>\n <li><a href = \"#\">SVN</a></li>\n\t\t\t\n <li class = \"dropdown\">\n <a href = \"#\" class = \"dropdown-toggle\" data-toggle = \"dropdown\">\n Java \n <b class = \"caret\"></b>\n </a>\n \n <ul class = \"dropdown-menu\">\n <li><a href = \"#\">jmeter</a></li>\n <li><a href = \"#\">EJB</a></li>\n <li><a href = \"#\">Jasper Report</a></li>\n \n <li class = \"divider\"></li>\n <li><a href = \"#\">Separated link</a></li>\n \n <li class = \"divider\"></li>\n <li><a href = \"#\">One more separated link</a></li>\n </ul>\n </li>\n </ul>\n </div>\n</nav>" }, { "code": null, "e": 5522, "s": 5518, "text": "iOS" }, { "code": null, "e": 5526, "s": 5522, "text": "SVN" }, { "code": null, "e": 5641, "s": 5526, "text": "\n\n Java \n \n\n\njmeter\nEJB\nJasper Report\n\nSeparated link\n\nOne more separated link\n\n" }, { "code": null, "e": 5648, "s": 5641, "text": "jmeter" }, { "code": null, "e": 5652, "s": 5648, "text": "EJB" }, { "code": null, "e": 5666, "s": 5652, "text": "Jasper Report" }, { "code": null, "e": 5681, "s": 5666, "text": "Separated link" }, { "code": null, "e": 5705, "s": 5681, "text": "One more separated link" }, { "code": null, "e": 6352, "s": 5705, "text": "To add responsive features to the navbar, the content that you want to be collapsed needs to be wrapped in a <div> with classes .collapse, .navbar-collapse. The collapsing nature is tripped by a button that has the class of .navbar-toggle and then features two data- elements. The first, data-toggle, is used to tell the JavaScript what to do with the button, and the second, data-target, indicates which element to toggle. Then with a class .icon-bar create what we like to call the hamburger button. This will toggle the elements that are in the .nav-collapse <div>. For this feature to work, you need to include the Bootstrap Collapse Plugin." }, { "code": null, "e": 6394, "s": 6352, "text": "The following example demonstrates this βˆ’" }, { "code": null, "e": 7809, "s": 6394, "text": "<nav class = \"navbar navbar-default\" role = \"navigation\">\n \n <div class = \"navbar-header\">\n <button type = \"button\" class = \"navbar-toggle\" \n data-toggle = \"collapse\" data-target = \"#example-navbar-collapse\">\n <span class = \"sr-only\">Toggle navigation</span>\n <span class = \"icon-bar\"></span>\n <span class = \"icon-bar\"></span>\n <span class = \"icon-bar\"></span>\n </button>\n\t\t\n <a class = \"navbar-brand\" href = \"#\">TutorialsPoint</a>\n </div>\n \n <div class = \"collapse navbar-collapse\" id = \"example-navbar-collapse\">\n\t\n <ul class = \"nav navbar-nav\">\n <li class = \"active\"><a href = \"#\">iOS</a></li>\n <li><a href = \"#\">SVN</a></li>\n\t\t\t\n <li class = \"dropdown\">\n <a href = \"#\" class = \"dropdown-toggle\" data-toggle = \"dropdown\">\n Java \n <b class = \"caret\"></b>\n </a>\n \n <ul class = \"dropdown-menu\">\n <li><a href = \"#\">jmeter</a></li>\n <li><a href = \"#\">EJB</a></li>\n <li><a href = \"#\">Jasper Report</a></li>\n \n <li class = \"divider\"></li>\n <li><a href = \"#\">Separated link</a></li>\n \n <li class = \"divider\"></li>\n <li><a href = \"#\">One more separated link</a></li>\n </ul>\n </li>\n </ul>\n </div>\n</nav>" }, { "code": null, "e": 7813, "s": 7809, "text": "iOS" }, { "code": null, "e": 7817, "s": 7813, "text": "SVN" }, { "code": null, "e": 7938, "s": 7817, "text": "\n\n Java \n \n\n\njmeter\nEJB\nJasper Report\n\nSeparated link\n\nOne more separated link\n\n" }, { "code": null, "e": 7945, "s": 7938, "text": "jmeter" }, { "code": null, "e": 7949, "s": 7945, "text": "EJB" }, { "code": null, "e": 7963, "s": 7949, "text": "Jasper Report" }, { "code": null, "e": 7978, "s": 7963, "text": "Separated link" }, { "code": null, "e": 8002, "s": 7978, "text": "One more separated link" }, { "code": null, "e": 8359, "s": 8002, "text": "Instead of using the default class-based forms from Chapter Bootstrap Forms, forms that are in the navbar, use the .navbar-form class. This ensures that the form’s proper vertical alignment and collapsed behavior in narrow viewports. Use the alignment options (explained in Component alignment section) to decide where it resides within the navbar content." }, { "code": null, "e": 8401, "s": 8359, "text": "The following example demonstrates this βˆ’" }, { "code": null, "e": 8910, "s": 8401, "text": "<nav class = \"navbar navbar-default\" role = \"navigation\">\n \n <div class = \"navbar-header\">\n <a class = \"navbar-brand\" href = \"#\">TutorialsPoint</a>\n </div>\n \n <div>\n <form class = \"navbar-form navbar-left\" role = \"search\">\n \n <div class = \"form-group\">\n <input type = \"text\" class = \"form-control\" placeholder = \"Search\">\n </div>\n <button type = \"submit\" class = \"btn btn-default\">Submit</button>\n \n </form> \n </div>\n \n</nav>" }, { "code": null, "e": 9095, "s": 8910, "text": "You can add buttons using class .navbar-btn to <button> elements not residing in a <form> to vertically center them in the navbar. .navbar-btn can be used on <a> and <input> elements." }, { "code": null, "e": 9137, "s": 9095, "text": "The following example demonstrates this βˆ’" }, { "code": null, "e": 9724, "s": 9137, "text": "<nav class = \"navbar navbar-default\" role = \"navigation\">\n \n <div class = \"navbar-header\">\n <a class = \"navbar-brand\" href = \"#\">TutorialsPoint</a>\n </div>\n \n <div>\n <form class = \"navbar-form navbar-left\" role = \"search\">\n <div class = \"form-group\">\n <input type = \"text\" class = \"form-control\" placeholder = \"Search\">\n </div>\n\t\t\t\n <button type = \"submit\" class = \"btn btn-default\">Submit Button</button>\n </form> \n\t\t\n <button type = \"button\" class = \"btn btn-default navbar-btn\">Navbar Button</button>\n </div>\n</nav>" }, { "code": null, "e": 9896, "s": 9724, "text": "To wrap strings of text in an element use the class .navbar-text. This is usually used with <p> tag for proper leading and color. The following example demonstrates this βˆ’" }, { "code": null, "e": 10144, "s": 9896, "text": "<nav class = \"navbar navbar-default\" role = \"navigation\">\n <div class = \"navbar-header\">\n <a class = \"navbar-brand\" href = \"#\">TutorialsPoint</a>\n </div>\n \n <div>\n <p class = \"navbar-text\">Signed in as Thomas</p>\n </div>\n</nav>" }, { "code": null, "e": 10164, "s": 10144, "text": "Signed in as Thomas" }, { "code": null, "e": 10394, "s": 10164, "text": "If you want to use the standard links that are not within the regular navbar navigation component, then use the class navbar-link to add proper colors for the default and inverse navbar options as shown in the following example βˆ’" }, { "code": null, "e": 10722, "s": 10394, "text": "<nav class = \"navbar navbar-default\" role = \"navigation\">\n <div class = \"navbar-header\">\n <a class = \"navbar-brand\" href = \"#\">TutorialsPoint</a>\n </div>\n \n <div>\n <p class = \"navbar-text navbar-right\">\n Signed in as \n <a href = \"#\" class = \"navbar-link\">Thomas</a>\n </p>\n </div>\n</nav>" }, { "code": null, "e": 10775, "s": 10722, "text": "\n Signed in as \n Thomas\n" }, { "code": null, "e": 11034, "s": 10775, "text": "You can align the components like nav links, forms, buttons, or text to left or right in a navbar using the utility classes .navbar-left or .navbar-right. Both classes will add a CSS float in the specified direction. The following example demonstrates this βˆ’" }, { "code": null, "e": 13301, "s": 11034, "text": "<nav class = \"navbar navbar-default\" role = \"navigation\">\n \n <div class = \"navbar-header\">\n <a class = \"navbar-brand\" href = \"#\">TutorialsPoint</a>\n </div>\n \n <div>\n \n <!--Left Align-->\n <ul class = \"nav navbar-nav navbar-left\">\n <li class = \"dropdown\">\n <a href = \"#\" class = \"dropdown-toggle\" data-toggle = \"dropdown\">\n Java \n <b class = \"caret\"></b>\n </a>\n \n <ul class = \"dropdown-menu\">\n <li><a href = \"#\">jmeter</a></li>\n <li><a href = \"#\">EJB</a></li>\n <li><a href = \"#\">Jasper Report</a></li>\n \n <li class = \"divider\"></li>\n <li><a href = \"#\">Separated link</a></li>\n \n <li class = \"divider\"></li>\n <li><a href = \"#\">One more separated link</a></li>\n </ul>\n \n </li>\n </ul>\n \n <form class = \"navbar-form navbar-left\" role = \"search\">\n <button type = \"submit\" class = \"btn btn-default\">Left align-Submit Button</button>\n </form> \n \n <p class = \"navbar-text navbar-left\">Left align-Text</p>\n \n <!--Right Align-->\n <ul class = \"nav navbar-nav navbar-right\">\n <li class = \"dropdown\">\n <a href = \"#\" class = \"dropdown-toggle\" data-toggle = \"dropdown\">\n Java \n <b class = \"caret\"></b>\n </a>\n \n <ul class = \"dropdown-menu\">\n <li><a href = \"#\">jmeter</a></li>\n <li><a href = \"#\">EJB</a></li>\n <li><a href = \"#\">Jasper Report</a></li>\n \n <li class = \"divider\"></li>\n <li><a href = \"#\">Separated link</a></li>\n \n <li class = \"divider\"></li>\n <li><a href = \"#\">One more separated link</a></li>\n </ul>\n \n </li>\n </ul>\n \n <form class = \"navbar-form navbar-right\" role = \"search\">\n <button type = \"submit\" class = \"btn btn-default\">\n Right align-Submit Button\n </button>\n </form> \n\t\t\n <p class = \"navbar-text navbar-right\">Right align-Text</p>\n \n </div>\n</nav>" }, { "code": null, "e": 13422, "s": 13301, "text": "\n\n Java \n \n\n\njmeter\nEJB\nJasper Report\n\nSeparated link\n\nOne more separated link\n\n" }, { "code": null, "e": 13429, "s": 13422, "text": "jmeter" }, { "code": null, "e": 13433, "s": 13429, "text": "EJB" }, { "code": null, "e": 13447, "s": 13433, "text": "Jasper Report" }, { "code": null, "e": 13462, "s": 13447, "text": "Separated link" }, { "code": null, "e": 13486, "s": 13462, "text": "One more separated link" }, { "code": null, "e": 13502, "s": 13486, "text": "Left align-Text" }, { "code": null, "e": 13611, "s": 13502, "text": "\n\n Java \n \n\n\njmeter\nEJB\nJasper Report\n\nSeparated link\n\nOne more separated link\n\n" }, { "code": null, "e": 13618, "s": 13611, "text": "jmeter" }, { "code": null, "e": 13622, "s": 13618, "text": "EJB" }, { "code": null, "e": 13636, "s": 13622, "text": "Jasper Report" }, { "code": null, "e": 13651, "s": 13636, "text": "Separated link" }, { "code": null, "e": 13675, "s": 13651, "text": "One more separated link" }, { "code": null, "e": 13692, "s": 13675, "text": "Right align-Text" }, { "code": null, "e": 13988, "s": 13692, "text": "The Bootstrap navbar can be dynamic in its positioning. By default, it is a block-level element that takes its positioning based on its placement in the HTML. With a few helper classes, you can place it either on the top or bottom of the page, or you can make it scroll statically with the page." }, { "code": null, "e": 14121, "s": 13988, "text": "If you want the navbar fixed to the top, add class .navbar-fixed-top to the .navbar class. The following example demonstrates this βˆ’" }, { "code": null, "e": 15174, "s": 14121, "text": "\n<nav class = \"navbar navbar-default navbar-fixed-top\" role = \"navigation\">\n \n <div class = \"navbar-header\">\n <a class = \"navbar-brand\" href = \"#\">TutorialsPoint</a>\n </div>\n \n <div>\n <ul class = \"nav navbar-nav\">\n <li class = \"active\"><a href = \"#\">iOS</a></li>\n <li><a href = \"#\">SVN</a></li>\n \n <li class = \"dropdown\">\n <a href = \"#\" class = \"dropdown-toggle\" data-toggle = \"dropdown\">\n Java\n <b class = \"caret\"></b>\n </a>\n \n <ul class = \"dropdown-menu\">\n <li><a href = \"#\">jmeter</a></li>\n <li><a href = \"#\">EJB</a></li>\n <li><a href = \"#\">Jasper Report</a></li>\n \n <li class = \"divider\"></li>\n <li><a href = \"#\">Separated link</a></li>\n \n <li class = \"divider\"></li>\n <li><a href = \"#\">One more separated link</a></li>\n </ul>\n \n </li>\n </ul>\n </div>\n \n</nav>" }, { "code": null, "e": 15325, "s": 15174, "text": "If you want the navbar fixed to the bottom of the page, add class .navbar-fixed-bottom to the .navbar class. The following example demonstrates this βˆ’" }, { "code": null, "e": 16374, "s": 15325, "text": "\n<nav class = \"navbar navbar-default navbar-fixed-bottom\" role = \"navigation\">\n \n <div class = \"navbar-header\">\n <a class = \"navbar-brand\" href = \"#\">TutorialsPoint</a>\n </div>\n \n <div>\n <ul class = \"nav navbar-nav\">\n <li class = \"active\"><a href = \"#\">iOS</a></li>\n <li><a href=\"#\">SVN</a></li>\n \n <li class = \"dropdown\">\n <a href = \"#\" class = \"dropdown-toggle\" data-toggle = \"dropdown\">\n Java\n <b class =\"caret\"></b>\n </a>\n \n <ul class = \"dropdown-menu\">\n <li><a href = \"#\">jmeter</a></li>\n <li><a href = \"#\">EJB</a></li>\n <li><a href = \"#\">Jasper Report</a></li>\n \n <li class = \"divider\"></li>\n <li><a href = \"#\">Separated link</a></li>\n \n <li class = \"divider\"></li>\n <li><a href = \"#\">One more separated link</a></li>\n </ul>\n \n </li>\n </ul>\n </div>\n</nav>" }, { "code": null, "e": 16378, "s": 16374, "text": "iOS" }, { "code": null, "e": 16382, "s": 16378, "text": "SVN" }, { "code": null, "e": 16502, "s": 16382, "text": "\n\n Java\n \n\n\njmeter\nEJB\nJasper Report\n\nSeparated link\n\nOne more separated link\n\n" }, { "code": null, "e": 16509, "s": 16502, "text": "jmeter" }, { "code": null, "e": 16513, "s": 16509, "text": "EJB" }, { "code": null, "e": 16527, "s": 16513, "text": "Jasper Report" }, { "code": null, "e": 16542, "s": 16527, "text": "Separated link" }, { "code": null, "e": 16566, "s": 16542, "text": "One more separated link" }, { "code": null, "e": 16709, "s": 16566, "text": "To create a navbar that scrolls with the page, add the .navbar-static-top class. This class does not require adding the padding to the <body>." }, { "code": null, "e": 17751, "s": 16709, "text": "\n<nav class = \"navbar navbar-default navbar-static-top\" role = \"navigation\">\n \n <div class = \"navbar-header\">\n <a class = \"navbar-brand\" href = \"#\">TutorialsPoint</a>\n </div>\n \n <div>\n <ul class = \"nav navbar-nav\">\n <li class = \"active\"><a href = \"#\">iOS</a></li>\n <li><a href = \"#\">SVN</a></li>\n \n <li class = \"dropdown\">\n <a href = \"#\" class = \"dropdown-toggle\" data-toggle = \"dropdown\">\n Java\n <b class = \"caret\"></b>\n </a>\n\t\t\t\t\n <ul class = \"dropdown-menu\">\n <li><a href = \"#\">jmeter</a></li>\n <li><a href = \"#\">EJB</a></li>\n <li><a href = \"#\">Jasper Report</a></li>\n \n <li class = \"divider\"></li>\n <li><a href = \"#\">Separated link</a></li>\n \n <li class = \"divider\"></li>\n <li><a href = \"#\">One more separated link</a></li>\n </ul>\n \n </li>\n </ul>\n </div>\n</nav>" }, { "code": null, "e": 17755, "s": 17751, "text": "iOS" }, { "code": null, "e": 17759, "s": 17755, "text": "SVN" }, { "code": null, "e": 17879, "s": 17759, "text": "\n\n Java\n \n\n\njmeter\nEJB\nJasper Report\n\nSeparated link\n\nOne more separated link\n\n" }, { "code": null, "e": 17886, "s": 17879, "text": "jmeter" }, { "code": null, "e": 17890, "s": 17886, "text": "EJB" }, { "code": null, "e": 17904, "s": 17890, "text": "Jasper Report" }, { "code": null, "e": 17919, "s": 17904, "text": "Separated link" }, { "code": null, "e": 17943, "s": 17919, "text": "One more separated link" }, { "code": null, "e": 18118, "s": 17943, "text": "To create an inverted navbar with a black background and with white text, simply add the .navbar-inverse class to the .navbar class as demonstrated in the following example βˆ’" }, { "code": null, "e": 19139, "s": 18118, "text": "<nav class = \"navbar navbar-inverse\" role = \"navigation\">\n \n <div class = \"navbar-header\">\n <a class = \"navbar-brand\" href = \"#\">TutorialsPoint</a>\n </div>\n \n <div>\n <ul class = \"nav navbar-nav\">\n <li class = \"active\"><a href = \"#\">iOS</a></li>\n <li><a href = \"#\">SVN</a></li>\n <li class = \"dropdown\">\n <a href = \"#\" class = \"dropdown-toggle\" data-toggle = \"dropdown\">\n Java\n <b class = \"caret\"></b>\n </a>\n \n <ul class = \"dropdown-menu\">\n <li><a href = \"#\">jmeter</a></li>\n <li><a href = \"#\">EJB</a></li>\n <li><a href = \"#\">Jasper Report</a></li>\n \n <li class = \"divider\"></li>\n <li><a href = \"#\">Separated link</a></li>\n \n <li class = \"divider\"></li>\n <li><a href = \"#\">One more separated link</a></li>\n </ul>\n \n </li>\n </ul>\n </div>\n</nav>" }, { "code": null, "e": 19143, "s": 19139, "text": "iOS" }, { "code": null, "e": 19147, "s": 19143, "text": "SVN" }, { "code": null, "e": 19267, "s": 19147, "text": "\n\n Java\n \n\n\njmeter\nEJB\nJasper Report\n\nSeparated link\n\nOne more separated link\n\n" }, { "code": null, "e": 19274, "s": 19267, "text": "jmeter" }, { "code": null, "e": 19278, "s": 19274, "text": "EJB" }, { "code": null, "e": 19292, "s": 19278, "text": "Jasper Report" }, { "code": null, "e": 19307, "s": 19292, "text": "Separated link" }, { "code": null, "e": 19331, "s": 19307, "text": "One more separated link" }, { "code": null, "e": 19364, "s": 19331, "text": "\n 26 Lectures \n 2 hours \n" }, { "code": null, "e": 19378, "s": 19364, "text": " Anadi Sharma" }, { "code": null, "e": 19413, "s": 19378, "text": "\n 54 Lectures \n 4.5 hours \n" }, { "code": null, "e": 19430, "s": 19413, "text": " Frahaan Hussain" }, { "code": null, "e": 19467, "s": 19430, "text": "\n 161 Lectures \n 14.5 hours \n" }, { "code": null, "e": 19495, "s": 19467, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 19528, "s": 19495, "text": "\n 20 Lectures \n 4 hours \n" }, { "code": null, "e": 19540, "s": 19528, "text": " Azaz Patel" }, { "code": null, "e": 19575, "s": 19540, "text": "\n 15 Lectures \n 1.5 hours \n" }, { "code": null, "e": 19592, "s": 19575, "text": " Muhammad Ismail" }, { "code": null, "e": 19625, "s": 19592, "text": "\n 62 Lectures \n 8 hours \n" }, { "code": null, "e": 19645, "s": 19625, "text": " Yossef Ayman Zedan" }, { "code": null, "e": 19652, "s": 19645, "text": " Print" }, { "code": null, "e": 19663, "s": 19652, "text": " Add Notes" } ]
Trace or track Python statement execution (trace)
Function in the 'trace' module in Python library generates trace of program execution, and annotated statement coverage. It also has functions to list functions called during run by generating caller relationships. Following two Python scripts are used as an example to demonstrate features of trace module. #myfunctions.py import math def area(x): a = math.pi*math.pow(x,2) return a def factorial(x): if x==1: return 1 else: return x*factorial(x-1) #mymain.py import myfunctions def main(): x = 5 print ('area=',myfunctions.area(x)) print ('factorial=',myfunctions.factorial(x)) if __name__=='__main__': main() The 'trace' module has a command line interface. All the functions in the module can be called using command line switches. The most important option is --trace which displays program lines as they are executed. In following example another option --ignore-dir is used. It ignores specified directories while generating the trace. E:\python37>python -m trace --ignore-dir=../lib --trace mymain.py mymain.py(2): def main(): mymain.py(7): if __name__=='__main__': mymain.py(8): main() --- modulename: mymain, funcname: main mymain.py(3): x=5 mymain.py(4): print ('area=',myfunctions.area(x)) --- modulename: myfunctions, funcname: area myfunctions.py(3): a=math.pi*math.pow(x,2) myfunctions.py(4): return a area= 78.53981633974483 mymain.py(5): print ('factorial=',myfunctions.factorial(x)) --- modulename: myfunctions, funcname: factorial myfunctions.py(6): if x==1: myfunctions.py(9): return x*factorial(x-1) --- modulename: myfunctions, funcname: factorial myfunctions.py(6): if x==1: myfunctions.py(9): return x*factorial(x-1) --- modulename: myfunctions, funcname: factorial myfunctions.py(6): if x==1: myfunctions.py(9): return x*factorial(x-1) --- modulename: myfunctions, funcname: factorial myfunctions.py(6): if x==1: myfunctions.py(9): return x*factorial(x-1) --- modulename: myfunctions, funcname: factorial myfunctions.py(6): if x==1: myfunctions.py(7): return 1 factorial= 120 The --count option generates a file for each module in use with, cover extension. E:\python37>python -m trace --count mymain.py area= 78.53981633974483 factorial = 120 myfunctions.cover 1: import math 1: def area(x): 1: a = math.pi*math.pow(x,2) 1: return a 1: def factorial(x): 5: if x==1: 1: return 1 else: 4: return x*factorial(x-1) mymain.cover 1: import myfunctions 1: def main(): 1: x = 5 1: print ('area=',myfunctions.area(x)) 1: print ('factorial=',myfunctions.factorial(x)) 1: if __name__=='__main__': 1: main() --summary option displays a brief summary if –count option is also used. E:\python37>python -m trace --count --summary mymain.py area = 78.53981633974483 factorial = 120 lines cov% module (path) 8 100% myfunctions (E:\python37\myfunctions.py) 7 100% mymain (mymain.py) The --file option specifies name of file in which accumulates count over several tracing runs. E:\python37>python -m trace --count --file report.txt mymain.py area = 78.53981633974483 factorial = 120 Skipping counts file 'report.txt': [Errno 2] No such file or directory: 'report.txt' E:\python37>python -m trace --count --file report.txt mymain.py area= 78.53981633974483 factorial= 120 --listfuncs option displays functions called during execution of program. E:\python37>python -m trace --listfunc mymain.py | findstr -v importlib area= 78.53981633974483 factorial= 120 functions called: filename: E:\python37\lib\encodings\cp1252.py, modulename: cp1252, funcname: IncrementalEncoder.encode filename: E:\python37\myfunctions.py, modulename: myfunctions, funcname: <module> filename: E:\python37\myfunctions.py, modulename: myfunctions, funcname: area filename: E:\python37\myfunctions.py, modulename: myfunctions, funcname: factorial filename: mymain.py, modulename: mymain, funcname: <module> filename: mymain.py, modulename: mymain, funcname: main --trackcalls option is used along with –list funcs option. It generates calling relationships. E:\python37>python -m trace --listfunc --trackcalls mymain.py | findstr -v importlib area= 78.53981633974483 factorial= 120 calling relationships: --> E:\python37\myfunctions.py *** E:\python37\lib\trace.py *** --> mymain.py trace.Trace.runctx -> mymain.<module> *** E:\python37\myfunctions.py *** myfunctions.factorial -> myfunctions.factorial *** mymain.py *** mymain.<module> -> mymain.main --> E:\python37\lib\encodings\cp1252.py mymain.main -> cp1252.IncrementalEncoder.encode --> E:\python37\myfunctions.py mymain.main -> myfunctions.area mymain.main -> myfunctions.factorial
[ { "code": null, "e": 1277, "s": 1062, "text": "Function in the 'trace' module in Python library generates trace of program execution, and annotated statement coverage. It also has functions to list functions called during run by generating caller relationships." }, { "code": null, "e": 1370, "s": 1277, "text": "Following two Python scripts are used as an example to demonstrate features of trace module." }, { "code": null, "e": 1530, "s": 1370, "text": "#myfunctions.py\nimport math\ndef area(x):\n a = math.pi*math.pow(x,2)\n return a\ndef factorial(x):\n if x==1:\n return 1\n else:\nreturn x*factorial(x-1)" }, { "code": null, "e": 1705, "s": 1530, "text": "#mymain.py\nimport myfunctions\ndef main():\n x = 5\n print ('area=',myfunctions.area(x))\n print ('factorial=',myfunctions.factorial(x))\n\nif __name__=='__main__':\n main()" }, { "code": null, "e": 2036, "s": 1705, "text": "The 'trace' module has a command line interface. All the functions in the module can be called using command line switches. The most important option is --trace which displays program lines as they are executed. In following example another option --ignore-dir is used. It ignores specified directories while generating the trace." }, { "code": null, "e": 2102, "s": 2036, "text": "E:\\python37>python -m trace --ignore-dir=../lib --trace mymain.py" }, { "code": null, "e": 3094, "s": 2102, "text": "mymain.py(2): def main():\nmymain.py(7): if __name__=='__main__':\nmymain.py(8): main()\n--- modulename: mymain, funcname: main\nmymain.py(3): x=5\nmymain.py(4): print ('area=',myfunctions.area(x))\n--- modulename: myfunctions, funcname: area\nmyfunctions.py(3): a=math.pi*math.pow(x,2)\nmyfunctions.py(4): return a\narea= 78.53981633974483\nmymain.py(5): print ('factorial=',myfunctions.factorial(x))\n--- modulename: myfunctions, funcname: factorial\nmyfunctions.py(6): if x==1:\nmyfunctions.py(9): return x*factorial(x-1)\n--- modulename: myfunctions, funcname: factorial\nmyfunctions.py(6): if x==1:\nmyfunctions.py(9): return x*factorial(x-1)\n--- modulename: myfunctions, funcname: factorial\nmyfunctions.py(6): if x==1:\nmyfunctions.py(9): return x*factorial(x-1)\n--- modulename: myfunctions, funcname: factorial\nmyfunctions.py(6): if x==1:\nmyfunctions.py(9): return x*factorial(x-1)\n--- modulename: myfunctions, funcname: factorial\nmyfunctions.py(6): if x==1:\nmyfunctions.py(7): return 1\nfactorial= 120" }, { "code": null, "e": 3176, "s": 3094, "text": "The --count option generates a file for each module in use with, cover extension." }, { "code": null, "e": 3262, "s": 3176, "text": "E:\\python37>python -m trace --count mymain.py\narea= 78.53981633974483\nfactorial = 120" }, { "code": null, "e": 3280, "s": 3262, "text": "myfunctions.cover" }, { "code": null, "e": 3451, "s": 3280, "text": "1: import math\n1: def area(x):\n1: a = math.pi*math.pow(x,2)\n1: return a\n1: def factorial(x):\n5: if x==1:\n1: return 1\n else:\n4: return x*factorial(x-1)" }, { "code": null, "e": 3464, "s": 3451, "text": "mymain.cover" }, { "code": null, "e": 3649, "s": 3464, "text": "1: import myfunctions\n1: def main():\n1: x = 5\n1: print ('area=',myfunctions.area(x))\n1: print ('factorial=',myfunctions.factorial(x))\n\n1: if __name__=='__main__':\n1: main()" }, { "code": null, "e": 3722, "s": 3649, "text": "--summary option displays a brief summary if –count option is also used." }, { "code": null, "e": 3924, "s": 3722, "text": "E:\\python37>python -m trace --count --summary mymain.py\narea = 78.53981633974483\nfactorial = 120\nlines cov% module (path)\n 8 100% myfunctions (E:\\python37\\myfunctions.py)\n 7 100% mymain (mymain.py)" }, { "code": null, "e": 4019, "s": 3924, "text": "The --file option specifies name of file in which accumulates count over several tracing runs." }, { "code": null, "e": 4313, "s": 4019, "text": "E:\\python37>python -m trace --count --file report.txt mymain.py\narea = 78.53981633974483\nfactorial = 120\nSkipping counts file 'report.txt': [Errno 2] No such file or directory: 'report.txt'\n\nE:\\python37>python -m trace --count --file report.txt mymain.py\narea= 78.53981633974483\nfactorial= 120" }, { "code": null, "e": 4387, "s": 4313, "text": "--listfuncs option displays functions called during execution of program." }, { "code": null, "e": 4979, "s": 4387, "text": "E:\\python37>python -m trace --listfunc mymain.py | findstr -v importlib\narea= 78.53981633974483\nfactorial= 120\n\nfunctions called:\nfilename: E:\\python37\\lib\\encodings\\cp1252.py, modulename: cp1252, funcname: IncrementalEncoder.encode\nfilename: E:\\python37\\myfunctions.py, modulename: myfunctions, funcname: <module>\nfilename: E:\\python37\\myfunctions.py, modulename: myfunctions, funcname: area\nfilename: E:\\python37\\myfunctions.py, modulename: myfunctions, funcname: factorial\nfilename: mymain.py, modulename: mymain, funcname: <module>\nfilename: mymain.py, modulename: mymain, funcname: main" }, { "code": null, "e": 5074, "s": 4979, "text": "--trackcalls option is used along with –list funcs option. It generates calling relationships." }, { "code": null, "e": 5662, "s": 5074, "text": "E:\\python37>python -m trace --listfunc --trackcalls mymain.py | findstr -v importlib\narea= 78.53981633974483\nfactorial= 120\n\ncalling relationships:\n\n--> E:\\python37\\myfunctions.py\n\n\n*** E:\\python37\\lib\\trace.py ***\n--> mymain.py\ntrace.Trace.runctx -> mymain.<module>\n\n*** E:\\python37\\myfunctions.py ***\nmyfunctions.factorial -> myfunctions.factorial\n\n*** mymain.py ***\nmymain.<module> -> mymain.main\n--> E:\\python37\\lib\\encodings\\cp1252.py\nmymain.main -> cp1252.IncrementalEncoder.encode\n--> E:\\python37\\myfunctions.py\nmymain.main -> myfunctions.area\nmymain.main -> myfunctions.factorial" } ]
Laravel - Redirections
Named route is used to give specific name to a route. The name can be assigned using the β€œas” array key. Route::get('user/profile', ['as' => 'profile', function () { // }]); Note βˆ’ Here, we have given the name profile to a route user/profile. Observe the following example to understand more about Redirecting to named routes βˆ’ Step 1 βˆ’ Create a view called test.php and save it at resources/views/test.php. <html> <body> <h1>Example of Redirecting to Named Routes</h1> </body> </html> Step 2 βˆ’ In routes.php, we have set up the route for test.php file. We have renamed it to testing. We have also set up another route redirect which will redirect the request to the named route testing. app/Http/routes.php Route::get('/test', ['as'=>'testing',function() { return view('test2'); }]); Route::get('redirect',function() { return redirect()->route('testing'); }); Step 3 βˆ’ Visit the following URL to test the named route example. http://localhost:8000/redirect Step 4 βˆ’ After execution of the above URL, you will be redirected to http://localhost:8000/test as we are redirecting to the named route testing. Step 5 βˆ’ After successful execution of the URL, you will receive the following output βˆ’ Not only named route but we can also redirect to controller actions. We need to simply pass the controller and name of the action to the action method as shown in the following example. If you want to pass a parameter, you can pass it as the second argument of the action method. return redirect()->action(β€˜NameOfController@methodName’,[parameters]); Step 1 βˆ’ Execute the following command to create a controller called RedirectController. php artisan make:controller RedirectController --plain Step 2 βˆ’ After successful execution, you will receive the following output βˆ’ Step 3 βˆ’ Copy the following code to file app/Http/Controllers/RedirectController.php. app/Http/Controllers/RedirectController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Requests; use App\Http\Controllers\Controller; class RedirectController extends Controller { public function index() { echo "Redirecting to controller's action."; } } Step 4 βˆ’ Add the following lines in app/Http/routes.php. app/Http/routes.php Route::get('rr','RedirectController@index'); Route::get('/redirectcontroller',function() { return redirect()->action('RedirectController@index'); }); Step 5 βˆ’ Visit the following URL to test the example. http://localhost:8000/redirectcontroller Step 6 βˆ’ The output will appear as shown in the following image. 13 Lectures 3 hours Sebastian Sulinski 35 Lectures 3.5 hours Antonio Papa 7 Lectures 1.5 hours Sebastian Sulinski 42 Lectures 1 hours Skillbakerystudios 165 Lectures 13 hours Paul Carlo Tordecilla 116 Lectures 13 hours Hafizullah Masoudi Print Add Notes Bookmark this page
[ { "code": null, "e": 2577, "s": 2472, "text": "Named route is used to give specific name to a route. The name can be assigned using the β€œas” array key." }, { "code": null, "e": 2650, "s": 2577, "text": "Route::get('user/profile', ['as' => 'profile', function () {\n //\n}]);\n" }, { "code": null, "e": 2719, "s": 2650, "text": "Note βˆ’ Here, we have given the name profile to a route user/profile." }, { "code": null, "e": 2804, "s": 2719, "text": "Observe the following example to understand more about Redirecting to named routes βˆ’" }, { "code": null, "e": 2858, "s": 2804, "text": "Step 1 βˆ’ Create a view called test.php and save it at" }, { "code": null, "e": 2884, "s": 2858, "text": "resources/views/test.php." }, { "code": null, "e": 2974, "s": 2884, "text": "<html>\n <body>\n <h1>Example of Redirecting to Named Routes</h1>\n </body>\n</html>" }, { "code": null, "e": 3176, "s": 2974, "text": "Step 2 βˆ’ In routes.php, we have set up the route for test.php file. We have renamed it to testing. We have also set up another route redirect which will redirect the request to the named route testing." }, { "code": null, "e": 3196, "s": 3176, "text": "app/Http/routes.php" }, { "code": null, "e": 3357, "s": 3196, "text": "Route::get('/test', ['as'=>'testing',function() {\n return view('test2');\n}]);\n\nRoute::get('redirect',function() {\n return redirect()->route('testing');\n});\n" }, { "code": null, "e": 3423, "s": 3357, "text": "Step 3 βˆ’ Visit the following URL to test the named route example." }, { "code": null, "e": 3455, "s": 3423, "text": "http://localhost:8000/redirect\n" }, { "code": null, "e": 3601, "s": 3455, "text": "Step 4 βˆ’ After execution of the above URL, you will be redirected to http://localhost:8000/test as we are redirecting to the named route testing." }, { "code": null, "e": 3689, "s": 3601, "text": "Step 5 βˆ’ After successful execution of the URL, you will receive the following output βˆ’" }, { "code": null, "e": 3969, "s": 3689, "text": "Not only named route but we can also redirect to controller actions. We need to simply pass the controller and name of the action to the action method as shown in the following example. If you want to pass a parameter, you can pass it as the second argument of the action method." }, { "code": null, "e": 4041, "s": 3969, "text": "return redirect()->action(β€˜NameOfController@methodName’,[parameters]);\n" }, { "code": null, "e": 4130, "s": 4041, "text": "Step 1 βˆ’ Execute the following command to create a controller called RedirectController." }, { "code": null, "e": 4186, "s": 4130, "text": "php artisan make:controller RedirectController --plain\n" }, { "code": null, "e": 4263, "s": 4186, "text": "Step 2 βˆ’ After successful execution, you will receive the following output βˆ’" }, { "code": null, "e": 4304, "s": 4263, "text": "Step 3 βˆ’ Copy the following code to file" }, { "code": null, "e": 4349, "s": 4304, "text": "app/Http/Controllers/RedirectController.php." }, { "code": null, "e": 4393, "s": 4349, "text": "app/Http/Controllers/RedirectController.php" }, { "code": null, "e": 4656, "s": 4393, "text": "<?php\n\nnamespace App\\Http\\Controllers;\n\nuse Illuminate\\Http\\Request;\nuse App\\Http\\Requests;\nuse App\\Http\\Controllers\\Controller;\n\nclass RedirectController extends Controller {\n public function index() {\n echo \"Redirecting to controller's action.\";\n }\n}\n" }, { "code": null, "e": 4713, "s": 4656, "text": "Step 4 βˆ’ Add the following lines in app/Http/routes.php." }, { "code": null, "e": 4733, "s": 4713, "text": "app/Http/routes.php" }, { "code": null, "e": 4887, "s": 4733, "text": "Route::get('rr','RedirectController@index');\nRoute::get('/redirectcontroller',function() {\n return redirect()->action('RedirectController@index');\n});\n" }, { "code": null, "e": 4941, "s": 4887, "text": "Step 5 βˆ’ Visit the following URL to test the example." }, { "code": null, "e": 4983, "s": 4941, "text": "http://localhost:8000/redirectcontroller\n" }, { "code": null, "e": 5048, "s": 4983, "text": "Step 6 βˆ’ The output will appear as shown in the following image." }, { "code": null, "e": 5081, "s": 5048, "text": "\n 13 Lectures \n 3 hours \n" }, { "code": null, "e": 5101, "s": 5081, "text": " Sebastian Sulinski" }, { "code": null, "e": 5136, "s": 5101, "text": "\n 35 Lectures \n 3.5 hours \n" }, { "code": null, "e": 5150, "s": 5136, "text": " Antonio Papa" }, { "code": null, "e": 5184, "s": 5150, "text": "\n 7 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5204, "s": 5184, "text": " Sebastian Sulinski" }, { "code": null, "e": 5237, "s": 5204, "text": "\n 42 Lectures \n 1 hours \n" }, { "code": null, "e": 5257, "s": 5237, "text": " Skillbakerystudios" }, { "code": null, "e": 5292, "s": 5257, "text": "\n 165 Lectures \n 13 hours \n" }, { "code": null, "e": 5315, "s": 5292, "text": " Paul Carlo Tordecilla" }, { "code": null, "e": 5350, "s": 5315, "text": "\n 116 Lectures \n 13 hours \n" }, { "code": null, "e": 5370, "s": 5350, "text": " Hafizullah Masoudi" }, { "code": null, "e": 5377, "s": 5370, "text": " Print" }, { "code": null, "e": 5388, "s": 5377, "text": " Add Notes" } ]
Node.js server.address() Method
03 Sep, 2021 The server.address() is an inbuilt application programming interface of class Socket within tls module which is used to get the bound address of the server. Syntax: const server.address() Parameters: This method does not accept any parameter. Return Value: This method return the bound address containing the family name, and port of the server. How to generate private key and public certificate? Private key: Open notepad and copy paste the following key:-----BEGIN RSA PRIVATE KEY----- MIICXQIBAAKBgQC38R9wXcUbhOd44FavgmE5R3K4JeYOHLnI7dUq1B8/Gv7l3SOg JKef/m9gM1KvUx951mapXGtcWgwB08J3vUE2YOZ4tWJArrVZES0BI/RmFAyhQFP5 HcWl3LSM9LRihP98F33oIkKaCxA5LxOrkgpV4HrUzIKTABDYah7RPex1WQIDAQAB AoGBAIXR71xxa9gUfc5L7+TqBs+EMmrUb6Vusp8CoGXzQvRHMJCMrMFySV0131Nu o0YYRDsAh1nJefYLMNcXd1BjqI+qY8IeRsxaY+9CB2KKGVVDO2uLdurdC2ZdlWXT Vwr3dDoyR0trnXJMmH2ijTeO6bush8HuXxvxJBjvEllM5QYxAkEA3jwny9JP+RFu 0rkqPBe/wi5pXpPl7PUtdNAGrh6S5958wUoR4f9bvwmTBv1nQzExKWu4EIp+7vjJ fBeRZhnBvQJBANPjjge8418PS9zAFyKlITq6cxmM4gOWeveQZwXVNvav0NH+OKdQ sZnnDiG26JWmnD/B8Audu97LcxjxcWI8Jc0CQEYA5PhLU229lA9EzI0JXhoozIBC TlcKFDuLm88VSmlHqDyqvF9YNOpEdc/p2rFLuZS2ndB4D+vu6mjwc5iZ3HECQCxy GBHRclQ3Ti9w76lpv+2kvI4IekRMZWDWnnWfwta+DGxwCgw2pfpleBZkWqdBepb5 JFQbcxQJ0wvRYXo8qaUCQQCgTvWswBj6OTP7LTvBlU1teAN2Lnrk/N5AYHZIXW6m nUG9lYvH7DztWDTioXMrruPF7bdXfZOVJD8t0I4OUzvC -----END RSA PRIVATE KEY-----Save file as private-key.pemPublic certificate: Open notepad and copy paste the following key:-----BEGIN CERTIFICATE----- MIICfzCCAegCCQDxxeXw914Y2DANBgkqhkiG9w0BAQsFADCBgzELMAkGA1UEBhMC SU4xEzARBgNVBAgMCldlc3RiZW5nYWwxEDAOBgNVBAcMB0tvbGthdGExFDASBgNV BAoMC1BhbmNvLCBJbmMuMRUwEwYDVQQDDAxSb2hpdCBQcmFzYWQxIDAeBgkqhkiG 9w0BCQEWEXJvZm9mb2ZAZ21haWwuY29tMB4XDTIwMDkwOTA1NTExN1oXDTIwMTAw OTA1NTExN1owgYMxCzAJBgNVBAYTAklOMRMwEQYDVQQIDApXZXN0YmVuZ2FsMRAw DgYDVQQHDAdLb2xrYXRhMRQwEgYDVQQKDAtQYW5jbywgSW5jLjEVMBMGA1UEAwwM Um9oaXQgUHJhc2FkMSAwHgYJKoZIhvcNAQkBFhFyb2ZvZm9mQGdtYWlsLmNvbTCB nzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAt/EfcF3FG4TneOBWr4JhOUdyuCXm Dhy5yO3VKtQfPxr+5d0joCSnn/5vYDNSr1MfedZmqVxrXFoMAdPCd71BNmDmeLVi QK61WREtASP0ZhQMoUBT+R3Fpdy0jPS0YoT/fBd96CJCmgsQOS8Tq5IKVeB61MyC kwAQ2Goe0T3sdVkCAwEAATANBgkqhkiG9w0BAQsFAAOBgQATe6ixdAjoV7BSHgRX bXM2+IZLq8kq3s7ck0EZrRVhsivutcaZwDXRCCinB+OlPedbzXwNZGvVX0nwPYHG BfiXwdiuZeVJ88ni6Fm6RhoPtu2QF1UExfBvSXuMBgR+evp+e3QadNpGx6Ppl1aC hWF6W2H9+MAlU7yvtmCQQuZmfQ== -----END CERTIFICATE-----Save file as public-cert.pem Private key: Open notepad and copy paste the following key:-----BEGIN RSA PRIVATE KEY----- MIICXQIBAAKBgQC38R9wXcUbhOd44FavgmE5R3K4JeYOHLnI7dUq1B8/Gv7l3SOg JKef/m9gM1KvUx951mapXGtcWgwB08J3vUE2YOZ4tWJArrVZES0BI/RmFAyhQFP5 HcWl3LSM9LRihP98F33oIkKaCxA5LxOrkgpV4HrUzIKTABDYah7RPex1WQIDAQAB AoGBAIXR71xxa9gUfc5L7+TqBs+EMmrUb6Vusp8CoGXzQvRHMJCMrMFySV0131Nu o0YYRDsAh1nJefYLMNcXd1BjqI+qY8IeRsxaY+9CB2KKGVVDO2uLdurdC2ZdlWXT Vwr3dDoyR0trnXJMmH2ijTeO6bush8HuXxvxJBjvEllM5QYxAkEA3jwny9JP+RFu 0rkqPBe/wi5pXpPl7PUtdNAGrh6S5958wUoR4f9bvwmTBv1nQzExKWu4EIp+7vjJ fBeRZhnBvQJBANPjjge8418PS9zAFyKlITq6cxmM4gOWeveQZwXVNvav0NH+OKdQ sZnnDiG26JWmnD/B8Audu97LcxjxcWI8Jc0CQEYA5PhLU229lA9EzI0JXhoozIBC TlcKFDuLm88VSmlHqDyqvF9YNOpEdc/p2rFLuZS2ndB4D+vu6mjwc5iZ3HECQCxy GBHRclQ3Ti9w76lpv+2kvI4IekRMZWDWnnWfwta+DGxwCgw2pfpleBZkWqdBepb5 JFQbcxQJ0wvRYXo8qaUCQQCgTvWswBj6OTP7LTvBlU1teAN2Lnrk/N5AYHZIXW6m nUG9lYvH7DztWDTioXMrruPF7bdXfZOVJD8t0I4OUzvC -----END RSA PRIVATE KEY-----Save file as private-key.pem -----BEGIN RSA PRIVATE KEY----- MIICXQIBAAKBgQC38R9wXcUbhOd44FavgmE5R3K4JeYOHLnI7dUq1B8/Gv7l3SOg JKef/m9gM1KvUx951mapXGtcWgwB08J3vUE2YOZ4tWJArrVZES0BI/RmFAyhQFP5 HcWl3LSM9LRihP98F33oIkKaCxA5LxOrkgpV4HrUzIKTABDYah7RPex1WQIDAQAB AoGBAIXR71xxa9gUfc5L7+TqBs+EMmrUb6Vusp8CoGXzQvRHMJCMrMFySV0131Nu o0YYRDsAh1nJefYLMNcXd1BjqI+qY8IeRsxaY+9CB2KKGVVDO2uLdurdC2ZdlWXT Vwr3dDoyR0trnXJMmH2ijTeO6bush8HuXxvxJBjvEllM5QYxAkEA3jwny9JP+RFu 0rkqPBe/wi5pXpPl7PUtdNAGrh6S5958wUoR4f9bvwmTBv1nQzExKWu4EIp+7vjJ fBeRZhnBvQJBANPjjge8418PS9zAFyKlITq6cxmM4gOWeveQZwXVNvav0NH+OKdQ sZnnDiG26JWmnD/B8Audu97LcxjxcWI8Jc0CQEYA5PhLU229lA9EzI0JXhoozIBC TlcKFDuLm88VSmlHqDyqvF9YNOpEdc/p2rFLuZS2ndB4D+vu6mjwc5iZ3HECQCxy GBHRclQ3Ti9w76lpv+2kvI4IekRMZWDWnnWfwta+DGxwCgw2pfpleBZkWqdBepb5 JFQbcxQJ0wvRYXo8qaUCQQCgTvWswBj6OTP7LTvBlU1teAN2Lnrk/N5AYHZIXW6m nUG9lYvH7DztWDTioXMrruPF7bdXfZOVJD8t0I4OUzvC -----END RSA PRIVATE KEY----- Save file as private-key.pem Public certificate: Open notepad and copy paste the following key:-----BEGIN CERTIFICATE----- MIICfzCCAegCCQDxxeXw914Y2DANBgkqhkiG9w0BAQsFADCBgzELMAkGA1UEBhMC SU4xEzARBgNVBAgMCldlc3RiZW5nYWwxEDAOBgNVBAcMB0tvbGthdGExFDASBgNV BAoMC1BhbmNvLCBJbmMuMRUwEwYDVQQDDAxSb2hpdCBQcmFzYWQxIDAeBgkqhkiG 9w0BCQEWEXJvZm9mb2ZAZ21haWwuY29tMB4XDTIwMDkwOTA1NTExN1oXDTIwMTAw OTA1NTExN1owgYMxCzAJBgNVBAYTAklOMRMwEQYDVQQIDApXZXN0YmVuZ2FsMRAw DgYDVQQHDAdLb2xrYXRhMRQwEgYDVQQKDAtQYW5jbywgSW5jLjEVMBMGA1UEAwwM Um9oaXQgUHJhc2FkMSAwHgYJKoZIhvcNAQkBFhFyb2ZvZm9mQGdtYWlsLmNvbTCB nzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAt/EfcF3FG4TneOBWr4JhOUdyuCXm Dhy5yO3VKtQfPxr+5d0joCSnn/5vYDNSr1MfedZmqVxrXFoMAdPCd71BNmDmeLVi QK61WREtASP0ZhQMoUBT+R3Fpdy0jPS0YoT/fBd96CJCmgsQOS8Tq5IKVeB61MyC kwAQ2Goe0T3sdVkCAwEAATANBgkqhkiG9w0BAQsFAAOBgQATe6ixdAjoV7BSHgRX bXM2+IZLq8kq3s7ck0EZrRVhsivutcaZwDXRCCinB+OlPedbzXwNZGvVX0nwPYHG BfiXwdiuZeVJ88ni6Fm6RhoPtu2QF1UExfBvSXuMBgR+evp+e3QadNpGx6Ppl1aC hWF6W2H9+MAlU7yvtmCQQuZmfQ== -----END CERTIFICATE-----Save file as public-cert.pem -----BEGIN CERTIFICATE----- MIICfzCCAegCCQDxxeXw914Y2DANBgkqhkiG9w0BAQsFADCBgzELMAkGA1UEBhMC SU4xEzARBgNVBAgMCldlc3RiZW5nYWwxEDAOBgNVBAcMB0tvbGthdGExFDASBgNV BAoMC1BhbmNvLCBJbmMuMRUwEwYDVQQDDAxSb2hpdCBQcmFzYWQxIDAeBgkqhkiG 9w0BCQEWEXJvZm9mb2ZAZ21haWwuY29tMB4XDTIwMDkwOTA1NTExN1oXDTIwMTAw OTA1NTExN1owgYMxCzAJBgNVBAYTAklOMRMwEQYDVQQIDApXZXN0YmVuZ2FsMRAw DgYDVQQHDAdLb2xrYXRhMRQwEgYDVQQKDAtQYW5jbywgSW5jLjEVMBMGA1UEAwwM Um9oaXQgUHJhc2FkMSAwHgYJKoZIhvcNAQkBFhFyb2ZvZm9mQGdtYWlsLmNvbTCB nzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAt/EfcF3FG4TneOBWr4JhOUdyuCXm Dhy5yO3VKtQfPxr+5d0joCSnn/5vYDNSr1MfedZmqVxrXFoMAdPCd71BNmDmeLVi QK61WREtASP0ZhQMoUBT+R3Fpdy0jPS0YoT/fBd96CJCmgsQOS8Tq5IKVeB61MyC kwAQ2Goe0T3sdVkCAwEAATANBgkqhkiG9w0BAQsFAAOBgQATe6ixdAjoV7BSHgRX bXM2+IZLq8kq3s7ck0EZrRVhsivutcaZwDXRCCinB+OlPedbzXwNZGvVX0nwPYHG BfiXwdiuZeVJ88ni6Fm6RhoPtu2QF1UExfBvSXuMBgR+evp+e3QadNpGx6Ppl1aC hWF6W2H9+MAlU7yvtmCQQuZmfQ== -----END CERTIFICATE----- Save file as public-cert.pem Example 1: Filename: index.js Javascript // Node.js program to demonstrate the// server.address() method var tls = require('tls'), fs = require('fs'), // Port and host address for server PORT = 1337,HOST = '127.0.0.1',value = ""; // Private key and public certificate for accessvar options = { key: fs.readFileSync('private-key.pem'), cert: fs.readFileSync('public-cert.pem'), rejectUnauthorized: false}; // Creating and initializing servervar server = tls.createServer(options, function(socket) { // Print the data that we received socket.on("data", function(data) { console.log('\nReceived: %s ', data.toString().replace(/(\n)/gm, "")); }); }); // Start listening on a specific port and addressserver.listen(PORT, HOST, function() { console.log("I'm listening at %s, on port %s", HOST, PORT);}); // When an error occurs, show it.server.on("error", function(error) { console.error(error); // Close the connection after the error occurred. // server.destroy(); }); server.on("end", ()=>{ server.end(); // server.destroy();}) // Creating and initializing clientvar client = tls.connect(PORT, HOST, options, function() { // Check if the authorization worked if (client.authorized) { console.log("Connection authorized by" + " a Certificate Authority."); } else { console.log("Connection not authorized: " + client.authorizationError) } // Send a friendly message client.write("Bound address : " + value); client.end();}); // Getting the bound address // by using address methodvalue = client.address(); // console.log("Bound address : " + value) client.on("close", function() { console.log("Connection closed");}); // When an error occurs, show it.client.on("error", function(error) { console.error(error); // Close the connection after the error occurred. client.destroy(); }); Output: I'm listening at 127.0.0.1, on port 1337 Connection not authorized: DEPTH_ZERO_SELF_SIGNED_CERT Received: Bound address : [object Object] Connection closed Example 2: Filename: index.js Javascript // Node.js program to demonstrate the// server.address() method var tls = require('tls'), fs = require('fs'), // Port and host address for server PORT = 1337,HOST = '127.0.0.1'; // Private key and public certificate for accessvar options = { key: fs.readFileSync('private-key.pem'), cert: fs.readFileSync('public-cert.pem'), rejectUnauthorized: false}; // Creating and initializing servervar server = tls.createServer(options, function(socket) { // Print the data that we received socket.on('data', function(data) { console.log('\nReceived: %s ', data.toString().replace(/(\n)/gm, "")); });}); // Start listening on a specific port and addressserver.listen(PORT, HOST, function() { console.log("I'm listening at %s, " + "on port %s", HOST, PORT);}); // Creating and initializing clientvar client = tls.connect(PORT, HOST, options, function() { // Getting the bound address // by using address method const value = client.address(); client.write("Bound address : " + value) client.end();}); Run the index.js file using the following command: node index.js Output: I'm listening at 127.0.0.1, on port 1337 Received: Bound address : [object Object] Reference: https://nodejs.org/dist/latest-v12.x/docs/api/tls.html#tls_server_address anikakapoor sweetyty Node.js-Methods Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n03 Sep, 2021" }, { "code": null, "e": 185, "s": 28, "text": "The server.address() is an inbuilt application programming interface of class Socket within tls module which is used to get the bound address of the server." }, { "code": null, "e": 193, "s": 185, "text": "Syntax:" }, { "code": null, "e": 217, "s": 193, "text": "const server.address()\n" }, { "code": null, "e": 272, "s": 217, "text": "Parameters: This method does not accept any parameter." }, { "code": null, "e": 375, "s": 272, "text": "Return Value: This method return the bound address containing the family name, and port of the server." }, { "code": null, "e": 427, "s": 375, "text": "How to generate private key and public certificate?" }, { "code": null, "e": 2422, "s": 427, "text": "Private key: Open notepad and copy paste the following key:-----BEGIN RSA PRIVATE KEY-----\nMIICXQIBAAKBgQC38R9wXcUbhOd44FavgmE5R3K4JeYOHLnI7dUq1B8/Gv7l3SOg\nJKef/m9gM1KvUx951mapXGtcWgwB08J3vUE2YOZ4tWJArrVZES0BI/RmFAyhQFP5\nHcWl3LSM9LRihP98F33oIkKaCxA5LxOrkgpV4HrUzIKTABDYah7RPex1WQIDAQAB\nAoGBAIXR71xxa9gUfc5L7+TqBs+EMmrUb6Vusp8CoGXzQvRHMJCMrMFySV0131Nu\no0YYRDsAh1nJefYLMNcXd1BjqI+qY8IeRsxaY+9CB2KKGVVDO2uLdurdC2ZdlWXT\nVwr3dDoyR0trnXJMmH2ijTeO6bush8HuXxvxJBjvEllM5QYxAkEA3jwny9JP+RFu\n0rkqPBe/wi5pXpPl7PUtdNAGrh6S5958wUoR4f9bvwmTBv1nQzExKWu4EIp+7vjJ\nfBeRZhnBvQJBANPjjge8418PS9zAFyKlITq6cxmM4gOWeveQZwXVNvav0NH+OKdQ\nsZnnDiG26JWmnD/B8Audu97LcxjxcWI8Jc0CQEYA5PhLU229lA9EzI0JXhoozIBC\nTlcKFDuLm88VSmlHqDyqvF9YNOpEdc/p2rFLuZS2ndB4D+vu6mjwc5iZ3HECQCxy\nGBHRclQ3Ti9w76lpv+2kvI4IekRMZWDWnnWfwta+DGxwCgw2pfpleBZkWqdBepb5\nJFQbcxQJ0wvRYXo8qaUCQQCgTvWswBj6OTP7LTvBlU1teAN2Lnrk/N5AYHZIXW6m\nnUG9lYvH7DztWDTioXMrruPF7bdXfZOVJD8t0I4OUzvC\n-----END RSA PRIVATE KEY-----Save file as private-key.pemPublic certificate: Open notepad and copy paste the following key:-----BEGIN CERTIFICATE-----\nMIICfzCCAegCCQDxxeXw914Y2DANBgkqhkiG9w0BAQsFADCBgzELMAkGA1UEBhMC\nSU4xEzARBgNVBAgMCldlc3RiZW5nYWwxEDAOBgNVBAcMB0tvbGthdGExFDASBgNV\nBAoMC1BhbmNvLCBJbmMuMRUwEwYDVQQDDAxSb2hpdCBQcmFzYWQxIDAeBgkqhkiG\n9w0BCQEWEXJvZm9mb2ZAZ21haWwuY29tMB4XDTIwMDkwOTA1NTExN1oXDTIwMTAw\nOTA1NTExN1owgYMxCzAJBgNVBAYTAklOMRMwEQYDVQQIDApXZXN0YmVuZ2FsMRAw\nDgYDVQQHDAdLb2xrYXRhMRQwEgYDVQQKDAtQYW5jbywgSW5jLjEVMBMGA1UEAwwM\nUm9oaXQgUHJhc2FkMSAwHgYJKoZIhvcNAQkBFhFyb2ZvZm9mQGdtYWlsLmNvbTCB\nnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAt/EfcF3FG4TneOBWr4JhOUdyuCXm\nDhy5yO3VKtQfPxr+5d0joCSnn/5vYDNSr1MfedZmqVxrXFoMAdPCd71BNmDmeLVi\nQK61WREtASP0ZhQMoUBT+R3Fpdy0jPS0YoT/fBd96CJCmgsQOS8Tq5IKVeB61MyC\nkwAQ2Goe0T3sdVkCAwEAATANBgkqhkiG9w0BAQsFAAOBgQATe6ixdAjoV7BSHgRX\nbXM2+IZLq8kq3s7ck0EZrRVhsivutcaZwDXRCCinB+OlPedbzXwNZGvVX0nwPYHG\nBfiXwdiuZeVJ88ni6Fm6RhoPtu2QF1UExfBvSXuMBgR+evp+e3QadNpGx6Ppl1aC\nhWF6W2H9+MAlU7yvtmCQQuZmfQ==\n-----END CERTIFICATE-----Save file as public-cert.pem" }, { "code": null, "e": 3396, "s": 2422, "text": "Private key: Open notepad and copy paste the following key:-----BEGIN RSA PRIVATE KEY-----\nMIICXQIBAAKBgQC38R9wXcUbhOd44FavgmE5R3K4JeYOHLnI7dUq1B8/Gv7l3SOg\nJKef/m9gM1KvUx951mapXGtcWgwB08J3vUE2YOZ4tWJArrVZES0BI/RmFAyhQFP5\nHcWl3LSM9LRihP98F33oIkKaCxA5LxOrkgpV4HrUzIKTABDYah7RPex1WQIDAQAB\nAoGBAIXR71xxa9gUfc5L7+TqBs+EMmrUb6Vusp8CoGXzQvRHMJCMrMFySV0131Nu\no0YYRDsAh1nJefYLMNcXd1BjqI+qY8IeRsxaY+9CB2KKGVVDO2uLdurdC2ZdlWXT\nVwr3dDoyR0trnXJMmH2ijTeO6bush8HuXxvxJBjvEllM5QYxAkEA3jwny9JP+RFu\n0rkqPBe/wi5pXpPl7PUtdNAGrh6S5958wUoR4f9bvwmTBv1nQzExKWu4EIp+7vjJ\nfBeRZhnBvQJBANPjjge8418PS9zAFyKlITq6cxmM4gOWeveQZwXVNvav0NH+OKdQ\nsZnnDiG26JWmnD/B8Audu97LcxjxcWI8Jc0CQEYA5PhLU229lA9EzI0JXhoozIBC\nTlcKFDuLm88VSmlHqDyqvF9YNOpEdc/p2rFLuZS2ndB4D+vu6mjwc5iZ3HECQCxy\nGBHRclQ3Ti9w76lpv+2kvI4IekRMZWDWnnWfwta+DGxwCgw2pfpleBZkWqdBepb5\nJFQbcxQJ0wvRYXo8qaUCQQCgTvWswBj6OTP7LTvBlU1teAN2Lnrk/N5AYHZIXW6m\nnUG9lYvH7DztWDTioXMrruPF7bdXfZOVJD8t0I4OUzvC\n-----END RSA PRIVATE KEY-----Save file as private-key.pem" }, { "code": null, "e": 4283, "s": 3396, "text": "-----BEGIN RSA PRIVATE KEY-----\nMIICXQIBAAKBgQC38R9wXcUbhOd44FavgmE5R3K4JeYOHLnI7dUq1B8/Gv7l3SOg\nJKef/m9gM1KvUx951mapXGtcWgwB08J3vUE2YOZ4tWJArrVZES0BI/RmFAyhQFP5\nHcWl3LSM9LRihP98F33oIkKaCxA5LxOrkgpV4HrUzIKTABDYah7RPex1WQIDAQAB\nAoGBAIXR71xxa9gUfc5L7+TqBs+EMmrUb6Vusp8CoGXzQvRHMJCMrMFySV0131Nu\no0YYRDsAh1nJefYLMNcXd1BjqI+qY8IeRsxaY+9CB2KKGVVDO2uLdurdC2ZdlWXT\nVwr3dDoyR0trnXJMmH2ijTeO6bush8HuXxvxJBjvEllM5QYxAkEA3jwny9JP+RFu\n0rkqPBe/wi5pXpPl7PUtdNAGrh6S5958wUoR4f9bvwmTBv1nQzExKWu4EIp+7vjJ\nfBeRZhnBvQJBANPjjge8418PS9zAFyKlITq6cxmM4gOWeveQZwXVNvav0NH+OKdQ\nsZnnDiG26JWmnD/B8Audu97LcxjxcWI8Jc0CQEYA5PhLU229lA9EzI0JXhoozIBC\nTlcKFDuLm88VSmlHqDyqvF9YNOpEdc/p2rFLuZS2ndB4D+vu6mjwc5iZ3HECQCxy\nGBHRclQ3Ti9w76lpv+2kvI4IekRMZWDWnnWfwta+DGxwCgw2pfpleBZkWqdBepb5\nJFQbcxQJ0wvRYXo8qaUCQQCgTvWswBj6OTP7LTvBlU1teAN2Lnrk/N5AYHZIXW6m\nnUG9lYvH7DztWDTioXMrruPF7bdXfZOVJD8t0I4OUzvC\n-----END RSA PRIVATE KEY-----" }, { "code": null, "e": 4312, "s": 4283, "text": "Save file as private-key.pem" }, { "code": null, "e": 5334, "s": 4312, "text": "Public certificate: Open notepad and copy paste the following key:-----BEGIN CERTIFICATE-----\nMIICfzCCAegCCQDxxeXw914Y2DANBgkqhkiG9w0BAQsFADCBgzELMAkGA1UEBhMC\nSU4xEzARBgNVBAgMCldlc3RiZW5nYWwxEDAOBgNVBAcMB0tvbGthdGExFDASBgNV\nBAoMC1BhbmNvLCBJbmMuMRUwEwYDVQQDDAxSb2hpdCBQcmFzYWQxIDAeBgkqhkiG\n9w0BCQEWEXJvZm9mb2ZAZ21haWwuY29tMB4XDTIwMDkwOTA1NTExN1oXDTIwMTAw\nOTA1NTExN1owgYMxCzAJBgNVBAYTAklOMRMwEQYDVQQIDApXZXN0YmVuZ2FsMRAw\nDgYDVQQHDAdLb2xrYXRhMRQwEgYDVQQKDAtQYW5jbywgSW5jLjEVMBMGA1UEAwwM\nUm9oaXQgUHJhc2FkMSAwHgYJKoZIhvcNAQkBFhFyb2ZvZm9mQGdtYWlsLmNvbTCB\nnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAt/EfcF3FG4TneOBWr4JhOUdyuCXm\nDhy5yO3VKtQfPxr+5d0joCSnn/5vYDNSr1MfedZmqVxrXFoMAdPCd71BNmDmeLVi\nQK61WREtASP0ZhQMoUBT+R3Fpdy0jPS0YoT/fBd96CJCmgsQOS8Tq5IKVeB61MyC\nkwAQ2Goe0T3sdVkCAwEAATANBgkqhkiG9w0BAQsFAAOBgQATe6ixdAjoV7BSHgRX\nbXM2+IZLq8kq3s7ck0EZrRVhsivutcaZwDXRCCinB+OlPedbzXwNZGvVX0nwPYHG\nBfiXwdiuZeVJ88ni6Fm6RhoPtu2QF1UExfBvSXuMBgR+evp+e3QadNpGx6Ppl1aC\nhWF6W2H9+MAlU7yvtmCQQuZmfQ==\n-----END CERTIFICATE-----Save file as public-cert.pem" }, { "code": null, "e": 6262, "s": 5334, "text": "-----BEGIN CERTIFICATE-----\nMIICfzCCAegCCQDxxeXw914Y2DANBgkqhkiG9w0BAQsFADCBgzELMAkGA1UEBhMC\nSU4xEzARBgNVBAgMCldlc3RiZW5nYWwxEDAOBgNVBAcMB0tvbGthdGExFDASBgNV\nBAoMC1BhbmNvLCBJbmMuMRUwEwYDVQQDDAxSb2hpdCBQcmFzYWQxIDAeBgkqhkiG\n9w0BCQEWEXJvZm9mb2ZAZ21haWwuY29tMB4XDTIwMDkwOTA1NTExN1oXDTIwMTAw\nOTA1NTExN1owgYMxCzAJBgNVBAYTAklOMRMwEQYDVQQIDApXZXN0YmVuZ2FsMRAw\nDgYDVQQHDAdLb2xrYXRhMRQwEgYDVQQKDAtQYW5jbywgSW5jLjEVMBMGA1UEAwwM\nUm9oaXQgUHJhc2FkMSAwHgYJKoZIhvcNAQkBFhFyb2ZvZm9mQGdtYWlsLmNvbTCB\nnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAt/EfcF3FG4TneOBWr4JhOUdyuCXm\nDhy5yO3VKtQfPxr+5d0joCSnn/5vYDNSr1MfedZmqVxrXFoMAdPCd71BNmDmeLVi\nQK61WREtASP0ZhQMoUBT+R3Fpdy0jPS0YoT/fBd96CJCmgsQOS8Tq5IKVeB61MyC\nkwAQ2Goe0T3sdVkCAwEAATANBgkqhkiG9w0BAQsFAAOBgQATe6ixdAjoV7BSHgRX\nbXM2+IZLq8kq3s7ck0EZrRVhsivutcaZwDXRCCinB+OlPedbzXwNZGvVX0nwPYHG\nBfiXwdiuZeVJ88ni6Fm6RhoPtu2QF1UExfBvSXuMBgR+evp+e3QadNpGx6Ppl1aC\nhWF6W2H9+MAlU7yvtmCQQuZmfQ==\n-----END CERTIFICATE-----" }, { "code": null, "e": 6291, "s": 6262, "text": "Save file as public-cert.pem" }, { "code": null, "e": 6321, "s": 6291, "text": "Example 1: Filename: index.js" }, { "code": null, "e": 6332, "s": 6321, "text": "Javascript" }, { "code": "// Node.js program to demonstrate the// server.address() method var tls = require('tls'), fs = require('fs'), // Port and host address for server PORT = 1337,HOST = '127.0.0.1',value = \"\"; // Private key and public certificate for accessvar options = { key: fs.readFileSync('private-key.pem'), cert: fs.readFileSync('public-cert.pem'), rejectUnauthorized: false}; // Creating and initializing servervar server = tls.createServer(options, function(socket) { // Print the data that we received socket.on(\"data\", function(data) { console.log('\\nReceived: %s ', data.toString().replace(/(\\n)/gm, \"\")); }); }); // Start listening on a specific port and addressserver.listen(PORT, HOST, function() { console.log(\"I'm listening at %s, on port %s\", HOST, PORT);}); // When an error occurs, show it.server.on(\"error\", function(error) { console.error(error); // Close the connection after the error occurred. // server.destroy(); }); server.on(\"end\", ()=>{ server.end(); // server.destroy();}) // Creating and initializing clientvar client = tls.connect(PORT, HOST, options, function() { // Check if the authorization worked if (client.authorized) { console.log(\"Connection authorized by\" + \" a Certificate Authority.\"); } else { console.log(\"Connection not authorized: \" + client.authorizationError) } // Send a friendly message client.write(\"Bound address : \" + value); client.end();}); // Getting the bound address // by using address methodvalue = client.address(); // console.log(\"Bound address : \" + value) client.on(\"close\", function() { console.log(\"Connection closed\");}); // When an error occurs, show it.client.on(\"error\", function(error) { console.error(error); // Close the connection after the error occurred. client.destroy(); });", "e": 8169, "s": 6332, "text": null }, { "code": null, "e": 8177, "s": 8169, "text": "Output:" }, { "code": null, "e": 8335, "s": 8177, "text": "I'm listening at 127.0.0.1, on port 1337\nConnection not authorized: DEPTH_ZERO_SELF_SIGNED_CERT\n\nReceived: Bound address : [object Object]\nConnection closed\n" }, { "code": null, "e": 8365, "s": 8335, "text": "Example 2: Filename: index.js" }, { "code": null, "e": 8376, "s": 8365, "text": "Javascript" }, { "code": "// Node.js program to demonstrate the// server.address() method var tls = require('tls'), fs = require('fs'), // Port and host address for server PORT = 1337,HOST = '127.0.0.1'; // Private key and public certificate for accessvar options = { key: fs.readFileSync('private-key.pem'), cert: fs.readFileSync('public-cert.pem'), rejectUnauthorized: false}; // Creating and initializing servervar server = tls.createServer(options, function(socket) { // Print the data that we received socket.on('data', function(data) { console.log('\\nReceived: %s ', data.toString().replace(/(\\n)/gm, \"\")); });}); // Start listening on a specific port and addressserver.listen(PORT, HOST, function() { console.log(\"I'm listening at %s, \" + \"on port %s\", HOST, PORT);}); // Creating and initializing clientvar client = tls.connect(PORT, HOST, options, function() { // Getting the bound address // by using address method const value = client.address(); client.write(\"Bound address : \" + value) client.end();});", "e": 9417, "s": 8376, "text": null }, { "code": null, "e": 9468, "s": 9417, "text": "Run the index.js file using the following command:" }, { "code": null, "e": 9483, "s": 9468, "text": "node index.js\n" }, { "code": null, "e": 9491, "s": 9483, "text": "Output:" }, { "code": null, "e": 9577, "s": 9491, "text": "I'm listening at 127.0.0.1, on port 1337\n\nReceived: Bound address : [object Object] \n" }, { "code": null, "e": 9662, "s": 9577, "text": "Reference: https://nodejs.org/dist/latest-v12.x/docs/api/tls.html#tls_server_address" }, { "code": null, "e": 9674, "s": 9662, "text": "anikakapoor" }, { "code": null, "e": 9683, "s": 9674, "text": "sweetyty" }, { "code": null, "e": 9699, "s": 9683, "text": "Node.js-Methods" }, { "code": null, "e": 9707, "s": 9699, "text": "Node.js" }, { "code": null, "e": 9724, "s": 9707, "text": "Web Technologies" } ]
Policy based data structures in g++
23 May, 2022 The g++ compiler also supports some data structures that are not part of the C++ standard library. Such structures are called policy-based data structures. These data structures are designed for high-performance, flexibility, semantic safety, and conformance to the corresponding containers in std.To use these structures, the following lines must be added to the code: C++ #include <ext/pb_ds/assoc_container.hpp>using namespace __gnu_pbds; For example, following is a code showing a policy-based data structure that is like set, it can add/remove elements, can find the number of elements less than x, kth smallest element etc in O(logn) time. It can also be indexed like an array. The specialty of this set is that we have access to the indices that the elements would have in a sorted array. If the element does not appear in the set, we get the position that the element would have in the set. C++ // Program showing a policy-based data structure.#include <ext/pb_ds/assoc_container.hpp> // Common file#include <ext/pb_ds/tree_policy.hpp>#include <functional> // for less#include <iostream>using namespace __gnu_pbds;using namespace std; // a new data structure defined. Please refer below// GNU link : https://goo.gl/WVDL6gtypedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> ordered_set; // Driver codeint main(){ ordered_set p; p.insert(5); p.insert(2); p.insert(6); p.insert(4); // value at 3rd index in sorted array. cout << "The value at 3rd index ::" << *p.find_by_order(3) << endl; // index of number 6 cout << "The index of number 6::" << p.order_of_key(6) << endl; // number 7 not in the set but it will show the // index number if it was there in sorted array. cout << "The index of number seven ::" << p.order_of_key(7) << endl; return 0;} Output: The value at 3rd index ::6 The index of number 6::3 The index of number seven ::4 NOTE: Both the functions order_of_key and find_by_order work in logarithmic time. NOTE (FOR WINDOW USERS) : Window users might face problem importing pbds library . To fix it follow the following steps: Step 1: Go to directory where MinGW is installed. Step 2: Navigate to \lib\gcc\mingw32\8.2.0\include\c++\ext\pb_ds\detail\resize_policy Step 3: Rename β€œhash_standard_resize_policy_imp.hpp0000644” to β€œhash_standard_resize_policy_imp.hpp” In order to insert multiple copies of the same element in the ordered set replace the following line, typedef tree<int , null_type, less<int> , rb_tree_tag , tree_order_statistics_node_update> ordered_set; With typedef tree<int , null_type , less_equal<int> , rb_tree_tag , tree_order_statistics_node_update> ordered_multiset C++ // Program showing a policy-based data structure.#include <ext/pb_ds/assoc_container.hpp> // Common file#include <ext/pb_ds/tree_policy.hpp>#include <functional> // for less#include <iostream>using namespace __gnu_pbds;using namespace std; // a new data structure defined. Please refer below// GNU link : https://goo.gl/WVDL6gtypedef tree<int, null_type, less_equal<int>, rb_tree_tag, tree_order_statistics_node_update> ordered_multiset; // Driver codeint main(){ ordered_multiset p; p.insert(5); p.insert(5); p.insert(5); p.insert(2); p.insert(2); p.insert(6); p.insert(4); for (int i = 0; i < (int)p.size(); i++) { cout << "The element present at the index " << i << " is "; // Print element present at the ith index cout << *p.find_by_order(i) << ' '; cout << '\n'; } return 0;} The element present at the index 0 is 2 The element present at the index 1 is 2 The element present at the index 2 is 4 The element present at the index 3 is 5 The element present at the index 4 is 5 The element present at the index 5 is 5 The element present at the index 6 is 6 bhuwanesh finest_atg assharmacr7 C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Vector in C++ STL Map in C++ Standard Template Library (STL) Initialize a vector in C++ (7 different ways) std::sort() in C++ STL Bitwise Operators in C/C++ Arrays in C/C++ Set in C++ Standard Template Library (STL) vector erase() and clear() in C++ unordered_map in C++ STL Inheritance in C++
[ { "code": null, "e": 54, "s": 26, "text": "\n23 May, 2022" }, { "code": null, "e": 426, "s": 54, "text": "The g++ compiler also supports some data structures that are not part of the C++ standard library. Such structures are called policy-based data structures. These data structures are designed for high-performance, flexibility, semantic safety, and conformance to the corresponding containers in std.To use these structures, the following lines must be added to the code: " }, { "code": null, "e": 430, "s": 426, "text": "C++" }, { "code": "#include <ext/pb_ds/assoc_container.hpp>using namespace __gnu_pbds;", "e": 498, "s": 430, "text": null }, { "code": null, "e": 956, "s": 498, "text": "For example, following is a code showing a policy-based data structure that is like set, it can add/remove elements, can find the number of elements less than x, kth smallest element etc in O(logn) time. It can also be indexed like an array. The specialty of this set is that we have access to the indices that the elements would have in a sorted array. If the element does not appear in the set, we get the position that the element would have in the set. " }, { "code": null, "e": 960, "s": 956, "text": "C++" }, { "code": "// Program showing a policy-based data structure.#include <ext/pb_ds/assoc_container.hpp> // Common file#include <ext/pb_ds/tree_policy.hpp>#include <functional> // for less#include <iostream>using namespace __gnu_pbds;using namespace std; // a new data structure defined. Please refer below// GNU link : https://goo.gl/WVDL6gtypedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> ordered_set; // Driver codeint main(){ ordered_set p; p.insert(5); p.insert(2); p.insert(6); p.insert(4); // value at 3rd index in sorted array. cout << \"The value at 3rd index ::\" << *p.find_by_order(3) << endl; // index of number 6 cout << \"The index of number 6::\" << p.order_of_key(6) << endl; // number 7 not in the set but it will show the // index number if it was there in sorted array. cout << \"The index of number seven ::\" << p.order_of_key(7) << endl; return 0;}", "e": 1931, "s": 960, "text": null }, { "code": null, "e": 1941, "s": 1931, "text": "Output: " }, { "code": null, "e": 2023, "s": 1941, "text": "The value at 3rd index ::6\nThe index of number 6::3\nThe index of number seven ::4" }, { "code": null, "e": 2105, "s": 2023, "text": "NOTE: Both the functions order_of_key and find_by_order work in logarithmic time." }, { "code": null, "e": 2226, "s": 2105, "text": "NOTE (FOR WINDOW USERS) : Window users might face problem importing pbds library . To fix it follow the following steps:" }, { "code": null, "e": 2286, "s": 2226, "text": " Step 1: Go to directory where MinGW is installed." }, { "code": null, "e": 2381, "s": 2286, "text": " Step 2: Navigate to \\lib\\gcc\\mingw32\\8.2.0\\include\\c++\\ext\\pb_ds\\detail\\resize_policy" }, { "code": null, "e": 2491, "s": 2381, "text": " Step 3: Rename β€œhash_standard_resize_policy_imp.hpp0000644” to β€œhash_standard_resize_policy_imp.hpp”" }, { "code": null, "e": 2593, "s": 2491, "text": "In order to insert multiple copies of the same element in the ordered set replace the following line," }, { "code": null, "e": 2697, "s": 2593, "text": "typedef tree<int , null_type, less<int> , rb_tree_tag , tree_order_statistics_node_update> ordered_set;" }, { "code": null, "e": 2702, "s": 2697, "text": "With" }, { "code": null, "e": 2818, "s": 2702, "text": "typedef tree<int , null_type , less_equal<int> , rb_tree_tag , tree_order_statistics_node_update> ordered_multiset" }, { "code": null, "e": 2822, "s": 2818, "text": "C++" }, { "code": "// Program showing a policy-based data structure.#include <ext/pb_ds/assoc_container.hpp> // Common file#include <ext/pb_ds/tree_policy.hpp>#include <functional> // for less#include <iostream>using namespace __gnu_pbds;using namespace std; // a new data structure defined. Please refer below// GNU link : https://goo.gl/WVDL6gtypedef tree<int, null_type, less_equal<int>, rb_tree_tag, tree_order_statistics_node_update> ordered_multiset; // Driver codeint main(){ ordered_multiset p; p.insert(5); p.insert(5); p.insert(5); p.insert(2); p.insert(2); p.insert(6); p.insert(4); for (int i = 0; i < (int)p.size(); i++) { cout << \"The element present at the index \" << i << \" is \"; // Print element present at the ith index cout << *p.find_by_order(i) << ' '; cout << '\\n'; } return 0;}", "e": 3696, "s": 2822, "text": null }, { "code": null, "e": 3983, "s": 3696, "text": "The element present at the index 0 is 2 \nThe element present at the index 1 is 2 \nThe element present at the index 2 is 4 \nThe element present at the index 3 is 5 \nThe element present at the index 4 is 5 \nThe element present at the index 5 is 5 \nThe element present at the index 6 is 6 " }, { "code": null, "e": 3993, "s": 3983, "text": "bhuwanesh" }, { "code": null, "e": 4004, "s": 3993, "text": "finest_atg" }, { "code": null, "e": 4016, "s": 4004, "text": "assharmacr7" }, { "code": null, "e": 4020, "s": 4016, "text": "C++" }, { "code": null, "e": 4024, "s": 4020, "text": "CPP" }, { "code": null, "e": 4122, "s": 4024, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4140, "s": 4122, "text": "Vector in C++ STL" }, { "code": null, "e": 4183, "s": 4140, "text": "Map in C++ Standard Template Library (STL)" }, { "code": null, "e": 4229, "s": 4183, "text": "Initialize a vector in C++ (7 different ways)" }, { "code": null, "e": 4252, "s": 4229, "text": "std::sort() in C++ STL" }, { "code": null, "e": 4279, "s": 4252, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 4295, "s": 4279, "text": "Arrays in C/C++" }, { "code": null, "e": 4338, "s": 4295, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 4372, "s": 4338, "text": "vector erase() and clear() in C++" }, { "code": null, "e": 4397, "s": 4372, "text": "unordered_map in C++ STL" } ]
How to Map a Rune to Uppercase in Golang?
27 Sep, 2019 Rune is a superset of ASCII or it is an alias of int32. It holds all the characters available in the world’s writing system, including accents and other diacritical marks, control codes like tab and carriage return, and assigns each one a standard number. This standard number is known as a Unicode code point or rune in the Go language.You are allowed to map the given rune into the upper case with the help of ToUpper() function. This function changes the case of the given rune(if the case of the rune is lower or title) into upper case and if the given rune is already present in upper case, then this function does nothing. This function is defined under Unicode package, so for accessing this method you need to import the Unicode package in your program. Syntax: func ToUpper(r rune) rune Example: // Go program to illustrate how to// Map a rune to Uppercasepackage main import ( "fmt" "unicode") // Main functionfunc main() { // Creating rune rune_1 := 'G' rune_2 := 'e' rune_3 := 'E' rune_4 := 'k' // Mapping the given rune // into upper case // Using ToUpper() function fmt.Printf("Result 1: %c ", unicode.ToUpper(rune_1)) fmt.Printf("\nResult 2: %c ", unicode.ToUpper(rune_2)) fmt.Printf("\nResult 3: %c ", unicode.ToUpper(rune_3)) fmt.Printf("\nResult 4: %c ", unicode.ToUpper(rune_4)) fmt.Printf("\nResult 5: %c ", unicode.ToUpper('s')) } Output: Result 1: G Result 2: E Result 3: E Result 4: K Result 5: S Golang Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Arrays in Go Golang Maps How to Split a String in Golang? Interfaces in Golang Slices in Golang Different Ways to Find the Type of Variable in Golang How to convert a string in lower case in Golang? How to Parse JSON in Golang? How to Trim a String in Golang? Inheritance in GoLang
[ { "code": null, "e": 28, "s": 0, "text": "\n27 Sep, 2019" }, { "code": null, "e": 790, "s": 28, "text": "Rune is a superset of ASCII or it is an alias of int32. It holds all the characters available in the world’s writing system, including accents and other diacritical marks, control codes like tab and carriage return, and assigns each one a standard number. This standard number is known as a Unicode code point or rune in the Go language.You are allowed to map the given rune into the upper case with the help of ToUpper() function. This function changes the case of the given rune(if the case of the rune is lower or title) into upper case and if the given rune is already present in upper case, then this function does nothing. This function is defined under Unicode package, so for accessing this method you need to import the Unicode package in your program." }, { "code": null, "e": 798, "s": 790, "text": "Syntax:" }, { "code": null, "e": 824, "s": 798, "text": "func ToUpper(r rune) rune" }, { "code": null, "e": 833, "s": 824, "text": "Example:" }, { "code": "// Go program to illustrate how to// Map a rune to Uppercasepackage main import ( \"fmt\" \"unicode\") // Main functionfunc main() { // Creating rune rune_1 := 'G' rune_2 := 'e' rune_3 := 'E' rune_4 := 'k' // Mapping the given rune // into upper case // Using ToUpper() function fmt.Printf(\"Result 1: %c \", unicode.ToUpper(rune_1)) fmt.Printf(\"\\nResult 2: %c \", unicode.ToUpper(rune_2)) fmt.Printf(\"\\nResult 3: %c \", unicode.ToUpper(rune_3)) fmt.Printf(\"\\nResult 4: %c \", unicode.ToUpper(rune_4)) fmt.Printf(\"\\nResult 5: %c \", unicode.ToUpper('s')) }", "e": 1432, "s": 833, "text": null }, { "code": null, "e": 1440, "s": 1432, "text": "Output:" }, { "code": null, "e": 1506, "s": 1440, "text": "Result 1: G \nResult 2: E \nResult 3: E \nResult 4: K \nResult 5: S \n" }, { "code": null, "e": 1513, "s": 1506, "text": "Golang" }, { "code": null, "e": 1525, "s": 1513, "text": "Go Language" }, { "code": null, "e": 1623, "s": 1525, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1636, "s": 1623, "text": "Arrays in Go" }, { "code": null, "e": 1648, "s": 1636, "text": "Golang Maps" }, { "code": null, "e": 1681, "s": 1648, "text": "How to Split a String in Golang?" }, { "code": null, "e": 1702, "s": 1681, "text": "Interfaces in Golang" }, { "code": null, "e": 1719, "s": 1702, "text": "Slices in Golang" }, { "code": null, "e": 1773, "s": 1719, "text": "Different Ways to Find the Type of Variable in Golang" }, { "code": null, "e": 1822, "s": 1773, "text": "How to convert a string in lower case in Golang?" }, { "code": null, "e": 1851, "s": 1822, "text": "How to Parse JSON in Golang?" }, { "code": null, "e": 1883, "s": 1851, "text": "How to Trim a String in Golang?" } ]
Software Testing | Database Testing
16 May, 2019 Database Testing is a type of software testing that checks the schema, tables, triggers etc. of the database under test. It involves creating complex queries for performing the load or stress test on the database and check its responsiveness. It checks integrity and consistency of data. Database testing usually consists of a layered process that includes the User Interface (UI) layer, the business layer, the data access layer and the database. Objective of the Database Testing: Ensure Data Mapping:It checks whether the fields in the user interface or front end forms are mapped consistently with the corresponding fields in the database table.Ensure ACID Properties of Transactions:Every transaction a database performs has to stick to these four properties: Atomicity, Consistency, Isolation and Durability.Ensure Data Integrity:The updated and the most recent values of shared data should appear on all the forms and screens. The value should not be updated on one screen and display an older value on another one. The status should also be updated simultaneously.Ensure the Accuracy of the Business Rules:Complex databases leads to complicated components like relational constraints, triggers and stored procedures. Hence in order testers come up with appropriate SQL queries to validate the complex objects. Ensure Data Mapping:It checks whether the fields in the user interface or front end forms are mapped consistently with the corresponding fields in the database table. Ensure ACID Properties of Transactions:Every transaction a database performs has to stick to these four properties: Atomicity, Consistency, Isolation and Durability. Ensure Data Integrity:The updated and the most recent values of shared data should appear on all the forms and screens. The value should not be updated on one screen and display an older value on another one. The status should also be updated simultaneously. Ensure the Accuracy of the Business Rules:Complex databases leads to complicated components like relational constraints, triggers and stored procedures. Hence in order testers come up with appropriate SQL queries to validate the complex objects. Database Testing Attributes: Transactions:Transactions means the access and retrieve of the data. Hence in order during the transaction processes the ACID properties should be followed.Database Schema:It is the design or the structure about the organization of the data in the database.Triggers:When a certain event occurs in a certain table, a trigger is auto-instructed to be executed.Procedures:It is the collection of the statements or functions governing the transactions in the database. Transactions:Transactions means the access and retrieve of the data. Hence in order during the transaction processes the ACID properties should be followed. Database Schema:It is the design or the structure about the organization of the data in the database. Triggers:When a certain event occurs in a certain table, a trigger is auto-instructed to be executed. Procedures:It is the collection of the statements or functions governing the transactions in the database. Database Testing Process: Test Environment Setup:Database testing starts with the setting up the testing environment for the testing process to be carried out in order get a good quality testing process.Test Scenario Generation:After setting up the test environment test cases are designed for conducting the test. Test scenario involve the different inputs and different transactions related to database.Execution:Execution is the core phase of the testing process in which the testing is conducted. It is basically related to the execution of the test cases designed for the testing process.Analysis:Once the execution phase is ended then all the process and the output obtained is analyzed. It is checked whether the testing process has been conducted properly or not.Log Defects:Log defects are also known as report submitting. In this last phase tester informs the developer about the defects found in the database of the system. Test Environment Setup:Database testing starts with the setting up the testing environment for the testing process to be carried out in order get a good quality testing process. Test Scenario Generation:After setting up the test environment test cases are designed for conducting the test. Test scenario involve the different inputs and different transactions related to database. Execution:Execution is the core phase of the testing process in which the testing is conducted. It is basically related to the execution of the test cases designed for the testing process. Analysis:Once the execution phase is ended then all the process and the output obtained is analyzed. It is checked whether the testing process has been conducted properly or not. Log Defects:Log defects are also known as report submitting. In this last phase tester informs the developer about the defects found in the database of the system. Misconceptions related to Database Testing: It requires experts to carry out database testing The process of database testing is lengthy It adds extra work bottlenecks It slows down the overall development process It is a highly costly process Software Testing Software Engineering Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Software Engineering | Black box testing Unit Testing | Software Testing System Testing Difference Between Edge Computing and Fog Computing Software Engineering | Integration Testing What is DFD(Data Flow Diagram)? Software Engineering | Calculation of Function Point (FP) Software Development Life Cycle (SDLC) Software Processes in Software Engineering Software Engineering | Re-engineering
[ { "code": null, "e": 28, "s": 0, "text": "\n16 May, 2019" }, { "code": null, "e": 316, "s": 28, "text": "Database Testing is a type of software testing that checks the schema, tables, triggers etc. of the database under test. It involves creating complex queries for performing the load or stress test on the database and check its responsiveness. It checks integrity and consistency of data." }, { "code": null, "e": 476, "s": 316, "text": "Database testing usually consists of a layered process that includes the User Interface (UI) layer, the business layer, the data access layer and the database." }, { "code": null, "e": 511, "s": 476, "text": "Objective of the Database Testing:" }, { "code": null, "e": 1346, "s": 511, "text": "Ensure Data Mapping:It checks whether the fields in the user interface or front end forms are mapped consistently with the corresponding fields in the database table.Ensure ACID Properties of Transactions:Every transaction a database performs has to stick to these four properties: Atomicity, Consistency, Isolation and Durability.Ensure Data Integrity:The updated and the most recent values of shared data should appear on all the forms and screens. The value should not be updated on one screen and display an older value on another one. The status should also be updated simultaneously.Ensure the Accuracy of the Business Rules:Complex databases leads to complicated components like relational constraints, triggers and stored procedures. Hence in order testers come up with appropriate SQL queries to validate the complex objects." }, { "code": null, "e": 1513, "s": 1346, "text": "Ensure Data Mapping:It checks whether the fields in the user interface or front end forms are mapped consistently with the corresponding fields in the database table." }, { "code": null, "e": 1679, "s": 1513, "text": "Ensure ACID Properties of Transactions:Every transaction a database performs has to stick to these four properties: Atomicity, Consistency, Isolation and Durability." }, { "code": null, "e": 1938, "s": 1679, "text": "Ensure Data Integrity:The updated and the most recent values of shared data should appear on all the forms and screens. The value should not be updated on one screen and display an older value on another one. The status should also be updated simultaneously." }, { "code": null, "e": 2184, "s": 1938, "text": "Ensure the Accuracy of the Business Rules:Complex databases leads to complicated components like relational constraints, triggers and stored procedures. Hence in order testers come up with appropriate SQL queries to validate the complex objects." }, { "code": null, "e": 2213, "s": 2184, "text": "Database Testing Attributes:" }, { "code": null, "e": 2678, "s": 2213, "text": "Transactions:Transactions means the access and retrieve of the data. Hence in order during the transaction processes the ACID properties should be followed.Database Schema:It is the design or the structure about the organization of the data in the database.Triggers:When a certain event occurs in a certain table, a trigger is auto-instructed to be executed.Procedures:It is the collection of the statements or functions governing the transactions in the database." }, { "code": null, "e": 2835, "s": 2678, "text": "Transactions:Transactions means the access and retrieve of the data. Hence in order during the transaction processes the ACID properties should be followed." }, { "code": null, "e": 2937, "s": 2835, "text": "Database Schema:It is the design or the structure about the organization of the data in the database." }, { "code": null, "e": 3039, "s": 2937, "text": "Triggers:When a certain event occurs in a certain table, a trigger is auto-instructed to be executed." }, { "code": null, "e": 3146, "s": 3039, "text": "Procedures:It is the collection of the statements or functions governing the transactions in the database." }, { "code": null, "e": 3172, "s": 3146, "text": "Database Testing Process:" }, { "code": null, "e": 4081, "s": 3172, "text": "Test Environment Setup:Database testing starts with the setting up the testing environment for the testing process to be carried out in order get a good quality testing process.Test Scenario Generation:After setting up the test environment test cases are designed for conducting the test. Test scenario involve the different inputs and different transactions related to database.Execution:Execution is the core phase of the testing process in which the testing is conducted. It is basically related to the execution of the test cases designed for the testing process.Analysis:Once the execution phase is ended then all the process and the output obtained is analyzed. It is checked whether the testing process has been conducted properly or not.Log Defects:Log defects are also known as report submitting. In this last phase tester informs the developer about the defects found in the database of the system." }, { "code": null, "e": 4259, "s": 4081, "text": "Test Environment Setup:Database testing starts with the setting up the testing environment for the testing process to be carried out in order get a good quality testing process." }, { "code": null, "e": 4462, "s": 4259, "text": "Test Scenario Generation:After setting up the test environment test cases are designed for conducting the test. Test scenario involve the different inputs and different transactions related to database." }, { "code": null, "e": 4651, "s": 4462, "text": "Execution:Execution is the core phase of the testing process in which the testing is conducted. It is basically related to the execution of the test cases designed for the testing process." }, { "code": null, "e": 4830, "s": 4651, "text": "Analysis:Once the execution phase is ended then all the process and the output obtained is analyzed. It is checked whether the testing process has been conducted properly or not." }, { "code": null, "e": 4994, "s": 4830, "text": "Log Defects:Log defects are also known as report submitting. In this last phase tester informs the developer about the defects found in the database of the system." }, { "code": null, "e": 5038, "s": 4994, "text": "Misconceptions related to Database Testing:" }, { "code": null, "e": 5088, "s": 5038, "text": "It requires experts to carry out database testing" }, { "code": null, "e": 5131, "s": 5088, "text": "The process of database testing is lengthy" }, { "code": null, "e": 5162, "s": 5131, "text": "It adds extra work bottlenecks" }, { "code": null, "e": 5208, "s": 5162, "text": "It slows down the overall development process" }, { "code": null, "e": 5238, "s": 5208, "text": "It is a highly costly process" }, { "code": null, "e": 5255, "s": 5238, "text": "Software Testing" }, { "code": null, "e": 5276, "s": 5255, "text": "Software Engineering" }, { "code": null, "e": 5374, "s": 5276, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5415, "s": 5374, "text": "Software Engineering | Black box testing" }, { "code": null, "e": 5447, "s": 5415, "text": "Unit Testing | Software Testing" }, { "code": null, "e": 5462, "s": 5447, "text": "System Testing" }, { "code": null, "e": 5514, "s": 5462, "text": "Difference Between Edge Computing and Fog Computing" }, { "code": null, "e": 5557, "s": 5514, "text": "Software Engineering | Integration Testing" }, { "code": null, "e": 5589, "s": 5557, "text": "What is DFD(Data Flow Diagram)?" }, { "code": null, "e": 5647, "s": 5589, "text": "Software Engineering | Calculation of Function Point (FP)" }, { "code": null, "e": 5686, "s": 5647, "text": "Software Development Life Cycle (SDLC)" }, { "code": null, "e": 5729, "s": 5686, "text": "Software Processes in Software Engineering" } ]
Types of Digital Signature Attacks
22 Jun, 2022 Digital Signature is a mathematical technique that verifies the authenticity of the message or document and also provides non-repudiation where the sender cannot deny signing the document. As the digital signature provides authenticity and non-repudiation in order to secure important data, it is very much susceptible to various attacks. Types of Digital Signature Attacks : There are three types of attacks on Digital Signatures: 1. Chosen-message Attack 2. Known-message Attack 3. Key-only Attack Let us consider an example where c is the attacker and A is the victim whose message and signature are under attack. 1. Chosen-message Attack : The chosen attack method is of two types: Generic chosen-method – In this method C tricks A to digitally sign the messages that A does not intend to do and without the knowledge about A’s public key.Direct chosen-method – In this method C has the knowledge about A’s public key and obtains A’s signature on the messages and replaces the original message with the message C wants A to sign with having A’s signature on them unchanged. Generic chosen-method – In this method C tricks A to digitally sign the messages that A does not intend to do and without the knowledge about A’s public key. Direct chosen-method – In this method C has the knowledge about A’s public key and obtains A’s signature on the messages and replaces the original message with the message C wants A to sign with having A’s signature on them unchanged. 2. Known-message Attack : In the known message attack, C has a few previous messages and signatures of A. Now C tries to forge the signature of A on to the documents that A does not intend to sign by using the brute force method by analyzing the previous data to recreate the signature of A. This attack is similar to known-plain text attack in encryption. 3. Key-only Attack : In key-only attack, the public key of A is available to every one and C makes use of this fact and try to recreate the signature of A and digitally sign the documents or messages that A does not intend to do. This would cause a great threat to authentication of the message which is non-repudiated as A cannot deny signing it. sahithya3chow cryptography Computer Networks cryptography Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Differences between TCP and UDP Types of Network Topology RSA Algorithm in Cryptography GSM in Wireless Communication Socket Programming in Python Differences between IPv4 and IPv6 Secure Socket Layer (SSL) Wireless Application Protocol Mobile Internet Protocol (or Mobile IP) Data encryption standard (DES) | Set 1
[ { "code": null, "e": 53, "s": 25, "text": "\n22 Jun, 2022" }, { "code": null, "e": 393, "s": 53, "text": "Digital Signature is a mathematical technique that verifies the authenticity of the message or document and also provides non-repudiation where the sender cannot deny signing the document. As the digital signature provides authenticity and non-repudiation in order to secure important data, it is very much susceptible to various attacks. " }, { "code": null, "e": 431, "s": 393, "text": "Types of Digital Signature Attacks : " }, { "code": null, "e": 487, "s": 431, "text": "There are three types of attacks on Digital Signatures:" }, { "code": null, "e": 556, "s": 487, "text": "1. Chosen-message Attack\n2. Known-message Attack\n3. Key-only Attack " }, { "code": null, "e": 674, "s": 556, "text": "Let us consider an example where c is the attacker and A is the victim whose message and signature are under attack. " }, { "code": null, "e": 702, "s": 674, "text": "1. Chosen-message Attack : " }, { "code": null, "e": 744, "s": 702, "text": "The chosen attack method is of two types:" }, { "code": null, "e": 1136, "s": 744, "text": "Generic chosen-method – In this method C tricks A to digitally sign the messages that A does not intend to do and without the knowledge about A’s public key.Direct chosen-method – In this method C has the knowledge about A’s public key and obtains A’s signature on the messages and replaces the original message with the message C wants A to sign with having A’s signature on them unchanged." }, { "code": null, "e": 1294, "s": 1136, "text": "Generic chosen-method – In this method C tricks A to digitally sign the messages that A does not intend to do and without the knowledge about A’s public key." }, { "code": null, "e": 1529, "s": 1294, "text": "Direct chosen-method – In this method C has the knowledge about A’s public key and obtains A’s signature on the messages and replaces the original message with the message C wants A to sign with having A’s signature on them unchanged." }, { "code": null, "e": 1556, "s": 1529, "text": "2. Known-message Attack : " }, { "code": null, "e": 1888, "s": 1556, "text": "In the known message attack, C has a few previous messages and signatures of A. Now C tries to forge the signature of A on to the documents that A does not intend to sign by using the brute force method by analyzing the previous data to recreate the signature of A. This attack is similar to known-plain text attack in encryption. " }, { "code": null, "e": 1910, "s": 1888, "text": "3. Key-only Attack : " }, { "code": null, "e": 2237, "s": 1910, "text": "In key-only attack, the public key of A is available to every one and C makes use of this fact and try to recreate the signature of A and digitally sign the documents or messages that A does not intend to do. This would cause a great threat to authentication of the message which is non-repudiated as A cannot deny signing it." }, { "code": null, "e": 2251, "s": 2237, "text": "sahithya3chow" }, { "code": null, "e": 2264, "s": 2251, "text": "cryptography" }, { "code": null, "e": 2282, "s": 2264, "text": "Computer Networks" }, { "code": null, "e": 2295, "s": 2282, "text": "cryptography" }, { "code": null, "e": 2313, "s": 2295, "text": "Computer Networks" }, { "code": null, "e": 2411, "s": 2313, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2443, "s": 2411, "text": "Differences between TCP and UDP" }, { "code": null, "e": 2469, "s": 2443, "text": "Types of Network Topology" }, { "code": null, "e": 2499, "s": 2469, "text": "RSA Algorithm in Cryptography" }, { "code": null, "e": 2529, "s": 2499, "text": "GSM in Wireless Communication" }, { "code": null, "e": 2558, "s": 2529, "text": "Socket Programming in Python" }, { "code": null, "e": 2592, "s": 2558, "text": "Differences between IPv4 and IPv6" }, { "code": null, "e": 2618, "s": 2592, "text": "Secure Socket Layer (SSL)" }, { "code": null, "e": 2648, "s": 2618, "text": "Wireless Application Protocol" }, { "code": null, "e": 2688, "s": 2648, "text": "Mobile Internet Protocol (or Mobile IP)" } ]
How to Change Apache HTTP Port in Linux?
19 Feb, 2021 The Apache HTTP server is one of the internet’s most popular web servers today, thanks to its versatility, consistency, and a plethora of features, some of which are actually not available on other web servers, such as Nginx’s competitor. Some of Apache’s most significant features include the ability to load and run various types of modules and special configurations at runtime, without actually stopping the server or, worse, compiling the program whenever most of the new module is installed, and the special role played by .htaccess files that can modify web server configurations specific to webroot directories. By default, the Apache webserver is instructed to listen and bind on port 80.0 for incoming connections. If you opt for a TLS setup, the server listens on port 443 for stable connections. You need to add a new statement containing the new port for future bindings in order to instruct the Apache webserver to connect and listen to web traffic on ports other than normal web ports. The configuration file that needs to be changed on a Debian/Ubuntu-based device is /etc/apache2/ports.conf and update /etc/httpd/conf/httpd.conf on RHEL/CentOS-based distributions. With a console text editor, open a file unique to your own distribution and add a new port comment, as seen in the excerpt below. nano /etc/apache2/ports.conf [On Debian/Ubuntu] Before port 8081 In this example, the Apache HTTP server will be configured to listen to the connections on port 8081. Make sure that you apply the statement below to this file after the directive instructing the webserver to listen on port 80, as seen in the image below. Listen 8081 After port 8081 After you have added the above line, to start the binding method, unique to your own vhost requirements, you need to build or change an Apache virtual host in the Debian/Ubuntu-based distribution. Finally, to implement the changes and connect Apache to a new port, restart the daemon. # systemctl restart apache2 Then use the netstat or ss command to search the local network sockets table. # netstat -tlpn| grep apache OR # ss -tlpn| grep apache You can also open a window and navigate to the IP address or domain name on port 8081 of your computer. The default Apache page in the browser should be shown. If you are unable to access the webpage, however, go back to the server console and make sure that the correct firewall rules are configured to allow port traffic. http://server.ip:8081 Picked Technical Scripter 2020 How To Linux-Unix Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n19 Feb, 2021" }, { "code": null, "e": 648, "s": 28, "text": "The Apache HTTP server is one of the internet’s most popular web servers today, thanks to its versatility, consistency, and a plethora of features, some of which are actually not available on other web servers, such as Nginx’s competitor. Some of Apache’s most significant features include the ability to load and run various types of modules and special configurations at runtime, without actually stopping the server or, worse, compiling the program whenever most of the new module is installed, and the special role played by .htaccess files that can modify web server configurations specific to webroot directories." }, { "code": null, "e": 836, "s": 648, "text": "By default, the Apache webserver is instructed to listen and bind on port 80.0 for incoming connections. If you opt for a TLS setup, the server listens on port 443 for stable connections." }, { "code": null, "e": 1029, "s": 836, "text": "You need to add a new statement containing the new port for future bindings in order to instruct the Apache webserver to connect and listen to web traffic on ports other than normal web ports." }, { "code": null, "e": 1210, "s": 1029, "text": "The configuration file that needs to be changed on a Debian/Ubuntu-based device is /etc/apache2/ports.conf and update /etc/httpd/conf/httpd.conf on RHEL/CentOS-based distributions." }, { "code": null, "e": 1340, "s": 1210, "text": "With a console text editor, open a file unique to your own distribution and add a new port comment, as seen in the excerpt below." }, { "code": null, "e": 1392, "s": 1340, "text": "nano /etc/apache2/ports.conf [On Debian/Ubuntu]" }, { "code": null, "e": 1409, "s": 1392, "text": "Before port 8081" }, { "code": null, "e": 1665, "s": 1409, "text": "In this example, the Apache HTTP server will be configured to listen to the connections on port 8081. Make sure that you apply the statement below to this file after the directive instructing the webserver to listen on port 80, as seen in the image below." }, { "code": null, "e": 1677, "s": 1665, "text": "Listen 8081" }, { "code": null, "e": 1693, "s": 1677, "text": "After port 8081" }, { "code": null, "e": 1890, "s": 1693, "text": "After you have added the above line, to start the binding method, unique to your own vhost requirements, you need to build or change an Apache virtual host in the Debian/Ubuntu-based distribution." }, { "code": null, "e": 1978, "s": 1890, "text": "Finally, to implement the changes and connect Apache to a new port, restart the daemon." }, { "code": null, "e": 2006, "s": 1978, "text": "# systemctl restart apache2" }, { "code": null, "e": 2085, "s": 2006, "text": " Then use the netstat or ss command to search the local network sockets table." }, { "code": null, "e": 2114, "s": 2085, "text": "# netstat -tlpn| grep apache" }, { "code": null, "e": 2117, "s": 2114, "text": "OR" }, { "code": null, "e": 2141, "s": 2117, "text": "# ss -tlpn| grep apache" }, { "code": null, "e": 2465, "s": 2141, "text": "You can also open a window and navigate to the IP address or domain name on port 8081 of your computer. The default Apache page in the browser should be shown. If you are unable to access the webpage, however, go back to the server console and make sure that the correct firewall rules are configured to allow port traffic." }, { "code": null, "e": 2487, "s": 2465, "text": "http://server.ip:8081" }, { "code": null, "e": 2494, "s": 2487, "text": "Picked" }, { "code": null, "e": 2518, "s": 2494, "text": "Technical Scripter 2020" }, { "code": null, "e": 2525, "s": 2518, "text": "How To" }, { "code": null, "e": 2536, "s": 2525, "text": "Linux-Unix" }, { "code": null, "e": 2555, "s": 2536, "text": "Technical Scripter" } ]
Jupyter notebook VS Python IDLE
26 May, 2020 This article will help you if you are confused about which platform to begin coding Python on as Python gives you a variety of options. We have compared two of the options. Jupyter Notebook is basically a web application. Unlike IDEs (Integrated Development Environment), it uses the internet to run. And even after not being able to perform offline, it is highly preferred by most of the beginners because of its rich formatting and user-friendly interface. It allows us to enter the code in the browser and automatically highlights the syntax. It helps us know if we are indenting the code correctly with the help of colors and bold formatting. For example, if we write the print command outside the scope of a loop, it will change the color of the print keyword. Whitespace plays a very important role in Python because Python doesn’t involve the use of braces for enclosing the bodies of loops, methods, etc. A single indentation mistake can lead to an error. The results are displayed in different representations like HTML, PNG, LaTeX, SVG, PDF, etc. Note: For more information, refer to How To Use Jupyter Notebook – An Ultimate Guide Advantages : Rich media representations and text formatting ; No need of separate installation. It comes with Anaconda installation; Highly preferred by data scientists because of its mathematical proficiency (Charting, graphing, complex equations); A notebook created in Jupyter can be accessed (for editing) from any device using a web browser . It comes with a debugger. It automatically saves the changes made to a notebook as we code. Disadvantages: Requires a server and a web browser, i.e., can not work offline like the other IDEs making it difficult to work on for people who don’t have access to a stable internet connection; Its installation takes more time than that taken by other IDEs; We can access it only from localhost by default. It requires us to follow some significant security steps to access it from any other server. Installation : Refer to the below articles for proper guidelines on installation – How to install Jupyter Notebook in Windows? How to install Jupyter Notebook in Linux? Python IDLE is one of the IDEs used for Python programming. It automatically gets downloaded when we install Anaconda. IDLE stands for Integrated Development and Learning Environment. You can access it by opening the command prompt and typing IDLE. It will give the IDLE as the result after opening it a Python shell is opened where you can begin coding. Shell is an interactive interpreter. It provides the output for each line of code immediately. Pressing the enter key not only changes the line but produces the immediate result of the line after which it is pressed. Unlike Jupyter Notebook, IDLE doesn’t allow us to write the complete code first and then compute the results. But if a user wants to check each line of his code as he types it, he will prefer Python IDLE over Jupyter Notebook. So basically, it depends on the user. He may want to complete his code and then run it OR check every line simultaneously while writing the code. But if you are one of those who want a visually attractive application to code on, you must go with Jupyter Notebook. Advantages: very simple and basic; runs without any server or browser; only requires Anaconda installation has an in-built debugger; can be customized according to the user’s preferences; Disadvantages: A file created using Python IDLE cannot be accessed from a device other than the one in which it is created unless being copied into or sent to another device. Changes are not saved automatically as we code. It is not as advanced as its contemporaries. Installation : Refer to the below article for proper guidelines on installation – Download and Install Python 3 Latest Version Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Create a directory in Python
[ { "code": null, "e": 53, "s": 25, "text": "\n26 May, 2020" }, { "code": null, "e": 226, "s": 53, "text": "This article will help you if you are confused about which platform to begin coding Python on as Python gives you a variety of options. We have compared two of the options." }, { "code": null, "e": 1115, "s": 226, "text": "Jupyter Notebook is basically a web application. Unlike IDEs (Integrated Development Environment), it uses the internet to run. And even after not being able to perform offline, it is highly preferred by most of the beginners because of its rich formatting and user-friendly interface. It allows us to enter the code in the browser and automatically highlights the syntax. It helps us know if we are indenting the code correctly with the help of colors and bold formatting. For example, if we write the print command outside the scope of a loop, it will change the color of the print keyword. Whitespace plays a very important role in Python because Python doesn’t involve the use of braces for enclosing the bodies of loops, methods, etc. A single indentation mistake can lead to an error. The results are displayed in different representations like HTML, PNG, LaTeX, SVG, PDF, etc. " }, { "code": null, "e": 1200, "s": 1115, "text": "Note: For more information, refer to How To Use Jupyter Notebook – An Ultimate Guide" }, { "code": null, "e": 1214, "s": 1200, "text": "Advantages : " }, { "code": null, "e": 1263, "s": 1214, "text": "Rich media representations and text formatting ;" }, { "code": null, "e": 1334, "s": 1263, "text": "No need of separate installation. It comes with Anaconda installation;" }, { "code": null, "e": 1451, "s": 1334, "text": "Highly preferred by data scientists because of its mathematical proficiency (Charting, graphing, complex equations);" }, { "code": null, "e": 1549, "s": 1451, "text": "A notebook created in Jupyter can be accessed (for editing) from any device using a web browser ." }, { "code": null, "e": 1575, "s": 1549, "text": "It comes with a debugger." }, { "code": null, "e": 1641, "s": 1575, "text": "It automatically saves the changes made to a notebook as we code." }, { "code": null, "e": 1656, "s": 1641, "text": "Disadvantages:" }, { "code": null, "e": 1837, "s": 1656, "text": "Requires a server and a web browser, i.e., can not work offline like the other IDEs making it difficult to work on for people who don’t have access to a stable internet connection;" }, { "code": null, "e": 1901, "s": 1837, "text": "Its installation takes more time than that taken by other IDEs;" }, { "code": null, "e": 2043, "s": 1901, "text": "We can access it only from localhost by default. It requires us to follow some significant security steps to access it from any other server." }, { "code": null, "e": 2127, "s": 2043, "text": "Installation : Refer to the below articles for proper guidelines on installation – " }, { "code": null, "e": 2171, "s": 2127, "text": "How to install Jupyter Notebook in Windows?" }, { "code": null, "e": 2213, "s": 2171, "text": "How to install Jupyter Notebook in Linux?" }, { "code": null, "e": 2403, "s": 2213, "text": "Python IDLE is one of the IDEs used for Python programming. It automatically gets downloaded when we install Anaconda. IDLE stands for Integrated Development and Learning Environment. " }, { "code": null, "e": 3020, "s": 2403, "text": "You can access it by opening the command prompt and typing IDLE. It will give the IDLE as the result after opening it a Python shell is opened where you can begin coding. Shell is an interactive interpreter. It provides the output for each line of code immediately. Pressing the enter key not only changes the line but produces the immediate result of the line after which it is pressed. Unlike Jupyter Notebook, IDLE doesn’t allow us to write the complete code first and then compute the results. But if a user wants to check each line of his code as he types it, he will prefer Python IDLE over Jupyter Notebook." }, { "code": null, "e": 3286, "s": 3020, "text": " So basically, it depends on the user. He may want to complete his code and then run it OR check every line simultaneously while writing the code. But if you are one of those who want a visually attractive application to code on, you must go with Jupyter Notebook." }, { "code": null, "e": 3298, "s": 3286, "text": "Advantages:" }, { "code": null, "e": 3321, "s": 3298, "text": "very simple and basic;" }, { "code": null, "e": 3357, "s": 3321, "text": "runs without any server or browser;" }, { "code": null, "e": 3393, "s": 3357, "text": "only requires Anaconda installation" }, { "code": null, "e": 3419, "s": 3393, "text": "has an in-built debugger;" }, { "code": null, "e": 3474, "s": 3419, "text": "can be customized according to the user’s preferences;" }, { "code": null, "e": 3489, "s": 3474, "text": "Disadvantages:" }, { "code": null, "e": 3649, "s": 3489, "text": "A file created using Python IDLE cannot be accessed from a device other than the one in which it is created unless being copied into or sent to another device." }, { "code": null, "e": 3697, "s": 3649, "text": "Changes are not saved automatically as we code." }, { "code": null, "e": 3742, "s": 3697, "text": "It is not as advanced as its contemporaries." }, { "code": null, "e": 3825, "s": 3742, "text": "Installation : Refer to the below article for proper guidelines on installation – " }, { "code": null, "e": 3870, "s": 3825, "text": "Download and Install Python 3 Latest Version" }, { "code": null, "e": 3877, "s": 3870, "text": "Python" }, { "code": null, "e": 3975, "s": 3877, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4007, "s": 3975, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 4034, "s": 4007, "text": "Python Classes and Objects" }, { "code": null, "e": 4055, "s": 4034, "text": "Python OOPs Concepts" }, { "code": null, "e": 4078, "s": 4055, "text": "Introduction To PYTHON" }, { "code": null, "e": 4134, "s": 4078, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 4165, "s": 4134, "text": "Python | os.path.join() method" }, { "code": null, "e": 4207, "s": 4165, "text": "Check if element exists in list in Python" }, { "code": null, "e": 4249, "s": 4207, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 4288, "s": 4249, "text": "Python | Get unique values from a list" } ]
Python SQLite – ORDER BY Clause
27 Apr, 2021 In this article, we will discuss ORDER BY clause in SQLite using Python. The ORDER BY statement is a SQL statement that is used to sort the data in either ascending or descending according to one or more columns. By default, ORDER BY sorts the data in ascending order. DESC is used to sort the data in descending order. ASC to sort in ascending order. Syntax: SELECT column1,column2,., column n FROM table_name ORDER BY column_name ASC|DESC; First, let’s create a database. Python3 # importing sqlite moduleimport sqlite3 # create connection to the database # geeks_databaseconnection = sqlite3.connect('geeks_database.db') # create table named address of customers # with 4 columns id,name age and addressconnection.execute('''CREATE TABLE customer_address (ID INT PRIMARY KEY NOT NULL, NAME TEXT NOT NULL, AGE INT NOT NULL, ADDRESS CHAR(50)); ''') # close the connectionconnection.close() Output: Now, Insert 5 records into the customer_address table. Python3 # importing sqlite moduleimport sqlite3 # create connection to the database # geeks_databaseconnection = sqlite3.connect('geeks_database.db') # insert records into tableconnection.execute( "INSERT INTO customer_address VALUES (1, 'nikhil teja', 22, 'hyderabad' )")connection.execute( "INSERT INTO customer_address VALUES (2, 'karthik', 25, 'khammam')")connection.execute( "INSERT INTO customer_address VALUES (3, 'sravan', 22, 'ponnur' )")connection.execute( "INSERT INTO customer_address VALUES (4, 'deepika', 25, 'chebrolu' )")connection.execute( "INSERT INTO customer_address VALUES (5, 'jyothika', 22, 'noida')") # close the connectionconnection.close() Output: After creating the database and adding data to it let’s see the use of order by clause. Example 1: Display all details from the table in ascending order(default) based on address. Python3 # importing sqlite moduleimport sqlite3 # create connection to the database# geeks_databaseconnection = sqlite3.connect('geeks_database.db') # sql query to display all details from # table in ascending order based on address.cursor = connection.execute( "SELECT ADDRESS,ID from customer_address ORDER BY address DESC") # display data row by rowfor i in cursor: print(i) # close the connectionconnection.close() Output: Example 2: Display address and id based on the address in descending order. Python3 # importing sqlite moduleimport sqlite3 # create connection to the database # geeks_databaseconnection = sqlite3.connect('geeks_database.db') # sql query to display address and id# based on address in descending ordercursor = connection.execute( "SELECT ADDRESS,ID from customer_address ORDER BY address DESC") # display data row by rowfor i in cursor: print(i) # close the connectionconnection.close() Output: Example 3: Display name and id based on name in descending order Python3 # importing sqlite moduleimport sqlite3 # create connection to the database # geeks_databaseconnection = sqlite3.connect('geeks_database.db') # sql query to display name and id based# on name in descending ordercursor = connection.execute( "SELECT NAME,ID from customer_address ORDER BY NAME DESC") # display data row by rowfor i in cursor: print(i) # close the connectionconnection.close() Output: Picked Python-SQLite Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n27 Apr, 2021" }, { "code": null, "e": 297, "s": 28, "text": "In this article, we will discuss ORDER BY clause in SQLite using Python. The ORDER BY statement is a SQL statement that is used to sort the data in either ascending or descending according to one or more columns. By default, ORDER BY sorts the data in ascending order." }, { "code": null, "e": 348, "s": 297, "text": "DESC is used to sort the data in descending order." }, { "code": null, "e": 380, "s": 348, "text": "ASC to sort in ascending order." }, { "code": null, "e": 471, "s": 380, "text": "Syntax: SELECT column1,column2,., column n FROM table_name ORDER BY column_name ASC|DESC;" }, { "code": null, "e": 503, "s": 471, "text": "First, let’s create a database." }, { "code": null, "e": 511, "s": 503, "text": "Python3" }, { "code": "# importing sqlite moduleimport sqlite3 # create connection to the database # geeks_databaseconnection = sqlite3.connect('geeks_database.db') # create table named address of customers # with 4 columns id,name age and addressconnection.execute('''CREATE TABLE customer_address (ID INT PRIMARY KEY NOT NULL, NAME TEXT NOT NULL, AGE INT NOT NULL, ADDRESS CHAR(50)); ''') # close the connectionconnection.close()", "e": 994, "s": 511, "text": null }, { "code": null, "e": 1002, "s": 994, "text": "Output:" }, { "code": null, "e": 1057, "s": 1002, "text": "Now, Insert 5 records into the customer_address table." }, { "code": null, "e": 1065, "s": 1057, "text": "Python3" }, { "code": "# importing sqlite moduleimport sqlite3 # create connection to the database # geeks_databaseconnection = sqlite3.connect('geeks_database.db') # insert records into tableconnection.execute( \"INSERT INTO customer_address VALUES (1, 'nikhil teja', 22, 'hyderabad' )\")connection.execute( \"INSERT INTO customer_address VALUES (2, 'karthik', 25, 'khammam')\")connection.execute( \"INSERT INTO customer_address VALUES (3, 'sravan', 22, 'ponnur' )\")connection.execute( \"INSERT INTO customer_address VALUES (4, 'deepika', 25, 'chebrolu' )\")connection.execute( \"INSERT INTO customer_address VALUES (5, 'jyothika', 22, 'noida')\") # close the connectionconnection.close()", "e": 1741, "s": 1065, "text": null }, { "code": null, "e": 1749, "s": 1741, "text": "Output:" }, { "code": null, "e": 1837, "s": 1749, "text": "After creating the database and adding data to it let’s see the use of order by clause." }, { "code": null, "e": 1929, "s": 1837, "text": "Example 1: Display all details from the table in ascending order(default) based on address." }, { "code": null, "e": 1937, "s": 1929, "text": "Python3" }, { "code": "# importing sqlite moduleimport sqlite3 # create connection to the database# geeks_databaseconnection = sqlite3.connect('geeks_database.db') # sql query to display all details from # table in ascending order based on address.cursor = connection.execute( \"SELECT ADDRESS,ID from customer_address ORDER BY address DESC\") # display data row by rowfor i in cursor: print(i) # close the connectionconnection.close()", "e": 2358, "s": 1937, "text": null }, { "code": null, "e": 2366, "s": 2358, "text": "Output:" }, { "code": null, "e": 2442, "s": 2366, "text": "Example 2: Display address and id based on the address in descending order." }, { "code": null, "e": 2450, "s": 2442, "text": "Python3" }, { "code": "# importing sqlite moduleimport sqlite3 # create connection to the database # geeks_databaseconnection = sqlite3.connect('geeks_database.db') # sql query to display address and id# based on address in descending ordercursor = connection.execute( \"SELECT ADDRESS,ID from customer_address ORDER BY address DESC\") # display data row by rowfor i in cursor: print(i) # close the connectionconnection.close()", "e": 2863, "s": 2450, "text": null }, { "code": null, "e": 2871, "s": 2863, "text": "Output:" }, { "code": null, "e": 2936, "s": 2871, "text": "Example 3: Display name and id based on name in descending order" }, { "code": null, "e": 2944, "s": 2936, "text": "Python3" }, { "code": "# importing sqlite moduleimport sqlite3 # create connection to the database # geeks_databaseconnection = sqlite3.connect('geeks_database.db') # sql query to display name and id based# on name in descending ordercursor = connection.execute( \"SELECT NAME,ID from customer_address ORDER BY NAME DESC\") # display data row by rowfor i in cursor: print(i) # close the connectionconnection.close()", "e": 3345, "s": 2944, "text": null }, { "code": null, "e": 3353, "s": 3345, "text": "Output:" }, { "code": null, "e": 3360, "s": 3353, "text": "Picked" }, { "code": null, "e": 3374, "s": 3360, "text": "Python-SQLite" }, { "code": null, "e": 3381, "s": 3374, "text": "Python" } ]
waitpid() - Unix, Linux System Call
Unix - Home Unix - Getting Started Unix - File Management Unix - Directories Unix - File Permission Unix - Environment Unix - Basic Utilities Unix - Pipes & Filters Unix - Processes Unix - Communication Unix - The vi Editor Unix - What is Shell? Unix - Using Variables Unix - Special Variables Unix - Using Arrays Unix - Basic Operators Unix - Decision Making Unix - Shell Loops Unix - Loop Control Unix - Shell Substitutions Unix - Quoting Mechanisms Unix - IO Redirections Unix - Shell Functions Unix - Manpage Help Unix - Regular Expressions Unix - File System Basics Unix - User Administration Unix - System Performance Unix - System Logging Unix - Signals and Traps Unix - Useful Commands Unix - Quick Guide Unix - Builtin Functions Unix - System Calls Unix - Commands List Unix Useful Resources Computer Glossary Who is Who Copyright Β© 2014 by tutorialspoint wait, waitpid - wait for process to change state #include <sys/types.h> #include <sys/wait.h> pid_t wait(int *status); pid_t waitpid(pid_t pid, int *status, int options); int waitid(idtype_t idtype, id_t id, siginfo_t * infop , int options ); pid_t wait(int *status); pid_t waitpid(pid_t pid, int *status, int options); int waitid(idtype_t idtype, id_t id, siginfo_t * infop , int options ); All of these system calls are used to wait for state changes in a child of the calling process, and obtain information about the child whose state has changed. A state change is considered to be: the child terminated; the child was stopped by a signal; or the child was resumed by a signal. In the case of a terminated child, performing a wait allows the system to release the resources associated with the child; if a wait is not performed, then terminated the child remains in a "zombie" state (see NOTES below). If a child has already changed state, then these calls return immediately. Otherwise they block until either a child changes state or a signal handler interrupts the call (assuming that system calls are not automatically restarted using the SA_RESTART flag of sigaction(2)). In the remainder of this page, a child whose state has changed and which has not yet been waited upon by one of these system calls is termed waitable. The wait() system call suspends execution of the current process until one of its children terminates. The call wait(&status) is equivalent to: waitpid(-1, &status, 0); The waitpid() system call suspends execution of the current process until a child specified by pid argument has changed state. By default, waitpid() waits only for terminated children, but this behaviour is modifiable via the options argument, as described below. The value of pid can be: The value of options is an OR of zero or more of the following constants: (For Linux-only options, see below.) The WUNTRACED and WCONTINUED options are only effective if the SA_NOCLDSTOP flag has not been set for the SIGCHLD signal (see sigaction(2)). If status is not NULL, wait() and waitpid() store status information in the int to which it points. This integer can be inspected with the following macros (which take the integer itself as an argument, not a pointer to it, as is done in wait() and waitpid()!): The waitid() system call (available since Linux 2.6.9) provides more precise control over which child state changes to wait for. The idtype and id arguments select the child(ren) to wait for, as follows: If WNOHANG was specified in options and there were no children in a waitable state, then waitid() returns 0 immediately and the state of the siginfo_t structure pointed to by infop is unspecified. To distinguish this case from that where a child was in a waitable state, zero out the si_pid field before the call and check for a non-zero value in this field after the call returns. wait(): on success, returns the process ID of the terminated child; on error, -1 is returned. waitpid(): on success, returns the process ID of the child whose state has changed; on error, -1 is returned; if WNOHANG was specified and no child(ren) specified by pid has yet changed state, then 0 is returned. waitid(): returns 0 on success or if WNOHANG was specified and no child(ren) specified by id has yet changed state; on error, -1 is returned. Each of these calls sets errno to an appropriate value in the case of an error. A child that terminates, but has not been waited for becomes a "zombie". The kernel maintains a minimal set of information about the zombie process (PID, termination status, resource usage information) in order to allow the parent to later perform a wait to obtain information about the child. As long as a zombie is not removed from the system via a wait, it will consume a slot in the kernel process table, and if this table fills, it will not be possible to create further processes. If a parent process terminates, then its "zombie" children (if any) are adopted by init(8), which automatically performs a wait to remove the zombies. POSIX.1-2001 specifies that if the disposition of SIGCHLD is set to SIG_IGN or the SA_NOCLDWAIT flag is set for SIGCHLD (see sigaction(2)), then children that terminate do not become zombies and a call to wait() or waitpid() will block until all children have terminated, and then fail with errno set to ECHILD. (The original POSIX standard left the behaviour of setting SIGCHLD to SIG_IGN unspecified.) Linux 2.6 conforms to this specification. However, Linux 2.4 (and earlier) does not: if a wait() or waitpid() call is made while SIGCHLD is being ignored, the call behaves just as though SIGCHLD were not being ignored, that is, the call blocks until the next child terminates and then returns the process ID and status of that child. In the Linux kernel, a kernel-scheduled thread is not a distinct construct from a process. Instead, a thread is simply a process that is created using the Linux-unique clone(2) system call; other routines such as the portable pthread_create(3) call are implemented using clone(2). Before Linux 2.4, a thread was just a special case of a process, and as a consequence one thread could not wait on the children of another thread, even when the latter belongs to the same thread group. However, POSIX prescribes such functionality, and since Linux 2.4 a thread can, and by default will, wait on children of other threads in the same thread group. The following Linux-specific options are for use with children created using clone(2); they cannot be used with waitid(): The following program demonstrates the use of fork(2) and waitpid(2). The program creates a child process. If no command-line argument is supplied to the program, then the child suspends its execution using pause(2), to allow the user to send signals to the child. Otherwise, if a command-line argument is supplied, then the child exits immediately, using the integer supplied on the command line as the exit status. The parent process executes a loop that monitors the child using waitpid(2), and uses the W*() macros described above to analyse the wait status value. The following shell session demonstrates the use of the program: $ ./a.out & Child PID is 32360 [1] 32359 $ kill -STOP 32360 stopped by signal 19 $ kill -CONT 32360 continued $ kill -TERM 32360 killed by signal 15 [1]+ Done ./a.out $ #include <sys/wait.h> #include <stdlib.h> #include <unistd.h> #include <stdio.h> int main(int argc, char *argv[]) { pid_t cpid, w; int status; cpid = fork(); if (cpid == -1) { perror("fork"); exit(EXIT_FAILURE); } if (cpid == 0) { /* Code executed by child */ printf("Child PID is %ld\n", (long) getpid()); if (argc == 1) pause(); /* Wait for signals */ _exit(atoi(argv[1])); } else { /* Code executed by parent */ do { w = waitpid(cpid, &status, WUNTRACED | WCONTINUED); if (w == -1) { perror("waitpid"); exit(EXIT_FAILURE); } if (WIFEXITED(status)) { printf("exited, status=%d\n", WEXITSTATUS(status)); } else if (WIFSIGNALED(status)) { printf("killed by signal %d\n", WTERMSIG(status)); } else if (WIFSTOPPED(status)) { printf("stopped by signal %d\n", WSTOPSIG(status)); } else if (WIFCONTINUED(status)) { printf("continued\n"); } } while (!WIFEXITED(status) && !WIFSIGNALED(status)); exit(EXIT_SUCCESS); } } $ ./a.out & Child PID is 32360 [1] 32359 $ kill -STOP 32360 stopped by signal 19 $ kill -CONT 32360 continued $ kill -TERM 32360 killed by signal 15 [1]+ Done ./a.out $ #include <sys/wait.h> #include <stdlib.h> #include <unistd.h> #include <stdio.h> int main(int argc, char *argv[]) { pid_t cpid, w; int status; cpid = fork(); if (cpid == -1) { perror("fork"); exit(EXIT_FAILURE); } if (cpid == 0) { /* Code executed by child */ printf("Child PID is %ld\n", (long) getpid()); if (argc == 1) pause(); /* Wait for signals */ _exit(atoi(argv[1])); } else { /* Code executed by parent */ do { w = waitpid(cpid, &status, WUNTRACED | WCONTINUED); if (w == -1) { perror("waitpid"); exit(EXIT_FAILURE); } if (WIFEXITED(status)) { printf("exited, status=%d\n", WEXITSTATUS(status)); } else if (WIFSIGNALED(status)) { printf("killed by signal %d\n", WTERMSIG(status)); } else if (WIFSTOPPED(status)) { printf("stopped by signal %d\n", WSTOPSIG(status)); } else if (WIFCONTINUED(status)) { printf("continued\n"); } } while (!WIFEXITED(status) && !WIFSIGNALED(status)); exit(EXIT_SUCCESS); } } SVr4, 4.3BSD, POSIX.1-2001.
[ { "code": null, "e": 1600, "s": 1588, "text": "Unix - Home" }, { "code": null, "e": 1623, "s": 1600, "text": "Unix - Getting Started" }, { "code": null, "e": 1646, "s": 1623, "text": "Unix - File Management" }, { "code": null, "e": 1665, "s": 1646, "text": "Unix - Directories" }, { "code": null, "e": 1688, "s": 1665, "text": "Unix - File Permission" }, { "code": null, "e": 1707, "s": 1688, "text": "Unix - Environment" }, { "code": null, "e": 1730, "s": 1707, "text": "Unix - Basic Utilities" }, { "code": null, "e": 1753, "s": 1730, "text": "Unix - Pipes & Filters" }, { "code": null, "e": 1770, "s": 1753, "text": "Unix - Processes" }, { "code": null, "e": 1791, "s": 1770, "text": "Unix - Communication" }, { "code": null, "e": 1812, "s": 1791, "text": "Unix - The vi Editor" }, { "code": null, "e": 1834, "s": 1812, "text": "Unix - What is Shell?" }, { "code": null, "e": 1857, "s": 1834, "text": "Unix - Using Variables" }, { "code": null, "e": 1882, "s": 1857, "text": "Unix - Special Variables" }, { "code": null, "e": 1902, "s": 1882, "text": "Unix - Using Arrays" }, { "code": null, "e": 1925, "s": 1902, "text": "Unix - Basic Operators" }, { "code": null, "e": 1948, "s": 1925, "text": "Unix - Decision Making" }, { "code": null, "e": 1967, "s": 1948, "text": "Unix - Shell Loops" }, { "code": null, "e": 1987, "s": 1967, "text": "Unix - Loop Control" }, { "code": null, "e": 2014, "s": 1987, "text": "Unix - Shell Substitutions" }, { "code": null, "e": 2040, "s": 2014, "text": "Unix - Quoting Mechanisms" }, { "code": null, "e": 2063, "s": 2040, "text": "Unix - IO Redirections" }, { "code": null, "e": 2086, "s": 2063, "text": "Unix - Shell Functions" }, { "code": null, "e": 2106, "s": 2086, "text": "Unix - Manpage Help" }, { "code": null, "e": 2133, "s": 2106, "text": "Unix - Regular Expressions" }, { "code": null, "e": 2159, "s": 2133, "text": "Unix - File System Basics" }, { "code": null, "e": 2186, "s": 2159, "text": "Unix - User Administration" }, { "code": null, "e": 2212, "s": 2186, "text": "Unix - System Performance" }, { "code": null, "e": 2234, "s": 2212, "text": "Unix - System Logging" }, { "code": null, "e": 2259, "s": 2234, "text": "Unix - Signals and Traps" }, { "code": null, "e": 2282, "s": 2259, "text": "Unix - Useful Commands" }, { "code": null, "e": 2301, "s": 2282, "text": "Unix - Quick Guide" }, { "code": null, "e": 2326, "s": 2301, "text": "Unix - Builtin Functions" }, { "code": null, "e": 2346, "s": 2326, "text": "Unix - System Calls" }, { "code": null, "e": 2367, "s": 2346, "text": "Unix - Commands List" }, { "code": null, "e": 2389, "s": 2367, "text": "Unix Useful Resources" }, { "code": null, "e": 2407, "s": 2389, "text": "Computer Glossary" }, { "code": null, "e": 2418, "s": 2407, "text": "Who is Who" }, { "code": null, "e": 2453, "s": 2418, "text": "Copyright Β© 2014 by tutorialspoint" }, { "code": null, "e": 2502, "s": 2453, "text": "wait, waitpid - wait for process to change state" }, { "code": null, "e": 2702, "s": 2502, "text": "#include <sys/types.h> \n#include <sys/wait.h> \n\npid_t wait(int *status); \npid_t waitpid(pid_t pid, int *status, int options); \nint waitid(idtype_t idtype, id_t id, siginfo_t * infop , int options );\n" }, { "code": null, "e": 2855, "s": 2702, "text": "\npid_t wait(int *status); \npid_t waitpid(pid_t pid, int *status, int options); \nint waitid(idtype_t idtype, id_t id, siginfo_t * infop , int options );\n" }, { "code": null, "e": 3370, "s": 2855, "text": "All of these system calls are used to wait for state changes\nin a child of the calling process, and obtain information\nabout the child whose state has changed.\nA state change is considered to be: the child terminated;\nthe child was stopped by a signal; or the child was resumed by a signal.\nIn the case of a terminated child, performing a wait allows\nthe system to release the resources associated with the child;\nif a wait is not performed, then terminated the child remains in\na \"zombie\" state (see NOTES below)." }, { "code": null, "e": 3796, "s": 3370, "text": "If a child has already changed state, then these calls return immediately.\nOtherwise they block until either a child changes state or\na signal handler interrupts the call (assuming that system calls\nare not automatically restarted using the SA_RESTART flag of\nsigaction(2)). In the remainder of this page, a child whose state has changed\nand which has not yet been waited upon by one of these system\ncalls is termed\nwaitable." }, { "code": null, "e": 3940, "s": 3796, "text": "The wait() system call suspends execution of the current process until one of its children terminates.\nThe call wait(&status) is equivalent to:" }, { "code": null, "e": 3970, "s": 3940, "text": " waitpid(-1, &status, 0);\n" }, { "code": null, "e": 4234, "s": 3970, "text": "The waitpid() system call suspends execution of the current process until a\nchild specified by pid argument has changed state.\nBy default,\nwaitpid() waits only for terminated children, but this behaviour is modifiable\nvia the\noptions argument, as described below." }, { "code": null, "e": 4260, "s": 4234, "text": "The value of pid can be:" }, { "code": null, "e": 4334, "s": 4260, "text": "The value of options is an OR of zero or more of the following constants:" }, { "code": null, "e": 4512, "s": 4334, "text": "(For Linux-only options, see below.) The\nWUNTRACED and WCONTINUED options are only effective if the\nSA_NOCLDSTOP flag has not been set for the\nSIGCHLD signal (see sigaction(2))." }, { "code": null, "e": 4775, "s": 4512, "text": "If status is not NULL, wait() and waitpid() store status information in the int to which it points.\nThis integer can be inspected with the following macros (which\ntake the integer itself as an argument, not a pointer to it, as is done in wait() and waitpid()!): " }, { "code": null, "e": 4904, "s": 4775, "text": "The waitid() system call (available since Linux 2.6.9) provides more precise\ncontrol over which child state changes to wait for." }, { "code": null, "e": 4979, "s": 4904, "text": "The\nidtype and\nid arguments select the child(ren) to wait for, as follows:" }, { "code": null, "e": 5361, "s": 4979, "text": "If WNOHANG was specified in\noptions and there were no children in a waitable state, then\nwaitid() returns 0 immediately and\nthe state of the\nsiginfo_t structure pointed to by\ninfop is unspecified.\nTo distinguish this case from that where a child was in a\nwaitable state, zero out the\nsi_pid field before the call and check for a non-zero value in this field\nafter the call returns." }, { "code": null, "e": 5455, "s": 5361, "text": "wait(): on success, returns the process ID of the terminated child;\non error, -1 is returned." }, { "code": null, "e": 5668, "s": 5455, "text": "waitpid(): on success, returns the process ID of the child whose state has changed;\non error, -1 is returned; if WNOHANG was specified and no child(ren) specified by pid has yet changed state, then 0 is returned." }, { "code": null, "e": 5810, "s": 5668, "text": "waitid(): returns 0 on success or\nif\nWNOHANG was specified and no child(ren) specified by\nid has yet changed state;\non error, -1 is returned." }, { "code": null, "e": 5890, "s": 5810, "text": "Each of these calls sets\nerrno to an appropriate value in the case of an error." }, { "code": null, "e": 6184, "s": 5890, "text": "A child that terminates, but has not been waited for becomes a \"zombie\".\nThe kernel maintains a minimal set of information about the zombie\nprocess (PID, termination status, resource usage information)\nin order to allow the parent to later perform a wait to obtain\ninformation about the child." }, { "code": null, "e": 6528, "s": 6184, "text": "As long as a zombie is not removed from the system via a wait,\nit will consume a slot in the kernel process table, and if\nthis table fills, it will not be possible to create further processes.\nIf a parent process terminates, then its \"zombie\" children (if any)\nare adopted by init(8),\nwhich automatically performs a wait to remove the zombies." }, { "code": null, "e": 7266, "s": 6528, "text": "POSIX.1-2001 specifies that if the disposition of\nSIGCHLD is set to\nSIG_IGN or the\nSA_NOCLDWAIT flag is set for\nSIGCHLD (see\nsigaction(2)),\nthen children that terminate do not become zombies and a call to\nwait() or\nwaitpid() will block until all children have terminated, and then fail with\nerrno set to\nECHILD. (The original POSIX standard left the behaviour of setting\nSIGCHLD to\nSIG_IGN unspecified.)\nLinux 2.6 conforms to this specification.\nHowever, Linux 2.4 (and earlier) does not: if a\nwait() or\nwaitpid() call is made while\nSIGCHLD is being ignored, the call behaves just as though\nSIGCHLD were not being ignored, that is, the call blocks until the next child\nterminates and then returns the process ID and status of that child." }, { "code": null, "e": 7547, "s": 7266, "text": "In the Linux kernel, a kernel-scheduled thread is not a distinct\nconstruct from a process. Instead, a thread is simply a process\nthat is created using the Linux-unique\nclone(2)\nsystem call; other routines such as the portable\npthread_create(3)\ncall are implemented using\nclone(2)." }, { "code": null, "e": 7911, "s": 7547, "text": "\nBefore Linux 2.4, a thread was just a special case of a process,\nand as a consequence one thread could not wait on the children\nof another thread, even when the latter belongs to the same thread group.\nHowever, POSIX prescribes such functionality, and since Linux 2.4\na thread can, and by default will, wait on children of other threads\nin the same thread group." }, { "code": null, "e": 8033, "s": 7911, "text": "The following Linux-specific\noptions are for use with children created using\nclone(2);\nthey cannot be used with\nwaitid():" }, { "code": null, "e": 8603, "s": 8033, "text": "The following program demonstrates the use of fork(2) \nand\nwaitpid(2).\nThe program creates a child process.\nIf no command-line argument is supplied to the program,\nthen the child suspends its execution using\npause(2),\nto allow the user to send signals to the child.\nOtherwise, if a command-line argument is supplied,\nthen the child exits immediately,\nusing the integer supplied on the command line as the exit status.\nThe parent process executes a loop that monitors the child using\nwaitpid(2),\nand uses the W*() macros described above to analyse the wait status value." }, { "code": null, "e": 8668, "s": 8603, "text": "The following shell session demonstrates the use of the program:" }, { "code": null, "e": 10064, "s": 8668, "text": "\n$ ./a.out &\nChild PID is 32360\n[1] 32359\n$ kill -STOP 32360\nstopped by signal 19\n$ kill -CONT 32360\ncontinued\n$ kill -TERM 32360\nkilled by signal 15\n[1]+ Done ./a.out\n$\n\n\n#include <sys/wait.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <stdio.h>\n\nint\nmain(int argc, char *argv[])\n{\n pid_t cpid, w;\n int status;\n\n cpid = fork();\n if (cpid == -1) { perror(\"fork\"); exit(EXIT_FAILURE); }\n\n if (cpid == 0) { /* Code executed by child */\n printf(\"Child PID is %ld\\n\", (long) getpid());\n if (argc == 1)\n pause(); /* Wait for signals */\n _exit(atoi(argv[1]));\n\n } else { /* Code executed by parent */\n do {\n w = waitpid(cpid, &status, WUNTRACED | WCONTINUED);\n if (w == -1) { perror(\"waitpid\"); exit(EXIT_FAILURE); }\n\n if (WIFEXITED(status)) {\n printf(\"exited, status=%d\\n\", WEXITSTATUS(status));\n } else if (WIFSIGNALED(status)) {\n printf(\"killed by signal %d\\n\", WTERMSIG(status));\n } else if (WIFSTOPPED(status)) {\n printf(\"stopped by signal %d\\n\", WSTOPSIG(status));\n } else if (WIFCONTINUED(status)) {\n printf(\"continued\\n\");\n }\n } while (!WIFEXITED(status) && !WIFSIGNALED(status));\n exit(EXIT_SUCCESS);\n }\n}\n" }, { "code": null, "e": 10255, "s": 10064, "text": "\n$ ./a.out &\nChild PID is 32360\n[1] 32359\n$ kill -STOP 32360\nstopped by signal 19\n$ kill -CONT 32360\ncontinued\n$ kill -TERM 32360\nkilled by signal 15\n[1]+ Done ./a.out\n$\n" }, { "code": null, "e": 10340, "s": 10257, "text": "\n#include <sys/wait.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <stdio.h>\n" }, { "code": null, "e": 10412, "s": 10340, "text": "\nint\nmain(int argc, char *argv[])\n{\n pid_t cpid, w;\n int status;\n" }, { "code": null, "e": 10493, "s": 10412, "text": "\n cpid = fork();\n if (cpid == -1) { perror(\"fork\"); exit(EXIT_FAILURE); }\n" }, { "code": null, "e": 10727, "s": 10493, "text": "\n if (cpid == 0) { /* Code executed by child */\n printf(\"Child PID is %ld\\n\", (long) getpid());\n if (argc == 1)\n pause(); /* Wait for signals */\n _exit(atoi(argv[1]));\n" }, { "code": null, "e": 10936, "s": 10727, "text": "\n } else { /* Code executed by parent */\n do {\n w = waitpid(cpid, &status, WUNTRACED | WCONTINUED);\n if (w == -1) { perror(\"waitpid\"); exit(EXIT_FAILURE); }\n" }, { "code": null, "e": 11467, "s": 10936, "text": "\n if (WIFEXITED(status)) {\n printf(\"exited, status=%d\\n\", WEXITSTATUS(status));\n } else if (WIFSIGNALED(status)) {\n printf(\"killed by signal %d\\n\", WTERMSIG(status));\n } else if (WIFSTOPPED(status)) {\n printf(\"stopped by signal %d\\n\", WSTOPSIG(status));\n } else if (WIFCONTINUED(status)) {\n printf(\"continued\\n\");\n }\n } while (!WIFEXITED(status) && !WIFSIGNALED(status));\n exit(EXIT_SUCCESS);\n }\n}\n" } ]
Python | Pandas dataframe.mode()
24 Nov, 2018 Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas dataframe.mode() function gets the mode(s) of each element along the axis selected. Adds a row for each mode per label, fills in gaps with nan. Note that there could be multiple values returned for the selected axis (when more than one item share the maximum frequency), which is the reason why a dataframe is returned. Syntax: DataFrame.mode(axis=0, numeric_only=False)Parameters :axis : get mode of each column1, get mode of each rownumeric_only : if True, only apply to numeric columns Returns : modes : DataFrame (sorted) Example #1: Use mode() function to find the mode over the index axis. # importing pandas as pdimport pandas as pd # Creating the dataframe df=pd.DataFrame({"A":[14,4,5,4,1], "B":[5,2,54,3,2], "C":[20,20,7,3,8], "D":[14,3,6,2,6]}) # Print the dataframedf Lets use the dataframe.mode() function to find the mode of dataframe # find mode of dataframe df.mode() Output : Example #2: Use mode() function to find the mode over the column axis # importing pandas as pdimport pandas as pd # Creating the dataframe df=pd.DataFrame({"A":[14,4,5,4,1], "B":[5,2,54,3,2], "C":[20,20,7,3,8], "D":[14,3,6,2,6]}) # Print the dataframedf Lets use the dataframe.mode() function to find the mode # axis = 1 indicates over the column axisdf.mode(axis = 1) Output : In the 0th and 3rd row, 14 and 3 is the mode, as they have the maximum occurrence (i.e. 2). In rest of the column all element are mode because they have the same frequency of occurrence. Python pandas-dataFrame Python pandas-dataFrame-methods Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Introduction To PYTHON
[ { "code": null, "e": 53, "s": 25, "text": "\n24 Nov, 2018" }, { "code": null, "e": 267, "s": 53, "text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier." }, { "code": null, "e": 594, "s": 267, "text": "Pandas dataframe.mode() function gets the mode(s) of each element along the axis selected. Adds a row for each mode per label, fills in gaps with nan. Note that there could be multiple values returned for the selected axis (when more than one item share the maximum frequency), which is the reason why a dataframe is returned." }, { "code": null, "e": 763, "s": 594, "text": "Syntax: DataFrame.mode(axis=0, numeric_only=False)Parameters :axis : get mode of each column1, get mode of each rownumeric_only : if True, only apply to numeric columns" }, { "code": null, "e": 800, "s": 763, "text": "Returns : modes : DataFrame (sorted)" }, { "code": null, "e": 870, "s": 800, "text": "Example #1: Use mode() function to find the mode over the index axis." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the dataframe df=pd.DataFrame({\"A\":[14,4,5,4,1], \"B\":[5,2,54,3,2], \"C\":[20,20,7,3,8], \"D\":[14,3,6,2,6]}) # Print the dataframedf", "e": 1104, "s": 870, "text": null }, { "code": null, "e": 1173, "s": 1104, "text": "Lets use the dataframe.mode() function to find the mode of dataframe" }, { "code": "# find mode of dataframe df.mode()", "e": 1208, "s": 1173, "text": null }, { "code": null, "e": 1217, "s": 1208, "text": "Output :" }, { "code": null, "e": 1288, "s": 1217, "text": " Example #2: Use mode() function to find the mode over the column axis" }, { "code": "# importing pandas as pdimport pandas as pd # Creating the dataframe df=pd.DataFrame({\"A\":[14,4,5,4,1], \"B\":[5,2,54,3,2], \"C\":[20,20,7,3,8], \"D\":[14,3,6,2,6]}) # Print the dataframedf", "e": 1522, "s": 1288, "text": null }, { "code": null, "e": 1578, "s": 1522, "text": "Lets use the dataframe.mode() function to find the mode" }, { "code": "# axis = 1 indicates over the column axisdf.mode(axis = 1)", "e": 1637, "s": 1578, "text": null }, { "code": null, "e": 1646, "s": 1637, "text": "Output :" }, { "code": null, "e": 1833, "s": 1646, "text": "In the 0th and 3rd row, 14 and 3 is the mode, as they have the maximum occurrence (i.e. 2). In rest of the column all element are mode because they have the same frequency of occurrence." }, { "code": null, "e": 1857, "s": 1833, "text": "Python pandas-dataFrame" }, { "code": null, "e": 1889, "s": 1857, "text": "Python pandas-dataFrame-methods" }, { "code": null, "e": 1903, "s": 1889, "text": "Python-pandas" }, { "code": null, "e": 1910, "s": 1903, "text": "Python" }, { "code": null, "e": 2008, "s": 1910, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2026, "s": 2008, "text": "Python Dictionary" }, { "code": null, "e": 2068, "s": 2026, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2090, "s": 2068, "text": "Enumerate() in Python" }, { "code": null, "e": 2125, "s": 2090, "text": "Read a file line by line in Python" }, { "code": null, "e": 2151, "s": 2125, "text": "Python String | replace()" }, { "code": null, "e": 2183, "s": 2151, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2212, "s": 2183, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2239, "s": 2212, "text": "Python Classes and Objects" }, { "code": null, "e": 2260, "s": 2239, "text": "Python OOPs Concepts" } ]
Working with Images in Python using Matplotlib
10 May, 2020 Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. The image module in matplotlib library is used for working with images in Python. The image module also includes two useful methods which are imread which is used to read images and imshow which is used to display the image. Below are some examples which illustrate various operations on images using matplotlib library: Example 1: In this example, the program reads an image using the matplotlib.image.imread() and displays that image using matplotlib.image.imread(). # importing required librariesimport matplotlib.pyplot as pltimport matplotlib.image as img # reading the imagetestImage = img.imread('g4g.png') # displaying the imageplt.imshow(testImage) Output: Example 2: The below program reads an image and then represents the image in array. # importing required librariesimport matplotlib.pyplot as pltimport matplotlib.image as img # reading the imagetestImage = img.imread('g4g.png') # displaying the image as an arrayprint(testImage) Output: [[[0.05490196 0.6156863 0.34117648] [0.05490196 0.6156863 0.34117648] [0.05490196 0.6156863 0.34117648] ... [0.05490196 0.6156863 0.34117648] [0.05490196 0.6156863 0.34117648] [0.05490196 0.6156863 0.34117648]] [[0.05490196 0.6156863 0.34117648] [0.05490196 0.6156863 0.34117648] [0.05490196 0.6156863 0.34117648] ... [0.05490196 0.6156863 0.34117648] [0.05490196 0.6156863 0.34117648] [0.05490196 0.6156863 0.34117648]] [[0.05490196 0.6156863 0.34117648] [0.05490196 0.6156863 0.34117648] [0.05490196 0.6156863 0.34117648] ... [0.05490196 0.6156863 0.34117648] [0.05490196 0.6156863 0.34117648] [0.05490196 0.6156863 0.34117648]] ... [[0.03529412 0.52156866 0.28235295] [0.03529412 0.52156866 0.28235295] [0.03529412 0.52156866 0.28235295] ... [0.05490196 0.6156863 0.34117648] [0.05490196 0.6156863 0.34117648] [0.05490196 0.6156863 0.34117648]] [[0.03529412 0.52156866 0.28235295] [0.03529412 0.52156866 0.28235295] [0.03529412 0.52156866 0.28235295] ... [0.05490196 0.6156863 0.34117648] [0.05490196 0.6156863 0.34117648] [0.05490196 0.6156863 0.34117648]] [[0.03529412 0.52156866 0.28235295] [0.03529412 0.52156866 0.28235295] [0.03529412 0.52156866 0.28235295] ... [0.05490196 0.6156863 0.34117648] [0.05490196 0.6156863 0.34117648] [0.05490196 0.6156863 0.34117648]]] Example 3: Here, the shape of the image is (225, 225, 3) which represents (height, width, mode) of the image, for colored image mode value is from 0 to 2 and for black and white image mode value is 0 and 1 only. In the output image, only the mode of the image is modified. # importing required librariesimport matplotlib.pyplot as pltimport matplotlib.image as img # reading the imagetestImage = img.imread('g4g.png') # displaying the shape of the imageprint(testImage.shape) # modifying the shape of the imagemodifiedImage = testImage[:, :, 0] # displaying the modified imageplt.imshow(modifiedImage) Output: (225, 225, 3) Example 4: In the below program, all the parameters of the shape of the image are modified. Here the height of the image is 150 pixels (displaying from the 50th pixel), width is 100 pixels (displaying from the 100th pixel) and mode value is 1. # importing required librariesimport matplotlib.pyplot as pltimport matplotlib.image as img # reading the imagetestImage = img.imread('g4g.png') # displaying the shape of the imageprint(testImage.shape) # modifying the shape of the imagemodifiedImage = testImage[50:200, 100:200, 1] # displaying the modified imageplt.imshow(modifiedImage) Output: (225, 225, 3) Example 5: Here, none of the parameters are modified. So, the original image is displayed. # importing required librariesimport matplotlib.pyplot as pltimport matplotlib.image as img # reading the imagetestImage = img.imread('g4g.png') # displaying the shape of the imageprint(testImage.shape) # modifying the shape of the imagemodifiedImage = testImage[:, :, :] # displaying the modified imageplt.imshow(modifiedImage) Output: (225, 225, 3) Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read JSON file using Python Python map() function Adding new column to existing DataFrame in Pandas Python Dictionary How to get column names in Pandas dataframe Different ways to create Pandas Dataframe Taking input in Python Enumerate() in Python Read a file line by line in Python Python String | replace()
[ { "code": null, "e": 28, "s": 0, "text": "\n10 May, 2020" }, { "code": null, "e": 240, "s": 28, "text": "Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack." }, { "code": null, "e": 465, "s": 240, "text": "The image module in matplotlib library is used for working with images in Python. The image module also includes two useful methods which are imread which is used to read images and imshow which is used to display the image." }, { "code": null, "e": 561, "s": 465, "text": "Below are some examples which illustrate various operations on images using matplotlib library:" }, { "code": null, "e": 709, "s": 561, "text": "Example 1: In this example, the program reads an image using the matplotlib.image.imread() and displays that image using matplotlib.image.imread()." }, { "code": "# importing required librariesimport matplotlib.pyplot as pltimport matplotlib.image as img # reading the imagetestImage = img.imread('g4g.png') # displaying the imageplt.imshow(testImage)", "e": 900, "s": 709, "text": null }, { "code": null, "e": 908, "s": 900, "text": "Output:" }, { "code": null, "e": 992, "s": 908, "text": "Example 2: The below program reads an image and then represents the image in array." }, { "code": "# importing required librariesimport matplotlib.pyplot as pltimport matplotlib.image as img # reading the imagetestImage = img.imread('g4g.png') # displaying the image as an arrayprint(testImage)", "e": 1190, "s": 992, "text": null }, { "code": null, "e": 1198, "s": 1190, "text": "Output:" }, { "code": null, "e": 2585, "s": 1198, "text": "[[[0.05490196 0.6156863 0.34117648]\n [0.05490196 0.6156863 0.34117648]\n [0.05490196 0.6156863 0.34117648]\n ...\n [0.05490196 0.6156863 0.34117648]\n [0.05490196 0.6156863 0.34117648]\n [0.05490196 0.6156863 0.34117648]]\n\n [[0.05490196 0.6156863 0.34117648]\n [0.05490196 0.6156863 0.34117648]\n [0.05490196 0.6156863 0.34117648]\n ...\n [0.05490196 0.6156863 0.34117648]\n [0.05490196 0.6156863 0.34117648]\n [0.05490196 0.6156863 0.34117648]]\n\n [[0.05490196 0.6156863 0.34117648]\n [0.05490196 0.6156863 0.34117648]\n [0.05490196 0.6156863 0.34117648]\n ...\n [0.05490196 0.6156863 0.34117648]\n [0.05490196 0.6156863 0.34117648]\n [0.05490196 0.6156863 0.34117648]]\n\n ...\n\n [[0.03529412 0.52156866 0.28235295]\n [0.03529412 0.52156866 0.28235295]\n [0.03529412 0.52156866 0.28235295]\n ...\n [0.05490196 0.6156863 0.34117648]\n [0.05490196 0.6156863 0.34117648]\n [0.05490196 0.6156863 0.34117648]]\n\n [[0.03529412 0.52156866 0.28235295]\n [0.03529412 0.52156866 0.28235295]\n [0.03529412 0.52156866 0.28235295]\n ...\n [0.05490196 0.6156863 0.34117648]\n [0.05490196 0.6156863 0.34117648]\n [0.05490196 0.6156863 0.34117648]]\n\n [[0.03529412 0.52156866 0.28235295]\n [0.03529412 0.52156866 0.28235295]\n [0.03529412 0.52156866 0.28235295]\n ...\n [0.05490196 0.6156863 0.34117648]\n [0.05490196 0.6156863 0.34117648]\n [0.05490196 0.6156863 0.34117648]]]\n" }, { "code": null, "e": 2858, "s": 2585, "text": "Example 3: Here, the shape of the image is (225, 225, 3) which represents (height, width, mode) of the image, for colored image mode value is from 0 to 2 and for black and white image mode value is 0 and 1 only. In the output image, only the mode of the image is modified." }, { "code": "# importing required librariesimport matplotlib.pyplot as pltimport matplotlib.image as img # reading the imagetestImage = img.imread('g4g.png') # displaying the shape of the imageprint(testImage.shape) # modifying the shape of the imagemodifiedImage = testImage[:, :, 0] # displaying the modified imageplt.imshow(modifiedImage)", "e": 3191, "s": 2858, "text": null }, { "code": null, "e": 3199, "s": 3191, "text": "Output:" }, { "code": null, "e": 3213, "s": 3199, "text": "(225, 225, 3)" }, { "code": null, "e": 3457, "s": 3213, "text": "Example 4: In the below program, all the parameters of the shape of the image are modified. Here the height of the image is 150 pixels (displaying from the 50th pixel), width is 100 pixels (displaying from the 100th pixel) and mode value is 1." }, { "code": "# importing required librariesimport matplotlib.pyplot as pltimport matplotlib.image as img # reading the imagetestImage = img.imread('g4g.png') # displaying the shape of the imageprint(testImage.shape) # modifying the shape of the imagemodifiedImage = testImage[50:200, 100:200, 1] # displaying the modified imageplt.imshow(modifiedImage)", "e": 3801, "s": 3457, "text": null }, { "code": null, "e": 3809, "s": 3801, "text": "Output:" }, { "code": null, "e": 3823, "s": 3809, "text": "(225, 225, 3)" }, { "code": null, "e": 3914, "s": 3823, "text": "Example 5: Here, none of the parameters are modified. So, the original image is displayed." }, { "code": "# importing required librariesimport matplotlib.pyplot as pltimport matplotlib.image as img # reading the imagetestImage = img.imread('g4g.png') # displaying the shape of the imageprint(testImage.shape) # modifying the shape of the imagemodifiedImage = testImage[:, :, :] # displaying the modified imageplt.imshow(modifiedImage)", "e": 4247, "s": 3914, "text": null }, { "code": null, "e": 4255, "s": 4247, "text": "Output:" }, { "code": null, "e": 4269, "s": 4255, "text": "(225, 225, 3)" }, { "code": null, "e": 4287, "s": 4269, "text": "Python-matplotlib" }, { "code": null, "e": 4294, "s": 4287, "text": "Python" }, { "code": null, "e": 4392, "s": 4294, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4420, "s": 4392, "text": "Read JSON file using Python" }, { "code": null, "e": 4442, "s": 4420, "text": "Python map() function" }, { "code": null, "e": 4492, "s": 4442, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 4510, "s": 4492, "text": "Python Dictionary" }, { "code": null, "e": 4554, "s": 4510, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 4596, "s": 4554, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 4619, "s": 4596, "text": "Taking input in Python" }, { "code": null, "e": 4641, "s": 4619, "text": "Enumerate() in Python" }, { "code": null, "e": 4676, "s": 4641, "text": "Read a file line by line in Python" } ]
How to read Excel file and select specific rows and columns in R?
20 May, 2021 In this article, we will discuss how to read an Excel file and select specific rows and columns from it using R Programming Language. File Used: To read an Excel file into R we have to pass its path as an argument to read_excel() function readxl library. Syntax: read_excel(path) To select a specific column we can use indexing. Syntax: df [ row_index , column_index ] Here df represents data frame name or Excel file name or anything For this, we have to pass the index of the row to be extracted as input to the indexing. As a result, the row at the provided index will be fetched and displayed. Example 1 : R library(readxl) setwd('C:/Users/KRISHNA KARTHIKEYA/Documents')df=read_excel('OSWT1.xlsx') a=df[5,]print(a) Output : Example 2 : R library(readxl) setwd('C:/Users/KRISHNA KARTHIKEYA/Documents')df=read_excel('OSWT1.xlsx') a=df[6,]print(a) Output : Example 3 : R library(readxl) setwd('C:/Users/KRISHNA KARTHIKEYA/Documents')df=read_excel('OSWT1.xlsx') a=df[7,]print(a) Output : To get multiple rows similarly not much modification is required. The index of the rows to be extracted should be passed as a vector to the row_index part of indexing syntax. Example 4 : R library("readxl") df=read_excel("C:/users/KRISHNA KARTHIKEYA/Documents/OSWT1.xlsx")print(df[c(2,3),]) Output : This is similar to the approach followed above except that to extract the column index of the column needs to be given as an argument. Example 1 : R library(readxl) setwd('C:/Users/KRISHNA KARTHIKEYA/Documents')df=read_excel('OSWT1.xlsx') a=df[,2]print(a) Output : Example 2: R library(readxl) setwd('C:/Users/KRISHNA KARTHIKEYA/Documents')df=read_excel('OSWT1.xlsx') a=df[,3]print(a) Output : Example 3 : R library(readxl) setwd('C:/Users/KRISHNA KARTHIKEYA/Documents')df=read_excel('OSWT1.xlsx') a=df[,4]print(a) Output : To get multiple columns at once the index of the columns to be extracted should be given as a vector in column_index part of the indexing syntax. All the columns with the index provided will be fetched and displayed. Example 4 : R library("readxl") df=read_excel("C:/users/KRISHNA KARTHIKEYA/Documents/OSWT1.xlsx") print(df[,c(2,3)]) Output : Picked R-Excel R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R How to Split Column Into Multiple Columns in R DataFrame? Group by function in R using Dplyr How to Change Axis Scales in R Plots? How to filter R DataFrame by values in a column? R - if statement Logistic Regression in R Programming Replace Specific Characters in String in R How to import an Excel File into R ? Joining of Dataframes in R Programming
[ { "code": null, "e": 28, "s": 0, "text": "\n20 May, 2021" }, { "code": null, "e": 162, "s": 28, "text": "In this article, we will discuss how to read an Excel file and select specific rows and columns from it using R Programming Language." }, { "code": null, "e": 173, "s": 162, "text": "File Used:" }, { "code": null, "e": 283, "s": 173, "text": "To read an Excel file into R we have to pass its path as an argument to read_excel() function readxl library." }, { "code": null, "e": 291, "s": 283, "text": "Syntax:" }, { "code": null, "e": 308, "s": 291, "text": "read_excel(path)" }, { "code": null, "e": 357, "s": 308, "text": "To select a specific column we can use indexing." }, { "code": null, "e": 365, "s": 357, "text": "Syntax:" }, { "code": null, "e": 397, "s": 365, "text": "df [ row_index , column_index ]" }, { "code": null, "e": 463, "s": 397, "text": "Here df represents data frame name or Excel file name or anything" }, { "code": null, "e": 626, "s": 463, "text": "For this, we have to pass the index of the row to be extracted as input to the indexing. As a result, the row at the provided index will be fetched and displayed." }, { "code": null, "e": 638, "s": 626, "text": "Example 1 :" }, { "code": null, "e": 640, "s": 638, "text": "R" }, { "code": "library(readxl) setwd('C:/Users/KRISHNA KARTHIKEYA/Documents')df=read_excel('OSWT1.xlsx') a=df[5,]print(a)", "e": 749, "s": 640, "text": null }, { "code": null, "e": 758, "s": 749, "text": "Output :" }, { "code": null, "e": 770, "s": 758, "text": "Example 2 :" }, { "code": null, "e": 772, "s": 770, "text": "R" }, { "code": "library(readxl) setwd('C:/Users/KRISHNA KARTHIKEYA/Documents')df=read_excel('OSWT1.xlsx') a=df[6,]print(a)", "e": 881, "s": 772, "text": null }, { "code": null, "e": 890, "s": 881, "text": "Output :" }, { "code": null, "e": 902, "s": 890, "text": "Example 3 :" }, { "code": null, "e": 904, "s": 902, "text": "R" }, { "code": "library(readxl) setwd('C:/Users/KRISHNA KARTHIKEYA/Documents')df=read_excel('OSWT1.xlsx') a=df[7,]print(a)", "e": 1013, "s": 904, "text": null }, { "code": null, "e": 1022, "s": 1013, "text": "Output :" }, { "code": null, "e": 1197, "s": 1022, "text": "To get multiple rows similarly not much modification is required. The index of the rows to be extracted should be passed as a vector to the row_index part of indexing syntax." }, { "code": null, "e": 1210, "s": 1197, "text": "Example 4 : " }, { "code": null, "e": 1212, "s": 1210, "text": "R" }, { "code": "library(\"readxl\") df=read_excel(\"C:/users/KRISHNA KARTHIKEYA/Documents/OSWT1.xlsx\")print(df[c(2,3),])", "e": 1315, "s": 1212, "text": null }, { "code": null, "e": 1324, "s": 1315, "text": "Output :" }, { "code": null, "e": 1459, "s": 1324, "text": "This is similar to the approach followed above except that to extract the column index of the column needs to be given as an argument." }, { "code": null, "e": 1471, "s": 1459, "text": "Example 1 :" }, { "code": null, "e": 1473, "s": 1471, "text": "R" }, { "code": "library(readxl) setwd('C:/Users/KRISHNA KARTHIKEYA/Documents')df=read_excel('OSWT1.xlsx') a=df[,2]print(a)", "e": 1582, "s": 1473, "text": null }, { "code": null, "e": 1591, "s": 1582, "text": "Output :" }, { "code": null, "e": 1602, "s": 1591, "text": "Example 2:" }, { "code": null, "e": 1604, "s": 1602, "text": "R" }, { "code": "library(readxl) setwd('C:/Users/KRISHNA KARTHIKEYA/Documents')df=read_excel('OSWT1.xlsx') a=df[,3]print(a)", "e": 1713, "s": 1604, "text": null }, { "code": null, "e": 1723, "s": 1713, "text": "Output : " }, { "code": null, "e": 1735, "s": 1723, "text": "Example 3 :" }, { "code": null, "e": 1737, "s": 1735, "text": "R" }, { "code": "library(readxl) setwd('C:/Users/KRISHNA KARTHIKEYA/Documents')df=read_excel('OSWT1.xlsx') a=df[,4]print(a)", "e": 1846, "s": 1737, "text": null }, { "code": null, "e": 1855, "s": 1846, "text": "Output :" }, { "code": null, "e": 2072, "s": 1855, "text": "To get multiple columns at once the index of the columns to be extracted should be given as a vector in column_index part of the indexing syntax. All the columns with the index provided will be fetched and displayed." }, { "code": null, "e": 2084, "s": 2072, "text": "Example 4 :" }, { "code": null, "e": 2086, "s": 2084, "text": "R" }, { "code": "library(\"readxl\") df=read_excel(\"C:/users/KRISHNA KARTHIKEYA/Documents/OSWT1.xlsx\") print(df[,c(2,3)])", "e": 2191, "s": 2086, "text": null }, { "code": null, "e": 2201, "s": 2191, "text": "Output : " }, { "code": null, "e": 2208, "s": 2201, "text": "Picked" }, { "code": null, "e": 2216, "s": 2208, "text": "R-Excel" }, { "code": null, "e": 2227, "s": 2216, "text": "R Language" }, { "code": null, "e": 2325, "s": 2227, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2377, "s": 2325, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 2435, "s": 2377, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 2470, "s": 2435, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 2508, "s": 2470, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 2557, "s": 2508, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 2574, "s": 2557, "text": "R - if statement" }, { "code": null, "e": 2611, "s": 2574, "text": "Logistic Regression in R Programming" }, { "code": null, "e": 2654, "s": 2611, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 2691, "s": 2654, "text": "How to import an Excel File into R ?" } ]
What is NgClass in Angular 10 ?
30 Apr, 2021 In this article, we are going to see what is NgClass in Angular 10 and how to use it. NgClass is used to Add or remove CSS classes on an HTML element Syntax: <element [ngClass] = "typescript_property"> Approach: Create the angular app to be used In app.component.html make an element and sets its class using ngclass directive serve the angular app using ng serve to see the output Example 1: app.component.ts import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html'})export class AppComponent { } app.component.html <div [ngClass] ="'gfgclass'"> GeeksforGeeks</div> Output: Angular10 AngularJS 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": "\n30 Apr, 2021" }, { "code": null, "e": 114, "s": 28, "text": "In this article, we are going to see what is NgClass in Angular 10 and how to use it." }, { "code": null, "e": 178, "s": 114, "text": "NgClass is used to Add or remove CSS classes on an HTML element" }, { "code": null, "e": 186, "s": 178, "text": "Syntax:" }, { "code": null, "e": 230, "s": 186, "text": "<element [ngClass] = \"typescript_property\">" }, { "code": null, "e": 241, "s": 230, "text": "Approach: " }, { "code": null, "e": 275, "s": 241, "text": "Create the angular app to be used" }, { "code": null, "e": 356, "s": 275, "text": "In app.component.html make an element and sets its class using ngclass directive" }, { "code": null, "e": 411, "s": 356, "text": "serve the angular app using ng serve to see the output" }, { "code": null, "e": 422, "s": 411, "text": "Example 1:" }, { "code": null, "e": 439, "s": 422, "text": "app.component.ts" }, { "code": "import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html'})export class AppComponent { }", "e": 602, "s": 439, "text": null }, { "code": null, "e": 621, "s": 602, "text": "app.component.html" }, { "code": "<div [ngClass] =\"'gfgclass'\"> GeeksforGeeks</div>", "e": 672, "s": 621, "text": null }, { "code": null, "e": 680, "s": 672, "text": "Output:" }, { "code": null, "e": 690, "s": 680, "text": "Angular10" }, { "code": null, "e": 700, "s": 690, "text": "AngularJS" }, { "code": null, "e": 717, "s": 700, "text": "Web Technologies" } ]
Python | Implementation of Polynomial Regression
22 Feb, 2022 Polynomial Regression is a form of linear regression in which the relationship between the independent variable x and dependent variable y is modeled as an nth degree polynomial. Polynomial regression fits a nonlinear relationship between the value of x and the corresponding conditional mean of y, denoted E(y |x)Why Polynomial Regression: There are some relationships that a researcher will hypothesize is curvilinear. Clearly, such types of cases will include a polynomial term. Inspection of residuals. If we try to fit a linear model to curved data, a scatter plot of residuals (Y-axis) on the predictor (X-axis) will have patches of many positive residuals in the middle. Hence in such a situation, it is not appropriate. An assumption in usual multiple linear regression analysis is that all the independent variables are independent. In polynomial regression model, this assumption is not satisfied. Uses of Polynomial Regression: These are basically used to define or describe non-linear phenomena such as: The growth rate of tissues. Progression of disease epidemics Distribution of carbon isotopes in lake sediments The basic goal of regression analysis is to model the expected value of a dependent variable y in terms of the value of an independent variable x. In simple regression, we used the following equation – y = a + bx + e Here y is a dependent variable, a is the y-intercept, b is the slope and e is the error rate.In many cases, this linear model will not work out For example if we analyzing the production of chemical synthesis in terms of temperature at which the synthesis take place in such cases we use a quadratic model y = a + b1x + b2^2 + e Here y is the dependent variable on x, a is the y-intercept and e is the error rate.In general, we can model it for nth value. y = a + b1x + b2x^2 +....+ bnx^n Since regression function is linear in terms of unknown variables, hence these models are linear from the point of estimation.Hence through the Least Square technique, let’s compute the response value that is y.Polynomial Regression in Python: To get the Dataset used for the analysis of Polynomial Regression, click here.Step 1: Import libraries and dataset Import the important libraries and the dataset we are using to perform Polynomial Regression. Python3 # Importing the librariesimport numpy as npimport matplotlib.pyplot as pltimport pandas as pd # Importing the datasetdatas = pd.read_csv('data.csv')datas Step 2: Dividing the dataset into 2 componentsDivide dataset into two components that is X and y.X will contain the Column between 1 and 2. y will contain the 2 columns. Python3 X = datas.iloc[:, 1:2].valuesy = datas.iloc[:, 2].values Step 3: Fitting Linear Regression to the datasetFitting the linear Regression model On two components. Python3 # Fitting Linear Regression to the datasetfrom sklearn.linear_model import LinearRegressionlin = LinearRegression() lin.fit(X, y) Step 4: Fitting Polynomial Regression to the datasetFitting the Polynomial Regression model on two components X and y. Python3 # Fitting Polynomial Regression to the datasetfrom sklearn.preprocessing import PolynomialFeatures poly = PolynomialFeatures(degree = 4)X_poly = poly.fit_transform(X) poly.fit(X_poly, y)lin2 = LinearRegression()lin2.fit(X_poly, y) Step 5: In this step, we are Visualising the Linear Regression results using a scatter plot. Python3 # Visualising the Linear Regression resultsplt.scatter(X, y, color = 'blue') plt.plot(X, lin.predict(X), color = 'red')plt.title('Linear Regression')plt.xlabel('Temperature')plt.ylabel('Pressure') plt.show() Step 6: Visualising the Polynomial Regression results using a scatter plot. Python3 # Visualising the Polynomial Regression resultsplt.scatter(X, y, color = 'blue') plt.plot(X, lin2.predict(poly.fit_transform(X)), color = 'red')plt.title('Polynomial Regression')plt.xlabel('Temperature')plt.ylabel('Pressure') plt.show() Step 7: Predicting new results with both Linear and Polynomial Regression. Note that the input variable must be in a numpy 2D array. Python3 # Predicting a new result with Linear Regression after converting predict variable to 2D arraypred = 110.0predarray = np.array([[pred]])lin.predict(predarray) Python3 # Predicting a new result with Polynomial Regression after converting predict variable to 2D arraypred2 = 110.0pred2array = np.array([[pred2]])lin2.predict(poly.fit_transform(pred2array)) Advantages of using Polynomial Regression: A broad range of functions can be fit under it. Polynomial basically fits a wide range of curvatures. Polynomial provides the best approximation of the relationship between dependent and independent variables. Disadvantages of using Polynomial Regression These are too sensitive to the outliers. The presence of one or two outliers in the data can seriously affect the results of nonlinear analysis. In addition, there are unfortunately fewer model validation tools for the detection of outliers in nonlinear regression than there are for linear regression. tanwarsinghvaibhav mbhouse Advanced Computer Subject Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. System Design Tutorial Reinforcement learning Docker - COPY Instruction Supervised and Unsupervised learning Decision Tree Introduction with example Reinforcement learning Agents in Artificial Intelligence Supervised and Unsupervised learning Search Algorithms in AI Decision Tree Introduction with example
[ { "code": null, "e": 54, "s": 26, "text": "\n22 Feb, 2022" }, { "code": null, "e": 397, "s": 54, "text": "Polynomial Regression is a form of linear regression in which the relationship between the independent variable x and dependent variable y is modeled as an nth degree polynomial. Polynomial regression fits a nonlinear relationship between the value of x and the corresponding conditional mean of y, denoted E(y |x)Why Polynomial Regression: " }, { "code": null, "e": 538, "s": 397, "text": "There are some relationships that a researcher will hypothesize is curvilinear. Clearly, such types of cases will include a polynomial term." }, { "code": null, "e": 784, "s": 538, "text": "Inspection of residuals. If we try to fit a linear model to curved data, a scatter plot of residuals (Y-axis) on the predictor (X-axis) will have patches of many positive residuals in the middle. Hence in such a situation, it is not appropriate." }, { "code": null, "e": 964, "s": 784, "text": "An assumption in usual multiple linear regression analysis is that all the independent variables are independent. In polynomial regression model, this assumption is not satisfied." }, { "code": null, "e": 1074, "s": 964, "text": "Uses of Polynomial Regression: These are basically used to define or describe non-linear phenomena such as: " }, { "code": null, "e": 1102, "s": 1074, "text": "The growth rate of tissues." }, { "code": null, "e": 1135, "s": 1102, "text": "Progression of disease epidemics" }, { "code": null, "e": 1185, "s": 1135, "text": "Distribution of carbon isotopes in lake sediments" }, { "code": null, "e": 1389, "s": 1185, "text": "The basic goal of regression analysis is to model the expected value of a dependent variable y in terms of the value of an independent variable x. In simple regression, we used the following equation – " }, { "code": null, "e": 1404, "s": 1389, "text": "y = a + bx + e" }, { "code": null, "e": 1712, "s": 1404, "text": "Here y is a dependent variable, a is the y-intercept, b is the slope and e is the error rate.In many cases, this linear model will not work out For example if we analyzing the production of chemical synthesis in terms of temperature at which the synthesis take place in such cases we use a quadratic model " }, { "code": null, "e": 1735, "s": 1712, "text": "y = a + b1x + b2^2 + e" }, { "code": null, "e": 1864, "s": 1735, "text": "Here y is the dependent variable on x, a is the y-intercept and e is the error rate.In general, we can model it for nth value. " }, { "code": null, "e": 1897, "s": 1864, "text": "y = a + b1x + b2x^2 +....+ bnx^n" }, { "code": null, "e": 2352, "s": 1897, "text": "Since regression function is linear in terms of unknown variables, hence these models are linear from the point of estimation.Hence through the Least Square technique, let’s compute the response value that is y.Polynomial Regression in Python: To get the Dataset used for the analysis of Polynomial Regression, click here.Step 1: Import libraries and dataset Import the important libraries and the dataset we are using to perform Polynomial Regression. " }, { "code": null, "e": 2360, "s": 2352, "text": "Python3" }, { "code": "# Importing the librariesimport numpy as npimport matplotlib.pyplot as pltimport pandas as pd # Importing the datasetdatas = pd.read_csv('data.csv')datas", "e": 2514, "s": 2360, "text": null }, { "code": null, "e": 2687, "s": 2514, "text": " Step 2: Dividing the dataset into 2 componentsDivide dataset into two components that is X and y.X will contain the Column between 1 and 2. y will contain the 2 columns. " }, { "code": null, "e": 2695, "s": 2687, "text": "Python3" }, { "code": "X = datas.iloc[:, 1:2].valuesy = datas.iloc[:, 2].values", "e": 2752, "s": 2695, "text": null }, { "code": null, "e": 2859, "s": 2752, "text": " Step 3: Fitting Linear Regression to the datasetFitting the linear Regression model On two components. " }, { "code": null, "e": 2867, "s": 2859, "text": "Python3" }, { "code": "# Fitting Linear Regression to the datasetfrom sklearn.linear_model import LinearRegressionlin = LinearRegression() lin.fit(X, y)", "e": 2997, "s": 2867, "text": null }, { "code": null, "e": 3120, "s": 2997, "text": " Step 4: Fitting Polynomial Regression to the datasetFitting the Polynomial Regression model on two components X and y. " }, { "code": null, "e": 3128, "s": 3120, "text": "Python3" }, { "code": "# Fitting Polynomial Regression to the datasetfrom sklearn.preprocessing import PolynomialFeatures poly = PolynomialFeatures(degree = 4)X_poly = poly.fit_transform(X) poly.fit(X_poly, y)lin2 = LinearRegression()lin2.fit(X_poly, y)", "e": 3359, "s": 3128, "text": null }, { "code": null, "e": 3456, "s": 3359, "text": " Step 5: In this step, we are Visualising the Linear Regression results using a scatter plot. " }, { "code": null, "e": 3464, "s": 3456, "text": "Python3" }, { "code": "# Visualising the Linear Regression resultsplt.scatter(X, y, color = 'blue') plt.plot(X, lin.predict(X), color = 'red')plt.title('Linear Regression')plt.xlabel('Temperature')plt.ylabel('Pressure') plt.show()", "e": 3672, "s": 3464, "text": null }, { "code": null, "e": 3751, "s": 3672, "text": " Step 6: Visualising the Polynomial Regression results using a scatter plot. " }, { "code": null, "e": 3759, "s": 3751, "text": "Python3" }, { "code": "# Visualising the Polynomial Regression resultsplt.scatter(X, y, color = 'blue') plt.plot(X, lin2.predict(poly.fit_transform(X)), color = 'red')plt.title('Polynomial Regression')plt.xlabel('Temperature')plt.ylabel('Pressure') plt.show()", "e": 3996, "s": 3759, "text": null }, { "code": null, "e": 4132, "s": 3996, "text": " Step 7: Predicting new results with both Linear and Polynomial Regression. Note that the input variable must be in a numpy 2D array. " }, { "code": null, "e": 4140, "s": 4132, "text": "Python3" }, { "code": "# Predicting a new result with Linear Regression after converting predict variable to 2D arraypred = 110.0predarray = np.array([[pred]])lin.predict(predarray)", "e": 4299, "s": 4140, "text": null }, { "code": null, "e": 4307, "s": 4299, "text": "Python3" }, { "code": "# Predicting a new result with Polynomial Regression after converting predict variable to 2D arraypred2 = 110.0pred2array = np.array([[pred2]])lin2.predict(poly.fit_transform(pred2array))", "e": 4495, "s": 4307, "text": null }, { "code": null, "e": 4541, "s": 4495, "text": " Advantages of using Polynomial Regression: " }, { "code": null, "e": 4589, "s": 4541, "text": "A broad range of functions can be fit under it." }, { "code": null, "e": 4643, "s": 4589, "text": "Polynomial basically fits a wide range of curvatures." }, { "code": null, "e": 4751, "s": 4643, "text": "Polynomial provides the best approximation of the relationship between dependent and independent variables." }, { "code": null, "e": 4798, "s": 4751, "text": "Disadvantages of using Polynomial Regression " }, { "code": null, "e": 4839, "s": 4798, "text": "These are too sensitive to the outliers." }, { "code": null, "e": 4943, "s": 4839, "text": "The presence of one or two outliers in the data can seriously affect the results of nonlinear analysis." }, { "code": null, "e": 5101, "s": 4943, "text": "In addition, there are unfortunately fewer model validation tools for the detection of outliers in nonlinear regression than there are for linear regression." }, { "code": null, "e": 5122, "s": 5103, "text": "tanwarsinghvaibhav" }, { "code": null, "e": 5130, "s": 5122, "text": "mbhouse" }, { "code": null, "e": 5156, "s": 5130, "text": "Advanced Computer Subject" }, { "code": null, "e": 5173, "s": 5156, "text": "Machine Learning" }, { "code": null, "e": 5180, "s": 5173, "text": "Python" }, { "code": null, "e": 5197, "s": 5180, "text": "Machine Learning" }, { "code": null, "e": 5295, "s": 5197, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5318, "s": 5295, "text": "System Design Tutorial" }, { "code": null, "e": 5341, "s": 5318, "text": "Reinforcement learning" }, { "code": null, "e": 5367, "s": 5341, "text": "Docker - COPY Instruction" }, { "code": null, "e": 5404, "s": 5367, "text": "Supervised and Unsupervised learning" }, { "code": null, "e": 5444, "s": 5404, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 5467, "s": 5444, "text": "Reinforcement learning" }, { "code": null, "e": 5501, "s": 5467, "text": "Agents in Artificial Intelligence" }, { "code": null, "e": 5538, "s": 5501, "text": "Supervised and Unsupervised learning" }, { "code": null, "e": 5562, "s": 5538, "text": "Search Algorithms in AI" } ]
Java Program to Take a Snapshot From System Camera
29 Jul, 2021 It is better to have a brief knowledge of the Swing class of java as it is applied in the implementation to do so as whenever there arises a need to deal with images or dealing with the two-dimensional matrix as an output or usage of it in generating the output in java, Swing class comes into play in achieving the same. We will be using Netbeans IDE o create GUI applications since it is a well crafted open-source IDE that provides features of a component inspector, Drag-and-Drop of widgets, Debugger, Object browser, etc and there is no need to import JAR files unlikely as seen in other IDEs such as an eclipse. Now this gives this IDE an extra edge over the other IDEs. Concept: Basically, this program is divided into 2 parts. One is the design part which is done using swing controls. And the other part is some code part to capture image. In the design part, I have used swing controls to design the interface. We just need to drag and drop the controls from palette. Here 2 labels and 1 button are used. The first label name is β€˜lblcloseβ€˜. There I have set a PNG image and written a code on events-> action performed. When you click on that image the output window will close. For this, I have used dispose() method. The second label name is β€˜lblphoto’. Here you can see your image when you run the program. The webcam will open when you run your code. Here I have used one button named β€˜btnclickβ€˜. You can see a button CLICK. When you click on the button the image will be captured in your β€˜lblphotoβ€˜ label.In the code part, I have used Webcam be named it β€˜wc’ ie created a webcam object. The library allows you to use your build-in or external webcam directly from Java. It’s designed to abstract commonly used camera features and support multiple capturing frameworks. Then by open() function, the webcam will open. Then after clicking on the CLICK button you will capture an image. Then convert this image according to the size of the label. Then assign this image to label. Then create and start the thread. In the design part, I have used swing controls to design the interface. We just need to drag and drop the controls from palette. Here 2 labels and 1 button are used. The first label name is β€˜lblcloseβ€˜. There I have set a PNG image and written a code on events-> action performed. When you click on that image the output window will close. For this, I have used dispose() method. The second label name is β€˜lblphoto’. Here you can see your image when you run the program. The webcam will open when you run your code. Here I have used one button named β€˜btnclickβ€˜. You can see a button CLICK. When you click on the button the image will be captured in your β€˜lblphotoβ€˜ label. In the code part, I have used Webcam be named it β€˜wc’ ie created a webcam object. The library allows you to use your build-in or external webcam directly from Java. It’s designed to abstract commonly used camera features and support multiple capturing frameworks. Then by open() function, the webcam will open. Then after clicking on the CLICK button you will capture an image. Then convert this image according to the size of the label. Then assign this image to label. Then create and start the thread. Procedure: Creation of a new java application and further creating a file under the project.`Start dragging toolkit widgets as per need from the palette situated on top-right.Click anywhere on the panel area and go to properties to change the background.Now double-click on the background area and select any color of choice and press the Ok button.Now start dragging widgets on the drawing area.Start writing the java program as explained below.Select the JAR files as in libraries JAR files need to be imported. Creation of a new java application and further creating a file under the project.` Start dragging toolkit widgets as per need from the palette situated on top-right. Click anywhere on the panel area and go to properties to change the background. Now double-click on the background area and select any color of choice and press the Ok button. Now start dragging widgets on the drawing area. Start writing the java program as explained below. Select the JAR files as in libraries JAR files need to be imported. Implementation: Step 1(a): Create a new Java application by clicking on β€˜New Project β†’ Java β†’ Java Applicationβ€˜ and give a suitable project name. Considering a random example for illustration purposes β€˜MyFirstFrame’ and click Finish. Step 1(b): To create a β€˜New File’ under the same Java project β€˜MyFirstFrame’, right-click on the project name on the left-hand side of the window, click as below shown, and click finish. E.g. MyFrame.java New -> JFrame Form and give a suitable file name Step 2: Now from the palette situated at the right-hand side of the window, start dragging the toolkit widgets as per requirements. To change the background color of the frame, we need to first insert a JPanel and change its properties. Step 3: Click anywhere on the panel area, go to β€˜properties β†’ background.’ Step 4: Double-click on the background option and select any color of the desired choice meeting requirement choice and click OK. Step 5: After setting the background color, drag other widgets onto the design area. Here I have dragged a button and a label. Button named CLICK and label is used to capture an image. In addition, a border is given to the label. Step 6(a): Now write the code by right-clicking as shown below MyFrame.java β†’ Split β†’ Horizontally Step 6(b): Then this pop-up window will appear. Here click on β€˜sourceβ€˜ to write the code, and further one can click on β€˜designβ€˜ to move to design. Step 7(a): Adding up the jar files, go to Libraries. Right-click on β€˜librariesβ€˜ and select β€˜ADD JAR/FOLDERβ€˜. Step 7(b): Select the 3 jar files, then click on β€˜openβ€˜. The requirements are as follows as in libraries JAR files need to be imported more specifically 3 JAR files need to be import bridj-0.7.0.jar slf4j-api-1.7.2.jar webcam-capture-0.3.12.jar Implementation: The sample input image is as shown below: Example: Java // Java Program to Take a Snapshot From System Camera package myfirstform; // The goal of this import com.github.sarxos.webcam.Webcam// is to allow integrated or USB-connected webcams// to be accessed directly from java// Using provided libraries users are able to// read camera images and detect motionimport com.github.sarxos.webcam.Webcam; // Provides classes for creating and modifying images*/import java.awt.Image; // Creates an ImageIcon from an array of bytes// which were read from an image file containing// a supported image format, such as GIF, JPG, PNGimport javax.swing.ImageIcon; // Class// Main classpublic class MyFrame extends javax.swing.JFrame implements Runnable { // Creates new form MyFrame public MyFrame() { // Initialising the components initComponents(); // This is for the closing button lblclose.setText(""); // Createing an image icon by adding path of image ImageIcon img = new ImageIcon( "C:\\Users\\dhannu\\Documents\\NetBeansProjects\\MyFirstForm\\src\\images\\sf.png"); // Creating an object of Image type Image myimg = img.getImage(); // Creating a new image whose size is same as label // size using algorithm - SCALE_SMOOTH Image newimage = myimg.getScaledInstance( lblclose.getWidth(), lblclose.getHeight(), Image.SCALE_SMOOTH); // Creating a image icon from new image ImageIcon ic = new ImageIcon(newimage); // Assigning the imageicon to the label lblclose.setIcon(ic); // Thread is created and started using // start() method which begins thread execution new Thread(this).start(); } // generated code // This method is called from within the constructor to // initialize the form. WARNING: Do NOT modify this // code. The content of this method is always // regenerated by the Form Editor. @SuppressWarnings("unchecked") private void initComponents() { jPanel1 = new javax.swing.JPanel(); lblclose = new javax.swing.JLabel(); lblphoto = new javax.swing.JLabel(); btnclick = new javax.swing.JButton(); setDefaultCloseOperation( javax.swing.WindowConstants.EXIT_ON_CLOSE); setUndecorated(true); // Setting the background by providing // Custom input bounds as parameters jPanel1.setBackground( new java.awt.Color(204, 204, 255)); lblclose.addMouseListener( new java.awt.event.MouseAdapter() { public void mouseClicked( java.awt.event.MouseEvent evt) { lblcloseMouseClicked(evt); } }); lblphoto.setBorder( javax.swing.BorderFactory.createLineBorder( new java.awt.Color(0, 0, 0), 4)); // Click button btnclick.setText("CLICK"); btnclick.addActionListener( new java.awt.event.ActionListener() { public void actionPerformed( java.awt.event.ActionEvent evt) { btnclickActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout .createParallelGroup(javax.swing.GroupLayout .Alignment.LEADING) .addGroup( jPanel1Layout.createSequentialGroup() .addGap(51, 51, 51) .addComponent( lblphoto, javax.swing.GroupLayout .PREFERRED_SIZE, 143, javax.swing.GroupLayout .PREFERRED_SIZE) .addPreferredGap( javax.swing.LayoutStyle .ComponentPlacement.RELATED, 34, Short.MAX_VALUE) .addComponent( lblclose, javax.swing.GroupLayout .PREFERRED_SIZE, 28, javax.swing.GroupLayout .PREFERRED_SIZE) .addContainerGap()) .addGroup( jPanel1Layout.createSequentialGroup() .addGap(97, 97, 97) .addComponent(btnclick) .addContainerGap( javax.swing.GroupLayout .DEFAULT_SIZE, Short.MAX_VALUE))); jPanel1Layout.setVerticalGroup( jPanel1Layout .createParallelGroup(javax.swing.GroupLayout .Alignment.LEADING) .addGroup( jPanel1Layout.createSequentialGroup() .addGroup( jPanel1Layout .createParallelGroup( javax.swing.GroupLayout .Alignment.LEADING) .addGroup( jPanel1Layout .createSequentialGroup() .addContainerGap() .addComponent( lblclose, javax.swing .GroupLayout .PREFERRED_SIZE, 28, javax.swing .GroupLayout .PREFERRED_SIZE)) .addGroup( jPanel1Layout .createSequentialGroup() .addGap(22, 22, 22) .addComponent( lblphoto, javax.swing .GroupLayout .PREFERRED_SIZE, 143, javax.swing .GroupLayout .PREFERRED_SIZE))) .addGap(18, 18, 18) .addComponent(btnclick) .addContainerGap(29, Short.MAX_VALUE))); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout .createParallelGroup(javax.swing.GroupLayout .Alignment.LEADING) .addComponent( jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout .PREFERRED_SIZE)); layout.setVerticalGroup( layout .createParallelGroup(javax.swing.GroupLayout .Alignment.LEADING) .addComponent( jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout .PREFERRED_SIZE)); pack(); setLocationRelativeTo(null); } // End of generate code private void lblcloseMouseClicked(java.awt.event.MouseEvent evt) { // Setting flag as false to stop the thread // so that you can capture the snapshot flag = false; // Destroying and cleaning the JFrame window // by the operating system\ // using dispose() method dispose(); } private void btnclickActionPerformed(java.awt.event.ActionEvent evt) { flag = false; } // Main driver method public static void main(String args[]) { // Set the Nimbus look and feel // If Nimbus(Java 6+) is not available // stay with the default look and feel. // Try block to check if any exceptions occur try { for (javax.swing.UIManager .LookAndFeelInfo info : javax.swing.UIManager .getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel( info.getClassName()); break; } } } // Catch blocks to handle exceptions // First catch block to handle exception // if class is not found catch (ClassNotFoundException ex) { java.util.logging.Logger .getLogger(MyFrame.class.getName()) .log(java.util.logging.Level.SEVERE, null, ex); } // Second catch block to handle for exception // InstantiationException // In generic, this exception is thrown // rarely catch (InstantiationException ex) { java.util.logging.Logger .getLogger(MyFrame.class.getName()) .log(java.util.logging.Level.SEVERE, null, ex); } // 3rd catch block to handle // IllegalAccessException catch (IllegalAccessException ex) { java.util.logging.Logger .getLogger(MyFrame.class.getName()) .log(java.util.logging.Level.SEVERE, null, ex); } // 4th catch block to handle Swing class // UnsupportedLookAndFeelException catch (javax.swing .UnsupportedLookAndFeelException ex) { java.util.logging.Logger .getLogger(MyFrame.class.getName()) .log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> // Create and display the form java.awt.EventQueue.invokeLater(new Runnable() { // Method run() which will later on // over-ridden public void run() { new MyFrame().setVisible(true); } }); } // End of generated code // Declaring variables private javax.swing.JButton btnclick; private javax.swing.JPanel jPanel1; private javax.swing.JLabel lblclose; private javax.swing.JLabel lblphoto; Webcam wc; // Initially setting flag as true boolean flag = true; // Overriding the run() method as // created above already // @Override public void run() { // Creating a webcam object wc = Webcam.getDefault(); // Method to open the camera wc.open(); // Checking condition over flag which // holds true for boolean true as // above flag is declared true while (flag) { // An image is clicked Image img = wc.getImage(); // Create a image whose size is same as label img = img.getScaledInstance( lblphoto.getWidth(), lblphoto.getHeight(), Image.SCALE_SMOOTH); // The clicked image is assigned to a Label lblphoto.setIcon(new ImageIcon(img)); // Try block to check for thread exception try { // Putting the thread to sleap Thread.sleep(20); } // Catch block in there is some // mishappening while the thread is // put to sleep catch (InterruptedException e) { } } }} Output: This is a snapshot captured from front camera where the code is compiled and run. It will differ with realtime basic what comes in front of front camera when the above same code is compiled and run again. akshaysingh98088 surinderdawra388 surindertarika1234 Picked Technical Scripter 2020 Java Java Programs Technical Scripter Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Introduction to Java Constructors in Java Exceptions in Java Generics in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class Factory method design pattern in Java Java Program to Remove Duplicate Elements From the Array
[ { "code": null, "e": 54, "s": 26, "text": "\n29 Jul, 2021" }, { "code": null, "e": 376, "s": 54, "text": "It is better to have a brief knowledge of the Swing class of java as it is applied in the implementation to do so as whenever there arises a need to deal with images or dealing with the two-dimensional matrix as an output or usage of it in generating the output in java, Swing class comes into play in achieving the same." }, { "code": null, "e": 731, "s": 376, "text": "We will be using Netbeans IDE o create GUI applications since it is a well crafted open-source IDE that provides features of a component inspector, Drag-and-Drop of widgets, Debugger, Object browser, etc and there is no need to import JAR files unlikely as seen in other IDEs such as an eclipse. Now this gives this IDE an extra edge over the other IDEs." }, { "code": null, "e": 740, "s": 731, "text": "Concept:" }, { "code": null, "e": 903, "s": 740, "text": "Basically, this program is divided into 2 parts. One is the design part which is done using swing controls. And the other part is some code part to capture image." }, { "code": null, "e": 2078, "s": 903, "text": "In the design part, I have used swing controls to design the interface. We just need to drag and drop the controls from palette. Here 2 labels and 1 button are used. The first label name is β€˜lblcloseβ€˜. There I have set a PNG image and written a code on events-> action performed. When you click on that image the output window will close. For this, I have used dispose() method. The second label name is β€˜lblphoto’. Here you can see your image when you run the program. The webcam will open when you run your code. Here I have used one button named β€˜btnclickβ€˜. You can see a button CLICK. When you click on the button the image will be captured in your β€˜lblphotoβ€˜ label.In the code part, I have used Webcam be named it β€˜wc’ ie created a webcam object. The library allows you to use your build-in or external webcam directly from Java. It’s designed to abstract commonly used camera features and support multiple capturing frameworks. Then by open() function, the webcam will open. Then after clicking on the CLICK button you will capture an image. Then convert this image according to the size of the label. Then assign this image to label. Then create and start the thread." }, { "code": null, "e": 2749, "s": 2078, "text": "In the design part, I have used swing controls to design the interface. We just need to drag and drop the controls from palette. Here 2 labels and 1 button are used. The first label name is β€˜lblcloseβ€˜. There I have set a PNG image and written a code on events-> action performed. When you click on that image the output window will close. For this, I have used dispose() method. The second label name is β€˜lblphoto’. Here you can see your image when you run the program. The webcam will open when you run your code. Here I have used one button named β€˜btnclickβ€˜. You can see a button CLICK. When you click on the button the image will be captured in your β€˜lblphotoβ€˜ label." }, { "code": null, "e": 3254, "s": 2749, "text": "In the code part, I have used Webcam be named it β€˜wc’ ie created a webcam object. The library allows you to use your build-in or external webcam directly from Java. It’s designed to abstract commonly used camera features and support multiple capturing frameworks. Then by open() function, the webcam will open. Then after clicking on the CLICK button you will capture an image. Then convert this image according to the size of the label. Then assign this image to label. Then create and start the thread." }, { "code": null, "e": 3266, "s": 3254, "text": " Procedure:" }, { "code": null, "e": 3769, "s": 3266, "text": "Creation of a new java application and further creating a file under the project.`Start dragging toolkit widgets as per need from the palette situated on top-right.Click anywhere on the panel area and go to properties to change the background.Now double-click on the background area and select any color of choice and press the Ok button.Now start dragging widgets on the drawing area.Start writing the java program as explained below.Select the JAR files as in libraries JAR files need to be imported." }, { "code": null, "e": 3852, "s": 3769, "text": "Creation of a new java application and further creating a file under the project.`" }, { "code": null, "e": 3935, "s": 3852, "text": "Start dragging toolkit widgets as per need from the palette situated on top-right." }, { "code": null, "e": 4015, "s": 3935, "text": "Click anywhere on the panel area and go to properties to change the background." }, { "code": null, "e": 4111, "s": 4015, "text": "Now double-click on the background area and select any color of choice and press the Ok button." }, { "code": null, "e": 4159, "s": 4111, "text": "Now start dragging widgets on the drawing area." }, { "code": null, "e": 4210, "s": 4159, "text": "Start writing the java program as explained below." }, { "code": null, "e": 4278, "s": 4210, "text": "Select the JAR files as in libraries JAR files need to be imported." }, { "code": null, "e": 4294, "s": 4278, "text": "Implementation:" }, { "code": null, "e": 4512, "s": 4294, "text": "Step 1(a): Create a new Java application by clicking on β€˜New Project β†’ Java β†’ Java Applicationβ€˜ and give a suitable project name. Considering a random example for illustration purposes β€˜MyFirstFrame’ and click Finish." }, { "code": null, "e": 4717, "s": 4512, "text": "Step 1(b): To create a β€˜New File’ under the same Java project β€˜MyFirstFrame’, right-click on the project name on the left-hand side of the window, click as below shown, and click finish. E.g. MyFrame.java" }, { "code": null, "e": 4766, "s": 4717, "text": "New -> JFrame Form and give a suitable file name" }, { "code": null, "e": 5003, "s": 4766, "text": "Step 2: Now from the palette situated at the right-hand side of the window, start dragging the toolkit widgets as per requirements. To change the background color of the frame, we need to first insert a JPanel and change its properties." }, { "code": null, "e": 5078, "s": 5003, "text": "Step 3: Click anywhere on the panel area, go to β€˜properties β†’ background.’" }, { "code": null, "e": 5208, "s": 5078, "text": "Step 4: Double-click on the background option and select any color of the desired choice meeting requirement choice and click OK." }, { "code": null, "e": 5438, "s": 5208, "text": "Step 5: After setting the background color, drag other widgets onto the design area. Here I have dragged a button and a label. Button named CLICK and label is used to capture an image. In addition, a border is given to the label." }, { "code": null, "e": 5502, "s": 5438, "text": "Step 6(a): Now write the code by right-clicking as shown below " }, { "code": null, "e": 5538, "s": 5502, "text": "MyFrame.java β†’ Split β†’ Horizontally" }, { "code": null, "e": 5685, "s": 5538, "text": "Step 6(b): Then this pop-up window will appear. Here click on β€˜sourceβ€˜ to write the code, and further one can click on β€˜designβ€˜ to move to design." }, { "code": null, "e": 5795, "s": 5685, "text": "Step 7(a): Adding up the jar files, go to Libraries. Right-click on β€˜librariesβ€˜ and select β€˜ADD JAR/FOLDERβ€˜. " }, { "code": null, "e": 5978, "s": 5795, "text": "Step 7(b): Select the 3 jar files, then click on β€˜openβ€˜. The requirements are as follows as in libraries JAR files need to be imported more specifically 3 JAR files need to be import" }, { "code": null, "e": 5994, "s": 5978, "text": "bridj-0.7.0.jar" }, { "code": null, "e": 6014, "s": 5994, "text": "slf4j-api-1.7.2.jar" }, { "code": null, "e": 6040, "s": 6014, "text": "webcam-capture-0.3.12.jar" }, { "code": null, "e": 6056, "s": 6040, "text": "Implementation:" }, { "code": null, "e": 6098, "s": 6056, "text": "The sample input image is as shown below:" }, { "code": null, "e": 6107, "s": 6098, "text": "Example:" }, { "code": null, "e": 6112, "s": 6107, "text": "Java" }, { "code": "// Java Program to Take a Snapshot From System Camera package myfirstform; // The goal of this import com.github.sarxos.webcam.Webcam// is to allow integrated or USB-connected webcams// to be accessed directly from java// Using provided libraries users are able to// read camera images and detect motionimport com.github.sarxos.webcam.Webcam; // Provides classes for creating and modifying images*/import java.awt.Image; // Creates an ImageIcon from an array of bytes// which were read from an image file containing// a supported image format, such as GIF, JPG, PNGimport javax.swing.ImageIcon; // Class// Main classpublic class MyFrame extends javax.swing.JFrame implements Runnable { // Creates new form MyFrame public MyFrame() { // Initialising the components initComponents(); // This is for the closing button lblclose.setText(\"\"); // Createing an image icon by adding path of image ImageIcon img = new ImageIcon( \"C:\\\\Users\\\\dhannu\\\\Documents\\\\NetBeansProjects\\\\MyFirstForm\\\\src\\\\images\\\\sf.png\"); // Creating an object of Image type Image myimg = img.getImage(); // Creating a new image whose size is same as label // size using algorithm - SCALE_SMOOTH Image newimage = myimg.getScaledInstance( lblclose.getWidth(), lblclose.getHeight(), Image.SCALE_SMOOTH); // Creating a image icon from new image ImageIcon ic = new ImageIcon(newimage); // Assigning the imageicon to the label lblclose.setIcon(ic); // Thread is created and started using // start() method which begins thread execution new Thread(this).start(); } // generated code // This method is called from within the constructor to // initialize the form. WARNING: Do NOT modify this // code. The content of this method is always // regenerated by the Form Editor. @SuppressWarnings(\"unchecked\") private void initComponents() { jPanel1 = new javax.swing.JPanel(); lblclose = new javax.swing.JLabel(); lblphoto = new javax.swing.JLabel(); btnclick = new javax.swing.JButton(); setDefaultCloseOperation( javax.swing.WindowConstants.EXIT_ON_CLOSE); setUndecorated(true); // Setting the background by providing // Custom input bounds as parameters jPanel1.setBackground( new java.awt.Color(204, 204, 255)); lblclose.addMouseListener( new java.awt.event.MouseAdapter() { public void mouseClicked( java.awt.event.MouseEvent evt) { lblcloseMouseClicked(evt); } }); lblphoto.setBorder( javax.swing.BorderFactory.createLineBorder( new java.awt.Color(0, 0, 0), 4)); // Click button btnclick.setText(\"CLICK\"); btnclick.addActionListener( new java.awt.event.ActionListener() { public void actionPerformed( java.awt.event.ActionEvent evt) { btnclickActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout .createParallelGroup(javax.swing.GroupLayout .Alignment.LEADING) .addGroup( jPanel1Layout.createSequentialGroup() .addGap(51, 51, 51) .addComponent( lblphoto, javax.swing.GroupLayout .PREFERRED_SIZE, 143, javax.swing.GroupLayout .PREFERRED_SIZE) .addPreferredGap( javax.swing.LayoutStyle .ComponentPlacement.RELATED, 34, Short.MAX_VALUE) .addComponent( lblclose, javax.swing.GroupLayout .PREFERRED_SIZE, 28, javax.swing.GroupLayout .PREFERRED_SIZE) .addContainerGap()) .addGroup( jPanel1Layout.createSequentialGroup() .addGap(97, 97, 97) .addComponent(btnclick) .addContainerGap( javax.swing.GroupLayout .DEFAULT_SIZE, Short.MAX_VALUE))); jPanel1Layout.setVerticalGroup( jPanel1Layout .createParallelGroup(javax.swing.GroupLayout .Alignment.LEADING) .addGroup( jPanel1Layout.createSequentialGroup() .addGroup( jPanel1Layout .createParallelGroup( javax.swing.GroupLayout .Alignment.LEADING) .addGroup( jPanel1Layout .createSequentialGroup() .addContainerGap() .addComponent( lblclose, javax.swing .GroupLayout .PREFERRED_SIZE, 28, javax.swing .GroupLayout .PREFERRED_SIZE)) .addGroup( jPanel1Layout .createSequentialGroup() .addGap(22, 22, 22) .addComponent( lblphoto, javax.swing .GroupLayout .PREFERRED_SIZE, 143, javax.swing .GroupLayout .PREFERRED_SIZE))) .addGap(18, 18, 18) .addComponent(btnclick) .addContainerGap(29, Short.MAX_VALUE))); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout .createParallelGroup(javax.swing.GroupLayout .Alignment.LEADING) .addComponent( jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout .PREFERRED_SIZE)); layout.setVerticalGroup( layout .createParallelGroup(javax.swing.GroupLayout .Alignment.LEADING) .addComponent( jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout .PREFERRED_SIZE)); pack(); setLocationRelativeTo(null); } // End of generate code private void lblcloseMouseClicked(java.awt.event.MouseEvent evt) { // Setting flag as false to stop the thread // so that you can capture the snapshot flag = false; // Destroying and cleaning the JFrame window // by the operating system\\ // using dispose() method dispose(); } private void btnclickActionPerformed(java.awt.event.ActionEvent evt) { flag = false; } // Main driver method public static void main(String args[]) { // Set the Nimbus look and feel // If Nimbus(Java 6+) is not available // stay with the default look and feel. // Try block to check if any exceptions occur try { for (javax.swing.UIManager .LookAndFeelInfo info : javax.swing.UIManager .getInstalledLookAndFeels()) { if (\"Nimbus\".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel( info.getClassName()); break; } } } // Catch blocks to handle exceptions // First catch block to handle exception // if class is not found catch (ClassNotFoundException ex) { java.util.logging.Logger .getLogger(MyFrame.class.getName()) .log(java.util.logging.Level.SEVERE, null, ex); } // Second catch block to handle for exception // InstantiationException // In generic, this exception is thrown // rarely catch (InstantiationException ex) { java.util.logging.Logger .getLogger(MyFrame.class.getName()) .log(java.util.logging.Level.SEVERE, null, ex); } // 3rd catch block to handle // IllegalAccessException catch (IllegalAccessException ex) { java.util.logging.Logger .getLogger(MyFrame.class.getName()) .log(java.util.logging.Level.SEVERE, null, ex); } // 4th catch block to handle Swing class // UnsupportedLookAndFeelException catch (javax.swing .UnsupportedLookAndFeelException ex) { java.util.logging.Logger .getLogger(MyFrame.class.getName()) .log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> // Create and display the form java.awt.EventQueue.invokeLater(new Runnable() { // Method run() which will later on // over-ridden public void run() { new MyFrame().setVisible(true); } }); } // End of generated code // Declaring variables private javax.swing.JButton btnclick; private javax.swing.JPanel jPanel1; private javax.swing.JLabel lblclose; private javax.swing.JLabel lblphoto; Webcam wc; // Initially setting flag as true boolean flag = true; // Overriding the run() method as // created above already // @Override public void run() { // Creating a webcam object wc = Webcam.getDefault(); // Method to open the camera wc.open(); // Checking condition over flag which // holds true for boolean true as // above flag is declared true while (flag) { // An image is clicked Image img = wc.getImage(); // Create a image whose size is same as label img = img.getScaledInstance( lblphoto.getWidth(), lblphoto.getHeight(), Image.SCALE_SMOOTH); // The clicked image is assigned to a Label lblphoto.setIcon(new ImageIcon(img)); // Try block to check for thread exception try { // Putting the thread to sleap Thread.sleep(20); } // Catch block in there is some // mishappening while the thread is // put to sleep catch (InterruptedException e) { } } }}", "e": 18418, "s": 6112, "text": null }, { "code": null, "e": 18427, "s": 18418, "text": "Output: " }, { "code": null, "e": 18632, "s": 18427, "text": "This is a snapshot captured from front camera where the code is compiled and run. It will differ with realtime basic what comes in front of front camera when the above same code is compiled and run again." }, { "code": null, "e": 18651, "s": 18634, "text": "akshaysingh98088" }, { "code": null, "e": 18668, "s": 18651, "text": "surinderdawra388" }, { "code": null, "e": 18687, "s": 18668, "text": "surindertarika1234" }, { "code": null, "e": 18694, "s": 18687, "text": "Picked" }, { "code": null, "e": 18718, "s": 18694, "text": "Technical Scripter 2020" }, { "code": null, "e": 18723, "s": 18718, "text": "Java" }, { "code": null, "e": 18737, "s": 18723, "text": "Java Programs" }, { "code": null, "e": 18756, "s": 18737, "text": "Technical Scripter" }, { "code": null, "e": 18761, "s": 18756, "text": "Java" }, { "code": null, "e": 18859, "s": 18761, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 18874, "s": 18859, "text": "Stream In Java" }, { "code": null, "e": 18895, "s": 18874, "text": "Introduction to Java" }, { "code": null, "e": 18916, "s": 18895, "text": "Constructors in Java" }, { "code": null, "e": 18935, "s": 18916, "text": "Exceptions in Java" }, { "code": null, "e": 18952, "s": 18935, "text": "Generics in Java" }, { "code": null, "e": 18978, "s": 18952, "text": "Java Programming Examples" }, { "code": null, "e": 19012, "s": 18978, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 19059, "s": 19012, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 19097, "s": 19059, "text": "Factory method design pattern in Java" } ]
Minimum distance to the corner of a grid from source
16 Jun, 2022 Given a binary grid of order r * c and an initial position. The task is to find the minimum distance from the source to get to the any corner of the grid. A move can be made to a cell grid[i][j] only if grid[i][j] = 0 and only left, right, up and down movements are permitted. If no valid path exists then print -1.Examples: Input: i = 1, j = 1, grid[][] = {{0, 0, 1}, {0, 0, 0}, {1, 1, 1}} Output: 2 (1, 1) -> (1, 0) -> (0, 0) Input: i = 0, j = 0, grid[][] = {{0, 1}, {1, 1}} Output: 0 Source is already a corner of the grid. Approach: If source is already any of the corner then print 0. Start traversing the grid starting with source using BFS as : Insert cell position in queue.Pop element from queue and mark it visited.For each valid move adjacent to popped one, insert the cell position into queue.On each move, update the minimum distance of the cell from initial position. Insert cell position in queue. Pop element from queue and mark it visited. For each valid move adjacent to popped one, insert the cell position into queue. On each move, update the minimum distance of the cell from initial position. After the completion of the BFS, find the minimum distance from source to every corner. Print the minimum among these in the end. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std;#define row 5#define col 5 // Global variables for grid, minDistance and visited arrayint minDistance[row + 1][col + 1], visited[row + 1][col + 1]; // Queue for BFSqueue<pair<int, int> > que; // Function to find whether the move is valid or notbool isValid(int grid[][col], int i, int j){ if (i < 0 || j < 0 || j >= col || i >= row || grid[i][j] || visited[i][j]) return false; return true;} // Function to return the minimum distance// from source to the end of the gridint minDistance(int grid[][col], int sourceRow, int sourceCol){ // If source is one of the destinations if ((sourceCol == 0 && sourceRow == 0) || (sourceCol == col - 1 && sourceRow == 0) || (sourceCol == 0 && sourceRow == row - 1) || (sourceCol == col - 1 && sourceRow == row - 1)) return 0; // Set minimum value int minFromSource = row * col; // Precalculate minDistance of each grid with R * C for (int i = 0; i < row; i++) for (int j = 0; j < col; j++) minDistance[i][j] = row * col; // Insert source position in queue que.push(make_pair(sourceRow, sourceCol)); // Update minimum distance to visit source minDistance[sourceRow][sourceCol] = 0; // Set source to visited visited[sourceRow][sourceCol] = 1; // BFS approach for calculating the minDistance // of each cell from source while (!que.empty()) { // Iterate over all four cells adjacent // to current cell pair<int, int> cell = que.front(); // Initialize position of current cell int cellRow = cell.first; int cellCol = cell.second; // Cell below the current cell if (isValid(grid, cellRow + 1, cellCol)) { // Push new cell to the queue que.push(make_pair(cellRow + 1, cellCol)); // Update one of its neightbor's distance minDistance[cellRow + 1][cellCol] = min(minDistance[cellRow + 1][cellCol], minDistance[cellRow][cellCol] + 1); visited[cellRow + 1][cellCol] = 1; } // Above the current cell if (isValid(grid, cellRow - 1, cellCol)) { que.push(make_pair(cellRow - 1, cellCol)); minDistance[cellRow - 1][cellCol] = min(minDistance[cellRow - 1][cellCol], minDistance[cellRow][cellCol] + 1); visited[cellRow - 1][cellCol] = 1; } // Right cell if (isValid(grid, cellRow, cellCol + 1)) { que.push(make_pair(cellRow, cellCol + 1)); minDistance[cellRow][cellCol + 1] = min(minDistance[cellRow][cellCol + 1], minDistance[cellRow][cellCol] + 1); visited[cellRow][cellCol + 1] = 1; } // Left cell if (isValid(grid, cellRow, cellCol - 1)) { que.push(make_pair(cellRow, cellCol - 1)); minDistance[cellRow][cellCol - 1] = min(minDistance[cellRow][cellCol - 1], minDistance[cellRow][cellCol] + 1); visited[cellRow][cellCol - 1] = 1; } // Pop the visited cell que.pop(); } int i; // Minimum distance to the corner // of the first row, first column minFromSource = min(minFromSource, minDistance[0][0]); // Minimum distance to the corner // of the last row, first column minFromSource = min(minFromSource, minDistance[row - 1][0]); // Minimum distance to the corner // of the last row, last column minFromSource = min(minFromSource, minDistance[row - 1][col - 1]); // Minimum distance to the corner // of the first row, last column minFromSource = min(minFromSource, minDistance[0][col - 1]); // If no path exists if (minFromSource == row * col) return -1; // Return the minimum distance return minFromSource;} // Driver codeint main(){ int sourceRow = 3, sourceCol = 3; int grid[row][col] = { 1, 1, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 0 }; cout << minDistance(grid, sourceRow, sourceCol); return 0;} // Java implementation of the approachimport java.util.*;class GFG{ // Pair classstatic class Pair{ int first,second; Pair(int a, int b) { first = a; second = b; }} static int row = 5;static int col = 5; // Global variables for grid, minDistance and visited arraystatic int minDistance[][] = new int[row + 1][col + 1], visited[][] = new int[row + 1][col + 1]; // Queue for BFSstatic Queue<Pair > que = new LinkedList<>(); // Function to find whether the move is valid or notstatic boolean isValid(int grid[][], int i, int j){ if (i < 0 || j < 0 || j >= col || i >= row || grid[i][j] != 0 || visited[i][j] != 0) return false; return true;} // Function to return the minimum distance// from source to the end of the gridstatic int minDistance(int grid[][], int sourceRow, int sourceCol){ // If source is one of the destinations if ((sourceCol == 0 && sourceRow == 0) || (sourceCol == col - 1 && sourceRow == 0) || (sourceCol == 0 && sourceRow == row - 1) || (sourceCol == col - 1 && sourceRow == row - 1)) return 0; // Set minimum value int minFromSource = row * col; // Precalculate minDistance of each grid with R * C for (int i = 0; i < row; i++) for (int j = 0; j < col; j++) minDistance[i][j] = row * col; // Insert source position in queue que.add(new Pair(sourceRow, sourceCol)); // Update minimum distance to visit source minDistance[sourceRow][sourceCol] = 0; // Set source to visited visited[sourceRow][sourceCol] = 1; // BFS approach for calculating the minDistance // of each cell from source while (que.size() > 0) { // Iterate over all four cells adjacent // to current cell Pair cell = que.peek(); // Initialize position of current cell int cellRow = cell.first; int cellCol = cell.second; // Cell below the current cell if (isValid(grid, cellRow + 1, cellCol)) { // add new cell to the queue que.add(new Pair(cellRow + 1, cellCol)); // Update one of its neightbor's distance minDistance[cellRow + 1][cellCol] = Math.min(minDistance[cellRow + 1][cellCol], minDistance[cellRow][cellCol] + 1); visited[cellRow + 1][cellCol] = 1; } // Above the current cell if (isValid(grid, cellRow - 1, cellCol)) { que.add(new Pair(cellRow - 1, cellCol)); minDistance[cellRow - 1][cellCol] = Math.min(minDistance[cellRow - 1][cellCol], minDistance[cellRow][cellCol] + 1); visited[cellRow - 1][cellCol] = 1; } // Right cell if (isValid(grid, cellRow, cellCol + 1)) { que.add(new Pair(cellRow, cellCol + 1)); minDistance[cellRow][cellCol + 1] = Math.min(minDistance[cellRow][cellCol + 1], minDistance[cellRow][cellCol] + 1); visited[cellRow][cellCol + 1] = 1; } // Left cell if (isValid(grid, cellRow, cellCol - 1)) { que.add(new Pair(cellRow, cellCol - 1)); minDistance[cellRow][cellCol - 1] = Math.min(minDistance[cellRow][cellCol - 1], minDistance[cellRow][cellCol] + 1); visited[cellRow][cellCol - 1] = 1; } // remove the visited cell que.remove(); } int i; // Minimum distance to the corner // of the first row, first column minFromSource = Math.min(minFromSource, minDistance[0][0]); // Minimum distance to the corner // of the last row, first column minFromSource = Math.min(minFromSource, minDistance[row - 1][0]); // Minimum distance to the corner // of the last row, last column minFromSource = Math.min(minFromSource, minDistance[row - 1][col - 1]); // Minimum distance to the corner // of the first row, last column minFromSource = Math.min(minFromSource, minDistance[0][col - 1]); // If no path exists if (minFromSource == row * col) return -1; // Return the minimum distance return minFromSource;} // Driver codepublic static void main(String args[]){ int sourceRow = 3, sourceCol = 3; int grid[][] = { {1, 1, 1, 0, 0}, {0, 0, 1, 0, 1}, {0, 0, 1, 0, 1}, {1, 0, 0, 0, 1}, {1, 1, 0, 1, 0} }; System.out.println(minDistance(grid, sourceRow, sourceCol));}} // This code is contributed by Arnab Kundu # Python 3 implementation of the approach row = 5col = 5 # Global variables for grid, minDistance and visited arrayminDistance = [[0 for i in range(col+1)] for j in range(row+1)]visited = [[0 for i in range(col+1)]for j in range(row+1)] # Queue for BFSque = [[0,0]] # Function to find whether the move is valid or notdef isValid(grid,i,j): if (i < 0 or j < 0 or j >= col or i >= row or grid[i][j] or visited[i][j]): return False return True # Function to return the minimum distance# from source to the end of the griddef minDistance1(grid,sourceRow,sourceCol): # If source is one of the destinations if ((sourceCol == 0 and sourceRow == 0) or (sourceCol == col - 1 and sourceRow == 0) or (sourceCol == 0 or sourceRow == row - 1) or (sourceCol == col - 1 and sourceRow == row - 1)): return 0 # Set minimum value minFromSource = row * col # Precalculate minDistance of each grid with R * C for i in range(row): for j in range(col): minDistance[i][j] = row * col # Insert source position in queue que.append([sourceRow, sourceCol]) # Update minimum distance to visit source minDistance[sourceRow][sourceCol] = 0 # Set source to visited visited[sourceRow][sourceCol] = 1 # BFS approach for calculating the minDistance # of each cell from source while (len(que)!=0): # Iterate over all four cells adjacent # to current cell cell = que[0] # Initialize position of current cell cellRow = cell[0] cellCol = cell[1] # Cell below the current cell if (isValid(grid, cellRow + 1, cellCol)): # Push new cell to the queue que.append([cellRow + 1, cellCol]) # Update one of its neightbor's distance minDistance[cellRow + 1][cellCol] = min(minDistance[cellRow + 1][cellCol], minDistance[cellRow][cellCol] + 1) visited[cellRow + 1][cellCol] = 1 # Above the current cell if (isValid(grid, cellRow - 1, cellCol)): que.append([cellRow - 1, cellCol]) minDistance[cellRow - 1][cellCol] = min(minDistance[cellRow - 1][cellCol], minDistance[cellRow][cellCol] + 1) visited[cellRow - 1][cellCol] = 1 # Right cell if (isValid(grid, cellRow, cellCol + 1)): que.append([cellRow, cellCol + 1]) minDistance[cellRow][cellCol + 1] = min(minDistance[cellRow][cellCol + 1], minDistance[cellRow][cellCol] + 1) visited[cellRow][cellCol + 1] = 1 # Left cell if (isValid(grid, cellRow, cellCol - 1)): que.append([cellRow, cellCol - 1]) minDistance[cellRow][cellCol - 1]= min(minDistance[cellRow][cellCol - 1], minDistance[cellRow][cellCol] + 1) visited[cellRow][cellCol - 1] = 1 # Pop the visited cell que.remove(que[0]) # Minimum distance to the corner # of the first row, first column minFromSource = min(minFromSource, minDistance[0][0]) # Minimum distance to the corner # of the last row, first column minFromSource = min(minFromSource, minDistance[row - 1][0]) # Minimum distance to the corner # of the last row, last column minFromSource = min(minFromSource,minDistance[row - 1][col - 1]) # Minimum distance to the corner # of the first row, last column minFromSource = min(minFromSource, minDistance[0][col - 1]) # If no path exists if (minFromSource == row * col): return -1 # Return the minimum distance return minFromSource # Driver codeif __name__ == '__main__': sourceRow = 3 sourceCol = 3 grid = [[1, 1, 1, 0, 0], [0, 0, 1, 0, 1], [0, 0, 1, 0, 1], [1, 0, 0, 0, 1], [1, 1, 0, 1, 0]] print(minDistance1(grid, sourceRow, sourceCol)) # This code is contributed by# Surendra_Gangwar // C# implementation of above approachusing System;using System.Collections;using System.Collections.Generic; class GFG { // Global variables for grid, minDistance and visited // array static class Globals { // global int public static int row = 5; public static int col = 5; // Global variables for grid, minDistance and // visited array public static int[, ] minDistance = new int[row + 1, col + 1]; public static int[, ] visited = new int[row + 1, col + 1]; // Queue for BFS public static Queue<KeyValuePair<int, int> > que = new Queue<KeyValuePair<int, int> >(); } // Function to find whether the move is valid or not static bool isValid(int[, ] grid, int i, int j) { if (i < 0 || j < 0 || j >= Globals.col || i >= Globals.row || grid[i, j] != 0 || Globals.visited[i, j] != 0) return false; return true; } // Function to return the minimum distance // from source to the end of the grid static int minDistance1(int[, ] grid, int sourceRow, int sourceCol) { // If source is one of the destinations if ((sourceCol == 0 && sourceRow == 0) || (sourceCol == Globals.col - 1 && sourceRow == 0) || (sourceCol == 0 && sourceRow == Globals.row - 1) || (sourceCol == Globals.col - 1 && sourceRow == Globals.row - 1)) return 0; // Set minimum value int minFromSource = Globals.row * Globals.col; // Precalculate minDistance of each grid with R * C for (int i = 0; i < Globals.row; i++) for (int j = 0; j < Globals.col; j++) Globals.minDistance[i, j] = Globals.row * Globals.col; // Insert source position in queue Globals.que.Enqueue(new KeyValuePair<int, int>( sourceRow, sourceCol)); // Update minimum distance to visit source Globals.minDistance[sourceRow, sourceCol] = 0; // Set source to visited Globals.visited[sourceRow, sourceCol] = 1; // BFS approach for calculating the minDistance // of each cell from source while (Globals.que.Count > 0) { // Iterate over all four cells adjacent // to current cell KeyValuePair<int, int> cell = Globals.que.Dequeue(); // Initialize position of current cell int cellRow = cell.Key; int cellCol = cell.Value; // Cell below the current cell if (isValid(grid, cellRow + 1, cellCol)) { // Push new cell to the queue Globals.que.Enqueue( new KeyValuePair<int, int>(cellRow + 1, cellCol)); // Update one of its neightbor's distance Globals.minDistance[cellRow + 1, cellCol] = Math.Min( Globals.minDistance[cellRow + 1, cellCol], Globals.minDistance[cellRow, cellCol] + 1); Globals.visited[cellRow + 1, cellCol] = 1; } // Above the current cell if (isValid(grid, cellRow - 1, cellCol)) { Globals.que.Enqueue( new KeyValuePair<int, int>(cellRow - 1, cellCol)); Globals.minDistance[cellRow - 1, cellCol] = Math.Min( Globals.minDistance[cellRow - 1, cellCol], Globals.minDistance[cellRow, cellCol] + 1); Globals.visited[cellRow - 1, cellCol] = 1; } // Right cell if (isValid(grid, cellRow, cellCol + 1)) { Globals.que.Enqueue( new KeyValuePair<int, int>( cellRow, cellCol + 1)); Globals.minDistance[cellRow, cellCol + 1] = Math.Min( Globals.minDistance[cellRow, cellCol + 1], Globals.minDistance[cellRow, cellCol] + 1); Globals.visited[cellRow, cellCol + 1] = 1; } // Left cell if (isValid(grid, cellRow, cellCol - 1)) { Globals.que.Enqueue( new KeyValuePair<int, int>( cellRow, cellCol - 1)); Globals.minDistance[cellRow, cellCol - 1] = Math.Min( Globals.minDistance[cellRow, cellCol - 1], Globals.minDistance[cellRow, cellCol] + 1); Globals.visited[cellRow, cellCol - 1] = 1; } } // Minimum distance to the corner // of the first row, first column minFromSource = Math.Min(minFromSource, Globals.minDistance[0, 0]); // Minimum distance to the corner // of the last row, first column minFromSource = Math.Min( minFromSource, Globals.minDistance[Globals.row - 1, 0]); // Minimum distance to the corner // of the last row, last column minFromSource = Math.Min( minFromSource, Globals.minDistance[Globals.row - 1, Globals.col - 1]); // Minimum distance to the corner // of the first row, last column minFromSource = Math.Min( minFromSource, Globals.minDistance[0, Globals.col - 1]); // If no path exists if (minFromSource == Globals.row * Globals.col) return -1; // Return the minimum distance return minFromSource; } // Driver Code static void Main() { int sourceRow = 3, sourceCol = 3; int[, ] grid = { { 1, 1, 1, 0, 0 }, { 0, 0, 1, 0, 1 }, { 0, 0, 1, 0, 1 }, { 1, 0, 0, 0, 1 }, { 1, 1, 0, 1, 0 } }; Console.WriteLine( minDistance1(grid, sourceRow, sourceCol)); }} // The code is contributed by Gautam goel (gautamgoel962) <script>// Javascript implementation of the approach // Pair classclass Pair{ constructor(a, b) { this.first = a; this.second = b; }} let row = 5;let col = 5; // Global variables for grid, minDistance and visited arraylet minDistance = new Array(row + 1);let visited = new Array(row + 1);for(let i = 0; i < row + 1; i++){ minDistance[i] = new Array(col+1); visited[i] = new Array(col+1); for(let j = 0; j < col + 1; j++) { minDistance[i][j] = 0; visited[i][j] = 0; } } // Queue for BFSlet que = []; // Function to find whether the move is valid or notfunction isValid(grid,i,j){ if (i < 0 || j < 0 || j >= col || i >= row || grid[i][j] != 0 || visited[i][j] != 0) return false; return true;} // Function to return the minimum distance// from source to the end of the gridfunction _minDistance(grid,sourceRow,sourceCol){ // If source is one of the destinations if ((sourceCol == 0 && sourceRow == 0) || (sourceCol == col - 1 && sourceRow == 0) || (sourceCol == 0 && sourceRow == row - 1) || (sourceCol == col - 1 && sourceRow == row - 1)) return 0; // Set minimum value let minFromSource = row * col; // Precalculate minDistance of each grid with R * C for (let i = 0; i < row; i++) for (let j = 0; j < col; j++) minDistance[i][j] = row * col; // Insert source position in queue que.push(new Pair(sourceRow, sourceCol)); // Update minimum distance to visit source minDistance[sourceRow][sourceCol] = 0; // Set source to visited visited[sourceRow][sourceCol] = 1; // BFS approach for calculating the minDistance // of each cell from source while (que.length > 0) { // Iterate over all four cells adjacent // to current cell let cell = que[0]; // Initialize position of current cell let cellRow = cell.first; let cellCol = cell.second; // Cell below the current cell if (isValid(grid, cellRow + 1, cellCol)) { // add new cell to the queue que.push(new Pair(cellRow + 1, cellCol)); // Update one of its neightbor's distance minDistance[cellRow + 1][cellCol] = Math.min(minDistance[cellRow + 1][cellCol], minDistance[cellRow][cellCol] + 1); visited[cellRow + 1][cellCol] = 1; } // Above the current cell if (isValid(grid, cellRow - 1, cellCol)) { que.push(new Pair(cellRow - 1, cellCol)); minDistance[cellRow - 1][cellCol] = Math.min(minDistance[cellRow - 1][cellCol], minDistance[cellRow][cellCol] + 1); visited[cellRow - 1][cellCol] = 1; } // Right cell if (isValid(grid, cellRow, cellCol + 1)) { que.push(new Pair(cellRow, cellCol + 1)); minDistance[cellRow][cellCol + 1] = Math.min(minDistance[cellRow][cellCol + 1], minDistance[cellRow][cellCol] + 1); visited[cellRow][cellCol + 1] = 1; } // Left cell if (isValid(grid, cellRow, cellCol - 1)) { que.push(new Pair(cellRow, cellCol - 1)); minDistance[cellRow][cellCol - 1] = Math.min(minDistance[cellRow][cellCol - 1], minDistance[cellRow][cellCol] + 1); visited[cellRow][cellCol - 1] = 1; } // remove the visited cell que.shift(); } let i; // Minimum distance to the corner // of the first row, first column minFromSource = Math.min(minFromSource, minDistance[0][0]); // Minimum distance to the corner // of the last row, first column minFromSource = Math.min(minFromSource, minDistance[row - 1][0]); // Minimum distance to the corner // of the last row, last column minFromSource = Math.min(minFromSource, minDistance[row - 1][col - 1]); // Minimum distance to the corner // of the first row, last column minFromSource = Math.min(minFromSource, minDistance[0][col - 1]); // If no path exists if (minFromSource == row * col) return -1; // Return the minimum distance return minFromSource;} // Driver codelet sourceRow = 3, sourceCol = 3;let grid = [[1, 1, 1, 0, 0], [0, 0, 1, 0, 1], [0, 0, 1, 0, 1], [1, 0, 0, 0, 1], [1, 1, 0, 1, 0]];document.write(_minDistance(grid, sourceRow, sourceCol)); // This code is contributed by avanitrachhadiya2155</script> 4 SURENDRA_GANGWAR Akanksha_Rai andrew1234 avanitrachhadiya2155 gautamgoel962 BFS Geometric Graph Matrix Queue Matrix Graph Queue Geometric BFS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Rotation of a point about another point in C++ Maximum Manhattan distance between a distinct pair from N coordinates C++ Program to Illustrate Trigonometric functions Total area of two overlapping rectangles Largest area possible after removal of a series of horizontal & vertical bars Breadth First Search or BFS for a Graph Depth First Search or DFS for a Graph Dijkstra's shortest path algorithm | Greedy Algo-7 Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5 Graph and its representations
[ { "code": null, "e": 54, "s": 26, "text": "\n16 Jun, 2022" }, { "code": null, "e": 381, "s": 54, "text": "Given a binary grid of order r * c and an initial position. The task is to find the minimum distance from the source to get to the any corner of the grid. A move can be made to a cell grid[i][j] only if grid[i][j] = 0 and only left, right, up and down movements are permitted. If no valid path exists then print -1.Examples: " }, { "code": null, "e": 485, "s": 381, "text": "Input: i = 1, j = 1, grid[][] = {{0, 0, 1}, {0, 0, 0}, {1, 1, 1}} Output: 2 (1, 1) -> (1, 0) -> (0, 0) " }, { "code": null, "e": 586, "s": 485, "text": "Input: i = 0, j = 0, grid[][] = {{0, 1}, {1, 1}} Output: 0 Source is already a corner of the grid. " }, { "code": null, "e": 600, "s": 588, "text": "Approach: " }, { "code": null, "e": 653, "s": 600, "text": "If source is already any of the corner then print 0." }, { "code": null, "e": 945, "s": 653, "text": "Start traversing the grid starting with source using BFS as : Insert cell position in queue.Pop element from queue and mark it visited.For each valid move adjacent to popped one, insert the cell position into queue.On each move, update the minimum distance of the cell from initial position." }, { "code": null, "e": 976, "s": 945, "text": "Insert cell position in queue." }, { "code": null, "e": 1020, "s": 976, "text": "Pop element from queue and mark it visited." }, { "code": null, "e": 1101, "s": 1020, "text": "For each valid move adjacent to popped one, insert the cell position into queue." }, { "code": null, "e": 1178, "s": 1101, "text": "On each move, update the minimum distance of the cell from initial position." }, { "code": null, "e": 1266, "s": 1178, "text": "After the completion of the BFS, find the minimum distance from source to every corner." }, { "code": null, "e": 1308, "s": 1266, "text": "Print the minimum among these in the end." }, { "code": null, "e": 1361, "s": 1308, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 1365, "s": 1361, "text": "C++" }, { "code": null, "e": 1370, "s": 1365, "text": "Java" }, { "code": null, "e": 1378, "s": 1370, "text": "Python3" }, { "code": null, "e": 1381, "s": 1378, "text": "C#" }, { "code": null, "e": 1392, "s": 1381, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std;#define row 5#define col 5 // Global variables for grid, minDistance and visited arrayint minDistance[row + 1][col + 1], visited[row + 1][col + 1]; // Queue for BFSqueue<pair<int, int> > que; // Function to find whether the move is valid or notbool isValid(int grid[][col], int i, int j){ if (i < 0 || j < 0 || j >= col || i >= row || grid[i][j] || visited[i][j]) return false; return true;} // Function to return the minimum distance// from source to the end of the gridint minDistance(int grid[][col], int sourceRow, int sourceCol){ // If source is one of the destinations if ((sourceCol == 0 && sourceRow == 0) || (sourceCol == col - 1 && sourceRow == 0) || (sourceCol == 0 && sourceRow == row - 1) || (sourceCol == col - 1 && sourceRow == row - 1)) return 0; // Set minimum value int minFromSource = row * col; // Precalculate minDistance of each grid with R * C for (int i = 0; i < row; i++) for (int j = 0; j < col; j++) minDistance[i][j] = row * col; // Insert source position in queue que.push(make_pair(sourceRow, sourceCol)); // Update minimum distance to visit source minDistance[sourceRow][sourceCol] = 0; // Set source to visited visited[sourceRow][sourceCol] = 1; // BFS approach for calculating the minDistance // of each cell from source while (!que.empty()) { // Iterate over all four cells adjacent // to current cell pair<int, int> cell = que.front(); // Initialize position of current cell int cellRow = cell.first; int cellCol = cell.second; // Cell below the current cell if (isValid(grid, cellRow + 1, cellCol)) { // Push new cell to the queue que.push(make_pair(cellRow + 1, cellCol)); // Update one of its neightbor's distance minDistance[cellRow + 1][cellCol] = min(minDistance[cellRow + 1][cellCol], minDistance[cellRow][cellCol] + 1); visited[cellRow + 1][cellCol] = 1; } // Above the current cell if (isValid(grid, cellRow - 1, cellCol)) { que.push(make_pair(cellRow - 1, cellCol)); minDistance[cellRow - 1][cellCol] = min(minDistance[cellRow - 1][cellCol], minDistance[cellRow][cellCol] + 1); visited[cellRow - 1][cellCol] = 1; } // Right cell if (isValid(grid, cellRow, cellCol + 1)) { que.push(make_pair(cellRow, cellCol + 1)); minDistance[cellRow][cellCol + 1] = min(minDistance[cellRow][cellCol + 1], minDistance[cellRow][cellCol] + 1); visited[cellRow][cellCol + 1] = 1; } // Left cell if (isValid(grid, cellRow, cellCol - 1)) { que.push(make_pair(cellRow, cellCol - 1)); minDistance[cellRow][cellCol - 1] = min(minDistance[cellRow][cellCol - 1], minDistance[cellRow][cellCol] + 1); visited[cellRow][cellCol - 1] = 1; } // Pop the visited cell que.pop(); } int i; // Minimum distance to the corner // of the first row, first column minFromSource = min(minFromSource, minDistance[0][0]); // Minimum distance to the corner // of the last row, first column minFromSource = min(minFromSource, minDistance[row - 1][0]); // Minimum distance to the corner // of the last row, last column minFromSource = min(minFromSource, minDistance[row - 1][col - 1]); // Minimum distance to the corner // of the first row, last column minFromSource = min(minFromSource, minDistance[0][col - 1]); // If no path exists if (minFromSource == row * col) return -1; // Return the minimum distance return minFromSource;} // Driver codeint main(){ int sourceRow = 3, sourceCol = 3; int grid[row][col] = { 1, 1, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 0 }; cout << minDistance(grid, sourceRow, sourceCol); return 0;}", "e": 5798, "s": 1392, "text": null }, { "code": "// Java implementation of the approachimport java.util.*;class GFG{ // Pair classstatic class Pair{ int first,second; Pair(int a, int b) { first = a; second = b; }} static int row = 5;static int col = 5; // Global variables for grid, minDistance and visited arraystatic int minDistance[][] = new int[row + 1][col + 1], visited[][] = new int[row + 1][col + 1]; // Queue for BFSstatic Queue<Pair > que = new LinkedList<>(); // Function to find whether the move is valid or notstatic boolean isValid(int grid[][], int i, int j){ if (i < 0 || j < 0 || j >= col || i >= row || grid[i][j] != 0 || visited[i][j] != 0) return false; return true;} // Function to return the minimum distance// from source to the end of the gridstatic int minDistance(int grid[][], int sourceRow, int sourceCol){ // If source is one of the destinations if ((sourceCol == 0 && sourceRow == 0) || (sourceCol == col - 1 && sourceRow == 0) || (sourceCol == 0 && sourceRow == row - 1) || (sourceCol == col - 1 && sourceRow == row - 1)) return 0; // Set minimum value int minFromSource = row * col; // Precalculate minDistance of each grid with R * C for (int i = 0; i < row; i++) for (int j = 0; j < col; j++) minDistance[i][j] = row * col; // Insert source position in queue que.add(new Pair(sourceRow, sourceCol)); // Update minimum distance to visit source minDistance[sourceRow][sourceCol] = 0; // Set source to visited visited[sourceRow][sourceCol] = 1; // BFS approach for calculating the minDistance // of each cell from source while (que.size() > 0) { // Iterate over all four cells adjacent // to current cell Pair cell = que.peek(); // Initialize position of current cell int cellRow = cell.first; int cellCol = cell.second; // Cell below the current cell if (isValid(grid, cellRow + 1, cellCol)) { // add new cell to the queue que.add(new Pair(cellRow + 1, cellCol)); // Update one of its neightbor's distance minDistance[cellRow + 1][cellCol] = Math.min(minDistance[cellRow + 1][cellCol], minDistance[cellRow][cellCol] + 1); visited[cellRow + 1][cellCol] = 1; } // Above the current cell if (isValid(grid, cellRow - 1, cellCol)) { que.add(new Pair(cellRow - 1, cellCol)); minDistance[cellRow - 1][cellCol] = Math.min(minDistance[cellRow - 1][cellCol], minDistance[cellRow][cellCol] + 1); visited[cellRow - 1][cellCol] = 1; } // Right cell if (isValid(grid, cellRow, cellCol + 1)) { que.add(new Pair(cellRow, cellCol + 1)); minDistance[cellRow][cellCol + 1] = Math.min(minDistance[cellRow][cellCol + 1], minDistance[cellRow][cellCol] + 1); visited[cellRow][cellCol + 1] = 1; } // Left cell if (isValid(grid, cellRow, cellCol - 1)) { que.add(new Pair(cellRow, cellCol - 1)); minDistance[cellRow][cellCol - 1] = Math.min(minDistance[cellRow][cellCol - 1], minDistance[cellRow][cellCol] + 1); visited[cellRow][cellCol - 1] = 1; } // remove the visited cell que.remove(); } int i; // Minimum distance to the corner // of the first row, first column minFromSource = Math.min(minFromSource, minDistance[0][0]); // Minimum distance to the corner // of the last row, first column minFromSource = Math.min(minFromSource, minDistance[row - 1][0]); // Minimum distance to the corner // of the last row, last column minFromSource = Math.min(minFromSource, minDistance[row - 1][col - 1]); // Minimum distance to the corner // of the first row, last column minFromSource = Math.min(minFromSource, minDistance[0][col - 1]); // If no path exists if (minFromSource == row * col) return -1; // Return the minimum distance return minFromSource;} // Driver codepublic static void main(String args[]){ int sourceRow = 3, sourceCol = 3; int grid[][] = { {1, 1, 1, 0, 0}, {0, 0, 1, 0, 1}, {0, 0, 1, 0, 1}, {1, 0, 0, 0, 1}, {1, 1, 0, 1, 0} }; System.out.println(minDistance(grid, sourceRow, sourceCol));}} // This code is contributed by Arnab Kundu", "e": 10523, "s": 5798, "text": null }, { "code": "# Python 3 implementation of the approach row = 5col = 5 # Global variables for grid, minDistance and visited arrayminDistance = [[0 for i in range(col+1)] for j in range(row+1)]visited = [[0 for i in range(col+1)]for j in range(row+1)] # Queue for BFSque = [[0,0]] # Function to find whether the move is valid or notdef isValid(grid,i,j): if (i < 0 or j < 0 or j >= col or i >= row or grid[i][j] or visited[i][j]): return False return True # Function to return the minimum distance# from source to the end of the griddef minDistance1(grid,sourceRow,sourceCol): # If source is one of the destinations if ((sourceCol == 0 and sourceRow == 0) or (sourceCol == col - 1 and sourceRow == 0) or (sourceCol == 0 or sourceRow == row - 1) or (sourceCol == col - 1 and sourceRow == row - 1)): return 0 # Set minimum value minFromSource = row * col # Precalculate minDistance of each grid with R * C for i in range(row): for j in range(col): minDistance[i][j] = row * col # Insert source position in queue que.append([sourceRow, sourceCol]) # Update minimum distance to visit source minDistance[sourceRow][sourceCol] = 0 # Set source to visited visited[sourceRow][sourceCol] = 1 # BFS approach for calculating the minDistance # of each cell from source while (len(que)!=0): # Iterate over all four cells adjacent # to current cell cell = que[0] # Initialize position of current cell cellRow = cell[0] cellCol = cell[1] # Cell below the current cell if (isValid(grid, cellRow + 1, cellCol)): # Push new cell to the queue que.append([cellRow + 1, cellCol]) # Update one of its neightbor's distance minDistance[cellRow + 1][cellCol] = min(minDistance[cellRow + 1][cellCol], minDistance[cellRow][cellCol] + 1) visited[cellRow + 1][cellCol] = 1 # Above the current cell if (isValid(grid, cellRow - 1, cellCol)): que.append([cellRow - 1, cellCol]) minDistance[cellRow - 1][cellCol] = min(minDistance[cellRow - 1][cellCol], minDistance[cellRow][cellCol] + 1) visited[cellRow - 1][cellCol] = 1 # Right cell if (isValid(grid, cellRow, cellCol + 1)): que.append([cellRow, cellCol + 1]) minDistance[cellRow][cellCol + 1] = min(minDistance[cellRow][cellCol + 1], minDistance[cellRow][cellCol] + 1) visited[cellRow][cellCol + 1] = 1 # Left cell if (isValid(grid, cellRow, cellCol - 1)): que.append([cellRow, cellCol - 1]) minDistance[cellRow][cellCol - 1]= min(minDistance[cellRow][cellCol - 1], minDistance[cellRow][cellCol] + 1) visited[cellRow][cellCol - 1] = 1 # Pop the visited cell que.remove(que[0]) # Minimum distance to the corner # of the first row, first column minFromSource = min(minFromSource, minDistance[0][0]) # Minimum distance to the corner # of the last row, first column minFromSource = min(minFromSource, minDistance[row - 1][0]) # Minimum distance to the corner # of the last row, last column minFromSource = min(minFromSource,minDistance[row - 1][col - 1]) # Minimum distance to the corner # of the first row, last column minFromSource = min(minFromSource, minDistance[0][col - 1]) # If no path exists if (minFromSource == row * col): return -1 # Return the minimum distance return minFromSource # Driver codeif __name__ == '__main__': sourceRow = 3 sourceCol = 3 grid = [[1, 1, 1, 0, 0], [0, 0, 1, 0, 1], [0, 0, 1, 0, 1], [1, 0, 0, 0, 1], [1, 1, 0, 1, 0]] print(minDistance1(grid, sourceRow, sourceCol)) # This code is contributed by# Surendra_Gangwar", "e": 14580, "s": 10523, "text": null }, { "code": "// C# implementation of above approachusing System;using System.Collections;using System.Collections.Generic; class GFG { // Global variables for grid, minDistance and visited // array static class Globals { // global int public static int row = 5; public static int col = 5; // Global variables for grid, minDistance and // visited array public static int[, ] minDistance = new int[row + 1, col + 1]; public static int[, ] visited = new int[row + 1, col + 1]; // Queue for BFS public static Queue<KeyValuePair<int, int> > que = new Queue<KeyValuePair<int, int> >(); } // Function to find whether the move is valid or not static bool isValid(int[, ] grid, int i, int j) { if (i < 0 || j < 0 || j >= Globals.col || i >= Globals.row || grid[i, j] != 0 || Globals.visited[i, j] != 0) return false; return true; } // Function to return the minimum distance // from source to the end of the grid static int minDistance1(int[, ] grid, int sourceRow, int sourceCol) { // If source is one of the destinations if ((sourceCol == 0 && sourceRow == 0) || (sourceCol == Globals.col - 1 && sourceRow == 0) || (sourceCol == 0 && sourceRow == Globals.row - 1) || (sourceCol == Globals.col - 1 && sourceRow == Globals.row - 1)) return 0; // Set minimum value int minFromSource = Globals.row * Globals.col; // Precalculate minDistance of each grid with R * C for (int i = 0; i < Globals.row; i++) for (int j = 0; j < Globals.col; j++) Globals.minDistance[i, j] = Globals.row * Globals.col; // Insert source position in queue Globals.que.Enqueue(new KeyValuePair<int, int>( sourceRow, sourceCol)); // Update minimum distance to visit source Globals.minDistance[sourceRow, sourceCol] = 0; // Set source to visited Globals.visited[sourceRow, sourceCol] = 1; // BFS approach for calculating the minDistance // of each cell from source while (Globals.que.Count > 0) { // Iterate over all four cells adjacent // to current cell KeyValuePair<int, int> cell = Globals.que.Dequeue(); // Initialize position of current cell int cellRow = cell.Key; int cellCol = cell.Value; // Cell below the current cell if (isValid(grid, cellRow + 1, cellCol)) { // Push new cell to the queue Globals.que.Enqueue( new KeyValuePair<int, int>(cellRow + 1, cellCol)); // Update one of its neightbor's distance Globals.minDistance[cellRow + 1, cellCol] = Math.Min( Globals.minDistance[cellRow + 1, cellCol], Globals.minDistance[cellRow, cellCol] + 1); Globals.visited[cellRow + 1, cellCol] = 1; } // Above the current cell if (isValid(grid, cellRow - 1, cellCol)) { Globals.que.Enqueue( new KeyValuePair<int, int>(cellRow - 1, cellCol)); Globals.minDistance[cellRow - 1, cellCol] = Math.Min( Globals.minDistance[cellRow - 1, cellCol], Globals.minDistance[cellRow, cellCol] + 1); Globals.visited[cellRow - 1, cellCol] = 1; } // Right cell if (isValid(grid, cellRow, cellCol + 1)) { Globals.que.Enqueue( new KeyValuePair<int, int>( cellRow, cellCol + 1)); Globals.minDistance[cellRow, cellCol + 1] = Math.Min( Globals.minDistance[cellRow, cellCol + 1], Globals.minDistance[cellRow, cellCol] + 1); Globals.visited[cellRow, cellCol + 1] = 1; } // Left cell if (isValid(grid, cellRow, cellCol - 1)) { Globals.que.Enqueue( new KeyValuePair<int, int>( cellRow, cellCol - 1)); Globals.minDistance[cellRow, cellCol - 1] = Math.Min( Globals.minDistance[cellRow, cellCol - 1], Globals.minDistance[cellRow, cellCol] + 1); Globals.visited[cellRow, cellCol - 1] = 1; } } // Minimum distance to the corner // of the first row, first column minFromSource = Math.Min(minFromSource, Globals.minDistance[0, 0]); // Minimum distance to the corner // of the last row, first column minFromSource = Math.Min( minFromSource, Globals.minDistance[Globals.row - 1, 0]); // Minimum distance to the corner // of the last row, last column minFromSource = Math.Min( minFromSource, Globals.minDistance[Globals.row - 1, Globals.col - 1]); // Minimum distance to the corner // of the first row, last column minFromSource = Math.Min( minFromSource, Globals.minDistance[0, Globals.col - 1]); // If no path exists if (minFromSource == Globals.row * Globals.col) return -1; // Return the minimum distance return minFromSource; } // Driver Code static void Main() { int sourceRow = 3, sourceCol = 3; int[, ] grid = { { 1, 1, 1, 0, 0 }, { 0, 0, 1, 0, 1 }, { 0, 0, 1, 0, 1 }, { 1, 0, 0, 0, 1 }, { 1, 1, 0, 1, 0 } }; Console.WriteLine( minDistance1(grid, sourceRow, sourceCol)); }} // The code is contributed by Gautam goel (gautamgoel962)", "e": 21266, "s": 14580, "text": null }, { "code": "<script>// Javascript implementation of the approach // Pair classclass Pair{ constructor(a, b) { this.first = a; this.second = b; }} let row = 5;let col = 5; // Global variables for grid, minDistance and visited arraylet minDistance = new Array(row + 1);let visited = new Array(row + 1);for(let i = 0; i < row + 1; i++){ minDistance[i] = new Array(col+1); visited[i] = new Array(col+1); for(let j = 0; j < col + 1; j++) { minDistance[i][j] = 0; visited[i][j] = 0; } } // Queue for BFSlet que = []; // Function to find whether the move is valid or notfunction isValid(grid,i,j){ if (i < 0 || j < 0 || j >= col || i >= row || grid[i][j] != 0 || visited[i][j] != 0) return false; return true;} // Function to return the minimum distance// from source to the end of the gridfunction _minDistance(grid,sourceRow,sourceCol){ // If source is one of the destinations if ((sourceCol == 0 && sourceRow == 0) || (sourceCol == col - 1 && sourceRow == 0) || (sourceCol == 0 && sourceRow == row - 1) || (sourceCol == col - 1 && sourceRow == row - 1)) return 0; // Set minimum value let minFromSource = row * col; // Precalculate minDistance of each grid with R * C for (let i = 0; i < row; i++) for (let j = 0; j < col; j++) minDistance[i][j] = row * col; // Insert source position in queue que.push(new Pair(sourceRow, sourceCol)); // Update minimum distance to visit source minDistance[sourceRow][sourceCol] = 0; // Set source to visited visited[sourceRow][sourceCol] = 1; // BFS approach for calculating the minDistance // of each cell from source while (que.length > 0) { // Iterate over all four cells adjacent // to current cell let cell = que[0]; // Initialize position of current cell let cellRow = cell.first; let cellCol = cell.second; // Cell below the current cell if (isValid(grid, cellRow + 1, cellCol)) { // add new cell to the queue que.push(new Pair(cellRow + 1, cellCol)); // Update one of its neightbor's distance minDistance[cellRow + 1][cellCol] = Math.min(minDistance[cellRow + 1][cellCol], minDistance[cellRow][cellCol] + 1); visited[cellRow + 1][cellCol] = 1; } // Above the current cell if (isValid(grid, cellRow - 1, cellCol)) { que.push(new Pair(cellRow - 1, cellCol)); minDistance[cellRow - 1][cellCol] = Math.min(minDistance[cellRow - 1][cellCol], minDistance[cellRow][cellCol] + 1); visited[cellRow - 1][cellCol] = 1; } // Right cell if (isValid(grid, cellRow, cellCol + 1)) { que.push(new Pair(cellRow, cellCol + 1)); minDistance[cellRow][cellCol + 1] = Math.min(minDistance[cellRow][cellCol + 1], minDistance[cellRow][cellCol] + 1); visited[cellRow][cellCol + 1] = 1; } // Left cell if (isValid(grid, cellRow, cellCol - 1)) { que.push(new Pair(cellRow, cellCol - 1)); minDistance[cellRow][cellCol - 1] = Math.min(minDistance[cellRow][cellCol - 1], minDistance[cellRow][cellCol] + 1); visited[cellRow][cellCol - 1] = 1; } // remove the visited cell que.shift(); } let i; // Minimum distance to the corner // of the first row, first column minFromSource = Math.min(minFromSource, minDistance[0][0]); // Minimum distance to the corner // of the last row, first column minFromSource = Math.min(minFromSource, minDistance[row - 1][0]); // Minimum distance to the corner // of the last row, last column minFromSource = Math.min(minFromSource, minDistance[row - 1][col - 1]); // Minimum distance to the corner // of the first row, last column minFromSource = Math.min(minFromSource, minDistance[0][col - 1]); // If no path exists if (minFromSource == row * col) return -1; // Return the minimum distance return minFromSource;} // Driver codelet sourceRow = 3, sourceCol = 3;let grid = [[1, 1, 1, 0, 0], [0, 0, 1, 0, 1], [0, 0, 1, 0, 1], [1, 0, 0, 0, 1], [1, 1, 0, 1, 0]];document.write(_minDistance(grid, sourceRow, sourceCol)); // This code is contributed by avanitrachhadiya2155</script>", "e": 26006, "s": 21266, "text": null }, { "code": null, "e": 26008, "s": 26006, "text": "4" }, { "code": null, "e": 26027, "s": 26010, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 26040, "s": 26027, "text": "Akanksha_Rai" }, { "code": null, "e": 26051, "s": 26040, "text": "andrew1234" }, { "code": null, "e": 26072, "s": 26051, "text": "avanitrachhadiya2155" }, { "code": null, "e": 26086, "s": 26072, "text": "gautamgoel962" }, { "code": null, "e": 26090, "s": 26086, "text": "BFS" }, { "code": null, "e": 26100, "s": 26090, "text": "Geometric" }, { "code": null, "e": 26106, "s": 26100, "text": "Graph" }, { "code": null, "e": 26113, "s": 26106, "text": "Matrix" }, { "code": null, "e": 26119, "s": 26113, "text": "Queue" }, { "code": null, "e": 26126, "s": 26119, "text": "Matrix" }, { "code": null, "e": 26132, "s": 26126, "text": "Graph" }, { "code": null, "e": 26138, "s": 26132, "text": "Queue" }, { "code": null, "e": 26148, "s": 26138, "text": "Geometric" }, { "code": null, "e": 26152, "s": 26148, "text": "BFS" }, { "code": null, "e": 26250, "s": 26152, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26297, "s": 26250, "text": "Rotation of a point about another point in C++" }, { "code": null, "e": 26367, "s": 26297, "text": "Maximum Manhattan distance between a distinct pair from N coordinates" }, { "code": null, "e": 26417, "s": 26367, "text": "C++ Program to Illustrate Trigonometric functions" }, { "code": null, "e": 26458, "s": 26417, "text": "Total area of two overlapping rectangles" }, { "code": null, "e": 26536, "s": 26458, "text": "Largest area possible after removal of a series of horizontal & vertical bars" }, { "code": null, "e": 26576, "s": 26536, "text": "Breadth First Search or BFS for a Graph" }, { "code": null, "e": 26614, "s": 26576, "text": "Depth First Search or DFS for a Graph" }, { "code": null, "e": 26665, "s": 26614, "text": "Dijkstra's shortest path algorithm | Greedy Algo-7" }, { "code": null, "e": 26716, "s": 26665, "text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5" } ]
How to Select Rows from Pandas DataFrame?
10 Jul, 2020 pandas.DataFrame.loc is a function used to select rows from Pandas DataFrame based on the condition provided. In this article, let’s learn to select the rows from Pandas DataFrame based on some conditions. Syntax: df.loc[df[β€˜cname’] β€˜condition’] Parameters:df: represents data framecname: represents column namecondition: represents condition on which rows has to be selected Example 1: # Importing pandas as pdfrom pandas import DataFrame # Creating a data framecart = {'Product': ['Mobile', 'AC', 'Laptop', 'TV', 'Football'], 'Type': ['Electronic', 'HomeAppliances', 'Electronic', 'HomeAppliances', 'Sports'], 'Price': [10000, 35000, 50000, 30000, 799] } df = DataFrame(cart, columns = ['Product', 'Type', 'Price']) # Print original data frameprint("Original data frame:\n")print(df) # Selecting the product of Electronic Typeselect_prod = df.loc[df['Type'] == 'Electronic'] print("\n") # Print selected rows based on the conditionprint("Selecting rows:\n")print (select_prod) Output:Example 2: # Importing pandas as pdfrom pandas import DataFrame # Creating a data framecart = {'Product': ['Mobile', 'AC', 'Laptop', 'TV', 'Football'], 'Type': ['Electronic', 'HomeAppliances', 'Electronic', 'HomeAppliances', 'Sports'], 'Price': [10000, 35000, 50000, 30000, 799] } df = DataFrame(cart, columns = ['Product', 'Type', 'Price']) # Print original data frameprint("Original data frame:\n")print(df) # Selecting the product of HomeAppliances Typeselect_prod = df.loc[df['Type'] == 'HomeAppliances'] print("\n") # Print selected rows based on the conditionprint("Selecting rows:\n")print (select_prod) Output:Example 3: # Importing pandas as pdfrom pandas import DataFrame # Creating a data framecart = {'Product': ['Mobile', 'AC', 'Laptop', 'TV', 'Football'], 'Type': ['Electronic', 'HomeAppliances', 'Electronic', 'HomeAppliances', 'Sports'], 'Price': [10000, 35000, 50000, 30000, 799] } df = DataFrame(cart, columns = ['Product', 'Type', 'Price']) # Print original data frameprint("Original data frame:\n")print(df) # Selecting the product of Price greater # than or equal to 25000select_prod = df.loc[df['Price'] >= 25000] print("\n") # Print selected rows based on the conditionprint("Selecting rows:\n")print (select_prod) Output:Example 4: # Importing pandas as pdfrom pandas import DataFrame # Creating a data framecart = {'Product': ['Mobile', 'AC', 'Laptop', 'TV', 'Football'], 'Type': ['Electronic', 'HomeAppliances', 'Electronic', 'HomeAppliances', 'Sports'], 'Price': [10000, 35000, 30000, 30000, 799] } df = DataFrame(cart, columns = ['Product', 'Type', 'Price']) # Print original data frameprint("Original data frame:\n")print(df) # Selecting the product of Price not # equal to 30000select_prod = df.loc[df['Price'] != 30000] print("\n") # Print selected rows based on the conditionprint("Selecting rows:\n")print (select_prod) Output: Python pandas-dataFrame Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n10 Jul, 2020" }, { "code": null, "e": 234, "s": 28, "text": "pandas.DataFrame.loc is a function used to select rows from Pandas DataFrame based on the condition provided. In this article, let’s learn to select the rows from Pandas DataFrame based on some conditions." }, { "code": null, "e": 274, "s": 234, "text": "Syntax: df.loc[df[β€˜cname’] β€˜condition’]" }, { "code": null, "e": 404, "s": 274, "text": "Parameters:df: represents data framecname: represents column namecondition: represents condition on which rows has to be selected" }, { "code": null, "e": 415, "s": 404, "text": "Example 1:" }, { "code": "# Importing pandas as pdfrom pandas import DataFrame # Creating a data framecart = {'Product': ['Mobile', 'AC', 'Laptop', 'TV', 'Football'], 'Type': ['Electronic', 'HomeAppliances', 'Electronic', 'HomeAppliances', 'Sports'], 'Price': [10000, 35000, 50000, 30000, 799] } df = DataFrame(cart, columns = ['Product', 'Type', 'Price']) # Print original data frameprint(\"Original data frame:\\n\")print(df) # Selecting the product of Electronic Typeselect_prod = df.loc[df['Type'] == 'Electronic'] print(\"\\n\") # Print selected rows based on the conditionprint(\"Selecting rows:\\n\")print (select_prod)", "e": 1050, "s": 415, "text": null }, { "code": null, "e": 1068, "s": 1050, "text": "Output:Example 2:" }, { "code": "# Importing pandas as pdfrom pandas import DataFrame # Creating a data framecart = {'Product': ['Mobile', 'AC', 'Laptop', 'TV', 'Football'], 'Type': ['Electronic', 'HomeAppliances', 'Electronic', 'HomeAppliances', 'Sports'], 'Price': [10000, 35000, 50000, 30000, 799] } df = DataFrame(cart, columns = ['Product', 'Type', 'Price']) # Print original data frameprint(\"Original data frame:\\n\")print(df) # Selecting the product of HomeAppliances Typeselect_prod = df.loc[df['Type'] == 'HomeAppliances'] print(\"\\n\") # Print selected rows based on the conditionprint(\"Selecting rows:\\n\")print (select_prod)", "e": 1710, "s": 1068, "text": null }, { "code": null, "e": 1728, "s": 1710, "text": "Output:Example 3:" }, { "code": "# Importing pandas as pdfrom pandas import DataFrame # Creating a data framecart = {'Product': ['Mobile', 'AC', 'Laptop', 'TV', 'Football'], 'Type': ['Electronic', 'HomeAppliances', 'Electronic', 'HomeAppliances', 'Sports'], 'Price': [10000, 35000, 50000, 30000, 799] } df = DataFrame(cart, columns = ['Product', 'Type', 'Price']) # Print original data frameprint(\"Original data frame:\\n\")print(df) # Selecting the product of Price greater # than or equal to 25000select_prod = df.loc[df['Price'] >= 25000] print(\"\\n\") # Print selected rows based on the conditionprint(\"Selecting rows:\\n\")print (select_prod)", "e": 2379, "s": 1728, "text": null }, { "code": null, "e": 2397, "s": 2379, "text": "Output:Example 4:" }, { "code": "# Importing pandas as pdfrom pandas import DataFrame # Creating a data framecart = {'Product': ['Mobile', 'AC', 'Laptop', 'TV', 'Football'], 'Type': ['Electronic', 'HomeAppliances', 'Electronic', 'HomeAppliances', 'Sports'], 'Price': [10000, 35000, 30000, 30000, 799] } df = DataFrame(cart, columns = ['Product', 'Type', 'Price']) # Print original data frameprint(\"Original data frame:\\n\")print(df) # Selecting the product of Price not # equal to 30000select_prod = df.loc[df['Price'] != 30000] print(\"\\n\") # Print selected rows based on the conditionprint(\"Selecting rows:\\n\")print (select_prod)", "e": 3036, "s": 2397, "text": null }, { "code": null, "e": 3044, "s": 3036, "text": "Output:" }, { "code": null, "e": 3068, "s": 3044, "text": "Python pandas-dataFrame" }, { "code": null, "e": 3082, "s": 3068, "text": "Python-pandas" }, { "code": null, "e": 3089, "s": 3082, "text": "Python" } ]
Sort the Queue using Recursion
09 Nov, 2021 Given a queue and the task is to sort it using recursion without using any loop. We can only use the following functions of queue: empty(q): Tests whether the queue is empty or not. push(q): Adds a new element to the queue. pop(q): Removes front element from the queue. size(q): Returns the number of elements in a queue. front(q): Returns the value of the front element without removing it. Examples: Input: queue = {10, 7, 16, 9, 20, 5} Output: 5 7 9 10 16 20Input: queue = {0, -2, -1, 2, 3, 1} Output: -2 -1 0 1 2 3 Approach: The idea of the solution is to hold all values in the function call stack until the queue becomes empty. When the queue becomes empty, insert all held items one by one in sorted order. Here sorted order is important. How to manage sorted order? Whenever you get the item from the function call stack, then first calculate the size of the queue and compare it with the elements of queue. Here, two cases arises: If the item (returned by function call stack) is greater then the front element of the queue then dequeue front element and enqueue this element into the same queue by decreasing the size.If the item is less than the front element from the queue then enqueue the element in the queue and dequeue the remaining element from the queue and enqueue by decreasing size repeat the case 1 and 2 unless size becomes zero. Take care of one thing, if size became zero and your element remains greater then all elements of the queue then push your element into the queue. If the item (returned by function call stack) is greater then the front element of the queue then dequeue front element and enqueue this element into the same queue by decreasing the size. If the item is less than the front element from the queue then enqueue the element in the queue and dequeue the remaining element from the queue and enqueue by decreasing size repeat the case 1 and 2 unless size becomes zero. Take care of one thing, if size became zero and your element remains greater then all elements of the queue then push your element into the queue. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to push element in last by// popping from front until size becomes 0void FrontToLast(queue<int>& q, int qsize){ // Base condition if (qsize <= 0) return; // pop front element and push // this last in a queue q.push(q.front()); q.pop(); // Recursive call for pushing element FrontToLast(q, qsize - 1);} // Function to push an element in the queue// while maintaining the sorted ordervoid pushInQueue(queue<int>& q, int temp, int qsize){ // Base condition if (q.empty() || qsize == 0) { q.push(temp); return; } // If current element is less than // the element at the front else if (temp <= q.front()) { // Call stack with front of queue q.push(temp); // Recursive call for inserting a front // element of the queue to the last FrontToLast(q, qsize); } else { // Push front element into // last in a queue q.push(q.front()); q.pop(); // Recursive call for pushing // element in a queue pushInQueue(q, temp, qsize - 1); }} // Function to sort the given// queue using recursionvoid sortQueue(queue<int>& q){ // Return if queue is empty if (q.empty()) return; // Get the front element which will // be stored in this variable // throughout the recursion stack int temp = q.front(); // Remove the front element q.pop(); // Recursive call sortQueue(q); // Push the current element into the queue // according to the sorting order pushInQueue(q, temp, q.size());} // Driver codeint main(){ // Push elements to the queue queue<int> qu; qu.push(10); qu.push(7); qu.push(16); qu.push(9); qu.push(20); qu.push(5); // Sort the queue sortQueue(qu); // Print the elements of the // queue after sorting while (!qu.empty()) { cout << qu.front() << " "; qu.pop(); }} // Java implementation of the approachimport java.util.*; class GFG{ // Function to push element in last by// popping from front until size becomes 0static void FrontToLast(Queue<Integer> q, int qsize){ // Base condition if (qsize <= 0) return; // pop front element and push // this last in a queue q.add(q.peek()); q.remove(); // Recursive call for pushing element FrontToLast(q, qsize - 1);} // Function to push an element in the queue// while maintaining the sorted orderstatic void pushInQueue(Queue<Integer> q, int temp, int qsize){ // Base condition if (q.isEmpty() || qsize == 0) { q.add(temp); return; } // If current element is less than // the element at the front else if (temp <= q.peek()) { // Call stack with front of queue q.add(temp); // Recursive call for inserting a front // element of the queue to the last FrontToLast(q, qsize); } else { // Push front element into // last in a queue q.add(q.peek()); q.remove(); // Recursive call for pushing // element in a queue pushInQueue(q, temp, qsize - 1); }} // Function to sort the given// queue using recursionstatic void sortQueue(Queue<Integer> q){ // Return if queue is empty if (q.isEmpty()) return; // Get the front element which will // be stored in this variable // throughout the recursion stack int temp = q.peek(); // Remove the front element q.remove(); // Recursive call sortQueue(q); // Push the current element into the queue // according to the sorting order pushInQueue(q, temp, q.size());} // Driver codepublic static void main(String[] args){ // Push elements to the queue Queue<Integer> qu = new LinkedList<>(); qu.add(10); qu.add(7); qu.add(16); qu.add(9); qu.add(20); qu.add(5); // Sort the queue sortQueue(qu); // Print the elements of the // queue after sorting while (!qu.isEmpty()) { System.out.print(qu.peek() + " "); qu.remove(); }}} // This code is contributed by PrinciRaj1992 # defining a class Queueclass Queue: def __init__(self): self.queue = [] def put(self, item): self.queue.append(item) def get(self): if len(self.queue) < 1: return None return self.queue.pop(0) def front(self): return self.queue[0] def size(self): return len(self.queue) def empty(self): return not(len(self.queue)) # Function to push element in last by# popping from front until size becomes 0def FrontToLast(q, qsize) : # Base condition if qsize <= 0: return # pop front element and push # this last in a queue q.put(q.get()) # Recursive call for pushing element FrontToLast(q, qsize - 1) # Function to push an element in the queue# while maintaining the sorted orderdef pushInQueue(q, temp, qsize) : # Base condition if q.empty() or qsize == 0: q.put(temp) return # If current element is less than # the element at the front elif temp <= q.front() : # Call stack with front of queue q.put(temp) # Recursive call for inserting a front # element of the queue to the last FrontToLast(q, qsize) else : # Push front element into # last in a queue q.put(q.get()) # Recursive call for pushing # element in a queue pushInQueue(q, temp, qsize - 1) # Function to sort the given# queue using recursiondef sortQueue(q): # Return if queue is empty if q.empty(): return # Get the front element which will # be stored in this variable # throughout the recursion stack temp = q.get() # Recursive call sortQueue(q) # Push the current element into the queue # according to the sorting order pushInQueue(q, temp, q.size()) # Driver codequ = Queue() # Data is inserted into Queue# using put() Data is inserted# at the endqu.put(10)qu.put(7)qu.put(16)qu.put(9)qu.put(20)qu.put(5) # Sort the queuesortQueue(qu) # Print the elements of the# queue after sortingwhile not qu.empty(): print(qu.get(), end = ' ') # This code is contributed by Sadik Ali // Program to print the given patternusing System;using System.Collections.Generic; class GFG{ // Function to push element in last by// popping from front until size becomes 0static void FrontToLast(Queue<int> q, int qsize){ // Base condition if (qsize <= 0) return; // pop front element and push // this last in a queue q.Enqueue(q.Peek()); q.Dequeue(); // Recursive call for pushing element FrontToLast(q, qsize - 1);} // Function to push an element in the queue// while maintaining the sorted orderstatic void pushInQueue(Queue<int> q, int temp, int qsize){ // Base condition if (q.Count == 0 || qsize == 0) { q.Enqueue(temp); return; } // If current element is less than // the element at the front else if (temp <= q.Peek()) { // Call stack with front of queue q.Enqueue(temp); // Recursive call for inserting a front // element of the queue to the last FrontToLast(q, qsize); } else { // Push front element into // last in a queue q.Enqueue(q.Peek()); q.Dequeue(); // Recursive call for pushing // element in a queue pushInQueue(q, temp, qsize - 1); }} // Function to sort the given// queue using recursionstatic void sortQueue(Queue<int> q){ // Return if queue is empty if (q.Count==0) return; // Get the front element which will // be stored in this variable // throughout the recursion stack int temp = q.Peek(); // Remove the front element q.Dequeue(); // Recursive call sortQueue(q); // Push the current element into the queue // according to the sorting order pushInQueue(q, temp, q.Count);} // Driver codepublic static void Main(String[] args){ // Push elements to the queue Queue<int> qu = new Queue<int>(); qu.Enqueue(10); qu.Enqueue(7); qu.Enqueue(16); qu.Enqueue(9); qu.Enqueue(20); qu.Enqueue(5); // Sort the queue sortQueue(qu); // Print the elements of the // queue after sorting while (qu.Count != 0) { Console.Write(qu.Peek() + " "); qu.Dequeue(); }}} // This code is contributed by Princi Singh <script> // Javascript implementation of the approach // Function to push element in last by // popping from front until size becomes 0 function FrontToLast(q, qsize) { // Base condition if (qsize <= 0) return; // pop front element and push // this last in a queue q.push(q[0]); q.shift(); // Recursive call for pushing element FrontToLast(q, qsize - 1); } // Function to push an element in the queue // while maintaining the sorted order function pushInQueue(q, temp, qsize) { // Base condition if (q.length == 0 || qsize == 0) { q.push(temp); return; } // If current element is less than // the element at the front else if (temp <= q[0]) { // Call stack with front of queue q.push(temp); // Recursive call for inserting a front // element of the queue to the last FrontToLast(q, qsize); } else { // Push front element into // last in a queue q.push(q[0]); q.shift(); // Recursive call for pushing // element in a queue pushInQueue(q, temp, qsize - 1); } } // Function to sort the given // queue using recursion function sortQueue(q) { // Return if queue is empty if (q.length==0) return; // Get the front element which will // be stored in this variable // throughout the recursion stack let temp = q[0]; // Remove the front element q.shift(); // Recursive call sortQueue(q); // Push the current element into the queue // according to the sorting order pushInQueue(q, temp, q.length); } // Push elements to the queue let qu = []; qu.push(10); qu.push(7); qu.push(16); qu.push(9); qu.push(20); qu.push(5); // Sort the queue sortQueue(qu); // Print the elements of the // queue after sorting while (qu.length != 0) { document.write(qu[0] + " "); qu.shift(); } // This code is contributed by mukesh07.</script> 5 7 9 10 16 20 princiraj1992 princi singh chsadik99 nidhi_biet mukesh07 Constructive Algorithms Queue Recursion Sorting Recursion Sorting Queue Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Data Structures What is Priority Queue | Introduction to Priority Queue Sliding Window Maximum (Maximum of all subarrays of size k) What is Data Structure: Types, Classifications and Applications LRU Cache Implementation Write a program to print all permutations of a given string Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Recursion Program for Tower of Hanoi Backtracking | Introduction
[ { "code": null, "e": 52, "s": 24, "text": "\n09 Nov, 2021" }, { "code": null, "e": 185, "s": 52, "text": "Given a queue and the task is to sort it using recursion without using any loop. We can only use the following functions of queue: " }, { "code": null, "e": 448, "s": 185, "text": "empty(q): Tests whether the queue is empty or not. push(q): Adds a new element to the queue. pop(q): Removes front element from the queue. size(q): Returns the number of elements in a queue. front(q): Returns the value of the front element without removing it. " }, { "code": null, "e": 460, "s": 448, "text": "Examples: " }, { "code": null, "e": 579, "s": 460, "text": "Input: queue = {10, 7, 16, 9, 20, 5} Output: 5 7 9 10 16 20Input: queue = {0, -2, -1, 2, 3, 1} Output: -2 -1 0 1 2 3 " }, { "code": null, "e": 1004, "s": 581, "text": "Approach: The idea of the solution is to hold all values in the function call stack until the queue becomes empty. When the queue becomes empty, insert all held items one by one in sorted order. Here sorted order is important. How to manage sorted order? Whenever you get the item from the function call stack, then first calculate the size of the queue and compare it with the elements of queue. Here, two cases arises: " }, { "code": null, "e": 1565, "s": 1004, "text": "If the item (returned by function call stack) is greater then the front element of the queue then dequeue front element and enqueue this element into the same queue by decreasing the size.If the item is less than the front element from the queue then enqueue the element in the queue and dequeue the remaining element from the queue and enqueue by decreasing size repeat the case 1 and 2 unless size becomes zero. Take care of one thing, if size became zero and your element remains greater then all elements of the queue then push your element into the queue." }, { "code": null, "e": 1754, "s": 1565, "text": "If the item (returned by function call stack) is greater then the front element of the queue then dequeue front element and enqueue this element into the same queue by decreasing the size." }, { "code": null, "e": 2127, "s": 1754, "text": "If the item is less than the front element from the queue then enqueue the element in the queue and dequeue the remaining element from the queue and enqueue by decreasing size repeat the case 1 and 2 unless size becomes zero. Take care of one thing, if size became zero and your element remains greater then all elements of the queue then push your element into the queue." }, { "code": null, "e": 2180, "s": 2127, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 2184, "s": 2180, "text": "C++" }, { "code": null, "e": 2189, "s": 2184, "text": "Java" }, { "code": null, "e": 2197, "s": 2189, "text": "Python3" }, { "code": null, "e": 2200, "s": 2197, "text": "C#" }, { "code": null, "e": 2211, "s": 2200, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to push element in last by// popping from front until size becomes 0void FrontToLast(queue<int>& q, int qsize){ // Base condition if (qsize <= 0) return; // pop front element and push // this last in a queue q.push(q.front()); q.pop(); // Recursive call for pushing element FrontToLast(q, qsize - 1);} // Function to push an element in the queue// while maintaining the sorted ordervoid pushInQueue(queue<int>& q, int temp, int qsize){ // Base condition if (q.empty() || qsize == 0) { q.push(temp); return; } // If current element is less than // the element at the front else if (temp <= q.front()) { // Call stack with front of queue q.push(temp); // Recursive call for inserting a front // element of the queue to the last FrontToLast(q, qsize); } else { // Push front element into // last in a queue q.push(q.front()); q.pop(); // Recursive call for pushing // element in a queue pushInQueue(q, temp, qsize - 1); }} // Function to sort the given// queue using recursionvoid sortQueue(queue<int>& q){ // Return if queue is empty if (q.empty()) return; // Get the front element which will // be stored in this variable // throughout the recursion stack int temp = q.front(); // Remove the front element q.pop(); // Recursive call sortQueue(q); // Push the current element into the queue // according to the sorting order pushInQueue(q, temp, q.size());} // Driver codeint main(){ // Push elements to the queue queue<int> qu; qu.push(10); qu.push(7); qu.push(16); qu.push(9); qu.push(20); qu.push(5); // Sort the queue sortQueue(qu); // Print the elements of the // queue after sorting while (!qu.empty()) { cout << qu.front() << \" \"; qu.pop(); }}", "e": 4228, "s": 2211, "text": null }, { "code": "// Java implementation of the approachimport java.util.*; class GFG{ // Function to push element in last by// popping from front until size becomes 0static void FrontToLast(Queue<Integer> q, int qsize){ // Base condition if (qsize <= 0) return; // pop front element and push // this last in a queue q.add(q.peek()); q.remove(); // Recursive call for pushing element FrontToLast(q, qsize - 1);} // Function to push an element in the queue// while maintaining the sorted orderstatic void pushInQueue(Queue<Integer> q, int temp, int qsize){ // Base condition if (q.isEmpty() || qsize == 0) { q.add(temp); return; } // If current element is less than // the element at the front else if (temp <= q.peek()) { // Call stack with front of queue q.add(temp); // Recursive call for inserting a front // element of the queue to the last FrontToLast(q, qsize); } else { // Push front element into // last in a queue q.add(q.peek()); q.remove(); // Recursive call for pushing // element in a queue pushInQueue(q, temp, qsize - 1); }} // Function to sort the given// queue using recursionstatic void sortQueue(Queue<Integer> q){ // Return if queue is empty if (q.isEmpty()) return; // Get the front element which will // be stored in this variable // throughout the recursion stack int temp = q.peek(); // Remove the front element q.remove(); // Recursive call sortQueue(q); // Push the current element into the queue // according to the sorting order pushInQueue(q, temp, q.size());} // Driver codepublic static void main(String[] args){ // Push elements to the queue Queue<Integer> qu = new LinkedList<>(); qu.add(10); qu.add(7); qu.add(16); qu.add(9); qu.add(20); qu.add(5); // Sort the queue sortQueue(qu); // Print the elements of the // queue after sorting while (!qu.isEmpty()) { System.out.print(qu.peek() + \" \"); qu.remove(); }}} // This code is contributed by PrinciRaj1992", "e": 6435, "s": 4228, "text": null }, { "code": "# defining a class Queueclass Queue: def __init__(self): self.queue = [] def put(self, item): self.queue.append(item) def get(self): if len(self.queue) < 1: return None return self.queue.pop(0) def front(self): return self.queue[0] def size(self): return len(self.queue) def empty(self): return not(len(self.queue)) # Function to push element in last by# popping from front until size becomes 0def FrontToLast(q, qsize) : # Base condition if qsize <= 0: return # pop front element and push # this last in a queue q.put(q.get()) # Recursive call for pushing element FrontToLast(q, qsize - 1) # Function to push an element in the queue# while maintaining the sorted orderdef pushInQueue(q, temp, qsize) : # Base condition if q.empty() or qsize == 0: q.put(temp) return # If current element is less than # the element at the front elif temp <= q.front() : # Call stack with front of queue q.put(temp) # Recursive call for inserting a front # element of the queue to the last FrontToLast(q, qsize) else : # Push front element into # last in a queue q.put(q.get()) # Recursive call for pushing # element in a queue pushInQueue(q, temp, qsize - 1) # Function to sort the given# queue using recursiondef sortQueue(q): # Return if queue is empty if q.empty(): return # Get the front element which will # be stored in this variable # throughout the recursion stack temp = q.get() # Recursive call sortQueue(q) # Push the current element into the queue # according to the sorting order pushInQueue(q, temp, q.size()) # Driver codequ = Queue() # Data is inserted into Queue# using put() Data is inserted# at the endqu.put(10)qu.put(7)qu.put(16)qu.put(9)qu.put(20)qu.put(5) # Sort the queuesortQueue(qu) # Print the elements of the# queue after sortingwhile not qu.empty(): print(qu.get(), end = ' ') # This code is contributed by Sadik Ali", "e": 8586, "s": 6435, "text": null }, { "code": "// Program to print the given patternusing System;using System.Collections.Generic; class GFG{ // Function to push element in last by// popping from front until size becomes 0static void FrontToLast(Queue<int> q, int qsize){ // Base condition if (qsize <= 0) return; // pop front element and push // this last in a queue q.Enqueue(q.Peek()); q.Dequeue(); // Recursive call for pushing element FrontToLast(q, qsize - 1);} // Function to push an element in the queue// while maintaining the sorted orderstatic void pushInQueue(Queue<int> q, int temp, int qsize){ // Base condition if (q.Count == 0 || qsize == 0) { q.Enqueue(temp); return; } // If current element is less than // the element at the front else if (temp <= q.Peek()) { // Call stack with front of queue q.Enqueue(temp); // Recursive call for inserting a front // element of the queue to the last FrontToLast(q, qsize); } else { // Push front element into // last in a queue q.Enqueue(q.Peek()); q.Dequeue(); // Recursive call for pushing // element in a queue pushInQueue(q, temp, qsize - 1); }} // Function to sort the given// queue using recursionstatic void sortQueue(Queue<int> q){ // Return if queue is empty if (q.Count==0) return; // Get the front element which will // be stored in this variable // throughout the recursion stack int temp = q.Peek(); // Remove the front element q.Dequeue(); // Recursive call sortQueue(q); // Push the current element into the queue // according to the sorting order pushInQueue(q, temp, q.Count);} // Driver codepublic static void Main(String[] args){ // Push elements to the queue Queue<int> qu = new Queue<int>(); qu.Enqueue(10); qu.Enqueue(7); qu.Enqueue(16); qu.Enqueue(9); qu.Enqueue(20); qu.Enqueue(5); // Sort the queue sortQueue(qu); // Print the elements of the // queue after sorting while (qu.Count != 0) { Console.Write(qu.Peek() + \" \"); qu.Dequeue(); }}} // This code is contributed by Princi Singh", "e": 10840, "s": 8586, "text": null }, { "code": "<script> // Javascript implementation of the approach // Function to push element in last by // popping from front until size becomes 0 function FrontToLast(q, qsize) { // Base condition if (qsize <= 0) return; // pop front element and push // this last in a queue q.push(q[0]); q.shift(); // Recursive call for pushing element FrontToLast(q, qsize - 1); } // Function to push an element in the queue // while maintaining the sorted order function pushInQueue(q, temp, qsize) { // Base condition if (q.length == 0 || qsize == 0) { q.push(temp); return; } // If current element is less than // the element at the front else if (temp <= q[0]) { // Call stack with front of queue q.push(temp); // Recursive call for inserting a front // element of the queue to the last FrontToLast(q, qsize); } else { // Push front element into // last in a queue q.push(q[0]); q.shift(); // Recursive call for pushing // element in a queue pushInQueue(q, temp, qsize - 1); } } // Function to sort the given // queue using recursion function sortQueue(q) { // Return if queue is empty if (q.length==0) return; // Get the front element which will // be stored in this variable // throughout the recursion stack let temp = q[0]; // Remove the front element q.shift(); // Recursive call sortQueue(q); // Push the current element into the queue // according to the sorting order pushInQueue(q, temp, q.length); } // Push elements to the queue let qu = []; qu.push(10); qu.push(7); qu.push(16); qu.push(9); qu.push(20); qu.push(5); // Sort the queue sortQueue(qu); // Print the elements of the // queue after sorting while (qu.length != 0) { document.write(qu[0] + \" \"); qu.shift(); } // This code is contributed by mukesh07.</script>", "e": 13096, "s": 10840, "text": null }, { "code": null, "e": 13111, "s": 13096, "text": "5 7 9 10 16 20" }, { "code": null, "e": 13127, "s": 13113, "text": "princiraj1992" }, { "code": null, "e": 13140, "s": 13127, "text": "princi singh" }, { "code": null, "e": 13150, "s": 13140, "text": "chsadik99" }, { "code": null, "e": 13161, "s": 13150, "text": "nidhi_biet" }, { "code": null, "e": 13170, "s": 13161, "text": "mukesh07" }, { "code": null, "e": 13194, "s": 13170, "text": "Constructive Algorithms" }, { "code": null, "e": 13200, "s": 13194, "text": "Queue" }, { "code": null, "e": 13210, "s": 13200, "text": "Recursion" }, { "code": null, "e": 13218, "s": 13210, "text": "Sorting" }, { "code": null, "e": 13228, "s": 13218, "text": "Recursion" }, { "code": null, "e": 13236, "s": 13228, "text": "Sorting" }, { "code": null, "e": 13242, "s": 13236, "text": "Queue" }, { "code": null, "e": 13340, "s": 13242, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 13372, "s": 13340, "text": "Introduction to Data Structures" }, { "code": null, "e": 13428, "s": 13372, "text": "What is Priority Queue | Introduction to Priority Queue" }, { "code": null, "e": 13488, "s": 13428, "text": "Sliding Window Maximum (Maximum of all subarrays of size k)" }, { "code": null, "e": 13552, "s": 13488, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 13577, "s": 13552, "text": "LRU Cache Implementation" }, { "code": null, "e": 13637, "s": 13577, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 13722, "s": 13637, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 13732, "s": 13722, "text": "Recursion" }, { "code": null, "e": 13759, "s": 13732, "text": "Program for Tower of Hanoi" } ]
VBA - Year Function
The Year function returns an integer that represents a year of the specified date. Year(date) Add a button and add the following function. Private Sub Constant_demo_Click() msgbox(Year("2013-06-30")) End sub When you execute the above function, it produces the following output. 2013 101 Lectures 6 hours Pavan Lalwani 41 Lectures 3 hours Arnold Higuit 80 Lectures 5.5 hours Prashant Panchal 25 Lectures 2 hours Prashant Panchal 26 Lectures 2 hours Arnold Higuit 92 Lectures 10.5 hours Vijay Kumar Parvatha Reddy Print Add Notes Bookmark this page
[ { "code": null, "e": 2018, "s": 1935, "text": "The Year function returns an integer that represents a year of the specified date." }, { "code": null, "e": 2031, "s": 2018, "text": "Year(date) \n" }, { "code": null, "e": 2076, "s": 2031, "text": "Add a button and add the following function." }, { "code": null, "e": 2148, "s": 2076, "text": "Private Sub Constant_demo_Click()\n msgbox(Year(\"2013-06-30\"))\nEnd sub" }, { "code": null, "e": 2219, "s": 2148, "text": "When you execute the above function, it produces the following output." }, { "code": null, "e": 2225, "s": 2219, "text": "2013\n" }, { "code": null, "e": 2259, "s": 2225, "text": "\n 101 Lectures \n 6 hours \n" }, { "code": null, "e": 2274, "s": 2259, "text": " Pavan Lalwani" }, { "code": null, "e": 2307, "s": 2274, "text": "\n 41 Lectures \n 3 hours \n" }, { "code": null, "e": 2322, "s": 2307, "text": " Arnold Higuit" }, { "code": null, "e": 2357, "s": 2322, "text": "\n 80 Lectures \n 5.5 hours \n" }, { "code": null, "e": 2375, "s": 2357, "text": " Prashant Panchal" }, { "code": null, "e": 2408, "s": 2375, "text": "\n 25 Lectures \n 2 hours \n" }, { "code": null, "e": 2426, "s": 2408, "text": " Prashant Panchal" }, { "code": null, "e": 2459, "s": 2426, "text": "\n 26 Lectures \n 2 hours \n" }, { "code": null, "e": 2474, "s": 2459, "text": " Arnold Higuit" }, { "code": null, "e": 2510, "s": 2474, "text": "\n 92 Lectures \n 10.5 hours \n" }, { "code": null, "e": 2538, "s": 2510, "text": " Vijay Kumar Parvatha Reddy" }, { "code": null, "e": 2545, "s": 2538, "text": " Print" }, { "code": null, "e": 2556, "s": 2545, "text": " Add Notes" } ]
What is CallableStatement in JDBC?
The CallableStatement interface provides methods to execute the stored procedures. Since the JDBC API provides a stored procedure SQL escape syntax, you can call stored procedures of all RDBMS in single standard way. You can create an object of the CallableStatement (interface) using the prepareCall() method of the Connection interface. This method accepts a string variable representing a query to call the stored procedure and returns a CallableStatement object. A Callable statement can have input parameters, output parameters or both. To pass input parameters to the procedure call you can use place holder and set values to these using the setter methods (setInt(), setString(), setFloat()) provided by the CallableStatement interface. Suppose you have a procedure name myProcedure in the database you can prepare a callable statement as: //Preparing a CallableStatement CallableStatement cstmt = con.prepareCall("{call myProcedure(?, ?, ?)}"); You can set values to the input parameters of the procedure call using the setter methods. These accepts two arguments, one is an integer value representing the placement index of the input parameter and, the other is a int or, String or, float etc... representing the value you need to pass as input parameter to the procedure. Note: Instead of index you can also pass the name of the parameter in String format. cstmt.setString(1, "Raghav"); cstmt.setInt(2, 3000); cstmt.setString(3, "Hyderabad"); Once you have created the CallableStatement object you can execute it using one of the execute() method. cstmt.execute(); Suppose we have a table named Employee in the MySQL database with the following data: +---------+--------+----------------+ | Name | Salary | Location | +---------+--------+----------------+ | Amit | 30000 | Hyderabad | | Kalyan | 40000 | Vishakhapatnam | | Renuka | 50000 | Delhi | | Archana | 15000 | Mumbai | +---------+--------+----------------+ And we have created a procedure named myProcedure to insert values in to this table as shown below: Create procedure myProcedure (IN name VARCHAR(30), IN sal INT, IN loc VARCHAR(45)) -> BEGIN -> INSERT INTO Employee(Name, Salary, Location) VALUES (name, sal, loc); -> END // Following is a JDBC example which inserts new records into the Employee table by calling the above created procedure, using a callable statement. import java.sql.CallableStatement; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class CallableStatementExample { public static void main(String args[]) throws SQLException { //Registering the Driver DriverManager.registerDriver(new com.mysql.jdbc.Driver()); //Getting the connection String mysqlUrl = "jdbc:mysql://localhost/testdb"; Connection con = DriverManager.getConnection(mysqlUrl, "root", "password"); System.out.println("Connection established......"); //Preparing a CallableStateement CallableStatement cstmt = con.prepareCall("{call myProcedure(?, ?, ?)}"); cstmt.setString(1, "Raghav"); cstmt.setInt(2, 3000); cstmt.setString(3, "Hyderabad"); cstmt.setString(1, "Kalyan"); cstmt.setInt(2, 4000); cstmt.setString(3, "Vishakhapatnam"); cstmt.setString(1, "Rukmini"); cstmt.setInt(2, 5000); cstmt.setString(3, "Delhi"); cstmt.setString(1, "Archana"); cstmt.setInt(2, 15000); cstmt.setString(3, "Mumbai"); cstmt.execute(); System.out.println("Rows inserted ...."); } } Connection established...... Rows inserted .... If you retrieve the contents of the Employee table using the select query, you can observe newly added records as shown below: mysql> select * from employee; +---------+--------+----------------+ | Name | Salary | Location | +---------+--------+----------------+ | Amit | 30000 | Hyderabad | | Kalyan | 40000 | Vishakhapatnam | | Renuka | 50000 | Delhi | | Archana | 15000 | Mumbai | | Raghav | 3000 | Hyderabad | | Raghav | 3000 | Hyderabad | | Kalyan | 4000 | Vishakhapatnam | | Rukmini | 5000 | Delhi | | Archana | 15000 | Mumbai | +---------+--------+----------------+ 9 rows in set (0.00 sec)
[ { "code": null, "e": 1279, "s": 1062, "text": "The CallableStatement interface provides methods to execute the stored procedures. Since the JDBC API provides a stored procedure SQL escape syntax, you can call stored procedures of all RDBMS in single standard way." }, { "code": null, "e": 1529, "s": 1279, "text": "You can create an object of the CallableStatement (interface) using the prepareCall() method of the Connection interface. This method accepts a string variable representing a query to call the stored procedure and returns a CallableStatement object." }, { "code": null, "e": 1806, "s": 1529, "text": "A Callable statement can have input parameters, output parameters or both. To pass input parameters to the procedure call you can use place holder and set values to these using the setter methods (setInt(), setString(), setFloat()) provided by the CallableStatement interface." }, { "code": null, "e": 1909, "s": 1806, "text": "Suppose you have a procedure name myProcedure in the database you can prepare a callable statement as:" }, { "code": null, "e": 2015, "s": 1909, "text": "//Preparing a CallableStatement\nCallableStatement cstmt = con.prepareCall(\"{call myProcedure(?, ?, ?)}\");" }, { "code": null, "e": 2106, "s": 2015, "text": "You can set values to the input parameters of the procedure call using the setter methods." }, { "code": null, "e": 2344, "s": 2106, "text": "These accepts two arguments, one is an integer value representing the placement index of the input parameter and, the other is a int or, String or, float etc... representing the value you need to pass as\ninput parameter to the procedure." }, { "code": null, "e": 2429, "s": 2344, "text": "Note: Instead of index you can also pass the name of the parameter in String format." }, { "code": null, "e": 2515, "s": 2429, "text": "cstmt.setString(1, \"Raghav\");\ncstmt.setInt(2, 3000);\ncstmt.setString(3, \"Hyderabad\");" }, { "code": null, "e": 2620, "s": 2515, "text": "Once you have created the CallableStatement object you can execute it using one of the execute() method." }, { "code": null, "e": 2637, "s": 2620, "text": "cstmt.execute();" }, { "code": null, "e": 2723, "s": 2637, "text": "Suppose we have a table named Employee in the MySQL database with the following data:" }, { "code": null, "e": 3027, "s": 2723, "text": "+---------+--------+----------------+\n| Name | Salary | Location |\n+---------+--------+----------------+\n| Amit | 30000 | Hyderabad |\n| Kalyan | 40000 | Vishakhapatnam |\n| Renuka | 50000 | Delhi |\n| Archana | 15000 | Mumbai |\n+---------+--------+----------------+" }, { "code": null, "e": 3127, "s": 3027, "text": "And we have created a procedure named myProcedure to insert values in to this table as shown below:" }, { "code": null, "e": 3311, "s": 3127, "text": "Create procedure myProcedure (IN name VARCHAR(30), IN sal INT, IN loc VARCHAR(45))\n -> BEGIN\n -> INSERT INTO Employee(Name, Salary, Location) VALUES (name, sal, loc);\n -> END //" }, { "code": null, "e": 3457, "s": 3311, "text": "Following is a JDBC example which inserts new records into the Employee table by calling the above created procedure, using a callable statement." }, { "code": null, "e": 4629, "s": 3457, "text": "import java.sql.CallableStatement;\nimport java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.SQLException;\npublic class CallableStatementExample {\n public static void main(String args[]) throws SQLException {\n //Registering the Driver\n DriverManager.registerDriver(new com.mysql.jdbc.Driver());\n\n //Getting the connection\n String mysqlUrl = \"jdbc:mysql://localhost/testdb\";\n Connection con = DriverManager.getConnection(mysqlUrl, \"root\", \"password\");\n System.out.println(\"Connection established......\");\n //Preparing a CallableStateement\n CallableStatement cstmt = con.prepareCall(\"{call myProcedure(?, ?, ?)}\");\n\n cstmt.setString(1, \"Raghav\");\n cstmt.setInt(2, 3000);\n cstmt.setString(3, \"Hyderabad\");\n\n cstmt.setString(1, \"Kalyan\");\n cstmt.setInt(2, 4000);\n cstmt.setString(3, \"Vishakhapatnam\");\n\n cstmt.setString(1, \"Rukmini\");\n cstmt.setInt(2, 5000);\n cstmt.setString(3, \"Delhi\");\n\n cstmt.setString(1, \"Archana\");\n cstmt.setInt(2, 15000);\n cstmt.setString(3, \"Mumbai\");\n\n cstmt.execute();\n System.out.println(\"Rows inserted ....\");\n }\n}" }, { "code": null, "e": 4677, "s": 4629, "text": "Connection established......\nRows inserted ...." }, { "code": null, "e": 4804, "s": 4677, "text": "If you retrieve the contents of the Employee table using the select query, you can observe newly added records as shown below:" }, { "code": null, "e": 5354, "s": 4804, "text": "mysql> select * from employee;\n+---------+--------+----------------+\n| Name | Salary | Location |\n+---------+--------+----------------+\n| Amit | 30000 | Hyderabad |\n| Kalyan | 40000 | Vishakhapatnam |\n| Renuka | 50000 | Delhi |\n| Archana | 15000 | Mumbai |\n| Raghav | 3000 | Hyderabad |\n| Raghav | 3000 | Hyderabad |\n| Kalyan | 4000 | Vishakhapatnam |\n| Rukmini | 5000 | Delhi |\n| Archana | 15000 | Mumbai |\n+---------+--------+----------------+\n9 rows in set (0.00 sec)" } ]
PostgreSQL - Removing Temporary Table - GeeksforGeeks
28 Aug, 2020 In PostgreSQL, one can drop a temporary table by the use of the DROP TABLE statement. Syntax: DROP TABLE temp_table_name; Unlike the CREATE TABLE statement, the DROP TABLE statement does not have the TEMP or TEMPORARY keyword created specifically for temporary tables. To demonstrate the process of dropping a temporary table let’s first create one by following the below instructions.First, we create a sample database(say, test) to add a temporary table using the below statement: CREATE DATABASE test; After creating the database we switch into it using the following command: \c test; Now we add a temporary table (say, mytemp) to the test database as below: CREATE TABLE mytemp(c INT); Verify if the table has been created using the below statement: SELECT * FROM mytemp; It should show you the below table:Now that our temporary table is created we remove it in the below example. Example:We use the DROP TABLE statement inside the database test as follows to drop the temporary table: DROP TABLE mytemp; Now we verify if the table has been removed successfully using the below statement: SELECT * FROM mytemp; Output: The above-shown error raised by PostgreSQL shows that the mytemp table doesn’t exist anymore. postgreSQL-managing-table PostgreSQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. PostgreSQL - GROUP BY clause PostgreSQL - DROP INDEX PostgreSQL - Copy Table PostgreSQL - Interval Data Type PostgreSQL - LEFT JOIN PostgreSQL - TEXT Data Type PostgreSQL - Record type variable PostgreSQL - TIME Data Type PostgreSQL - CREATE PROCEDURE PostgreSQL - ROW_NUMBER Function
[ { "code": null, "e": 24138, "s": 24110, "text": "\n28 Aug, 2020" }, { "code": null, "e": 24224, "s": 24138, "text": "In PostgreSQL, one can drop a temporary table by the use of the DROP TABLE statement." }, { "code": null, "e": 24260, "s": 24224, "text": "Syntax: DROP TABLE temp_table_name;" }, { "code": null, "e": 24621, "s": 24260, "text": "Unlike the CREATE TABLE statement, the DROP TABLE statement does not have the TEMP or TEMPORARY keyword created specifically for temporary tables. To demonstrate the process of dropping a temporary table let’s first create one by following the below instructions.First, we create a sample database(say, test) to add a temporary table using the below statement:" }, { "code": null, "e": 24643, "s": 24621, "text": "CREATE DATABASE test;" }, { "code": null, "e": 24718, "s": 24643, "text": "After creating the database we switch into it using the following command:" }, { "code": null, "e": 24727, "s": 24718, "text": "\\c test;" }, { "code": null, "e": 24801, "s": 24727, "text": "Now we add a temporary table (say, mytemp) to the test database as below:" }, { "code": null, "e": 24829, "s": 24801, "text": "CREATE TABLE mytemp(c INT);" }, { "code": null, "e": 24893, "s": 24829, "text": "Verify if the table has been created using the below statement:" }, { "code": null, "e": 24915, "s": 24893, "text": "SELECT * FROM mytemp;" }, { "code": null, "e": 25025, "s": 24915, "text": "It should show you the below table:Now that our temporary table is created we remove it in the below example." }, { "code": null, "e": 25130, "s": 25025, "text": "Example:We use the DROP TABLE statement inside the database test as follows to drop the temporary table:" }, { "code": null, "e": 25149, "s": 25130, "text": "DROP TABLE mytemp;" }, { "code": null, "e": 25233, "s": 25149, "text": "Now we verify if the table has been removed successfully using the below statement:" }, { "code": null, "e": 25255, "s": 25233, "text": "SELECT * FROM mytemp;" }, { "code": null, "e": 25263, "s": 25255, "text": "Output:" }, { "code": null, "e": 25357, "s": 25263, "text": "The above-shown error raised by PostgreSQL shows that the mytemp table doesn’t exist anymore." }, { "code": null, "e": 25383, "s": 25357, "text": "postgreSQL-managing-table" }, { "code": null, "e": 25394, "s": 25383, "text": "PostgreSQL" }, { "code": null, "e": 25492, "s": 25394, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25521, "s": 25492, "text": "PostgreSQL - GROUP BY clause" }, { "code": null, "e": 25545, "s": 25521, "text": "PostgreSQL - DROP INDEX" }, { "code": null, "e": 25569, "s": 25545, "text": "PostgreSQL - Copy Table" }, { "code": null, "e": 25601, "s": 25569, "text": "PostgreSQL - Interval Data Type" }, { "code": null, "e": 25624, "s": 25601, "text": "PostgreSQL - LEFT JOIN" }, { "code": null, "e": 25652, "s": 25624, "text": "PostgreSQL - TEXT Data Type" }, { "code": null, "e": 25686, "s": 25652, "text": "PostgreSQL - Record type variable" }, { "code": null, "e": 25714, "s": 25686, "text": "PostgreSQL - TIME Data Type" }, { "code": null, "e": 25744, "s": 25714, "text": "PostgreSQL - CREATE PROCEDURE" } ]
instanceof operator vs isInstance() Method in Java
03 Jan, 2022 The instanceof operator and isInstance() method both are used for checking the class of the object. But the main difference comes when we want to check the class of objects dynamically then isInstance() method will work. There is no way we can do this by instanceof operator. The isInstance method is equivalent to instanceof operator. The method is used in case of objects are created at runtime using reflection. General practice says if the type is to be checked at runtime then use the isInstance method otherwise instanceof operator can be used. The instanceof operator and isInstance() method both return a boolean value. isInstance() method is a method of class Class in java while instanceof is an operator. Consider an Example: Java // Java program to demonstrate working of// instanceof operator public class Test{ public static void main(String[] args) { Integer i = new Integer(5); // prints true as i is instance of class // Integer System.out.println(i instanceof Integer); }} Output: true Now if we want to check the class of the object at run time, then we must use isInstance() method. Java // Java program to demonstrate working of isInstance()// methodpublic class Test { // This method tells us whether the object is an // instance of class whose name is passed as a // string 'c'. public static boolean fun(Object obj, String c) throws ClassNotFoundException { return Class.forName(c).isInstance(obj); } // Driver code that calls fun() public static void main(String[] args) throws ClassNotFoundException { Integer i = new Integer(5); // print true as i is instance of class // Integer boolean b = fun(i, "java.lang.Integer"); // print false as i is not instance of class // String boolean b1 = fun(i, "java.lang.String"); // print true as i is also instance of class // Number as Integer class extends Number // class boolean b2 = fun(i, "java.lang.Number"); System.out.println(b); System.out.println(b1); System.out.println(b2); }} Output: true false true Note: instanceof operator throws compile-time error(Incompatible conditional operand types) if we check object with other classes which it doesn’t instantiate. Java public class Test { public static void main(String[] args) { Integer i = new Integer(5); // Below line causes compile time error:- // Incompatible conditional operand types // Integer and String System.out.println(i instanceof String); }} Output : 9: error: incompatible types: Integer cannot be converted to String System.out.println(i instanceof String); ^ Must Read: new operator vs newInstance() method in Java Reflections in Java This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. _tanyajain nishkarshgandhi Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n03 Jan, 2022" }, { "code": null, "e": 328, "s": 52, "text": "The instanceof operator and isInstance() method both are used for checking the class of the object. But the main difference comes when we want to check the class of objects dynamically then isInstance() method will work. There is no way we can do this by instanceof operator." }, { "code": null, "e": 603, "s": 328, "text": "The isInstance method is equivalent to instanceof operator. The method is used in case of objects are created at runtime using reflection. General practice says if the type is to be checked at runtime then use the isInstance method otherwise instanceof operator can be used." }, { "code": null, "e": 769, "s": 603, "text": "The instanceof operator and isInstance() method both return a boolean value. isInstance() method is a method of class Class in java while instanceof is an operator. " }, { "code": null, "e": 790, "s": 769, "text": "Consider an Example:" }, { "code": null, "e": 795, "s": 790, "text": "Java" }, { "code": "// Java program to demonstrate working of// instanceof operator public class Test{ public static void main(String[] args) { Integer i = new Integer(5); // prints true as i is instance of class // Integer System.out.println(i instanceof Integer); }}", "e": 1084, "s": 795, "text": null }, { "code": null, "e": 1093, "s": 1084, "text": "Output: " }, { "code": null, "e": 1098, "s": 1093, "text": "true" }, { "code": null, "e": 1197, "s": 1098, "text": "Now if we want to check the class of the object at run time, then we must use isInstance() method." }, { "code": null, "e": 1202, "s": 1197, "text": "Java" }, { "code": "// Java program to demonstrate working of isInstance()// methodpublic class Test { // This method tells us whether the object is an // instance of class whose name is passed as a // string 'c'. public static boolean fun(Object obj, String c) throws ClassNotFoundException { return Class.forName(c).isInstance(obj); } // Driver code that calls fun() public static void main(String[] args) throws ClassNotFoundException { Integer i = new Integer(5); // print true as i is instance of class // Integer boolean b = fun(i, \"java.lang.Integer\"); // print false as i is not instance of class // String boolean b1 = fun(i, \"java.lang.String\"); // print true as i is also instance of class // Number as Integer class extends Number // class boolean b2 = fun(i, \"java.lang.Number\"); System.out.println(b); System.out.println(b1); System.out.println(b2); }}", "e": 2208, "s": 1202, "text": null }, { "code": null, "e": 2217, "s": 2208, "text": "Output: " }, { "code": null, "e": 2233, "s": 2217, "text": "true\nfalse\ntrue" }, { "code": null, "e": 2393, "s": 2233, "text": "Note: instanceof operator throws compile-time error(Incompatible conditional operand types) if we check object with other classes which it doesn’t instantiate." }, { "code": null, "e": 2398, "s": 2393, "text": "Java" }, { "code": "public class Test { public static void main(String[] args) { Integer i = new Integer(5); // Below line causes compile time error:- // Incompatible conditional operand types // Integer and String System.out.println(i instanceof String); }}", "e": 2683, "s": 2398, "text": null }, { "code": null, "e": 2693, "s": 2683, "text": "Output : " }, { "code": null, "e": 2839, "s": 2693, "text": "9: error: incompatible types: Integer cannot be converted to String\n System.out.println(i instanceof String);\n ^" }, { "code": null, "e": 2850, "s": 2839, "text": "Must Read:" }, { "code": null, "e": 2896, "s": 2850, "text": "new operator vs newInstance() method in Java " }, { "code": null, "e": 2916, "s": 2896, "text": "Reflections in Java" }, { "code": null, "e": 3339, "s": 2916, "text": "This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 3350, "s": 3339, "text": "_tanyajain" }, { "code": null, "e": 3366, "s": 3350, "text": "nishkarshgandhi" }, { "code": null, "e": 3371, "s": 3366, "text": "Java" }, { "code": null, "e": 3376, "s": 3371, "text": "Java" } ]
GATE | GATE-CS-2007 | Question 85
20 Nov, 2018 In a look-ahead carry generator, the carry generate function Gi and the carry propagate function Pi for inputs Ai and Bi are given by: Pi = Ai ⨁ Bi and Gi = AiBi The expressions for the sum bit Si and the carry bit Ci+1 of the look-ahead carry adder are given by: Si = Pi ⨁ Ci and Ci+1 = Gi + PiCi , where C0 is the input carry. Consider a two-level logic implementation of the look-ahead carry generator. Assume that all Pi and Gi are available for the carry generator circuit and that the AND and OR gates can have any number of inputs. The number of AND gates and OR gates needed to implement the look-ahead carry generator for a 4-bit adder with S3, S2, S1, S0 and C4 as its outputs are respectively:(A) 6, 3(B) 10, 4(C) 6, 4(D) 10, 5Answer: (B)Explanation: let the carry input be c0 Now, c1 = g0 + p0c0 = 1 AND, 1 OR c2 = g1 + p1g0 + p1p0c0 = 2 AND, 1 OR c3 = g2 + p2g1 + p2p1go + p2p1p0c0 = 3 AND, 1 OR c4 = g3 + p3g2 + p3p2g1 + p3p2p1g0 + p3p2p1p0c0 = 4 AND, 1 OR So, total AND gates = 1+2+3+4 = 10 , OR gates = 1+1+1+1 = 4 So as a general formula we can observe that we need a total of ” n(n+1)/2 ” AND gates and β€œn” OR gates for a n-bit carry look ahead circuit used for addition of two binary numbers.Quiz of this Question GATE-CS-2007 GATE-GATE-CS-2007 GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n20 Nov, 2018" }, { "code": null, "e": 163, "s": 28, "text": "In a look-ahead carry generator, the carry generate function Gi and the carry propagate function Pi for inputs Ai and Bi are given by:" }, { "code": null, "e": 191, "s": 163, "text": "Pi = Ai ⨁ Bi and Gi = AiBi " }, { "code": null, "e": 293, "s": 191, "text": "The expressions for the sum bit Si and the carry bit Ci+1 of the look-ahead carry adder are given by:" }, { "code": null, "e": 359, "s": 293, "text": "Si = Pi ⨁ Ci and Ci+1 = Gi + PiCi , where C0 is the input carry. " }, { "code": null, "e": 818, "s": 359, "text": "Consider a two-level logic implementation of the look-ahead carry generator. Assume that all Pi and Gi are available for the carry generator circuit and that the AND and OR gates can have any number of inputs. The number of AND gates and OR gates needed to implement the look-ahead carry generator for a 4-bit adder with S3, S2, S1, S0 and C4 as its outputs are respectively:(A) 6, 3(B) 10, 4(C) 6, 4(D) 10, 5Answer: (B)Explanation: let the carry input be c0" }, { "code": null, "e": 823, "s": 818, "text": "Now," }, { "code": null, "e": 1014, "s": 823, "text": "c1 = g0 + p0c0 = 1 AND, 1 OR\nc2 = g1 + p1g0 + p1p0c0 \n = 2 AND, 1 OR\n\nc3 = g2 + p2g1 + p2p1go + p2p1p0c0 \n = 3 AND, 1 OR\nc4 = g3 + p3g2 + p3p2g1 + p3p2p1g0 + p3p2p1p0c0 \n = 4 AND, 1 OR" }, { "code": null, "e": 1074, "s": 1014, "text": "So, total AND gates = 1+2+3+4 = 10 , OR gates = 1+1+1+1 = 4" }, { "code": null, "e": 1276, "s": 1074, "text": "So as a general formula we can observe that we need a total of ” n(n+1)/2 ” AND gates and β€œn” OR gates for a n-bit carry look ahead circuit used for addition of two binary numbers.Quiz of this Question" }, { "code": null, "e": 1289, "s": 1276, "text": "GATE-CS-2007" }, { "code": null, "e": 1307, "s": 1289, "text": "GATE-GATE-CS-2007" }, { "code": null, "e": 1312, "s": 1307, "text": "GATE" } ]
Python | Pandas dataframe.eval()
20 Nov, 2018 Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas dataframe.eval() function is used to evaluate an expression in the context of the calling dataframe instance. The expression is evaluated over the columns of the dataframe. Syntax: DataFrame.eval(expr, inplace=False, **kwargs) Parameters:expr : The expression string to evaluate.inplace : If the expression contains an assignment, whether to perform the operation inplace and mutate the existing DataFrame. Otherwise, a newDataFrame is returned.kwargs : See the documentation for eval() for complete details on the keyword arguments accepted by query(). Returns: ret : ndarray, scalar, or pandas object Example #1: Use eval() function to evaluate the sum of all column element in the dataframe and insert the resulting column in the dataframe. # importing pandas as pdimport pandas as pd # Creating the dataframe df=pd.DataFrame({"A":[1,5,7,8], "B":[5,8,4,3], "C":[10,4,9,3]}) # Print the first dataframedf Let’s evaluate the sum over all the columns and add the resultant column to the dataframe # To evaluate the sum over all the columnsdf.eval('D = A + B+C', inplace = True) # Print the modified dataframedf Output : Example #2: Use eval() function to evaluate the sum of any two column element in the dataframe and insert the resulting column in the dataframe. The dataframe has NaN value. Note : Any expression can not be evaluated over NaN values. So the corresponding cells will be NaN too. # importing pandas as pdimport pandas as pd # Creating the dataframedf=pd.DataFrame({"A":[1,2,3], "B":[4,5,None], "C":[7,8,9]}) # Print the dataframedf Let’s evaluate the sum of column β€œB” and β€œC”. # To evaluate the sum of two columns in the dataframedf.eval('D = B + C', inplace = True) # Print the modified dataframedf Output : Notice, the resulting column β€˜D’ has NaN value in the last row as the corresponding cell used in evaluation was a NaN cell. Python pandas-dataFrame Python pandas-dataFrame-methods Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n20 Nov, 2018" }, { "code": null, "e": 242, "s": 28, "text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier." }, { "code": null, "e": 422, "s": 242, "text": "Pandas dataframe.eval() function is used to evaluate an expression in the context of the calling dataframe instance. The expression is evaluated over the columns of the dataframe." }, { "code": null, "e": 476, "s": 422, "text": "Syntax: DataFrame.eval(expr, inplace=False, **kwargs)" }, { "code": null, "e": 803, "s": 476, "text": "Parameters:expr : The expression string to evaluate.inplace : If the expression contains an assignment, whether to perform the operation inplace and mutate the existing DataFrame. Otherwise, a newDataFrame is returned.kwargs : See the documentation for eval() for complete details on the keyword arguments accepted by query()." }, { "code": null, "e": 852, "s": 803, "text": "Returns: ret : ndarray, scalar, or pandas object" }, { "code": null, "e": 993, "s": 852, "text": "Example #1: Use eval() function to evaluate the sum of all column element in the dataframe and insert the resulting column in the dataframe." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the dataframe df=pd.DataFrame({\"A\":[1,5,7,8], \"B\":[5,8,4,3], \"C\":[10,4,9,3]}) # Print the first dataframedf", "e": 1190, "s": 993, "text": null }, { "code": null, "e": 1280, "s": 1190, "text": "Let’s evaluate the sum over all the columns and add the resultant column to the dataframe" }, { "code": "# To evaluate the sum over all the columnsdf.eval('D = A + B+C', inplace = True) # Print the modified dataframedf", "e": 1395, "s": 1280, "text": null }, { "code": null, "e": 1404, "s": 1395, "text": "Output :" }, { "code": null, "e": 1580, "s": 1406, "text": "Example #2: Use eval() function to evaluate the sum of any two column element in the dataframe and insert the resulting column in the dataframe. The dataframe has NaN value." }, { "code": null, "e": 1684, "s": 1580, "text": "Note : Any expression can not be evaluated over NaN values. So the corresponding cells will be NaN too." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the dataframedf=pd.DataFrame({\"A\":[1,2,3], \"B\":[4,5,None], \"C\":[7,8,9]}) # Print the dataframedf", "e": 1870, "s": 1684, "text": null }, { "code": null, "e": 1916, "s": 1870, "text": "Let’s evaluate the sum of column β€œB” and β€œC”." }, { "code": "# To evaluate the sum of two columns in the dataframedf.eval('D = B + C', inplace = True) # Print the modified dataframedf", "e": 2040, "s": 1916, "text": null }, { "code": null, "e": 2049, "s": 2040, "text": "Output :" }, { "code": null, "e": 2173, "s": 2049, "text": "Notice, the resulting column β€˜D’ has NaN value in the last row as the corresponding cell used in evaluation was a NaN cell." }, { "code": null, "e": 2197, "s": 2173, "text": "Python pandas-dataFrame" }, { "code": null, "e": 2229, "s": 2197, "text": "Python pandas-dataFrame-methods" }, { "code": null, "e": 2243, "s": 2229, "text": "Python-pandas" }, { "code": null, "e": 2250, "s": 2243, "text": "Python" } ]
Noble integers in an array (count of greater elements is equal to value)
11 Jul, 2022 Given an array arr[], find a Noble integer in it. An integer x is said to be Noble in arr[] if the number of integers greater than x is equal to x. If there are many Noble integers, return any of them. If there is no, then return -1. Examples : Input : [7, 3, 16, 10] Output : 3 Number of integers greater than 3 is three. Input : [-1, -9, -2, -78, 0] Output : 0 Number of integers greater than 0 is zero. Method 1 (Brute Force): Iterate through the array. For every element arr[i], find the number of elements greater than arr[i]. Implementation: C++ Java Python3 C# PHP Javascript // C++ program to find Noble elements// in an array.#include <bits/stdc++.h>using namespace std; // Returns a Noble integer if present,// else returns -1.int nobleInteger(int arr[], int size){ for (int i = 0; i < size; i++ ) { int count = 0; for (int j = 0; j < size; j++) if (arr[i] < arr[j]) count++; // If count of greater elements // is equal to arr[i] if (count == arr[i]) return arr[i]; } return -1;} // Driver codeint main(){ int arr[] = {10, 3, 20, 40, 2}; int size = sizeof(arr) / sizeof(arr[0]); int res = nobleInteger(arr, size); if (res != -1) cout<<"The noble integer is "<< res; else cout<<"No Noble Integer Found";} // This code is contributed by Smitha. // Java program to find Noble elements// in an array.import java.util.ArrayList; class GFG { // Returns a Noble integer if present, // else returns -1. public static int nobleInteger(int arr[]) { int size = arr.length; for (int i = 0; i < size; i++ ) { int count = 0; for (int j = 0; j < size; j++) if (arr[i] < arr[j]) count++; // If count of greater elements // is equal to arr[i] if (count == arr[i]) return arr[i]; } return -1; } // Driver code public static void main(String args[]) { int [] arr = {10, 3, 20, 40, 2}; int res = nobleInteger(arr); if (res != -1) System.out.println("The noble " + "integer is "+ res); else System.out.println("No Noble " + "Integer Found"); }} # Python3 program to find Noble# elements in an array. # Returns a Noble integer if# present, else returns -1.def nobleInteger(arr, size): for i in range(0, size): count = 0 for j in range(0, size): if (arr[i] < arr[j]): count += 1 # If count of greater # elements is equal # to arr[i] if (count == arr[i]): return arr[i] return -1 # Driver codearr = [10, 3, 20, 40, 2]size = len(arr)res = nobleInteger(arr,size)if (res != -1): print("The noble integer is ", res)else: print("No Noble Integer Found") # This code is contributed by# Smitha. // C# program to find Noble elements// in an array.using System; class GFG { // Returns a Noble integer if present, // else returns -1. public static int nobleInteger(int [] arr) { int size = arr.Length; for (int i = 0; i < size; i++ ) { int count = 0; for (int j = 0; j < size; j++) if (arr[i] < arr[j]) count++; // If count of greater elements // is equal to arr[i] if (count == arr[i]) return arr[i]; } return -1; } // Driver code public static void Main() { int [] arr = {10, 3, 20, 40, 2}; int res = nobleInteger(arr); if (res != -1) Console.Write("The noble integer" + " is "+ res); else Console.Write("No Noble Integer" + " Found"); }} // This code is contributed by Smitha. <?php// PHP program to find Noble// elements in an array. // Returns a Noble integer// if present, else returns -1.function nobleInteger( $arr, $size){ for ( $i = 0; $i < $size; $i++ ) { $count = 0; for ( $j = 0; $j < $size; $j++) if ($arr[$i] < $arr[$j]) $count++; // If count of greater elements // is equal to arr[i] if ($count == $arr[$i]) return $arr[$i]; } return -1;} // Driver code$arr = array(10, 3, 20, 40, 2);$size = count($arr);$res = nobleInteger($arr, $size); if ($res != -1) echo "The noble integer is ", $res;else echo "No Noble Integer Found"; // This code is contributed by anuj_67.?> <script>// Javascript program to find Noble elements// in an array. // Returns a Noble integer if present, // else returns -1. function nobleInteger(arr) { let size = arr.length; for (let i = 0; i < size; i++ ) { let count = 0; for (let j = 0; j < size; j++) if (arr[i] < arr[j]) count++; // If count of greater elements // is equal to arr[i] if (count == arr[i]) return arr[i]; } return -1; } // Driver code let arr=[10, 3, 20, 40, 2]; let res = nobleInteger(arr); if (res != -1) document.write("The noble " + "integer is "+ res); else document.write("No Noble " + "Integer Found"); // This code is contributed by unknown2108</script> The noble integer is 3 Method 2 (Use Sorting) Sort the Array arr[] in ascending order. This step takes (O(nlogn)).Iterate through the array. Compare the value of index i to the number of elements after index i. If arr[i] equals the number of elements after arr[i], it is a noble Integer. Condition to check: (A[i] == length-i-1). This step takes O(n). Sort the Array arr[] in ascending order. This step takes (O(nlogn)). Iterate through the array. Compare the value of index i to the number of elements after index i. If arr[i] equals the number of elements after arr[i], it is a noble Integer. Condition to check: (A[i] == length-i-1). This step takes O(n). Note: Array may have duplicate elements. So, we should skip the elements (adjacent elements in the sorted array) that are same. Implementation: C++ Java Python3 C# PHP Javascript // C++ program to find Noble elements// in an array.#include<bits/stdc++.h>using namespace std; // Returns a Noble integer if present,// else returns -1.int nobleInteger(int arr[], int n){ sort(arr, arr + n); // Return a Noble element if present // before last. for (int i = 0; i < n - 1; i++) { if (arr[i] == arr[i + 1]) continue; // In case of duplicates, we // reach last occurrence here. if (arr[i] == n - i - 1) return arr[i]; } if (arr[n - 1] == 0) return arr[n - 1]; return -1;} // Driver codeint main(){ int arr[] = {10, 3, 20, 40, 2}; int res = nobleInteger(arr, 5); if (res != -1) cout << "The noble integer is " << res; else cout << "No Noble Integer Found"; return 0;} // This code is contributed by Rajput-Ji // Java program to find Noble elements// in an array.import java.util.Arrays; public class Main{ // Returns a Noble integer if present, // else returns -1. public static int nobleInteger(int arr[]) { Arrays.sort(arr); // Return a Noble element if present // before last. int n = arr.length; for (int i=0; i<n-1; i++) { if (arr[i] == arr[i+1]) continue; // In case of duplicates, we // reach last occurrence here. if (arr[i] == n-i-1) return arr[i]; } if (arr[n-1] == 0) return arr[n-1]; return -1; } // Driver code public static void main(String args[]) { int [] arr = {10, 3, 20, 40, 2}; int res = nobleInteger(arr); if (res != -1) System.out.println("The noble integer is "+ res); else System.out.println("No Noble Integer Found"); }} # Python3 code to find Noble elements# in an array def nobleInteger(arr): arr.sort() # Return a Noble element if # present before last n = len(arr) for i in range(n - 1): if arr[i] == arr[i + 1]: continue # In case of duplicates we reach # last occurrence here if arr[i] == n - i - 1: return arr[i] if arr[n - 1] == 0: return arr[n - 1] return -1 # Driver codearr = [10, 3, 20, 40, 2] res = nobleInteger(arr) if res != -1: print("The noble integer is", res)else: print("No Noble Integer Found") # This code is contributed# by Mohit Kumar // C# program to find Noble elements// in an array.using System; public class GFG { public static int nobleInteger(int[] arr) { Array.Sort(arr); // Return a Noble element if present // before last. int n = arr.Length; for (int i = 0; i < n-1; i++) { if (arr[i] == arr[i+1]) continue; // In case of duplicates, we // reach last occurrence here. if (arr[i] == n-i-1) return arr[i]; } if (arr[n-1] == 0) return arr[n-1]; return -1; } // Driver code static public void Main () { int [] arr = {10, 3, 20, 40, 2}; int res = nobleInteger(arr); if (res != -1) Console.Write("The noble integer is " + res); else Console.Write("No Noble Integer " + "Found"); }} // This code is contributed by Shrikant13. <?php// PHP program to find Noble elements // Returns a Noble integer if present,// else returns -1.function nobleInteger( $arr) { sort($arr); // Return a Noble element if // present before last. $n = count($arr); for ( $i = 0; $i < $n - 1; $i++) { if ($arr[$i] == $arr[$i + 1]) continue; // In case of duplicates, we // reach last occurrence here. if ($arr[$i] == $n - $i - 1) return $arr[$i]; } if ($arr[$n - 1] == 0) return $arr[$n - 1]; return -1; } // Driver code $arr = array(10, 3, 20, 40, 2); $res = nobleInteger($arr); if ($res != -1) echo "The noble integer is ", $res; else echo "No Noble Integer Found"; // This code is contributed by anuj_67.?> <script> // Javascript program to find Noble elements// in an array. // Returns a Noble integer if present,// else returns -1.function nobleInteger(arr){ arr.sort(function(a, b){return a - b;}); // Return a Noble element if present // before last. let n = arr.length; for(let i = 0; i < n - 1; i++) { if (arr[i] == arr[i + 1]) continue; // In case of duplicates, we // reach last occurrence here. if (arr[i] == n - i - 1) return arr[i]; } if (arr[n - 1] == 0) return arr[n - 1]; return -1;} // Driver codelet arr = [ 10, 3, 20, 40, 2 ];let res = nobleInteger(arr);if (res != -1) document.write("The noble integer is " + res);else document.write("No Noble Integer Found"); // This code is contributed by patel2127 </script> The noble integer is 3 Method 3 (Using Count Array): Maintain a count array countArr[] which keeps count of all elements greater than or equal to arr[i]. Declare an integer array countArr[] of size n + 1 (where n is the size of given array arr), and initialize it as zero.Iterate through array arr, if arr[i] < 0, we ignore it, if arr[i] >= n, we increment countArr[n], else simply increment countArr[arr[i]].Declare an integer totalGreater, which keeps count of elements greater than current element, and initialize it as countArr[arr[n]].Iterate through count array countArr from last to first index, if at any point we find that totalGreater = i for countArr[i] > 0, we have found our solution. Else keep increasing totalGreater with countArr[i]. Declare an integer array countArr[] of size n + 1 (where n is the size of given array arr), and initialize it as zero. Iterate through array arr, if arr[i] < 0, we ignore it, if arr[i] >= n, we increment countArr[n], else simply increment countArr[arr[i]]. Declare an integer totalGreater, which keeps count of elements greater than current element, and initialize it as countArr[arr[n]]. Iterate through count array countArr from last to first index, if at any point we find that totalGreater = i for countArr[i] > 0, we have found our solution. Else keep increasing totalGreater with countArr[i]. Implementation: C++ Java Python3 C# Javascript // C++ program to find Noble elements// in an array.#include <bits/stdc++.h>using namespace std; int nobleInteger(int arr[], int n){ // Declare a countArr which keeps // count of all elements // greater than or equal to arr[i]. // Initialize it with zero. int countArr[n + 1] = { 0 }; // Iterating through the given array for (int i = 0; i < n; i++) { // If current element is less // than zero, it cannot // be a solution so we skip it. if (arr[i] < 0) { continue; } // If current element is >= size of input array, if // will be greater than all elements which can be // considered as our solution, as it cannot be // greater than size of array. else if (arr[i] >= n) { countArr[n]++; } // Else we increase the count // of elements >= our // current array in countArr else { countArr[arr[i]]++; } } // Initially, countArr[n] is // count of elements greater // than all possible solutions int totalGreater = countArr[n]; // Iterating through countArr for (int i = n - 1; i >= 0; i--) { // If totalGreater = current index, means we found // arr[i] for which count of elements >= arr[i] is // equal to arr[i] if (totalGreater == i && countArr[i] > 0) { return i; } // If at any point count of elements greater than // arr[i] becomes more than current index, then it // means we can no longer have a solution else if (totalGreater > i) { return -1; } // Adding count of elements >= arr[i] to // totalGreater. totalGreater += countArr[i]; } return -1;} // Driver Codeint main(){ int arr[] = { 10, 3, 20, 40, 2 }; int res = nobleInteger(arr, 5); if (res != -1) cout << "The noble integer is " << res; else cout << "No Noble Integer Found"; return 0;} // Java program to find Noble elements// in an array.import java.util.Arrays;class GFG { static int nobleInteger(int arr[], int n) { // Declare a countArr which keeps // count of all elements // greater than or equal to arr[i]. // Initialize it with zero. int countArr[] = new int[n + 1]; Arrays.fill(countArr, 0); // Iterating through the given array for (int i = 0; i < n; i++) { // If current element is less // than zero, it cannot // be a solution so we skip it. if (arr[i] < 0) { continue; } // If current element is >= size of input array, if // will be greater than all elements which can be // considered as our solution, as it cannot be // greater than size of array. else if (arr[i] >= n) { countArr[n]++; } // Else we increase the count // of elements >= our // current array in countArr else { countArr[arr[i]]++; } } // Initially, countArr[n] is // count of elements greater // than all possible solutions int totalGreater = countArr[n]; // Iterating through countArr for (int i = n - 1; i >= 0; i--) { // If totalGreater = current index, means we found // arr[i] for which count of elements >= arr[i] is // equal to arr[i] if (totalGreater == i && countArr[i] > 0) { return i; } // If at any point count of elements greater than // arr[i] becomes more than current index, then it // means we can no longer have a solution else if (totalGreater > i) { return -1; } // Adding count of elements >= arr[i] to // totalGreater. totalGreater += countArr[i]; } return -1; } // Driver Code public static void main(String args[]) { int arr[] = { 10, 3, 20, 40, 2 }; int res = nobleInteger(arr, 5); if (res != -1) System.out.println("The noble integer is " + res); else System.out.println("No Noble Integer Found"); }} // This code is contributed by saurabh_jaiswal. # Python program to find Noble elements# in an array.def nobleInteger(arr, n): # Declare a countArr which keeps # count of all elements # greater than or equal to arr[i]. # Initialize it with zero. countArr = [0] * (n + 1) # Iterating through the given array for i in range(n): # If current element is less # than zero, it cannot # be a solution so we skip it. if (arr[i] < 0): continue # If current element is >= size of input # array, if will be greater than all # elements which can be considered as # our solution, as it cannot be # greater than size of array. else if (arr[i] >= n): countArr[n] += 1 # Else we increase the count # of elements >= our # current array in countArr else: countArr[arr[i]] += 1 # Initially, countArr[n] is # count of elements greater # than all possible solutions totalGreater = countArr[n] # Iterating through countArr for i in range(n - 1, -1, -1): # If totalGreater = current index, # means we found arr[i] for which # count of elements >= arr[i] is # equal to arr[i] if (totalGreater == i and countArr[i] > 0): return i # If at any point count of elements # greater than arr[i] becomes more # than current index, then it means # we can no longer have a solution else if (totalGreater > i): return -1 # Adding count of elements >= arr[i] to # totalGreater. totalGreater += countArr[i] return -1 # Driver Codearr = [10, 3, 20, 40, 2]res = nobleInteger(arr, 5) if (res != -1): print(f"The noble integer is {res}")else: print("No Noble Integer Found") # This code is contributed by gfgking // C# program to find Noble elements// in an array.using System; public class GFG { static int nobleInteger(int[] arr, int n) { // Declare a countArr which keeps // count of all elements // greater than or equal to arr[i]. // Initialize it with zero. int[] countArr = new int[n + 1]; for (int i = 0; i < n + 1; i++) countArr[i] = 0; // Iterating through the given array for (int i = 0; i < n; i++) { // If current element is less // than zero, it cannot // be a solution so we skip it. if (arr[i] < 0) { continue; } // If current element is >= size of input array, // if will be greater than all elements which // can be considered as our solution, as it // cannot be greater than size of array. else if (arr[i] >= n) { countArr[n]++; } // Else we increase the count // of elements >= our // current array in countArr else { countArr[arr[i]]++; } } // Initially, countArr[n] is // count of elements greater // than all possible solutions int totalGreater = countArr[n]; // Iterating through countArr for (int i = n - 1; i >= 0; i--) { // If totalGreater = current index, means we // found arr[i] for which count of elements >= // arr[i] is equal to arr[i] if (totalGreater == i && countArr[i] > 0) { return i; } // If at any point count of elements greater // than arr[i] becomes more than current index, // then it means we can no longer have a // solution else if (totalGreater > i) { return -1; } // Adding count of elements >= arr[i] to // totalGreater. totalGreater += countArr[i]; } return -1; } // Driver code static public void Main() { int[] arr = { 10, 3, 20, 40, 2 }; int n = arr.Length; int res = nobleInteger(arr, n); if (res != -1) Console.Write("The noble integer is " + res); else Console.Write("No Noble Integer " + "Found"); }} // This code is contributed by Aarti_Rathi <script> // JavaScript program to find Noble elements// in an array.function nobleInteger(arr, n){ // Declare a countArr which keeps // count of all elements // greater than or equal to arr[i]. // Initialize it with zero. let countArr = new Uint8Array(n + 1); // Iterating through the given array for(let i = 0; i < n; i++) { // If current element is less // than zero, it cannot // be a solution so we skip it. if (arr[i] < 0) { continue; } // If current element is >= size of input // array, if will be greater than all // elements which can be considered as // our solution, as it cannot be // greater than size of array. else if (arr[i] >= n) { countArr[n]++; } // Else we increase the count // of elements >= our // current array in countArr else { countArr[arr[i]]++; } } // Initially, countArr[n] is // count of elements greater // than all possible solutions let totalGreater = countArr[n]; // Iterating through countArr for(let i = n - 1; i >= 0; i--) { // If totalGreater = current index, // means we found arr[i] for which // count of elements >= arr[i] is // equal to arr[i] if (totalGreater == i && countArr[i] > 0) { return i; } // If at any point count of elements // greater than arr[i] becomes more // than current index, then it means // we can no longer have a solution else if (totalGreater > i) { return -1; } // Adding count of elements >= arr[i] to // totalGreater. totalGreater += countArr[i]; } return -1;} // Driver Codelet arr = [ 10, 3, 20, 40, 2 ];let res = nobleInteger(arr, 5); if (res != -1) document.write("The noble integer is " + res);else document.write("No Noble Integer Found"); // This code is contributed by Surbhi Tyagi. </script> The noble integer is 3 Complexity Analysis:Time Complexity: O(n). As we iterate through both input array and countArr once.Space Complexity: O(n). As we use countArr of size same as given array. Time Complexity: O(n). As we iterate through both input array and countArr once. Space Complexity: O(n). As we use countArr of size same as given array. Noble integers in an array | GeeksforGeeks - YouTubeGeeksforGeeks532K subscribersNoble integers in an array | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:42β€’Liveβ€’<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=0bm_x59CVLA" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> This article is contributed by Saloni Baweja. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. shrikanth13 Smitha Dinesh Semwal vt_m mohit kumar 29 Rajput-Ji nidhi_biet prateekmandaliya unknown2108 patel2127 surbhityagi15 gfgking simmytarika5 _saurabh_jaiswal codewithrathi hardikkoriintern Arrays Sorting Technical Scripter Arrays Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n11 Jul, 2022" }, { "code": null, "e": 288, "s": 54, "text": "Given an array arr[], find a Noble integer in it. An integer x is said to be Noble in arr[] if the number of integers greater than x is equal to x. If there are many Noble integers, return any of them. If there is no, then return -1." }, { "code": null, "e": 300, "s": 288, "text": "Examples : " }, { "code": null, "e": 466, "s": 300, "text": "Input : [7, 3, 16, 10]\nOutput : 3 \nNumber of integers greater than 3\nis three.\n\nInput : [-1, -9, -2, -78, 0]\nOutput : 0\nNumber of integers greater than 0\nis zero." }, { "code": null, "e": 593, "s": 466, "text": "Method 1 (Brute Force): Iterate through the array. For every element arr[i], find the number of elements greater than arr[i]. " }, { "code": null, "e": 609, "s": 593, "text": "Implementation:" }, { "code": null, "e": 613, "s": 609, "text": "C++" }, { "code": null, "e": 618, "s": 613, "text": "Java" }, { "code": null, "e": 626, "s": 618, "text": "Python3" }, { "code": null, "e": 629, "s": 626, "text": "C#" }, { "code": null, "e": 633, "s": 629, "text": "PHP" }, { "code": null, "e": 644, "s": 633, "text": "Javascript" }, { "code": "// C++ program to find Noble elements// in an array.#include <bits/stdc++.h>using namespace std; // Returns a Noble integer if present,// else returns -1.int nobleInteger(int arr[], int size){ for (int i = 0; i < size; i++ ) { int count = 0; for (int j = 0; j < size; j++) if (arr[i] < arr[j]) count++; // If count of greater elements // is equal to arr[i] if (count == arr[i]) return arr[i]; } return -1;} // Driver codeint main(){ int arr[] = {10, 3, 20, 40, 2}; int size = sizeof(arr) / sizeof(arr[0]); int res = nobleInteger(arr, size); if (res != -1) cout<<\"The noble integer is \"<< res; else cout<<\"No Noble Integer Found\";} // This code is contributed by Smitha.", "e": 1454, "s": 644, "text": null }, { "code": "// Java program to find Noble elements// in an array.import java.util.ArrayList; class GFG { // Returns a Noble integer if present, // else returns -1. public static int nobleInteger(int arr[]) { int size = arr.length; for (int i = 0; i < size; i++ ) { int count = 0; for (int j = 0; j < size; j++) if (arr[i] < arr[j]) count++; // If count of greater elements // is equal to arr[i] if (count == arr[i]) return arr[i]; } return -1; } // Driver code public static void main(String args[]) { int [] arr = {10, 3, 20, 40, 2}; int res = nobleInteger(arr); if (res != -1) System.out.println(\"The noble \" + \"integer is \"+ res); else System.out.println(\"No Noble \" + \"Integer Found\"); }}", "e": 2401, "s": 1454, "text": null }, { "code": "# Python3 program to find Noble# elements in an array. # Returns a Noble integer if# present, else returns -1.def nobleInteger(arr, size): for i in range(0, size): count = 0 for j in range(0, size): if (arr[i] < arr[j]): count += 1 # If count of greater # elements is equal # to arr[i] if (count == arr[i]): return arr[i] return -1 # Driver codearr = [10, 3, 20, 40, 2]size = len(arr)res = nobleInteger(arr,size)if (res != -1): print(\"The noble integer is \", res)else: print(\"No Noble Integer Found\") # This code is contributed by# Smitha.", "e": 3072, "s": 2401, "text": null }, { "code": "// C# program to find Noble elements// in an array.using System; class GFG { // Returns a Noble integer if present, // else returns -1. public static int nobleInteger(int [] arr) { int size = arr.Length; for (int i = 0; i < size; i++ ) { int count = 0; for (int j = 0; j < size; j++) if (arr[i] < arr[j]) count++; // If count of greater elements // is equal to arr[i] if (count == arr[i]) return arr[i]; } return -1; } // Driver code public static void Main() { int [] arr = {10, 3, 20, 40, 2}; int res = nobleInteger(arr); if (res != -1) Console.Write(\"The noble integer\" + \" is \"+ res); else Console.Write(\"No Noble Integer\" + \" Found\"); }} // This code is contributed by Smitha.", "e": 4047, "s": 3072, "text": null }, { "code": "<?php// PHP program to find Noble// elements in an array. // Returns a Noble integer// if present, else returns -1.function nobleInteger( $arr, $size){ for ( $i = 0; $i < $size; $i++ ) { $count = 0; for ( $j = 0; $j < $size; $j++) if ($arr[$i] < $arr[$j]) $count++; // If count of greater elements // is equal to arr[i] if ($count == $arr[$i]) return $arr[$i]; } return -1;} // Driver code$arr = array(10, 3, 20, 40, 2);$size = count($arr);$res = nobleInteger($arr, $size); if ($res != -1) echo \"The noble integer is \", $res;else echo \"No Noble Integer Found\"; // This code is contributed by anuj_67.?>", "e": 4762, "s": 4047, "text": null }, { "code": "<script>// Javascript program to find Noble elements// in an array. // Returns a Noble integer if present, // else returns -1. function nobleInteger(arr) { let size = arr.length; for (let i = 0; i < size; i++ ) { let count = 0; for (let j = 0; j < size; j++) if (arr[i] < arr[j]) count++; // If count of greater elements // is equal to arr[i] if (count == arr[i]) return arr[i]; } return -1; } // Driver code let arr=[10, 3, 20, 40, 2]; let res = nobleInteger(arr); if (res != -1) document.write(\"The noble \" + \"integer is \"+ res); else document.write(\"No Noble \" + \"Integer Found\"); // This code is contributed by unknown2108</script>", "e": 5636, "s": 4762, "text": null }, { "code": null, "e": 5659, "s": 5636, "text": "The noble integer is 3" }, { "code": null, "e": 5684, "s": 5659, "text": "Method 2 (Use Sorting) " }, { "code": null, "e": 5990, "s": 5684, "text": "Sort the Array arr[] in ascending order. This step takes (O(nlogn)).Iterate through the array. Compare the value of index i to the number of elements after index i. If arr[i] equals the number of elements after arr[i], it is a noble Integer. Condition to check: (A[i] == length-i-1). This step takes O(n)." }, { "code": null, "e": 6059, "s": 5990, "text": "Sort the Array arr[] in ascending order. This step takes (O(nlogn))." }, { "code": null, "e": 6297, "s": 6059, "text": "Iterate through the array. Compare the value of index i to the number of elements after index i. If arr[i] equals the number of elements after arr[i], it is a noble Integer. Condition to check: (A[i] == length-i-1). This step takes O(n)." }, { "code": null, "e": 6427, "s": 6297, "text": "Note: Array may have duplicate elements. So, we should skip the elements (adjacent elements in the sorted array) that are same. " }, { "code": null, "e": 6443, "s": 6427, "text": "Implementation:" }, { "code": null, "e": 6447, "s": 6443, "text": "C++" }, { "code": null, "e": 6452, "s": 6447, "text": "Java" }, { "code": null, "e": 6460, "s": 6452, "text": "Python3" }, { "code": null, "e": 6463, "s": 6460, "text": "C#" }, { "code": null, "e": 6467, "s": 6463, "text": "PHP" }, { "code": null, "e": 6478, "s": 6467, "text": "Javascript" }, { "code": "// C++ program to find Noble elements// in an array.#include<bits/stdc++.h>using namespace std; // Returns a Noble integer if present,// else returns -1.int nobleInteger(int arr[], int n){ sort(arr, arr + n); // Return a Noble element if present // before last. for (int i = 0; i < n - 1; i++) { if (arr[i] == arr[i + 1]) continue; // In case of duplicates, we // reach last occurrence here. if (arr[i] == n - i - 1) return arr[i]; } if (arr[n - 1] == 0) return arr[n - 1]; return -1;} // Driver codeint main(){ int arr[] = {10, 3, 20, 40, 2}; int res = nobleInteger(arr, 5); if (res != -1) cout << \"The noble integer is \" << res; else cout << \"No Noble Integer Found\"; return 0;} // This code is contributed by Rajput-Ji", "e": 7312, "s": 6478, "text": null }, { "code": "// Java program to find Noble elements// in an array.import java.util.Arrays; public class Main{ // Returns a Noble integer if present, // else returns -1. public static int nobleInteger(int arr[]) { Arrays.sort(arr); // Return a Noble element if present // before last. int n = arr.length; for (int i=0; i<n-1; i++) { if (arr[i] == arr[i+1]) continue; // In case of duplicates, we // reach last occurrence here. if (arr[i] == n-i-1) return arr[i]; } if (arr[n-1] == 0) return arr[n-1]; return -1; } // Driver code public static void main(String args[]) { int [] arr = {10, 3, 20, 40, 2}; int res = nobleInteger(arr); if (res != -1) System.out.println(\"The noble integer is \"+ res); else System.out.println(\"No Noble Integer Found\"); }}", "e": 8279, "s": 7312, "text": null }, { "code": "# Python3 code to find Noble elements# in an array def nobleInteger(arr): arr.sort() # Return a Noble element if # present before last n = len(arr) for i in range(n - 1): if arr[i] == arr[i + 1]: continue # In case of duplicates we reach # last occurrence here if arr[i] == n - i - 1: return arr[i] if arr[n - 1] == 0: return arr[n - 1] return -1 # Driver codearr = [10, 3, 20, 40, 2] res = nobleInteger(arr) if res != -1: print(\"The noble integer is\", res)else: print(\"No Noble Integer Found\") # This code is contributed# by Mohit Kumar", "e": 8943, "s": 8279, "text": null }, { "code": "// C# program to find Noble elements// in an array.using System; public class GFG { public static int nobleInteger(int[] arr) { Array.Sort(arr); // Return a Noble element if present // before last. int n = arr.Length; for (int i = 0; i < n-1; i++) { if (arr[i] == arr[i+1]) continue; // In case of duplicates, we // reach last occurrence here. if (arr[i] == n-i-1) return arr[i]; } if (arr[n-1] == 0) return arr[n-1]; return -1; } // Driver code static public void Main () { int [] arr = {10, 3, 20, 40, 2}; int res = nobleInteger(arr); if (res != -1) Console.Write(\"The noble integer is \" + res); else Console.Write(\"No Noble Integer \" + \"Found\"); }} // This code is contributed by Shrikant13.", "e": 9946, "s": 8943, "text": null }, { "code": "<?php// PHP program to find Noble elements // Returns a Noble integer if present,// else returns -1.function nobleInteger( $arr) { sort($arr); // Return a Noble element if // present before last. $n = count($arr); for ( $i = 0; $i < $n - 1; $i++) { if ($arr[$i] == $arr[$i + 1]) continue; // In case of duplicates, we // reach last occurrence here. if ($arr[$i] == $n - $i - 1) return $arr[$i]; } if ($arr[$n - 1] == 0) return $arr[$n - 1]; return -1; } // Driver code $arr = array(10, 3, 20, 40, 2); $res = nobleInteger($arr); if ($res != -1) echo \"The noble integer is \", $res; else echo \"No Noble Integer Found\"; // This code is contributed by anuj_67.?>", "e": 10792, "s": 9946, "text": null }, { "code": "<script> // Javascript program to find Noble elements// in an array. // Returns a Noble integer if present,// else returns -1.function nobleInteger(arr){ arr.sort(function(a, b){return a - b;}); // Return a Noble element if present // before last. let n = arr.length; for(let i = 0; i < n - 1; i++) { if (arr[i] == arr[i + 1]) continue; // In case of duplicates, we // reach last occurrence here. if (arr[i] == n - i - 1) return arr[i]; } if (arr[n - 1] == 0) return arr[n - 1]; return -1;} // Driver codelet arr = [ 10, 3, 20, 40, 2 ];let res = nobleInteger(arr);if (res != -1) document.write(\"The noble integer is \" + res);else document.write(\"No Noble Integer Found\"); // This code is contributed by patel2127 </script>", "e": 11612, "s": 10792, "text": null }, { "code": null, "e": 11635, "s": 11612, "text": "The noble integer is 3" }, { "code": null, "e": 11665, "s": 11635, "text": "Method 3 (Using Count Array):" }, { "code": null, "e": 11766, "s": 11665, "text": "Maintain a count array countArr[] which keeps count of all elements greater than or equal to arr[i]." }, { "code": null, "e": 12362, "s": 11766, "text": "Declare an integer array countArr[] of size n + 1 (where n is the size of given array arr), and initialize it as zero.Iterate through array arr, if arr[i] < 0, we ignore it, if arr[i] >= n, we increment countArr[n], else simply increment countArr[arr[i]].Declare an integer totalGreater, which keeps count of elements greater than current element, and initialize it as countArr[arr[n]].Iterate through count array countArr from last to first index, if at any point we find that totalGreater = i for countArr[i] > 0, we have found our solution. Else keep increasing totalGreater with countArr[i]." }, { "code": null, "e": 12481, "s": 12362, "text": "Declare an integer array countArr[] of size n + 1 (where n is the size of given array arr), and initialize it as zero." }, { "code": null, "e": 12619, "s": 12481, "text": "Iterate through array arr, if arr[i] < 0, we ignore it, if arr[i] >= n, we increment countArr[n], else simply increment countArr[arr[i]]." }, { "code": null, "e": 12751, "s": 12619, "text": "Declare an integer totalGreater, which keeps count of elements greater than current element, and initialize it as countArr[arr[n]]." }, { "code": null, "e": 12961, "s": 12751, "text": "Iterate through count array countArr from last to first index, if at any point we find that totalGreater = i for countArr[i] > 0, we have found our solution. Else keep increasing totalGreater with countArr[i]." }, { "code": null, "e": 12977, "s": 12961, "text": "Implementation:" }, { "code": null, "e": 12981, "s": 12977, "text": "C++" }, { "code": null, "e": 12986, "s": 12981, "text": "Java" }, { "code": null, "e": 12994, "s": 12986, "text": "Python3" }, { "code": null, "e": 12997, "s": 12994, "text": "C#" }, { "code": null, "e": 13008, "s": 12997, "text": "Javascript" }, { "code": "// C++ program to find Noble elements// in an array.#include <bits/stdc++.h>using namespace std; int nobleInteger(int arr[], int n){ // Declare a countArr which keeps // count of all elements // greater than or equal to arr[i]. // Initialize it with zero. int countArr[n + 1] = { 0 }; // Iterating through the given array for (int i = 0; i < n; i++) { // If current element is less // than zero, it cannot // be a solution so we skip it. if (arr[i] < 0) { continue; } // If current element is >= size of input array, if // will be greater than all elements which can be // considered as our solution, as it cannot be // greater than size of array. else if (arr[i] >= n) { countArr[n]++; } // Else we increase the count // of elements >= our // current array in countArr else { countArr[arr[i]]++; } } // Initially, countArr[n] is // count of elements greater // than all possible solutions int totalGreater = countArr[n]; // Iterating through countArr for (int i = n - 1; i >= 0; i--) { // If totalGreater = current index, means we found // arr[i] for which count of elements >= arr[i] is // equal to arr[i] if (totalGreater == i && countArr[i] > 0) { return i; } // If at any point count of elements greater than // arr[i] becomes more than current index, then it // means we can no longer have a solution else if (totalGreater > i) { return -1; } // Adding count of elements >= arr[i] to // totalGreater. totalGreater += countArr[i]; } return -1;} // Driver Codeint main(){ int arr[] = { 10, 3, 20, 40, 2 }; int res = nobleInteger(arr, 5); if (res != -1) cout << \"The noble integer is \" << res; else cout << \"No Noble Integer Found\"; return 0;}", "e": 15023, "s": 13008, "text": null }, { "code": "// Java program to find Noble elements// in an array.import java.util.Arrays;class GFG { static int nobleInteger(int arr[], int n) { // Declare a countArr which keeps // count of all elements // greater than or equal to arr[i]. // Initialize it with zero. int countArr[] = new int[n + 1]; Arrays.fill(countArr, 0); // Iterating through the given array for (int i = 0; i < n; i++) { // If current element is less // than zero, it cannot // be a solution so we skip it. if (arr[i] < 0) { continue; } // If current element is >= size of input array, if // will be greater than all elements which can be // considered as our solution, as it cannot be // greater than size of array. else if (arr[i] >= n) { countArr[n]++; } // Else we increase the count // of elements >= our // current array in countArr else { countArr[arr[i]]++; } } // Initially, countArr[n] is // count of elements greater // than all possible solutions int totalGreater = countArr[n]; // Iterating through countArr for (int i = n - 1; i >= 0; i--) { // If totalGreater = current index, means we found // arr[i] for which count of elements >= arr[i] is // equal to arr[i] if (totalGreater == i && countArr[i] > 0) { return i; } // If at any point count of elements greater than // arr[i] becomes more than current index, then it // means we can no longer have a solution else if (totalGreater > i) { return -1; } // Adding count of elements >= arr[i] to // totalGreater. totalGreater += countArr[i]; } return -1; } // Driver Code public static void main(String args[]) { int arr[] = { 10, 3, 20, 40, 2 }; int res = nobleInteger(arr, 5); if (res != -1) System.out.println(\"The noble integer is \" + res); else System.out.println(\"No Noble Integer Found\"); }} // This code is contributed by saurabh_jaiswal.", "e": 17065, "s": 15023, "text": null }, { "code": "# Python program to find Noble elements# in an array.def nobleInteger(arr, n): # Declare a countArr which keeps # count of all elements # greater than or equal to arr[i]. # Initialize it with zero. countArr = [0] * (n + 1) # Iterating through the given array for i in range(n): # If current element is less # than zero, it cannot # be a solution so we skip it. if (arr[i] < 0): continue # If current element is >= size of input # array, if will be greater than all # elements which can be considered as # our solution, as it cannot be # greater than size of array. else if (arr[i] >= n): countArr[n] += 1 # Else we increase the count # of elements >= our # current array in countArr else: countArr[arr[i]] += 1 # Initially, countArr[n] is # count of elements greater # than all possible solutions totalGreater = countArr[n] # Iterating through countArr for i in range(n - 1, -1, -1): # If totalGreater = current index, # means we found arr[i] for which # count of elements >= arr[i] is # equal to arr[i] if (totalGreater == i and countArr[i] > 0): return i # If at any point count of elements # greater than arr[i] becomes more # than current index, then it means # we can no longer have a solution else if (totalGreater > i): return -1 # Adding count of elements >= arr[i] to # totalGreater. totalGreater += countArr[i] return -1 # Driver Codearr = [10, 3, 20, 40, 2]res = nobleInteger(arr, 5) if (res != -1): print(f\"The noble integer is {res}\")else: print(\"No Noble Integer Found\") # This code is contributed by gfgking", "e": 18890, "s": 17065, "text": null }, { "code": "// C# program to find Noble elements// in an array.using System; public class GFG { static int nobleInteger(int[] arr, int n) { // Declare a countArr which keeps // count of all elements // greater than or equal to arr[i]. // Initialize it with zero. int[] countArr = new int[n + 1]; for (int i = 0; i < n + 1; i++) countArr[i] = 0; // Iterating through the given array for (int i = 0; i < n; i++) { // If current element is less // than zero, it cannot // be a solution so we skip it. if (arr[i] < 0) { continue; } // If current element is >= size of input array, // if will be greater than all elements which // can be considered as our solution, as it // cannot be greater than size of array. else if (arr[i] >= n) { countArr[n]++; } // Else we increase the count // of elements >= our // current array in countArr else { countArr[arr[i]]++; } } // Initially, countArr[n] is // count of elements greater // than all possible solutions int totalGreater = countArr[n]; // Iterating through countArr for (int i = n - 1; i >= 0; i--) { // If totalGreater = current index, means we // found arr[i] for which count of elements >= // arr[i] is equal to arr[i] if (totalGreater == i && countArr[i] > 0) { return i; } // If at any point count of elements greater // than arr[i] becomes more than current index, // then it means we can no longer have a // solution else if (totalGreater > i) { return -1; } // Adding count of elements >= arr[i] to // totalGreater. totalGreater += countArr[i]; } return -1; } // Driver code static public void Main() { int[] arr = { 10, 3, 20, 40, 2 }; int n = arr.Length; int res = nobleInteger(arr, n); if (res != -1) Console.Write(\"The noble integer is \" + res); else Console.Write(\"No Noble Integer \" + \"Found\"); }} // This code is contributed by Aarti_Rathi", "e": 20983, "s": 18890, "text": null }, { "code": "<script> // JavaScript program to find Noble elements// in an array.function nobleInteger(arr, n){ // Declare a countArr which keeps // count of all elements // greater than or equal to arr[i]. // Initialize it with zero. let countArr = new Uint8Array(n + 1); // Iterating through the given array for(let i = 0; i < n; i++) { // If current element is less // than zero, it cannot // be a solution so we skip it. if (arr[i] < 0) { continue; } // If current element is >= size of input // array, if will be greater than all // elements which can be considered as // our solution, as it cannot be // greater than size of array. else if (arr[i] >= n) { countArr[n]++; } // Else we increase the count // of elements >= our // current array in countArr else { countArr[arr[i]]++; } } // Initially, countArr[n] is // count of elements greater // than all possible solutions let totalGreater = countArr[n]; // Iterating through countArr for(let i = n - 1; i >= 0; i--) { // If totalGreater = current index, // means we found arr[i] for which // count of elements >= arr[i] is // equal to arr[i] if (totalGreater == i && countArr[i] > 0) { return i; } // If at any point count of elements // greater than arr[i] becomes more // than current index, then it means // we can no longer have a solution else if (totalGreater > i) { return -1; } // Adding count of elements >= arr[i] to // totalGreater. totalGreater += countArr[i]; } return -1;} // Driver Codelet arr = [ 10, 3, 20, 40, 2 ];let res = nobleInteger(arr, 5); if (res != -1) document.write(\"The noble integer is \" + res);else document.write(\"No Noble Integer Found\"); // This code is contributed by Surbhi Tyagi. </script>", "e": 23064, "s": 20983, "text": null }, { "code": null, "e": 23087, "s": 23064, "text": "The noble integer is 3" }, { "code": null, "e": 23259, "s": 23087, "text": "Complexity Analysis:Time Complexity: O(n). As we iterate through both input array and countArr once.Space Complexity: O(n). As we use countArr of size same as given array." }, { "code": null, "e": 23340, "s": 23259, "text": "Time Complexity: O(n). As we iterate through both input array and countArr once." }, { "code": null, "e": 23412, "s": 23340, "text": "Space Complexity: O(n). As we use countArr of size same as given array." }, { "code": null, "e": 24282, "s": 23412, "text": "Noble integers in an array | GeeksforGeeks - YouTubeGeeksforGeeks532K subscribersNoble integers in an array | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:42β€’Liveβ€’<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=0bm_x59CVLA\" 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": 24579, "s": 24282, "text": "This article is contributed by Saloni Baweja. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 24591, "s": 24579, "text": "shrikanth13" }, { "code": null, "e": 24612, "s": 24591, "text": "Smitha Dinesh Semwal" }, { "code": null, "e": 24617, "s": 24612, "text": "vt_m" }, { "code": null, "e": 24632, "s": 24617, "text": "mohit kumar 29" }, { "code": null, "e": 24642, "s": 24632, "text": "Rajput-Ji" }, { "code": null, "e": 24653, "s": 24642, "text": "nidhi_biet" }, { "code": null, "e": 24670, "s": 24653, "text": "prateekmandaliya" }, { "code": null, "e": 24682, "s": 24670, "text": "unknown2108" }, { "code": null, "e": 24692, "s": 24682, "text": "patel2127" }, { "code": null, "e": 24706, "s": 24692, "text": "surbhityagi15" }, { "code": null, "e": 24714, "s": 24706, "text": "gfgking" }, { "code": null, "e": 24727, "s": 24714, "text": "simmytarika5" }, { "code": null, "e": 24744, "s": 24727, "text": "_saurabh_jaiswal" }, { "code": null, "e": 24758, "s": 24744, "text": "codewithrathi" }, { "code": null, "e": 24775, "s": 24758, "text": "hardikkoriintern" }, { "code": null, "e": 24782, "s": 24775, "text": "Arrays" }, { "code": null, "e": 24790, "s": 24782, "text": "Sorting" }, { "code": null, "e": 24809, "s": 24790, "text": "Technical Scripter" }, { "code": null, "e": 24816, "s": 24809, "text": "Arrays" }, { "code": null, "e": 24824, "s": 24816, "text": "Sorting" } ]
How to hash string with md5 function in Node.js ?
13 Jun, 2022 Hashing means taking any string as a key and generating some other string for it as a value. It’s like key-value pair in maps or dictionaries. md5 hash is an encryption algorithm that takes the various bits of a file and outputs a unique text string. md5 is a one-way encryption algorithm, i.e. there is no direct way of decryption. Using md5 hashing, you can only compare if two strings are equal or not by comparing the hash strings generated for them. For this purpose, we are going to use the md5 npm package and prompt module md5 is a javascript module that is used to encrypt the data and the prompt module is used for taking the input from the terminal. Steps to use md5 function to hash the string: Step 1: create an β€œapp.js” file and initialize the project using npm. npm init Step 2: Install md5 and prompt npm packages using npm install. npm install md5 npm install prompt Project structure: Step 3: Now let’s code the β€œapp.js” file. We take the required string as input from the user then use the md5() function to generate its hash string. app.js Javascript // Prompt is used to take input from consoleconst prompt = require("prompt"); // md5 is used to hash the given stringconst md5 = require("md5"); // Utility function to perform the operationfunction hash() { // Start the prompt prompt.start(); // Get string input as str from the console prompt.get(["str"], function (err, res) { // To handle any error if occurred if (err) { console.log(err); } else { // To generate the hashed string const hash = md5(res.str); // To print hashed string in the console console.log("hashed string is: ", hash); } });} // Calling the functionhash(); Step 4: Run app.js file using below command: node app.js Output: nikhatkhan11 JavaScript-Questions NodeJS-Questions Picked Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n13 Jun, 2022" }, { "code": null, "e": 690, "s": 28, "text": "Hashing means taking any string as a key and generating some other string for it as a value. It’s like key-value pair in maps or dictionaries. md5 hash is an encryption algorithm that takes the various bits of a file and outputs a unique text string. md5 is a one-way encryption algorithm, i.e. there is no direct way of decryption. Using md5 hashing, you can only compare if two strings are equal or not by comparing the hash strings generated for them. For this purpose, we are going to use the md5 npm package and prompt module md5 is a javascript module that is used to encrypt the data and the prompt module is used for taking the input from the terminal." }, { "code": null, "e": 736, "s": 690, "text": "Steps to use md5 function to hash the string:" }, { "code": null, "e": 806, "s": 736, "text": "Step 1: create an β€œapp.js” file and initialize the project using npm." }, { "code": null, "e": 815, "s": 806, "text": "npm init" }, { "code": null, "e": 878, "s": 815, "text": "Step 2: Install md5 and prompt npm packages using npm install." }, { "code": null, "e": 913, "s": 878, "text": "npm install md5\nnpm install prompt" }, { "code": null, "e": 932, "s": 913, "text": "Project structure:" }, { "code": null, "e": 1082, "s": 932, "text": "Step 3: Now let’s code the β€œapp.js” file. We take the required string as input from the user then use the md5() function to generate its hash string." }, { "code": null, "e": 1089, "s": 1082, "text": "app.js" }, { "code": null, "e": 1100, "s": 1089, "text": "Javascript" }, { "code": "// Prompt is used to take input from consoleconst prompt = require(\"prompt\"); // md5 is used to hash the given stringconst md5 = require(\"md5\"); // Utility function to perform the operationfunction hash() { // Start the prompt prompt.start(); // Get string input as str from the console prompt.get([\"str\"], function (err, res) { // To handle any error if occurred if (err) { console.log(err); } else { // To generate the hashed string const hash = md5(res.str); // To print hashed string in the console console.log(\"hashed string is: \", hash); } });} // Calling the functionhash();", "e": 1729, "s": 1100, "text": null }, { "code": null, "e": 1774, "s": 1729, "text": "Step 4: Run app.js file using below command:" }, { "code": null, "e": 1786, "s": 1774, "text": "node app.js" }, { "code": null, "e": 1794, "s": 1786, "text": "Output:" }, { "code": null, "e": 1807, "s": 1794, "text": "nikhatkhan11" }, { "code": null, "e": 1828, "s": 1807, "text": "JavaScript-Questions" }, { "code": null, "e": 1845, "s": 1828, "text": "NodeJS-Questions" }, { "code": null, "e": 1852, "s": 1845, "text": "Picked" }, { "code": null, "e": 1860, "s": 1852, "text": "Node.js" }, { "code": null, "e": 1877, "s": 1860, "text": "Web Technologies" } ]
IBM HR Analytics Employee Attrition & Performance using KNN
02 Jun, 2022 Attrition is a problem that impacts all businesses, irrespective of geography, industry and size of the company. It is a major problem to an organization, and predicting turnover is at the forefront of the needs of Human Resources (HR) in many organizations. Organizations face huge costs resulting from employee turnover. With advances in machine learning and data science, it’s possible to predict the employee attrition and we will predict using KNN (k-nearest neighbours) algorithm. Dataset: The dataset that is published by the Human Resource department of IBM is made available at Kaggle. datasetCode: Implementation of KNN algorithm for classification.Loading the Libraries Python3 # performing linear algebraimport numpy as np # data processingimport pandas as pd # visualisationimport matplotlib.pyplot as pltimport seaborn as sns % matplotlib inline Code: Importing the dataset Python3 dataset = pd.read_csv("WA_Fn-UseC_-HR-Employee-Attrition.csv")print (dataset.head) Output : Code: Information about the dataset Python3 df.info() Output : RangeIndex: 1470 entries, 0 to 1469 Data columns (total 35 columns): Age 1470 non-null int64 Attrition 1470 non-null object BusinessTravel 1470 non-null object DailyRate 1470 non-null int64 Department 1470 non-null object DistanceFromHome 1470 non-null int64 Education 1470 non-null int64 EducationField 1470 non-null object EmployeeCount 1470 non-null int64 EmployeeNumber 1470 non-null int64 EnvironmentSatisfaction 1470 non-null int64 Gender 1470 non-null object HourlyRate 1470 non-null int64 JobInvolvement 1470 non-null int64 JobLevel 1470 non-null int64 JobRole 1470 non-null object JobSatisfaction 1470 non-null int64 MaritalStatus 1470 non-null object MonthlyIncome 1470 non-null int64 MonthlyRate 1470 non-null int64 NumCompaniesWorked 1470 non-null int64 Over18 1470 non-null object OverTime 1470 non-null object PercentSalaryHike 1470 non-null int64 PerformanceRating 1470 non-null int64 RelationshipSatisfaction 1470 non-null int64 StandardHours 1470 non-null int64 StockOptionLevel 1470 non-null int64 TotalWorkingYears 1470 non-null int64 TrainingTimesLastYear 1470 non-null int64 WorkLifeBalance 1470 non-null int64 YearsAtCompany 1470 non-null int64 YearsInCurrentRole 1470 non-null int64 YearsSinceLastPromotion 1470 non-null int64 YearsWithCurrManager 1470 non-null int64 dtypes: int64(26), object(9) memory usage: 402.0+ KB Code: Visualizing the data Python3 # heatmap to check the missing valueplt.figure(figsize =(10, 4))sns.heatmap(dataset.isnull(), yticklabels = False, cbar = False, cmap ='viridis') Output: So, we can see that there are no missing values in the dataset. This is a Binary Classification Problem, so the Distribution of instances among the 2 classes, is visualized below: Python3 sns.set_style('darkgrid')sns.countplot(x ='Attrition', data = dataset) Output: Code: Python3 sns.lmplot(x = 'Age', y = 'DailyRate', hue = 'Attrition', data = dataset) Output: Code : Python3 plt.figure(figsize =(10, 6))sns.boxplot(y ='MonthlyIncome', x ='Attrition', data = dataset) Output: Preprocessing the data In the dataset there are 4 irrelevant columns, i.e:EmployeeCount, EmployeeNumber, Over18 and StandardHour. So, we have to remove these for more accuracy. Code: Python3 dataset.drop('EmployeeCount', axis = 1, inplace = True)dataset.drop('StandardHours', axis = 1, inplace = True)dataset.drop('EmployeeNumber', axis = 1, inplace = True)dataset.drop('Over18', axis = 1, inplace = True)print(dataset.shape) Output: (1470, 31) So, we have removed the irrelevant column.Code: Input and Output data Python3 y = dataset.iloc[:, 1]X = datasetX.drop('Attrition', axis = 1, inplace = True) Code: Label Encoding Python3 from sklearn.preprocessing import LabelEncoderlb = LabelEncoder()y = lb.fit_transform(y) In the dataset there are 7 categorical data, so we have to change them to int data, i.e we have to create 7 dummy variable for better accuracy.Code: Dummy variable creation Python3 dum_BusinessTravel = pd.get_dummies(dataset['BusinessTravel'], prefix ='BusinessTravel')dum_Department = pd.get_dummies(dataset['Department'], prefix ='Department')dum_EducationField = pd.get_dummies(dataset['EducationField'], prefix ='EducationField')dum_Gender = pd.get_dummies(dataset['Gender'], prefix ='Gender', drop_first = True)dum_JobRole = pd.get_dummies(dataset['JobRole'], prefix ='JobRole')dum_MaritalStatus = pd.get_dummies(dataset['MaritalStatus'], prefix ='MaritalStatus')dum_OverTime = pd.get_dummies(dataset['OverTime'], prefix ='OverTime', drop_first = True)# Adding these dummy variable to input XX = pd.concat([x, dum_BusinessTravel, dum_Department, dum_EducationField, dum_Gender, dum_JobRole, dum_MaritalStatus, dum_OverTime], axis = 1)# Removing the categorical dataX.drop(['BusinessTravel', 'Department', 'EducationField', 'Gender', 'JobRole', 'MaritalStatus', 'OverTime'], axis = 1, inplace = True) print(X.shape)print(y.shape) Output: (1470, 49) (1470, ) Code: Splitting data to training and testing Python3 from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split( X, y, test_size = 0.25, random_state = 40) So, the preprocessing is done, now we have to apply KNN to the dataset. Model Execution code: Using KNeighborsClassifier for finding the best number of neighbour with the help of misclassification error. Python3 from sklearn.neighbors import KNeighborsClassifierneighbors = []cv_scores = [] from sklearn.model_selection import cross_val_score# perform 10 fold cross validationfor k in range(1, 40, 2): neighbors.append(k) knn = KNeighborsClassifier(n_neighbors = k) scores = cross_val_score( knn, X_train, y_train, cv = 10, scoring = 'accuracy') cv_scores.append(scores.mean())error_rate = [1-x for x in cv_scores] # determining the best koptimal_k = neighbors[error_rate.index(min(error_rate))]print('The optimal number of neighbors is % d ' % optimal_k) # plot misclassification error versus kplt.figure(figsize = (10, 6))plt.plot(range(1, 40, 2), error_rate, color ='blue', linestyle ='dashed', marker ='o', markerfacecolor ='red', markersize = 10)plt.xlabel('Number of neighbors')plt.ylabel('Misclassification Error')plt.show() Output: The optimal number of neighbors is 7 Code: Prediction Score Python3 from sklearn.model_selection import cross_val_predict, cross_val_scorefrom sklearn.metrics import accuracy_score, classification_reportfrom sklearn.metrics import confusion_matrix def print_score(clf, X_train, y_train, X_test, y_test, train = True): if train: print("Train Result:") print("------------") print("Classification Report: \n {}\n".format(classification_report( y_train, clf.predict(X_train)))) print("Confusion Matrix: \n {}\n".format(confusion_matrix( y_train, clf.predict(X_train)))) res = cross_val_score(clf, X_train, y_train, cv = 10, scoring ='accuracy') print("Average Accuracy: \t {0:.4f}".format(np.mean(res))) print("Accuracy SD: \t\t {0:.4f}".format(np.std(res))) print("accuracy score: {0:.4f}\n".format(accuracy_score( y_train, clf.predict(X_train)))) print("----------------------------------------------------------") elif train == False: print("Test Result:") print("-----------") print("Classification Report: \n {}\n".format( classification_report(y_test, clf.predict(X_test)))) print("Confusion Matrix: \n {}\n".format( confusion_matrix(y_test, clf.predict(X_test)))) print("accuracy score: {0:.4f}\n".format( accuracy_score(y_test, clf.predict(X_test)))) print("-----------------------------------------------------------") knn = KNeighborsClassifier(n_neighbors = 7)knn.fit(X_train, y_train)print_score(knn, X_train, y_train, X_test, y_test, train = True)print_score(knn, X_train, y_train, X_test, y_test, train = False) Output: Train Result: ------------ Classification Report: precision recall f1-score support 0 0.86 0.99 0.92 922 1 0.83 0.19 0.32 180 accuracy 0.86 1102 macro avg 0.85 0.59 0.62 1102 weighted avg 0.86 0.86 0.82 1102 Confusion Matrix: [[915 7] [145 35]] Average Accuracy: 0.8421 Accuracy SD: 0.0148 accuracy score: 0.8621 ----------------------------------------------------------- Test Result: ----------- Classification Report: precision recall f1-score support 0 0.84 0.96 0.90 311 1 0.14 0.04 0.06 57 accuracy 0.82 368 macro avg 0.49 0.50 0.48 368 weighted avg 0.74 0.82 0.77 368 Confusion Matrix: [[299 12] [ 55 2]] accuracy score: 0.8179 prachisoda1234 sagartomar9927 Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ML | Monte Carlo Tree Search (MCTS) Search Algorithms in AI Markov Decision Process Introduction to Recurrent Neural Network Getting started with Machine Learning Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function Python Dictionary How to get column names in Pandas dataframe
[ { "code": null, "e": 28, "s": 0, "text": "\n02 Jun, 2022" }, { "code": null, "e": 710, "s": 28, "text": "Attrition is a problem that impacts all businesses, irrespective of geography, industry and size of the company. It is a major problem to an organization, and predicting turnover is at the forefront of the needs of Human Resources (HR) in many organizations. Organizations face huge costs resulting from employee turnover. With advances in machine learning and data science, it’s possible to predict the employee attrition and we will predict using KNN (k-nearest neighbours) algorithm. Dataset: The dataset that is published by the Human Resource department of IBM is made available at Kaggle. datasetCode: Implementation of KNN algorithm for classification.Loading the Libraries " }, { "code": null, "e": 718, "s": 710, "text": "Python3" }, { "code": "# performing linear algebraimport numpy as np # data processingimport pandas as pd # visualisationimport matplotlib.pyplot as pltimport seaborn as sns % matplotlib inline", "e": 889, "s": 718, "text": null }, { "code": null, "e": 919, "s": 889, "text": "Code: Importing the dataset " }, { "code": null, "e": 927, "s": 919, "text": "Python3" }, { "code": "dataset = pd.read_csv(\"WA_Fn-UseC_-HR-Employee-Attrition.csv\")print (dataset.head)", "e": 1010, "s": 927, "text": null }, { "code": null, "e": 1020, "s": 1010, "text": "Output : " }, { "code": null, "e": 1057, "s": 1020, "text": "Code: Information about the dataset " }, { "code": null, "e": 1065, "s": 1057, "text": "Python3" }, { "code": "df.info()", "e": 1075, "s": 1065, "text": null }, { "code": null, "e": 1085, "s": 1075, "text": "Output : " }, { "code": null, "e": 2896, "s": 1085, "text": "RangeIndex: 1470 entries, 0 to 1469\nData columns (total 35 columns):\nAge 1470 non-null int64\nAttrition 1470 non-null object\nBusinessTravel 1470 non-null object\nDailyRate 1470 non-null int64\nDepartment 1470 non-null object\nDistanceFromHome 1470 non-null int64\nEducation 1470 non-null int64\nEducationField 1470 non-null object\nEmployeeCount 1470 non-null int64\nEmployeeNumber 1470 non-null int64\nEnvironmentSatisfaction 1470 non-null int64\nGender 1470 non-null object\nHourlyRate 1470 non-null int64\nJobInvolvement 1470 non-null int64\nJobLevel 1470 non-null int64\nJobRole 1470 non-null object\nJobSatisfaction 1470 non-null int64\nMaritalStatus 1470 non-null object\nMonthlyIncome 1470 non-null int64\nMonthlyRate 1470 non-null int64\nNumCompaniesWorked 1470 non-null int64\nOver18 1470 non-null object\nOverTime 1470 non-null object\nPercentSalaryHike 1470 non-null int64\nPerformanceRating 1470 non-null int64\nRelationshipSatisfaction 1470 non-null int64\nStandardHours 1470 non-null int64\nStockOptionLevel 1470 non-null int64\nTotalWorkingYears 1470 non-null int64\nTrainingTimesLastYear 1470 non-null int64\nWorkLifeBalance 1470 non-null int64\nYearsAtCompany 1470 non-null int64\nYearsInCurrentRole 1470 non-null int64\nYearsSinceLastPromotion 1470 non-null int64\nYearsWithCurrManager 1470 non-null int64\ndtypes: int64(26), object(9)\nmemory usage: 402.0+ KB" }, { "code": null, "e": 2924, "s": 2896, "text": "Code: Visualizing the data " }, { "code": null, "e": 2932, "s": 2924, "text": "Python3" }, { "code": "# heatmap to check the missing valueplt.figure(figsize =(10, 4))sns.heatmap(dataset.isnull(), yticklabels = False, cbar = False, cmap ='viridis')", "e": 3078, "s": 2932, "text": null }, { "code": null, "e": 3087, "s": 3078, "text": "Output: " }, { "code": null, "e": 3268, "s": 3087, "text": "So, we can see that there are no missing values in the dataset. This is a Binary Classification Problem, so the Distribution of instances among the 2 classes, is visualized below: " }, { "code": null, "e": 3276, "s": 3268, "text": "Python3" }, { "code": "sns.set_style('darkgrid')sns.countplot(x ='Attrition', data = dataset)", "e": 3347, "s": 3276, "text": null }, { "code": null, "e": 3356, "s": 3347, "text": "Output: " }, { "code": null, "e": 3363, "s": 3356, "text": "Code: " }, { "code": null, "e": 3371, "s": 3363, "text": "Python3" }, { "code": "sns.lmplot(x = 'Age', y = 'DailyRate', hue = 'Attrition', data = dataset)", "e": 3445, "s": 3371, "text": null }, { "code": null, "e": 3454, "s": 3445, "text": "Output: " }, { "code": null, "e": 3464, "s": 3456, "text": "Code : " }, { "code": null, "e": 3472, "s": 3464, "text": "Python3" }, { "code": "plt.figure(figsize =(10, 6))sns.boxplot(y ='MonthlyIncome', x ='Attrition', data = dataset)", "e": 3564, "s": 3472, "text": null }, { "code": null, "e": 3574, "s": 3564, "text": "Output: " }, { "code": null, "e": 3760, "s": 3576, "text": "Preprocessing the data In the dataset there are 4 irrelevant columns, i.e:EmployeeCount, EmployeeNumber, Over18 and StandardHour. So, we have to remove these for more accuracy. Code: " }, { "code": null, "e": 3768, "s": 3760, "text": "Python3" }, { "code": "dataset.drop('EmployeeCount', axis = 1, inplace = True)dataset.drop('StandardHours', axis = 1, inplace = True)dataset.drop('EmployeeNumber', axis = 1, inplace = True)dataset.drop('Over18', axis = 1, inplace = True)print(dataset.shape)", "e": 4003, "s": 3768, "text": null }, { "code": null, "e": 4012, "s": 4003, "text": "Output: " }, { "code": null, "e": 4023, "s": 4012, "text": "(1470, 31)" }, { "code": null, "e": 4095, "s": 4023, "text": "So, we have removed the irrelevant column.Code: Input and Output data " }, { "code": null, "e": 4103, "s": 4095, "text": "Python3" }, { "code": "y = dataset.iloc[:, 1]X = datasetX.drop('Attrition', axis = 1, inplace = True)", "e": 4182, "s": 4103, "text": null }, { "code": null, "e": 4204, "s": 4182, "text": "Code: Label Encoding " }, { "code": null, "e": 4212, "s": 4204, "text": "Python3" }, { "code": "from sklearn.preprocessing import LabelEncoderlb = LabelEncoder()y = lb.fit_transform(y)", "e": 4301, "s": 4212, "text": null }, { "code": null, "e": 4476, "s": 4301, "text": "In the dataset there are 7 categorical data, so we have to change them to int data, i.e we have to create 7 dummy variable for better accuracy.Code: Dummy variable creation " }, { "code": null, "e": 4484, "s": 4476, "text": "Python3" }, { "code": "dum_BusinessTravel = pd.get_dummies(dataset['BusinessTravel'], prefix ='BusinessTravel')dum_Department = pd.get_dummies(dataset['Department'], prefix ='Department')dum_EducationField = pd.get_dummies(dataset['EducationField'], prefix ='EducationField')dum_Gender = pd.get_dummies(dataset['Gender'], prefix ='Gender', drop_first = True)dum_JobRole = pd.get_dummies(dataset['JobRole'], prefix ='JobRole')dum_MaritalStatus = pd.get_dummies(dataset['MaritalStatus'], prefix ='MaritalStatus')dum_OverTime = pd.get_dummies(dataset['OverTime'], prefix ='OverTime', drop_first = True)# Adding these dummy variable to input XX = pd.concat([x, dum_BusinessTravel, dum_Department, dum_EducationField, dum_Gender, dum_JobRole, dum_MaritalStatus, dum_OverTime], axis = 1)# Removing the categorical dataX.drop(['BusinessTravel', 'Department', 'EducationField', 'Gender', 'JobRole', 'MaritalStatus', 'OverTime'], axis = 1, inplace = True) print(X.shape)print(y.shape)", "e": 5698, "s": 4484, "text": null }, { "code": null, "e": 5707, "s": 5698, "text": "Output: " }, { "code": null, "e": 5727, "s": 5707, "text": "(1470, 49)\n(1470, )" }, { "code": null, "e": 5774, "s": 5727, "text": "Code: Splitting data to training and testing " }, { "code": null, "e": 5782, "s": 5774, "text": "Python3" }, { "code": "from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split( X, y, test_size = 0.25, random_state = 40)", "e": 5933, "s": 5782, "text": null }, { "code": null, "e": 6138, "s": 5933, "text": "So, the preprocessing is done, now we have to apply KNN to the dataset. Model Execution code: Using KNeighborsClassifier for finding the best number of neighbour with the help of misclassification error. " }, { "code": null, "e": 6146, "s": 6138, "text": "Python3" }, { "code": "from sklearn.neighbors import KNeighborsClassifierneighbors = []cv_scores = [] from sklearn.model_selection import cross_val_score# perform 10 fold cross validationfor k in range(1, 40, 2): neighbors.append(k) knn = KNeighborsClassifier(n_neighbors = k) scores = cross_val_score( knn, X_train, y_train, cv = 10, scoring = 'accuracy') cv_scores.append(scores.mean())error_rate = [1-x for x in cv_scores] # determining the best koptimal_k = neighbors[error_rate.index(min(error_rate))]print('The optimal number of neighbors is % d ' % optimal_k) # plot misclassification error versus kplt.figure(figsize = (10, 6))plt.plot(range(1, 40, 2), error_rate, color ='blue', linestyle ='dashed', marker ='o', markerfacecolor ='red', markersize = 10)plt.xlabel('Number of neighbors')plt.ylabel('Misclassification Error')plt.show()", "e": 6999, "s": 6146, "text": null }, { "code": null, "e": 7008, "s": 6999, "text": "Output: " }, { "code": null, "e": 7048, "s": 7008, "text": "The optimal number of neighbors is 7 " }, { "code": null, "e": 7072, "s": 7048, "text": "Code: Prediction Score " }, { "code": null, "e": 7080, "s": 7072, "text": "Python3" }, { "code": "from sklearn.model_selection import cross_val_predict, cross_val_scorefrom sklearn.metrics import accuracy_score, classification_reportfrom sklearn.metrics import confusion_matrix def print_score(clf, X_train, y_train, X_test, y_test, train = True): if train: print(\"Train Result:\") print(\"------------\") print(\"Classification Report: \\n {}\\n\".format(classification_report( y_train, clf.predict(X_train)))) print(\"Confusion Matrix: \\n {}\\n\".format(confusion_matrix( y_train, clf.predict(X_train)))) res = cross_val_score(clf, X_train, y_train, cv = 10, scoring ='accuracy') print(\"Average Accuracy: \\t {0:.4f}\".format(np.mean(res))) print(\"Accuracy SD: \\t\\t {0:.4f}\".format(np.std(res))) print(\"accuracy score: {0:.4f}\\n\".format(accuracy_score( y_train, clf.predict(X_train)))) print(\"----------------------------------------------------------\") elif train == False: print(\"Test Result:\") print(\"-----------\") print(\"Classification Report: \\n {}\\n\".format( classification_report(y_test, clf.predict(X_test)))) print(\"Confusion Matrix: \\n {}\\n\".format( confusion_matrix(y_test, clf.predict(X_test)))) print(\"accuracy score: {0:.4f}\\n\".format( accuracy_score(y_test, clf.predict(X_test)))) print(\"-----------------------------------------------------------\") knn = KNeighborsClassifier(n_neighbors = 7)knn.fit(X_train, y_train)print_score(knn, X_train, y_train, X_test, y_test, train = True)print_score(knn, X_train, y_train, X_test, y_test, train = False)", "e": 8790, "s": 7080, "text": null }, { "code": null, "e": 8799, "s": 8790, "text": "Output: " }, { "code": null, "e": 9811, "s": 8799, "text": "Train Result:\n------------\nClassification Report: \n precision recall f1-score support\n\n 0 0.86 0.99 0.92 922\n 1 0.83 0.19 0.32 180\n\n accuracy 0.86 1102\n macro avg 0.85 0.59 0.62 1102\nweighted avg 0.86 0.86 0.82 1102\n\n\nConfusion Matrix: \n [[915 7]\n [145 35]]\n\nAverage Accuracy: 0.8421\nAccuracy SD: 0.0148\naccuracy score: 0.8621\n\n-----------------------------------------------------------\nTest Result:\n-----------\nClassification Report: \n precision recall f1-score support\n\n 0 0.84 0.96 0.90 311\n 1 0.14 0.04 0.06 57\n\n accuracy 0.82 368\n macro avg 0.49 0.50 0.48 368\nweighted avg 0.74 0.82 0.77 368\n\n\nConfusion Matrix: \n [[299 12]\n [ 55 2]]\n\naccuracy score: 0.8179" }, { "code": null, "e": 9826, "s": 9811, "text": "prachisoda1234" }, { "code": null, "e": 9841, "s": 9826, "text": "sagartomar9927" }, { "code": null, "e": 9858, "s": 9841, "text": "Machine Learning" }, { "code": null, "e": 9865, "s": 9858, "text": "Python" }, { "code": null, "e": 9882, "s": 9865, "text": "Machine Learning" }, { "code": null, "e": 9980, "s": 9882, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 10016, "s": 9980, "text": "ML | Monte Carlo Tree Search (MCTS)" }, { "code": null, "e": 10040, "s": 10016, "text": "Search Algorithms in AI" }, { "code": null, "e": 10064, "s": 10040, "text": "Markov Decision Process" }, { "code": null, "e": 10105, "s": 10064, "text": "Introduction to Recurrent Neural Network" }, { "code": null, "e": 10143, "s": 10105, "text": "Getting started with Machine Learning" }, { "code": null, "e": 10171, "s": 10143, "text": "Read JSON file using Python" }, { "code": null, "e": 10221, "s": 10171, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 10243, "s": 10221, "text": "Python map() function" }, { "code": null, "e": 10261, "s": 10243, "text": "Python Dictionary" } ]
Encrypting and Decrypting the Files Using GnuPG in Linux
18 Jun, 2021 GnuPG is an encryption module that uses OpenPGP at its core. PGP stands for Pretty Good Privacy. It is an encryption program that provides authentication and cryptographic privacy for data communication. In the age where data is the new oil, the modern age thieves won’t intrude in through doors, windows or roofs, but instead, via wires and electrical signals in form of a few lines of code and commands. Nothing in this world is secure, which leads to an obvious conclusion that these thieves are inevitable. But instead of trying to figure out which door these thieves will intrude through, we might just need to focus on what is it they need ... Data. Data is the holy grail of wine which contains the ingredients of an individual’s social, financial, emotional, habitual and sometimes physical well-being. Encryption can serve as a solution to elude hackers, private organizations and government surveillance systems from monitoring your data. Encryption makes data useless to the person who does not possess a decryption key and useful to the one who does. If the key is lost, the data create remains locked forever. We are assuming that you have installed GnuPG already. If not, go to GnuPG official website and download the required software and install it. Encryption Process: 1. You can start the encryption process by generating a key. gpg --gen-key 2. A name and an email address will later serve you like an easy way to remember your key rather than the long key-id. 3. As soon as you choose okay a prompt for entering a passphrase will popup. This passphrase serves as a password for confirmation of the decryption key. It is a last line of defense for verification that the key belongs to you. 4. To see all the keys in your keyring, you can use the below command $gpg --list-keys 5. Considering a file named sample.txt which is to be encrypted. For encrypting, use the below command $gpg --output encryptionoutput.gpg --encrypt --recipient [email protected] sample.txt Here, .gpg is an extension used for encrypted files. Decryption Process: 1. The encrypted file named encryptionoutput.gpg from the above given encryption process is to be sent to the recipient and in case you being the recipient, decryption is needed. Use the below command: $gpg --output decrypted_sample.txt --decrypt encryptionoutput.gpg 2. Now it will ask you to enter the passphrase to unlock the OpenPGP secret key. Now, you can check the result using ls command. The decryption process will only work if the private key has been imported into the keyring. You can also confirm the decryption by reading the content of the original file and decrypted file. Important Points: Passphrase is needed for decryption, importing/exporting of private keys. GnuPG is user-specific as all other terminals programs i.e. if you run gpg as root then gpg will refer the root user keyring for further processes. Losing the private keys will result in a total loss of data encrypted via those keys and recovery will be impossible until the Quantum computers arrive and make the decryption math a child’s play. anikakapoor Technical Scripter 2019 Linux-Unix Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n18 Jun, 2021" }, { "code": null, "e": 540, "s": 28, "text": "GnuPG is an encryption module that uses OpenPGP at its core. PGP stands for Pretty Good Privacy. It is an encryption program that provides authentication and cryptographic privacy for data communication. In the age where data is the new oil, the modern age thieves won’t intrude in through doors, windows or roofs, but instead, via wires and electrical signals in form of a few lines of code and commands. Nothing in this world is secure, which leads to an obvious conclusion that these thieves are inevitable. " }, { "code": null, "e": 1153, "s": 540, "text": "But instead of trying to figure out which door these thieves will intrude through, we might just need to focus on what is it they need ... Data. Data is the holy grail of wine which contains the ingredients of an individual’s social, financial, emotional, habitual and sometimes physical well-being. Encryption can serve as a solution to elude hackers, private organizations and government surveillance systems from monitoring your data. Encryption makes data useless to the person who does not possess a decryption key and useful to the one who does. If the key is lost, the data create remains locked forever. " }, { "code": null, "e": 1298, "s": 1153, "text": "We are assuming that you have installed GnuPG already. If not, go to GnuPG official website and download the required software and install it. " }, { "code": null, "e": 1319, "s": 1298, "text": "Encryption Process: " }, { "code": null, "e": 1382, "s": 1319, "text": "1. You can start the encryption process by generating a key. " }, { "code": null, "e": 1397, "s": 1382, "text": "gpg --gen-key " }, { "code": null, "e": 1518, "s": 1397, "text": "2. A name and an email address will later serve you like an easy way to remember your key rather than the long key-id. " }, { "code": null, "e": 1748, "s": 1518, "text": "3. As soon as you choose okay a prompt for entering a passphrase will popup. This passphrase serves as a password for confirmation of the decryption key. It is a last line of defense for verification that the key belongs to you. " }, { "code": null, "e": 1819, "s": 1748, "text": "4. To see all the keys in your keyring, you can use the below command " }, { "code": null, "e": 1836, "s": 1819, "text": "$gpg --list-keys" }, { "code": null, "e": 1941, "s": 1836, "text": "5. Considering a file named sample.txt which is to be encrypted. For encrypting, use the below command " }, { "code": null, "e": 2032, "s": 1941, "text": "$gpg --output encryptionoutput.gpg --encrypt --recipient [email protected] sample.txt" }, { "code": null, "e": 2086, "s": 2032, "text": "Here, .gpg is an extension used for encrypted files. " }, { "code": null, "e": 2107, "s": 2086, "text": "Decryption Process: " }, { "code": null, "e": 2311, "s": 2107, "text": "1. The encrypted file named encryptionoutput.gpg from the above given encryption process is to be sent to the recipient and in case you being the recipient, decryption is needed. Use the below command: " }, { "code": null, "e": 2377, "s": 2311, "text": "$gpg --output decrypted_sample.txt --decrypt encryptionoutput.gpg" }, { "code": null, "e": 2460, "s": 2377, "text": "2. Now it will ask you to enter the passphrase to unlock the OpenPGP secret key. " }, { "code": null, "e": 2703, "s": 2460, "text": "Now, you can check the result using ls command. The decryption process will only work if the private key has been imported into the keyring. You can also confirm the decryption by reading the content of the original file and decrypted file. " }, { "code": null, "e": 2723, "s": 2703, "text": "Important Points: " }, { "code": null, "e": 2797, "s": 2723, "text": "Passphrase is needed for decryption, importing/exporting of private keys." }, { "code": null, "e": 2945, "s": 2797, "text": "GnuPG is user-specific as all other terminals programs i.e. if you run gpg as root then gpg will refer the root user keyring for further processes." }, { "code": null, "e": 3142, "s": 2945, "text": "Losing the private keys will result in a total loss of data encrypted via those keys and recovery will be impossible until the Quantum computers arrive and make the decryption math a child’s play." }, { "code": null, "e": 3156, "s": 3144, "text": "anikakapoor" }, { "code": null, "e": 3180, "s": 3156, "text": "Technical Scripter 2019" }, { "code": null, "e": 3191, "s": 3180, "text": "Linux-Unix" }, { "code": null, "e": 3210, "s": 3191, "text": "Technical Scripter" } ]
Python program to convert camel case string to snake case
01 Feb, 2021 Given a string in camel case, write a Python program to convert the given string from camel case to snake case.Examples: Input : GeeksForGeeks Output : geeks_for_geeks Input : ThisIsInCamelCase Output : this_is_in_camel_case Let’s see the different ways we can do this task. Method #1 : Naive ApproachThis is a naive implementation to convert camel case to snake case. First, we initialize a variable β€˜res’ with an empty list and append first character (in lower case) to it. Now, Each time we encounter a Capital alphabet, we append β€˜_’ and the alphabet (in lower case) to β€˜res’, otherwise, just append the alphabet only. Python3 # Python3 program to convert string# from camel case to snake case def change_case(str): res = [str[0].lower()] for c in str[1:]: if c in ('ABCDEFGHIJKLMNOPQRSTUVWXYZ'): res.append('_') res.append(c.lower()) else: res.append(c) return ''.join(res) # Driver codestr = "GeeksForGeeks"print(change_case(str)) geeks_for_geeks Method #2 : List comprehension Python3 # Python3 program to convert string# from camel case to snake case def change_case(str): return ''.join(['_'+i.lower() if i.isupper() else i for i in str]).lstrip('_') # Driver codestr = "GeeksForGeeks"print(change_case(str)) geeks_for_geeks Method #3 : Python reduce()Python reduce() method applies a function to all the string alphabets, that wherever it find uppercase alphabet, it add β€˜_’ in front of it and replace the uppercase alphabet with lowercase alphabet. Python3 # Python3 program to convert string# from camel case to snake casefrom functools import reduce def change_case(str): return reduce(lambda x, y: x + ('_' if y.isupper() else '') + y, str).lower() # Driver codestr = "GeeksForGeeks"print(change_case(str)) geeks_for_geeks Method #4 : Python Regex Python3 # Python3 program to convert string# from camel case to snake caseimport re def change_case(str): s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', str) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() # Driver codestr = "GeeksForGeeks"print(change_case(str)) geeks_for_geeks shubham_singh dulanthaf Python string-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Feb, 2021" }, { "code": null, "e": 150, "s": 28, "text": "Given a string in camel case, write a Python program to convert the given string from camel case to snake case.Examples: " }, { "code": null, "e": 255, "s": 150, "text": "Input : GeeksForGeeks\nOutput : geeks_for_geeks\n\nInput : ThisIsInCamelCase\nOutput : this_is_in_camel_case" }, { "code": null, "e": 655, "s": 255, "text": "Let’s see the different ways we can do this task. Method #1 : Naive ApproachThis is a naive implementation to convert camel case to snake case. First, we initialize a variable β€˜res’ with an empty list and append first character (in lower case) to it. Now, Each time we encounter a Capital alphabet, we append β€˜_’ and the alphabet (in lower case) to β€˜res’, otherwise, just append the alphabet only. " }, { "code": null, "e": 663, "s": 655, "text": "Python3" }, { "code": "# Python3 program to convert string# from camel case to snake case def change_case(str): res = [str[0].lower()] for c in str[1:]: if c in ('ABCDEFGHIJKLMNOPQRSTUVWXYZ'): res.append('_') res.append(c.lower()) else: res.append(c) return ''.join(res) # Driver codestr = \"GeeksForGeeks\"print(change_case(str))", "e": 1034, "s": 663, "text": null }, { "code": null, "e": 1050, "s": 1034, "text": "geeks_for_geeks" }, { "code": null, "e": 1085, "s": 1052, "text": " Method #2 : List comprehension" }, { "code": null, "e": 1093, "s": 1085, "text": "Python3" }, { "code": "# Python3 program to convert string# from camel case to snake case def change_case(str): return ''.join(['_'+i.lower() if i.isupper() else i for i in str]).lstrip('_') # Driver codestr = \"GeeksForGeeks\"print(change_case(str))", "e": 1345, "s": 1093, "text": null }, { "code": null, "e": 1361, "s": 1345, "text": "geeks_for_geeks" }, { "code": null, "e": 1592, "s": 1363, "text": " Method #3 : Python reduce()Python reduce() method applies a function to all the string alphabets, that wherever it find uppercase alphabet, it add β€˜_’ in front of it and replace the uppercase alphabet with lowercase alphabet. " }, { "code": null, "e": 1600, "s": 1592, "text": "Python3" }, { "code": "# Python3 program to convert string# from camel case to snake casefrom functools import reduce def change_case(str): return reduce(lambda x, y: x + ('_' if y.isupper() else '') + y, str).lower() # Driver codestr = \"GeeksForGeeks\"print(change_case(str))", "e": 1865, "s": 1600, "text": null }, { "code": null, "e": 1881, "s": 1865, "text": "geeks_for_geeks" }, { "code": null, "e": 1911, "s": 1883, "text": " Method #4 : Python Regex " }, { "code": null, "e": 1919, "s": 1911, "text": "Python3" }, { "code": "# Python3 program to convert string# from camel case to snake caseimport re def change_case(str): s1 = re.sub('(.)([A-Z][a-z]+)', r'\\1_\\2', str) return re.sub('([a-z0-9])([A-Z])', r'\\1_\\2', s1).lower() # Driver codestr = \"GeeksForGeeks\"print(change_case(str))", "e": 2189, "s": 1919, "text": null }, { "code": null, "e": 2205, "s": 2189, "text": "geeks_for_geeks" }, { "code": null, "e": 2221, "s": 2207, "text": "shubham_singh" }, { "code": null, "e": 2231, "s": 2221, "text": "dulanthaf" }, { "code": null, "e": 2254, "s": 2231, "text": "Python string-programs" }, { "code": null, "e": 2261, "s": 2254, "text": "Python" }, { "code": null, "e": 2277, "s": 2261, "text": "Python Programs" } ]
String containing first letter of every word in a given string with spaces
02 Jul, 2022 String str is given which contains lowercase English letters and spaces. It may contain multiple spaces. Get the first letter of every word and return the result as a string. The result should not contain any space. Examples: Input : str = "geeks for geeks" Output : gfg Input : str = "happy coding" Output : hc Source: https://www.geeksforgeeks.org/amazon-interview-set-8-2/ The idea is to traverse each character of string str and maintain a boolean variable, which was initially set as true. Whenever we encounter space we set the boolean variable is true. And if we encounter any character other than space, we will check the boolean variable, if it was set as true as copy that charter to the output string and set the boolean variable as false. If the boolean variable is set false, do nothing. Algorithm: 1. Traverse string str. And initialize a variable v as true. 2. If str[i] == ' '. Set v as true. 3. If str[i] != ' '. Check if v is true or not. a) If true, copy str[i] to output string and set v as false. b) If false, do nothing. C++ Java Python 3 C# Javascript // C++ program to find the string which contain// the first character of each word of another// string.#include<bits/stdc++.h>using namespace std; // Function to find string which has first// character of each word.string firstLetterWord(string str){ string result = ""; // Traverse the string. bool v = true; for (int i=0; i<str.length(); i++) { // If it is space, set v as true. if (str[i] == ' ') v = true; // Else check if v is true or not. // If true, copy character in output // string and set v as false. else if (str[i] != ' ' && v == true) { result.push_back(str[i]); v = false; } } return result;} // Driver codeint main(){ string str = "geeks for geeks"; cout << firstLetterWord(str); return 0;} // Java program to find the string which// contain the first character of each word // of another string. class GFG{ // Function to find string which has first // character of each word. static String firstLetterWord(String str) { String result = ""; // Traverse the string. boolean v = true; for (int i = 0; i < str.length(); i++) { // If it is space, set v as true. if (str.charAt(i) == ' ') { v = true; } // Else check if v is true or not. // If true, copy character in output // string and set v as false. else if (str.charAt(i) != ' ' && v == true) { result += (str.charAt(i)); v = false; } } return result; } // Driver code public static void main(String[] args) { String str = "geeks for geeks"; System.out.println(firstLetterWord(str)); }} // This code is contributed by// 29AjayKumar # Python 3 program to find the string which# contain the first character of each word# of another string. # Function to find string which has first# character of each word.def firstLetterWord(str): result = "" # Traverse the string. v = True for i in range(len(str)): # If it is space, set v as true. if (str[i] == ' '): v = True # Else check if v is true or not. # If true, copy character in output # string and set v as false. elif (str[i] != ' ' and v == True): result += (str[i]) v = False return result # Driver Codeif __name__ == "__main__": str = "geeks for geeks" print(firstLetterWord(str)) # This code is contributed by ita_c // C# program to find the string which// contain the first character of each word// of another string.using System; class GFG{ // Function to find string which has first // character of each word. static String firstLetterWord(String str) { String result = ""; // Traverse the string. bool v = true; for (int i = 0; i < str.Length; i++) { // If it is space, set v as true. if (str[i] == ' ') { v = true; } // Else check if v is true or not. // If true, copy character in output // string and set v as false. else if (str[i] != ' ' && v == true) { result += (str[i]); v = false; } } return result; } // Driver code public static void Main() { String str = "geeks for geeks"; Console.WriteLine(firstLetterWord(str)); }} // This code is contributed by PrinciRaj1992 <script> // Javascript program to find the string which // contain the first character of each word // of another string. // Function to find string which has first // character of each word. function firstLetterWord(str) { let result = ""; // Traverse the string. let v = true; for (let i = 0; i < str.length; i++) { // If it is space, set v as true. if (str[i] == ' ') { v = true; } // Else check if v is true or not. // If true, copy character in output // string and set v as false. else if (str[i] != ' ' && v == true) { result += (str[i]); v = false; } } return result; } let str = "geeks for geeks"; document.write(firstLetterWord(str)); </script> Output: gfg Time Complexity: O(n) Auxiliary space: O(n). This approach uses the StringBuilder class of Java. In this approach, we will first split the input string based on the spaces. The spaces in the strings can be matched using a regular expression. The split strings are stored in an array of strings. Then we can simply append the first character of each split string in the String Builder object. C++ Java Python3 C# Javascript // C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; string processWords(char *input){ /* we are splitting the input based on spaces (s)+ : this regular expression will handle scenarios where we have words separated by multiple spaces */ char *p; vector<string> s; p = strtok(input, " "); while (p != NULL) { s.push_back(p); p = strtok(NULL, " "); } string charBuffer; for (string values : s) /* charAt(0) will pick only the first character from the string and append to buffer */ charBuffer += values[0]; return charBuffer;} // Driver codeint main(){ char input[] = "geeks for geeks"; cout << processWords(input); return 0;} // This code is contributed by// sanjeev2552 // Java implementation of the above approach class GFG{ private static StringBuilder charBuffer = new StringBuilder(); public static String processWords(String input) { /* we are splitting the input based on spaces (s)+ : this regular expression will handle scenarios where we have words separated by multiple spaces */ String s[] = input.split("(\\s)+"); for(String values : s) { /* charAt(0) will pick only the first character from the string and append to buffer */ charBuffer.append(values.charAt(0)); } return charBuffer.toString(); } // main function public static void main (String[] args) { String input = "geeks for geeks geeks for geeks"; System.out.println(processWords(input)); }} // This code is contributed by Goutam Das # An efficient Python3 implementation# of above approachcharBuffer = []def processWords(input): """ we are splitting the input based on spaces (s)+ : this regular expression will handle scenarios where we have words separated by multiple spaces """ s = input.split(" ") for values in s: """ charAt(0) will pick only the first character from the string and append to buffer """ charBuffer.append(values[0]) return charBuffer # Driver Codeif __name__ == '__main__': input = "geeks for geeks" print(*processWords(input), sep = "") # This code is contributed# by SHUBHAMSINGH10 // C# implementation of above approachusing System;using System.Text; class GFG{ private static StringBuilder charBuffer = new StringBuilder(); public static String processWords(String input){ /* we are splitting the input based on spaces (s)+ : this regular expression will handle scenarios where we have words separated by multiple spaces */ String []s = input.Split(' '); foreach(String values in s) { /* charAt(0) will pick only the first character from the string and append to buffer */ charBuffer.Append(values[0]); } return charBuffer.ToString();} // Driver codepublic static void Main(){ String input = "geeks for geeks"; Console.WriteLine(processWords(input));}} // This code is contributed by Rajput-Ji <script>// Javascript implementation of the above approachvar charBuffer = ""; function processWords(input){ /* we are splitting the input based on spaces (s)+ : this regular expression will handle scenarios where we have words separated by multiple spaces */ var s = input.split(' '); s.forEach(element => { /* charAt(0) will pick only the first character from the string and append to buffer */ charBuffer+=element[0]; }); return charBuffer;} // Driver codevar input = "geeks for geeks";document.write( processWords(input)); // This code is contributed by rutvik_56.</script> Output: gfg Time Complexity: O(n2) Auxiliary space: O(n). Using boundary checker, refer https://www.geeksforgeeks.org/get-first-letter-word-string-using-regex-java/ This article is contributed by Aarti_Rathi and Anuj Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 29AjayKumar princiraj1992 Rajput-Ji ukasp gfg_sal_gfg SHUBHAMSINGH10 nidhi_biet sanjeev2552 mulchandanimanisha5 rameshtravel07 rutvik_56 akhilarora011 gulshankumarar231 codewithrathi Amazon School Programming Strings Amazon Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction To PYTHON Interfaces in Java Types of Operating Systems Operator Overloading in C++ Polymorphism in C++ Write a program to reverse an array or string Write a program to print all permutations of a given string Python program to check if a string is palindrome or not Check for Balanced Brackets in an expression (well-formedness) using Stack Longest Common Subsequence | DP-4
[ { "code": null, "e": 52, "s": 24, "text": "\n02 Jul, 2022" }, { "code": null, "e": 269, "s": 52, "text": "String str is given which contains lowercase English letters and spaces. It may contain multiple spaces. Get the first letter of every word and return the result as a string. The result should not contain any space. " }, { "code": null, "e": 280, "s": 269, "text": "Examples: " }, { "code": null, "e": 369, "s": 280, "text": "Input : str = \"geeks for geeks\"\nOutput : gfg\n\nInput : str = \"happy coding\"\nOutput : hc" }, { "code": null, "e": 433, "s": 369, "text": "Source: https://www.geeksforgeeks.org/amazon-interview-set-8-2/" }, { "code": null, "e": 870, "s": 433, "text": "The idea is to traverse each character of string str and maintain a boolean variable, which was initially set as true. Whenever we encounter space we set the boolean variable is true. And if we encounter any character other than space, we will check the boolean variable, if it was set as true as copy that charter to the output string and set the boolean variable as false. If the boolean variable is set false, do nothing. Algorithm: " }, { "code": null, "e": 1107, "s": 870, "text": "1. Traverse string str. And initialize a variable v as true.\n2. If str[i] == ' '. Set v as true.\n3. If str[i] != ' '. Check if v is true or not.\n a) If true, copy str[i] to output string and set v as false.\n b) If false, do nothing." }, { "code": null, "e": 1111, "s": 1107, "text": "C++" }, { "code": null, "e": 1116, "s": 1111, "text": "Java" }, { "code": null, "e": 1125, "s": 1116, "text": "Python 3" }, { "code": null, "e": 1128, "s": 1125, "text": "C#" }, { "code": null, "e": 1139, "s": 1128, "text": "Javascript" }, { "code": "// C++ program to find the string which contain// the first character of each word of another// string.#include<bits/stdc++.h>using namespace std; // Function to find string which has first// character of each word.string firstLetterWord(string str){ string result = \"\"; // Traverse the string. bool v = true; for (int i=0; i<str.length(); i++) { // If it is space, set v as true. if (str[i] == ' ') v = true; // Else check if v is true or not. // If true, copy character in output // string and set v as false. else if (str[i] != ' ' && v == true) { result.push_back(str[i]); v = false; } } return result;} // Driver codeint main(){ string str = \"geeks for geeks\"; cout << firstLetterWord(str); return 0;}", "e": 1968, "s": 1139, "text": null }, { "code": "// Java program to find the string which// contain the first character of each word // of another string. class GFG{ // Function to find string which has first // character of each word. static String firstLetterWord(String str) { String result = \"\"; // Traverse the string. boolean v = true; for (int i = 0; i < str.length(); i++) { // If it is space, set v as true. if (str.charAt(i) == ' ') { v = true; } // Else check if v is true or not. // If true, copy character in output // string and set v as false. else if (str.charAt(i) != ' ' && v == true) { result += (str.charAt(i)); v = false; } } return result; } // Driver code public static void main(String[] args) { String str = \"geeks for geeks\"; System.out.println(firstLetterWord(str)); }} // This code is contributed by// 29AjayKumar", "e": 3027, "s": 1968, "text": null }, { "code": "# Python 3 program to find the string which# contain the first character of each word# of another string. # Function to find string which has first# character of each word.def firstLetterWord(str): result = \"\" # Traverse the string. v = True for i in range(len(str)): # If it is space, set v as true. if (str[i] == ' '): v = True # Else check if v is true or not. # If true, copy character in output # string and set v as false. elif (str[i] != ' ' and v == True): result += (str[i]) v = False return result # Driver Codeif __name__ == \"__main__\": str = \"geeks for geeks\" print(firstLetterWord(str)) # This code is contributed by ita_c", "e": 3777, "s": 3027, "text": null }, { "code": "// C# program to find the string which// contain the first character of each word// of another string.using System; class GFG{ // Function to find string which has first // character of each word. static String firstLetterWord(String str) { String result = \"\"; // Traverse the string. bool v = true; for (int i = 0; i < str.Length; i++) { // If it is space, set v as true. if (str[i] == ' ') { v = true; } // Else check if v is true or not. // If true, copy character in output // string and set v as false. else if (str[i] != ' ' && v == true) { result += (str[i]); v = false; } } return result; } // Driver code public static void Main() { String str = \"geeks for geeks\"; Console.WriteLine(firstLetterWord(str)); }} // This code is contributed by PrinciRaj1992", "e": 4805, "s": 3777, "text": null }, { "code": "<script> // Javascript program to find the string which // contain the first character of each word // of another string. // Function to find string which has first // character of each word. function firstLetterWord(str) { let result = \"\"; // Traverse the string. let v = true; for (let i = 0; i < str.length; i++) { // If it is space, set v as true. if (str[i] == ' ') { v = true; } // Else check if v is true or not. // If true, copy character in output // string and set v as false. else if (str[i] != ' ' && v == true) { result += (str[i]); v = false; } } return result; } let str = \"geeks for geeks\"; document.write(firstLetterWord(str)); </script>", "e": 5733, "s": 4805, "text": null }, { "code": null, "e": 5742, "s": 5733, "text": "Output: " }, { "code": null, "e": 5746, "s": 5742, "text": "gfg" }, { "code": null, "e": 5768, "s": 5746, "text": "Time Complexity: O(n)" }, { "code": null, "e": 5792, "s": 5768, "text": "Auxiliary space: O(n). " }, { "code": null, "e": 6141, "s": 5792, "text": "This approach uses the StringBuilder class of Java. In this approach, we will first split the input string based on the spaces. The spaces in the strings can be matched using a regular expression. The split strings are stored in an array of strings. Then we can simply append the first character of each split string in the String Builder object. " }, { "code": null, "e": 6145, "s": 6141, "text": "C++" }, { "code": null, "e": 6150, "s": 6145, "text": "Java" }, { "code": null, "e": 6158, "s": 6150, "text": "Python3" }, { "code": null, "e": 6161, "s": 6158, "text": "C#" }, { "code": null, "e": 6172, "s": 6161, "text": "Javascript" }, { "code": "// C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; string processWords(char *input){ /* we are splitting the input based on spaces (s)+ : this regular expression will handle scenarios where we have words separated by multiple spaces */ char *p; vector<string> s; p = strtok(input, \" \"); while (p != NULL) { s.push_back(p); p = strtok(NULL, \" \"); } string charBuffer; for (string values : s) /* charAt(0) will pick only the first character from the string and append to buffer */ charBuffer += values[0]; return charBuffer;} // Driver codeint main(){ char input[] = \"geeks for geeks\"; cout << processWords(input); return 0;} // This code is contributed by// sanjeev2552", "e": 6966, "s": 6172, "text": null }, { "code": "// Java implementation of the above approach class GFG{ private static StringBuilder charBuffer = new StringBuilder(); public static String processWords(String input) { /* we are splitting the input based on spaces (s)+ : this regular expression will handle scenarios where we have words separated by multiple spaces */ String s[] = input.split(\"(\\\\s)+\"); for(String values : s) { /* charAt(0) will pick only the first character from the string and append to buffer */ charBuffer.append(values.charAt(0)); } return charBuffer.toString(); } // main function public static void main (String[] args) { String input = \"geeks for geeks geeks for geeks\"; System.out.println(processWords(input)); }} // This code is contributed by Goutam Das", "e": 7869, "s": 6966, "text": null }, { "code": "# An efficient Python3 implementation# of above approachcharBuffer = []def processWords(input): \"\"\" we are splitting the input based on spaces (s)+ : this regular expression will handle scenarios where we have words separated by multiple spaces \"\"\" s = input.split(\" \") for values in s: \"\"\" charAt(0) will pick only the first character from the string and append to buffer \"\"\" charBuffer.append(values[0]) return charBuffer # Driver Codeif __name__ == '__main__': input = \"geeks for geeks\" print(*processWords(input), sep = \"\") # This code is contributed# by SHUBHAMSINGH10", "e": 8500, "s": 7869, "text": null }, { "code": "// C# implementation of above approachusing System;using System.Text; class GFG{ private static StringBuilder charBuffer = new StringBuilder(); public static String processWords(String input){ /* we are splitting the input based on spaces (s)+ : this regular expression will handle scenarios where we have words separated by multiple spaces */ String []s = input.Split(' '); foreach(String values in s) { /* charAt(0) will pick only the first character from the string and append to buffer */ charBuffer.Append(values[0]); } return charBuffer.ToString();} // Driver codepublic static void Main(){ String input = \"geeks for geeks\"; Console.WriteLine(processWords(input));}} // This code is contributed by Rajput-Ji", "e": 9351, "s": 8500, "text": null }, { "code": "<script>// Javascript implementation of the above approachvar charBuffer = \"\"; function processWords(input){ /* we are splitting the input based on spaces (s)+ : this regular expression will handle scenarios where we have words separated by multiple spaces */ var s = input.split(' '); s.forEach(element => { /* charAt(0) will pick only the first character from the string and append to buffer */ charBuffer+=element[0]; }); return charBuffer;} // Driver codevar input = \"geeks for geeks\";document.write( processWords(input)); // This code is contributed by rutvik_56.</script>", "e": 10041, "s": 9351, "text": null }, { "code": null, "e": 10051, "s": 10041, "text": "Output: " }, { "code": null, "e": 10055, "s": 10051, "text": "gfg" }, { "code": null, "e": 10078, "s": 10055, "text": "Time Complexity: O(n2)" }, { "code": null, "e": 10102, "s": 10078, "text": "Auxiliary space: O(n). " }, { "code": null, "e": 10209, "s": 10102, "text": "Using boundary checker, refer https://www.geeksforgeeks.org/get-first-letter-word-string-using-regex-java/" }, { "code": null, "e": 10645, "s": 10209, "text": "This article is contributed by Aarti_Rathi and Anuj Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 10657, "s": 10645, "text": "29AjayKumar" }, { "code": null, "e": 10671, "s": 10657, "text": "princiraj1992" }, { "code": null, "e": 10681, "s": 10671, "text": "Rajput-Ji" }, { "code": null, "e": 10687, "s": 10681, "text": "ukasp" }, { "code": null, "e": 10699, "s": 10687, "text": "gfg_sal_gfg" }, { "code": null, "e": 10714, "s": 10699, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 10725, "s": 10714, "text": "nidhi_biet" }, { "code": null, "e": 10737, "s": 10725, "text": "sanjeev2552" }, { "code": null, "e": 10757, "s": 10737, "text": "mulchandanimanisha5" }, { "code": null, "e": 10772, "s": 10757, "text": "rameshtravel07" }, { "code": null, "e": 10782, "s": 10772, "text": "rutvik_56" }, { "code": null, "e": 10796, "s": 10782, "text": "akhilarora011" }, { "code": null, "e": 10814, "s": 10796, "text": "gulshankumarar231" }, { "code": null, "e": 10828, "s": 10814, "text": "codewithrathi" }, { "code": null, "e": 10835, "s": 10828, "text": "Amazon" }, { "code": null, "e": 10854, "s": 10835, "text": "School Programming" }, { "code": null, "e": 10862, "s": 10854, "text": "Strings" }, { "code": null, "e": 10869, "s": 10862, "text": "Amazon" }, { "code": null, "e": 10877, "s": 10869, "text": "Strings" }, { "code": null, "e": 10975, "s": 10877, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 10998, "s": 10975, "text": "Introduction To PYTHON" }, { "code": null, "e": 11017, "s": 10998, "text": "Interfaces in Java" }, { "code": null, "e": 11044, "s": 11017, "text": "Types of Operating Systems" }, { "code": null, "e": 11072, "s": 11044, "text": "Operator Overloading in C++" }, { "code": null, "e": 11092, "s": 11072, "text": "Polymorphism in C++" }, { "code": null, "e": 11138, "s": 11092, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 11198, "s": 11138, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 11255, "s": 11198, "text": "Python program to check if a string is palindrome or not" }, { "code": null, "e": 11330, "s": 11255, "text": "Check for Balanced Brackets in an expression (well-formedness) using Stack" } ]
What is Collation and Character Set in MySQL?
07 Sep, 2020 MySQL Collation has always been a mystifying topic for beginners of MySQL learners. A MySQL collation is a well-defined set of rules which are used to compare characters of a particular character-set by using their corresponding encoding. Each character set in MySQL might have more than one collation, and has, at least, one default collation. Two character sets cannot have the same collation. A character set is a set of specific symbols and encoding techniques. A collation is a set of rules for comparing characters in a character set. A Character-set allows us to store data through a variety of character sets and do comparisons according to a variety of collations. We can highlight character sets at the server, database, table, and column level. Suppose, we have some alphabet with A,B,C,D,a,b,c,d. We assigned a number to all letters like A=1,B=2,C=3,D=4,a=5,b=6,c=7,d=8. So, for symbol A encoding is 1, for B encoding is 2, for C encoding is 3, and so on. If we want to compare string A, B, a, b. We have an easier method to do this, just a moment ago we have assigned a distinct value to some alphabets like encoding of A is 1, for B it is 2 similarly encoding for a and b is 5 and 6. So, how we have able to perform this comparison, just because of Collation. We explicitly apply the technique of Collation(Compare there corresponding encoding) to our Character-set. Character-set not only affects data storage but also affects the communication medium between client programs and the MySQL server. If you want the client program to communicate with the server using a Character-set different from the default, you’ll need to highlight which one of the character set you are using. For example, to use the utf8 Unicode character set, use this statement after establishing connecting to the server : SET NAMES 'utf8'; There is a MySQL statement to know about the default collations of character sets as follows: SHOW CHARACTER SET; Char-set By default, the SHOW CHARACTER SET statement displays all available character sets. But if you want access character-set of specific types, then you need to use the LIKE or WHERE clause of MySQL that indicates which character-set names that match the conditions. The following example shows some Unicode character-sets that matches with the format(β€˜utf%’) : Fetching char-set using LIKE statement If you want to have all collations for a specific or given character-set, So MySQL provides a statement SHOW COLLATION as follows: SHOW COLLATION LIKE 'character_set_name%'; Fetching Collations using WHERE statement In the above tables, Collations are ending with _ci, the ci here stands for Case-insensitive. There may be other types of Collations like: 1. _cs(Case-sensitive) , 2. _bin(Binary) MySQL query for Setting of character-set and collations at the database level: If you don’t specify the character set at the time of creation then the database uses default character set, but in case you want to assign a specific character set so you can explicitly express it via MySQL query : CREATE DATABASE name_of_database CHARACTER SET character-set_name; COLLATE collation_name; Example: CREATE DATABASE my_database CHARACTER SET utf8mb4 COLLATE utf8_unicode_ci; You can also change or apply character-set and collation-name for database using MySQL β€˜ALTER’ statement : ALTER DATABASE database_name CHARACTER SET character_set_name COLLATE collation_name; Example: ALTER DATABASE my_database CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci; MySQL query for Setting of character-set and collations at the table level: </b> You can also explicitly specify what type of character set and collation you want at the time of table creation, but If you don’t specify then default character-set and collation would be applied. CREATE TABLE table_name( ID INT AUTO_INCREMENT NOT NULL, NAME VARCHAR (20) NOT NULL, ADDRESS CHAR (25) , SALARY DECIMAL (18, 2), PRIMARY KEY (ID) ); CHARACTER SET character_set_name COLLATE collation_name ; You have also an option to set Character-set and Collation name as you want if you haven’t applied them at the time of table creation via MySQL β€˜ALTER’ statement : ALTER TABLE table_name( RENAME COLUMN old_name TO new_name); CHARACTER SET character_set_name COLLATE collation_name; You can also set character-set and collation name at the column level :</b> As we know that Column in a table may contain a variety of data like (varchar, Int, float ). So you can explicitly specify the character set and collation name for a different type(data-type) of columns as you want. ALTER TABLE table_name MODIFY column_name VARCHAR(25) CHARACTER SET latin1; khushboogoyal499 mysql DBMS DBMS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Types of Functional dependencies in DBMS MySQL | Regular expressions (Regexp) Difference between OLAP and OLTP in DBMS What is Temporary Table in SQL? Relational Model in DBMS Difference between Where and Having Clause in SQL SQL | DDL, DML, TCL and DCL Introduction of Relational Algebra in DBMS Difference between File System and DBMS Difference between Star Schema and Snowflake Schema
[ { "code": null, "e": 54, "s": 26, "text": "\n07 Sep, 2020" }, { "code": null, "e": 451, "s": 54, "text": "MySQL Collation has always been a mystifying topic for beginners of MySQL learners. A MySQL collation is a well-defined set of rules which are used to compare characters of a particular character-set by using their corresponding encoding. Each character set in MySQL might have more than one collation, and has, at least, one default collation. Two character sets cannot have the same collation." }, { "code": null, "e": 811, "s": 451, "text": "A character set is a set of specific symbols and encoding techniques. A collation is a set of rules for comparing characters in a character set. A Character-set allows us to store data through a variety of character sets and do comparisons according to a variety of collations. We can highlight character sets at the server, database, table, and column level." }, { "code": null, "e": 1436, "s": 811, "text": "Suppose, we have some alphabet with A,B,C,D,a,b,c,d. We assigned a number to all letters like A=1,B=2,C=3,D=4,a=5,b=6,c=7,d=8. So, for symbol A encoding is 1, for B encoding is 2, for C encoding is 3, and so on. If we want to compare string A, B, a, b. We have an easier method to do this, just a moment ago we have assigned a distinct value to some alphabets like encoding of A is 1, for B it is 2 similarly encoding for a and b is 5 and 6. So, how we have able to perform this comparison, just because of Collation. We explicitly apply the technique of Collation(Compare there corresponding encoding) to our Character-set." }, { "code": null, "e": 1869, "s": 1436, "text": "Character-set not only affects data storage but also affects the communication medium between client programs and the MySQL server. If you want the client program to communicate with the server using a Character-set different from the default, you’ll need to highlight which one of the character set you are using. For example, to use the utf8 Unicode character set, use this statement after establishing connecting to the server :" }, { "code": null, "e": 1889, "s": 1869, "text": "SET NAMES 'utf8'; \n" }, { "code": null, "e": 1983, "s": 1889, "text": "There is a MySQL statement to know about the default collations of character sets as follows:" }, { "code": null, "e": 2004, "s": 1983, "text": "SHOW CHARACTER SET;\n" }, { "code": null, "e": 2075, "s": 2066, "text": "Char-set" }, { "code": null, "e": 2434, "s": 2075, "text": "By default, the SHOW CHARACTER SET statement displays all available character sets. But if you want access character-set of specific types, then you need to use the LIKE or WHERE clause of MySQL that indicates which character-set names that match the conditions. The following example shows some Unicode character-sets that matches with the format(β€˜utf%’) :" }, { "code": null, "e": 2542, "s": 2503, "text": "Fetching char-set using LIKE statement" }, { "code": null, "e": 2674, "s": 2542, "text": "If you want to have all collations for a specific or given character-set, So MySQL provides a statement SHOW COLLATION as follows:" }, { "code": null, "e": 2720, "s": 2674, "text": "SHOW COLLATION LIKE 'character_set_name%';\n\n\n" }, { "code": null, "e": 2845, "s": 2803, "text": "Fetching Collations using WHERE statement" }, { "code": null, "e": 2984, "s": 2845, "text": "In the above tables, Collations are ending with _ci, the ci here stands for Case-insensitive. There may be other types of Collations like:" }, { "code": null, "e": 3029, "s": 2984, "text": "1. _cs(Case-sensitive) ,\n2. _bin(Binary) \n" }, { "code": null, "e": 3325, "s": 3029, "text": "MySQL query for Setting of character-set and collations at the database level: If you don’t specify the character set at the time of creation then the database uses default character set, but in case you want to assign a specific character set so you can explicitly express it via MySQL query :" }, { "code": null, "e": 3417, "s": 3325, "text": "CREATE DATABASE name_of_database\nCHARACTER SET character-set_name;\nCOLLATE collation_name;\n" }, { "code": null, "e": 3426, "s": 3417, "text": "Example:" }, { "code": null, "e": 3502, "s": 3426, "text": "CREATE DATABASE my_database\nCHARACTER SET utf8mb4\nCOLLATE utf8_unicode_ci;\n" }, { "code": null, "e": 3609, "s": 3502, "text": "You can also change or apply character-set and collation-name for database using MySQL β€˜ALTER’ statement :" }, { "code": null, "e": 3697, "s": 3609, "text": "ALTER DATABASE database_name\nCHARACTER SET character_set_name\nCOLLATE collation_name; \n" }, { "code": null, "e": 3706, "s": 3697, "text": "Example:" }, { "code": null, "e": 3785, "s": 3706, "text": "ALTER DATABASE my_database\nCHARACTER SET utf8mb4\nCOLLATE utf8mb4_0900_ai_ci;\n" }, { "code": null, "e": 4063, "s": 3785, "text": "MySQL query for Setting of character-set and collations at the table level: </b> You can also explicitly specify what type of character set and collation you want at the time of table creation, but If you don’t specify then default character-set and collation would be applied." }, { "code": null, "e": 4291, "s": 4063, "text": "CREATE TABLE table_name(\nID INT AUTO_INCREMENT NOT NULL,\nNAME VARCHAR (20) NOT NULL,\nADDRESS CHAR (25) ,\nSALARY DECIMAL (18, 2), \nPRIMARY KEY (ID) );\nCHARACTER SET character_set_name\nCOLLATE collation_name ;\n" }, { "code": null, "e": 4455, "s": 4291, "text": "You have also an option to set Character-set and Collation name as you want if you haven’t applied them at the time of table creation via MySQL β€˜ALTER’ statement :" }, { "code": null, "e": 4574, "s": 4455, "text": "ALTER TABLE table_name(\nRENAME COLUMN old_name TO new_name);\nCHARACTER SET character_set_name\nCOLLATE collation_name;\n" }, { "code": null, "e": 4866, "s": 4574, "text": "You can also set character-set and collation name at the column level :</b> As we know that Column in a table may contain a variety of data like (varchar, Int, float ). So you can explicitly specify the character set and collation name for a different type(data-type) of columns as you want." }, { "code": null, "e": 4944, "s": 4866, "text": "ALTER TABLE table_name\nMODIFY column_name VARCHAR(25)\nCHARACTER SET latin1;" }, { "code": null, "e": 4961, "s": 4944, "text": "khushboogoyal499" }, { "code": null, "e": 4967, "s": 4961, "text": "mysql" }, { "code": null, "e": 4972, "s": 4967, "text": "DBMS" }, { "code": null, "e": 4977, "s": 4972, "text": "DBMS" }, { "code": null, "e": 5075, "s": 4977, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5116, "s": 5075, "text": "Types of Functional dependencies in DBMS" }, { "code": null, "e": 5153, "s": 5116, "text": "MySQL | Regular expressions (Regexp)" }, { "code": null, "e": 5194, "s": 5153, "text": "Difference between OLAP and OLTP in DBMS" }, { "code": null, "e": 5226, "s": 5194, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 5251, "s": 5226, "text": "Relational Model in DBMS" }, { "code": null, "e": 5301, "s": 5251, "text": "Difference between Where and Having Clause in SQL" }, { "code": null, "e": 5329, "s": 5301, "text": "SQL | DDL, DML, TCL and DCL" }, { "code": null, "e": 5372, "s": 5329, "text": "Introduction of Relational Algebra in DBMS" }, { "code": null, "e": 5412, "s": 5372, "text": "Difference between File System and DBMS" } ]
MongoDB – Comparison Query Operators
10 May, 2020 MongoDB uses various comparison query operators to compare the values of the documents. The following table contains the comparison query operators: In the following examples, we are working with: Database: GeeksforGeeksCollection: contributorDocument: three documents that contain the details of the contributors in the form of field-value pairs. In this example, we are retrieving only those employee’s documents whose name is not Amit or Suman. db.contributor.find({name: {$nin: ["Amit", "Suman"]}}).pretty() In this example, we are retrieving only those employee’s documents whose name is either Amit or Suman. db.contributor.find({name: {$in: ["Amit", "Suman"]}}).pretty() In this example, we are selecting those documents where the value of the salary field is less than 2000. db.contributor.find({salary: {$lt: 2000}}).pretty() In this example, we are selecting those documents where the value of the branch field is equal to CSE. db.contributor.find({branch: {$eq: "CSE"}}).pretty() In this example, we are selecting those documents where the value of the branch field is not equal to CSE. db.contributor.find({branch: {$ne: "CSE"}}).pretty() In this example, we are selecting those documents where the value of the salary field is greater than 1000. db.contributor.find({salary: {$gt: 1000}}).pretty() In this example, we are selecting those documents where the value of the joiningYear field is greater than equals to 2017. db.contributor.find({joiningYear: {$gte: 2017}}) In this example, we are selecting those documents where the value of the salary field is less than equals to 1000. db.contributor.find({salary: {$lte: 1000}}).pretty() MongoDB MongoDB-operators MongoDB Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n10 May, 2020" }, { "code": null, "e": 177, "s": 28, "text": "MongoDB uses various comparison query operators to compare the values of the documents. The following table contains the comparison query operators:" }, { "code": null, "e": 225, "s": 177, "text": "In the following examples, we are working with:" }, { "code": null, "e": 376, "s": 225, "text": "Database: GeeksforGeeksCollection: contributorDocument: three documents that contain the details of the contributors in the form of field-value pairs." }, { "code": null, "e": 476, "s": 376, "text": "In this example, we are retrieving only those employee’s documents whose name is not Amit or Suman." }, { "code": "db.contributor.find({name: {$nin: [\"Amit\", \"Suman\"]}}).pretty()", "e": 540, "s": 476, "text": null }, { "code": null, "e": 643, "s": 540, "text": "In this example, we are retrieving only those employee’s documents whose name is either Amit or Suman." }, { "code": "db.contributor.find({name: {$in: [\"Amit\", \"Suman\"]}}).pretty()", "e": 706, "s": 643, "text": null }, { "code": null, "e": 811, "s": 706, "text": "In this example, we are selecting those documents where the value of the salary field is less than 2000." }, { "code": "db.contributor.find({salary: {$lt: 2000}}).pretty()", "e": 863, "s": 811, "text": null }, { "code": null, "e": 966, "s": 863, "text": "In this example, we are selecting those documents where the value of the branch field is equal to CSE." }, { "code": "db.contributor.find({branch: {$eq: \"CSE\"}}).pretty()", "e": 1019, "s": 966, "text": null }, { "code": null, "e": 1126, "s": 1019, "text": "In this example, we are selecting those documents where the value of the branch field is not equal to CSE." }, { "code": "db.contributor.find({branch: {$ne: \"CSE\"}}).pretty()", "e": 1179, "s": 1126, "text": null }, { "code": null, "e": 1287, "s": 1179, "text": "In this example, we are selecting those documents where the value of the salary field is greater than 1000." }, { "code": "db.contributor.find({salary: {$gt: 1000}}).pretty()", "e": 1339, "s": 1287, "text": null }, { "code": null, "e": 1462, "s": 1339, "text": "In this example, we are selecting those documents where the value of the joiningYear field is greater than equals to 2017." }, { "code": "db.contributor.find({joiningYear: {$gte: 2017}})", "e": 1511, "s": 1462, "text": null }, { "code": null, "e": 1626, "s": 1511, "text": "In this example, we are selecting those documents where the value of the salary field is less than equals to 1000." }, { "code": "db.contributor.find({salary: {$lte: 1000}}).pretty()", "e": 1679, "s": 1626, "text": null }, { "code": null, "e": 1687, "s": 1679, "text": "MongoDB" }, { "code": null, "e": 1705, "s": 1687, "text": "MongoDB-operators" }, { "code": null, "e": 1713, "s": 1705, "text": "MongoDB" } ]
Count consonants in a string (Iterative and recursive methods)
15 Jul, 2022 Given a string, count total number of consonants in it. A consonant is a English alphabet character that is not vowel (a, e, i, o and u). Examples of constants are b, c, d, f, g, .. Examples : Chapters descriptions off, selected captions settings, opens captions settings dialog captions off, selected English This is a modal window. Beginning of dialog window. Escape will cancel and close the window. End of dialog window. Input : abc de Output : 3 There are three consonants b, c and d. Input : geeksforgeeks portal Output : 12 1. Iterative Method C++ Java Python3 C# PHP Javascript // Iterative CPP program to count total number// of consonants #include <iostream>using namespace std; // Function to check for consonantbool isConsonant(char ch){ // To handle lower case ch = toupper(ch); return !(ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') && ch >= 65 && ch <= 90;} int totalConsonants(string str){ int count = 0; for (int i = 0; i < str.length(); i++) // To check is character is Consonant if (isConsonant(str[i])) ++count; return count;} // Driver codeint main(){ string str = "abc de"; cout << totalConsonants(str); return 0;} // Iterative Java program// to count total number// of consonants import java.io.*; class GFG { // Function to check for consonant static boolean isConsonant(char ch) { // To handle lower case ch = Character.toUpperCase(ch); return !(ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') && ch >= 65 && ch <= 90; } static int totalConsonants(String str) { int count = 0; for (int i = 0; i < str.length(); i++) // To check is character is Consonant if (isConsonant(str.charAt(i))) ++count; return count; } // Driver code public static void main(String args[]) { String str = "abc de"; System.out.println( totalConsonants(str)); }} // This code is contributed by Nikita Tiwari. # Iterative Python3 program to count # total number of consonants # Function to check for consonantdef isConsonant(ch): # To handle lower case ch = ch.upper() return not (ch == 'A' or ch == 'E' or ch == 'I' or ch == 'O' or ch == 'U') and ord(ch) >= 65 and ord(ch) <= 90 def totalConsonants(string): count = 0 for i in range(len(string)): # To check is character is Consonant if (isConsonant(string[i])): count += 1 return count # Driver codestring = "abc de"print(totalConsonants(string)) # This code id contributed by Ansu Kumari. // Iterative C# program to count // total number of consonants using System; class GFG { // Function to check for consonant static bool isConsonant(char ch) { // To handle lower case ch = Char.ToUpper(ch); return !(ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') && ch >= 65 && ch <= 90; } static int totalConsonants(String str) { int count = 0; for (int i = 0; i < str.Length; i++) // To check is character is Consonant if (isConsonant(str[i])) ++count; return count; } // Driver code public static void Main() { String str = "abc de"; Console.Write( totalConsonants(str)); }} // This code is contributed by nitin mittal. <?php // Iterative PHP program to count total number// of consonants // Function to check for consonantfunction isConsonant($ch){ // To handle lower case $ch = strtoupper($ch); return !($ch == 'A' || $ch == 'E' || $ch == 'I' || $ch == 'O' || $ch == 'U') && ord($ch) >= 65 && ord($ch) <= 90;} function totalConsonants($str){ $count = 0; for ($i = 0; $i < strlen($str); $i++) // To check is character is Consonant if (isConsonant($str[$i])) ++$count; return $count;} // Driver code $str = "abc de";echo totalConsonants($str);return 0; // This code is contributed by Ita_c.?> <script> // Iterative JavaScript program to count total number // of consonants // Function to check for consonant function isConsonant(ch) { // To handle lower case ch = ch.toUpperCase(); console.log(ch); return ( !(ch == "A" || ch == "E" || ch == "I" || ch == "O" || ch == "U") && ch.match(/[A-Z]/i) ); } function totalConsonants(str) { var count = 0; for (var i = 0; i < str.length; i++) // To check is character is Consonant if (isConsonant(str[i])) ++count; return count; } // Driver code var str = "abc de"; document.write(totalConsonants(str)); // This code is contributed by rdtank. </script> Output: 3 Time Complexity: O(n), where n is the length of the string Auxiliary Space: O(1) 2. Recursive Method C++ Java Python3 C# Javascript // Recursive CPP program to count total number// of consonants #include <iostream>using namespace std; // Function to check for consonantbool isConsonant(char ch){ // To handle lower case ch = toupper(ch); return !(ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') && ch >= 65 && ch <= 90;} // to count total number of consonants from // 0 to n-1int totalConsonants(string str, int n){ if (n == 1) return isConsonant(str[0]); return totalConsonants(str, n - 1) + isConsonant(str[n-1]);} // Driver codeint main(){ string str = "abc de"; cout << totalConsonants(str, str.length()); return 0;} // Recursive Java program to count // total number of consonants import java.util.*;import java.lang.*; class GFG{ // Function to check for consonantstatic boolean isConsonant(char ch){ // To handle lower case ch = Character.toUpperCase(ch); return (ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U')== false && ch >= 65 && ch <= 90;} // to count total number // of consonants from 0 to n-1static int totalConsonants(String str, int n){ if (n == 1) { if(isConsonant(str.charAt(0))) return 1; else return 0; } if(isConsonant(str.charAt(n - 1))) return totalConsonants(str, n - 1) + 1; else return totalConsonants(str, n - 1);} // Driver codepublic static void main(String args[]){ String str = "abc de"; System.out.println(totalConsonants(str, str.length()));}} // This code is contributed by// Surendra_Gangwar # Recursive Python3 program to count # total number of consonants # Function to check for consonantdef isConsonant(ch): # To handle lower case ch = ch.upper() return not (ch == 'A' or ch == 'E' or ch == 'I' or ch == 'O' or ch == 'U') and ord(ch) >= 65 and ord(ch) <= 90 # To count total number of # consonants from 0 to n-1def totalConsonants(string, n): if n == 1: return isConsonant(string[0]) return totalConsonants(string, n - 1) + isConsonant(string[n-1]) # Driver codestring = "abc de"print(totalConsonants(string, len(string))) # This code is contributed by Ansu Kuamri. // Recursive C# program to count // total number of consonants using System; class GFG{ // Function to check for consonantstatic Boolean isConsonant(char ch){ // To handle lower case ch = char.ToUpper(ch); return (ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') == false && ch >= 65 && ch <= 90;} // to count total number // of consonants from 0 to n-1static int totalConsonants(String str, int n){ if (n == 1) { if(isConsonant(str[0])) return 1; else return 0; } if(isConsonant(str[n - 1])) return totalConsonants(str, n - 1) + 1; else return totalConsonants(str, n - 1);} // Driver codepublic static void Main(String []args){ String str = "abc de"; Console.WriteLine(totalConsonants(str, str.Length));}} // This code contributed by Rajput-Ji <script> // Recursive Javascript program to // count total number of consonants // Function to check for consonantfunction isConsonant(ch){ // To handle lower case ch = ch.toUpperCase(); return (!(ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') && ch.charCodeAt(0) >= 65 && ch.charCodeAt(0) <= 90) ;} // To count total number of consonants from // 0 to n-1function totalConsonants(str, n){ if (n == 1) return isConsonant(str[0]); return totalConsonants(str, n - 1) + isConsonant(str[n - 1]);} // Driver codevar str = "abc de"; document.write(totalConsonants(str,str.length)); // This code is contributed by jana_sayantan </script> Output : 3 Time Complexity: O(n), where n is the length of the string Auxiliary Space: O(1) Illustration of recursive method: nitin mittal ukasp SURENDRA_GANGWAR Rajput-Ji rdtank jana_sayantan samim2000 vowel-consonant Recursion School Programming Strings Strings Recursion Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n15 Jul, 2022" }, { "code": null, "e": 234, "s": 52, "text": "Given a string, count total number of consonants in it. A consonant is a English alphabet character that is not vowel (a, e, i, o and u). Examples of constants are b, c, d, f, g, .." }, { "code": null, "e": 246, "s": 234, "text": "Examples : " }, { "code": null, "e": 255, "s": 246, "text": "Chapters" }, { "code": null, "e": 282, "s": 255, "text": "descriptions off, selected" }, { "code": null, "e": 332, "s": 282, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 355, "s": 332, "text": "captions off, selected" }, { "code": null, "e": 363, "s": 355, "text": "English" }, { "code": null, "e": 387, "s": 363, "text": "This is a modal window." }, { "code": null, "e": 456, "s": 387, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 478, "s": 456, "text": "End of dialog window." }, { "code": null, "e": 585, "s": 478, "text": "Input : abc de\nOutput : 3\nThere are three consonants b, c and d.\n\nInput : geeksforgeeks portal\nOutput : 12" }, { "code": null, "e": 607, "s": 585, "text": " 1. Iterative Method " }, { "code": null, "e": 611, "s": 607, "text": "C++" }, { "code": null, "e": 616, "s": 611, "text": "Java" }, { "code": null, "e": 624, "s": 616, "text": "Python3" }, { "code": null, "e": 627, "s": 624, "text": "C#" }, { "code": null, "e": 631, "s": 627, "text": "PHP" }, { "code": null, "e": 642, "s": 631, "text": "Javascript" }, { "code": "// Iterative CPP program to count total number// of consonants #include <iostream>using namespace std; // Function to check for consonantbool isConsonant(char ch){ // To handle lower case ch = toupper(ch); return !(ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') && ch >= 65 && ch <= 90;} int totalConsonants(string str){ int count = 0; for (int i = 0; i < str.length(); i++) // To check is character is Consonant if (isConsonant(str[i])) ++count; return count;} // Driver codeint main(){ string str = \"abc de\"; cout << totalConsonants(str); return 0;}", "e": 1294, "s": 642, "text": null }, { "code": "// Iterative Java program// to count total number// of consonants import java.io.*; class GFG { // Function to check for consonant static boolean isConsonant(char ch) { // To handle lower case ch = Character.toUpperCase(ch); return !(ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') && ch >= 65 && ch <= 90; } static int totalConsonants(String str) { int count = 0; for (int i = 0; i < str.length(); i++) // To check is character is Consonant if (isConsonant(str.charAt(i))) ++count; return count; } // Driver code public static void main(String args[]) { String str = \"abc de\"; System.out.println( totalConsonants(str)); }} // This code is contributed by Nikita Tiwari.", "e": 2167, "s": 1294, "text": null }, { "code": "# Iterative Python3 program to count # total number of consonants # Function to check for consonantdef isConsonant(ch): # To handle lower case ch = ch.upper() return not (ch == 'A' or ch == 'E' or ch == 'I' or ch == 'O' or ch == 'U') and ord(ch) >= 65 and ord(ch) <= 90 def totalConsonants(string): count = 0 for i in range(len(string)): # To check is character is Consonant if (isConsonant(string[i])): count += 1 return count # Driver codestring = \"abc de\"print(totalConsonants(string)) # This code id contributed by Ansu Kumari.", "e": 2817, "s": 2167, "text": null }, { "code": "// Iterative C# program to count // total number of consonants using System; class GFG { // Function to check for consonant static bool isConsonant(char ch) { // To handle lower case ch = Char.ToUpper(ch); return !(ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') && ch >= 65 && ch <= 90; } static int totalConsonants(String str) { int count = 0; for (int i = 0; i < str.Length; i++) // To check is character is Consonant if (isConsonant(str[i])) ++count; return count; } // Driver code public static void Main() { String str = \"abc de\"; Console.Write( totalConsonants(str)); }} // This code is contributed by nitin mittal.", "e": 3640, "s": 2817, "text": null }, { "code": "<?php // Iterative PHP program to count total number// of consonants // Function to check for consonantfunction isConsonant($ch){ // To handle lower case $ch = strtoupper($ch); return !($ch == 'A' || $ch == 'E' || $ch == 'I' || $ch == 'O' || $ch == 'U') && ord($ch) >= 65 && ord($ch) <= 90;} function totalConsonants($str){ $count = 0; for ($i = 0; $i < strlen($str); $i++) // To check is character is Consonant if (isConsonant($str[$i])) ++$count; return $count;} // Driver code $str = \"abc de\";echo totalConsonants($str);return 0; // This code is contributed by Ita_c.?>", "e": 4295, "s": 3640, "text": null }, { "code": "<script> // Iterative JavaScript program to count total number // of consonants // Function to check for consonant function isConsonant(ch) { // To handle lower case ch = ch.toUpperCase(); console.log(ch); return ( !(ch == \"A\" || ch == \"E\" || ch == \"I\" || ch == \"O\" || ch == \"U\") && ch.match(/[A-Z]/i) ); } function totalConsonants(str) { var count = 0; for (var i = 0; i < str.length; i++) // To check is character is Consonant if (isConsonant(str[i])) ++count; return count; } // Driver code var str = \"abc de\"; document.write(totalConsonants(str)); // This code is contributed by rdtank. </script>", "e": 5069, "s": 4295, "text": null }, { "code": null, "e": 5078, "s": 5069, "text": "Output: " }, { "code": null, "e": 5080, "s": 5078, "text": "3" }, { "code": null, "e": 5139, "s": 5080, "text": "Time Complexity: O(n), where n is the length of the string" }, { "code": null, "e": 5161, "s": 5139, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 5183, "s": 5161, "text": " 2. Recursive Method " }, { "code": null, "e": 5187, "s": 5183, "text": "C++" }, { "code": null, "e": 5192, "s": 5187, "text": "Java" }, { "code": null, "e": 5200, "s": 5192, "text": "Python3" }, { "code": null, "e": 5203, "s": 5200, "text": "C#" }, { "code": null, "e": 5214, "s": 5203, "text": "Javascript" }, { "code": "// Recursive CPP program to count total number// of consonants #include <iostream>using namespace std; // Function to check for consonantbool isConsonant(char ch){ // To handle lower case ch = toupper(ch); return !(ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') && ch >= 65 && ch <= 90;} // to count total number of consonants from // 0 to n-1int totalConsonants(string str, int n){ if (n == 1) return isConsonant(str[0]); return totalConsonants(str, n - 1) + isConsonant(str[n-1]);} // Driver codeint main(){ string str = \"abc de\"; cout << totalConsonants(str, str.length()); return 0;}", "e": 5891, "s": 5214, "text": null }, { "code": "// Recursive Java program to count // total number of consonants import java.util.*;import java.lang.*; class GFG{ // Function to check for consonantstatic boolean isConsonant(char ch){ // To handle lower case ch = Character.toUpperCase(ch); return (ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U')== false && ch >= 65 && ch <= 90;} // to count total number // of consonants from 0 to n-1static int totalConsonants(String str, int n){ if (n == 1) { if(isConsonant(str.charAt(0))) return 1; else return 0; } if(isConsonant(str.charAt(n - 1))) return totalConsonants(str, n - 1) + 1; else return totalConsonants(str, n - 1);} // Driver codepublic static void main(String args[]){ String str = \"abc de\"; System.out.println(totalConsonants(str, str.length()));}} // This code is contributed by// Surendra_Gangwar", "e": 6832, "s": 5891, "text": null }, { "code": "# Recursive Python3 program to count # total number of consonants # Function to check for consonantdef isConsonant(ch): # To handle lower case ch = ch.upper() return not (ch == 'A' or ch == 'E' or ch == 'I' or ch == 'O' or ch == 'U') and ord(ch) >= 65 and ord(ch) <= 90 # To count total number of # consonants from 0 to n-1def totalConsonants(string, n): if n == 1: return isConsonant(string[0]) return totalConsonants(string, n - 1) + isConsonant(string[n-1]) # Driver codestring = \"abc de\"print(totalConsonants(string, len(string))) # This code is contributed by Ansu Kuamri.", "e": 7490, "s": 6832, "text": null }, { "code": "// Recursive C# program to count // total number of consonants using System; class GFG{ // Function to check for consonantstatic Boolean isConsonant(char ch){ // To handle lower case ch = char.ToUpper(ch); return (ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') == false && ch >= 65 && ch <= 90;} // to count total number // of consonants from 0 to n-1static int totalConsonants(String str, int n){ if (n == 1) { if(isConsonant(str[0])) return 1; else return 0; } if(isConsonant(str[n - 1])) return totalConsonants(str, n - 1) + 1; else return totalConsonants(str, n - 1);} // Driver codepublic static void Main(String []args){ String str = \"abc de\"; Console.WriteLine(totalConsonants(str, str.Length));}} // This code contributed by Rajput-Ji", "e": 8383, "s": 7490, "text": null }, { "code": "<script> // Recursive Javascript program to // count total number of consonants // Function to check for consonantfunction isConsonant(ch){ // To handle lower case ch = ch.toUpperCase(); return (!(ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') && ch.charCodeAt(0) >= 65 && ch.charCodeAt(0) <= 90) ;} // To count total number of consonants from // 0 to n-1function totalConsonants(str, n){ if (n == 1) return isConsonant(str[0]); return totalConsonants(str, n - 1) + isConsonant(str[n - 1]);} // Driver codevar str = \"abc de\"; document.write(totalConsonants(str,str.length)); // This code is contributed by jana_sayantan </script>", "e": 9143, "s": 8383, "text": null }, { "code": null, "e": 9153, "s": 9143, "text": "Output : " }, { "code": null, "e": 9155, "s": 9153, "text": "3" }, { "code": null, "e": 9214, "s": 9155, "text": "Time Complexity: O(n), where n is the length of the string" }, { "code": null, "e": 9236, "s": 9214, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 9271, "s": 9236, "text": "Illustration of recursive method: " }, { "code": null, "e": 9286, "s": 9273, "text": "nitin mittal" }, { "code": null, "e": 9292, "s": 9286, "text": "ukasp" }, { "code": null, "e": 9309, "s": 9292, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 9319, "s": 9309, "text": "Rajput-Ji" }, { "code": null, "e": 9326, "s": 9319, "text": "rdtank" }, { "code": null, "e": 9340, "s": 9326, "text": "jana_sayantan" }, { "code": null, "e": 9350, "s": 9340, "text": "samim2000" }, { "code": null, "e": 9366, "s": 9350, "text": "vowel-consonant" }, { "code": null, "e": 9376, "s": 9366, "text": "Recursion" }, { "code": null, "e": 9395, "s": 9376, "text": "School Programming" }, { "code": null, "e": 9403, "s": 9395, "text": "Strings" }, { "code": null, "e": 9411, "s": 9403, "text": "Strings" }, { "code": null, "e": 9421, "s": 9411, "text": "Recursion" } ]
Bayes’ Theorem, Simply Explained. If ignorance is bliss, knowing how to... | by Riccardo Di Sipio | Towards Data Science
Bayes’ Theorem formalizes how to calculate the probability of an event to occur given our incomplete knowledge about other factors affecting its realization, and our pre-existing belief. For example, is it going to rain today if the sky is cloudy? Let’s start with some basic definitions. The probability of an event A to occur is a number between 0 and 1 (or 0% and 100%) and is represented mathematically by some function P(A) called marginal probability, i.e. irrespective of other events. If we are considering two events A and B at the same time, then the probability is a 2-dimensional function P(A,B) which is called joint probability. Notably, it’s symmetrical, meaning that P(A,B) = P(B,A). If the two events are completely uncorrelated, then it factorizes into P(A,B) = P(A)*P(B). The next thing we may want to know is what’s the probability of event A to occur knowing that B already happened. This is called conditional probability, described by a function P(A|B). There is a well-known principle in statistics called product rule which tells you how to derive the conditional probability P(A|B) from the joint probability P(A,B) and the marginal probability of the conditioning event i.e. P(B). It’s actually pretty simple: P(A|B) = P(A,B) / P(B) The division by P(B) ensures that the probability is between 0 and 1. Notably, the conditional probability is not symmetrical, meaning that in general P(A|B) =ΜΈ P(B|A). For example, the chance of rain with an overcast sky is arguably smaller (e.g. 30%) than the chance of having an overcast sky while its raining (e.g. 99%). These relationships can be inverted easily: P(A,B) = P(A|B) * P(B)P(B,A) = P(B|A) * P(A) which basically shows that having the joint probability is the key to hold complete information about a system. The catch is, in most of the cases our knowledge of a certain process is incomplete, which means we do not have access to the joint probability P(A,B)! On the other hand, we often have some knowledge about event A happening under the assumption that event B is true, and we probably have some pre-existing ideas about how likely event A is in general. Then, a theorem devised by revered Thomas Bayes comes to rescue to tells us how to β€œswitch” between the two conditional probabilities, i.e.: P(B|A) = P(A|B) * P(B) / P(A) This is easily derived by realizing that: P(A|B) * P(B) = P(A,B) P(B|A) * P(A) = P(B,A) = P(A,B)=>P(A|B) * P(B) = P(B|A) * P(A)=>P(B|A) = P(A|B) * P(B) / P(A) In the Bayesian statistics lingo, P(B|A) is the posterior probability (what we want to calculate), P(A|B) is called the likelihood, P(B) is called prior probability, and the normalization factor P(A) is the marginal likelihood or model evidence. In plain English, the likelihood encodes the probability that event A can occur under some set of assumptions B, and the prior is our belief that B is actually possible. To stretch it a little bit: what is the probability that God exists given that we have observed what looked like a miracle, and our belief that miracles can happen at all irrespective of the existence of a God? Maybe that’s what Thomas Bayes was mulling over. To summarize: Joint probability: P(A and B) = P(A, B) = P(B, A) Conditional probability: P(A given B)= P(A|B) Product rule: P(A|B) = P(A, B) / P(B) P(A|B) * P(B) = P(A, B) = P(B, A) = P(B|A) * P(A) P(B|A)= P(A|B)*P(B) / P(A) (Bayes’ Theorem) If you are reading this post, it’s probably because you heard about the Naive Bayes Classifier and its success at rejecting unwanted emails. How does it work, and why is it β€œnaïve”? First of all, we are talking about a classifier, which is a statistical model that separates instances into different (often mutually-exclusive) categories based on the value of some features vector X. In the example mentioned above, the features may be whether it’s raining or not, and the categories whether you should bring an umbrella or not. A full-fledged application of Bayes’ Theorem would require quite some computations, for example that of the normalization factor P(X) which often implies running a Markov Chain Monte Carlo integration over the multi-dimensional feature space. However, in most applications, we only want to know the category, not the (normalized) probability. This way, the theorem can be simplified to: P(umbrella | X ) ∝ P(X | umbrella) * P(umbrella) The other big problem is the correlation among the features X. In real life, there are correlations between the level of humidity, temperature and time of the day, and the classifier should take this fact into account during the optimization step. For example, an increase in humidity may be correlated with an increase in temperature. However, in practical terms, it’s often the case that the input features are treated or engineered in such a way that their correlation is in fact very small or negligible. If that’s the case, then the likelihood (remember it’s a conditional probability!) factorizes into: P(X|umbrella) = P(rainy|umbrella) * P(cloudy|umbrella) * P(humid|umbrella) * P(hour|umbrella) Thus, for a given instance of the features vector X = (X_1, X_2, X_3, X_4), the algorithm just has to find the maximum of P(rainy=X_1|umbrella), P(cloudy=X_2|umbrella), etc.. separately, and then multiply the factors together: umbrella = argmax_j P(umbrella_j) * Prod_i[ P(X_i|umbrella_j) ] = max{P(Y) * P(X_1|Y) * P(X_2|Y) * P(X_3|Y) * P(X_4|Y),P(N) * P(X_1|N) * P(X_2|N) * P(X_3|N) * P(X_4|N)} In many cases, handling a product of perhaps a hundred features can cause numerical instabilities or memory overflows. It is customary then to take the negative log of the product, and instead minimize the function: -logP(X|umbrella) = -logP(umbrella) - log(P(X_1|umbrella) - log(P(X_2|umbrella) - log(P(X_3|umbrella) - log(P(X_4|umbrella) To conclude, Bayes’ Theorem is a formal way to calculate the probability of a given event A based on incomplete knowledge about its relationship with other events B_1, B_2, ... and our prior beliefs. Its importance in statistics cannot be overstated, and its applications are ubiquitous. We discussed here the Naive Bayes Classifier, a popular approach implemented for example in the scikit-learn library. I also discussed how to train Neural Networks with Bayesian optimization in a previous post.
[ { "code": null, "e": 420, "s": 172, "text": "Bayes’ Theorem formalizes how to calculate the probability of an event to occur given our incomplete knowledge about other factors affecting its realization, and our pre-existing belief. For example, is it going to rain today if the sky is cloudy?" }, { "code": null, "e": 963, "s": 420, "text": "Let’s start with some basic definitions. The probability of an event A to occur is a number between 0 and 1 (or 0% and 100%) and is represented mathematically by some function P(A) called marginal probability, i.e. irrespective of other events. If we are considering two events A and B at the same time, then the probability is a 2-dimensional function P(A,B) which is called joint probability. Notably, it’s symmetrical, meaning that P(A,B) = P(B,A). If the two events are completely uncorrelated, then it factorizes into P(A,B) = P(A)*P(B)." }, { "code": null, "e": 1409, "s": 963, "text": "The next thing we may want to know is what’s the probability of event A to occur knowing that B already happened. This is called conditional probability, described by a function P(A|B). There is a well-known principle in statistics called product rule which tells you how to derive the conditional probability P(A|B) from the joint probability P(A,B) and the marginal probability of the conditioning event i.e. P(B). It’s actually pretty simple:" }, { "code": null, "e": 1432, "s": 1409, "text": "P(A|B) = P(A,B) / P(B)" }, { "code": null, "e": 1757, "s": 1432, "text": "The division by P(B) ensures that the probability is between 0 and 1. Notably, the conditional probability is not symmetrical, meaning that in general P(A|B) =ΜΈ P(B|A). For example, the chance of rain with an overcast sky is arguably smaller (e.g. 30%) than the chance of having an overcast sky while its raining (e.g. 99%)." }, { "code": null, "e": 1801, "s": 1757, "text": "These relationships can be inverted easily:" }, { "code": null, "e": 1846, "s": 1801, "text": "P(A,B) = P(A|B) * P(B)P(B,A) = P(B|A) * P(A)" }, { "code": null, "e": 1958, "s": 1846, "text": "which basically shows that having the joint probability is the key to hold complete information about a system." }, { "code": null, "e": 2451, "s": 1958, "text": "The catch is, in most of the cases our knowledge of a certain process is incomplete, which means we do not have access to the joint probability P(A,B)! On the other hand, we often have some knowledge about event A happening under the assumption that event B is true, and we probably have some pre-existing ideas about how likely event A is in general. Then, a theorem devised by revered Thomas Bayes comes to rescue to tells us how to β€œswitch” between the two conditional probabilities, i.e.:" }, { "code": null, "e": 2481, "s": 2451, "text": "P(B|A) = P(A|B) * P(B) / P(A)" }, { "code": null, "e": 2523, "s": 2481, "text": "This is easily derived by realizing that:" }, { "code": null, "e": 2640, "s": 2523, "text": "P(A|B) * P(B) = P(A,B) P(B|A) * P(A) = P(B,A) = P(A,B)=>P(A|B) * P(B) = P(B|A) * P(A)=>P(B|A) = P(A|B) * P(B) / P(A)" }, { "code": null, "e": 3316, "s": 2640, "text": "In the Bayesian statistics lingo, P(B|A) is the posterior probability (what we want to calculate), P(A|B) is called the likelihood, P(B) is called prior probability, and the normalization factor P(A) is the marginal likelihood or model evidence. In plain English, the likelihood encodes the probability that event A can occur under some set of assumptions B, and the prior is our belief that B is actually possible. To stretch it a little bit: what is the probability that God exists given that we have observed what looked like a miracle, and our belief that miracles can happen at all irrespective of the existence of a God? Maybe that’s what Thomas Bayes was mulling over." }, { "code": null, "e": 3330, "s": 3316, "text": "To summarize:" }, { "code": null, "e": 3380, "s": 3330, "text": "Joint probability: P(A and B) = P(A, B) = P(B, A)" }, { "code": null, "e": 3426, "s": 3380, "text": "Conditional probability: P(A given B)= P(A|B)" }, { "code": null, "e": 3464, "s": 3426, "text": "Product rule: P(A|B) = P(A, B) / P(B)" }, { "code": null, "e": 3514, "s": 3464, "text": "P(A|B) * P(B) = P(A, B) = P(B, A) = P(B|A) * P(A)" }, { "code": null, "e": 3558, "s": 3514, "text": "P(B|A)= P(A|B)*P(B) / P(A) (Bayes’ Theorem)" }, { "code": null, "e": 3741, "s": 3558, "text": "If you are reading this post, it’s probably because you heard about the Naive Bayes Classifier and its success at rejecting unwanted emails. How does it work, and why is it β€œnaïve”?" }, { "code": null, "e": 4475, "s": 3741, "text": "First of all, we are talking about a classifier, which is a statistical model that separates instances into different (often mutually-exclusive) categories based on the value of some features vector X. In the example mentioned above, the features may be whether it’s raining or not, and the categories whether you should bring an umbrella or not. A full-fledged application of Bayes’ Theorem would require quite some computations, for example that of the normalization factor P(X) which often implies running a Markov Chain Monte Carlo integration over the multi-dimensional feature space. However, in most applications, we only want to know the category, not the (normalized) probability. This way, the theorem can be simplified to:" }, { "code": null, "e": 4524, "s": 4475, "text": "P(umbrella | X ) ∝ P(X | umbrella) * P(umbrella)" }, { "code": null, "e": 5133, "s": 4524, "text": "The other big problem is the correlation among the features X. In real life, there are correlations between the level of humidity, temperature and time of the day, and the classifier should take this fact into account during the optimization step. For example, an increase in humidity may be correlated with an increase in temperature. However, in practical terms, it’s often the case that the input features are treated or engineered in such a way that their correlation is in fact very small or negligible. If that’s the case, then the likelihood (remember it’s a conditional probability!) factorizes into:" }, { "code": null, "e": 5227, "s": 5133, "text": "P(X|umbrella) = P(rainy|umbrella) * P(cloudy|umbrella) * P(humid|umbrella) * P(hour|umbrella)" }, { "code": null, "e": 5454, "s": 5227, "text": "Thus, for a given instance of the features vector X = (X_1, X_2, X_3, X_4), the algorithm just has to find the maximum of P(rainy=X_1|umbrella), P(cloudy=X_2|umbrella), etc.. separately, and then multiply the factors together:" }, { "code": null, "e": 5623, "s": 5454, "text": "umbrella = argmax_j P(umbrella_j) * Prod_i[ P(X_i|umbrella_j) ] = max{P(Y) * P(X_1|Y) * P(X_2|Y) * P(X_3|Y) * P(X_4|Y),P(N) * P(X_1|N) * P(X_2|N) * P(X_3|N) * P(X_4|N)}" }, { "code": null, "e": 5839, "s": 5623, "text": "In many cases, handling a product of perhaps a hundred features can cause numerical instabilities or memory overflows. It is customary then to take the negative log of the product, and instead minimize the function:" }, { "code": null, "e": 5963, "s": 5839, "text": "-logP(X|umbrella) = -logP(umbrella) - log(P(X_1|umbrella) - log(P(X_2|umbrella) - log(P(X_3|umbrella) - log(P(X_4|umbrella)" } ]
What's the difference between assignment operator and copy constructor in C++?
The Copy constructor and the assignment operators are used to initialize one object to another object. The main difference between them is that the copy constructor creates a separate memory block for the new object. But the assignment operator does not make new memory space. It uses reference variable to point to the previous memory block. classname (const classname &obj) { // body of constructor } classname Ob1, Ob2; Ob2 = Ob1; Let us see the detailed differences between Copy constructor and Assignment Operator.
[ { "code": null, "e": 1405, "s": 1062, "text": "The Copy constructor and the assignment operators are used to initialize one object to another object. The main difference between them is that the copy constructor creates a separate memory block for the new object. But the assignment operator does not make new memory space. It uses reference variable to point to the previous memory block." }, { "code": null, "e": 1468, "s": 1405, "text": "classname (const classname &obj) {\n // body of constructor\n}" }, { "code": null, "e": 1499, "s": 1468, "text": "classname Ob1, Ob2;\nOb2 = Ob1;" }, { "code": null, "e": 1585, "s": 1499, "text": "Let us see the detailed differences between Copy constructor and Assignment Operator." } ]
Face Recognition for Beginners. Face Recognition is a recognition... | by Divyansh Dwivedi | Towards Data Science
Face Recognition is a recognition technique used to detect faces of individuals whose images saved in the data set. Despite the point that other methods of identification can be more accurate, face recognition has always remained a significant focus of research because of its non-meddling nature and because it is people’s facile method of personal identification. There are different methods for face recognition, which are as follows- Face recognition algorithms classified as geometry based or template based algorithms. The template-based methods can be constructed using statistical tools like SVM [Support Vector Machines], PCA [Principal Component Analysis], LDA [Linear Discriminant Analysis], Kernel methods or Trace Transforms. The geometric feature based methods analyse local facial features and their geometric relationship. It is also known as a feature-based method. The relation between the elements or the connection of a function with the whole face not undergone into the amount, many researchers followed this approach, trying to deduce the most relevant characteristics. Some methods attempted to use the eyes, a combination of features and so on. Some Hidden Markov Model methods also fall into this category, and feature processing is very famous in face recognition. The appearance-based method shows a face regarding several images. An image considered as a high dimensional vector. This technique is usually used to derive a feature space from the image division. The sample image compared to the training set. On the other hand, the model-based approach tries to model a face. The new sample implemented to the model and the parameters of the model used to recognise the image. The appearance-based method can classify as linear or nonlinear. Ex- PCA, LDA, IDA used in direct approach whereas Kernel PCA used in nonlinear approach. On the other hand, in the model-based method can be classified as 2D or 3D Ex- Elastic Bunch Graph Matching used. In template matching the patterns are represented by samples, models, pixels, textures, etc. The recognition function is usually a correlation or distance measure. In the Statistical approach, the patterns expressed as features. The recognition function in a discriminant function. Each image represented regarding d features. Therefore, the goal is to choose and apply the right statistical tool for extraction and analysis. There are many statistical tools, which used for face recognition. These analytical tools used in a two or more groups or classification methods. These tools are as follows- One of the most used and cited statistical method is the Principal Component Analysis. A mathematical procedure performs a dimensionality reduction by extracting the principal component of multi-dimensional data. It signifies a series of data points regarding a sum of cosine functions different oscillating frequencies. The Discrete Cosine Transform is based on Fourier discrete transform and therefore, by compacting the variations it can be used to transform images and allowing an efficient dimensionality reduction. LDA is widely used to find the linear combination of features while preserving class separability. Unlike PCA, the LDA tries to model to the difference between levels. For each level the LDA obtains differenced in multiple projection vectors. HE and NIYOGI introduced The LPP. It is the best alternative of PCA for preserve locality structure and designing. Pattern recognition algorithms usually search for the nearest pattern or neighbours. Therefore, the locality maintaining the quality of LLP can quicken the recognition. NIn this algorithm, it signifies that Neuro-physiological data evidence from the visual cortex of mammalian brains suggests that simple cells in the visual cortex can view as a family of self-similar 2D Gabor wavelets. The Gabor functions proposed by Daugman are local spatial bandpass filters that achieve the theoretical limit for conjoint resolution of information in the 2D spatial and 2D Fourier domains. ICA aims to transform the data as linear combinations of the statistically independent data point. Therefore, its goal is to provide an independent instead that uncorrelated image representation. ICA is an alternative to PCA, which give a more powerful data representation. It is a discriminant analysis criterion, which can be used to enhance PCA. Scholkopf et al. introduced the use of Kernel functions for performing nonlinear PCA. Its basic methodology is to apply a nonlinear mapping to the input and then solve a linear PCA in the resulting feature subspace. Neural Network has continued to use pattern recognition and classification. Kohonen was the first to show that a neuron network could be used to recognise aligned and normalised faces. There are methods, which perform feature extraction using neural networks. There are many methods, which combined with tools like PCA or LCA and make a hybrid classifier for face recognition. These are like Feed Forward Neural Network with additional bias, Self-Organizing Maps with PCA, and Convolutional Neural Networks with multi-layer perception, etc. These can increase the efficiency of the models. The algorithm achieves face recognition by implementing a multilayer perceptron with a back-propagation algorithm. Firstly, there is a preprocessing step. Each image normalised in phases of contrast and illumination. Then each image is processed through a Gabor filter. The Gabor filter has five orientation parameters and three spatial frequencies, so there are 15 Gabor wavelengths. Hidden Markov Models are a statistical tool used in face recognition. They have used in conjunction with neural networks. It generated in a neural network that trains pseudo 2D HMM. The input of this 2D HMM process is the output of the ANN, and It provides the algorithm with the proper dimensionality reduction. The fuzzy neural networks for face recognition introduce in 2009. In this a face recognition system using a multilayer perceptron. The concept behind this approach is to capture decision surfaces in nonlinear manifolds a task that a simple MLP can hardly complete. The feature vectors are obtained using Gabor wavelength transforms. There are many ways for face recognition. Here we use OpenCV for face recognition. In face recognition, the image first prepared for preprocessing and then trained the face recogniser to recognise the faces. After teaching the recogniser, we test the recogniser to see the results. The OpenCV face recogniser are of three types, which are as follows- EigenFaces face recogniser views at all the training images of all the characters as a complex and try to deduce the components. These components are necessary and helpful (the parts that grab the most variance/change) and discard the rest of the images, This way it not only extracts the essential elements from the training data but also saves memory by rejecting the less critical segments. Fisherfaces algorithm, instead of obtaining useful features that represent all the faces of all the persons, it removes valuable features that discriminate one person from the others. This features of one person do not dominate over the others, and you have the features that distinguish one person from the others. We know that Eigenfaces and Fisherfaces are both affected by light and in real life; we cannot guarantee perfect light conditions. LBPH face recogniser is an improvement to overcome this drawback. The idea is not to find the local features of an image. LBPH algorithm tries to find the local structure of an image, and it does that by comparing each pixel with its neighbouring pixels. #import OpenCV moduleimport cv2import osimport numpy as npimport matplotlib.pyplot as plt%matplotlib inline#function to detect facedef detect_face (img):#convert the test image to gray imagegray = cv2.cvtColor (img, cv2.COLOR_BGR2GRAY)#load OpenCV face detectorface_cas = cv2.CascadeClassifier ('-File name.xml-')faces = face_cas.detectMultiScale (gray, scaleFactor=1.3, minNeighbors=4);#if no faces are detected then return imageif (len (faces) == 0):return None, None#extract the facefaces [0]=(x, y, w, h)#return only the face partreturn gray[y: y+w, x: x+h], faces [0]#this function will read all persons' training images, detect face #from each image#and will return two lists of exactly same size, one listdef prepare_training_data(data_folder_path):#------STEP-1--------#get the directories (one directory for each subject) in data folderdirs = os.listdir(data_folder_path)faces = []labels = []for dir_name in dirs:#our subject directories start with letter 's' so#ignore any non-relevant directories if anyif not dir_name.startswith("s"):continue;#------STEP-2--------#extract label number of subject from dir_name#format of dir name = slabel#, so removing letter 's' from dir_name will give us labellabel = int(dir_name.replace("s", ""))#build path of directory containin images for current subject subject#sample subject_dir_path = "training-data/s1"subject_dir_path = data_folder_path + "/" + dir_name#get the images names that are inside the given subject directorysubject_images_names = os.listdir(subject_dir_path)#------STEP-3--------#go through each image name, read image,#detect face and add face to list of facesfor image_name in subject_images_names:#ignore system files like .DS_Storeif image_name.startswith("."):continue;#build image path#sample image path = training-data/s1/1.pgmimage_path = subject_dir_path + "/" + image_name#read imageimage = cv2.imread(image_path)#display an image window to show the imagecv2.imshow("Training on image...", image)cv2.waitKey(100)#detect faceface, rect = detect_face(image)#------STEP-4--------#we will ignore faces that are not detectedif face is not None:#add face to list of facesfaces.append(face)#add label for this facelabels.append(label)cv2.destroyAllWindows()cv2.waitKey(1)cv2.destroyAllWindows()return faces, labels#let's first prepare our training data#data will be in two lists of same size#one list will contain all the faces#and other list will contain respective labels for each faceprint("Preparing data...")faces, labels = prepare_training_data("training-data")print("Data prepared")#print total faces and labelsprint("Total faces: ", len(faces))print("Total labels: ", len(labels))#create our LBPH face recognizerface_recognizer = cv2.face.createLBPHFaceRecognizer()#train our face recognizer of our training facesface_recognizer.train(faces, np.array(labels))#function to draw rectangle on image#according to given (x, y) coordinates and#given width and heighdef draw_rectangle(img, rect):(x, y, w, h) = rectcv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 2)#function to draw text on give image starting from#passed (x, y) coordinates.def draw_text(img, text, x, y):cv2.putText(img, text, (x, y), cv2.FONT_HERSHEY_PLAIN, 1.5, (0, 255, 0), 2)#this function recognizes the person in image passed#and draws a rectangle around detected face with name of the subjectdef predict(test_img):#make a copy of the image as we don't want to chang original imageimg = test_img.copy()#detect face from the imageface, rect = detect_face(img)#predict the image using our face recognizerlabel= face_recognizer.predict(face)#get name of respective label returned by face recognizerlabel_text = subjects[label]#draw a rectangle around face detecteddraw_rectangle(img, rect)#draw name of predicted persondraw_text(img, label_text, rect[0], rect[1]-5)return img#load test imagestest_img1 = cv2.imread("test-data/test1.jpg")test_img2 = cv2.imread("test-data/test2.jpg")#perform a predictionpredicted_img1 = predict(test_img1)predicted_img2 = predict(test_img2)print("Prediction complete")#create a figure of 2 plots (one for each test image)f, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 5))#display test image1 resultax1.imshow(cv2.cvtColor(predicted_img1, cv2.COLOR_BGR2RGB))#display test image2 resultax2.imshow(cv2.cvtColor(predicted_img2, cv2.COLOR_BGR2RGB))#display both imagescv2.imshow("Tom cruise test", predicted_img1)cv2.imshow("Shahrukh Khan test", predicted_img2)cv2.waitKey(0)cv2.destroyAllWindows()cv2.waitKey(1)cv2.destroyAllWindows() This blog is for beginners who want to start their carrier in the field of Computer Vision or AI by learning about what is face recognition, its types, and how it works.
[ { "code": null, "e": 538, "s": 172, "text": "Face Recognition is a recognition technique used to detect faces of individuals whose images saved in the data set. Despite the point that other methods of identification can be more accurate, face recognition has always remained a significant focus of research because of its non-meddling nature and because it is people’s facile method of personal identification." }, { "code": null, "e": 610, "s": 538, "text": "There are different methods for face recognition, which are as follows-" }, { "code": null, "e": 1055, "s": 610, "text": "Face recognition algorithms classified as geometry based or template based algorithms. The template-based methods can be constructed using statistical tools like SVM [Support Vector Machines], PCA [Principal Component Analysis], LDA [Linear Discriminant Analysis], Kernel methods or Trace Transforms. The geometric feature based methods analyse local facial features and their geometric relationship. It is also known as a feature-based method." }, { "code": null, "e": 1464, "s": 1055, "text": "The relation between the elements or the connection of a function with the whole face not undergone into the amount, many researchers followed this approach, trying to deduce the most relevant characteristics. Some methods attempted to use the eyes, a combination of features and so on. Some Hidden Markov Model methods also fall into this category, and feature processing is very famous in face recognition." }, { "code": null, "e": 1878, "s": 1464, "text": "The appearance-based method shows a face regarding several images. An image considered as a high dimensional vector. This technique is usually used to derive a feature space from the image division. The sample image compared to the training set. On the other hand, the model-based approach tries to model a face. The new sample implemented to the model and the parameters of the model used to recognise the image." }, { "code": null, "e": 2146, "s": 1878, "text": "The appearance-based method can classify as linear or nonlinear. Ex- PCA, LDA, IDA used in direct approach whereas Kernel PCA used in nonlinear approach. On the other hand, in the model-based method can be classified as 2D or 3D Ex- Elastic Bunch Graph Matching used." }, { "code": null, "e": 2310, "s": 2146, "text": "In template matching the patterns are represented by samples, models, pixels, textures, etc. The recognition function is usually a correlation or distance measure." }, { "code": null, "e": 2572, "s": 2310, "text": "In the Statistical approach, the patterns expressed as features. The recognition function in a discriminant function. Each image represented regarding d features. Therefore, the goal is to choose and apply the right statistical tool for extraction and analysis." }, { "code": null, "e": 2746, "s": 2572, "text": "There are many statistical tools, which used for face recognition. These analytical tools used in a two or more groups or classification methods. These tools are as follows-" }, { "code": null, "e": 2959, "s": 2746, "text": "One of the most used and cited statistical method is the Principal Component Analysis. A mathematical procedure performs a dimensionality reduction by extracting the principal component of multi-dimensional data." }, { "code": null, "e": 3267, "s": 2959, "text": "It signifies a series of data points regarding a sum of cosine functions different oscillating frequencies. The Discrete Cosine Transform is based on Fourier discrete transform and therefore, by compacting the variations it can be used to transform images and allowing an efficient dimensionality reduction." }, { "code": null, "e": 3510, "s": 3267, "text": "LDA is widely used to find the linear combination of features while preserving class separability. Unlike PCA, the LDA tries to model to the difference between levels. For each level the LDA obtains differenced in multiple projection vectors." }, { "code": null, "e": 3794, "s": 3510, "text": "HE and NIYOGI introduced The LPP. It is the best alternative of PCA for preserve locality structure and designing. Pattern recognition algorithms usually search for the nearest pattern or neighbours. Therefore, the locality maintaining the quality of LLP can quicken the recognition." }, { "code": null, "e": 4204, "s": 3794, "text": "NIn this algorithm, it signifies that Neuro-physiological data evidence from the visual cortex of mammalian brains suggests that simple cells in the visual cortex can view as a family of self-similar 2D Gabor wavelets. The Gabor functions proposed by Daugman are local spatial bandpass filters that achieve the theoretical limit for conjoint resolution of information in the 2D spatial and 2D Fourier domains." }, { "code": null, "e": 4553, "s": 4204, "text": "ICA aims to transform the data as linear combinations of the statistically independent data point. Therefore, its goal is to provide an independent instead that uncorrelated image representation. ICA is an alternative to PCA, which give a more powerful data representation. It is a discriminant analysis criterion, which can be used to enhance PCA." }, { "code": null, "e": 4769, "s": 4553, "text": "Scholkopf et al. introduced the use of Kernel functions for performing nonlinear PCA. Its basic methodology is to apply a nonlinear mapping to the input and then solve a linear PCA in the resulting feature subspace." }, { "code": null, "e": 5359, "s": 4769, "text": "Neural Network has continued to use pattern recognition and classification. Kohonen was the first to show that a neuron network could be used to recognise aligned and normalised faces. There are methods, which perform feature extraction using neural networks. There are many methods, which combined with tools like PCA or LCA and make a hybrid classifier for face recognition. These are like Feed Forward Neural Network with additional bias, Self-Organizing Maps with PCA, and Convolutional Neural Networks with multi-layer perception, etc. These can increase the efficiency of the models." }, { "code": null, "e": 5744, "s": 5359, "text": "The algorithm achieves face recognition by implementing a multilayer perceptron with a back-propagation algorithm. Firstly, there is a preprocessing step. Each image normalised in phases of contrast and illumination. Then each image is processed through a Gabor filter. The Gabor filter has five orientation parameters and three spatial frequencies, so there are 15 Gabor wavelengths." }, { "code": null, "e": 6057, "s": 5744, "text": "Hidden Markov Models are a statistical tool used in face recognition. They have used in conjunction with neural networks. It generated in a neural network that trains pseudo 2D HMM. The input of this 2D HMM process is the output of the ANN, and It provides the algorithm with the proper dimensionality reduction." }, { "code": null, "e": 6390, "s": 6057, "text": "The fuzzy neural networks for face recognition introduce in 2009. In this a face recognition system using a multilayer perceptron. The concept behind this approach is to capture decision surfaces in nonlinear manifolds a task that a simple MLP can hardly complete. The feature vectors are obtained using Gabor wavelength transforms." }, { "code": null, "e": 6741, "s": 6390, "text": "There are many ways for face recognition. Here we use OpenCV for face recognition. In face recognition, the image first prepared for preprocessing and then trained the face recogniser to recognise the faces. After teaching the recogniser, we test the recogniser to see the results. The OpenCV face recogniser are of three types, which are as follows-" }, { "code": null, "e": 7135, "s": 6741, "text": "EigenFaces face recogniser views at all the training images of all the characters as a complex and try to deduce the components. These components are necessary and helpful (the parts that grab the most variance/change) and discard the rest of the images, This way it not only extracts the essential elements from the training data but also saves memory by rejecting the less critical segments." }, { "code": null, "e": 7451, "s": 7135, "text": "Fisherfaces algorithm, instead of obtaining useful features that represent all the faces of all the persons, it removes valuable features that discriminate one person from the others. This features of one person do not dominate over the others, and you have the features that distinguish one person from the others." }, { "code": null, "e": 7837, "s": 7451, "text": "We know that Eigenfaces and Fisherfaces are both affected by light and in real life; we cannot guarantee perfect light conditions. LBPH face recogniser is an improvement to overcome this drawback. The idea is not to find the local features of an image. LBPH algorithm tries to find the local structure of an image, and it does that by comparing each pixel with its neighbouring pixels." }, { "code": null, "e": 12352, "s": 7837, "text": "#import OpenCV moduleimport cv2import osimport numpy as npimport matplotlib.pyplot as plt%matplotlib inline#function to detect facedef detect_face (img):#convert the test image to gray imagegray = cv2.cvtColor (img, cv2.COLOR_BGR2GRAY)#load OpenCV face detectorface_cas = cv2.CascadeClassifier ('-File name.xml-')faces = face_cas.detectMultiScale (gray, scaleFactor=1.3, minNeighbors=4);#if no faces are detected then return imageif (len (faces) == 0):return None, None#extract the facefaces [0]=(x, y, w, h)#return only the face partreturn gray[y: y+w, x: x+h], faces [0]#this function will read all persons' training images, detect face #from each image#and will return two lists of exactly same size, one listdef prepare_training_data(data_folder_path):#------STEP-1--------#get the directories (one directory for each subject) in data folderdirs = os.listdir(data_folder_path)faces = []labels = []for dir_name in dirs:#our subject directories start with letter 's' so#ignore any non-relevant directories if anyif not dir_name.startswith(\"s\"):continue;#------STEP-2--------#extract label number of subject from dir_name#format of dir name = slabel#, so removing letter 's' from dir_name will give us labellabel = int(dir_name.replace(\"s\", \"\"))#build path of directory containin images for current subject subject#sample subject_dir_path = \"training-data/s1\"subject_dir_path = data_folder_path + \"/\" + dir_name#get the images names that are inside the given subject directorysubject_images_names = os.listdir(subject_dir_path)#------STEP-3--------#go through each image name, read image,#detect face and add face to list of facesfor image_name in subject_images_names:#ignore system files like .DS_Storeif image_name.startswith(\".\"):continue;#build image path#sample image path = training-data/s1/1.pgmimage_path = subject_dir_path + \"/\" + image_name#read imageimage = cv2.imread(image_path)#display an image window to show the imagecv2.imshow(\"Training on image...\", image)cv2.waitKey(100)#detect faceface, rect = detect_face(image)#------STEP-4--------#we will ignore faces that are not detectedif face is not None:#add face to list of facesfaces.append(face)#add label for this facelabels.append(label)cv2.destroyAllWindows()cv2.waitKey(1)cv2.destroyAllWindows()return faces, labels#let's first prepare our training data#data will be in two lists of same size#one list will contain all the faces#and other list will contain respective labels for each faceprint(\"Preparing data...\")faces, labels = prepare_training_data(\"training-data\")print(\"Data prepared\")#print total faces and labelsprint(\"Total faces: \", len(faces))print(\"Total labels: \", len(labels))#create our LBPH face recognizerface_recognizer = cv2.face.createLBPHFaceRecognizer()#train our face recognizer of our training facesface_recognizer.train(faces, np.array(labels))#function to draw rectangle on image#according to given (x, y) coordinates and#given width and heighdef draw_rectangle(img, rect):(x, y, w, h) = rectcv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 2)#function to draw text on give image starting from#passed (x, y) coordinates.def draw_text(img, text, x, y):cv2.putText(img, text, (x, y), cv2.FONT_HERSHEY_PLAIN, 1.5, (0, 255, 0), 2)#this function recognizes the person in image passed#and draws a rectangle around detected face with name of the subjectdef predict(test_img):#make a copy of the image as we don't want to chang original imageimg = test_img.copy()#detect face from the imageface, rect = detect_face(img)#predict the image using our face recognizerlabel= face_recognizer.predict(face)#get name of respective label returned by face recognizerlabel_text = subjects[label]#draw a rectangle around face detecteddraw_rectangle(img, rect)#draw name of predicted persondraw_text(img, label_text, rect[0], rect[1]-5)return img#load test imagestest_img1 = cv2.imread(\"test-data/test1.jpg\")test_img2 = cv2.imread(\"test-data/test2.jpg\")#perform a predictionpredicted_img1 = predict(test_img1)predicted_img2 = predict(test_img2)print(\"Prediction complete\")#create a figure of 2 plots (one for each test image)f, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 5))#display test image1 resultax1.imshow(cv2.cvtColor(predicted_img1, cv2.COLOR_BGR2RGB))#display test image2 resultax2.imshow(cv2.cvtColor(predicted_img2, cv2.COLOR_BGR2RGB))#display both imagescv2.imshow(\"Tom cruise test\", predicted_img1)cv2.imshow(\"Shahrukh Khan test\", predicted_img2)cv2.waitKey(0)cv2.destroyAllWindows()cv2.waitKey(1)cv2.destroyAllWindows()" } ]
8 Types of Sampling Techniques. Understanding Sampling Methods (Visuals... | by Prakhar Mishra | Towards Data Science
Sampling is the process of selecting a subset(a predetermined number of observations) from a larger population. It’s a pretty common technique wherein, we run experiments and draw conclusions about the population, without the need of having to study the entire population. In this blog, we will go through two types of sampling methods: Probability Sampling β€”Here we choose a sample based on the theory of probability.Non-Probability Sampling β€” Here we choose a sample based on non-random criteria, and not every member of the population has a chance of being included. Probability Sampling β€”Here we choose a sample based on the theory of probability. Non-Probability Sampling β€” Here we choose a sample based on non-random criteria, and not every member of the population has a chance of being included. Under Random sampling, every element of the population has an equal probability of getting selected. Below fig. shows the pictorial view of the same β€” All the points collectively represent the entire population wherein every point has an equal chance of getting selected. You can implement it using python as shown below β€” import randompopulation = 100data = range(population)print(random.sample(data,5))> 4, 19, 82, 45, 41 Under stratified sampling, we group the entire population into subpopulations by some common property. For example β€” Class labels in a typical ML classification task. We then randomly sample from those groups individually, such that the groups are still maintained in the same ratio as they were in the entire population. Below fig. shows a pictorial view of the same β€” We have two groups with a count ratio of x and 4x based on the colour, we randomly sample from yellow and green sets separately and represent the final set in the same ratio of these groups. You can implement it very easily using python sklearn lib. as shown below β€” from sklearn.model_selection import train_test_splitstratified_sample, _ = train_test_split(population, test_size=0.9, stratify=population[['label']])print (stratified_sample) You can also implement it without the lib., read this. In Cluster sampling, we divide the entire population into subgroups, wherein, each of those subgroups has similar characteristics to that of the population when considered in totality. Also, instead of sampling individuals, we randomly select the entire subgroups. As can be seen in the below fig. that we had 4 clusters with similar properties (size and shape), we randomly select two clusters and treat them as samples. Real-Life example β€” Class of 120 students divided into groups of 12 for a common class project. Clustering parameters like (Designation, Class, Topic) are all similar over here as well. You can implement it using python as shown below β€” import numpy as npclusters=5pop_size = 100sample_clusters=2#assigning cluster ids sequentially from 1 to 5 on gap of 20cluster_ids = np.repeat([range(1,clusters+1)], pop_size/clusters)cluster_to_select = random.sample(set(cluster_ids), sample_clusters)indexes = [i for i, x in enumerate(cluster_ids) if x in cluster_to_select]cluster_associated_elements = [el for idx, el in enumerate(range(1, 101)) if idx in indexes]print (cluster_associated_elements) Systematic sampling is about sampling items from the population at regular predefined intervals(basically fixed and periodic intervals). For example β€” Every 5th element, 21st element and so on. This sampling method tends to be more effective than the vanilla random sampling method in general. Below fig. shows a pictorial view of the same β€” We sample every 9th and 7th element in order and then repeat this pattern. You can implement it using python as shown below β€” population = 100step = 5sample = [element for element in range(1, population, step)]print (sample) Under Multistage sampling, we stack multiple sampling methods one after the other. For example, at the first stage, cluster sampling can be used to choose clusters from the population and then we can perform random sampling to choose elements from each cluster to form the final set. Below fig. shows a pictorial view of the same β€” You can implement it using python as shown below β€” import numpy as npclusters=5pop_size = 100sample_clusters=2sample_size=5#assigning cluster ids sequentially from 1 to 5 on gap of 20cluster_ids = np.repeat([range(1,clusters+1)], pop_size/clusters)cluster_to_select = random.sample(set(cluster_ids), sample_clusters)indexes = [i for i, x in enumerate(cluster_ids) if x in cluster_to_select]cluster_associated_elements = [el for idx, el in enumerate(range(1, 101)) if idx in indexes]print (random.sample(cluster_associated_elements, sample_size)) Under convenience sampling, the researcher includes only those individuals who are most accessible and available to participate in the study. Below fig. shows the pictorial view of the same β€” Blue dot is the researcher and orange dots are the most accessible set of people in orange’s vicinity. Under Voluntary sampling, interested people usually take part by themselves by filling in some sort of survey forms. A good example of this is the youtube survey about β€œHave you seen any of these ads”, which has been recently shown a lot. Here, the researcher who is conducting the survey has no right to choose anyone. Below fig. shows the pictorial view of the same β€” Blue dot is the researcher, orange one’s are those who voluntarily agreed to take part in the study. Under Snowball sampling, the final set is chosen via other participants, i.e. The researcher asks other known contacts to find people who would like to participate in the study. Below fig. shows the pictorial view of the same β€” Blue dot is the researcher, orange ones are known contacts(of the researcher), and yellow ones (orange’s contacts) are other people that got ready to participate in the study. Also if research papers interest you then you can checkout some research paper summaries that I have written. I hope you enjoyed reading this. If you’d like to support me as a writer, consider signing up to become a Medium member. It’s just $5 a month and you get unlimited access to Medium So, that’s it for this blog. Thank you for your time!
[ { "code": null, "e": 508, "s": 171, "text": "Sampling is the process of selecting a subset(a predetermined number of observations) from a larger population. It’s a pretty common technique wherein, we run experiments and draw conclusions about the population, without the need of having to study the entire population. In this blog, we will go through two types of sampling methods:" }, { "code": null, "e": 741, "s": 508, "text": "Probability Sampling β€”Here we choose a sample based on the theory of probability.Non-Probability Sampling β€” Here we choose a sample based on non-random criteria, and not every member of the population has a chance of being included." }, { "code": null, "e": 823, "s": 741, "text": "Probability Sampling β€”Here we choose a sample based on the theory of probability." }, { "code": null, "e": 975, "s": 823, "text": "Non-Probability Sampling β€” Here we choose a sample based on non-random criteria, and not every member of the population has a chance of being included." }, { "code": null, "e": 1247, "s": 975, "text": "Under Random sampling, every element of the population has an equal probability of getting selected. Below fig. shows the pictorial view of the same β€” All the points collectively represent the entire population wherein every point has an equal chance of getting selected." }, { "code": null, "e": 1298, "s": 1247, "text": "You can implement it using python as shown below β€”" }, { "code": null, "e": 1399, "s": 1298, "text": "import randompopulation = 100data = range(population)print(random.sample(data,5))> 4, 19, 82, 45, 41" }, { "code": null, "e": 1960, "s": 1399, "text": "Under stratified sampling, we group the entire population into subpopulations by some common property. For example β€” Class labels in a typical ML classification task. We then randomly sample from those groups individually, such that the groups are still maintained in the same ratio as they were in the entire population. Below fig. shows a pictorial view of the same β€” We have two groups with a count ratio of x and 4x based on the colour, we randomly sample from yellow and green sets separately and represent the final set in the same ratio of these groups." }, { "code": null, "e": 2036, "s": 1960, "text": "You can implement it very easily using python sklearn lib. as shown below β€”" }, { "code": null, "e": 2212, "s": 2036, "text": "from sklearn.model_selection import train_test_splitstratified_sample, _ = train_test_split(population, test_size=0.9, stratify=population[['label']])print (stratified_sample)" }, { "code": null, "e": 2267, "s": 2212, "text": "You can also implement it without the lib., read this." }, { "code": null, "e": 2689, "s": 2267, "text": "In Cluster sampling, we divide the entire population into subgroups, wherein, each of those subgroups has similar characteristics to that of the population when considered in totality. Also, instead of sampling individuals, we randomly select the entire subgroups. As can be seen in the below fig. that we had 4 clusters with similar properties (size and shape), we randomly select two clusters and treat them as samples." }, { "code": null, "e": 2875, "s": 2689, "text": "Real-Life example β€” Class of 120 students divided into groups of 12 for a common class project. Clustering parameters like (Designation, Class, Topic) are all similar over here as well." }, { "code": null, "e": 2926, "s": 2875, "text": "You can implement it using python as shown below β€”" }, { "code": null, "e": 3380, "s": 2926, "text": "import numpy as npclusters=5pop_size = 100sample_clusters=2#assigning cluster ids sequentially from 1 to 5 on gap of 20cluster_ids = np.repeat([range(1,clusters+1)], pop_size/clusters)cluster_to_select = random.sample(set(cluster_ids), sample_clusters)indexes = [i for i, x in enumerate(cluster_ids) if x in cluster_to_select]cluster_associated_elements = [el for idx, el in enumerate(range(1, 101)) if idx in indexes]print (cluster_associated_elements)" }, { "code": null, "e": 3797, "s": 3380, "text": "Systematic sampling is about sampling items from the population at regular predefined intervals(basically fixed and periodic intervals). For example β€” Every 5th element, 21st element and so on. This sampling method tends to be more effective than the vanilla random sampling method in general. Below fig. shows a pictorial view of the same β€” We sample every 9th and 7th element in order and then repeat this pattern." }, { "code": null, "e": 3848, "s": 3797, "text": "You can implement it using python as shown below β€”" }, { "code": null, "e": 3947, "s": 3848, "text": "population = 100step = 5sample = [element for element in range(1, population, step)]print (sample)" }, { "code": null, "e": 4279, "s": 3947, "text": "Under Multistage sampling, we stack multiple sampling methods one after the other. For example, at the first stage, cluster sampling can be used to choose clusters from the population and then we can perform random sampling to choose elements from each cluster to form the final set. Below fig. shows a pictorial view of the same β€”" }, { "code": null, "e": 4330, "s": 4279, "text": "You can implement it using python as shown below β€”" }, { "code": null, "e": 4825, "s": 4330, "text": "import numpy as npclusters=5pop_size = 100sample_clusters=2sample_size=5#assigning cluster ids sequentially from 1 to 5 on gap of 20cluster_ids = np.repeat([range(1,clusters+1)], pop_size/clusters)cluster_to_select = random.sample(set(cluster_ids), sample_clusters)indexes = [i for i, x in enumerate(cluster_ids) if x in cluster_to_select]cluster_associated_elements = [el for idx, el in enumerate(range(1, 101)) if idx in indexes]print (random.sample(cluster_associated_elements, sample_size))" }, { "code": null, "e": 5120, "s": 4825, "text": "Under convenience sampling, the researcher includes only those individuals who are most accessible and available to participate in the study. Below fig. shows the pictorial view of the same β€” Blue dot is the researcher and orange dots are the most accessible set of people in orange’s vicinity." }, { "code": null, "e": 5591, "s": 5120, "text": "Under Voluntary sampling, interested people usually take part by themselves by filling in some sort of survey forms. A good example of this is the youtube survey about β€œHave you seen any of these ads”, which has been recently shown a lot. Here, the researcher who is conducting the survey has no right to choose anyone. Below fig. shows the pictorial view of the same β€” Blue dot is the researcher, orange one’s are those who voluntarily agreed to take part in the study." }, { "code": null, "e": 5995, "s": 5591, "text": "Under Snowball sampling, the final set is chosen via other participants, i.e. The researcher asks other known contacts to find people who would like to participate in the study. Below fig. shows the pictorial view of the same β€” Blue dot is the researcher, orange ones are known contacts(of the researcher), and yellow ones (orange’s contacts) are other people that got ready to participate in the study." }, { "code": null, "e": 6105, "s": 5995, "text": "Also if research papers interest you then you can checkout some research paper summaries that I have written." }, { "code": null, "e": 6286, "s": 6105, "text": "I hope you enjoyed reading this. If you’d like to support me as a writer, consider signing up to become a Medium member. It’s just $5 a month and you get unlimited access to Medium" } ]
Division without using β€˜/’ operator in C++ Program
In this tutorial, we are going to learn how to divide a number without using the division (/) operator. We have given two numbers, the program should return the quotient of the division operation. We are going to use the subtraction (-) operator for the division. Let's see the steps to solve the problem. Initialize the dividend and divisor. Initialize the dividend and divisor. If the number is zero, then return 0. If the number is zero, then return 0. Store whether the result will be negative or not by checking the signs of dividend and divisor. Store whether the result will be negative or not by checking the signs of dividend and divisor. Initialize a count to 0. Initialize a count to 0. Write a loop that runs until the number one is greater than or equals to the number two.Subtract the number two from the number one and assign the result to the number oneIncrement the counter. Write a loop that runs until the number one is greater than or equals to the number two. Subtract the number two from the number one and assign the result to the number one Subtract the number two from the number one and assign the result to the number one Increment the counter. Increment the counter. Print the counter. Print the counter. Let's see the code. Live Demo #include <bits/stdc++.h> using namespace std; int division(int num_one, int num_two) { if (num_one == 0) { return 0; } if (num_two == 0) { return INT_MAX; } bool negative_result = false; if (num_one < 0) { num_one = -num_one ; if (num_two < 0) { num_two = -num_two ; } else { negative_result = true; } } else if (num_two < 0) { num_two = -num_two; negative_result = true; } int quotient = 0; while (num_one >= num_two) { num_one = num_one - num_two; quotient++; } if (negative_result) { quotient = -quotient; } return quotient; } int main() { int num_one = 24, num_two = 5; cout << division(num_one, num_two) << endl; return 0; } If you run the above code, then you will get the following result. 4 If you have any queries in the tutorial, mention them in the comment section.
[ { "code": null, "e": 1166, "s": 1062, "text": "In this tutorial, we are going to learn how to divide a number without using the division (/) operator." }, { "code": null, "e": 1259, "s": 1166, "text": "We have given two numbers, the program should return the quotient of the division operation." }, { "code": null, "e": 1326, "s": 1259, "text": "We are going to use the subtraction (-) operator for the division." }, { "code": null, "e": 1368, "s": 1326, "text": "Let's see the steps to solve the problem." }, { "code": null, "e": 1405, "s": 1368, "text": "Initialize the dividend and divisor." }, { "code": null, "e": 1442, "s": 1405, "text": "Initialize the dividend and divisor." }, { "code": null, "e": 1480, "s": 1442, "text": "If the number is zero, then return 0." }, { "code": null, "e": 1518, "s": 1480, "text": "If the number is zero, then return 0." }, { "code": null, "e": 1614, "s": 1518, "text": "Store whether the result will be negative or not by checking the signs of dividend and divisor." }, { "code": null, "e": 1710, "s": 1614, "text": "Store whether the result will be negative or not by checking the signs of dividend and divisor." }, { "code": null, "e": 1735, "s": 1710, "text": "Initialize a count to 0." }, { "code": null, "e": 1760, "s": 1735, "text": "Initialize a count to 0." }, { "code": null, "e": 1954, "s": 1760, "text": "Write a loop that runs until the number one is greater than or equals to the number two.Subtract the number two from the number one and assign the result to the number oneIncrement the counter." }, { "code": null, "e": 2043, "s": 1954, "text": "Write a loop that runs until the number one is greater than or equals to the number two." }, { "code": null, "e": 2127, "s": 2043, "text": "Subtract the number two from the number one and assign the result to the number one" }, { "code": null, "e": 2211, "s": 2127, "text": "Subtract the number two from the number one and assign the result to the number one" }, { "code": null, "e": 2234, "s": 2211, "text": "Increment the counter." }, { "code": null, "e": 2257, "s": 2234, "text": "Increment the counter." }, { "code": null, "e": 2276, "s": 2257, "text": "Print the counter." }, { "code": null, "e": 2295, "s": 2276, "text": "Print the counter." }, { "code": null, "e": 2315, "s": 2295, "text": "Let's see the code." }, { "code": null, "e": 2326, "s": 2315, "text": " Live Demo" }, { "code": null, "e": 3100, "s": 2326, "text": "#include <bits/stdc++.h>\nusing namespace std;\nint division(int num_one, int num_two) {\n if (num_one == 0) {\n return 0;\n }\n if (num_two == 0) {\n return INT_MAX;\n }\n bool negative_result = false;\n if (num_one < 0) {\n num_one = -num_one ;\n if (num_two < 0) {\n num_two = -num_two ;\n }\n else {\n negative_result = true;\n }\n }\n else if (num_two < 0) {\n num_two = -num_two;\n negative_result = true;\n }\n int quotient = 0;\n while (num_one >= num_two) {\n num_one = num_one - num_two;\n quotient++;\n }\n if (negative_result) {\n quotient = -quotient;\n }\n return quotient;\n}\nint main() {\n int num_one = 24, num_two = 5;\n cout << division(num_one, num_two) << endl;\n return 0;\n}" }, { "code": null, "e": 3167, "s": 3100, "text": "If you run the above code, then you will get the following result." }, { "code": null, "e": 3169, "s": 3167, "text": "4" }, { "code": null, "e": 3247, "s": 3169, "text": "If you have any queries in the tutorial, mention them in the comment section." } ]
Design and Implement Special Stack Data Structure | Added Space Optimized Version - GeeksforGeeks
21 Feb, 2022 Question: Design a Data Structure SpecialStack that supports all the stack operations like push(), pop(), isEmpty(), isFull() and an additional operation getMin() which should return minimum element from the SpecialStack. All these operations of SpecialStack must be O(1). To implement SpecialStack, you should only use standard Stack data structure and no other data structure like arrays, list, . etc. Example: Consider the following SpecialStack 16 --> TOP 15 29 19 18 When getMin() is called it should return 15, which is the minimum element in the current stack. If we do pop two times on stack, the stack becomes 29 --> TOP 19 18 When getMin() is called, it should return 18 which is the minimum in the current stack. Solution: Use two stacks: one to store actual stack elements and the other as an auxiliary stack to store minimum values. The idea is to do push() and pop() operations in such a way that the top of the auxiliary stack is always the minimum. Let us see how push() and pop() operations work. Push(int x) // inserts an element x to Special Stack 1) push x to the first stack (the stack with actual elements) 2) compare x with the top element of the second stack (the auxiliary stack). Let the top element be y. .....a) If x is smaller than y then push x to the auxiliary stack. .....b) If x is greater than y then push y to the auxiliary stack.int Pop() // removes an element from Special Stack and return the removed element 1) pop the top element from the auxiliary stack. 2) pop the top element from the actual stack and return it.Step 1 is necessary to make sure that the auxiliary stack is also updated for future operations.int getMin() // returns the minimum element from Special Stack 1) Return the top element of the auxiliary stack. We can see that all the above operations are O(1). Let us see an example. Let us assume that both stacks are initially empty and 18, 19, 29, 15, and 16 are inserted to the SpecialStack. When we insert 18, both stacks change to following. Actual Stack 18 <--- top Auxiliary Stack 18 <---- top When 19 is inserted, both stacks change to following. Actual Stack 19 <--- top 18 Auxiliary Stack 18 <---- top 18 When 29 is inserted, both stacks change to following. Actual Stack 29 <--- top 19 18 Auxiliary Stack 18 <---- top 18 18 When 15 is inserted, both stacks change to following. Actual Stack 15 <--- top 29 19 18 Auxiliary Stack 15 <---- top 18 18 18 When 16 is inserted, both stacks change to following. Actual Stack 16 <--- top 15 29 19 18 Auxiliary Stack 15 <---- top 15 18 18 18 The following is the implementation for SpecialStack class. In the below implementation, SpecialStack inherits from Stack and has one Stack object min which works as an auxiliary stack. C++ Java Python3 #include <iostream>#include <stdlib.h> using namespace std; /* A simple stack class withbasic stack functionalities */class Stack {private: static const int max = 100; int arr[max]; int top; public: Stack() { top = -1; } bool isEmpty(); bool isFull(); int pop(); void push(int x);}; /* Stack's member method to checkif the stack is empty */bool Stack::isEmpty(){ if (top == -1) return true; return false;} /* Stack's member method to checkif the stack is full */bool Stack::isFull(){ if (top == max - 1) return true; return false;} /* Stack's member method to removean element from it */int Stack::pop(){ if (isEmpty()) { cout << "Stack Underflow"; abort(); } int x = arr[top]; top--; return x;} /* Stack's member method to insertan element to it */void Stack::push(int x){ if (isFull()) { cout << "Stack Overflow"; abort(); } top++; arr[top] = x;} /* A class that supports all the stackoperations and one additional operation getMin() that returns theminimum element from stack at any time. This class inherits fromthe stack class and uses an auxiliary stack that holds minimumelements */class SpecialStack : public Stack { Stack min; public: int pop(); void push(int x); int getMin();}; /* SpecialStack's member method to insert an element to it. This method makes sure that the min stack is alsoupdated with appropriate minimum values */void SpecialStack::push(int x){ if (isEmpty() == true) { Stack::push(x); min.push(x); } else { Stack::push(x); int y = min.pop(); min.push(y); if (x < y) min.push(x); else min.push(y); }} /* SpecialStack's member method toremove an element from it. This method removes top element from min stack also. */int SpecialStack::pop(){ int x = Stack::pop(); min.pop(); return x;} /* SpecialStack's member method to get minimum element from it. */int SpecialStack::getMin(){ int x = min.pop(); min.push(x); return x;} /* Driver program to test SpecialStack methods */int main(){ SpecialStack s; s.push(10); s.push(20); s.push(30); cout << s.getMin() << endl; s.push(5); cout << s.getMin(); return 0;} // Java implementation of SpecialStack// Note : here we use Stack class for// Stack implementation import java.util.Stack; /* A class that supports all thestack operations and one additionaloperation getMin() that returnsthe minimum element from stack atany time. This class inherits fromthe stack class and uses anauxiliary stack that holds minimum elements */ class SpecialStack extends Stack<Integer> { Stack<Integer> min = new Stack<>(); /* SpecialStack's member method toinsert an element to it. This method makes sure that the min stack isalso updated with appropriate minimum values */ void push(int x) { if (isEmpty() == true) { super.push(x); min.push(x); } else { super.push(x); int y = min.pop(); min.push(y); if (x < y) min.push(x); else min.push(y); } } /* SpecialStack's member method toinsert an element to it. This method makes sure that the min stack isalso updated with appropriate minimum values */ public Integer pop() { int x = super.pop(); min.pop(); return x; } /* SpecialStack's member method to getminimum element from it. */ int getMin() { int x = min.pop(); min.push(x); return x; } /* Driver program to test SpecialStackmethods */ public static void main(String[] args) { SpecialStack s = new SpecialStack(); s.push(10); s.push(20); s.push(30); System.out.println(s.getMin()); s.push(5); System.out.println(s.getMin()); }}// This code is contributed by Sumit Ghosh # Python3 program for the# above approach# A simple stack class with # basic stack functionalitiesclass stack: def __init__(self): self.array = [] self.top = -1 self.max = 100 # Stack's member method to check # if the stack is empty def isEmpty(self): if self.top == -1: return True else: return False # Stack's member method to check # if the stack is full def isFull(self): if self.top == self.max - 1: return True else: return False # Stack's member method to # insert an element to it def push(self, data): if self.isFull(): print('Stack OverFlow') return else: self.top += 1 self.array.append(data) # Stack's member method to # remove an element from it def pop(self): if self.isEmpty(): print('Stack UnderFlow') return else: self.top -= 1 return self.array.pop() # A class that supports all the stack # operations and one additional# operation getMin() that returns the# minimum element from stack at# any time. This class inherits from# the stack class and uses an# auxiliary stack that holds# minimum elements class SpecialStack(stack): def __init__(self): super().__init__() self.Min = stack() # SpecialStack's member method to # insert an element to it. This method # makes sure that the min stack is also # updated with appropriate minimum # values def push(self, x): if self.isEmpty(): super().push(x) self.Min.push(x) else: super().push(x) y = self.Min.pop() self.Min.push(y) if x <= y: self.Min.push(x) else: self.Min.push(y) # SpecialStack's member method to # remove an element from it. This # method removes top element from # min stack also. def pop(self): x = super().pop() self.Min.pop() return x # SpecialStack's member method # to get minimum element from it. def getmin(self): x = self.Min.pop() self.Min.push(x) return x # Driver codeif __name__ == '__main__': s = SpecialStack() s.push(10) s.push(20) s.push(30) print(s.getmin()) s.push(5) print(s.getmin()) # This code is contributed by rachitkatiyar99 10 5 Complexity Analysis: Time Complexity: For insert operation: O(1) (As insertion β€˜push’ in a stack takes constant time)For delete operation: O(1) (As deletion β€˜pop’ in a stack takes constant time)For β€˜Get Min’ operation: O(1) (As we have used an auxiliary stack which has it’s top as the minimum element) For insert operation: O(1) (As insertion β€˜push’ in a stack takes constant time)For delete operation: O(1) (As deletion β€˜pop’ in a stack takes constant time)For β€˜Get Min’ operation: O(1) (As we have used an auxiliary stack which has it’s top as the minimum element) For insert operation: O(1) (As insertion β€˜push’ in a stack takes constant time) For delete operation: O(1) (As deletion β€˜pop’ in a stack takes constant time) For β€˜Get Min’ operation: O(1) (As we have used an auxiliary stack which has it’s top as the minimum element) Auxiliary Space: O(n). Use of auxiliary stack for storing values. Space Optimized Version The above approach can be optimized. We can limit the number of elements in the auxiliary stack. We can push only when the incoming element of the main stack is smaller than or equal to the top of the auxiliary stack. Similarly during pop, if the pop-off element equal to the top of the auxiliary stack, remove the top element of the auxiliary stack. Following is the modified implementation of push() and pop(). C++ Java Python3 C# Javascript /* SpecialStack's member method to insert an element to it. This method makes sure that the min stack is also updated with appropriate minimum values */void SpecialStack::push(int x){ if (isEmpty() == true) { Stack::push(x); min.push(x); } else { Stack::push(x); int y = min.pop(); min.push(y); /* push only when the incoming element of main stack is smaller than or equal to top of auxiliary stack */ if (x <= y) min.push(x); }} /* SpecialStack's member method to remove an element from it. This method removes top element from min stack also. */int SpecialStack::pop(){ int x = Stack::pop(); int y = min.pop(); /* Push the popped element y back only if it is not equal to x */ if (y != x) min.push(y); return x;} /* SpecialStack's member method toinsert an element to it. This methodmakes sure that the min stack isalso updated with appropriate minimumvalues */ void push(int x){ if (isEmpty() == true) { super.push(x); min.push(x); } else { super.push(x); int y = min.pop(); min.push(y); /* push only when the incoming element of main stack is smaller than or equal to top of auxiliary stack */ if (x <= y) min.push(x); }} /* SpecialStack's member method to remove an element from it. This method removes top element from min stack also. */public Integer pop(){ int x = super.pop(); int y = min.pop(); /* Push the popped element y back only if it is not equal to x */ if (y != x) min.push(y); return x;} // This code is contributed by Sumit Ghosh ''' SpecialStack's member method toinsert an element to it. This methodmakes sure that the min stack isalso updated with appropriate minimumvalues ''' def push(x): if (isEmpty() == True): super.append(x); min.append(x); else: super.append(x); y = min.pop(); min.append(y); ''' push only when the incoming element of main stack is smaller than or equal to top of auxiliary stack ''' if (x <= y): min.append(x); ''' SpecialStack's member method to remove an element from it. This method removes top element from min stack also. '''def pop(): x = super.pop(); y = min.pop(); ''' Push the popped element y back only if it is not equal to x ''' if (y != x): min.append(y); return x; # This code contributed by umadevi9616 /* SpecialStack's member method toinsert an element to it. This methodmakes sure that the min stack isalso updated with appropriate minimumvalues */ void push(int x){ if (min.Count==0) { super.Push(x); min.Push(x); } else { super.Push(x); int y = min.Pop(); min.Push(y); /* push only when the incoming element of main stack is smaller than or equal to top of auxiliary stack */ if (x <= y) min.Push(x); }} /* SpecialStack's member method to remove an element from it. This method removes top element from min stack also. */public int pop(){ int x = super.Pop(); int y = min.Pop(); /* Push the popped element y back only if it is not equal to x */ if (y != x) min.Push(y); return x;} // This code is contributed by umadevi9616 <script>/* SpecialStack's member method toinsert an element to it. This methodmakes sure that the min stack isalso updated with appropriate minimumvalues */ function push(x){ if (isEmpty() == true) { super.push(x); min.push(x); } else { super.push(x); var y = min.pop(); min.push(y); /* push only when the incoming element of main stack is smaller than or equal to top of auxiliary stack */ if (x <= y) min.push(x); }} /* SpecialStack's member method to remove an element from it. This method removes top element from min stack also. */ function pop(){ var x = super.pop(); var y = min.pop(); /* Push the popped element y back only if it is not equal to x */ if (y != x) min.push(y); return x;} // This code is contributed by umadevi9616</script> Complexity Analysis: Time Complexity: For Insert operation: O(1) (As insertion β€˜push’ in a stack takes constant time)For Delete operation: O(1) (As deletion β€˜pop’ in a stack takes constant time)For β€˜Get Min’ operation: O(1) (As we have used an auxiliary which has it’s top as the minimum element) For Insert operation: O(1) (As insertion β€˜push’ in a stack takes constant time)For Delete operation: O(1) (As deletion β€˜pop’ in a stack takes constant time)For β€˜Get Min’ operation: O(1) (As we have used an auxiliary which has it’s top as the minimum element) For Insert operation: O(1) (As insertion β€˜push’ in a stack takes constant time) For Delete operation: O(1) (As deletion β€˜pop’ in a stack takes constant time) For β€˜Get Min’ operation: O(1) (As we have used an auxiliary which has it’s top as the minimum element) Auxiliary Space: O(n). The complexity in the worst case is the same as above but in other cases, it will take slightly less space than the above approach as repetition is neglected. Further optimized O(1) time complexity and O(1) space complexity solution :The above approach can be optimized further and the solution can be made to work in O(1) time complexity and O(1) space complexity. The idea is to store min element found till current insertion) along with all the elements as a reminder of a DUMMY_VALUE, and the actual element as a multiple of the DUMMY_VALUE.For example, while pushing an element β€˜e’ into the stack, store it as (e * DUMMY_VALUE + minFoundSoFar), this way we know what was the minimum value present in the stack at the time β€˜e’ was being inserted. To pop the actual value just return e/DUMMY_VALUE and set the new minimum as (minFoundSoFar % DUMMY_VALUE). Note: Following method will fail if we try to insert DUMMY_VALUE in the stack, so we have to make our selection of DUMMY_VALUE carefully.Let’s say the following elements are being inserted in the stack – 3 2 6 1 8 5 d is dummy value. s is wrapper stack top is top element of the stack min is the minimum value at that instant when the elements were inserted/removed The following steps shows the current state of the above variables at any instant – s.push(3);min=3 //updated min as stack here is empty s = {3*d + 3}top = (3*d + 3)/d = 3 s.push(2);min = 2 //updated min as min > current elements = {3*d + 3-> 2*d + 2}top = (2*d + 2)/d = 2 s.push(6);min = 2s = {3*d + 3-> 2*d + 2-> 6*d + 2}top = (6*d + 2)/d = 6 s.push(1);min = 1 //updated min as min > current elements = {3*d + 3-> 2*d + 2-> 6*d + 2 -> 1*d + 1}top = (1*d + 1)/d = 1 s.push(8);min = 1s = {3*d + 3-> 2*d + 2-> 6*d + 2 -> 1*d + 1 -> 8*d + 1}top = (8*d + 1)/d = 8 s.push(5);min = 1s = {3*d + 3-> 2*d + 2-> 6*d + 2 -> 1*d + 1 -> 8*d + 1 -> 5*d + 1}top = (5*d + 1)/d = 5 s.pop();s = {3*d + 3 -> 2*d + 2 -> 6*d + 2 -> 1*d + 1 -> 8*d + 1 -> 5*d + 1}top = (5*d + 1)/d = 5min = (8*d + 1)%d = 1 // min is always remainder of the second top element in stack. s.pop();s = {3*d + 3 -> 2*d + 2-> 6*d + 2 -> 1*d + 1 -> 8*d + 1}top = (8*d + 1)/d = 8min = (1*d + 1)%d = 1 s.pop()s = {3*d + 3 -> 2*d + 2-> 6*d + 2 -> 1*d + 1} top = (1*d + 1)/d = 1min = (6*d + 2)%d = 2 s.pop()s = {3*d + 3-> 2*d + 2-> 6*d + 2}top = (6*d + 2)/d = 6min = (2*d + 2)%d = 2 s.pop()s = {3*d + 3-> 2*d + 2}top = (2*d + 2)/d = 2min = (3*d + 3)%d = 3 s.pop()s = {3*d + 3}top = (3*d + 3)/d = 3min = -1 // since stack is now empty s.push(3);min=3 //updated min as stack here is empty s = {3*d + 3}top = (3*d + 3)/d = 3 s.push(2);min = 2 //updated min as min > current elements = {3*d + 3-> 2*d + 2}top = (2*d + 2)/d = 2 s.push(6);min = 2s = {3*d + 3-> 2*d + 2-> 6*d + 2}top = (6*d + 2)/d = 6 s.push(1);min = 1 //updated min as min > current elements = {3*d + 3-> 2*d + 2-> 6*d + 2 -> 1*d + 1}top = (1*d + 1)/d = 1 s.push(8);min = 1s = {3*d + 3-> 2*d + 2-> 6*d + 2 -> 1*d + 1 -> 8*d + 1}top = (8*d + 1)/d = 8 s.push(5);min = 1s = {3*d + 3-> 2*d + 2-> 6*d + 2 -> 1*d + 1 -> 8*d + 1 -> 5*d + 1}top = (5*d + 1)/d = 5 s.pop();s = {3*d + 3 -> 2*d + 2 -> 6*d + 2 -> 1*d + 1 -> 8*d + 1 -> 5*d + 1}top = (5*d + 1)/d = 5min = (8*d + 1)%d = 1 // min is always remainder of the second top element in stack. s.pop();s = {3*d + 3 -> 2*d + 2-> 6*d + 2 -> 1*d + 1 -> 8*d + 1}top = (8*d + 1)/d = 8min = (1*d + 1)%d = 1 s.pop()s = {3*d + 3 -> 2*d + 2-> 6*d + 2 -> 1*d + 1} top = (1*d + 1)/d = 1min = (6*d + 2)%d = 2 s.pop()s = {3*d + 3-> 2*d + 2-> 6*d + 2}top = (6*d + 2)/d = 6min = (2*d + 2)%d = 2 s.pop()s = {3*d + 3-> 2*d + 2}top = (2*d + 2)/d = 2min = (3*d + 3)%d = 3 s.pop()s = {3*d + 3}top = (3*d + 3)/d = 3min = -1 // since stack is now empty C++ Java C# #include <iostream>#include <stack>#include <vector>using namespace std; /* A special stack having peek() pop() and * push() along with additional getMin() that * returns minimum value in a stack without * using extra space and all operations in O(1) * time.. ???? */class SpecialStack{ // Sentinel value for min int min = -1; // DEMO_VALUE static const int demoVal = 9999; stack<int> st; public: void getMin() { cout << "min is: " << min << endl; } void push(int val) { // If stack is empty OR current element // is less than min, update min. if (st.empty() || val < min) { min = val; } // Encode the current value with // demoVal, combine with min and // insert into stack st.push(val * demoVal + min); cout << "pushed: " << val << endl; } int pop() { // if stack is empty return -1; if ( st.empty() ) { cout << "stack underflow" << endl ; return -1; } int val = st.top(); st.pop(); // If stack is empty, there would // be no min value present, so // make min as -1 if (!st.empty()) min = st.top() % demoVal; else min = -1; cout << "popped: " << val / demoVal << endl; // Decode actual value from // encoded value return val / demoVal; } int peek() { // Decode actual value // from encoded value return st.top() / demoVal; }}; // Driver Codeint main(){ SpecialStack s; vector<int> arr = { 3, 2, 6, 1, 8, 5, 5, 5, 5 }; for(int i = 0; i < arr.size(); i++) { s.push(arr[i]); s.getMin(); } cout << endl; for(int i = 0; i < arr.size(); i++) { s.pop(); s.getMin(); } return 0;} // This code is contributed by scisaif import java.util.Stack; /* A special stack having peek() pop() and push() along with * additional getMin() that returns minimum value in a stack * without using extra space and all operations in O(1) * time.. * */public class SpecialStack { int min = -1; // sentinel value for min static int demoVal = 9999; // DEMO_VALUE Stack<Integer> st = new Stack<Integer>(); void getMin() { System.out.println("min is: " + min); } void push(int val) { // if stack is empty OR current element is less than // min, update min.. if (st.isEmpty() || val < min) { min = val; } st.push(val * demoVal + min); // encode the current value with // demoVal, combine with min and // insert into stack System.out.println("pushed: " + val); } int pop() { // if stack is empty return -1; if (st.isEmpty() ) { System.out.println("stack underflow"); return -1; } int val = st.pop(); if (!st.isEmpty()) // if stack is empty, there would // be no min value present, so // make min as -1 min = st.peek() % demoVal; else min = -1; System.out.println("popped: " + val / demoVal); return val / demoVal; // decode actual value from // encoded value } int peek() { return st.peek() / demoVal; // decode actual value // from encoded value } // Driver Code public static void main(String[] args) { SpecialStack s = new SpecialStack(); int[] arr = { 3, 2, 6, 1, 8, 5, 5, 5, 5 }; for (int i = 0; i < arr.length; i++) { s.push(arr[i]); s.getMin(); } System.out.println(); for (int i = 0; i < arr.length; i++) { s.pop(); s.getMin(); } }} using System;using System.Collections.Generic; /* A special stack having peek() pop() and push() along with * additional getMin() that returns minimum value in a stack * without using extra space and all operations in O(1) * time.. * */public class SpecialStack { int min = -1; // sentinel value for min static int demoVal = 9999; // DEMO_VALUE Stack<int> st = new Stack<int>(); void getMin() { Console.WriteLine("min is: " + min); } void push(int val) { // if stack is empty OR current element is less than // min, update min.. if (st.Count==0 || val < min) { min = val; } st.Push(val * demoVal + min); // encode the current value with // demoVal, combine with min and // insert into stack Console.WriteLine("pushed: " + val); } int pop() { // if stack is empty return -1; if (st.Count==0 ) { Console.WriteLine("stack underflow"); return -1; } int val = st.Pop(); if (st.Count!=0) // if stack is empty, there would // be no min value present, so // make min as -1 min = st.Peek() % demoVal; else min = -1; Console.WriteLine("popped: " + val / demoVal); return val / demoVal; // decode actual value from // encoded value } int peek() { return st.Peek() / demoVal; // decode actual value // from encoded value } // Driver Code public static void Main(String[] args) { SpecialStack s = new SpecialStack(); int[] arr = { 3, 2, 6, 1, 8, 5, 5, 5, 5 }; for (int i = 0; i < arr.Length; i++) { s.push(arr[i]); s.getMin(); } Console.WriteLine(); for (int i = 0; i < arr.Length; i++) { s.pop(); s.getMin(); } }} // This code is contributed by gauravrajput1 pushed: 3 min is: 3 pushed: 2 min is: 2 pushed: 6 min is: 2 pushed: 1 min is: 1 pushed: 8 min is: 1 pushed: 5 min is: 1 pushed: 5 min is: 1 pushed: 5 min is: 1 pushed: 5 min is: 1 popped: 5 min is: 1 popped: 5 min is: 1 popped: 5 min is: 1 popped: 5 min is: 1 popped: 8 min is: 1 popped: 1 min is: 2 popped: 6 min is: 2 popped: 2 min is: 3 popped: 3 min is: -1 Complexity Analysis: For push() operation: O(1) (As insertion β€˜push’ in a stack takes constant time)For pop() operation: O(1) (As pop operation in a stack takes constant time) For β€˜Get Min’ operation: O(1) (As we have maintained min variable throughout the code) Auxiliary Space: O(1). No extra space is used. https://youtu.be/1Ld7gbW1oHcDesign a stack that supports getMin() in O(1) time and O(1) extra spaceThanks to @Venki, @swarup, and @Jing Huang for their inputs.Please write comments if you find the above code incorrect, or find other ways to solve the same problem. bidibaaz123 zeekgeek sinhaiscena scisaif vasutiwari409 architgwl2000 GauravRajput1 umadevi9616 germanshephered48 Adobe Amazon Linkedin Paytm STL VMWare Stack Paytm VMWare Amazon Adobe Linkedin Stack STL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Check for Balanced Brackets in an expression (well-formedness) using Stack Stack | Set 2 (Infix to Postfix) Program for Tower of Hanoi Stack | Set 4 (Evaluation of Postfix Expression) Implement a stack using singly linked list Next Greater Element Merge Overlapping Intervals Difference between Stack and Queue Data Structures Iterative Depth First Traversal of Graph Largest Rectangular Area in a Histogram | Set 2
[ { "code": null, "e": 39005, "s": 38977, "text": "\n21 Feb, 2022" }, { "code": null, "e": 39410, "s": 39005, "text": "Question: Design a Data Structure SpecialStack that supports all the stack operations like push(), pop(), isEmpty(), isFull() and an additional operation getMin() which should return minimum element from the SpecialStack. All these operations of SpecialStack must be O(1). To implement SpecialStack, you should only use standard Stack data structure and no other data structure like arrays, list, . etc. " }, { "code": null, "e": 39420, "s": 39410, "text": "Example: " }, { "code": null, "e": 39742, "s": 39420, "text": "Consider the following SpecialStack\n16 --> TOP\n15\n29\n19\n18\n\nWhen getMin() is called it should \nreturn 15, which is the minimum \nelement in the current stack. \n\nIf we do pop two times on stack, \nthe stack becomes\n29 --> TOP\n19\n18\n\nWhen getMin() is called, it should \nreturn 18 which is the minimum in \nthe current stack." }, { "code": null, "e": 40032, "s": 39742, "text": "Solution: Use two stacks: one to store actual stack elements and the other as an auxiliary stack to store minimum values. The idea is to do push() and pop() operations in such a way that the top of the auxiliary stack is always the minimum. Let us see how push() and pop() operations work." }, { "code": null, "e": 40782, "s": 40032, "text": "Push(int x) // inserts an element x to Special Stack 1) push x to the first stack (the stack with actual elements) 2) compare x with the top element of the second stack (the auxiliary stack). Let the top element be y. .....a) If x is smaller than y then push x to the auxiliary stack. .....b) If x is greater than y then push y to the auxiliary stack.int Pop() // removes an element from Special Stack and return the removed element 1) pop the top element from the auxiliary stack. 2) pop the top element from the actual stack and return it.Step 1 is necessary to make sure that the auxiliary stack is also updated for future operations.int getMin() // returns the minimum element from Special Stack 1) Return the top element of the auxiliary stack." }, { "code": null, "e": 40969, "s": 40782, "text": "We can see that all the above operations are O(1). Let us see an example. Let us assume that both stacks are initially empty and 18, 19, 29, 15, and 16 are inserted to the SpecialStack. " }, { "code": null, "e": 41598, "s": 40969, "text": "When we insert 18, both stacks change to following.\nActual Stack\n18 <--- top \nAuxiliary Stack\n18 <---- top\n\nWhen 19 is inserted, both stacks change to following.\nActual Stack\n19 <--- top \n18\nAuxiliary Stack\n18 <---- top\n18\n\nWhen 29 is inserted, both stacks change to following.\nActual Stack\n29 <--- top \n19\n18\nAuxiliary Stack\n18 <---- top\n18\n18\n\nWhen 15 is inserted, both stacks change to following.\nActual Stack\n15 <--- top \n29\n19 \n18\nAuxiliary Stack\n15 <---- top\n18\n18\n18\n\nWhen 16 is inserted, both stacks change to following.\nActual Stack\n16 <--- top \n15\n29\n19 \n18\nAuxiliary Stack\n15 <---- top\n15\n18\n18\n18" }, { "code": null, "e": 41784, "s": 41598, "text": "The following is the implementation for SpecialStack class. In the below implementation, SpecialStack inherits from Stack and has one Stack object min which works as an auxiliary stack." }, { "code": null, "e": 41788, "s": 41784, "text": "C++" }, { "code": null, "e": 41793, "s": 41788, "text": "Java" }, { "code": null, "e": 41801, "s": 41793, "text": "Python3" }, { "code": "#include <iostream>#include <stdlib.h> using namespace std; /* A simple stack class withbasic stack functionalities */class Stack {private: static const int max = 100; int arr[max]; int top; public: Stack() { top = -1; } bool isEmpty(); bool isFull(); int pop(); void push(int x);}; /* Stack's member method to checkif the stack is empty */bool Stack::isEmpty(){ if (top == -1) return true; return false;} /* Stack's member method to checkif the stack is full */bool Stack::isFull(){ if (top == max - 1) return true; return false;} /* Stack's member method to removean element from it */int Stack::pop(){ if (isEmpty()) { cout << \"Stack Underflow\"; abort(); } int x = arr[top]; top--; return x;} /* Stack's member method to insertan element to it */void Stack::push(int x){ if (isFull()) { cout << \"Stack Overflow\"; abort(); } top++; arr[top] = x;} /* A class that supports all the stackoperations and one additional operation getMin() that returns theminimum element from stack at any time. This class inherits fromthe stack class and uses an auxiliary stack that holds minimumelements */class SpecialStack : public Stack { Stack min; public: int pop(); void push(int x); int getMin();}; /* SpecialStack's member method to insert an element to it. This method makes sure that the min stack is alsoupdated with appropriate minimum values */void SpecialStack::push(int x){ if (isEmpty() == true) { Stack::push(x); min.push(x); } else { Stack::push(x); int y = min.pop(); min.push(y); if (x < y) min.push(x); else min.push(y); }} /* SpecialStack's member method toremove an element from it. This method removes top element from min stack also. */int SpecialStack::pop(){ int x = Stack::pop(); min.pop(); return x;} /* SpecialStack's member method to get minimum element from it. */int SpecialStack::getMin(){ int x = min.pop(); min.push(x); return x;} /* Driver program to test SpecialStack methods */int main(){ SpecialStack s; s.push(10); s.push(20); s.push(30); cout << s.getMin() << endl; s.push(5); cout << s.getMin(); return 0;}", "e": 44086, "s": 41801, "text": null }, { "code": "// Java implementation of SpecialStack// Note : here we use Stack class for// Stack implementation import java.util.Stack; /* A class that supports all thestack operations and one additionaloperation getMin() that returnsthe minimum element from stack atany time. This class inherits fromthe stack class and uses anauxiliary stack that holds minimum elements */ class SpecialStack extends Stack<Integer> { Stack<Integer> min = new Stack<>(); /* SpecialStack's member method toinsert an element to it. This method makes sure that the min stack isalso updated with appropriate minimum values */ void push(int x) { if (isEmpty() == true) { super.push(x); min.push(x); } else { super.push(x); int y = min.pop(); min.push(y); if (x < y) min.push(x); else min.push(y); } } /* SpecialStack's member method toinsert an element to it. This method makes sure that the min stack isalso updated with appropriate minimum values */ public Integer pop() { int x = super.pop(); min.pop(); return x; } /* SpecialStack's member method to getminimum element from it. */ int getMin() { int x = min.pop(); min.push(x); return x; } /* Driver program to test SpecialStackmethods */ public static void main(String[] args) { SpecialStack s = new SpecialStack(); s.push(10); s.push(20); s.push(30); System.out.println(s.getMin()); s.push(5); System.out.println(s.getMin()); }}// This code is contributed by Sumit Ghosh", "e": 45772, "s": 44086, "text": null }, { "code": "# Python3 program for the# above approach# A simple stack class with # basic stack functionalitiesclass stack: def __init__(self): self.array = [] self.top = -1 self.max = 100 # Stack's member method to check # if the stack is empty def isEmpty(self): if self.top == -1: return True else: return False # Stack's member method to check # if the stack is full def isFull(self): if self.top == self.max - 1: return True else: return False # Stack's member method to # insert an element to it def push(self, data): if self.isFull(): print('Stack OverFlow') return else: self.top += 1 self.array.append(data) # Stack's member method to # remove an element from it def pop(self): if self.isEmpty(): print('Stack UnderFlow') return else: self.top -= 1 return self.array.pop() # A class that supports all the stack # operations and one additional# operation getMin() that returns the# minimum element from stack at# any time. This class inherits from# the stack class and uses an# auxiliary stack that holds# minimum elements class SpecialStack(stack): def __init__(self): super().__init__() self.Min = stack() # SpecialStack's member method to # insert an element to it. This method # makes sure that the min stack is also # updated with appropriate minimum # values def push(self, x): if self.isEmpty(): super().push(x) self.Min.push(x) else: super().push(x) y = self.Min.pop() self.Min.push(y) if x <= y: self.Min.push(x) else: self.Min.push(y) # SpecialStack's member method to # remove an element from it. This # method removes top element from # min stack also. def pop(self): x = super().pop() self.Min.pop() return x # SpecialStack's member method # to get minimum element from it. def getmin(self): x = self.Min.pop() self.Min.push(x) return x # Driver codeif __name__ == '__main__': s = SpecialStack() s.push(10) s.push(20) s.push(30) print(s.getmin()) s.push(5) print(s.getmin()) # This code is contributed by rachitkatiyar99", "e": 47950, "s": 45772, "text": null }, { "code": null, "e": 47955, "s": 47950, "text": "10\n5" }, { "code": null, "e": 47977, "s": 47955, "text": "Complexity Analysis: " }, { "code": null, "e": 48259, "s": 47977, "text": "Time Complexity: For insert operation: O(1) (As insertion β€˜push’ in a stack takes constant time)For delete operation: O(1) (As deletion β€˜pop’ in a stack takes constant time)For β€˜Get Min’ operation: O(1) (As we have used an auxiliary stack which has it’s top as the minimum element)" }, { "code": null, "e": 48524, "s": 48259, "text": "For insert operation: O(1) (As insertion β€˜push’ in a stack takes constant time)For delete operation: O(1) (As deletion β€˜pop’ in a stack takes constant time)For β€˜Get Min’ operation: O(1) (As we have used an auxiliary stack which has it’s top as the minimum element)" }, { "code": null, "e": 48604, "s": 48524, "text": "For insert operation: O(1) (As insertion β€˜push’ in a stack takes constant time)" }, { "code": null, "e": 48682, "s": 48604, "text": "For delete operation: O(1) (As deletion β€˜pop’ in a stack takes constant time)" }, { "code": null, "e": 48791, "s": 48682, "text": "For β€˜Get Min’ operation: O(1) (As we have used an auxiliary stack which has it’s top as the minimum element)" }, { "code": null, "e": 48857, "s": 48791, "text": "Auxiliary Space: O(n). Use of auxiliary stack for storing values." }, { "code": null, "e": 49295, "s": 48857, "text": "Space Optimized Version The above approach can be optimized. We can limit the number of elements in the auxiliary stack. We can push only when the incoming element of the main stack is smaller than or equal to the top of the auxiliary stack. Similarly during pop, if the pop-off element equal to the top of the auxiliary stack, remove the top element of the auxiliary stack. Following is the modified implementation of push() and pop(). " }, { "code": null, "e": 49299, "s": 49295, "text": "C++" }, { "code": null, "e": 49304, "s": 49299, "text": "Java" }, { "code": null, "e": 49312, "s": 49304, "text": "Python3" }, { "code": null, "e": 49315, "s": 49312, "text": "C#" }, { "code": null, "e": 49326, "s": 49315, "text": "Javascript" }, { "code": "/* SpecialStack's member method to insert an element to it. This method makes sure that the min stack is also updated with appropriate minimum values */void SpecialStack::push(int x){ if (isEmpty() == true) { Stack::push(x); min.push(x); } else { Stack::push(x); int y = min.pop(); min.push(y); /* push only when the incoming element of main stack is smaller than or equal to top of auxiliary stack */ if (x <= y) min.push(x); }} /* SpecialStack's member method to remove an element from it. This method removes top element from min stack also. */int SpecialStack::pop(){ int x = Stack::pop(); int y = min.pop(); /* Push the popped element y back only if it is not equal to x */ if (y != x) min.push(y); return x;}", "e": 50173, "s": 49326, "text": null }, { "code": "/* SpecialStack's member method toinsert an element to it. This methodmakes sure that the min stack isalso updated with appropriate minimumvalues */ void push(int x){ if (isEmpty() == true) { super.push(x); min.push(x); } else { super.push(x); int y = min.pop(); min.push(y); /* push only when the incoming element of main stack is smaller than or equal to top of auxiliary stack */ if (x <= y) min.push(x); }} /* SpecialStack's member method to remove an element from it. This method removes top element from min stack also. */public Integer pop(){ int x = super.pop(); int y = min.pop(); /* Push the popped element y back only if it is not equal to x */ if (y != x) min.push(y); return x;} // This code is contributed by Sumit Ghosh", "e": 51031, "s": 50173, "text": null }, { "code": "''' SpecialStack's member method toinsert an element to it. This methodmakes sure that the min stack isalso updated with appropriate minimumvalues ''' def push(x): if (isEmpty() == True): super.append(x); min.append(x); else: super.append(x); y = min.pop(); min.append(y); ''' push only when the incoming element of main stack is smaller than or equal to top of auxiliary stack ''' if (x <= y): min.append(x); ''' SpecialStack's member method to remove an element from it. This method removes top element from min stack also. '''def pop(): x = super.pop(); y = min.pop(); ''' Push the popped element y back only if it is not equal to x ''' if (y != x): min.append(y); return x; # This code contributed by umadevi9616", "e": 51877, "s": 51031, "text": null }, { "code": "/* SpecialStack's member method toinsert an element to it. This methodmakes sure that the min stack isalso updated with appropriate minimumvalues */ void push(int x){ if (min.Count==0) { super.Push(x); min.Push(x); } else { super.Push(x); int y = min.Pop(); min.Push(y); /* push only when the incoming element of main stack is smaller than or equal to top of auxiliary stack */ if (x <= y) min.Push(x); }} /* SpecialStack's member method to remove an element from it. This method removes top element from min stack also. */public int pop(){ int x = super.Pop(); int y = min.Pop(); /* Push the popped element y back only if it is not equal to x */ if (y != x) min.Push(y); return x;} // This code is contributed by umadevi9616", "e": 52726, "s": 51877, "text": null }, { "code": "<script>/* SpecialStack's member method toinsert an element to it. This methodmakes sure that the min stack isalso updated with appropriate minimumvalues */ function push(x){ if (isEmpty() == true) { super.push(x); min.push(x); } else { super.push(x); var y = min.pop(); min.push(y); /* push only when the incoming element of main stack is smaller than or equal to top of auxiliary stack */ if (x <= y) min.push(x); }} /* SpecialStack's member method to remove an element from it. This method removes top element from min stack also. */ function pop(){ var x = super.pop(); var y = min.pop(); /* Push the popped element y back only if it is not equal to x */ if (y != x) min.push(y); return x;} // This code is contributed by umadevi9616</script>", "e": 53596, "s": 52726, "text": null }, { "code": null, "e": 53619, "s": 53596, "text": "Complexity Analysis: " }, { "code": null, "e": 53895, "s": 53619, "text": "Time Complexity: For Insert operation: O(1) (As insertion β€˜push’ in a stack takes constant time)For Delete operation: O(1) (As deletion β€˜pop’ in a stack takes constant time)For β€˜Get Min’ operation: O(1) (As we have used an auxiliary which has it’s top as the minimum element)" }, { "code": null, "e": 54154, "s": 53895, "text": "For Insert operation: O(1) (As insertion β€˜push’ in a stack takes constant time)For Delete operation: O(1) (As deletion β€˜pop’ in a stack takes constant time)For β€˜Get Min’ operation: O(1) (As we have used an auxiliary which has it’s top as the minimum element)" }, { "code": null, "e": 54234, "s": 54154, "text": "For Insert operation: O(1) (As insertion β€˜push’ in a stack takes constant time)" }, { "code": null, "e": 54312, "s": 54234, "text": "For Delete operation: O(1) (As deletion β€˜pop’ in a stack takes constant time)" }, { "code": null, "e": 54415, "s": 54312, "text": "For β€˜Get Min’ operation: O(1) (As we have used an auxiliary which has it’s top as the minimum element)" }, { "code": null, "e": 54597, "s": 54415, "text": "Auxiliary Space: O(n). The complexity in the worst case is the same as above but in other cases, it will take slightly less space than the above approach as repetition is neglected." }, { "code": null, "e": 55189, "s": 54597, "text": "Further optimized O(1) time complexity and O(1) space complexity solution :The above approach can be optimized further and the solution can be made to work in O(1) time complexity and O(1) space complexity. The idea is to store min element found till current insertion) along with all the elements as a reminder of a DUMMY_VALUE, and the actual element as a multiple of the DUMMY_VALUE.For example, while pushing an element β€˜e’ into the stack, store it as (e * DUMMY_VALUE + minFoundSoFar), this way we know what was the minimum value present in the stack at the time β€˜e’ was being inserted." }, { "code": null, "e": 55297, "s": 55189, "text": "To pop the actual value just return e/DUMMY_VALUE and set the new minimum as (minFoundSoFar % DUMMY_VALUE)." }, { "code": null, "e": 55513, "s": 55297, "text": "Note: Following method will fail if we try to insert DUMMY_VALUE in the stack, so we have to make our selection of DUMMY_VALUE carefully.Let’s say the following elements are being inserted in the stack – 3 2 6 1 8 5" }, { "code": null, "e": 55531, "s": 55513, "text": "d is dummy value." }, { "code": null, "e": 55550, "s": 55531, "text": "s is wrapper stack" }, { "code": null, "e": 55582, "s": 55550, "text": "top is top element of the stack" }, { "code": null, "e": 55663, "s": 55582, "text": "min is the minimum value at that instant when the elements were inserted/removed" }, { "code": null, "e": 55748, "s": 55663, "text": "The following steps shows the current state of the above variables at any instant – " }, { "code": null, "e": 56951, "s": 55748, "text": "s.push(3);min=3 //updated min as stack here is empty s = {3*d + 3}top = (3*d + 3)/d = 3 s.push(2);min = 2 //updated min as min > current elements = {3*d + 3-> 2*d + 2}top = (2*d + 2)/d = 2 s.push(6);min = 2s = {3*d + 3-> 2*d + 2-> 6*d + 2}top = (6*d + 2)/d = 6 s.push(1);min = 1 //updated min as min > current elements = {3*d + 3-> 2*d + 2-> 6*d + 2 -> 1*d + 1}top = (1*d + 1)/d = 1 s.push(8);min = 1s = {3*d + 3-> 2*d + 2-> 6*d + 2 -> 1*d + 1 -> 8*d + 1}top = (8*d + 1)/d = 8 s.push(5);min = 1s = {3*d + 3-> 2*d + 2-> 6*d + 2 -> 1*d + 1 -> 8*d + 1 -> 5*d + 1}top = (5*d + 1)/d = 5 s.pop();s = {3*d + 3 -> 2*d + 2 -> 6*d + 2 -> 1*d + 1 -> 8*d + 1 -> 5*d + 1}top = (5*d + 1)/d = 5min = (8*d + 1)%d = 1 // min is always remainder of the second top element in stack. s.pop();s = {3*d + 3 -> 2*d + 2-> 6*d + 2 -> 1*d + 1 -> 8*d + 1}top = (8*d + 1)/d = 8min = (1*d + 1)%d = 1 s.pop()s = {3*d + 3 -> 2*d + 2-> 6*d + 2 -> 1*d + 1} top = (1*d + 1)/d = 1min = (6*d + 2)%d = 2 s.pop()s = {3*d + 3-> 2*d + 2-> 6*d + 2}top = (6*d + 2)/d = 6min = (2*d + 2)%d = 2 s.pop()s = {3*d + 3-> 2*d + 2}top = (2*d + 2)/d = 2min = (3*d + 3)%d = 3 s.pop()s = {3*d + 3}top = (3*d + 3)/d = 3min = -1 // since stack is now empty" }, { "code": null, "e": 57041, "s": 56951, "text": "s.push(3);min=3 //updated min as stack here is empty s = {3*d + 3}top = (3*d + 3)/d = 3 " }, { "code": null, "e": 57143, "s": 57041, "text": "s.push(2);min = 2 //updated min as min > current elements = {3*d + 3-> 2*d + 2}top = (2*d + 2)/d = 2 " }, { "code": null, "e": 57216, "s": 57143, "text": "s.push(6);min = 2s = {3*d + 3-> 2*d + 2-> 6*d + 2}top = (6*d + 2)/d = 6 " }, { "code": null, "e": 57339, "s": 57216, "text": "s.push(1);min = 1 //updated min as min > current elements = {3*d + 3-> 2*d + 2-> 6*d + 2 -> 1*d + 1}top = (1*d + 1)/d = 1 " }, { "code": null, "e": 57434, "s": 57339, "text": "s.push(8);min = 1s = {3*d + 3-> 2*d + 2-> 6*d + 2 -> 1*d + 1 -> 8*d + 1}top = (8*d + 1)/d = 8 " }, { "code": null, "e": 57540, "s": 57434, "text": "s.push(5);min = 1s = {3*d + 3-> 2*d + 2-> 6*d + 2 -> 1*d + 1 -> 8*d + 1 -> 5*d + 1}top = (5*d + 1)/d = 5 " }, { "code": null, "e": 57723, "s": 57540, "text": "s.pop();s = {3*d + 3 -> 2*d + 2 -> 6*d + 2 -> 1*d + 1 -> 8*d + 1 -> 5*d + 1}top = (5*d + 1)/d = 5min = (8*d + 1)%d = 1 // min is always remainder of the second top element in stack. " }, { "code": null, "e": 57831, "s": 57723, "text": "s.pop();s = {3*d + 3 -> 2*d + 2-> 6*d + 2 -> 1*d + 1 -> 8*d + 1}top = (8*d + 1)/d = 8min = (1*d + 1)%d = 1 " }, { "code": null, "e": 57928, "s": 57831, "text": "s.pop()s = {3*d + 3 -> 2*d + 2-> 6*d + 2 -> 1*d + 1} top = (1*d + 1)/d = 1min = (6*d + 2)%d = 2 " }, { "code": null, "e": 58012, "s": 57928, "text": "s.pop()s = {3*d + 3-> 2*d + 2-> 6*d + 2}top = (6*d + 2)/d = 6min = (2*d + 2)%d = 2 " }, { "code": null, "e": 58086, "s": 58012, "text": "s.pop()s = {3*d + 3-> 2*d + 2}top = (2*d + 2)/d = 2min = (3*d + 3)%d = 3 " }, { "code": null, "e": 58165, "s": 58086, "text": "s.pop()s = {3*d + 3}top = (3*d + 3)/d = 3min = -1 // since stack is now empty" }, { "code": null, "e": 58169, "s": 58165, "text": "C++" }, { "code": null, "e": 58174, "s": 58169, "text": "Java" }, { "code": null, "e": 58177, "s": 58174, "text": "C#" }, { "code": "#include <iostream>#include <stack>#include <vector>using namespace std; /* A special stack having peek() pop() and * push() along with additional getMin() that * returns minimum value in a stack without * using extra space and all operations in O(1) * time.. ???? */class SpecialStack{ // Sentinel value for min int min = -1; // DEMO_VALUE static const int demoVal = 9999; stack<int> st; public: void getMin() { cout << \"min is: \" << min << endl; } void push(int val) { // If stack is empty OR current element // is less than min, update min. if (st.empty() || val < min) { min = val; } // Encode the current value with // demoVal, combine with min and // insert into stack st.push(val * demoVal + min); cout << \"pushed: \" << val << endl; } int pop() { // if stack is empty return -1; if ( st.empty() ) { cout << \"stack underflow\" << endl ; return -1; } int val = st.top(); st.pop(); // If stack is empty, there would // be no min value present, so // make min as -1 if (!st.empty()) min = st.top() % demoVal; else min = -1; cout << \"popped: \" << val / demoVal << endl; // Decode actual value from // encoded value return val / demoVal; } int peek() { // Decode actual value // from encoded value return st.top() / demoVal; }}; // Driver Codeint main(){ SpecialStack s; vector<int> arr = { 3, 2, 6, 1, 8, 5, 5, 5, 5 }; for(int i = 0; i < arr.size(); i++) { s.push(arr[i]); s.getMin(); } cout << endl; for(int i = 0; i < arr.size(); i++) { s.pop(); s.getMin(); } return 0;} // This code is contributed by scisaif", "e": 60136, "s": 58177, "text": null }, { "code": "import java.util.Stack; /* A special stack having peek() pop() and push() along with * additional getMin() that returns minimum value in a stack * without using extra space and all operations in O(1) * time.. * */public class SpecialStack { int min = -1; // sentinel value for min static int demoVal = 9999; // DEMO_VALUE Stack<Integer> st = new Stack<Integer>(); void getMin() { System.out.println(\"min is: \" + min); } void push(int val) { // if stack is empty OR current element is less than // min, update min.. if (st.isEmpty() || val < min) { min = val; } st.push(val * demoVal + min); // encode the current value with // demoVal, combine with min and // insert into stack System.out.println(\"pushed: \" + val); } int pop() { // if stack is empty return -1; if (st.isEmpty() ) { System.out.println(\"stack underflow\"); return -1; } int val = st.pop(); if (!st.isEmpty()) // if stack is empty, there would // be no min value present, so // make min as -1 min = st.peek() % demoVal; else min = -1; System.out.println(\"popped: \" + val / demoVal); return val / demoVal; // decode actual value from // encoded value } int peek() { return st.peek() / demoVal; // decode actual value // from encoded value } // Driver Code public static void main(String[] args) { SpecialStack s = new SpecialStack(); int[] arr = { 3, 2, 6, 1, 8, 5, 5, 5, 5 }; for (int i = 0; i < arr.length; i++) { s.push(arr[i]); s.getMin(); } System.out.println(); for (int i = 0; i < arr.length; i++) { s.pop(); s.getMin(); } }}", "e": 62140, "s": 60136, "text": null }, { "code": "using System;using System.Collections.Generic; /* A special stack having peek() pop() and push() along with * additional getMin() that returns minimum value in a stack * without using extra space and all operations in O(1) * time.. * */public class SpecialStack { int min = -1; // sentinel value for min static int demoVal = 9999; // DEMO_VALUE Stack<int> st = new Stack<int>(); void getMin() { Console.WriteLine(\"min is: \" + min); } void push(int val) { // if stack is empty OR current element is less than // min, update min.. if (st.Count==0 || val < min) { min = val; } st.Push(val * demoVal + min); // encode the current value with // demoVal, combine with min and // insert into stack Console.WriteLine(\"pushed: \" + val); } int pop() { // if stack is empty return -1; if (st.Count==0 ) { Console.WriteLine(\"stack underflow\"); return -1; } int val = st.Pop(); if (st.Count!=0) // if stack is empty, there would // be no min value present, so // make min as -1 min = st.Peek() % demoVal; else min = -1; Console.WriteLine(\"popped: \" + val / demoVal); return val / demoVal; // decode actual value from // encoded value } int peek() { return st.Peek() / demoVal; // decode actual value // from encoded value } // Driver Code public static void Main(String[] args) { SpecialStack s = new SpecialStack(); int[] arr = { 3, 2, 6, 1, 8, 5, 5, 5, 5 }; for (int i = 0; i < arr.Length; i++) { s.push(arr[i]); s.getMin(); } Console.WriteLine(); for (int i = 0; i < arr.Length; i++) { s.pop(); s.getMin(); } }} // This code is contributed by gauravrajput1", "e": 64196, "s": 62140, "text": null }, { "code": null, "e": 64558, "s": 64196, "text": "pushed: 3\nmin is: 3\npushed: 2\nmin is: 2\npushed: 6\nmin is: 2\npushed: 1\nmin is: 1\npushed: 8\nmin is: 1\npushed: 5\nmin is: 1\npushed: 5\nmin is: 1\npushed: 5\nmin is: 1\npushed: 5\nmin is: 1\n\npopped: 5\nmin is: 1\npopped: 5\nmin is: 1\npopped: 5\nmin is: 1\npopped: 5\nmin is: 1\npopped: 8\nmin is: 1\npopped: 1\nmin is: 2\npopped: 6\nmin is: 2\npopped: 2\nmin is: 3\npopped: 3\nmin is: -1" }, { "code": null, "e": 64581, "s": 64558, "text": "Complexity Analysis: " }, { "code": null, "e": 64736, "s": 64581, "text": "For push() operation: O(1) (As insertion β€˜push’ in a stack takes constant time)For pop() operation: O(1) (As pop operation in a stack takes constant time)" }, { "code": null, "e": 64823, "s": 64736, "text": "For β€˜Get Min’ operation: O(1) (As we have maintained min variable throughout the code)" }, { "code": null, "e": 64870, "s": 64823, "text": "Auxiliary Space: O(1). No extra space is used." }, { "code": null, "e": 65135, "s": 64870, "text": "https://youtu.be/1Ld7gbW1oHcDesign a stack that supports getMin() in O(1) time and O(1) extra spaceThanks to @Venki, @swarup, and @Jing Huang for their inputs.Please write comments if you find the above code incorrect, or find other ways to solve the same problem." }, { "code": null, "e": 65147, "s": 65135, "text": "bidibaaz123" }, { "code": null, "e": 65156, "s": 65147, "text": "zeekgeek" }, { "code": null, "e": 65168, "s": 65156, "text": "sinhaiscena" }, { "code": null, "e": 65176, "s": 65168, "text": "scisaif" }, { "code": null, "e": 65190, "s": 65176, "text": "vasutiwari409" }, { "code": null, "e": 65204, "s": 65190, "text": "architgwl2000" }, { "code": null, "e": 65218, "s": 65204, "text": "GauravRajput1" }, { "code": null, "e": 65230, "s": 65218, "text": "umadevi9616" }, { "code": null, "e": 65248, "s": 65230, "text": "germanshephered48" }, { "code": null, "e": 65254, "s": 65248, "text": "Adobe" }, { "code": null, "e": 65261, "s": 65254, "text": "Amazon" }, { "code": null, "e": 65270, "s": 65261, "text": "Linkedin" }, { "code": null, "e": 65276, "s": 65270, "text": "Paytm" }, { "code": null, "e": 65280, "s": 65276, "text": "STL" }, { "code": null, "e": 65287, "s": 65280, "text": "VMWare" }, { "code": null, "e": 65293, "s": 65287, "text": "Stack" }, { "code": null, "e": 65299, "s": 65293, "text": "Paytm" }, { "code": null, "e": 65306, "s": 65299, "text": "VMWare" }, { "code": null, "e": 65313, "s": 65306, "text": "Amazon" }, { "code": null, "e": 65319, "s": 65313, "text": "Adobe" }, { "code": null, "e": 65328, "s": 65319, "text": "Linkedin" }, { "code": null, "e": 65334, "s": 65328, "text": "Stack" }, { "code": null, "e": 65338, "s": 65334, "text": "STL" }, { "code": null, "e": 65436, "s": 65338, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 65511, "s": 65436, "text": "Check for Balanced Brackets in an expression (well-formedness) using Stack" }, { "code": null, "e": 65544, "s": 65511, "text": "Stack | Set 2 (Infix to Postfix)" }, { "code": null, "e": 65571, "s": 65544, "text": "Program for Tower of Hanoi" }, { "code": null, "e": 65620, "s": 65571, "text": "Stack | Set 4 (Evaluation of Postfix Expression)" }, { "code": null, "e": 65663, "s": 65620, "text": "Implement a stack using singly linked list" }, { "code": null, "e": 65684, "s": 65663, "text": "Next Greater Element" }, { "code": null, "e": 65712, "s": 65684, "text": "Merge Overlapping Intervals" }, { "code": null, "e": 65763, "s": 65712, "text": "Difference between Stack and Queue Data Structures" }, { "code": null, "e": 65804, "s": 65763, "text": "Iterative Depth First Traversal of Graph" } ]
How do I display only the visible text with jQuery?
To display only the visible text, use the concept of βˆ’ visible selector in jQuery. It selects the element currently visible. Following is the code βˆ’ Live Demo <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initialscale= 1.0"> <title>Document</title> <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> </head> <body> <div id="myDiv"> <span class="test" style="display:none"><b>Test Class</b></span> <span class="demo"> <b>Demo class</b></span> </div> <script> $('#myDiv').children(":visible").text() </script> </body> </html> To run the above program, save the file name β€œanyName.html(index.html)” and right click on the file. Select the option β€œOpen with Live Server” in VS Code editor. This will produce the following output displaying the visible text βˆ’
[ { "code": null, "e": 1211, "s": 1062, "text": "To display only the visible text, use the concept of βˆ’ visible selector in jQuery. It selects the\nelement currently visible. Following is the code βˆ’" }, { "code": null, "e": 1222, "s": 1211, "text": " Live Demo" }, { "code": null, "e": 1828, "s": 1222, "text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\">\n<meta name=\"viewport\" content=\"width=device-width, initialscale=\n1.0\">\n<title>Document</title>\n<link rel=\"stylesheet\" href=\"//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css\">\n<script src=\"https://code.jquery.com/jquery-1.12.4.js\"></script>\n<script src=\"https://code.jquery.com/ui/1.12.1/jquery-ui.js\"></script>\n</head>\n<body>\n<div id=\"myDiv\">\n<span class=\"test\" style=\"display:none\"><b>Test Class</b></span>\n<span class=\"demo\"> <b>Demo class</b></span>\n</div>\n<script>\n $('#myDiv').children(\":visible\").text()\n</script>\n</body>\n</html>" }, { "code": null, "e": 1990, "s": 1828, "text": "To run the above program, save the file name β€œanyName.html(index.html)” and right click on the\nfile. Select the option β€œOpen with Live Server” in VS Code editor." }, { "code": null, "e": 2059, "s": 1990, "text": "This will produce the following output displaying the visible text βˆ’" } ]
Cryptography with Python - XOR Process
In this chapter, let us understand the XOR process along with its coding in Python. XOR algorithm of encryption and decryption converts the plain text in the format ASCII bytes and uses XOR procedure to convert it to a specified byte. It offers the following advantages to its users βˆ’ Fast computation No difference marked in left and right side Easy to understand and analyze You can use the following piece of code to perform XOR process βˆ’ def xor_crypt_string(data, key = 'awesomepassword', encode = False, decode = False): from itertools import izip, cycle import base64 if decode: data = base64.decodestring(data) xored = ''.join(chr(ord(x) ^ ord(y)) for (x,y) in izip(data, cycle(key))) if encode: return base64.encodestring(xored).strip() return xored secret_data = "XOR procedure" print("The cipher text is") print xor_crypt_string(secret_data, encode = True) print("The plain text fetched") print xor_crypt_string(xor_crypt_string(secret_data, encode = True), decode = True) The code for XOR process gives you the following output βˆ’ The function xor_crypt_string() includes a parameter to specify mode of encode and decode and also the string value. The function xor_crypt_string() includes a parameter to specify mode of encode and decode and also the string value. The basic functions are taken with base64 modules which follows the XOR procedure/ operation to encrypt or decrypt the plain text/ cipher text. The basic functions are taken with base64 modules which follows the XOR procedure/ operation to encrypt or decrypt the plain text/ cipher text. Note βˆ’ XOR encryption is used to encrypt data and is hard to crack by brute-force method, that is by generating random encrypting keys to match with the correct cipher text. 10 Lectures 2 hours Total Seminars 10 Lectures 2 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 2376, "s": 2292, "text": "In this chapter, let us understand the XOR process along with its coding in Python." }, { "code": null, "e": 2577, "s": 2376, "text": "XOR algorithm of encryption and decryption converts the plain text in the format ASCII bytes and uses XOR procedure to convert it to a specified byte. It offers the following advantages to its users βˆ’" }, { "code": null, "e": 2594, "s": 2577, "text": "Fast computation" }, { "code": null, "e": 2638, "s": 2594, "text": "No difference marked in left and right side" }, { "code": null, "e": 2669, "s": 2638, "text": "Easy to understand and analyze" }, { "code": null, "e": 2734, "s": 2669, "text": "You can use the following piece of code to perform XOR process βˆ’" }, { "code": null, "e": 3315, "s": 2734, "text": "def xor_crypt_string(data, key = 'awesomepassword', encode = False, decode = False):\n from itertools import izip, cycle\n import base64\n \n if decode:\n data = base64.decodestring(data)\n xored = ''.join(chr(ord(x) ^ ord(y)) for (x,y) in izip(data, cycle(key)))\n \n if encode:\n return base64.encodestring(xored).strip()\n return xored\nsecret_data = \"XOR procedure\"\n\nprint(\"The cipher text is\")\nprint xor_crypt_string(secret_data, encode = True)\nprint(\"The plain text fetched\")\nprint xor_crypt_string(xor_crypt_string(secret_data, encode = True), decode = True)" }, { "code": null, "e": 3373, "s": 3315, "text": "The code for XOR process gives you the following output βˆ’" }, { "code": null, "e": 3490, "s": 3373, "text": "The function xor_crypt_string() includes a parameter to specify mode of encode and decode and also the string value." }, { "code": null, "e": 3607, "s": 3490, "text": "The function xor_crypt_string() includes a parameter to specify mode of encode and decode and also the string value." }, { "code": null, "e": 3751, "s": 3607, "text": "The basic functions are taken with base64 modules which follows the XOR procedure/ operation to encrypt or decrypt the plain text/ cipher text." }, { "code": null, "e": 3895, "s": 3751, "text": "The basic functions are taken with base64 modules which follows the XOR procedure/ operation to encrypt or decrypt the plain text/ cipher text." }, { "code": null, "e": 4069, "s": 3895, "text": "Note βˆ’ XOR encryption is used to encrypt data and is hard to crack by brute-force method, that is by generating random encrypting keys to match with the correct cipher text." }, { "code": null, "e": 4102, "s": 4069, "text": "\n 10 Lectures \n 2 hours \n" }, { "code": null, "e": 4118, "s": 4102, "text": " Total Seminars" }, { "code": null, "e": 4151, "s": 4118, "text": "\n 10 Lectures \n 2 hours \n" }, { "code": null, "e": 4174, "s": 4151, "text": " Stone River ELearning" }, { "code": null, "e": 4181, "s": 4174, "text": " Print" }, { "code": null, "e": 4192, "s": 4181, "text": " Add Notes" } ]
Android Popup Menu Example
Popup menu just like a menu, it going to be display either above of the view or below of the view according to space on activity. Here is the simple solution to create android popup menu. Step 1 βˆ’ Create a new project in Android Studio, go to File β‡’ New Project and fill all required details to create a new project. Step 2 βˆ’ Add the following code to res/layout/activity_main.xml. <?xml version = "1.0" encoding = "utf-8"?> <LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" xmlns:tools = "http://schemas.android.com/tools" android:id = "@+id/rootview" android:layout_width = "match_parent" android:layout_height = "match_parent" android:orientation = "vertical" android:background = "#c1c1c1" android:gravity = "center_horizontal" tools:context = ".MainActivity"> <Button android:id = "@+id/popup" android:text = "Download" android:layout_width = "wrap_content" android:layout_height = "wrap_content" /> </LinearLayout> In the above code, we have given button. when you click on the above button, it going to show popup menu. Step 3 βˆ’ Add the following code to src/MainActivity.java package com.example.andy.myapplication; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.PopupMenu; import android.widget.Toast; public class MainActivity extends AppCompatActivity { Button popupButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); popupButton = findViewById(R.id.popup); popupButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { popupMenuExample(); } }); } private void popupMenuExample() { PopupMenu p = new PopupMenu(MainActivity.this, popupButton); p.getMenuInflater().inflate(R.menu.popup_menu_example, p .getMenu()); p.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { Toast.makeText(MainActivity.this,item.getTitle(), Toast.LENGTH_SHORT).show(); return true; } }); p.show(); } } In the above code when you click on button it going to create popup menu object and add to menu as shown below - PopupMenu p = new PopupMenu(MainActivity.this, popupButton); p.getMenuInflater().inflate(R.menu.popup_menu_example, p .getMenu()); In the above code we have inflate menu as popup_menu_example as shown below - <?xml version = "1.0" encoding = "utf-8"?> <menu xmlns:android = "http://schemas.android.com/apk/res/android"> <item android:id = "@+id/android" android:title = "Android" /> <item android:id = "@+id/java" android:title = "JAVA"/> <item android:id = "@+id/kotlin" android:title = "Kotlin"/> </menu> When user click on the menu item it will call onMenuItemClickListener() as shown below - p.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { Toast.makeText(MainActivity.this,item.getTitle(), Toast.LENGTH_SHORT).show(); return true; } }); To show the popup menu we have to call show() as shown below - p.show(); 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 βˆ’ When you click on download button it will show popup menu. Button doesn't have space on the above so it will show at bottom. as shown below - Now click on any item it will give message as shown below - Click here to download the project code
[ { "code": null, "e": 1250, "s": 1062, "text": "Popup menu just like a menu, it going to be display either above of the view or below of the view according to space on activity. Here is the simple solution to create android popup menu." }, { "code": null, "e": 1379, "s": 1250, "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": 1444, "s": 1379, "text": "Step 2 βˆ’ Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2059, "s": 1444, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<LinearLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:id = \"@+id/rootview\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n android:orientation = \"vertical\"\n android:background = \"#c1c1c1\"\n android:gravity = \"center_horizontal\"\n tools:context = \".MainActivity\">\n <Button\n android:id = \"@+id/popup\"\n android:text = \"Download\"\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\" />\n</LinearLayout>" }, { "code": null, "e": 2165, "s": 2059, "text": "In the above code, we have given button. when you click on the above button, it going to show popup menu." }, { "code": null, "e": 2222, "s": 2165, "text": "Step 3 βˆ’ Add the following code to src/MainActivity.java" }, { "code": null, "e": 3421, "s": 2222, "text": "package com.example.andy.myapplication;\nimport android.os.Bundle;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.MenuItem;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.PopupMenu;\nimport android.widget.Toast;\n\npublic class MainActivity extends AppCompatActivity {\n Button popupButton;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n popupButton = findViewById(R.id.popup);\n popupButton.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n popupMenuExample();\n }\n });\n }\n private void popupMenuExample() {\n PopupMenu p = new PopupMenu(MainActivity.this, popupButton);\n p.getMenuInflater().inflate(R.menu.popup_menu_example, p .getMenu());\n p.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {\n public boolean onMenuItemClick(MenuItem item) {\n Toast.makeText(MainActivity.this,item.getTitle(), Toast.LENGTH_SHORT).show();\n return true;\n }\n });\n p.show();\n }\n}" }, { "code": null, "e": 3534, "s": 3421, "text": "In the above code when you click on button it going to create popup menu object and add to menu as shown below -" }, { "code": null, "e": 3665, "s": 3534, "text": "PopupMenu p = new PopupMenu(MainActivity.this, popupButton);\np.getMenuInflater().inflate(R.menu.popup_menu_example, p .getMenu());" }, { "code": null, "e": 3743, "s": 3665, "text": "In the above code we have inflate menu as popup_menu_example as shown below -" }, { "code": null, "e": 4086, "s": 3743, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<menu xmlns:android = \"http://schemas.android.com/apk/res/android\">\n <item\n android:id = \"@+id/android\"\n android:title = \"Android\" />\n <item\n android:id = \"@+id/java\"\n android:title = \"JAVA\"/>\n <item\n android:id = \"@+id/kotlin\"\n android:title = \"Kotlin\"/>\n</menu>" }, { "code": null, "e": 4175, "s": 4086, "text": "When user click on the menu item it will call onMenuItemClickListener() as shown below -" }, { "code": null, "e": 4409, "s": 4175, "text": "p.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {\n public boolean onMenuItemClick(MenuItem item) {\n Toast.makeText(MainActivity.this,item.getTitle(), Toast.LENGTH_SHORT).show();\n return true;\n }\n});" }, { "code": null, "e": 4472, "s": 4409, "text": "To show the popup menu we have to call show() as shown below -" }, { "code": null, "e": 4482, "s": 4472, "text": "p.show();" }, { "code": null, "e": 4829, "s": 4482, "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": 4971, "s": 4829, "text": "When you click on download button it will show popup menu. Button doesn't have space on the above so it will show at bottom. as shown below -" }, { "code": null, "e": 5031, "s": 4971, "text": "Now click on any item it will give message as shown below -" }, { "code": null, "e": 5071, "s": 5031, "text": "Click here to download the project code" } ]
\bigvee - Tex Command
\bigvee - Used to draw big V symbol. { \bigvee } \bigvee command draws V symbol. \bigvee ⋁ \bigvee ⋁ \bigvee 14 Lectures 52 mins Ashraf Said 11 Lectures 1 hours Ashraf Said 9 Lectures 1 hours Emenwa Global, Ejike IfeanyiChukwu 29 Lectures 2.5 hours Mohammad Nauman 14 Lectures 1 hours Daniel Stern 15 Lectures 47 mins Nishant Kumar Print Add Notes Bookmark this page
[ { "code": null, "e": 8023, "s": 7986, "text": "\\bigvee - Used to draw big V symbol." }, { "code": null, "e": 8035, "s": 8023, "text": "{ \\bigvee }" }, { "code": null, "e": 8067, "s": 8035, "text": "\\bigvee command draws V symbol." }, { "code": null, "e": 8083, "s": 8067, "text": "\n\\bigvee \n\n⋁\n\n\n" }, { "code": null, "e": 8097, "s": 8083, "text": "\\bigvee \n\n⋁\n\n" }, { "code": null, "e": 8106, "s": 8097, "text": "\\bigvee " }, { "code": null, "e": 8138, "s": 8106, "text": "\n 14 Lectures \n 52 mins\n" }, { "code": null, "e": 8151, "s": 8138, "text": " Ashraf Said" }, { "code": null, "e": 8184, "s": 8151, "text": "\n 11 Lectures \n 1 hours \n" }, { "code": null, "e": 8197, "s": 8184, "text": " Ashraf Said" }, { "code": null, "e": 8229, "s": 8197, "text": "\n 9 Lectures \n 1 hours \n" }, { "code": null, "e": 8265, "s": 8229, "text": " Emenwa Global, Ejike IfeanyiChukwu" }, { "code": null, "e": 8300, "s": 8265, "text": "\n 29 Lectures \n 2.5 hours \n" }, { "code": null, "e": 8317, "s": 8300, "text": " Mohammad Nauman" }, { "code": null, "e": 8350, "s": 8317, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 8364, "s": 8350, "text": " Daniel Stern" }, { "code": null, "e": 8396, "s": 8364, "text": "\n 15 Lectures \n 47 mins\n" }, { "code": null, "e": 8411, "s": 8396, "text": " Nishant Kumar" }, { "code": null, "e": 8418, "s": 8411, "text": " Print" }, { "code": null, "e": 8429, "s": 8418, "text": " Add Notes" } ]
Array sum in C++ STL
The array is a linear data structure that stores elements of the same data type in continuous memory locations. Array sum is the sum of all elements of the array. In c++ programming language there are multiple methods by with you can find the array sum. The basic method to find the sum of all elements of the array is to loop over the elements of the array and add the element’s value to the sum variable. Step 1 : For i from 0 to n-1, follow step 2 ; Step 2 : sum = sum + arr[i] Step 3 : print sum. Live Demo #include <iostream> using namespace std; int main (){ int arr[] = { 2, 5, 7, 8, 2, 6, 9 }; int n = 7, sum = 0; for(int i = 0; i<n ; i++){ sum+=arr[i]; } cout<<"The array sum is "<<sum; return 0; } The array sum is 39 The accumulate method in c++ used to find the array sum. This function can be accessed from the numeric library in c++. accumulate(array_name , array_name+length , sum); Live Demo #include <iostream> #include <numeric> using namespace std; int main (){ int arr[] = { 2, 5, 7, 8, 2, 6, 9 }; int n = 7, sum = 0; sum = accumulate(arr, arr+n, sum); cout<<"The array sum is "<<sum; return 0; } The array sum is 39 You can use the accumulate function on vectors too. It will return the sum of array which is it vector form. Live Demo #include <iostream> #include <vector> #include <numeric> using namespace std; int arraySum(vector<int> &v){ int initial_sum = 0; return accumulate(v.begin(), v.end(), initial_sum); } int main(){ vector<int> v{12, 56, 76, 2, 90 , 3} ; int sum = 0; sum=accumulate(v.begin(), v.end(), sum); cout<<"The sum of array is "<<sum; return 0; } The sum of array is 239
[ { "code": null, "e": 1174, "s": 1062, "text": "The array is a linear data structure that stores elements of the same data type in continuous memory locations." }, { "code": null, "e": 1225, "s": 1174, "text": "Array sum is the sum of all elements of the array." }, { "code": null, "e": 1316, "s": 1225, "text": "In c++ programming language there are multiple methods by with you can find the array sum." }, { "code": null, "e": 1469, "s": 1316, "text": "The basic method to find the sum of all elements of the array is to loop over the elements of the array and add the element’s value to the sum variable." }, { "code": null, "e": 1563, "s": 1469, "text": "Step 1 : For i from 0 to n-1, follow step 2 ;\nStep 2 : sum = sum + arr[i]\nStep 3 : print sum." }, { "code": null, "e": 1574, "s": 1563, "text": " Live Demo" }, { "code": null, "e": 1795, "s": 1574, "text": "#include <iostream>\nusing namespace std;\nint main (){\n int arr[] = { 2, 5, 7, 8, 2, 6, 9 };\n int n = 7, sum = 0;\n for(int i = 0; i<n ; i++){\n sum+=arr[i];\n }\n cout<<\"The array sum is \"<<sum;\n return 0;\n}" }, { "code": null, "e": 1815, "s": 1795, "text": "The array sum is 39" }, { "code": null, "e": 1935, "s": 1815, "text": "The accumulate method in c++ used to find the array sum. This function can be accessed from the numeric library in c++." }, { "code": null, "e": 1985, "s": 1935, "text": "accumulate(array_name , array_name+length , sum);" }, { "code": null, "e": 1996, "s": 1985, "text": " Live Demo" }, { "code": null, "e": 2220, "s": 1996, "text": "#include <iostream>\n#include <numeric>\nusing namespace std;\nint main (){\n int arr[] = { 2, 5, 7, 8, 2, 6, 9 };\n int n = 7, sum = 0;\n sum = accumulate(arr, arr+n, sum);\n cout<<\"The array sum is \"<<sum;\n return 0;\n}" }, { "code": null, "e": 2240, "s": 2220, "text": "The array sum is 39" }, { "code": null, "e": 2349, "s": 2240, "text": "You can use the accumulate function on vectors too. It will return the sum of array which is it vector form." }, { "code": null, "e": 2360, "s": 2349, "text": " Live Demo" }, { "code": null, "e": 2716, "s": 2360, "text": "#include <iostream>\n#include <vector>\n#include <numeric>\nusing namespace std;\nint arraySum(vector<int> &v){\n int initial_sum = 0;\n return accumulate(v.begin(), v.end(), initial_sum);\n}\nint main(){\n vector<int> v{12, 56, 76, 2, 90 , 3} ;\n int sum = 0;\n sum=accumulate(v.begin(), v.end(), sum);\n cout<<\"The sum of array is \"<<sum;\n return 0;\n}" }, { "code": null, "e": 2740, "s": 2716, "text": "The sum of array is 239" } ]
How to detect shake event in Android app?
This example demonstrates how to do I in android. Step 1 βˆ’ Create a new project in Android Studio, go to File β‡’ New Project and fill all required details to create a new project. Step 2 βˆ’ Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <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:padding="8dp" android:orientation="vertical" tools:context=".MainActivity"> <TextView android:text="Shake the phone to detect to shake event" android:textSize="24sp" android:textStyle="bold" android:layout_width="wrap_content" android:layout_height="wrap_content"/> </LinearLayout> Step 3 βˆ’ Add the following code to src/MainActivity.java import androidx.appcompat.app.AppCompatActivity; import android.content.Context; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.os.Bundle; import android.widget.Toast; import java.util.Objects; public class MainActivity extends AppCompatActivity { private SensorManager mSensorManager; private float mAccel; private float mAccelCurrent; private float mAccelLast; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); Objects.requireNonNull(mSensorManager).registerListener(mSensorListener, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL); mAccel = 10f; mAccelCurrent = SensorManager.GRAVITY_EARTH; mAccelLast = SensorManager.GRAVITY_EARTH; } private final SensorEventListener mSensorListener = new SensorEventListener() { @Override public void onSensorChanged(SensorEvent event) { float x = event.values[0]; float y = event.values[1]; float z = event.values[2]; mAccelLast = mAccelCurrent; mAccelCurrent = (float) Math.sqrt((double) (x * x + y * y + z * z)); float delta = mAccelCurrent - mAccelLast; mAccel = mAccel * 0.9f + delta; if (mAccel > 12) { Toast.makeText(getApplicationContext(), "Shake event detected", Toast.LENGTH_SHORT).show(); } } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } }; @Override protected void onResume() { mSensorManager.registerListener(mSensorListener, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL); super.onResume(); } @Override protected void onPause() { mSensorManager.unregisterListener(mSensorListener); super.onPause(); } } Step 4 βˆ’ Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the 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": 1112, "s": 1062, "text": "This example demonstrates how to do I in android." }, { "code": null, "e": 1241, "s": 1112, "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": 1306, "s": 1241, "text": "Step 2 βˆ’ Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 1879, "s": 1306, "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:padding=\"8dp\"\n android:orientation=\"vertical\"\n tools:context=\".MainActivity\">\n <TextView\n android:text=\"Shake the phone to detect to shake event\"\n android:textSize=\"24sp\"\n android:textStyle=\"bold\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"/>\n</LinearLayout>" }, { "code": null, "e": 1936, "s": 1879, "text": "Step 3 βˆ’ Add the following code to src/MainActivity.java" }, { "code": null, "e": 4053, "s": 1936, "text": "import androidx.appcompat.app.AppCompatActivity;\nimport android.content.Context;\nimport android.hardware.Sensor;\nimport android.hardware.SensorEvent;\nimport android.hardware.SensorEventListener;\nimport android.hardware.SensorManager;\nimport android.os.Bundle;\nimport android.widget.Toast;\nimport java.util.Objects;\npublic class MainActivity extends AppCompatActivity {\n private SensorManager mSensorManager;\n private float mAccel;\n private float mAccelCurrent;\n private float mAccelLast;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);\n Objects.requireNonNull(mSensorManager).registerListener(mSensorListener, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),\n SensorManager.SENSOR_DELAY_NORMAL);\n mAccel = 10f;\n mAccelCurrent = SensorManager.GRAVITY_EARTH;\n mAccelLast = SensorManager.GRAVITY_EARTH;\n }\n private final SensorEventListener mSensorListener = new SensorEventListener() {\n @Override\n public void onSensorChanged(SensorEvent event) {\n float x = event.values[0];\n float y = event.values[1];\n float z = event.values[2];\n mAccelLast = mAccelCurrent;\n mAccelCurrent = (float) Math.sqrt((double) (x * x + y * y + z * z));\n float delta = mAccelCurrent - mAccelLast;\n mAccel = mAccel * 0.9f + delta;\n if (mAccel > 12) {\n Toast.makeText(getApplicationContext(), \"Shake event detected\", Toast.LENGTH_SHORT).show();\n }\n }\n @Override\n public void onAccuracyChanged(Sensor sensor, int accuracy) {\n }\n };\n @Override\n protected void onResume() {\n mSensorManager.registerListener(mSensorListener, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),\n SensorManager.SENSOR_DELAY_NORMAL);\n super.onResume();\n }\n @Override\n protected void onPause() {\n mSensorManager.unregisterListener(mSensorListener);\n super.onPause();\n }\n}" }, { "code": null, "e": 4108, "s": 4053, "text": "Step 4 βˆ’ Add the following code to androidManifest.xml" }, { "code": null, "e": 4781, "s": 4108, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"app.com.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 5132, "s": 4781, "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 the 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": 5173, "s": 5132, "text": "Click here to download the project code." } ]
Mouse swipe controls in Angular 9 using HammerJS - GeeksforGeeks
19 Aug, 2020 Angular is an application design framework and development platform for creating efficient and sophisticated single-page apps. It has been changed a lot from its first release. And it keeps adding new features and modifications in its releases which is a good thing. But sometimes what we have used in the previous version stops working in the latest version. Same is the case with HammerJS. HammerJS is a very good open-source library that can recognise gestures made by touch, mouse and pointer events. You can read more about HammerJS and its documentation here. In Angular 9, if you use previous methods of adding HammerJS, it will not work because Angular has modified some of its features. So you will go through the whole process of working with HammerJS in Angular 9 from starting. Approach: The approach is to install the hammerjs package locally, import it in main.ts and set the Hammer gesture configuration by extending the HammerGestureConfig class. Then you can bind to specific events like swipe, pan, pinch, press, etc. The most important thing is to import the HammerModule in app module file. In your angular project, install the hammerjs package locally by running the below command.npm install --save hammerjs In your angular project, install the hammerjs package locally by running the below command. npm install --save hammerjs Now, you will need to import the hammerjs module in your main.ts file. If you do not import this, you will get an error in your console. Error: Hammer.js is not loaded, can not bind to XYZ event. import 'hammerjs'; Now, you will need to import the hammerjs module in your main.ts file. If you do not import this, you will get an error in your console. Error: Hammer.js is not loaded, can not bind to XYZ event. import 'hammerjs'; Let us move on to our app.module.ts, here you can add your own configuration of Hammer gestures using HammerGestureConfig class and HAMMER_GESTURE_CONFIG like in the below image.Also make sure to import HammerModule as it is the current modification which has been done in Angular 9.Otherwise your project will not work and will not give error too. ( Although this is in typescript, but the editor does not support that yet so ignore and do not get confused. )app.module.ts// add this in your app.module.tsimport { NgModule, Injectable } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { FormsModule } from '@angular/forms';// particular imports for hammerimport * as Hammer from 'hammerjs';import {HammerModule, HammerGestureConfig, HAMMER_GESTURE_CONFIG} from '@angular/platform-browser';import { AppComponent } from './app.component'; @Injectable()export class MyHammerConfig extends HammerGestureConfig { overrides = <any> { swipe: { direction: Hammer.DIRECTION_ALL }, };} @NgModule({ imports: [ BrowserModule, FormsModule, HammerModule ], declarations: [ AppComponent, HelloComponent ], bootstrap: [ AppComponent ], providers: [ { provide: HAMMER_GESTURE_CONFIG, useClass: MyHammerConfig, }, ],})export class AppModule { } Let us move on to our app.module.ts, here you can add your own configuration of Hammer gestures using HammerGestureConfig class and HAMMER_GESTURE_CONFIG like in the below image.Also make sure to import HammerModule as it is the current modification which has been done in Angular 9.Otherwise your project will not work and will not give error too. ( Although this is in typescript, but the editor does not support that yet so ignore and do not get confused. ) app.module.ts // add this in your app.module.tsimport { NgModule, Injectable } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { FormsModule } from '@angular/forms';// particular imports for hammerimport * as Hammer from 'hammerjs';import {HammerModule, HammerGestureConfig, HAMMER_GESTURE_CONFIG} from '@angular/platform-browser';import { AppComponent } from './app.component'; @Injectable()export class MyHammerConfig extends HammerGestureConfig { overrides = <any> { swipe: { direction: Hammer.DIRECTION_ALL }, };} @NgModule({ imports: [ BrowserModule, FormsModule, HammerModule ], declarations: [ AppComponent, HelloComponent ], bootstrap: [ AppComponent ], providers: [ { provide: HAMMER_GESTURE_CONFIG, useClass: MyHammerConfig, }, ],})export class AppModule { } Now we will create our simple example for Swipe gestures. For app.component.html, you can add the following code.app.component.html<!--add this in your app.component.html --><div class="swipe" (swipe)="onSwipe($event)"> <h1>Swipe Gesture</h1> <p>Works with both mouse and touch.</p> <h5 [innerHTML]="direction"></h5></div> <!--add this in your app.component.html --><div class="swipe" (swipe)="onSwipe($event)"> <h1>Swipe Gesture</h1> <p>Works with both mouse and touch.</p> <h5 [innerHTML]="direction"></h5></div> Add some styles to your example like this in app.component.css. The important thing to notice is where you want the swipe gesture, set user-select as none.app.component.css.swipe { background-color: #76b490; padding: 20px; margin: 10px; border-radius: 3px; height: 500px; text-align: center; overflow: auto; color: rgb(78, 22, 131); user-select: none;}h1,p { color: rgb(116, 49, 11);} app.component.css .swipe { background-color: #76b490; padding: 20px; margin: 10px; border-radius: 3px; height: 500px; text-align: center; overflow: auto; color: rgb(78, 22, 131); user-select: none;}h1,p { color: rgb(116, 49, 11);} Lastly, add your typescript code in app.component.ts like this.// add this in your app.component.tsimport { Component } from "@angular/core"; @Component({ selector: "my-app", templateUrl: "./app.component.html", styleUrls: ["./app.component.css"]})export class AppComponent { direction = ""; onSwipe(event) { const x = Math.abs(event.deltaX) > 40 ? (event.deltaX > 0 ? "Right" : "Left") : ""; const y = Math.abs(event.deltaY) > 40 ? (event.deltaY > 0 ? "Down" : "Up") : ""; this.direction += `You swiped in <b> ${x} ${y} </b> direction <hr>`; }} // add this in your app.component.tsimport { Component } from "@angular/core"; @Component({ selector: "my-app", templateUrl: "./app.component.html", styleUrls: ["./app.component.css"]})export class AppComponent { direction = ""; onSwipe(event) { const x = Math.abs(event.deltaX) > 40 ? (event.deltaX > 0 ? "Right" : "Left") : ""; const y = Math.abs(event.deltaY) > 40 ? (event.deltaY > 0 ? "Down" : "Up") : ""; this.direction += `You swiped in <b> ${x} ${y} </b> direction <hr>`; }} Output: There are several other gestures you can implement using HammerJS just like that. For more information, please read their documentation. AngularJS-Misc AngularJS JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Angular PrimeNG Dropdown Component How to make a Bootstrap Modal Popup in Angular 9/8 ? Angular 10 (blur) Event How to setup 404 page in angular routing ? How to create module with Routing in Angular 9 ? 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 calculate the number of days between two dates in javascript? File uploading in React.js
[ { "code": null, "e": 24743, "s": 24715, "text": "\n19 Aug, 2020" }, { "code": null, "e": 25135, "s": 24743, "text": "Angular is an application design framework and development platform for creating efficient and sophisticated single-page apps. It has been changed a lot from its first release. And it keeps adding new features and modifications in its releases which is a good thing. But sometimes what we have used in the previous version stops working in the latest version. Same is the case with HammerJS." }, { "code": null, "e": 25309, "s": 25135, "text": "HammerJS is a very good open-source library that can recognise gestures made by touch, mouse and pointer events. You can read more about HammerJS and its documentation here." }, { "code": null, "e": 25533, "s": 25309, "text": "In Angular 9, if you use previous methods of adding HammerJS, it will not work because Angular has modified some of its features. So you will go through the whole process of working with HammerJS in Angular 9 from starting." }, { "code": null, "e": 25543, "s": 25533, "text": "Approach:" }, { "code": null, "e": 25854, "s": 25543, "text": "The approach is to install the hammerjs package locally, import it in main.ts and set the Hammer gesture configuration by extending the HammerGestureConfig class. Then you can bind to specific events like swipe, pan, pinch, press, etc. The most important thing is to import the HammerModule in app module file." }, { "code": null, "e": 25973, "s": 25854, "text": "In your angular project, install the hammerjs package locally by running the below command.npm install --save hammerjs" }, { "code": null, "e": 26065, "s": 25973, "text": "In your angular project, install the hammerjs package locally by running the below command." }, { "code": null, "e": 26093, "s": 26065, "text": "npm install --save hammerjs" }, { "code": null, "e": 26308, "s": 26093, "text": "Now, you will need to import the hammerjs module in your main.ts file. If you do not import this, you will get an error in your console. Error: Hammer.js is not loaded, can not bind to XYZ event. import 'hammerjs';" }, { "code": null, "e": 26505, "s": 26308, "text": "Now, you will need to import the hammerjs module in your main.ts file. If you do not import this, you will get an error in your console. Error: Hammer.js is not loaded, can not bind to XYZ event. " }, { "code": null, "e": 26524, "s": 26505, "text": "import 'hammerjs';" }, { "code": null, "e": 27826, "s": 26524, "text": "Let us move on to our app.module.ts, here you can add your own configuration of Hammer gestures using HammerGestureConfig class and HAMMER_GESTURE_CONFIG like in the below image.Also make sure to import HammerModule as it is the current modification which has been done in Angular 9.Otherwise your project will not work and will not give error too. ( Although this is in typescript, but the editor does not support that yet so ignore and do not get confused. )app.module.ts// add this in your app.module.tsimport { NgModule, Injectable } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { FormsModule } from '@angular/forms';// particular imports for hammerimport * as Hammer from 'hammerjs';import {HammerModule, HammerGestureConfig, HAMMER_GESTURE_CONFIG} from '@angular/platform-browser';import { AppComponent } from './app.component'; @Injectable()export class MyHammerConfig extends HammerGestureConfig { overrides = <any> { swipe: { direction: Hammer.DIRECTION_ALL }, };} @NgModule({ imports: [ BrowserModule, FormsModule, HammerModule ], declarations: [ AppComponent, HelloComponent ], bootstrap: [ AppComponent ], providers: [ { provide: HAMMER_GESTURE_CONFIG, useClass: MyHammerConfig, }, ],})export class AppModule { }" }, { "code": null, "e": 28287, "s": 27826, "text": "Let us move on to our app.module.ts, here you can add your own configuration of Hammer gestures using HammerGestureConfig class and HAMMER_GESTURE_CONFIG like in the below image.Also make sure to import HammerModule as it is the current modification which has been done in Angular 9.Otherwise your project will not work and will not give error too. ( Although this is in typescript, but the editor does not support that yet so ignore and do not get confused. )" }, { "code": null, "e": 28301, "s": 28287, "text": "app.module.ts" }, { "code": "// add this in your app.module.tsimport { NgModule, Injectable } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { FormsModule } from '@angular/forms';// particular imports for hammerimport * as Hammer from 'hammerjs';import {HammerModule, HammerGestureConfig, HAMMER_GESTURE_CONFIG} from '@angular/platform-browser';import { AppComponent } from './app.component'; @Injectable()export class MyHammerConfig extends HammerGestureConfig { overrides = <any> { swipe: { direction: Hammer.DIRECTION_ALL }, };} @NgModule({ imports: [ BrowserModule, FormsModule, HammerModule ], declarations: [ AppComponent, HelloComponent ], bootstrap: [ AppComponent ], providers: [ { provide: HAMMER_GESTURE_CONFIG, useClass: MyHammerConfig, }, ],})export class AppModule { }", "e": 29130, "s": 28301, "text": null }, { "code": null, "e": 29456, "s": 29130, "text": "Now we will create our simple example for Swipe gestures. For app.component.html, you can add the following code.app.component.html<!--add this in your app.component.html --><div class=\"swipe\" (swipe)=\"onSwipe($event)\"> <h1>Swipe Gesture</h1> <p>Works with both mouse and touch.</p> <h5 [innerHTML]=\"direction\"></h5></div>" }, { "code": "<!--add this in your app.component.html --><div class=\"swipe\" (swipe)=\"onSwipe($event)\"> <h1>Swipe Gesture</h1> <p>Works with both mouse and touch.</p> <h5 [innerHTML]=\"direction\"></h5></div>", "e": 29651, "s": 29456, "text": null }, { "code": null, "e": 30066, "s": 29651, "text": "Add some styles to your example like this in app.component.css. The important thing to notice is where you want the swipe gesture, set user-select as none.app.component.css.swipe { background-color: #76b490; padding: 20px; margin: 10px; border-radius: 3px; height: 500px; text-align: center; overflow: auto; color: rgb(78, 22, 131); user-select: none;}h1,p { color: rgb(116, 49, 11);}" }, { "code": null, "e": 30084, "s": 30066, "text": "app.component.css" }, { "code": ".swipe { background-color: #76b490; padding: 20px; margin: 10px; border-radius: 3px; height: 500px; text-align: center; overflow: auto; color: rgb(78, 22, 131); user-select: none;}h1,p { color: rgb(116, 49, 11);}", "e": 30327, "s": 30084, "text": null }, { "code": null, "e": 30891, "s": 30327, "text": "Lastly, add your typescript code in app.component.ts like this.// add this in your app.component.tsimport { Component } from \"@angular/core\"; @Component({ selector: \"my-app\", templateUrl: \"./app.component.html\", styleUrls: [\"./app.component.css\"]})export class AppComponent { direction = \"\"; onSwipe(event) { const x = Math.abs(event.deltaX) > 40 ? (event.deltaX > 0 ? \"Right\" : \"Left\") : \"\"; const y = Math.abs(event.deltaY) > 40 ? (event.deltaY > 0 ? \"Down\" : \"Up\") : \"\"; this.direction += `You swiped in <b> ${x} ${y} </b> direction <hr>`; }}" }, { "code": "// add this in your app.component.tsimport { Component } from \"@angular/core\"; @Component({ selector: \"my-app\", templateUrl: \"./app.component.html\", styleUrls: [\"./app.component.css\"]})export class AppComponent { direction = \"\"; onSwipe(event) { const x = Math.abs(event.deltaX) > 40 ? (event.deltaX > 0 ? \"Right\" : \"Left\") : \"\"; const y = Math.abs(event.deltaY) > 40 ? (event.deltaY > 0 ? \"Down\" : \"Up\") : \"\"; this.direction += `You swiped in <b> ${x} ${y} </b> direction <hr>`; }}", "e": 31392, "s": 30891, "text": null }, { "code": null, "e": 31400, "s": 31392, "text": "Output:" }, { "code": null, "e": 31537, "s": 31400, "text": "There are several other gestures you can implement using HammerJS just like that. For more information, please read their documentation." }, { "code": null, "e": 31552, "s": 31537, "text": "AngularJS-Misc" }, { "code": null, "e": 31562, "s": 31552, "text": "AngularJS" }, { "code": null, "e": 31573, "s": 31562, "text": "JavaScript" }, { "code": null, "e": 31590, "s": 31573, "text": "Web Technologies" }, { "code": null, "e": 31688, "s": 31590, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31697, "s": 31688, "text": "Comments" }, { "code": null, "e": 31710, "s": 31697, "text": "Old Comments" }, { "code": null, "e": 31745, "s": 31710, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 31798, "s": 31745, "text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?" }, { "code": null, "e": 31822, "s": 31798, "text": "Angular 10 (blur) Event" }, { "code": null, "e": 31865, "s": 31822, "text": "How to setup 404 page in angular routing ?" }, { "code": null, "e": 31914, "s": 31865, "text": "How to create module with Routing in Angular 9 ?" }, { "code": null, "e": 31975, "s": 31914, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 32020, "s": 31975, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 32092, "s": 32020, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 32161, "s": 32092, "text": "How to calculate the number of days between two dates in javascript?" } ]
Kibana - Introduction To Elk Stack
Kibana is an open source visualization tool mainly used to analyze a large volume of logs in the form of line graph, bar graph, pie charts, heatmaps etc. Kibana works in sync with Elasticsearch and Logstash which together forms the so called ELK stack. ELK stands for Elasticsearch, Logstash, and Kibana. ELK is one of the popular log management platform used worldwide for log analysis. In the ELK stack βˆ’ Logstash extracts the logging data or other events from different input sources. It processes the events and later stores it in Elasticsearch. Logstash extracts the logging data or other events from different input sources. It processes the events and later stores it in Elasticsearch. Kibana is a visualization tool, which accesses the logs from Elasticsearch and is able to display to the user in the form of line graph, bar graph, pie charts etc. Kibana is a visualization tool, which accesses the logs from Elasticsearch and is able to display to the user in the form of line graph, bar graph, pie charts etc. In this tutorial, we will work closely with Kibana and Elasticsearch and visualize the data in different forms. In this chapter, let us understand how to work with ELK stack together. Besides, you will also see how to βˆ’ Load CSV data from Logstash to Elasticsearch. Use indices from Elasticsearch in Kibana. We are going to use CSV data to upload data using Logstash to Elasticsearch. To work on data analysis, we can get data from kaggle.com website. Kaggle.com site has all types of data uploaded and users can use it to work on data analysis. We have taken the countries.csv data from here: https://www.kaggle.com/fernandol/countries-of-the-world. You can download the csv file and use it. The csv file which we are going to use has following details. File name βˆ’ countriesdata.csv Columns βˆ’ "Country","Region","Population","Area" You can also create a dummy csv file and use it. We will be using logstash to dump this data from countriesdata.csv to elasticsearch. Start the elasticsearch and Kibana in your terminal and keep it running. We have to create the config file for logstash which will have details about the columns of the CSV file and also other details as shown in the logstash-config file given below βˆ’ input { file { path => "C:/kibanaproject/countriesdata.csv" start_position => "beginning" sincedb_path => "NUL" } } filter { csv { separator => "," columns => ["Country","Region","Population","Area"] } mutate {convert => ["Population", "integer"]} mutate {convert => ["Area", "integer"]} } output { elasticsearch { hosts => ["localhost:9200"] => "countriesdata-%{+dd.MM.YYYY}" } stdout {codec => json_lines } } In the config file, we have created 3 components βˆ’ We need to specify the path of the input file which in our case is a csv file. The path where the csv file is stored is given to the path field. Will have the csv component with separator used which in our case is comma, and also the columns available for our csv file. As logstash considers all the data coming in as string , in-case we want any column to be used as integer , float the same has to be specified using mutate as shown above. For output, we need to specify where we need to put the data. Here, in our case we are using elasticsearch. The data required to be given to the elasticsearch is the hosts where it is running, we have mentioned it as localhost. The next field in is index which we have given the name as countries-currentdate. We have to use the same index in Kibana once the data is updated in Elasticsearch. Save the above config file as logstash_countries.config. Note that we need to give the path of this config to logstash command in the next step. To load the data from the csv file to elasticsearch, we need to start the elasticsearch server βˆ’ Now, run http://localhost:9200 in the browser to confirm if elasticsearch is running successfully. We have elasticsearch running. Now go to the path where logstash is installed and run following command to upload the data to elasticsearch. > logstash -f logstash_countries.conf The above screen shows data loading from the CSV file to Elasticsearch. To know if we have the index created in Elasticsearch we can check same as follows βˆ’ We can see the countriesdata-28.12.2018 index created as shown above. The details of the index βˆ’ countries-28.12.2018 is as follows βˆ’ Note that the mapping details with properties are created when data is uploaded from logstash to elasticsearch. Currently, we have Kibana running on localhost, port 5601 βˆ’ http://localhost:5601. The UI of Kibana is shown here βˆ’ Note that we already have Kibana connected to Elasticsearch and we should be able to see index :countries-28.12.2018 inside Kibana. In the Kibana UI, click on Management Menu option on left side βˆ’ Now, click Index Management βˆ’ The indices present in Elasticsearch are displayed in index management. The index we are going to use in Kibana is countriesdata-28.12.2018. Thus, as we already have the elasticsearch index in Kibana, next will understand how to use the index in Kibana to visualize data in the form of pie chart, bar graph, line chart etc. Print Add Notes Bookmark this page
[ { "code": null, "e": 2358, "s": 2105, "text": "Kibana is an open source visualization tool mainly used to analyze a large volume of logs in the form of line graph, bar graph, pie charts, heatmaps etc. Kibana works in sync with Elasticsearch and Logstash which together forms the so called ELK stack." }, { "code": null, "e": 2493, "s": 2358, "text": "ELK stands for Elasticsearch, Logstash, and Kibana. ELK is one of the popular log\nmanagement platform used worldwide for log analysis." }, { "code": null, "e": 2512, "s": 2493, "text": "In the ELK stack βˆ’" }, { "code": null, "e": 2655, "s": 2512, "text": "Logstash extracts the logging data or other events from different input sources.\nIt processes the events and later stores it in Elasticsearch." }, { "code": null, "e": 2798, "s": 2655, "text": "Logstash extracts the logging data or other events from different input sources.\nIt processes the events and later stores it in Elasticsearch." }, { "code": null, "e": 2962, "s": 2798, "text": "Kibana is a visualization tool, which accesses the logs from Elasticsearch and is\nable to display to the user in the form of line graph, bar graph, pie charts etc." }, { "code": null, "e": 3126, "s": 2962, "text": "Kibana is a visualization tool, which accesses the logs from Elasticsearch and is\nable to display to the user in the form of line graph, bar graph, pie charts etc." }, { "code": null, "e": 3238, "s": 3126, "text": "In this tutorial, we will work closely with Kibana and Elasticsearch and visualize the data\nin different forms." }, { "code": null, "e": 3346, "s": 3238, "text": "In this chapter, let us understand how to work with ELK stack together. Besides, you will\nalso see how to βˆ’" }, { "code": null, "e": 3392, "s": 3346, "text": "Load CSV data from Logstash to Elasticsearch." }, { "code": null, "e": 3434, "s": 3392, "text": "Use indices from Elasticsearch in Kibana." }, { "code": null, "e": 3672, "s": 3434, "text": "We are going to use CSV data to upload data using Logstash to Elasticsearch. To work on\ndata analysis, we can get data from kaggle.com website. Kaggle.com site has all types of\ndata uploaded and users can use it to work on data analysis." }, { "code": null, "e": 3819, "s": 3672, "text": "We have taken the countries.csv data from here:\nhttps://www.kaggle.com/fernandol/countries-of-the-world. You can download the csv file\nand use it." }, { "code": null, "e": 3881, "s": 3819, "text": "The csv file which we are going to use has following details." }, { "code": null, "e": 3911, "s": 3881, "text": "File name βˆ’ countriesdata.csv" }, { "code": null, "e": 3960, "s": 3911, "text": "Columns βˆ’ \"Country\",\"Region\",\"Population\",\"Area\"" }, { "code": null, "e": 4094, "s": 3960, "text": "You can also create a dummy csv file and use it. We will be using logstash to dump this data from countriesdata.csv to elasticsearch." }, { "code": null, "e": 4346, "s": 4094, "text": "Start the elasticsearch and Kibana in your terminal and keep it running. We have to create\nthe config file for logstash which will have details about the columns of the CSV file and\nalso other details as shown in the logstash-config file given below βˆ’" }, { "code": null, "e": 4826, "s": 4346, "text": "input {\n file {\n path => \"C:/kibanaproject/countriesdata.csv\"\n start_position => \"beginning\"\n sincedb_path => \"NUL\"\n }\n}\nfilter {\n csv {\n separator => \",\"\n columns => [\"Country\",\"Region\",\"Population\",\"Area\"]\n }\n mutate {convert => [\"Population\", \"integer\"]}\n mutate {convert => [\"Area\", \"integer\"]}\n}\noutput {\n elasticsearch {\n hosts => [\"localhost:9200\"]\n => \"countriesdata-%{+dd.MM.YYYY}\"\n }\n stdout {codec => json_lines }\n}" }, { "code": null, "e": 4877, "s": 4826, "text": "In the config file, we have created 3 components βˆ’" }, { "code": null, "e": 5022, "s": 4877, "text": "We need to specify the path of the input file which in our case is a csv file. The path where\nthe csv file is stored is given to the path field." }, { "code": null, "e": 5319, "s": 5022, "text": "Will have the csv component with separator used which in our case is comma, and also the columns available for our csv file. As logstash considers all the data coming in as string , in-case we want any column to be used as integer , float the same has to be specified using mutate as shown above." }, { "code": null, "e": 5712, "s": 5319, "text": "For output, we need to specify where we need to put the data. Here, in our case we are using elasticsearch. The data required to be given to the elasticsearch is the hosts where it is running, we have mentioned it as localhost. The next field in is index which we have given the name as countries-currentdate. We have to use the same index in Kibana once the data is updated in Elasticsearch." }, { "code": null, "e": 5857, "s": 5712, "text": "Save the above config file as logstash_countries.config. Note that we need to give the path of this config to logstash command in the next step." }, { "code": null, "e": 5954, "s": 5857, "text": "To load the data from the csv file to elasticsearch, we need to start the elasticsearch server βˆ’" }, { "code": null, "e": 6053, "s": 5954, "text": "Now, run http://localhost:9200 in the browser to confirm if elasticsearch is running\nsuccessfully." }, { "code": null, "e": 6194, "s": 6053, "text": "We have elasticsearch running. Now go to the path where logstash is installed and run following command to upload the data to elasticsearch." }, { "code": null, "e": 6233, "s": 6194, "text": "> logstash -f logstash_countries.conf\n" }, { "code": null, "e": 6390, "s": 6233, "text": "The above screen shows data loading from the CSV file to Elasticsearch. To know if we have the index created in Elasticsearch we can check same as follows βˆ’" }, { "code": null, "e": 6460, "s": 6390, "text": "We can see the countriesdata-28.12.2018 index created as shown above." }, { "code": null, "e": 6524, "s": 6460, "text": "The details of the index βˆ’ countries-28.12.2018 is as follows βˆ’" }, { "code": null, "e": 6636, "s": 6524, "text": "Note that the mapping details with properties are created when data is uploaded from logstash to elasticsearch." }, { "code": null, "e": 6752, "s": 6636, "text": "Currently, we have Kibana running on localhost, port 5601 βˆ’ http://localhost:5601. The UI of Kibana is shown here βˆ’" }, { "code": null, "e": 6884, "s": 6752, "text": "Note that we already have Kibana connected to Elasticsearch and we should be able to see\nindex :countries-28.12.2018 inside Kibana." }, { "code": null, "e": 6949, "s": 6884, "text": "In the Kibana UI, click on Management Menu option on left side βˆ’" }, { "code": null, "e": 6979, "s": 6949, "text": "Now, click Index Management βˆ’" }, { "code": null, "e": 7120, "s": 6979, "text": "The indices present in Elasticsearch are displayed in index management. The index we are going to use in Kibana is countriesdata-28.12.2018." }, { "code": null, "e": 7303, "s": 7120, "text": "Thus, as we already have the elasticsearch index in Kibana, next will understand how to use the index in Kibana to visualize data in the form of pie chart, bar graph, line chart etc." }, { "code": null, "e": 7310, "s": 7303, "text": " Print" }, { "code": null, "e": 7321, "s": 7310, "text": " Add Notes" } ]