title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
Java Program for Longest Increasing Subsequence | 08 Jun, 2022
The Longest Increasing Subsequence (LIS) problem is to find the length of the longest subsequence of a given sequence such that all elements of the subsequence are sorted in increasing order. For example, the length of LIS for {10, 22, 9, 33, 21, 50, 41, 60, 80} is 6 and LIS is {10, 22, 33, 50, 60, 80}. More Examples:
Input : arr[] = {3, 10, 2, 1, 20}
Output : Length of LIS = 3
The longest increasing subsequence is 3, 10, 20
Input : arr[] = {3, 2}
Output : Length of LIS = 1
The longest increasing subsequences are {3} and {2}
Input : arr[] = {50, 3, 10, 7, 40, 80}
Output : Length of LIS = 4
The longest increasing subsequence is {3, 7, 40, 80}
Optimal Substructure: Let arr[0..n-1] be the input array and L(i) be the length of the LIS ending at index i such that arr[i] is the last element of the LIS. Then, L(i) can be recursively written as: L(i) = 1 + max( L(j) ) where 0 < j < i and arr[j] < arr[i]; or L(i) = 1, if no such j exists. To find the LIS for a given array, we need to return max(L(i)) where 0 < i < n. Thus, we see the LIS problem satisfies the optimal substructure property as the main problem can be solved using solutions to subproblems. Following is a simple recursive implementation of the LIS problem. It follows the recursive structure discussed above.
Java
/* A Naive Java Program for LIS Implementation */class LIS { static int max_ref; // stores the LIS /* To make use of recursive calls, this function must return two things: 1) Length of LIS ending with element arr[n-1]. We use max_ending_here for this purpose 2) Overall maximum as the LIS may end with an element before arr[n-1] max_ref is used this purpose. The value of LIS of full array of size n is stored in *max_ref which is our final result */ static int _lis(int arr[], int n) { // base case if (n == 1) return 1; // 'max_ending_here' is length of LIS ending with arr[n-1] int res, max_ending_here = 1; /* Recursively get all LIS ending with arr[0], arr[1] ... arr[n-2]. If arr[i-1] is smaller than arr[n-1], and max ending with arr[n-1] needs to be updated, then update it */ for (int i = 1; i < n; i++) { res = _lis(arr, i); if (arr[i - 1] < arr[n - 1] && res + 1 > max_ending_here) max_ending_here = res + 1; } // Compare max_ending_here with the overall max. And // update the overall max if needed if (max_ref < max_ending_here) max_ref = max_ending_here; // Return length of LIS ending with arr[n-1] return max_ending_here; } // The wrapper function for _lis() static int lis(int arr[], int n) { // The max variable holds the result max_ref = 1; // The function _lis() stores its result in max _lis(arr, n); // returns max return max_ref; } // driver program to test above functions public static void main(String args[]) { int arr[] = { 10, 22, 9, 33, 21, 50, 41, 60 }; int n = arr.length; System.out.println("Length of lis is " + lis(arr, n) + "\n"); }}/*This code is contributed by Rajat Mishra*/
Length of lis is 5
Time Complexity: O(2n)
Auxiliary Space: O(1)
Overlapping Subproblems: Considering the above implementation, following is recursion tree for an array of size 4. lis(n) gives us the length of LIS for arr[].
lis(4)
/ |
lis(3) lis(2) lis(1)
/ /
lis(2) lis(1) lis(1)
/
lis(1)
We can see that there are many subproblems which are solved again and again. So this problem has Overlapping Substructure property and recomputation of same subproblems can be avoided by either using Memoization or Tabulation. Following is a tabluated implementation for the LIS problem.
Java
/* Dynamic Programming Java implementation of LIS problem */ class LIS { /* lis() returns the length of the longest increasing subsequence in arr[] of size n */ static int lis(int arr[], int n) { int lis[] = new int[n]; int i, j, max = 0; /* Initialize LIS values for all indexes */ for (i = 0; i < n; i++) lis[i] = 1; /* Compute optimized LIS values in bottom up manner */ for (i = 1; i < n; i++) for (j = 0; j < i; j++) if (arr[i] > arr[j] && lis[i] < lis[j] + 1) lis[i] = lis[j] + 1; /* Pick maximum of all LIS values */ for (i = 0; i < n; i++) if (max < lis[i]) max = lis[i]; return max; } public static void main(String args[]) { int arr[] = { 10, 22, 9, 33, 21, 50, 41, 60 }; int n = arr.length; System.out.println("Length of lis is " + lis(arr, n) + "\n"); }}/*This code is contributed by Rajat Mishra*/
Length of lis is 5
Time Complexity: O(n2)
Auxiliary Space: O(n)
Please refer complete article on Dynamic Programming | Set 3 (Longest Increasing Subsequence) for more details!
chandramauliguptach
LIS
Dynamic Programming
Java Programs
Dynamic Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n08 Jun, 2022"
},
{
"code": null,
"e": 375,
"s": 54,
"text": "The Longest Increasing Subsequence (LIS) problem is to find the length of the longest subsequence of a given sequence such that all elements of the subsequence are sorted in increasing order. For example, the length of LIS for {10, 22, 9, 33, 21, 50, 41, 60, 80} is 6 and LIS is {10, 22, 33, 50, 60, 80}. More Examples:"
},
{
"code": null,
"e": 709,
"s": 375,
"text": "Input : arr[] = {3, 10, 2, 1, 20}\nOutput : Length of LIS = 3\nThe longest increasing subsequence is 3, 10, 20\n\nInput : arr[] = {3, 2}\nOutput : Length of LIS = 1\nThe longest increasing subsequences are {3} and {2}\n\nInput : arr[] = {50, 3, 10, 7, 40, 80}\nOutput : Length of LIS = 4\nThe longest increasing subsequence is {3, 7, 40, 80}"
},
{
"code": null,
"e": 1342,
"s": 709,
"text": "Optimal Substructure: Let arr[0..n-1] be the input array and L(i) be the length of the LIS ending at index i such that arr[i] is the last element of the LIS. Then, L(i) can be recursively written as: L(i) = 1 + max( L(j) ) where 0 < j < i and arr[j] < arr[i]; or L(i) = 1, if no such j exists. To find the LIS for a given array, we need to return max(L(i)) where 0 < i < n. Thus, we see the LIS problem satisfies the optimal substructure property as the main problem can be solved using solutions to subproblems. Following is a simple recursive implementation of the LIS problem. It follows the recursive structure discussed above. "
},
{
"code": null,
"e": 1347,
"s": 1342,
"text": "Java"
},
{
"code": "/* A Naive Java Program for LIS Implementation */class LIS { static int max_ref; // stores the LIS /* To make use of recursive calls, this function must return two things: 1) Length of LIS ending with element arr[n-1]. We use max_ending_here for this purpose 2) Overall maximum as the LIS may end with an element before arr[n-1] max_ref is used this purpose. The value of LIS of full array of size n is stored in *max_ref which is our final result */ static int _lis(int arr[], int n) { // base case if (n == 1) return 1; // 'max_ending_here' is length of LIS ending with arr[n-1] int res, max_ending_here = 1; /* Recursively get all LIS ending with arr[0], arr[1] ... arr[n-2]. If arr[i-1] is smaller than arr[n-1], and max ending with arr[n-1] needs to be updated, then update it */ for (int i = 1; i < n; i++) { res = _lis(arr, i); if (arr[i - 1] < arr[n - 1] && res + 1 > max_ending_here) max_ending_here = res + 1; } // Compare max_ending_here with the overall max. And // update the overall max if needed if (max_ref < max_ending_here) max_ref = max_ending_here; // Return length of LIS ending with arr[n-1] return max_ending_here; } // The wrapper function for _lis() static int lis(int arr[], int n) { // The max variable holds the result max_ref = 1; // The function _lis() stores its result in max _lis(arr, n); // returns max return max_ref; } // driver program to test above functions public static void main(String args[]) { int arr[] = { 10, 22, 9, 33, 21, 50, 41, 60 }; int n = arr.length; System.out.println(\"Length of lis is \" + lis(arr, n) + \"\\n\"); }}/*This code is contributed by Rajat Mishra*/",
"e": 3293,
"s": 1347,
"text": null
},
{
"code": null,
"e": 3312,
"s": 3293,
"text": "Length of lis is 5"
},
{
"code": null,
"e": 3335,
"s": 3312,
"text": "Time Complexity: O(2n)"
},
{
"code": null,
"e": 3357,
"s": 3335,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 3517,
"s": 3357,
"text": "Overlapping Subproblems: Considering the above implementation, following is recursion tree for an array of size 4. lis(n) gives us the length of LIS for arr[]."
},
{
"code": null,
"e": 3649,
"s": 3517,
"text": " lis(4)\n / | \n lis(3) lis(2) lis(1)\n / /\n lis(2) lis(1) lis(1)\n /\nlis(1)"
},
{
"code": null,
"e": 3938,
"s": 3649,
"text": "We can see that there are many subproblems which are solved again and again. So this problem has Overlapping Substructure property and recomputation of same subproblems can be avoided by either using Memoization or Tabulation. Following is a tabluated implementation for the LIS problem. "
},
{
"code": null,
"e": 3943,
"s": 3938,
"text": "Java"
},
{
"code": "/* Dynamic Programming Java implementation of LIS problem */ class LIS { /* lis() returns the length of the longest increasing subsequence in arr[] of size n */ static int lis(int arr[], int n) { int lis[] = new int[n]; int i, j, max = 0; /* Initialize LIS values for all indexes */ for (i = 0; i < n; i++) lis[i] = 1; /* Compute optimized LIS values in bottom up manner */ for (i = 1; i < n; i++) for (j = 0; j < i; j++) if (arr[i] > arr[j] && lis[i] < lis[j] + 1) lis[i] = lis[j] + 1; /* Pick maximum of all LIS values */ for (i = 0; i < n; i++) if (max < lis[i]) max = lis[i]; return max; } public static void main(String args[]) { int arr[] = { 10, 22, 9, 33, 21, 50, 41, 60 }; int n = arr.length; System.out.println(\"Length of lis is \" + lis(arr, n) + \"\\n\"); }}/*This code is contributed by Rajat Mishra*/",
"e": 4952,
"s": 3943,
"text": null
},
{
"code": null,
"e": 4971,
"s": 4952,
"text": "Length of lis is 5"
},
{
"code": null,
"e": 4994,
"s": 4971,
"text": "Time Complexity: O(n2)"
},
{
"code": null,
"e": 5016,
"s": 4994,
"text": "Auxiliary Space: O(n)"
},
{
"code": null,
"e": 5128,
"s": 5016,
"text": "Please refer complete article on Dynamic Programming | Set 3 (Longest Increasing Subsequence) for more details!"
},
{
"code": null,
"e": 5148,
"s": 5128,
"text": "chandramauliguptach"
},
{
"code": null,
"e": 5152,
"s": 5148,
"text": "LIS"
},
{
"code": null,
"e": 5172,
"s": 5152,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 5186,
"s": 5172,
"text": "Java Programs"
},
{
"code": null,
"e": 5206,
"s": 5186,
"text": "Dynamic Programming"
}
] |
Variable initialization in C++ | Variables are the names given by the user. A datatype is also used to declare and initialize a variable which allocates memory to that variable. There are several datatypes like int, char, float etc. to allocate the memory to that variable.
There are two ways to initialize the variable. One is static initialization in which the variable is assigned a value in the program and another is dynamic initialization in which the variables is assigned a value at the run time.
The following is the syntax of variable initialization.
datatype variable_name = value;
Here,
datatype − The datatype of variable like int, char, float etc.
variable_name − This is the name of variable given by user.
value − Any value to initialize the variable. By default, it is zero.
The following is an example of variable initialization.
Live Demo
#include <iostream>
using namespace std;
int main() {
int a = 20;
int b;
cout << "The value of variable a : "<< a; // static initialization
cout << "\nEnter the value of variable b : "; // dynamic initialization
cin >> b;
cout << "\nThe value of variable b : "<< b;
return 0;
}
The value of variable a : 20
Enter the value of variable b : 28
The value of variable b : 28
In the above program, two variables are declared a and b.
int a = 20;
int b;
The variable a is initialized with a value in the program while the variable b is initialized dynamically.
cout << "The value of variable a : "<< a; // static initialization
cout << "\nEnter the value of variable b : "; // dynamic initialization
cin >> b;
cout << "\nThe value of variable b : "<< b; | [
{
"code": null,
"e": 1428,
"s": 1187,
"text": "Variables are the names given by the user. A datatype is also used to declare and initialize a variable which allocates memory to that variable. There are several datatypes like int, char, float etc. to allocate the memory to that variable."
},
{
"code": null,
"e": 1659,
"s": 1428,
"text": "There are two ways to initialize the variable. One is static initialization in which the variable is assigned a value in the program and another is dynamic initialization in which the variables is assigned a value at the run time."
},
{
"code": null,
"e": 1715,
"s": 1659,
"text": "The following is the syntax of variable initialization."
},
{
"code": null,
"e": 1747,
"s": 1715,
"text": "datatype variable_name = value;"
},
{
"code": null,
"e": 1753,
"s": 1747,
"text": "Here,"
},
{
"code": null,
"e": 1816,
"s": 1753,
"text": "datatype − The datatype of variable like int, char, float etc."
},
{
"code": null,
"e": 1876,
"s": 1816,
"text": "variable_name − This is the name of variable given by user."
},
{
"code": null,
"e": 1946,
"s": 1876,
"text": "value − Any value to initialize the variable. By default, it is zero."
},
{
"code": null,
"e": 2002,
"s": 1946,
"text": "The following is an example of variable initialization."
},
{
"code": null,
"e": 2013,
"s": 2002,
"text": " Live Demo"
},
{
"code": null,
"e": 2312,
"s": 2013,
"text": "#include <iostream>\nusing namespace std;\nint main() {\n int a = 20;\n int b;\n cout << \"The value of variable a : \"<< a; // static initialization\n cout << \"\\nEnter the value of variable b : \"; // dynamic initialization\n cin >> b;\n cout << \"\\nThe value of variable b : \"<< b;\n return 0;\n}"
},
{
"code": null,
"e": 2405,
"s": 2312,
"text": "The value of variable a : 20\nEnter the value of variable b : 28\nThe value of variable b : 28"
},
{
"code": null,
"e": 2463,
"s": 2405,
"text": "In the above program, two variables are declared a and b."
},
{
"code": null,
"e": 2482,
"s": 2463,
"text": "int a = 20;\nint b;"
},
{
"code": null,
"e": 2589,
"s": 2482,
"text": "The variable a is initialized with a value in the program while the variable b is initialized dynamically."
},
{
"code": null,
"e": 2782,
"s": 2589,
"text": "cout << \"The value of variable a : \"<< a; // static initialization\ncout << \"\\nEnter the value of variable b : \"; // dynamic initialization\ncin >> b;\ncout << \"\\nThe value of variable b : \"<< b;"
}
] |
The Initialize Method in Ruby | 25 Sep, 2019
The initialize method is useful when we want to initialize some class variables at the time of object creation. The initialize method is part of the object-creation process in Ruby and it allows us to set the initial values for an object.
Below are some points about Initialize :
We can define default argument.
It will always return a new object so return keyword is not used inside initialize method
Defining initialize keyword is not necessary if our class doesn’t require any arguments.
If we try to pass arguments into new and if we don’t define initialize we are going to get an error.
Syntax:
def initialize(argument1, argument2, .....)
Example :
# Ruby program of Initialize methodclass Geeks # Method with initialize keyword def initialize(name) endend
Output :
=> :initialize
In above example, we add a method called initialize to the class, method have a single argument name. using initialize method will initialize a object.
Example :
# Ruby program of Initialize methodclass Rectangle # Method with initialize keyword def initialize(x, y) # Initialize variable @x = x @y = y endend # create a new Rectangle instance by calling Rectangle.new(10, 20)
Output :
#<Rectangle:0x0000555e7b1ba0b0 @x=10, @y=20>
In above example, Initialize variable are accessed using the @ operator within the class but to access them outside of the class we will use public methods.
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Make a Custom Array of Hashes in Ruby?
Ruby | Enumerator each_with_index function
Ruby | unless Statement and unless Modifier
Ruby For Beginners
Ruby | Array class find_index() operation
Ruby | String concat Method
Ruby on Rails Introduction
Ruby | Types of Variables
Ruby | Array shift() function | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n25 Sep, 2019"
},
{
"code": null,
"e": 291,
"s": 52,
"text": "The initialize method is useful when we want to initialize some class variables at the time of object creation. The initialize method is part of the object-creation process in Ruby and it allows us to set the initial values for an object."
},
{
"code": null,
"e": 332,
"s": 291,
"text": "Below are some points about Initialize :"
},
{
"code": null,
"e": 364,
"s": 332,
"text": "We can define default argument."
},
{
"code": null,
"e": 454,
"s": 364,
"text": "It will always return a new object so return keyword is not used inside initialize method"
},
{
"code": null,
"e": 543,
"s": 454,
"text": "Defining initialize keyword is not necessary if our class doesn’t require any arguments."
},
{
"code": null,
"e": 644,
"s": 543,
"text": "If we try to pass arguments into new and if we don’t define initialize we are going to get an error."
},
{
"code": null,
"e": 652,
"s": 644,
"text": "Syntax:"
},
{
"code": null,
"e": 696,
"s": 652,
"text": "def initialize(argument1, argument2, .....)"
},
{
"code": null,
"e": 706,
"s": 696,
"text": "Example :"
},
{
"code": "# Ruby program of Initialize methodclass Geeks # Method with initialize keyword def initialize(name) endend",
"e": 819,
"s": 706,
"text": null
},
{
"code": null,
"e": 828,
"s": 819,
"text": "Output :"
},
{
"code": null,
"e": 843,
"s": 828,
"text": "=> :initialize"
},
{
"code": null,
"e": 995,
"s": 843,
"text": "In above example, we add a method called initialize to the class, method have a single argument name. using initialize method will initialize a object."
},
{
"code": null,
"e": 1005,
"s": 995,
"text": "Example :"
},
{
"code": "# Ruby program of Initialize methodclass Rectangle # Method with initialize keyword def initialize(x, y) # Initialize variable @x = x @y = y endend # create a new Rectangle instance by calling Rectangle.new(10, 20)",
"e": 1237,
"s": 1005,
"text": null
},
{
"code": null,
"e": 1246,
"s": 1237,
"text": "Output :"
},
{
"code": null,
"e": 1291,
"s": 1246,
"text": "#<Rectangle:0x0000555e7b1ba0b0 @x=10, @y=20>"
},
{
"code": null,
"e": 1448,
"s": 1291,
"text": "In above example, Initialize variable are accessed using the @ operator within the class but to access them outside of the class we will use public methods."
},
{
"code": null,
"e": 1453,
"s": 1448,
"text": "Ruby"
},
{
"code": null,
"e": 1551,
"s": 1453,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1597,
"s": 1551,
"text": "How to Make a Custom Array of Hashes in Ruby?"
},
{
"code": null,
"e": 1640,
"s": 1597,
"text": "Ruby | Enumerator each_with_index function"
},
{
"code": null,
"e": 1684,
"s": 1640,
"text": "Ruby | unless Statement and unless Modifier"
},
{
"code": null,
"e": 1703,
"s": 1684,
"text": "Ruby For Beginners"
},
{
"code": null,
"e": 1745,
"s": 1703,
"text": "Ruby | Array class find_index() operation"
},
{
"code": null,
"e": 1773,
"s": 1745,
"text": "Ruby | String concat Method"
},
{
"code": null,
"e": 1800,
"s": 1773,
"text": "Ruby on Rails Introduction"
},
{
"code": null,
"e": 1826,
"s": 1800,
"text": "Ruby | Types of Variables"
}
] |
Spring MVC - Generate PDF Example | The following example shows how to generate a PDF using the Spring Web MVC Framework. To start with, let us have a working Eclipse IDE in place and adhere to the following steps to develop a Dynamic Form based Web Application using the Spring Web Framework.
package com.tutorialspoint;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
public class PDFController extends AbstractController {
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request,
HttpServletResponse response) throws Exception {
//user data
Map<String,String> userData = new HashMap<String,String>();
userData.put("1", "Mahesh");
userData.put("2", "Suresh");
userData.put("3", "Ramesh");
userData.put("4", "Naresh");
return new ModelAndView("UserSummary","userData",userData);
}
}
package com.tutorialspoint;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.view.document.AbstractPdfView;
import com.lowagie.text.Document;
import com.lowagie.text.Table;
import com.lowagie.text.pdf.PdfWriter;
public class UserPDFView extends AbstractPdfView {
protected void buildPdfDocument(Map<String, Object> model, Document document,
PdfWriter pdfWriter, HttpServletRequest request, HttpServletResponse response)
throws Exception {
Map<String,String> userData = (Map<String,String>) model.get("userData");
Table table = new Table(2);
table.addCell("Roll No");
table.addCell("Name");
for (Map.Entry<String, String> entry : userData.entrySet()) {
table.addCell(entry.getKey());
table.addCell(entry.getValue());
}
document.add(table);
}
}
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:context = "http://www.springframework.org/schema/context"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc = "http://www.springframework.org/schema/mvc"
xsi:schemaLocation = "
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<bean class = "org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping" />
<bean class = "com.tutorialspoint.PDFController" />
<bean class = "org.springframework.web.servlet.view.XmlViewResolver">
<property name = "location">
<value>/WEB-INF/views.xml</value>
</property>
</bean>
</beans>
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:context = "http://www.springframework.org/schema/context"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean id = "UserSummary" class = "com.tutorialspoint.UserPDFView"></bean>
</beans>
Here, we have created a PDFController and UserPDFView. iText library deals with the PDF file formats and will convert the data to a PDF document.
Once you are done with creating source and configuration files, export your application. Right click on your application, use Export → WAR File option and save the TestWeb.war file in Tomcat's webapps folder.
Now, start the Tomcat server and make sure you are able to access other webpages from the webapps folder using a standard browser. We can also try the following URL − http://localhost:8080/TestWeb/pdf and if all goes as planned, we will see the following screen. | [
{
"code": null,
"e": 3183,
"s": 2925,
"text": "The following example shows how to generate a PDF using the Spring Web MVC Framework. To start with, let us have a working Eclipse IDE in place and adhere to the following steps to develop a Dynamic Form based Web Application using the Spring Web Framework."
},
{
"code": null,
"e": 3971,
"s": 3183,
"text": "package com.tutorialspoint;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\n\nimport org.springframework.web.servlet.ModelAndView;\nimport org.springframework.web.servlet.mvc.AbstractController;\n\npublic class PDFController extends AbstractController {\n\n @Override\n protected ModelAndView handleRequestInternal(HttpServletRequest request,\n HttpServletResponse response) throws Exception {\n //user data\n Map<String,String> userData = new HashMap<String,String>();\n userData.put(\"1\", \"Mahesh\");\n userData.put(\"2\", \"Suresh\");\n userData.put(\"3\", \"Ramesh\");\n userData.put(\"4\", \"Naresh\");\n return new ModelAndView(\"UserSummary\",\"userData\",userData);\n }\n}\n"
},
{
"code": null,
"e": 4905,
"s": 3971,
"text": "package com.tutorialspoint;\n\nimport java.util.Map;\n\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\n\nimport org.springframework.web.servlet.view.document.AbstractPdfView;\n\nimport com.lowagie.text.Document;\nimport com.lowagie.text.Table;\nimport com.lowagie.text.pdf.PdfWriter;\n\npublic class UserPDFView extends AbstractPdfView {\n\n protected void buildPdfDocument(Map<String, Object> model, Document document,\n PdfWriter pdfWriter, HttpServletRequest request, HttpServletResponse response)\n throws Exception {\n Map<String,String> userData = (Map<String,String>) model.get(\"userData\");\n\n Table table = new Table(2);\n table.addCell(\"Roll No\");\n table.addCell(\"Name\");\n\n for (Map.Entry<String, String> entry : userData.entrySet()) {\n table.addCell(entry.getKey());\n table.addCell(entry.getValue());\n }\n document.add(table);\n }\n}"
},
{
"code": null,
"e": 5879,
"s": 4905,
"text": "<beans xmlns = \"http://www.springframework.org/schema/beans\"\n xmlns:context = \"http://www.springframework.org/schema/context\" \n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xmlns:mvc = \"http://www.springframework.org/schema/mvc\"\n xsi:schemaLocation = \"\n http://www.springframework.org/schema/beans \n http://www.springframework.org/schema/beans/spring-beans-3.0.xsd\n http://www.springframework.org/schema/context \n http://www.springframework.org/schema/context/spring-context-3.0.xsd\n http://www.springframework.org/schema/mvc\n http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd\">\n <bean class = \"org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping\" />\n\n <bean class = \"com.tutorialspoint.PDFController\" />\n\n <bean class = \"org.springframework.web.servlet.view.XmlViewResolver\">\n <property name = \"location\">\n <value>/WEB-INF/views.xml</value>\n </property>\n </bean>\n</beans>"
},
{
"code": null,
"e": 6423,
"s": 5879,
"text": "<beans xmlns = \"http://www.springframework.org/schema/beans\"\n xmlns:context = \"http://www.springframework.org/schema/context\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"\n http://www.springframework.org/schema/beans \n http://www.springframework.org/schema/beans/spring-beans-3.0.xsd\n http://www.springframework.org/schema/context \n http://www.springframework.org/schema/context/spring-context-3.0.xsd\">\n\n <bean id = \"UserSummary\" class = \"com.tutorialspoint.UserPDFView\"></bean>\n</beans>"
},
{
"code": null,
"e": 6569,
"s": 6423,
"text": "Here, we have created a PDFController and UserPDFView. iText library deals with the PDF file formats and will convert the data to a PDF document."
},
{
"code": null,
"e": 6778,
"s": 6569,
"text": "Once you are done with creating source and configuration files, export your application. Right click on your application, use Export → WAR File option and save the TestWeb.war file in Tomcat's webapps folder."
}
] |
PHP | strtoupper() Function | 08 Mar, 2018
The strtoupper() function is used to convert a string into uppercase. This function takes a string as parameter and converts all the lowercase english alphabets present in the string to uppercase. All other numeric characters or special characters in the string remains unchanged.
Syntax:
string strtoupper ( $string )
Parameter: The only parameter to this function is a string that is to be converted to upper case.
Return value: This function returns a string in which all the alphabets are uppercase.
Examples:
Input : $str = "GeeksForGeeks"
strtoupper($str)
Output: GEEKSFORGEEKS
Input : $str = "going BACK he SAW THIS 123$#%"
strtoupper($str)
Output: GOING BACK HE SAW THIS 123$#%
Below programs illustrate the strtoupper() function in PHP:
Program 1
<?php // original string$str = "GeeksForGeeks"; // string converted to upper case$resStr = strtoupper($str); print_r($resStr); ?>
Output:
GEEKSFORGEEKS
Program 2
<?php // original string$str = "going BACK he SAW THIS 123$#%"; // string to upper case$resStr = strtoupper($str); print_r($resStr); ?>
Output:
GOING BACK HE SAW THIS 123$#%
Reference:http://php.net/manual/en/function.strtoupper.php
PHP-function
PHP-string
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to Upload Image into Database and Display it using PHP ?
How to check whether an array is empty using PHP?
PHP | Converting string to Date and DateTime
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n08 Mar, 2018"
},
{
"code": null,
"e": 309,
"s": 28,
"text": "The strtoupper() function is used to convert a string into uppercase. This function takes a string as parameter and converts all the lowercase english alphabets present in the string to uppercase. All other numeric characters or special characters in the string remains unchanged."
},
{
"code": null,
"e": 317,
"s": 309,
"text": "Syntax:"
},
{
"code": null,
"e": 348,
"s": 317,
"text": "string strtoupper ( $string )\n"
},
{
"code": null,
"e": 446,
"s": 348,
"text": "Parameter: The only parameter to this function is a string that is to be converted to upper case."
},
{
"code": null,
"e": 533,
"s": 446,
"text": "Return value: This function returns a string in which all the alphabets are uppercase."
},
{
"code": null,
"e": 543,
"s": 533,
"text": "Examples:"
},
{
"code": null,
"e": 735,
"s": 543,
"text": "Input : $str = \"GeeksForGeeks\"\n strtoupper($str)\nOutput: GEEKSFORGEEKS\n\nInput : $str = \"going BACK he SAW THIS 123$#%\"\n strtoupper($str)\nOutput: GOING BACK HE SAW THIS 123$#%\n"
},
{
"code": null,
"e": 795,
"s": 735,
"text": "Below programs illustrate the strtoupper() function in PHP:"
},
{
"code": null,
"e": 805,
"s": 795,
"text": "Program 1"
},
{
"code": "<?php // original string$str = \"GeeksForGeeks\"; // string converted to upper case$resStr = strtoupper($str); print_r($resStr); ?>",
"e": 939,
"s": 805,
"text": null
},
{
"code": null,
"e": 947,
"s": 939,
"text": "Output:"
},
{
"code": null,
"e": 962,
"s": 947,
"text": "GEEKSFORGEEKS\n"
},
{
"code": null,
"e": 972,
"s": 962,
"text": "Program 2"
},
{
"code": "<?php // original string$str = \"going BACK he SAW THIS 123$#%\"; // string to upper case$resStr = strtoupper($str); print_r($resStr); ?>",
"e": 1112,
"s": 972,
"text": null
},
{
"code": null,
"e": 1120,
"s": 1112,
"text": "Output:"
},
{
"code": null,
"e": 1151,
"s": 1120,
"text": "GOING BACK HE SAW THIS 123$#%\n"
},
{
"code": null,
"e": 1210,
"s": 1151,
"text": "Reference:http://php.net/manual/en/function.strtoupper.php"
},
{
"code": null,
"e": 1223,
"s": 1210,
"text": "PHP-function"
},
{
"code": null,
"e": 1234,
"s": 1223,
"text": "PHP-string"
},
{
"code": null,
"e": 1238,
"s": 1234,
"text": "PHP"
},
{
"code": null,
"e": 1255,
"s": 1238,
"text": "Web Technologies"
},
{
"code": null,
"e": 1259,
"s": 1255,
"text": "PHP"
},
{
"code": null,
"e": 1357,
"s": 1259,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1407,
"s": 1357,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 1447,
"s": 1407,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 1508,
"s": 1447,
"text": "How to Upload Image into Database and Display it using PHP ?"
},
{
"code": null,
"e": 1558,
"s": 1508,
"text": "How to check whether an array is empty using PHP?"
},
{
"code": null,
"e": 1603,
"s": 1558,
"text": "PHP | Converting string to Date and DateTime"
},
{
"code": null,
"e": 1665,
"s": 1603,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 1698,
"s": 1665,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 1759,
"s": 1698,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1809,
"s": 1759,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Java Program to Generate Harmonic Series | 22 Jun, 2021
Harmonic series is the inverse of an arithmetic progression. In general, the terms in a harmonic progression can be denoted as
h1 = 1/a, h2 = 1/(a+d), h3 = 1/(a+2d), h4 = 1/(a+3d), ................., hn = 1/(a+nd).
Where h is the harmonic series, a is arithmetic progression and d is the common difference between arithmetic progression and n is the nth term.
Example 1: (Using while loop)
Java
// Java Program to Generate Harmonic Series class HarmonicSeries { // this is a main function public static void main(String args[]) { // num is the number of values we want in a series int num = 5; double result = 0.0; System.out.println("The harmonic series is: "); // printing the harmonic series till num value // using while loop while (num > 0) { // calculating harmonic values result = result + (double)1 / num; // after calculating harmonic value // decrementing num by 1 which means the common // difference is 1 num--; System.out.print(result + ", "); } }}
The harmonic series is:
0.2, 0.45, 0.7833333333333333, 1.2833333333333332, 2.283333333333333,
Example 2: (Using for loop)
Java
// Java Program to Generate Harmonic Series class HarmonicSeries { // this is a main function public static void main(String args[]) { // num is the number of values we want in a series int num = 5; double result = 0.0; System.out.println("The harmonic series is: "); // printing the harmonic series till num value // using for loop for (int i = num; i > 0; i--) { // calculating harmonic values result = result + (double)1 / i; System.out.print(result + ", "); } }}
The harmonic series is:
0.2, 0.45, 0.7833333333333333, 1.2833333333333332, 2.283333333333333,
Example 3:
Java
// Java Program to Generate Harmonic Series // importing necessary java packagesimport java.util.Scanner;import java.lang.*; class HarmonicSeries { // this is a main function public static void main(String args[]) { // scanner class is a pre-defined class in java // for taking input from keyboard Scanner in = new Scanner(System.in); System.out.print("Enter Number: "); // storing input value in num int num = in.nextInt(); double result = 0.0; System.out.println("The harmonic series is: "); // printing the harmonic series till num value // using for loop for (int i = num; i > 0; i--) { // calculating harmonic values result = result + (double)1 / i; System.out.print(result + ", "); } }}
Output
$ javac HarmonicSeries.java
$ java HarmonicSeries
Enter Number: 5
The harmonic series is:
0.2, 0.45, 0.7833333333333333, 1.2833333333333332, 2.283333333333333
$ javac HarmonicSeries.java
$ java HarmonicSeries
Enter Number: 6
The harmonic series is:
0.16666666666666666, 0.3666666666666667, 0.6166666666666667, 0.95, 1.45, 2.45
arorakashish0911
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": 28,
"s": 0,
"text": "\n22 Jun, 2021"
},
{
"code": null,
"e": 155,
"s": 28,
"text": "Harmonic series is the inverse of an arithmetic progression. In general, the terms in a harmonic progression can be denoted as"
},
{
"code": null,
"e": 245,
"s": 155,
"text": "h1 = 1/a, h2 = 1/(a+d), h3 = 1/(a+2d), h4 = 1/(a+3d), ................., hn = 1/(a+nd)."
},
{
"code": null,
"e": 390,
"s": 245,
"text": "Where h is the harmonic series, a is arithmetic progression and d is the common difference between arithmetic progression and n is the nth term."
},
{
"code": null,
"e": 420,
"s": 390,
"text": "Example 1: (Using while loop)"
},
{
"code": null,
"e": 425,
"s": 420,
"text": "Java"
},
{
"code": "// Java Program to Generate Harmonic Series class HarmonicSeries { // this is a main function public static void main(String args[]) { // num is the number of values we want in a series int num = 5; double result = 0.0; System.out.println(\"The harmonic series is: \"); // printing the harmonic series till num value // using while loop while (num > 0) { // calculating harmonic values result = result + (double)1 / num; // after calculating harmonic value // decrementing num by 1 which means the common // difference is 1 num--; System.out.print(result + \", \"); } }}",
"e": 1143,
"s": 425,
"text": null
},
{
"code": null,
"e": 1238,
"s": 1143,
"text": "The harmonic series is: \n0.2, 0.45, 0.7833333333333333, 1.2833333333333332, 2.283333333333333,"
},
{
"code": null,
"e": 1267,
"s": 1238,
"text": "Example 2: (Using for loop) "
},
{
"code": null,
"e": 1272,
"s": 1267,
"text": "Java"
},
{
"code": "// Java Program to Generate Harmonic Series class HarmonicSeries { // this is a main function public static void main(String args[]) { // num is the number of values we want in a series int num = 5; double result = 0.0; System.out.println(\"The harmonic series is: \"); // printing the harmonic series till num value // using for loop for (int i = num; i > 0; i--) { // calculating harmonic values result = result + (double)1 / i; System.out.print(result + \", \"); } }}",
"e": 1845,
"s": 1272,
"text": null
},
{
"code": null,
"e": 1940,
"s": 1845,
"text": "The harmonic series is: \n0.2, 0.45, 0.7833333333333333, 1.2833333333333332, 2.283333333333333,"
},
{
"code": null,
"e": 1952,
"s": 1940,
"text": "Example 3: "
},
{
"code": null,
"e": 1957,
"s": 1952,
"text": "Java"
},
{
"code": "// Java Program to Generate Harmonic Series // importing necessary java packagesimport java.util.Scanner;import java.lang.*; class HarmonicSeries { // this is a main function public static void main(String args[]) { // scanner class is a pre-defined class in java // for taking input from keyboard Scanner in = new Scanner(System.in); System.out.print(\"Enter Number: \"); // storing input value in num int num = in.nextInt(); double result = 0.0; System.out.println(\"The harmonic series is: \"); // printing the harmonic series till num value // using for loop for (int i = num; i > 0; i--) { // calculating harmonic values result = result + (double)1 / i; System.out.print(result + \", \"); } }}",
"e": 2787,
"s": 1957,
"text": null
},
{
"code": null,
"e": 2795,
"s": 2787,
"text": "Output "
},
{
"code": null,
"e": 2956,
"s": 2795,
"text": "$ javac HarmonicSeries.java\n$ java HarmonicSeries\n\nEnter Number: 5\nThe harmonic series is: \n0.2, 0.45, 0.7833333333333333, 1.2833333333333332, 2.283333333333333"
},
{
"code": null,
"e": 3126,
"s": 2956,
"text": "$ javac HarmonicSeries.java\n$ java HarmonicSeries\n\nEnter Number: 6\nThe harmonic series is: \n0.16666666666666666, 0.3666666666666667, 0.6166666666666667, 0.95, 1.45, 2.45"
},
{
"code": null,
"e": 3145,
"s": 3128,
"text": "arorakashish0911"
},
{
"code": null,
"e": 3152,
"s": 3145,
"text": "Picked"
},
{
"code": null,
"e": 3176,
"s": 3152,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 3181,
"s": 3176,
"text": "Java"
},
{
"code": null,
"e": 3195,
"s": 3181,
"text": "Java Programs"
},
{
"code": null,
"e": 3214,
"s": 3195,
"text": "Technical Scripter"
},
{
"code": null,
"e": 3219,
"s": 3214,
"text": "Java"
},
{
"code": null,
"e": 3317,
"s": 3219,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3332,
"s": 3317,
"text": "Stream In Java"
},
{
"code": null,
"e": 3353,
"s": 3332,
"text": "Introduction to Java"
},
{
"code": null,
"e": 3374,
"s": 3353,
"text": "Constructors in Java"
},
{
"code": null,
"e": 3393,
"s": 3374,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 3410,
"s": 3393,
"text": "Generics in Java"
},
{
"code": null,
"e": 3436,
"s": 3410,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 3470,
"s": 3436,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 3517,
"s": 3470,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 3555,
"s": 3517,
"text": "Factory method design pattern in Java"
}
] |
ctags command in Linux with examples | 15 May, 2019
ctags command in Linux system is used for the with the classic editors. It allows quick access across the files (For example quickly seeing definition of a function). A user can run tags or ctags inside a directory to create a simple index of the source files while working on. Tags-capable editors like vi/vim can then refer to these tags index file to allow you to follow references. Basically, this command generates the tag files for source code. It is also used to create a cross reference file which lists and contain the information about the various source objects found in a set of human-readable language files.
Syntax:
ctags [options] [file(s)]
Options:
–help: It will print the general syntax of the command along with the various options that can be used with the ctags command as well as gives a brief description about each option.
ctags -a: This option used to append the tags to an existing tag file. Equivalent to –append. [Ignored with -e]
ctags -B: This option used for backward searching patterns (e.g. ?regexp?). [Ignored with -e]
ctags -e: This option used for output a tag file for use with Emacs. If this program is being executed by the name etags, this option is already enabled by default.
ctags -F: This option used for searching patterns (e.g. /regexp/)(default). [Ignored with -e]
ctags -i: This option is similar to the –c-types option and is retained for all the compatibility with earlier versions.
ctags -n: This option is Equivalent to –excmd=number.
ctags -N: This option is Equivalent to –excmd=pattern.
ctags -o: This option is Equivalent to -f tagfile.
ctags -p: This option is Used path as the default directory for each supplied source file, unless the source file is already specified as an absolute path.
ctags -R: This option is Equivalent to –recurse=yes.
ctags -u: This option is Equivalent to –sort=no (i.e. “unsorted”).
ctags -V: This option Enables the verbose mode. This prints out a brief message describing that what action is being taken for each of the file considered by ctags.
ctags with Vim:
cd to the folder of your choice where your file is located:Example:cd /home/algoscale/Desktop/pers/angularappRun ctags recursively over the entire folder of your choice to generate the tags file
Example:
cd /home/algoscale/Desktop/pers/angularapp
Run ctags recursively over the entire folder of your choice to generate the tags file
Now run this command:ctags -R *
ctags -R *
To search for a specific tag and open the output in Vim to its definition, run the following command in your shell:vim -t "tag"Example:vim -t titleAs a result this screen pops up with the matching result:
vim -t "tag"
Example:
vim -t title
As a result this screen pops up with the matching result:
linux-command
Linux-misc-commands
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Docker - COPY Instruction
scp command in Linux with Examples
chown command in Linux with Examples
SED command in Linux | Set 2
nohup Command in Linux with Examples
mv command in Linux with examples
chmod command in Linux with examples
Array Basics in Shell Scripting | Set 1
Introduction to Linux Operating System
Basic Operators in Shell Scripting | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n15 May, 2019"
},
{
"code": null,
"e": 650,
"s": 28,
"text": "ctags command in Linux system is used for the with the classic editors. It allows quick access across the files (For example quickly seeing definition of a function). A user can run tags or ctags inside a directory to create a simple index of the source files while working on. Tags-capable editors like vi/vim can then refer to these tags index file to allow you to follow references. Basically, this command generates the tag files for source code. It is also used to create a cross reference file which lists and contain the information about the various source objects found in a set of human-readable language files."
},
{
"code": null,
"e": 658,
"s": 650,
"text": "Syntax:"
},
{
"code": null,
"e": 684,
"s": 658,
"text": "ctags [options] [file(s)]"
},
{
"code": null,
"e": 693,
"s": 684,
"text": "Options:"
},
{
"code": null,
"e": 875,
"s": 693,
"text": "–help: It will print the general syntax of the command along with the various options that can be used with the ctags command as well as gives a brief description about each option."
},
{
"code": null,
"e": 987,
"s": 875,
"text": "ctags -a: This option used to append the tags to an existing tag file. Equivalent to –append. [Ignored with -e]"
},
{
"code": null,
"e": 1081,
"s": 987,
"text": "ctags -B: This option used for backward searching patterns (e.g. ?regexp?). [Ignored with -e]"
},
{
"code": null,
"e": 1246,
"s": 1081,
"text": "ctags -e: This option used for output a tag file for use with Emacs. If this program is being executed by the name etags, this option is already enabled by default."
},
{
"code": null,
"e": 1340,
"s": 1246,
"text": "ctags -F: This option used for searching patterns (e.g. /regexp/)(default). [Ignored with -e]"
},
{
"code": null,
"e": 1461,
"s": 1340,
"text": "ctags -i: This option is similar to the –c-types option and is retained for all the compatibility with earlier versions."
},
{
"code": null,
"e": 1515,
"s": 1461,
"text": "ctags -n: This option is Equivalent to –excmd=number."
},
{
"code": null,
"e": 1570,
"s": 1515,
"text": "ctags -N: This option is Equivalent to –excmd=pattern."
},
{
"code": null,
"e": 1621,
"s": 1570,
"text": "ctags -o: This option is Equivalent to -f tagfile."
},
{
"code": null,
"e": 1777,
"s": 1621,
"text": "ctags -p: This option is Used path as the default directory for each supplied source file, unless the source file is already specified as an absolute path."
},
{
"code": null,
"e": 1830,
"s": 1777,
"text": "ctags -R: This option is Equivalent to –recurse=yes."
},
{
"code": null,
"e": 1897,
"s": 1830,
"text": "ctags -u: This option is Equivalent to –sort=no (i.e. “unsorted”)."
},
{
"code": null,
"e": 2062,
"s": 1897,
"text": "ctags -V: This option Enables the verbose mode. This prints out a brief message describing that what action is being taken for each of the file considered by ctags."
},
{
"code": null,
"e": 2078,
"s": 2062,
"text": "ctags with Vim:"
},
{
"code": null,
"e": 2273,
"s": 2078,
"text": "cd to the folder of your choice where your file is located:Example:cd /home/algoscale/Desktop/pers/angularappRun ctags recursively over the entire folder of your choice to generate the tags file"
},
{
"code": null,
"e": 2282,
"s": 2273,
"text": "Example:"
},
{
"code": null,
"e": 2325,
"s": 2282,
"text": "cd /home/algoscale/Desktop/pers/angularapp"
},
{
"code": null,
"e": 2411,
"s": 2325,
"text": "Run ctags recursively over the entire folder of your choice to generate the tags file"
},
{
"code": null,
"e": 2443,
"s": 2411,
"text": "Now run this command:ctags -R *"
},
{
"code": null,
"e": 2454,
"s": 2443,
"text": "ctags -R *"
},
{
"code": null,
"e": 2659,
"s": 2454,
"text": "To search for a specific tag and open the output in Vim to its definition, run the following command in your shell:vim -t \"tag\"Example:vim -t titleAs a result this screen pops up with the matching result:"
},
{
"code": null,
"e": 2672,
"s": 2659,
"text": "vim -t \"tag\""
},
{
"code": null,
"e": 2681,
"s": 2672,
"text": "Example:"
},
{
"code": null,
"e": 2694,
"s": 2681,
"text": "vim -t title"
},
{
"code": null,
"e": 2752,
"s": 2694,
"text": "As a result this screen pops up with the matching result:"
},
{
"code": null,
"e": 2766,
"s": 2752,
"text": "linux-command"
},
{
"code": null,
"e": 2786,
"s": 2766,
"text": "Linux-misc-commands"
},
{
"code": null,
"e": 2793,
"s": 2786,
"text": "Picked"
},
{
"code": null,
"e": 2804,
"s": 2793,
"text": "Linux-Unix"
},
{
"code": null,
"e": 2902,
"s": 2804,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2928,
"s": 2902,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 2963,
"s": 2928,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 3000,
"s": 2963,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 3029,
"s": 3000,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 3066,
"s": 3029,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 3100,
"s": 3066,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 3137,
"s": 3100,
"text": "chmod command in Linux with examples"
},
{
"code": null,
"e": 3177,
"s": 3137,
"text": "Array Basics in Shell Scripting | Set 1"
},
{
"code": null,
"e": 3216,
"s": 3177,
"text": "Introduction to Linux Operating System"
}
] |
How to download Files with Scrapy ? | 03 Mar, 2021
Scrapy is a fast high-level web crawling and web scraping framework used to crawl websites and extract structured data from their pages. It can be used for a wide range of purposes, from data mining to monitoring and automated testing. In this tutorial, we will be exploring how to download files using a scrapy crawl spider.
For beginners, web crawling is the method of traversing through the World Wide Web to download information related to a particular topic. One thing to keep in mind is not all websites will permit you to crawl their pages and so it is always a good practice to refer to their robots.txt file before attempting to crawl the page.
Step 1: Installing packages:
Before we start coding, we need to install the Scrapy package
pip install scrapy
Step 2: Creating a project
# scrapyProject is the name we chose for
# the folder that will contain the project
mkdir scrapyProject
cd scrapyProject
# downFiles is the name of the project
scrapy startproject downFiles
The output after running the above code in your terminal will be as follows:
Output on starting a new scrapy project
Step 3: Choosing a spider template
Scrapy comes with 4 spider templates, namely:
basic: general purposecrawl: for crawling, or following links (preferred for downloading files)csvfeeed: for parsing CSV filesxmlfeed: for parsing XML files
basic: general purpose
crawl: for crawling, or following links (preferred for downloading files)
csvfeeed: for parsing CSV files
xmlfeed: for parsing XML files
In this tutorial, we will be using the crawl spider template and building upon it further.
To view the available spider templates in scrapy:
scrapy genspider -l
The 4 available spider templates in scrapy
Before we start building the basic structure of the spider, ensure that you are working inside the project directory (the directory containing the spider.cfg file) that you had created in step 2
To change your directory:
# the project name we had decided was
# downFiles in step2
cd downFiles
To create the basic structure of the crawl spider:
scrapy genspider -t crawl nirsoft www.nirsoft.net # nirsoft is the spider name, www.nirsoft.com is the website (domain) we will be crawling
A new python file with the name of your spider will be created with the following content:
This file will be located
...\scrapyProject\downFiles\downFiles\spiders\nirsoft.py
where
scrapyProject is the directory name that contains the project
downFiles is the project name
nirsoft.py is the newly created “empty” spider
Code:
Python3
import scrapyfrom scrapy.linkextractors import LinkExtractorfrom scrapy.spiders import CrawlSpider, Rule class NirsoftSpider(CrawlSpider): name = 'nirsoft' allowed_domains = ['www.nirsoft.net'] start_urls = ['http://www.nirsoft.net/'] rules = ( Rule(LinkExtractor(allow=r'Items/'), callback='parse_item', follow=True), ) def parse_item(self, response): item = {} return item
This is an “empty” crawler. When executed it won’t yield any result. To extract the information we need to tell the spider which links it needs to crawl.
Note: This is what sets Scrapy apart from other popular web crawling packages like Selenium which, if not specified, crawl all the data (even if unnecessary). This feature makes Scrapy faster than Selenium.
Step 4: Defining the rules for link extraction
Python3
rules = ( Rule(LinkExtractor(allow = r'Items/'), callback = 'parse_item', follow = True),)
The above segment of code is what handles which links the spider will be crawling. Several Commands can be used to make rules, but for this tutorial, we will be using only a common handful. We will be attempting to download some tools offered by nirsoft.net All the tools or rather the utilities are available under their utilities, and so all the relevant links follow the given pattern:
https://www.nirsoft.net/utils/...
Example:
https://www.nirsoft.net/utils/simple_program_debugger.html
https://www.nirsoft.net/utils/web_browser_password.html
https://www.nirsoft.net/utils/browsing_history_view.html
So the above code segment will be edited as follows:
Python3
rules = ( Rule(LinkExtractor(allow=r'utils/'), callback='parse_item', follow = True),)
Step 4: Parsing the crawled pages
Now that we have set which links are to be crawled, next we need to define what the spider should crawl exactly. For this, we will have to inspect the pages in question. Head to any of the above examples and open the inspect Element mode (ctrl+shift+c for Windows, cmd+shift+c for MacOS)
a.downloadline shows that all the download links are anchor tags under the class name “downloadline”
As we can see the download links are all an anchor tag (a) with a class name “downloadline” (a.downloadline)
So now we will use this in a CSS selector and extract the href attribute of the anchor tag
For the crawler to work efficiently we also need to convert the relative links to absolute links. Luckily for us the latest versions of Scrapy enable us to do that with a simple method: urljoin()
So the parse_item() method will look as follows:
Python3
def parse_item(self, response): file_url = response.css('.downloadline::attr(href)').get() file_url = response.urljoin(file_url) yield {'file_url': file_url}
If we run the crawler at this state, we will get the links to all the utilities available in nirsoft.
scrapy crawl nirsoft
For beginners: I would advise against running the above command at the moment because your command prompt will just be flooded with a ton of URLs that scroll past too quickly for your eyes to perceive anything.
In a matter of few seconds, our command line will be flooded with all the scraped URLs
Instead, let’s move on to the next step
Step 5: Downloading Files
Finally, the moment we all have been waiting for, downloading the files. However, before we get to that, we need to edit the item class that was created when we created the spider initially. The file can be found in the following location:
...\scrapyProject\downFiles\downFiles\items.py
where
scrapyProject is the directory name that contains the project
downFiles is the project name
items.py is the item’s class in question
The items class has to be edited as follows:
Python3
class DownfilesItem(scrapy.Item): # define the fields for your item here like: file_urls = scrapy.Field() files = scrapy.Field
Now we update the spider script to make use of the data fields we have defined
Python3
def parse_item(self, response): file_url = response.css('.downloadline::attr(href)').get() file_url = response.urljoin(file_url) item = DownfilesItem() item['file_urls'] = [file_url] yield item
You will also have to import the item class you defined earlier into your spider script, and so the import section of the spider script will look like this,
Python3
import scrapyfrom scrapy.linkextractors import LinkExtractorfrom scrapy.spiders import CrawlSpider, Rulefrom downFiles.items import DownfilesItem
Finally, to enable file download we need to make two small changes in the settings.py file in our project directory:
1. Enable file downloads:
ITEM_PIPELINES = {
'scrapy.pipelines.files.FilesPipeline': 1,
}
2. Specify the destination folder for the downloads in settings.py:
FILES_STORE = r"D:\scrapyProject\nirsoft\downloads"
Note: The folder destination should be an actual destination
We use raw string to avoid any errors due to the backslash in Windows location string
Now if we run
scrapy crawl nirsoft
We will be able to find all the files downloaded to the specified destination folder, and hence we are done!
Since we aimed to download the installation files for the utilities, it would be better to limit the crawler to downloading only the .zip and .exe files and leave the rest out. This will also reduce the crawl time thus making the script more efficient.
For this we need to edit our parse_items() functions as shown below:
Python3
def parse_item(self, response): file_url = response.css('.downloadline::attr(href)').get() file_url = response.urljoin(file_url) file_extension = file_url.split('.')[-1] if file_extension not in ('zip', 'exe', 'msi'): return item = DownfilesItem() item['file_urls'] = [file_url] item['original_file_name'] = file_url.split('/')[-1] yield item
We also need to add the new data field “original_file_name” to our items class definition:
Python3
class DownfilesItem(scrapy.Item): # define the fields for your item here like: file_urls = scrapy.Field() original_file_name = scrapy.Field() files = scrapy.Field
Save all your changes and run,
scrapy crawl nirsoft
We will be able to find all the .zip and .exe files downloaded to the specified destination folder. However, we still have one issue:
SHA1 hash codes are not human readable, so it would be preferable if the files were saved with their original (human-readable) names, which leads us to the next section
Initially, we used Scrapy’s default pipeline to download the files, however, the issue was the files were being saved with their SHA1 hash codes instead of their human-readable file names. So we need to create a custom pipeline that will save the original filename and then use that name while downloading the files.
Just like our items class (items.py), we also have a pipeline class (pipelines.py) with a class for our project generated when we created the project, we will be using this class to create our custom pipeline
Python3
from scrapy.pipelines.files import FilesPipeline class DownfilesPipeline(FilesPipeline): def file_path(self, request, response=None, info=None): file_name: str = request.url.split("/")[-1] return file_name
We imported the default FilesPipeline provided by Scrapy and then overwrote the file_path function so that instead of using the hash code as file name, it would use the file name.
We commented out the process_item function so that it does not overwrite the default process_item function from FilesPipeline.
Next, we update our settings.py file to use our custom pipeline instead of the default one.
ITEM_PIPELINES = {
'downFiles.pipelines.DownfilesPipeline': 1,
}
Finally, we run
scrapy crawl nirsoft
And we have our result:
Thanks to the custom Pipeline, the downloaded files are much more readable
Picked
Python-Scrapy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n03 Mar, 2021"
},
{
"code": null,
"e": 378,
"s": 52,
"text": "Scrapy is a fast high-level web crawling and web scraping framework used to crawl websites and extract structured data from their pages. It can be used for a wide range of purposes, from data mining to monitoring and automated testing. In this tutorial, we will be exploring how to download files using a scrapy crawl spider."
},
{
"code": null,
"e": 706,
"s": 378,
"text": "For beginners, web crawling is the method of traversing through the World Wide Web to download information related to a particular topic. One thing to keep in mind is not all websites will permit you to crawl their pages and so it is always a good practice to refer to their robots.txt file before attempting to crawl the page."
},
{
"code": null,
"e": 735,
"s": 706,
"text": "Step 1: Installing packages:"
},
{
"code": null,
"e": 798,
"s": 735,
"text": "Before we start coding, we need to install the Scrapy package "
},
{
"code": null,
"e": 817,
"s": 798,
"text": "pip install scrapy"
},
{
"code": null,
"e": 844,
"s": 817,
"text": "Step 2: Creating a project"
},
{
"code": null,
"e": 1036,
"s": 844,
"text": "# scrapyProject is the name we chose for \n# the folder that will contain the project\nmkdir scrapyProject\ncd scrapyProject\n\n# downFiles is the name of the project\nscrapy startproject downFiles"
},
{
"code": null,
"e": 1113,
"s": 1036,
"text": "The output after running the above code in your terminal will be as follows:"
},
{
"code": null,
"e": 1153,
"s": 1113,
"text": "Output on starting a new scrapy project"
},
{
"code": null,
"e": 1188,
"s": 1153,
"text": "Step 3: Choosing a spider template"
},
{
"code": null,
"e": 1234,
"s": 1188,
"text": "Scrapy comes with 4 spider templates, namely:"
},
{
"code": null,
"e": 1391,
"s": 1234,
"text": "basic: general purposecrawl: for crawling, or following links (preferred for downloading files)csvfeeed: for parsing CSV filesxmlfeed: for parsing XML files"
},
{
"code": null,
"e": 1414,
"s": 1391,
"text": "basic: general purpose"
},
{
"code": null,
"e": 1488,
"s": 1414,
"text": "crawl: for crawling, or following links (preferred for downloading files)"
},
{
"code": null,
"e": 1520,
"s": 1488,
"text": "csvfeeed: for parsing CSV files"
},
{
"code": null,
"e": 1551,
"s": 1520,
"text": "xmlfeed: for parsing XML files"
},
{
"code": null,
"e": 1642,
"s": 1551,
"text": "In this tutorial, we will be using the crawl spider template and building upon it further."
},
{
"code": null,
"e": 1692,
"s": 1642,
"text": "To view the available spider templates in scrapy:"
},
{
"code": null,
"e": 1712,
"s": 1692,
"text": "scrapy genspider -l"
},
{
"code": null,
"e": 1755,
"s": 1712,
"text": "The 4 available spider templates in scrapy"
},
{
"code": null,
"e": 1950,
"s": 1755,
"text": "Before we start building the basic structure of the spider, ensure that you are working inside the project directory (the directory containing the spider.cfg file) that you had created in step 2"
},
{
"code": null,
"e": 1976,
"s": 1950,
"text": "To change your directory:"
},
{
"code": null,
"e": 2050,
"s": 1976,
"text": "# the project name we had decided was \n# downFiles in step2\ncd downFiles "
},
{
"code": null,
"e": 2101,
"s": 2050,
"text": "To create the basic structure of the crawl spider:"
},
{
"code": null,
"e": 2241,
"s": 2101,
"text": "scrapy genspider -t crawl nirsoft www.nirsoft.net # nirsoft is the spider name, www.nirsoft.com is the website (domain) we will be crawling"
},
{
"code": null,
"e": 2332,
"s": 2241,
"text": "A new python file with the name of your spider will be created with the following content:"
},
{
"code": null,
"e": 2359,
"s": 2332,
"text": "This file will be located "
},
{
"code": null,
"e": 2416,
"s": 2359,
"text": "...\\scrapyProject\\downFiles\\downFiles\\spiders\\nirsoft.py"
},
{
"code": null,
"e": 2423,
"s": 2416,
"text": "where "
},
{
"code": null,
"e": 2485,
"s": 2423,
"text": "scrapyProject is the directory name that contains the project"
},
{
"code": null,
"e": 2515,
"s": 2485,
"text": "downFiles is the project name"
},
{
"code": null,
"e": 2562,
"s": 2515,
"text": "nirsoft.py is the newly created “empty” spider"
},
{
"code": null,
"e": 2568,
"s": 2562,
"text": "Code:"
},
{
"code": null,
"e": 2576,
"s": 2568,
"text": "Python3"
},
{
"code": "import scrapyfrom scrapy.linkextractors import LinkExtractorfrom scrapy.spiders import CrawlSpider, Rule class NirsoftSpider(CrawlSpider): name = 'nirsoft' allowed_domains = ['www.nirsoft.net'] start_urls = ['http://www.nirsoft.net/'] rules = ( Rule(LinkExtractor(allow=r'Items/'), callback='parse_item', follow=True), ) def parse_item(self, response): item = {} return item",
"e": 3009,
"s": 2576,
"text": null
},
{
"code": null,
"e": 3164,
"s": 3009,
"text": "This is an “empty” crawler. When executed it won’t yield any result. To extract the information we need to tell the spider which links it needs to crawl. "
},
{
"code": null,
"e": 3371,
"s": 3164,
"text": "Note: This is what sets Scrapy apart from other popular web crawling packages like Selenium which, if not specified, crawl all the data (even if unnecessary). This feature makes Scrapy faster than Selenium."
},
{
"code": null,
"e": 3418,
"s": 3371,
"text": "Step 4: Defining the rules for link extraction"
},
{
"code": null,
"e": 3426,
"s": 3418,
"text": "Python3"
},
{
"code": "rules = ( Rule(LinkExtractor(allow = r'Items/'), callback = 'parse_item', follow = True),)",
"e": 3536,
"s": 3426,
"text": null
},
{
"code": null,
"e": 3925,
"s": 3536,
"text": "The above segment of code is what handles which links the spider will be crawling. Several Commands can be used to make rules, but for this tutorial, we will be using only a common handful. We will be attempting to download some tools offered by nirsoft.net All the tools or rather the utilities are available under their utilities, and so all the relevant links follow the given pattern:"
},
{
"code": null,
"e": 3959,
"s": 3925,
"text": "https://www.nirsoft.net/utils/..."
},
{
"code": null,
"e": 3968,
"s": 3959,
"text": "Example:"
},
{
"code": null,
"e": 4027,
"s": 3968,
"text": "https://www.nirsoft.net/utils/simple_program_debugger.html"
},
{
"code": null,
"e": 4083,
"s": 4027,
"text": "https://www.nirsoft.net/utils/web_browser_password.html"
},
{
"code": null,
"e": 4140,
"s": 4083,
"text": "https://www.nirsoft.net/utils/browsing_history_view.html"
},
{
"code": null,
"e": 4193,
"s": 4140,
"text": "So the above code segment will be edited as follows:"
},
{
"code": null,
"e": 4201,
"s": 4193,
"text": "Python3"
},
{
"code": "rules = ( Rule(LinkExtractor(allow=r'utils/'), callback='parse_item', follow = True),)",
"e": 4299,
"s": 4201,
"text": null
},
{
"code": null,
"e": 4335,
"s": 4301,
"text": "Step 4: Parsing the crawled pages"
},
{
"code": null,
"e": 4623,
"s": 4335,
"text": "Now that we have set which links are to be crawled, next we need to define what the spider should crawl exactly. For this, we will have to inspect the pages in question. Head to any of the above examples and open the inspect Element mode (ctrl+shift+c for Windows, cmd+shift+c for MacOS)"
},
{
"code": null,
"e": 4724,
"s": 4623,
"text": "a.downloadline shows that all the download links are anchor tags under the class name “downloadline”"
},
{
"code": null,
"e": 4833,
"s": 4724,
"text": "As we can see the download links are all an anchor tag (a) with a class name “downloadline” (a.downloadline)"
},
{
"code": null,
"e": 4924,
"s": 4833,
"text": "So now we will use this in a CSS selector and extract the href attribute of the anchor tag"
},
{
"code": null,
"e": 5120,
"s": 4924,
"text": "For the crawler to work efficiently we also need to convert the relative links to absolute links. Luckily for us the latest versions of Scrapy enable us to do that with a simple method: urljoin()"
},
{
"code": null,
"e": 5169,
"s": 5120,
"text": "So the parse_item() method will look as follows:"
},
{
"code": null,
"e": 5177,
"s": 5169,
"text": "Python3"
},
{
"code": "def parse_item(self, response): file_url = response.css('.downloadline::attr(href)').get() file_url = response.urljoin(file_url) yield {'file_url': file_url}",
"e": 5344,
"s": 5177,
"text": null
},
{
"code": null,
"e": 5446,
"s": 5344,
"text": "If we run the crawler at this state, we will get the links to all the utilities available in nirsoft."
},
{
"code": null,
"e": 5467,
"s": 5446,
"text": "scrapy crawl nirsoft"
},
{
"code": null,
"e": 5679,
"s": 5467,
"text": "For beginners: I would advise against running the above command at the moment because your command prompt will just be flooded with a ton of URLs that scroll past too quickly for your eyes to perceive anything. "
},
{
"code": null,
"e": 5766,
"s": 5679,
"text": "In a matter of few seconds, our command line will be flooded with all the scraped URLs"
},
{
"code": null,
"e": 5806,
"s": 5766,
"text": "Instead, let’s move on to the next step"
},
{
"code": null,
"e": 5832,
"s": 5806,
"text": "Step 5: Downloading Files"
},
{
"code": null,
"e": 6072,
"s": 5832,
"text": "Finally, the moment we all have been waiting for, downloading the files. However, before we get to that, we need to edit the item class that was created when we created the spider initially. The file can be found in the following location:"
},
{
"code": null,
"e": 6119,
"s": 6072,
"text": "...\\scrapyProject\\downFiles\\downFiles\\items.py"
},
{
"code": null,
"e": 6125,
"s": 6119,
"text": "where"
},
{
"code": null,
"e": 6187,
"s": 6125,
"text": "scrapyProject is the directory name that contains the project"
},
{
"code": null,
"e": 6217,
"s": 6187,
"text": "downFiles is the project name"
},
{
"code": null,
"e": 6258,
"s": 6217,
"text": "items.py is the item’s class in question"
},
{
"code": null,
"e": 6303,
"s": 6258,
"text": "The items class has to be edited as follows:"
},
{
"code": null,
"e": 6311,
"s": 6303,
"text": "Python3"
},
{
"code": "class DownfilesItem(scrapy.Item): # define the fields for your item here like: file_urls = scrapy.Field() files = scrapy.Field",
"e": 6451,
"s": 6311,
"text": null
},
{
"code": null,
"e": 6530,
"s": 6451,
"text": "Now we update the spider script to make use of the data fields we have defined"
},
{
"code": null,
"e": 6538,
"s": 6530,
"text": "Python3"
},
{
"code": "def parse_item(self, response): file_url = response.css('.downloadline::attr(href)').get() file_url = response.urljoin(file_url) item = DownfilesItem() item['file_urls'] = [file_url] yield item",
"e": 6747,
"s": 6538,
"text": null
},
{
"code": null,
"e": 6904,
"s": 6747,
"text": "You will also have to import the item class you defined earlier into your spider script, and so the import section of the spider script will look like this,"
},
{
"code": null,
"e": 6912,
"s": 6904,
"text": "Python3"
},
{
"code": "import scrapyfrom scrapy.linkextractors import LinkExtractorfrom scrapy.spiders import CrawlSpider, Rulefrom downFiles.items import DownfilesItem",
"e": 7058,
"s": 6912,
"text": null
},
{
"code": null,
"e": 7175,
"s": 7058,
"text": "Finally, to enable file download we need to make two small changes in the settings.py file in our project directory:"
},
{
"code": null,
"e": 7201,
"s": 7175,
"text": "1. Enable file downloads:"
},
{
"code": null,
"e": 7267,
"s": 7201,
"text": "ITEM_PIPELINES = {\n 'scrapy.pipelines.files.FilesPipeline': 1,\n}"
},
{
"code": null,
"e": 7335,
"s": 7267,
"text": "2. Specify the destination folder for the downloads in settings.py:"
},
{
"code": null,
"e": 7387,
"s": 7335,
"text": "FILES_STORE = r\"D:\\scrapyProject\\nirsoft\\downloads\""
},
{
"code": null,
"e": 7448,
"s": 7387,
"text": "Note: The folder destination should be an actual destination"
},
{
"code": null,
"e": 7534,
"s": 7448,
"text": "We use raw string to avoid any errors due to the backslash in Windows location string"
},
{
"code": null,
"e": 7549,
"s": 7534,
"text": "Now if we run "
},
{
"code": null,
"e": 7570,
"s": 7549,
"text": "scrapy crawl nirsoft"
},
{
"code": null,
"e": 7679,
"s": 7570,
"text": "We will be able to find all the files downloaded to the specified destination folder, and hence we are done!"
},
{
"code": null,
"e": 7932,
"s": 7679,
"text": "Since we aimed to download the installation files for the utilities, it would be better to limit the crawler to downloading only the .zip and .exe files and leave the rest out. This will also reduce the crawl time thus making the script more efficient."
},
{
"code": null,
"e": 8001,
"s": 7932,
"text": "For this we need to edit our parse_items() functions as shown below:"
},
{
"code": null,
"e": 8009,
"s": 8001,
"text": "Python3"
},
{
"code": "def parse_item(self, response): file_url = response.css('.downloadline::attr(href)').get() file_url = response.urljoin(file_url) file_extension = file_url.split('.')[-1] if file_extension not in ('zip', 'exe', 'msi'): return item = DownfilesItem() item['file_urls'] = [file_url] item['original_file_name'] = file_url.split('/')[-1] yield item",
"e": 8383,
"s": 8009,
"text": null
},
{
"code": null,
"e": 8474,
"s": 8383,
"text": "We also need to add the new data field “original_file_name” to our items class definition:"
},
{
"code": null,
"e": 8482,
"s": 8474,
"text": "Python3"
},
{
"code": "class DownfilesItem(scrapy.Item): # define the fields for your item here like: file_urls = scrapy.Field() original_file_name = scrapy.Field() files = scrapy.Field",
"e": 8657,
"s": 8482,
"text": null
},
{
"code": null,
"e": 8688,
"s": 8657,
"text": "Save all your changes and run,"
},
{
"code": null,
"e": 8709,
"s": 8688,
"text": "scrapy crawl nirsoft"
},
{
"code": null,
"e": 8843,
"s": 8709,
"text": "We will be able to find all the .zip and .exe files downloaded to the specified destination folder. However, we still have one issue:"
},
{
"code": null,
"e": 9012,
"s": 8843,
"text": "SHA1 hash codes are not human readable, so it would be preferable if the files were saved with their original (human-readable) names, which leads us to the next section"
},
{
"code": null,
"e": 9329,
"s": 9012,
"text": "Initially, we used Scrapy’s default pipeline to download the files, however, the issue was the files were being saved with their SHA1 hash codes instead of their human-readable file names. So we need to create a custom pipeline that will save the original filename and then use that name while downloading the files."
},
{
"code": null,
"e": 9538,
"s": 9329,
"text": "Just like our items class (items.py), we also have a pipeline class (pipelines.py) with a class for our project generated when we created the project, we will be using this class to create our custom pipeline"
},
{
"code": null,
"e": 9546,
"s": 9538,
"text": "Python3"
},
{
"code": "from scrapy.pipelines.files import FilesPipeline class DownfilesPipeline(FilesPipeline): def file_path(self, request, response=None, info=None): file_name: str = request.url.split(\"/\")[-1] return file_name",
"e": 9772,
"s": 9546,
"text": null
},
{
"code": null,
"e": 9952,
"s": 9772,
"text": "We imported the default FilesPipeline provided by Scrapy and then overwrote the file_path function so that instead of using the hash code as file name, it would use the file name."
},
{
"code": null,
"e": 10079,
"s": 9952,
"text": "We commented out the process_item function so that it does not overwrite the default process_item function from FilesPipeline."
},
{
"code": null,
"e": 10171,
"s": 10079,
"text": "Next, we update our settings.py file to use our custom pipeline instead of the default one."
},
{
"code": null,
"e": 10238,
"s": 10171,
"text": "ITEM_PIPELINES = {\n 'downFiles.pipelines.DownfilesPipeline': 1,\n}"
},
{
"code": null,
"e": 10254,
"s": 10238,
"text": "Finally, we run"
},
{
"code": null,
"e": 10275,
"s": 10254,
"text": "scrapy crawl nirsoft"
},
{
"code": null,
"e": 10299,
"s": 10275,
"text": "And we have our result:"
},
{
"code": null,
"e": 10374,
"s": 10299,
"text": "Thanks to the custom Pipeline, the downloaded files are much more readable"
},
{
"code": null,
"e": 10381,
"s": 10374,
"text": "Picked"
},
{
"code": null,
"e": 10395,
"s": 10381,
"text": "Python-Scrapy"
},
{
"code": null,
"e": 10402,
"s": 10395,
"text": "Python"
}
] |
How to count the number of words in a text file using Java? | Read the number of words in text file
Create a FileInputStream object by passing the required file (object) as a parameter to its constructor.
Read the contents of the file using the read() method into a byte array.
Insatiate a String class by passing the byte array to its constructor.
Using split() method read the words of the String to an array.
Create an integer variable, initialize it with 0, int the for loop for each element of the string array increment the count.
import java.io.File;
import java.io.FileInputStream;
public class Sample {
public static void main(String args[]) throws Exception{
int count =0;
File file = new File("data");
FileInputStream fis = new FileInputStream(file);
byte[] bytesArray = new byte[(int)file.length()];
fis.read(bytesArray);
String s = new String(bytesArray);
String [] data = s.split(" ");
for (int i=0; i<data.length; i++) {
count++;
}
System.out.println("Number of characters in the given file are " +count);
}
}
Number of characters in the given String are 4 | [
{
"code": null,
"e": 1225,
"s": 1187,
"text": "Read the number of words in text file"
},
{
"code": null,
"e": 1330,
"s": 1225,
"text": "Create a FileInputStream object by passing the required file (object) as a parameter to its constructor."
},
{
"code": null,
"e": 1403,
"s": 1330,
"text": "Read the contents of the file using the read() method into a byte array."
},
{
"code": null,
"e": 1475,
"s": 1403,
"text": " Insatiate a String class by passing the byte array to its constructor."
},
{
"code": null,
"e": 1538,
"s": 1475,
"text": "Using split() method read the words of the String to an array."
},
{
"code": null,
"e": 1663,
"s": 1538,
"text": "Create an integer variable, initialize it with 0, int the for loop for each element of the string array increment the count."
},
{
"code": null,
"e": 2227,
"s": 1663,
"text": "import java.io.File;\nimport java.io.FileInputStream;\npublic class Sample {\n public static void main(String args[]) throws Exception{\n\n int count =0;\n File file = new File(\"data\");\n FileInputStream fis = new FileInputStream(file);\n byte[] bytesArray = new byte[(int)file.length()];\n fis.read(bytesArray);\n String s = new String(bytesArray);\n String [] data = s.split(\" \");\n for (int i=0; i<data.length; i++) {\n count++;\n }\n System.out.println(\"Number of characters in the given file are \" +count);\n }\n}"
},
{
"code": null,
"e": 2274,
"s": 2227,
"text": "Number of characters in the given String are 4"
}
] |
Data Munging in R Programming | 01 Jun, 2022
Data Munging is the general technique of transforming data from unusable or erroneous form to useful form. Without a few degrees of data munging (irrespective of whether a specialized user or automated system performs it), the data can’t be ready for downstream consumption. Basically the procedure of cleansing the data manually is known as data munging. In R Programming the following ways are oriented with data munging process:
apply() Family
aggregate()
dplyr package
plyr package
In apply() collection of R the most basic function is the apply() function. Apart from that, there exists lapply(), sapply() and tapply(). The entire collection of apply() can be considered a substitute for a loop. It is the most restrictive type of function. It should be performed on a matrix which contains all homogeneous element. If the apply() function is performed using a data frame or any other kind of object, the function will first change it to a matrix and then perform its operation. It is basically used to avoid the explicit use of loop structure or construct.
Syntax:
apply(X, margin, function)
Parameters:
x: an array or matrix
margin: a value between 1 and 2 in order to decide where to apply the function [ 1- row; 2- column]
function: the function to apply
Example:
R
# Using apply()m <- matrix(C <- (1:10), nrow = 5, ncol = 6)ma_m <- apply(m, 2, sum)a_m
Output:
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 1 6 1 6 1 6
[2,] 2 7 2 7 2 7
[3,] 3 8 3 8 3 8
[4,] 4 9 4 9 4 9
[5,] 5 10 5 10 5 10
[1] 15 40 15 40 15 40
In the above example, we are calculating the sum of the elements column-wise. Hence for a large set of data, we can easily produce the desired output.
The lapply() function is used to perform operations on a list and it returns a resultant list of the same size as the input list. The ‘l’ in lapply() refers to lists. The lapply() function does not need the margin parameter.
Syntax:
lapply(X, func)
Parameters:
X: the list or a vector or an object
func: the function to apply
Example:
R
# Using lapply()movies <- c("SPIDERMAN", "BATMAN", "AVENGERS", "FROZEN")moviesmovies_lower <- lapply(movies, tolower)str(movies_lower)
Output:
[1] "SPIDERMAN" "BATMAN" "AVENGERS" "FROZEN"
List of 4
$ : chr "spiderman"
$ : chr "batman"
$ : chr "avengers"
$ : chr "frozen"
The sapply() function takes any vector or object or list and performs the exact operation as the lapply() function. Both of them have the same syntax.
The tapply() function is used to calculate or measure mean, median, maximum, and so on, or to perform a function on each and every factor of the variable. It is efficiently used to create a subset of any vector and then to apply or perform any function on them.
Syntax:
tapply(X, index, func = NULL)
Parameters:
X: an object or vector
index: a list of factorfunc: the function to apply
Example:
R
# Using tapply()data(iris)tapply(iris$Sepal.Width, iris$Species, median)
Output:
setosa versicolor virginica
3.4 2.8 3.0
In R, aggregate() function is used to combine or aggregate the input data frame by applying a function on each column of a sub-data frame. In order to perform aggregation or to apply the aggregate() function we must include the following:
The input data that we wish to aggregate
The variable within the data that will be used to group by
The function or calculation to apply
The aggregate() function will always return a data frame which contains all unique values from the input data frame after applying the specific function. We can only apply a single function inside an aggregate function. In order to include multiple functions inside the aggregate() function, we need to use the plyr package.
Syntax:
aggregate(formula, data, function)
Parameters:
formula: the variable(s) of the input data frame we want to apply functions on.
data: the data that we want to use for group by operation.function: the function or calculation to be applied.
Example:
R
# R program to illustrate# aggregate() functionassets <- data.frame( asset.class = c("equity", "equity", "equity", "option", "option", "option", "bond", "bond"), rating = c("AAA", "A", "A", "AAA", "BB", "BB", "AAA", "A"),counterparty.a = c(runif(3), rnorm(5)),counterparty.b = c(runif(3), rnorm(5)),counterparty.c = c(runif(3), rnorm(5)))assetsexposures <- aggregate( x = assets[c("counterparty.a", "counterparty.b", "counterparty.c")], by = assets[c("asset.class", "rating")], FUN = function(market.values){ sum(pmax(market.values, 0)) })exposures
Output:
asset.class rating counterparty.a counterparty.b counterparty.c
1 equity AAA 0.08250275 0.5474595 0.9966172
2 equity A 0.33931258 0.6442402 0.2348197
3 equity A 0.68078755 0.5962635 0.6126720
4 option AAA -0.47624689 -0.4622881 -1.2362731
5 option BB -0.78860284 0.3219559 -1.2847157
6 option BB -0.59461727 -0.2840014 -0.5739735
7 bond AAA 1.65090747 1.0918564 0.6179858
8 bond A -0.05402813 0.1602164 1.1098481
asset.class rating counterparty.a counterparty.b counterparty.c
1 bond A 0.00000000 0.1602164 1.1098481
2 equity A 1.02010013 1.2405038 0.8474916
3 bond AAA 1.65090747 1.0918564 0.6179858
4 equity AAA 0.08250275 0.5474595 0.9966172
5 option AAA 0.00000000 0.0000000 0.0000000
6 option BB 0.00000000 0.3219559 0.0000000
We can see that in the above example the values of assets data frame have been aggregated on “asset.class” and “rating” columns.
The plyr package is used for splitting, applying, and combining data. The plyr is a set of tools that can be used for splitting up huge or big data for creating a homogeneous piece, then applying a function on each and every piece and finally combine all the resultant values. We can already perform these actions in R, but on using plyr we can do it easily since:
The names, arguments, and outputs are totally consistent
Convenient parallelism
Both input and output involves data frames, matrices or lists
To track the long execution or running programs it provides a progress bar
Built-in informative error messages and error recovery
Labels which are maintained through all transformations.
The two functions that we are going to discuss in this section are ddply() and llply(). For each subset of a given data frame, the ddply() applies a function and then combine the result.
Syntax:
ddply(.data, .variables, .fun = NULL, ..., .progress = “none”, .inform = FALSE,
.drop = TRUE, .parallel = FALSE, .paropts = NULL)
Parameters:
data: the data frame that is to be processed
variable: the variable based on which it will split the data frame
fun: the function to be applied
...: other arguments that are passed to fun
progress: name of the progress bar
inform: whether to produce any informative error message
drop: combination of variables that is not in the input data frame should be preserved or dropped.
parallel: whether to apply function parallel
paropts: list of extra or additional options passed
Example:
R
# Using ddply()library(plyr)dfx <- data.frame( group = c(rep('A', 8), rep('B', 15), rep('C', 6)), sex = sample(c("M", "F"), size = 29, replace = TRUE), age = runif(n = 29, min = 18, max = 54)) ddply(dfx, .(group, sex), summarize, mean = round(mean(age), 2), sd = round(sd(age), 2))
Output:
group sex mean sd
1 A F 41.00 9.19
2 A M 35.76 12.14
3 B F 34.75 11.70
4 B M 40.01 10.10
5 C F 25.13 10.37
6 C M 43.26 7.63
Now we will see how to use llply() to work on data munging. The llply() function is used on each element of lists, where we apply a function on them, and the combined resultant output is also a list.
Syntax:
llply(.data, .fun = NULL, ..., .progress = “none”, .inform = FALSE, .parallel = FALSE, .paropts = NULL)
Example:
R
# Using llply()library(plyr)x <- list(a = 1:10, beta = exp(-3:3), logic = c(TRUE, FALSE, FALSE, TRUE))llply(x, mean)llply(x, quantile, probs = 1:3 / 4)
Output:
$a
[1] 5.5
$beta
[1] 4.535125
$logic
[1] 0.5
$a
25% 50% 75%
3.25 5.50 7.75
$beta
25% 50% 75%
0.2516074 1.0000000 5.0536690
$logic
25% 50% 75%
0.0 0.5 1.0
The dplyr package can be considered as a grammar of data manipulation which is providing us a consistent set of verbs that helps us to solve some most common challenges of data manipulation:
arrange() is used to change the order of the rows.
filter() is used to pick cases depending on their value or based on the value.
mutate() is used to add new variables that are functions of already existing variables.
select() is used to pick or select variables based on their names.
summarize() is used to reduce multiple values to a single summary.
There are many more functions under dplyr. The dplyr uses a very efficient backend which leads to less waiting time for the computation. It is more efficient than the plyr package.
Syntax:
arrange(.data, ..., .by_group = FALSE)
filter(.data, ...)
mutate(.data, ...)
select(.data, ...)
summarize(X, by, fun, ..., stat.name = deparse(substitute(X)),
type = c(“variable”,”matrix”), subset = TRUE, keepcolnames = FALSE)
Example:
R
# Using dplyr package # Import the librarylibrary(dplyr) # Using arrange()starwars %>% arrange(desc(mass)) # Using filter()starwars %>% filter(species == "Droid") # Using mutate()starwars %>% mutate(name, bmi = mass / ((height / 100) ^ 2)) %>% select(name:mass, bmi) # Using select()starwars %>% select(name, ends_with("color")) # Using summarise()starwars %>% group_by(species) %>% summarise(n = n(), mass = mean(mass, na.rm = TRUE)) %>% filter(n > 1)
Output:
> starwars %>% arrange(desc(mass))
# A tibble: 87 x 13
name height mass hair_color skin_color eye_color birth_year gender homeworld species films vehicles starships
<chr> <int> <dbl> <chr> <chr> <chr> <dbl> <chr> <chr> <chr> <lis> <list> <list>
1 Jabba D~ 175 1358 NA green-tan, ~ orange 600 hermap~ Nal Hutta Hutt <chr~ <chr [0~ <chr [0]>
2 Grievous 216 159 none brown, white green, ye~ NA male Kalee Kaleesh <chr~ <chr [1~ <chr [1]>
3 IG-88 200 140 none metal red 15 none NA Droid <chr~ <chr [0~ <chr [0]>
4 Darth V~ 202 136 none white yellow 41.9 male Tatooine Human <chr~ <chr [0~ <chr [1]>
5 Tarfful 234 136 brown brown blue NA male Kashyyyk Wookiee <chr~ <chr [0~ <chr [0]>
6 Owen La~ 178 120 brown, grey light blue 52 male Tatooine Human <chr~ <chr [0~ <chr [0]>
7 Bossk 190 113 none green red 53 male Trandosha Trando~ <chr~ <chr [0~ <chr [0]>
8 Chewbac~ 228 112 brown unknown blue 200 male Kashyyyk Wookiee <chr~ <chr [1~ <chr [2]>
9 Jek Ton~ 180 110 brown fair blue NA male Bestine ~ Human <chr~ <chr [0~ <chr [1]>
10 Dexter ~ 198 102 none brown yellow NA male Ojom Besali~ <chr~ <chr [0~ <chr [0]>
# ... with 77 more rows
> starwars %>% filter(species == "Droid")
# A tibble: 5 x 13
name height mass hair_color skin_color eye_color birth_year gender homeworld species films vehicles starships
<chr> <int> <dbl> <chr> <chr> <chr> <dbl> <chr> <chr> <chr> <list> <list> <list>
1 C-3PO 167 75 NA gold yellow 112 NA Tatooine Droid <chr [6]> <chr [0]> <chr [0]>
2 R2-D2 96 32 NA white, blue red 33 NA Naboo Droid <chr [7]> <chr [0]> <chr [0]>
3 R5-D4 97 32 NA white, red red NA NA Tatooine Droid <chr [1]> <chr [0]> <chr [0]>
4 IG-88 200 140 none metal red 15 none NA Droid <chr [1]> <chr [0]> <chr [0]>
5 BB8 NA NA none none black NA none NA Droid <chr [1]> <chr [0]> <chr [0]>
> starwars %>% mutate(name, bmi = mass / ((height / 100) ^ 2)) %>% select(name:mass, bmi)
# A tibble: 87 x 4
name height mass bmi
<chr> <int> <dbl> <dbl>
1 Luke Skywalker 172 77 26.0
2 C-3PO 167 75 26.9
3 R2-D2 96 32 34.7
4 Darth Vader 202 136 33.3
5 Leia Organa 150 49 21.8
6 Owen Lars 178 120 37.9
7 Beru Whitesun lars 165 75 27.5
8 R5-D4 97 32 34.0
9 Biggs Darklighter 183 84 25.1
10 Obi-Wan Kenobi 182 77 23.2
# ... with 77 more rows
> starwars %>% select(name, ends_with("color"))
# A tibble: 87 x 4
name hair_color skin_color eye_color
<chr> <chr> <chr> <chr>
1 Luke Skywalker blond fair blue
2 C-3PO NA gold yellow
3 R2-D2 NA white, blue red
4 Darth Vader none white yellow
5 Leia Organa brown light brown
6 Owen Lars brown, grey light blue
7 Beru Whitesun lars brown light blue
8 R5-D4 NA white, red red
9 Biggs Darklighter black light brown
10 Obi-Wan Kenobi auburn, white fair blue-gray
# ... with 77 more rows
> starwars %>% group_by(species) %>%
+ summarise(n = n(),mass = mean(mass, na.rm = TRUE)) %>%
+ filter(n > 1)
# A tibble: 9 x 3
species n mass
<chr> <int> <dbl>
1 Droid 5 69.8
2 Gungan 3 74
3 Human 35 82.8
4 Kaminoan 2 88
5 Mirialan 2 53.1
6 Twi'lek 2 55
7 Wookiee 2 124
8 Zabrak 2 80
9 NA 5 48
varshagumber28
surinderdawra388
rkbhola5
R-Packages
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change column name of a given DataFrame in R
Filter data by multiple conditions in R using Dplyr
How to Replace specific values in column in R DataFrame ?
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Loops in R (for, while, repeat)
Group by function in R using Dplyr
Adding elements in a vector in R programming - append() method
How to change Row Names of DataFrame in R ?
Convert Factor to Numeric and Numeric to Factor in R Programming | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 Jun, 2022"
},
{
"code": null,
"e": 460,
"s": 28,
"text": "Data Munging is the general technique of transforming data from unusable or erroneous form to useful form. Without a few degrees of data munging (irrespective of whether a specialized user or automated system performs it), the data can’t be ready for downstream consumption. Basically the procedure of cleansing the data manually is known as data munging. In R Programming the following ways are oriented with data munging process:"
},
{
"code": null,
"e": 475,
"s": 460,
"text": "apply() Family"
},
{
"code": null,
"e": 487,
"s": 475,
"text": "aggregate()"
},
{
"code": null,
"e": 501,
"s": 487,
"text": "dplyr package"
},
{
"code": null,
"e": 514,
"s": 501,
"text": "plyr package"
},
{
"code": null,
"e": 1091,
"s": 514,
"text": "In apply() collection of R the most basic function is the apply() function. Apart from that, there exists lapply(), sapply() and tapply(). The entire collection of apply() can be considered a substitute for a loop. It is the most restrictive type of function. It should be performed on a matrix which contains all homogeneous element. If the apply() function is performed using a data frame or any other kind of object, the function will first change it to a matrix and then perform its operation. It is basically used to avoid the explicit use of loop structure or construct."
},
{
"code": null,
"e": 1099,
"s": 1091,
"text": "Syntax:"
},
{
"code": null,
"e": 1128,
"s": 1099,
"text": "apply(X, margin, function) "
},
{
"code": null,
"e": 1140,
"s": 1128,
"text": "Parameters:"
},
{
"code": null,
"e": 1163,
"s": 1140,
"text": "x: an array or matrix "
},
{
"code": null,
"e": 1264,
"s": 1163,
"text": "margin: a value between 1 and 2 in order to decide where to apply the function [ 1- row; 2- column] "
},
{
"code": null,
"e": 1296,
"s": 1264,
"text": "function: the function to apply"
},
{
"code": null,
"e": 1305,
"s": 1296,
"text": "Example:"
},
{
"code": null,
"e": 1307,
"s": 1305,
"text": "R"
},
{
"code": "# Using apply()m <- matrix(C <- (1:10), nrow = 5, ncol = 6)ma_m <- apply(m, 2, sum)a_m",
"e": 1416,
"s": 1307,
"text": null
},
{
"code": null,
"e": 1424,
"s": 1416,
"text": "Output:"
},
{
"code": null,
"e": 1657,
"s": 1424,
"text": " [,1] [,2] [,3] [,4] [,5] [,6]\n[1,] 1 6 1 6 1 6\n[2,] 2 7 2 7 2 7\n[3,] 3 8 3 8 3 8\n[4,] 4 9 4 9 4 9\n[5,] 5 10 5 10 5 10\n\n[1] 15 40 15 40 15 40"
},
{
"code": null,
"e": 1810,
"s": 1657,
"text": "In the above example, we are calculating the sum of the elements column-wise. Hence for a large set of data, we can easily produce the desired output. "
},
{
"code": null,
"e": 2035,
"s": 1810,
"text": "The lapply() function is used to perform operations on a list and it returns a resultant list of the same size as the input list. The ‘l’ in lapply() refers to lists. The lapply() function does not need the margin parameter."
},
{
"code": null,
"e": 2043,
"s": 2035,
"text": "Syntax:"
},
{
"code": null,
"e": 2061,
"s": 2043,
"text": "lapply(X, func) "
},
{
"code": null,
"e": 2073,
"s": 2061,
"text": "Parameters:"
},
{
"code": null,
"e": 2111,
"s": 2073,
"text": "X: the list or a vector or an object "
},
{
"code": null,
"e": 2139,
"s": 2111,
"text": "func: the function to apply"
},
{
"code": null,
"e": 2148,
"s": 2139,
"text": "Example:"
},
{
"code": null,
"e": 2150,
"s": 2148,
"text": "R"
},
{
"code": "# Using lapply()movies <- c(\"SPIDERMAN\", \"BATMAN\", \"AVENGERS\", \"FROZEN\")moviesmovies_lower <- lapply(movies, tolower)str(movies_lower)",
"e": 2318,
"s": 2150,
"text": null
},
{
"code": null,
"e": 2326,
"s": 2318,
"text": "Output:"
},
{
"code": null,
"e": 2466,
"s": 2326,
"text": "[1] \"SPIDERMAN\" \"BATMAN\" \"AVENGERS\" \"FROZEN\" \n\nList of 4\n $ : chr \"spiderman\"\n $ : chr \"batman\"\n $ : chr \"avengers\"\n $ : chr \"frozen\""
},
{
"code": null,
"e": 2617,
"s": 2466,
"text": "The sapply() function takes any vector or object or list and performs the exact operation as the lapply() function. Both of them have the same syntax."
},
{
"code": null,
"e": 2879,
"s": 2617,
"text": "The tapply() function is used to calculate or measure mean, median, maximum, and so on, or to perform a function on each and every factor of the variable. It is efficiently used to create a subset of any vector and then to apply or perform any function on them."
},
{
"code": null,
"e": 2887,
"s": 2879,
"text": "Syntax:"
},
{
"code": null,
"e": 2917,
"s": 2887,
"text": "tapply(X, index, func = NULL)"
},
{
"code": null,
"e": 2929,
"s": 2917,
"text": "Parameters:"
},
{
"code": null,
"e": 2953,
"s": 2929,
"text": "X: an object or vector "
},
{
"code": null,
"e": 3004,
"s": 2953,
"text": "index: a list of factorfunc: the function to apply"
},
{
"code": null,
"e": 3013,
"s": 3004,
"text": "Example:"
},
{
"code": null,
"e": 3015,
"s": 3013,
"text": "R"
},
{
"code": "# Using tapply()data(iris)tapply(iris$Sepal.Width, iris$Species, median)",
"e": 3100,
"s": 3015,
"text": null
},
{
"code": null,
"e": 3108,
"s": 3100,
"text": "Output:"
},
{
"code": null,
"e": 3166,
"s": 3108,
"text": "setosa versicolor virginica \n 3.4 2.8 3.0 "
},
{
"code": null,
"e": 3405,
"s": 3166,
"text": "In R, aggregate() function is used to combine or aggregate the input data frame by applying a function on each column of a sub-data frame. In order to perform aggregation or to apply the aggregate() function we must include the following:"
},
{
"code": null,
"e": 3446,
"s": 3405,
"text": "The input data that we wish to aggregate"
},
{
"code": null,
"e": 3505,
"s": 3446,
"text": "The variable within the data that will be used to group by"
},
{
"code": null,
"e": 3542,
"s": 3505,
"text": "The function or calculation to apply"
},
{
"code": null,
"e": 3867,
"s": 3542,
"text": "The aggregate() function will always return a data frame which contains all unique values from the input data frame after applying the specific function. We can only apply a single function inside an aggregate function. In order to include multiple functions inside the aggregate() function, we need to use the plyr package."
},
{
"code": null,
"e": 3875,
"s": 3867,
"text": "Syntax:"
},
{
"code": null,
"e": 3910,
"s": 3875,
"text": "aggregate(formula, data, function)"
},
{
"code": null,
"e": 3922,
"s": 3910,
"text": "Parameters:"
},
{
"code": null,
"e": 4003,
"s": 3922,
"text": "formula: the variable(s) of the input data frame we want to apply functions on. "
},
{
"code": null,
"e": 4115,
"s": 4003,
"text": "data: the data that we want to use for group by operation.function: the function or calculation to be applied. "
},
{
"code": null,
"e": 4124,
"s": 4115,
"text": "Example:"
},
{
"code": null,
"e": 4126,
"s": 4124,
"text": "R"
},
{
"code": "# R program to illustrate# aggregate() functionassets <- data.frame( asset.class = c(\"equity\", \"equity\", \"equity\", \"option\", \"option\", \"option\", \"bond\", \"bond\"), rating = c(\"AAA\", \"A\", \"A\", \"AAA\", \"BB\", \"BB\", \"AAA\", \"A\"),counterparty.a = c(runif(3), rnorm(5)),counterparty.b = c(runif(3), rnorm(5)),counterparty.c = c(runif(3), rnorm(5)))assetsexposures <- aggregate( x = assets[c(\"counterparty.a\", \"counterparty.b\", \"counterparty.c\")], by = assets[c(\"asset.class\", \"rating\")], FUN = function(market.values){ sum(pmax(market.values, 0)) })exposures",
"e": 4818,
"s": 4126,
"text": null
},
{
"code": null,
"e": 4826,
"s": 4818,
"text": "Output:"
},
{
"code": null,
"e": 5883,
"s": 4826,
"text": " asset.class rating counterparty.a counterparty.b counterparty.c\n1 equity AAA 0.08250275 0.5474595 0.9966172\n2 equity A 0.33931258 0.6442402 0.2348197\n3 equity A 0.68078755 0.5962635 0.6126720\n4 option AAA -0.47624689 -0.4622881 -1.2362731\n5 option BB -0.78860284 0.3219559 -1.2847157\n6 option BB -0.59461727 -0.2840014 -0.5739735\n7 bond AAA 1.65090747 1.0918564 0.6179858\n8 bond A -0.05402813 0.1602164 1.1098481\n\n asset.class rating counterparty.a counterparty.b counterparty.c\n1 bond A 0.00000000 0.1602164 1.1098481\n2 equity A 1.02010013 1.2405038 0.8474916\n3 bond AAA 1.65090747 1.0918564 0.6179858\n4 equity AAA 0.08250275 0.5474595 0.9966172\n5 option AAA 0.00000000 0.0000000 0.0000000\n6 option BB 0.00000000 0.3219559 0.0000000"
},
{
"code": null,
"e": 6012,
"s": 5883,
"text": "We can see that in the above example the values of assets data frame have been aggregated on “asset.class” and “rating” columns."
},
{
"code": null,
"e": 6377,
"s": 6012,
"text": "The plyr package is used for splitting, applying, and combining data. The plyr is a set of tools that can be used for splitting up huge or big data for creating a homogeneous piece, then applying a function on each and every piece and finally combine all the resultant values. We can already perform these actions in R, but on using plyr we can do it easily since:"
},
{
"code": null,
"e": 6434,
"s": 6377,
"text": "The names, arguments, and outputs are totally consistent"
},
{
"code": null,
"e": 6457,
"s": 6434,
"text": "Convenient parallelism"
},
{
"code": null,
"e": 6519,
"s": 6457,
"text": "Both input and output involves data frames, matrices or lists"
},
{
"code": null,
"e": 6594,
"s": 6519,
"text": "To track the long execution or running programs it provides a progress bar"
},
{
"code": null,
"e": 6649,
"s": 6594,
"text": "Built-in informative error messages and error recovery"
},
{
"code": null,
"e": 6706,
"s": 6649,
"text": "Labels which are maintained through all transformations."
},
{
"code": null,
"e": 6893,
"s": 6706,
"text": "The two functions that we are going to discuss in this section are ddply() and llply(). For each subset of a given data frame, the ddply() applies a function and then combine the result."
},
{
"code": null,
"e": 6901,
"s": 6893,
"text": "Syntax:"
},
{
"code": null,
"e": 6981,
"s": 6901,
"text": "ddply(.data, .variables, .fun = NULL, ..., .progress = “none”, .inform = FALSE,"
},
{
"code": null,
"e": 7040,
"s": 6981,
"text": " .drop = TRUE, .parallel = FALSE, .paropts = NULL)"
},
{
"code": null,
"e": 7052,
"s": 7040,
"text": "Parameters:"
},
{
"code": null,
"e": 7097,
"s": 7052,
"text": "data: the data frame that is to be processed"
},
{
"code": null,
"e": 7164,
"s": 7097,
"text": "variable: the variable based on which it will split the data frame"
},
{
"code": null,
"e": 7196,
"s": 7164,
"text": "fun: the function to be applied"
},
{
"code": null,
"e": 7240,
"s": 7196,
"text": "...: other arguments that are passed to fun"
},
{
"code": null,
"e": 7275,
"s": 7240,
"text": "progress: name of the progress bar"
},
{
"code": null,
"e": 7332,
"s": 7275,
"text": "inform: whether to produce any informative error message"
},
{
"code": null,
"e": 7433,
"s": 7332,
"text": "drop: combination of variables that is not in the input data frame should be preserved or dropped. "
},
{
"code": null,
"e": 7478,
"s": 7433,
"text": "parallel: whether to apply function parallel"
},
{
"code": null,
"e": 7531,
"s": 7478,
"text": "paropts: list of extra or additional options passed "
},
{
"code": null,
"e": 7540,
"s": 7531,
"text": "Example:"
},
{
"code": null,
"e": 7542,
"s": 7540,
"text": "R"
},
{
"code": "# Using ddply()library(plyr)dfx <- data.frame( group = c(rep('A', 8), rep('B', 15), rep('C', 6)), sex = sample(c(\"M\", \"F\"), size = 29, replace = TRUE), age = runif(n = 29, min = 18, max = 54)) ddply(dfx, .(group, sex), summarize, mean = round(mean(age), 2), sd = round(sd(age), 2))",
"e": 7913,
"s": 7542,
"text": null
},
{
"code": null,
"e": 7921,
"s": 7913,
"text": "Output:"
},
{
"code": null,
"e": 8089,
"s": 7921,
"text": " group sex mean sd\n1 A F 41.00 9.19\n2 A M 35.76 12.14\n3 B F 34.75 11.70\n4 B M 40.01 10.10\n5 C F 25.13 10.37\n6 C M 43.26 7.63"
},
{
"code": null,
"e": 8289,
"s": 8089,
"text": "Now we will see how to use llply() to work on data munging. The llply() function is used on each element of lists, where we apply a function on them, and the combined resultant output is also a list."
},
{
"code": null,
"e": 8297,
"s": 8289,
"text": "Syntax:"
},
{
"code": null,
"e": 8402,
"s": 8297,
"text": "llply(.data, .fun = NULL, ..., .progress = “none”, .inform = FALSE, .parallel = FALSE, .paropts = NULL) "
},
{
"code": null,
"e": 8411,
"s": 8402,
"text": "Example:"
},
{
"code": null,
"e": 8413,
"s": 8411,
"text": "R"
},
{
"code": "# Using llply()library(plyr)x <- list(a = 1:10, beta = exp(-3:3), logic = c(TRUE, FALSE, FALSE, TRUE))llply(x, mean)llply(x, quantile, probs = 1:3 / 4)",
"e": 8593,
"s": 8413,
"text": null
},
{
"code": null,
"e": 8601,
"s": 8593,
"text": "Output:"
},
{
"code": null,
"e": 8787,
"s": 8601,
"text": "$a\n[1] 5.5\n\n$beta\n[1] 4.535125\n\n$logic\n[1] 0.5\n\n$a\n 25% 50% 75% \n3.25 5.50 7.75 \n\n$beta\n 25% 50% 75% \n0.2516074 1.0000000 5.0536690 \n\n$logic\n25% 50% 75% \n0.0 0.5 1.0 "
},
{
"code": null,
"e": 8978,
"s": 8787,
"text": "The dplyr package can be considered as a grammar of data manipulation which is providing us a consistent set of verbs that helps us to solve some most common challenges of data manipulation:"
},
{
"code": null,
"e": 9030,
"s": 8978,
"text": "arrange() is used to change the order of the rows."
},
{
"code": null,
"e": 9109,
"s": 9030,
"text": "filter() is used to pick cases depending on their value or based on the value."
},
{
"code": null,
"e": 9197,
"s": 9109,
"text": "mutate() is used to add new variables that are functions of already existing variables."
},
{
"code": null,
"e": 9264,
"s": 9197,
"text": "select() is used to pick or select variables based on their names."
},
{
"code": null,
"e": 9331,
"s": 9264,
"text": "summarize() is used to reduce multiple values to a single summary."
},
{
"code": null,
"e": 9513,
"s": 9331,
"text": "There are many more functions under dplyr. The dplyr uses a very efficient backend which leads to less waiting time for the computation. It is more efficient than the plyr package. "
},
{
"code": null,
"e": 9522,
"s": 9513,
"text": " Syntax:"
},
{
"code": null,
"e": 9561,
"s": 9522,
"text": "arrange(.data, ..., .by_group = FALSE)"
},
{
"code": null,
"e": 9580,
"s": 9561,
"text": "filter(.data, ...)"
},
{
"code": null,
"e": 9599,
"s": 9580,
"text": "mutate(.data, ...)"
},
{
"code": null,
"e": 9618,
"s": 9599,
"text": "select(.data, ...)"
},
{
"code": null,
"e": 9683,
"s": 9618,
"text": "summarize(X, by, fun, ..., stat.name = deparse(substitute(X)), "
},
{
"code": null,
"e": 9770,
"s": 9683,
"text": " type = c(“variable”,”matrix”), subset = TRUE, keepcolnames = FALSE) "
},
{
"code": null,
"e": 9779,
"s": 9770,
"text": "Example:"
},
{
"code": null,
"e": 9781,
"s": 9779,
"text": "R"
},
{
"code": "# Using dplyr package # Import the librarylibrary(dplyr) # Using arrange()starwars %>% arrange(desc(mass)) # Using filter()starwars %>% filter(species == \"Droid\") # Using mutate()starwars %>% mutate(name, bmi = mass / ((height / 100) ^ 2)) %>% select(name:mass, bmi) # Using select()starwars %>% select(name, ends_with(\"color\")) # Using summarise()starwars %>% group_by(species) %>% summarise(n = n(), mass = mean(mass, na.rm = TRUE)) %>% filter(n > 1)",
"e": 10256,
"s": 9781,
"text": null
},
{
"code": null,
"e": 10264,
"s": 10256,
"text": "Output:"
},
{
"code": null,
"e": 14523,
"s": 10264,
"text": "> starwars %>% arrange(desc(mass))\n# A tibble: 87 x 13\n name height mass hair_color skin_color eye_color birth_year gender homeworld species films vehicles starships\n <chr> <int> <dbl> <chr> <chr> <chr> <dbl> <chr> <chr> <chr> <lis> <list> <list> \n 1 Jabba D~ 175 1358 NA green-tan, ~ orange 600 hermap~ Nal Hutta Hutt <chr~ <chr [0~ <chr [0]>\n 2 Grievous 216 159 none brown, white green, ye~ NA male Kalee Kaleesh <chr~ <chr [1~ <chr [1]>\n 3 IG-88 200 140 none metal red 15 none NA Droid <chr~ <chr [0~ <chr [0]>\n 4 Darth V~ 202 136 none white yellow 41.9 male Tatooine Human <chr~ <chr [0~ <chr [1]>\n 5 Tarfful 234 136 brown brown blue NA male Kashyyyk Wookiee <chr~ <chr [0~ <chr [0]>\n 6 Owen La~ 178 120 brown, grey light blue 52 male Tatooine Human <chr~ <chr [0~ <chr [0]>\n 7 Bossk 190 113 none green red 53 male Trandosha Trando~ <chr~ <chr [0~ <chr [0]>\n 8 Chewbac~ 228 112 brown unknown blue 200 male Kashyyyk Wookiee <chr~ <chr [1~ <chr [2]>\n 9 Jek Ton~ 180 110 brown fair blue NA male Bestine ~ Human <chr~ <chr [0~ <chr [1]>\n10 Dexter ~ 198 102 none brown yellow NA male Ojom Besali~ <chr~ <chr [0~ <chr [0]>\n# ... with 77 more rows\n\n> starwars %>% filter(species == \"Droid\")\n# A tibble: 5 x 13\n name height mass hair_color skin_color eye_color birth_year gender homeworld species films vehicles starships\n <chr> <int> <dbl> <chr> <chr> <chr> <dbl> <chr> <chr> <chr> <list> <list> <list> \n1 C-3PO 167 75 NA gold yellow 112 NA Tatooine Droid <chr [6]> <chr [0]> <chr [0]>\n2 R2-D2 96 32 NA white, blue red 33 NA Naboo Droid <chr [7]> <chr [0]> <chr [0]>\n3 R5-D4 97 32 NA white, red red NA NA Tatooine Droid <chr [1]> <chr [0]> <chr [0]>\n4 IG-88 200 140 none metal red 15 none NA Droid <chr [1]> <chr [0]> <chr [0]>\n5 BB8 NA NA none none black NA none NA Droid <chr [1]> <chr [0]> <chr [0]>\n\n> starwars %>% mutate(name, bmi = mass / ((height / 100) ^ 2)) %>% select(name:mass, bmi)\n# A tibble: 87 x 4\n name height mass bmi\n <chr> <int> <dbl> <dbl>\n 1 Luke Skywalker 172 77 26.0\n 2 C-3PO 167 75 26.9\n 3 R2-D2 96 32 34.7\n 4 Darth Vader 202 136 33.3\n 5 Leia Organa 150 49 21.8\n 6 Owen Lars 178 120 37.9\n 7 Beru Whitesun lars 165 75 27.5\n 8 R5-D4 97 32 34.0\n 9 Biggs Darklighter 183 84 25.1\n10 Obi-Wan Kenobi 182 77 23.2\n# ... with 77 more rows\n\n> starwars %>% select(name, ends_with(\"color\"))\n# A tibble: 87 x 4\n name hair_color skin_color eye_color\n <chr> <chr> <chr> <chr> \n 1 Luke Skywalker blond fair blue \n 2 C-3PO NA gold yellow \n 3 R2-D2 NA white, blue red \n 4 Darth Vader none white yellow \n 5 Leia Organa brown light brown \n 6 Owen Lars brown, grey light blue \n 7 Beru Whitesun lars brown light blue \n 8 R5-D4 NA white, red red \n 9 Biggs Darklighter black light brown \n10 Obi-Wan Kenobi auburn, white fair blue-gray\n# ... with 77 more rows\n\n> starwars %>% group_by(species) %>% \n+ summarise(n = n(),mass = mean(mass, na.rm = TRUE)) %>%\n+ filter(n > 1)\n# A tibble: 9 x 3\n species n mass\n <chr> <int> <dbl>\n1 Droid 5 69.8\n2 Gungan 3 74 \n3 Human 35 82.8\n4 Kaminoan 2 88 \n5 Mirialan 2 53.1\n6 Twi'lek 2 55 \n7 Wookiee 2 124 \n8 Zabrak 2 80 \n9 NA 5 48 "
},
{
"code": null,
"e": 14538,
"s": 14523,
"text": "varshagumber28"
},
{
"code": null,
"e": 14555,
"s": 14538,
"text": "surinderdawra388"
},
{
"code": null,
"e": 14564,
"s": 14555,
"text": "rkbhola5"
},
{
"code": null,
"e": 14575,
"s": 14564,
"text": "R-Packages"
},
{
"code": null,
"e": 14586,
"s": 14575,
"text": "R Language"
},
{
"code": null,
"e": 14684,
"s": 14586,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 14729,
"s": 14684,
"text": "Change column name of a given DataFrame in R"
},
{
"code": null,
"e": 14781,
"s": 14729,
"text": "Filter data by multiple conditions in R using Dplyr"
},
{
"code": null,
"e": 14839,
"s": 14781,
"text": "How to Replace specific values in column in R DataFrame ?"
},
{
"code": null,
"e": 14891,
"s": 14839,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 14949,
"s": 14891,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 14981,
"s": 14949,
"text": "Loops in R (for, while, repeat)"
},
{
"code": null,
"e": 15016,
"s": 14981,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 15079,
"s": 15016,
"text": "Adding elements in a vector in R programming - append() method"
},
{
"code": null,
"e": 15123,
"s": 15079,
"text": "How to change Row Names of DataFrame in R ?"
}
] |
Difference between Server OS and Client OS | 02 Jul, 2020
1. Client OS :It is an operating system that operates within desktop. It is used to obtain services from a server. It run on the client devices like laptop, computer and is very simple operating system.
2. Server OS :It is an operating system that is designed to be used on server. It is used to provide services to multiple client. It can serve multiple client at a time and is very advanced operating system.
Difference between Server OS and Client OS :
Computer Networks
Difference Between
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n02 Jul, 2020"
},
{
"code": null,
"e": 231,
"s": 28,
"text": "1. Client OS :It is an operating system that operates within desktop. It is used to obtain services from a server. It run on the client devices like laptop, computer and is very simple operating system."
},
{
"code": null,
"e": 439,
"s": 231,
"text": "2. Server OS :It is an operating system that is designed to be used on server. It is used to provide services to multiple client. It can serve multiple client at a time and is very advanced operating system."
},
{
"code": null,
"e": 484,
"s": 439,
"text": "Difference between Server OS and Client OS :"
},
{
"code": null,
"e": 502,
"s": 484,
"text": "Computer Networks"
},
{
"code": null,
"e": 521,
"s": 502,
"text": "Difference Between"
},
{
"code": null,
"e": 539,
"s": 521,
"text": "Computer Networks"
}
] |
PHP | Types of Errors | 24 Aug, 2018
Error is the fault or mistake in a program. It can be several types. Error can occur due to wrong syntax or wrong logic. It is a type of mistakes or condition of having incorrect knowledge of the code.
There are various types of errors in PHP but it contains basically four main type of errors.
Parse error or Syntax Error: It is the type of error done by the programmer in the source code of the program. The syntax error is caught by the compiler. After fixing the syntax error the compiler compile the code and execute it. Parse errors can be caused dues to unclosed quotes, missing or Extra parentheses, Unclosed braces, Missing semicolon etcExample:<?php$x = "geeks";y = "Computer science";echo $x;echo $y;?>Error:PHP Parse error: syntax error, unexpected '='
in /home/18cb2875ac563160a6120819bab084c8.php on line 3
Explanation: In above program, $ sign is missing in line 3 so it gives an error message.Fatal Error: It is the type of error where PHP compiler understand the PHP code but it recognizes an undeclared function. This means that function is called without the definition of function.Example:<?php function add($x, $y){ $sum = $x + $y; echo "sum = " . $sum;}$x = 0;$y = 20;add($x, $y); diff($x, $y);?>Error:PHP Fatal error: Uncaught Error:
Call to undefined function diff()
in /home/36db1ad4634ff7deb7f7347a4ac14d3a.php:12
Stack trace:
#0 {main}
thrown in /home/36db1ad4634ff7deb7f7347a4ac14d3a.php on line 12
Explanation : In line 12, function is called but the definition of function is not available. So it gives error.Warning Errors : The main reason of warning errors are including a missing file. This means that the PHP function call the missing file.Example:<?php $x = "GeeksforGeeks"; include ("gfg.php"); echo $x . "Computer science portal";?>Error:PHP Warning: include(gfg.php): failed to
open stream: No such file or directory in
/home/aed0ed3b35fece41022f332aba5c9b45.php on line 5
PHP Warning: include(): Failed opening 'gfg.php'
for inclusion (include_path='.:/usr/share/php') in
/home/aed0ed3b35fece41022f332aba5c9b45.php on line 5
Explanation: This program call an undefined file gfg.php which are not available. So it produces error.Notice Error: It is similar to warning error. It means that the program contains something wrong but it allows the execution of script.Example:<?php $x = "GeeksforGeeks"; echo $x; echo $geeks;?>Error:PHP Notice: Undefined variable: geeks in
/home/84c47fe936e1068b69fb834508d59689.php on line 5
Output:GeeksforGeeks
Explanation: This program use undeclared variable $geeks so it gives error message.
Parse error or Syntax Error: It is the type of error done by the programmer in the source code of the program. The syntax error is caught by the compiler. After fixing the syntax error the compiler compile the code and execute it. Parse errors can be caused dues to unclosed quotes, missing or Extra parentheses, Unclosed braces, Missing semicolon etcExample:<?php$x = "geeks";y = "Computer science";echo $x;echo $y;?>Error:PHP Parse error: syntax error, unexpected '='
in /home/18cb2875ac563160a6120819bab084c8.php on line 3
Explanation: In above program, $ sign is missing in line 3 so it gives an error message.
<?php$x = "geeks";y = "Computer science";echo $x;echo $y;?>
Error:
PHP Parse error: syntax error, unexpected '='
in /home/18cb2875ac563160a6120819bab084c8.php on line 3
Explanation: In above program, $ sign is missing in line 3 so it gives an error message.
Fatal Error: It is the type of error where PHP compiler understand the PHP code but it recognizes an undeclared function. This means that function is called without the definition of function.Example:<?php function add($x, $y){ $sum = $x + $y; echo "sum = " . $sum;}$x = 0;$y = 20;add($x, $y); diff($x, $y);?>Error:PHP Fatal error: Uncaught Error:
Call to undefined function diff()
in /home/36db1ad4634ff7deb7f7347a4ac14d3a.php:12
Stack trace:
#0 {main}
thrown in /home/36db1ad4634ff7deb7f7347a4ac14d3a.php on line 12
Explanation : In line 12, function is called but the definition of function is not available. So it gives error.
<?php function add($x, $y){ $sum = $x + $y; echo "sum = " . $sum;}$x = 0;$y = 20;add($x, $y); diff($x, $y);?>
Error:
PHP Fatal error: Uncaught Error:
Call to undefined function diff()
in /home/36db1ad4634ff7deb7f7347a4ac14d3a.php:12
Stack trace:
#0 {main}
thrown in /home/36db1ad4634ff7deb7f7347a4ac14d3a.php on line 12
Explanation : In line 12, function is called but the definition of function is not available. So it gives error.
Warning Errors : The main reason of warning errors are including a missing file. This means that the PHP function call the missing file.Example:<?php $x = "GeeksforGeeks"; include ("gfg.php"); echo $x . "Computer science portal";?>Error:PHP Warning: include(gfg.php): failed to
open stream: No such file or directory in
/home/aed0ed3b35fece41022f332aba5c9b45.php on line 5
PHP Warning: include(): Failed opening 'gfg.php'
for inclusion (include_path='.:/usr/share/php') in
/home/aed0ed3b35fece41022f332aba5c9b45.php on line 5
Explanation: This program call an undefined file gfg.php which are not available. So it produces error.
<?php $x = "GeeksforGeeks"; include ("gfg.php"); echo $x . "Computer science portal";?>
Error:
PHP Warning: include(gfg.php): failed to
open stream: No such file or directory in
/home/aed0ed3b35fece41022f332aba5c9b45.php on line 5
PHP Warning: include(): Failed opening 'gfg.php'
for inclusion (include_path='.:/usr/share/php') in
/home/aed0ed3b35fece41022f332aba5c9b45.php on line 5
Explanation: This program call an undefined file gfg.php which are not available. So it produces error.
Notice Error: It is similar to warning error. It means that the program contains something wrong but it allows the execution of script.Example:<?php $x = "GeeksforGeeks"; echo $x; echo $geeks;?>Error:PHP Notice: Undefined variable: geeks in
/home/84c47fe936e1068b69fb834508d59689.php on line 5
Output:GeeksforGeeks
Explanation: This program use undeclared variable $geeks so it gives error message.
<?php $x = "GeeksforGeeks"; echo $x; echo $geeks;?>
Error:
PHP Notice: Undefined variable: geeks in
/home/84c47fe936e1068b69fb834508d59689.php on line 5
Output:
GeeksforGeeks
Explanation: This program use undeclared variable $geeks so it gives error message.
PHP error constants and their description :
E_ERROR : A fatal error that causes script termination
E_WARNING : Run-time warning that does not cause script termination
E_PARSE : Compile time parse error.
E_NOTICE : Run time notice caused due to error in code
E_CORE_ERROR : Fatal errors that occur during PHP’s initial startup (installation)
E_CORE_WARNING : Warnings that occur during PHP’s initial startup
E_COMPILE_ERROR : Fatal compile-time errors indication problem with script.
E_USER_ERROR : User-generated error message.
E_USER_WARNING : User-generated warning message.
E_USER_NOTICE : User-generated notice message.
E_STRICT : Run-time notices.
E_RECOVERABLE_ERROR : Catchable fatal error indicating a dangerous error
E_DEPRECATED : Run-time notices.
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n24 Aug, 2018"
},
{
"code": null,
"e": 254,
"s": 52,
"text": "Error is the fault or mistake in a program. It can be several types. Error can occur due to wrong syntax or wrong logic. It is a type of mistakes or condition of having incorrect knowledge of the code."
},
{
"code": null,
"e": 347,
"s": 254,
"text": "There are various types of errors in PHP but it contains basically four main type of errors."
},
{
"code": null,
"e": 2651,
"s": 347,
"text": "Parse error or Syntax Error: It is the type of error done by the programmer in the source code of the program. The syntax error is caught by the compiler. After fixing the syntax error the compiler compile the code and execute it. Parse errors can be caused dues to unclosed quotes, missing or Extra parentheses, Unclosed braces, Missing semicolon etcExample:<?php$x = \"geeks\";y = \"Computer science\";echo $x;echo $y;?>Error:PHP Parse error: syntax error, unexpected '=' \nin /home/18cb2875ac563160a6120819bab084c8.php on line 3\nExplanation: In above program, $ sign is missing in line 3 so it gives an error message.Fatal Error: It is the type of error where PHP compiler understand the PHP code but it recognizes an undeclared function. This means that function is called without the definition of function.Example:<?php function add($x, $y){ $sum = $x + $y; echo \"sum = \" . $sum;}$x = 0;$y = 20;add($x, $y); diff($x, $y);?>Error:PHP Fatal error: Uncaught Error: \nCall to undefined function diff() \nin /home/36db1ad4634ff7deb7f7347a4ac14d3a.php:12\n\nStack trace:\n#0 {main}\n thrown in /home/36db1ad4634ff7deb7f7347a4ac14d3a.php on line 12\nExplanation : In line 12, function is called but the definition of function is not available. So it gives error.Warning Errors : The main reason of warning errors are including a missing file. This means that the PHP function call the missing file.Example:<?php $x = \"GeeksforGeeks\"; include (\"gfg.php\"); echo $x . \"Computer science portal\";?>Error:PHP Warning: include(gfg.php): failed to \nopen stream: No such file or directory in \n/home/aed0ed3b35fece41022f332aba5c9b45.php on line 5\nPHP Warning: include(): Failed opening 'gfg.php'\n for inclusion (include_path='.:/usr/share/php') in \n/home/aed0ed3b35fece41022f332aba5c9b45.php on line 5\nExplanation: This program call an undefined file gfg.php which are not available. So it produces error.Notice Error: It is similar to warning error. It means that the program contains something wrong but it allows the execution of script.Example:<?php $x = \"GeeksforGeeks\"; echo $x; echo $geeks;?>Error:PHP Notice: Undefined variable: geeks in \n/home/84c47fe936e1068b69fb834508d59689.php on line 5\nOutput:GeeksforGeeks\nExplanation: This program use undeclared variable $geeks so it gives error message."
},
{
"code": null,
"e": 3268,
"s": 2651,
"text": "Parse error or Syntax Error: It is the type of error done by the programmer in the source code of the program. The syntax error is caught by the compiler. After fixing the syntax error the compiler compile the code and execute it. Parse errors can be caused dues to unclosed quotes, missing or Extra parentheses, Unclosed braces, Missing semicolon etcExample:<?php$x = \"geeks\";y = \"Computer science\";echo $x;echo $y;?>Error:PHP Parse error: syntax error, unexpected '=' \nin /home/18cb2875ac563160a6120819bab084c8.php on line 3\nExplanation: In above program, $ sign is missing in line 3 so it gives an error message."
},
{
"code": "<?php$x = \"geeks\";y = \"Computer science\";echo $x;echo $y;?>",
"e": 3328,
"s": 3268,
"text": null
},
{
"code": null,
"e": 3335,
"s": 3328,
"text": "Error:"
},
{
"code": null,
"e": 3440,
"s": 3335,
"text": "PHP Parse error: syntax error, unexpected '=' \nin /home/18cb2875ac563160a6120819bab084c8.php on line 3\n"
},
{
"code": null,
"e": 3529,
"s": 3440,
"text": "Explanation: In above program, $ sign is missing in line 3 so it gives an error message."
},
{
"code": null,
"e": 4174,
"s": 3529,
"text": "Fatal Error: It is the type of error where PHP compiler understand the PHP code but it recognizes an undeclared function. This means that function is called without the definition of function.Example:<?php function add($x, $y){ $sum = $x + $y; echo \"sum = \" . $sum;}$x = 0;$y = 20;add($x, $y); diff($x, $y);?>Error:PHP Fatal error: Uncaught Error: \nCall to undefined function diff() \nin /home/36db1ad4634ff7deb7f7347a4ac14d3a.php:12\n\nStack trace:\n#0 {main}\n thrown in /home/36db1ad4634ff7deb7f7347a4ac14d3a.php on line 12\nExplanation : In line 12, function is called but the definition of function is not available. So it gives error."
},
{
"code": "<?php function add($x, $y){ $sum = $x + $y; echo \"sum = \" . $sum;}$x = 0;$y = 20;add($x, $y); diff($x, $y);?>",
"e": 4292,
"s": 4174,
"text": null
},
{
"code": null,
"e": 4299,
"s": 4292,
"text": "Error:"
},
{
"code": null,
"e": 4509,
"s": 4299,
"text": "PHP Fatal error: Uncaught Error: \nCall to undefined function diff() \nin /home/36db1ad4634ff7deb7f7347a4ac14d3a.php:12\n\nStack trace:\n#0 {main}\n thrown in /home/36db1ad4634ff7deb7f7347a4ac14d3a.php on line 12\n"
},
{
"code": null,
"e": 4622,
"s": 4509,
"text": "Explanation : In line 12, function is called but the definition of function is not available. So it gives error."
},
{
"code": null,
"e": 5262,
"s": 4622,
"text": "Warning Errors : The main reason of warning errors are including a missing file. This means that the PHP function call the missing file.Example:<?php $x = \"GeeksforGeeks\"; include (\"gfg.php\"); echo $x . \"Computer science portal\";?>Error:PHP Warning: include(gfg.php): failed to \nopen stream: No such file or directory in \n/home/aed0ed3b35fece41022f332aba5c9b45.php on line 5\nPHP Warning: include(): Failed opening 'gfg.php'\n for inclusion (include_path='.:/usr/share/php') in \n/home/aed0ed3b35fece41022f332aba5c9b45.php on line 5\nExplanation: This program call an undefined file gfg.php which are not available. So it produces error."
},
{
"code": "<?php $x = \"GeeksforGeeks\"; include (\"gfg.php\"); echo $x . \"Computer science portal\";?>",
"e": 5354,
"s": 5262,
"text": null
},
{
"code": null,
"e": 5361,
"s": 5354,
"text": "Error:"
},
{
"code": null,
"e": 5657,
"s": 5361,
"text": "PHP Warning: include(gfg.php): failed to \nopen stream: No such file or directory in \n/home/aed0ed3b35fece41022f332aba5c9b45.php on line 5\nPHP Warning: include(): Failed opening 'gfg.php'\n for inclusion (include_path='.:/usr/share/php') in \n/home/aed0ed3b35fece41022f332aba5c9b45.php on line 5\n"
},
{
"code": null,
"e": 5761,
"s": 5657,
"text": "Explanation: This program call an undefined file gfg.php which are not available. So it produces error."
},
{
"code": null,
"e": 6166,
"s": 5761,
"text": "Notice Error: It is similar to warning error. It means that the program contains something wrong but it allows the execution of script.Example:<?php $x = \"GeeksforGeeks\"; echo $x; echo $geeks;?>Error:PHP Notice: Undefined variable: geeks in \n/home/84c47fe936e1068b69fb834508d59689.php on line 5\nOutput:GeeksforGeeks\nExplanation: This program use undeclared variable $geeks so it gives error message."
},
{
"code": "<?php $x = \"GeeksforGeeks\"; echo $x; echo $geeks;?>",
"e": 6222,
"s": 6166,
"text": null
},
{
"code": null,
"e": 6229,
"s": 6222,
"text": "Error:"
},
{
"code": null,
"e": 6326,
"s": 6229,
"text": "PHP Notice: Undefined variable: geeks in \n/home/84c47fe936e1068b69fb834508d59689.php on line 5\n"
},
{
"code": null,
"e": 6334,
"s": 6326,
"text": "Output:"
},
{
"code": null,
"e": 6349,
"s": 6334,
"text": "GeeksforGeeks\n"
},
{
"code": null,
"e": 6433,
"s": 6349,
"text": "Explanation: This program use undeclared variable $geeks so it gives error message."
},
{
"code": null,
"e": 6477,
"s": 6433,
"text": "PHP error constants and their description :"
},
{
"code": null,
"e": 6532,
"s": 6477,
"text": "E_ERROR : A fatal error that causes script termination"
},
{
"code": null,
"e": 6600,
"s": 6532,
"text": "E_WARNING : Run-time warning that does not cause script termination"
},
{
"code": null,
"e": 6636,
"s": 6600,
"text": "E_PARSE : Compile time parse error."
},
{
"code": null,
"e": 6691,
"s": 6636,
"text": "E_NOTICE : Run time notice caused due to error in code"
},
{
"code": null,
"e": 6774,
"s": 6691,
"text": "E_CORE_ERROR : Fatal errors that occur during PHP’s initial startup (installation)"
},
{
"code": null,
"e": 6840,
"s": 6774,
"text": "E_CORE_WARNING : Warnings that occur during PHP’s initial startup"
},
{
"code": null,
"e": 6916,
"s": 6840,
"text": "E_COMPILE_ERROR : Fatal compile-time errors indication problem with script."
},
{
"code": null,
"e": 6961,
"s": 6916,
"text": "E_USER_ERROR : User-generated error message."
},
{
"code": null,
"e": 7010,
"s": 6961,
"text": "E_USER_WARNING : User-generated warning message."
},
{
"code": null,
"e": 7057,
"s": 7010,
"text": "E_USER_NOTICE : User-generated notice message."
},
{
"code": null,
"e": 7086,
"s": 7057,
"text": "E_STRICT : Run-time notices."
},
{
"code": null,
"e": 7159,
"s": 7086,
"text": "E_RECOVERABLE_ERROR : Catchable fatal error indicating a dangerous error"
},
{
"code": null,
"e": 7192,
"s": 7159,
"text": "E_DEPRECATED : Run-time notices."
},
{
"code": null,
"e": 7196,
"s": 7192,
"text": "PHP"
},
{
"code": null,
"e": 7213,
"s": 7196,
"text": "Web Technologies"
},
{
"code": null,
"e": 7217,
"s": 7213,
"text": "PHP"
}
] |
What is RowSet in Java JDBC? | 24 Jun, 2021
RowSet is an interface in java that is present in the java.sql package. Geek do note not to confuse RowSet with ResultSet.
Note: RowSet is present in package javax.sql while ResultSet is present in package java.sql.
The instance of RowSet is the java bean component because it has properties and a java bean notification mechanism. It is introduced in JDK5. A JDBC RowSet provides a way to store the data in tabular form. It makes the data more flexible and easier than a ResultSet. The connection between the RowSet object and the data source is maintained throughout its life cycle.
RowSets are classified into five categories based on how they are implemented which are listed namely as below:
JdbcRowSet
CachedRowSet
WebRowSet
FilteredRowSet
JoinRowSet
The advantage of RowSet is as follows:
It is easy and flexible to use.It is by default scrollable and can be updated by default whereas ResultSet by default is only forwardable and read-only operation is valid there only.
It is easy and flexible to use.
It is by default scrollable and can be updated by default whereas ResultSet by default is only forwardable and read-only operation is valid there only.
The JDBC RowSet interface is a RowSet extension. It’s a wrapper for the ResultSet object that adds some extra features.
Syntax: Declaration of Jdbc RowSet interface
public interface JdbcRowSet
extends RowSet, Joinable
In order to connect RowSet with the database, the RowSet interface provides methods for configuring Java bean properties which are depicted below:
void setURL(String url):
void setUserName(String user_name):
void setPassword(String password):
Lastly, we just need to create a JdbcRowSet object where a sample is shown below illustration as follows:
Illustration:
JdbcRowSetrowSet = RowSetProvider.newFactory().createJdbcRowSet();
// 1. Oracle database considered
rowSet.setUrl("jdbc:oracle:thin:@localhost:1521:xe");
// 2. username is set customly as - root
rowSet.setUsername("root");
// 3. Password is set customly as - pass
rowSet.setPassword("pass");
// 4. Query
rowSet.setCommand("select * from Students");
Implementation: Assume we have a table named student in the database as:
+--------------+-------------+
| RollNo | Name | Marks |
+--------------+-------------+
| 1 | jack | 92 |
| 2 | jenny | 90 |
| 3 | mark | 80 |
| 4 | joe | 82 |
+--------------+-------------+
Implementing JdbcRowSet and retrieving the records
Java
// Java Program to Illustrate RowSet in JDBC // Importing databaseimport java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.Statement;import javax.sql.RowSetEvent;import javax.sql.RowSetListener;import javax.sql.rowset.JdbcRowSet;import javax.sql.rowset.RowSetProvider; // Main classclass RowSetDemo { // Main driver method public static void main(String args[]) { // Try block to check for exceptions try { // Loading and registering drivers Class.forName( "oracle.jdbc.driver.OracleDriver"); // Creating a RowSet JdbcRowSetrowSet = RowSetProvider.newFactory() .createJdbcRowSet(); // Setting URL, username, password rowSet.setUrl( "jdbc:oracle:thin:@localhost:1521:xe"); rowSet.setUsername("root"); rowSet.setPassword("pass"); // Creating a query rowSet.setCommand("select * from Student"); // Executing the query rowSet.execute(); // Processign the results while (rowSet.next()) { // Print and display commands System.out.println("RollNo: " + rowSet.getInt(1)); System.out.println("Name: " + rowSet.getString(2)); System.out.println("Marks: " + rowSet.getString(3)); } } // Catch block to handle the exceptions catch (Exception e) { // Print and display the exception along with // line number using printStackTrace() method e.printStackTrace(); } }}
Output:
RollNo: 1
Name: jack
Marks: 92
RollNo: 2
Name: jenny
Marks: 90
RollNo: 3
Name: mark
Marks: 80
RollNo: 4
Name: joe
Marks: 82
AshokJaiswal
JDBC
Picked
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n24 Jun, 2021"
},
{
"code": null,
"e": 152,
"s": 28,
"text": "RowSet is an interface in java that is present in the java.sql package. Geek do note not to confuse RowSet with ResultSet. "
},
{
"code": null,
"e": 248,
"s": 152,
"text": "Note: RowSet is present in package javax.sql while ResultSet is present in package java.sql. "
},
{
"code": null,
"e": 617,
"s": 248,
"text": "The instance of RowSet is the java bean component because it has properties and a java bean notification mechanism. It is introduced in JDK5. A JDBC RowSet provides a way to store the data in tabular form. It makes the data more flexible and easier than a ResultSet. The connection between the RowSet object and the data source is maintained throughout its life cycle."
},
{
"code": null,
"e": 729,
"s": 617,
"text": "RowSets are classified into five categories based on how they are implemented which are listed namely as below:"
},
{
"code": null,
"e": 740,
"s": 729,
"text": "JdbcRowSet"
},
{
"code": null,
"e": 753,
"s": 740,
"text": "CachedRowSet"
},
{
"code": null,
"e": 763,
"s": 753,
"text": "WebRowSet"
},
{
"code": null,
"e": 778,
"s": 763,
"text": "FilteredRowSet"
},
{
"code": null,
"e": 789,
"s": 778,
"text": "JoinRowSet"
},
{
"code": null,
"e": 828,
"s": 789,
"text": "The advantage of RowSet is as follows:"
},
{
"code": null,
"e": 1011,
"s": 828,
"text": "It is easy and flexible to use.It is by default scrollable and can be updated by default whereas ResultSet by default is only forwardable and read-only operation is valid there only."
},
{
"code": null,
"e": 1043,
"s": 1011,
"text": "It is easy and flexible to use."
},
{
"code": null,
"e": 1195,
"s": 1043,
"text": "It is by default scrollable and can be updated by default whereas ResultSet by default is only forwardable and read-only operation is valid there only."
},
{
"code": null,
"e": 1315,
"s": 1195,
"text": "The JDBC RowSet interface is a RowSet extension. It’s a wrapper for the ResultSet object that adds some extra features."
},
{
"code": null,
"e": 1360,
"s": 1315,
"text": "Syntax: Declaration of Jdbc RowSet interface"
},
{
"code": null,
"e": 1413,
"s": 1360,
"text": "public interface JdbcRowSet\nextends RowSet, Joinable"
},
{
"code": null,
"e": 1560,
"s": 1413,
"text": "In order to connect RowSet with the database, the RowSet interface provides methods for configuring Java bean properties which are depicted below:"
},
{
"code": null,
"e": 1656,
"s": 1560,
"text": "void setURL(String url):\nvoid setUserName(String user_name):\nvoid setPassword(String password):"
},
{
"code": null,
"e": 1762,
"s": 1656,
"text": "Lastly, we just need to create a JdbcRowSet object where a sample is shown below illustration as follows:"
},
{
"code": null,
"e": 1776,
"s": 1762,
"text": "Illustration:"
},
{
"code": null,
"e": 2132,
"s": 1776,
"text": "JdbcRowSetrowSet = RowSetProvider.newFactory().createJdbcRowSet();\n\n// 1. Oracle database considered \nrowSet.setUrl(\"jdbc:oracle:thin:@localhost:1521:xe\");\n\n// 2. username is set customly as - root \nrowSet.setUsername(\"root\");\n\n// 3. Password is set customly as - pass\nrowSet.setPassword(\"pass\");\n\n// 4. Query \nrowSet.setCommand(\"select * from Students\");"
},
{
"code": null,
"e": 2205,
"s": 2132,
"text": "Implementation: Assume we have a table named student in the database as:"
},
{
"code": null,
"e": 2470,
"s": 2205,
"text": "+--------------+-------------+\n| RollNo | Name | Marks |\n+--------------+-------------+\n| 1 | jack | 92 |\n| 2 | jenny | 90 | \n| 3 | mark | 80 |\n| 4 | joe | 82 |\n+--------------+-------------+"
},
{
"code": null,
"e": 2521,
"s": 2470,
"text": "Implementing JdbcRowSet and retrieving the records"
},
{
"code": null,
"e": 2526,
"s": 2521,
"text": "Java"
},
{
"code": "// Java Program to Illustrate RowSet in JDBC // Importing databaseimport java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.Statement;import javax.sql.RowSetEvent;import javax.sql.RowSetListener;import javax.sql.rowset.JdbcRowSet;import javax.sql.rowset.RowSetProvider; // Main classclass RowSetDemo { // Main driver method public static void main(String args[]) { // Try block to check for exceptions try { // Loading and registering drivers Class.forName( \"oracle.jdbc.driver.OracleDriver\"); // Creating a RowSet JdbcRowSetrowSet = RowSetProvider.newFactory() .createJdbcRowSet(); // Setting URL, username, password rowSet.setUrl( \"jdbc:oracle:thin:@localhost:1521:xe\"); rowSet.setUsername(\"root\"); rowSet.setPassword(\"pass\"); // Creating a query rowSet.setCommand(\"select * from Student\"); // Executing the query rowSet.execute(); // Processign the results while (rowSet.next()) { // Print and display commands System.out.println(\"RollNo: \" + rowSet.getInt(1)); System.out.println(\"Name: \" + rowSet.getString(2)); System.out.println(\"Marks: \" + rowSet.getString(3)); } } // Catch block to handle the exceptions catch (Exception e) { // Print and display the exception along with // line number using printStackTrace() method e.printStackTrace(); } }}",
"e": 4310,
"s": 2526,
"text": null
},
{
"code": null,
"e": 4322,
"s": 4314,
"text": "Output:"
},
{
"code": null,
"e": 4451,
"s": 4324,
"text": "RollNo: 1\nName: jack \nMarks: 92\nRollNo: 2\nName: jenny \nMarks: 90\nRollNo: 3\nName: mark\nMarks: 80\nRollNo: 4\nName: joe\nMarks: 82"
},
{
"code": null,
"e": 4466,
"s": 4453,
"text": "AshokJaiswal"
},
{
"code": null,
"e": 4471,
"s": 4466,
"text": "JDBC"
},
{
"code": null,
"e": 4478,
"s": 4471,
"text": "Picked"
},
{
"code": null,
"e": 4483,
"s": 4478,
"text": "Java"
},
{
"code": null,
"e": 4488,
"s": 4483,
"text": "Java"
}
] |
JavaFX - 2D Shapes Rectangle | In general, a rectangle is a four-sided polygon that has two pairs of parallel and concurrent sides with all interior angles as right angles.
It is described by two parameters namely −
height − The vertical length of the rectangle is known as height.
height − The vertical length of the rectangle is known as height.
width − The horizontal length of the rectangle is known as width.
width − The horizontal length of the rectangle is known as width.
In JavaFX, a Rectangle is represented by a class named Rectangle. This class belongs to the package javafx.scene.shape.
By instantiating this class, you can create a Rectangle node in JavaFX.
This class has 4 properties of the double datatype namely −
X − The x coordinate of the start point (upper left) of the rectangle.
X − The x coordinate of the start point (upper left) of the rectangle.
Y − The y coordinate of the start point (upper left) of the rectangle.
Y − The y coordinate of the start point (upper left) of the rectangle.
Width − The width of the rectangle.
Width − The width of the rectangle.
height − The height of the rectangle.
height − The height of the rectangle.
To draw a rectangle, you need to pass values to these properties, either by passing them to the constructor of this class, in the same order, at the time of instantiation, as shown below −
Rectangle rectangle = new Rectangle(x, y, width, height);
Or, by using their respective setter methods as shown in the following code block −
setX(value);
setY(value);
setWidth(value);
setHeight(value);
You need to follow the steps given below to draw a rectangle in JavaFX.
Create a Java class and inherit the Application class of the package javafx.application and implement the start() method of this class as shown below.
public class ClassName extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
}
}
You can create a rectangle in JavaFX by instantiating the class named Rectangle which belongs to a package javafx.scene.shape, instantiate this class as follows.
//Creating a rectangle object
Rectangle rectangle = new Rectangle();
Specify the x, y coordinates of the starting point (upper left), height and the width of the rectangle, that is needed to be drawn. You can do this by setting the properties x, y, height and width, using their respective setter methods as shown in the following code block.
line.setStartX(100.0);
line.setStartY(150.0);
line.setEndX(500.0);
line.setEndY(150.0);
In the start() method, create a group object by instantiating the class named Group, which belongs to the package javafx.scene.
Pass the Rectangle (node) object, created in the previous step, as a parameter to the constructor of the Group class, in order to add it to the group as follows −
Group root = new Group(rectangle);
Create a Scene by instantiating the class named Scene that belongs to the package javafx.scene. To this class, pass the Group object (root), created in the previous step.
In addition to the root object, you can also pass two double parameters representing height and width of the screen along with the object of the Group class as follows.
Scene scene = new Scene(group ,600, 300)
You can set the title to the stage using the setTitle() method of the Stage class. The primaryStage is a Stage object, which is passed to the start method of the scene class, as a parameter.
Using the primaryStage object, set the title of the scene as Sample Application as follows.
primaryStage.setTitle("Sample Application");
You can add a Scene object to the stage using the method setScene() of the class named Stage. Add the Scene object prepared in the previous steps using the method shown below.
primaryStage.setScene(scene)
Display the contents of the scene using the method named show() of the Stage class as follows.
primaryStage.show()
Launch the JavaFX application by calling the static method launch() of the Application class from the main method as follows.
public static void main(String args[]){
launch(args);
}
Following is the program which generates a rectangle JavaFX. Save this code in a file with the name RectangleExample.java.
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.scene.shape.Rectangle;
public class RectangleExample extends Application {
@Override
public void start(Stage stage) {
//Drawing a Rectangle
Rectangle rectangle = new Rectangle();
//Setting the properties of the rectangle
rectangle.setX(150.0f);
rectangle.setY(75.0f);
rectangle.setWidth(300.0f);
rectangle.setHeight(150.0f);
//Creating a Group object
Group root = new Group(rectangle);
//Creating a scene object
Scene scene = new Scene(root, 600, 300);
//Setting title to the Stage
stage.setTitle("Drawing a Rectangle");
//Adding scene to the stage
stage.setScene(scene);
//Displaying the contents of the stage
stage.show();
}
public static void main(String args[]){
launch(args);
}
}
Compile and execute the saved java file from the command prompt using the following commands.
javac RectangleExample.java
java RectangleExample
On executing, the above program generates a JavaFX window displaying a rectangle as shown in the following screenshot. | [
{
"code": null,
"e": 2176,
"s": 2034,
"text": "In general, a rectangle is a four-sided polygon that has two pairs of parallel and concurrent sides with all interior angles as right angles."
},
{
"code": null,
"e": 2219,
"s": 2176,
"text": "It is described by two parameters namely −"
},
{
"code": null,
"e": 2285,
"s": 2219,
"text": "height − The vertical length of the rectangle is known as height."
},
{
"code": null,
"e": 2351,
"s": 2285,
"text": "height − The vertical length of the rectangle is known as height."
},
{
"code": null,
"e": 2417,
"s": 2351,
"text": "width − The horizontal length of the rectangle is known as width."
},
{
"code": null,
"e": 2483,
"s": 2417,
"text": "width − The horizontal length of the rectangle is known as width."
},
{
"code": null,
"e": 2603,
"s": 2483,
"text": "In JavaFX, a Rectangle is represented by a class named Rectangle. This class belongs to the package javafx.scene.shape."
},
{
"code": null,
"e": 2675,
"s": 2603,
"text": "By instantiating this class, you can create a Rectangle node in JavaFX."
},
{
"code": null,
"e": 2735,
"s": 2675,
"text": "This class has 4 properties of the double datatype namely −"
},
{
"code": null,
"e": 2806,
"s": 2735,
"text": "X − The x coordinate of the start point (upper left) of the rectangle."
},
{
"code": null,
"e": 2877,
"s": 2806,
"text": "X − The x coordinate of the start point (upper left) of the rectangle."
},
{
"code": null,
"e": 2948,
"s": 2877,
"text": "Y − The y coordinate of the start point (upper left) of the rectangle."
},
{
"code": null,
"e": 3019,
"s": 2948,
"text": "Y − The y coordinate of the start point (upper left) of the rectangle."
},
{
"code": null,
"e": 3055,
"s": 3019,
"text": "Width − The width of the rectangle."
},
{
"code": null,
"e": 3091,
"s": 3055,
"text": "Width − The width of the rectangle."
},
{
"code": null,
"e": 3129,
"s": 3091,
"text": "height − The height of the rectangle."
},
{
"code": null,
"e": 3167,
"s": 3129,
"text": "height − The height of the rectangle."
},
{
"code": null,
"e": 3356,
"s": 3167,
"text": "To draw a rectangle, you need to pass values to these properties, either by passing them to the constructor of this class, in the same order, at the time of instantiation, as shown below −"
},
{
"code": null,
"e": 3415,
"s": 3356,
"text": "Rectangle rectangle = new Rectangle(x, y, width, height);\n"
},
{
"code": null,
"e": 3499,
"s": 3415,
"text": "Or, by using their respective setter methods as shown in the following code block −"
},
{
"code": null,
"e": 3564,
"s": 3499,
"text": "setX(value); \nsetY(value); \nsetWidth(value); \nsetHeight(value);\n"
},
{
"code": null,
"e": 3636,
"s": 3564,
"text": "You need to follow the steps given below to draw a rectangle in JavaFX."
},
{
"code": null,
"e": 3787,
"s": 3636,
"text": "Create a Java class and inherit the Application class of the package javafx.application and implement the start() method of this class as shown below."
},
{
"code": null,
"e": 3929,
"s": 3787,
"text": "public class ClassName extends Application { \n @Override \n public void start(Stage primaryStage) throws Exception { \n } \n}"
},
{
"code": null,
"e": 4091,
"s": 3929,
"text": "You can create a rectangle in JavaFX by instantiating the class named Rectangle which belongs to a package javafx.scene.shape, instantiate this class as follows."
},
{
"code": null,
"e": 4170,
"s": 4091,
"text": "//Creating a rectangle object \nRectangle rectangle = new Rectangle();\n"
},
{
"code": null,
"e": 4444,
"s": 4170,
"text": "Specify the x, y coordinates of the starting point (upper left), height and the width of the rectangle, that is needed to be drawn. You can do this by setting the properties x, y, height and width, using their respective setter methods as shown in the following code block."
},
{
"code": null,
"e": 4536,
"s": 4444,
"text": "line.setStartX(100.0); \nline.setStartY(150.0); \nline.setEndX(500.0); \nline.setEndY(150.0);\n"
},
{
"code": null,
"e": 4664,
"s": 4536,
"text": "In the start() method, create a group object by instantiating the class named Group, which belongs to the package javafx.scene."
},
{
"code": null,
"e": 4827,
"s": 4664,
"text": "Pass the Rectangle (node) object, created in the previous step, as a parameter to the constructor of the Group class, in order to add it to the group as follows −"
},
{
"code": null,
"e": 4863,
"s": 4827,
"text": "Group root = new Group(rectangle);\n"
},
{
"code": null,
"e": 5034,
"s": 4863,
"text": "Create a Scene by instantiating the class named Scene that belongs to the package javafx.scene. To this class, pass the Group object (root), created in the previous step."
},
{
"code": null,
"e": 5203,
"s": 5034,
"text": "In addition to the root object, you can also pass two double parameters representing height and width of the screen along with the object of the Group class as follows."
},
{
"code": null,
"e": 5245,
"s": 5203,
"text": "Scene scene = new Scene(group ,600, 300)\n"
},
{
"code": null,
"e": 5436,
"s": 5245,
"text": "You can set the title to the stage using the setTitle() method of the Stage class. The primaryStage is a Stage object, which is passed to the start method of the scene class, as a parameter."
},
{
"code": null,
"e": 5528,
"s": 5436,
"text": "Using the primaryStage object, set the title of the scene as Sample Application as follows."
},
{
"code": null,
"e": 5574,
"s": 5528,
"text": "primaryStage.setTitle(\"Sample Application\");\n"
},
{
"code": null,
"e": 5750,
"s": 5574,
"text": "You can add a Scene object to the stage using the method setScene() of the class named Stage. Add the Scene object prepared in the previous steps using the method shown below."
},
{
"code": null,
"e": 5780,
"s": 5750,
"text": "primaryStage.setScene(scene)\n"
},
{
"code": null,
"e": 5875,
"s": 5780,
"text": "Display the contents of the scene using the method named show() of the Stage class as follows."
},
{
"code": null,
"e": 5896,
"s": 5875,
"text": "primaryStage.show()\n"
},
{
"code": null,
"e": 6023,
"s": 5896,
"text": "Launch the JavaFX application by calling the static method launch() of the Application class from the main method as follows."
},
{
"code": null,
"e": 6091,
"s": 6023,
"text": "public static void main(String args[]){ \n launch(args); \n}"
},
{
"code": null,
"e": 6214,
"s": 6091,
"text": "Following is the program which generates a rectangle JavaFX. Save this code in a file with the name RectangleExample.java."
},
{
"code": null,
"e": 7253,
"s": 6214,
"text": "import javafx.application.Application; \nimport javafx.scene.Group; \nimport javafx.scene.Scene; \nimport javafx.stage.Stage; \nimport javafx.scene.shape.Rectangle;\n\npublic class RectangleExample extends Application { \n @Override \n public void start(Stage stage) { \n //Drawing a Rectangle \n Rectangle rectangle = new Rectangle(); \n \n //Setting the properties of the rectangle \n rectangle.setX(150.0f); \n rectangle.setY(75.0f); \n rectangle.setWidth(300.0f); \n rectangle.setHeight(150.0f); \n \n //Creating a Group object \n Group root = new Group(rectangle); \n \n //Creating a scene object \n Scene scene = new Scene(root, 600, 300); \n \n //Setting title to the Stage \n stage.setTitle(\"Drawing a Rectangle\"); \n \n //Adding scene to the stage \n stage.setScene(scene); \n \n //Displaying the contents of the stage \n stage.show(); \n } \n public static void main(String args[]){ \n launch(args); \n } \n} "
},
{
"code": null,
"e": 7347,
"s": 7253,
"text": "Compile and execute the saved java file from the command prompt using the following commands."
},
{
"code": null,
"e": 7399,
"s": 7347,
"text": "javac RectangleExample.java \njava RectangleExample\n"
}
] |
Primorial of a number | 11 May, 2021
Given a number n, the task is to calculate its primorial. Primorial (denoted as Pn#) is a product of first n prime numbers. Primorial of a number is similar to the factorial of a number. In primorial, not all the natural numbers get multiplied only prime numbers are multiplied to calculate the primorial of a number. It is denoted with P#.Examples:
Input: n = 3
Output: 30
Priomorial = 2 * 3 * 5 = 30
As a side note, factorial is 2 * 3 * 4 * 5
Input: n = 5
Output: 2310
Primorial = 2 * 3 * 5 * 7 * 11
A naive approach is to check all numbers from 1 to n one by one is prime or not, if yes then store the multiplication in result, similarly store the result of multiplication of primes till n.An efficient method is to find all the prime up-to n using Sieve of Sundaram and then just calculate the primorial by multiplying them all.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find Primorial of given numbers#include<bits/stdc++.h>using namespace std;const int MAX = 1000000; // vector to store all prime less than and equal to 10^6vector <int> primes; // Function for sieve of sundaram. This function stores all// prime numbers less than MAX in primesvoid sieveSundaram(){ // In general Sieve of Sundaram, produces primes smaller // than (2*x + 2) for a number given number x. Since // we want primes smaller than MAX, we reduce MAX to half // This array is used to separate numbers of the form // i+j+2ij from others where 1 <= i <= j bool marked[MAX/2 + 1] = {0}; // Main logic of Sundaram. Mark all numbers which // do not generate prime number by doing 2*i+1 for (int i = 1; i <= (sqrt(MAX)-1)/2 ; i++) for (int j = (i*(i+1))<<1 ; j <= MAX/2 ; j += 2*i +1) marked[j] = true; // Since 2 is a prime number primes.push_back(2); // Print other primes. Remaining primes are of the // form 2*i + 1 such that marked[i] is false. for (int i=1; i<=MAX/2; i++) if (marked[i] == false) primes.push_back(2*i + 1);} // Function to calculate primorial of nint calculatePrimorial(int n){ // Multiply first n primes int result = 1; for (int i=0; i<n; i++) result = result * primes[i]; return result;} // Driver codeint main(){ int n = 5; sieveSundaram(); for (int i = 1 ; i<= n; i++) cout << "Primorial(P#) of " << i << " is " << calculatePrimorial(i) <<endl; return 0;}
// Java program to find Primorial of given numbersimport java.util.*; class GFG{ public static int MAX = 1000000; // vector to store all prime less than and equal to 10^6static ArrayList<Integer> primes = new ArrayList<Integer>(); // Function for sieve of sundaram. This function stores all// prime numbers less than MAX in primesstatic void sieveSundaram(){ // In general Sieve of Sundaram, produces primes smaller // than (2*x + 2) for a number given number x. Since // we want primes smaller than MAX, we reduce MAX to half // This array is used to separate numbers of the form // i+j+2ij from others where 1 <= i <= j boolean[] marked = new boolean[MAX]; // Main logic of Sundaram. Mark all numbers which // do not generate prime number by doing 2*i+1 for (int i = 1; i <= (Math.sqrt(MAX) - 1) / 2 ; i++) { for (int j = (i * (i + 1)) << 1 ; j <= MAX / 2 ; j += 2 * i + 1) { marked[j] = true; } } // Since 2 is a prime number primes.add(2); // Print other primes. Remaining primes are of the // form 2*i + 1 such that marked[i] is false. for (int i = 1; i <= MAX / 2; i++) { if (marked[i] == false) { primes.add(2 * i + 1); } }} // Function to calculate primorial of nstatic int calculatePrimorial(int n){ // Multiply first n primes int result = 1; for (int i = 0; i < n; i++) { result = result * primes.get(i); } return result;} // Driver codepublic static void main(String[] args){ int n = 5; sieveSundaram(); for (int i = 1 ; i <= n; i++) { System.out.println("Primorial(P#) of "+i+" is "+calculatePrimorial(i)); }}}// This Code is contributed by mits
# Python3 program to find Primorial of given numbersimport mathMAX = 1000000; # vector to store all prime less than and equal to 10^6primes=[]; # Function for sieve of sundaram. This function stores all# prime numbers less than MAX in primesdef sieveSundaram(): # In general Sieve of Sundaram, produces primes smaller # than (2*x + 2) for a number given number x. Since # we want primes smaller than MAX, we reduce MAX to half # This array is used to separate numbers of the form # i+j+2ij from others where 1 <= i <= j marked=[False]*(int(MAX/2)+1); # Main logic of Sundaram. Mark all numbers which # do not generate prime number by doing 2*i+1 for i in range(1,int((math.sqrt(MAX)-1)/2)+1): for j in range(((i*(i+1))<<1),(int(MAX/2)+1),(2*i+1)): marked[j] = True; # Since 2 is a prime number primes.append(2); # Print other primes. Remaining primes are of the # form 2*i + 1 such that marked[i] is false. for i in range(1,int(MAX/2)): if (marked[i] == False): primes.append(2*i + 1); # Function to calculate primorial of ndef calculatePrimorial(n): # Multiply first n primes result = 1; for i in range(n): result = result * primes[i]; return result; # Driver coden = 5;sieveSundaram();for i in range(1,n+1): print("Primorial(P#) of",i,"is",calculatePrimorial(i)); # This code is contributed by mits
// C# program to find Primorial of given numbersusing System;using System.Collections; class GFG{ public static int MAX = 1000000; // vector to store all prime less than and equal to 10^6static ArrayList primes = new ArrayList(); // Function for sieve of sundaram. This function stores all// prime numbers less than MAX in primesstatic void sieveSundaram(){ // In general Sieve of Sundaram, produces primes smaller // than (2*x + 2) for a number given number x. Since // we want primes smaller than MAX, we reduce MAX to half // This array is used to separate numbers of the form // i+j+2ij from others where 1 <= i <= j bool[] marked = new bool[MAX]; // Main logic of Sundaram. Mark all numbers which // do not generate prime number by doing 2*i+1 for (int i = 1; i <= (Math.Sqrt(MAX) - 1) / 2 ; i++) { for (int j = (i * (i + 1)) << 1 ; j <= MAX / 2 ; j += 2 * i + 1) { marked[j] = true; } } // Since 2 is a prime number primes.Add(2); // Print other primes. Remaining primes are of the // form 2*i + 1 such that marked[i] is false. for (int i = 1; i <= MAX / 2; i++) { if (marked[i] == false) { primes.Add(2 * i + 1); } }} // Function to calculate primorial of nstatic int calculatePrimorial(int n){ // Multiply first n primes int result = 1; for (int i = 0; i < n; i++) { result = result * (int)primes[i]; } return result;} // Driver codepublic static void Main(){ int n = 5; sieveSundaram(); for (int i = 1 ; i <= n; i++) { System.Console.WriteLine("Primorial(P#) of "+i+" is "+calculatePrimorial(i)); }}}// This Code is contributed by mits
<?php// PHP program to find Primorial// of given numbers$MAX = 100000; // vector to store all prime less// than and equal to 10^6$primes = array(); // Function for sieve of sundaram.// This function stores all prime// numbers less than MAX in primesfunction sieveSundaram(){ global $MAX, $primes; // In general Sieve of Sundaram, // produces primes smaller than // (2*x + 2) for a number given // number x. Since we want primes // smaller than MAX, we reduce MAX // to half. This array is used to // separate numbers of the form // i+j+2ij from others where 1 <= i <= j $marked = array_fill(0, $MAX / 2 + 1, 0); // Main logic of Sundaram. Mark all numbers which // do not generate prime number by doing 2*i+1 for ($i = 1; $i <= (sqrt($MAX) - 1) / 2 ; $i++) for ($j = ($i * ($i + 1)) << 1 ; $j <= $MAX / 2 ; $j += 2 * $i + 1) $marked[$j] = true; // Since 2 is a prime number array_push($primes, 2); // Print other primes. Remaining primes // are of the form 2*i + 1 such that // marked[i] is false. for ($i = 1; $i <= $MAX / 2; $i++) if ($marked[$i] == false) array_push($primes, (2 * $i + 1));} // Function to calculate primorial of nfunction calculatePrimorial($n){ global $primes; // Multiply first n primes $result = 1; for ($i = 0; $i < $n; $i++) $result = $result * $primes[$i]; return $result;} // Driver code$n = 5;sieveSundaram();for ($i = 1 ; $i<= $n; $i++) echo "Primorial(P#) of " . $i . " is " . calculatePrimorial($i) . "\n"; // This code is contributed by mits?>
<script> // Javascript program to find Primorial// of given numberslet MAX = 100000; // vector to store all prime less// than and equal to 10^6let primes = new Array(); // Function for sieve of sundaram.// This function stores all prime// numbers less than MAX in primesfunction sieveSundaram(){ // In general Sieve of Sundaram, // produces primes smaller than // (2*x + 2) for a number given // number x. Since we want primes // smaller than MAX, we reduce MAX // to half. This array is used to // separate numbers of the form // i+j+2ij from others where 1 <= i <= j let marked = new Array(MAX / 2 + 1).fill(0); // Main logic of Sundaram. Mark all numbers which // do not generate prime number by doing 2*i+1 for (let i = 1; i <= (Math.sqrt(MAX) - 1) / 2 ; i++) for (let j = (i * (i + 1)) << 1 ; j <= MAX / 2 ; j += 2 * i + 1) marked[j] = true; // Since 2 is a prime number primes.push(2); // Print other primes. Remaining primes // are of the form 2*i + 1 such that // marked[i] is false. for (let i = 1; i <= MAX / 2; i++) if (marked[i] == false) primes.push(2 * i + 1);} // Function to calculate primorial of nfunction calculatePrimorial(n){ // Multiply first n primes let result = 1; for (let i = 0; i < n; i++) result = result * primes[i]; return result;} // Driver codelet n = 5;sieveSundaram();for (let i = 1 ; i<= n; i++) document.write("Primorial(P#) of " + i + " is " + calculatePrimorial(i) + "<br>"); // This code is contributed by gfgking </script>
Output:
Primorial(P#) of 1 is 2
Primorial(P#) of 2 is 6
Primorial(P#) of 3 is 30
Primorial(P#) of 4 is 210
Primorial(P#) of 5 is 2310
This article is contributed by Sahil Chhabra (KILLER). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Mithun Kumar
gfgking
factorial
Prime Number
prime-factor
Mathematical
Mathematical
Prime Number
factorial
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n11 May, 2021"
},
{
"code": null,
"e": 405,
"s": 53,
"text": "Given a number n, the task is to calculate its primorial. Primorial (denoted as Pn#) is a product of first n prime numbers. Primorial of a number is similar to the factorial of a number. In primorial, not all the natural numbers get multiplied only prime numbers are multiplied to calculate the primorial of a number. It is denoted with P#.Examples: "
},
{
"code": null,
"e": 560,
"s": 405,
"text": "Input: n = 3\nOutput: 30 \nPriomorial = 2 * 3 * 5 = 30\nAs a side note, factorial is 2 * 3 * 4 * 5\n\nInput: n = 5\nOutput: 2310\nPrimorial = 2 * 3 * 5 * 7 * 11 "
},
{
"code": null,
"e": 894,
"s": 562,
"text": "A naive approach is to check all numbers from 1 to n one by one is prime or not, if yes then store the multiplication in result, similarly store the result of multiplication of primes till n.An efficient method is to find all the prime up-to n using Sieve of Sundaram and then just calculate the primorial by multiplying them all. "
},
{
"code": null,
"e": 898,
"s": 894,
"text": "C++"
},
{
"code": null,
"e": 903,
"s": 898,
"text": "Java"
},
{
"code": null,
"e": 911,
"s": 903,
"text": "Python3"
},
{
"code": null,
"e": 914,
"s": 911,
"text": "C#"
},
{
"code": null,
"e": 918,
"s": 914,
"text": "PHP"
},
{
"code": null,
"e": 929,
"s": 918,
"text": "Javascript"
},
{
"code": "// C++ program to find Primorial of given numbers#include<bits/stdc++.h>using namespace std;const int MAX = 1000000; // vector to store all prime less than and equal to 10^6vector <int> primes; // Function for sieve of sundaram. This function stores all// prime numbers less than MAX in primesvoid sieveSundaram(){ // In general Sieve of Sundaram, produces primes smaller // than (2*x + 2) for a number given number x. Since // we want primes smaller than MAX, we reduce MAX to half // This array is used to separate numbers of the form // i+j+2ij from others where 1 <= i <= j bool marked[MAX/2 + 1] = {0}; // Main logic of Sundaram. Mark all numbers which // do not generate prime number by doing 2*i+1 for (int i = 1; i <= (sqrt(MAX)-1)/2 ; i++) for (int j = (i*(i+1))<<1 ; j <= MAX/2 ; j += 2*i +1) marked[j] = true; // Since 2 is a prime number primes.push_back(2); // Print other primes. Remaining primes are of the // form 2*i + 1 such that marked[i] is false. for (int i=1; i<=MAX/2; i++) if (marked[i] == false) primes.push_back(2*i + 1);} // Function to calculate primorial of nint calculatePrimorial(int n){ // Multiply first n primes int result = 1; for (int i=0; i<n; i++) result = result * primes[i]; return result;} // Driver codeint main(){ int n = 5; sieveSundaram(); for (int i = 1 ; i<= n; i++) cout << \"Primorial(P#) of \" << i << \" is \" << calculatePrimorial(i) <<endl; return 0;}",
"e": 2460,
"s": 929,
"text": null
},
{
"code": "// Java program to find Primorial of given numbersimport java.util.*; class GFG{ public static int MAX = 1000000; // vector to store all prime less than and equal to 10^6static ArrayList<Integer> primes = new ArrayList<Integer>(); // Function for sieve of sundaram. This function stores all// prime numbers less than MAX in primesstatic void sieveSundaram(){ // In general Sieve of Sundaram, produces primes smaller // than (2*x + 2) for a number given number x. Since // we want primes smaller than MAX, we reduce MAX to half // This array is used to separate numbers of the form // i+j+2ij from others where 1 <= i <= j boolean[] marked = new boolean[MAX]; // Main logic of Sundaram. Mark all numbers which // do not generate prime number by doing 2*i+1 for (int i = 1; i <= (Math.sqrt(MAX) - 1) / 2 ; i++) { for (int j = (i * (i + 1)) << 1 ; j <= MAX / 2 ; j += 2 * i + 1) { marked[j] = true; } } // Since 2 is a prime number primes.add(2); // Print other primes. Remaining primes are of the // form 2*i + 1 such that marked[i] is false. for (int i = 1; i <= MAX / 2; i++) { if (marked[i] == false) { primes.add(2 * i + 1); } }} // Function to calculate primorial of nstatic int calculatePrimorial(int n){ // Multiply first n primes int result = 1; for (int i = 0; i < n; i++) { result = result * primes.get(i); } return result;} // Driver codepublic static void main(String[] args){ int n = 5; sieveSundaram(); for (int i = 1 ; i <= n; i++) { System.out.println(\"Primorial(P#) of \"+i+\" is \"+calculatePrimorial(i)); }}}// This Code is contributed by mits",
"e": 4182,
"s": 2460,
"text": null
},
{
"code": "# Python3 program to find Primorial of given numbersimport mathMAX = 1000000; # vector to store all prime less than and equal to 10^6primes=[]; # Function for sieve of sundaram. This function stores all# prime numbers less than MAX in primesdef sieveSundaram(): # In general Sieve of Sundaram, produces primes smaller # than (2*x + 2) for a number given number x. Since # we want primes smaller than MAX, we reduce MAX to half # This array is used to separate numbers of the form # i+j+2ij from others where 1 <= i <= j marked=[False]*(int(MAX/2)+1); # Main logic of Sundaram. Mark all numbers which # do not generate prime number by doing 2*i+1 for i in range(1,int((math.sqrt(MAX)-1)/2)+1): for j in range(((i*(i+1))<<1),(int(MAX/2)+1),(2*i+1)): marked[j] = True; # Since 2 is a prime number primes.append(2); # Print other primes. Remaining primes are of the # form 2*i + 1 such that marked[i] is false. for i in range(1,int(MAX/2)): if (marked[i] == False): primes.append(2*i + 1); # Function to calculate primorial of ndef calculatePrimorial(n): # Multiply first n primes result = 1; for i in range(n): result = result * primes[i]; return result; # Driver coden = 5;sieveSundaram();for i in range(1,n+1): print(\"Primorial(P#) of\",i,\"is\",calculatePrimorial(i)); # This code is contributed by mits",
"e": 5588,
"s": 4182,
"text": null
},
{
"code": "// C# program to find Primorial of given numbersusing System;using System.Collections; class GFG{ public static int MAX = 1000000; // vector to store all prime less than and equal to 10^6static ArrayList primes = new ArrayList(); // Function for sieve of sundaram. This function stores all// prime numbers less than MAX in primesstatic void sieveSundaram(){ // In general Sieve of Sundaram, produces primes smaller // than (2*x + 2) for a number given number x. Since // we want primes smaller than MAX, we reduce MAX to half // This array is used to separate numbers of the form // i+j+2ij from others where 1 <= i <= j bool[] marked = new bool[MAX]; // Main logic of Sundaram. Mark all numbers which // do not generate prime number by doing 2*i+1 for (int i = 1; i <= (Math.Sqrt(MAX) - 1) / 2 ; i++) { for (int j = (i * (i + 1)) << 1 ; j <= MAX / 2 ; j += 2 * i + 1) { marked[j] = true; } } // Since 2 is a prime number primes.Add(2); // Print other primes. Remaining primes are of the // form 2*i + 1 such that marked[i] is false. for (int i = 1; i <= MAX / 2; i++) { if (marked[i] == false) { primes.Add(2 * i + 1); } }} // Function to calculate primorial of nstatic int calculatePrimorial(int n){ // Multiply first n primes int result = 1; for (int i = 0; i < n; i++) { result = result * (int)primes[i]; } return result;} // Driver codepublic static void Main(){ int n = 5; sieveSundaram(); for (int i = 1 ; i <= n; i++) { System.Console.WriteLine(\"Primorial(P#) of \"+i+\" is \"+calculatePrimorial(i)); }}}// This Code is contributed by mits",
"e": 7297,
"s": 5588,
"text": null
},
{
"code": "<?php// PHP program to find Primorial// of given numbers$MAX = 100000; // vector to store all prime less// than and equal to 10^6$primes = array(); // Function for sieve of sundaram.// This function stores all prime// numbers less than MAX in primesfunction sieveSundaram(){ global $MAX, $primes; // In general Sieve of Sundaram, // produces primes smaller than // (2*x + 2) for a number given // number x. Since we want primes // smaller than MAX, we reduce MAX // to half. This array is used to // separate numbers of the form // i+j+2ij from others where 1 <= i <= j $marked = array_fill(0, $MAX / 2 + 1, 0); // Main logic of Sundaram. Mark all numbers which // do not generate prime number by doing 2*i+1 for ($i = 1; $i <= (sqrt($MAX) - 1) / 2 ; $i++) for ($j = ($i * ($i + 1)) << 1 ; $j <= $MAX / 2 ; $j += 2 * $i + 1) $marked[$j] = true; // Since 2 is a prime number array_push($primes, 2); // Print other primes. Remaining primes // are of the form 2*i + 1 such that // marked[i] is false. for ($i = 1; $i <= $MAX / 2; $i++) if ($marked[$i] == false) array_push($primes, (2 * $i + 1));} // Function to calculate primorial of nfunction calculatePrimorial($n){ global $primes; // Multiply first n primes $result = 1; for ($i = 0; $i < $n; $i++) $result = $result * $primes[$i]; return $result;} // Driver code$n = 5;sieveSundaram();for ($i = 1 ; $i<= $n; $i++) echo \"Primorial(P#) of \" . $i . \" is \" . calculatePrimorial($i) . \"\\n\"; // This code is contributed by mits?>",
"e": 8921,
"s": 7297,
"text": null
},
{
"code": "<script> // Javascript program to find Primorial// of given numberslet MAX = 100000; // vector to store all prime less// than and equal to 10^6let primes = new Array(); // Function for sieve of sundaram.// This function stores all prime// numbers less than MAX in primesfunction sieveSundaram(){ // In general Sieve of Sundaram, // produces primes smaller than // (2*x + 2) for a number given // number x. Since we want primes // smaller than MAX, we reduce MAX // to half. This array is used to // separate numbers of the form // i+j+2ij from others where 1 <= i <= j let marked = new Array(MAX / 2 + 1).fill(0); // Main logic of Sundaram. Mark all numbers which // do not generate prime number by doing 2*i+1 for (let i = 1; i <= (Math.sqrt(MAX) - 1) / 2 ; i++) for (let j = (i * (i + 1)) << 1 ; j <= MAX / 2 ; j += 2 * i + 1) marked[j] = true; // Since 2 is a prime number primes.push(2); // Print other primes. Remaining primes // are of the form 2*i + 1 such that // marked[i] is false. for (let i = 1; i <= MAX / 2; i++) if (marked[i] == false) primes.push(2 * i + 1);} // Function to calculate primorial of nfunction calculatePrimorial(n){ // Multiply first n primes let result = 1; for (let i = 0; i < n; i++) result = result * primes[i]; return result;} // Driver codelet n = 5;sieveSundaram();for (let i = 1 ; i<= n; i++) document.write(\"Primorial(P#) of \" + i + \" is \" + calculatePrimorial(i) + \"<br>\"); // This code is contributed by gfgking </script>",
"e": 10518,
"s": 8921,
"text": null
},
{
"code": null,
"e": 10528,
"s": 10518,
"text": "Output: "
},
{
"code": null,
"e": 10654,
"s": 10528,
"text": "Primorial(P#) of 1 is 2\nPrimorial(P#) of 2 is 6\nPrimorial(P#) of 3 is 30\nPrimorial(P#) of 4 is 210\nPrimorial(P#) of 5 is 2310"
},
{
"code": null,
"e": 11085,
"s": 10654,
"text": "This article is contributed by Sahil Chhabra (KILLER). 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": 11098,
"s": 11085,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 11106,
"s": 11098,
"text": "gfgking"
},
{
"code": null,
"e": 11116,
"s": 11106,
"text": "factorial"
},
{
"code": null,
"e": 11129,
"s": 11116,
"text": "Prime Number"
},
{
"code": null,
"e": 11142,
"s": 11129,
"text": "prime-factor"
},
{
"code": null,
"e": 11155,
"s": 11142,
"text": "Mathematical"
},
{
"code": null,
"e": 11168,
"s": 11155,
"text": "Mathematical"
},
{
"code": null,
"e": 11181,
"s": 11168,
"text": "Prime Number"
},
{
"code": null,
"e": 11191,
"s": 11181,
"text": "factorial"
}
] |
How to update the State of a component in ReactJS ? | 27 Sep, 2021
The State is an instance of React Component that can be defined as an object of a set of observable properties that control the behavior of the component. In other words, the State of a component is an object that holds some information that may change over the lifetime of the component. The state of a component can be updated during the lifetime.
Generally, there are two types of components in React. The Class Based Components and Functional Components. The method by which we can update the State of a component is different in these two types of components. We are going to learn them one by one.
Creating react application:
Step 1: Create a React application using the following command:
npx create-react-app name_of_the_app
Step 2: After creating the react application move to the directory as per your app name using the following command:
cd name_of_the_app
Project Structure: Now open your application folder in an editor. You will see the following file structure:
1. Update the State of Class-Based Components: Now we are going to learn how to update the state of a class-based component. The steps are discussed below.
Go inside the App.js file and clear everything.
At the top of the App.js file import React,{Component} from ‘react‘.
Create a Class based component named ‘App’. This is the default App component that we have reconstructed.
Create a state object named text, using this.state syntax. Give it a value.
Create another method inside the class and update the state of the component using ‘this.setState()’ method.
Pass the state object in a JSX element and call the method to update the state on a specific event like button click.
Example :
Filename: App.js
Javascript
// The App.js fileimport React,{Component} from 'react'; class App extends Component { constructor(){ super() this.state={ text : 'Welcome to Geeksforgeeks' } } goPremium(){ this.setState({ text:'Subscription successful' }) } render() { return ( <div> <h1>{this.state.text}</h1> <button onClick={() => this.goPremium()}> Go Premium </button> </div> ); }} export default App;
Step to run the application: Open the terminal and type the following command.
npm start
Output:
2. Update the State of functional Components: The steps for updating the state of a functional component are given below.
Clear everything inside the App component of the App.js file.
At the top of the App.js file import React, {useState} from “react”.
Inside the App component create a state named ‘text’ using the following syntax. This is the built-in useState method for react functional components. :
const [state, setState] = useState({text:'Default value of the text state'});
Pass the ‘text’ state to the JSX element using ‘{state.text}’ method.
Update the state on a specific event like button click using the ‘setState’ method. The syntax is given below :
setState({text:'Updated Content'})
Example:
Filename: App.js
Javascript
// App.js fileimport React, {useState} from "react"; function App(){ const [state, setState] = useState({ text:'Welcome to Geeksforgeeks' }); return ( <div> <h1>{state.text}</h1> <button onClick={() => setState({ text:'Subscription successful' })}> Go Premium </button> </div> );}; export default App;
Step to run the application: Open the terminal and type the following command.
npm start
Output:
saurabh1990aror
Blogathon-2021
Picked
React-Questions
Blogathon
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Import JSON Data into SQL Server?
SQL Query to Convert Datetime to Date
Python program to convert XML to Dictionary
Scrape LinkedIn Using Selenium And Beautiful Soup in Python
How to toggle password visibility in forms using Bootstrap-icons ?
How to fetch data from an API in ReactJS ?
How to redirect to another page in ReactJS ?
Axios in React: A Guide for Beginners
ReactJS Functional Components | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n27 Sep, 2021"
},
{
"code": null,
"e": 404,
"s": 54,
"text": "The State is an instance of React Component that can be defined as an object of a set of observable properties that control the behavior of the component. In other words, the State of a component is an object that holds some information that may change over the lifetime of the component. The state of a component can be updated during the lifetime."
},
{
"code": null,
"e": 658,
"s": 404,
"text": "Generally, there are two types of components in React. The Class Based Components and Functional Components. The method by which we can update the State of a component is different in these two types of components. We are going to learn them one by one."
},
{
"code": null,
"e": 686,
"s": 658,
"text": "Creating react application:"
},
{
"code": null,
"e": 750,
"s": 686,
"text": "Step 1: Create a React application using the following command:"
},
{
"code": null,
"e": 787,
"s": 750,
"text": "npx create-react-app name_of_the_app"
},
{
"code": null,
"e": 904,
"s": 787,
"text": "Step 2: After creating the react application move to the directory as per your app name using the following command:"
},
{
"code": null,
"e": 923,
"s": 904,
"text": "cd name_of_the_app"
},
{
"code": null,
"e": 1032,
"s": 923,
"text": "Project Structure: Now open your application folder in an editor. You will see the following file structure:"
},
{
"code": null,
"e": 1188,
"s": 1032,
"text": "1. Update the State of Class-Based Components: Now we are going to learn how to update the state of a class-based component. The steps are discussed below."
},
{
"code": null,
"e": 1236,
"s": 1188,
"text": "Go inside the App.js file and clear everything."
},
{
"code": null,
"e": 1305,
"s": 1236,
"text": "At the top of the App.js file import React,{Component} from ‘react‘."
},
{
"code": null,
"e": 1411,
"s": 1305,
"text": "Create a Class based component named ‘App’. This is the default App component that we have reconstructed."
},
{
"code": null,
"e": 1487,
"s": 1411,
"text": "Create a state object named text, using this.state syntax. Give it a value."
},
{
"code": null,
"e": 1596,
"s": 1487,
"text": "Create another method inside the class and update the state of the component using ‘this.setState()’ method."
},
{
"code": null,
"e": 1714,
"s": 1596,
"text": "Pass the state object in a JSX element and call the method to update the state on a specific event like button click."
},
{
"code": null,
"e": 1724,
"s": 1714,
"text": "Example :"
},
{
"code": null,
"e": 1741,
"s": 1724,
"text": "Filename: App.js"
},
{
"code": null,
"e": 1752,
"s": 1741,
"text": "Javascript"
},
{
"code": "// The App.js fileimport React,{Component} from 'react'; class App extends Component { constructor(){ super() this.state={ text : 'Welcome to Geeksforgeeks' } } goPremium(){ this.setState({ text:'Subscription successful' }) } render() { return ( <div> <h1>{this.state.text}</h1> <button onClick={() => this.goPremium()}> Go Premium </button> </div> ); }} export default App;",
"e": 2234,
"s": 1752,
"text": null
},
{
"code": null,
"e": 2314,
"s": 2234,
"text": "Step to run the application: Open the terminal and type the following command. "
},
{
"code": null,
"e": 2324,
"s": 2314,
"text": "npm start"
},
{
"code": null,
"e": 2332,
"s": 2324,
"text": "Output:"
},
{
"code": null,
"e": 2454,
"s": 2332,
"text": "2. Update the State of functional Components: The steps for updating the state of a functional component are given below."
},
{
"code": null,
"e": 2516,
"s": 2454,
"text": "Clear everything inside the App component of the App.js file."
},
{
"code": null,
"e": 2585,
"s": 2516,
"text": "At the top of the App.js file import React, {useState} from “react”."
},
{
"code": null,
"e": 2738,
"s": 2585,
"text": "Inside the App component create a state named ‘text’ using the following syntax. This is the built-in useState method for react functional components. :"
},
{
"code": null,
"e": 2816,
"s": 2738,
"text": "const [state, setState] = useState({text:'Default value of the text state'});"
},
{
"code": null,
"e": 2886,
"s": 2816,
"text": "Pass the ‘text’ state to the JSX element using ‘{state.text}’ method."
},
{
"code": null,
"e": 2998,
"s": 2886,
"text": "Update the state on a specific event like button click using the ‘setState’ method. The syntax is given below :"
},
{
"code": null,
"e": 3033,
"s": 2998,
"text": "setState({text:'Updated Content'})"
},
{
"code": null,
"e": 3042,
"s": 3033,
"text": "Example:"
},
{
"code": null,
"e": 3059,
"s": 3042,
"text": "Filename: App.js"
},
{
"code": null,
"e": 3070,
"s": 3059,
"text": "Javascript"
},
{
"code": "// App.js fileimport React, {useState} from \"react\"; function App(){ const [state, setState] = useState({ text:'Welcome to Geeksforgeeks' }); return ( <div> <h1>{state.text}</h1> <button onClick={() => setState({ text:'Subscription successful' })}> Go Premium </button> </div> );}; export default App;",
"e": 3475,
"s": 3070,
"text": null
},
{
"code": null,
"e": 3556,
"s": 3475,
"text": " Step to run the application: Open the terminal and type the following command. "
},
{
"code": null,
"e": 3566,
"s": 3556,
"text": "npm start"
},
{
"code": null,
"e": 3574,
"s": 3566,
"text": "Output:"
},
{
"code": null,
"e": 3592,
"s": 3576,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 3607,
"s": 3592,
"text": "Blogathon-2021"
},
{
"code": null,
"e": 3614,
"s": 3607,
"text": "Picked"
},
{
"code": null,
"e": 3630,
"s": 3614,
"text": "React-Questions"
},
{
"code": null,
"e": 3640,
"s": 3630,
"text": "Blogathon"
},
{
"code": null,
"e": 3648,
"s": 3640,
"text": "ReactJS"
},
{
"code": null,
"e": 3665,
"s": 3648,
"text": "Web Technologies"
},
{
"code": null,
"e": 3763,
"s": 3665,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3804,
"s": 3763,
"text": "How to Import JSON Data into SQL Server?"
},
{
"code": null,
"e": 3842,
"s": 3804,
"text": "SQL Query to Convert Datetime to Date"
},
{
"code": null,
"e": 3886,
"s": 3842,
"text": "Python program to convert XML to Dictionary"
},
{
"code": null,
"e": 3946,
"s": 3886,
"text": "Scrape LinkedIn Using Selenium And Beautiful Soup in Python"
},
{
"code": null,
"e": 4013,
"s": 3946,
"text": "How to toggle password visibility in forms using Bootstrap-icons ?"
},
{
"code": null,
"e": 4056,
"s": 4013,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 4101,
"s": 4056,
"text": "How to redirect to another page in ReactJS ?"
},
{
"code": null,
"e": 4139,
"s": 4101,
"text": "Axios in React: A Guide for Beginners"
}
] |
How to convert Set to Array in JavaScript? | 21 Jul, 2021
A set can be converted to an array in JavaScript by the following way-
By using Array.from() method:This method returns a new Array from an array like object or iterable objects like Map, Set, etc.SyntaxArray.from(arrayLike object);Example-1<!DOCTYPE html><html> <head> <title> Convert Set to Array </title></head> <body> <center> <h1 style="color:green"> GeeksforGeeks </h1> <script> const set = new Set(['welcome', 'to', 'GFG']); Array.from(set); document.write(Array.from(set)); </script> </center></body> </html>Output
Array.from(arrayLike object);
Example-1
<!DOCTYPE html><html> <head> <title> Convert Set to Array </title></head> <body> <center> <h1 style="color:green"> GeeksforGeeks </h1> <script> const set = new Set(['welcome', 'to', 'GFG']); Array.from(set); document.write(Array.from(set)); </script> </center></body> </html>
Output
Using spread operator:Using of spread operator can also help us convert Set to array.Syntaxvar variablename = [...value]; Example-2:<!DOCTYPE html><html> <head> <title> Convert Set to Array </title></head> <body> <center> <h1 style="color:green"> GeeksforGeeks </h1> <script> const set = new Set(['GFG', 'JS']); const array = [...set]; document.write(array); </script> </center></body> </html>Output
var variablename = [...value];
Example-2:
<!DOCTYPE html><html> <head> <title> Convert Set to Array </title></head> <body> <center> <h1 style="color:green"> GeeksforGeeks </h1> <script> const set = new Set(['GFG', 'JS']); const array = [...set]; document.write(array); </script> </center></body> </html>
Output
Using forEach:Example-3:<!DOCTYPE html><html> <head> <title> Convert Set to Array </title></head> <body> <center> <h1 style="color:green"> GeeksforGeeks </h1> <script> var gfgSet = new Set(); var gfgArray = []; gfgSet.add("Geeks"); gfgSet.add("for"); // duplicate item gfgSet.add("Geeks"); var someFunction = function( val1, val2, setItself) { gfgArray.push(val1); }; gfgSet.forEach(someFunction); document.write("Array: " + gfgArray); </script> </center></body> </html>Output
<!DOCTYPE html><html> <head> <title> Convert Set to Array </title></head> <body> <center> <h1 style="color:green"> GeeksforGeeks </h1> <script> var gfgSet = new Set(); var gfgArray = []; gfgSet.add("Geeks"); gfgSet.add("for"); // duplicate item gfgSet.add("Geeks"); var someFunction = function( val1, val2, setItself) { gfgArray.push(val1); }; gfgSet.forEach(someFunction); document.write("Array: " + gfgArray); </script> </center></body> </html>
Output
Supported Browsers:
Google Chrome
Firefox
Edge
Opera
Apple Safari
JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.
javascript-array
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
How to append HTML code to a div using JavaScript ?
Difference Between PUT and PATCH Request
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Jul, 2021"
},
{
"code": null,
"e": 99,
"s": 28,
"text": "A set can be converted to an array in JavaScript by the following way-"
},
{
"code": null,
"e": 658,
"s": 99,
"text": "By using Array.from() method:This method returns a new Array from an array like object or iterable objects like Map, Set, etc.SyntaxArray.from(arrayLike object);Example-1<!DOCTYPE html><html> <head> <title> Convert Set to Array </title></head> <body> <center> <h1 style=\"color:green\"> GeeksforGeeks </h1> <script> const set = new Set(['welcome', 'to', 'GFG']); Array.from(set); document.write(Array.from(set)); </script> </center></body> </html>Output"
},
{
"code": null,
"e": 688,
"s": 658,
"text": "Array.from(arrayLike object);"
},
{
"code": null,
"e": 698,
"s": 688,
"text": "Example-1"
},
{
"code": "<!DOCTYPE html><html> <head> <title> Convert Set to Array </title></head> <body> <center> <h1 style=\"color:green\"> GeeksforGeeks </h1> <script> const set = new Set(['welcome', 'to', 'GFG']); Array.from(set); document.write(Array.from(set)); </script> </center></body> </html>",
"e": 1081,
"s": 698,
"text": null
},
{
"code": null,
"e": 1088,
"s": 1081,
"text": "Output"
},
{
"code": null,
"e": 1596,
"s": 1088,
"text": "Using spread operator:Using of spread operator can also help us convert Set to array.Syntaxvar variablename = [...value]; Example-2:<!DOCTYPE html><html> <head> <title> Convert Set to Array </title></head> <body> <center> <h1 style=\"color:green\"> GeeksforGeeks </h1> <script> const set = new Set(['GFG', 'JS']); const array = [...set]; document.write(array); </script> </center></body> </html>Output"
},
{
"code": null,
"e": 1628,
"s": 1596,
"text": "var variablename = [...value]; "
},
{
"code": null,
"e": 1639,
"s": 1628,
"text": "Example-2:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> Convert Set to Array </title></head> <body> <center> <h1 style=\"color:green\"> GeeksforGeeks </h1> <script> const set = new Set(['GFG', 'JS']); const array = [...set]; document.write(array); </script> </center></body> </html>",
"e": 2009,
"s": 1639,
"text": null
},
{
"code": null,
"e": 2016,
"s": 2009,
"text": "Output"
},
{
"code": null,
"e": 2692,
"s": 2016,
"text": "Using forEach:Example-3:<!DOCTYPE html><html> <head> <title> Convert Set to Array </title></head> <body> <center> <h1 style=\"color:green\"> GeeksforGeeks </h1> <script> var gfgSet = new Set(); var gfgArray = []; gfgSet.add(\"Geeks\"); gfgSet.add(\"for\"); // duplicate item gfgSet.add(\"Geeks\"); var someFunction = function( val1, val2, setItself) { gfgArray.push(val1); }; gfgSet.forEach(someFunction); document.write(\"Array: \" + gfgArray); </script> </center></body> </html>Output"
},
{
"code": "<!DOCTYPE html><html> <head> <title> Convert Set to Array </title></head> <body> <center> <h1 style=\"color:green\"> GeeksforGeeks </h1> <script> var gfgSet = new Set(); var gfgArray = []; gfgSet.add(\"Geeks\"); gfgSet.add(\"for\"); // duplicate item gfgSet.add(\"Geeks\"); var someFunction = function( val1, val2, setItself) { gfgArray.push(val1); }; gfgSet.forEach(someFunction); document.write(\"Array: \" + gfgArray); </script> </center></body> </html>",
"e": 3338,
"s": 2692,
"text": null
},
{
"code": null,
"e": 3345,
"s": 3338,
"text": "Output"
},
{
"code": null,
"e": 3365,
"s": 3345,
"text": "Supported Browsers:"
},
{
"code": null,
"e": 3379,
"s": 3365,
"text": "Google Chrome"
},
{
"code": null,
"e": 3387,
"s": 3379,
"text": "Firefox"
},
{
"code": null,
"e": 3392,
"s": 3387,
"text": "Edge"
},
{
"code": null,
"e": 3398,
"s": 3392,
"text": "Opera"
},
{
"code": null,
"e": 3411,
"s": 3398,
"text": "Apple Safari"
},
{
"code": null,
"e": 3630,
"s": 3411,
"text": "JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples."
},
{
"code": null,
"e": 3647,
"s": 3630,
"text": "javascript-array"
},
{
"code": null,
"e": 3654,
"s": 3647,
"text": "Picked"
},
{
"code": null,
"e": 3665,
"s": 3654,
"text": "JavaScript"
},
{
"code": null,
"e": 3682,
"s": 3665,
"text": "Web Technologies"
},
{
"code": null,
"e": 3780,
"s": 3682,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3841,
"s": 3780,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3913,
"s": 3841,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 3953,
"s": 3913,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 4005,
"s": 3953,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 4046,
"s": 4005,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 4108,
"s": 4046,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 4141,
"s": 4108,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 4202,
"s": 4141,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 4252,
"s": 4202,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
PyQt5 – How to change font and size of Label text ? | 26 Mar, 2020
A label is a graphical control element which displays text on a form. A label is generally used to identify a nearby text box or other widget. Some labels can respond to events such as mouse clicks, allowing the text of the label to be copied, but this is not standard user-interface practice.
In this article, we will see how to change the font and size of the text in Label, we can do this by using setFont() method.
Syntax : label.setFont(QFont(font_name, size))
Argument : It take two argument :1. Font name it can be ‘Arial’, ‘Times’ etc.2. Size to be set in integer.
Below is the Python implementation –
# importing the required libraries from PyQt5.QtWidgets import * from PyQt5.QtGui import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # set the title self.setWindowTitle("Label") # setting the geometry of window self.setGeometry(0, 0, 400, 300) # creating a label widget # by default label will display at top left corner self.label_1 = QLabel('Arial font', self) # moving position self.label_1.move(100, 100) # setting font and size self.label_1.setFont(QFont('Arial', 10)) # creating a label widget # by default label will display at top left corner self.label_2 = QLabel('Times font', self) # moving position self.label_2.move(100, 120) # setting font and size self.label_2.setFont(QFont('Times', 10)) # show all the widgets self.show() # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
Output :
Python-gui
Python-PyQt
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, 2020"
},
{
"code": null,
"e": 322,
"s": 28,
"text": "A label is a graphical control element which displays text on a form. A label is generally used to identify a nearby text box or other widget. Some labels can respond to events such as mouse clicks, allowing the text of the label to be copied, but this is not standard user-interface practice."
},
{
"code": null,
"e": 447,
"s": 322,
"text": "In this article, we will see how to change the font and size of the text in Label, we can do this by using setFont() method."
},
{
"code": null,
"e": 494,
"s": 447,
"text": "Syntax : label.setFont(QFont(font_name, size))"
},
{
"code": null,
"e": 601,
"s": 494,
"text": "Argument : It take two argument :1. Font name it can be ‘Arial’, ‘Times’ etc.2. Size to be set in integer."
},
{
"code": null,
"e": 638,
"s": 601,
"text": "Below is the Python implementation –"
},
{
"code": "# importing the required libraries from PyQt5.QtWidgets import * from PyQt5.QtGui import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # set the title self.setWindowTitle(\"Label\") # setting the geometry of window self.setGeometry(0, 0, 400, 300) # creating a label widget # by default label will display at top left corner self.label_1 = QLabel('Arial font', self) # moving position self.label_1.move(100, 100) # setting font and size self.label_1.setFont(QFont('Arial', 10)) # creating a label widget # by default label will display at top left corner self.label_2 = QLabel('Times font', self) # moving position self.label_2.move(100, 120) # setting font and size self.label_2.setFont(QFont('Times', 10)) # show all the widgets self.show() # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())",
"e": 1728,
"s": 638,
"text": null
},
{
"code": null,
"e": 1737,
"s": 1728,
"text": "Output :"
},
{
"code": null,
"e": 1748,
"s": 1737,
"text": "Python-gui"
},
{
"code": null,
"e": 1760,
"s": 1748,
"text": "Python-PyQt"
},
{
"code": null,
"e": 1767,
"s": 1760,
"text": "Python"
}
] |
How to find top-N records using MapReduce | 11 Feb, 2022
Finding top 10 or 20 records from a large dataset is the heart of many recommendation systems and it is also an important attribute for data analysis. Here, we will discuss the two methods to find top-N records as follows.Method 1: First, let’s find out top-10 most viewed movies to understand the methods and then we will generalize it for ‘n’ records.Data format:
movie_name and no_of_views (tab separated)
Approach Used: Using TreeMap. Here, the idea is to use Mappers to find local top 10 records, as there can be many Mappers running parallelly on different blocks of data of a file. And then all these local top 10 records will be aggregated at Reducer where we find top 10 global records for the file.Example: Assume that file(30 TB) is divided into 3 blocks of 10 TB each and each block is processed by a Mapper parallelly so we find top 10 records (local) for that block. Then this data moves to the reducer where we find the actual top 10 records from the file movie.txt. Movie.txt file: You can see the whole file by click here
Mapper code:
Java
import java.io.*;import java.util.*;import org.apache.hadoop.io.Text;import org.apache.hadoop.io.LongWritable;import org.apache.hadoop.mapreduce.Mapper; public class top_10_Movies_Mapper extends Mapper<Object, Text, Text, LongWritable> { private TreeMap<Long, String> tmap; @Override public void setup(Context context) throws IOException, InterruptedException { tmap = new TreeMap<Long, String>(); } @Override public void map(Object key, Text value, Context context) throws IOException, InterruptedException { // input data format => movie_name // no_of_views (tab separated) // we split the input data String[] tokens = value.toString().split("\t"); String movie_name = tokens[0]; long no_of_views = Long.parseLong(tokens[1]); // insert data into treeMap, // we want top 10 viewed movies // so we pass no_of_views as key tmap.put(no_of_views, movie_name); // we remove the first key-value // if it's size increases 10 if (tmap.size() > 10) { tmap.remove(tmap.firstKey()); } } @Override public void cleanup(Context context) throws IOException, InterruptedException { for (Map.Entry<Long, String> entry : tmap.entrySet()) { long count = entry.getKey(); String name = entry.getValue(); context.write(new Text(name), new LongWritable(count)); } }}
Explanation: The important point to note here is that we use “context.write()” in cleanup() method which runs only once at the end in the lifetime of Mapper. Mapper processes one key-value pair at a time and writes them as intermediate output on local disk. But we have to process whole block (all key-value pairs) to find top10, before writing the output, hence we use context.write() in cleanup().Reducer code:
Java
import java.io.IOException;import java.util.Map;import java.util.TreeMap; import org.apache.hadoop.io.LongWritable;import org.apache.hadoop.io.Text;import org.apache.hadoop.mapreduce.Reducer; public class top_10_Movies_Reducer extends Reducer<Text, LongWritable, LongWritable, Text> { private TreeMap<Long, String> tmap2; @Override public void setup(Context context) throws IOException, InterruptedException { tmap2 = new TreeMap<Long, String>(); } @Override public void reduce(Text key, Iterable<LongWritable> values, Context context) throws IOException, InterruptedException { // input data from mapper // key values // movie_name [ count ] String name = key.toString(); long count = 0; for (LongWritable val : values) { count = val.get(); } // insert data into treeMap, // we want top 10 viewed movies // so we pass count as key tmap2.put(count, name); // we remove the first key-value // if it's size increases 10 if (tmap2.size() > 10) { tmap2.remove(tmap2.firstKey()); } } @Override public void cleanup(Context context) throws IOException, InterruptedException { for (Map.Entry<Long, String> entry : tmap2.entrySet()) { long count = entry.getKey(); String name = entry.getValue(); context.write(new LongWritable(count), new Text(name)); } }}
Explanation: Same logic as mapper. Reducer processes one key-value pair at a time and writes them as final output on HDFS. But we have to process all key-value pairs to find top10, before writing the output, hence we use cleanup().Driver Code:
Java
import org.apache.hadoop.conf.Configuration;import org.apache.hadoop.fs.Path;import org.apache.hadoop.io.LongWritable;import org.apache.hadoop.io.Text;import org.apache.hadoop.mapreduce.Job;import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;import org.apache.hadoop.util.GenericOptionsParser; public class Driver { public static void main(String[] args) throws Exception { Configuration conf = new Configuration(); String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs(); // if less than two paths // provided will show error if (otherArgs.length < 2) { System.err.println("Error: please provide two paths"); System.exit(2); } Job job = Job.getInstance(conf, "top 10"); job.setJarByClass(Driver.class); job.setMapperClass(top_10_Movies_Mapper.class); job.setReducerClass(top_10_Movies_Reducer.class); job.setMapOutputKeyClass(Text.class); job.setMapOutputValueClass(LongWritable.class); job.setOutputKeyClass(LongWritable.class); job.setOutputValueClass(Text.class); FileInputFormat.addInputPath(job, new Path(otherArgs[0])); FileOutputFormat.setOutputPath(job, new Path(otherArgs[1])); System.exit(job.waitForCompletion(true) ? 0 : 1); }}
Running the jar file:
We export all the classes as jar files.
We move our file movie.txt from local file system to /geeksInput in HDFS.
bin/hdfs dfs -put ../Desktop/movie.txt /geeksInput
We now run the yarn services to run the jar file.
bin/yarn jar jar_file_location package_Name.Driver_classname input_path output_path
We make our custom parameter using set() method
configuration_object.set(String name, String value)
This value can be accessed in any Mapper/Reducer by using get() method
Configuration conf = context.getConfiguration();
// we will store value in String variable
String value = conf.get(String name);
saurabh1990aror
sweetyty
MapReduce
Hadoop
Hadoop
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 Feb, 2022"
},
{
"code": null,
"e": 395,
"s": 28,
"text": "Finding top 10 or 20 records from a large dataset is the heart of many recommendation systems and it is also an important attribute for data analysis. Here, we will discuss the two methods to find top-N records as follows.Method 1: First, let’s find out top-10 most viewed movies to understand the methods and then we will generalize it for ‘n’ records.Data format: "
},
{
"code": null,
"e": 438,
"s": 395,
"text": "movie_name and no_of_views (tab separated)"
},
{
"code": null,
"e": 1069,
"s": 438,
"text": "Approach Used: Using TreeMap. Here, the idea is to use Mappers to find local top 10 records, as there can be many Mappers running parallelly on different blocks of data of a file. And then all these local top 10 records will be aggregated at Reducer where we find top 10 global records for the file.Example: Assume that file(30 TB) is divided into 3 blocks of 10 TB each and each block is processed by a Mapper parallelly so we find top 10 records (local) for that block. Then this data moves to the reducer where we find the actual top 10 records from the file movie.txt. Movie.txt file: You can see the whole file by click here "
},
{
"code": null,
"e": 1085,
"s": 1071,
"text": "Mapper code: "
},
{
"code": null,
"e": 1090,
"s": 1085,
"text": "Java"
},
{
"code": "import java.io.*;import java.util.*;import org.apache.hadoop.io.Text;import org.apache.hadoop.io.LongWritable;import org.apache.hadoop.mapreduce.Mapper; public class top_10_Movies_Mapper extends Mapper<Object, Text, Text, LongWritable> { private TreeMap<Long, String> tmap; @Override public void setup(Context context) throws IOException, InterruptedException { tmap = new TreeMap<Long, String>(); } @Override public void map(Object key, Text value, Context context) throws IOException, InterruptedException { // input data format => movie_name // no_of_views (tab separated) // we split the input data String[] tokens = value.toString().split(\"\\t\"); String movie_name = tokens[0]; long no_of_views = Long.parseLong(tokens[1]); // insert data into treeMap, // we want top 10 viewed movies // so we pass no_of_views as key tmap.put(no_of_views, movie_name); // we remove the first key-value // if it's size increases 10 if (tmap.size() > 10) { tmap.remove(tmap.firstKey()); } } @Override public void cleanup(Context context) throws IOException, InterruptedException { for (Map.Entry<Long, String> entry : tmap.entrySet()) { long count = entry.getKey(); String name = entry.getValue(); context.write(new Text(name), new LongWritable(count)); } }}",
"e": 2694,
"s": 1090,
"text": null
},
{
"code": null,
"e": 3108,
"s": 2694,
"text": "Explanation: The important point to note here is that we use “context.write()” in cleanup() method which runs only once at the end in the lifetime of Mapper. Mapper processes one key-value pair at a time and writes them as intermediate output on local disk. But we have to process whole block (all key-value pairs) to find top10, before writing the output, hence we use context.write() in cleanup().Reducer code: "
},
{
"code": null,
"e": 3113,
"s": 3108,
"text": "Java"
},
{
"code": "import java.io.IOException;import java.util.Map;import java.util.TreeMap; import org.apache.hadoop.io.LongWritable;import org.apache.hadoop.io.Text;import org.apache.hadoop.mapreduce.Reducer; public class top_10_Movies_Reducer extends Reducer<Text, LongWritable, LongWritable, Text> { private TreeMap<Long, String> tmap2; @Override public void setup(Context context) throws IOException, InterruptedException { tmap2 = new TreeMap<Long, String>(); } @Override public void reduce(Text key, Iterable<LongWritable> values, Context context) throws IOException, InterruptedException { // input data from mapper // key values // movie_name [ count ] String name = key.toString(); long count = 0; for (LongWritable val : values) { count = val.get(); } // insert data into treeMap, // we want top 10 viewed movies // so we pass count as key tmap2.put(count, name); // we remove the first key-value // if it's size increases 10 if (tmap2.size() > 10) { tmap2.remove(tmap2.firstKey()); } } @Override public void cleanup(Context context) throws IOException, InterruptedException { for (Map.Entry<Long, String> entry : tmap2.entrySet()) { long count = entry.getKey(); String name = entry.getValue(); context.write(new LongWritable(count), new Text(name)); } }}",
"e": 4734,
"s": 3113,
"text": null
},
{
"code": null,
"e": 4979,
"s": 4734,
"text": "Explanation: Same logic as mapper. Reducer processes one key-value pair at a time and writes them as final output on HDFS. But we have to process all key-value pairs to find top10, before writing the output, hence we use cleanup().Driver Code: "
},
{
"code": null,
"e": 4984,
"s": 4979,
"text": "Java"
},
{
"code": "import org.apache.hadoop.conf.Configuration;import org.apache.hadoop.fs.Path;import org.apache.hadoop.io.LongWritable;import org.apache.hadoop.io.Text;import org.apache.hadoop.mapreduce.Job;import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;import org.apache.hadoop.util.GenericOptionsParser; public class Driver { public static void main(String[] args) throws Exception { Configuration conf = new Configuration(); String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs(); // if less than two paths // provided will show error if (otherArgs.length < 2) { System.err.println(\"Error: please provide two paths\"); System.exit(2); } Job job = Job.getInstance(conf, \"top 10\"); job.setJarByClass(Driver.class); job.setMapperClass(top_10_Movies_Mapper.class); job.setReducerClass(top_10_Movies_Reducer.class); job.setMapOutputKeyClass(Text.class); job.setMapOutputValueClass(LongWritable.class); job.setOutputKeyClass(LongWritable.class); job.setOutputValueClass(Text.class); FileInputFormat.addInputPath(job, new Path(otherArgs[0])); FileOutputFormat.setOutputPath(job, new Path(otherArgs[1])); System.exit(job.waitForCompletion(true) ? 0 : 1); }}",
"e": 6416,
"s": 4984,
"text": null
},
{
"code": null,
"e": 6440,
"s": 6416,
"text": "Running the jar file: "
},
{
"code": null,
"e": 6480,
"s": 6440,
"text": "We export all the classes as jar files."
},
{
"code": null,
"e": 6556,
"s": 6480,
"text": "We move our file movie.txt from local file system to /geeksInput in HDFS. "
},
{
"code": null,
"e": 6608,
"s": 6556,
"text": "bin/hdfs dfs -put ../Desktop/movie.txt /geeksInput"
},
{
"code": null,
"e": 6660,
"s": 6608,
"text": "We now run the yarn services to run the jar file. "
},
{
"code": null,
"e": 6751,
"s": 6660,
"text": "bin/yarn jar jar_file_location package_Name.Driver_classname input_path output_path "
},
{
"code": null,
"e": 6804,
"s": 6755,
"text": "We make our custom parameter using set() method "
},
{
"code": null,
"e": 6856,
"s": 6804,
"text": "configuration_object.set(String name, String value)"
},
{
"code": null,
"e": 6930,
"s": 6858,
"text": "This value can be accessed in any Mapper/Reducer by using get() method "
},
{
"code": null,
"e": 7078,
"s": 6930,
"text": "Configuration conf = context.getConfiguration();\n\n// we will store value in String variable\nString value = conf.get(String name); "
},
{
"code": null,
"e": 7096,
"s": 7080,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 7105,
"s": 7096,
"text": "sweetyty"
},
{
"code": null,
"e": 7115,
"s": 7105,
"text": "MapReduce"
},
{
"code": null,
"e": 7122,
"s": 7115,
"text": "Hadoop"
},
{
"code": null,
"e": 7129,
"s": 7122,
"text": "Hadoop"
}
] |
LongStream sum() in Java - GeeksforGeeks | 06 Dec, 2018
LongStream sum() returns the sum of elements in this stream. This is a special case of a reduction. LongStream sum() is a terminal operation i.e, it may traverse the stream to produce a result or a side-effect.
Note : A reduction operation (also called a fold) takes a sequence of input elements and combines them into a single summary result by repeated application of a combining operation, such as finding the sum or maximum of a set of numbers.
Syntax :
long sum()
Return Value : The function returns the sum of elements in this stream.
Example 1 :
// Java code for LongStream.sum() to// find the sum of elements in LongStreamimport java.util.*;import java.util.stream.LongStream; class GFG { // Driver code public static void main(String[] args) { // Creating an LongStream LongStream stream = LongStream.of(2L, 4L, 6L, -2L, -4L); // Using LongStream.sum() to find // sum of elements in LongStream long sumOfElements = stream.sum(); // Displaying the calculated sum System.out.println(sumOfElements); }}
6
Example 2 :
// Java code for LongStream.sum() to// find the sum of elements// divisible by 3 in given rangeimport java.util.*;import java.util.stream.LongStream; class GFG { // Driver code public static void main(String[] args) { // Using LongStream.sum() to find // sum of elements dividible by 3 // in given range long sumOfElements = LongStream.range(2L, 10L) .filter(num -> num % 3 == 0) .sum(); // Displaying the calculated sum System.out.println(sumOfElements); }}
18
Java - util package
Java-Functions
java-longstream
java-stream
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Functional Interfaces in Java
Stream In Java
Constructors in Java
Different ways of Reading a text file in Java
Exceptions in Java
Generics in Java
Comparator Interface in Java with Examples
Strings in Java
Difference between Abstract Class and Interface in Java
How to remove an element from ArrayList in Java? | [
{
"code": null,
"e": 23557,
"s": 23529,
"text": "\n06 Dec, 2018"
},
{
"code": null,
"e": 23768,
"s": 23557,
"text": "LongStream sum() returns the sum of elements in this stream. This is a special case of a reduction. LongStream sum() is a terminal operation i.e, it may traverse the stream to produce a result or a side-effect."
},
{
"code": null,
"e": 24006,
"s": 23768,
"text": "Note : A reduction operation (also called a fold) takes a sequence of input elements and combines them into a single summary result by repeated application of a combining operation, such as finding the sum or maximum of a set of numbers."
},
{
"code": null,
"e": 24015,
"s": 24006,
"text": "Syntax :"
},
{
"code": null,
"e": 24027,
"s": 24015,
"text": "long sum()\n"
},
{
"code": null,
"e": 24099,
"s": 24027,
"text": "Return Value : The function returns the sum of elements in this stream."
},
{
"code": null,
"e": 24111,
"s": 24099,
"text": "Example 1 :"
},
{
"code": "// Java code for LongStream.sum() to// find the sum of elements in LongStreamimport java.util.*;import java.util.stream.LongStream; class GFG { // Driver code public static void main(String[] args) { // Creating an LongStream LongStream stream = LongStream.of(2L, 4L, 6L, -2L, -4L); // Using LongStream.sum() to find // sum of elements in LongStream long sumOfElements = stream.sum(); // Displaying the calculated sum System.out.println(sumOfElements); }}",
"e": 24635,
"s": 24111,
"text": null
},
{
"code": null,
"e": 24638,
"s": 24635,
"text": "6\n"
},
{
"code": null,
"e": 24650,
"s": 24638,
"text": "Example 2 :"
},
{
"code": "// Java code for LongStream.sum() to// find the sum of elements// divisible by 3 in given rangeimport java.util.*;import java.util.stream.LongStream; class GFG { // Driver code public static void main(String[] args) { // Using LongStream.sum() to find // sum of elements dividible by 3 // in given range long sumOfElements = LongStream.range(2L, 10L) .filter(num -> num % 3 == 0) .sum(); // Displaying the calculated sum System.out.println(sumOfElements); }}",
"e": 25232,
"s": 24650,
"text": null
},
{
"code": null,
"e": 25236,
"s": 25232,
"text": "18\n"
},
{
"code": null,
"e": 25256,
"s": 25236,
"text": "Java - util package"
},
{
"code": null,
"e": 25271,
"s": 25256,
"text": "Java-Functions"
},
{
"code": null,
"e": 25287,
"s": 25271,
"text": "java-longstream"
},
{
"code": null,
"e": 25299,
"s": 25287,
"text": "java-stream"
},
{
"code": null,
"e": 25304,
"s": 25299,
"text": "Java"
},
{
"code": null,
"e": 25309,
"s": 25304,
"text": "Java"
},
{
"code": null,
"e": 25407,
"s": 25309,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25416,
"s": 25407,
"text": "Comments"
},
{
"code": null,
"e": 25429,
"s": 25416,
"text": "Old Comments"
},
{
"code": null,
"e": 25459,
"s": 25429,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 25474,
"s": 25459,
"text": "Stream In Java"
},
{
"code": null,
"e": 25495,
"s": 25474,
"text": "Constructors in Java"
},
{
"code": null,
"e": 25541,
"s": 25495,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 25560,
"s": 25541,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 25577,
"s": 25560,
"text": "Generics in Java"
},
{
"code": null,
"e": 25620,
"s": 25577,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 25636,
"s": 25620,
"text": "Strings in Java"
},
{
"code": null,
"e": 25692,
"s": 25636,
"text": "Difference between Abstract Class and Interface in Java"
}
] |
Using MALLET LDA to Learn Why Players Hate Pokémon Sword /Shield | by Adeline Ong | Towards Data Science | The latest Pokémon game for Nintendo Switch launched with fanfare, promising to wow fans with stunning visuals and an open-world adventure. Despite praise from critics, the game was a let-down for most players. In this article, I will walk you through how I used MALLET Latent Dirichlet Allocation (LDA) to find out key reasons why players didn’t like the game.
I used BeautifulSoup to scrap Pokémon Sword and Shield user reviews from Metacritic (I’ve detailed the steps here). Metacritic reviews have rating scores that indicate users’ overall evaluation of the game. This makes our lives easier since we won’t need to run a separate sentiment analysis to find negative reviews.
In total, I collected 3,261 user reviews that were posted from 15 to 28 November 2019. The dataset contained these features:
name: reviewer's username
date: date of review
rating: numeric score ranging from 0 to 10 that gives an overall evaluation of the game. Higher scores indicate a more positive experience.
review: actual review text
The following packages were used for data cleaning and analysis: numpy, pandas, regex, string, nltk, langdetect, sklearn, spaCy, gensim, pprint (optional), matplotlib, and collections.
You will also need to install gensim’s wrapper for MALLET LDA, if you don’t already have it.
Importing logging is also optional, but it’s a best practice as it enables you to have a sense of what’s happening behind the scenes when the model is running.
import numpy as np import pandas as pdimport re import stringimport nltkfrom langdetect import detectfrom sklearn.feature_extraction.text import CountVectorizer import spacyfrom spacy.lang.en.stop_words import STOP_WORDSimport gensimfrom gensim import corpora, models, matutilsfrom gensim.models import CoherenceModelimport osfrom gensim.models.wrappers import LdaMalletmallet_path = '/Users/adelweiss/mallet-2.0.8/bin/mallet'from pprint import pprint #optionalimport matplotlib.pyplot as plt%matplotlib inlinefrom collections import Counterimport logging #optionallogging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
Label the reviews positive, negative or mixed. Metacritic considers scores less than 5 as negative, those 5 to 7 as mixed, and anything above 7 as positive. In the code below, I defined a function to label the reviews based on these rules.
Label the reviews positive, negative or mixed. Metacritic considers scores less than 5 as negative, those 5 to 7 as mixed, and anything above 7 as positive. In the code below, I defined a function to label the reviews based on these rules.
def sentiment(x): if x > 7: return 'positive' if x < 5: return 'negative' else: return 'mixed'df['sentiment'] = df['rating'].apply(lambda x:sentiment(x))
Drop duplicate user reviews. Some users posted the same review for both Pokémon Sword and Shield (which is expected, since both games only slightly differ in their content).
Drop duplicate user reviews. Some users posted the same review for both Pokémon Sword and Shield (which is expected, since both games only slightly differ in their content).
df.drop_duplicates(subset='name', keep = 'first', inplace = True)
2. Filter out non-English reviews. To do this, I used langdetect package, which relies on Google’s language detection library and supports 55 languages. The detect function reads a text input, calculates the probability of the text being in the supported languages, and returns the language that has the highest probability.
def language_detection(x): result = detect(x) if result == 'en':return x else: return np.NaN df['review'] = df['review'].apply(lambda x:language_detection(x))
3. Remove stopwords. I combined stopwords from nltk and spaCy, and added custom stopwords such as ‘game’, ‘pokemon’ and ‘pokémon’.
The custom stopwords were added after inspecting each word’s review frequency (e.g. a frequency of 5 means that the word appeared in 5 reviews. More about this in Step 6.). The custom stopwords appeared in a large majority of reviews. Their high frequency across reviews implies that that they are not useful for topic modeling. Consequently, I removed them in subsequent runs to improve model performance.
The code creates a list of stopwords. These words will be removed from the reviews in the next step.
nltk_stop_words = nltk.corpus.stopwords.words('english')stop_words = list(STOP_WORDS)stop_words.extend(['game','pokemon','pokémon']) ### these are common words that appear in almost all reviewsfor word in nltk_stop_words: if word in stop_words: continue else: stop_words.append(word)
4. Text cleaning. This is a list of standard text cleaning steps mostly using regex:
Cast all words in lowercase
Remove words from a list (we will use this to remove stopwords, and rare words that appear in less than 4 reviews)
Remove digits
Remove punctuation
Replace words (to standardize inconsistencies in spelling that I noticed such as ‘game freak’ and ‘gamefreak’)
Remove ‘\r’ string literals
Strip extra whitespaces from words (i.e. two whitespaces in a row), which result from the functions that remove digits, punctuation and string literals
def make_lower(text): return text.lower()def remove_words(text,wordlist): for word in wordlist: if word in text.split(): text = re.sub(r'\b{}\b'.format(word), '', text) return textdef remove_digits(text): return re.sub('\d', ' ', text)def remove_punctuation(text): text = re.sub('[%s]' % re.escape(string.punctuation), ' ', text) return re.sub(r'[^\w\s]', ' ', text)def strip_extraspace(text): return re.sub('\s\s+',' ', text)def replace_word(text,word,replacement): return text.replace(word,replacement)def remove_r(text): return text.replace('\r',' ')#df['review'] = df['review'].apply(lambda x:remove_punctuation(x))def clean_text(text): text = make_lower(text) text = remove_punctuation(text) text = remove_digits(text) text = replace_word(text,'game freak','gamefreak') text = replace_word(text, 'game play', 'gameplay') text = remove_words(text,stop_words) text = remove_r(text) text = strip_extraspace(text) return textdf['review'] = df['review'].apply(lambda x:clean_text(x))
5. Lemmatizing. I used spaCy’s lemmatizer with parts of speech tagging to reduce the reviews to nouns and verbs. Using only nouns and verbs makes it easier to discern what the topics are about.
The code below loops through each word in a review and returns words that are tagged as ‘nouns ’or ‘verbs’. It skips through words that have been lemmatized to ‘-PRON-’ which is what spaCy returns when a word is a pronoun, as well as lemmatized words that are in the stopwords list.
sp = spacy.load('en_core_web_sm')def lemmatize_words(text, allowed_postags=['NOUN', 'ADJ', 'VERB', ‘ADV’]): text = sp(text) lemmed_string ='' for word in text: if word.pos_ in allowed_postags: if word.lemma_ == '-PRON-' or word.lemma_ in stop_words: ### skip words that are not in allowed postags or becomes a stopword when lemmatised continue else: lemmed_string = lemmed_string+' '+word.lemma_ return lemmed_string.lstrip()df['review'] = df['review'].apply(lambda x:lemmatize_words(x, allowed_postags=['NOUN', 'VERB']))
6. Removing rare words. Rare words that do not appear in a substantial number of reviews are also not useful for topic modeling. As with stopwords, I removed them to improve model performance.
This code counts the number of times a word appears across reviews, and appends words that appeared in less than 4 reviews into a list.
word_frequency = Counter()for text in df.review: text = text.split() word_frequency.update(set(text))rare_words = []for key, value in word_frequency.items(): if value < 4: rare_words.append(key)df['review'] = df['review'].apply(lambda x:remove_words(x,rare_words))
7. Select only negative reviews, and create tokens. Finally, since we’re only interested in negative reviews, I filtered the reviews based on their sentiment labels and applied sklearn’s CountVectorizer to create word tokens.
CountVectorizer’s token_pattern argument specifies that only words that have at least 3 characters should be included. My assumption is that 1 and 2-letter words are not very informative, and less useful for topic modeling. Also, the ngram_range argument is set to (1,2) to include bigrams as tokens.
negative = df[df['sentiment']=='negative']vectorizer = CountVectorizer(stop_words=stop_words, ngram_range = (1,2), token_pattern="\\b[a-z][a-z][a-z]+\\b")
To use MALLET LDA, we’ll need to fit and transform the data using the vectorizer and create some variables that the model needs. First, we fit the CountVectorizer to our negative reviews. Then, we create a document-word matrix and convert it from a sparse matrix into a gensim word corpus. Following this, we create word2id and id2word variables that match words to their numeric token ids and vice versa and save these variables into a dictionary.
vectorizer.fit(negative.review)doc_word = vectorizer.transform(negative.review).transpose()corpus = matutils.Sparse2Corpus(doc_word)word2id = dict((v, k) for v, k in vectorizer.vocabulary_.items())id2word = dict((v, k) for k, v in vectorizer.vocabulary_.items())dictionary = corpora.Dictionary()dictionary.id2token = id2worddictionary.token2id = word2id
To choose the number of topics, we’ll calculate coherence scores for each number of topics specified.
Coherence scores assess the quality of the topics by examining the degree of semantic similarity between each topic’s top words. The higher the score, the better the model.
To calculate the coherence score for each mode, I used the code below that I found here under Section 17. The code loops through a range of numbers, representing the number of topics to apply to the model, calculates the coherence score for each model, saves the scores and plots them.
def compute_coherence_values(dictionary, corpus, texts, limit, start=2, step=3): """ Compute c_v coherence for various number of topics Parameters: ---------- dictionary : Gensim dictionary corpus : Gensim corpus texts : List of input texts limit : Max num of topics Returns: ------- model_list : List of LDA topic models coherence_values : Coherence values corresponding to the LDA model with respective number of topics """ coherence_values = [] model_list = [] for num_topics in range(start, limit, step): model = gensim.models.wrappers.LdaMallet(mallet_path, corpus=corpus, num_topics=num_topics, id2word=id2word) model_list.append(model) coherencemodel = CoherenceModel(model=model, texts=texts, dictionary=dictionary, coherence='c_v') coherence_values.append(coherencemodel.get_coherence()) return model_list, coherence_values# Can take a long time to run.model_list, coherence_values = compute_coherence_values(dictionary=id2word, corpus=corpus, texts=data_lemmatized, start=2, limit=40, step=6)# Show graphlimit=40; start=2; step=6;x = range(start, limit, step)plt.plot(x, coherence_values)plt.xlabel("Num Topics")plt.ylabel("Coherence score")plt.legend(("coherence_values"), loc='best')plt.show()
According to the graph, 2 or 5 would be good numbers to choose from since their coherence scores are the highest. However, choosing 2 topics might be oversimplifying things, so let’s go with 5.
To look at the top 10 words that are most associated with each topic, we re-run the model specifying 5 topics, and use show_topics. You can use a simple print statement instead, but pprint makes things easier to read.
ldamallet = LdaMallet(mallet_path, corpus=corpus, num_topics=5, id2word=id2word, random_seed = 77)# Show Topicspprint(ldamallet.show_topics(formatted=False))
Below are the top words for each topic, and my labels for them. Most of the topics are related to the gameplay, except the last one. Since we only looked at negative reviews, we can assume that these are problem areas.
Here’s a quick overview of each topic after inspecting the reviews:
Time: Play time was too short. Many players completed the game in 10 to 25 hours
Experience: The story was lacking, and overall game play was too easy. Moreover, the much hyped-up wild area was poorly animated, and mostly empty.
Visuals: Animation, graphics, and models lacked quality and texture. Expectations were sky high on the visuals because Game Freak cited this as the reason for cutting out so many Pokémon from the game.
Content: Players often compared the switch games to the 3DS games, which had a lot more features, content, and available Pokémon.
Developer: Players felt betrayed by Game Freak because it did not deliver on its promise of stunning visuals. They felt Game Freak lied to them, and that the cut in Pokémon was not justified.
LDA is a good way of finding topics within texts, especially when it’s used for exploratory purposes. I think MALLET LDA gave a pretty good overview of why players hated the game. I did a quick exploration of the positive reviews, and two broad topics came up: gameplay and positive feelings. Perhaps, this might be the case of new players who started Pokémon on the switch (and are hence using Let’s Go as a benchmark) versus seasoned players who are more used to complex gameplay.
**Code can be found here** | [
{
"code": null,
"e": 535,
"s": 172,
"text": "The latest Pokémon game for Nintendo Switch launched with fanfare, promising to wow fans with stunning visuals and an open-world adventure. Despite praise from critics, the game was a let-down for most players. In this article, I will walk you through how I used MALLET Latent Dirichlet Allocation (LDA) to find out key reasons why players didn’t like the game."
},
{
"code": null,
"e": 854,
"s": 535,
"text": "I used BeautifulSoup to scrap Pokémon Sword and Shield user reviews from Metacritic (I’ve detailed the steps here). Metacritic reviews have rating scores that indicate users’ overall evaluation of the game. This makes our lives easier since we won’t need to run a separate sentiment analysis to find negative reviews."
},
{
"code": null,
"e": 979,
"s": 854,
"text": "In total, I collected 3,261 user reviews that were posted from 15 to 28 November 2019. The dataset contained these features:"
},
{
"code": null,
"e": 1005,
"s": 979,
"text": "name: reviewer's username"
},
{
"code": null,
"e": 1026,
"s": 1005,
"text": "date: date of review"
},
{
"code": null,
"e": 1166,
"s": 1026,
"text": "rating: numeric score ranging from 0 to 10 that gives an overall evaluation of the game. Higher scores indicate a more positive experience."
},
{
"code": null,
"e": 1193,
"s": 1166,
"text": "review: actual review text"
},
{
"code": null,
"e": 1378,
"s": 1193,
"text": "The following packages were used for data cleaning and analysis: numpy, pandas, regex, string, nltk, langdetect, sklearn, spaCy, gensim, pprint (optional), matplotlib, and collections."
},
{
"code": null,
"e": 1471,
"s": 1378,
"text": "You will also need to install gensim’s wrapper for MALLET LDA, if you don’t already have it."
},
{
"code": null,
"e": 1631,
"s": 1471,
"text": "Importing logging is also optional, but it’s a best practice as it enables you to have a sense of what’s happening behind the scenes when the model is running."
},
{
"code": null,
"e": 2288,
"s": 1631,
"text": "import numpy as np import pandas as pdimport re import stringimport nltkfrom langdetect import detectfrom sklearn.feature_extraction.text import CountVectorizer import spacyfrom spacy.lang.en.stop_words import STOP_WORDSimport gensimfrom gensim import corpora, models, matutilsfrom gensim.models import CoherenceModelimport osfrom gensim.models.wrappers import LdaMalletmallet_path = '/Users/adelweiss/mallet-2.0.8/bin/mallet'from pprint import pprint #optionalimport matplotlib.pyplot as plt%matplotlib inlinefrom collections import Counterimport logging #optionallogging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)"
},
{
"code": null,
"e": 2528,
"s": 2288,
"text": "Label the reviews positive, negative or mixed. Metacritic considers scores less than 5 as negative, those 5 to 7 as mixed, and anything above 7 as positive. In the code below, I defined a function to label the reviews based on these rules."
},
{
"code": null,
"e": 2768,
"s": 2528,
"text": "Label the reviews positive, negative or mixed. Metacritic considers scores less than 5 as negative, those 5 to 7 as mixed, and anything above 7 as positive. In the code below, I defined a function to label the reviews based on these rules."
},
{
"code": null,
"e": 2945,
"s": 2768,
"text": "def sentiment(x): if x > 7: return 'positive' if x < 5: return 'negative' else: return 'mixed'df['sentiment'] = df['rating'].apply(lambda x:sentiment(x))"
},
{
"code": null,
"e": 3120,
"s": 2945,
"text": "Drop duplicate user reviews. Some users posted the same review for both Pokémon Sword and Shield (which is expected, since both games only slightly differ in their content)."
},
{
"code": null,
"e": 3295,
"s": 3120,
"text": "Drop duplicate user reviews. Some users posted the same review for both Pokémon Sword and Shield (which is expected, since both games only slightly differ in their content)."
},
{
"code": null,
"e": 3361,
"s": 3295,
"text": "df.drop_duplicates(subset='name', keep = 'first', inplace = True)"
},
{
"code": null,
"e": 3686,
"s": 3361,
"text": "2. Filter out non-English reviews. To do this, I used langdetect package, which relies on Google’s language detection library and supports 55 languages. The detect function reads a text input, calculates the probability of the text being in the supported languages, and returns the language that has the highest probability."
},
{
"code": null,
"e": 3848,
"s": 3686,
"text": "def language_detection(x): result = detect(x) if result == 'en':return x else: return np.NaN df['review'] = df['review'].apply(lambda x:language_detection(x))"
},
{
"code": null,
"e": 3980,
"s": 3848,
"text": "3. Remove stopwords. I combined stopwords from nltk and spaCy, and added custom stopwords such as ‘game’, ‘pokemon’ and ‘pokémon’."
},
{
"code": null,
"e": 4387,
"s": 3980,
"text": "The custom stopwords were added after inspecting each word’s review frequency (e.g. a frequency of 5 means that the word appeared in 5 reviews. More about this in Step 6.). The custom stopwords appeared in a large majority of reviews. Their high frequency across reviews implies that that they are not useful for topic modeling. Consequently, I removed them in subsequent runs to improve model performance."
},
{
"code": null,
"e": 4488,
"s": 4387,
"text": "The code creates a list of stopwords. These words will be removed from the reviews in the next step."
},
{
"code": null,
"e": 4773,
"s": 4488,
"text": "nltk_stop_words = nltk.corpus.stopwords.words('english')stop_words = list(STOP_WORDS)stop_words.extend(['game','pokemon','pokémon']) ### these are common words that appear in almost all reviewsfor word in nltk_stop_words: if word in stop_words: continue else: stop_words.append(word)"
},
{
"code": null,
"e": 4858,
"s": 4773,
"text": "4. Text cleaning. This is a list of standard text cleaning steps mostly using regex:"
},
{
"code": null,
"e": 4886,
"s": 4858,
"text": "Cast all words in lowercase"
},
{
"code": null,
"e": 5001,
"s": 4886,
"text": "Remove words from a list (we will use this to remove stopwords, and rare words that appear in less than 4 reviews)"
},
{
"code": null,
"e": 5015,
"s": 5001,
"text": "Remove digits"
},
{
"code": null,
"e": 5034,
"s": 5015,
"text": "Remove punctuation"
},
{
"code": null,
"e": 5145,
"s": 5034,
"text": "Replace words (to standardize inconsistencies in spelling that I noticed such as ‘game freak’ and ‘gamefreak’)"
},
{
"code": null,
"e": 5173,
"s": 5145,
"text": "Remove ‘\\r’ string literals"
},
{
"code": null,
"e": 5325,
"s": 5173,
"text": "Strip extra whitespaces from words (i.e. two whitespaces in a row), which result from the functions that remove digits, punctuation and string literals"
},
{
"code": null,
"e": 6316,
"s": 5325,
"text": "def make_lower(text): return text.lower()def remove_words(text,wordlist): for word in wordlist: if word in text.split(): text = re.sub(r'\\b{}\\b'.format(word), '', text) return textdef remove_digits(text): return re.sub('\\d', ' ', text)def remove_punctuation(text): text = re.sub('[%s]' % re.escape(string.punctuation), ' ', text) return re.sub(r'[^\\w\\s]', ' ', text)def strip_extraspace(text): return re.sub('\\s\\s+',' ', text)def replace_word(text,word,replacement): return text.replace(word,replacement)def remove_r(text): return text.replace('\\r',' ')#df['review'] = df['review'].apply(lambda x:remove_punctuation(x))def clean_text(text): text = make_lower(text) text = remove_punctuation(text) text = remove_digits(text) text = replace_word(text,'game freak','gamefreak') text = replace_word(text, 'game play', 'gameplay') text = remove_words(text,stop_words) text = remove_r(text) text = strip_extraspace(text) return textdf['review'] = df['review'].apply(lambda x:clean_text(x))"
},
{
"code": null,
"e": 6510,
"s": 6316,
"text": "5. Lemmatizing. I used spaCy’s lemmatizer with parts of speech tagging to reduce the reviews to nouns and verbs. Using only nouns and verbs makes it easier to discern what the topics are about."
},
{
"code": null,
"e": 6793,
"s": 6510,
"text": "The code below loops through each word in a review and returns words that are tagged as ‘nouns ’or ‘verbs’. It skips through words that have been lemmatized to ‘-PRON-’ which is what spaCy returns when a word is a pronoun, as well as lemmatized words that are in the stopwords list."
},
{
"code": null,
"e": 7357,
"s": 6793,
"text": "sp = spacy.load('en_core_web_sm')def lemmatize_words(text, allowed_postags=['NOUN', 'ADJ', 'VERB', ‘ADV’]): text = sp(text) lemmed_string ='' for word in text: if word.pos_ in allowed_postags: if word.lemma_ == '-PRON-' or word.lemma_ in stop_words: ### skip words that are not in allowed postags or becomes a stopword when lemmatised continue else: lemmed_string = lemmed_string+' '+word.lemma_ return lemmed_string.lstrip()df['review'] = df['review'].apply(lambda x:lemmatize_words(x, allowed_postags=['NOUN', 'VERB']))"
},
{
"code": null,
"e": 7550,
"s": 7357,
"text": "6. Removing rare words. Rare words that do not appear in a substantial number of reviews are also not useful for topic modeling. As with stopwords, I removed them to improve model performance."
},
{
"code": null,
"e": 7686,
"s": 7550,
"text": "This code counts the number of times a word appears across reviews, and appends words that appeared in less than 4 reviews into a list."
},
{
"code": null,
"e": 7951,
"s": 7686,
"text": "word_frequency = Counter()for text in df.review: text = text.split() word_frequency.update(set(text))rare_words = []for key, value in word_frequency.items(): if value < 4: rare_words.append(key)df['review'] = df['review'].apply(lambda x:remove_words(x,rare_words))"
},
{
"code": null,
"e": 8177,
"s": 7951,
"text": "7. Select only negative reviews, and create tokens. Finally, since we’re only interested in negative reviews, I filtered the reviews based on their sentiment labels and applied sklearn’s CountVectorizer to create word tokens."
},
{
"code": null,
"e": 8478,
"s": 8177,
"text": "CountVectorizer’s token_pattern argument specifies that only words that have at least 3 characters should be included. My assumption is that 1 and 2-letter words are not very informative, and less useful for topic modeling. Also, the ngram_range argument is set to (1,2) to include bigrams as tokens."
},
{
"code": null,
"e": 8634,
"s": 8478,
"text": "negative = df[df['sentiment']=='negative']vectorizer = CountVectorizer(stop_words=stop_words, ngram_range = (1,2), token_pattern=\"\\\\b[a-z][a-z][a-z]+\\\\b\") "
},
{
"code": null,
"e": 9083,
"s": 8634,
"text": "To use MALLET LDA, we’ll need to fit and transform the data using the vectorizer and create some variables that the model needs. First, we fit the CountVectorizer to our negative reviews. Then, we create a document-word matrix and convert it from a sparse matrix into a gensim word corpus. Following this, we create word2id and id2word variables that match words to their numeric token ids and vice versa and save these variables into a dictionary."
},
{
"code": null,
"e": 9437,
"s": 9083,
"text": "vectorizer.fit(negative.review)doc_word = vectorizer.transform(negative.review).transpose()corpus = matutils.Sparse2Corpus(doc_word)word2id = dict((v, k) for v, k in vectorizer.vocabulary_.items())id2word = dict((v, k) for k, v in vectorizer.vocabulary_.items())dictionary = corpora.Dictionary()dictionary.id2token = id2worddictionary.token2id = word2id"
},
{
"code": null,
"e": 9539,
"s": 9437,
"text": "To choose the number of topics, we’ll calculate coherence scores for each number of topics specified."
},
{
"code": null,
"e": 9712,
"s": 9539,
"text": "Coherence scores assess the quality of the topics by examining the degree of semantic similarity between each topic’s top words. The higher the score, the better the model."
},
{
"code": null,
"e": 9998,
"s": 9712,
"text": "To calculate the coherence score for each mode, I used the code below that I found here under Section 17. The code loops through a range of numbers, representing the number of topics to apply to the model, calculates the coherence score for each model, saves the scores and plots them."
},
{
"code": null,
"e": 11283,
"s": 9998,
"text": "def compute_coherence_values(dictionary, corpus, texts, limit, start=2, step=3): \"\"\" Compute c_v coherence for various number of topics Parameters: ---------- dictionary : Gensim dictionary corpus : Gensim corpus texts : List of input texts limit : Max num of topics Returns: ------- model_list : List of LDA topic models coherence_values : Coherence values corresponding to the LDA model with respective number of topics \"\"\" coherence_values = [] model_list = [] for num_topics in range(start, limit, step): model = gensim.models.wrappers.LdaMallet(mallet_path, corpus=corpus, num_topics=num_topics, id2word=id2word) model_list.append(model) coherencemodel = CoherenceModel(model=model, texts=texts, dictionary=dictionary, coherence='c_v') coherence_values.append(coherencemodel.get_coherence()) return model_list, coherence_values# Can take a long time to run.model_list, coherence_values = compute_coherence_values(dictionary=id2word, corpus=corpus, texts=data_lemmatized, start=2, limit=40, step=6)# Show graphlimit=40; start=2; step=6;x = range(start, limit, step)plt.plot(x, coherence_values)plt.xlabel(\"Num Topics\")plt.ylabel(\"Coherence score\")plt.legend((\"coherence_values\"), loc='best')plt.show()"
},
{
"code": null,
"e": 11477,
"s": 11283,
"text": "According to the graph, 2 or 5 would be good numbers to choose from since their coherence scores are the highest. However, choosing 2 topics might be oversimplifying things, so let’s go with 5."
},
{
"code": null,
"e": 11695,
"s": 11477,
"text": "To look at the top 10 words that are most associated with each topic, we re-run the model specifying 5 topics, and use show_topics. You can use a simple print statement instead, but pprint makes things easier to read."
},
{
"code": null,
"e": 11853,
"s": 11695,
"text": "ldamallet = LdaMallet(mallet_path, corpus=corpus, num_topics=5, id2word=id2word, random_seed = 77)# Show Topicspprint(ldamallet.show_topics(formatted=False))"
},
{
"code": null,
"e": 12072,
"s": 11853,
"text": "Below are the top words for each topic, and my labels for them. Most of the topics are related to the gameplay, except the last one. Since we only looked at negative reviews, we can assume that these are problem areas."
},
{
"code": null,
"e": 12140,
"s": 12072,
"text": "Here’s a quick overview of each topic after inspecting the reviews:"
},
{
"code": null,
"e": 12221,
"s": 12140,
"text": "Time: Play time was too short. Many players completed the game in 10 to 25 hours"
},
{
"code": null,
"e": 12369,
"s": 12221,
"text": "Experience: The story was lacking, and overall game play was too easy. Moreover, the much hyped-up wild area was poorly animated, and mostly empty."
},
{
"code": null,
"e": 12572,
"s": 12369,
"text": "Visuals: Animation, graphics, and models lacked quality and texture. Expectations were sky high on the visuals because Game Freak cited this as the reason for cutting out so many Pokémon from the game."
},
{
"code": null,
"e": 12703,
"s": 12572,
"text": "Content: Players often compared the switch games to the 3DS games, which had a lot more features, content, and available Pokémon."
},
{
"code": null,
"e": 12896,
"s": 12703,
"text": "Developer: Players felt betrayed by Game Freak because it did not deliver on its promise of stunning visuals. They felt Game Freak lied to them, and that the cut in Pokémon was not justified."
},
{
"code": null,
"e": 13380,
"s": 12896,
"text": "LDA is a good way of finding topics within texts, especially when it’s used for exploratory purposes. I think MALLET LDA gave a pretty good overview of why players hated the game. I did a quick exploration of the positive reviews, and two broad topics came up: gameplay and positive feelings. Perhaps, this might be the case of new players who started Pokémon on the switch (and are hence using Let’s Go as a benchmark) versus seasoned players who are more used to complex gameplay."
}
] |
Java super Keyword | ❮ Java Keywords
Using super to call the superclass of Dog
(subclass):
class Animal { // Superclass (parent)
public void animalSound() {
System.out.println("The animal makes a sound");
}
}
class Dog extends Animal { // Subclass (child)
public void animalSound() {
super.animalSound(); // Call the superclass method
System.out.println("The dog says: bow wow");
}
}
public class Main {
public static void main(String args[]) {
Animal myDog = new Dog(); // Create a Dog object
myDog.animalSound(); // Call the method on the Dog object
}
}
Try it Yourself »
The super keyword refers to superclass
(parent) objects.
It is used to call superclass methods, and to access the superclass
constructor.
The most common use of the super keyword is to eliminate
the confusion between superclasses and subclasses that have methods with the
same name.
To understand the super keyword, you should have a basic understanding of Inheritance and Polymorphism.
Read more about inheritance (subclasses and superclasses) in our Java Inheritance Tutorial.
Read more about polymorphism in our Java Polymorphism Tutorial.
❮ Java Keywords
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": 18,
"s": 0,
"text": "\n❮ Java Keywords\n"
},
{
"code": null,
"e": 73,
"s": 18,
"text": "Using super to call the superclass of Dog \n(subclass):"
},
{
"code": null,
"e": 573,
"s": 73,
"text": "class Animal { // Superclass (parent)\n public void animalSound() {\n System.out.println(\"The animal makes a sound\");\n }\n}\n\nclass Dog extends Animal { // Subclass (child)\n public void animalSound() {\n super.animalSound(); // Call the superclass method\n System.out.println(\"The dog says: bow wow\");\n }\n}\n\npublic class Main {\n public static void main(String args[]) {\n Animal myDog = new Dog(); // Create a Dog object\n myDog.animalSound(); // Call the method on the Dog object\n }\n}\n"
},
{
"code": null,
"e": 593,
"s": 573,
"text": "\nTry it Yourself »\n"
},
{
"code": null,
"e": 651,
"s": 593,
"text": "The super keyword refers to superclass \n(parent) objects."
},
{
"code": null,
"e": 733,
"s": 651,
"text": "It is used to call superclass methods, and to access the superclass \nconstructor."
},
{
"code": null,
"e": 880,
"s": 733,
"text": "The most common use of the super keyword is to eliminate \nthe confusion between superclasses and subclasses that have methods with the \nsame name."
},
{
"code": null,
"e": 984,
"s": 880,
"text": "To understand the super keyword, you should have a basic understanding of Inheritance and Polymorphism."
},
{
"code": null,
"e": 1076,
"s": 984,
"text": "Read more about inheritance (subclasses and superclasses) in our Java Inheritance Tutorial."
},
{
"code": null,
"e": 1140,
"s": 1076,
"text": "Read more about polymorphism in our Java Polymorphism Tutorial."
},
{
"code": null,
"e": 1158,
"s": 1140,
"text": "\n❮ Java Keywords\n"
},
{
"code": null,
"e": 1191,
"s": 1158,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 1233,
"s": 1191,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 1340,
"s": 1233,
"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": 1359,
"s": 1340,
"text": "[email protected]"
}
] |
Squares of Matrix Diagonal Elements | 20 Jun, 2022
You have given an integer matrix with odd dimensions. Find the square of the diagonals elements on both sides.
Examples:
Input : 1 2 3
4 5 6
7 8 9
Output : Diagonal one: 1 25 81
Diagonal two: 9 25 49
Input : 2 5 7
3 7 2
5 6 9
Output : Diagonal one : 4 49 81
Diagonal two : 49 49 25
Method 1: Firstly we find the diagonal element of the matrix and then we print the square of that element.
C++
Java
Python3
C#
PHP
// Simple CPP program to print squares of// diagonal elements.#include <iostream>using namespace std; #define MAX 100 // function of diagonal squarevoid diagonalsquare(int mat[][MAX], int row, int column){ // This loop is for finding square of first // diagonal elements cout << "Diagonal one : "; for (int i = 0; i < row; i++) { for (int j = 0; j < column; j++) // if this condition will become true // then we will get diagonal element if (i == j) // printing square of diagonal element cout << mat[i][j] * mat[i][j] << " "; } // This loop is for finding square of second // side of diagonal elements cout << " \n\nDiagonal two : "; for (int i = 0; i < row; i++) { for (int j = 0; j < column; j++) // if this condition will become true // then we will get second side diagonal // element if (i + j == column - 1) // printing square of diagonal element cout << mat[i][j] * mat[i][j] << " "; }} // Driver codeint main(){ int mat[][MAX] = { { 2, 5, 7 }, { 3, 7, 2 }, { 5, 6, 9 } }; diagonalsquare(mat, 3, 3); return 0;}
// Simple JAva program to print squares of// diagonal elements.import java.io.*; class GFG{ static int MAX =100; // function of diagonal square static void diagonalsquare(int mat[][], int row, int column) { // This loop is for finding square of first // diagonal elements System.out.print( "Diagonal one : "); for (int i = 0; i < row; i++) { for (int j = 0; j < column; j++) // if this condition will become true // then we will get diagonal element if (i == j) // printing square of diagonal element System.out.print ( mat[i][j] * mat[i][j] +" "); } System.out.println(); // This loop is for finding square of second // side of diagonal elements System.out.print("Diagonal two : "); for (int i = 0; i < row; i++) { for (int j = 0; j < column; j++) // if this condition will become true // then we will get second side diagonal // element if (i + j == column - 1) // printing square of diagonal element System.out.print(mat[i][j] * mat[i][j] +" "); } } // Driver code public static void main (String[] args) { int mat[][] = { { 2, 5, 7 }, { 3, 7, 2 }, { 5, 6, 9 } }; diagonalsquare(mat, 3, 3); }} // This code is contributed by vt_m.
# Simple Python program# to print squares# of diagonal elements. # function of diagonal squaredef diagonalsquare(mat, row, column) : # This loop is for finding square # of first diagonal elements print ("Diagonal one : ", end = "") for i in range(0, row) : for j in range(0, column) : # if this condition will # become true then we will # get diagonal element if (i == j) : # printing square of # diagonal element print ("{} ".format(mat[i][j] * mat[i][j]), end = "") # This loop is for finding # square of second side # of diagonal elements print (" \n\nDiagonal two : ", end = "") for i in range(0, row) : for j in range(0, column) : # if this condition will become # true then we will get second # side diagonal element if (i + j == column - 1) : # printing square of diagonal # element print ("{} ".format(mat[i][j] * mat[i][j]), end = "") # Driver codemat = [[ 2, 5, 7 ], [ 3, 7, 2 ], [ 5, 6, 9 ]]diagonalsquare(mat, 3, 3) # This code is contributed by# Manish Shaw(manishshaw1)
// Simple C# program to print squares of// diagonal elements.using System; class GFG{ //static int MAX =100; // function of diagonal square static void diagonalsquare(int [,]mat, int row, int column) { // This loop is for finding // square of first // diagonal elements Console.Write( "Diagonal one : "); for (int i = 0; i < row; i++) { for (int j = 0; j < column; j++) // if this condition will become true // then we will get diagonal element if (i == j) // printing square of diagonal element Console.Write ( mat[i,j] * mat[i,j] +" "); } Console.WriteLine(); // This loop is for finding // square of second side of // diagonal elements Console.Write("Diagonal two : "); for (int i = 0; i < row; i++) { for (int j = 0; j < column; j++) // if this condition will become true // then we will get second side diagonal // element if (i + j == column - 1) // printing square of diagonal element Console.Write(mat[i,j] * mat[i,j] +" "); } } // Driver code public static void Main () { int [,]mat = {{ 2, 5, 7 }, { 3, 7, 2 }, { 5, 6, 9 }}; diagonalsquare(mat, 3, 3); }} // This code is contributed by anuj_67.
<?php// Simple PHP program to print squares// of diagonal elements. //$MAX = 100; // function of diagonal squarefunction diagonalsquare($mat, $row, $column){ // This loop is for finding square // of first diagonal elements echo "Diagonal one : "; for ( $i = 0; $i < $row; $i++) { for ( $j = 0; $j < $column; $j++) // if this condition will become true // then we will get diagonal element if ($i == $j) // printing square of diagonal // element echo $mat[$i][$j] * $mat[$i][$j] , " "; } // This loop is for finding square of second // side of diagonal elements echo " \n\nDiagonal two : "; for ( $i = 0; $i < $row; $i++) { for ($j = 0; $j < $column; $j++) // if this condition will become // true then we will get second // side diagonal element if ($i + $j == $column - 1) // printing square of diagonal // element echo $mat[$i][$j] * $mat[$i][$j], " "; }} // Driver code $mat = array(array( 2, 5, 7 ), array( 3, 7, 2 ), array( 5, 6, 9 ) ); diagonalsquare($mat, 3, 3); // This code is contributed by anuj_67.?>
Diagonal one : 4 49 81
Diagonal two : 49 49 25
Time Complexity O(n*n)
Method 2:An efficient solution is also same as in naive approach but in this, we are taking only one loop to find the diagonal element and then we print the square of that element.
C++
Java
Python3
C#
PHP
// Efficient CPP program to print squares of// diagonal elements.#include <iostream>using namespace std; #define MAX 100 // function of diagonal squarevoid diagonalsquare(int mat[][MAX], int row, int column){ // This loop is for finding of square of // the first side of diagonal elements cout << " \nDiagonal one : "; for (int i = 0; i < row; i++) { // printing direct square of diagonal // element there is no need to check // condition cout << mat[i][i] * mat[i][i] << " "; } // This loop is for finding square of the // second side of diagonal elements cout << " \n\nDiagonal two : "; for (int i = 0; i < row; i++) { // printing direct square of diagonal // element in the second side cout << mat[i][row - i - 1] * mat[i][row - i - 1] << " "; }} // Driver codeint main(){ int mat[][MAX] = { { 2, 5, 7 }, { 3, 7, 2 }, { 5, 6, 9 } }; diagonalsquare(mat, 3, 3); return 0;}
// Efficient JAVA program to print squares of// diagonal elements.import java.io.*; class GFG{ static int MAX =100; // function of diagonal square static void diagonalsquare(int mat[][], int row, int column) { // This loop is for finding of square of // the first side of diagonal elements System.out.print (" Diagonal one : "); for (int i = 0; i < row; i++) { // printing direct square of diagonal // element there is no need to check // condition System.out.print( mat[i][i] * mat[i][i] +" "); } System.out.println(); // This loop is for finding square of the // second side of diagonal elements System.out.print( " Diagonal two : "); for (int i = 0; i < row; i++) { // printing direct square of diagonal // element in the second side System.out.print( mat[i][row - i - 1] * mat[i][row - i - 1] + " "); } } // Driver code public static void main (String[] args) { int mat[][] = { { 2, 5, 7 }, { 3, 7, 2 }, { 5, 6, 9 } }; diagonalsquare(mat, 3, 3); }} // This code is contributed by vt_m.
# Efficient Python program# to print squares of# diagonal elements. # function of diagonal squaredef diagonalsquare(mat, row, column) : # This loop is for finding # of square of the first # side of diagonal elements print ("Diagonal one : ", end = "") for i in range(0, row) : # printing direct square # of diagonal element # there is no need to # check condition print (mat[i][i] * mat[i][i], end = " ") # This loop is for finding # square of the second side # of diagonal elements print ("\n\nDiagonal two : ", end = "") for i in range(0, row) : # printing direct square # of diagonal element in # the second side print (mat[i][row - i - 1] * mat[i][row - i - 1] , end = " ") # Driver codemat = [[2, 5, 7 ], [3, 7, 2 ], [5, 6, 9 ]]diagonalsquare(mat, 3, 3) # This code is contributed by# Manish Shaw(manishshaw1)
// Efficient C# program to print// squares of diagonal elements.using System; class GFG { static int MAX =100; // function of diagonal square static void diagonalsquare(int [,] mat, int row, int column) { // This loop is for finding of // square of the first side of // diagonal elements Console.Write ("Diagonal one : "); for (int i = 0; i < row; i++) { // printing direct square of diagonal // element there is no need to check // condition Console.Write(mat[i, i] * mat[i, i] +" "); } Console.WriteLine(); // This loop is for finding square // of the second side of diagonal // elements Console.Write("Diagonal two : "); for (int i = 0; i < row; i++) { // printing direct square of diagonal // element in the second side Console.Write(mat[i, row - i - 1] * mat[i, row - i - 1] + " "); } } // Driver code public static void Main () { int [,] mat = new int[,]{{ 2, 5, 7 }, { 3, 7, 2 }, { 5, 6, 9 }}; diagonalsquare(mat, 3, 3); }} // This code is contributed by KRV.
<?php// Efficient PHP program to print squares of// diagonal elements. $MAX = 100; // function of diagonal squarefunction diagonalsquare( $mat, $row, $column){ // This loop is for finding of square of // the first side of diagonal elements echo " \nDiagonal one : "; for($i = 0; $i < $row; $i++) { // printing direct square of diagonal // element there is no need to check // condition echo $mat[$i][$i] * $mat[$i][$i] , " "; } // This loop is for finding square of the // second side of diagonal elements echo " \n\nDiagonal two : "; for ( $i = 0; $i < $row; $i++) { // printing direct square of diagonal // element in the second side echo $mat[$i][$row - $i - 1] * $mat[$i][$row - $i - 1] , " "; }} // Driver code $mat = array(array(2, 5, 7 ), array(3, 7, 2 ), array(5, 6, 9 )); diagonalsquare($mat, 3, 3); // This code is contributed by anuj_67.?>
Output:
Diagonal one : 4 49 81
Diagonal two : 49 49 25
Time Complexity O(n)Space Complexity O(n^2) for creating 2-Dimensional array
KRV
vt_m
manishshaw1
technophpfij
Matrix
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Matrix Chain Multiplication | DP-8
Program to find largest element in an array
Rat in a Maze | Backtracking-2
Sudoku | Backtracking-7
The Celebrity Problem
Find the number of islands | Set 1 (Using DFS)
Rotate a matrix by 90 degree in clockwise direction without using any extra space
Count all possible paths from top left to bottom right of a mXn matrix
Unique paths in a Grid with Obstacles
Printing all solutions in N-Queen Problem | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n20 Jun, 2022"
},
{
"code": null,
"e": 164,
"s": 53,
"text": "You have given an integer matrix with odd dimensions. Find the square of the diagonals elements on both sides."
},
{
"code": null,
"e": 174,
"s": 164,
"text": "Examples:"
},
{
"code": null,
"e": 405,
"s": 174,
"text": "Input : 1 2 3\n 4 5 6\n 7 8 9\nOutput : Diagonal one: 1 25 81\n Diagonal two: 9 25 49\n\nInput : 2 5 7 \n 3 7 2\n 5 6 9\nOutput : Diagonal one : 4 49 81\n Diagonal two : 49 49 25\n"
},
{
"code": null,
"e": 512,
"s": 405,
"text": "Method 1: Firstly we find the diagonal element of the matrix and then we print the square of that element."
},
{
"code": null,
"e": 516,
"s": 512,
"text": "C++"
},
{
"code": null,
"e": 521,
"s": 516,
"text": "Java"
},
{
"code": null,
"e": 529,
"s": 521,
"text": "Python3"
},
{
"code": null,
"e": 532,
"s": 529,
"text": "C#"
},
{
"code": null,
"e": 536,
"s": 532,
"text": "PHP"
},
{
"code": "// Simple CPP program to print squares of// diagonal elements.#include <iostream>using namespace std; #define MAX 100 // function of diagonal squarevoid diagonalsquare(int mat[][MAX], int row, int column){ // This loop is for finding square of first // diagonal elements cout << \"Diagonal one : \"; for (int i = 0; i < row; i++) { for (int j = 0; j < column; j++) // if this condition will become true // then we will get diagonal element if (i == j) // printing square of diagonal element cout << mat[i][j] * mat[i][j] << \" \"; } // This loop is for finding square of second // side of diagonal elements cout << \" \\n\\nDiagonal two : \"; for (int i = 0; i < row; i++) { for (int j = 0; j < column; j++) // if this condition will become true // then we will get second side diagonal // element if (i + j == column - 1) // printing square of diagonal element cout << mat[i][j] * mat[i][j] << \" \"; }} // Driver codeint main(){ int mat[][MAX] = { { 2, 5, 7 }, { 3, 7, 2 }, { 5, 6, 9 } }; diagonalsquare(mat, 3, 3); return 0;}",
"e": 1834,
"s": 536,
"text": null
},
{
"code": "// Simple JAva program to print squares of// diagonal elements.import java.io.*; class GFG{ static int MAX =100; // function of diagonal square static void diagonalsquare(int mat[][], int row, int column) { // This loop is for finding square of first // diagonal elements System.out.print( \"Diagonal one : \"); for (int i = 0; i < row; i++) { for (int j = 0; j < column; j++) // if this condition will become true // then we will get diagonal element if (i == j) // printing square of diagonal element System.out.print ( mat[i][j] * mat[i][j] +\" \"); } System.out.println(); // This loop is for finding square of second // side of diagonal elements System.out.print(\"Diagonal two : \"); for (int i = 0; i < row; i++) { for (int j = 0; j < column; j++) // if this condition will become true // then we will get second side diagonal // element if (i + j == column - 1) // printing square of diagonal element System.out.print(mat[i][j] * mat[i][j] +\" \"); } } // Driver code public static void main (String[] args) { int mat[][] = { { 2, 5, 7 }, { 3, 7, 2 }, { 5, 6, 9 } }; diagonalsquare(mat, 3, 3); }} // This code is contributed by vt_m.",
"e": 3433,
"s": 1834,
"text": null
},
{
"code": "# Simple Python program# to print squares# of diagonal elements. # function of diagonal squaredef diagonalsquare(mat, row, column) : # This loop is for finding square # of first diagonal elements print (\"Diagonal one : \", end = \"\") for i in range(0, row) : for j in range(0, column) : # if this condition will # become true then we will # get diagonal element if (i == j) : # printing square of # diagonal element print (\"{} \".format(mat[i][j] * mat[i][j]), end = \"\") # This loop is for finding # square of second side # of diagonal elements print (\" \\n\\nDiagonal two : \", end = \"\") for i in range(0, row) : for j in range(0, column) : # if this condition will become # true then we will get second # side diagonal element if (i + j == column - 1) : # printing square of diagonal # element print (\"{} \".format(mat[i][j] * mat[i][j]), end = \"\") # Driver codemat = [[ 2, 5, 7 ], [ 3, 7, 2 ], [ 5, 6, 9 ]]diagonalsquare(mat, 3, 3) # This code is contributed by# Manish Shaw(manishshaw1)",
"e": 4726,
"s": 3433,
"text": null
},
{
"code": "// Simple C# program to print squares of// diagonal elements.using System; class GFG{ //static int MAX =100; // function of diagonal square static void diagonalsquare(int [,]mat, int row, int column) { // This loop is for finding // square of first // diagonal elements Console.Write( \"Diagonal one : \"); for (int i = 0; i < row; i++) { for (int j = 0; j < column; j++) // if this condition will become true // then we will get diagonal element if (i == j) // printing square of diagonal element Console.Write ( mat[i,j] * mat[i,j] +\" \"); } Console.WriteLine(); // This loop is for finding // square of second side of // diagonal elements Console.Write(\"Diagonal two : \"); for (int i = 0; i < row; i++) { for (int j = 0; j < column; j++) // if this condition will become true // then we will get second side diagonal // element if (i + j == column - 1) // printing square of diagonal element Console.Write(mat[i,j] * mat[i,j] +\" \"); } } // Driver code public static void Main () { int [,]mat = {{ 2, 5, 7 }, { 3, 7, 2 }, { 5, 6, 9 }}; diagonalsquare(mat, 3, 3); }} // This code is contributed by anuj_67.",
"e": 6314,
"s": 4726,
"text": null
},
{
"code": "<?php// Simple PHP program to print squares// of diagonal elements. //$MAX = 100; // function of diagonal squarefunction diagonalsquare($mat, $row, $column){ // This loop is for finding square // of first diagonal elements echo \"Diagonal one : \"; for ( $i = 0; $i < $row; $i++) { for ( $j = 0; $j < $column; $j++) // if this condition will become true // then we will get diagonal element if ($i == $j) // printing square of diagonal // element echo $mat[$i][$j] * $mat[$i][$j] , \" \"; } // This loop is for finding square of second // side of diagonal elements echo \" \\n\\nDiagonal two : \"; for ( $i = 0; $i < $row; $i++) { for ($j = 0; $j < $column; $j++) // if this condition will become // true then we will get second // side diagonal element if ($i + $j == $column - 1) // printing square of diagonal // element echo $mat[$i][$j] * $mat[$i][$j], \" \"; }} // Driver code $mat = array(array( 2, 5, 7 ), array( 3, 7, 2 ), array( 5, 6, 9 ) ); diagonalsquare($mat, 3, 3); // This code is contributed by anuj_67.?>",
"e": 7697,
"s": 6314,
"text": null
},
{
"code": null,
"e": 7749,
"s": 7697,
"text": "Diagonal one : 4 49 81 \n\nDiagonal two : 49 49 25"
},
{
"code": null,
"e": 7772,
"s": 7749,
"text": "Time Complexity O(n*n)"
},
{
"code": null,
"e": 7953,
"s": 7772,
"text": "Method 2:An efficient solution is also same as in naive approach but in this, we are taking only one loop to find the diagonal element and then we print the square of that element."
},
{
"code": null,
"e": 7957,
"s": 7953,
"text": "C++"
},
{
"code": null,
"e": 7962,
"s": 7957,
"text": "Java"
},
{
"code": null,
"e": 7970,
"s": 7962,
"text": "Python3"
},
{
"code": null,
"e": 7973,
"s": 7970,
"text": "C#"
},
{
"code": null,
"e": 7977,
"s": 7973,
"text": "PHP"
},
{
"code": "// Efficient CPP program to print squares of// diagonal elements.#include <iostream>using namespace std; #define MAX 100 // function of diagonal squarevoid diagonalsquare(int mat[][MAX], int row, int column){ // This loop is for finding of square of // the first side of diagonal elements cout << \" \\nDiagonal one : \"; for (int i = 0; i < row; i++) { // printing direct square of diagonal // element there is no need to check // condition cout << mat[i][i] * mat[i][i] << \" \"; } // This loop is for finding square of the // second side of diagonal elements cout << \" \\n\\nDiagonal two : \"; for (int i = 0; i < row; i++) { // printing direct square of diagonal // element in the second side cout << mat[i][row - i - 1] * mat[i][row - i - 1] << \" \"; }} // Driver codeint main(){ int mat[][MAX] = { { 2, 5, 7 }, { 3, 7, 2 }, { 5, 6, 9 } }; diagonalsquare(mat, 3, 3); return 0;}",
"e": 9028,
"s": 7977,
"text": null
},
{
"code": "// Efficient JAVA program to print squares of// diagonal elements.import java.io.*; class GFG{ static int MAX =100; // function of diagonal square static void diagonalsquare(int mat[][], int row, int column) { // This loop is for finding of square of // the first side of diagonal elements System.out.print (\" Diagonal one : \"); for (int i = 0; i < row; i++) { // printing direct square of diagonal // element there is no need to check // condition System.out.print( mat[i][i] * mat[i][i] +\" \"); } System.out.println(); // This loop is for finding square of the // second side of diagonal elements System.out.print( \" Diagonal two : \"); for (int i = 0; i < row; i++) { // printing direct square of diagonal // element in the second side System.out.print( mat[i][row - i - 1] * mat[i][row - i - 1] + \" \"); } } // Driver code public static void main (String[] args) { int mat[][] = { { 2, 5, 7 }, { 3, 7, 2 }, { 5, 6, 9 } }; diagonalsquare(mat, 3, 3); }} // This code is contributed by vt_m.",
"e": 10327,
"s": 9028,
"text": null
},
{
"code": "# Efficient Python program# to print squares of# diagonal elements. # function of diagonal squaredef diagonalsquare(mat, row, column) : # This loop is for finding # of square of the first # side of diagonal elements print (\"Diagonal one : \", end = \"\") for i in range(0, row) : # printing direct square # of diagonal element # there is no need to # check condition print (mat[i][i] * mat[i][i], end = \" \") # This loop is for finding # square of the second side # of diagonal elements print (\"\\n\\nDiagonal two : \", end = \"\") for i in range(0, row) : # printing direct square # of diagonal element in # the second side print (mat[i][row - i - 1] * mat[i][row - i - 1] , end = \" \") # Driver codemat = [[2, 5, 7 ], [3, 7, 2 ], [5, 6, 9 ]]diagonalsquare(mat, 3, 3) # This code is contributed by# Manish Shaw(manishshaw1)",
"e": 11394,
"s": 10327,
"text": null
},
{
"code": "// Efficient C# program to print// squares of diagonal elements.using System; class GFG { static int MAX =100; // function of diagonal square static void diagonalsquare(int [,] mat, int row, int column) { // This loop is for finding of // square of the first side of // diagonal elements Console.Write (\"Diagonal one : \"); for (int i = 0; i < row; i++) { // printing direct square of diagonal // element there is no need to check // condition Console.Write(mat[i, i] * mat[i, i] +\" \"); } Console.WriteLine(); // This loop is for finding square // of the second side of diagonal // elements Console.Write(\"Diagonal two : \"); for (int i = 0; i < row; i++) { // printing direct square of diagonal // element in the second side Console.Write(mat[i, row - i - 1] * mat[i, row - i - 1] + \" \"); } } // Driver code public static void Main () { int [,] mat = new int[,]{{ 2, 5, 7 }, { 3, 7, 2 }, { 5, 6, 9 }}; diagonalsquare(mat, 3, 3); }} // This code is contributed by KRV.",
"e": 12806,
"s": 11394,
"text": null
},
{
"code": "<?php// Efficient PHP program to print squares of// diagonal elements. $MAX = 100; // function of diagonal squarefunction diagonalsquare( $mat, $row, $column){ // This loop is for finding of square of // the first side of diagonal elements echo \" \\nDiagonal one : \"; for($i = 0; $i < $row; $i++) { // printing direct square of diagonal // element there is no need to check // condition echo $mat[$i][$i] * $mat[$i][$i] , \" \"; } // This loop is for finding square of the // second side of diagonal elements echo \" \\n\\nDiagonal two : \"; for ( $i = 0; $i < $row; $i++) { // printing direct square of diagonal // element in the second side echo $mat[$i][$row - $i - 1] * $mat[$i][$row - $i - 1] , \" \"; }} // Driver code $mat = array(array(2, 5, 7 ), array(3, 7, 2 ), array(5, 6, 9 )); diagonalsquare($mat, 3, 3); // This code is contributed by anuj_67.?>",
"e": 13847,
"s": 12806,
"text": null
},
{
"code": null,
"e": 13855,
"s": 13847,
"text": "Output:"
},
{
"code": null,
"e": 13906,
"s": 13855,
"text": "Diagonal one : 4 49 81 \n\nDiagonal two : 49 49 25 "
},
{
"code": null,
"e": 13983,
"s": 13906,
"text": "Time Complexity O(n)Space Complexity O(n^2) for creating 2-Dimensional array"
},
{
"code": null,
"e": 13987,
"s": 13983,
"text": "KRV"
},
{
"code": null,
"e": 13992,
"s": 13987,
"text": "vt_m"
},
{
"code": null,
"e": 14004,
"s": 13992,
"text": "manishshaw1"
},
{
"code": null,
"e": 14017,
"s": 14004,
"text": "technophpfij"
},
{
"code": null,
"e": 14024,
"s": 14017,
"text": "Matrix"
},
{
"code": null,
"e": 14031,
"s": 14024,
"text": "Matrix"
},
{
"code": null,
"e": 14129,
"s": 14031,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 14164,
"s": 14129,
"text": "Matrix Chain Multiplication | DP-8"
},
{
"code": null,
"e": 14208,
"s": 14164,
"text": "Program to find largest element in an array"
},
{
"code": null,
"e": 14239,
"s": 14208,
"text": "Rat in a Maze | Backtracking-2"
},
{
"code": null,
"e": 14263,
"s": 14239,
"text": "Sudoku | Backtracking-7"
},
{
"code": null,
"e": 14285,
"s": 14263,
"text": "The Celebrity Problem"
},
{
"code": null,
"e": 14332,
"s": 14285,
"text": "Find the number of islands | Set 1 (Using DFS)"
},
{
"code": null,
"e": 14414,
"s": 14332,
"text": "Rotate a matrix by 90 degree in clockwise direction without using any extra space"
},
{
"code": null,
"e": 14485,
"s": 14414,
"text": "Count all possible paths from top left to bottom right of a mXn matrix"
},
{
"code": null,
"e": 14523,
"s": 14485,
"text": "Unique paths in a Grid with Obstacles"
}
] |
Multidimensional Arrays in Java | 08 Jul, 2022
Array-Basics in JavaMultidimensional Arrays can be defined in simple words as array of arrays. Data in multidimensional arrays are stored in tabular form (in row major order).
Syntax:
data_type[1st dimension][2nd dimension][]..[Nth dimension] array_name = new data_type[size1][size2]....[sizeN];
where:
data_type: Type of data to be stored in the array. For example: int, char, etc.
dimension: The dimension of the array created.For example: 1D, 2D, etc.
array_name: Name of the array
size1, size2, ..., sizeN: Sizes of the dimensions respectively.
Examples:
Two dimensional array:
int[][] twoD_arr = new int[10][20];
Three dimensional array:
int[][][] threeD_arr = new int[10][20][30];
Size of multidimensional arrays: The total number of elements that can be stored in a multidimensional array can be calculated by multiplying the size of all the dimensions.
For example:The array int[][] x = new int[10][20] can store a total of (10*20) = 200 elements.Similarly, array int[][][] x = new int[5][10][20] can store a total of (5*10*20) = 1000 elements.
Two – dimensional array is the simplest form of a multidimensional array. A two – dimensional array can be seen as an array of one – dimensional array for easier understanding.
Indirect Method of Declaration:
Declaration – Syntax:data_type[][] array_name = new data_type[x][y];
For example: int[][] arr = new int[10][20];
data_type[][] array_name = new data_type[x][y];
For example: int[][] arr = new int[10][20];
Initialization – Syntax:array_name[row_index][column_index] = value;
For example: arr[0][0] = 1;
array_name[row_index][column_index] = value;
For example: arr[0][0] = 1;
Example:
class GFG { public static void main(String[] args) { int[][] arr = new int[10][20]; arr[0][0] = 1; System.out.println("arr[0][0] = " + arr[0][0]); }}
arr[0][0] = 1
Direct Method of Declaration:
Syntax:
data_type[][] array_name = {
{valueR1C1, valueR1C2, ....},
{valueR2C1, valueR2C2, ....}
};
For example: int[][] arr = {{1, 2}, {3, 4}};
Example:
class GFG { public static void main(String[] args) { int[][] arr = { { 1, 2 }, { 3, 4 } }; for (int i = 0; i < 2; i++) for (int j = 0; j < 2; j++) System.out.println("arr[" + i + "][" + j + "] = " + arr[i][j]); }}
arr[0][0] = 1
arr[0][1] = 2
arr[1][0] = 3
arr[1][1] = 4
Elements in two-dimensional arrays are commonly referred by x[i][j] where ‘i’ is the row number and ‘j’ is the column number.
Syntax:
x[row_index][column_index]
For example:
int[][] arr = new int[10][20];
arr[0][0] = 1;
The above example represents the element present in first row and first column.
Note: In arrays if size of array is N. Its index will be from 0 to N-1. Therefore, for row_index 2, actual row number is 2+1 = 3.
Example:
class GFG { public static void main(String[] args) { int[][] arr = { { 1, 2 }, { 3, 4 } }; System.out.println("arr[0][0] = " + arr[0][0]); }}
arr[0][0] = 1
Representation of 2D array in Tabular Format: A two – dimensional array can be seen as a table with ‘x’ rows and ‘y’ columns where the row number ranges from 0 to (x-1) and column number ranges from 0 to (y-1). A two – dimensional array ‘x’ with 3 rows and 3 columns is shown below:
Print 2D array in tabular format:
To output all the elements of a Two-Dimensional array, use nested for loops. For this two for loops are required, One to traverse the rows and another to traverse columns.
Example:
class GFG { public static void main(String[] args) { int[][] arr = { { 1, 2 }, { 3, 4 } }; for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { System.out.print(arr[i][j] + " "); } System.out.println(); } }}
1 2
3 4
Three – dimensional array is a complex form of a multidimensional array. A three – dimensional array can be seen as an array of two – dimensional array for easier understanding.
Indirect Method of Declaration:
Declaration – Syntax:data_type[][][] array_name = new data_type[x][y][z];
For example: int[][][] arr = new int[10][20][30];
data_type[][][] array_name = new data_type[x][y][z];
For example: int[][][] arr = new int[10][20][30];
Initialization – Syntax:array_name[array_index][row_index][column_index] = value;
For example: arr[0][0][0] = 1;
array_name[array_index][row_index][column_index] = value;
For example: arr[0][0][0] = 1;
Example:
class GFG { public static void main(String[] args) { int[][][] arr = new int[10][20][30]; arr[0][0][0] = 1; System.out.println("arr[0][0][0] = " + arr[0][0][0]); }}
arr[0][0][0] = 1
Direct Method of Declaration:
Syntax:
data_type[][][] array_name = {
{
{valueA1R1C1, valueA1R1C2, ....},
{valueA1R2C1, valueA1R2C2, ....}
},
{
{valueA2R1C1, valueA2R1C2, ....},
{valueA2R2C1, valueA2R2C2, ....}
}
};
For example: int[][][] arr = { {{1, 2}, {3, 4}}, {{5, 6}, {7, 8}} };
Example:
class GFG { public static void main(String[] args) { int[][][] arr = { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } }; for (int i = 0; i < 2; i++) for (int j = 0; j < 2; j++) for (int z = 0; z < 2; z++) System.out.println("arr[" + i + "][" + j + "][" + z + "] = " + arr[i][j][z]); }}
arr[0][0][0] = 1
arr[0][0][1] = 2
arr[0][1][0] = 3
arr[0][1][1] = 4
arr[1][0][0] = 5
arr[1][0][1] = 6
arr[1][1][0] = 7
arr[1][1][1] = 8
Elements in three-dimensional arrays are commonly referred by x[i][j][k] where ‘i’ is the array number, ‘j’ is the row number and ‘k’ is the column number.
Syntax:
x[array_index][row_index][column_index]
For example:
int[][][] arr = new int[10][20][30];
arr[0][0][0] = 1;
The above example represents the element present in the first row and first column of the first array in the declared 3D array.
Note: In arrays if size of array is N. Its index will be from 0 to N-1. Therefore, for row_index 2, actual row number is 2+1 = 3.
Example:
class GFG { public static void main(String[] args) { int[][][] arr = { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } }; System.out.println("arr[0][0][0] = " + arr[0][0][0]); }}
arr[0][0][0] = 1
Representation of 3D array in Tabular Format: A three – dimensional array can be seen as a tables of arrays with ‘x’ rows and ‘y’ columns where the row number ranges from 0 to (x-1) and column number ranges from 0 to (y-1). A three – dimensional array with 3 array containing 3 rows and 3 columns is shown below:
Print 3D array in tabular format:
To output all the elements of a Three-Dimensional array, use nested for loops. For this three for loops are required, One to traverse the arrays, second to traverse the rows and another to traverse columns.
Example:
class GFG { public static void main(String[] args) { int[][][] arr = { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } }; for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { for (int k = 0; k < 2; k++) { System.out.print(arr[i][j][k] + " "); } System.out.println(); } System.out.println(); } }}
1 2
3 4
5 6
7 8
Inserting a Multi-dimensional Array during Runtime:This topic is forced n taking user-defined input into a multidimensional array during runtime. It is focused on the user first giving all the input to the program during runtime and after all entered input, the program will give output with respect to each input accordingly. It is useful when the user wishes to make input for multiple Test-Cases with multiple different values first and after all those things done, program will start providing output.
As an example, let’s find the total number of even and odd numbers in an input array. Here, we will use the concept of a 2-dimensional array. Here are a few points that explain the use of the various elements in the upcoming code:
Row integer number is considered as the number of Test-Cases and Column values are considered as values in each Test-Case.
One for() loop is used for updating Test-Case number and another for() loop is used for taking respective array values.
As all input entry is done, again two for() loops are used in the same manner to execute the program according to the condition specified.
The first line of input is the total number of TestCases.
The second line shows the total number of first array values.
The third line gives array values and so on.
Implementation:
import java.util.Scanner; public class GFGTestCase { public static void main( String[] args) { // Scanner class to take // values from console Scanner scanner = new Scanner(System.in); // totalTestCases = total // number of TestCases // eachTestCaseValues = // values in each TestCase as // an Array values int totalTestCases, eachTestCaseValues; // takes total number of // TestCases as integer number totalTestCases = scanner.nextInt(); // An array is formed as row // values for total testCases int[][] arrayMain = new int[totalTestCases][]; // for loop to take input of // values in each TestCase for (int i = 0; i < arrayMain.length; i++) { eachTestCaseValues = scanner.nextInt(); arrayMain[i] = new int[eachTestCaseValues]; for (int j = 0; j < arrayMain[i].length; j++) { arrayMain[i][j] = scanner.nextInt(); } } // All input entry is done. // Start executing output // according to condition provided for (int i = 0; i < arrayMain.length; i++) { // Initialize total number of // even & odd numbers to zero int nEvenNumbers = 0, nOddNumbers = 0; // prints TestCase number with // total number of its arguments System.out.println( "TestCase " + i + " with " + arrayMain[i].length + " values:"); for (int j = 0; j < arrayMain[i].length; j++) { System.out.print(arrayMain[i][j] + " "); // even & odd counter updated as // eligible number is found if (arrayMain[i][j] % 2 == 0) { nEvenNumbers++; } else { nOddNumbers++; } } System.out.println(); // Prints total numbers of // even & odd System.out.println( "Total Even numbers: " + nEvenNumbers + ", Total Odd numbers: " + nOddNumbers); } }}// This code is contributed by Udayan Kamble.
Input:
2
2
1 2
3
1 2 3
Output:
TestCase 0 with 2 values:
1 2
Total Even numbers: 1, Total Odd numbers: 1
TestCase 1 with 3 values:
1 2 3
Total Even numbers: 1, Total Odd numbers: 2
Input:
3
8
1 2 3 4 5 11 55 66
5
100 101 55 35 108
6
3 80 11 2 1 5
Output:
TestCase 0 with 8 values:
1 2 3 4 5 11 55 66
Total Even numbers: 3, Total Odd numbers: 5
TestCase 1 with 5 values:
100 101 55 35 108
Total Even numbers: 2, Total Odd numbers: 3
TestCase 2 with 6 values:
3 80 11 2 1 5
Total Even numbers: 2, Total Odd numbers: 4
udayanbk
Java-Array-Programs
Java-Arrays
Picked
Arrays
Java
Arrays
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Write a program to reverse an array or string
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Largest Sum Contiguous Subarray
Arrays in C/C++
Split() String method in Java with examples
Arrays.sort() in Java with examples
Reverse a string in Java
How to iterate any Map in Java
Stream In Java | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n08 Jul, 2022"
},
{
"code": null,
"e": 228,
"s": 52,
"text": "Array-Basics in JavaMultidimensional Arrays can be defined in simple words as array of arrays. Data in multidimensional arrays are stored in tabular form (in row major order)."
},
{
"code": null,
"e": 236,
"s": 228,
"text": "Syntax:"
},
{
"code": null,
"e": 348,
"s": 236,
"text": "data_type[1st dimension][2nd dimension][]..[Nth dimension] array_name = new data_type[size1][size2]....[sizeN];"
},
{
"code": null,
"e": 355,
"s": 348,
"text": "where:"
},
{
"code": null,
"e": 435,
"s": 355,
"text": "data_type: Type of data to be stored in the array. For example: int, char, etc."
},
{
"code": null,
"e": 507,
"s": 435,
"text": "dimension: The dimension of the array created.For example: 1D, 2D, etc."
},
{
"code": null,
"e": 537,
"s": 507,
"text": "array_name: Name of the array"
},
{
"code": null,
"e": 601,
"s": 537,
"text": "size1, size2, ..., sizeN: Sizes of the dimensions respectively."
},
{
"code": null,
"e": 611,
"s": 601,
"text": "Examples:"
},
{
"code": null,
"e": 741,
"s": 611,
"text": "Two dimensional array:\nint[][] twoD_arr = new int[10][20];\n\nThree dimensional array:\nint[][][] threeD_arr = new int[10][20][30];\n"
},
{
"code": null,
"e": 915,
"s": 741,
"text": "Size of multidimensional arrays: The total number of elements that can be stored in a multidimensional array can be calculated by multiplying the size of all the dimensions."
},
{
"code": null,
"e": 1107,
"s": 915,
"text": "For example:The array int[][] x = new int[10][20] can store a total of (10*20) = 200 elements.Similarly, array int[][][] x = new int[5][10][20] can store a total of (5*10*20) = 1000 elements."
},
{
"code": null,
"e": 1284,
"s": 1107,
"text": "Two – dimensional array is the simplest form of a multidimensional array. A two – dimensional array can be seen as an array of one – dimensional array for easier understanding."
},
{
"code": null,
"e": 1316,
"s": 1284,
"text": "Indirect Method of Declaration:"
},
{
"code": null,
"e": 1446,
"s": 1316,
"text": "Declaration – Syntax:data_type[][] array_name = new data_type[x][y];\n For example: int[][] arr = new int[10][20];\n "
},
{
"code": null,
"e": 1555,
"s": 1446,
"text": "data_type[][] array_name = new data_type[x][y];\n For example: int[][] arr = new int[10][20];\n "
},
{
"code": null,
"e": 1669,
"s": 1555,
"text": "Initialization – Syntax:array_name[row_index][column_index] = value;\n For example: arr[0][0] = 1;\n "
},
{
"code": null,
"e": 1759,
"s": 1669,
"text": "array_name[row_index][column_index] = value;\n For example: arr[0][0] = 1;\n "
},
{
"code": null,
"e": 1768,
"s": 1759,
"text": "Example:"
},
{
"code": "class GFG { public static void main(String[] args) { int[][] arr = new int[10][20]; arr[0][0] = 1; System.out.println(\"arr[0][0] = \" + arr[0][0]); }}",
"e": 1952,
"s": 1768,
"text": null
},
{
"code": null,
"e": 1967,
"s": 1952,
"text": "arr[0][0] = 1\n"
},
{
"code": null,
"e": 1997,
"s": 1967,
"text": "Direct Method of Declaration:"
},
{
"code": null,
"e": 2005,
"s": 1997,
"text": "Syntax:"
},
{
"code": null,
"e": 2230,
"s": 2005,
"text": "\ndata_type[][] array_name = {\n {valueR1C1, valueR1C2, ....}, \n {valueR2C1, valueR2C2, ....}\n };\n\nFor example: int[][] arr = {{1, 2}, {3, 4}};\n"
},
{
"code": null,
"e": 2239,
"s": 2230,
"text": "Example:"
},
{
"code": "class GFG { public static void main(String[] args) { int[][] arr = { { 1, 2 }, { 3, 4 } }; for (int i = 0; i < 2; i++) for (int j = 0; j < 2; j++) System.out.println(\"arr[\" + i + \"][\" + j + \"] = \" + arr[i][j]); }}",
"e": 2540,
"s": 2239,
"text": null
},
{
"code": null,
"e": 2597,
"s": 2540,
"text": "arr[0][0] = 1\narr[0][1] = 2\narr[1][0] = 3\narr[1][1] = 4\n"
},
{
"code": null,
"e": 2723,
"s": 2597,
"text": "Elements in two-dimensional arrays are commonly referred by x[i][j] where ‘i’ is the row number and ‘j’ is the column number."
},
{
"code": null,
"e": 2731,
"s": 2723,
"text": "Syntax:"
},
{
"code": null,
"e": 2758,
"s": 2731,
"text": "x[row_index][column_index]"
},
{
"code": null,
"e": 2771,
"s": 2758,
"text": "For example:"
},
{
"code": null,
"e": 2817,
"s": 2771,
"text": "int[][] arr = new int[10][20];\narr[0][0] = 1;"
},
{
"code": null,
"e": 2897,
"s": 2817,
"text": "The above example represents the element present in first row and first column."
},
{
"code": null,
"e": 3027,
"s": 2897,
"text": "Note: In arrays if size of array is N. Its index will be from 0 to N-1. Therefore, for row_index 2, actual row number is 2+1 = 3."
},
{
"code": null,
"e": 3036,
"s": 3027,
"text": "Example:"
},
{
"code": "class GFG { public static void main(String[] args) { int[][] arr = { { 1, 2 }, { 3, 4 } }; System.out.println(\"arr[0][0] = \" + arr[0][0]); }}",
"e": 3205,
"s": 3036,
"text": null
},
{
"code": null,
"e": 3220,
"s": 3205,
"text": "arr[0][0] = 1\n"
},
{
"code": null,
"e": 3503,
"s": 3220,
"text": "Representation of 2D array in Tabular Format: A two – dimensional array can be seen as a table with ‘x’ rows and ‘y’ columns where the row number ranges from 0 to (x-1) and column number ranges from 0 to (y-1). A two – dimensional array ‘x’ with 3 rows and 3 columns is shown below:"
},
{
"code": null,
"e": 3537,
"s": 3503,
"text": "Print 2D array in tabular format:"
},
{
"code": null,
"e": 3709,
"s": 3537,
"text": "To output all the elements of a Two-Dimensional array, use nested for loops. For this two for loops are required, One to traverse the rows and another to traverse columns."
},
{
"code": null,
"e": 3718,
"s": 3709,
"text": "Example:"
},
{
"code": "class GFG { public static void main(String[] args) { int[][] arr = { { 1, 2 }, { 3, 4 } }; for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { System.out.print(arr[i][j] + \" \"); } System.out.println(); } }}",
"e": 4017,
"s": 3718,
"text": null
},
{
"code": null,
"e": 4027,
"s": 4017,
"text": "1 2 \n3 4\n"
},
{
"code": null,
"e": 4205,
"s": 4027,
"text": "Three – dimensional array is a complex form of a multidimensional array. A three – dimensional array can be seen as an array of two – dimensional array for easier understanding."
},
{
"code": null,
"e": 4237,
"s": 4205,
"text": "Indirect Method of Declaration:"
},
{
"code": null,
"e": 4378,
"s": 4237,
"text": "Declaration – Syntax:data_type[][][] array_name = new data_type[x][y][z];\n For example: int[][][] arr = new int[10][20][30];\n "
},
{
"code": null,
"e": 4498,
"s": 4378,
"text": "data_type[][][] array_name = new data_type[x][y][z];\n For example: int[][][] arr = new int[10][20][30];\n "
},
{
"code": null,
"e": 4628,
"s": 4498,
"text": "Initialization – Syntax:array_name[array_index][row_index][column_index] = value;\n For example: arr[0][0][0] = 1;\n "
},
{
"code": null,
"e": 4734,
"s": 4628,
"text": "array_name[array_index][row_index][column_index] = value;\n For example: arr[0][0][0] = 1;\n "
},
{
"code": null,
"e": 4743,
"s": 4734,
"text": "Example:"
},
{
"code": "class GFG { public static void main(String[] args) { int[][][] arr = new int[10][20][30]; arr[0][0][0] = 1; System.out.println(\"arr[0][0][0] = \" + arr[0][0][0]); }}",
"e": 4942,
"s": 4743,
"text": null
},
{
"code": null,
"e": 4960,
"s": 4942,
"text": "arr[0][0][0] = 1\n"
},
{
"code": null,
"e": 4990,
"s": 4960,
"text": "Direct Method of Declaration:"
},
{
"code": null,
"e": 4998,
"s": 4990,
"text": "Syntax:"
},
{
"code": null,
"e": 5522,
"s": 4998,
"text": "\ndata_type[][][] array_name = {\n {\n {valueA1R1C1, valueA1R1C2, ....}, \n {valueA1R2C1, valueA1R2C2, ....}\n },\n {\n {valueA2R1C1, valueA2R1C2, ....}, \n {valueA2R2C1, valueA2R2C2, ....}\n }\n };\n\nFor example: int[][][] arr = { {{1, 2}, {3, 4}}, {{5, 6}, {7, 8}} };\n"
},
{
"code": null,
"e": 5531,
"s": 5522,
"text": "Example:"
},
{
"code": "class GFG { public static void main(String[] args) { int[][][] arr = { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } }; for (int i = 0; i < 2; i++) for (int j = 0; j < 2; j++) for (int z = 0; z < 2; z++) System.out.println(\"arr[\" + i + \"][\" + j + \"][\" + z + \"] = \" + arr[i][j][z]); }}",
"e": 6041,
"s": 5531,
"text": null
},
{
"code": null,
"e": 6178,
"s": 6041,
"text": "arr[0][0][0] = 1\narr[0][0][1] = 2\narr[0][1][0] = 3\narr[0][1][1] = 4\narr[1][0][0] = 5\narr[1][0][1] = 6\narr[1][1][0] = 7\narr[1][1][1] = 8\n"
},
{
"code": null,
"e": 6334,
"s": 6178,
"text": "Elements in three-dimensional arrays are commonly referred by x[i][j][k] where ‘i’ is the array number, ‘j’ is the row number and ‘k’ is the column number."
},
{
"code": null,
"e": 6342,
"s": 6334,
"text": "Syntax:"
},
{
"code": null,
"e": 6382,
"s": 6342,
"text": "x[array_index][row_index][column_index]"
},
{
"code": null,
"e": 6395,
"s": 6382,
"text": "For example:"
},
{
"code": null,
"e": 6450,
"s": 6395,
"text": "int[][][] arr = new int[10][20][30];\narr[0][0][0] = 1;"
},
{
"code": null,
"e": 6578,
"s": 6450,
"text": "The above example represents the element present in the first row and first column of the first array in the declared 3D array."
},
{
"code": null,
"e": 6708,
"s": 6578,
"text": "Note: In arrays if size of array is N. Its index will be from 0 to N-1. Therefore, for row_index 2, actual row number is 2+1 = 3."
},
{
"code": null,
"e": 6717,
"s": 6708,
"text": "Example:"
},
{
"code": "class GFG { public static void main(String[] args) { int[][][] arr = { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } }; System.out.println(\"arr[0][0][0] = \" + arr[0][0][0]); }}",
"e": 6922,
"s": 6717,
"text": null
},
{
"code": null,
"e": 6940,
"s": 6922,
"text": "arr[0][0][0] = 1\n"
},
{
"code": null,
"e": 7253,
"s": 6940,
"text": "Representation of 3D array in Tabular Format: A three – dimensional array can be seen as a tables of arrays with ‘x’ rows and ‘y’ columns where the row number ranges from 0 to (x-1) and column number ranges from 0 to (y-1). A three – dimensional array with 3 array containing 3 rows and 3 columns is shown below:"
},
{
"code": null,
"e": 7287,
"s": 7253,
"text": "Print 3D array in tabular format:"
},
{
"code": null,
"e": 7494,
"s": 7287,
"text": "To output all the elements of a Three-Dimensional array, use nested for loops. For this three for loops are required, One to traverse the arrays, second to traverse the rows and another to traverse columns."
},
{
"code": null,
"e": 7503,
"s": 7494,
"text": "Example:"
},
{
"code": "class GFG { public static void main(String[] args) { int[][][] arr = { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } }; for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { for (int k = 0; k < 2; k++) { System.out.print(arr[i][j][k] + \" \"); } System.out.println(); } System.out.println(); } }}",
"e": 7969,
"s": 7503,
"text": null
},
{
"code": null,
"e": 7990,
"s": 7969,
"text": "1 2 \n3 4 \n\n5 6 \n7 8\n"
},
{
"code": null,
"e": 8496,
"s": 7990,
"text": "Inserting a Multi-dimensional Array during Runtime:This topic is forced n taking user-defined input into a multidimensional array during runtime. It is focused on the user first giving all the input to the program during runtime and after all entered input, the program will give output with respect to each input accordingly. It is useful when the user wishes to make input for multiple Test-Cases with multiple different values first and after all those things done, program will start providing output."
},
{
"code": null,
"e": 8727,
"s": 8496,
"text": "As an example, let’s find the total number of even and odd numbers in an input array. Here, we will use the concept of a 2-dimensional array. Here are a few points that explain the use of the various elements in the upcoming code:"
},
{
"code": null,
"e": 8850,
"s": 8727,
"text": "Row integer number is considered as the number of Test-Cases and Column values are considered as values in each Test-Case."
},
{
"code": null,
"e": 8970,
"s": 8850,
"text": "One for() loop is used for updating Test-Case number and another for() loop is used for taking respective array values."
},
{
"code": null,
"e": 9109,
"s": 8970,
"text": "As all input entry is done, again two for() loops are used in the same manner to execute the program according to the condition specified."
},
{
"code": null,
"e": 9167,
"s": 9109,
"text": "The first line of input is the total number of TestCases."
},
{
"code": null,
"e": 9229,
"s": 9167,
"text": "The second line shows the total number of first array values."
},
{
"code": null,
"e": 9274,
"s": 9229,
"text": "The third line gives array values and so on."
},
{
"code": null,
"e": 9290,
"s": 9274,
"text": "Implementation:"
},
{
"code": "import java.util.Scanner; public class GFGTestCase { public static void main( String[] args) { // Scanner class to take // values from console Scanner scanner = new Scanner(System.in); // totalTestCases = total // number of TestCases // eachTestCaseValues = // values in each TestCase as // an Array values int totalTestCases, eachTestCaseValues; // takes total number of // TestCases as integer number totalTestCases = scanner.nextInt(); // An array is formed as row // values for total testCases int[][] arrayMain = new int[totalTestCases][]; // for loop to take input of // values in each TestCase for (int i = 0; i < arrayMain.length; i++) { eachTestCaseValues = scanner.nextInt(); arrayMain[i] = new int[eachTestCaseValues]; for (int j = 0; j < arrayMain[i].length; j++) { arrayMain[i][j] = scanner.nextInt(); } } // All input entry is done. // Start executing output // according to condition provided for (int i = 0; i < arrayMain.length; i++) { // Initialize total number of // even & odd numbers to zero int nEvenNumbers = 0, nOddNumbers = 0; // prints TestCase number with // total number of its arguments System.out.println( \"TestCase \" + i + \" with \" + arrayMain[i].length + \" values:\"); for (int j = 0; j < arrayMain[i].length; j++) { System.out.print(arrayMain[i][j] + \" \"); // even & odd counter updated as // eligible number is found if (arrayMain[i][j] % 2 == 0) { nEvenNumbers++; } else { nOddNumbers++; } } System.out.println(); // Prints total numbers of // even & odd System.out.println( \"Total Even numbers: \" + nEvenNumbers + \", Total Odd numbers: \" + nOddNumbers); } }}// This code is contributed by Udayan Kamble.",
"e": 11519,
"s": 9290,
"text": null
},
{
"code": null,
"e": 12044,
"s": 11519,
"text": "Input:\n2\n2\n1 2\n3\n1 2 3\n\nOutput:\nTestCase 0 with 2 values:\n1 2 \nTotal Even numbers: 1, Total Odd numbers: 1\nTestCase 1 with 3 values:\n1 2 3 \nTotal Even numbers: 1, Total Odd numbers: 2\n\nInput:\n3\n8\n1 2 3 4 5 11 55 66\n5\n100 101 55 35 108\n6\n3 80 11 2 1 5\n\nOutput:\nTestCase 0 with 8 values:\n1 2 3 4 5 11 55 66 \nTotal Even numbers: 3, Total Odd numbers: 5\nTestCase 1 with 5 values:\n100 101 55 35 108 \nTotal Even numbers: 2, Total Odd numbers: 3\nTestCase 2 with 6 values:\n3 80 11 2 1 5 \nTotal Even numbers: 2, Total Odd numbers: 4\n"
},
{
"code": null,
"e": 12053,
"s": 12044,
"text": "udayanbk"
},
{
"code": null,
"e": 12073,
"s": 12053,
"text": "Java-Array-Programs"
},
{
"code": null,
"e": 12085,
"s": 12073,
"text": "Java-Arrays"
},
{
"code": null,
"e": 12092,
"s": 12085,
"text": "Picked"
},
{
"code": null,
"e": 12099,
"s": 12092,
"text": "Arrays"
},
{
"code": null,
"e": 12104,
"s": 12099,
"text": "Java"
},
{
"code": null,
"e": 12111,
"s": 12104,
"text": "Arrays"
},
{
"code": null,
"e": 12116,
"s": 12111,
"text": "Java"
},
{
"code": null,
"e": 12214,
"s": 12116,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 12260,
"s": 12214,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 12328,
"s": 12260,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 12372,
"s": 12328,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 12404,
"s": 12372,
"text": "Largest Sum Contiguous Subarray"
},
{
"code": null,
"e": 12420,
"s": 12404,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 12464,
"s": 12420,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 12500,
"s": 12464,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 12525,
"s": 12500,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 12556,
"s": 12525,
"text": "How to iterate any Map in Java"
}
] |
How to convert text to speech in Node.js ? | 19 May, 2020
To convert text to speech in Node.js, there are various modules but the most popular among them is gtts(Google Text to Speech) module.
Feature of gtts module:
It is easy to get started and easy to use.It is widely used and popular for converting text to speech.
It is easy to get started and easy to use.
It is widely used and popular for converting text to speech.
Installation of gtts module:
You can visit the link to Install gtts module. You can install this package by using this command.npm install gttsAfter installing gtts module, you can check your gtts version in command prompt using the command.npm version gttsAfter that, you can create a folder and add a file, for example index.js. To run this file you need to run the following command.node index.js
You can visit the link to Install gtts module. You can install this package by using this command.npm install gtts
npm install gtts
After installing gtts module, you can check your gtts version in command prompt using the command.npm version gtts
npm version gtts
After that, you can create a folder and add a file, for example index.js. To run this file you need to run the following command.node index.js
node index.js
Filename: index.js
const gTTS = require('gtts'); var speech = 'Welcome to GeeksforGeeks';var gtts = new gTTS(speech, 'en'); gtts.save('Voice.mp3', function (err, result){ if(err) { throw new Error(err); } console.log("Text to speech converted!");});
Steps to run the program:
The project structure will look like this:Make sure you have installed gtts module using the following commands:npm install gttsRun index.js file using below command:node index.jsAfter running above command, your text is converted to speech and save in your Voice.mp3 file as shown below:
The project structure will look like this:
Make sure you have installed gtts module using the following commands:npm install gtts
npm install gtts
Run index.js file using below command:node index.js
node index.js
After running above command, your text is converted to speech and save in your Voice.mp3 file as shown below:
So this is how you can use the gtts (Google Text to Speech) module for converting text to speech in Node.js.
Node.js-Misc
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between promise and async await in Node.js
Mongoose | findByIdAndUpdate() Function
Installation of Node.js on Windows
JWT Authentication with Node.js
Node.js forEach() function
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n19 May, 2020"
},
{
"code": null,
"e": 188,
"s": 53,
"text": "To convert text to speech in Node.js, there are various modules but the most popular among them is gtts(Google Text to Speech) module."
},
{
"code": null,
"e": 212,
"s": 188,
"text": "Feature of gtts module:"
},
{
"code": null,
"e": 315,
"s": 212,
"text": "It is easy to get started and easy to use.It is widely used and popular for converting text to speech."
},
{
"code": null,
"e": 358,
"s": 315,
"text": "It is easy to get started and easy to use."
},
{
"code": null,
"e": 419,
"s": 358,
"text": "It is widely used and popular for converting text to speech."
},
{
"code": null,
"e": 448,
"s": 419,
"text": "Installation of gtts module:"
},
{
"code": null,
"e": 819,
"s": 448,
"text": "You can visit the link to Install gtts module. You can install this package by using this command.npm install gttsAfter installing gtts module, you can check your gtts version in command prompt using the command.npm version gttsAfter that, you can create a folder and add a file, for example index.js. To run this file you need to run the following command.node index.js"
},
{
"code": null,
"e": 934,
"s": 819,
"text": "You can visit the link to Install gtts module. You can install this package by using this command.npm install gtts"
},
{
"code": null,
"e": 951,
"s": 934,
"text": "npm install gtts"
},
{
"code": null,
"e": 1066,
"s": 951,
"text": "After installing gtts module, you can check your gtts version in command prompt using the command.npm version gtts"
},
{
"code": null,
"e": 1083,
"s": 1066,
"text": "npm version gtts"
},
{
"code": null,
"e": 1226,
"s": 1083,
"text": "After that, you can create a folder and add a file, for example index.js. To run this file you need to run the following command.node index.js"
},
{
"code": null,
"e": 1240,
"s": 1226,
"text": "node index.js"
},
{
"code": null,
"e": 1259,
"s": 1240,
"text": "Filename: index.js"
},
{
"code": "const gTTS = require('gtts'); var speech = 'Welcome to GeeksforGeeks';var gtts = new gTTS(speech, 'en'); gtts.save('Voice.mp3', function (err, result){ if(err) { throw new Error(err); } console.log(\"Text to speech converted!\");});",
"e": 1502,
"s": 1259,
"text": null
},
{
"code": null,
"e": 1528,
"s": 1502,
"text": "Steps to run the program:"
},
{
"code": null,
"e": 1817,
"s": 1528,
"text": "The project structure will look like this:Make sure you have installed gtts module using the following commands:npm install gttsRun index.js file using below command:node index.jsAfter running above command, your text is converted to speech and save in your Voice.mp3 file as shown below:"
},
{
"code": null,
"e": 1860,
"s": 1817,
"text": "The project structure will look like this:"
},
{
"code": null,
"e": 1947,
"s": 1860,
"text": "Make sure you have installed gtts module using the following commands:npm install gtts"
},
{
"code": null,
"e": 1964,
"s": 1947,
"text": "npm install gtts"
},
{
"code": null,
"e": 2016,
"s": 1964,
"text": "Run index.js file using below command:node index.js"
},
{
"code": null,
"e": 2030,
"s": 2016,
"text": "node index.js"
},
{
"code": null,
"e": 2140,
"s": 2030,
"text": "After running above command, your text is converted to speech and save in your Voice.mp3 file as shown below:"
},
{
"code": null,
"e": 2249,
"s": 2140,
"text": "So this is how you can use the gtts (Google Text to Speech) module for converting text to speech in Node.js."
},
{
"code": null,
"e": 2262,
"s": 2249,
"text": "Node.js-Misc"
},
{
"code": null,
"e": 2270,
"s": 2262,
"text": "Node.js"
},
{
"code": null,
"e": 2287,
"s": 2270,
"text": "Web Technologies"
},
{
"code": null,
"e": 2385,
"s": 2287,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2439,
"s": 2385,
"text": "Difference between promise and async await in Node.js"
},
{
"code": null,
"e": 2479,
"s": 2439,
"text": "Mongoose | findByIdAndUpdate() Function"
},
{
"code": null,
"e": 2514,
"s": 2479,
"text": "Installation of Node.js on Windows"
},
{
"code": null,
"e": 2546,
"s": 2514,
"text": "JWT Authentication with Node.js"
},
{
"code": null,
"e": 2573,
"s": 2546,
"text": "Node.js forEach() function"
},
{
"code": null,
"e": 2635,
"s": 2573,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2696,
"s": 2635,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2746,
"s": 2696,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 2789,
"s": 2746,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
What is an extern storage class in C language? | There are four storage classes in C programming language, which are as follows −
auto
extern
static
register
The keyword is extern. These variables are declared outside the block.
Scope − Scope of a global variable is available throughout the program.
Scope − Scope of a global variable is available throughout the program.
Default value is zero.
Default value is zero.
The algorithm is given below −
START
Step 1: Declare and initialized extern variable
Step 2: Declare and initialized int variable a=3
Step 3: Print a
Step 4: Call function step 5
Step 5: Called function
Print a (takes the value of extern variable)
Following is the C program for extern storage class −
extern int a =5; /* this ‘a’ is available entire program */
main ( ){
int a = 3; /* this ‘a' is valid only in main */
printf ("%d",a);
fun ( );
}
fun ( ){
printf ("%d", a);
}
The output is stated below −
3 1
Consider another program for extern storage class −
External.h
extern int a=14;
extern int b=8;
externstorage.c file
#include<stdio.h>
#include "External.h"
int main(){
int sub = a-b;
printf("%d -%d = %d ", a, b, sub);
return 0;
}
The output is stated below −
a-b=6 | [
{
"code": null,
"e": 1268,
"s": 1187,
"text": "There are four storage classes in C programming language, which are as follows −"
},
{
"code": null,
"e": 1273,
"s": 1268,
"text": "auto"
},
{
"code": null,
"e": 1280,
"s": 1273,
"text": "extern"
},
{
"code": null,
"e": 1287,
"s": 1280,
"text": "static"
},
{
"code": null,
"e": 1296,
"s": 1287,
"text": "register"
},
{
"code": null,
"e": 1367,
"s": 1296,
"text": "The keyword is extern. These variables are declared outside the block."
},
{
"code": null,
"e": 1439,
"s": 1367,
"text": "Scope − Scope of a global variable is available throughout the program."
},
{
"code": null,
"e": 1511,
"s": 1439,
"text": "Scope − Scope of a global variable is available throughout the program."
},
{
"code": null,
"e": 1534,
"s": 1511,
"text": "Default value is zero."
},
{
"code": null,
"e": 1557,
"s": 1534,
"text": "Default value is zero."
},
{
"code": null,
"e": 1588,
"s": 1557,
"text": "The algorithm is given below −"
},
{
"code": null,
"e": 1805,
"s": 1588,
"text": "START\nStep 1: Declare and initialized extern variable\nStep 2: Declare and initialized int variable a=3\nStep 3: Print a\nStep 4: Call function step 5\nStep 5: Called function\nPrint a (takes the value of extern variable)"
},
{
"code": null,
"e": 1859,
"s": 1805,
"text": "Following is the C program for extern storage class −"
},
{
"code": null,
"e": 2046,
"s": 1859,
"text": "extern int a =5; /* this ‘a’ is available entire program */\nmain ( ){\n int a = 3; /* this ‘a' is valid only in main */\n printf (\"%d\",a);\n fun ( );\n}\nfun ( ){\n printf (\"%d\", a);\n}"
},
{
"code": null,
"e": 2075,
"s": 2046,
"text": "The output is stated below −"
},
{
"code": null,
"e": 2079,
"s": 2075,
"text": "3 1"
},
{
"code": null,
"e": 2131,
"s": 2079,
"text": "Consider another program for extern storage class −"
},
{
"code": null,
"e": 2319,
"s": 2131,
"text": "External.h\nextern int a=14;\nextern int b=8;\nexternstorage.c file\n#include<stdio.h>\n#include \"External.h\"\nint main(){\n int sub = a-b;\n printf(\"%d -%d = %d \", a, b, sub);\n return 0;\n}"
},
{
"code": null,
"e": 2348,
"s": 2319,
"text": "The output is stated below −"
},
{
"code": null,
"e": 2354,
"s": 2348,
"text": "a-b=6"
}
] |
Python | Pandas Series.values | 28 Jan, 2019
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 series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index.
Pandas Series.values attribute return Series as ndarray or ndarray-like depending on the dtype.
Syntax:Series.values
Parameter : None
Returns : ndarray
Example #1: Use Series.values attribute to return the values in the given series object as an ndarray.
# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon', 'Rio']) # Creating the row axis labelssr.index = ['City 1', 'City 2', 'City 3', 'City 4', 'City 5'] # Print the seriesprint(sr)
Output :
Now we will use Series.values attribute to return the values of the given Series object as an ndarray.
# return an ndarraysr.values
Output :
As we can see in the output, the Series.values attribute has returned an ndarray object containing the values of the given Series object. Example #2 : Use Series.values attribute to return the values in the given series object as an ndarray.
# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['1/1/2018', '2/1/2018', '3/1/2018', '4/1/2018']) # Creating the row axis labelssr.index = ['Day 1', 'Day 2', 'Day 3', 'Day 4'] # Print the seriesprint(sr)
Output :
Now we will use Series.values attribute to return the values of the given Series object as an ndarray.
# return an ndarraysr.values
Output :As we can see in the output, the Series.values attribute has returned an ndarray object containing the values of the given Series object.
Python pandas-series
Python pandas-series-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Python | datetime.timedelta() function | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Jan, 2019"
},
{
"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": 499,
"s": 242,
"text": "Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index."
},
{
"code": null,
"e": 595,
"s": 499,
"text": "Pandas Series.values attribute return Series as ndarray or ndarray-like depending on the dtype."
},
{
"code": null,
"e": 616,
"s": 595,
"text": "Syntax:Series.values"
},
{
"code": null,
"e": 633,
"s": 616,
"text": "Parameter : None"
},
{
"code": null,
"e": 651,
"s": 633,
"text": "Returns : ndarray"
},
{
"code": null,
"e": 754,
"s": 651,
"text": "Example #1: Use Series.values attribute to return the values in the given series object as an ndarray."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon', 'Rio']) # Creating the row axis labelssr.index = ['City 1', 'City 2', 'City 3', 'City 4', 'City 5'] # Print the seriesprint(sr)",
"e": 1011,
"s": 754,
"text": null
},
{
"code": null,
"e": 1020,
"s": 1011,
"text": "Output :"
},
{
"code": null,
"e": 1123,
"s": 1020,
"text": "Now we will use Series.values attribute to return the values of the given Series object as an ndarray."
},
{
"code": "# return an ndarraysr.values",
"e": 1152,
"s": 1123,
"text": null
},
{
"code": null,
"e": 1161,
"s": 1152,
"text": "Output :"
},
{
"code": null,
"e": 1403,
"s": 1161,
"text": "As we can see in the output, the Series.values attribute has returned an ndarray object containing the values of the given Series object. Example #2 : Use Series.values attribute to return the values in the given series object as an ndarray."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['1/1/2018', '2/1/2018', '3/1/2018', '4/1/2018']) # Creating the row axis labelssr.index = ['Day 1', 'Day 2', 'Day 3', 'Day 4'] # Print the seriesprint(sr)",
"e": 1642,
"s": 1403,
"text": null
},
{
"code": null,
"e": 1651,
"s": 1642,
"text": "Output :"
},
{
"code": null,
"e": 1754,
"s": 1651,
"text": "Now we will use Series.values attribute to return the values of the given Series object as an ndarray."
},
{
"code": "# return an ndarraysr.values",
"e": 1783,
"s": 1754,
"text": null
},
{
"code": null,
"e": 1929,
"s": 1783,
"text": "Output :As we can see in the output, the Series.values attribute has returned an ndarray object containing the values of the given Series object."
},
{
"code": null,
"e": 1950,
"s": 1929,
"text": "Python pandas-series"
},
{
"code": null,
"e": 1979,
"s": 1950,
"text": "Python pandas-series-methods"
},
{
"code": null,
"e": 1993,
"s": 1979,
"text": "Python-pandas"
},
{
"code": null,
"e": 2000,
"s": 1993,
"text": "Python"
},
{
"code": null,
"e": 2098,
"s": 2000,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2130,
"s": 2098,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2157,
"s": 2130,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2178,
"s": 2157,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2201,
"s": 2178,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2232,
"s": 2201,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2288,
"s": 2232,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2330,
"s": 2288,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 2372,
"s": 2330,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 2411,
"s": 2372,
"text": "Python | Get unique values from a list"
}
] |
GATE | GATE CS 2020 | Question 32 | 11 Aug, 2021
Consider the following C program.
#include <stdio.h> int main () { int a[4][5] = {{1, 2, 3, 4, 5}, {6, 7, 8, 9, 10}, {11, 12, 13, 14, 15}, {16, 17, 18, 19, 20}}; printf("%d\n", *(*(a+**a+2)+3)); return(0); }
The output of the program is _______ .
Note – This question was Numerical Type.(A) 18(B) 19(C) 20(D) 14Answer: (B)Explanation: Given a[4][5] is 2D array. Let starting address (or base address) of given array is 1000.
Therefore,
= *(*(a+**a+2)+3))
= *(*(1000+**1000+2)+3))
= *(*(1000+3)+3)) {given element **1002 = 3}
= *(*(1003)+3))
= *((1003)+3) {4th row selected in given matrix}
= *((1003)+3) {address of 4th element in 4th row}
= a[3][3]
= 19 {element selected a[3][3] = 19}
#include <stdio.h> int main () { int a[4][5] = {{1, 2, 3, 4, 5}, {6, 7, 8, 9, 10}, {11, 12, 13, 14, 15}, {16, 17, 18, 19, 20}}; printf("%d\n", *(*(a+**a+2)+3)); return(0); }
Option (B) is correct.
GATE PYQs 2019 and 2020 | Programming and Data Structures | Shubham Agrawal | GeeksforGeeks GATE CSE - YouTubeGeeksforGeeks GATE Computer Science17.5K subscribersGATE PYQs 2019 and 2020 | Programming and Data Structures | Shubham Agrawal | GeeksforGeeks GATE CSEWatch 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:0054:27 / 1:16:33•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=fP8QED8d6ws" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n11 Aug, 2021"
},
{
"code": null,
"e": 88,
"s": 54,
"text": "Consider the following C program."
},
{
"code": "#include <stdio.h> int main () { int a[4][5] = {{1, 2, 3, 4, 5}, {6, 7, 8, 9, 10}, {11, 12, 13, 14, 15}, {16, 17, 18, 19, 20}}; printf(\"%d\\n\", *(*(a+**a+2)+3)); return(0); } ",
"e": 338,
"s": 88,
"text": null
},
{
"code": null,
"e": 377,
"s": 338,
"text": "The output of the program is _______ ."
},
{
"code": null,
"e": 555,
"s": 377,
"text": "Note – This question was Numerical Type.(A) 18(B) 19(C) 20(D) 14Answer: (B)Explanation: Given a[4][5] is 2D array. Let starting address (or base address) of given array is 1000."
},
{
"code": null,
"e": 566,
"s": 555,
"text": "Therefore,"
},
{
"code": null,
"e": 838,
"s": 566,
"text": "= *(*(a+**a+2)+3))\n= *(*(1000+**1000+2)+3))\n= *(*(1000+3)+3)) {given element **1002 = 3}\n= *(*(1003)+3))\n= *((1003)+3) {4th row selected in given matrix}\n= *((1003)+3) {address of 4th element in 4th row}\n= a[3][3]\n= 19 {element selected a[3][3] = 19} "
},
{
"code": "#include <stdio.h> int main () { int a[4][5] = {{1, 2, 3, 4, 5}, {6, 7, 8, 9, 10}, {11, 12, 13, 14, 15}, {16, 17, 18, 19, 20}}; printf(\"%d\\n\", *(*(a+**a+2)+3)); return(0); } ",
"e": 1088,
"s": 838,
"text": null
},
{
"code": null,
"e": 1111,
"s": 1088,
"text": "Option (B) is correct."
},
{
"code": null,
"e": 2145,
"s": 1111,
"text": "GATE PYQs 2019 and 2020 | Programming and Data Structures | Shubham Agrawal | GeeksforGeeks GATE CSE - YouTubeGeeksforGeeks GATE Computer Science17.5K subscribersGATE PYQs 2019 and 2020 | Programming and Data Structures | Shubham Agrawal | GeeksforGeeks GATE CSEWatch 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:0054:27 / 1:16:33•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=fP8QED8d6ws\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question"
},
{
"code": null,
"e": 2150,
"s": 2145,
"text": "GATE"
}
] |
How to add a datepicker in form using HTML ? | 22 Jul, 2021
We know that a datepicker is used to select a particular date from a calendar. A datepicker is an interactive dropdown that makes it easy to choose the date from a calendar instead of typing it manually. It is generally used to save a birthdate of a user or also used in many cases.
In this article, we will learn how to add a datepicker in form using HTML5.
Approach:
Create an HTML document that contains a form with an input field.
Using a type attribute in input element which is set to “datetime-local“.
Syntax:
<input type="datetime-local">
HTML Code:
HTML
<!DOCTYPE html><html> <head> <style> body { text-align: center; } </style></head> <body> <h2 style="color:green">GeeksforGeeks</h1> <b> How to add a datepicker in form using HTML </b> <br> <h4>Date Of Birth: <input type="datetime-local" id="Test_DatetimeLocal"> </h4></body> </html>
Output:
Datepicker modal
HTML-Attributes
HTML-Questions
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
Design a Tribute Page using HTML & CSS
Build a Survey Form using HTML and CSS
Angular File Upload
Form validation using jQuery
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Jul, 2021"
},
{
"code": null,
"e": 312,
"s": 28,
"text": "We know that a datepicker is used to select a particular date from a calendar. A datepicker is an interactive dropdown that makes it easy to choose the date from a calendar instead of typing it manually. It is generally used to save a birthdate of a user or also used in many cases. "
},
{
"code": null,
"e": 389,
"s": 312,
"text": "In this article, we will learn how to add a datepicker in form using HTML5. "
},
{
"code": null,
"e": 400,
"s": 389,
"text": "Approach: "
},
{
"code": null,
"e": 466,
"s": 400,
"text": "Create an HTML document that contains a form with an input field."
},
{
"code": null,
"e": 540,
"s": 466,
"text": "Using a type attribute in input element which is set to “datetime-local“."
},
{
"code": null,
"e": 548,
"s": 540,
"text": "Syntax:"
},
{
"code": null,
"e": 578,
"s": 548,
"text": "<input type=\"datetime-local\">"
},
{
"code": null,
"e": 589,
"s": 578,
"text": "HTML Code:"
},
{
"code": null,
"e": 594,
"s": 589,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <style> body { text-align: center; } </style></head> <body> <h2 style=\"color:green\">GeeksforGeeks</h1> <b> How to add a datepicker in form using HTML </b> <br> <h4>Date Of Birth: <input type=\"datetime-local\" id=\"Test_DatetimeLocal\"> </h4></body> </html> ",
"e": 1000,
"s": 594,
"text": null
},
{
"code": null,
"e": 1008,
"s": 1000,
"text": "Output:"
},
{
"code": null,
"e": 1026,
"s": 1008,
"text": "Datepicker modal "
},
{
"code": null,
"e": 1042,
"s": 1026,
"text": "HTML-Attributes"
},
{
"code": null,
"e": 1057,
"s": 1042,
"text": "HTML-Questions"
},
{
"code": null,
"e": 1062,
"s": 1057,
"text": "HTML"
},
{
"code": null,
"e": 1079,
"s": 1062,
"text": "Web Technologies"
},
{
"code": null,
"e": 1084,
"s": 1079,
"text": "HTML"
},
{
"code": null,
"e": 1182,
"s": 1084,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1206,
"s": 1182,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 1245,
"s": 1206,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 1284,
"s": 1245,
"text": "Build a Survey Form using HTML and CSS"
},
{
"code": null,
"e": 1304,
"s": 1284,
"text": "Angular File Upload"
},
{
"code": null,
"e": 1333,
"s": 1304,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 1366,
"s": 1333,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 1427,
"s": 1366,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1470,
"s": 1427,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 1542,
"s": 1470,
"text": "Differences between Functional Components and Class Components in React"
}
] |
Scala String startsWith(String prefix) method with example | 29 Oct, 2019
The startsWith(String prefix) method is utilized to check if the stated string starts with the prefix or not that is being specified by us.
Method Definition: Boolean startsWith(String prefix)
Return Type: It returns true if the string starts with the specified prefix else it returns false.
Example: 1#
// Scala program of startsWith()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Applying startsWith method val result = "GeeksforGeeks".startsWith("Geeks") // Displays output println(result) }}
true
Example: 2#
// Scala program of startsWith()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Applying startsWith method val result = "GeeksforGeeks".startsWith("geeks") // Displays output println(result) }}
false
Scala
Scala-Method
Scala-Strings
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Type Casting in Scala
Class and Object in Scala
Scala List filter() method with example
Scala Map
Scala Tutorial – Learn Scala with Step By Step Guide
Scala Lists
Operators in Scala
Scala | Arrays
Scala Constructors
Enumeration in Scala | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 Oct, 2019"
},
{
"code": null,
"e": 168,
"s": 28,
"text": "The startsWith(String prefix) method is utilized to check if the stated string starts with the prefix or not that is being specified by us."
},
{
"code": null,
"e": 221,
"s": 168,
"text": "Method Definition: Boolean startsWith(String prefix)"
},
{
"code": null,
"e": 320,
"s": 221,
"text": "Return Type: It returns true if the string starts with the specified prefix else it returns false."
},
{
"code": null,
"e": 332,
"s": 320,
"text": "Example: 1#"
},
{
"code": "// Scala program of startsWith()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Applying startsWith method val result = \"GeeksforGeeks\".startsWith(\"Geeks\") // Displays output println(result) }} ",
"e": 634,
"s": 332,
"text": null
},
{
"code": null,
"e": 640,
"s": 634,
"text": "true\n"
},
{
"code": null,
"e": 652,
"s": 640,
"text": "Example: 2#"
},
{
"code": "// Scala program of startsWith()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Applying startsWith method val result = \"GeeksforGeeks\".startsWith(\"geeks\") // Displays output println(result) }} ",
"e": 954,
"s": 652,
"text": null
},
{
"code": null,
"e": 961,
"s": 954,
"text": "false\n"
},
{
"code": null,
"e": 967,
"s": 961,
"text": "Scala"
},
{
"code": null,
"e": 980,
"s": 967,
"text": "Scala-Method"
},
{
"code": null,
"e": 994,
"s": 980,
"text": "Scala-Strings"
},
{
"code": null,
"e": 1000,
"s": 994,
"text": "Scala"
},
{
"code": null,
"e": 1098,
"s": 1000,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1120,
"s": 1098,
"text": "Type Casting in Scala"
},
{
"code": null,
"e": 1146,
"s": 1120,
"text": "Class and Object in Scala"
},
{
"code": null,
"e": 1186,
"s": 1146,
"text": "Scala List filter() method with example"
},
{
"code": null,
"e": 1196,
"s": 1186,
"text": "Scala Map"
},
{
"code": null,
"e": 1249,
"s": 1196,
"text": "Scala Tutorial – Learn Scala with Step By Step Guide"
},
{
"code": null,
"e": 1261,
"s": 1249,
"text": "Scala Lists"
},
{
"code": null,
"e": 1280,
"s": 1261,
"text": "Operators in Scala"
},
{
"code": null,
"e": 1295,
"s": 1280,
"text": "Scala | Arrays"
},
{
"code": null,
"e": 1314,
"s": 1295,
"text": "Scala Constructors"
}
] |
Executing SQL query with Psycopg2 in Python | 17 Oct, 2021
In this article, we are going to see how to execute SQL queries in PostgreSQL using Psycopg2 in Python.
Psycopg2 is a PostgreSQL database driver, it is used to perform operations on PostgreSQL using python, it is designed for multi-threaded applications. SQL queries are executed with psycopg2 with the help of the execute() method. It is used to Execute a database operation query or command.
Parameters can be provided in the form of a sequence or a mapping, and they’ll be tied to variables in the operation. Positional ( % s) or named ( % (name)s) placeholders are used to specify variables. execute() method returns “none” if the query is properly executed (without errors).
Python3
import psycopg2 conn = psycopg2.connect( database="geeks", user='postgres', password='root', host='localhost', port='5432') conn.autocommit = Truecursor = conn.cursor() sql = '''CREATE TABLE employees(emp_id int,emp_name varchar, \salary decimal); ''' cursor.execute(sql) conn.commit()conn.close()
Output:
Python3
import psycopg2 conn = psycopg2.connect( database="geeks", user='postgres', password='root', host='localhost', port='5432') conn.autocommit = Truecursor = conn.cursor() sql = '''insert into employee values('191351','divit','100000.0'), ('191352','rhea','70000.0'); ''' cursor.execute(sql) conn.commit()conn.close()
Output:
Python3
import psycopg2 conn = psycopg2.connect( database="geeks", user='postgres', password='root', host='localhost', port='5432') conn.autocommit = Truecursor = conn.cursor() sql = '''SELECT * FROM employee;''' cursor.execute(sql)results = cursor.fetchall()print(results) conn.commit()conn.close()
Output:
[(1216755, ‘raj’, ‘data analyst’, 1000000, 2), (1216756, ‘sarah’, ‘App developer’, 60000, 3), (1216757, ‘rishi’, ‘web developer’, 60000, 1), (1216758, ‘radha’, ‘project analyst’, 70000, 4), (1216759, ‘gowtam’, ‘ml engineer’, 90000, 5), (1216754, ‘rahul’, ‘web developer’, 70000, 5), (191351, ‘divit’, ‘100000.0’, None, None), (191352, ‘rhea’, ‘70000.0’, None, None)]
Picked
Python PostgreSQL
Python Pyscopg2
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
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
Introduction To PYTHON
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n17 Oct, 2021"
},
{
"code": null,
"e": 132,
"s": 28,
"text": "In this article, we are going to see how to execute SQL queries in PostgreSQL using Psycopg2 in Python."
},
{
"code": null,
"e": 423,
"s": 132,
"text": "Psycopg2 is a PostgreSQL database driver, it is used to perform operations on PostgreSQL using python, it is designed for multi-threaded applications. SQL queries are executed with psycopg2 with the help of the execute() method. It is used to Execute a database operation query or command."
},
{
"code": null,
"e": 709,
"s": 423,
"text": "Parameters can be provided in the form of a sequence or a mapping, and they’ll be tied to variables in the operation. Positional ( % s) or named ( % (name)s) placeholders are used to specify variables. execute() method returns “none” if the query is properly executed (without errors)."
},
{
"code": null,
"e": 717,
"s": 709,
"text": "Python3"
},
{
"code": "import psycopg2 conn = psycopg2.connect( database=\"geeks\", user='postgres', password='root', host='localhost', port='5432') conn.autocommit = Truecursor = conn.cursor() sql = '''CREATE TABLE employees(emp_id int,emp_name varchar, \\salary decimal); ''' cursor.execute(sql) conn.commit()conn.close()",
"e": 1025,
"s": 717,
"text": null
},
{
"code": null,
"e": 1033,
"s": 1025,
"text": "Output:"
},
{
"code": null,
"e": 1041,
"s": 1033,
"text": "Python3"
},
{
"code": "import psycopg2 conn = psycopg2.connect( database=\"geeks\", user='postgres', password='root', host='localhost', port='5432') conn.autocommit = Truecursor = conn.cursor() sql = '''insert into employee values('191351','divit','100000.0'), ('191352','rhea','70000.0'); ''' cursor.execute(sql) conn.commit()conn.close()",
"e": 1403,
"s": 1041,
"text": null
},
{
"code": null,
"e": 1411,
"s": 1403,
"text": "Output:"
},
{
"code": null,
"e": 1419,
"s": 1411,
"text": "Python3"
},
{
"code": "import psycopg2 conn = psycopg2.connect( database=\"geeks\", user='postgres', password='root', host='localhost', port='5432') conn.autocommit = Truecursor = conn.cursor() sql = '''SELECT * FROM employee;''' cursor.execute(sql)results = cursor.fetchall()print(results) conn.commit()conn.close()",
"e": 1722,
"s": 1419,
"text": null
},
{
"code": null,
"e": 1730,
"s": 1722,
"text": "Output:"
},
{
"code": null,
"e": 2097,
"s": 1730,
"text": "[(1216755, ‘raj’, ‘data analyst’, 1000000, 2), (1216756, ‘sarah’, ‘App developer’, 60000, 3), (1216757, ‘rishi’, ‘web developer’, 60000, 1), (1216758, ‘radha’, ‘project analyst’, 70000, 4), (1216759, ‘gowtam’, ‘ml engineer’, 90000, 5), (1216754, ‘rahul’, ‘web developer’, 70000, 5), (191351, ‘divit’, ‘100000.0’, None, None), (191352, ‘rhea’, ‘70000.0’, None, None)]"
},
{
"code": null,
"e": 2104,
"s": 2097,
"text": "Picked"
},
{
"code": null,
"e": 2122,
"s": 2104,
"text": "Python PostgreSQL"
},
{
"code": null,
"e": 2138,
"s": 2122,
"text": "Python Pyscopg2"
},
{
"code": null,
"e": 2145,
"s": 2138,
"text": "Python"
},
{
"code": null,
"e": 2243,
"s": 2145,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2275,
"s": 2243,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2302,
"s": 2275,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2323,
"s": 2302,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2354,
"s": 2323,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2410,
"s": 2354,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2433,
"s": 2410,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2475,
"s": 2433,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 2517,
"s": 2475,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 2556,
"s": 2517,
"text": "Python | datetime.timedelta() function"
}
] |
Java program to count the occurrence of each character in a string using Hashmap | 07 Aug, 2021
Given a string, the task is to write a program in Java which prints the number of occurrences of each character in a string.
Examples:
Input: str = "GeeksForGeeks"
Output:
r 1
s 2
e 4
F 1
G 2
k 2
o 1
Input: str = "Ajit"
Output:
A 1
t 1
i 1
j 1
An approach using frequency[] array has already been discussed in the previous post. In this program an approach using Hashmap in Java has been discussed.
Declare a Hashmap in Java of {char, int}.
Traverse in the string, check if the Hashmap already contains the traversed character or not.
If it is present, then increase its count using get() and put() function in Hashmap.
Once the traversal is completed, traverse in the Hashmap and print the character and its frequency.
Below is the implementation of the above approach.
Java
// Java program to count frequencies of// characters in string using Hashmapimport java.io.*;import java.util.*;class OccurenceOfCharInString { static void characterCount(String inputString) { // Creating a HashMap containing char // as a key and occurrences as a value HashMap<Character, Integer> charCountMap = new HashMap<Character, Integer>(); // Converting given string to char array char[] strArray = inputString.toCharArray(); // checking each char of strArray for (char c : strArray) { if (charCountMap.containsKey(c)) { // If char is present in charCountMap, // incrementing it's count by 1 charCountMap.put(c, charCountMap.get(c) + 1); } else { // If char is not present in charCountMap, // putting this char to charCountMap with 1 as it's value charCountMap.put(c, 1); } } // Printing the charCountMap for (Map.Entry entry : charCountMap.entrySet()) { System.out.println(entry.getKey() + " " + entry.getValue()); } } // Driver Code public static void main(String[] args) { String str = "Ajit"; characterCount(str); }}
A 1
t 1
i 1
j 1
kk9826225
Java-HashMap
Java-Strings
Java Programs
Java-Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Factory method design pattern in Java
Java Program to Remove Duplicate Elements From the Array
Iterate through List in Java
How to Iterate HashMap in Java?
Remove first and last character of a string in Java
Iterate Over the Characters of a String in Java
How to Convert Char to String in Java?
Java Program to find largest element in an array
How to Get Elements By Index from HashSet in Java?
Find the duration of difference between two dates in Java | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n07 Aug, 2021"
},
{
"code": null,
"e": 177,
"s": 52,
"text": "Given a string, the task is to write a program in Java which prints the number of occurrences of each character in a string."
},
{
"code": null,
"e": 188,
"s": 177,
"text": "Examples: "
},
{
"code": null,
"e": 303,
"s": 188,
"text": "Input: str = \"GeeksForGeeks\"\nOutput:\nr 1\ns 2\ne 4\nF 1\nG 2\nk 2\no 1\n\nInput: str = \"Ajit\" \nOutput: \nA 1\nt 1\ni 1\nj 1 \n "
},
{
"code": null,
"e": 460,
"s": 303,
"text": "An approach using frequency[] array has already been discussed in the previous post. In this program an approach using Hashmap in Java has been discussed. "
},
{
"code": null,
"e": 502,
"s": 460,
"text": "Declare a Hashmap in Java of {char, int}."
},
{
"code": null,
"e": 596,
"s": 502,
"text": "Traverse in the string, check if the Hashmap already contains the traversed character or not."
},
{
"code": null,
"e": 681,
"s": 596,
"text": "If it is present, then increase its count using get() and put() function in Hashmap."
},
{
"code": null,
"e": 781,
"s": 681,
"text": "Once the traversal is completed, traverse in the Hashmap and print the character and its frequency."
},
{
"code": null,
"e": 834,
"s": 781,
"text": "Below is the implementation of the above approach. "
},
{
"code": null,
"e": 839,
"s": 834,
"text": "Java"
},
{
"code": "// Java program to count frequencies of// characters in string using Hashmapimport java.io.*;import java.util.*;class OccurenceOfCharInString { static void characterCount(String inputString) { // Creating a HashMap containing char // as a key and occurrences as a value HashMap<Character, Integer> charCountMap = new HashMap<Character, Integer>(); // Converting given string to char array char[] strArray = inputString.toCharArray(); // checking each char of strArray for (char c : strArray) { if (charCountMap.containsKey(c)) { // If char is present in charCountMap, // incrementing it's count by 1 charCountMap.put(c, charCountMap.get(c) + 1); } else { // If char is not present in charCountMap, // putting this char to charCountMap with 1 as it's value charCountMap.put(c, 1); } } // Printing the charCountMap for (Map.Entry entry : charCountMap.entrySet()) { System.out.println(entry.getKey() + \" \" + entry.getValue()); } } // Driver Code public static void main(String[] args) { String str = \"Ajit\"; characterCount(str); }}",
"e": 2144,
"s": 839,
"text": null
},
{
"code": null,
"e": 2160,
"s": 2144,
"text": "A 1\nt 1\ni 1\nj 1"
},
{
"code": null,
"e": 2172,
"s": 2162,
"text": "kk9826225"
},
{
"code": null,
"e": 2185,
"s": 2172,
"text": "Java-HashMap"
},
{
"code": null,
"e": 2198,
"s": 2185,
"text": "Java-Strings"
},
{
"code": null,
"e": 2212,
"s": 2198,
"text": "Java Programs"
},
{
"code": null,
"e": 2225,
"s": 2212,
"text": "Java-Strings"
},
{
"code": null,
"e": 2323,
"s": 2225,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2361,
"s": 2323,
"text": "Factory method design pattern in Java"
},
{
"code": null,
"e": 2418,
"s": 2361,
"text": "Java Program to Remove Duplicate Elements From the Array"
},
{
"code": null,
"e": 2447,
"s": 2418,
"text": "Iterate through List in Java"
},
{
"code": null,
"e": 2479,
"s": 2447,
"text": "How to Iterate HashMap in Java?"
},
{
"code": null,
"e": 2531,
"s": 2479,
"text": "Remove first and last character of a string in Java"
},
{
"code": null,
"e": 2579,
"s": 2531,
"text": "Iterate Over the Characters of a String in Java"
},
{
"code": null,
"e": 2618,
"s": 2579,
"text": "How to Convert Char to String in Java?"
},
{
"code": null,
"e": 2667,
"s": 2618,
"text": "Java Program to find largest element in an array"
},
{
"code": null,
"e": 2718,
"s": 2667,
"text": "How to Get Elements By Index from HashSet in Java?"
}
] |
MySQL SELECT to add a new column to a query and give it a value? | To add column to MySQL query and give it a value, use the below syntax −
select yourColumnName1,yourColumnName2,.....N ,yourValue AS anyAliasName from yourTableName;
Let us first create a table −
mysql> create table DemoTable
(
Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
FirstName varchar(20)
);
Query OK, 0 rows affected (0.84 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable(FirstName) values('John');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable(FirstName) values('Larry');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable(FirstName) values('Chris');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable(FirstName) values('Robert');
Query OK, 1 row affected (0.15 sec)
Following is the query to display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+----+-----------+
| Id | FirstName |
+----+-----------+
| 1 | John |
| 2 | Larry |
| 3 | Chris |
| 4 | Robert |
+----+-----------+
4 rows in set (0.00 sec)
Following is the query to add column to MySQL and give it a value. Here we have set the value 23 after creating a new column AGE −
mysql> select Id,FirstName,23 AS AGE from DemoTable;
This will produce the following output −
+----+-----------+-----+
| Id | FirstName | AGE |
+----+-----------+-----+
| 1 | John | 23 |
| 2 | Larry | 23 |
| 3 | Chris | 23 |
| 4 | Robert | 23 |
+----+-----------+-----+
4 rows in set (0.00 sec) | [
{
"code": null,
"e": 1260,
"s": 1187,
"text": "To add column to MySQL query and give it a value, use the below syntax −"
},
{
"code": null,
"e": 1353,
"s": 1260,
"text": "select yourColumnName1,yourColumnName2,.....N ,yourValue AS anyAliasName from yourTableName;"
},
{
"code": null,
"e": 1383,
"s": 1353,
"text": "Let us first create a table −"
},
{
"code": null,
"e": 1527,
"s": 1383,
"text": "mysql> create table DemoTable\n(\n Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n FirstName varchar(20)\n);\nQuery OK, 0 rows affected (0.84 sec)"
},
{
"code": null,
"e": 1583,
"s": 1527,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 1955,
"s": 1583,
"text": "mysql> insert into DemoTable(FirstName) values('John');\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into DemoTable(FirstName) values('Larry');\nQuery OK, 1 row affected (0.17 sec)\nmysql> insert into DemoTable(FirstName) values('Chris');\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into DemoTable(FirstName) values('Robert');\nQuery OK, 1 row affected (0.15 sec)"
},
{
"code": null,
"e": 2041,
"s": 1955,
"text": "Following is the query to display all records from the table using select statement −"
},
{
"code": null,
"e": 2072,
"s": 2041,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 2113,
"s": 2072,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2290,
"s": 2113,
"text": "+----+-----------+\n| Id | FirstName |\n+----+-----------+\n| 1 | John |\n| 2 | Larry |\n| 3 | Chris |\n| 4 | Robert |\n+----+-----------+\n4 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2421,
"s": 2290,
"text": "Following is the query to add column to MySQL and give it a value. Here we have set the value 23 after creating a new column AGE −"
},
{
"code": null,
"e": 2474,
"s": 2421,
"text": "mysql> select Id,FirstName,23 AS AGE from DemoTable;"
},
{
"code": null,
"e": 2515,
"s": 2474,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2740,
"s": 2515,
"text": "+----+-----------+-----+\n| Id | FirstName | AGE |\n+----+-----------+-----+\n| 1 | John | 23 |\n| 2 | Larry | 23 |\n| 3 | Chris | 23 |\n| 4 | Robert | 23 |\n+----+-----------+-----+\n4 rows in set (0.00 sec)"
}
] |
Memory Leak in Python requests | 01 Dec, 2021
When a programmer forgets to clear a memory allocated in heap memory, the memory leak occurs. It’s a type of resource leak or wastage. When there is a memory leak in the application, the memory of the machine gets filled and slows down the performance of the machine. This is a serious issue while building a large scalable application.
Request: The requests library is an integral part of Python for making HTTP requests to a specified URL. Whether it be REST APIs or Web Scrapping, requests are must be learned for proceeding further with these technologies. When one makes a request to a URI, it returns a response. Python requests provide inbuilt functionalities for managing both the request and response.
Gc Module: Module gc is a python inbuilt module, that provides an interface to the python Garbage collector. It provides features to enable collector, disable collector, tune collection frequency, debug options and more.
In lower-level languages like C and C++, the programmer should manually free the resource that is unused i.e write code to manage the resource. But high-level languages like python, java have a concept of automatic memory manager known as Garbage collector. Garbage collector manages the allocation and release of memory for an application.
Some gc methods that we will be using are listed below.
get_objects(): This method returns a list of all tracked objects by the Garbage collector, excluded the list being returned.
collect(): This method free the non referenced object in the list that is maintained by the Collector. Some non-referenced objects are not immediately free automatically due to their implementation.
We will be using get() method in requests, that returns a response object. When the response object is non-referenced i.e deleted its memory should be freed immediately, but due to its implementation, the resource is not freed automatically. Here its stats leaking memory.
Approach:
Get and store the number of objects, tracked ( created and alive) by Collector. You can use gc.get_objects() to get list of tracked objects then use len function to count no. of objects.
Call the function that calls the request.get() method.
Print the response status code, so that we can confirm that the object is created.
Then return the function. When the function is returned, all the created within the function should be deleted.
Get the number of objects tracked currently and compare the valve with the previous value for the leaked objects.
If currently, returned object count is greater, so there is a memory leak.
Below is the implementation:
Python3
import requestsimport gc def call(): # call the get with a url,here I used google.com # get method returns a response object response = requests.get('https://google.com') # print the status code of response print("Status code", response.status_code) # After the function is been returned, # the response object becomes non-referenced return def main(): print("No.of tracked objects before calling get method") # gc.get_objects() returns list objects been tracked # by the collector. # print the length of object list with len function. print(len( gc.get_objects() ) ) # make a call to the function, that calls get method. call() print("No.of tracked objects after calling get method") # print the length of object list with len function. print(len( gc.get_objects() ) ) if __name__ == "__main__": main()
Output:
No.of tracked objects before calling get method
16071
Status code 200
No.of tracked objects after calling get method
16158
A simple solution to this is to manually call the gc.collect() method, this method will free the resource immediately.
Approach:
Get and store the number of objects, tracked ( created and alive) by Collector. You can use gc.get_objects() to get list of tracked objects then use len function to count no. of objects.
Call the function that calls the request.get() method.
Print the response status code, so that we can confirm that the object is created.
Then return the function. When the function is returned, all the created within the function should be deleted.
Call the garbage collector to free the unused resource, i.e to call the gc.collect() method.
Get the number of objects tracked currently, now you can notice the lesser number objects this due to cleaning unused resource.
Below is the implementation:
Python3
import requestsimport gc def call(): # call the get with a url,here I used google.com # get method returns a response object response = requests.get('https://google.com') # print the status code of response print("Status code",response.status_code) # After the function is been returned, # the response object becomes non-referenced return def main(): print("No.of tracked objects before calling get method") # gc.get_objects() returns list objects been tracked # by the collector. # print the length of object list with len function. print(len( gc.get_objects() ) ) # make a call to the function, that calls get method. call() # collect method immediately free the resource of # non-referenced object. gc.collect() # print the length of object list with len # function after removing non-referenced object. print("No.of tracked objects after removing non-referenced objects") print(len( gc.get_objects() ) ) if __name__ == "__main__": main()
Output:
No.of tracked objects before calling get method
16071
Status code 200
No.of tracked objects after removing non-referenced objects
15954
akshaysingh98088
surindertarika1234
Picked
Python-requests
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
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Python | datetime.timedelta() function | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 Dec, 2021"
},
{
"code": null,
"e": 365,
"s": 28,
"text": "When a programmer forgets to clear a memory allocated in heap memory, the memory leak occurs. It’s a type of resource leak or wastage. When there is a memory leak in the application, the memory of the machine gets filled and slows down the performance of the machine. This is a serious issue while building a large scalable application."
},
{
"code": null,
"e": 739,
"s": 365,
"text": "Request: The requests library is an integral part of Python for making HTTP requests to a specified URL. Whether it be REST APIs or Web Scrapping, requests are must be learned for proceeding further with these technologies. When one makes a request to a URI, it returns a response. Python requests provide inbuilt functionalities for managing both the request and response."
},
{
"code": null,
"e": 961,
"s": 739,
"text": " Gc Module: Module gc is a python inbuilt module, that provides an interface to the python Garbage collector. It provides features to enable collector, disable collector, tune collection frequency, debug options and more."
},
{
"code": null,
"e": 1304,
"s": 961,
"text": "In lower-level languages like C and C++, the programmer should manually free the resource that is unused i.e write code to manage the resource. But high-level languages like python, java have a concept of automatic memory manager known as Garbage collector. Garbage collector manages the allocation and release of memory for an application. "
},
{
"code": null,
"e": 1360,
"s": 1304,
"text": "Some gc methods that we will be using are listed below."
},
{
"code": null,
"e": 1485,
"s": 1360,
"text": "get_objects(): This method returns a list of all tracked objects by the Garbage collector, excluded the list being returned."
},
{
"code": null,
"e": 1684,
"s": 1485,
"text": "collect(): This method free the non referenced object in the list that is maintained by the Collector. Some non-referenced objects are not immediately free automatically due to their implementation."
},
{
"code": null,
"e": 1957,
"s": 1684,
"text": "We will be using get() method in requests, that returns a response object. When the response object is non-referenced i.e deleted its memory should be freed immediately, but due to its implementation, the resource is not freed automatically. Here its stats leaking memory."
},
{
"code": null,
"e": 1967,
"s": 1957,
"text": "Approach:"
},
{
"code": null,
"e": 2154,
"s": 1967,
"text": "Get and store the number of objects, tracked ( created and alive) by Collector. You can use gc.get_objects() to get list of tracked objects then use len function to count no. of objects."
},
{
"code": null,
"e": 2209,
"s": 2154,
"text": "Call the function that calls the request.get() method."
},
{
"code": null,
"e": 2292,
"s": 2209,
"text": "Print the response status code, so that we can confirm that the object is created."
},
{
"code": null,
"e": 2404,
"s": 2292,
"text": "Then return the function. When the function is returned, all the created within the function should be deleted."
},
{
"code": null,
"e": 2518,
"s": 2404,
"text": "Get the number of objects tracked currently and compare the valve with the previous value for the leaked objects."
},
{
"code": null,
"e": 2593,
"s": 2518,
"text": "If currently, returned object count is greater, so there is a memory leak."
},
{
"code": null,
"e": 2622,
"s": 2593,
"text": "Below is the implementation:"
},
{
"code": null,
"e": 2630,
"s": 2622,
"text": "Python3"
},
{
"code": "import requestsimport gc def call(): # call the get with a url,here I used google.com # get method returns a response object response = requests.get('https://google.com') # print the status code of response print(\"Status code\", response.status_code) # After the function is been returned, # the response object becomes non-referenced return def main(): print(\"No.of tracked objects before calling get method\") # gc.get_objects() returns list objects been tracked # by the collector. # print the length of object list with len function. print(len( gc.get_objects() ) ) # make a call to the function, that calls get method. call() print(\"No.of tracked objects after calling get method\") # print the length of object list with len function. print(len( gc.get_objects() ) ) if __name__ == \"__main__\": main()",
"e": 3521,
"s": 2630,
"text": null
},
{
"code": null,
"e": 3529,
"s": 3521,
"text": "Output:"
},
{
"code": null,
"e": 3652,
"s": 3529,
"text": "No.of tracked objects before calling get method\n16071\nStatus code 200\nNo.of tracked objects after calling get method\n16158"
},
{
"code": null,
"e": 3771,
"s": 3652,
"text": "A simple solution to this is to manually call the gc.collect() method, this method will free the resource immediately."
},
{
"code": null,
"e": 3781,
"s": 3771,
"text": "Approach:"
},
{
"code": null,
"e": 3968,
"s": 3781,
"text": "Get and store the number of objects, tracked ( created and alive) by Collector. You can use gc.get_objects() to get list of tracked objects then use len function to count no. of objects."
},
{
"code": null,
"e": 4023,
"s": 3968,
"text": "Call the function that calls the request.get() method."
},
{
"code": null,
"e": 4106,
"s": 4023,
"text": "Print the response status code, so that we can confirm that the object is created."
},
{
"code": null,
"e": 4218,
"s": 4106,
"text": "Then return the function. When the function is returned, all the created within the function should be deleted."
},
{
"code": null,
"e": 4311,
"s": 4218,
"text": "Call the garbage collector to free the unused resource, i.e to call the gc.collect() method."
},
{
"code": null,
"e": 4439,
"s": 4311,
"text": "Get the number of objects tracked currently, now you can notice the lesser number objects this due to cleaning unused resource."
},
{
"code": null,
"e": 4468,
"s": 4439,
"text": "Below is the implementation:"
},
{
"code": null,
"e": 4476,
"s": 4468,
"text": "Python3"
},
{
"code": "import requestsimport gc def call(): # call the get with a url,here I used google.com # get method returns a response object response = requests.get('https://google.com') # print the status code of response print(\"Status code\",response.status_code) # After the function is been returned, # the response object becomes non-referenced return def main(): print(\"No.of tracked objects before calling get method\") # gc.get_objects() returns list objects been tracked # by the collector. # print the length of object list with len function. print(len( gc.get_objects() ) ) # make a call to the function, that calls get method. call() # collect method immediately free the resource of # non-referenced object. gc.collect() # print the length of object list with len # function after removing non-referenced object. print(\"No.of tracked objects after removing non-referenced objects\") print(len( gc.get_objects() ) ) if __name__ == \"__main__\": main()",
"e": 5519,
"s": 4476,
"text": null
},
{
"code": null,
"e": 5527,
"s": 5519,
"text": "Output:"
},
{
"code": null,
"e": 5663,
"s": 5527,
"text": "No.of tracked objects before calling get method\n16071\nStatus code 200\nNo.of tracked objects after removing non-referenced objects\n15954"
},
{
"code": null,
"e": 5680,
"s": 5663,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 5699,
"s": 5680,
"text": "surindertarika1234"
},
{
"code": null,
"e": 5706,
"s": 5699,
"text": "Picked"
},
{
"code": null,
"e": 5722,
"s": 5706,
"text": "Python-requests"
},
{
"code": null,
"e": 5729,
"s": 5722,
"text": "Python"
},
{
"code": null,
"e": 5827,
"s": 5729,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5859,
"s": 5827,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 5886,
"s": 5859,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 5907,
"s": 5886,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 5930,
"s": 5907,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 5961,
"s": 5930,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 6017,
"s": 5961,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 6059,
"s": 6017,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 6101,
"s": 6059,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 6140,
"s": 6101,
"text": "Python | Get unique values from a list"
}
] |
ML | Types of Regression Techniques | 19 Aug, 2021
When Regression is chosen? A regression problem is when the output variable is a real or continuous value, such as “salary” or “weight”. Many different models can be used, the simplest is linear regression. It tries to fit data with the best hyperplane which goes through the points.
Regression Analysis is a statistical process for estimating the relationships between the dependent variables or criterion variables and one or more independent variables or predictors. Regression analysis explains the changes in criteria in relation to changes in select predictors. The conditional expectation of the criteria is based on predictors where the average value of the dependent variables is given when the independent variables are changed. Three major uses for regression analysis are determining the strength of predictors, forecasting an effect, and trend forecasting.
Types of Regression:
Linear regression is used for predictive analysis. Linear regression is a linear approach for modelling the relationship between the criterion or the scalar response and the multiple predictors or explanatory variables. Linear regression focuses on the conditional probability distribution of the response given the values of the predictors. For linear regression, there is a danger of overfitting. The formula for linear regression is: Y’ = bX + A.
Polynomial regression is used for curvilinear data. Polynomial regression is fit with the method of least squares. The goal of regression analysis is to model the expected value of a dependent variable y in regards to the independent variable x. The equation for polynomial regression is: l = .
Stepwise regression is used for fitting regression models with predictive models. It is carried out automatically. With each step, the variable is added or subtracted from the set of explanatory variables. The approaches for stepwise regression are forward selection, backward elimination, and bidirectional elimination. The formula for stepwise regression is .
Ridge regression is a technique for analyzing multiple regression data. When multicollinearity occurs, least squares estimates are unbiased. A degree of bias is added to the regression estimates, and as a result, ridge regression reduces the standard errors. The formula for ridge regression is .
Lasso regression is a regression analysis method that performs both variable selection and regularization. Lasso regression uses soft thresholding. Lasso regression selects only a subset of the provided covariates for use in the final model. Lasso regression is .
ElasticNet regression is a regularized regression method that linearly combines the penalties of the lasso and ridge methods. ElasticNet regression is used for support vector machines, metric learning, and portfolio optimization. The penalty function is given by:.Below is the simple implementation:
Python3
# importing librariesimport numpy as npimport matplotlib.pyplot as pltfrom sklearn.linear_model import LinearRegression x = 11 * np.random.random((10, 1)) # y = a * x + by = 1.0 * x + 3.0 # create a linear regression modelmodel = LinearRegression()model.fit(x, y) # predict y from the data where the x is predicted from the xx_pred = np.linspace(0, 11, 100)y_pred = model.predict(x_pred[:, np.newaxis]) # plot the resultsplt.figure(figsize =(3, 5))ax = plt.axes()ax.scatter(x, y) ax.plot(x_pred, y_pred)ax.set_xlabel('predictors')ax.set_ylabel('criterion')ax.axis('tight') plt.show()
Output:
ShubhamMaurya3
shruti20
Picked
Technical Scripter 2018
Machine Learning
Python
Technical Scripter
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
What is Information Retrieval?
Support Vector Machine Algorithm
Random Forest Regression in Python
Elbow Method for optimal value of k in KMeans
Introduction to Recurrent Neural Network
Iterate over a list in Python
How to iterate through Excel rows in Python?
Read JSON file using Python
Python map() function
Enumerate() in Python | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n19 Aug, 2021"
},
{
"code": null,
"e": 338,
"s": 54,
"text": "When Regression is chosen? A regression problem is when the output variable is a real or continuous value, such as “salary” or “weight”. Many different models can be used, the simplest is linear regression. It tries to fit data with the best hyperplane which goes through the points."
},
{
"code": null,
"e": 925,
"s": 338,
"text": "Regression Analysis is a statistical process for estimating the relationships between the dependent variables or criterion variables and one or more independent variables or predictors. Regression analysis explains the changes in criteria in relation to changes in select predictors. The conditional expectation of the criteria is based on predictors where the average value of the dependent variables is given when the independent variables are changed. Three major uses for regression analysis are determining the strength of predictors, forecasting an effect, and trend forecasting. "
},
{
"code": null,
"e": 948,
"s": 925,
"text": "Types of Regression: "
},
{
"code": null,
"e": 1398,
"s": 948,
"text": "Linear regression is used for predictive analysis. Linear regression is a linear approach for modelling the relationship between the criterion or the scalar response and the multiple predictors or explanatory variables. Linear regression focuses on the conditional probability distribution of the response given the values of the predictors. For linear regression, there is a danger of overfitting. The formula for linear regression is: Y’ = bX + A."
},
{
"code": null,
"e": 1694,
"s": 1398,
"text": "Polynomial regression is used for curvilinear data. Polynomial regression is fit with the method of least squares. The goal of regression analysis is to model the expected value of a dependent variable y in regards to the independent variable x. The equation for polynomial regression is: l = . "
},
{
"code": null,
"e": 2057,
"s": 1694,
"text": "Stepwise regression is used for fitting regression models with predictive models. It is carried out automatically. With each step, the variable is added or subtracted from the set of explanatory variables. The approaches for stepwise regression are forward selection, backward elimination, and bidirectional elimination. The formula for stepwise regression is . "
},
{
"code": null,
"e": 2355,
"s": 2057,
"text": "Ridge regression is a technique for analyzing multiple regression data. When multicollinearity occurs, least squares estimates are unbiased. A degree of bias is added to the regression estimates, and as a result, ridge regression reduces the standard errors. The formula for ridge regression is . "
},
{
"code": null,
"e": 2619,
"s": 2355,
"text": "Lasso regression is a regression analysis method that performs both variable selection and regularization. Lasso regression uses soft thresholding. Lasso regression selects only a subset of the provided covariates for use in the final model. Lasso regression is ."
},
{
"code": null,
"e": 2921,
"s": 2619,
"text": "ElasticNet regression is a regularized regression method that linearly combines the penalties of the lasso and ridge methods. ElasticNet regression is used for support vector machines, metric learning, and portfolio optimization. The penalty function is given by:.Below is the simple implementation: "
},
{
"code": null,
"e": 2929,
"s": 2921,
"text": "Python3"
},
{
"code": "# importing librariesimport numpy as npimport matplotlib.pyplot as pltfrom sklearn.linear_model import LinearRegression x = 11 * np.random.random((10, 1)) # y = a * x + by = 1.0 * x + 3.0 # create a linear regression modelmodel = LinearRegression()model.fit(x, y) # predict y from the data where the x is predicted from the xx_pred = np.linspace(0, 11, 100)y_pred = model.predict(x_pred[:, np.newaxis]) # plot the resultsplt.figure(figsize =(3, 5))ax = plt.axes()ax.scatter(x, y) ax.plot(x_pred, y_pred)ax.set_xlabel('predictors')ax.set_ylabel('criterion')ax.axis('tight') plt.show()",
"e": 3513,
"s": 2929,
"text": null
},
{
"code": null,
"e": 3523,
"s": 3513,
"text": "Output: "
},
{
"code": null,
"e": 3540,
"s": 3525,
"text": "ShubhamMaurya3"
},
{
"code": null,
"e": 3549,
"s": 3540,
"text": "shruti20"
},
{
"code": null,
"e": 3556,
"s": 3549,
"text": "Picked"
},
{
"code": null,
"e": 3580,
"s": 3556,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 3597,
"s": 3580,
"text": "Machine Learning"
},
{
"code": null,
"e": 3604,
"s": 3597,
"text": "Python"
},
{
"code": null,
"e": 3623,
"s": 3604,
"text": "Technical Scripter"
},
{
"code": null,
"e": 3640,
"s": 3623,
"text": "Machine Learning"
},
{
"code": null,
"e": 3738,
"s": 3640,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3769,
"s": 3738,
"text": "What is Information Retrieval?"
},
{
"code": null,
"e": 3802,
"s": 3769,
"text": "Support Vector Machine Algorithm"
},
{
"code": null,
"e": 3837,
"s": 3802,
"text": "Random Forest Regression in Python"
},
{
"code": null,
"e": 3883,
"s": 3837,
"text": "Elbow Method for optimal value of k in KMeans"
},
{
"code": null,
"e": 3924,
"s": 3883,
"text": "Introduction to Recurrent Neural Network"
},
{
"code": null,
"e": 3954,
"s": 3924,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 3999,
"s": 3954,
"text": "How to iterate through Excel rows in Python?"
},
{
"code": null,
"e": 4027,
"s": 3999,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 4049,
"s": 4027,
"text": "Python map() function"
}
] |
How to call a jQuery library function? | Calling a JavaScript library function is quite easy. You need to use the script tag. As almost everything we do when using jQuery reads or manipulates the document object model (DOM), we need to make sure that we start adding events etc. as soon as the DOM is ready.
If you want an event to work on your page, you should call it inside the $(document).ready() function. Everything inside it will load as soon as the DOM is loaded and before the page contents are loaded.
To do this, we register a ready event for the document as follows:
$(document).ready(function() {
// do stuff when DOM is ready
});
To call upon any jQuery library function, use HTML script tags:
Live Demo
<html>
<head>
<title>jQuery Function</title>
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("div").click(function() {alert("Hello, world!");});
});
</script>
</head>
<body>
<div id = "mydiv">
Click on this to see a dialogue box.
</div>
</body>
</html> | [
{
"code": null,
"e": 1454,
"s": 1187,
"text": "Calling a JavaScript library function is quite easy. You need to use the script tag. As almost everything we do when using jQuery reads or manipulates the document object model (DOM), we need to make sure that we start adding events etc. as soon as the DOM is ready."
},
{
"code": null,
"e": 1658,
"s": 1454,
"text": "If you want an event to work on your page, you should call it inside the $(document).ready() function. Everything inside it will load as soon as the DOM is loaded and before the page contents are loaded."
},
{
"code": null,
"e": 1725,
"s": 1658,
"text": "To do this, we register a ready event for the document as follows:"
},
{
"code": null,
"e": 1793,
"s": 1725,
"text": "$(document).ready(function() {\n // do stuff when DOM is ready\n});"
},
{
"code": null,
"e": 1857,
"s": 1793,
"text": "To call upon any jQuery library function, use HTML script tags:"
},
{
"code": null,
"e": 1867,
"s": 1857,
"text": "Live Demo"
},
{
"code": null,
"e": 2292,
"s": 1867,
"text": "<html>\n <head>\n <title>jQuery Function</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 $(\"div\").click(function() {alert(\"Hello, world!\");});\n });\n </script>\n </head>\n <body>\n <div id = \"mydiv\">\n Click on this to see a dialogue box.\n </div>\n </body>\n</html>"
}
] |
System tray applications using PyQt5 | 22 May, 2020
In this article, we will learn how to create a System Tray application using PyQt.
System Tray(or menu bar) is an area on the taskbar in an operating system. You can find this system on the bottom right side of the desktop if you’re using windows, and top right if using macOS. The icons which are visible in this notification area are the ones that run in the foreground. Some of the famous applications which use system tray to function, and they are Windscribe(VPN application) and Adobe Creative Cloud.
Menu bar applications are also useful to minimally control the desktop application using the shortcuts provided in the menu bar icon. One can choose to not open the whole application and still work by just using the options provided on the System Tray. In this article, you will learn how to create these applications.
Below is an example of an application named Windscribe.
Code:
from PyQt5.QtGui import * from PyQt5.QtWidgets import * app = QApplication([])app.setQuitOnLastWindowClosed(False) # Adding an iconicon = QIcon("icon.png") # Adding item on the menu bartray = QSystemTrayIcon()tray.setIcon(icon)tray.setVisible(True) # Creating the optionsmenu = QMenu()option1 = QAction("Geeks for Geeks")option2 = QAction("GFG")menu.addAction(option1)menu.addAction(option2) # To quit the appquit = QAction("Quit")quit.triggered.connect(app.quit)menu.addAction(quit) # Adding options to the System Traytray.setContextMenu(menu) app.exec_()
Output:
As you can see there is a marker icon on my mac menu bar, and there are three options visible namely Geeks for Geeks, GFG, and quit. By clicking on the last option(quit) you will exit the application.
PyQt-exercise
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Iterate over a list in Python
Python Classes and Objects
Convert integer to string in Python | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 May, 2020"
},
{
"code": null,
"e": 111,
"s": 28,
"text": "In this article, we will learn how to create a System Tray application using PyQt."
},
{
"code": null,
"e": 535,
"s": 111,
"text": "System Tray(or menu bar) is an area on the taskbar in an operating system. You can find this system on the bottom right side of the desktop if you’re using windows, and top right if using macOS. The icons which are visible in this notification area are the ones that run in the foreground. Some of the famous applications which use system tray to function, and they are Windscribe(VPN application) and Adobe Creative Cloud."
},
{
"code": null,
"e": 854,
"s": 535,
"text": "Menu bar applications are also useful to minimally control the desktop application using the shortcuts provided in the menu bar icon. One can choose to not open the whole application and still work by just using the options provided on the System Tray. In this article, you will learn how to create these applications."
},
{
"code": null,
"e": 910,
"s": 854,
"text": "Below is an example of an application named Windscribe."
},
{
"code": null,
"e": 916,
"s": 910,
"text": "Code:"
},
{
"code": "from PyQt5.QtGui import * from PyQt5.QtWidgets import * app = QApplication([])app.setQuitOnLastWindowClosed(False) # Adding an iconicon = QIcon(\"icon.png\") # Adding item on the menu bartray = QSystemTrayIcon()tray.setIcon(icon)tray.setVisible(True) # Creating the optionsmenu = QMenu()option1 = QAction(\"Geeks for Geeks\")option2 = QAction(\"GFG\")menu.addAction(option1)menu.addAction(option2) # To quit the appquit = QAction(\"Quit\")quit.triggered.connect(app.quit)menu.addAction(quit) # Adding options to the System Traytray.setContextMenu(menu) app.exec_()",
"e": 1483,
"s": 916,
"text": null
},
{
"code": null,
"e": 1491,
"s": 1483,
"text": "Output:"
},
{
"code": null,
"e": 1692,
"s": 1491,
"text": "As you can see there is a marker icon on my mac menu bar, and there are three options visible namely Geeks for Geeks, GFG, and quit. By clicking on the last option(quit) you will exit the application."
},
{
"code": null,
"e": 1706,
"s": 1692,
"text": "PyQt-exercise"
},
{
"code": null,
"e": 1718,
"s": 1706,
"text": "Python-PyQt"
},
{
"code": null,
"e": 1725,
"s": 1718,
"text": "Python"
},
{
"code": null,
"e": 1823,
"s": 1725,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1841,
"s": 1823,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1883,
"s": 1841,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1905,
"s": 1883,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1940,
"s": 1905,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 1966,
"s": 1940,
"text": "Python String | replace()"
},
{
"code": null,
"e": 1998,
"s": 1966,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2027,
"s": 1998,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2057,
"s": 2027,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 2084,
"s": 2057,
"text": "Python Classes and Objects"
}
] |
Gateway Load Balancing Protocol (GLBP) - GeeksforGeeks | 09 Aug, 2019
Gateway Load Balancing Protocol (GLBP) is one of First Hop Redundancy Protocol (FHRP) which provides redundancy like other First Hop Redundancy Protocol, also provides load Balancing. It is a Cisco proprietary protocol which can perform both functions. It provides load Balancing over multiple routers using single virtual IP address and multiple virtual Mac address.
GLBP terms :
Virtual IP address : An IP address is assigned as a virtual IP address from the local subnet which is configured as a default gateway for all the local hosts.Actual Virtual Gateway (AVG) : It is one of the router operating GLBP in a single group which is responsible for assigning virtual Mac address for each member in the group and for responding of the ARP request coming from the devices. The AVG has the highest priority value or IP address in the group.Actual Virtual forwarder (AVF) : These are the routers including the AVG in a single GLBP group. These are actually responsible for forwarding the data after they are assigned by the AVG for the task. If in case AVG goes down, one of the AVFs can become the AVG.Preempt : It is a state in which the one of the AVF will become the AVG router (when the AVG router goes down). Also, when the AVG router comes up again, it will become the AVG router as it’s priority is still higher (assumed).Object tracking : GLBP uses a weighting scheme to determine the forwarding capacity of each router in the GLBP group. GLBP tracks interface and adjusts it’s weighting i.e if the tracked interface goes down then it reduces by certain value (according to the configuration).
Virtual IP address : An IP address is assigned as a virtual IP address from the local subnet which is configured as a default gateway for all the local hosts.
Actual Virtual Gateway (AVG) : It is one of the router operating GLBP in a single group which is responsible for assigning virtual Mac address for each member in the group and for responding of the ARP request coming from the devices. The AVG has the highest priority value or IP address in the group.
Actual Virtual forwarder (AVF) : These are the routers including the AVG in a single GLBP group. These are actually responsible for forwarding the data after they are assigned by the AVG for the task. If in case AVG goes down, one of the AVFs can become the AVG.
Preempt : It is a state in which the one of the AVF will become the AVG router (when the AVG router goes down). Also, when the AVG router comes up again, it will become the AVG router as it’s priority is still higher (assumed).
Object tracking : GLBP uses a weighting scheme to determine the forwarding capacity of each router in the GLBP group. GLBP tracks interface and adjusts it’s weighting i.e if the tracked interface goes down then it reduces by certain value (according to the configuration).
The Actual Virtual Gateway (AVG) provides virtual Mac addresses to all the other routers operating GLBP of the same group. The remaining routers are Actual Virtual Forwarder (AVF). When an ARP request comes from subnet device to know the Mac address of the virtual IP address, one of the virtual Mac addresses is provided by the AVG. AVG will provide the virtual Mac address by using Round Robin algorithm or other algorithms that have been applied. In this way, all devices running GLBP are used to forward traffic.
GLBP virtual Mac address Assignment : When a subnet device (host) wants to send traffic, it requests a Mac address for the virtual IP (gateway) by sending an ARP request. In response to the ARP request, AVG will provide one of the virtual Mac address (provided to AVF by AVG).
Virtual Gateway Redundancy : To detect a gateway failure, GLBP members communicate with each other through hello messages, sent in every 3-seconds to the multicast address 224.0.0.102. If AVG fails, then the AVF having highest priority will become the AVG i.e responsible for providing the Mac address of AVFs.
Virtual forwarder Redundancy : Just like in HSRP, if one of the AVF fails then the other AVF in the same GLBP group will take the responsibility of forwarding the packets. There can be maximum 4 routers in a GLBP group.
GLBP uses 3 algorithm for load Balancing –
Round-Robin : AVG will assign the virtual Mac addresses serial wise, like first virtual Mac address is assigned to AVF1, then to AVF2 etc.Host-dependent : If particular host needs specific virtual Mac address every time then specific AVF is assigned to the hosts by the AVG.Weighted : The load will be distributed according to the requirement i.e assigning virtual Mac address in proportions. If we want some AVFs to handle more traffic than other, then change the weight.
Round-Robin : AVG will assign the virtual Mac addresses serial wise, like first virtual Mac address is assigned to AVF1, then to AVF2 etc.
Host-dependent : If particular host needs specific virtual Mac address every time then specific AVF is assigned to the hosts by the AVG.
Weighted : The load will be distributed according to the requirement i.e assigning virtual Mac address in proportions. If we want some AVFs to handle more traffic than other, then change the weight.
Configuration :In given topology, there are 2 routers named R1 and R2 where R1 is connected via fa0/0 ip address is 10.1.1.1/24 and R2 is connected via fa0/0 ip address is 10.1.1.2/24.
Assigning IP address to router R1.
r1(config)# int fa0/0
r1(config-if)# ip add 10.1.1.1 255.255.255.0
Assigning IP address to router R2.
r2(config)# int fa0/0
r2(config-if)# ip address 10.1.1.2 255.255.255.0
Now, configure virtual IP, GLBP priority, preemption and type of load Balancing.
r1(config-if)# glbp 1 ip 10.1.1.100
r1(config-if)# glbp 1 priority 120
r1(config-if)# glbp 1 preempt
r1(config-if)# glbp 1 load-balancing round-robin
Here, assign the virtual IP as 10.1.1.100 from the local subnet and priority(assign R1 with higher priority as we want this router to become AVG). Also, preempt has been enabled and load Balancing of type round-robin. Now, configure same GLBP for r2.
r2(config-if)# glbp 1 ip 10.1.1.100
r2(config-if)# glbp 1 priority 100
r2(config-if)# glbp 1 preempt
r2(config-if)# glbp 1 load-balancing round-robin
Note : Here, switch resides between the AVG and AVF, then how switch will learn the same Mac address on another port, when AVG goes down? When AVG goes down, then the newly elected AVG will produce a gratuitous ARP to flush the CAM table of switches and the host ARP cache.
Advantages :
GLBP supports clear text and MD5 password Authentication.It supports up to 1024 virtual routers(GLBP groups).Allows load sharing using single virtual IP and multiple virtual Mac address.
GLBP supports clear text and MD5 password Authentication.
It supports up to 1024 virtual routers(GLBP groups).
Allows load sharing using single virtual IP and multiple virtual Mac address.
Computer Networks-Network Layer
Computer Networks
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
RSA Algorithm in Cryptography
Differences between TCP and UDP
Differences between IPv4 and IPv6
Data encryption standard (DES) | Set 1
Socket Programming in Python
Types of Network Topology
Implementation of Diffie-Hellman Algorithm
TCP 3-Way Handshake Process
User Datagram Protocol (UDP)
Types of Transmission Media | [
{
"code": null,
"e": 26207,
"s": 26179,
"text": "\n09 Aug, 2019"
},
{
"code": null,
"e": 26575,
"s": 26207,
"text": "Gateway Load Balancing Protocol (GLBP) is one of First Hop Redundancy Protocol (FHRP) which provides redundancy like other First Hop Redundancy Protocol, also provides load Balancing. It is a Cisco proprietary protocol which can perform both functions. It provides load Balancing over multiple routers using single virtual IP address and multiple virtual Mac address."
},
{
"code": null,
"e": 26588,
"s": 26575,
"text": "GLBP terms :"
},
{
"code": null,
"e": 27809,
"s": 26588,
"text": "Virtual IP address : An IP address is assigned as a virtual IP address from the local subnet which is configured as a default gateway for all the local hosts.Actual Virtual Gateway (AVG) : It is one of the router operating GLBP in a single group which is responsible for assigning virtual Mac address for each member in the group and for responding of the ARP request coming from the devices. The AVG has the highest priority value or IP address in the group.Actual Virtual forwarder (AVF) : These are the routers including the AVG in a single GLBP group. These are actually responsible for forwarding the data after they are assigned by the AVG for the task. If in case AVG goes down, one of the AVFs can become the AVG.Preempt : It is a state in which the one of the AVF will become the AVG router (when the AVG router goes down). Also, when the AVG router comes up again, it will become the AVG router as it’s priority is still higher (assumed).Object tracking : GLBP uses a weighting scheme to determine the forwarding capacity of each router in the GLBP group. GLBP tracks interface and adjusts it’s weighting i.e if the tracked interface goes down then it reduces by certain value (according to the configuration)."
},
{
"code": null,
"e": 27968,
"s": 27809,
"text": "Virtual IP address : An IP address is assigned as a virtual IP address from the local subnet which is configured as a default gateway for all the local hosts."
},
{
"code": null,
"e": 28270,
"s": 27968,
"text": "Actual Virtual Gateway (AVG) : It is one of the router operating GLBP in a single group which is responsible for assigning virtual Mac address for each member in the group and for responding of the ARP request coming from the devices. The AVG has the highest priority value or IP address in the group."
},
{
"code": null,
"e": 28533,
"s": 28270,
"text": "Actual Virtual forwarder (AVF) : These are the routers including the AVG in a single GLBP group. These are actually responsible for forwarding the data after they are assigned by the AVG for the task. If in case AVG goes down, one of the AVFs can become the AVG."
},
{
"code": null,
"e": 28761,
"s": 28533,
"text": "Preempt : It is a state in which the one of the AVF will become the AVG router (when the AVG router goes down). Also, when the AVG router comes up again, it will become the AVG router as it’s priority is still higher (assumed)."
},
{
"code": null,
"e": 29034,
"s": 28761,
"text": "Object tracking : GLBP uses a weighting scheme to determine the forwarding capacity of each router in the GLBP group. GLBP tracks interface and adjusts it’s weighting i.e if the tracked interface goes down then it reduces by certain value (according to the configuration)."
},
{
"code": null,
"e": 29551,
"s": 29034,
"text": "The Actual Virtual Gateway (AVG) provides virtual Mac addresses to all the other routers operating GLBP of the same group. The remaining routers are Actual Virtual Forwarder (AVF). When an ARP request comes from subnet device to know the Mac address of the virtual IP address, one of the virtual Mac addresses is provided by the AVG. AVG will provide the virtual Mac address by using Round Robin algorithm or other algorithms that have been applied. In this way, all devices running GLBP are used to forward traffic."
},
{
"code": null,
"e": 29828,
"s": 29551,
"text": "GLBP virtual Mac address Assignment : When a subnet device (host) wants to send traffic, it requests a Mac address for the virtual IP (gateway) by sending an ARP request. In response to the ARP request, AVG will provide one of the virtual Mac address (provided to AVF by AVG)."
},
{
"code": null,
"e": 30139,
"s": 29828,
"text": "Virtual Gateway Redundancy : To detect a gateway failure, GLBP members communicate with each other through hello messages, sent in every 3-seconds to the multicast address 224.0.0.102. If AVG fails, then the AVF having highest priority will become the AVG i.e responsible for providing the Mac address of AVFs."
},
{
"code": null,
"e": 30359,
"s": 30139,
"text": "Virtual forwarder Redundancy : Just like in HSRP, if one of the AVF fails then the other AVF in the same GLBP group will take the responsibility of forwarding the packets. There can be maximum 4 routers in a GLBP group."
},
{
"code": null,
"e": 30402,
"s": 30359,
"text": "GLBP uses 3 algorithm for load Balancing –"
},
{
"code": null,
"e": 30875,
"s": 30402,
"text": "Round-Robin : AVG will assign the virtual Mac addresses serial wise, like first virtual Mac address is assigned to AVF1, then to AVF2 etc.Host-dependent : If particular host needs specific virtual Mac address every time then specific AVF is assigned to the hosts by the AVG.Weighted : The load will be distributed according to the requirement i.e assigning virtual Mac address in proportions. If we want some AVFs to handle more traffic than other, then change the weight."
},
{
"code": null,
"e": 31014,
"s": 30875,
"text": "Round-Robin : AVG will assign the virtual Mac addresses serial wise, like first virtual Mac address is assigned to AVF1, then to AVF2 etc."
},
{
"code": null,
"e": 31151,
"s": 31014,
"text": "Host-dependent : If particular host needs specific virtual Mac address every time then specific AVF is assigned to the hosts by the AVG."
},
{
"code": null,
"e": 31350,
"s": 31151,
"text": "Weighted : The load will be distributed according to the requirement i.e assigning virtual Mac address in proportions. If we want some AVFs to handle more traffic than other, then change the weight."
},
{
"code": null,
"e": 31535,
"s": 31350,
"text": "Configuration :In given topology, there are 2 routers named R1 and R2 where R1 is connected via fa0/0 ip address is 10.1.1.1/24 and R2 is connected via fa0/0 ip address is 10.1.1.2/24."
},
{
"code": null,
"e": 31570,
"s": 31535,
"text": "Assigning IP address to router R1."
},
{
"code": null,
"e": 31637,
"s": 31570,
"text": "r1(config)# int fa0/0\nr1(config-if)# ip add 10.1.1.1 255.255.255.0"
},
{
"code": null,
"e": 31672,
"s": 31637,
"text": "Assigning IP address to router R2."
},
{
"code": null,
"e": 31743,
"s": 31672,
"text": "r2(config)# int fa0/0\nr2(config-if)# ip address 10.1.1.2 255.255.255.0"
},
{
"code": null,
"e": 31824,
"s": 31743,
"text": "Now, configure virtual IP, GLBP priority, preemption and type of load Balancing."
},
{
"code": null,
"e": 31974,
"s": 31824,
"text": "r1(config-if)# glbp 1 ip 10.1.1.100\nr1(config-if)# glbp 1 priority 120\nr1(config-if)# glbp 1 preempt\nr1(config-if)# glbp 1 load-balancing round-robin"
},
{
"code": null,
"e": 32225,
"s": 31974,
"text": "Here, assign the virtual IP as 10.1.1.100 from the local subnet and priority(assign R1 with higher priority as we want this router to become AVG). Also, preempt has been enabled and load Balancing of type round-robin. Now, configure same GLBP for r2."
},
{
"code": null,
"e": 32375,
"s": 32225,
"text": "r2(config-if)# glbp 1 ip 10.1.1.100\nr2(config-if)# glbp 1 priority 100\nr2(config-if)# glbp 1 preempt\nr2(config-if)# glbp 1 load-balancing round-robin"
},
{
"code": null,
"e": 32649,
"s": 32375,
"text": "Note : Here, switch resides between the AVG and AVF, then how switch will learn the same Mac address on another port, when AVG goes down? When AVG goes down, then the newly elected AVG will produce a gratuitous ARP to flush the CAM table of switches and the host ARP cache."
},
{
"code": null,
"e": 32662,
"s": 32649,
"text": "Advantages :"
},
{
"code": null,
"e": 32849,
"s": 32662,
"text": "GLBP supports clear text and MD5 password Authentication.It supports up to 1024 virtual routers(GLBP groups).Allows load sharing using single virtual IP and multiple virtual Mac address."
},
{
"code": null,
"e": 32907,
"s": 32849,
"text": "GLBP supports clear text and MD5 password Authentication."
},
{
"code": null,
"e": 32960,
"s": 32907,
"text": "It supports up to 1024 virtual routers(GLBP groups)."
},
{
"code": null,
"e": 33038,
"s": 32960,
"text": "Allows load sharing using single virtual IP and multiple virtual Mac address."
},
{
"code": null,
"e": 33070,
"s": 33038,
"text": "Computer Networks-Network Layer"
},
{
"code": null,
"e": 33088,
"s": 33070,
"text": "Computer Networks"
},
{
"code": null,
"e": 33106,
"s": 33088,
"text": "Computer Networks"
},
{
"code": null,
"e": 33204,
"s": 33106,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33234,
"s": 33204,
"text": "RSA Algorithm in Cryptography"
},
{
"code": null,
"e": 33266,
"s": 33234,
"text": "Differences between TCP and UDP"
},
{
"code": null,
"e": 33300,
"s": 33266,
"text": "Differences between IPv4 and IPv6"
},
{
"code": null,
"e": 33339,
"s": 33300,
"text": "Data encryption standard (DES) | Set 1"
},
{
"code": null,
"e": 33368,
"s": 33339,
"text": "Socket Programming in Python"
},
{
"code": null,
"e": 33394,
"s": 33368,
"text": "Types of Network Topology"
},
{
"code": null,
"e": 33437,
"s": 33394,
"text": "Implementation of Diffie-Hellman Algorithm"
},
{
"code": null,
"e": 33465,
"s": 33437,
"text": "TCP 3-Way Handshake Process"
},
{
"code": null,
"e": 33494,
"s": 33465,
"text": "User Datagram Protocol (UDP)"
}
] |
4-ZERO-3: Tool to bypass 403/401 - GeeksforGeeks | 04 Jan, 2022
4-ZERO-3 is a free and open-source tool available on GitHub. It’s a bash script.4-ZERO-3 is used to bypass 403 and 401 technical obstacles on any domain. Content length matters when performing bypass using the 4-ZERO-3 tool. If you see multiple 200 while bypassing then you must check the content length. 4-ZERO-3 can curl Payload automatically if any bypass is found.
Step 1: Use the following command to install the tool from Github.
git clone https://github.com/Dheerajmadhukar/4-ZERO-3
Step 2: Use the following command to run the tool.
bash 403-bypass.sh
The tool has been installed and running successfully. Now we will see examples to use the tool.
Example 1: Use the 4-ZERO-3 tool to perform 403/402 bypass using content headers of the domain.
bash 403-bypass.sh -u https://target.com/secret –header
Example 2: Use the 4-ZERO-3 tool to perform 403/402 bypass using content protocols of the domain.
bash 403-bypass.sh -u https://target.com/secret –protocol
Example 3:Use the 4-ZERO-3 tool to perform PORT based bypasses/payloads.
bash 403-bypass.sh -u https://target.com/secret –port
Example 4: Use the 4-ZERO-3 tool to perform HTTP Method based bypasses/payloads
bash 403-bypass.sh -u https://target.com/secret –HTTPmethod
Example 4: Use the 4-ZERO-3 tool to perform URL Encoded bypasses/payloads
bash 403-bypass.sh -u https://target.com/secret –encode
Example 5: Use the 4-ZERO-3 tool to perform MySQL mod_Security & libinjection bypasses/payloads [** New **]
bash 403-bypass.sh -u https://target.com/secret –SQLi
Example 6: Use the 4-ZERO-3 tool to perform complete Scan {includes all exploits/payloads} for an endpoint [ –exploit ]
bash 403-bypass.sh -u https://target.com/secret –exploit
Kali-Linux
Linux-Tools
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Thread functions in C/C++
Basic Operators in Shell Scripting
nohup Command in Linux with Examples
Array Basics in Shell Scripting | Set 1
Named Pipe or FIFO with example C program
chown command in Linux with Examples
mv command in Linux with examples
Docker - COPY Instruction
Start/Stop/Restart Services Using Systemctl in Linux
SED command in Linux | Set 2 | [
{
"code": null,
"e": 24326,
"s": 24298,
"text": "\n04 Jan, 2022"
},
{
"code": null,
"e": 24697,
"s": 24326,
"text": "4-ZERO-3 is a free and open-source tool available on GitHub. It’s a bash script.4-ZERO-3 is used to bypass 403 and 401 technical obstacles on any domain. Content length matters when performing bypass using the 4-ZERO-3 tool. If you see multiple 200 while bypassing then you must check the content length. 4-ZERO-3 can curl Payload automatically if any bypass is found."
},
{
"code": null,
"e": 24764,
"s": 24697,
"text": "Step 1: Use the following command to install the tool from Github."
},
{
"code": null,
"e": 24818,
"s": 24764,
"text": "git clone https://github.com/Dheerajmadhukar/4-ZERO-3"
},
{
"code": null,
"e": 24869,
"s": 24818,
"text": "Step 2: Use the following command to run the tool."
},
{
"code": null,
"e": 24889,
"s": 24869,
"text": "bash 403-bypass.sh "
},
{
"code": null,
"e": 24985,
"s": 24889,
"text": "The tool has been installed and running successfully. Now we will see examples to use the tool."
},
{
"code": null,
"e": 25083,
"s": 24985,
"text": "Example 1: Use the 4-ZERO-3 tool to perform 403/402 bypass using content headers of the domain."
},
{
"code": null,
"e": 25139,
"s": 25083,
"text": "bash 403-bypass.sh -u https://target.com/secret –header"
},
{
"code": null,
"e": 25239,
"s": 25139,
"text": "Example 2: Use the 4-ZERO-3 tool to perform 403/402 bypass using content protocols of the domain."
},
{
"code": null,
"e": 25298,
"s": 25239,
"text": " bash 403-bypass.sh -u https://target.com/secret –protocol"
},
{
"code": null,
"e": 25374,
"s": 25298,
"text": "Example 3:Use the 4-ZERO-3 tool to perform PORT based bypasses/payloads."
},
{
"code": null,
"e": 25428,
"s": 25374,
"text": "bash 403-bypass.sh -u https://target.com/secret –port"
},
{
"code": null,
"e": 25510,
"s": 25428,
"text": "Example 4: Use the 4-ZERO-3 tool to perform HTTP Method based bypasses/payloads"
},
{
"code": null,
"e": 25570,
"s": 25510,
"text": "bash 403-bypass.sh -u https://target.com/secret –HTTPmethod"
},
{
"code": null,
"e": 25646,
"s": 25570,
"text": "Example 4: Use the 4-ZERO-3 tool to perform URL Encoded bypasses/payloads"
},
{
"code": null,
"e": 25702,
"s": 25646,
"text": "bash 403-bypass.sh -u https://target.com/secret –encode"
},
{
"code": null,
"e": 25813,
"s": 25702,
"text": "Example 5: Use the 4-ZERO-3 tool to perform MySQL mod_Security & libinjection bypasses/payloads [** New **]"
},
{
"code": null,
"e": 25867,
"s": 25813,
"text": "bash 403-bypass.sh -u https://target.com/secret –SQLi"
},
{
"code": null,
"e": 25989,
"s": 25867,
"text": "Example 6: Use the 4-ZERO-3 tool to perform complete Scan {includes all exploits/payloads} for an endpoint [ –exploit ]"
},
{
"code": null,
"e": 26046,
"s": 25989,
"text": "bash 403-bypass.sh -u https://target.com/secret –exploit"
},
{
"code": null,
"e": 26057,
"s": 26046,
"text": "Kali-Linux"
},
{
"code": null,
"e": 26069,
"s": 26057,
"text": "Linux-Tools"
},
{
"code": null,
"e": 26080,
"s": 26069,
"text": "Linux-Unix"
},
{
"code": null,
"e": 26178,
"s": 26080,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26187,
"s": 26178,
"text": "Comments"
},
{
"code": null,
"e": 26200,
"s": 26187,
"text": "Old Comments"
},
{
"code": null,
"e": 26226,
"s": 26200,
"text": "Thread functions in C/C++"
},
{
"code": null,
"e": 26261,
"s": 26226,
"text": "Basic Operators in Shell Scripting"
},
{
"code": null,
"e": 26298,
"s": 26261,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 26338,
"s": 26298,
"text": "Array Basics in Shell Scripting | Set 1"
},
{
"code": null,
"e": 26380,
"s": 26338,
"text": "Named Pipe or FIFO with example C program"
},
{
"code": null,
"e": 26417,
"s": 26380,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 26451,
"s": 26417,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 26477,
"s": 26451,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 26530,
"s": 26477,
"text": "Start/Stop/Restart Services Using Systemctl in Linux"
}
] |
Extract Just Number from Named Numeric Vector in R - GeeksforGeeks | 16 May, 2021
In this article, we are going to see how to extract just the number from the named numeric vector in R Programming Language.
Method 1: Using NULL
The names() method can be invoked on the vector and assigned to NULL in order to remove any instances of the names set to this object. It makes modifications to the original vector object.
R
# declaring a vector vec <- c(0 : 5) # assigning names to the vectornames(vec)<-c("Ele1", "Ele2", "Ele3", "Ele4", "Ele5", "Ele6")print("Original vector")print(vec) # assigning the names vector to nullnames(vec) <- NULLprint("Modified vector")print(vec)
Output:
[1] "Original vector"
Ele1 Ele2 Ele3 Ele4 Ele5 Ele6
0 1 2 3 4 5
[1] "Modified vector"
[1] 0 1 2 3 4 5
Explanation: The string names have been assigned as names to the corresponding elements of the vector. As soon as null is assigned to the names() method, the names are reset, and only the numerical values are returned.
Method 2: Using unname() method
unname() method in R is used to remove any instances of the names assigned to the R object over which it is invoked. It resets the names assigned to the vector object and extracts the numeric portion from it. The changes have to be stored in order to make them reflect during further usage.
R
# declaring a vector vec <- c(0 : 5) # assigning names to the vectornames(vec)<-c("Ele1", "Ele2", "Ele3", "Ele4", "Ele5")print("Original vector")print(vec) # assigning the names vector to nullvec_mod <- unname(vec)print("Modified vector")print(vec_mod)
Output:
[1] "Original vector"
Ele1 Ele2 Ele3 Ele4 Ele5 <NA>
0 1 2 3 4 5
[1] "Modified vector"
[1] 0 1 2 3 4 5
Method 3: Using as.numeric() method
The as.numeric() method in R is used to coerce an argument to a numerical value. However, it’s a generic function applicable to both integers, float, or double type numbers. It eliminates any strings stored within the numbers, be it names or elements that are not convertible to numeric data. The changes have to be stored in order to make them reflect during further usage.
as.numeric(x)
R
# declaring a vector vec <- c(1.2, 35.6, 35.2, 0.9, 46.7) # assigning names to the vectornames(vec)<-c("Ele1", "Ele2", "Ele3", "Ele4", "Ele5")print("Original vector")print(vec) # reassigning namesvec_mod <- as.numeric(vec)print("Modified vector")print(vec_mod)
Output:
[1] "Original vector"
Ele1 Ele2 Ele3 Ele4 Ele5
1.2 35.6 35.2 0.9 46.7
[1] "Modified vector"
[1] 1.2 35.6 35.2 0.9 46.7
Picked
R Vector-Programs
R-Vectors
R Language
R Programs
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
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
How to Change Axis Scales in R Plots?
Replace Specific Characters in String in R
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
How to filter R dataframe by multiple conditions?
Convert Matrix to Dataframe in R | [
{
"code": null,
"e": 26487,
"s": 26459,
"text": "\n16 May, 2021"
},
{
"code": null,
"e": 26612,
"s": 26487,
"text": "In this article, we are going to see how to extract just the number from the named numeric vector in R Programming Language."
},
{
"code": null,
"e": 26633,
"s": 26612,
"text": "Method 1: Using NULL"
},
{
"code": null,
"e": 26823,
"s": 26633,
"text": "The names() method can be invoked on the vector and assigned to NULL in order to remove any instances of the names set to this object. It makes modifications to the original vector object. "
},
{
"code": null,
"e": 26825,
"s": 26823,
"text": "R"
},
{
"code": "# declaring a vector vec <- c(0 : 5) # assigning names to the vectornames(vec)<-c(\"Ele1\", \"Ele2\", \"Ele3\", \"Ele4\", \"Ele5\", \"Ele6\")print(\"Original vector\")print(vec) # assigning the names vector to nullnames(vec) <- NULLprint(\"Modified vector\")print(vec)",
"e": 27093,
"s": 26825,
"text": null
},
{
"code": null,
"e": 27101,
"s": 27093,
"text": "Output:"
},
{
"code": null,
"e": 27220,
"s": 27101,
"text": "[1] \"Original vector\"\nEle1 Ele2 Ele3 Ele4 Ele5 Ele6\n 0 1 2 3 4 5\n[1] \"Modified vector\"\n[1] 0 1 2 3 4 5"
},
{
"code": null,
"e": 27440,
"s": 27220,
"text": "Explanation: The string names have been assigned as names to the corresponding elements of the vector. As soon as null is assigned to the names() method, the names are reset, and only the numerical values are returned. "
},
{
"code": null,
"e": 27472,
"s": 27440,
"text": "Method 2: Using unname() method"
},
{
"code": null,
"e": 27764,
"s": 27472,
"text": "unname() method in R is used to remove any instances of the names assigned to the R object over which it is invoked. It resets the names assigned to the vector object and extracts the numeric portion from it. The changes have to be stored in order to make them reflect during further usage. "
},
{
"code": null,
"e": 27766,
"s": 27764,
"text": "R"
},
{
"code": "# declaring a vector vec <- c(0 : 5) # assigning names to the vectornames(vec)<-c(\"Ele1\", \"Ele2\", \"Ele3\", \"Ele4\", \"Ele5\")print(\"Original vector\")print(vec) # assigning the names vector to nullvec_mod <- unname(vec)print(\"Modified vector\")print(vec_mod)",
"e": 28035,
"s": 27766,
"text": null
},
{
"code": null,
"e": 28043,
"s": 28035,
"text": "Output:"
},
{
"code": null,
"e": 28162,
"s": 28043,
"text": "[1] \"Original vector\"\nEle1 Ele2 Ele3 Ele4 Ele5 <NA>\n 0 1 2 3 4 5\n[1] \"Modified vector\"\n[1] 0 1 2 3 4 5"
},
{
"code": null,
"e": 28198,
"s": 28162,
"text": "Method 3: Using as.numeric() method"
},
{
"code": null,
"e": 28574,
"s": 28198,
"text": "The as.numeric() method in R is used to coerce an argument to a numerical value. However, it’s a generic function applicable to both integers, float, or double type numbers. It eliminates any strings stored within the numbers, be it names or elements that are not convertible to numeric data. The changes have to be stored in order to make them reflect during further usage. "
},
{
"code": null,
"e": 28588,
"s": 28574,
"text": "as.numeric(x)"
},
{
"code": null,
"e": 28590,
"s": 28588,
"text": "R"
},
{
"code": "# declaring a vector vec <- c(1.2, 35.6, 35.2, 0.9, 46.7) # assigning names to the vectornames(vec)<-c(\"Ele1\", \"Ele2\", \"Ele3\", \"Ele4\", \"Ele5\")print(\"Original vector\")print(vec) # reassigning namesvec_mod <- as.numeric(vec)print(\"Modified vector\")print(vec_mod)",
"e": 28867,
"s": 28590,
"text": null
},
{
"code": null,
"e": 28875,
"s": 28867,
"text": "Output:"
},
{
"code": null,
"e": 28997,
"s": 28875,
"text": "[1] \"Original vector\"\nEle1 Ele2 Ele3 Ele4 Ele5\n1.2 35.6 35.2 0.9 46.7\n[1] \"Modified vector\"\n[1] 1.2 35.6 35.2 0.9 46.7"
},
{
"code": null,
"e": 29004,
"s": 28997,
"text": "Picked"
},
{
"code": null,
"e": 29022,
"s": 29004,
"text": "R Vector-Programs"
},
{
"code": null,
"e": 29032,
"s": 29022,
"text": "R-Vectors"
},
{
"code": null,
"e": 29043,
"s": 29032,
"text": "R Language"
},
{
"code": null,
"e": 29054,
"s": 29043,
"text": "R Programs"
},
{
"code": null,
"e": 29152,
"s": 29054,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29204,
"s": 29152,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 29239,
"s": 29204,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 29297,
"s": 29239,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 29335,
"s": 29297,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 29378,
"s": 29335,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 29436,
"s": 29378,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 29479,
"s": 29436,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 29528,
"s": 29479,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 29578,
"s": 29528,
"text": "How to filter R dataframe by multiple conditions?"
}
] |
How to format numbers by prepending 0 to single-digit numbers? - GeeksforGeeks | 18 Jul, 2019
A number can be formatted to prepend a 0 to single-digit numbers using 3 approaches:
Method 1: Using padStart() method:The padStart() method is used to pad a string with another string to a certain length. The padding is started from the left of the string. It takes two parameters, the target length, and the string to be replaced with.
The number to be formatted is first converted to a string by passing it to the String constructor. The padStart() method is used on this string with the length parameter given as 2 and the string to be replaced with, given the character ‘0’. This will format any single digit number to 2 digits by prepending a ‘0’ and leave 2 digit numbers as is.
Syntax:
prepended_number = String(number).padStart(2, '0')
Example:
<!DOCTYPE html><html> <head> <title> How to format numbers by prepending 0 to single-digit numbers? </title></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b>How to format numbers by prepending 0 to single-digit numbers? </b> <p>Output for prepending to '1': <span class="output"> </span> </p> <p>Output for prepending to '03': <span class="output-2"> </span> </p> <button onclick="padNumber()"> Format to 2 digits </button> <script type="text/javascript"> function padNumber() { single_digit = 1; two_digits = 03; prepended_out = String(single_digit).padStart(2, '0'); prepended_out2 = String(two_digits).padStart(2, '0'); document.querySelector( '.output').textContent = prepended_out; document.querySelector( '.output-2').textContent = prepended_out2; } </script></body> </html>
Output:
Before clicking the button:
After clicking the button:
Method 2: Checking if number is less than 9:In this method, the number is first checked if it is less than 9. If true, the character ‘0’ is appended to the number otherwise, the number is returned without any change. This will format any single digit number to 2 digits by prepending a ‘0’ and leave 2 digit numbers as is.
Syntax:
function prependZero(number) {
if (number < 9)
return "0" + number;
else
return number;
}
Example:
<!DOCTYPE html><html> <head> <title> How to format numbers by prepending 0 to single-digit numbers? </title></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b>How to format numbers by prepending 0 to single-digit numbers?</b> <p>Output for prepending to '1': <span class="output"> </span> </p> <p>Output for prepending to '03': <span class="output-2"> </span> </p> <button onclick="padNumber()"> Format to 2 digits </button> <script type="text/javascript"> function prependZero(number) { if (number < 9) return "0" + number; else return number; } function padNumber() { single_digit = 1; two_digits = 03; prepended_out = prependZero(single_digit); prepended_out2 = prependZero(two_digits); document.querySelector( '.output').textContent = prepended_out; document.querySelector( '.output-2').textContent = prepended_out2; } </script></body> </html>
Output:
Before clicking the button:
After clicking the button:
Method 3: Using the slice() method:The slice() method is used to extract parts of a string from the specified starting and ending indices. First, the number is prepended with a '0' character regardless of it being a single digit. This will make the single digit number into 2 digits but the 2-digit number would be converted to a 3-digit one with the extra '0'. The slice() method is used to extract the last 2 digits of the resulting number.
This will correctly get the last 2 digits of the 2-digit number discarding the extra '0' added to it. The single-digit number is now formatted with a '0'.
Syntax:prepended_number = ("0" + number).slice(-2)
Example:
<!DOCTYPE html><html> <head> <title> How to format numbers by prepending 0 to single-digit numbers? </title></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b>How to format numbers by prepending 0 to single-digit numbers? </b> <p> Output for prepending to '1': <span class="output"> </span> </p> <p> Output for prepending to '03': <span class="output-2"> </span></p> <button onclick="padNumber()"> Format to 2 digits </button> <script type="text/javascript"> function padNumber() { single_digit = 1; two_digits = 03; prepended_out = ( "0" + single_digit).slice(-2); prepended_out2 = ( "0" + two_digits).slice(-2); document.querySelector( '.output').textContent = prepended_out; document.querySelector( '.output-2').textContent = prepended_out2; } </script></body> </html>
Output:
Before clicking the button:
After clicking the button:
JavaScript-Misc
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript | [
{
"code": null,
"e": 26545,
"s": 26517,
"text": "\n18 Jul, 2019"
},
{
"code": null,
"e": 26630,
"s": 26545,
"text": "A number can be formatted to prepend a 0 to single-digit numbers using 3 approaches:"
},
{
"code": null,
"e": 26883,
"s": 26630,
"text": "Method 1: Using padStart() method:The padStart() method is used to pad a string with another string to a certain length. The padding is started from the left of the string. It takes two parameters, the target length, and the string to be replaced with."
},
{
"code": null,
"e": 27231,
"s": 26883,
"text": "The number to be formatted is first converted to a string by passing it to the String constructor. The padStart() method is used on this string with the length parameter given as 2 and the string to be replaced with, given the character ‘0’. This will format any single digit number to 2 digits by prepending a ‘0’ and leave 2 digit numbers as is."
},
{
"code": null,
"e": 27239,
"s": 27231,
"text": "Syntax:"
},
{
"code": null,
"e": 27290,
"s": 27239,
"text": "prepended_number = String(number).padStart(2, '0')"
},
{
"code": null,
"e": 27299,
"s": 27290,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> How to format numbers by prepending 0 to single-digit numbers? </title></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b>How to format numbers by prepending 0 to single-digit numbers? </b> <p>Output for prepending to '1': <span class=\"output\"> </span> </p> <p>Output for prepending to '03': <span class=\"output-2\"> </span> </p> <button onclick=\"padNumber()\"> Format to 2 digits </button> <script type=\"text/javascript\"> function padNumber() { single_digit = 1; two_digits = 03; prepended_out = String(single_digit).padStart(2, '0'); prepended_out2 = String(two_digits).padStart(2, '0'); document.querySelector( '.output').textContent = prepended_out; document.querySelector( '.output-2').textContent = prepended_out2; } </script></body> </html>",
"e": 28305,
"s": 27299,
"text": null
},
{
"code": null,
"e": 28313,
"s": 28305,
"text": "Output:"
},
{
"code": null,
"e": 28341,
"s": 28313,
"text": "Before clicking the button:"
},
{
"code": null,
"e": 28368,
"s": 28341,
"text": "After clicking the button:"
},
{
"code": null,
"e": 28691,
"s": 28368,
"text": "Method 2: Checking if number is less than 9:In this method, the number is first checked if it is less than 9. If true, the character ‘0’ is appended to the number otherwise, the number is returned without any change. This will format any single digit number to 2 digits by prepending a ‘0’ and leave 2 digit numbers as is."
},
{
"code": null,
"e": 28699,
"s": 28691,
"text": "Syntax:"
},
{
"code": null,
"e": 28862,
"s": 28699,
"text": " function prependZero(number) {\n if (number < 9)\n return \"0\" + number;\n else\n return number;\n }\n"
},
{
"code": null,
"e": 28871,
"s": 28862,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> How to format numbers by prepending 0 to single-digit numbers? </title></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b>How to format numbers by prepending 0 to single-digit numbers?</b> <p>Output for prepending to '1': <span class=\"output\"> </span> </p> <p>Output for prepending to '03': <span class=\"output-2\"> </span> </p> <button onclick=\"padNumber()\"> Format to 2 digits </button> <script type=\"text/javascript\"> function prependZero(number) { if (number < 9) return \"0\" + number; else return number; } function padNumber() { single_digit = 1; two_digits = 03; prepended_out = prependZero(single_digit); prepended_out2 = prependZero(two_digits); document.querySelector( '.output').textContent = prepended_out; document.querySelector( '.output-2').textContent = prepended_out2; } </script></body> </html>",
"e": 29980,
"s": 28871,
"text": null
},
{
"code": null,
"e": 29988,
"s": 29980,
"text": "Output:"
},
{
"code": null,
"e": 30016,
"s": 29988,
"text": "Before clicking the button:"
},
{
"code": null,
"e": 30043,
"s": 30016,
"text": "After clicking the button:"
},
{
"code": null,
"e": 30486,
"s": 30043,
"text": "Method 3: Using the slice() method:The slice() method is used to extract parts of a string from the specified starting and ending indices. First, the number is prepended with a '0' character regardless of it being a single digit. This will make the single digit number into 2 digits but the 2-digit number would be converted to a 3-digit one with the extra '0'. The slice() method is used to extract the last 2 digits of the resulting number."
},
{
"code": null,
"e": 30641,
"s": 30486,
"text": "This will correctly get the last 2 digits of the 2-digit number discarding the extra '0' added to it. The single-digit number is now formatted with a '0'."
},
{
"code": null,
"e": 30692,
"s": 30641,
"text": "Syntax:prepended_number = (\"0\" + number).slice(-2)"
},
{
"code": null,
"e": 30701,
"s": 30692,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> How to format numbers by prepending 0 to single-digit numbers? </title></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b>How to format numbers by prepending 0 to single-digit numbers? </b> <p> Output for prepending to '1': <span class=\"output\"> </span> </p> <p> Output for prepending to '03': <span class=\"output-2\"> </span></p> <button onclick=\"padNumber()\"> Format to 2 digits </button> <script type=\"text/javascript\"> function padNumber() { single_digit = 1; two_digits = 03; prepended_out = ( \"0\" + single_digit).slice(-2); prepended_out2 = ( \"0\" + two_digits).slice(-2); document.querySelector( '.output').textContent = prepended_out; document.querySelector( '.output-2').textContent = prepended_out2; } </script></body> </html>",
"e": 31703,
"s": 30701,
"text": null
},
{
"code": null,
"e": 31711,
"s": 31703,
"text": "Output:"
},
{
"code": null,
"e": 31739,
"s": 31711,
"text": "Before clicking the button:"
},
{
"code": null,
"e": 31766,
"s": 31739,
"text": "After clicking the button:"
},
{
"code": null,
"e": 31782,
"s": 31766,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 31789,
"s": 31782,
"text": "Picked"
},
{
"code": null,
"e": 31800,
"s": 31789,
"text": "JavaScript"
},
{
"code": null,
"e": 31817,
"s": 31800,
"text": "Web Technologies"
},
{
"code": null,
"e": 31915,
"s": 31817,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31955,
"s": 31915,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 32016,
"s": 31955,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 32057,
"s": 32016,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 32079,
"s": 32057,
"text": "JavaScript | Promises"
},
{
"code": null,
"e": 32133,
"s": 32079,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 32173,
"s": 32133,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 32206,
"s": 32173,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 32249,
"s": 32206,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 32299,
"s": 32249,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Difference between function expression vs declaration in JavaScript - GeeksforGeeks | 23 May, 2019
Function Declaration:A Function Declaration( or a Function Statement) defines a function with the specified parameters without requiring a variable assignment. They exist on their own, i.e, they are standalone constructs and cannot be nested within a non-function block. A function is declared using the function keyword.
Syntax:function gfg(parameter1, parameter2) {
//A set of statements
}
function gfg(parameter1, parameter2) {
//A set of statements
}
Function Expression:A Function Expression works just like a function declaration or a function statement, the only difference is that a function name is NOT started in a function expression, that is, anonymous functions are created in function expressions. The function expressions run as soon as they are defined.
Syntax:var gfg = function(parameter1, parameter2) {
//A set of statements
}
var gfg = function(parameter1, parameter2) {
//A set of statements
}
Example 1: Using a Function Declaration
<!DOCTYPE html><html> <head> <title>Function Declaration</title></head> <body> <center> <h1 style="color:green">GeeksforGeeks</h1> <h3>Function Declaration</h3> <script> function gfg(a, b) { return a * b; } var result = gfg(5, 5); document.write(result); </script> </center></body> </html>
Output:
25
Example 2: Using a Function Expression
<!DOCTYPE html><html> <head> <title>Function Expression</title></head> <body> <center> <h1 style="color:green">GeeksforGeeks</h1> <h3>Function Expression</h3> <script> var gfg = function(a, b) { return a * b; } document.write(gfg(5, 5)); </script> </center></body> </html>
Output:
25
Picked
Difference Between
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Difference between Process and Thread
Stack vs Heap Memory Allocation
Difference Between Method Overloading and Method Overriding in Java
Differences between JDK, JRE and JVM
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
How to calculate the number of days between two dates in javascript?
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ? | [
{
"code": null,
"e": 24418,
"s": 24390,
"text": "\n23 May, 2019"
},
{
"code": null,
"e": 24740,
"s": 24418,
"text": "Function Declaration:A Function Declaration( or a Function Statement) defines a function with the specified parameters without requiring a variable assignment. They exist on their own, i.e, they are standalone constructs and cannot be nested within a non-function block. A function is declared using the function keyword."
},
{
"code": null,
"e": 24813,
"s": 24740,
"text": "Syntax:function gfg(parameter1, parameter2) {\n //A set of statements\n }\n"
},
{
"code": null,
"e": 24879,
"s": 24813,
"text": "function gfg(parameter1, parameter2) {\n //A set of statements\n }\n"
},
{
"code": null,
"e": 25194,
"s": 24879,
"text": "Function Expression:A Function Expression works just like a function declaration or a function statement, the only difference is that a function name is NOT started in a function expression, that is, anonymous functions are created in function expressions. The function expressions run as soon as they are defined."
},
{
"code": null,
"e": 25273,
"s": 25194,
"text": "Syntax:var gfg = function(parameter1, parameter2) {\n //A set of statements\n }\n"
},
{
"code": null,
"e": 25345,
"s": 25273,
"text": "var gfg = function(parameter1, parameter2) {\n //A set of statements\n }\n"
},
{
"code": null,
"e": 25385,
"s": 25345,
"text": "Example 1: Using a Function Declaration"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Function Declaration</title></head> <body> <center> <h1 style=\"color:green\">GeeksforGeeks</h1> <h3>Function Declaration</h3> <script> function gfg(a, b) { return a * b; } var result = gfg(5, 5); document.write(result); </script> </center></body> </html>",
"e": 25774,
"s": 25385,
"text": null
},
{
"code": null,
"e": 25782,
"s": 25774,
"text": "Output:"
},
{
"code": null,
"e": 25786,
"s": 25782,
"text": "25\n"
},
{
"code": null,
"e": 25825,
"s": 25786,
"text": "Example 2: Using a Function Expression"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Function Expression</title></head> <body> <center> <h1 style=\"color:green\">GeeksforGeeks</h1> <h3>Function Expression</h3> <script> var gfg = function(a, b) { return a * b; } document.write(gfg(5, 5)); </script> </center></body> </html>",
"e": 26186,
"s": 25825,
"text": null
},
{
"code": null,
"e": 26194,
"s": 26186,
"text": "Output:"
},
{
"code": null,
"e": 26198,
"s": 26194,
"text": "25\n"
},
{
"code": null,
"e": 26205,
"s": 26198,
"text": "Picked"
},
{
"code": null,
"e": 26224,
"s": 26205,
"text": "Difference Between"
},
{
"code": null,
"e": 26235,
"s": 26224,
"text": "JavaScript"
},
{
"code": null,
"e": 26252,
"s": 26235,
"text": "Web Technologies"
},
{
"code": null,
"e": 26350,
"s": 26252,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26411,
"s": 26350,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 26449,
"s": 26411,
"text": "Difference between Process and Thread"
},
{
"code": null,
"e": 26481,
"s": 26449,
"text": "Stack vs Heap Memory Allocation"
},
{
"code": null,
"e": 26549,
"s": 26481,
"text": "Difference Between Method Overloading and Method Overriding in Java"
},
{
"code": null,
"e": 26586,
"s": 26549,
"text": "Differences between JDK, JRE and JVM"
},
{
"code": null,
"e": 26631,
"s": 26586,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 26692,
"s": 26631,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 26761,
"s": 26692,
"text": "How to calculate the number of days between two dates in javascript?"
},
{
"code": null,
"e": 26833,
"s": 26761,
"text": "Differences between Functional Components and Class Components in React"
}
] |
CheckBox in Kotlin - GeeksforGeeks | 19 Feb, 2021
A CheckBox is a special kind of button in Android which has two states either checked or unchecked. The Checkbox is a very common widget to be used in Android and a very good example is the “Remember me” option in any kind of Login activity of an app which asks the user to activate or deactivate that service. There are many other uses of the CheckBox widget like offering a list of options to the user to choose from and the options are mutually exclusive i.e., the user can select more than one option. This feature of the CheckBox makes it a better option to be used in designing multiple-choice questions application or survey application in android.
This example demonstrates the steps involved in designing an activity that consists of 5 CheckBox and an additional submit button to display a toast message that user response has been recorded.
Note: Following steps are performed on Android Studio version 4.0
Click on File, then New => New Project.Choose “Empty Activity” for the project template.Select language as Kotlin.Select the minimum SDK as per your need.
Click on File, then New => New Project.
Choose “Empty Activity” for the project template.
Select language as Kotlin.
Select the minimum SDK as per your need.
Below is the code for activity_main.xml file to add 5 CheckBox. A normal “submit” button is also added to display a toast message that user response has been recorded.
<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#168BC34A" tools:context=".MainActivity" > <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:fontFamily="@font/roboto" android:text="@string/Heading" android:textAlignment="center" android:textColor="@android:color/holo_green_dark" android:textSize="36sp" android:textStyle="bold" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.17000002" /> <LinearLayout android:id="@+id/checkBox_container" android:layout_width="0dp" android:layout_height="wrap_content" android:orientation="vertical" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/textView" app:layout_constraintVertical_bias="0.18"> <CheckBox android:id="@+id/checkBox" android:layout_width="match_parent" android:layout_height="wrap_content" android:fontFamily="@font/roboto" android:text="@string/checkBox1_text" android:textSize="18sp" android:padding="7dp"/> <CheckBox android:id="@+id/checkBox2" android:layout_width="match_parent" android:layout_height="wrap_content" android:fontFamily="@font/roboto" android:text="@string/checkBox2_text" android:textSize="18sp" android:padding="7dp"/> <CheckBox android:id="@+id/checkBox3" android:layout_width="match_parent" android:layout_height="wrap_content" android:fontFamily="@font/roboto" android:text="@string/checkBox3_text" android:textSize="18sp" android:padding="7dp"/> <CheckBox android:id="@+id/checkBox4" android:layout_width="match_parent" android:layout_height="wrap_content" android:fontFamily="@font/roboto" android:text="@string/checkBox4_text" android:textSize="18sp" android:padding="7dp"/> <CheckBox android:id="@+id/checkBox5" android:layout_width="match_parent" android:layout_height="wrap_content" android:fontFamily="@font/roboto" android:text="@string/checkBox5_text" android:textSize="18sp" android:padding="7dp"/> </LinearLayout> <Button android:id="@+id/submitButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="#AB4CAF50" android:fontFamily="@font/roboto" android:text="@string/submitButton" android:textSize="18sp" android:textStyle="bold" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/checkBox_container" app:layout_constraintVertical_bias="0.23000002" /></androidx.constraintlayout.widget.ConstraintLayout>
Below is the code for MainActivity.kt file to access CheckBox widget in kotlin file and show a proper message whenever the submit button is clicked by the user.
package com.example.checkboxinkotlin import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.widget.Buttonimport android.widget.Toast class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Assigning id of the submit button val button : Button = findViewById(R.id.submitButton) // Actions to be performed // when Submit button is clicked button.setOnClickListener{ // Display toast message Toast.makeText(applicationContext, "Your response has been recorded", Toast.LENGTH_LONG).show() } }}
All the strings which are used in the activity, from the text view to the Checkbox texts are listed in this file.
<resources> <string name="app_name">CheckBox in Kotlin</string> <string name="Heading">Services provided by GeeksforGeeks</string> <string name="checkBox1">Coding contests</string> <string name="checkBox2_text">Civil Engineering Courses</string> <string name="checkBox1_text">Coding Contests</string> <string name="checkBox3_text">Computer Science Courses</string> <string name="checkBox4_text">Company specific coding questions</string> <string name="checkBox5_text">Download movies</string> <string name="submitButton">SUBMIT</string></resources>
Below is the code for AndroidManifest.xml file.
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http:// schemas.android.com/apk/res/android" package="com.example.checkboxinkotlin"> <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>
Android-Button
Kotlin Android
Picked
Android
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Create and Add Data to SQLite Database in Android?
Broadcast Receiver in Android With Example
Content Providers in Android with Example
Android RecyclerView in Kotlin
Flutter - Custom Bottom Navigation Bar
Broadcast Receiver in Android With Example
Content Providers in Android with Example
Android UI Layouts
Android RecyclerView in Kotlin
Retrofit with Kotlin Coroutine in Android | [
{
"code": null,
"e": 24232,
"s": 24204,
"text": "\n19 Feb, 2021"
},
{
"code": null,
"e": 24888,
"s": 24232,
"text": "A CheckBox is a special kind of button in Android which has two states either checked or unchecked. The Checkbox is a very common widget to be used in Android and a very good example is the “Remember me” option in any kind of Login activity of an app which asks the user to activate or deactivate that service. There are many other uses of the CheckBox widget like offering a list of options to the user to choose from and the options are mutually exclusive i.e., the user can select more than one option. This feature of the CheckBox makes it a better option to be used in designing multiple-choice questions application or survey application in android."
},
{
"code": null,
"e": 25083,
"s": 24888,
"text": "This example demonstrates the steps involved in designing an activity that consists of 5 CheckBox and an additional submit button to display a toast message that user response has been recorded."
},
{
"code": null,
"e": 25149,
"s": 25083,
"text": "Note: Following steps are performed on Android Studio version 4.0"
},
{
"code": null,
"e": 25304,
"s": 25149,
"text": "Click on File, then New => New Project.Choose “Empty Activity” for the project template.Select language as Kotlin.Select the minimum SDK as per your need."
},
{
"code": null,
"e": 25344,
"s": 25304,
"text": "Click on File, then New => New Project."
},
{
"code": null,
"e": 25394,
"s": 25344,
"text": "Choose “Empty Activity” for the project template."
},
{
"code": null,
"e": 25421,
"s": 25394,
"text": "Select language as Kotlin."
},
{
"code": null,
"e": 25462,
"s": 25421,
"text": "Select the minimum SDK as per your need."
},
{
"code": null,
"e": 25630,
"s": 25462,
"text": "Below is the code for activity_main.xml file to add 5 CheckBox. A normal “submit” button is also added to display a toast message that user response has been recorded."
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:background=\"#168BC34A\" tools:context=\".MainActivity\" > <TextView android:id=\"@+id/textView\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:fontFamily=\"@font/roboto\" android:text=\"@string/Heading\" android:textAlignment=\"center\" android:textColor=\"@android:color/holo_green_dark\" android:textSize=\"36sp\" android:textStyle=\"bold\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" app:layout_constraintVertical_bias=\"0.17000002\" /> <LinearLayout android:id=\"@+id/checkBox_container\" android:layout_width=\"0dp\" android:layout_height=\"wrap_content\" android:orientation=\"vertical\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toBottomOf=\"@+id/textView\" app:layout_constraintVertical_bias=\"0.18\"> <CheckBox android:id=\"@+id/checkBox\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:fontFamily=\"@font/roboto\" android:text=\"@string/checkBox1_text\" android:textSize=\"18sp\" android:padding=\"7dp\"/> <CheckBox android:id=\"@+id/checkBox2\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:fontFamily=\"@font/roboto\" android:text=\"@string/checkBox2_text\" android:textSize=\"18sp\" android:padding=\"7dp\"/> <CheckBox android:id=\"@+id/checkBox3\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:fontFamily=\"@font/roboto\" android:text=\"@string/checkBox3_text\" android:textSize=\"18sp\" android:padding=\"7dp\"/> <CheckBox android:id=\"@+id/checkBox4\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:fontFamily=\"@font/roboto\" android:text=\"@string/checkBox4_text\" android:textSize=\"18sp\" android:padding=\"7dp\"/> <CheckBox android:id=\"@+id/checkBox5\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:fontFamily=\"@font/roboto\" android:text=\"@string/checkBox5_text\" android:textSize=\"18sp\" android:padding=\"7dp\"/> </LinearLayout> <Button android:id=\"@+id/submitButton\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:background=\"#AB4CAF50\" android:fontFamily=\"@font/roboto\" android:text=\"@string/submitButton\" android:textSize=\"18sp\" android:textStyle=\"bold\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toBottomOf=\"@+id/checkBox_container\" app:layout_constraintVertical_bias=\"0.23000002\" /></androidx.constraintlayout.widget.ConstraintLayout>",
"e": 29379,
"s": 25630,
"text": null
},
{
"code": null,
"e": 29540,
"s": 29379,
"text": "Below is the code for MainActivity.kt file to access CheckBox widget in kotlin file and show a proper message whenever the submit button is clicked by the user."
},
{
"code": "package com.example.checkboxinkotlin import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.widget.Buttonimport android.widget.Toast class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Assigning id of the submit button val button : Button = findViewById(R.id.submitButton) // Actions to be performed // when Submit button is clicked button.setOnClickListener{ // Display toast message Toast.makeText(applicationContext, \"Your response has been recorded\", Toast.LENGTH_LONG).show() } }}",
"e": 30285,
"s": 29540,
"text": null
},
{
"code": null,
"e": 30399,
"s": 30285,
"text": "All the strings which are used in the activity, from the text view to the Checkbox texts are listed in this file."
},
{
"code": "<resources> <string name=\"app_name\">CheckBox in Kotlin</string> <string name=\"Heading\">Services provided by GeeksforGeeks</string> <string name=\"checkBox1\">Coding contests</string> <string name=\"checkBox2_text\">Civil Engineering Courses</string> <string name=\"checkBox1_text\">Coding Contests</string> <string name=\"checkBox3_text\">Computer Science Courses</string> <string name=\"checkBox4_text\">Company specific coding questions</string> <string name=\"checkBox5_text\">Download movies</string> <string name=\"submitButton\">SUBMIT</string></resources>",
"e": 30975,
"s": 30399,
"text": null
},
{
"code": null,
"e": 31023,
"s": 30975,
"text": "Below is the code for AndroidManifest.xml file."
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><manifest xmlns:android=\"http:// schemas.android.com/apk/res/android\" package=\"com.example.checkboxinkotlin\"> <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>",
"e": 31733,
"s": 31023,
"text": null
},
{
"code": null,
"e": 31748,
"s": 31733,
"text": "Android-Button"
},
{
"code": null,
"e": 31763,
"s": 31748,
"text": "Kotlin Android"
},
{
"code": null,
"e": 31770,
"s": 31763,
"text": "Picked"
},
{
"code": null,
"e": 31778,
"s": 31770,
"text": "Android"
},
{
"code": null,
"e": 31785,
"s": 31778,
"text": "Kotlin"
},
{
"code": null,
"e": 31793,
"s": 31785,
"text": "Android"
},
{
"code": null,
"e": 31891,
"s": 31793,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31949,
"s": 31891,
"text": "How to Create and Add Data to SQLite Database in Android?"
},
{
"code": null,
"e": 31992,
"s": 31949,
"text": "Broadcast Receiver in Android With Example"
},
{
"code": null,
"e": 32034,
"s": 31992,
"text": "Content Providers in Android with Example"
},
{
"code": null,
"e": 32065,
"s": 32034,
"text": "Android RecyclerView in Kotlin"
},
{
"code": null,
"e": 32104,
"s": 32065,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 32147,
"s": 32104,
"text": "Broadcast Receiver in Android With Example"
},
{
"code": null,
"e": 32189,
"s": 32147,
"text": "Content Providers in Android with Example"
},
{
"code": null,
"e": 32208,
"s": 32189,
"text": "Android UI Layouts"
},
{
"code": null,
"e": 32239,
"s": 32208,
"text": "Android RecyclerView in Kotlin"
}
] |
gRPC - Bidirectional RPC | Let us see now see how the client-server streaming works while using gRPCcommunication. In this case, the client will search and add books to the cart. The server would respond with live cart value every time a book is added.
First let us define the bookstore.proto file in common_proto_files −
syntax = "proto3";
option java_package = "com.tp.bookstore";
service BookStore {
rpc liveCartValue (stream Book) returns (stream Cart) {}
}
message Book {
string name = 1;
string author = 2;
int32 price = 3;
}
message Cart {
int32 books = 1;
int32 price = 2;
}
The following block represents the name of the service "BookStore" and the function name "liveCartValue" which can be called. The "liveCartValue" function takes in the input of type "Book" which is a stream. And the function returns a stream of object of type "Cart". So, effectively, we let the client add books in a streaming fashion and whenever a new book is added, the server responds the current cart value to the client.
service BookStore {
rpc liveCartValue (stream Book) returns (stream Cart) {}
}
Now let us look at these types.
message Book {
string name = 1;
string author = 2;
int32 price = 3;
}
The client would send in the "Book" it wants to buy. It does not have to be thecomplete book info; it can simply be title of the book.
message Cart {
int32 books = 1;
int32 price = 2;
}
The server, on getting the list of books, would return the "Cart" object which is nothing but the total number of books the client has purchased and the totalprice.
Note that we already had the Maven setup done for auto-generating our class files as well as our RPC code. So, now we can simply compile our project:
mvn clean install
This should auto-generate the source code required for us to use gRPC. The source code would be placed under
Protobuf class code: target/generatedsources/protobuf/java/com.tp.bookstore
Protobuf gRPC code: target/generated-sources/protobuf/grpcjava/com.tp.bookstore
Now that we have defined the proto file which contains the function definition,let us setup a server which can call these functions.
Let us write our server code to serve the above function and save it in com.tp.bookstore.BookeStoreServerBothStreaming.java −
package com.tp.bookstore;
import io.grpc.Server;
import io.grpc.ServerBuilder;
import io.grpc.stub.StreamObserver;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import com.tp.bookstore.BookStoreOuterClass.Book;
import com.tp.bookstore.BookStoreOuterClass.BookSearch;
import com.tp.bookstore.BookStoreOuterClass.Cart;
public class BookeStoreServerBothStreaming {
private static final Logger logger =Logger.getLogger(BookeStoreServerBothStreaming.class.getName());
static Map<String, Book> bookMap = new HashMap<>();
static {
bookMap.put("Great Gatsby", Book.newBuilder().setName("Great Gatsby")
.setAuthor("Scott Fitzgerald")
.setPrice(300).build());
bookMap.put("To Kill MockingBird", Book.newBuilder().setName("To Kill MockingBird")
.setAuthor("Harper Lee")
.setPrice(400).build());
bookMap.put("Passage to India", Book.newBuilder().setName("Passage to India")
.setAuthor("E.M.Forster")
.setPrice(500).build());
bookMap.put("The Side of Paradise", Book.newBuilder().setName("The Side of Paradise")
.setAuthor("Scott Fitzgerald")
.setPrice(600).build());
bookMap.put("Go Set a Watchman",Book.newBuilder().setName("Go Set a Watchman")
.setAuthor("Harper Lee")
.setPrice(700).build());
}
private Server server;
private void start() throws IOException {
int port = 50051;
server = ServerBuilder.forPort(port)
.addService(new BookStoreImpl()).build().start();
logger.info("Server started, listening on " + port);
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
System.err.println("Shutting down gRPC server");
try {
server.shutdown().awaitTermination(30, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace(System.err);
}
}
});
}
public static void main(String[] args) throws IOException,InterruptedException {
final BookeStoreServerBothStreaming greetServer = newBookeStoreServerBothStreaming();
greetServer.start();
greetServer.server.awaitTermination();
}
static class BookStoreImpl extendsBookStoreGrpc.BookStoreImplBase {
@Override
public StreamObserver<Book>liveCartValue(StreamObserver<Cart> responseObserver) {
return new StreamObserver<Book>() {
ArrayList<Book> bookCart = new ArrayList<Book>();
int cartValue = 0;
@Override
public void onNext(Book book) {
logger.info("Searching for book with titlestarting with: " + book.getName());
for (Entry<String, Book> bookEntry :bookMap.entrySet()) {
if(bookEntry.getValue().getName().startsWith(book.getName())){
logger.info("Found book, adding tocart:....");
bookCart.add(bookEntry.getValue());
cartValue +=bookEntry.getValue().getPrice();
}
}
logger.info("Updating cart value...");
responseObserver.onNext(Cart.newBuilder()
.setPrice(cartValue)
.setBooks(bookCart.size()).build());
}
@Override
public void onError(Throwable t) {
logger.info("Error while reading book stream: " + t);
}
@Override
public void onCompleted() {
logger.info("Order completed");
responseObserver.onCompleted();
}
};
}
}
}
The above code starts a gRPC server at a specified port and serves the functions and services which we had written in our proto file. Let us walk through the above code −
Starting from the main method, we create a gRPC server at a specifiedport.
Starting from the main method, we create a gRPC server at a specifiedport.
But before starting the server, we assign the server the service which we want to run, i.e., in our case, the BookStore service.
But before starting the server, we assign the server the service which we want to run, i.e., in our case, the BookStore service.
For this purpose, we need to pass in the service instance to the server, so we go ahead and create service instance i.e. in our case theBookStoreImpl
For this purpose, we need to pass in the service instance to the server, so we go ahead and create service instance i.e. in our case theBookStoreImpl
The service instance need to provide an implementation of the method/function which is present in the proto file, i.e., in our case, the totalCartValue method.
The service instance need to provide an implementation of the method/function which is present in the proto file, i.e., in our case, the totalCartValue method.
Now, given that this is the case of server and client streaming, the server will get the list of Books (defined in the proto file) as the client adds them. The server thus returns a custom stream observer. This stream observer implements what happens when a new Book is found and what happens when the stream is closed.
Now, given that this is the case of server and client streaming, the server will get the list of Books (defined in the proto file) as the client adds them. The server thus returns a custom stream observer. This stream observer implements what happens when a new Book is found and what happens when the stream is closed.
The onNext() method would be called by the gRPC framework when the client adds a Book. At this point, the server adds that to the cart and uses the response observer to return the Cart Value. In case of streaming, the server does not wait for all the valid books to be available.
The onNext() method would be called by the gRPC framework when the client adds a Book. At this point, the server adds that to the cart and uses the response observer to return the Cart Value. In case of streaming, the server does not wait for all the valid books to be available.
When the client is done with the addition of Books, the stream observer's onCompleted() method is called. This method implements what the server wants to do when the client is done adding the Books, i.e., claim it is done with taking the client order.
When the client is done with the addition of Books, the stream observer's onCompleted() method is called. This method implements what the server wants to do when the client is done adding the Books, i.e., claim it is done with taking the client order.
Finally, we also have a shutdown hook to ensure clean shutting down of the server when we are done executing our code.
Finally, we also have a shutdown hook to ensure clean shutting down of the server when we are done executing our code.
Now that we have written the code for the server, let us setup a client which can call these functions.
Let us write our client code to call the above function and save it in com.tp.bookstore.BookStoreClientBothStreaming.java −
package com.tp.bookstore;
import io.grpc.Channel;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.StatusRuntimeException;
import io.grpc.stub.StreamObserver;
import java.util.Iterator;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.tp.bookstore.BookStoreGrpc.BookStoreFutureStub;
import com.tp.bookstore.BookStoreGrpc.BookStoreStub;
import com.tp.bookstore.BookStoreOuterClass.Book;
import com.tp.bookstore.BookStoreOuterClass.BookSearch;
import com.tp.bookstore.BookStoreOuterClass.Cart;
import com.tp.greeting.GreeterGrpc;
import com.tp.greeting.Greeting.ServerOutput;
import com.tp.greeting.Greeting.ClientInput;
public class BookStoreClientBothStreaming {
private static final Logger logger = Logger.getLogger(BookStoreClientBothStreaming.class.getName());
private final BookStoreStub stub;
private boolean serverIntermediateResponseCompleted = true;
private boolean serverResponseCompleted = false;
StreamObserver<Book> streamClientSender;
public BookStoreClientBothStreaming(Channel channel) {
stub = BookStoreGrpc.newStub(channel);
}
public StreamObserver>Cart< getServerResponseObserver(){
StreamObserver>Cart< observer = new StreamObserver<Cart>(){
@Override
public void onNext(Cart cart) {
logger.info("Order summary:" +
"\nTotal number of Books:" + cart.getBooks()+
"\nTotal Order Value:" cart.getPrice());
serverIntermediateResponseCompleted = true;
}
@Override
public void onError(Throwable t) {
logger.info("Error while reading response fromServer: " + t);
}
@Override
public void onCompleted() {
//logger.info("Server: Done reading orderreading cart");
serverResponseCompleted = true;
}
};
return observer;
}
public void addBook(String book) {
logger.info("Adding book with title starting with: " + book);
Book request = Book.newBuilder().setName(book).build();
if(streamClientSender == null) {
streamClientSender =stub.liveCartValue(getServerResponseObserver());
}
try {
streamClientSender.onNext(request);
}
catch (StatusRuntimeException e) {
logger.log(Level.WARNING, "RPC failed: {0}", e.getStatus());
}
}
public void completeOrder() {
logger.info("Done, waiting for server to create ordersummary...");
if(streamClientSender != null); {
streamClientSender.onCompleted();
}
}
public static void main(String[] args) throws Exception {
String serverAddress = "localhost:50051";
ManagedChannel channel = ManagedChannelBuilder.forTarget(serverAddress)
.usePlaintext()
.build();
try {
BookStoreClientBothStreaming client = new
BookStoreClientBothStreaming(channel);
String bookName = "";
while(true) {
if(client.serverIntermediateResponseCompleted ==true) {
System.out.println("Type book name to beadded to the cart....");
bookName = System.console().readLine();
if(bookName.equals("EXIT")) {
client.completeOrder();
break;
}
client.serverIntermediateResponseCompleted = false;
client.addBook(bookName);
Thread.sleep(500);
}
}
while(client.serverResponseCompleted == false) {
Thread.sleep(2000);
}
} finally {
channel.shutdownNow().awaitTermination(5, TimeUnit.SECONDS);
}
}
}
The above code starts a gRPC client and connects to a server at a specified port and call the functions and services which we had written in our proto file. Let us walk through the above code −
Starting from the main method, we accept the name of the books to be added to the cart. Once all the books are to be added, the user is expected to print "EXIT".
Starting from the main method, we accept the name of the books to be added to the cart. Once all the books are to be added, the user is expected to print "EXIT".
We setup a Channel for gRPC communication with our server.
We setup a Channel for gRPC communication with our server.
Next, we create a non-blocking stub using the channel. This is where we are choosing the service "BookStore" whose functions we plan to call.
Next, we create a non-blocking stub using the channel. This is where we are choosing the service "BookStore" whose functions we plan to call.
Then, we simply create the expected input defined in the proto file, i.e., in our case, Book, and we add the title we want the server to add.
Then, we simply create the expected input defined in the proto file, i.e., in our case, Book, and we add the title we want the server to add.
But given that this is the case of both server and client streaming, we first create a stream observer for the server. This server stream observer lists the behavior on what needs to be done when the server responds, i.e., onNext() and onCompleted().
But given that this is the case of both server and client streaming, we first create a stream observer for the server. This server stream observer lists the behavior on what needs to be done when the server responds, i.e., onNext() and onCompleted().
And using the stub, we also get the client stream observer. We use this stream observer for sending the data, i.e., the Book to be added to the cart.
And using the stub, we also get the client stream observer. We use this stream observer for sending the data, i.e., the Book to be added to the cart.
And once our order is complete, we ensure that the client stream observer is closed. This tells the server to close the stream and perform the cleanup.
And once our order is complete, we ensure that the client stream observer is closed. This tells the server to close the stream and perform the cleanup.
Finally, we close the channel to avoid any resource leak.
Finally, we close the channel to avoid any resource leak.
So, that is our client code.
To sum up, what we want to do is the following −
Start the gRPC server.
Start the gRPC server.
The Client adds a stream of books by notifying them to the server.
The Client adds a stream of books by notifying them to the server.
The Server searches the book in its store and adds them to the cart.
The Server searches the book in its store and adds them to the cart.
With each book addition, the server tells the client about the cart value.
With each book addition, the server tells the client about the cart value.
When the client is done ordering, both the server and the client close the stream.
When the client is done ordering, both the server and the client close the stream.
Now that we have defined our proto file, written our server and the client code, let us now execute this code and see things in action.
For running the code, fire up two shells. Start the server on the first shell by executing the following command −
java -cp .\target\grpc-point-1.0.jar
com.tp.bookstore.BookeStoreServerClientStreaming
We would see the following output −
Jul 03, 2021 10:37:21 PM
com.tp.bookstore.BookeStoreServerStreaming start
INFO: Server started, listening on 50051
This output implies that the server has started.
Now, let us start the client.
java -cp .\target\grpc-point-1.0.jar
com.tp.bookstore.BookStoreClientBothStreaming
Let us add a book to our client.
Jul 24, 2021 7:21:45 PM
com.tp.bookstore.BookStoreClientBothStreaming main
Type book name to be added to the cart....
Great
Jul 24, 2021 7:21:48 PM
com.tp.bookstore.BookStoreClientBothStreaming addBook
INFO: Adding book with title starting with: Gr
Jul 24, 2021 7:21:48 PM
com.tp.bookstore.BookStoreClientBothStreaming$1 onNext
INFO: Order summary:
Total number of Books: 1
Total Order Value: 300
So, as we can see, we get the current cart value of the order. Let us now add one more book to our client.
Type book name to be added to the cart....
Passage
Jul 24, 2021 7:21:51 PM
com.tp.bookstore.BookStoreClientBothStreaming addBook
INFO: Adding book with title starting with: Pa
Jul 24, 2021 7:21:51 PM
com.tp.bookstore.BookStoreClientBothStreaming$1 onNext
INFO: Order summary:
Total number of Books: 2
Total Order Value: 800
Once we have added the books and we input "EXIT", the client shuts down.
Type book name to be added to the cart....
EXIT
Jul 24, 2021 7:21:59 PM
com.tp.bookstore.BookStoreClientBothStreaming completeOrder
INFO: Done, waiting for server to create order summary...
So, as we can see the client was able to add books. And as the books are being added, the server responds with the current cart value.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2063,
"s": 1837,
"text": "Let us see now see how the client-server streaming works while using gRPCcommunication. In this case, the client will search and add books to the cart. The server would respond with live cart value every time a book is added."
},
{
"code": null,
"e": 2132,
"s": 2063,
"text": "First let us define the bookstore.proto file in common_proto_files −"
},
{
"code": null,
"e": 2412,
"s": 2132,
"text": "syntax = \"proto3\";\noption java_package = \"com.tp.bookstore\";\nservice BookStore {\n rpc liveCartValue (stream Book) returns (stream Cart) {}\n}\nmessage Book {\n string name = 1;\n string author = 2;\n int32 price = 3;\n}\nmessage Cart {\n int32 books = 1;\n int32 price = 2;\n}\n"
},
{
"code": null,
"e": 2840,
"s": 2412,
"text": "The following block represents the name of the service \"BookStore\" and the function name \"liveCartValue\" which can be called. The \"liveCartValue\" function takes in the input of type \"Book\" which is a stream. And the function returns a stream of object of type \"Cart\". So, effectively, we let the client add books in a streaming fashion and whenever a new book is added, the server responds the current cart value to the client."
},
{
"code": null,
"e": 2923,
"s": 2840,
"text": "service BookStore {\n rpc liveCartValue (stream Book) returns (stream Cart) {}\n}\n"
},
{
"code": null,
"e": 2955,
"s": 2923,
"text": "Now let us look at these types."
},
{
"code": null,
"e": 3035,
"s": 2955,
"text": "message Book {\n string name = 1;\n string author = 2;\n int32 price = 3;\n}\n"
},
{
"code": null,
"e": 3170,
"s": 3035,
"text": "The client would send in the \"Book\" it wants to buy. It does not have to be thecomplete book info; it can simply be title of the book."
},
{
"code": null,
"e": 3228,
"s": 3170,
"text": "message Cart {\n int32 books = 1;\n int32 price = 2;\n}\n"
},
{
"code": null,
"e": 3393,
"s": 3228,
"text": "The server, on getting the list of books, would return the \"Cart\" object which is nothing but the total number of books the client has purchased and the totalprice."
},
{
"code": null,
"e": 3543,
"s": 3393,
"text": "Note that we already had the Maven setup done for auto-generating our class files as well as our RPC code. So, now we can simply compile our project:"
},
{
"code": null,
"e": 3562,
"s": 3543,
"text": "mvn clean install\n"
},
{
"code": null,
"e": 3671,
"s": 3562,
"text": "This should auto-generate the source code required for us to use gRPC. The source code would be placed under"
},
{
"code": null,
"e": 3828,
"s": 3671,
"text": "Protobuf class code: target/generatedsources/protobuf/java/com.tp.bookstore\nProtobuf gRPC code: target/generated-sources/protobuf/grpcjava/com.tp.bookstore\n"
},
{
"code": null,
"e": 3961,
"s": 3828,
"text": "Now that we have defined the proto file which contains the function definition,let us setup a server which can call these functions."
},
{
"code": null,
"e": 4087,
"s": 3961,
"text": "Let us write our server code to serve the above function and save it in com.tp.bookstore.BookeStoreServerBothStreaming.java −"
},
{
"code": null,
"e": 7955,
"s": 4087,
"text": "package com.tp.bookstore;\n\nimport io.grpc.Server;\nimport io.grpc.ServerBuilder;\nimport io.grpc.stub.StreamObserver;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Map.Entry;\nimport java.util.concurrent.TimeUnit;\nimport java.util.logging.Logger;\nimport java.util.stream.Collectors;\n\nimport com.tp.bookstore.BookStoreOuterClass.Book;\nimport com.tp.bookstore.BookStoreOuterClass.BookSearch;\nimport com.tp.bookstore.BookStoreOuterClass.Cart;\n\npublic class BookeStoreServerBothStreaming {\n private static final Logger logger =Logger.getLogger(BookeStoreServerBothStreaming.class.getName());\n\n static Map<String, Book> bookMap = new HashMap<>();\n static {\n bookMap.put(\"Great Gatsby\", Book.newBuilder().setName(\"Great Gatsby\")\n .setAuthor(\"Scott Fitzgerald\")\n .setPrice(300).build());\n bookMap.put(\"To Kill MockingBird\", Book.newBuilder().setName(\"To Kill MockingBird\")\n .setAuthor(\"Harper Lee\")\n .setPrice(400).build());\n bookMap.put(\"Passage to India\", Book.newBuilder().setName(\"Passage to India\")\n .setAuthor(\"E.M.Forster\")\n .setPrice(500).build());\n bookMap.put(\"The Side of Paradise\", Book.newBuilder().setName(\"The Side of Paradise\")\n .setAuthor(\"Scott Fitzgerald\")\n .setPrice(600).build());\n bookMap.put(\"Go Set a Watchman\",Book.newBuilder().setName(\"Go Set a Watchman\")\n .setAuthor(\"Harper Lee\")\n .setPrice(700).build());\n }\n private Server server;\n private void start() throws IOException {\n int port = 50051;\n server = ServerBuilder.forPort(port)\n .addService(new BookStoreImpl()).build().start();\n\n logger.info(\"Server started, listening on \" + port);\n Runtime.getRuntime().addShutdownHook(new Thread() {\n @Override\n public void run() {\n System.err.println(\"Shutting down gRPC server\");\n try {\n server.shutdown().awaitTermination(30, TimeUnit.SECONDS);\n } catch (InterruptedException e) {\n e.printStackTrace(System.err);\n }\n }\n });\n }\n public static void main(String[] args) throws IOException,InterruptedException {\n final BookeStoreServerBothStreaming greetServer = newBookeStoreServerBothStreaming();\n greetServer.start();\n greetServer.server.awaitTermination();\n }\n static class BookStoreImpl extendsBookStoreGrpc.BookStoreImplBase {\n @Override\n public StreamObserver<Book>liveCartValue(StreamObserver<Cart> responseObserver) {\n return new StreamObserver<Book>() {\n ArrayList<Book> bookCart = new ArrayList<Book>();\n int cartValue = 0;\n @Override\n public void onNext(Book book) {\n logger.info(\"Searching for book with titlestarting with: \" + book.getName());\n for (Entry<String, Book> bookEntry :bookMap.entrySet()) {\n if(bookEntry.getValue().getName().startsWith(book.getName())){\n logger.info(\"Found book, adding tocart:....\");\n bookCart.add(bookEntry.getValue());\n cartValue +=bookEntry.getValue().getPrice();\n }\n }\n logger.info(\"Updating cart value...\");\n\n responseObserver.onNext(Cart.newBuilder()\n .setPrice(cartValue)\n .setBooks(bookCart.size()).build());\n }\n @Override\n public void onError(Throwable t) {\n logger.info(\"Error while reading book stream: \" + t);\n }\n @Override\n public void onCompleted() {\n logger.info(\"Order completed\");\n responseObserver.onCompleted();\n }\n };\n }\n }\n}"
},
{
"code": null,
"e": 8126,
"s": 7955,
"text": "The above code starts a gRPC server at a specified port and serves the functions and services which we had written in our proto file. Let us walk through the above code −"
},
{
"code": null,
"e": 8201,
"s": 8126,
"text": "Starting from the main method, we create a gRPC server at a specifiedport."
},
{
"code": null,
"e": 8276,
"s": 8201,
"text": "Starting from the main method, we create a gRPC server at a specifiedport."
},
{
"code": null,
"e": 8405,
"s": 8276,
"text": "But before starting the server, we assign the server the service which we want to run, i.e., in our case, the BookStore service."
},
{
"code": null,
"e": 8534,
"s": 8405,
"text": "But before starting the server, we assign the server the service which we want to run, i.e., in our case, the BookStore service."
},
{
"code": null,
"e": 8684,
"s": 8534,
"text": "For this purpose, we need to pass in the service instance to the server, so we go ahead and create service instance i.e. in our case theBookStoreImpl"
},
{
"code": null,
"e": 8834,
"s": 8684,
"text": "For this purpose, we need to pass in the service instance to the server, so we go ahead and create service instance i.e. in our case theBookStoreImpl"
},
{
"code": null,
"e": 8994,
"s": 8834,
"text": "The service instance need to provide an implementation of the method/function which is present in the proto file, i.e., in our case, the totalCartValue method."
},
{
"code": null,
"e": 9154,
"s": 8994,
"text": "The service instance need to provide an implementation of the method/function which is present in the proto file, i.e., in our case, the totalCartValue method."
},
{
"code": null,
"e": 9474,
"s": 9154,
"text": "Now, given that this is the case of server and client streaming, the server will get the list of Books (defined in the proto file) as the client adds them. The server thus returns a custom stream observer. This stream observer implements what happens when a new Book is found and what happens when the stream is closed."
},
{
"code": null,
"e": 9794,
"s": 9474,
"text": "Now, given that this is the case of server and client streaming, the server will get the list of Books (defined in the proto file) as the client adds them. The server thus returns a custom stream observer. This stream observer implements what happens when a new Book is found and what happens when the stream is closed."
},
{
"code": null,
"e": 10074,
"s": 9794,
"text": "The onNext() method would be called by the gRPC framework when the client adds a Book. At this point, the server adds that to the cart and uses the response observer to return the Cart Value. In case of streaming, the server does not wait for all the valid books to be available."
},
{
"code": null,
"e": 10354,
"s": 10074,
"text": "The onNext() method would be called by the gRPC framework when the client adds a Book. At this point, the server adds that to the cart and uses the response observer to return the Cart Value. In case of streaming, the server does not wait for all the valid books to be available."
},
{
"code": null,
"e": 10606,
"s": 10354,
"text": "When the client is done with the addition of Books, the stream observer's onCompleted() method is called. This method implements what the server wants to do when the client is done adding the Books, i.e., claim it is done with taking the client order."
},
{
"code": null,
"e": 10858,
"s": 10606,
"text": "When the client is done with the addition of Books, the stream observer's onCompleted() method is called. This method implements what the server wants to do when the client is done adding the Books, i.e., claim it is done with taking the client order."
},
{
"code": null,
"e": 10977,
"s": 10858,
"text": "Finally, we also have a shutdown hook to ensure clean shutting down of the server when we are done executing our code."
},
{
"code": null,
"e": 11096,
"s": 10977,
"text": "Finally, we also have a shutdown hook to ensure clean shutting down of the server when we are done executing our code."
},
{
"code": null,
"e": 11200,
"s": 11096,
"text": "Now that we have written the code for the server, let us setup a client which can call these functions."
},
{
"code": null,
"e": 11324,
"s": 11200,
"text": "Let us write our client code to call the above function and save it in com.tp.bookstore.BookStoreClientBothStreaming.java −"
},
{
"code": null,
"e": 15085,
"s": 11324,
"text": "package com.tp.bookstore;\n\nimport io.grpc.Channel;\nimport io.grpc.ManagedChannel;\nimport io.grpc.ManagedChannelBuilder;\nimport io.grpc.StatusRuntimeException;\nimport io.grpc.stub.StreamObserver;\n\nimport java.util.Iterator;\nimport java.util.concurrent.TimeUnit;\nimport java.util.logging.Level;\nimport java.util.logging.Logger;\n\nimport com.tp.bookstore.BookStoreGrpc.BookStoreFutureStub;\nimport com.tp.bookstore.BookStoreGrpc.BookStoreStub;\nimport com.tp.bookstore.BookStoreOuterClass.Book;\nimport com.tp.bookstore.BookStoreOuterClass.BookSearch;\nimport com.tp.bookstore.BookStoreOuterClass.Cart;\nimport com.tp.greeting.GreeterGrpc;\nimport com.tp.greeting.Greeting.ServerOutput;\nimport com.tp.greeting.Greeting.ClientInput;\n\npublic class BookStoreClientBothStreaming {\n private static final Logger logger = Logger.getLogger(BookStoreClientBothStreaming.class.getName());\n private final BookStoreStub stub;\n private boolean serverIntermediateResponseCompleted = true;\n private boolean serverResponseCompleted = false;\n\n StreamObserver<Book> streamClientSender;\n \n public BookStoreClientBothStreaming(Channel channel) {\n stub = BookStoreGrpc.newStub(channel);\n }\n public StreamObserver>Cart< getServerResponseObserver(){\n StreamObserver>Cart< observer = new StreamObserver<Cart>(){\n @Override\n public void onNext(Cart cart) {\n logger.info(\"Order summary:\" + \n \"\\nTotal number of Books:\" + cart.getBooks()+ \n \"\\nTotal Order Value:\" cart.getPrice());\n\n serverIntermediateResponseCompleted = true;\n }\n @Override\n public void onError(Throwable t) {\n logger.info(\"Error while reading response fromServer: \" + t);\n }\n @Override\n public void onCompleted() {\n //logger.info(\"Server: Done reading orderreading cart\");\n serverResponseCompleted = true;\n }\n };\n return observer;\n }\n public void addBook(String book) {\n logger.info(\"Adding book with title starting with: \" + book);\n Book request = Book.newBuilder().setName(book).build();\n if(streamClientSender == null) {\n streamClientSender =stub.liveCartValue(getServerResponseObserver());\n }\n try {\n streamClientSender.onNext(request);\n }\n catch (StatusRuntimeException e) {\n logger.log(Level.WARNING, \"RPC failed: {0}\", e.getStatus());\n }\n }\n public void completeOrder() {\n logger.info(\"Done, waiting for server to create ordersummary...\");\n if(streamClientSender != null); {\n streamClientSender.onCompleted();\n }\n }\n public static void main(String[] args) throws Exception {\n String serverAddress = \"localhost:50051\";\n ManagedChannel channel = ManagedChannelBuilder.forTarget(serverAddress)\n .usePlaintext()\n .build();\n try {\n BookStoreClientBothStreaming client = new\n BookStoreClientBothStreaming(channel);\n String bookName = \"\";\n\n while(true) {\n if(client.serverIntermediateResponseCompleted ==true) {\n System.out.println(\"Type book name to beadded to the cart....\");\n bookName = System.console().readLine();\n if(bookName.equals(\"EXIT\")) {\n client.completeOrder();\n break;\n }\n client.serverIntermediateResponseCompleted = false;\n client.addBook(bookName);\n Thread.sleep(500);\n }\n }\n while(client.serverResponseCompleted == false) {\n Thread.sleep(2000);\n }\n \n } finally {\n channel.shutdownNow().awaitTermination(5, TimeUnit.SECONDS);\n } \n }\n}"
},
{
"code": null,
"e": 15279,
"s": 15085,
"text": "The above code starts a gRPC client and connects to a server at a specified port and call the functions and services which we had written in our proto file. Let us walk through the above code −"
},
{
"code": null,
"e": 15441,
"s": 15279,
"text": "Starting from the main method, we accept the name of the books to be added to the cart. Once all the books are to be added, the user is expected to print \"EXIT\"."
},
{
"code": null,
"e": 15603,
"s": 15441,
"text": "Starting from the main method, we accept the name of the books to be added to the cart. Once all the books are to be added, the user is expected to print \"EXIT\"."
},
{
"code": null,
"e": 15662,
"s": 15603,
"text": "We setup a Channel for gRPC communication with our server."
},
{
"code": null,
"e": 15721,
"s": 15662,
"text": "We setup a Channel for gRPC communication with our server."
},
{
"code": null,
"e": 15863,
"s": 15721,
"text": "Next, we create a non-blocking stub using the channel. This is where we are choosing the service \"BookStore\" whose functions we plan to call."
},
{
"code": null,
"e": 16005,
"s": 15863,
"text": "Next, we create a non-blocking stub using the channel. This is where we are choosing the service \"BookStore\" whose functions we plan to call."
},
{
"code": null,
"e": 16147,
"s": 16005,
"text": "Then, we simply create the expected input defined in the proto file, i.e., in our case, Book, and we add the title we want the server to add."
},
{
"code": null,
"e": 16289,
"s": 16147,
"text": "Then, we simply create the expected input defined in the proto file, i.e., in our case, Book, and we add the title we want the server to add."
},
{
"code": null,
"e": 16540,
"s": 16289,
"text": "But given that this is the case of both server and client streaming, we first create a stream observer for the server. This server stream observer lists the behavior on what needs to be done when the server responds, i.e., onNext() and onCompleted()."
},
{
"code": null,
"e": 16791,
"s": 16540,
"text": "But given that this is the case of both server and client streaming, we first create a stream observer for the server. This server stream observer lists the behavior on what needs to be done when the server responds, i.e., onNext() and onCompleted()."
},
{
"code": null,
"e": 16941,
"s": 16791,
"text": "And using the stub, we also get the client stream observer. We use this stream observer for sending the data, i.e., the Book to be added to the cart."
},
{
"code": null,
"e": 17091,
"s": 16941,
"text": "And using the stub, we also get the client stream observer. We use this stream observer for sending the data, i.e., the Book to be added to the cart."
},
{
"code": null,
"e": 17243,
"s": 17091,
"text": "And once our order is complete, we ensure that the client stream observer is closed. This tells the server to close the stream and perform the cleanup."
},
{
"code": null,
"e": 17395,
"s": 17243,
"text": "And once our order is complete, we ensure that the client stream observer is closed. This tells the server to close the stream and perform the cleanup."
},
{
"code": null,
"e": 17453,
"s": 17395,
"text": "Finally, we close the channel to avoid any resource leak."
},
{
"code": null,
"e": 17511,
"s": 17453,
"text": "Finally, we close the channel to avoid any resource leak."
},
{
"code": null,
"e": 17540,
"s": 17511,
"text": "So, that is our client code."
},
{
"code": null,
"e": 17589,
"s": 17540,
"text": "To sum up, what we want to do is the following −"
},
{
"code": null,
"e": 17612,
"s": 17589,
"text": "Start the gRPC server."
},
{
"code": null,
"e": 17635,
"s": 17612,
"text": "Start the gRPC server."
},
{
"code": null,
"e": 17702,
"s": 17635,
"text": "The Client adds a stream of books by notifying them to the server."
},
{
"code": null,
"e": 17769,
"s": 17702,
"text": "The Client adds a stream of books by notifying them to the server."
},
{
"code": null,
"e": 17838,
"s": 17769,
"text": "The Server searches the book in its store and adds them to the cart."
},
{
"code": null,
"e": 17907,
"s": 17838,
"text": "The Server searches the book in its store and adds them to the cart."
},
{
"code": null,
"e": 17982,
"s": 17907,
"text": "With each book addition, the server tells the client about the cart value."
},
{
"code": null,
"e": 18057,
"s": 17982,
"text": "With each book addition, the server tells the client about the cart value."
},
{
"code": null,
"e": 18140,
"s": 18057,
"text": "When the client is done ordering, both the server and the client close the stream."
},
{
"code": null,
"e": 18223,
"s": 18140,
"text": "When the client is done ordering, both the server and the client close the stream."
},
{
"code": null,
"e": 18359,
"s": 18223,
"text": "Now that we have defined our proto file, written our server and the client code, let us now execute this code and see things in action."
},
{
"code": null,
"e": 18474,
"s": 18359,
"text": "For running the code, fire up two shells. Start the server on the first shell by executing the following command −"
},
{
"code": null,
"e": 18561,
"s": 18474,
"text": "java -cp .\\target\\grpc-point-1.0.jar\ncom.tp.bookstore.BookeStoreServerClientStreaming\n"
},
{
"code": null,
"e": 18597,
"s": 18561,
"text": "We would see the following output −"
},
{
"code": null,
"e": 18713,
"s": 18597,
"text": "Jul 03, 2021 10:37:21 PM\ncom.tp.bookstore.BookeStoreServerStreaming start\nINFO: Server started, listening on 50051\n"
},
{
"code": null,
"e": 18762,
"s": 18713,
"text": "This output implies that the server has started."
},
{
"code": null,
"e": 18792,
"s": 18762,
"text": "Now, let us start the client."
},
{
"code": null,
"e": 18876,
"s": 18792,
"text": "java -cp .\\target\\grpc-point-1.0.jar\ncom.tp.bookstore.BookStoreClientBothStreaming\n"
},
{
"code": null,
"e": 18909,
"s": 18876,
"text": "Let us add a book to our client."
},
{
"code": null,
"e": 19310,
"s": 18909,
"text": "Jul 24, 2021 7:21:45 PM\ncom.tp.bookstore.BookStoreClientBothStreaming main\nType book name to be added to the cart....\nGreat\n\nJul 24, 2021 7:21:48 PM\ncom.tp.bookstore.BookStoreClientBothStreaming addBook\nINFO: Adding book with title starting with: Gr\n\nJul 24, 2021 7:21:48 PM\ncom.tp.bookstore.BookStoreClientBothStreaming$1 onNext\nINFO: Order summary:\n\nTotal number of Books: 1\nTotal Order Value: 300\n"
},
{
"code": null,
"e": 19417,
"s": 19310,
"text": "So, as we can see, we get the current cart value of the order. Let us now add one more book to our client."
},
{
"code": null,
"e": 19744,
"s": 19417,
"text": "Type book name to be added to the cart....\nPassage\n\nJul 24, 2021 7:21:51 PM\ncom.tp.bookstore.BookStoreClientBothStreaming addBook\nINFO: Adding book with title starting with: Pa\n\nJul 24, 2021 7:21:51 PM\ncom.tp.bookstore.BookStoreClientBothStreaming$1 onNext\nINFO: Order summary:\nTotal number of Books: 2\nTotal Order Value: 800\n"
},
{
"code": null,
"e": 19817,
"s": 19744,
"text": "Once we have added the books and we input \"EXIT\", the client shuts down."
},
{
"code": null,
"e": 20008,
"s": 19817,
"text": "Type book name to be added to the cart....\nEXIT\nJul 24, 2021 7:21:59 PM\ncom.tp.bookstore.BookStoreClientBothStreaming completeOrder\nINFO: Done, waiting for server to create order summary...\n"
},
{
"code": null,
"e": 20143,
"s": 20008,
"text": "So, as we can see the client was able to add books. And as the books are being added, the server responds with the current cart value."
},
{
"code": null,
"e": 20150,
"s": 20143,
"text": " Print"
},
{
"code": null,
"e": 20161,
"s": 20150,
"text": " Add Notes"
}
] |
Feature Importance with Time Series and Recurrent Neural Network | by Marco Cerliani | Towards Data Science | Neural networks are often considered black-box algorithms. This is true but with few tricks and some useful external inference techniques we can extract lots of information from them. Amazing examples come from the application of Deep Learning with images. The extraction of internal features from the network is useful to understand how the network works: famous are heatmap representations which point in the image the areas of interest for the model to make a decision.
The concepts behind this process of knowledge extraction can be generalized for every domain of application of deep learning, like NLP and Time Series forecasting. Practically speaking, we can query our trained neural network with few lines of code with the scope of check the importance of output filters towards the final prediction.
In this post, I investigate the decision taken by a neural network trained to forecast the future. I used a recurrent structure to automatically learn information also from the time dimension. With some simple steps, we extract all we needed to understand the output of our model. We do this without the usage of any additional external library but simply squeezing what the model has learned.
The data for our experiment is collected from the UCI repository. The Beijing PM2.5 Dataset stores, as suggested by the name, the pm2.5 hourly observations (from 2010 to 2015) together with other weather regressors like temperature, pressure, wind and rain levels. Our scope is to forecast the exact value of pm2.5 one step ahead (the concentration of the next hour).
We use the first three years at our disposal as trainset and the latter two respectively for validation and test.
To train our sequential neural network we rearrange the data properly as 3D sequences of dimension: sample x time dimension x features. Below an example of a generated sequence of length 30 hours, where the values of each series are standardized with standard scaling.
This is an example of input samples for our model. We also standardize the target with mean and standard deviation.
The neural network structure we use for time series forecasting is as follow:
def get_model(params): inp = Input(shape=(sequence_length, len(columns))) x = GRU(params['units_gru'], return_sequences=True)(inp) x = AveragePooling1D(2)(x) x = Conv1D(params['units_cnn'], 3, activation='relu', padding='same', name='extractor')(x) x = Flatten()(x) out = Dense(1)(x) model = Model(inp, out) model.compile(optimizer=Adam(lr=params['lr']), loss='mse') return model
A recurrent layer processes the initial sequences returning the full output in form of sequences. An average pooling compresses the output which is then treated by a one-dimensional convolutional layer. In the end, all is flattened to turn in a 2D dimension before generating the final predictions. Below a comparison between predictions and real values in a subsample of the test set (this is a demo, we are not interested in performances).
With our neural network trained we are ready to inspect the predictions. I provide two interpretations of the model outputs which can be easily retrieved for every test sequence.
Our idea is to check the contribution of each single input feature on the final prediction output. The contribution in our case is given by the value of the gradients obtained from the differentiation operation of the input sequences on the forecasts.
With Tensorflow, the implementation of this method is only 3 steps:
use the GradientTape object to capture the gradients on the input;
get the gradients with tape.gradient: this operation produces gradients of the same shape of the single input sequence (time dimension x features);
obtain the impact of each sequence feature as average over the time dimension.
def gradient_importance(seq, model): seq = tf.Variable(seq[np.newaxis,:,:], dtype=tf.float32) with tf.GradientTape() as tape: predictions = model(seq) grads = tape.gradient(predictions, seq) grads = tf.reduce_mean(grads, axis=1).numpy()[0] return grads
Some graphical examples of results are shown below:
The higher the average gradients are, the bigger is the impact of the feature on the final prediction. So for each of the cases shown above, we can identify which variable, in the input sequence, weighs more for the prediction of the next hour value of pm2.5 concentration.
Visualizing which input feature influences the most a prediction can help detect weird behaviors. However, it gives fewer insights into why a neural network makes a decision. This method tends to underline what specific part of the input is influencing the output value.
The process of reaching these conclusions is based on the same assumption made before. In other words, we need to operate gradient importance. The difference now it’s that this operation is computed with some internal filters instead of with the raw input sequence. Given our internal convolutional/recurrent filters, we operate the gradients towards the outputs. To establish the importance of each filter in the decision, we take the average of its weights (gradients importance) and multiply each map by its corresponding weights. If an activation map has been lightened up during forward pass and if its gradients are large, it means the region which is activated has a large impact on the decision.
Speaking in code language, little changes have to be made; particularly in the end where we operate normalization and we need to adjust the dimensions, to match the input sequences.
def activation_grad(seq, model): seq = seq[np.newaxis,:,:] grad_model = Model([model.inputs], [model.get_layer('extractor').output, model.output]) # Obtain the predicted value and the intermediate filters with tf.GradientTape() as tape: seq_outputs, predictions = grad_model(seq) # Extract filters and gradients output = seq_outputs[0] grads = tape.gradient(predictions, seq_outputs)[0] # Average gradients spatially weights = tf.reduce_mean(grads, axis=0) # Get a ponderated map of filters according to grad importance cam = np.ones(output.shape[0], dtype=np.float32) for index, w in enumerate(weights): cam += w * output[:, index] time = int(seq.shape[1]/output.shape[0]) cam = zoom(cam.numpy(), time, order=1) heatmap = (cam - cam.min())/(cam.max() - cam.min()) return heatmap
In this post, I’ve built a sequential neural network for time series forecasting. Our purpose was to extract useful information from it. To do this, we’ve provided 2 different methods, based on gradients computation to operate inference after training. I’ve shown that also for sequential neural networks (recurrent/convolutional), in a time series application, it’s possible to investigate the behavior of deep models with simple tricks and few lines of code.
CHECK MY GITHUB REPO
Keep in touch: Linkedin | [
{
"code": null,
"e": 520,
"s": 47,
"text": "Neural networks are often considered black-box algorithms. This is true but with few tricks and some useful external inference techniques we can extract lots of information from them. Amazing examples come from the application of Deep Learning with images. The extraction of internal features from the network is useful to understand how the network works: famous are heatmap representations which point in the image the areas of interest for the model to make a decision."
},
{
"code": null,
"e": 856,
"s": 520,
"text": "The concepts behind this process of knowledge extraction can be generalized for every domain of application of deep learning, like NLP and Time Series forecasting. Practically speaking, we can query our trained neural network with few lines of code with the scope of check the importance of output filters towards the final prediction."
},
{
"code": null,
"e": 1250,
"s": 856,
"text": "In this post, I investigate the decision taken by a neural network trained to forecast the future. I used a recurrent structure to automatically learn information also from the time dimension. With some simple steps, we extract all we needed to understand the output of our model. We do this without the usage of any additional external library but simply squeezing what the model has learned."
},
{
"code": null,
"e": 1618,
"s": 1250,
"text": "The data for our experiment is collected from the UCI repository. The Beijing PM2.5 Dataset stores, as suggested by the name, the pm2.5 hourly observations (from 2010 to 2015) together with other weather regressors like temperature, pressure, wind and rain levels. Our scope is to forecast the exact value of pm2.5 one step ahead (the concentration of the next hour)."
},
{
"code": null,
"e": 1732,
"s": 1618,
"text": "We use the first three years at our disposal as trainset and the latter two respectively for validation and test."
},
{
"code": null,
"e": 2001,
"s": 1732,
"text": "To train our sequential neural network we rearrange the data properly as 3D sequences of dimension: sample x time dimension x features. Below an example of a generated sequence of length 30 hours, where the values of each series are standardized with standard scaling."
},
{
"code": null,
"e": 2117,
"s": 2001,
"text": "This is an example of input samples for our model. We also standardize the target with mean and standard deviation."
},
{
"code": null,
"e": 2195,
"s": 2117,
"text": "The neural network structure we use for time series forecasting is as follow:"
},
{
"code": null,
"e": 2644,
"s": 2195,
"text": "def get_model(params): inp = Input(shape=(sequence_length, len(columns))) x = GRU(params['units_gru'], return_sequences=True)(inp) x = AveragePooling1D(2)(x) x = Conv1D(params['units_cnn'], 3, activation='relu', padding='same', name='extractor')(x) x = Flatten()(x) out = Dense(1)(x) model = Model(inp, out) model.compile(optimizer=Adam(lr=params['lr']), loss='mse') return model"
},
{
"code": null,
"e": 3086,
"s": 2644,
"text": "A recurrent layer processes the initial sequences returning the full output in form of sequences. An average pooling compresses the output which is then treated by a one-dimensional convolutional layer. In the end, all is flattened to turn in a 2D dimension before generating the final predictions. Below a comparison between predictions and real values in a subsample of the test set (this is a demo, we are not interested in performances)."
},
{
"code": null,
"e": 3265,
"s": 3086,
"text": "With our neural network trained we are ready to inspect the predictions. I provide two interpretations of the model outputs which can be easily retrieved for every test sequence."
},
{
"code": null,
"e": 3517,
"s": 3265,
"text": "Our idea is to check the contribution of each single input feature on the final prediction output. The contribution in our case is given by the value of the gradients obtained from the differentiation operation of the input sequences on the forecasts."
},
{
"code": null,
"e": 3585,
"s": 3517,
"text": "With Tensorflow, the implementation of this method is only 3 steps:"
},
{
"code": null,
"e": 3652,
"s": 3585,
"text": "use the GradientTape object to capture the gradients on the input;"
},
{
"code": null,
"e": 3800,
"s": 3652,
"text": "get the gradients with tape.gradient: this operation produces gradients of the same shape of the single input sequence (time dimension x features);"
},
{
"code": null,
"e": 3879,
"s": 3800,
"text": "obtain the impact of each sequence feature as average over the time dimension."
},
{
"code": null,
"e": 4158,
"s": 3879,
"text": "def gradient_importance(seq, model): seq = tf.Variable(seq[np.newaxis,:,:], dtype=tf.float32) with tf.GradientTape() as tape: predictions = model(seq) grads = tape.gradient(predictions, seq) grads = tf.reduce_mean(grads, axis=1).numpy()[0] return grads"
},
{
"code": null,
"e": 4210,
"s": 4158,
"text": "Some graphical examples of results are shown below:"
},
{
"code": null,
"e": 4484,
"s": 4210,
"text": "The higher the average gradients are, the bigger is the impact of the feature on the final prediction. So for each of the cases shown above, we can identify which variable, in the input sequence, weighs more for the prediction of the next hour value of pm2.5 concentration."
},
{
"code": null,
"e": 4755,
"s": 4484,
"text": "Visualizing which input feature influences the most a prediction can help detect weird behaviors. However, it gives fewer insights into why a neural network makes a decision. This method tends to underline what specific part of the input is influencing the output value."
},
{
"code": null,
"e": 5459,
"s": 4755,
"text": "The process of reaching these conclusions is based on the same assumption made before. In other words, we need to operate gradient importance. The difference now it’s that this operation is computed with some internal filters instead of with the raw input sequence. Given our internal convolutional/recurrent filters, we operate the gradients towards the outputs. To establish the importance of each filter in the decision, we take the average of its weights (gradients importance) and multiply each map by its corresponding weights. If an activation map has been lightened up during forward pass and if its gradients are large, it means the region which is activated has a large impact on the decision."
},
{
"code": null,
"e": 5641,
"s": 5459,
"text": "Speaking in code language, little changes have to be made; particularly in the end where we operate normalization and we need to adjust the dimensions, to match the input sequences."
},
{
"code": null,
"e": 6538,
"s": 5641,
"text": "def activation_grad(seq, model): seq = seq[np.newaxis,:,:] grad_model = Model([model.inputs], [model.get_layer('extractor').output, model.output]) # Obtain the predicted value and the intermediate filters with tf.GradientTape() as tape: seq_outputs, predictions = grad_model(seq) # Extract filters and gradients output = seq_outputs[0] grads = tape.gradient(predictions, seq_outputs)[0] # Average gradients spatially weights = tf.reduce_mean(grads, axis=0) # Get a ponderated map of filters according to grad importance cam = np.ones(output.shape[0], dtype=np.float32) for index, w in enumerate(weights): cam += w * output[:, index] time = int(seq.shape[1]/output.shape[0]) cam = zoom(cam.numpy(), time, order=1) heatmap = (cam - cam.min())/(cam.max() - cam.min()) return heatmap"
},
{
"code": null,
"e": 6999,
"s": 6538,
"text": "In this post, I’ve built a sequential neural network for time series forecasting. Our purpose was to extract useful information from it. To do this, we’ve provided 2 different methods, based on gradients computation to operate inference after training. I’ve shown that also for sequential neural networks (recurrent/convolutional), in a time series application, it’s possible to investigate the behavior of deep models with simple tricks and few lines of code."
},
{
"code": null,
"e": 7020,
"s": 6999,
"text": "CHECK MY GITHUB REPO"
}
] |
Groovy - Maps size() | Returns the number of key-value mappings in this Map.
int size()
None.
The size of the map.
Following is an example of the usage of this method −
class Example {
static void main(String[] args) {
def mp = ["TopicName" : "Maps", "TopicDescription" : "Methods in Maps"]
println(mp.size());
mp.put("TopicID","1");
println(mp.size());
}
}
When we run the above program, we will get the following result −
2
3
52 Lectures
8 hours
Krishna Sakinala
49 Lectures
2.5 hours
Packt Publishing
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2292,
"s": 2238,
"text": "Returns the number of key-value mappings in this Map."
},
{
"code": null,
"e": 2304,
"s": 2292,
"text": "int size()\n"
},
{
"code": null,
"e": 2310,
"s": 2304,
"text": "None."
},
{
"code": null,
"e": 2331,
"s": 2310,
"text": "The size of the map."
},
{
"code": null,
"e": 2385,
"s": 2331,
"text": "Following is an example of the usage of this method −"
},
{
"code": null,
"e": 2615,
"s": 2385,
"text": "class Example { \n static void main(String[] args) { \n def mp = [\"TopicName\" : \"Maps\", \"TopicDescription\" : \"Methods in Maps\"] \n println(mp.size()); \n\t\t\n mp.put(\"TopicID\",\"1\"); \n println(mp.size()); \n } \n} "
},
{
"code": null,
"e": 2681,
"s": 2615,
"text": "When we run the above program, we will get the following result −"
},
{
"code": null,
"e": 2688,
"s": 2681,
"text": "2 \n3 \n"
},
{
"code": null,
"e": 2721,
"s": 2688,
"text": "\n 52 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 2739,
"s": 2721,
"text": " Krishna Sakinala"
},
{
"code": null,
"e": 2774,
"s": 2739,
"text": "\n 49 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 2792,
"s": 2774,
"text": " Packt Publishing"
},
{
"code": null,
"e": 2799,
"s": 2792,
"text": " Print"
},
{
"code": null,
"e": 2810,
"s": 2799,
"text": " Add Notes"
}
] |
Deep Demand Forecasting with Amazon SageMaker | by Ehsan M. Kermani | Towards Data Science | In this article, we explore how to use Deep Learning methods for Demand Forecasting using Amazon SageMaker.
TL;DR: The code for this project is available on GitHub with a single click AWS CloudFormation template to set up the required stack.
Demand forecasting uses historical time-series data to help streamline the supply-demand decision-making process across businesses. Examples include predicting the number of
Customer representatives to hire for multiple locations in the next month
Product sales across multiple regions in the next quarter
Cloud server usage for the next day for a video streaming service
Electricity consumption for multiple regions over the next week
IoT devices and sensors such as energy consumption
Any data indexed with time is time-series data. Time-series data are categorized as univariate and multi-variate. For example, the total electricity consumption for a single household is a univariate time-series over a period of time. Here is how a univariate time-series looks like with some forecasts in green
When multiple univariate time-series are stacked up on each other, it’s called multi-variate time-series. For example, total electricity consumption of 10 different (but correlated) households in a single neighborhood make up a multi-variate time-series data. Such data encapsulates more information such as being correlated in a neighborhood. Therefore, we potentially can use this shared information to get better forecasts for each of the households. The status quo approaches for time-series forecasting include Auto-Regressive methods such as
Auto Regressive Integrated Moving Average (ARIMA) for univariate time-series data
Vector Auto-Regression (VAR) for multi-variate time-series data
One of the disadvantages of these classical methods is that they require tedious data preprocessing and feature engineering prior to model training such as incorporating various data normalization, lags, different time scales, some categorical data, dealing with missing values, etc. all usually with stationarity assumption. However, Deep Learning (DL) models can automate these steps. Moreover, it is widely known that DL methods have surpassed classical methods in areas such as Computer Vision or Natural Language Process with enough data but how about time-series data?
The use of Deep Learning methods in time-series forecasting has been a major point of research in particular for (stationary/non-stationary) multi-variate time-series data. With highly optimized, dedicated frameworks such as Apache MXNet, PyTorch and TensorFlow, with fast GPU-enabled training and inference capabilities. Research indicates that DL methods outperform the aforementioned classical methods ARIMA and VAR, in particular when dealing with large volumes of (correlated) multi-variate time-series data that have categorical features and missing values. One reason is that neural network models can predict seasonality for new events since these global models learn patterns jointly over the whole dataset and can extrapolate learned regularities to new series better. One such method is LSTNet from Modeling Long- and Short-Term Temporal Patterns with Deep Neural Networks.
LSTNet is one of the state-of-the-art DL methods for forecasting. We have contributed it to GluonTS which currently is based on the MXNet Gluon API. The advantage of LSTNet is that it incorporates traditional auto-regressive linear models in parallel to the non-linear neural network part. This makes the non-linear DL model more robust for the time series which violates scale changes. The following is the LSTNet architecture, which contains a
Convolution as the first layer, followed byRecurrent and Skip-Recurrent layersFully Connected layer combining the non-linear features and the linear features
Convolution as the first layer, followed by
Recurrent and Skip-Recurrent layers
Fully Connected layer combining the non-linear features and the linear features
For this demonstration, we will use multi-variate time-series electricity consumption data1. A cleaned version of the data is available to download directly via GluonTS. The data contains 321 time-series with 1 Hour frequency, where
training data starts from 2012–01–01 00:00:00 and ends at 2014–05–26 19:00:00
testing data has additional data to from 2014–05–26 19:00:00 until 2014–05–27 19:00:00
Here is a snapshot of the normalized training data in a Pandas DataFrame
The dataset is stored in an S3 bucket. The project that uses Amazon SageMaker has three main components as follows:
Pre-processing step to normalize the data designed as a micro-service to handle heavy duty jobsTraining an LSTNet model and examine the metrics such as sMAPE for the predictions(Optional) Deploying and creating a real-time prediction HTTPS endpoint that connects to Amazon CloudWatch for monitoring
Pre-processing step to normalize the data designed as a micro-service to handle heavy duty jobs
Training an LSTNet model and examine the metrics such as sMAPE for the predictions
(Optional) Deploying and creating a real-time prediction HTTPS endpoint that connects to Amazon CloudWatch for monitoring
This complete code project is available in GitHub. Follow the instructions for a single click setup. Here is the visual architecture guide:
Since we are using GluonTS, we need to train our model using an MXNet estimator by providing train.py as our entry point. For example, we train our model for 1 epoch for context_length=12 which is the training window size of 12 hours of past electricity consumption to predict for the next 6 hours prediction_length=6 as testing window size.
import loggingfrom sagemaker.mxnet import MXNetCONTEXT_LENGTH = 12PREDICTION_LENGTH = 6hyperparameters = { 'context_length': CONTEXT_LENGTH, 'prediction_length': PREDICTION_LENGTH, 'skip_size': 4, 'ar_window': 4, 'channels': 72, 'scaling': False, 'output_activation': 'sigmoid', 'epochs': 1,}estimator = MXNet(entry_point='train.py', source_dir='deep_demand_forecast', role=role, train_instance_count=1, train_instance_type='ml.p3.2xlarge', framework_version="1.6.0", py_version='py3', hyperparameters=hyperparameters, output_path=train_output, code_location=code_location, sagemaker_session=session, container_log_level=logging.DEBUG, )estimator.fit(train_data)
One of the most common evaluation metrics in time-series forecasting is
Symmetric Mean Absolution Percentage Error (sMAPE) which quantifies how much the model is under-forecasting or over-forecasting where the forecast at time t is Ft and the actual value of time t is At
When can visually compare it with another useful metric known as Mean Absolute Scaled Error (MASE) where the closer the values are to zero, generally the better the predictions become. We use Altair Python package to interactively examine their relationships.
Finally, we can interactively visualize the predictions vs. train and test data. For example, here is a sample of first 10 time-series covariates in train, test and predicted results.
As you can see, the model is performing relatively well for 1 epoch in capture the overall trends. One can use the HyperparameterTuner in the Amazon SageMaker Python SDK to achieve the state-of-the-art results on this data.
Depending on the business objectives such as in a power station facility, when we are satisfied with how the model is performing offline, we can deploy an endpoint directly within Amazon SageMaker Notebooks as follows:
from sagemaker.mxnet import MXNetModelmodel = MXNetModel(model_data, role, entry_point='inference.py', source_dir='deep_demand_forecast', py_version='py3', framework_version='1.6.0', )predictor = model.deploy(instance_type='ml.m4.xlarge', initial_instance_count=1)
after that, we can hit the endpoint with some request_data to get predictions in a single line of code with automatic JSON serialization and de-serialization features
predictions = predictor.predict(request_data)
Thanks for reading through the article! In this blog, we demonstrated how Deep Learning models be used in Demand Forecasting applications using Amazon SageMaker for preprocessing, training, testing, and deployment. We would love to hear your opinions. Please use the GitHub issues for any questions, comments or feedback.
Last but not least, I would like to thank Vishaal Kapoor, Jonathan Chung and Adriana Simmons for their valuable feedbacks when writing this article.
Amazon SageMaker: https://docs.aws.amazon.com/sagemaker/index.html Deep demand forecasting with Amazon SageMaker: https://github.com/awslabs/sagemaker-deep-demand-forecast GluonTS: https://arxiv.org/pdf/1906.05264.pdf and https://github.com/awslabs/gluon-ts LSTNet: https://arxiv.org/pdf/1703.07015.pdf
[1]: Dua, D. and Graff, C. (2019). UCI Machine Learning Repository, Irvine, CA: University of California, School of Information and Computer Science | [
{
"code": null,
"e": 280,
"s": 172,
"text": "In this article, we explore how to use Deep Learning methods for Demand Forecasting using Amazon SageMaker."
},
{
"code": null,
"e": 414,
"s": 280,
"text": "TL;DR: The code for this project is available on GitHub with a single click AWS CloudFormation template to set up the required stack."
},
{
"code": null,
"e": 588,
"s": 414,
"text": "Demand forecasting uses historical time-series data to help streamline the supply-demand decision-making process across businesses. Examples include predicting the number of"
},
{
"code": null,
"e": 662,
"s": 588,
"text": "Customer representatives to hire for multiple locations in the next month"
},
{
"code": null,
"e": 720,
"s": 662,
"text": "Product sales across multiple regions in the next quarter"
},
{
"code": null,
"e": 786,
"s": 720,
"text": "Cloud server usage for the next day for a video streaming service"
},
{
"code": null,
"e": 850,
"s": 786,
"text": "Electricity consumption for multiple regions over the next week"
},
{
"code": null,
"e": 901,
"s": 850,
"text": "IoT devices and sensors such as energy consumption"
},
{
"code": null,
"e": 1213,
"s": 901,
"text": "Any data indexed with time is time-series data. Time-series data are categorized as univariate and multi-variate. For example, the total electricity consumption for a single household is a univariate time-series over a period of time. Here is how a univariate time-series looks like with some forecasts in green"
},
{
"code": null,
"e": 1762,
"s": 1213,
"text": "When multiple univariate time-series are stacked up on each other, it’s called multi-variate time-series. For example, total electricity consumption of 10 different (but correlated) households in a single neighborhood make up a multi-variate time-series data. Such data encapsulates more information such as being correlated in a neighborhood. Therefore, we potentially can use this shared information to get better forecasts for each of the households. The status quo approaches for time-series forecasting include Auto-Regressive methods such as"
},
{
"code": null,
"e": 1844,
"s": 1762,
"text": "Auto Regressive Integrated Moving Average (ARIMA) for univariate time-series data"
},
{
"code": null,
"e": 1908,
"s": 1844,
"text": "Vector Auto-Regression (VAR) for multi-variate time-series data"
},
{
"code": null,
"e": 2483,
"s": 1908,
"text": "One of the disadvantages of these classical methods is that they require tedious data preprocessing and feature engineering prior to model training such as incorporating various data normalization, lags, different time scales, some categorical data, dealing with missing values, etc. all usually with stationarity assumption. However, Deep Learning (DL) models can automate these steps. Moreover, it is widely known that DL methods have surpassed classical methods in areas such as Computer Vision or Natural Language Process with enough data but how about time-series data?"
},
{
"code": null,
"e": 3368,
"s": 2483,
"text": "The use of Deep Learning methods in time-series forecasting has been a major point of research in particular for (stationary/non-stationary) multi-variate time-series data. With highly optimized, dedicated frameworks such as Apache MXNet, PyTorch and TensorFlow, with fast GPU-enabled training and inference capabilities. Research indicates that DL methods outperform the aforementioned classical methods ARIMA and VAR, in particular when dealing with large volumes of (correlated) multi-variate time-series data that have categorical features and missing values. One reason is that neural network models can predict seasonality for new events since these global models learn patterns jointly over the whole dataset and can extrapolate learned regularities to new series better. One such method is LSTNet from Modeling Long- and Short-Term Temporal Patterns with Deep Neural Networks."
},
{
"code": null,
"e": 3815,
"s": 3368,
"text": "LSTNet is one of the state-of-the-art DL methods for forecasting. We have contributed it to GluonTS which currently is based on the MXNet Gluon API. The advantage of LSTNet is that it incorporates traditional auto-regressive linear models in parallel to the non-linear neural network part. This makes the non-linear DL model more robust for the time series which violates scale changes. The following is the LSTNet architecture, which contains a"
},
{
"code": null,
"e": 3973,
"s": 3815,
"text": "Convolution as the first layer, followed byRecurrent and Skip-Recurrent layersFully Connected layer combining the non-linear features and the linear features"
},
{
"code": null,
"e": 4017,
"s": 3973,
"text": "Convolution as the first layer, followed by"
},
{
"code": null,
"e": 4053,
"s": 4017,
"text": "Recurrent and Skip-Recurrent layers"
},
{
"code": null,
"e": 4133,
"s": 4053,
"text": "Fully Connected layer combining the non-linear features and the linear features"
},
{
"code": null,
"e": 4366,
"s": 4133,
"text": "For this demonstration, we will use multi-variate time-series electricity consumption data1. A cleaned version of the data is available to download directly via GluonTS. The data contains 321 time-series with 1 Hour frequency, where"
},
{
"code": null,
"e": 4444,
"s": 4366,
"text": "training data starts from 2012–01–01 00:00:00 and ends at 2014–05–26 19:00:00"
},
{
"code": null,
"e": 4531,
"s": 4444,
"text": "testing data has additional data to from 2014–05–26 19:00:00 until 2014–05–27 19:00:00"
},
{
"code": null,
"e": 4604,
"s": 4531,
"text": "Here is a snapshot of the normalized training data in a Pandas DataFrame"
},
{
"code": null,
"e": 4720,
"s": 4604,
"text": "The dataset is stored in an S3 bucket. The project that uses Amazon SageMaker has three main components as follows:"
},
{
"code": null,
"e": 5019,
"s": 4720,
"text": "Pre-processing step to normalize the data designed as a micro-service to handle heavy duty jobsTraining an LSTNet model and examine the metrics such as sMAPE for the predictions(Optional) Deploying and creating a real-time prediction HTTPS endpoint that connects to Amazon CloudWatch for monitoring"
},
{
"code": null,
"e": 5115,
"s": 5019,
"text": "Pre-processing step to normalize the data designed as a micro-service to handle heavy duty jobs"
},
{
"code": null,
"e": 5198,
"s": 5115,
"text": "Training an LSTNet model and examine the metrics such as sMAPE for the predictions"
},
{
"code": null,
"e": 5320,
"s": 5198,
"text": "(Optional) Deploying and creating a real-time prediction HTTPS endpoint that connects to Amazon CloudWatch for monitoring"
},
{
"code": null,
"e": 5461,
"s": 5320,
"text": "This complete code project is available in GitHub. Follow the instructions for a single click setup. Here is the visual architecture guide:"
},
{
"code": null,
"e": 5803,
"s": 5461,
"text": "Since we are using GluonTS, we need to train our model using an MXNet estimator by providing train.py as our entry point. For example, we train our model for 1 epoch for context_length=12 which is the training window size of 12 hours of past electricity consumption to predict for the next 6 hours prediction_length=6 as testing window size."
},
{
"code": null,
"e": 6694,
"s": 5803,
"text": "import loggingfrom sagemaker.mxnet import MXNetCONTEXT_LENGTH = 12PREDICTION_LENGTH = 6hyperparameters = { 'context_length': CONTEXT_LENGTH, 'prediction_length': PREDICTION_LENGTH, 'skip_size': 4, 'ar_window': 4, 'channels': 72, 'scaling': False, 'output_activation': 'sigmoid', 'epochs': 1,}estimator = MXNet(entry_point='train.py', source_dir='deep_demand_forecast', role=role, train_instance_count=1, train_instance_type='ml.p3.2xlarge', framework_version=\"1.6.0\", py_version='py3', hyperparameters=hyperparameters, output_path=train_output, code_location=code_location, sagemaker_session=session, container_log_level=logging.DEBUG, )estimator.fit(train_data)"
},
{
"code": null,
"e": 6766,
"s": 6694,
"text": "One of the most common evaluation metrics in time-series forecasting is"
},
{
"code": null,
"e": 6966,
"s": 6766,
"text": "Symmetric Mean Absolution Percentage Error (sMAPE) which quantifies how much the model is under-forecasting or over-forecasting where the forecast at time t is Ft and the actual value of time t is At"
},
{
"code": null,
"e": 7226,
"s": 6966,
"text": "When can visually compare it with another useful metric known as Mean Absolute Scaled Error (MASE) where the closer the values are to zero, generally the better the predictions become. We use Altair Python package to interactively examine their relationships."
},
{
"code": null,
"e": 7410,
"s": 7226,
"text": "Finally, we can interactively visualize the predictions vs. train and test data. For example, here is a sample of first 10 time-series covariates in train, test and predicted results."
},
{
"code": null,
"e": 7634,
"s": 7410,
"text": "As you can see, the model is performing relatively well for 1 epoch in capture the overall trends. One can use the HyperparameterTuner in the Amazon SageMaker Python SDK to achieve the state-of-the-art results on this data."
},
{
"code": null,
"e": 7853,
"s": 7634,
"text": "Depending on the business objectives such as in a power station facility, when we are satisfied with how the model is performing offline, we can deploy an endpoint directly within Amazon SageMaker Notebooks as follows:"
},
{
"code": null,
"e": 8225,
"s": 7853,
"text": "from sagemaker.mxnet import MXNetModelmodel = MXNetModel(model_data, role, entry_point='inference.py', source_dir='deep_demand_forecast', py_version='py3', framework_version='1.6.0', )predictor = model.deploy(instance_type='ml.m4.xlarge', initial_instance_count=1)"
},
{
"code": null,
"e": 8392,
"s": 8225,
"text": "after that, we can hit the endpoint with some request_data to get predictions in a single line of code with automatic JSON serialization and de-serialization features"
},
{
"code": null,
"e": 8438,
"s": 8392,
"text": "predictions = predictor.predict(request_data)"
},
{
"code": null,
"e": 8763,
"s": 8438,
"text": "Thanks for reading through the article! In this blog, we demonstrated how Deep Learning models be used in Demand Forecasting applications using Amazon SageMaker for preprocessing, training, testing, and deployment. We would love to hear your opinions. Please use the GitHub issues for any questions, comments or feedback."
},
{
"code": null,
"e": 8912,
"s": 8763,
"text": "Last but not least, I would like to thank Vishaal Kapoor, Jonathan Chung and Adriana Simmons for their valuable feedbacks when writing this article."
},
{
"code": null,
"e": 9215,
"s": 8912,
"text": "Amazon SageMaker: https://docs.aws.amazon.com/sagemaker/index.html Deep demand forecasting with Amazon SageMaker: https://github.com/awslabs/sagemaker-deep-demand-forecast GluonTS: https://arxiv.org/pdf/1906.05264.pdf and https://github.com/awslabs/gluon-ts LSTNet: https://arxiv.org/pdf/1703.07015.pdf"
}
] |
Java.lang.Thread Class in Java - GeeksforGeeks | 26 Apr, 2022
Thread a line of execution within a program. Each program can have multiple associated threads. Each thread has a priority which is used by the thread scheduler to determine which thread must run first. Java provides a thread class that has various method calls in order to manage the behavior of threads by providing constructors and methods to perform operations on threads.
Ways of creating threads
Creating own class which is extending to parent Thread classImplementing the Runnable interface.
Creating own class which is extending to parent Thread class
Implementing the Runnable interface.
Below are the pseudo-codes that one can refer to get a better picture about thread henceforth Thread class.
Illustration 1:
Java
// Way 1// Creating thread By Extending To Thread class class MyThread extends Thread { // Method 1 // Run() method for our thread public void run() { // Print statement System.out.println( "Thread is running created by extending to parent Thread class"); } // Method 2 // Main driver method public static void main(String[] args) { // Creating object of our thread class inside main() // method MyThread myThread = new MyThread(); // Starting the thread myThread.start(); }}
Thread is running created by extending to parent Thread class
Illustration 2:
Java
// Way 2// Creating thread using Runnable interface class ThreadUsingInterface implements Runnable { // Method 1 // run() method for the thread public void run() { // Print statement System.out.println("Thread is created using Runnable interface"); } // Method 2 // Main driver method public static void main(String[] args) { // Creating object of our thread class inside main() // method ThreadUsingInterface obj = new ThreadUsingInterface(); // Passing the object to thread in main() Thread myThread = new Thread(obj); // Starting the thread myThread.start(); }}
Thread is created using Runnable interface
A thread is a program that starts with a method() frequently used in this class only known as the start() method. This method looks out for the run() method which is also a method of this class and begins executing the bod of the run() method. here keep an eye over the sleep() method which will be discussed later below.
Note: Every class that is used as thread must implement Runnable interface and over ride it’s run method.
Syntax:
public class Thread extends Object implements Runnable
Now let us do discuss all the methods of this class are illustrated as follows:
Also do remember there are certain methods inherited from class java. lang.Object that are as follows:
equals() Method finalize() Method getClass() Method hashCode() Method notify() Method notifyAll() Method toString() Methodwait() Method
equals() Method
finalize() Method
getClass() Method
hashCode() Method
notify() Method
notifyAll() Method
toString() Method
wait() Method
Example: Java program to demonstrate usage of Thread class
Java
// Java program Demonstrating Methods of Thread class // Importing packagepackage generic; // Class 1// Helper class implementing Runnable interfaceclass Helper implements Runnable { // public void run() { // Try block to check for exceptions try { // Print statement System.out.println("thread2 going to sleep for 5000"); // Making thread sleep for 0.5 seconds Thread.sleep(5000); } // Catch block to handle exception catch (InterruptedException e) { // Print statement System.out.println("Thread2 interrupted"); } }} // Class 2// Helper class extending Runnable interfacepublic class Test implements Runnable { // Method 1 // run() method of this class public void run() { // Thread run() method } // Method 2 // Main driver method public static void main(String[] args) { // Making objects of class 1 and 2 in main() method Test obj = new Test(); Helper obj2 = new Helper(); // Creating 2 threads in main() method Thread thread1 = new Thread(obj); Thread thread2 = new Thread(obj2); // Moving thread to runnable states thread1.start(); thread2.start(); // Loading thread 1 in class 1 ClassLoader loader = thread1.getContextClassLoader(); // Creating 3rd thread in main() method Thread thread3 = new Thread(new Helper()); // Getting number of active threads System.out.println(Thread.activeCount()); thread1.checkAccess(); // Fetching an instance of this thread Thread t = Thread.currentThread(); // Print and display commands System.out.println(t.getName()); System.out.println("Thread1 name: " + thread1.getName()); System.out.println("Thread1 ID: " + thread1.getId()); // Fetching the priority and state of thread1 System.out.println("Priority of thread1 = " + thread1.getPriority()); // Getting the state of thread 1 using getState() method // and printing the same System.out.println(thread1.getState()); thread2 = new Thread(obj2); thread2.start(); thread2.interrupt(); System.out.println("Is thread2 interrupted? " + thread2.interrupted() ); System.out.println("Is thread2 alive? " + thread2.isAlive()); thread1 = new Thread(obj); thread1.setDaemon(true); System.out.println("Is thread1 a daemon thread? " + thread1.isDaemon()); System.out.println("Is thread1 interrupted? " + thread1.isInterrupted()); // Waiting for thread2 to complete its execution System.out.println("thread1 waiting for thread2 to join"); try { thread2.join(); } catch (InterruptedException e) { // Display the exception along with line number // using printStackTrace() method e.printStackTrace(); } // Now setting the name of thread1 thread1.setName("child thread xyz"); // Print and display command System.out.println("New name set for thread 1" + thread1.getName()); // Setting the priority of thread1 thread1.setPriority(5); thread2.yield(); // Fetching the string representation of thread1 System.out.println(thread1.toString()); // Getting list of active thread in current thread's group Thread[] tarray = new Thread[3]; Thread.enumerate(tarray); // Display commands System.out.println("List of active threads:"); System.out.printf("["); // Looking out using for each loop for (Thread thread : tarray) { System.out.println(thread); } // Display commands System.out.printf("]\n"); System.out.println(Thread.getAllStackTraces()); ClassLoader classLoader = thread1.getContextClassLoader(); System.out.println(classLoader.toString()); System.out.println(thread1.getDefaultUncaughtExceptionHandler()); thread2.setUncaughtExceptionHandler(thread1.getDefaultUncaughtExceptionHandler()); thread1.setContextClassLoader(thread2.getContextClassLoader()); thread1.setDefaultUncaughtExceptionHandler(thread2.getUncaughtExceptionHandler()); thread1 = new Thread(obj); StackTraceElement[] trace = thread1.getStackTrace(); System.out.println("Printing stack trace elements for thread1:"); for (StackTraceElement e : trace) { System.out.println(e); } ThreadGroup grp = thread1.getThreadGroup(); System.out.println("ThreadGroup to which thread1 belongs " + grp.toString()); System.out.println(thread1.getUncaughtExceptionHandler()); System.out.println("Does thread1 holds Lock? " + thread1.holdsLock(obj2)); Thread.dumpStack(); }}
Output:
3
main
Thread1 name: Thread-0
Thread1 ID: 10
Priority of thread1 = 5
RUNNABLE
Is thread2 interrupted? false
Is thread2 alive? true
Is thread1 a daemon thread? true
Is thread1 interrupted? false
thread1 waiting for thread2 to join
thread2 going to sleep for 5000 ms
thread2 going to sleep for 5000 ms
Thread2 interrupted
New name set for thread 1child thread xyz
Thread[child thread xyz, 5, main]
List of active threads:
[Thread[main, 5, main]
Thread[Thread-1, 5, main]
null
]
{Thread[Signal Dispatcher, 9, system]=[Ljava.lang.StackTraceElement;@33909752,
Thread[Thread-1, 5, main]=[Ljava.lang.StackTraceElement;@55f96302,
Thread[main, 5, main]=[Ljava.lang.StackTraceElement;@3d4eac69,
Thread[Attach Listener, 5, system]=[Ljava.lang.StackTraceElement;@42a57993,
Thread[Finalizer, 8, system]=[Ljava.lang.StackTraceElement;@75b84c92,
Thread[Reference Handler, 10, system]=[Ljava.lang.StackTraceElement;@6bc7c054}
sun.misc.Launcher$AppClassLoader@73d16e93
null
Printing stack trace elements for thread1:
ThreadGroup to which thread1 belongs java.lang.ThreadGroup[name=main, maxpri=10]
java.lang.ThreadGroup[name=main, maxpri=10]
Does thread1 holds Lock? false
java.lang.Exception: Stack trace
at java.lang.Thread.dumpStack(Unknown Source)
at generic.Test.main(Test.java:111)
This article is contributed by Mayank Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
solankimayank
sweetyty
gabaa406
codeviking
kashishsoda
singghakshay
nishkarshgandhi
simranarora5sos
surinderdawra388
simmytarika5
Java-lang package
Java-Multithreading
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Arrays.sort() in Java with examples
Reverse a string in Java
Initialize an ArrayList in Java
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Interfaces in Java
ArrayList in Java | [
{
"code": null,
"e": 23952,
"s": 23924,
"text": "\n26 Apr, 2022"
},
{
"code": null,
"e": 24330,
"s": 23952,
"text": "Thread a line of execution within a program. Each program can have multiple associated threads. Each thread has a priority which is used by the thread scheduler to determine which thread must run first. Java provides a thread class that has various method calls in order to manage the behavior of threads by providing constructors and methods to perform operations on threads. "
},
{
"code": null,
"e": 24355,
"s": 24330,
"text": "Ways of creating threads"
},
{
"code": null,
"e": 24452,
"s": 24355,
"text": "Creating own class which is extending to parent Thread classImplementing the Runnable interface."
},
{
"code": null,
"e": 24513,
"s": 24452,
"text": "Creating own class which is extending to parent Thread class"
},
{
"code": null,
"e": 24550,
"s": 24513,
"text": "Implementing the Runnable interface."
},
{
"code": null,
"e": 24658,
"s": 24550,
"text": "Below are the pseudo-codes that one can refer to get a better picture about thread henceforth Thread class."
},
{
"code": null,
"e": 24674,
"s": 24658,
"text": "Illustration 1:"
},
{
"code": null,
"e": 24679,
"s": 24674,
"text": "Java"
},
{
"code": "// Way 1// Creating thread By Extending To Thread class class MyThread extends Thread { // Method 1 // Run() method for our thread public void run() { // Print statement System.out.println( \"Thread is running created by extending to parent Thread class\"); } // Method 2 // Main driver method public static void main(String[] args) { // Creating object of our thread class inside main() // method MyThread myThread = new MyThread(); // Starting the thread myThread.start(); }}",
"e": 25256,
"s": 24679,
"text": null
},
{
"code": null,
"e": 25318,
"s": 25256,
"text": "Thread is running created by extending to parent Thread class"
},
{
"code": null,
"e": 25334,
"s": 25318,
"text": "Illustration 2:"
},
{
"code": null,
"e": 25339,
"s": 25334,
"text": "Java"
},
{
"code": "// Way 2// Creating thread using Runnable interface class ThreadUsingInterface implements Runnable { // Method 1 // run() method for the thread public void run() { // Print statement System.out.println(\"Thread is created using Runnable interface\"); } // Method 2 // Main driver method public static void main(String[] args) { // Creating object of our thread class inside main() // method ThreadUsingInterface obj = new ThreadUsingInterface(); // Passing the object to thread in main() Thread myThread = new Thread(obj); // Starting the thread myThread.start(); }}",
"e": 26015,
"s": 25339,
"text": null
},
{
"code": null,
"e": 26058,
"s": 26015,
"text": "Thread is created using Runnable interface"
},
{
"code": null,
"e": 26380,
"s": 26058,
"text": "A thread is a program that starts with a method() frequently used in this class only known as the start() method. This method looks out for the run() method which is also a method of this class and begins executing the bod of the run() method. here keep an eye over the sleep() method which will be discussed later below."
},
{
"code": null,
"e": 26486,
"s": 26380,
"text": "Note: Every class that is used as thread must implement Runnable interface and over ride it’s run method."
},
{
"code": null,
"e": 26495,
"s": 26486,
"text": "Syntax: "
},
{
"code": null,
"e": 26550,
"s": 26495,
"text": "public class Thread extends Object implements Runnable"
},
{
"code": null,
"e": 26630,
"s": 26550,
"text": "Now let us do discuss all the methods of this class are illustrated as follows:"
},
{
"code": null,
"e": 26734,
"s": 26630,
"text": "Also do remember there are certain methods inherited from class java. lang.Object that are as follows: "
},
{
"code": null,
"e": 26870,
"s": 26734,
"text": "equals() Method finalize() Method getClass() Method hashCode() Method notify() Method notifyAll() Method toString() Methodwait() Method"
},
{
"code": null,
"e": 26887,
"s": 26870,
"text": "equals() Method "
},
{
"code": null,
"e": 26906,
"s": 26887,
"text": "finalize() Method "
},
{
"code": null,
"e": 26925,
"s": 26906,
"text": "getClass() Method "
},
{
"code": null,
"e": 26944,
"s": 26925,
"text": "hashCode() Method "
},
{
"code": null,
"e": 26961,
"s": 26944,
"text": "notify() Method "
},
{
"code": null,
"e": 26981,
"s": 26961,
"text": "notifyAll() Method "
},
{
"code": null,
"e": 26999,
"s": 26981,
"text": "toString() Method"
},
{
"code": null,
"e": 27013,
"s": 26999,
"text": "wait() Method"
},
{
"code": null,
"e": 27073,
"s": 27013,
"text": "Example: Java program to demonstrate usage of Thread class "
},
{
"code": null,
"e": 27078,
"s": 27073,
"text": "Java"
},
{
"code": "// Java program Demonstrating Methods of Thread class // Importing packagepackage generic; // Class 1// Helper class implementing Runnable interfaceclass Helper implements Runnable { // public void run() { // Try block to check for exceptions try { // Print statement System.out.println(\"thread2 going to sleep for 5000\"); // Making thread sleep for 0.5 seconds Thread.sleep(5000); } // Catch block to handle exception catch (InterruptedException e) { // Print statement System.out.println(\"Thread2 interrupted\"); } }} // Class 2// Helper class extending Runnable interfacepublic class Test implements Runnable { // Method 1 // run() method of this class public void run() { // Thread run() method } // Method 2 // Main driver method public static void main(String[] args) { // Making objects of class 1 and 2 in main() method Test obj = new Test(); Helper obj2 = new Helper(); // Creating 2 threads in main() method Thread thread1 = new Thread(obj); Thread thread2 = new Thread(obj2); // Moving thread to runnable states thread1.start(); thread2.start(); // Loading thread 1 in class 1 ClassLoader loader = thread1.getContextClassLoader(); // Creating 3rd thread in main() method Thread thread3 = new Thread(new Helper()); // Getting number of active threads System.out.println(Thread.activeCount()); thread1.checkAccess(); // Fetching an instance of this thread Thread t = Thread.currentThread(); // Print and display commands System.out.println(t.getName()); System.out.println(\"Thread1 name: \" + thread1.getName()); System.out.println(\"Thread1 ID: \" + thread1.getId()); // Fetching the priority and state of thread1 System.out.println(\"Priority of thread1 = \" + thread1.getPriority()); // Getting the state of thread 1 using getState() method // and printing the same System.out.println(thread1.getState()); thread2 = new Thread(obj2); thread2.start(); thread2.interrupt(); System.out.println(\"Is thread2 interrupted? \" + thread2.interrupted() ); System.out.println(\"Is thread2 alive? \" + thread2.isAlive()); thread1 = new Thread(obj); thread1.setDaemon(true); System.out.println(\"Is thread1 a daemon thread? \" + thread1.isDaemon()); System.out.println(\"Is thread1 interrupted? \" + thread1.isInterrupted()); // Waiting for thread2 to complete its execution System.out.println(\"thread1 waiting for thread2 to join\"); try { thread2.join(); } catch (InterruptedException e) { // Display the exception along with line number // using printStackTrace() method e.printStackTrace(); } // Now setting the name of thread1 thread1.setName(\"child thread xyz\"); // Print and display command System.out.println(\"New name set for thread 1\" + thread1.getName()); // Setting the priority of thread1 thread1.setPriority(5); thread2.yield(); // Fetching the string representation of thread1 System.out.println(thread1.toString()); // Getting list of active thread in current thread's group Thread[] tarray = new Thread[3]; Thread.enumerate(tarray); // Display commands System.out.println(\"List of active threads:\"); System.out.printf(\"[\"); // Looking out using for each loop for (Thread thread : tarray) { System.out.println(thread); } // Display commands System.out.printf(\"]\\n\"); System.out.println(Thread.getAllStackTraces()); ClassLoader classLoader = thread1.getContextClassLoader(); System.out.println(classLoader.toString()); System.out.println(thread1.getDefaultUncaughtExceptionHandler()); thread2.setUncaughtExceptionHandler(thread1.getDefaultUncaughtExceptionHandler()); thread1.setContextClassLoader(thread2.getContextClassLoader()); thread1.setDefaultUncaughtExceptionHandler(thread2.getUncaughtExceptionHandler()); thread1 = new Thread(obj); StackTraceElement[] trace = thread1.getStackTrace(); System.out.println(\"Printing stack trace elements for thread1:\"); for (StackTraceElement e : trace) { System.out.println(e); } ThreadGroup grp = thread1.getThreadGroup(); System.out.println(\"ThreadGroup to which thread1 belongs \" + grp.toString()); System.out.println(thread1.getUncaughtExceptionHandler()); System.out.println(\"Does thread1 holds Lock? \" + thread1.holdsLock(obj2)); Thread.dumpStack(); }}",
"e": 31994,
"s": 27078,
"text": null
},
{
"code": null,
"e": 32003,
"s": 31994,
"text": "Output: "
},
{
"code": null,
"e": 33288,
"s": 32003,
"text": "3\nmain\nThread1 name: Thread-0\nThread1 ID: 10\nPriority of thread1 = 5\nRUNNABLE\nIs thread2 interrupted? false\nIs thread2 alive? true\nIs thread1 a daemon thread? true\nIs thread1 interrupted? false\nthread1 waiting for thread2 to join\nthread2 going to sleep for 5000 ms\nthread2 going to sleep for 5000 ms\nThread2 interrupted\nNew name set for thread 1child thread xyz\nThread[child thread xyz, 5, main]\nList of active threads:\n[Thread[main, 5, main]\nThread[Thread-1, 5, main]\nnull\n]\n{Thread[Signal Dispatcher, 9, system]=[Ljava.lang.StackTraceElement;@33909752, \nThread[Thread-1, 5, main]=[Ljava.lang.StackTraceElement;@55f96302, \nThread[main, 5, main]=[Ljava.lang.StackTraceElement;@3d4eac69, \nThread[Attach Listener, 5, system]=[Ljava.lang.StackTraceElement;@42a57993, \nThread[Finalizer, 8, system]=[Ljava.lang.StackTraceElement;@75b84c92, \nThread[Reference Handler, 10, system]=[Ljava.lang.StackTraceElement;@6bc7c054}\nsun.misc.Launcher$AppClassLoader@73d16e93\nnull\nPrinting stack trace elements for thread1:\nThreadGroup to which thread1 belongs java.lang.ThreadGroup[name=main, maxpri=10]\njava.lang.ThreadGroup[name=main, maxpri=10]\nDoes thread1 holds Lock? false\njava.lang.Exception: Stack trace\n at java.lang.Thread.dumpStack(Unknown Source)\n at generic.Test.main(Test.java:111) "
},
{
"code": null,
"e": 33710,
"s": 33288,
"text": "This article is contributed by Mayank Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 33724,
"s": 33710,
"text": "solankimayank"
},
{
"code": null,
"e": 33733,
"s": 33724,
"text": "sweetyty"
},
{
"code": null,
"e": 33742,
"s": 33733,
"text": "gabaa406"
},
{
"code": null,
"e": 33753,
"s": 33742,
"text": "codeviking"
},
{
"code": null,
"e": 33765,
"s": 33753,
"text": "kashishsoda"
},
{
"code": null,
"e": 33778,
"s": 33765,
"text": "singghakshay"
},
{
"code": null,
"e": 33794,
"s": 33778,
"text": "nishkarshgandhi"
},
{
"code": null,
"e": 33810,
"s": 33794,
"text": "simranarora5sos"
},
{
"code": null,
"e": 33827,
"s": 33810,
"text": "surinderdawra388"
},
{
"code": null,
"e": 33840,
"s": 33827,
"text": "simmytarika5"
},
{
"code": null,
"e": 33858,
"s": 33840,
"text": "Java-lang package"
},
{
"code": null,
"e": 33878,
"s": 33858,
"text": "Java-Multithreading"
},
{
"code": null,
"e": 33883,
"s": 33878,
"text": "Java"
},
{
"code": null,
"e": 33888,
"s": 33883,
"text": "Java"
},
{
"code": null,
"e": 33986,
"s": 33888,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34001,
"s": 33986,
"text": "Arrays in Java"
},
{
"code": null,
"e": 34045,
"s": 34001,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 34067,
"s": 34045,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 34103,
"s": 34067,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 34128,
"s": 34103,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 34160,
"s": 34128,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 34211,
"s": 34160,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 34241,
"s": 34211,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 34260,
"s": 34241,
"text": "Interfaces in Java"
}
] |
Abstract Factory Pattern - GeeksforGeeks | 13 Oct, 2021
Introduction
Abstract Factory design pattern is one of the Creational pattern. Abstract Factory pattern is almost similar to Factory Pattern is considered as another layer of abstraction over factory pattern. Abstract Factory patterns work around a super-factory which creates other factories.Abstract factory pattern implementation provides us with a framework that allows us to create objects that follow a general pattern. So at runtime, the abstract factory is coupled with any desired concrete factory which can create objects of the desired type.Let see the GOFs representation of Abstract Factory Pattern :
UML class diagram example for the Abstract Factory Design Pattern.
AbstractFactory: Declares an interface for operations that create abstract product objects.
ConcreteFactory: Implements the operations declared in the AbstractFactory to create concrete product objects.
Product: Defines a product object to be created by the corresponding concrete factory and implements the AbstractProduct interface.
Client: Uses only interfaces declared by AbstractFactory and AbstractProduct classes.
Abstract Factory provides interfaces for creating families of related or dependent objects without specifying their concrete classes.Client software creates a concrete implementation of the abstract factory and then uses the generic interfaces to create the concrete objects that are part of the family of objects. The client does not know or care which concrete objects it gets from each of these concrete factories since it uses only the generic interfaces of their products.So with this idea of Abstract Factory pattern, we will now try to create a design that will facilitate the creation of related objects.
Implementation
Let’s take an example, Suppose we want to build a global car factory. If it was a factory design pattern, then it was suitable for a single location. But for this pattern, we need multiple locations and some critical design changes.We need car factories in each location like IndiaCarFactory, USACarFactory, and DefaultCarFactory. Now, our application should be smart enough to identify the location where it is being used, so we should be able to use the appropriate car factory without even knowing which car factory implementation will be used internally. This also saves us from someone calling the wrong factory for a particular location.Here we need another layer of abstraction that will identify the location and internally use correct car factory implementation without even giving a single hint to the user. This is exactly the problem, which an abstract factory pattern is used to solve.
Java
// Java Program to demonstrate the// working of Abstract Factory Pattern enum CarType{ MICRO, MINI, LUXURY} abstract class Car{ Car(CarType model, Location location) { this.model = model; this.location = location; } abstract void construct(); CarType model = null; Location location = null; CarType getModel() { return model; } void setModel(CarType model) { this.model = model; } Location getLocation() { return location; } void setLocation(Location location) { this.location = location; } @Override public String toString() { return "CarModel - "+model + " located in "+location; }} class LuxuryCar extends Car{ LuxuryCar(Location location) { super(CarType.LUXURY, location); construct(); } @Override protected void construct() { System.out.println("Connecting to luxury car"); }} class MicroCar extends Car{ MicroCar(Location location) { super(CarType.MICRO, location); construct(); } @Override protected void construct() { System.out.println("Connecting to Micro Car "); }} class MiniCar extends Car{ MiniCar(Location location) { super(CarType.MINI,location ); construct(); } @Override void construct() { System.out.println("Connecting to Mini car"); }} enum Location{ DEFAULT, USA, INDIA} class INDIACarFactory{ static Car buildCar(CarType model) { Car car = null; switch (model) { case MICRO: car = new MicroCar(Location.INDIA); break; case MINI: car = new MiniCar(Location.INDIA); break; case LUXURY: car = new LuxuryCar(Location.INDIA); break; default: break; } return car; }} class DefaultCarFactory{ public static Car buildCar(CarType model) { Car car = null; switch (model) { case MICRO: car = new MicroCar(Location.DEFAULT); break; case MINI: car = new MiniCar(Location.DEFAULT); break; case LUXURY: car = new LuxuryCar(Location.DEFAULT); break; default: break; } return car; }} class USACarFactory{ public static Car buildCar(CarType model) { Car car = null; switch (model) { case MICRO: car = new MicroCar(Location.USA); break; case MINI: car = new MiniCar(Location.USA); break; case LUXURY: car = new LuxuryCar(Location.USA); break; default: break; } return car; }} class CarFactory{ private CarFactory() { } public static Car buildCar(CarType type) { Car car = null; // We can add any GPS Function here which // read location property somewhere from configuration // and use location specific car factory // Currently I'm just using INDIA as Location Location location = Location.INDIA; switch(location) { case USA: car = USACarFactory.buildCar(type); break; case INDIA: car = INDIACarFactory.buildCar(type); break; default: car = DefaultCarFactory.buildCar(type); } return car; }} class AbstractDesign{ public static void main(String[] args) { System.out.println(CarFactory.buildCar(CarType.MICRO)); System.out.println(CarFactory.buildCar(CarType.MINI)); System.out.println(CarFactory.buildCar(CarType.LUXURY)); }}
Output :
Connecting to Micro Car
CarModel - MICRO located in INDIA
Connecting to Mini car
CarModel - MINI located in INDIA
Connecting to luxury car
CarModel - LUXURY located in INDIA
Difference
The main difference between a “factory method” and an “abstract factory” is that the factory method is a single method, and an abstract factory is an object.
The factory method is just a method, it can be overridden in a subclass, whereas the abstract factory is an object that has multiple factory methods on it.
The Factory Method pattern uses inheritance and relies on a subclass to handle the desired object instantiation.
Advantages: This pattern is particularly useful when the client doesn’t know exactly what type to create.
Isolation of concrete classes: The Abstract Factory pattern helps you control the classes of objects that an application creates. Because a factory encapsulates the responsibility and the process of creating product objects, it isolates clients from implementation classes. Clients manipulate instances through their abstract interfaces. Product class names are isolated in the implementation of the concrete factory; they do not appear in client code.
Exchanging Product Families easily: The class of a concrete factory appears only once in an application, that is where it’s instantiated. This makes it easy to change the concrete factory an application uses. It can use various product configurations simply by changing the concrete factory. Because an abstract factory creates a complete family of products, the whole product family changes at once.
Promoting consistency among products: When product objects in a family are designed to work together, it’s important that an application use objects from only one family at a time. AbstractFactory makes this easy to enforce.n.
Disadvantages
Difficult to support new kinds of products: Extending abstract factories to produce new kinds of Products isn’t easy. That’s because the AbstractFactory interface fixes the set of products that can be created. Supporting new kinds of products requires extending the factory interface, which involves changing the AbstractFactory class and all of its subclasses.
Somewhat the above example is also based on How the Cabs like uber and ola function on the large scale.Further Read: Abstract Factory Method in PythonThis article is contributed by Saket Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Pushpender007
Design Pattern
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
SDE SHEET - A Complete Guide for SDE Preparation
Factory method design pattern in Java
Unified Modeling Language (UML) | An Introduction
MVC Design Pattern
Builder Design Pattern
Unified Modeling Language (UML) | Activity Diagrams
Unified Modeling Language (UML) | State Diagrams
Introduction of Programming Paradigms
Monolithic vs Microservices architecture
How to design a parking lot using object-oriented principles? | [
{
"code": null,
"e": 24292,
"s": 24264,
"text": "\n13 Oct, 2021"
},
{
"code": null,
"e": 24305,
"s": 24292,
"text": "Introduction"
},
{
"code": null,
"e": 24908,
"s": 24305,
"text": "Abstract Factory design pattern is one of the Creational pattern. Abstract Factory pattern is almost similar to Factory Pattern is considered as another layer of abstraction over factory pattern. Abstract Factory patterns work around a super-factory which creates other factories.Abstract factory pattern implementation provides us with a framework that allows us to create objects that follow a general pattern. So at runtime, the abstract factory is coupled with any desired concrete factory which can create objects of the desired type.Let see the GOFs representation of Abstract Factory Pattern : "
},
{
"code": null,
"e": 24977,
"s": 24908,
"text": "UML class diagram example for the Abstract Factory Design Pattern. "
},
{
"code": null,
"e": 25070,
"s": 24977,
"text": "AbstractFactory: Declares an interface for operations that create abstract product objects. "
},
{
"code": null,
"e": 25181,
"s": 25070,
"text": "ConcreteFactory: Implements the operations declared in the AbstractFactory to create concrete product objects."
},
{
"code": null,
"e": 25313,
"s": 25181,
"text": "Product: Defines a product object to be created by the corresponding concrete factory and implements the AbstractProduct interface."
},
{
"code": null,
"e": 25399,
"s": 25313,
"text": "Client: Uses only interfaces declared by AbstractFactory and AbstractProduct classes."
},
{
"code": null,
"e": 26014,
"s": 25399,
"text": "Abstract Factory provides interfaces for creating families of related or dependent objects without specifying their concrete classes.Client software creates a concrete implementation of the abstract factory and then uses the generic interfaces to create the concrete objects that are part of the family of objects. The client does not know or care which concrete objects it gets from each of these concrete factories since it uses only the generic interfaces of their products.So with this idea of Abstract Factory pattern, we will now try to create a design that will facilitate the creation of related objects. "
},
{
"code": null,
"e": 26029,
"s": 26014,
"text": "Implementation"
},
{
"code": null,
"e": 26929,
"s": 26029,
"text": "Let’s take an example, Suppose we want to build a global car factory. If it was a factory design pattern, then it was suitable for a single location. But for this pattern, we need multiple locations and some critical design changes.We need car factories in each location like IndiaCarFactory, USACarFactory, and DefaultCarFactory. Now, our application should be smart enough to identify the location where it is being used, so we should be able to use the appropriate car factory without even knowing which car factory implementation will be used internally. This also saves us from someone calling the wrong factory for a particular location.Here we need another layer of abstraction that will identify the location and internally use correct car factory implementation without even giving a single hint to the user. This is exactly the problem, which an abstract factory pattern is used to solve. "
},
{
"code": null,
"e": 26934,
"s": 26929,
"text": "Java"
},
{
"code": "// Java Program to demonstrate the// working of Abstract Factory Pattern enum CarType{ MICRO, MINI, LUXURY} abstract class Car{ Car(CarType model, Location location) { this.model = model; this.location = location; } abstract void construct(); CarType model = null; Location location = null; CarType getModel() { return model; } void setModel(CarType model) { this.model = model; } Location getLocation() { return location; } void setLocation(Location location) { this.location = location; } @Override public String toString() { return \"CarModel - \"+model + \" located in \"+location; }} class LuxuryCar extends Car{ LuxuryCar(Location location) { super(CarType.LUXURY, location); construct(); } @Override protected void construct() { System.out.println(\"Connecting to luxury car\"); }} class MicroCar extends Car{ MicroCar(Location location) { super(CarType.MICRO, location); construct(); } @Override protected void construct() { System.out.println(\"Connecting to Micro Car \"); }} class MiniCar extends Car{ MiniCar(Location location) { super(CarType.MINI,location ); construct(); } @Override void construct() { System.out.println(\"Connecting to Mini car\"); }} enum Location{ DEFAULT, USA, INDIA} class INDIACarFactory{ static Car buildCar(CarType model) { Car car = null; switch (model) { case MICRO: car = new MicroCar(Location.INDIA); break; case MINI: car = new MiniCar(Location.INDIA); break; case LUXURY: car = new LuxuryCar(Location.INDIA); break; default: break; } return car; }} class DefaultCarFactory{ public static Car buildCar(CarType model) { Car car = null; switch (model) { case MICRO: car = new MicroCar(Location.DEFAULT); break; case MINI: car = new MiniCar(Location.DEFAULT); break; case LUXURY: car = new LuxuryCar(Location.DEFAULT); break; default: break; } return car; }} class USACarFactory{ public static Car buildCar(CarType model) { Car car = null; switch (model) { case MICRO: car = new MicroCar(Location.USA); break; case MINI: car = new MiniCar(Location.USA); break; case LUXURY: car = new LuxuryCar(Location.USA); break; default: break; } return car; }} class CarFactory{ private CarFactory() { } public static Car buildCar(CarType type) { Car car = null; // We can add any GPS Function here which // read location property somewhere from configuration // and use location specific car factory // Currently I'm just using INDIA as Location Location location = Location.INDIA; switch(location) { case USA: car = USACarFactory.buildCar(type); break; case INDIA: car = INDIACarFactory.buildCar(type); break; default: car = DefaultCarFactory.buildCar(type); } return car; }} class AbstractDesign{ public static void main(String[] args) { System.out.println(CarFactory.buildCar(CarType.MICRO)); System.out.println(CarFactory.buildCar(CarType.MINI)); System.out.println(CarFactory.buildCar(CarType.LUXURY)); }}",
"e": 31097,
"s": 26934,
"text": null
},
{
"code": null,
"e": 31108,
"s": 31097,
"text": "Output : "
},
{
"code": null,
"e": 31283,
"s": 31108,
"text": "Connecting to Micro Car \nCarModel - MICRO located in INDIA\nConnecting to Mini car\nCarModel - MINI located in INDIA\nConnecting to luxury car\nCarModel - LUXURY located in INDIA"
},
{
"code": null,
"e": 31296,
"s": 31285,
"text": "Difference"
},
{
"code": null,
"e": 31455,
"s": 31296,
"text": "The main difference between a “factory method” and an “abstract factory” is that the factory method is a single method, and an abstract factory is an object. "
},
{
"code": null,
"e": 31611,
"s": 31455,
"text": "The factory method is just a method, it can be overridden in a subclass, whereas the abstract factory is an object that has multiple factory methods on it."
},
{
"code": null,
"e": 31724,
"s": 31611,
"text": "The Factory Method pattern uses inheritance and relies on a subclass to handle the desired object instantiation."
},
{
"code": null,
"e": 31831,
"s": 31724,
"text": "Advantages: This pattern is particularly useful when the client doesn’t know exactly what type to create. "
},
{
"code": null,
"e": 32284,
"s": 31831,
"text": "Isolation of concrete classes: The Abstract Factory pattern helps you control the classes of objects that an application creates. Because a factory encapsulates the responsibility and the process of creating product objects, it isolates clients from implementation classes. Clients manipulate instances through their abstract interfaces. Product class names are isolated in the implementation of the concrete factory; they do not appear in client code."
},
{
"code": null,
"e": 32685,
"s": 32284,
"text": "Exchanging Product Families easily: The class of a concrete factory appears only once in an application, that is where it’s instantiated. This makes it easy to change the concrete factory an application uses. It can use various product configurations simply by changing the concrete factory. Because an abstract factory creates a complete family of products, the whole product family changes at once."
},
{
"code": null,
"e": 32912,
"s": 32685,
"text": "Promoting consistency among products: When product objects in a family are designed to work together, it’s important that an application use objects from only one family at a time. AbstractFactory makes this easy to enforce.n."
},
{
"code": null,
"e": 32926,
"s": 32912,
"text": "Disadvantages"
},
{
"code": null,
"e": 33288,
"s": 32926,
"text": "Difficult to support new kinds of products: Extending abstract factories to produce new kinds of Products isn’t easy. That’s because the AbstractFactory interface fixes the set of products that can be created. Supporting new kinds of products requires extending the factory interface, which involves changing the AbstractFactory class and all of its subclasses."
},
{
"code": null,
"e": 33858,
"s": 33288,
"text": "Somewhat the above example is also based on How the Cabs like uber and ola function on the large scale.Further Read: Abstract Factory Method in PythonThis article is contributed by Saket Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 33872,
"s": 33858,
"text": "Pushpender007"
},
{
"code": null,
"e": 33887,
"s": 33872,
"text": "Design Pattern"
},
{
"code": null,
"e": 33985,
"s": 33887,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33994,
"s": 33985,
"text": "Comments"
},
{
"code": null,
"e": 34007,
"s": 33994,
"text": "Old Comments"
},
{
"code": null,
"e": 34056,
"s": 34007,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 34094,
"s": 34056,
"text": "Factory method design pattern in Java"
},
{
"code": null,
"e": 34144,
"s": 34094,
"text": "Unified Modeling Language (UML) | An Introduction"
},
{
"code": null,
"e": 34163,
"s": 34144,
"text": "MVC Design Pattern"
},
{
"code": null,
"e": 34186,
"s": 34163,
"text": "Builder Design Pattern"
},
{
"code": null,
"e": 34238,
"s": 34186,
"text": "Unified Modeling Language (UML) | Activity Diagrams"
},
{
"code": null,
"e": 34287,
"s": 34238,
"text": "Unified Modeling Language (UML) | State Diagrams"
},
{
"code": null,
"e": 34325,
"s": 34287,
"text": "Introduction of Programming Paradigms"
},
{
"code": null,
"e": 34366,
"s": 34325,
"text": "Monolithic vs Microservices architecture"
}
] |
Python PIL | getbands() and getextrema() method - GeeksforGeeks | 16 Aug, 2021
Python PIL library contains Image module in which variety of functions are defined. PIL.Image.Image.getbands() This method is used to get the mode (bands) present in an image.
Syntax: PIL.Image.Image.getbands(image_object [valid image path])Parameters: It takes a parameter image_object i.e it the reference of the image which is opened using open() method or image path can also be mentioned.Return value: Returns a tuple containing the name of each band in this image. For example, getbands on an RGB image returns (“R”, “G”, “B”).
Python3
# Importing Image module from PIL packagefrom PIL import Image # Opening a multiband imageim = Image.open(r"C:\Users\Admin\Pictures\images.png") # This returns the bands used in im (image)im1 = Image.Image.getbands(im) print("Multiband image", im1) # Opening a single band imageim2 = Image.open(r"C:\Users\Admin\Pictures\singleband.png") # This returns the band used in im2im3 = Image.Image.getbands(im2) print("Single band image", im3)
Output:
Multiband image ('R', 'G', 'B')
Single band image ('P', )
Gets the minimum and maximum pixel values for each band in the image.
Syntax: PIL.Image.Image.getextrema(image_object [valid image path])Parameters: It takes a parameter image_object i.e it the reference of the image which is opened using open() method or image path can also be mentioned.Return Value: For a single-band image, a 2-tuple containing the minimum and maximum pixel value. For a multi-band image, a tuple containing one 2-tuple for each band.
Python3
# importing Image module from PIL packagefrom PIL import Image # opening a multiband imageim = Image.open(r"C:\Users\Admin\Pictures\download.png") # getting maximum and minimum pixels of# multiband images (RBG)im1 = Image.Image.getextrema(im) print("Multi band image ", im1) # Opening a single band imageim2 = Image.open(r"C:\Users\Admin\Pictures\singleband.png") # getting maximum and minimum pixels of# single band imageim3 = Image.Image.getextrema(im2) print("Single band image ", im3)
Output:
Multi band image ((73, 255), (0, 255), (0, 255))
Single band image (0, 123)
These images used in above article –Multiband Images
Single band Image
Akanksha_Rai
sumitgumber28
Image-Processing
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Python program to convert a list to string
Reading and Writing to text files in Python | [
{
"code": null,
"e": 24406,
"s": 24378,
"text": "\n16 Aug, 2021"
},
{
"code": null,
"e": 24583,
"s": 24406,
"text": "Python PIL library contains Image module in which variety of functions are defined. PIL.Image.Image.getbands() This method is used to get the mode (bands) present in an image. "
},
{
"code": null,
"e": 24941,
"s": 24583,
"text": "Syntax: PIL.Image.Image.getbands(image_object [valid image path])Parameters: It takes a parameter image_object i.e it the reference of the image which is opened using open() method or image path can also be mentioned.Return value: Returns a tuple containing the name of each band in this image. For example, getbands on an RGB image returns (“R”, “G”, “B”)."
},
{
"code": null,
"e": 24951,
"s": 24943,
"text": "Python3"
},
{
"code": "# Importing Image module from PIL packagefrom PIL import Image # Opening a multiband imageim = Image.open(r\"C:\\Users\\Admin\\Pictures\\images.png\") # This returns the bands used in im (image)im1 = Image.Image.getbands(im) print(\"Multiband image\", im1) # Opening a single band imageim2 = Image.open(r\"C:\\Users\\Admin\\Pictures\\singleband.png\") # This returns the band used in im2im3 = Image.Image.getbands(im2) print(\"Single band image\", im3)",
"e": 25388,
"s": 24951,
"text": null
},
{
"code": null,
"e": 25398,
"s": 25388,
"text": "Output: "
},
{
"code": null,
"e": 25456,
"s": 25398,
"text": "Multiband image ('R', 'G', 'B')\nSingle band image ('P', )"
},
{
"code": null,
"e": 25529,
"s": 25458,
"text": "Gets the minimum and maximum pixel values for each band in the image. "
},
{
"code": null,
"e": 25915,
"s": 25529,
"text": "Syntax: PIL.Image.Image.getextrema(image_object [valid image path])Parameters: It takes a parameter image_object i.e it the reference of the image which is opened using open() method or image path can also be mentioned.Return Value: For a single-band image, a 2-tuple containing the minimum and maximum pixel value. For a multi-band image, a tuple containing one 2-tuple for each band."
},
{
"code": null,
"e": 25925,
"s": 25917,
"text": "Python3"
},
{
"code": "# importing Image module from PIL packagefrom PIL import Image # opening a multiband imageim = Image.open(r\"C:\\Users\\Admin\\Pictures\\download.png\") # getting maximum and minimum pixels of# multiband images (RBG)im1 = Image.Image.getextrema(im) print(\"Multi band image \", im1) # Opening a single band imageim2 = Image.open(r\"C:\\Users\\Admin\\Pictures\\singleband.png\") # getting maximum and minimum pixels of# single band imageim3 = Image.Image.getextrema(im2) print(\"Single band image \", im3)",
"e": 26415,
"s": 25925,
"text": null
},
{
"code": null,
"e": 26425,
"s": 26415,
"text": "Output: "
},
{
"code": null,
"e": 26503,
"s": 26425,
"text": "Multi band image ((73, 255), (0, 255), (0, 255))\nSingle band image (0, 123)"
},
{
"code": null,
"e": 26557,
"s": 26503,
"text": "These images used in above article –Multiband Images "
},
{
"code": null,
"e": 26578,
"s": 26559,
"text": "Single band Image "
},
{
"code": null,
"e": 26593,
"s": 26580,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 26607,
"s": 26593,
"text": "sumitgumber28"
},
{
"code": null,
"e": 26624,
"s": 26607,
"text": "Image-Processing"
},
{
"code": null,
"e": 26639,
"s": 26624,
"text": "python-utility"
},
{
"code": null,
"e": 26646,
"s": 26639,
"text": "Python"
},
{
"code": null,
"e": 26744,
"s": 26646,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26762,
"s": 26744,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26797,
"s": 26762,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 26819,
"s": 26797,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 26851,
"s": 26819,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26881,
"s": 26851,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 26923,
"s": 26881,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 26949,
"s": 26923,
"text": "Python String | replace()"
},
{
"code": null,
"e": 26986,
"s": 26949,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 27029,
"s": 26986,
"text": "Python program to convert a list to string"
}
] |
Why Makefile? | Compiling the source code files can be tiring, especially when you have to include several source files and type the compiling command every time you need to compile. Makefiles are the solution to simplify this task.
Makefiles are special format files that help build and manage the projects automatically.
For example, let’s assume we have the following source files.
main.cpp
hello.cpp
factorial.cpp
functions.h
main.cpp
The following is the code for main.cpp source file −
#include <iostream>
using namespace std;
#include "functions.h"
int main(){
print_hello();
cout << endl;
cout << "The factorial of 5 is " << factorial(5) << endl;
return 0;
}
hello.cpp
The code given below is for hello.cpp source file −
#include <iostream>
using namespace std;
#include "functions.h"
void print_hello(){
cout << "Hello World!";
}
factorial.cpp
The code for factorial.cpp is given below −
#include "functions.h"
int factorial(int n){
if(n!=1){
return(n * factorial(n-1));
} else return 1;
}
functions.h
The following is the code for fnctions.h −
void print_hello();
int factorial(int n);
The trivial way to compile the files and obtain an executable, is by running the command −
gcc main.cpp hello.cpp factorial.cpp -o hello
This command generates hello binary. In this example we have only four files and we know the sequence of the function calls. Hence, it is feasible to type the above command and prepare a final binary.
However, for a large project where we have thousands of source code files, it becomes difficult to maintain the binary builds.
The make command allows you to manage large programs or groups of programs. As you begin to write large programs, you notice that re-compiling large programs takes longer time than re-compiling short programs. Moreover, you notice that you usually only work on a small section of the program ( such as a single function ), and much of the remaining program is unchanged.
In the subsequent section, we see how to prepare a makefile for our project.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2001,
"s": 1784,
"text": "Compiling the source code files can be tiring, especially when you have to include several source files and type the compiling command every time you need to compile. Makefiles are the solution to simplify this task."
},
{
"code": null,
"e": 2091,
"s": 2001,
"text": "Makefiles are special format files that help build and manage the projects automatically."
},
{
"code": null,
"e": 2153,
"s": 2091,
"text": "For example, let’s assume we have the following source files."
},
{
"code": null,
"e": 2162,
"s": 2153,
"text": "main.cpp"
},
{
"code": null,
"e": 2172,
"s": 2162,
"text": "hello.cpp"
},
{
"code": null,
"e": 2186,
"s": 2172,
"text": "factorial.cpp"
},
{
"code": null,
"e": 2198,
"s": 2186,
"text": "functions.h"
},
{
"code": null,
"e": 2207,
"s": 2198,
"text": "main.cpp"
},
{
"code": null,
"e": 2260,
"s": 2207,
"text": "The following is the code for main.cpp source file −"
},
{
"code": null,
"e": 2450,
"s": 2260,
"text": "#include <iostream>\n\nusing namespace std;\n\n#include \"functions.h\"\n\nint main(){\n print_hello();\n cout << endl;\n cout << \"The factorial of 5 is \" << factorial(5) << endl;\n return 0;\n}"
},
{
"code": null,
"e": 2460,
"s": 2450,
"text": "hello.cpp"
},
{
"code": null,
"e": 2512,
"s": 2460,
"text": "The code given below is for hello.cpp source file −"
},
{
"code": null,
"e": 2628,
"s": 2512,
"text": "#include <iostream>\n\nusing namespace std;\n\n#include \"functions.h\"\n\nvoid print_hello(){\n cout << \"Hello World!\";\n}"
},
{
"code": null,
"e": 2642,
"s": 2628,
"text": "factorial.cpp"
},
{
"code": null,
"e": 2686,
"s": 2642,
"text": "The code for factorial.cpp is given below −"
},
{
"code": null,
"e": 2805,
"s": 2686,
"text": "#include \"functions.h\"\n\nint factorial(int n){\n \n if(n!=1){\n return(n * factorial(n-1));\n } else return 1;\n}"
},
{
"code": null,
"e": 2817,
"s": 2805,
"text": "functions.h"
},
{
"code": null,
"e": 2860,
"s": 2817,
"text": "The following is the code for fnctions.h −"
},
{
"code": null,
"e": 2902,
"s": 2860,
"text": "void print_hello();\nint factorial(int n);"
},
{
"code": null,
"e": 2993,
"s": 2902,
"text": "The trivial way to compile the files and obtain an executable, is by running the command −"
},
{
"code": null,
"e": 3041,
"s": 2993,
"text": "gcc main.cpp hello.cpp factorial.cpp -o hello\n"
},
{
"code": null,
"e": 3242,
"s": 3041,
"text": "This command generates hello binary. In this example we have only four files and we know the sequence of the function calls. Hence, it is feasible to type the above command and prepare a final binary."
},
{
"code": null,
"e": 3369,
"s": 3242,
"text": "However, for a large project where we have thousands of source code files, it becomes difficult to maintain the binary builds."
},
{
"code": null,
"e": 3740,
"s": 3369,
"text": "The make command allows you to manage large programs or groups of programs. As you begin to write large programs, you notice that re-compiling large programs takes longer time than re-compiling short programs. Moreover, you notice that you usually only work on a small section of the program ( such as a single function ), and much of the remaining program is unchanged."
},
{
"code": null,
"e": 3817,
"s": 3740,
"text": "In the subsequent section, we see how to prepare a makefile for our project."
},
{
"code": null,
"e": 3824,
"s": 3817,
"text": " Print"
},
{
"code": null,
"e": 3835,
"s": 3824,
"text": " Add Notes"
}
] |
Prime Palindrome in C++ | Suppose we have to find the smallest prime palindrome that is greater than or equal to N. So if the N is 13, then the smallest palindrome will be 101.
To solve this, we will follow these steps −
If N is in range 8 to 11, then return 11
If N is in range 8 to 11, then return 11
for i in range 1 to 99999s := i as a stringr := sreverse rnum := concatenate s and substring of r from index 1, then convert to numberif num >= N and num is prime, then return num
for i in range 1 to 99999
s := i as a string
s := i as a string
r := s
r := s
reverse r
reverse r
num := concatenate s and substring of r from index 1, then convert to number
num := concatenate s and substring of r from index 1, then convert to number
if num >= N and num is prime, then return num
if num >= N and num is prime, then return num
return 0
return 0
Let us see the following implementation to get better understanding −
Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
bool isPrime(int n){
if(n % 2 == 0 && n > 2) return false;
for(int i = 3; i * i <= n; i++){
if(n % i == 0) return false;
}
return n != 1 && n != 0;
}
int primePalindrome(int N) {
if(8 <= N && N <= 11) return 11;
for(int i = 1; i < 100000; i++){
string s = to_string(i);
string r = s;
reverse(r.begin(), r.end());
int num = stoi(s + r.substr(1));
if(num >= N && isPrime(num)) return num;
}
return 0;
}
};
main(){
Solution ob;
cout << (ob.primePalindrome(105));
}
105
131 | [
{
"code": null,
"e": 1213,
"s": 1062,
"text": "Suppose we have to find the smallest prime palindrome that is greater than or equal to N. So if the N is 13, then the smallest palindrome will be 101."
},
{
"code": null,
"e": 1257,
"s": 1213,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1298,
"s": 1257,
"text": "If N is in range 8 to 11, then return 11"
},
{
"code": null,
"e": 1339,
"s": 1298,
"text": "If N is in range 8 to 11, then return 11"
},
{
"code": null,
"e": 1519,
"s": 1339,
"text": "for i in range 1 to 99999s := i as a stringr := sreverse rnum := concatenate s and substring of r from index 1, then convert to numberif num >= N and num is prime, then return num"
},
{
"code": null,
"e": 1545,
"s": 1519,
"text": "for i in range 1 to 99999"
},
{
"code": null,
"e": 1564,
"s": 1545,
"text": "s := i as a string"
},
{
"code": null,
"e": 1583,
"s": 1564,
"text": "s := i as a string"
},
{
"code": null,
"e": 1590,
"s": 1583,
"text": "r := s"
},
{
"code": null,
"e": 1597,
"s": 1590,
"text": "r := s"
},
{
"code": null,
"e": 1607,
"s": 1597,
"text": "reverse r"
},
{
"code": null,
"e": 1617,
"s": 1607,
"text": "reverse r"
},
{
"code": null,
"e": 1694,
"s": 1617,
"text": "num := concatenate s and substring of r from index 1, then convert to number"
},
{
"code": null,
"e": 1771,
"s": 1694,
"text": "num := concatenate s and substring of r from index 1, then convert to number"
},
{
"code": null,
"e": 1817,
"s": 1771,
"text": "if num >= N and num is prime, then return num"
},
{
"code": null,
"e": 1863,
"s": 1817,
"text": "if num >= N and num is prime, then return num"
},
{
"code": null,
"e": 1872,
"s": 1863,
"text": "return 0"
},
{
"code": null,
"e": 1881,
"s": 1872,
"text": "return 0"
},
{
"code": null,
"e": 1951,
"s": 1881,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 1962,
"s": 1951,
"text": " Live Demo"
},
{
"code": null,
"e": 2618,
"s": 1962,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nclass Solution {\n public:\n bool isPrime(int n){\n if(n % 2 == 0 && n > 2) return false;\n for(int i = 3; i * i <= n; i++){\n if(n % i == 0) return false;\n }\n return n != 1 && n != 0;\n }\n int primePalindrome(int N) {\n if(8 <= N && N <= 11) return 11;\n for(int i = 1; i < 100000; i++){\n string s = to_string(i);\n string r = s;\n reverse(r.begin(), r.end());\n int num = stoi(s + r.substr(1));\n if(num >= N && isPrime(num)) return num;\n }\n return 0;\n }\n};\nmain(){\n Solution ob;\n cout << (ob.primePalindrome(105));\n}"
},
{
"code": null,
"e": 2622,
"s": 2618,
"text": "105"
},
{
"code": null,
"e": 2626,
"s": 2622,
"text": "131"
}
] |
Find rows where column value ends with a specific substring in MySQL? | To find rows and update with new value where column value ends with specific substring you need to use LIKE operator.
The syntax is as follows:
UPDATE yourTableName
SET yourColumnName=’yourValue’
WHERE yourColumnName LIKE ‘%.yourString’;
To understand the above syntax, let us create a table. The query to create a table is as follows:
mysql> create table RowEndsWithSpecificString
-> (
-> Id int NOT NULL AUTO_INCREMENT,
-> FileName varchar(30),
-> PRIMARY KEY(Id)
-> );
Query OK, 0 rows affected (1.50 sec)
Now you can insert some records in the table using insert command. The query is as follows:
mysql> insert into RowEndsWithSpecificString(FileName) values('MergeSort.c');
Query OK, 1 row affected (0.11 sec)
mysql> insert into RowEndsWithSpecificString(FileName) values('BubbleSortIntroduction.pdf');
Query OK, 1 row affected (0.25 sec)
mysql> insert into RowEndsWithSpecificString(FileName) values('AllMySQLQuery.docx');
Query OK, 1 row affected (0.18 sec)
mysql> insert into RowEndsWithSpecificString(FileName) values('JavaCollections.pdf');
Query OK, 1 row affected (0.16 sec)
mysql> insert into RowEndsWithSpecificString(FileName) values('JavaServlet.pdf');
Query OK, 1 row affected (0.18 sec)
Display all records from the table using select statement. The query is as follows:
mysql> select *from RowEndsWithSpecificString;
The following is the output:
+----+----------------------------+
| Id | FileName |
+----+----------------------------+
| 1 | MergeSort.c |
| 2 | BubbleSortIntroduction.pdf |
| 3 | AllMySQLQuery.docx |
| 4 | JavaCollections.pdf |
| 5 | JavaServlet.pdf |
+----+----------------------------+
5 rows in set (0.00 sec)
Here is the query to find and update where column value ends with specific substring. The following query finds a substring that ends with ‘.docx’ and updates with a new substring which is ‘.pdf’. The query is as follows:
mysql> update RowEndsWithSpecificString
-> set FileName='IntroductionToCoreJava.pdf'
-> where FileName LIKE '%.docx';
Query OK, 1 row affected (0.14 sec)
Rows matched: 1 Changed: 1 Warnings: 0
Now check the table records once again. The query is as follows:
mysql> select *from RowEndsWithSpecificString;
The following is the output:
+----+----------------------------+
| Id | FileName |
+----+----------------------------+
| 1 | IntroductionToCoreJava.pdf |
| 2 | BubbleSortIntroduction.pdf |
| 3 | IntroductionToCoreJava.pdf |
| 4 | JavaCollections.pdf |
| 5 | JavaServlet.pdf |
+----+----------------------------+
5 rows in set (0.00 sec) | [
{
"code": null,
"e": 1180,
"s": 1062,
"text": "To find rows and update with new value where column value ends with specific substring you need to use LIKE operator."
},
{
"code": null,
"e": 1206,
"s": 1180,
"text": "The syntax is as follows:"
},
{
"code": null,
"e": 1300,
"s": 1206,
"text": "UPDATE yourTableName\nSET yourColumnName=’yourValue’\nWHERE yourColumnName LIKE ‘%.yourString’;"
},
{
"code": null,
"e": 1398,
"s": 1300,
"text": "To understand the above syntax, let us create a table. The query to create a table is as follows:"
},
{
"code": null,
"e": 1586,
"s": 1398,
"text": "mysql> create table RowEndsWithSpecificString\n -> (\n -> Id int NOT NULL AUTO_INCREMENT,\n -> FileName varchar(30),\n -> PRIMARY KEY(Id)\n -> );\nQuery OK, 0 rows affected (1.50 sec)"
},
{
"code": null,
"e": 1678,
"s": 1586,
"text": "Now you can insert some records in the table using insert command. The query is as follows:"
},
{
"code": null,
"e": 2282,
"s": 1678,
"text": "mysql> insert into RowEndsWithSpecificString(FileName) values('MergeSort.c');\nQuery OK, 1 row affected (0.11 sec)\nmysql> insert into RowEndsWithSpecificString(FileName) values('BubbleSortIntroduction.pdf');\nQuery OK, 1 row affected (0.25 sec)\nmysql> insert into RowEndsWithSpecificString(FileName) values('AllMySQLQuery.docx');\nQuery OK, 1 row affected (0.18 sec)\nmysql> insert into RowEndsWithSpecificString(FileName) values('JavaCollections.pdf');\nQuery OK, 1 row affected (0.16 sec)\nmysql> insert into RowEndsWithSpecificString(FileName) values('JavaServlet.pdf');\nQuery OK, 1 row affected (0.18 sec)"
},
{
"code": null,
"e": 2366,
"s": 2282,
"text": "Display all records from the table using select statement. The query is as follows:"
},
{
"code": null,
"e": 2413,
"s": 2366,
"text": "mysql> select *from RowEndsWithSpecificString;"
},
{
"code": null,
"e": 2442,
"s": 2413,
"text": "The following is the output:"
},
{
"code": null,
"e": 2791,
"s": 2442,
"text": "+----+----------------------------+\n| Id | FileName |\n+----+----------------------------+\n| 1 | MergeSort.c |\n| 2 | BubbleSortIntroduction.pdf |\n| 3 | AllMySQLQuery.docx |\n| 4 | JavaCollections.pdf |\n| 5 | JavaServlet.pdf |\n+----+----------------------------+\n5 rows in set (0.00 sec)"
},
{
"code": null,
"e": 3013,
"s": 2791,
"text": "Here is the query to find and update where column value ends with specific substring. The following query finds a substring that ends with ‘.docx’ and updates with a new substring which is ‘.pdf’. The query is as follows:"
},
{
"code": null,
"e": 3212,
"s": 3013,
"text": "mysql> update RowEndsWithSpecificString\n -> set FileName='IntroductionToCoreJava.pdf'\n -> where FileName LIKE '%.docx';\nQuery OK, 1 row affected (0.14 sec)\nRows matched: 1 Changed: 1 Warnings: 0"
},
{
"code": null,
"e": 3277,
"s": 3212,
"text": "Now check the table records once again. The query is as follows:"
},
{
"code": null,
"e": 3324,
"s": 3277,
"text": "mysql> select *from RowEndsWithSpecificString;"
},
{
"code": null,
"e": 3353,
"s": 3324,
"text": "The following is the output:"
},
{
"code": null,
"e": 3702,
"s": 3353,
"text": "+----+----------------------------+\n| Id | FileName |\n+----+----------------------------+\n| 1 | IntroductionToCoreJava.pdf |\n| 2 | BubbleSortIntroduction.pdf |\n| 3 | IntroductionToCoreJava.pdf |\n| 4 | JavaCollections.pdf |\n| 5 | JavaServlet.pdf |\n+----+----------------------------+\n5 rows in set (0.00 sec)"
}
] |
Rearrange characters in a string such that no two adjacent are same in C++ | We are given a string, let's say, str of any given length. The task is to rearrange the given string in such a manner that there won't be the same adjacent characters arranged together in the resultant string.
Input − string str = "itinn"
Output − Rearrangement of characters in a string such that no two adjacent are same is: initn.
Explanation − We are given a string type variable let’s say, str. Now we will rearrange the characters of an input string in such a manner that no two same characters occur at the same position i.e. shifting ‘nn’ because they are the same and adjacent to each other. So the final
string will be ‘initn’.
Input − string str = "abbaabbaa"
Output − Rearrangement of characters in a string such that no two adjacent are same is: ababababa
Explanation − We are given a string type variable let’s say, str. Now we will rearrange the characters of an input string in such a manner that no two same characters occur at the same position i.e. shifting ‘bb’, ‘aa’, ‘bb’, ‘aa’ because they are the same and adjacent to each other. So the final string will be ‘ababababa’.
Input a variable of string type, let’s say, str and calculate the size of a string and store it in a length named variable.
Input a variable of string type, let’s say, str and calculate the size of a string and store it in a length named variable.
Check IF length is 0 then return.
Check IF length is 0 then return.
Pass the data to the function Rearrangement(str, length).
Pass the data to the function Rearrangement(str, length).
Inside the function Rearrangement(arr, length)Set size of a string with (length + 1)/2.Declare a vector type variable as vec(26, 0) that will store the integer type data and a ptr of string type as ptr(length, ‘ ‘). A temporary variable of type integer as 0.Start loop FOR to iterate str through it. Inside the loop, set vec[it - ‘a’]++.Create a character type variable as ch and set it with a call to the maximum(vec) function.Declare an integer type variable as total and set it with vec[ch - ‘a’].Check IF total greater than size then return.Start loop WHILE total then set ptr[temp] to ch, set temp to temp + 2 and decrement the total by 1.Set vec[ch - 'a'] to 0. Start loop FOR from i to 0 till i less than 26. Inside the loop, start while vec[i] is greater than 0. Set temp to (temp >= length) ? 1 : temp and ptr[temp] to 'a' + i and temp to temp + 2 and decrement the vec[i] by 1.Return ptr
Inside the function Rearrangement(arr, length)
Set size of a string with (length + 1)/2.
Set size of a string with (length + 1)/2.
Declare a vector type variable as vec(26, 0) that will store the integer type data and a ptr of string type as ptr(length, ‘ ‘). A temporary variable of type integer as 0.
Declare a vector type variable as vec(26, 0) that will store the integer type data and a ptr of string type as ptr(length, ‘ ‘). A temporary variable of type integer as 0.
Start loop FOR to iterate str through it. Inside the loop, set vec[it - ‘a’]++.
Start loop FOR to iterate str through it. Inside the loop, set vec[it - ‘a’]++.
Create a character type variable as ch and set it with a call to the maximum(vec) function.
Create a character type variable as ch and set it with a call to the maximum(vec) function.
Declare an integer type variable as total and set it with vec[ch - ‘a’].
Declare an integer type variable as total and set it with vec[ch - ‘a’].
Check IF total greater than size then return.
Check IF total greater than size then return.
Start loop WHILE total then set ptr[temp] to ch, set temp to temp + 2 and decrement the total by 1.
Start loop WHILE total then set ptr[temp] to ch, set temp to temp + 2 and decrement the total by 1.
Set vec[ch - 'a'] to 0. Start loop FOR from i to 0 till i less than 26. Inside the loop, start while vec[i] is greater than 0. Set temp to (temp >= length) ? 1 : temp and ptr[temp] to 'a' + i and temp to temp + 2 and decrement the vec[i] by 1.
Set vec[ch - 'a'] to 0. Start loop FOR from i to 0 till i less than 26. Inside the loop, start while vec[i] is greater than 0. Set temp to (temp >= length) ? 1 : temp and ptr[temp] to 'a' + i and temp to temp + 2 and decrement the vec[i] by 1.
Return ptr
Return ptr
Inside the function char maximum(const vector<int>& vec)Declare an integer type variable as high to 0 and character type variable as ‘c’Start loop FOR from i to 0 till i less than 26. Inside the loop, check IF vec[i] is less than high then set high to vec[i] and c to 'a' + i.Return c
Inside the function char maximum(const vector<int>& vec)
Declare an integer type variable as high to 0 and character type variable as ‘c’
Declare an integer type variable as high to 0 and character type variable as ‘c’
Start loop FOR from i to 0 till i less than 26. Inside the loop, check IF vec[i] is less than high then set high to vec[i] and c to 'a' + i.
Start loop FOR from i to 0 till i less than 26. Inside the loop, check IF vec[i] is less than high then set high to vec[i] and c to 'a' + i.
Return c
Return c
Print the result.
Print the result.
#include <bits/stdc++.h>
using namespace std;
char maximum(const vector<int>& vec){
int high = 0;
char c;
for(int i = 0; i < 26; i++){
if(vec[i] > high){
high = vec[i];
c = 'a' + i;
}
}
return c;
}
string Rearrangement(string str, int length){
int size = (length + 1) / 2;
vector<int> vec(26, 0);
string ptr(length, ' ');
int temp = 0;
for(auto it : str){
vec[it - 'a']++;
}
char ch = maximum(vec);
int total = vec[ch - 'a'];
if(total > size){
return "";
}
while(total){
ptr[temp] = ch;
temp = temp + 2;
total--;
}
vec[ch - 'a'] = 0;
for(int i = 0; i < 26; i++){
while (vec[i] > 0){
temp = (temp >= length) ? 1 : temp;
ptr[temp] = 'a' + i;
temp = temp + 2;
vec[i]--;
}
}
return ptr;
}
int main(){
string str = "itinn";
int length = str.length();
if(length == 0){
cout<<"Please enter a valid string";
}
string count = Rearrangement(str, length);
if(count == ""){
cout<<"Please enter a valid string";
}
else{
cout<<"Rearrangement of characters in a string such that no two adjacent are same is: "<<count;
}
return 0;
}
If we run the above code it will generate the following Output
Rearrangement of characters in a string such that no two adjacent are same is: initn | [
{
"code": null,
"e": 1272,
"s": 1062,
"text": "We are given a string, let's say, str of any given length. The task is to rearrange the given string in such a manner that there won't be the same adjacent characters arranged together in the resultant string."
},
{
"code": null,
"e": 1301,
"s": 1272,
"text": "Input − string str = \"itinn\""
},
{
"code": null,
"e": 1396,
"s": 1301,
"text": "Output − Rearrangement of characters in a string such that no two adjacent are same is: initn."
},
{
"code": null,
"e": 1700,
"s": 1396,
"text": "Explanation − We are given a string type variable let’s say, str. Now we will rearrange the characters of an input string in such a manner that no two same characters occur at the same position i.e. shifting ‘nn’ because they are the same and adjacent to each other. So the final\nstring will be ‘initn’."
},
{
"code": null,
"e": 1733,
"s": 1700,
"text": "Input − string str = \"abbaabbaa\""
},
{
"code": null,
"e": 1831,
"s": 1733,
"text": "Output − Rearrangement of characters in a string such that no two adjacent are same is: ababababa"
},
{
"code": null,
"e": 2157,
"s": 1831,
"text": "Explanation − We are given a string type variable let’s say, str. Now we will rearrange the characters of an input string in such a manner that no two same characters occur at the same position i.e. shifting ‘bb’, ‘aa’, ‘bb’, ‘aa’ because they are the same and adjacent to each other. So the final string will be ‘ababababa’."
},
{
"code": null,
"e": 2281,
"s": 2157,
"text": "Input a variable of string type, let’s say, str and calculate the size of a string and store it in a length named variable."
},
{
"code": null,
"e": 2405,
"s": 2281,
"text": "Input a variable of string type, let’s say, str and calculate the size of a string and store it in a length named variable."
},
{
"code": null,
"e": 2439,
"s": 2405,
"text": "Check IF length is 0 then return."
},
{
"code": null,
"e": 2473,
"s": 2439,
"text": "Check IF length is 0 then return."
},
{
"code": null,
"e": 2531,
"s": 2473,
"text": "Pass the data to the function Rearrangement(str, length)."
},
{
"code": null,
"e": 2589,
"s": 2531,
"text": "Pass the data to the function Rearrangement(str, length)."
},
{
"code": null,
"e": 3487,
"s": 2589,
"text": "Inside the function Rearrangement(arr, length)Set size of a string with (length + 1)/2.Declare a vector type variable as vec(26, 0) that will store the integer type data and a ptr of string type as ptr(length, ‘ ‘). A temporary variable of type integer as 0.Start loop FOR to iterate str through it. Inside the loop, set vec[it - ‘a’]++.Create a character type variable as ch and set it with a call to the maximum(vec) function.Declare an integer type variable as total and set it with vec[ch - ‘a’].Check IF total greater than size then return.Start loop WHILE total then set ptr[temp] to ch, set temp to temp + 2 and decrement the total by 1.Set vec[ch - 'a'] to 0. Start loop FOR from i to 0 till i less than 26. Inside the loop, start while vec[i] is greater than 0. Set temp to (temp >= length) ? 1 : temp and ptr[temp] to 'a' + i and temp to temp + 2 and decrement the vec[i] by 1.Return ptr"
},
{
"code": null,
"e": 3534,
"s": 3487,
"text": "Inside the function Rearrangement(arr, length)"
},
{
"code": null,
"e": 3576,
"s": 3534,
"text": "Set size of a string with (length + 1)/2."
},
{
"code": null,
"e": 3618,
"s": 3576,
"text": "Set size of a string with (length + 1)/2."
},
{
"code": null,
"e": 3790,
"s": 3618,
"text": "Declare a vector type variable as vec(26, 0) that will store the integer type data and a ptr of string type as ptr(length, ‘ ‘). A temporary variable of type integer as 0."
},
{
"code": null,
"e": 3962,
"s": 3790,
"text": "Declare a vector type variable as vec(26, 0) that will store the integer type data and a ptr of string type as ptr(length, ‘ ‘). A temporary variable of type integer as 0."
},
{
"code": null,
"e": 4042,
"s": 3962,
"text": "Start loop FOR to iterate str through it. Inside the loop, set vec[it - ‘a’]++."
},
{
"code": null,
"e": 4122,
"s": 4042,
"text": "Start loop FOR to iterate str through it. Inside the loop, set vec[it - ‘a’]++."
},
{
"code": null,
"e": 4214,
"s": 4122,
"text": "Create a character type variable as ch and set it with a call to the maximum(vec) function."
},
{
"code": null,
"e": 4306,
"s": 4214,
"text": "Create a character type variable as ch and set it with a call to the maximum(vec) function."
},
{
"code": null,
"e": 4379,
"s": 4306,
"text": "Declare an integer type variable as total and set it with vec[ch - ‘a’]."
},
{
"code": null,
"e": 4452,
"s": 4379,
"text": "Declare an integer type variable as total and set it with vec[ch - ‘a’]."
},
{
"code": null,
"e": 4498,
"s": 4452,
"text": "Check IF total greater than size then return."
},
{
"code": null,
"e": 4544,
"s": 4498,
"text": "Check IF total greater than size then return."
},
{
"code": null,
"e": 4644,
"s": 4544,
"text": "Start loop WHILE total then set ptr[temp] to ch, set temp to temp + 2 and decrement the total by 1."
},
{
"code": null,
"e": 4744,
"s": 4644,
"text": "Start loop WHILE total then set ptr[temp] to ch, set temp to temp + 2 and decrement the total by 1."
},
{
"code": null,
"e": 4988,
"s": 4744,
"text": "Set vec[ch - 'a'] to 0. Start loop FOR from i to 0 till i less than 26. Inside the loop, start while vec[i] is greater than 0. Set temp to (temp >= length) ? 1 : temp and ptr[temp] to 'a' + i and temp to temp + 2 and decrement the vec[i] by 1."
},
{
"code": null,
"e": 5232,
"s": 4988,
"text": "Set vec[ch - 'a'] to 0. Start loop FOR from i to 0 till i less than 26. Inside the loop, start while vec[i] is greater than 0. Set temp to (temp >= length) ? 1 : temp and ptr[temp] to 'a' + i and temp to temp + 2 and decrement the vec[i] by 1."
},
{
"code": null,
"e": 5243,
"s": 5232,
"text": "Return ptr"
},
{
"code": null,
"e": 5254,
"s": 5243,
"text": "Return ptr"
},
{
"code": null,
"e": 5539,
"s": 5254,
"text": "Inside the function char maximum(const vector<int>& vec)Declare an integer type variable as high to 0 and character type variable as ‘c’Start loop FOR from i to 0 till i less than 26. Inside the loop, check IF vec[i] is less than high then set high to vec[i] and c to 'a' + i.Return c"
},
{
"code": null,
"e": 5596,
"s": 5539,
"text": "Inside the function char maximum(const vector<int>& vec)"
},
{
"code": null,
"e": 5677,
"s": 5596,
"text": "Declare an integer type variable as high to 0 and character type variable as ‘c’"
},
{
"code": null,
"e": 5758,
"s": 5677,
"text": "Declare an integer type variable as high to 0 and character type variable as ‘c’"
},
{
"code": null,
"e": 5899,
"s": 5758,
"text": "Start loop FOR from i to 0 till i less than 26. Inside the loop, check IF vec[i] is less than high then set high to vec[i] and c to 'a' + i."
},
{
"code": null,
"e": 6040,
"s": 5899,
"text": "Start loop FOR from i to 0 till i less than 26. Inside the loop, check IF vec[i] is less than high then set high to vec[i] and c to 'a' + i."
},
{
"code": null,
"e": 6049,
"s": 6040,
"text": "Return c"
},
{
"code": null,
"e": 6058,
"s": 6049,
"text": "Return c"
},
{
"code": null,
"e": 6076,
"s": 6058,
"text": "Print the result."
},
{
"code": null,
"e": 6094,
"s": 6076,
"text": "Print the result."
},
{
"code": null,
"e": 7330,
"s": 6094,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nchar maximum(const vector<int>& vec){\n int high = 0;\n char c;\n for(int i = 0; i < 26; i++){\n if(vec[i] > high){\n high = vec[i];\n c = 'a' + i;\n }\n }\n return c;\n}\nstring Rearrangement(string str, int length){\n int size = (length + 1) / 2;\n vector<int> vec(26, 0);\n string ptr(length, ' ');\n int temp = 0;\n for(auto it : str){\n vec[it - 'a']++;\n }\n char ch = maximum(vec);\n int total = vec[ch - 'a'];\n if(total > size){\n return \"\";\n }\n while(total){\n ptr[temp] = ch;\n temp = temp + 2;\n total--;\n }\n vec[ch - 'a'] = 0;\n for(int i = 0; i < 26; i++){\n while (vec[i] > 0){\n temp = (temp >= length) ? 1 : temp;\n ptr[temp] = 'a' + i;\n temp = temp + 2;\n vec[i]--;\n }\n }\n return ptr;\n}\nint main(){\n string str = \"itinn\";\n int length = str.length();\n if(length == 0){\n cout<<\"Please enter a valid string\";\n }\n string count = Rearrangement(str, length);\n if(count == \"\"){\n cout<<\"Please enter a valid string\";\n }\n else{\n cout<<\"Rearrangement of characters in a string such that no two adjacent are same is: \"<<count;\n }\n return 0;\n}"
},
{
"code": null,
"e": 7393,
"s": 7330,
"text": "If we run the above code it will generate the following Output"
},
{
"code": null,
"e": 7478,
"s": 7393,
"text": "Rearrangement of characters in a string such that no two adjacent are same is: initn"
}
] |
D3.js brush() Function - GeeksforGeeks | 31 Jul, 2020
The d3.brush() function in D3.js is used to new create a 2-D brush. The brush is generally created SVG element.
Syntax:
d3.brush();
Parameters: This function does not accept any parameters.
Return Value: This function returns a newly created brush.
Example: In this example, we will create a brush of size 600×600 pixels on an SVG element using this method.
HTML
<!DOCTYPE html> <html> <head> <title> D3.js | d3.brush() Function </title> <script src = "https://d3js.org/d3.v4.min.js"> </script> </head> <body> <svg width=600 height=600 id="brush"></svg> <script> // Selecting SVG element d3.select("#brush") // Creating a brush using the // d3.brush function .call( d3.brush() // Initialise the brush area: start at // 0,0 and finishes at given width,height .extent( [ [0,0], [600,600] ] ) ) </script> </body> </html>
Output: The brush is created successfully, you can drag to create rectangles using this brush.
Reference: https://devdocs.io/d3~5/d3-brush#_brush
D3.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
How to filter object array based on attributes?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 25300,
"s": 25272,
"text": "\n31 Jul, 2020"
},
{
"code": null,
"e": 25412,
"s": 25300,
"text": "The d3.brush() function in D3.js is used to new create a 2-D brush. The brush is generally created SVG element."
},
{
"code": null,
"e": 25420,
"s": 25412,
"text": "Syntax:"
},
{
"code": null,
"e": 25433,
"s": 25420,
"text": "d3.brush();\n"
},
{
"code": null,
"e": 25491,
"s": 25433,
"text": "Parameters: This function does not accept any parameters."
},
{
"code": null,
"e": 25550,
"s": 25491,
"text": "Return Value: This function returns a newly created brush."
},
{
"code": null,
"e": 25659,
"s": 25550,
"text": "Example: In this example, we will create a brush of size 600×600 pixels on an SVG element using this method."
},
{
"code": null,
"e": 25664,
"s": 25659,
"text": "HTML"
},
{
"code": "<!DOCTYPE html> <html> <head> <title> D3.js | d3.brush() Function </title> <script src = \"https://d3js.org/d3.v4.min.js\"> </script> </head> <body> <svg width=600 height=600 id=\"brush\"></svg> <script> // Selecting SVG element d3.select(\"#brush\") // Creating a brush using the // d3.brush function .call( d3.brush() // Initialise the brush area: start at // 0,0 and finishes at given width,height .extent( [ [0,0], [600,600] ] ) ) </script> </body> </html> ",
"e": 26272,
"s": 25664,
"text": null
},
{
"code": null,
"e": 26367,
"s": 26272,
"text": "Output: The brush is created successfully, you can drag to create rectangles using this brush."
},
{
"code": null,
"e": 26418,
"s": 26367,
"text": "Reference: https://devdocs.io/d3~5/d3-brush#_brush"
},
{
"code": null,
"e": 26424,
"s": 26418,
"text": "D3.js"
},
{
"code": null,
"e": 26435,
"s": 26424,
"text": "JavaScript"
},
{
"code": null,
"e": 26452,
"s": 26435,
"text": "Web Technologies"
},
{
"code": null,
"e": 26550,
"s": 26452,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26559,
"s": 26550,
"text": "Comments"
},
{
"code": null,
"e": 26572,
"s": 26559,
"text": "Old Comments"
},
{
"code": null,
"e": 26633,
"s": 26572,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 26674,
"s": 26633,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 26728,
"s": 26674,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 26768,
"s": 26728,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 26816,
"s": 26768,
"text": "How to filter object array based on attributes?"
},
{
"code": null,
"e": 26858,
"s": 26816,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 26891,
"s": 26858,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 26934,
"s": 26891,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 26996,
"s": 26934,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
] |
Python – Strip whitespace from a Pandas DataFrame | To strip whitespace, whether its leading or trailing, use the strip() method. At first, let us import thr required Pandas library with an alias −
import pandas as pd
Let’s create a DataFrame with 3 columns. The first column is having leading and trailing whitespaces −
dataFrame = pd.DataFrame({
'Product Category': [' Computer', ' Mobile Phone', 'Electronics ', 'Appliances', ' Furniture', 'Stationery'],'Product Name': ['Keyboard', 'Charger', 'SmartTV', 'Refrigerators', 'Chairs', 'Diaries'],'Quantity': [10, 50, 10, 20, 25, 50]})
Removing whitespace from a single column “Product Category” −
dataFrame['Product Category'].str.strip()
Following is the complete code −
import pandas as pd
# create a dataframe with 3 columns
dataFrame = pd.DataFrame({
'Product Category': [' Computer', ' Mobile Phone', 'Electronics ', 'Appliances', ' Furniture', 'Stationery'],'Product Name': ['Keyboard', 'Charger', 'SmartTV', 'Refrigerators', 'Chairs', 'Diaries'],'Quantity': [10, 50, 10, 20, 25, 50]})
# removing whitespace from a single column
dataFrame['Product Category'].str.strip()
# dataframe
print"Dataframe after removing whitespaces...\n",dataFrame
This will produce the following output −
Dataframe after removing whitespaces...
Product Category Product Name Quantity
0 Computer Keyboard 10
1 Mobile Phone Charger 50
2 Electronics SmartTV 10
3 Appliances Refrigerators 20
4 Furniture Chairs 25
5 Stationery Diaries 50 | [
{
"code": null,
"e": 1208,
"s": 1062,
"text": "To strip whitespace, whether its leading or trailing, use the strip() method. At first, let us import thr required Pandas library with an alias −"
},
{
"code": null,
"e": 1228,
"s": 1208,
"text": "import pandas as pd"
},
{
"code": null,
"e": 1331,
"s": 1228,
"text": "Let’s create a DataFrame with 3 columns. The first column is having leading and trailing whitespaces −"
},
{
"code": null,
"e": 1600,
"s": 1331,
"text": "dataFrame = pd.DataFrame({\n 'Product Category': [' Computer', ' Mobile Phone', 'Electronics ', 'Appliances', ' Furniture', 'Stationery'],'Product Name': ['Keyboard', 'Charger', 'SmartTV', 'Refrigerators', 'Chairs', 'Diaries'],'Quantity': [10, 50, 10, 20, 25, 50]})\n\n"
},
{
"code": null,
"e": 1662,
"s": 1600,
"text": "Removing whitespace from a single column “Product Category” −"
},
{
"code": null,
"e": 1704,
"s": 1662,
"text": "dataFrame['Product Category'].str.strip()"
},
{
"code": null,
"e": 1737,
"s": 1704,
"text": "Following is the complete code −"
},
{
"code": null,
"e": 2221,
"s": 1737,
"text": "import pandas as pd\n\n# create a dataframe with 3 columns\ndataFrame = pd.DataFrame({\n 'Product Category': [' Computer', ' Mobile Phone', 'Electronics ', 'Appliances', ' Furniture', 'Stationery'],'Product Name': ['Keyboard', 'Charger', 'SmartTV', 'Refrigerators', 'Chairs', 'Diaries'],'Quantity': [10, 50, 10, 20, 25, 50]})\n\n# removing whitespace from a single column\ndataFrame['Product Category'].str.strip()\n\n# dataframe\nprint\"Dataframe after removing whitespaces...\\n\",dataFrame\n\n"
},
{
"code": null,
"e": 2262,
"s": 2221,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2624,
"s": 2262,
"text": "Dataframe after removing whitespaces...\n Product Category Product Name Quantity\n0 Computer Keyboard 10\n1 Mobile Phone Charger 50\n2 Electronics SmartTV 10\n3 Appliances Refrigerators 20\n4 Furniture Chairs 25\n5 Stationery Diaries 50"
}
] |
Getting Started with Reinforcement Learning and Open AI Gym | by Genevieve Hayes | Towards Data Science | This is the third in a series of articles on Reinforcement Learning and Open AI Gym. Part 1 can be found here, while Part 2 can be found here.
Reinforcement learning (RL) is the branch of machine learning that deals with learning from interacting with an environment where feedback may be delayed.
Although RL is a very powerful tool that has been successfully applied to problems ranging from the optimization of chemical reactions to teaching a computer to play video games, it has historically been difficult to get started with, due to the lack of availability of interesting and challenging environments on which to experiment.
This is where OpenAI Gym comes in.
OpenAI Gym is a Python package comprising a selection of RL environments, ranging from simple “toy” environments to more challenging environments, including simulated robotics environments and Atari video game environments.
It was developed with the aim of becoming a standardized environment and benchmark for RL research.
In this article, we will use the OpenAI Gym Mountain Car environment to demonstrate how to get started in using this exciting tool and show how Q-learning can be used to solve this problem.
This tutorial assumes you already have OpenAI Gym installed on your computer. If you haven’t done so, installation instructions can be found here for Windows and here for Mac or Linux.
On the OpenAI Gym website, the Mountain Car problem is described as follows:
A car is on a one-dimensional track, positioned between two “mountains”. The goal is to drive up the mountain on the right; however, the car’s engine is not strong enough to scale the mountain in a single pass. Therefore, the only way to succeed is to drive back and forth to build up momentum.
The car’s state, at any point in time, is given by a vector containing its horizonal position and velocity. The car commences each episode stationary, at the bottom of the valley between the hills (at position approximately -0.5), and the episode ends when either the car reaches the flag (position > 0.5) or after 200 moves.
At each move, the car has three actions available to it: push left, push right or do nothing, and a penalty of 1 unit is applied for each move taken (including doing nothing). This means that, unless the can figure out a way to ascend the mountain in less than 200 moves, it will always achieve a total “reward” of -200 units.
To begin with this environment, import and initialize it as follows:
import gymenv = gym.make(‘MountainCar-v0’)env.reset()
Once you have imported the Mountain car environment, the next step is to explore it. All RL environments have a state space (that is, the set of all possible states of the environment you can be in) and an action space (that is, the set of all actions that you can take within the environment).
You can see the size of these spaces using:
> print(‘State space: ‘, env.observation_space)State space: Box(2,)> print(‘Action space: ‘, env.action_space)Action space: Discrete(3)
This tells us that the state space represents a 2-dimensional box, so each state observation is a vector of 2 (float) values, and that the action space comprises three discrete actions (which is what we already knew).
By default, the three actions are represented by the integers 0, 1 and 2. However, we don’t know what values the elements of the state vector can take. This can be found using:
> print(env.observation_space.low)[-1.2 -0.07]>print(env.observation_space.high)[0.6 0.07]
From this, we can see that the first element of the state vector (representing the cart’s position) can take on any value in the range -1.2 to 0.6, while the second element (representing the cart’s velocity) can take on any value in the range -0.07 to 0.07.
When we introduced the Q-learning algorithm in the first article in this series, we said that it was guaranteed to converge provided each state-action pair is visited a sufficiently large number of times. In this situation, however, we are dealing with a continuous state space, which means that there are infinitely many state-action pairs, making it impossible to satisfy this condition.
One way to address this problem is to use deep Q-networks (DQNs). DQNs combine deep learning with Q-learning by using a deep neural network as an approximator for the Q-function. DQNs have been successfully applied to developing artificial intelligence capable of playing Atari video games.
However, for a problem as simple as the Mountain Car problem, this may be a bit of overkill.
An alternative approach is to just discretize the state space. One simple way in which this can be done is to round the first element of the state vector to the nearest 0.1 and the second element to the nearest 0.01, and then (for convenience) multiply the first element by 10 and the second by 100.
This reduces the number of state-action pairs down to 855, which now makes it possible to satisfy the condition required for Q-learning to converge.
In the first article in this series, we went through the Q-learning algorithm in detail. When going though this algorithm, we assumed a one-dimensional state space, so our goal was to find the optimal Q table, Q(s,a).
In this problem, since we our dealing with a two-dimensional state space, we replace Q(s, a) with Q(s1, s2, a), but other than that, the Q-learning algorithm remains more or less the same.
To recap, the algorithm is as follows:
Initialize Q(s1, s2, a) by setting all of the elements equal to small random values;Observe the current state, (s1, s2);Based on the exploration strategy, choose an action to take, a;Take action a and observe the resulting reward, r, and the new state of the environment, (s1’, s2’);Update Q(s1, s2, a) based on the update rule:
Initialize Q(s1, s2, a) by setting all of the elements equal to small random values;
Observe the current state, (s1, s2);
Based on the exploration strategy, choose an action to take, a;
Take action a and observe the resulting reward, r, and the new state of the environment, (s1’, s2’);
Update Q(s1, s2, a) based on the update rule:
Q’(s1, s2, a) = (1 — w)*Q(s1, s2, a) + w*(r+d*Q(s1’, s2’, argmax a’ Q(s1’, s2’, a’)))
Where w is the learning rate and d is the discount rate;
6. Repeat steps 2–5 until convergence.
To implement Q-learning in OpenAI Gym, we need ways of observing the current state; taking an action and observing the consequences of that action. These can be done as follows.
The initial state of an environment is returned when you reset the environment:
> print(env.reset())array([-0.50926558, 0. ])
To take an action (for example, a = 2), it is necessary to “step forward” the environment by that action using the step() method. This returns a 4-ple giving the new state, reward, a Boolean indicating whether or not the episode has terminated (due to the goal being reached or 200 steps having elapsed), and any additional information (this is always empty for this problem).
> print(env.step(2))(array([-0.50837305, 0.00089253]), -1.0, False, {})
If we assume an epsilon-greedy exploration strategy where epsilon decays linearly to a specified minimum (min_eps) over the total number of episodes, we can put all of the above together with the algorithm from the previous section and produce the following function for implementing Q-learning.
For tracking purposes, this function returns a list containing the average total reward for each run of 100 episodes. It also visualizes the movements of the Mountain Car for the final 10 episodes using the env.render() method.
The environment is only visualized for the final 10 episodes, rather than for all episodes, because visualizing the environment dramatically increases the code run time.
Suppose we assuming a learning rate of 0.2, a discount rate of 0.9, an initial epsilon value of 0.8, and a minimum epsilon value of 0. If we run the algorithm for 500 episodes, at the end of these episodes, the car has started to figure out that it needs to rock back and fourth to gain the momentum necessary to ascend the mountain, but can only make it about halfway up.
If we increase the number of episodes by an order of magnitude to 5000, however, by the end of the 5000 episodes the car is able to ascend the mountain perfectly, almost every time.
Plotting the average reward vs the episode number for the 5000 episodes, we can see that, initially, the average reward is fairly flat, with each run terminating once the maximum 200 movements is reached. This is the exploration phase of the algorithm.
Nevertheless, in the final 1000 episodes, the algorithm takes what it’s learned through exploration and exploits it in order to increase the average reward, with the episodes now ending in less than 200 movements, as the car learns to ascend the mountain.
This exploitation phase is only possible because the algorithm was given sufficient time to explore the environment, which is why the car was unable to climb the mountain when the algorithm was only run for 500 episodes.
In this article, we have demonstrated how RL can be used to solve the OpenAI Gym Mountain Car problem. To solve this problem, it was necessary to discretize our state space and make some small modifications to the Q-learning algorithm, but other than that, the technique used was the same as that used to solve the simple grid world problem in the first article in this series.
But this is just one of the many environments available to users in Open AI Gym. For readers interested in trying out the skills they have learned in this article on their own, I recommend experimenting with any of the other Classic Control problem (available here) and then moving on to the Box 2D problems.
By continually modifying and building on the Q-learning algorithm, it should be possible to solve any of the environments available to users of OpenAI Gym. Nevertheless, as with everything, the first step is learning the basics. This is what we have succeeded in doing today. | [
{
"code": null,
"e": 315,
"s": 172,
"text": "This is the third in a series of articles on Reinforcement Learning and Open AI Gym. Part 1 can be found here, while Part 2 can be found here."
},
{
"code": null,
"e": 470,
"s": 315,
"text": "Reinforcement learning (RL) is the branch of machine learning that deals with learning from interacting with an environment where feedback may be delayed."
},
{
"code": null,
"e": 805,
"s": 470,
"text": "Although RL is a very powerful tool that has been successfully applied to problems ranging from the optimization of chemical reactions to teaching a computer to play video games, it has historically been difficult to get started with, due to the lack of availability of interesting and challenging environments on which to experiment."
},
{
"code": null,
"e": 840,
"s": 805,
"text": "This is where OpenAI Gym comes in."
},
{
"code": null,
"e": 1064,
"s": 840,
"text": "OpenAI Gym is a Python package comprising a selection of RL environments, ranging from simple “toy” environments to more challenging environments, including simulated robotics environments and Atari video game environments."
},
{
"code": null,
"e": 1164,
"s": 1064,
"text": "It was developed with the aim of becoming a standardized environment and benchmark for RL research."
},
{
"code": null,
"e": 1354,
"s": 1164,
"text": "In this article, we will use the OpenAI Gym Mountain Car environment to demonstrate how to get started in using this exciting tool and show how Q-learning can be used to solve this problem."
},
{
"code": null,
"e": 1539,
"s": 1354,
"text": "This tutorial assumes you already have OpenAI Gym installed on your computer. If you haven’t done so, installation instructions can be found here for Windows and here for Mac or Linux."
},
{
"code": null,
"e": 1616,
"s": 1539,
"text": "On the OpenAI Gym website, the Mountain Car problem is described as follows:"
},
{
"code": null,
"e": 1911,
"s": 1616,
"text": "A car is on a one-dimensional track, positioned between two “mountains”. The goal is to drive up the mountain on the right; however, the car’s engine is not strong enough to scale the mountain in a single pass. Therefore, the only way to succeed is to drive back and forth to build up momentum."
},
{
"code": null,
"e": 2237,
"s": 1911,
"text": "The car’s state, at any point in time, is given by a vector containing its horizonal position and velocity. The car commences each episode stationary, at the bottom of the valley between the hills (at position approximately -0.5), and the episode ends when either the car reaches the flag (position > 0.5) or after 200 moves."
},
{
"code": null,
"e": 2564,
"s": 2237,
"text": "At each move, the car has three actions available to it: push left, push right or do nothing, and a penalty of 1 unit is applied for each move taken (including doing nothing). This means that, unless the can figure out a way to ascend the mountain in less than 200 moves, it will always achieve a total “reward” of -200 units."
},
{
"code": null,
"e": 2633,
"s": 2564,
"text": "To begin with this environment, import and initialize it as follows:"
},
{
"code": null,
"e": 2687,
"s": 2633,
"text": "import gymenv = gym.make(‘MountainCar-v0’)env.reset()"
},
{
"code": null,
"e": 2982,
"s": 2687,
"text": "Once you have imported the Mountain car environment, the next step is to explore it. All RL environments have a state space (that is, the set of all possible states of the environment you can be in) and an action space (that is, the set of all actions that you can take within the environment)."
},
{
"code": null,
"e": 3026,
"s": 2982,
"text": "You can see the size of these spaces using:"
},
{
"code": null,
"e": 3162,
"s": 3026,
"text": "> print(‘State space: ‘, env.observation_space)State space: Box(2,)> print(‘Action space: ‘, env.action_space)Action space: Discrete(3)"
},
{
"code": null,
"e": 3380,
"s": 3162,
"text": "This tells us that the state space represents a 2-dimensional box, so each state observation is a vector of 2 (float) values, and that the action space comprises three discrete actions (which is what we already knew)."
},
{
"code": null,
"e": 3557,
"s": 3380,
"text": "By default, the three actions are represented by the integers 0, 1 and 2. However, we don’t know what values the elements of the state vector can take. This can be found using:"
},
{
"code": null,
"e": 3650,
"s": 3557,
"text": "> print(env.observation_space.low)[-1.2 -0.07]>print(env.observation_space.high)[0.6 0.07]"
},
{
"code": null,
"e": 3908,
"s": 3650,
"text": "From this, we can see that the first element of the state vector (representing the cart’s position) can take on any value in the range -1.2 to 0.6, while the second element (representing the cart’s velocity) can take on any value in the range -0.07 to 0.07."
},
{
"code": null,
"e": 4298,
"s": 3908,
"text": "When we introduced the Q-learning algorithm in the first article in this series, we said that it was guaranteed to converge provided each state-action pair is visited a sufficiently large number of times. In this situation, however, we are dealing with a continuous state space, which means that there are infinitely many state-action pairs, making it impossible to satisfy this condition."
},
{
"code": null,
"e": 4589,
"s": 4298,
"text": "One way to address this problem is to use deep Q-networks (DQNs). DQNs combine deep learning with Q-learning by using a deep neural network as an approximator for the Q-function. DQNs have been successfully applied to developing artificial intelligence capable of playing Atari video games."
},
{
"code": null,
"e": 4682,
"s": 4589,
"text": "However, for a problem as simple as the Mountain Car problem, this may be a bit of overkill."
},
{
"code": null,
"e": 4982,
"s": 4682,
"text": "An alternative approach is to just discretize the state space. One simple way in which this can be done is to round the first element of the state vector to the nearest 0.1 and the second element to the nearest 0.01, and then (for convenience) multiply the first element by 10 and the second by 100."
},
{
"code": null,
"e": 5131,
"s": 4982,
"text": "This reduces the number of state-action pairs down to 855, which now makes it possible to satisfy the condition required for Q-learning to converge."
},
{
"code": null,
"e": 5349,
"s": 5131,
"text": "In the first article in this series, we went through the Q-learning algorithm in detail. When going though this algorithm, we assumed a one-dimensional state space, so our goal was to find the optimal Q table, Q(s,a)."
},
{
"code": null,
"e": 5538,
"s": 5349,
"text": "In this problem, since we our dealing with a two-dimensional state space, we replace Q(s, a) with Q(s1, s2, a), but other than that, the Q-learning algorithm remains more or less the same."
},
{
"code": null,
"e": 5577,
"s": 5538,
"text": "To recap, the algorithm is as follows:"
},
{
"code": null,
"e": 5906,
"s": 5577,
"text": "Initialize Q(s1, s2, a) by setting all of the elements equal to small random values;Observe the current state, (s1, s2);Based on the exploration strategy, choose an action to take, a;Take action a and observe the resulting reward, r, and the new state of the environment, (s1’, s2’);Update Q(s1, s2, a) based on the update rule:"
},
{
"code": null,
"e": 5991,
"s": 5906,
"text": "Initialize Q(s1, s2, a) by setting all of the elements equal to small random values;"
},
{
"code": null,
"e": 6028,
"s": 5991,
"text": "Observe the current state, (s1, s2);"
},
{
"code": null,
"e": 6092,
"s": 6028,
"text": "Based on the exploration strategy, choose an action to take, a;"
},
{
"code": null,
"e": 6193,
"s": 6092,
"text": "Take action a and observe the resulting reward, r, and the new state of the environment, (s1’, s2’);"
},
{
"code": null,
"e": 6239,
"s": 6193,
"text": "Update Q(s1, s2, a) based on the update rule:"
},
{
"code": null,
"e": 6325,
"s": 6239,
"text": "Q’(s1, s2, a) = (1 — w)*Q(s1, s2, a) + w*(r+d*Q(s1’, s2’, argmax a’ Q(s1’, s2’, a’)))"
},
{
"code": null,
"e": 6382,
"s": 6325,
"text": "Where w is the learning rate and d is the discount rate;"
},
{
"code": null,
"e": 6421,
"s": 6382,
"text": "6. Repeat steps 2–5 until convergence."
},
{
"code": null,
"e": 6599,
"s": 6421,
"text": "To implement Q-learning in OpenAI Gym, we need ways of observing the current state; taking an action and observing the consequences of that action. These can be done as follows."
},
{
"code": null,
"e": 6679,
"s": 6599,
"text": "The initial state of an environment is returned when you reset the environment:"
},
{
"code": null,
"e": 6725,
"s": 6679,
"text": "> print(env.reset())array([-0.50926558, 0. ])"
},
{
"code": null,
"e": 7102,
"s": 6725,
"text": "To take an action (for example, a = 2), it is necessary to “step forward” the environment by that action using the step() method. This returns a 4-ple giving the new state, reward, a Boolean indicating whether or not the episode has terminated (due to the goal being reached or 200 steps having elapsed), and any additional information (this is always empty for this problem)."
},
{
"code": null,
"e": 7174,
"s": 7102,
"text": "> print(env.step(2))(array([-0.50837305, 0.00089253]), -1.0, False, {})"
},
{
"code": null,
"e": 7470,
"s": 7174,
"text": "If we assume an epsilon-greedy exploration strategy where epsilon decays linearly to a specified minimum (min_eps) over the total number of episodes, we can put all of the above together with the algorithm from the previous section and produce the following function for implementing Q-learning."
},
{
"code": null,
"e": 7698,
"s": 7470,
"text": "For tracking purposes, this function returns a list containing the average total reward for each run of 100 episodes. It also visualizes the movements of the Mountain Car for the final 10 episodes using the env.render() method."
},
{
"code": null,
"e": 7868,
"s": 7698,
"text": "The environment is only visualized for the final 10 episodes, rather than for all episodes, because visualizing the environment dramatically increases the code run time."
},
{
"code": null,
"e": 8241,
"s": 7868,
"text": "Suppose we assuming a learning rate of 0.2, a discount rate of 0.9, an initial epsilon value of 0.8, and a minimum epsilon value of 0. If we run the algorithm for 500 episodes, at the end of these episodes, the car has started to figure out that it needs to rock back and fourth to gain the momentum necessary to ascend the mountain, but can only make it about halfway up."
},
{
"code": null,
"e": 8423,
"s": 8241,
"text": "If we increase the number of episodes by an order of magnitude to 5000, however, by the end of the 5000 episodes the car is able to ascend the mountain perfectly, almost every time."
},
{
"code": null,
"e": 8676,
"s": 8423,
"text": "Plotting the average reward vs the episode number for the 5000 episodes, we can see that, initially, the average reward is fairly flat, with each run terminating once the maximum 200 movements is reached. This is the exploration phase of the algorithm."
},
{
"code": null,
"e": 8932,
"s": 8676,
"text": "Nevertheless, in the final 1000 episodes, the algorithm takes what it’s learned through exploration and exploits it in order to increase the average reward, with the episodes now ending in less than 200 movements, as the car learns to ascend the mountain."
},
{
"code": null,
"e": 9153,
"s": 8932,
"text": "This exploitation phase is only possible because the algorithm was given sufficient time to explore the environment, which is why the car was unable to climb the mountain when the algorithm was only run for 500 episodes."
},
{
"code": null,
"e": 9531,
"s": 9153,
"text": "In this article, we have demonstrated how RL can be used to solve the OpenAI Gym Mountain Car problem. To solve this problem, it was necessary to discretize our state space and make some small modifications to the Q-learning algorithm, but other than that, the technique used was the same as that used to solve the simple grid world problem in the first article in this series."
},
{
"code": null,
"e": 9840,
"s": 9531,
"text": "But this is just one of the many environments available to users in Open AI Gym. For readers interested in trying out the skills they have learned in this article on their own, I recommend experimenting with any of the other Classic Control problem (available here) and then moving on to the Box 2D problems."
}
] |
Debugging Dbt: When Your Table Name is a Reserved Keyword | by Madison Schott | Towards Data Science | Welcome to my newest series- debugging dbt. As an analytics engineer, I use dbt every day in my job to write robust data models. It is a great tool for simplifying and containerizing the way data models run. While it makes things easier, there are still things I am constantly learning about the tool. I wanted to use my struggles and learnings as a way to teach others within the community that may run into the same issues.
Today I will be addressing a problem I had using Snowflake tables with the same name as reserved keywords. If you are using Fivetran to ingest your data, then you may experience a similar issue.
Two data sources that we ingest using Fivetran are Zendesk and Shopify. Both of these sources contain tables with the names order and group. Because these words are considered reserved keywords in many databases, in my case Snowflake, then we are going to run into some issues running them with dbt.
This may show up in the form of an error that looks like this:
SQL compilation error: syntax error line 1 at position 26 unexpected 'group'. syntax error line 1 at position 31 unexpected '<EOF>'.
How to fix this:
Go to the src.yml file that contains the database/schema information for your corresponding source table.Under the name of you table add identifier and the name of the table.
Go to the src.yml file that contains the database/schema information for your corresponding source table.
Under the name of you table add identifier and the name of the table.
identifier: ORDER# or identifier: GROUP
3. Also add another line that says quoting and sets the nested identifier to be true.
quoting: identifier: true
Adding these few things to your src.yml file for these sources changes the way the SQL is compiled in dbt. Instead of reading your source tables as
select * from raw.zendesk.group
it will now be read as
select * from raw.zendesk."GROUP"
The changes simply add quotes to the table name which lets SQL know that this is actually the table’s name rather than a reserved keyword.
Issues like these often manifest themselves in many different types of error messages. It can be hard to get to exactly what is causing a certain issue, but it often ends up being fairly simple. Be sure to follow to stay updated on the rest of my Debugging Dbt series. Next up is incremental models! | [
{
"code": null,
"e": 597,
"s": 171,
"text": "Welcome to my newest series- debugging dbt. As an analytics engineer, I use dbt every day in my job to write robust data models. It is a great tool for simplifying and containerizing the way data models run. While it makes things easier, there are still things I am constantly learning about the tool. I wanted to use my struggles and learnings as a way to teach others within the community that may run into the same issues."
},
{
"code": null,
"e": 792,
"s": 597,
"text": "Today I will be addressing a problem I had using Snowflake tables with the same name as reserved keywords. If you are using Fivetran to ingest your data, then you may experience a similar issue."
},
{
"code": null,
"e": 1092,
"s": 792,
"text": "Two data sources that we ingest using Fivetran are Zendesk and Shopify. Both of these sources contain tables with the names order and group. Because these words are considered reserved keywords in many databases, in my case Snowflake, then we are going to run into some issues running them with dbt."
},
{
"code": null,
"e": 1155,
"s": 1092,
"text": "This may show up in the form of an error that looks like this:"
},
{
"code": null,
"e": 1288,
"s": 1155,
"text": "SQL compilation error: syntax error line 1 at position 26 unexpected 'group'. syntax error line 1 at position 31 unexpected '<EOF>'."
},
{
"code": null,
"e": 1305,
"s": 1288,
"text": "How to fix this:"
},
{
"code": null,
"e": 1480,
"s": 1305,
"text": "Go to the src.yml file that contains the database/schema information for your corresponding source table.Under the name of you table add identifier and the name of the table."
},
{
"code": null,
"e": 1586,
"s": 1480,
"text": "Go to the src.yml file that contains the database/schema information for your corresponding source table."
},
{
"code": null,
"e": 1656,
"s": 1586,
"text": "Under the name of you table add identifier and the name of the table."
},
{
"code": null,
"e": 1696,
"s": 1656,
"text": "identifier: ORDER# or identifier: GROUP"
},
{
"code": null,
"e": 1782,
"s": 1696,
"text": "3. Also add another line that says quoting and sets the nested identifier to be true."
},
{
"code": null,
"e": 1809,
"s": 1782,
"text": "quoting: identifier: true"
},
{
"code": null,
"e": 1957,
"s": 1809,
"text": "Adding these few things to your src.yml file for these sources changes the way the SQL is compiled in dbt. Instead of reading your source tables as"
},
{
"code": null,
"e": 1989,
"s": 1957,
"text": "select * from raw.zendesk.group"
},
{
"code": null,
"e": 2012,
"s": 1989,
"text": "it will now be read as"
},
{
"code": null,
"e": 2046,
"s": 2012,
"text": "select * from raw.zendesk.\"GROUP\""
},
{
"code": null,
"e": 2185,
"s": 2046,
"text": "The changes simply add quotes to the table name which lets SQL know that this is actually the table’s name rather than a reserved keyword."
}
] |
Add an autoincrement column with a custom start value in MySQL | To add a new column to an already created table, use ALTER TABLE and ADD COLUMN. Use AUTO_INCREMENT to set auto increment custom value.
Let us first create a table −
mysql> create table DemoTable
-> (
-> StudentName varchar(20)
-> );
Query OK, 0 rows affected (0.63 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('Robert');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values('Adam');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values('Mike');
Query OK, 1 row affected (0.12 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+-------------+
| StudentName |
+-------------+
| Robert |
| Adam |
| Mike |
+-------------+
3 rows in set (0.00 sec)
Following is the query to add an autoincrement column with start value −
mysql> alter table DemoTable add column StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,AUTO_INCREMENT=1000;
Query OK, 0 rows affected (1.83 sec)
Records: 0 Duplicates: 0 Warnings: 0
Let us check the table records once again −
mysql> select *from DemoTable;
This will produce the following output −
+-------------+-----------+
| StudentName | StudentId |
+-------------+-----------+
| Robert | 1000 |
| Adam | 1001 |
| Mike | 1002 |
+-------------+-----------+
3 rows in set (0.00 sec) | [
{
"code": null,
"e": 1198,
"s": 1062,
"text": "To add a new column to an already created table, use ALTER TABLE and ADD COLUMN. Use AUTO_INCREMENT to set auto increment custom value."
},
{
"code": null,
"e": 1228,
"s": 1198,
"text": "Let us first create a table −"
},
{
"code": null,
"e": 1342,
"s": 1228,
"text": "mysql> create table DemoTable\n -> (\n -> StudentName varchar(20)\n -> );\nQuery OK, 0 rows affected (0.63 sec)"
},
{
"code": null,
"e": 1398,
"s": 1342,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 1643,
"s": 1398,
"text": "mysql> insert into DemoTable values('Robert');\nQuery OK, 1 row affected (0.12 sec)\nmysql> insert into DemoTable values('Adam');\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into DemoTable values('Mike');\nQuery OK, 1 row affected (0.12 sec)"
},
{
"code": null,
"e": 1703,
"s": 1643,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 1734,
"s": 1703,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 1775,
"s": 1734,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1912,
"s": 1775,
"text": "+-------------+\n| StudentName |\n+-------------+\n| Robert |\n| Adam |\n| Mike |\n+-------------+\n3 rows in set (0.00 sec)"
},
{
"code": null,
"e": 1985,
"s": 1912,
"text": "Following is the query to add an autoincrement column with start value −"
},
{
"code": null,
"e": 2170,
"s": 1985,
"text": "mysql> alter table DemoTable add column StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,AUTO_INCREMENT=1000;\nQuery OK, 0 rows affected (1.83 sec)\nRecords: 0 Duplicates: 0 Warnings: 0"
},
{
"code": null,
"e": 2214,
"s": 2170,
"text": "Let us check the table records once again −"
},
{
"code": null,
"e": 2245,
"s": 2214,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 2286,
"s": 2245,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2507,
"s": 2286,
"text": "+-------------+-----------+\n| StudentName | StudentId |\n+-------------+-----------+\n| Robert | 1000 |\n| Adam | 1001 |\n| Mike | 1002 |\n+-------------+-----------+\n3 rows in set (0.00 sec)"
}
] |
Training Neural Networks for price prediction with TensorFlow | by Jan Majewski | Towards Data Science | Using Deep Neural Networks for regression problems might seem like overkill (and quite often is), but for some cases where you have a significant amount of high dimensional data they can outperform any other ML models.
When you learn about Neural Networks you usually start with some image classification problem like the MNIST dataset — this is an obvious choice as advanced tasks with high dimensional data is where DNNs really thrive.
Surprisingly, when you try to apply what you learned on MNIST on a regression tasks you might struggle for a while before your super-advanced DNN model is any better than a basic Random Forest Regressor. Sometimes you might never reach that moment...
In this guide, I listed some key tips and tricks learned while using DNN for regression problems. The data is a set of nearly 50 features describing 25k properties in Warsaw. I described the feature selection process in my previous article: feature-selection-and-error-analysis-while-working-with-spatial-data so now we will focus on creating the best possible model predicting property price per m2 using the selected features.
The code and data source used for this article can be found on GitHub.
When training a Deep Neural Network I usually follow these key steps:
A) Choose a default architecture — no. of layers, no. of neurons, activation
B) Regularize model
C) Adjust network architecture
D) Adjust the learning rate and no. of epochs
E) Extract optimal model using CallBacks
Usually creating the final model takes a few runs through all of these steps but an important thing to remember is: DO ONE THING AT A TIME. Don’t try to change architecture, regularization, and learning rate at the same time as you will not know what really worked and probably spend hours going in circles.
Before you start building any DNNs for regression tasks there are 3 key things you must remember:
Standarize your data to make training more efficient
Use RELU activation function for all hidden layers — you will be going nowhere with default sigmoid activation
Use Linear activation function for the single-neuron output layer
Another important task is selecting the loss function. Mean Squared Error or Mean Absolute Error are the two most common choices. As my goal to minimize the average percentage error and maximize the share of all buildings within 5% error I choose MAE, as it penalizes outliers less and is easier to interpret — it pretty much tells you how many $$/m2 on average each offer is off the actual value.
There is also a function directly linked to my goal — Mean Absolute Percentage Error, but after testing it against MAE I found the training to be less efficient.
We start with a basic network with 5 hidden layers and a decreasing number of neurons in every second layer.
tf.keras.backend.clear_session()tf.random.set_seed(60)model=keras.models.Sequential([ keras.layers.Dense(512, input_dim = X_train.shape[1], activation='relu'), keras.layers.Dense(512, input_dim = X_train.shape[1], activation='relu'), keras.layers.Dense(units=256,activation='relu'), keras.layers.Dense(units=256,activation='relu'), keras.layers.Dense(units=128,activation='relu'), keras.layers.Dense(units=1, activation="linear"),],name="Initial_model",)model.summary()
We use Adam optimizer and start with training each model for 200 epochs — this part of the model configuration will be kept constant up to point 7.
optimizer = keras.optimizers.Adam()model.compile(optimizer=optimizer, warm_start=False, loss='mean_absolute_error')history = model.fit(X_train, y_train, epochs=200, batch_size=1024, validation_data=(X_test, y_test), verbose=1)
Our first model turned out to be quite a failure, we have horrendous overfitting on Training data and our Validation Loss is actually increasing after epoch 100.
Drop out is probably the best answer to DNN regularization and works with all types of network sizes and architectures. Applying Dropout randomly drops a portion of neurons in a layer in each epoch during training, which forces the remaining neurons to be more versatile — this decreases overfitting as one Neuron can no longer map one specific instance as it will not always be there during training.
I advise reading the original paper as it describes the idea very well and does not require years of academic experience to understand it — Dropout: A Simple Way to Prevent Neural Networks from Overfitting
tf.keras.backend.clear_session()tf.random.set_seed(60)model=keras.models.Sequential([ keras.layers.Dense(512, input_dim = X_train.shape[1], activation='relu'), keras.layers.Dropout(0.3), keras.layers.Dense(512, activation='relu'), keras.layers.Dropout(0.3),keras.layers.Dense(units=256,activation='relu'), keras.layers.Dropout(0.2), keras.layers.Dense(units=256,activation='relu'), keras.layers.Dropout(0.2), keras.layers.Dense(units=128,activation='relu'), keras.layers.Dense(units=1, activation="linear"),],name="Dropout",)
The (0.x) after Dropout specifies what share of Neurons you want to drop, which translates into how much you want to regularize. I usually start with dropout around (0.3–0.5) in the largest layer and then reduce its rigidness in deeper layers. The idea behind such approach is that neurons in deeper networks tend to have more specific tasks and therefore dropping too many will increase bias too much.
Analyzing learning curve for the modified model we can see that we are going in the right direction. First of all we managed to make progress from the Validation Loss of the previous model (marked by the grey threshold line), secondly, we seem to replace overfitting with a slight underfit.
When working with several layers with RELU activation we have a significant risk of dying neurons having a negative effect on our performance. This can lead to underfitting we could see in the previous model as we might actually not be using a large share of our neurons, which basically reduced their outputs to 0.
Batch Normalization is one of the best ways to handle this issue — when applied we normalize activation outputs of each layer for each batch to reduce the effect of extreme activations on parameter training, which in turn reduces the risk of vanishing/exploding gradients. The original paper describing the solution is more complicated to read than the previous one referenced but I would still suggest giving it a try — Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift
tf.keras.backend.clear_session()tf.random.set_seed(60)model=keras.models.Sequential([ keras.layers.Dense(512, input_dim = X_train.shape[1], activation='relu'), keras.layers.BatchNormalization(), keras.layers.Dropout(0.3), keras.layers.Dense(512, activation='relu'), keras.layers.BatchNormalization(), keras.layers.Dropout(0.3),keras.layers.Dense(units=256,activation='relu'), keras.layers.BatchNormalization(), keras.layers.Dropout(0.2), keras.layers.Dense(units=256,activation='relu'), keras.layers.BatchNormalization(), keras.layers.Dropout(0.2), keras.layers.Dense(units=128,activation='relu'), keras.layers.Dense(units=1, activation="linear"),],name="Batchnorm",)
Adding Batch Normalization helped us to bring some of the neurons back to life, which increased our model variance changing underfitting to slight overfitting — training neural networks is often a game of cat and mouse, balancing between optimal bias and variance.
Another good news is that we still are improving in terms of a validation error.
Leaky RELU activation function is a slight modification of RELU function, which allows some negative activations to leak through, further reducing the risk of dying neurons. Leaky RELU usually takes longer to train, which is why we will train this model for another 100 epochs.
tf.keras.backend.clear_session()tf.random.set_seed(60)model=keras.models.Sequential([ keras.layers.Dense(512, input_dim = X_train.shape[1]), keras.layers.LeakyReLU(), keras.layers.BatchNormalization(), keras.layers.Dropout(0.3), keras.layers.Dense(512), keras.layers.LeakyReLU(), keras.layers.BatchNormalization(), keras.layers.Dropout(0.3),keras.layers.Dense(units=256), keras.layers.LeakyReLU(), keras.layers.BatchNormalization(), keras.layers.Dropout(0.2), keras.layers.Dense(units=256), keras.layers.LeakyReLU(), keras.layers.BatchNormalization(), keras.layers.Dropout(0.2), keras.layers.Dense(units=128), keras.layers.LeakyReLU(), keras.layers.Dense(units=1, activation="linear"),],name="LeakyRELU",)
It seems Leaky RELU reduced the overfitting and gave us a healthier learning curve, where we can see the potential for improvement even after 300 epochs. We nearly reached the lowest error from previous model, but we managed to do that without overfitting, which leaves us space for increasing variance.
At this point, I am happy enough with the basic model to make the network larger by adding another hidden layer with 1024 neurons. The new layer also has the highest dropout rate. I also experimented with dropout rates for lower levels due to change in the overall architecture.
tf.keras.backend.clear_session()tf.random.set_seed(60)model=keras.models.Sequential([ keras.layers.Dense(1024, input_dim = X_train.shape[1]), keras.layers.LeakyReLU(), keras.layers.BatchNormalization(), keras.layers.Dropout(0.4), keras.layers.Dense(512), keras.layers.LeakyReLU(), keras.layers.BatchNormalization(), keras.layers.Dropout(0.3),keras.layers.Dense(512), keras.layers.LeakyReLU(), keras.layers.BatchNormalization(), keras.layers.Dropout(0.3), keras.layers.Dense(units=256), keras.layers.LeakyReLU(), keras.layers.BatchNormalization(), keras.layers.Dropout(0.2), keras.layers.Dense(units=256), keras.layers.LeakyReLU(), keras.layers.BatchNormalization(), keras.layers.Dropout(0.01),keras.layers.Dense(units=128), keras.layers.LeakyReLU(), keras.layers.Dropout(0.05), keras.layers.Dense(units=1, activation="linear"),],name="Larger_network",)
Expanding network architecture seems to be going in the right direction, we increased variance slightly getting learning curve, which is close to optimal balance. We also managed to get our Validation Loss nearly on par with the overfitted BatchNorm model.
Once we are happy with the network architecture, Learning Rate is the most important hyperparameter, which needs tuning. I decided to use learning rate decay, which allows me to train my model faster at the beginning and then decrease the learning rate with further epochs to make training more precise.
optimizer = keras.optimizers.Adam(lr=0.005, decay=5e-4)
Selecting the right starting rate and decay can be challenging and takes some trial and error. In my case it turned out that the default Adam learning rate in Keras, which is 0.001 was a bit high. I started with a Learning rate of 0.005 and over 400 epochs decreased it to 0.001.
Tuning Learning Rate helped us to finally improve our validation error result, while still keeping the learning curve healthy without too much risk of overfitting — there might even be some space for training the model for another 100 epochs.
The last task remaining before choosing our best model is to use CallBacks to stop training at the optimal epoch. This allows us to retrieve the model at the exact epoch, where we reached minimall error. The big advantage of this solution is that you do not really need to worry if you want to train for 300 or 600 epochs — if your model starts overfitting the Call Back will get you back to the optimal epoch.
checkpoint_name = 'Weights\Weights-{epoch:03d}--{val_loss:.5f}.hdf5' checkpoint = ModelCheckpoint(checkpoint_name, monitor='val_loss', verbose = 1, save_best_only = True, mode ='auto')callbacks_list = [checkpoint]
You need to define your callbacks: checkpoint_name specifying where and how you want to save weights for each epoch, checkpoint specifies how the CallBack should behave —I advise monitoring val_loss for improvement and saving only if the epoch made some progress on that.
history = model.fit(X_train, y_train, epochs=500, batch_size=1024, validation_data=(X_test, y_test), callbacks=callbacks_list, verbose=1)
Then all you need to do is to add callbacks while fitting your model.
Using Callbacks allowed us to retrieve the optimal model trained at epoch 468 — the next 30 epochs did not improve as we started to overfit the train set.
It took us 7 steps in order to get to the desired model output. We managed to improve at nearly every step, with a plateau between batch_norm and 1024_layer model, when our key goal was to reduce overfitting. To be honest refining these 7 steps, probably took me 70 steps so bear in mind that training DNNs is an interative process and don’t be put off if your improvement stagnates for a few hours.
Finally, how did our best DNN perform in comparison to a base Random Forest Regressor trained on the same data in the previous article?
In two key KPIs our Random Forest scored as follows:
Share of forecasts within 5% absolute error = 44.6%
Mean percentage error = 8.8%
Our best Deep Neural Network scored:
Share of forecasts within 5% absolute error = 43.3% (-1.3 p.p.)
Mean percentage error = 9.1% (+0.3 p.p.)
Can we cry now? How is it possible that after hours of meticulous training our advanced neural network did not beat a Random Forest? To be honest there are two key reasons:
A sample size of 25k records is still quite small in terms of training DNNs, I choose to give this architecture a try as I am gathering new data every month and I am confident that within a few months I will reach samples closer to 100k, which should give DNN the needed edge
The Random Forest model was quite overfitted and I am not confident that it would generalize well too other properties, despite high performance on validation set — at this point, I would probably still use the DNN model in production as more reliable.
To summarize — I would advise against starting the solving of a regression problem with DNN. Unless you are working with hundreds of k samples on a really complex project, a Random Forest Regressor will usually be much faster to get initial results — if they prove to be promising you can proceed to DNN. Training efficient DNN takes more time and if your data sample is not large enough it might never reach Random Forest performance.
[1]: Nitish Srivastava. (June 14 2014). Dropout: A Simple Way to Prevent Neural Networks from Overfitting
[2]: Sergey Ioffe. (Mar 2 2015). Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift | [
{
"code": null,
"e": 391,
"s": 172,
"text": "Using Deep Neural Networks for regression problems might seem like overkill (and quite often is), but for some cases where you have a significant amount of high dimensional data they can outperform any other ML models."
},
{
"code": null,
"e": 610,
"s": 391,
"text": "When you learn about Neural Networks you usually start with some image classification problem like the MNIST dataset — this is an obvious choice as advanced tasks with high dimensional data is where DNNs really thrive."
},
{
"code": null,
"e": 861,
"s": 610,
"text": "Surprisingly, when you try to apply what you learned on MNIST on a regression tasks you might struggle for a while before your super-advanced DNN model is any better than a basic Random Forest Regressor. Sometimes you might never reach that moment..."
},
{
"code": null,
"e": 1290,
"s": 861,
"text": "In this guide, I listed some key tips and tricks learned while using DNN for regression problems. The data is a set of nearly 50 features describing 25k properties in Warsaw. I described the feature selection process in my previous article: feature-selection-and-error-analysis-while-working-with-spatial-data so now we will focus on creating the best possible model predicting property price per m2 using the selected features."
},
{
"code": null,
"e": 1361,
"s": 1290,
"text": "The code and data source used for this article can be found on GitHub."
},
{
"code": null,
"e": 1431,
"s": 1361,
"text": "When training a Deep Neural Network I usually follow these key steps:"
},
{
"code": null,
"e": 1508,
"s": 1431,
"text": "A) Choose a default architecture — no. of layers, no. of neurons, activation"
},
{
"code": null,
"e": 1528,
"s": 1508,
"text": "B) Regularize model"
},
{
"code": null,
"e": 1559,
"s": 1528,
"text": "C) Adjust network architecture"
},
{
"code": null,
"e": 1605,
"s": 1559,
"text": "D) Adjust the learning rate and no. of epochs"
},
{
"code": null,
"e": 1646,
"s": 1605,
"text": "E) Extract optimal model using CallBacks"
},
{
"code": null,
"e": 1954,
"s": 1646,
"text": "Usually creating the final model takes a few runs through all of these steps but an important thing to remember is: DO ONE THING AT A TIME. Don’t try to change architecture, regularization, and learning rate at the same time as you will not know what really worked and probably spend hours going in circles."
},
{
"code": null,
"e": 2052,
"s": 1954,
"text": "Before you start building any DNNs for regression tasks there are 3 key things you must remember:"
},
{
"code": null,
"e": 2105,
"s": 2052,
"text": "Standarize your data to make training more efficient"
},
{
"code": null,
"e": 2216,
"s": 2105,
"text": "Use RELU activation function for all hidden layers — you will be going nowhere with default sigmoid activation"
},
{
"code": null,
"e": 2282,
"s": 2216,
"text": "Use Linear activation function for the single-neuron output layer"
},
{
"code": null,
"e": 2680,
"s": 2282,
"text": "Another important task is selecting the loss function. Mean Squared Error or Mean Absolute Error are the two most common choices. As my goal to minimize the average percentage error and maximize the share of all buildings within 5% error I choose MAE, as it penalizes outliers less and is easier to interpret — it pretty much tells you how many $$/m2 on average each offer is off the actual value."
},
{
"code": null,
"e": 2842,
"s": 2680,
"text": "There is also a function directly linked to my goal — Mean Absolute Percentage Error, but after testing it against MAE I found the training to be less efficient."
},
{
"code": null,
"e": 2951,
"s": 2842,
"text": "We start with a basic network with 5 hidden layers and a decreasing number of neurons in every second layer."
},
{
"code": null,
"e": 3453,
"s": 2951,
"text": "tf.keras.backend.clear_session()tf.random.set_seed(60)model=keras.models.Sequential([ keras.layers.Dense(512, input_dim = X_train.shape[1], activation='relu'), keras.layers.Dense(512, input_dim = X_train.shape[1], activation='relu'), keras.layers.Dense(units=256,activation='relu'), keras.layers.Dense(units=256,activation='relu'), keras.layers.Dense(units=128,activation='relu'), keras.layers.Dense(units=1, activation=\"linear\"),],name=\"Initial_model\",)model.summary()"
},
{
"code": null,
"e": 3601,
"s": 3453,
"text": "We use Adam optimizer and start with training each model for 200 epochs — this part of the model configuration will be kept constant up to point 7."
},
{
"code": null,
"e": 3898,
"s": 3601,
"text": "optimizer = keras.optimizers.Adam()model.compile(optimizer=optimizer, warm_start=False, loss='mean_absolute_error')history = model.fit(X_train, y_train, epochs=200, batch_size=1024, validation_data=(X_test, y_test), verbose=1)"
},
{
"code": null,
"e": 4060,
"s": 3898,
"text": "Our first model turned out to be quite a failure, we have horrendous overfitting on Training data and our Validation Loss is actually increasing after epoch 100."
},
{
"code": null,
"e": 4462,
"s": 4060,
"text": "Drop out is probably the best answer to DNN regularization and works with all types of network sizes and architectures. Applying Dropout randomly drops a portion of neurons in a layer in each epoch during training, which forces the remaining neurons to be more versatile — this decreases overfitting as one Neuron can no longer map one specific instance as it will not always be there during training."
},
{
"code": null,
"e": 4668,
"s": 4462,
"text": "I advise reading the original paper as it describes the idea very well and does not require years of academic experience to understand it — Dropout: A Simple Way to Prevent Neural Networks from Overfitting"
},
{
"code": null,
"e": 5243,
"s": 4668,
"text": "tf.keras.backend.clear_session()tf.random.set_seed(60)model=keras.models.Sequential([ keras.layers.Dense(512, input_dim = X_train.shape[1], activation='relu'), keras.layers.Dropout(0.3), keras.layers.Dense(512, activation='relu'), keras.layers.Dropout(0.3),keras.layers.Dense(units=256,activation='relu'), keras.layers.Dropout(0.2), keras.layers.Dense(units=256,activation='relu'), keras.layers.Dropout(0.2), keras.layers.Dense(units=128,activation='relu'), keras.layers.Dense(units=1, activation=\"linear\"),],name=\"Dropout\",)"
},
{
"code": null,
"e": 5646,
"s": 5243,
"text": "The (0.x) after Dropout specifies what share of Neurons you want to drop, which translates into how much you want to regularize. I usually start with dropout around (0.3–0.5) in the largest layer and then reduce its rigidness in deeper layers. The idea behind such approach is that neurons in deeper networks tend to have more specific tasks and therefore dropping too many will increase bias too much."
},
{
"code": null,
"e": 5937,
"s": 5646,
"text": "Analyzing learning curve for the modified model we can see that we are going in the right direction. First of all we managed to make progress from the Validation Loss of the previous model (marked by the grey threshold line), secondly, we seem to replace overfitting with a slight underfit."
},
{
"code": null,
"e": 6253,
"s": 5937,
"text": "When working with several layers with RELU activation we have a significant risk of dying neurons having a negative effect on our performance. This can lead to underfitting we could see in the previous model as we might actually not be using a large share of our neurons, which basically reduced their outputs to 0."
},
{
"code": null,
"e": 6767,
"s": 6253,
"text": "Batch Normalization is one of the best ways to handle this issue — when applied we normalize activation outputs of each layer for each batch to reduce the effect of extreme activations on parameter training, which in turn reduces the risk of vanishing/exploding gradients. The original paper describing the solution is more complicated to read than the previous one referenced but I would still suggest giving it a try — Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift"
},
{
"code": null,
"e": 7495,
"s": 6767,
"text": "tf.keras.backend.clear_session()tf.random.set_seed(60)model=keras.models.Sequential([ keras.layers.Dense(512, input_dim = X_train.shape[1], activation='relu'), keras.layers.BatchNormalization(), keras.layers.Dropout(0.3), keras.layers.Dense(512, activation='relu'), keras.layers.BatchNormalization(), keras.layers.Dropout(0.3),keras.layers.Dense(units=256,activation='relu'), keras.layers.BatchNormalization(), keras.layers.Dropout(0.2), keras.layers.Dense(units=256,activation='relu'), keras.layers.BatchNormalization(), keras.layers.Dropout(0.2), keras.layers.Dense(units=128,activation='relu'), keras.layers.Dense(units=1, activation=\"linear\"),],name=\"Batchnorm\",)"
},
{
"code": null,
"e": 7760,
"s": 7495,
"text": "Adding Batch Normalization helped us to bring some of the neurons back to life, which increased our model variance changing underfitting to slight overfitting — training neural networks is often a game of cat and mouse, balancing between optimal bias and variance."
},
{
"code": null,
"e": 7841,
"s": 7760,
"text": "Another good news is that we still are improving in terms of a validation error."
},
{
"code": null,
"e": 8119,
"s": 7841,
"text": "Leaky RELU activation function is a slight modification of RELU function, which allows some negative activations to leak through, further reducing the risk of dying neurons. Leaky RELU usually takes longer to train, which is why we will train this model for another 100 epochs."
},
{
"code": null,
"e": 8901,
"s": 8119,
"text": "tf.keras.backend.clear_session()tf.random.set_seed(60)model=keras.models.Sequential([ keras.layers.Dense(512, input_dim = X_train.shape[1]), keras.layers.LeakyReLU(), keras.layers.BatchNormalization(), keras.layers.Dropout(0.3), keras.layers.Dense(512), keras.layers.LeakyReLU(), keras.layers.BatchNormalization(), keras.layers.Dropout(0.3),keras.layers.Dense(units=256), keras.layers.LeakyReLU(), keras.layers.BatchNormalization(), keras.layers.Dropout(0.2), keras.layers.Dense(units=256), keras.layers.LeakyReLU(), keras.layers.BatchNormalization(), keras.layers.Dropout(0.2), keras.layers.Dense(units=128), keras.layers.LeakyReLU(), keras.layers.Dense(units=1, activation=\"linear\"),],name=\"LeakyRELU\",)"
},
{
"code": null,
"e": 9205,
"s": 8901,
"text": "It seems Leaky RELU reduced the overfitting and gave us a healthier learning curve, where we can see the potential for improvement even after 300 epochs. We nearly reached the lowest error from previous model, but we managed to do that without overfitting, which leaves us space for increasing variance."
},
{
"code": null,
"e": 9484,
"s": 9205,
"text": "At this point, I am happy enough with the basic model to make the network larger by adding another hidden layer with 1024 neurons. The new layer also has the highest dropout rate. I also experimented with dropout rates for lower levels due to change in the overall architecture."
},
{
"code": null,
"e": 10427,
"s": 9484,
"text": "tf.keras.backend.clear_session()tf.random.set_seed(60)model=keras.models.Sequential([ keras.layers.Dense(1024, input_dim = X_train.shape[1]), keras.layers.LeakyReLU(), keras.layers.BatchNormalization(), keras.layers.Dropout(0.4), keras.layers.Dense(512), keras.layers.LeakyReLU(), keras.layers.BatchNormalization(), keras.layers.Dropout(0.3),keras.layers.Dense(512), keras.layers.LeakyReLU(), keras.layers.BatchNormalization(), keras.layers.Dropout(0.3), keras.layers.Dense(units=256), keras.layers.LeakyReLU(), keras.layers.BatchNormalization(), keras.layers.Dropout(0.2), keras.layers.Dense(units=256), keras.layers.LeakyReLU(), keras.layers.BatchNormalization(), keras.layers.Dropout(0.01),keras.layers.Dense(units=128), keras.layers.LeakyReLU(), keras.layers.Dropout(0.05), keras.layers.Dense(units=1, activation=\"linear\"),],name=\"Larger_network\",)"
},
{
"code": null,
"e": 10684,
"s": 10427,
"text": "Expanding network architecture seems to be going in the right direction, we increased variance slightly getting learning curve, which is close to optimal balance. We also managed to get our Validation Loss nearly on par with the overfitted BatchNorm model."
},
{
"code": null,
"e": 10988,
"s": 10684,
"text": "Once we are happy with the network architecture, Learning Rate is the most important hyperparameter, which needs tuning. I decided to use learning rate decay, which allows me to train my model faster at the beginning and then decrease the learning rate with further epochs to make training more precise."
},
{
"code": null,
"e": 11044,
"s": 10988,
"text": "optimizer = keras.optimizers.Adam(lr=0.005, decay=5e-4)"
},
{
"code": null,
"e": 11324,
"s": 11044,
"text": "Selecting the right starting rate and decay can be challenging and takes some trial and error. In my case it turned out that the default Adam learning rate in Keras, which is 0.001 was a bit high. I started with a Learning rate of 0.005 and over 400 epochs decreased it to 0.001."
},
{
"code": null,
"e": 11567,
"s": 11324,
"text": "Tuning Learning Rate helped us to finally improve our validation error result, while still keeping the learning curve healthy without too much risk of overfitting — there might even be some space for training the model for another 100 epochs."
},
{
"code": null,
"e": 11978,
"s": 11567,
"text": "The last task remaining before choosing our best model is to use CallBacks to stop training at the optimal epoch. This allows us to retrieve the model at the exact epoch, where we reached minimall error. The big advantage of this solution is that you do not really need to worry if you want to train for 300 or 600 epochs — if your model starts overfitting the Call Back will get you back to the optimal epoch."
},
{
"code": null,
"e": 12192,
"s": 11978,
"text": "checkpoint_name = 'Weights\\Weights-{epoch:03d}--{val_loss:.5f}.hdf5' checkpoint = ModelCheckpoint(checkpoint_name, monitor='val_loss', verbose = 1, save_best_only = True, mode ='auto')callbacks_list = [checkpoint]"
},
{
"code": null,
"e": 12464,
"s": 12192,
"text": "You need to define your callbacks: checkpoint_name specifying where and how you want to save weights for each epoch, checkpoint specifies how the CallBack should behave —I advise monitoring val_loss for improvement and saving only if the epoch made some progress on that."
},
{
"code": null,
"e": 12680,
"s": 12464,
"text": "history = model.fit(X_train, y_train, epochs=500, batch_size=1024, validation_data=(X_test, y_test), callbacks=callbacks_list, verbose=1)"
},
{
"code": null,
"e": 12750,
"s": 12680,
"text": "Then all you need to do is to add callbacks while fitting your model."
},
{
"code": null,
"e": 12905,
"s": 12750,
"text": "Using Callbacks allowed us to retrieve the optimal model trained at epoch 468 — the next 30 epochs did not improve as we started to overfit the train set."
},
{
"code": null,
"e": 13305,
"s": 12905,
"text": "It took us 7 steps in order to get to the desired model output. We managed to improve at nearly every step, with a plateau between batch_norm and 1024_layer model, when our key goal was to reduce overfitting. To be honest refining these 7 steps, probably took me 70 steps so bear in mind that training DNNs is an interative process and don’t be put off if your improvement stagnates for a few hours."
},
{
"code": null,
"e": 13441,
"s": 13305,
"text": "Finally, how did our best DNN perform in comparison to a base Random Forest Regressor trained on the same data in the previous article?"
},
{
"code": null,
"e": 13494,
"s": 13441,
"text": "In two key KPIs our Random Forest scored as follows:"
},
{
"code": null,
"e": 13546,
"s": 13494,
"text": "Share of forecasts within 5% absolute error = 44.6%"
},
{
"code": null,
"e": 13575,
"s": 13546,
"text": "Mean percentage error = 8.8%"
},
{
"code": null,
"e": 13612,
"s": 13575,
"text": "Our best Deep Neural Network scored:"
},
{
"code": null,
"e": 13676,
"s": 13612,
"text": "Share of forecasts within 5% absolute error = 43.3% (-1.3 p.p.)"
},
{
"code": null,
"e": 13717,
"s": 13676,
"text": "Mean percentage error = 9.1% (+0.3 p.p.)"
},
{
"code": null,
"e": 13890,
"s": 13717,
"text": "Can we cry now? How is it possible that after hours of meticulous training our advanced neural network did not beat a Random Forest? To be honest there are two key reasons:"
},
{
"code": null,
"e": 14166,
"s": 13890,
"text": "A sample size of 25k records is still quite small in terms of training DNNs, I choose to give this architecture a try as I am gathering new data every month and I am confident that within a few months I will reach samples closer to 100k, which should give DNN the needed edge"
},
{
"code": null,
"e": 14419,
"s": 14166,
"text": "The Random Forest model was quite overfitted and I am not confident that it would generalize well too other properties, despite high performance on validation set — at this point, I would probably still use the DNN model in production as more reliable."
},
{
"code": null,
"e": 14855,
"s": 14419,
"text": "To summarize — I would advise against starting the solving of a regression problem with DNN. Unless you are working with hundreds of k samples on a really complex project, a Random Forest Regressor will usually be much faster to get initial results — if they prove to be promising you can proceed to DNN. Training efficient DNN takes more time and if your data sample is not large enough it might never reach Random Forest performance."
},
{
"code": null,
"e": 14961,
"s": 14855,
"text": "[1]: Nitish Srivastava. (June 14 2014). Dropout: A Simple Way to Prevent Neural Networks from Overfitting"
}
] |
Generating Errors using HTTP-errors module in Node.js - GeeksforGeeks | 06 Jul, 2021
HTTP-errors module is used for generating errors for Node.js applications. It is very easy to use. We can use it with express, Koa, etc. applications. We will implement this module in an express application.
Installation and Setup: First, initialize the application with package.json file with the following command:
npm init
Then, install the module by the following command:
npm install http-errors --save
Also, we are using an express application, therefore, install the express module by the following command:
npm install express --save
Now, create a file and name it app.js. You can name your file whatever you want.
For importing the modules in your application, write the following code in your app.js file:
javascript
const createError = require('http-errors');const express = require('express');const app = express();
Implementation: Here, comes the main part of our application. For using this module, write the following code in your app.js file:
javascript
var createError = require('http-errors');var express = require('express');var app = express(); app.use((req, res, next) => { if (!req.user) return next( createError(401, 'Login Required!!')); next();}); app.listen(8080, (err) => { if (err) console.log(err); console.log(`Server Running at http://localhost:8080`);});
Here, we are importing the http-errors module and storing it in a variable named as createError. Next, in app.use(), if the user is not authenticated, then our application will create a 401 error saying Login Required!!. The createError is used for generating errors in an application.
To run the code, run the following command in the terminal:
node app.js
and navigate to http://localhost:8080. The output for the above code will be:
List of all Status Code with their Error Message:
Status
Code Error Message
400 BadRequest
401 Unauthorized
402 PaymentRequired
403 Forbidden
404 NotFound
405 MethodNotAllowed
406 NotAcceptable
407 ProxyAuthenticationRequired
408 RequestTimeout
409 Conflict
410 Gone
411 LengthRequired
412 PreconditionFailed
413 PayloadTooLarge
414 URITooLong
415 UnsupportedMediaType
416 RangeNotSatisfiable
417 ExpectationFailed
418 ImATeapot
421 MisdirectedRequest
422 UnprocessableEntity
423 Locked
424 FailedDependency
425 UnorderedCollection
426 UpgradeRequired
428 PreconditionRequired
429 TooManyRequests
431 RequestHeaderFieldsTooLarge
451 UnavailableForLegalReasons
500 InternalServerError
501 NotImplemented
502 BadGateway
503 ServiceUnavailable
504 GatewayTimeout
505 HTTPVersionNotSupported
506 VariantAlsoNegotiates
507 InsufficientStorage
508 LoopDetected
509 BandwidthLimitExceeded
510 NotExtended
511 NetworkAuthenticationRequired
Conclusion: The http-errors module is very useful for developers for quick generation of errors with their message. In this article, we learned about the http-errors module for Node.js. We have also seen its installation and Implementation.
gabaa406
Node.js-Misc
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Express.js express.Router() Function
Node.js fs.readFile() Method
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
Roadmap to Become a Web Developer in 2022
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Convert a string to an integer in JavaScript | [
{
"code": null,
"e": 24664,
"s": 24636,
"text": "\n06 Jul, 2021"
},
{
"code": null,
"e": 24872,
"s": 24664,
"text": "HTTP-errors module is used for generating errors for Node.js applications. It is very easy to use. We can use it with express, Koa, etc. applications. We will implement this module in an express application."
},
{
"code": null,
"e": 24983,
"s": 24872,
"text": "Installation and Setup: First, initialize the application with package.json file with the following command: "
},
{
"code": null,
"e": 24992,
"s": 24983,
"text": "npm init"
},
{
"code": null,
"e": 25045,
"s": 24994,
"text": "Then, install the module by the following command:"
},
{
"code": null,
"e": 25078,
"s": 25047,
"text": "npm install http-errors --save"
},
{
"code": null,
"e": 25187,
"s": 25080,
"text": "Also, we are using an express application, therefore, install the express module by the following command:"
},
{
"code": null,
"e": 25216,
"s": 25189,
"text": "npm install express --save"
},
{
"code": null,
"e": 25299,
"s": 25218,
"text": "Now, create a file and name it app.js. You can name your file whatever you want."
},
{
"code": null,
"e": 25394,
"s": 25301,
"text": "For importing the modules in your application, write the following code in your app.js file:"
},
{
"code": null,
"e": 25407,
"s": 25396,
"text": "javascript"
},
{
"code": "const createError = require('http-errors');const express = require('express');const app = express();",
"e": 25508,
"s": 25407,
"text": null
},
{
"code": null,
"e": 25640,
"s": 25508,
"text": "Implementation: Here, comes the main part of our application. For using this module, write the following code in your app.js file: "
},
{
"code": null,
"e": 25651,
"s": 25640,
"text": "javascript"
},
{
"code": "var createError = require('http-errors');var express = require('express');var app = express(); app.use((req, res, next) => { if (!req.user) return next( createError(401, 'Login Required!!')); next();}); app.listen(8080, (err) => { if (err) console.log(err); console.log(`Server Running at http://localhost:8080`);});",
"e": 25980,
"s": 25651,
"text": null
},
{
"code": null,
"e": 26266,
"s": 25980,
"text": "Here, we are importing the http-errors module and storing it in a variable named as createError. Next, in app.use(), if the user is not authenticated, then our application will create a 401 error saying Login Required!!. The createError is used for generating errors in an application."
},
{
"code": null,
"e": 26326,
"s": 26266,
"text": "To run the code, run the following command in the terminal:"
},
{
"code": null,
"e": 26338,
"s": 26326,
"text": "node app.js"
},
{
"code": null,
"e": 26416,
"s": 26338,
"text": "and navigate to http://localhost:8080. The output for the above code will be:"
},
{
"code": null,
"e": 26468,
"s": 26416,
"text": "List of all Status Code with their Error Message: "
},
{
"code": null,
"e": 27477,
"s": 26468,
"text": "Status\nCode Error Message\n\n400 BadRequest\n401 Unauthorized\n402 PaymentRequired\n403 Forbidden\n404 NotFound\n405 MethodNotAllowed\n406 NotAcceptable\n407 ProxyAuthenticationRequired\n408 RequestTimeout\n409 Conflict\n410 Gone\n411 LengthRequired\n412 PreconditionFailed\n413 PayloadTooLarge\n414 URITooLong\n415 UnsupportedMediaType\n416 RangeNotSatisfiable\n417 ExpectationFailed\n418 ImATeapot\n421 MisdirectedRequest\n422 UnprocessableEntity\n423 Locked\n424 FailedDependency\n425 UnorderedCollection\n426 UpgradeRequired\n428 PreconditionRequired\n429 TooManyRequests\n431 RequestHeaderFieldsTooLarge\n451 UnavailableForLegalReasons\n500 InternalServerError\n501 NotImplemented\n502 BadGateway\n503 ServiceUnavailable\n504 GatewayTimeout\n505 HTTPVersionNotSupported\n506 VariantAlsoNegotiates\n507 InsufficientStorage\n508 LoopDetected\n509 BandwidthLimitExceeded\n510 NotExtended\n511 NetworkAuthenticationRequired"
},
{
"code": null,
"e": 27719,
"s": 27477,
"text": "Conclusion: The http-errors module is very useful for developers for quick generation of errors with their message. In this article, we learned about the http-errors module for Node.js. We have also seen its installation and Implementation. "
},
{
"code": null,
"e": 27728,
"s": 27719,
"text": "gabaa406"
},
{
"code": null,
"e": 27741,
"s": 27728,
"text": "Node.js-Misc"
},
{
"code": null,
"e": 27749,
"s": 27741,
"text": "Node.js"
},
{
"code": null,
"e": 27766,
"s": 27749,
"text": "Web Technologies"
},
{
"code": null,
"e": 27864,
"s": 27766,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27873,
"s": 27864,
"text": "Comments"
},
{
"code": null,
"e": 27886,
"s": 27873,
"text": "Old Comments"
},
{
"code": null,
"e": 27923,
"s": 27886,
"text": "Express.js express.Router() Function"
},
{
"code": null,
"e": 27952,
"s": 27923,
"text": "Node.js fs.readFile() Method"
},
{
"code": null,
"e": 27982,
"s": 27952,
"text": "Node.js fs.writeFile() Method"
},
{
"code": null,
"e": 28039,
"s": 27982,
"text": "How to install the previous version of node.js and npm ?"
},
{
"code": null,
"e": 28093,
"s": 28039,
"text": "Difference between promise and async await in Node.js"
},
{
"code": null,
"e": 28135,
"s": 28093,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 28197,
"s": 28135,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 28240,
"s": 28197,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 28290,
"s": 28240,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Auto-scrolling animation in React.js using react-spring | In this article, we will see how to create a scroll to top animation in React JS using the react-spring package.
First create a react project −
npx create-react-app tutorialpurpose
Now go to the project directory −
cd tutorialpurpose
Install the react-spring package −
npm install react-spring
react-spring is used to add Spring concept based animations to our website.
Next,Add the following lines of code in App.js −
import React,{useState} from 'react'
import { useSpring, animated } from 'react-spring'
export default function App(){
const [flip, set] = useState(false)
const words = ['We', 'came.', 'We', 'saw.', 'We', 'hold', 'it s', 'hands.']
const { scroll } = useSpring({
scroll: (words.length - 1) * 50,
from: { scroll: 0 },
reset: true,
reverse: flip,
delay: 200,
onRest: () => set(!flip),
})
return (
<animated.div
style={{
position: 'relative',
width: '100%',
height: 60,
overflow: 'auto',
fontSize: '1em',
marginTop:200 ,
border:"1px solid black"
}}
scrollTop={scroll}>
{words.map((word, i) => (
<div
key={`${word}_${i}`}
style={{ width: '100%', height: 50, textAlign: 'center' }}>
{word}
</div>
))}
</animated.div>
)
}
In the scroll attribute of spring object, we defined how much we have to scroll. If you change the value from 50 to 20, it will only scroll three words
The from attribute indicates from where to start scrolling; "0" means start scrolling from the beginning.
We also have some extra attributes like
reset which is meant for looping
reset which is meant for looping
reverse signifies when the counting should start or end,
reverse signifies when the counting should start or end,
delay to introduce time delay between animation, and
delay to introduce time delay between animation, and
onRest indicates what to do on when the counting stops.
onRest indicates what to do on when the counting stops.
On execution, it will produce the following output −
Your browser does not support HTML5 video. | [
{
"code": null,
"e": 1175,
"s": 1062,
"text": "In this article, we will see how to create a scroll to top animation in React JS using the react-spring package."
},
{
"code": null,
"e": 1206,
"s": 1175,
"text": "First create a react project −"
},
{
"code": null,
"e": 1243,
"s": 1206,
"text": "npx create-react-app tutorialpurpose"
},
{
"code": null,
"e": 1277,
"s": 1243,
"text": "Now go to the project directory −"
},
{
"code": null,
"e": 1296,
"s": 1277,
"text": "cd tutorialpurpose"
},
{
"code": null,
"e": 1331,
"s": 1296,
"text": "Install the react-spring package −"
},
{
"code": null,
"e": 1356,
"s": 1331,
"text": "npm install react-spring"
},
{
"code": null,
"e": 1432,
"s": 1356,
"text": "react-spring is used to add Spring concept based animations to our website."
},
{
"code": null,
"e": 1481,
"s": 1432,
"text": "Next,Add the following lines of code in App.js −"
},
{
"code": null,
"e": 2412,
"s": 1481,
"text": "import React,{useState} from 'react'\nimport { useSpring, animated } from 'react-spring'\n\nexport default function App(){\n const [flip, set] = useState(false)\n\n const words = ['We', 'came.', 'We', 'saw.', 'We', 'hold', 'it s', 'hands.']\n\n const { scroll } = useSpring({\n scroll: (words.length - 1) * 50,\n from: { scroll: 0 },\n reset: true,\n reverse: flip,\n delay: 200,\n onRest: () => set(!flip),\n })\n return (\n <animated.div\n style={{\n position: 'relative',\n width: '100%',\n height: 60,\n overflow: 'auto',\n fontSize: '1em',\n marginTop:200 ,\n border:\"1px solid black\"\n }}\n scrollTop={scroll}>\n {words.map((word, i) => (\n <div\n key={`${word}_${i}`}\n style={{ width: '100%', height: 50, textAlign: 'center' }}>\n {word}\n </div>\n ))}\n </animated.div>\n )\n}"
},
{
"code": null,
"e": 2564,
"s": 2412,
"text": "In the scroll attribute of spring object, we defined how much we have to scroll. If you change the value from 50 to 20, it will only scroll three words"
},
{
"code": null,
"e": 2670,
"s": 2564,
"text": "The from attribute indicates from where to start scrolling; \"0\" means start scrolling from the beginning."
},
{
"code": null,
"e": 2710,
"s": 2670,
"text": "We also have some extra attributes like"
},
{
"code": null,
"e": 2743,
"s": 2710,
"text": "reset which is meant for looping"
},
{
"code": null,
"e": 2776,
"s": 2743,
"text": "reset which is meant for looping"
},
{
"code": null,
"e": 2833,
"s": 2776,
"text": "reverse signifies when the counting should start or end,"
},
{
"code": null,
"e": 2890,
"s": 2833,
"text": "reverse signifies when the counting should start or end,"
},
{
"code": null,
"e": 2943,
"s": 2890,
"text": "delay to introduce time delay between animation, and"
},
{
"code": null,
"e": 2996,
"s": 2943,
"text": "delay to introduce time delay between animation, and"
},
{
"code": null,
"e": 3052,
"s": 2996,
"text": "onRest indicates what to do on when the counting stops."
},
{
"code": null,
"e": 3108,
"s": 3052,
"text": "onRest indicates what to do on when the counting stops."
},
{
"code": null,
"e": 3161,
"s": 3108,
"text": "On execution, it will produce the following output −"
},
{
"code": null,
"e": 3204,
"s": 3161,
"text": "Your browser does not support HTML5 video."
}
] |
20 Golden Rules to Learn in Software Development - GeeksforGeeks | 23 Oct, 2020
If you are a developer then you might have experienced a few things in your team...
Sometimes it’s difficult for you to make small changes in code.
You break the functionality of software due to the changes you made in your code.
You introduce a new bug while fixing the other one.
You implement some unnecessary code which is not required in your application.
Adding a new feature is difficult for you because of the complicated code.
The never-shipping product
You remove some code from your application and rewrite it from scratch.
You may have wished to cry in these situations if any one of the above statements is true for you.
All the above problems are common that happens in most of the development team.
There are a lot of small factors responsible for damaging the developer’s project. You won’t see the effect immediately and maybe not for a year or even more. Most of the time we do not pay attention to these small factors, and we consider that it won’t affect our project badly but these small factors can harm your project in the long-term.
In development when you start working on a project everything seems to be working fine but as time goes on, the complexity of your project gets increases and you start ignoring some small factors in your application. Later these small factors create a big issue and your own project becomes a nightmare and a horror story for you.
These issues can be avoided if you learn some fundamental laws of software and if you understand the mindset of great developers. We are going to discuss this topic in detail it will help you in taking the right decisions in your development journey. You will be able to keep your software manageable and as simple as possible.
Before you start working on a project understand the main goal or the purpose of your software. What’s the purpose of your software??....to help people. If you look around yourself you will find many applications you are using in your day-to-day life and all these applications have a single purpose....to help people.
The purpose of the software is not to show off how intelligent you are.
-Max Kanat-Alexander, Code Simplicity
Always remember the above-written quote. Great developers never consider the purpose of software showing off how clever they are in writing the code for a project. You will be building a complex system or a bad application if you don’t understand the purpose of the software. A bad application doesn’t help people that much.
When you start working on a project ask a single question to yourself “How can we help?” and then the answer will help you to understand the main goal of your application. Also, in this way, you will be able to prioritize feature requests in your application.
Keep in mind only two things to understand the aim of your software design. Your design should be as simple as possible and it should be helpful for other users.
Many times in software development when it’s hard to create or modify something, developers shift their focus on making things “just work” and they spend less time focusing on helping users. Every programmer is a designer and being a developer you need to understand the goal of software design.
The goal of software design is to make the developer’s job as easy as possible. This way, developers will be able to focus on other important things that matter in an application. Understanding the aim of your software design will help you to create an application that helps users and it will be continued for a long time.
Before you start working on a project make sure that you fully understand your system, its behavior, functionality, features, and tools you’re working with. If you don’t understand your system and it’s working properly then you will be making your job more difficult and you will be heading towards building a complex system.
Also, a misunderstanding leads to further misunderstanding and that becomes a vicious cycle in an application. These misunderstanding only increases complexity in your system and this complexity can harm your project very badly in the future. If a developer understands their system properly, they will also understand what they need to do in their application.
Good developers know what they need to do in their application whereas bad developers don’t know what they’re doing in an application just because they don’t understand the system and its work properly.
Being a developer how would you feel if you need to work on a complex code where you don’t understand what a specific bunch of code is doing in the application. How would you continue with it and perform your own task if you don’t understand the code which is already implemented in the codebase? Surely it’s frustrating for any developer and also it’s difficult for them to work on these kinds of systems.
Being a developer your aim should be to reduce the complexity of the system not to create it, not to increase it. If you think that writing complex code makes you a smart and intelligent developer then you’re totally wrong. It’s a wrong mindset and you should never do this mistake in software development. A good developer always keeps the code as simple as possible so that other developers can understand it and work on it.
Remember that in software development complexity has nothing to do with intelligence, simplicity does. The simplicity of your code shows how good a developer you’re, not complexity.
A good developer creates things that are easy to understand and easy to change. Remember that developers who are new to your code, they have to learn everything about it. So before you write some complex code just ask one question to yourself “Do I want other developers to understand this code, be happy and continue to work with it, or do I want them to be confused and frustrated?”.
Now you might be asking one question to yourself...“How simple do you have to be?”
The answer is...stupid, dumb simple.
In software development, most of the projects get failed due to the complexity of the system. You start with a simple project but as time goes on you keep adding features to it and after a couple of months when you look back at your own code you realize that you have written a lot of unnecessary code and you have built a much more complex system. You realize that you have expanded a few things in your software for no reason.
Your problem doesn’t end here. Due to the complexity, you become the victim of a lot of bugs in your system. You start fixing these bugs without realizing that it’s badly affecting the other parts of your application. Fixing one bug is introducing a new bug and now you realize that it’s difficult to make even a small change in your system.
In the end when you realize it’s time-consuming and things are now out of control. You make a final decision to fix everything: Rewrite the code from scratch.
The above story is one of the most common horror stories in programming. Most of the developers face it and become victims of it. So the question is...how to avoid this problem?
First, you need to know the exact purpose of your software. Second, you need to be as simple as possible in every single piece of code you write. Third, when a new feature is requested, evaluate them based on your application purpose and question them.
Also, being a developer your behavior should be resistant to change. Do not make any change or add some features until or unless it’s not much needed. You will prevent yourself from writing unnecessary code in your application.
Most of the time developers do not pay attention to the maintenance of the code. They focus on quick coding and fast shipping of the product and ignore the importance of code maintenance. No matter how small or large applications you build, you will always have to implement a few changes in your application.
Every feature you have built in your application and every change you have made in your application requires maintenance. So keep in mind that being a developer your job is not just implementing the features or changes in your application. You also need to pay attention to the future maintenance of code or changes in your application.
Simplicity and complexity, both of the factors are mainly responsible for code maintenance. The more simple code you write for any piece of software the easier it would be to maintain it. A complex system requires more effort for maintenance.
It is more important to reduce the effort of maintenance than it is to reduce the effort of implementation.
— Max Kanat-Alexander, Code Simplicity
The simplicity of your system depends a lot on consistency. Inconsistent code is always hard to understand and developers need to put more effort into learning and understanding it.
If you have followed a way to do something in one place then follow a similar way in every place. For example: In your application, if you name a variable ‘variableOne’ then all of your variables should be named that way (variableTwo, variableThree etc. not variable_three).
In your programming journey, you will have many options for a certain thing or a specific problem. There you will have to make a decision about choosing the best option. Now the question is... how to make a decision about your software? How to prioritize the things and what are some factors you need to consider making a better decision.
In the book Code Simplicity, it is explained very well with some equation...
The desirability of a change (D): Measurement of change you want in your system to happen (How much?)
The value of a change (V): Measurement of value the change offers (How much?). How much does it help the users?
Required efforts to perform the change (E): Measurement of work you need to do to fulfill this change (How much?)
Below is the equation to prioritize the thing and make the decision.
D=V/E
The desirability of any change is directly proportional to the value of the change and inversely proportional to the effort involved in making the change.
— Code Simplicity
The above line will help you to make a better decision. Choose the options that require less effort but bring a lot of value. Ignore the options that require more effort but bring a little value.
To solve the problem you need to first understand the problem. You should know what exactly is being asked and make sure that you clear all the confusion.
You can follow the Feynman technique to understand a hard problem. In this technique, you need to explain your problem to someone else in simple terms.
If you can’t explain something in simple terms, you don’t understand it.
— Richard Feynman
Once you understand the problem, make a plan, and take the action.
Looking at the big whole problem can scare you, so it’s good to divide the problem into various small tasks. Once you divide the task, solve each sub-problem one by one, and then merge it to get the complete solution.
One of the common mistakes most developers make is that they want to make everything too perfect in an application. Each and every feature they want to build with perfection and because of this, they tend to plan everything in detail from the beginning. Most of the time their focus gets shifted to making things perfect only instead of solving the problem and helping people with their software.
“Perfect is the enemy of good.”
— Voltaire
When developers start working on a project they start thinking about each and every small detail or feature they want to build in their system. Every time they make some assumptions, prediction, and they ask a single question to themselves “What if“. They think about their software from a future perspective, and they predict everything according to that.
For any developer, the imagination of the project from a future perspective becomes the main reason to build everything too perfect. Developers think that their project has to be perfect as they imagined it. Developers do not pay attention to certain things but seeking too much perfection can be harmful to them. Being a developer, if you’re chasing too much perfection in your project then below are the things that can happen later with you...
You will be writing unnecessary code, thinking from a future perspective.
Complexity will be increased due to the unnecessary code.
You will be too generic.
You will be missing deadlines.
The complexity of your project will introduce many bugs in your software.
None of the developers wants to face all the above things. So being a developer what you should do in this case...
Start small, improve it, then extend.
Let’s consider the example of implementing a calculator in a system...
Make a plan to build a system that does only addition and nothing else.Work on your plan and implement it.Make improvements in your existing system so that you can add other operations.Now make a plan for subtraction and repeat steps 2 and 3.Make a plan for multiplication and repeat steps 2 and 3.Make a plan for division and repeat steps 2 and 3.
Make a plan to build a system that does only addition and nothing else.
Work on your plan and implement it.
Make improvements in your existing system so that you can add other operations.
Now make a plan for subtraction and repeat steps 2 and 3.
Make a plan for multiplication and repeat steps 2 and 3.
Make a plan for division and repeat steps 2 and 3.
Do not chase too much perfection in your software. Good enough is fine.
Thinking from the future perspective we write a lot of unnecessary code and we become too generic in our application which is not good. In software development, you can’t predict the future, so no matter how generic your solution is, you won’t be able to fulfill the actual future requirements.
Most of the time those requirements won’t be needed in the future and you will end up with writing unnecessary code and increasing the complexity of your system. A more complex system becomes a burden on a developer and also it can destroy your application as well.
So it’s good not to predict the future and implement something which isn’t needed yet. Be only as generic as you know you need to be right now.
Do not implement something, if it already exists.
A lot of developers spend their time building or creating something which already exists on the portal. This is one of the common mistakes and it just consumes the developer’s valuable time. Instead of reinventing the wheel, they can spend their time on something else which is more important.
Now the question is...when it’s okay to reinvent the wheel? Below is the answer...
Implement something which doesn’t exist yet.
If all the existing “wheels” are built on bad technologies and it’s not capable to fulfill your needs.
Lack of maintenance in existing “wheels”
Say no to changing requests until or unless it’s not important. You will be making mistake if you will say ‘yes’ to each and every request and if you will start working on each one of them.
You will be adding more code to your application and that will increase the complexity of your system. So it’s good not to make unnecessary changes in your software.
Now the question is....which changing request we need to implement in our software?
Go back, remember your software purpose, and the simple equation in the prioritizing section.
One of the most frustrating things in software development is working on some repetitive tasks. The repetitive task just consumes your additional time and it’s a foolish thing to work on it again and again. When you realize that you are doing something, again and again, set them up, automate it and forget about them. If you can automate something and if it’s saving your valuable time then automate it.
Do not measure the quality of software based on the number of lines of code. Writing more number of lines of code doesn’t make you a great developer. If you think that a thousand lines of code are always a sign of a big software or application then it’s not true in every case. In most cases, something goes wrong with the software design.
If you pay attention carefully then you can solve a lot of problems in a little bunch of code. Most of the simple solutions in an application don’t require a lot of code. Less code makes your application simpler but you also need to remember that you do not write very fewer lines of code.
If you focus on writing very fewer lines of code then you may fall into the trap of writing clever code that is hard to understand for other developers. So you need to find a balance and you need to write only that much amount of code that is easy to understand and easy to read.
A lot of developers measure their productivity with the number of lines of code they write in an application. Remember that in software development you can increase productivity if you throw unnecessary code from your codebase.
Your goal shouldn’t be writing more code and increasing complexity. You should think about removing unnecessary code and making things as simple as possible. This golden rule is not just going to increase your productivity, but also it will increase the productivity of other developers.
In software development always add logging in an early stage of implementation. You will be saving a lot of time and you will find the problems easily in your application.
Now consider a scenario that you have written a simple if-else block in your application. You give the input to the software and that enters inside the if block. You test it and you commit the code to source control. From your end it’s done but what about the else block? When your software will be shipped to the production, it will generate an error.
To avoid such kind of issue test your code properly. Execute all new lines at least once and test each and every part instead of testing the whole application in the end. Keep testing the parts of the application when you’re implementing it. You might be thinking that it’s time-consuming to test each part but if you really want to prevent yourself from a big issue and if you want to save your valuable time then surely you should test each part of the application during the implementation.
When you see bugs in your application, reproduce it. Do not guess the source of the bug and fix it based on your assumption. Apply fixes when you see it with your own eyes. Be reliable and make sure that your code is properly tested before you commit that to the source control.
Everything takes longer than you think.
This is one of the most important and golden rules you should remember in software development.
Most of the developers make one common mistake in software development. They underestimate the time and efforts needed to develop a small amount of code or implement a feature. You will be missing the deadlines if you underestimate both of the things.
For correct estimation, you can break the big task into smaller tasks. Smaller tasks are easy to estimate and even if you guess it wrong then there will be only a slight difference between your own estimation and the correct estimation. This won’t affect your software badly.
When most of the developers comment on a piece of code they think that they need to mention “what code is doing”. This is wrong. If you need to mention this then surely your code is not readable and you need to make it easier and simpler.
When you’re unable to make code simpler then write the comment and explain the complexity of it. The real purpose of the comment is to mention “Why” you did something not “What” the code is doing. Commenting on the code help other programmers to continue with the software and work on it. If you don’t do this then developers can remove the important parts from your code.
You also need to pay attention to the documentation. Your software’s architecture, module and its components everything should be mentioned in the documentation. Documentations are helpful to see the high level of a picture of your software and it would be easier for new developers to work on it if they understand the complete architecture of the software. They can make mistakes if they won’t have any clue about the different parts or the complete architecture of the application.
A lot of times it happens that we overestimate our potential to complete some task. It’s good to be confident about your potential but it’s not good to become overconfident. Many times it’s better to quit rather than being a superman and showing that you can do something. Instead of making things perfect and fulfilling your task, you will make blunder mistakes and you will screw up everything.
Suppose you estimate that a task can be completed in two hours. You started working on it and it’s been four hours but you’re still only a quarter of the way done. Here you need to quit the task instead of thinking that “I shouldn’t give up, I have already spent four hours on it”
You are determined to complete the task but sometimes you really need to think practically and ask questions to yourself “is it better to quit the task with short damage or it’s better to continue with it making a blunder mistake in the end?”
Don’t be obsessive. Know when to quit and don’t hesitate to ask for help.
Career-Advices
GBlog
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Roadmap to Become a Web Developer in 2022
DSA Sheet by Love Babbar
Top 10 Angular Libraries For Web Developers
A Freshers Guide To Programming
Virtualization In Cloud Computing and Types
ML | Underfitting and Overfitting
Top 10 Programming Languages to Learn in 2022
What is web socket and how it is different from the HTTP?
Software Testing | Basics
How to Install and Run Apache Kafka on Windows? | [
{
"code": null,
"e": 24928,
"s": 24900,
"text": "\n23 Oct, 2020"
},
{
"code": null,
"e": 25012,
"s": 24928,
"text": "If you are a developer then you might have experienced a few things in your team..."
},
{
"code": null,
"e": 25076,
"s": 25012,
"text": "Sometimes it’s difficult for you to make small changes in code."
},
{
"code": null,
"e": 25158,
"s": 25076,
"text": "You break the functionality of software due to the changes you made in your code."
},
{
"code": null,
"e": 25210,
"s": 25158,
"text": "You introduce a new bug while fixing the other one."
},
{
"code": null,
"e": 25289,
"s": 25210,
"text": "You implement some unnecessary code which is not required in your application."
},
{
"code": null,
"e": 25364,
"s": 25289,
"text": "Adding a new feature is difficult for you because of the complicated code."
},
{
"code": null,
"e": 25391,
"s": 25364,
"text": "The never-shipping product"
},
{
"code": null,
"e": 25463,
"s": 25391,
"text": "You remove some code from your application and rewrite it from scratch."
},
{
"code": null,
"e": 25562,
"s": 25463,
"text": "You may have wished to cry in these situations if any one of the above statements is true for you."
},
{
"code": null,
"e": 25643,
"s": 25562,
"text": "All the above problems are common that happens in most of the development team. "
},
{
"code": null,
"e": 25987,
"s": 25643,
"text": "There are a lot of small factors responsible for damaging the developer’s project. You won’t see the effect immediately and maybe not for a year or even more. Most of the time we do not pay attention to these small factors, and we consider that it won’t affect our project badly but these small factors can harm your project in the long-term. "
},
{
"code": null,
"e": 26319,
"s": 25987,
"text": "In development when you start working on a project everything seems to be working fine but as time goes on, the complexity of your project gets increases and you start ignoring some small factors in your application. Later these small factors create a big issue and your own project becomes a nightmare and a horror story for you. "
},
{
"code": null,
"e": 26648,
"s": 26319,
"text": "These issues can be avoided if you learn some fundamental laws of software and if you understand the mindset of great developers. We are going to discuss this topic in detail it will help you in taking the right decisions in your development journey. You will be able to keep your software manageable and as simple as possible. "
},
{
"code": null,
"e": 26967,
"s": 26648,
"text": "Before you start working on a project understand the main goal or the purpose of your software. What’s the purpose of your software??....to help people. If you look around yourself you will find many applications you are using in your day-to-day life and all these applications have a single purpose....to help people."
},
{
"code": null,
"e": 27039,
"s": 26967,
"text": "The purpose of the software is not to show off how intelligent you are."
},
{
"code": null,
"e": 27077,
"s": 27039,
"text": "-Max Kanat-Alexander, Code Simplicity"
},
{
"code": null,
"e": 27403,
"s": 27077,
"text": "Always remember the above-written quote. Great developers never consider the purpose of software showing off how clever they are in writing the code for a project. You will be building a complex system or a bad application if you don’t understand the purpose of the software. A bad application doesn’t help people that much. "
},
{
"code": null,
"e": 27664,
"s": 27403,
"text": "When you start working on a project ask a single question to yourself “How can we help?” and then the answer will help you to understand the main goal of your application. Also, in this way, you will be able to prioritize feature requests in your application. "
},
{
"code": null,
"e": 27827,
"s": 27664,
"text": "Keep in mind only two things to understand the aim of your software design. Your design should be as simple as possible and it should be helpful for other users. "
},
{
"code": null,
"e": 28124,
"s": 27827,
"text": "Many times in software development when it’s hard to create or modify something, developers shift their focus on making things “just work” and they spend less time focusing on helping users. Every programmer is a designer and being a developer you need to understand the goal of software design. "
},
{
"code": null,
"e": 28449,
"s": 28124,
"text": "The goal of software design is to make the developer’s job as easy as possible. This way, developers will be able to focus on other important things that matter in an application. Understanding the aim of your software design will help you to create an application that helps users and it will be continued for a long time. "
},
{
"code": null,
"e": 28775,
"s": 28449,
"text": "Before you start working on a project make sure that you fully understand your system, its behavior, functionality, features, and tools you’re working with. If you don’t understand your system and it’s working properly then you will be making your job more difficult and you will be heading towards building a complex system."
},
{
"code": null,
"e": 29138,
"s": 28775,
"text": "Also, a misunderstanding leads to further misunderstanding and that becomes a vicious cycle in an application. These misunderstanding only increases complexity in your system and this complexity can harm your project very badly in the future. If a developer understands their system properly, they will also understand what they need to do in their application. "
},
{
"code": null,
"e": 29342,
"s": 29138,
"text": "Good developers know what they need to do in their application whereas bad developers don’t know what they’re doing in an application just because they don’t understand the system and its work properly. "
},
{
"code": null,
"e": 29749,
"s": 29342,
"text": "Being a developer how would you feel if you need to work on a complex code where you don’t understand what a specific bunch of code is doing in the application. How would you continue with it and perform your own task if you don’t understand the code which is already implemented in the codebase? Surely it’s frustrating for any developer and also it’s difficult for them to work on these kinds of systems."
},
{
"code": null,
"e": 30176,
"s": 29749,
"text": "Being a developer your aim should be to reduce the complexity of the system not to create it, not to increase it. If you think that writing complex code makes you a smart and intelligent developer then you’re totally wrong. It’s a wrong mindset and you should never do this mistake in software development. A good developer always keeps the code as simple as possible so that other developers can understand it and work on it."
},
{
"code": null,
"e": 30359,
"s": 30176,
"text": "Remember that in software development complexity has nothing to do with intelligence, simplicity does. The simplicity of your code shows how good a developer you’re, not complexity. "
},
{
"code": null,
"e": 30745,
"s": 30359,
"text": "A good developer creates things that are easy to understand and easy to change. Remember that developers who are new to your code, they have to learn everything about it. So before you write some complex code just ask one question to yourself “Do I want other developers to understand this code, be happy and continue to work with it, or do I want them to be confused and frustrated?”."
},
{
"code": null,
"e": 30828,
"s": 30745,
"text": "Now you might be asking one question to yourself...“How simple do you have to be?”"
},
{
"code": null,
"e": 30865,
"s": 30828,
"text": "The answer is...stupid, dumb simple."
},
{
"code": null,
"e": 31295,
"s": 30865,
"text": "In software development, most of the projects get failed due to the complexity of the system. You start with a simple project but as time goes on you keep adding features to it and after a couple of months when you look back at your own code you realize that you have written a lot of unnecessary code and you have built a much more complex system. You realize that you have expanded a few things in your software for no reason. "
},
{
"code": null,
"e": 31638,
"s": 31295,
"text": "Your problem doesn’t end here. Due to the complexity, you become the victim of a lot of bugs in your system. You start fixing these bugs without realizing that it’s badly affecting the other parts of your application. Fixing one bug is introducing a new bug and now you realize that it’s difficult to make even a small change in your system. "
},
{
"code": null,
"e": 31798,
"s": 31638,
"text": "In the end when you realize it’s time-consuming and things are now out of control. You make a final decision to fix everything: Rewrite the code from scratch. "
},
{
"code": null,
"e": 31976,
"s": 31798,
"text": "The above story is one of the most common horror stories in programming. Most of the developers face it and become victims of it. So the question is...how to avoid this problem?"
},
{
"code": null,
"e": 32230,
"s": 31976,
"text": "First, you need to know the exact purpose of your software. Second, you need to be as simple as possible in every single piece of code you write. Third, when a new feature is requested, evaluate them based on your application purpose and question them. "
},
{
"code": null,
"e": 32459,
"s": 32230,
"text": "Also, being a developer your behavior should be resistant to change. Do not make any change or add some features until or unless it’s not much needed. You will prevent yourself from writing unnecessary code in your application. "
},
{
"code": null,
"e": 32770,
"s": 32459,
"text": "Most of the time developers do not pay attention to the maintenance of the code. They focus on quick coding and fast shipping of the product and ignore the importance of code maintenance. No matter how small or large applications you build, you will always have to implement a few changes in your application. "
},
{
"code": null,
"e": 33108,
"s": 32770,
"text": "Every feature you have built in your application and every change you have made in your application requires maintenance. So keep in mind that being a developer your job is not just implementing the features or changes in your application. You also need to pay attention to the future maintenance of code or changes in your application. "
},
{
"code": null,
"e": 33352,
"s": 33108,
"text": "Simplicity and complexity, both of the factors are mainly responsible for code maintenance. The more simple code you write for any piece of software the easier it would be to maintain it. A complex system requires more effort for maintenance. "
},
{
"code": null,
"e": 33460,
"s": 33352,
"text": "It is more important to reduce the effort of maintenance than it is to reduce the effort of implementation."
},
{
"code": null,
"e": 33499,
"s": 33460,
"text": "— Max Kanat-Alexander, Code Simplicity"
},
{
"code": null,
"e": 33682,
"s": 33499,
"text": "The simplicity of your system depends a lot on consistency. Inconsistent code is always hard to understand and developers need to put more effort into learning and understanding it. "
},
{
"code": null,
"e": 33958,
"s": 33682,
"text": "If you have followed a way to do something in one place then follow a similar way in every place. For example: In your application, if you name a variable ‘variableOne’ then all of your variables should be named that way (variableTwo, variableThree etc. not variable_three). "
},
{
"code": null,
"e": 34298,
"s": 33958,
"text": "In your programming journey, you will have many options for a certain thing or a specific problem. There you will have to make a decision about choosing the best option. Now the question is... how to make a decision about your software? How to prioritize the things and what are some factors you need to consider making a better decision. "
},
{
"code": null,
"e": 34375,
"s": 34298,
"text": "In the book Code Simplicity, it is explained very well with some equation..."
},
{
"code": null,
"e": 34477,
"s": 34375,
"text": "The desirability of a change (D): Measurement of change you want in your system to happen (How much?)"
},
{
"code": null,
"e": 34589,
"s": 34477,
"text": "The value of a change (V): Measurement of value the change offers (How much?). How much does it help the users?"
},
{
"code": null,
"e": 34703,
"s": 34589,
"text": "Required efforts to perform the change (E): Measurement of work you need to do to fulfill this change (How much?)"
},
{
"code": null,
"e": 34773,
"s": 34703,
"text": "Below is the equation to prioritize the thing and make the decision. "
},
{
"code": null,
"e": 34779,
"s": 34773,
"text": "D=V/E"
},
{
"code": null,
"e": 34935,
"s": 34779,
"text": "The desirability of any change is directly proportional to the value of the change and inversely proportional to the effort involved in making the change. "
},
{
"code": null,
"e": 34953,
"s": 34935,
"text": "— Code Simplicity"
},
{
"code": null,
"e": 35150,
"s": 34953,
"text": "The above line will help you to make a better decision. Choose the options that require less effort but bring a lot of value. Ignore the options that require more effort but bring a little value. "
},
{
"code": null,
"e": 35306,
"s": 35150,
"text": "To solve the problem you need to first understand the problem. You should know what exactly is being asked and make sure that you clear all the confusion. "
},
{
"code": null,
"e": 35458,
"s": 35306,
"text": "You can follow the Feynman technique to understand a hard problem. In this technique, you need to explain your problem to someone else in simple terms."
},
{
"code": null,
"e": 35531,
"s": 35458,
"text": "If you can’t explain something in simple terms, you don’t understand it."
},
{
"code": null,
"e": 35551,
"s": 35531,
"text": " — Richard Feynman "
},
{
"code": null,
"e": 35619,
"s": 35551,
"text": "Once you understand the problem, make a plan, and take the action. "
},
{
"code": null,
"e": 35837,
"s": 35619,
"text": "Looking at the big whole problem can scare you, so it’s good to divide the problem into various small tasks. Once you divide the task, solve each sub-problem one by one, and then merge it to get the complete solution."
},
{
"code": null,
"e": 36235,
"s": 35837,
"text": "One of the common mistakes most developers make is that they want to make everything too perfect in an application. Each and every feature they want to build with perfection and because of this, they tend to plan everything in detail from the beginning. Most of the time their focus gets shifted to making things perfect only instead of solving the problem and helping people with their software. "
},
{
"code": null,
"e": 36267,
"s": 36235,
"text": "“Perfect is the enemy of good.”"
},
{
"code": null,
"e": 36279,
"s": 36267,
"text": " — Voltaire"
},
{
"code": null,
"e": 36637,
"s": 36279,
"text": "When developers start working on a project they start thinking about each and every small detail or feature they want to build in their system. Every time they make some assumptions, prediction, and they ask a single question to themselves “What if“. They think about their software from a future perspective, and they predict everything according to that. "
},
{
"code": null,
"e": 37084,
"s": 36637,
"text": "For any developer, the imagination of the project from a future perspective becomes the main reason to build everything too perfect. Developers think that their project has to be perfect as they imagined it. Developers do not pay attention to certain things but seeking too much perfection can be harmful to them. Being a developer, if you’re chasing too much perfection in your project then below are the things that can happen later with you..."
},
{
"code": null,
"e": 37158,
"s": 37084,
"text": "You will be writing unnecessary code, thinking from a future perspective."
},
{
"code": null,
"e": 37216,
"s": 37158,
"text": "Complexity will be increased due to the unnecessary code."
},
{
"code": null,
"e": 37241,
"s": 37216,
"text": "You will be too generic."
},
{
"code": null,
"e": 37272,
"s": 37241,
"text": "You will be missing deadlines."
},
{
"code": null,
"e": 37346,
"s": 37272,
"text": "The complexity of your project will introduce many bugs in your software."
},
{
"code": null,
"e": 37461,
"s": 37346,
"text": "None of the developers wants to face all the above things. So being a developer what you should do in this case..."
},
{
"code": null,
"e": 37499,
"s": 37461,
"text": "Start small, improve it, then extend."
},
{
"code": null,
"e": 37570,
"s": 37499,
"text": "Let’s consider the example of implementing a calculator in a system..."
},
{
"code": null,
"e": 37919,
"s": 37570,
"text": "Make a plan to build a system that does only addition and nothing else.Work on your plan and implement it.Make improvements in your existing system so that you can add other operations.Now make a plan for subtraction and repeat steps 2 and 3.Make a plan for multiplication and repeat steps 2 and 3.Make a plan for division and repeat steps 2 and 3."
},
{
"code": null,
"e": 37991,
"s": 37919,
"text": "Make a plan to build a system that does only addition and nothing else."
},
{
"code": null,
"e": 38027,
"s": 37991,
"text": "Work on your plan and implement it."
},
{
"code": null,
"e": 38107,
"s": 38027,
"text": "Make improvements in your existing system so that you can add other operations."
},
{
"code": null,
"e": 38165,
"s": 38107,
"text": "Now make a plan for subtraction and repeat steps 2 and 3."
},
{
"code": null,
"e": 38222,
"s": 38165,
"text": "Make a plan for multiplication and repeat steps 2 and 3."
},
{
"code": null,
"e": 38273,
"s": 38222,
"text": "Make a plan for division and repeat steps 2 and 3."
},
{
"code": null,
"e": 38346,
"s": 38273,
"text": "Do not chase too much perfection in your software. Good enough is fine. "
},
{
"code": null,
"e": 38642,
"s": 38346,
"text": "Thinking from the future perspective we write a lot of unnecessary code and we become too generic in our application which is not good. In software development, you can’t predict the future, so no matter how generic your solution is, you won’t be able to fulfill the actual future requirements. "
},
{
"code": null,
"e": 38908,
"s": 38642,
"text": "Most of the time those requirements won’t be needed in the future and you will end up with writing unnecessary code and increasing the complexity of your system. A more complex system becomes a burden on a developer and also it can destroy your application as well."
},
{
"code": null,
"e": 39052,
"s": 38908,
"text": "So it’s good not to predict the future and implement something which isn’t needed yet. Be only as generic as you know you need to be right now."
},
{
"code": null,
"e": 39104,
"s": 39052,
"text": "Do not implement something, if it already exists. "
},
{
"code": null,
"e": 39399,
"s": 39104,
"text": "A lot of developers spend their time building or creating something which already exists on the portal. This is one of the common mistakes and it just consumes the developer’s valuable time. Instead of reinventing the wheel, they can spend their time on something else which is more important. "
},
{
"code": null,
"e": 39482,
"s": 39399,
"text": "Now the question is...when it’s okay to reinvent the wheel? Below is the answer..."
},
{
"code": null,
"e": 39527,
"s": 39482,
"text": "Implement something which doesn’t exist yet."
},
{
"code": null,
"e": 39630,
"s": 39527,
"text": "If all the existing “wheels” are built on bad technologies and it’s not capable to fulfill your needs."
},
{
"code": null,
"e": 39671,
"s": 39630,
"text": "Lack of maintenance in existing “wheels”"
},
{
"code": null,
"e": 39861,
"s": 39671,
"text": "Say no to changing requests until or unless it’s not important. You will be making mistake if you will say ‘yes’ to each and every request and if you will start working on each one of them."
},
{
"code": null,
"e": 40027,
"s": 39861,
"text": "You will be adding more code to your application and that will increase the complexity of your system. So it’s good not to make unnecessary changes in your software."
},
{
"code": null,
"e": 40111,
"s": 40027,
"text": "Now the question is....which changing request we need to implement in our software?"
},
{
"code": null,
"e": 40205,
"s": 40111,
"text": "Go back, remember your software purpose, and the simple equation in the prioritizing section."
},
{
"code": null,
"e": 40610,
"s": 40205,
"text": "One of the most frustrating things in software development is working on some repetitive tasks. The repetitive task just consumes your additional time and it’s a foolish thing to work on it again and again. When you realize that you are doing something, again and again, set them up, automate it and forget about them. If you can automate something and if it’s saving your valuable time then automate it."
},
{
"code": null,
"e": 40951,
"s": 40610,
"text": "Do not measure the quality of software based on the number of lines of code. Writing more number of lines of code doesn’t make you a great developer. If you think that a thousand lines of code are always a sign of a big software or application then it’s not true in every case. In most cases, something goes wrong with the software design. "
},
{
"code": null,
"e": 41241,
"s": 40951,
"text": "If you pay attention carefully then you can solve a lot of problems in a little bunch of code. Most of the simple solutions in an application don’t require a lot of code. Less code makes your application simpler but you also need to remember that you do not write very fewer lines of code."
},
{
"code": null,
"e": 41521,
"s": 41241,
"text": "If you focus on writing very fewer lines of code then you may fall into the trap of writing clever code that is hard to understand for other developers. So you need to find a balance and you need to write only that much amount of code that is easy to understand and easy to read."
},
{
"code": null,
"e": 41750,
"s": 41521,
"text": "A lot of developers measure their productivity with the number of lines of code they write in an application. Remember that in software development you can increase productivity if you throw unnecessary code from your codebase. "
},
{
"code": null,
"e": 42038,
"s": 41750,
"text": "Your goal shouldn’t be writing more code and increasing complexity. You should think about removing unnecessary code and making things as simple as possible. This golden rule is not just going to increase your productivity, but also it will increase the productivity of other developers."
},
{
"code": null,
"e": 42211,
"s": 42038,
"text": "In software development always add logging in an early stage of implementation. You will be saving a lot of time and you will find the problems easily in your application. "
},
{
"code": null,
"e": 42565,
"s": 42211,
"text": "Now consider a scenario that you have written a simple if-else block in your application. You give the input to the software and that enters inside the if block. You test it and you commit the code to source control. From your end it’s done but what about the else block? When your software will be shipped to the production, it will generate an error. "
},
{
"code": null,
"e": 43062,
"s": 42565,
"text": "To avoid such kind of issue test your code properly. Execute all new lines at least once and test each and every part instead of testing the whole application in the end. Keep testing the parts of the application when you’re implementing it. You might be thinking that it’s time-consuming to test each part but if you really want to prevent yourself from a big issue and if you want to save your valuable time then surely you should test each part of the application during the implementation. "
},
{
"code": null,
"e": 43342,
"s": 43062,
"text": "When you see bugs in your application, reproduce it. Do not guess the source of the bug and fix it based on your assumption. Apply fixes when you see it with your own eyes. Be reliable and make sure that your code is properly tested before you commit that to the source control. "
},
{
"code": null,
"e": 43383,
"s": 43342,
"text": "Everything takes longer than you think. "
},
{
"code": null,
"e": 43480,
"s": 43383,
"text": "This is one of the most important and golden rules you should remember in software development. "
},
{
"code": null,
"e": 43733,
"s": 43480,
"text": "Most of the developers make one common mistake in software development. They underestimate the time and efforts needed to develop a small amount of code or implement a feature. You will be missing the deadlines if you underestimate both of the things. "
},
{
"code": null,
"e": 44010,
"s": 43733,
"text": "For correct estimation, you can break the big task into smaller tasks. Smaller tasks are easy to estimate and even if you guess it wrong then there will be only a slight difference between your own estimation and the correct estimation. This won’t affect your software badly. "
},
{
"code": null,
"e": 44250,
"s": 44010,
"text": "When most of the developers comment on a piece of code they think that they need to mention “what code is doing”. This is wrong. If you need to mention this then surely your code is not readable and you need to make it easier and simpler. "
},
{
"code": null,
"e": 44624,
"s": 44250,
"text": "When you’re unable to make code simpler then write the comment and explain the complexity of it. The real purpose of the comment is to mention “Why” you did something not “What” the code is doing. Commenting on the code help other programmers to continue with the software and work on it. If you don’t do this then developers can remove the important parts from your code. "
},
{
"code": null,
"e": 45110,
"s": 44624,
"text": "You also need to pay attention to the documentation. Your software’s architecture, module and its components everything should be mentioned in the documentation. Documentations are helpful to see the high level of a picture of your software and it would be easier for new developers to work on it if they understand the complete architecture of the software. They can make mistakes if they won’t have any clue about the different parts or the complete architecture of the application. "
},
{
"code": null,
"e": 45508,
"s": 45110,
"text": "A lot of times it happens that we overestimate our potential to complete some task. It’s good to be confident about your potential but it’s not good to become overconfident. Many times it’s better to quit rather than being a superman and showing that you can do something. Instead of making things perfect and fulfilling your task, you will make blunder mistakes and you will screw up everything. "
},
{
"code": null,
"e": 45789,
"s": 45508,
"text": "Suppose you estimate that a task can be completed in two hours. You started working on it and it’s been four hours but you’re still only a quarter of the way done. Here you need to quit the task instead of thinking that “I shouldn’t give up, I have already spent four hours on it”"
},
{
"code": null,
"e": 46032,
"s": 45789,
"text": "You are determined to complete the task but sometimes you really need to think practically and ask questions to yourself “is it better to quit the task with short damage or it’s better to continue with it making a blunder mistake in the end?”"
},
{
"code": null,
"e": 46106,
"s": 46032,
"text": "Don’t be obsessive. Know when to quit and don’t hesitate to ask for help."
},
{
"code": null,
"e": 46121,
"s": 46106,
"text": "Career-Advices"
},
{
"code": null,
"e": 46127,
"s": 46121,
"text": "GBlog"
},
{
"code": null,
"e": 46225,
"s": 46127,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 46234,
"s": 46225,
"text": "Comments"
},
{
"code": null,
"e": 46247,
"s": 46234,
"text": "Old Comments"
},
{
"code": null,
"e": 46289,
"s": 46247,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 46314,
"s": 46289,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 46358,
"s": 46314,
"text": "Top 10 Angular Libraries For Web Developers"
},
{
"code": null,
"e": 46390,
"s": 46358,
"text": "A Freshers Guide To Programming"
},
{
"code": null,
"e": 46434,
"s": 46390,
"text": "Virtualization In Cloud Computing and Types"
},
{
"code": null,
"e": 46468,
"s": 46434,
"text": "ML | Underfitting and Overfitting"
},
{
"code": null,
"e": 46514,
"s": 46468,
"text": "Top 10 Programming Languages to Learn in 2022"
},
{
"code": null,
"e": 46572,
"s": 46514,
"text": "What is web socket and how it is different from the HTTP?"
},
{
"code": null,
"e": 46598,
"s": 46572,
"text": "Software Testing | Basics"
}
] |
Tryit Editor v3.7 | HTML Input types
Tryit: default text on submit button | [
{
"code": null,
"e": 27,
"s": 10,
"text": "HTML Input types"
}
] |
How can I add items to a spinner in Android? | Spinner is just like a drop down button, using this button we can select a item from set of items. This example demonstrate about how to add items to a spinner 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"?>
<android.support.constraint.ConstraintLayout
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">
<LinearLayout
android:layout_width = "match_parent"
android:layout_height = "match_parent"
android:gravity = "center"
android:orientation = "vertical">
<Spinner
android:id = "@+id/spinner"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:prompt = "@string/app_name"
/>
</LinearLayout>
</android.support.constraint.ConstraintLayout>
Step 3 − Add the following code to src/MainActivity.java.
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Spinner spinner = findViewById(R.id.spinner);
ArrayList<String> arrayList = new ArrayList<>();
arrayList.add("JAVA");
arrayList.add("ANDROID");
arrayList.add("C Language");
arrayList.add("CPP Language");
arrayList.add("Go Language");
arrayList.add("AVN SYSTEMS");
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, arrayList);
arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(arrayAdapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
string tutorialsName = parent.getItemAtPosition(position).toString();
Toast.makeText(parent.getContext(), "Selected: " + tutorialsName, Toast.LENGTH_LONG).show();
}
@Override
public void onNothingSelected(AdapterView <?> parent) {
}
});
}
}
In the above code we are adding item to array list and added to ArrayAdpter as shown below.
ArrayList<String> arrayList = new ArrayList<>();
arrayList.add("JAVA");
arrayList.add("ANDROID");
arrayList.add("C Language");
arrayList.add("CPP Language");
arrayList.add("Go Language");
arrayList.add("AVN SYSTEMS");
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, arrayList);
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.
Now select any item, it will show as shown below.
Click here to download the project code | [
{
"code": null,
"e": 1234,
"s": 1062,
"text": "Spinner is just like a drop down button, using this button we can select a item from set of items. This example demonstrate about how to add items to a spinner in android."
},
{
"code": null,
"e": 1363,
"s": 1234,
"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": 1428,
"s": 1363,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2117,
"s": 1428,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<android.support.constraint.ConstraintLayout\nxmlns:android = \"http://schemas.android.com/apk/res/android\" xmlns:tools = \"http://schemas.android.com/tools\" android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\">\n<LinearLayout\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n android:gravity = \"center\"\n android:orientation = \"vertical\">\n <Spinner\n android:id = \"@+id/spinner\"\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\"\n android:prompt = \"@string/app_name\"\n />\n</LinearLayout>\n</android.support.constraint.ConstraintLayout>"
},
{
"code": null,
"e": 2175,
"s": 2117,
"text": "Step 3 − Add the following code to src/MainActivity.java."
},
{
"code": null,
"e": 3785,
"s": 2175,
"text": "import android.os.Bundle;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.MotionEvent;\nimport android.view.View;\nimport android.widget.AdapterView;\nimport android.widget.ArrayAdapter;\nimport android.widget.Spinner;\nimport android.widget.Toast;\nimport java.util.ArrayList;\npublic class MainActivity extends AppCompatActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n Spinner spinner = findViewById(R.id.spinner);\n ArrayList<String> arrayList = new ArrayList<>();\n arrayList.add(\"JAVA\");\n arrayList.add(\"ANDROID\");\n arrayList.add(\"C Language\");\n arrayList.add(\"CPP Language\");\n arrayList.add(\"Go Language\");\n arrayList.add(\"AVN SYSTEMS\");\n ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, arrayList);\n arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);\n spinner.setAdapter(arrayAdapter);\n spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {\n @Override\n public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {\n string tutorialsName = parent.getItemAtPosition(position).toString();\n Toast.makeText(parent.getContext(), \"Selected: \" + tutorialsName, Toast.LENGTH_LONG).show();\n }\n @Override\n public void onNothingSelected(AdapterView <?> parent) {\n }\n });\n }\n}"
},
{
"code": null,
"e": 3877,
"s": 3785,
"text": "In the above code we are adding item to array list and added to ArrayAdpter as shown below."
},
{
"code": null,
"e": 4212,
"s": 3877,
"text": "ArrayList<String> arrayList = new ArrayList<>();\narrayList.add(\"JAVA\");\narrayList.add(\"ANDROID\");\narrayList.add(\"C Language\");\narrayList.add(\"CPP Language\");\narrayList.add(\"Go Language\");\narrayList.add(\"AVN SYSTEMS\");\nArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, arrayList);"
},
{
"code": null,
"e": 4558,
"s": 4212,
"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": 4608,
"s": 4558,
"text": "Now select any item, it will show as shown below."
},
{
"code": null,
"e": 4648,
"s": 4608,
"text": "Click here to download the project code"
}
] |
How can we provide an alias name for an action method in Asp .Net MVC C#? | ActionName attribute is an action selector which is used for a different name of the
action method. We use ActionName attribute when we want that action method to be
called with a different name instead of the actual name of the method.
[ActionName("AliasName")]
using System.Collections.Generic;
using System.Web.Mvc;
namespace DemoMvcApplication.Controllers{
public class HomeController : Controller{
[ActionName("ListCountries")]
public ViewResult Index(){
ViewData["Countries"] = new List<string>{
"India",
"Malaysia",
"Dubai",
"USA",
"UK"
};
return View();
}
}
}
@{
ViewBag.Title = "Countries List";
}
<h2>Countries List</h2>
<ul>
@foreach(string country in (List<string>)ViewData["Countries"])
{
<li>@country</li>
}
In the above since we have provided a different action name for the Index method,
when we try to navigate with action name Index will get 404 error.
Now let us try to navigate using ListCountries action name. | [
{
"code": null,
"e": 1299,
"s": 1062,
"text": "ActionName attribute is an action selector which is used for a different name of the\naction method. We use ActionName attribute when we want that action method to be\ncalled with a different name instead of the actual name of the method."
},
{
"code": null,
"e": 1325,
"s": 1299,
"text": "[ActionName(\"AliasName\")]"
},
{
"code": null,
"e": 1741,
"s": 1325,
"text": "using System.Collections.Generic;\nusing System.Web.Mvc;\nnamespace DemoMvcApplication.Controllers{\n public class HomeController : Controller{\n [ActionName(\"ListCountries\")]\n public ViewResult Index(){\n ViewData[\"Countries\"] = new List<string>{\n \"India\",\n \"Malaysia\",\n \"Dubai\",\n \"USA\",\n \"UK\"\n };\n return View();\n }\n }\n}"
},
{
"code": null,
"e": 1901,
"s": 1741,
"text": "@{\n ViewBag.Title = \"Countries List\";\n}\n<h2>Countries List</h2>\n<ul>\n@foreach(string country in (List<string>)ViewData[\"Countries\"])\n{\n <li>@country</li>\n}"
},
{
"code": null,
"e": 2050,
"s": 1901,
"text": "In the above since we have provided a different action name for the Index method,\nwhen we try to navigate with action name Index will get 404 error."
},
{
"code": null,
"e": 2110,
"s": 2050,
"text": "Now let us try to navigate using ListCountries action name."
}
] |
Can we remove the Title Bar of a Frame in Java? | Yes, we can remove the title bar of a frame using the setUndecorated() method. Set it to TRUE if you don’t want to remove the Title Bar.
The following is an example to remove the title bar of a frame in Java −
package my;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
public class SwingDemo {
public static void main(String[] args) throws Exception {
JFrame frame = new JFrame("Login!");
JLabel label1, label2, label3;
frame.setLayout(new GridLayout(2, 2));
label1 = new JLabel("DeptId", SwingConstants.CENTER);
label2 = new JLabel("SSN", SwingConstants.CENTER);
label3 = new JLabel("Password", SwingConstants.CENTER);
JTextField deptid = new JTextField(20);
JTextField ssn = new JTextField(20);
JPasswordField passwd = new JPasswordField();
passwd.setEchoChar('*');
frame.add(label1);
frame.add(label2);
frame.add(label3);
frame.add(deptid);
frame.add(ssn);
frame.add(passwd);
frame.setUndecorated(true);
frame.setSize(550, 400);
frame.setVisible(true);
}
}
The output is as follows. The title is hidden − | [
{
"code": null,
"e": 1199,
"s": 1062,
"text": "Yes, we can remove the title bar of a frame using the setUndecorated() method. Set it to TRUE if you don’t want to remove the Title Bar."
},
{
"code": null,
"e": 1272,
"s": 1199,
"text": "The following is an example to remove the title bar of a frame in Java −"
},
{
"code": null,
"e": 2278,
"s": 1272,
"text": "package my;\nimport java.awt.GridLayout;\nimport javax.swing.JFrame;\nimport javax.swing.JLabel;\nimport javax.swing.JPasswordField;\nimport javax.swing.JTextField;\nimport javax.swing.SwingConstants;\npublic class SwingDemo {\n public static void main(String[] args) throws Exception {\n JFrame frame = new JFrame(\"Login!\");\n JLabel label1, label2, label3;\n frame.setLayout(new GridLayout(2, 2));\n label1 = new JLabel(\"DeptId\", SwingConstants.CENTER);\n label2 = new JLabel(\"SSN\", SwingConstants.CENTER);\n label3 = new JLabel(\"Password\", SwingConstants.CENTER);\n JTextField deptid = new JTextField(20);\n JTextField ssn = new JTextField(20);\n JPasswordField passwd = new JPasswordField();\n passwd.setEchoChar('*');\n frame.add(label1);\n frame.add(label2);\n frame.add(label3);\n frame.add(deptid);\n frame.add(ssn);\n frame.add(passwd);\n frame.setUndecorated(true);\n frame.setSize(550, 400);\n frame.setVisible(true);\n }\n}"
},
{
"code": null,
"e": 2326,
"s": 2278,
"text": "The output is as follows. The title is hidden −"
}
] |
Different methods to reverse a string in C/C++ - GeeksforGeeks | 03 Feb, 2022
Given a string, write a C/C++ program to reverse it.
Write own reverse function by swapping characters: One simple solution is to write our own reverse function to reverse a string in C++.CPPCPP// A Simple C++ program to reverse a string#include <bits/stdc++.h>using namespace std; // Function to reverse a stringvoid reverseStr(string& str){ int n = str.length(); // Swap character starting from two // corners for (int i = 0; i < n / 2; i++) swap(str[i], str[n - i - 1]);} // Driver programint main(){ string str = "geeksforgeeks"; reverseStr(str); cout << str; return 0;}Output :skeegrofskeegUsing inbuilt “reverse” function: There is a direct function in “algorithm” header file for doing reverse that saves our time when programming.// Reverses elements in [begin, end]
void reverse (BidirectionalIterator begin,
BidirectionalIterator end);
CPPCPP// A quickly written program for reversing a string// using reverse()#include <bits/stdc++.h>using namespace std;int main(){ string str = "geeksforgeeks"; // Reverse str[begin..end] reverse(str.begin(), str.end()); cout << str; return 0;}Output :skeegrofskeegOnly printing reverse:CPPCPP// C++ program to print reverse of a string#include <bits/stdc++.h>using namespace std; // Function to reverse a stringvoid reverse(string str){ for (int i=str.length()-1; i>=0; i--) cout << str[i]; } // Driver codeint main(void){ string s = "GeeksforGeeks"; reverse(s); return (0);}Output:skeegrofskeeG
Getting reverse of a const string:CPPCPP// C++ program to get reverse of a const string#include <bits/stdc++.h>using namespace std; // Function to reverse string and return// reverse string pointer of thatchar* reverseConstString(char const* str){ // find length of string int n = strlen(str); // create a dynamic pointer char array char *rev = new char[n+1]; // copy of string to ptr array strcpy(rev, str); // Swap character starting from two // corners for (int i=0, j=n-1; i<j; i++,j--) swap(rev[i], rev[j]); // return pointer of the reversed string return rev;} // Driver codeint main(void){ const char *s = "GeeksforGeeks"; printf("%s", reverseConstString(s)); return (0);}Output:skeeGrofskeeG
Reverse string using the constructor : Passing reverse iterators to the constructor returns us a reversed string.CPPCPP// A simple C++ program to reverse string using constructor #include <bits/stdc++.h> using namespace std; int main(){ string str = "GeeksforGeeks"; //Use of reverse iterators string rev = string(str.rbegin(),str.rend()); cout<<rev<<endl; return 0;}Output:skeeGrofskeeG
Using a temporary string:CPPCPP// A simple C++ program to reverse string using constructor#include <bits/stdc++.h>using namespace std;int main(){ string str = "GeeksforGeeks"; int n=str.length(); //Temporary string to store the reverse string rev; for(int i=n-1;i>=0;i--) rev.push_back(str[i]); cout<<rev<<endl; return 0;}Output:skeeGrofskeeG
Write own reverse function by swapping characters: One simple solution is to write our own reverse function to reverse a string in C++.CPPCPP// A Simple C++ program to reverse a string#include <bits/stdc++.h>using namespace std; // Function to reverse a stringvoid reverseStr(string& str){ int n = str.length(); // Swap character starting from two // corners for (int i = 0; i < n / 2; i++) swap(str[i], str[n - i - 1]);} // Driver programint main(){ string str = "geeksforgeeks"; reverseStr(str); cout << str; return 0;}Output :skeegrofskeeg
CPP
// A Simple C++ program to reverse a string#include <bits/stdc++.h>using namespace std; // Function to reverse a stringvoid reverseStr(string& str){ int n = str.length(); // Swap character starting from two // corners for (int i = 0; i < n / 2; i++) swap(str[i], str[n - i - 1]);} // Driver programint main(){ string str = "geeksforgeeks"; reverseStr(str); cout << str; return 0;}
skeegrofskeeg
Using inbuilt “reverse” function: There is a direct function in “algorithm” header file for doing reverse that saves our time when programming.// Reverses elements in [begin, end]
void reverse (BidirectionalIterator begin,
BidirectionalIterator end);
CPPCPP// A quickly written program for reversing a string// using reverse()#include <bits/stdc++.h>using namespace std;int main(){ string str = "geeksforgeeks"; // Reverse str[begin..end] reverse(str.begin(), str.end()); cout << str; return 0;}Output :skeegrofskeeg
// Reverses elements in [begin, end]
void reverse (BidirectionalIterator begin,
BidirectionalIterator end);
CPP
// A quickly written program for reversing a string// using reverse()#include <bits/stdc++.h>using namespace std;int main(){ string str = "geeksforgeeks"; // Reverse str[begin..end] reverse(str.begin(), str.end()); cout << str; return 0;}
skeegrofskeeg
Only printing reverse:CPPCPP// C++ program to print reverse of a string#include <bits/stdc++.h>using namespace std; // Function to reverse a stringvoid reverse(string str){ for (int i=str.length()-1; i>=0; i--) cout << str[i]; } // Driver codeint main(void){ string s = "GeeksforGeeks"; reverse(s); return (0);}Output:skeegrofskeeG
CPP
// C++ program to print reverse of a string#include <bits/stdc++.h>using namespace std; // Function to reverse a stringvoid reverse(string str){ for (int i=str.length()-1; i>=0; i--) cout << str[i]; } // Driver codeint main(void){ string s = "GeeksforGeeks"; reverse(s); return (0);}
skeegrofskeeG
Getting reverse of a const string:CPPCPP// C++ program to get reverse of a const string#include <bits/stdc++.h>using namespace std; // Function to reverse string and return// reverse string pointer of thatchar* reverseConstString(char const* str){ // find length of string int n = strlen(str); // create a dynamic pointer char array char *rev = new char[n+1]; // copy of string to ptr array strcpy(rev, str); // Swap character starting from two // corners for (int i=0, j=n-1; i<j; i++,j--) swap(rev[i], rev[j]); // return pointer of the reversed string return rev;} // Driver codeint main(void){ const char *s = "GeeksforGeeks"; printf("%s", reverseConstString(s)); return (0);}Output:skeeGrofskeeG
CPP
// C++ program to get reverse of a const string#include <bits/stdc++.h>using namespace std; // Function to reverse string and return// reverse string pointer of thatchar* reverseConstString(char const* str){ // find length of string int n = strlen(str); // create a dynamic pointer char array char *rev = new char[n+1]; // copy of string to ptr array strcpy(rev, str); // Swap character starting from two // corners for (int i=0, j=n-1; i<j; i++,j--) swap(rev[i], rev[j]); // return pointer of the reversed string return rev;} // Driver codeint main(void){ const char *s = "GeeksforGeeks"; printf("%s", reverseConstString(s)); return (0);}
skeeGrofskeeG
Reverse string using the constructor : Passing reverse iterators to the constructor returns us a reversed string.CPPCPP// A simple C++ program to reverse string using constructor #include <bits/stdc++.h> using namespace std; int main(){ string str = "GeeksforGeeks"; //Use of reverse iterators string rev = string(str.rbegin(),str.rend()); cout<<rev<<endl; return 0;}Output:skeeGrofskeeG
CPP
// A simple C++ program to reverse string using constructor #include <bits/stdc++.h> using namespace std; int main(){ string str = "GeeksforGeeks"; //Use of reverse iterators string rev = string(str.rbegin(),str.rend()); cout<<rev<<endl; return 0;}
skeeGrofskeeG
Using a temporary string:CPPCPP// A simple C++ program to reverse string using constructor#include <bits/stdc++.h>using namespace std;int main(){ string str = "GeeksforGeeks"; int n=str.length(); //Temporary string to store the reverse string rev; for(int i=n-1;i>=0;i--) rev.push_back(str[i]); cout<<rev<<endl; return 0;}Output:skeeGrofskeeG
CPP
// A simple C++ program to reverse string using constructor#include <bits/stdc++.h>using namespace std;int main(){ string str = "GeeksforGeeks"; int n=str.length(); //Temporary string to store the reverse string rev; for(int i=n-1;i>=0;i--) rev.push_back(str[i]); cout<<rev<<endl; return 0;}
skeeGrofskeeG
YouTubeGeeksforGeeks500K subscribersReverse a string in C/C++ | GeeksforGeeksWatch laterShareCopy link27/45InfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 1:51•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=L44_gKvPZ34" 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 Priyam kakati, Ranju Kumari, Somesh Awasthi and improved by Supratik Mitra, Lakshay Bansal. If you like GeeksforGeeks and would like to contribute, you can also write an article and 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
Omkar Goulay
supratik_mitra
Lakshay313
shettykaran21
CoderSaty
cpp-string
Reverse
STL
C Language
C++
School Programming
Strings
Strings
STL
Reverse
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Command line arguments in C/C++
rand() and srand() in C/C++
Core Dump (Segmentation fault) in C/C++
fork() in C
Exception Handling in C++
Inheritance in C++
Iterators in C++ STL
Initialize a vector in C++ (6 different ways)
Socket Programming in C/C++
Operator Overloading in C++ | [
{
"code": null,
"e": 24418,
"s": 24390,
"text": "\n03 Feb, 2022"
},
{
"code": null,
"e": 24471,
"s": 24418,
"text": "Given a string, write a C/C++ program to reverse it."
},
{
"code": null,
"e": 27486,
"s": 24471,
"text": "Write own reverse function by swapping characters: One simple solution is to write our own reverse function to reverse a string in C++.CPPCPP// A Simple C++ program to reverse a string#include <bits/stdc++.h>using namespace std; // Function to reverse a stringvoid reverseStr(string& str){ int n = str.length(); // Swap character starting from two // corners for (int i = 0; i < n / 2; i++) swap(str[i], str[n - i - 1]);} // Driver programint main(){ string str = \"geeksforgeeks\"; reverseStr(str); cout << str; return 0;}Output :skeegrofskeegUsing inbuilt “reverse” function: There is a direct function in “algorithm” header file for doing reverse that saves our time when programming.// Reverses elements in [begin, end]\nvoid reverse (BidirectionalIterator begin, \nBidirectionalIterator end);\nCPPCPP// A quickly written program for reversing a string// using reverse()#include <bits/stdc++.h>using namespace std;int main(){ string str = \"geeksforgeeks\"; // Reverse str[begin..end] reverse(str.begin(), str.end()); cout << str; return 0;}Output :skeegrofskeegOnly printing reverse:CPPCPP// C++ program to print reverse of a string#include <bits/stdc++.h>using namespace std; // Function to reverse a stringvoid reverse(string str){ for (int i=str.length()-1; i>=0; i--) cout << str[i]; } // Driver codeint main(void){ string s = \"GeeksforGeeks\"; reverse(s); return (0);}Output:skeegrofskeeG\nGetting reverse of a const string:CPPCPP// C++ program to get reverse of a const string#include <bits/stdc++.h>using namespace std; // Function to reverse string and return// reverse string pointer of thatchar* reverseConstString(char const* str){ // find length of string int n = strlen(str); // create a dynamic pointer char array char *rev = new char[n+1]; // copy of string to ptr array strcpy(rev, str); // Swap character starting from two // corners for (int i=0, j=n-1; i<j; i++,j--) swap(rev[i], rev[j]); // return pointer of the reversed string return rev;} // Driver codeint main(void){ const char *s = \"GeeksforGeeks\"; printf(\"%s\", reverseConstString(s)); return (0);}Output:skeeGrofskeeG\nReverse string using the constructor : Passing reverse iterators to the constructor returns us a reversed string.CPPCPP// A simple C++ program to reverse string using constructor #include <bits/stdc++.h> using namespace std; int main(){ string str = \"GeeksforGeeks\"; //Use of reverse iterators string rev = string(str.rbegin(),str.rend()); cout<<rev<<endl; return 0;}Output:skeeGrofskeeG\nUsing a temporary string:CPPCPP// A simple C++ program to reverse string using constructor#include <bits/stdc++.h>using namespace std;int main(){ string str = \"GeeksforGeeks\"; int n=str.length(); //Temporary string to store the reverse string rev; for(int i=n-1;i>=0;i--) rev.push_back(str[i]); cout<<rev<<endl; return 0;}Output:skeeGrofskeeG\n"
},
{
"code": null,
"e": 28064,
"s": 27486,
"text": "Write own reverse function by swapping characters: One simple solution is to write our own reverse function to reverse a string in C++.CPPCPP// A Simple C++ program to reverse a string#include <bits/stdc++.h>using namespace std; // Function to reverse a stringvoid reverseStr(string& str){ int n = str.length(); // Swap character starting from two // corners for (int i = 0; i < n / 2; i++) swap(str[i], str[n - i - 1]);} // Driver programint main(){ string str = \"geeksforgeeks\"; reverseStr(str); cout << str; return 0;}Output :skeegrofskeeg"
},
{
"code": null,
"e": 28068,
"s": 28064,
"text": "CPP"
},
{
"code": "// A Simple C++ program to reverse a string#include <bits/stdc++.h>using namespace std; // Function to reverse a stringvoid reverseStr(string& str){ int n = str.length(); // Swap character starting from two // corners for (int i = 0; i < n / 2; i++) swap(str[i], str[n - i - 1]);} // Driver programint main(){ string str = \"geeksforgeeks\"; reverseStr(str); cout << str; return 0;}",
"e": 28484,
"s": 28068,
"text": null
},
{
"code": null,
"e": 28498,
"s": 28484,
"text": "skeegrofskeeg"
},
{
"code": null,
"e": 29035,
"s": 28498,
"text": "Using inbuilt “reverse” function: There is a direct function in “algorithm” header file for doing reverse that saves our time when programming.// Reverses elements in [begin, end]\nvoid reverse (BidirectionalIterator begin, \nBidirectionalIterator end);\nCPPCPP// A quickly written program for reversing a string// using reverse()#include <bits/stdc++.h>using namespace std;int main(){ string str = \"geeksforgeeks\"; // Reverse str[begin..end] reverse(str.begin(), str.end()); cout << str; return 0;}Output :skeegrofskeeg"
},
{
"code": null,
"e": 29145,
"s": 29035,
"text": "// Reverses elements in [begin, end]\nvoid reverse (BidirectionalIterator begin, \nBidirectionalIterator end);\n"
},
{
"code": null,
"e": 29149,
"s": 29145,
"text": "CPP"
},
{
"code": "// A quickly written program for reversing a string// using reverse()#include <bits/stdc++.h>using namespace std;int main(){ string str = \"geeksforgeeks\"; // Reverse str[begin..end] reverse(str.begin(), str.end()); cout << str; return 0;}",
"e": 29407,
"s": 29149,
"text": null
},
{
"code": null,
"e": 29421,
"s": 29407,
"text": "skeegrofskeeg"
},
{
"code": null,
"e": 29772,
"s": 29421,
"text": "Only printing reverse:CPPCPP// C++ program to print reverse of a string#include <bits/stdc++.h>using namespace std; // Function to reverse a stringvoid reverse(string str){ for (int i=str.length()-1; i>=0; i--) cout << str[i]; } // Driver codeint main(void){ string s = \"GeeksforGeeks\"; reverse(s); return (0);}Output:skeegrofskeeG\n"
},
{
"code": null,
"e": 29776,
"s": 29772,
"text": "CPP"
},
{
"code": "// C++ program to print reverse of a string#include <bits/stdc++.h>using namespace std; // Function to reverse a stringvoid reverse(string str){ for (int i=str.length()-1; i>=0; i--) cout << str[i]; } // Driver codeint main(void){ string s = \"GeeksforGeeks\"; reverse(s); return (0);}",
"e": 30078,
"s": 29776,
"text": null
},
{
"code": null,
"e": 30093,
"s": 30078,
"text": "skeegrofskeeG\n"
},
{
"code": null,
"e": 30864,
"s": 30093,
"text": "Getting reverse of a const string:CPPCPP// C++ program to get reverse of a const string#include <bits/stdc++.h>using namespace std; // Function to reverse string and return// reverse string pointer of thatchar* reverseConstString(char const* str){ // find length of string int n = strlen(str); // create a dynamic pointer char array char *rev = new char[n+1]; // copy of string to ptr array strcpy(rev, str); // Swap character starting from two // corners for (int i=0, j=n-1; i<j; i++,j--) swap(rev[i], rev[j]); // return pointer of the reversed string return rev;} // Driver codeint main(void){ const char *s = \"GeeksforGeeks\"; printf(\"%s\", reverseConstString(s)); return (0);}Output:skeeGrofskeeG\n"
},
{
"code": null,
"e": 30868,
"s": 30864,
"text": "CPP"
},
{
"code": "// C++ program to get reverse of a const string#include <bits/stdc++.h>using namespace std; // Function to reverse string and return// reverse string pointer of thatchar* reverseConstString(char const* str){ // find length of string int n = strlen(str); // create a dynamic pointer char array char *rev = new char[n+1]; // copy of string to ptr array strcpy(rev, str); // Swap character starting from two // corners for (int i=0, j=n-1; i<j; i++,j--) swap(rev[i], rev[j]); // return pointer of the reversed string return rev;} // Driver codeint main(void){ const char *s = \"GeeksforGeeks\"; printf(\"%s\", reverseConstString(s)); return (0);}",
"e": 31578,
"s": 30868,
"text": null
},
{
"code": null,
"e": 31593,
"s": 31578,
"text": "skeeGrofskeeG\n"
},
{
"code": null,
"e": 32004,
"s": 31593,
"text": "Reverse string using the constructor : Passing reverse iterators to the constructor returns us a reversed string.CPPCPP// A simple C++ program to reverse string using constructor #include <bits/stdc++.h> using namespace std; int main(){ string str = \"GeeksforGeeks\"; //Use of reverse iterators string rev = string(str.rbegin(),str.rend()); cout<<rev<<endl; return 0;}Output:skeeGrofskeeG\n"
},
{
"code": null,
"e": 32008,
"s": 32004,
"text": "CPP"
},
{
"code": "// A simple C++ program to reverse string using constructor #include <bits/stdc++.h> using namespace std; int main(){ string str = \"GeeksforGeeks\"; //Use of reverse iterators string rev = string(str.rbegin(),str.rend()); cout<<rev<<endl; return 0;}",
"e": 32279,
"s": 32008,
"text": null
},
{
"code": null,
"e": 32294,
"s": 32279,
"text": "skeeGrofskeeG\n"
},
{
"code": null,
"e": 32666,
"s": 32294,
"text": "Using a temporary string:CPPCPP// A simple C++ program to reverse string using constructor#include <bits/stdc++.h>using namespace std;int main(){ string str = \"GeeksforGeeks\"; int n=str.length(); //Temporary string to store the reverse string rev; for(int i=n-1;i>=0;i--) rev.push_back(str[i]); cout<<rev<<endl; return 0;}Output:skeeGrofskeeG\n"
},
{
"code": null,
"e": 32670,
"s": 32666,
"text": "CPP"
},
{
"code": "// A simple C++ program to reverse string using constructor#include <bits/stdc++.h>using namespace std;int main(){ string str = \"GeeksforGeeks\"; int n=str.length(); //Temporary string to store the reverse string rev; for(int i=n-1;i>=0;i--) rev.push_back(str[i]); cout<<rev<<endl; return 0;}",
"e": 32990,
"s": 32670,
"text": null
},
{
"code": null,
"e": 33005,
"s": 32990,
"text": "skeeGrofskeeG\n"
},
{
"code": null,
"e": 33834,
"s": 33005,
"text": "YouTubeGeeksforGeeks500K subscribersReverse a string in C/C++ | GeeksforGeeksWatch laterShareCopy link27/45InfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 1:51•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=L44_gKvPZ34\" 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": 34178,
"s": 33834,
"text": "This article is contributed by Priyam kakati, Ranju Kumari, Somesh Awasthi and improved by Supratik Mitra, Lakshay Bansal. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 34302,
"s": 34178,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above"
},
{
"code": null,
"e": 34315,
"s": 34302,
"text": "Omkar Goulay"
},
{
"code": null,
"e": 34330,
"s": 34315,
"text": "supratik_mitra"
},
{
"code": null,
"e": 34341,
"s": 34330,
"text": "Lakshay313"
},
{
"code": null,
"e": 34355,
"s": 34341,
"text": "shettykaran21"
},
{
"code": null,
"e": 34365,
"s": 34355,
"text": "CoderSaty"
},
{
"code": null,
"e": 34376,
"s": 34365,
"text": "cpp-string"
},
{
"code": null,
"e": 34384,
"s": 34376,
"text": "Reverse"
},
{
"code": null,
"e": 34388,
"s": 34384,
"text": "STL"
},
{
"code": null,
"e": 34399,
"s": 34388,
"text": "C Language"
},
{
"code": null,
"e": 34403,
"s": 34399,
"text": "C++"
},
{
"code": null,
"e": 34422,
"s": 34403,
"text": "School Programming"
},
{
"code": null,
"e": 34430,
"s": 34422,
"text": "Strings"
},
{
"code": null,
"e": 34438,
"s": 34430,
"text": "Strings"
},
{
"code": null,
"e": 34442,
"s": 34438,
"text": "STL"
},
{
"code": null,
"e": 34450,
"s": 34442,
"text": "Reverse"
},
{
"code": null,
"e": 34454,
"s": 34450,
"text": "CPP"
},
{
"code": null,
"e": 34552,
"s": 34454,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34561,
"s": 34552,
"text": "Comments"
},
{
"code": null,
"e": 34574,
"s": 34561,
"text": "Old Comments"
},
{
"code": null,
"e": 34606,
"s": 34574,
"text": "Command line arguments in C/C++"
},
{
"code": null,
"e": 34634,
"s": 34606,
"text": "rand() and srand() in C/C++"
},
{
"code": null,
"e": 34674,
"s": 34634,
"text": "Core Dump (Segmentation fault) in C/C++"
},
{
"code": null,
"e": 34686,
"s": 34674,
"text": "fork() in C"
},
{
"code": null,
"e": 34712,
"s": 34686,
"text": "Exception Handling in C++"
},
{
"code": null,
"e": 34731,
"s": 34712,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 34752,
"s": 34731,
"text": "Iterators in C++ STL"
},
{
"code": null,
"e": 34798,
"s": 34752,
"text": "Initialize a vector in C++ (6 different ways)"
},
{
"code": null,
"e": 34826,
"s": 34798,
"text": "Socket Programming in C/C++"
}
] |
What are the local static variables in C language? | A local static variable is a variable, whose lifetime doesn’t stop with a function call where it is declared. It extends until the lifetime of a complete program. All function calls share the same copy of local static variables.
These variables are used to count the number of times a function is called. The default value of static variable is 0. Whereas, normal local scope specifies that the variables defined within the block are visible only in that block and are invisible outside the block.
The global variables which are outside the block are visible up to the end of the program.
Following is the C program for local variable −
Live Demo
#include<stdio.h>
main ( ){
int a=40 ,b=30,sum; //local variables life is within the block
printf ("sum=%d" ,a+b);
}
When the above program is executed, it produces the following output −
sum=70
Following is the C program for global variable −
Live Demo
int c= 30; /* global area */
main ( ){
int a = 10; //local area
printf ("a=%d, c=%d", a,c);
fun ( );
}
fun ( ){
printf ("c=%d",c);
}
When the above program is executed, it produces the following output −
a =10, c = 30
Following is the C program for the local static variable −
#include <stdio.h>
void fun(){
static int x; //default value of static variable is 0
printf("%d ", a);
a = a + 1;
}
int main(){
fun(); //local static variable whose lifetime doesn’t stop with a function
call, where it is declared.
fun();
return 0;
}
When the above program is executed, it produces the following output −
0 1 | [
{
"code": null,
"e": 1291,
"s": 1062,
"text": "A local static variable is a variable, whose lifetime doesn’t stop with a function call where it is declared. It extends until the lifetime of a complete program. All function calls share the same copy of local static variables."
},
{
"code": null,
"e": 1560,
"s": 1291,
"text": "These variables are used to count the number of times a function is called. The default value of static variable is 0. Whereas, normal local scope specifies that the variables defined within the block are visible only in that block and are invisible outside the block."
},
{
"code": null,
"e": 1651,
"s": 1560,
"text": "The global variables which are outside the block are visible up to the end of the program."
},
{
"code": null,
"e": 1699,
"s": 1651,
"text": "Following is the C program for local variable −"
},
{
"code": null,
"e": 1710,
"s": 1699,
"text": " Live Demo"
},
{
"code": null,
"e": 1833,
"s": 1710,
"text": "#include<stdio.h>\nmain ( ){\n int a=40 ,b=30,sum; //local variables life is within the block\n printf (\"sum=%d\" ,a+b);\n}"
},
{
"code": null,
"e": 1904,
"s": 1833,
"text": "When the above program is executed, it produces the following output −"
},
{
"code": null,
"e": 1911,
"s": 1904,
"text": "sum=70"
},
{
"code": null,
"e": 1960,
"s": 1911,
"text": "Following is the C program for global variable −"
},
{
"code": null,
"e": 1971,
"s": 1960,
"text": " Live Demo"
},
{
"code": null,
"e": 2116,
"s": 1971,
"text": "int c= 30; /* global area */\nmain ( ){\n int a = 10; //local area\n printf (\"a=%d, c=%d\", a,c);\n fun ( );\n}\nfun ( ){\n printf (\"c=%d\",c);\n}"
},
{
"code": null,
"e": 2187,
"s": 2116,
"text": "When the above program is executed, it produces the following output −"
},
{
"code": null,
"e": 2201,
"s": 2187,
"text": "a =10, c = 30"
},
{
"code": null,
"e": 2260,
"s": 2201,
"text": "Following is the C program for the local static variable −"
},
{
"code": null,
"e": 2531,
"s": 2260,
"text": "#include <stdio.h>\nvoid fun(){\n static int x; //default value of static variable is 0\n printf(\"%d \", a);\n a = a + 1;\n}\nint main(){\n fun(); //local static variable whose lifetime doesn’t stop with a function\n call, where it is declared.\n fun();\n return 0;\n}"
},
{
"code": null,
"e": 2602,
"s": 2531,
"text": "When the above program is executed, it produces the following output −"
},
{
"code": null,
"e": 2606,
"s": 2602,
"text": "0 1"
}
] |
CSS 2D Transforms | CSS transforms allow you to move, rotate, scale, and skew elements.
Mouse over the element below to see a 2D transformation:
In this chapter you will learn about the following CSS property:
transform
The numbers in the table specify the first browser version that fully supports the property.
With the CSS transform property you can use
the following 2D transformation methods:
translate()
rotate()
scaleX()
scaleY()
scale()
skewX()
skewY()
skew()
matrix()
Tip: You will learn about 3D transformations in the next chapter.
The translate() method moves an element from its current position (according
to the parameters given for the X-axis and the Y-axis).
The following example moves the <div> element 50 pixels to the right,
and 100 pixels down from its current position:
The rotate() method rotates an element clockwise or counter-clockwise according to a given degree.
The following example rotates the <div> element clockwise with 20 degrees:
Using negative values will rotate the element counter-clockwise.
The following example rotates the <div> element counter-clockwise with 20 degrees:
The scale() method increases or decreases the size of an element (according to the parameters given for the width and height).
The following example increases the <div> element to be two times of its original width, and three times of its original height:
The following example decreases the <div> element to be half of its original width and height:
The scaleX() method increases or decreases the
width of an element.
The following example increases the <div> element to be two times of its original width:
The following example decreases the <div> element to be half of its original width:
The scaleY() method increases or decreases the
height of an element.
The following example increases the <div> element to be three times of its original
height:
The following example decreases the <div> element to be half of its original
height:
The skewX() method skews an element along the X-axis by the given angle.
The following example skews the <div> element 20 degrees along the
X-axis:
The skewY() method skews an element along the Y-axis by the given angle.
The following example skews the <div> element 20 degrees along the Y-axis:
The skew() method skews an element along the X and Y-axis by the given angles.
The following example skews the <div> element 20 degrees along the X-axis, and 10 degrees along the Y-axis:
If the second parameter is not specified, it has a zero value. So, the following example skews the <div> element 20 degrees along the X-axis:
The matrix() method combines all the 2D transform methods into one.
The matrix() method take six parameters, containing mathematic functions,
which allows you to rotate, scale, move (translate), and skew elements.
The parameters are as follow: matrix(scaleX(),skewY(),skewX(),scaleY(),translateX(),translateY())
With the transform property, move the <div> element 100px to the right, and 200px down.
<style>
div {
width: 100px;
height: 100px;
background-color: lightblue;
border: 1px solid black;
: ;
}
</style>
<body>
<div>This is a div</div>
</body>
Start the Exercise
The following table lists all the 2D transform properties:
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": 68,
"s": 0,
"text": "CSS transforms allow you to move, rotate, scale, and skew elements."
},
{
"code": null,
"e": 125,
"s": 68,
"text": "Mouse over the element below to see a 2D transformation:"
},
{
"code": null,
"e": 190,
"s": 125,
"text": "In this chapter you will learn about the following CSS property:"
},
{
"code": null,
"e": 200,
"s": 190,
"text": "transform"
},
{
"code": null,
"e": 293,
"s": 200,
"text": "The numbers in the table specify the first browser version that fully supports the property."
},
{
"code": null,
"e": 379,
"s": 293,
"text": "With the CSS transform property you can use \nthe following 2D transformation methods:"
},
{
"code": null,
"e": 391,
"s": 379,
"text": "translate()"
},
{
"code": null,
"e": 400,
"s": 391,
"text": "rotate()"
},
{
"code": null,
"e": 409,
"s": 400,
"text": "scaleX()"
},
{
"code": null,
"e": 418,
"s": 409,
"text": "scaleY()"
},
{
"code": null,
"e": 426,
"s": 418,
"text": "scale()"
},
{
"code": null,
"e": 434,
"s": 426,
"text": "skewX()"
},
{
"code": null,
"e": 442,
"s": 434,
"text": "skewY()"
},
{
"code": null,
"e": 449,
"s": 442,
"text": "skew()"
},
{
"code": null,
"e": 458,
"s": 449,
"text": "matrix()"
},
{
"code": null,
"e": 524,
"s": 458,
"text": "Tip: You will learn about 3D transformations in the next chapter."
},
{
"code": null,
"e": 658,
"s": 524,
"text": "The translate() method moves an element from its current position (according \nto the parameters given for the X-axis and the Y-axis)."
},
{
"code": null,
"e": 776,
"s": 658,
"text": "The following example moves the <div> element 50 pixels to the right, \nand 100 pixels down from its current position:"
},
{
"code": null,
"e": 875,
"s": 776,
"text": "The rotate() method rotates an element clockwise or counter-clockwise according to a given degree."
},
{
"code": null,
"e": 950,
"s": 875,
"text": "The following example rotates the <div> element clockwise with 20 degrees:"
},
{
"code": null,
"e": 1015,
"s": 950,
"text": "Using negative values will rotate the element counter-clockwise."
},
{
"code": null,
"e": 1098,
"s": 1015,
"text": "The following example rotates the <div> element counter-clockwise with 20 degrees:"
},
{
"code": null,
"e": 1225,
"s": 1098,
"text": "The scale() method increases or decreases the size of an element (according to the parameters given for the width and height)."
},
{
"code": null,
"e": 1355,
"s": 1225,
"text": "The following example increases the <div> element to be two times of its original width, and three times of its original height: "
},
{
"code": null,
"e": 1451,
"s": 1355,
"text": "The following example decreases the <div> element to be half of its original width and height: "
},
{
"code": null,
"e": 1520,
"s": 1451,
"text": "The scaleX() method increases or decreases the \nwidth of an element."
},
{
"code": null,
"e": 1610,
"s": 1520,
"text": "The following example increases the <div> element to be two times of its original width: "
},
{
"code": null,
"e": 1695,
"s": 1610,
"text": "The following example decreases the <div> element to be half of its original width: "
},
{
"code": null,
"e": 1765,
"s": 1695,
"text": "The scaleY() method increases or decreases the \nheight of an element."
},
{
"code": null,
"e": 1859,
"s": 1765,
"text": "The following example increases the <div> element to be three times of its original \nheight: "
},
{
"code": null,
"e": 1946,
"s": 1859,
"text": "The following example decreases the <div> element to be half of its original \nheight: "
},
{
"code": null,
"e": 2019,
"s": 1946,
"text": "The skewX() method skews an element along the X-axis by the given angle."
},
{
"code": null,
"e": 2095,
"s": 2019,
"text": "The following example skews the <div> element 20 degrees along the \nX-axis:"
},
{
"code": null,
"e": 2168,
"s": 2095,
"text": "The skewY() method skews an element along the Y-axis by the given angle."
},
{
"code": null,
"e": 2243,
"s": 2168,
"text": "The following example skews the <div> element 20 degrees along the Y-axis:"
},
{
"code": null,
"e": 2322,
"s": 2243,
"text": "The skew() method skews an element along the X and Y-axis by the given angles."
},
{
"code": null,
"e": 2430,
"s": 2322,
"text": "The following example skews the <div> element 20 degrees along the X-axis, and 10 degrees along the Y-axis:"
},
{
"code": null,
"e": 2572,
"s": 2430,
"text": "If the second parameter is not specified, it has a zero value. So, the following example skews the <div> element 20 degrees along the X-axis:"
},
{
"code": null,
"e": 2640,
"s": 2572,
"text": "The matrix() method combines all the 2D transform methods into one."
},
{
"code": null,
"e": 2787,
"s": 2640,
"text": "The matrix() method take six parameters, containing mathematic functions, \nwhich allows you to rotate, scale, move (translate), and skew elements."
},
{
"code": null,
"e": 2885,
"s": 2787,
"text": "The parameters are as follow: matrix(scaleX(),skewY(),skewX(),scaleY(),translateX(),translateY())"
},
{
"code": null,
"e": 2973,
"s": 2885,
"text": "With the transform property, move the <div> element 100px to the right, and 200px down."
},
{
"code": null,
"e": 3139,
"s": 2973,
"text": "<style>\ndiv {\n width: 100px;\n height: 100px;\n background-color: lightblue;\n border: 1px solid black;\n : ;\n}\n</style>\n\n<body>\n <div>This is a div</div>\n</body>\n"
},
{
"code": null,
"e": 3158,
"s": 3139,
"text": "Start the Exercise"
},
{
"code": null,
"e": 3217,
"s": 3158,
"text": "The following table lists all the 2D transform properties:"
},
{
"code": null,
"e": 3250,
"s": 3217,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 3292,
"s": 3250,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 3399,
"s": 3292,
"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": 3418,
"s": 3399,
"text": "[email protected]"
}
] |
Java program to generate and print Floyd’s triangle | Floyd's triangle, named after Robert Floyd, is a right-angled triangle, which is made using natural numbers. It starts at 1 and consecutively selects the next greater number in the sequence.
Take a number of rows to be printed, n.
Make outer iteration I for n times to print rows
Make inner iteration for J to I
Print K
Increment K
Print NEWLINE character after each inner iteration
import java.util.Scanner;
public class FloyidsTriangle {
public static void main(String args[]){
int n,i,j,k = 1;
System.out.println("Enter the number of lines you need in the FloyidsTriangle");
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
for(i = 1; i <= n; i++) {
for(j=1;j <= i; j++){
System.out.print(" "+k++);
}
System.out.println();
}
}
}
Enter the number of lines you need in the FloyidsTriangle
9
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31 32 33 34 35 36
37 38 39 40 41 42 43 44 45 | [
{
"code": null,
"e": 1253,
"s": 1062,
"text": "Floyd's triangle, named after Robert Floyd, is a right-angled triangle, which is made using natural numbers. It starts at 1 and consecutively selects the next greater number in the sequence."
},
{
"code": null,
"e": 1293,
"s": 1253,
"text": "Take a number of rows to be printed, n."
},
{
"code": null,
"e": 1342,
"s": 1293,
"text": "Make outer iteration I for n times to print rows"
},
{
"code": null,
"e": 1374,
"s": 1342,
"text": "Make inner iteration for J to I"
},
{
"code": null,
"e": 1382,
"s": 1374,
"text": "Print K"
},
{
"code": null,
"e": 1394,
"s": 1382,
"text": "Increment K"
},
{
"code": null,
"e": 1445,
"s": 1394,
"text": "Print NEWLINE character after each inner iteration"
},
{
"code": null,
"e": 1882,
"s": 1445,
"text": "import java.util.Scanner;\npublic class FloyidsTriangle {\n public static void main(String args[]){\n int n,i,j,k = 1;\n System.out.println(\"Enter the number of lines you need in the FloyidsTriangle\");\n Scanner sc = new Scanner(System.in);\n n = sc.nextInt();\n\n for(i = 1; i <= n; i++) {\n for(j=1;j <= i; j++){\n System.out.print(\" \"+k++);\n }\n System.out.println();\n }\n }\n}"
},
{
"code": null,
"e": 2068,
"s": 1882,
"text": "Enter the number of lines you need in the FloyidsTriangle\n9\n1\n2 3\n4 5 6\n7 8 9 10\n11 12 13 14 15\n16 17 18 19 20 21\n22 23 24 25 26 27 28\n29 30 31 32 33 34 35 36\n37 38 39 40 41 42 43 44 45"
}
] |
How to Commit a Query in JDBC? - GeeksforGeeks | 07 Apr, 2022
COMMIT command is used to permanently save any transaction into the database. It is used to end your current transaction and make permanent all changes performed in the transaction. A transaction is a sequence of SQL statements that Oracle Database treats as a single unit. This statement also erases all save points in the transaction and releases transaction locks.
When we use any DML command like INSERT, UPDATE or DELETE, the changes made by these commands are not permanent, until the current session is closed, the changes made by these commands can be rolled back. To avoid that, we use the COMMIT command to mark the changes as permanent.
7 steps to Connect our Java program to MySQL Server using JDBC API
Import the package Load and Register the driver Create a Connection Create a Statement Execute the Query Process the ResultsClose the connection
Import the package
Load and Register the driver
Create a Connection
Create a Statement
Execute the Query
Process the Results
Close the connection
We also need to include MySQL connector in our project.
Syntax of Commit
COMMIT;
SQL Queries used in the SQL server to create the respective DB and Table
Creates a Database
CREATE DATABASE <DataBaseName>;
Current DataBase
use <DataBaseName>;
Creates a Table in the Current DataBase
CREATE TABLE <TableName> (usn int,, name varchar(20) , place varchar (20) );
Example
Java
// importing the my sql packageimport java.sql.*; /* The below code cannot generate the output here, since * there is no connection between client and mysql server * * Before running the project in your device * make SQL server connection with your project * create the respective database/table in sql server * in URL write the port number in which your mysql server * is running (By default it run in port number 3306) */ public class GFG { public static void main(String[] args) { // Database name String databaseName = "student"; // Database URL String url = "jdbc:mysql://localhost:3306/" + databaseName; // Database credentials String userName = "root"; String password = "root"; Connection con = null; Statement st = null; ResultSet res = null; String query = ""; try { // Register the jdbc driver Class.forName("com.mysql.jdbc.Driver"); // open a connection to database con = DriverManager.getConnection(url, userName, password); // set auto commit false con.setAutoCommit(false); // creating statement st = con.createStatement(); // first let us try to understand , how DB works // without commit statement query = "INSERT INTO Student values ( 11 , 'Ram' , 'banglore' )"; // executing query 1 -> adding the above // information into the table st.executeUpdate(query); System.out.println( "Inserted row 1 FIRST TIME in the table...."); query = "INSERT INTO Student values ( 22 , 'Shyam' , 'Chennai' )"; st.executeUpdate(query); System.out.println( "Inserted row 2 FIRST TIME in the table...."); // lets , print what we have updated in the table query = "Select * from Student ; "; res = st.executeQuery(query); System.out.println( "printing data (without Rollback && without Commit )...."); while (res.next()) System.out.print(res.getString("name") + " "); System.out.println(); // lets try to rollback (undo the things ,till now we did) // see what difference it will make in the Database con.rollback(); // lets checkout our DB again query = "Select * from Student"; res = st.executeQuery(query); System.out.println( "printing data (with Rollback && without Commit )...."); boolean empty = true; while (res.next()) { empty = false; System.out.print(res.getString("name") + " "); } if (empty) { System.out.println("Empty table\n\n"); } // Since we haven't committed our transaction , // when we did rollback, everything is gone // Now lets ,try with the Commit Statement from // begining query = "INSERT INTO Student values ( 11 , 'Ram' , 'banglore' )"; st.executeUpdate(query); System.out.println( "Inserted row 1 SECOND TIME in the table...."); query = "INSERT INTO Student values ( 22 , 'Shyam' , 'Chennai' )"; st.executeUpdate(query); System.out.println( "Inserted row 2 SECOND TIME in the table...."); // now we have committed our transaction con.commit(); System.out.println( "committed the transaction successfully...."); // lets rollback and like previous lets check // what will be left in our database con.rollback(); System.out.println("Done Rollback...."); query = "Select * from Student"; res = st.executeQuery(query); System.out.println( "printing data ( with Commit and then Rollback)...."); while (res.next()) System.out.print(res.getString("name") + " "); System.out.println("\n"); } catch (ClassNotFoundException e) { System.out.println("Driver Error"); e.printStackTrace(); } catch (SQLException e) { System.out.println("Connection Error"); e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } try { // Clean-up environment if (con != null) con.close(); if (st != null) con.close(); if (res != null) res.close(); } catch (Exception e) { // Handle errors for JDBC System.out.println(e.getMessage()); } finally { System.out.println("Thank you ........."); } }}
Output
Inserted row 1 FIRST TIME in the table....
Inserted row 2 FIRST TIME in the table....
printing data (without Rollback && without Commit )....
Ram Shyam
printing data (with Rollback && without Commit )....
Empty table
Inserted row 1 SECOND TIME in the table....
Inserted row 2 SECOND TIME in the table....
committed the transaction successfully....
Done Rollback....
printing data ( with Commit and then Rollback)....
Ram Shyam
Thank you .........
rkbhola5
JDBC
Picked
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Constructors in Java
Stream In Java
Exceptions in Java
Different ways of Reading a text file in Java
Functional Interfaces in Java
Java Programming Examples
StringBuilder Class in Java with Examples
Checked vs Unchecked Exceptions in Java
Comparator Interface in Java with Examples
Strings in Java | [
{
"code": null,
"e": 23892,
"s": 23864,
"text": "\n07 Apr, 2022"
},
{
"code": null,
"e": 24260,
"s": 23892,
"text": "COMMIT command is used to permanently save any transaction into the database. It is used to end your current transaction and make permanent all changes performed in the transaction. A transaction is a sequence of SQL statements that Oracle Database treats as a single unit. This statement also erases all save points in the transaction and releases transaction locks."
},
{
"code": null,
"e": 24540,
"s": 24260,
"text": "When we use any DML command like INSERT, UPDATE or DELETE, the changes made by these commands are not permanent, until the current session is closed, the changes made by these commands can be rolled back. To avoid that, we use the COMMIT command to mark the changes as permanent."
},
{
"code": null,
"e": 24607,
"s": 24540,
"text": "7 steps to Connect our Java program to MySQL Server using JDBC API"
},
{
"code": null,
"e": 24753,
"s": 24607,
"text": "Import the package Load and Register the driver Create a Connection Create a Statement Execute the Query Process the ResultsClose the connection "
},
{
"code": null,
"e": 24773,
"s": 24753,
"text": "Import the package "
},
{
"code": null,
"e": 24803,
"s": 24773,
"text": "Load and Register the driver "
},
{
"code": null,
"e": 24824,
"s": 24803,
"text": "Create a Connection "
},
{
"code": null,
"e": 24844,
"s": 24824,
"text": "Create a Statement "
},
{
"code": null,
"e": 24863,
"s": 24844,
"text": "Execute the Query "
},
{
"code": null,
"e": 24883,
"s": 24863,
"text": "Process the Results"
},
{
"code": null,
"e": 24905,
"s": 24883,
"text": "Close the connection "
},
{
"code": null,
"e": 24961,
"s": 24905,
"text": "We also need to include MySQL connector in our project."
},
{
"code": null,
"e": 24978,
"s": 24961,
"text": "Syntax of Commit"
},
{
"code": null,
"e": 24986,
"s": 24978,
"text": "COMMIT;"
},
{
"code": null,
"e": 25059,
"s": 24986,
"text": "SQL Queries used in the SQL server to create the respective DB and Table"
},
{
"code": null,
"e": 25078,
"s": 25059,
"text": "Creates a Database"
},
{
"code": null,
"e": 25111,
"s": 25078,
"text": "CREATE DATABASE <DataBaseName>; "
},
{
"code": null,
"e": 25128,
"s": 25111,
"text": "Current DataBase"
},
{
"code": null,
"e": 25148,
"s": 25128,
"text": "use <DataBaseName>;"
},
{
"code": null,
"e": 25188,
"s": 25148,
"text": "Creates a Table in the Current DataBase"
},
{
"code": null,
"e": 25267,
"s": 25188,
"text": "CREATE TABLE <TableName> (usn int,, name varchar(20) , place varchar (20) );"
},
{
"code": null,
"e": 25275,
"s": 25267,
"text": "Example"
},
{
"code": null,
"e": 25280,
"s": 25275,
"text": "Java"
},
{
"code": "// importing the my sql packageimport java.sql.*; /* The below code cannot generate the output here, since * there is no connection between client and mysql server * * Before running the project in your device * make SQL server connection with your project * create the respective database/table in sql server * in URL write the port number in which your mysql server * is running (By default it run in port number 3306) */ public class GFG { public static void main(String[] args) { // Database name String databaseName = \"student\"; // Database URL String url = \"jdbc:mysql://localhost:3306/\" + databaseName; // Database credentials String userName = \"root\"; String password = \"root\"; Connection con = null; Statement st = null; ResultSet res = null; String query = \"\"; try { // Register the jdbc driver Class.forName(\"com.mysql.jdbc.Driver\"); // open a connection to database con = DriverManager.getConnection(url, userName, password); // set auto commit false con.setAutoCommit(false); // creating statement st = con.createStatement(); // first let us try to understand , how DB works // without commit statement query = \"INSERT INTO Student values ( 11 , 'Ram' , 'banglore' )\"; // executing query 1 -> adding the above // information into the table st.executeUpdate(query); System.out.println( \"Inserted row 1 FIRST TIME in the table....\"); query = \"INSERT INTO Student values ( 22 , 'Shyam' , 'Chennai' )\"; st.executeUpdate(query); System.out.println( \"Inserted row 2 FIRST TIME in the table....\"); // lets , print what we have updated in the table query = \"Select * from Student ; \"; res = st.executeQuery(query); System.out.println( \"printing data (without Rollback && without Commit )....\"); while (res.next()) System.out.print(res.getString(\"name\") + \" \"); System.out.println(); // lets try to rollback (undo the things ,till now we did) // see what difference it will make in the Database con.rollback(); // lets checkout our DB again query = \"Select * from Student\"; res = st.executeQuery(query); System.out.println( \"printing data (with Rollback && without Commit )....\"); boolean empty = true; while (res.next()) { empty = false; System.out.print(res.getString(\"name\") + \" \"); } if (empty) { System.out.println(\"Empty table\\n\\n\"); } // Since we haven't committed our transaction , // when we did rollback, everything is gone // Now lets ,try with the Commit Statement from // begining query = \"INSERT INTO Student values ( 11 , 'Ram' , 'banglore' )\"; st.executeUpdate(query); System.out.println( \"Inserted row 1 SECOND TIME in the table....\"); query = \"INSERT INTO Student values ( 22 , 'Shyam' , 'Chennai' )\"; st.executeUpdate(query); System.out.println( \"Inserted row 2 SECOND TIME in the table....\"); // now we have committed our transaction con.commit(); System.out.println( \"committed the transaction successfully....\"); // lets rollback and like previous lets check // what will be left in our database con.rollback(); System.out.println(\"Done Rollback....\"); query = \"Select * from Student\"; res = st.executeQuery(query); System.out.println( \"printing data ( with Commit and then Rollback)....\"); while (res.next()) System.out.print(res.getString(\"name\") + \" \"); System.out.println(\"\\n\"); } catch (ClassNotFoundException e) { System.out.println(\"Driver Error\"); e.printStackTrace(); } catch (SQLException e) { System.out.println(\"Connection Error\"); e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } try { // Clean-up environment if (con != null) con.close(); if (st != null) con.close(); if (res != null) res.close(); } catch (Exception e) { // Handle errors for JDBC System.out.println(e.getMessage()); } finally { System.out.println(\"Thank you .........\"); } }}",
"e": 30429,
"s": 25280,
"text": null
},
{
"code": null,
"e": 30436,
"s": 30429,
"text": "Output"
},
{
"code": null,
"e": 30900,
"s": 30436,
"text": "Inserted row 1 FIRST TIME in the table....\nInserted row 2 FIRST TIME in the table....\nprinting data (without Rollback && without Commit )....\nRam Shyam \nprinting data (with Rollback && without Commit )....\nEmpty table\n\n\nInserted row 1 SECOND TIME in the table....\nInserted row 2 SECOND TIME in the table....\ncommitted the transaction successfully....\nDone Rollback....\nprinting data ( with Commit and then Rollback)....\nRam Shyam \n\nThank you ........."
},
{
"code": null,
"e": 30909,
"s": 30900,
"text": "rkbhola5"
},
{
"code": null,
"e": 30914,
"s": 30909,
"text": "JDBC"
},
{
"code": null,
"e": 30921,
"s": 30914,
"text": "Picked"
},
{
"code": null,
"e": 30926,
"s": 30921,
"text": "Java"
},
{
"code": null,
"e": 30931,
"s": 30926,
"text": "Java"
},
{
"code": null,
"e": 31029,
"s": 30931,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31038,
"s": 31029,
"text": "Comments"
},
{
"code": null,
"e": 31051,
"s": 31038,
"text": "Old Comments"
},
{
"code": null,
"e": 31072,
"s": 31051,
"text": "Constructors in Java"
},
{
"code": null,
"e": 31087,
"s": 31072,
"text": "Stream In Java"
},
{
"code": null,
"e": 31106,
"s": 31087,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 31152,
"s": 31106,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 31182,
"s": 31152,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 31208,
"s": 31182,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 31250,
"s": 31208,
"text": "StringBuilder Class in Java with Examples"
},
{
"code": null,
"e": 31290,
"s": 31250,
"text": "Checked vs Unchecked Exceptions in Java"
},
{
"code": null,
"e": 31333,
"s": 31290,
"text": "Comparator Interface in Java with Examples"
}
] |
Change value of input on form submit in JavaScript? | To change value of input, use the concept of document. The syntax is as follows −
document.yourFormName.yourTextName.value=anyValue;
Let’s say the following is our input type calling submitForm() on clicking “Submit Form” −
<form name="studentForm" onsubmit="submitForm();">
<input type="hidden" name="txtInput" value="10000" />
<input type="submit" value="Submit Form"/>
</form>
The submitForm() function changing the value of input −
function submitForm(){
document.studentForm.txtInput.value='STUDENT-100';
}
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>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"
></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.
css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
crossorigin="anonymous">
</head>
<body>
<form name="studentForm" onsubmit="submitForm();">
<input type="hidden" name="txtInput" value="10000" />
<input type="submit" value="Submit Form"/>
</form>
<script>
function submitForm(){
document.studentForm.txtInput.value='STUDENT-100';
}
</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 −
On clicking the button “Submit Form”, you will get the change value in query string. This will
produce the following output − | [
{
"code": null,
"e": 1144,
"s": 1062,
"text": "To change value of input, use the concept of document. The syntax is as follows −"
},
{
"code": null,
"e": 1195,
"s": 1144,
"text": "document.yourFormName.yourTextName.value=anyValue;"
},
{
"code": null,
"e": 1286,
"s": 1195,
"text": "Let’s say the following is our input type calling submitForm() on clicking “Submit Form” −"
},
{
"code": null,
"e": 1448,
"s": 1286,
"text": "<form name=\"studentForm\" onsubmit=\"submitForm();\">\n <input type=\"hidden\" name=\"txtInput\" value=\"10000\" />\n <input type=\"submit\" value=\"Submit Form\"/>\n</form>"
},
{
"code": null,
"e": 1504,
"s": 1448,
"text": "The submitForm() function changing the value of input −"
},
{
"code": null,
"e": 1583,
"s": 1504,
"text": "function submitForm(){\n document.studentForm.txtInput.value='STUDENT-100';\n}"
},
{
"code": null,
"e": 1594,
"s": 1583,
"text": " Live Demo"
},
{
"code": null,
"e": 2568,
"s": 1594,
"text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\">\n<meta name=\"viewport\" content=\"width=device-width, initialscale=1.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<script src=\"http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js\"\n></script>\n<link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.\ncss\" integrity=\"sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u\"\ncrossorigin=\"anonymous\">\n</head>\n<body>\n<form name=\"studentForm\" onsubmit=\"submitForm();\">\n<input type=\"hidden\" name=\"txtInput\" value=\"10000\" />\n<input type=\"submit\" value=\"Submit Form\"/>\n</form>\n<script>\n function submitForm(){\n document.studentForm.txtInput.value='STUDENT-100';\n }\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 2730,
"s": 2568,
"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": 2771,
"s": 2730,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2897,
"s": 2771,
"text": "On clicking the button “Submit Form”, you will get the change value in query string. This will\nproduce the following output −"
}
] |
Output of Java Programs | Set 43 (Conditional statements & Loops) | 29 Sep, 2017
Prerequisite: Decision Control and Loops
1. What will be the output of the following program?
class Test {public static void main(String[] args) { int i = 0, j = 9; do { i++; if (j-- < i++) { break; } } while (i < 5); System.out.println(i + "" + j); }}
Options:1.442.553.664.77
The answer is option (3)
Explanation : In the above program, we have to specially take care about the break statement. The execution of the program is going as usual as the control flow of do-while loop but whenever compiler encountered break statement its control comes out from the loop.
2. What will be the output of the following program?
class Test {public static void main(String[] args) { int j = 0; do for (int i = 0; i++ < 1 System.out.println(i); while (j++ < 2); }}
Options:1. 1112. 2223. 3334. error
The answer is option (1)
Explanation : As we all know that curly braces are optional in do and for loop. But the only criteria is if we declare a statement without curly statement, then the statement should not be declarative.
3. What will be the output of the following program?
class Test { static String s = "";public static void main(String[] args) { P: for (int i = 2; i < 7; i++) { if (i == 3) continue; if (i == 5) break P; s = s + i; } System.out.println(s); }}
Options:1. 322. 233. 244. 42
The answer is option (3)
Explanation : In the above example, when the first for loop is executed then it holds the value of i as 2. As long as the i value is 2, the loop will not execute the if condition and will be directly as s=s+i. Here s stores the value in a string format. Next time when s=s+i is executed, the i value becomes 4. Both these values are stored in the s in the form of a string.
4. What will be the output of the following program?
class Test {public static void main(String[] args) { int x = 10; if (++x < 10 && (x / 0 > 10)) { System.out.println("Bishal"); } else { System.out.println("GEEKS"); } }}
Options:1.Compile time error2. RuntimeException:ArithmeticException: / by zero3. Bishal4. GEEKS
The answer is option (4)
Explanation : In the above program we are using && operator (short-circuit operator). Whenever we use && operator then if the first condition is false then the control does not go to the 2nd condition whether it is true or false. In the above program, the first condition in the if block is not true that’s why the else part is executed.
5. What will be the output of the following program?
class Test {public static void main(String[] args) { final int a = 10, b = 20; while (a > b) { System.out.println("Hello"); } System.out.println("GEEKS"); }}
Options:1. Compile time error2. GEEKS3. Hello4. No Output
The answer is option (1)
Explanation: In the above program, we declare two variables as final. In the while loop, it always returns false and the control does not go inside while loop and it does not get the chance in the entire program. Thats why we will get compile time error saying error: unreachable statement.
This article is contributed by Bishal Kumar Dubey. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Java-Output
Loops & Control Structure
Program Output
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n29 Sep, 2017"
},
{
"code": null,
"e": 93,
"s": 52,
"text": "Prerequisite: Decision Control and Loops"
},
{
"code": null,
"e": 146,
"s": 93,
"text": "1. What will be the output of the following program?"
},
{
"code": "class Test {public static void main(String[] args) { int i = 0, j = 9; do { i++; if (j-- < i++) { break; } } while (i < 5); System.out.println(i + \"\" + j); }}",
"e": 390,
"s": 146,
"text": null
},
{
"code": null,
"e": 415,
"s": 390,
"text": "Options:1.442.553.664.77"
},
{
"code": null,
"e": 440,
"s": 415,
"text": "The answer is option (3)"
},
{
"code": null,
"e": 705,
"s": 440,
"text": "Explanation : In the above program, we have to specially take care about the break statement. The execution of the program is going as usual as the control flow of do-while loop but whenever compiler encountered break statement its control comes out from the loop."
},
{
"code": null,
"e": 758,
"s": 705,
"text": "2. What will be the output of the following program?"
},
{
"code": "class Test {public static void main(String[] args) { int j = 0; do for (int i = 0; i++ < 1 System.out.println(i); while (j++ < 2); }}",
"e": 948,
"s": 758,
"text": null
},
{
"code": null,
"e": 983,
"s": 948,
"text": "Options:1. 1112. 2223. 3334. error"
},
{
"code": null,
"e": 1008,
"s": 983,
"text": "The answer is option (1)"
},
{
"code": null,
"e": 1210,
"s": 1008,
"text": "Explanation : As we all know that curly braces are optional in do and for loop. But the only criteria is if we declare a statement without curly statement, then the statement should not be declarative."
},
{
"code": null,
"e": 1263,
"s": 1210,
"text": "3. What will be the output of the following program?"
},
{
"code": "class Test { static String s = \"\";public static void main(String[] args) { P: for (int i = 2; i < 7; i++) { if (i == 3) continue; if (i == 5) break P; s = s + i; } System.out.println(s); }}",
"e": 1552,
"s": 1263,
"text": null
},
{
"code": null,
"e": 1581,
"s": 1552,
"text": "Options:1. 322. 233. 244. 42"
},
{
"code": null,
"e": 1607,
"s": 1581,
"text": " The answer is option (3)"
},
{
"code": null,
"e": 1981,
"s": 1607,
"text": "Explanation : In the above example, when the first for loop is executed then it holds the value of i as 2. As long as the i value is 2, the loop will not execute the if condition and will be directly as s=s+i. Here s stores the value in a string format. Next time when s=s+i is executed, the i value becomes 4. Both these values are stored in the s in the form of a string."
},
{
"code": null,
"e": 2034,
"s": 1981,
"text": "4. What will be the output of the following program?"
},
{
"code": "class Test {public static void main(String[] args) { int x = 10; if (++x < 10 && (x / 0 > 10)) { System.out.println(\"Bishal\"); } else { System.out.println(\"GEEKS\"); } }}",
"e": 2263,
"s": 2034,
"text": null
},
{
"code": null,
"e": 2359,
"s": 2263,
"text": "Options:1.Compile time error2. RuntimeException:ArithmeticException: / by zero3. Bishal4. GEEKS"
},
{
"code": null,
"e": 2384,
"s": 2359,
"text": "The answer is option (4)"
},
{
"code": null,
"e": 2722,
"s": 2384,
"text": "Explanation : In the above program we are using && operator (short-circuit operator). Whenever we use && operator then if the first condition is false then the control does not go to the 2nd condition whether it is true or false. In the above program, the first condition in the if block is not true that’s why the else part is executed."
},
{
"code": null,
"e": 2775,
"s": 2722,
"text": "5. What will be the output of the following program?"
},
{
"code": "class Test {public static void main(String[] args) { final int a = 10, b = 20; while (a > b) { System.out.println(\"Hello\"); } System.out.println(\"GEEKS\"); }}",
"e": 2981,
"s": 2775,
"text": null
},
{
"code": null,
"e": 3039,
"s": 2981,
"text": "Options:1. Compile time error2. GEEKS3. Hello4. No Output"
},
{
"code": null,
"e": 3064,
"s": 3039,
"text": "The answer is option (1)"
},
{
"code": null,
"e": 3355,
"s": 3064,
"text": "Explanation: In the above program, we declare two variables as final. In the while loop, it always returns false and the control does not go inside while loop and it does not get the chance in the entire program. Thats why we will get compile time error saying error: unreachable statement."
},
{
"code": null,
"e": 3661,
"s": 3355,
"text": "This article is contributed by Bishal Kumar Dubey. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 3786,
"s": 3661,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 3798,
"s": 3786,
"text": "Java-Output"
},
{
"code": null,
"e": 3824,
"s": 3798,
"text": "Loops & Control Structure"
},
{
"code": null,
"e": 3839,
"s": 3824,
"text": "Program Output"
}
] |
Mediator design pattern | 22 Feb, 2018
Mediator design pattern is one of the important and widely used behavioral design pattern. Mediator enables decoupling of objects by introducing a layer in between so that the interaction between objects happen via the layer. If the objects interact with each other directly, the system components are tightly-coupled with each other that makes higher maintainability cost and not hard to extend. Mediator pattern focuses on providing a mediator between objects for communication and help in implementing lose-coupling between objects.
Air traffic controller is a great example of mediator pattern where the airport control room works as a mediator for communication between different flights. Mediator works as a router between objects and it can have it’s own logic to provide way of communication.
UML Diagram Mediator design pattern
Design components
Mediator :It defines the interface for communication between colleague objects.
ConcreteMediator : It implements the mediator interface and coordinates communication between colleague objects.
Colleague : It defines the interface for communication with other colleagues
ConcreteColleague : It implements the colleague interface and communicates with other colleagues through its mediator
Let’s see an example of Mediator design pattern.
class ATCMediator implements IATCMediator { private Flight flight; private Runway runway; public boolean land; public void registerRunway(Runway runway) { this.runway = runway; } public void registerFlight(Flight flight) { this.flight = flight; } public boolean isLandingOk() { return land; } @Override public void setLandingStatus(boolean status) { land = status; }} interface Command { void land();} interface IATCMediator{ public void registerRunway(Runway runway); public void registerFlight(Flight flight); public boolean isLandingOk(); public void setLandingStatus(boolean status);} class Flight implements Command { private IATCMediator atcMediator; public Flight(IATCMediator atcMediator) { this.atcMediator = atcMediator; } public void land() { if (atcMediator.isLandingOk()) { System.out.println("Successfully Landed."); atcMediator.setLandingStatus(true); } else System.out.println("Waiting for landing."); } public void getReady() { System.out.println("Ready for landing."); } } class Runway implements Command { private IATCMediator atcMediator; public Runway(IATCMediator atcMediator) { this.atcMediator = atcMediator; atcMediator.setLandingStatus(true); } @Override public void land() { System.out.println("Landing permission granted."); atcMediator.setLandingStatus(true); } } class MediatorDesignPattern { public static void main(String args[]) { IATCMediator atcMediator = new ATCMediator(); Flight sparrow101 = new Flight(atcMediator); Runway mainRunway = new Runway(atcMediator); atcMediator.registerFlight(sparrow101); atcMediator.registerRunway(mainRunway); sparrow101.getReady(); mainRunway.land(); sparrow101.land(); }}
Output:
Ready for landing.
Landing permission granted.
Successfully Landed.
Advantage
It limits subclassing. A mediator localizes behavior that otherwise would be distributed among several objects. Changing this behaviour requires subclassing Mediator only, Colleague classes can be reused as is.
Disadvantage
It centralizes control. The mediator pattern trades complexity of interaction for complexity in the mediator. Because a mediator encapsulates protocols, it can become more complex than any individual colleague. This can make the mediator itself a monolith that’s hard to maintain
This article is contributed by Saket Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Design Pattern
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n22 Feb, 2018"
},
{
"code": null,
"e": 588,
"s": 52,
"text": "Mediator design pattern is one of the important and widely used behavioral design pattern. Mediator enables decoupling of objects by introducing a layer in between so that the interaction between objects happen via the layer. If the objects interact with each other directly, the system components are tightly-coupled with each other that makes higher maintainability cost and not hard to extend. Mediator pattern focuses on providing a mediator between objects for communication and help in implementing lose-coupling between objects."
},
{
"code": null,
"e": 853,
"s": 588,
"text": "Air traffic controller is a great example of mediator pattern where the airport control room works as a mediator for communication between different flights. Mediator works as a router between objects and it can have it’s own logic to provide way of communication."
},
{
"code": null,
"e": 889,
"s": 853,
"text": "UML Diagram Mediator design pattern"
},
{
"code": null,
"e": 907,
"s": 889,
"text": "Design components"
},
{
"code": null,
"e": 987,
"s": 907,
"text": "Mediator :It defines the interface for communication between colleague objects."
},
{
"code": null,
"e": 1100,
"s": 987,
"text": "ConcreteMediator : It implements the mediator interface and coordinates communication between colleague objects."
},
{
"code": null,
"e": 1177,
"s": 1100,
"text": "Colleague : It defines the interface for communication with other colleagues"
},
{
"code": null,
"e": 1295,
"s": 1177,
"text": "ConcreteColleague : It implements the colleague interface and communicates with other colleagues through its mediator"
},
{
"code": null,
"e": 1344,
"s": 1295,
"text": "Let’s see an example of Mediator design pattern."
},
{
"code": "class ATCMediator implements IATCMediator { private Flight flight; private Runway runway; public boolean land; public void registerRunway(Runway runway) { this.runway = runway; } public void registerFlight(Flight flight) { this.flight = flight; } public boolean isLandingOk() { return land; } @Override public void setLandingStatus(boolean status) { land = status; }} interface Command { void land();} interface IATCMediator{ public void registerRunway(Runway runway); public void registerFlight(Flight flight); public boolean isLandingOk(); public void setLandingStatus(boolean status);} class Flight implements Command { private IATCMediator atcMediator; public Flight(IATCMediator atcMediator) { this.atcMediator = atcMediator; } public void land() { if (atcMediator.isLandingOk()) { System.out.println(\"Successfully Landed.\"); atcMediator.setLandingStatus(true); } else System.out.println(\"Waiting for landing.\"); } public void getReady() { System.out.println(\"Ready for landing.\"); } } class Runway implements Command { private IATCMediator atcMediator; public Runway(IATCMediator atcMediator) { this.atcMediator = atcMediator; atcMediator.setLandingStatus(true); } @Override public void land() { System.out.println(\"Landing permission granted.\"); atcMediator.setLandingStatus(true); } } class MediatorDesignPattern { public static void main(String args[]) { IATCMediator atcMediator = new ATCMediator(); Flight sparrow101 = new Flight(atcMediator); Runway mainRunway = new Runway(atcMediator); atcMediator.registerFlight(sparrow101); atcMediator.registerRunway(mainRunway); sparrow101.getReady(); mainRunway.land(); sparrow101.land(); }}",
"e": 3357,
"s": 1344,
"text": null
},
{
"code": null,
"e": 3365,
"s": 3357,
"text": "Output:"
},
{
"code": null,
"e": 3434,
"s": 3365,
"text": "Ready for landing.\nLanding permission granted.\nSuccessfully Landed.\n"
},
{
"code": null,
"e": 3444,
"s": 3434,
"text": "Advantage"
},
{
"code": null,
"e": 3655,
"s": 3444,
"text": "It limits subclassing. A mediator localizes behavior that otherwise would be distributed among several objects. Changing this behaviour requires subclassing Mediator only, Colleague classes can be reused as is."
},
{
"code": null,
"e": 3668,
"s": 3655,
"text": "Disadvantage"
},
{
"code": null,
"e": 3948,
"s": 3668,
"text": "It centralizes control. The mediator pattern trades complexity of interaction for complexity in the mediator. Because a mediator encapsulates protocols, it can become more complex than any individual colleague. This can make the mediator itself a monolith that’s hard to maintain"
},
{
"code": null,
"e": 4247,
"s": 3948,
"text": "This article is contributed by Saket Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 4372,
"s": 4247,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 4387,
"s": 4372,
"text": "Design Pattern"
}
] |
HTML | DOM Input Radio defaultvalue Property | 30 Nov, 2019
The Input Radio defaultValue Property in HTML DOM is used to set or return the default value of a Radio field. This property is used to reflect the HTML value attribute. The main difference between the default value and value is that the default value indicate the default value and the value contains the current value after making some changes. This property is useful to find out whether the Date field have been changed or not.
Syntax:
It returns the defaultValue property.RadioObject.defaultValue
RadioObject.defaultValue
It is used to set the defaultValue property.RadioObject.defaultValue = value
RadioObject.defaultValue = value
Property Values: It contains single property value value which defines the default value for Input Radio field.
Return Value: It returns a string value which represents the default value of the Input Radio field.
Example 1: This example illustrates how to return Input radio defaultValue Property.
<!DOCTYPE html> <html> <head> <style> body { text-align: center; } h1 { color: green; } </style> </head> <body> <h1>GeeksforGeeks</h1> <h2> HTML DOM Input Radio defaultvalue Property </h2> Radio Button: <input type="radio" checked=true id="radioID" value="Geeks_radio"> <br><br> <button onclick="GFG()"> Click! </button> <p id="GFG" style= "font-size:25px;color:green;"> </p> <script> function GFG() { // Accessing input element // type="radio" var x = document.getElementById( "radioID").defaultValue; document.getElementById( "GFG").innerHTML = x; } </script> </body> </html>
Output:
Before Clicking On Button:
After Clicking On Button:
Example 2: This example illustrates how to set Input radio defaultValue Property.
<!DOCTYPE html> <html> <head> <style> body { text-align: center; } h1 { color: green; } </style> </head> <body> <h1>GeeksforGeeks</h1> <h2> HTML DOM Input Radio defaultvalue Property </h2> Radio Button: <input type="radio" checked=true id="radioID" value="Geeks_radio"> <br><br> <button onclick="GFG()"> Click! </button> <p id="GFG" style= "font-size:25px;color:green;"> </p> <script> function GFG() { // Accessing input element // type="radio" var x = document.getElementById("radioID" ).defaultValue = "GeeksForGeeks"; document.getElementById("GFG").innerHTML = x; } </script> </body> </html>
Output:
Before Clicking On Button:
After Clicking On Button:
Supported Browsers: The browsers supported by DOM Input Radio defaultValue Property are listed below:
Google Chrome
Internet Explorer
Firefox
Apple Safari
Opera
HTML-DOM
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Nov, 2019"
},
{
"code": null,
"e": 460,
"s": 28,
"text": "The Input Radio defaultValue Property in HTML DOM is used to set or return the default value of a Radio field. This property is used to reflect the HTML value attribute. The main difference between the default value and value is that the default value indicate the default value and the value contains the current value after making some changes. This property is useful to find out whether the Date field have been changed or not."
},
{
"code": null,
"e": 468,
"s": 460,
"text": "Syntax:"
},
{
"code": null,
"e": 530,
"s": 468,
"text": "It returns the defaultValue property.RadioObject.defaultValue"
},
{
"code": null,
"e": 555,
"s": 530,
"text": "RadioObject.defaultValue"
},
{
"code": null,
"e": 632,
"s": 555,
"text": "It is used to set the defaultValue property.RadioObject.defaultValue = value"
},
{
"code": null,
"e": 665,
"s": 632,
"text": "RadioObject.defaultValue = value"
},
{
"code": null,
"e": 777,
"s": 665,
"text": "Property Values: It contains single property value value which defines the default value for Input Radio field."
},
{
"code": null,
"e": 878,
"s": 777,
"text": "Return Value: It returns a string value which represents the default value of the Input Radio field."
},
{
"code": null,
"e": 963,
"s": 878,
"text": "Example 1: This example illustrates how to return Input radio defaultValue Property."
},
{
"code": "<!DOCTYPE html> <html> <head> <style> body { text-align: center; } h1 { color: green; } </style> </head> <body> <h1>GeeksforGeeks</h1> <h2> HTML DOM Input Radio defaultvalue Property </h2> Radio Button: <input type=\"radio\" checked=true id=\"radioID\" value=\"Geeks_radio\"> <br><br> <button onclick=\"GFG()\"> Click! </button> <p id=\"GFG\" style= \"font-size:25px;color:green;\"> </p> <script> function GFG() { // Accessing input element // type=\"radio\" var x = document.getElementById( \"radioID\").defaultValue; document.getElementById( \"GFG\").innerHTML = x; } </script> </body> </html>",
"e": 1844,
"s": 963,
"text": null
},
{
"code": null,
"e": 1852,
"s": 1844,
"text": "Output:"
},
{
"code": null,
"e": 1879,
"s": 1852,
"text": "Before Clicking On Button:"
},
{
"code": null,
"e": 1905,
"s": 1879,
"text": "After Clicking On Button:"
},
{
"code": null,
"e": 1987,
"s": 1905,
"text": "Example 2: This example illustrates how to set Input radio defaultValue Property."
},
{
"code": "<!DOCTYPE html> <html> <head> <style> body { text-align: center; } h1 { color: green; } </style> </head> <body> <h1>GeeksforGeeks</h1> <h2> HTML DOM Input Radio defaultvalue Property </h2> Radio Button: <input type=\"radio\" checked=true id=\"radioID\" value=\"Geeks_radio\"> <br><br> <button onclick=\"GFG()\"> Click! </button> <p id=\"GFG\" style= \"font-size:25px;color:green;\"> </p> <script> function GFG() { // Accessing input element // type=\"radio\" var x = document.getElementById(\"radioID\" ).defaultValue = \"GeeksForGeeks\"; document.getElementById(\"GFG\").innerHTML = x; } </script> </body> </html>",
"e": 2882,
"s": 1987,
"text": null
},
{
"code": null,
"e": 2890,
"s": 2882,
"text": "Output:"
},
{
"code": null,
"e": 2917,
"s": 2890,
"text": "Before Clicking On Button:"
},
{
"code": null,
"e": 2943,
"s": 2917,
"text": "After Clicking On Button:"
},
{
"code": null,
"e": 3045,
"s": 2943,
"text": "Supported Browsers: The browsers supported by DOM Input Radio defaultValue Property are listed below:"
},
{
"code": null,
"e": 3059,
"s": 3045,
"text": "Google Chrome"
},
{
"code": null,
"e": 3077,
"s": 3059,
"text": "Internet Explorer"
},
{
"code": null,
"e": 3085,
"s": 3077,
"text": "Firefox"
},
{
"code": null,
"e": 3098,
"s": 3085,
"text": "Apple Safari"
},
{
"code": null,
"e": 3104,
"s": 3098,
"text": "Opera"
},
{
"code": null,
"e": 3113,
"s": 3104,
"text": "HTML-DOM"
},
{
"code": null,
"e": 3118,
"s": 3113,
"text": "HTML"
},
{
"code": null,
"e": 3135,
"s": 3118,
"text": "Web Technologies"
},
{
"code": null,
"e": 3140,
"s": 3135,
"text": "HTML"
}
] |
Data type of a Pointer in C++ | 05 Jan, 2022
A pointer is a variable that stores the memory address of an object. The pointer then simply “points” to the object. The type of the object must correspond with the type of the pointer. Pointers are used extensively in both C and C++ for three main purposes:
To allocate new objects on the heap.
To pass functions to other functions.
To iterate over elements in arrays or other data structures.
Pointers are used to store and manage the addresses of dynamically allocated blocks of memory. Such blocks are used to store data objects or arrays of objects. Most structured and object-oriented languages provide an area of memory, called the heap or free store, from which objects are dynamically allocated.
Data Type of Pointer
Pointer is a data type and the purest form of it in C is void *. A void * can pass the memory address around which is what a pointer does but it cannot be dereferenced.
Dereferencing means to get at the data contained at the memory location the pointer is pointing at. This means that one will know what type of data will be read from the memory.
Since void is nothing, it means that it can point to any block of memory, that contains any type of data. void * is rather a restricted type as one cannot dereference it and thus it cannot be used for pointer arithmetic.
To make life easier C provides a series of derived pointer types like char *, int *, double *, and so on. Pointers have their own size irrespective of the type of data they are pointing to.
Example:
char *x – pointer to char
int *x – pointer to integer
C program to print the size of the pointer:
C
// C program to print the// size of pointer#include <stdio.h> // Driver codeint main(){ int x = 10; int* ptr = &x; // Print size of variable printf("Size of variable: %zu", sizeof x); // Print size of pointer printf("\nSize of pointer: %zu", sizeof ptr); return 0;}
Size of variable: 4
Size of pointer: 8
C++ program to print the address of the pointer:
C++
// C++ program to point address// of a pointer#include <iostream>using namespace std; // Driver codeint main(){ int *ptr, var; var = 5; // Assign address of var // to ptr ptr = &var; // Access value pointed by ptr cout << "Value pointed by ptr: " << *ptr << endl; // Address stored by ptr cout << "Address stored at ptr: " << ptr << endl; // Address of pointer ptr cout << "Address of ptr: " << &ptr;}
Value pointed by ptr: 5
Address stored at ptr: 0x7ffe1c19b10c
Address of ptr: 0x7ffe1c19b110
Why declaring data type of pointer is necessary?
The data type of a pointer is needed in two situations:
Dereferencing the pointer.Pointer arithmetic.
Dereferencing the pointer.
Pointer arithmetic.
Let’s discuss each of these in detail.
Dereferencing the pointer:
The data type of pointer is needed when dereferencing the pointer so it knows how much data it should read. For example, dereferencing a char pointer should read the next byte from the address it is pointing to, while an integer pointer should read 4 bytes.
Below is the C program to demonstrate the dereferencing an int pointer
C
// C program to demonstrate// dereferencing int pointer#include <stdio.h>int main(){ // Declare the integer variable int a = 20; // Declare the integer pointer // variable. int* ptr; // Store the address of 'x' variable // to the pointer variable 'ptr' ptr = &a; // value of 'x' variable is changed // to 8 by dereferencing a pointer 'ptr' *ptr = 8; printf("Value of x is : %d", a); return 0;}
Pointer arithmetic:
Different types of pointers take different amounts of memory. So, in the case of advancing a pointer one needs to take the type’s size into the account.
Example:
char takes 1 bytechar c = ‘a’;char *ptr = &c;ptr++;Here, ptr++ means ptr = ptr + 1 as char takes 1 byte. This means adding 0x01 to the address.
Similarly, for int it is 4 bytes, so ptr++ in case of int will be adding 0x04 to the address stored in the pointer.
Pointer data type is a special kind of variable which are meant to store addresses only, instead of values(integer, float, double, char, etc). It knows how many bytes the data is stored in. When we increment a pointer, we increase the pointer by the size of the data type to which it points. Let’s consider the following memory block-
A pointer takes 8 bytes of memory to get stored. In the above memory block-
If the pointer ‘ptr’ is stored at Point B (address between 1000000-10000099) with which pointer type is not declared (i.e. it will get stored in any available spot) and originally the address it is pointing to a variable which lies between 2100-2199 then it will take a lot of time to access the variable it is pointing to.If the pointer is declared with data type then it gets stored to nearest available position to that value like getting stored at Point A (address 2200-2299) which is nearest to ‘int’ type variables i.e. 4-byte row so the access would also be faster in comparison.
If the pointer ‘ptr’ is stored at Point B (address between 1000000-10000099) with which pointer type is not declared (i.e. it will get stored in any available spot) and originally the address it is pointing to a variable which lies between 2100-2199 then it will take a lot of time to access the variable it is pointing to.
If the pointer is declared with data type then it gets stored to nearest available position to that value like getting stored at Point A (address 2200-2299) which is nearest to ‘int’ type variables i.e. 4-byte row so the access would also be faster in comparison.
Therefore, it can be concluded that the main reason behind declaring pointers with data type is it can help with saving extra time spend in access of variables during its implementation.
Significance of declaring data type of pointer:
Without data type safety cannot be assured.Declaring data type helps to increase the speed of access to the variable pointer is pointing to.The compiler has to know the size of the memory cell, the pointer is pointing to.Typecasting of pointer is a must when accessing structures from the pointer.
Without data type safety cannot be assured.
Declaring data type helps to increase the speed of access to the variable pointer is pointing to.
The compiler has to know the size of the memory cell, the pointer is pointing to.
Typecasting of pointer is a must when accessing structures from the pointer.
Pointers
C++
Pointers
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n05 Jan, 2022"
},
{
"code": null,
"e": 288,
"s": 28,
"text": "A pointer is a variable that stores the memory address of an object. The pointer then simply “points” to the object. The type of the object must correspond with the type of the pointer. Pointers are used extensively in both C and C++ for three main purposes:"
},
{
"code": null,
"e": 325,
"s": 288,
"text": "To allocate new objects on the heap."
},
{
"code": null,
"e": 363,
"s": 325,
"text": "To pass functions to other functions."
},
{
"code": null,
"e": 424,
"s": 363,
"text": "To iterate over elements in arrays or other data structures."
},
{
"code": null,
"e": 734,
"s": 424,
"text": "Pointers are used to store and manage the addresses of dynamically allocated blocks of memory. Such blocks are used to store data objects or arrays of objects. Most structured and object-oriented languages provide an area of memory, called the heap or free store, from which objects are dynamically allocated."
},
{
"code": null,
"e": 755,
"s": 734,
"text": "Data Type of Pointer"
},
{
"code": null,
"e": 925,
"s": 755,
"text": "Pointer is a data type and the purest form of it in C is void *. A void * can pass the memory address around which is what a pointer does but it cannot be dereferenced. "
},
{
"code": null,
"e": 1103,
"s": 925,
"text": "Dereferencing means to get at the data contained at the memory location the pointer is pointing at. This means that one will know what type of data will be read from the memory."
},
{
"code": null,
"e": 1325,
"s": 1103,
"text": "Since void is nothing, it means that it can point to any block of memory, that contains any type of data. void * is rather a restricted type as one cannot dereference it and thus it cannot be used for pointer arithmetic. "
},
{
"code": null,
"e": 1515,
"s": 1325,
"text": "To make life easier C provides a series of derived pointer types like char *, int *, double *, and so on. Pointers have their own size irrespective of the type of data they are pointing to."
},
{
"code": null,
"e": 1524,
"s": 1515,
"text": "Example:"
},
{
"code": null,
"e": 1550,
"s": 1524,
"text": "char *x – pointer to char"
},
{
"code": null,
"e": 1578,
"s": 1550,
"text": "int *x – pointer to integer"
},
{
"code": null,
"e": 1622,
"s": 1578,
"text": "C program to print the size of the pointer:"
},
{
"code": null,
"e": 1624,
"s": 1622,
"text": "C"
},
{
"code": "// C program to print the// size of pointer#include <stdio.h> // Driver codeint main(){ int x = 10; int* ptr = &x; // Print size of variable printf(\"Size of variable: %zu\", sizeof x); // Print size of pointer printf(\"\\nSize of pointer: %zu\", sizeof ptr); return 0;}",
"e": 1940,
"s": 1624,
"text": null
},
{
"code": null,
"e": 1979,
"s": 1940,
"text": "Size of variable: 4\nSize of pointer: 8"
},
{
"code": null,
"e": 2028,
"s": 1979,
"text": "C++ program to print the address of the pointer:"
},
{
"code": null,
"e": 2032,
"s": 2028,
"text": "C++"
},
{
"code": "// C++ program to point address// of a pointer#include <iostream>using namespace std; // Driver codeint main(){ int *ptr, var; var = 5; // Assign address of var // to ptr ptr = &var; // Access value pointed by ptr cout << \"Value pointed by ptr: \" << *ptr << endl; // Address stored by ptr cout << \"Address stored at ptr: \" << ptr << endl; // Address of pointer ptr cout << \"Address of ptr: \" << &ptr;}",
"e": 2514,
"s": 2032,
"text": null
},
{
"code": null,
"e": 2607,
"s": 2514,
"text": "Value pointed by ptr: 5\nAddress stored at ptr: 0x7ffe1c19b10c\nAddress of ptr: 0x7ffe1c19b110"
},
{
"code": null,
"e": 2656,
"s": 2607,
"text": "Why declaring data type of pointer is necessary?"
},
{
"code": null,
"e": 2712,
"s": 2656,
"text": "The data type of a pointer is needed in two situations:"
},
{
"code": null,
"e": 2758,
"s": 2712,
"text": "Dereferencing the pointer.Pointer arithmetic."
},
{
"code": null,
"e": 2785,
"s": 2758,
"text": "Dereferencing the pointer."
},
{
"code": null,
"e": 2805,
"s": 2785,
"text": "Pointer arithmetic."
},
{
"code": null,
"e": 2844,
"s": 2805,
"text": "Let’s discuss each of these in detail."
},
{
"code": null,
"e": 2871,
"s": 2844,
"text": "Dereferencing the pointer:"
},
{
"code": null,
"e": 3129,
"s": 2871,
"text": "The data type of pointer is needed when dereferencing the pointer so it knows how much data it should read. For example, dereferencing a char pointer should read the next byte from the address it is pointing to, while an integer pointer should read 4 bytes."
},
{
"code": null,
"e": 3200,
"s": 3129,
"text": "Below is the C program to demonstrate the dereferencing an int pointer"
},
{
"code": null,
"e": 3202,
"s": 3200,
"text": "C"
},
{
"code": "// C program to demonstrate// dereferencing int pointer#include <stdio.h>int main(){ // Declare the integer variable int a = 20; // Declare the integer pointer // variable. int* ptr; // Store the address of 'x' variable // to the pointer variable 'ptr' ptr = &a; // value of 'x' variable is changed // to 8 by dereferencing a pointer 'ptr' *ptr = 8; printf(\"Value of x is : %d\", a); return 0;}",
"e": 3641,
"s": 3202,
"text": null
},
{
"code": null,
"e": 3661,
"s": 3641,
"text": "Pointer arithmetic:"
},
{
"code": null,
"e": 3814,
"s": 3661,
"text": "Different types of pointers take different amounts of memory. So, in the case of advancing a pointer one needs to take the type’s size into the account."
},
{
"code": null,
"e": 3823,
"s": 3814,
"text": "Example:"
},
{
"code": null,
"e": 3968,
"s": 3823,
"text": "char takes 1 bytechar c = ‘a’;char *ptr = &c;ptr++;Here, ptr++ means ptr = ptr + 1 as char takes 1 byte. This means adding 0x01 to the address."
},
{
"code": null,
"e": 4084,
"s": 3968,
"text": "Similarly, for int it is 4 bytes, so ptr++ in case of int will be adding 0x04 to the address stored in the pointer."
},
{
"code": null,
"e": 4420,
"s": 4084,
"text": "Pointer data type is a special kind of variable which are meant to store addresses only, instead of values(integer, float, double, char, etc). It knows how many bytes the data is stored in. When we increment a pointer, we increase the pointer by the size of the data type to which it points. Let’s consider the following memory block-"
},
{
"code": null,
"e": 4496,
"s": 4420,
"text": "A pointer takes 8 bytes of memory to get stored. In the above memory block-"
},
{
"code": null,
"e": 5084,
"s": 4496,
"text": "If the pointer ‘ptr’ is stored at Point B (address between 1000000-10000099) with which pointer type is not declared (i.e. it will get stored in any available spot) and originally the address it is pointing to a variable which lies between 2100-2199 then it will take a lot of time to access the variable it is pointing to.If the pointer is declared with data type then it gets stored to nearest available position to that value like getting stored at Point A (address 2200-2299) which is nearest to ‘int’ type variables i.e. 4-byte row so the access would also be faster in comparison. "
},
{
"code": null,
"e": 5408,
"s": 5084,
"text": "If the pointer ‘ptr’ is stored at Point B (address between 1000000-10000099) with which pointer type is not declared (i.e. it will get stored in any available spot) and originally the address it is pointing to a variable which lies between 2100-2199 then it will take a lot of time to access the variable it is pointing to."
},
{
"code": null,
"e": 5673,
"s": 5408,
"text": "If the pointer is declared with data type then it gets stored to nearest available position to that value like getting stored at Point A (address 2200-2299) which is nearest to ‘int’ type variables i.e. 4-byte row so the access would also be faster in comparison. "
},
{
"code": null,
"e": 5860,
"s": 5673,
"text": "Therefore, it can be concluded that the main reason behind declaring pointers with data type is it can help with saving extra time spend in access of variables during its implementation."
},
{
"code": null,
"e": 5908,
"s": 5860,
"text": "Significance of declaring data type of pointer:"
},
{
"code": null,
"e": 6206,
"s": 5908,
"text": "Without data type safety cannot be assured.Declaring data type helps to increase the speed of access to the variable pointer is pointing to.The compiler has to know the size of the memory cell, the pointer is pointing to.Typecasting of pointer is a must when accessing structures from the pointer."
},
{
"code": null,
"e": 6250,
"s": 6206,
"text": "Without data type safety cannot be assured."
},
{
"code": null,
"e": 6348,
"s": 6250,
"text": "Declaring data type helps to increase the speed of access to the variable pointer is pointing to."
},
{
"code": null,
"e": 6430,
"s": 6348,
"text": "The compiler has to know the size of the memory cell, the pointer is pointing to."
},
{
"code": null,
"e": 6507,
"s": 6430,
"text": "Typecasting of pointer is a must when accessing structures from the pointer."
},
{
"code": null,
"e": 6516,
"s": 6507,
"text": "Pointers"
},
{
"code": null,
"e": 6520,
"s": 6516,
"text": "C++"
},
{
"code": null,
"e": 6529,
"s": 6520,
"text": "Pointers"
},
{
"code": null,
"e": 6533,
"s": 6529,
"text": "CPP"
}
] |
Python | Pandas dataframe.mean() | 19 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.mean() function return the mean of the values for the requested axis. If the method is applied on a pandas series object, then the method returns a scalar value which is the mean value of all the observations in the dataframe. If the method is applied on a pandas dataframe object, then the method returns a pandas series object which contains the mean of the values over the specified axis.
Syntax: DataFrame.mean(axis=None, skipna=None, level=None, numeric_only=None, **kwargs)
Parameters :axis : {index (0), columns (1)}skipna : Exclude NA/null values when computing the result
level : If the axis is a MultiIndex (hierarchical), count along a particular level, collapsing into a Series
numeric_only : Include only float, int, boolean columns. If None, will attempt to use everything, then use only numeric data. Not implemented for Series.
Returns : mean : Series or DataFrame (if level specified)
Example #1: Use mean() function to find the mean of all the observations over the index axis.
# importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.DataFrame({"A":[12, 4, 5, 44, 1], "B":[5, 2, 54, 3, 2], "C":[20, 16, 7, 3, 8], "D":[14, 3, 17, 2, 6]}) # Print the dataframedf
Let’s use the dataframe.mean() function to find the mean over the index axis.
# Even if we do not specify axis = 0,# the method will return the mean over# the index axis by defaultdf.mean(axis = 0)
Output : Example #2: Use mean() function on a dataframe which has Na values. Also find the mean over the column axis.
# importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.DataFrame({"A":[12, 4, 5, None, 1], "B":[7, 2, 54, 3, None], "C":[20, 16, 11, 3, 8],. "D":[14, 3, None, 2, 6]}) # skip the Na values while finding the meandf.mean(axis = 1, skipna = True)
Output :
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
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Convert integer to string in Python
Python | os.path.join() method
Create a Pandas DataFrame from Lists
Introduction To PYTHON | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n19 Nov, 2018"
},
{
"code": null,
"e": 266,
"s": 52,
"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": 675,
"s": 266,
"text": "Pandas dataframe.mean() function return the mean of the values for the requested axis. If the method is applied on a pandas series object, then the method returns a scalar value which is the mean value of all the observations in the dataframe. If the method is applied on a pandas dataframe object, then the method returns a pandas series object which contains the mean of the values over the specified axis."
},
{
"code": null,
"e": 763,
"s": 675,
"text": "Syntax: DataFrame.mean(axis=None, skipna=None, level=None, numeric_only=None, **kwargs)"
},
{
"code": null,
"e": 864,
"s": 763,
"text": "Parameters :axis : {index (0), columns (1)}skipna : Exclude NA/null values when computing the result"
},
{
"code": null,
"e": 973,
"s": 864,
"text": "level : If the axis is a MultiIndex (hierarchical), count along a particular level, collapsing into a Series"
},
{
"code": null,
"e": 1127,
"s": 973,
"text": "numeric_only : Include only float, int, boolean columns. If None, will attempt to use everything, then use only numeric data. Not implemented for Series."
},
{
"code": null,
"e": 1185,
"s": 1127,
"text": "Returns : mean : Series or DataFrame (if level specified)"
},
{
"code": null,
"e": 1279,
"s": 1185,
"text": "Example #1: Use mean() function to find the mean of all the observations over the index axis."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.DataFrame({\"A\":[12, 4, 5, 44, 1], \"B\":[5, 2, 54, 3, 2], \"C\":[20, 16, 7, 3, 8], \"D\":[14, 3, 17, 2, 6]}) # Print the dataframedf",
"e": 1540,
"s": 1279,
"text": null
},
{
"code": null,
"e": 1618,
"s": 1540,
"text": "Let’s use the dataframe.mean() function to find the mean over the index axis."
},
{
"code": "# Even if we do not specify axis = 0,# the method will return the mean over# the index axis by defaultdf.mean(axis = 0)",
"e": 1738,
"s": 1618,
"text": null
},
{
"code": null,
"e": 1856,
"s": 1738,
"text": "Output : Example #2: Use mean() function on a dataframe which has Na values. Also find the mean over the column axis."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.DataFrame({\"A\":[12, 4, 5, None, 1], \"B\":[7, 2, 54, 3, None], \"C\":[20, 16, 11, 3, 8],. \"D\":[14, 3, None, 2, 6]}) # skip the Na values while finding the meandf.mean(axis = 1, skipna = True)",
"e": 2177,
"s": 1856,
"text": null
},
{
"code": null,
"e": 2186,
"s": 2177,
"text": "Output :"
},
{
"code": null,
"e": 2210,
"s": 2186,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 2242,
"s": 2210,
"text": "Python pandas-dataFrame-methods"
},
{
"code": null,
"e": 2256,
"s": 2242,
"text": "Python-pandas"
},
{
"code": null,
"e": 2263,
"s": 2256,
"text": "Python"
},
{
"code": null,
"e": 2361,
"s": 2263,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2379,
"s": 2361,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2421,
"s": 2379,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2443,
"s": 2421,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2475,
"s": 2443,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2504,
"s": 2475,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2531,
"s": 2504,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2567,
"s": 2531,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 2598,
"s": 2567,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2635,
"s": 2598,
"text": "Create a Pandas DataFrame from Lists"
}
] |
Python | Ways to determine common prefix in set of strings | 22 Jun, 2022
Given a set of strings, write a Python program to determine common prefix from a set of strings. Given below are a few methods to solve the above task.Method #1: Using Naive Approach
Python3
# Python code to demonstrate# to find common prefix# from set of strings # Initialising stringini_strlist = ['akshat', 'akash', 'akshay', 'akshita'] # Finding common prefix using Naive Approachres = ''prefix = ini_strlist[0] for string in ini_strlist[1:]: while string[:len(prefix)] != prefix and prefix: prefix = prefix[:len(prefix)-1] if not prefix: breakres = prefix # Printing resultprint("Resultant prefix", str(res))
Resultant prefix ak
Method #2: Using itertools.takewhile and zip
Python3
# Python code to demonstrate# to find common prefix# from set of strings from itertools import takewhile # Initialising stringini_strlist = ['akshat', 'akash', 'akshay', 'akshita'] # Finding common prefix using Naive Approachres = ''.join(c[0] for c in takewhile(lambda x: all(x[0] == y for y in x), zip(*ini_strlist))) # Printing resultprint("Resultant prefix", str(res))
Resultant prefix ak
In both the solution time and space complexity are the same:
Time Complexity: O(n2)
Space Complexity: O(n)
sagar0719kumar
harshmaster07705
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to iterate through Excel rows in Python?
Rotate axis tick labels in Seaborn and Matplotlib
Deque in Python
Queue in Python
Defaultdict in Python
Defaultdict in Python
Python program to add two numbers
Python | Get dictionary keys as a list
Python Program for Fibonacci numbers
Python Program for factorial of a number | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n22 Jun, 2022"
},
{
"code": null,
"e": 237,
"s": 52,
"text": "Given a set of strings, write a Python program to determine common prefix from a set of strings. Given below are a few methods to solve the above task.Method #1: Using Naive Approach "
},
{
"code": null,
"e": 245,
"s": 237,
"text": "Python3"
},
{
"code": "# Python code to demonstrate# to find common prefix# from set of strings # Initialising stringini_strlist = ['akshat', 'akash', 'akshay', 'akshita'] # Finding common prefix using Naive Approachres = ''prefix = ini_strlist[0] for string in ini_strlist[1:]: while string[:len(prefix)] != prefix and prefix: prefix = prefix[:len(prefix)-1] if not prefix: breakres = prefix # Printing resultprint(\"Resultant prefix\", str(res))",
"e": 688,
"s": 245,
"text": null
},
{
"code": null,
"e": 708,
"s": 688,
"text": "Resultant prefix ak"
},
{
"code": null,
"e": 759,
"s": 710,
"text": " Method #2: Using itertools.takewhile and zip "
},
{
"code": null,
"e": 767,
"s": 759,
"text": "Python3"
},
{
"code": "# Python code to demonstrate# to find common prefix# from set of strings from itertools import takewhile # Initialising stringini_strlist = ['akshat', 'akash', 'akshay', 'akshita'] # Finding common prefix using Naive Approachres = ''.join(c[0] for c in takewhile(lambda x: all(x[0] == y for y in x), zip(*ini_strlist))) # Printing resultprint(\"Resultant prefix\", str(res))",
"e": 1147,
"s": 767,
"text": null
},
{
"code": null,
"e": 1167,
"s": 1147,
"text": "Resultant prefix ak"
},
{
"code": null,
"e": 1230,
"s": 1169,
"text": "In both the solution time and space complexity are the same:"
},
{
"code": null,
"e": 1253,
"s": 1230,
"text": "Time Complexity: O(n2)"
},
{
"code": null,
"e": 1276,
"s": 1253,
"text": "Space Complexity: O(n)"
},
{
"code": null,
"e": 1291,
"s": 1276,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 1308,
"s": 1291,
"text": "harshmaster07705"
},
{
"code": null,
"e": 1331,
"s": 1308,
"text": "Python string-programs"
},
{
"code": null,
"e": 1338,
"s": 1331,
"text": "Python"
},
{
"code": null,
"e": 1354,
"s": 1338,
"text": "Python Programs"
},
{
"code": null,
"e": 1452,
"s": 1354,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1497,
"s": 1452,
"text": "How to iterate through Excel rows in Python?"
},
{
"code": null,
"e": 1547,
"s": 1497,
"text": "Rotate axis tick labels in Seaborn and Matplotlib"
},
{
"code": null,
"e": 1563,
"s": 1547,
"text": "Deque in Python"
},
{
"code": null,
"e": 1579,
"s": 1563,
"text": "Queue in Python"
},
{
"code": null,
"e": 1601,
"s": 1579,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 1623,
"s": 1601,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 1657,
"s": 1623,
"text": "Python program to add two numbers"
},
{
"code": null,
"e": 1696,
"s": 1657,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 1733,
"s": 1696,
"text": "Python Program for Fibonacci numbers"
}
] |
Select rows from a DataFrame based on values in a vector in R | 09 May, 2021
In this article, we will discuss how to select rows from a DataFrame based on values in a vector in R Programming Language.
%in% operator in R, is used to identify if an element belongs to a vector or Dataframe. It is used to perform a selection of the elements satisfying the condition. It takes the value and checks for its existence in the object specified.
Syntax:
val %in% vec
It returns a boolean TRUE or FALSE value depending on whether the element is found or not. Then the corresponding element is accessed from the DataFrame. This approach creates a subset of the DataFrame without making any changes to the existing DataFrame. Any particular column can be accessed using df$colname and then matched with vector using this comparison operator.
Example:
R
# declare a DataFramedata_frame <- data.frame(col1 = c(1:7),col2 = LETTERS[1:7]) print ("Original DataFrame")print (data_frame) # declaring the vectorvec <- c('A','a','C') # getting the subset DataFrame after # checking values if belonging to vectorsub_df <- data_frame[data_frame$col2 %in% vec,] print ("Resultant DataFrame")print (sub_df)
Output
[1] "Original DataFrame"
col1 col2
1 1 A
2 2 B
3 3 C
4 4 D
5 5 E
6 6 F
7 7 G
[1] "Resultant DataFrame"
col1 col2
1 1 A
3 3 C
This is an instance of the comparison operator which is used to check the existence of an element in a vector or a DataFrame. is.element(x, y) is identical to x %in% y. It returns a boolean logical value to return TRUE if the value is found, else FALSE.
Syntax:
is.element(val,vec)
rbind is applied here to combine two subsets of DataFrames where in, in the first case col2 values can be checked for existence in the vector and then col3 values in vector. Both the sub-DataFrames can then be combined.
Example:
R
# declare a DataFramedata_frame <- data.frame( col1 = c(1:7),col2 = LETTERS[1:7],col3 = letters[1:7]) print ("Original DataFrame")print (data_frame) # declaring the vectorvec <- c('a','C','D') # getting the subset DataFrame after checking # values if belonging to vector of the # corresponding columnssub_df <- rbind(data_frame[is.element(data_frame$col2, vec),], data_frame[is.element(data_frame$col3, vec),]) print ("Resultant DataFrame")print (sub_df)
Output
[1] "Original DataFrame"
col1 col2 col3
1 1 A a
2 2 B b
3 3 C c
4 4 D d
5 5 E e
6 6 F f
7 7 G g
[1] "Resultant DataFrame"
col1 col2 col3
3 3 C c
4 4 D d
1 1 A a
The data.table package in R can be explicitly invoked into the R working space as an enhanced version of the DataFrames. The setDT() method in R is used to convert the DataFrame to data table by reference.
Syntax: setDT(df, keep.rownames=FALSE, key=NULL, check.names=FALSE)
Parameter:
df – DataFrame
key – The column name or any vector which has to be passed to setkeyv.
Also, the function J(vec) is then applied, which returns the vec elements by mapping it to the passed column index in the key argument of the setDT() method. It is used to create a join of the table involved along with the character vector.
The following key points are noticed while using this approach :
The dataframe is converted to a data table, therefore, each result row of the table is lead by a row number identifier followed by “:”.
The dataframe is checked against each value of the vector, and row of the final output DataFrame is printed in accordance with that.
Application of this approach may lead to ambiguity between the actual available data and the obtained result.
Example:
R
# declare a DataFrame# different data type have been # indicated for different colslibrary("data.table") data_frame <- data.frame( col1 = c(6:9), col2 = c(4.5,6.7,89.0,6.2), col3 = factor(letters[1:4])) print("Original DataFrame")print (data_frame) # declaring the vector vec <- c(4,6)data_frame <- setDT(data_frame, key = "col1")[J(vec)] print ("Modified Dataframe")print (data_frame)
Output
[1] "Original DataFrame"
col1 col2 col3
1 6 4.5 a
2 7 6.7 b
3 8 89.0 c
4 9 6.2 d
[1] "Modified Dataframe"
col1 col2 col3
1: 4 NA <NA>
2: 6 4.5 a
The dplyr package provides a variety of modules and method to simulate data manipulations. The dplyr package is not available in base R and needs to incorporated in the working space to use it as a library. A method filter() is available in this package to produce a subset of the original DataFrame where the columns remain unmodified and the rows are filtered based on the constraints applied. The rows returning a boolean TRUE value for the conditions are available as a result of the operation. However, like other operations if the filter() method yields an NA result, it is considered to be equivalent to the FALSE boolean values and hence dropped from the resulting DataFrame.
Syntax : filter(df, FUN)
Parameter :
df – A DataFrame,
FUN – The function defined using the df variables, which return a boolean value upon evaluation<data-masking>
This method is used in combination with the %in% operator to select rows satisfying the indicated conditions.
Example:
R
# declare a DataFrame# different data type have # been indicated for different # colslibrary(dplyr) data_frame <- data.frame( "col1" = as.character(6:9), "col2" = c(4.5,6.7,89.0,6.2), "col3" = factor(letters[1:4])) print("Original DataFrame")print (data_frame) # declaring the vector vec <- (8:11)data_frame <- filter(data_frame, col1 %in% vec) print("Modified DataFrame")print (data_frame)
Output
[1] "Original DataFrame"
col1 col2 col3
1 6 4.5 a
2 7 6.7 b
3 8 89.0 c
4 9 6.2 d
[1] "Modified Dataframe"
col1 col2 col3
1 8 89.0 c
2 9 6.2 d
Picked
R DataFrame-Programs
R-DataFrame
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Filter data by multiple conditions in R using Dplyr
Printing Output of an R Program
Group by function in R using Dplyr
How to Replace specific values in column in R DataFrame ?
How to filter R DataFrame by values in a column?
How to Replace specific values in column in R DataFrame ?
How to filter R DataFrame by values in a column?
How to change Row Names of DataFrame in R ?
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n09 May, 2021"
},
{
"code": null,
"e": 152,
"s": 28,
"text": "In this article, we will discuss how to select rows from a DataFrame based on values in a vector in R Programming Language."
},
{
"code": null,
"e": 390,
"s": 152,
"text": "%in% operator in R, is used to identify if an element belongs to a vector or Dataframe. It is used to perform a selection of the elements satisfying the condition. It takes the value and checks for its existence in the object specified. "
},
{
"code": null,
"e": 398,
"s": 390,
"text": "Syntax:"
},
{
"code": null,
"e": 411,
"s": 398,
"text": "val %in% vec"
},
{
"code": null,
"e": 784,
"s": 411,
"text": "It returns a boolean TRUE or FALSE value depending on whether the element is found or not. Then the corresponding element is accessed from the DataFrame. This approach creates a subset of the DataFrame without making any changes to the existing DataFrame. Any particular column can be accessed using df$colname and then matched with vector using this comparison operator. "
},
{
"code": null,
"e": 793,
"s": 784,
"text": "Example:"
},
{
"code": null,
"e": 795,
"s": 793,
"text": "R"
},
{
"code": "# declare a DataFramedata_frame <- data.frame(col1 = c(1:7),col2 = LETTERS[1:7]) print (\"Original DataFrame\")print (data_frame) # declaring the vectorvec <- c('A','a','C') # getting the subset DataFrame after # checking values if belonging to vectorsub_df <- data_frame[data_frame$col2 %in% vec,] print (\"Resultant DataFrame\")print (sub_df)",
"e": 1140,
"s": 795,
"text": null
},
{
"code": null,
"e": 1147,
"s": 1140,
"text": "Output"
},
{
"code": null,
"e": 1328,
"s": 1147,
"text": "[1] \"Original DataFrame\"\n col1 col2\n1 1 A\n2 2 B\n3 3 C\n4 4 D\n5 5 E\n6 6 F\n7 7 G\n[1] \"Resultant DataFrame\"\n col1 col2\n1 1 A\n3 3 C"
},
{
"code": null,
"e": 1583,
"s": 1328,
"text": "This is an instance of the comparison operator which is used to check the existence of an element in a vector or a DataFrame. is.element(x, y) is identical to x %in% y. It returns a boolean logical value to return TRUE if the value is found, else FALSE. "
},
{
"code": null,
"e": 1591,
"s": 1583,
"text": "Syntax:"
},
{
"code": null,
"e": 1611,
"s": 1591,
"text": "is.element(val,vec)"
},
{
"code": null,
"e": 1831,
"s": 1611,
"text": "rbind is applied here to combine two subsets of DataFrames where in, in the first case col2 values can be checked for existence in the vector and then col3 values in vector. Both the sub-DataFrames can then be combined."
},
{
"code": null,
"e": 1840,
"s": 1831,
"text": "Example:"
},
{
"code": null,
"e": 1842,
"s": 1840,
"text": "R"
},
{
"code": "# declare a DataFramedata_frame <- data.frame( col1 = c(1:7),col2 = LETTERS[1:7],col3 = letters[1:7]) print (\"Original DataFrame\")print (data_frame) # declaring the vectorvec <- c('a','C','D') # getting the subset DataFrame after checking # values if belonging to vector of the # corresponding columnssub_df <- rbind(data_frame[is.element(data_frame$col2, vec),], data_frame[is.element(data_frame$col3, vec),]) print (\"Resultant DataFrame\")print (sub_df)",
"e": 2317,
"s": 1842,
"text": null
},
{
"code": null,
"e": 2324,
"s": 2317,
"text": "Output"
},
{
"code": null,
"e": 2577,
"s": 2324,
"text": "[1] \"Original DataFrame\"\n col1 col2 col3\n1 1 A a\n2 2 B b\n3 3 C c\n4 4 D d\n5 5 E e\n6 6 F f\n7 7 G g\n[1] \"Resultant DataFrame\"\n col1 col2 col3\n3 3 C c\n4 4 D d\n1 1 A a"
},
{
"code": null,
"e": 2784,
"s": 2577,
"text": "The data.table package in R can be explicitly invoked into the R working space as an enhanced version of the DataFrames. The setDT() method in R is used to convert the DataFrame to data table by reference. "
},
{
"code": null,
"e": 2852,
"s": 2784,
"text": "Syntax: setDT(df, keep.rownames=FALSE, key=NULL, check.names=FALSE)"
},
{
"code": null,
"e": 2863,
"s": 2852,
"text": "Parameter:"
},
{
"code": null,
"e": 2878,
"s": 2863,
"text": "df – DataFrame"
},
{
"code": null,
"e": 2949,
"s": 2878,
"text": "key – The column name or any vector which has to be passed to setkeyv."
},
{
"code": null,
"e": 3191,
"s": 2949,
"text": "Also, the function J(vec) is then applied, which returns the vec elements by mapping it to the passed column index in the key argument of the setDT() method. It is used to create a join of the table involved along with the character vector. "
},
{
"code": null,
"e": 3257,
"s": 3191,
"text": "The following key points are noticed while using this approach : "
},
{
"code": null,
"e": 3393,
"s": 3257,
"text": "The dataframe is converted to a data table, therefore, each result row of the table is lead by a row number identifier followed by “:”."
},
{
"code": null,
"e": 3526,
"s": 3393,
"text": "The dataframe is checked against each value of the vector, and row of the final output DataFrame is printed in accordance with that."
},
{
"code": null,
"e": 3636,
"s": 3526,
"text": "Application of this approach may lead to ambiguity between the actual available data and the obtained result."
},
{
"code": null,
"e": 3645,
"s": 3636,
"text": "Example:"
},
{
"code": null,
"e": 3647,
"s": 3645,
"text": "R"
},
{
"code": "# declare a DataFrame# different data type have been # indicated for different colslibrary(\"data.table\") data_frame <- data.frame( col1 = c(6:9), col2 = c(4.5,6.7,89.0,6.2), col3 = factor(letters[1:4])) print(\"Original DataFrame\")print (data_frame) # declaring the vector vec <- c(4,6)data_frame <- setDT(data_frame, key = \"col1\")[J(vec)] print (\"Modified Dataframe\")print (data_frame)",
"e": 4042,
"s": 3647,
"text": null
},
{
"code": null,
"e": 4049,
"s": 4042,
"text": "Output"
},
{
"code": null,
"e": 4248,
"s": 4049,
"text": "[1] \"Original DataFrame\" \ncol1 col2 col3 \n1 6 4.5 a \n2 7 6.7 b \n3 8 89.0 c \n4 9 6.2 d \n[1] \"Modified Dataframe\" \n col1 col2 col3 \n1: 4 NA <NA> \n2: 6 4.5 a"
},
{
"code": null,
"e": 4933,
"s": 4248,
"text": "The dplyr package provides a variety of modules and method to simulate data manipulations. The dplyr package is not available in base R and needs to incorporated in the working space to use it as a library. A method filter() is available in this package to produce a subset of the original DataFrame where the columns remain unmodified and the rows are filtered based on the constraints applied. The rows returning a boolean TRUE value for the conditions are available as a result of the operation. However, like other operations if the filter() method yields an NA result, it is considered to be equivalent to the FALSE boolean values and hence dropped from the resulting DataFrame. "
},
{
"code": null,
"e": 4958,
"s": 4933,
"text": "Syntax : filter(df, FUN)"
},
{
"code": null,
"e": 4971,
"s": 4958,
"text": "Parameter : "
},
{
"code": null,
"e": 4989,
"s": 4971,
"text": "df – A DataFrame,"
},
{
"code": null,
"e": 5100,
"s": 4989,
"text": "FUN – The function defined using the df variables, which return a boolean value upon evaluation<data-masking>"
},
{
"code": null,
"e": 5211,
"s": 5100,
"text": "This method is used in combination with the %in% operator to select rows satisfying the indicated conditions. "
},
{
"code": null,
"e": 5220,
"s": 5211,
"text": "Example:"
},
{
"code": null,
"e": 5222,
"s": 5220,
"text": "R"
},
{
"code": "# declare a DataFrame# different data type have # been indicated for different # colslibrary(dplyr) data_frame <- data.frame( \"col1\" = as.character(6:9), \"col2\" = c(4.5,6.7,89.0,6.2), \"col3\" = factor(letters[1:4])) print(\"Original DataFrame\")print (data_frame) # declaring the vector vec <- (8:11)data_frame <- filter(data_frame, col1 %in% vec) print(\"Modified DataFrame\")print (data_frame)",
"e": 5623,
"s": 5222,
"text": null
},
{
"code": null,
"e": 5630,
"s": 5623,
"text": "Output"
},
{
"code": null,
"e": 5825,
"s": 5630,
"text": "[1] \"Original DataFrame\" \n col1 col2 col3 \n1 6 4.5 a \n2 7 6.7 b \n3 8 89.0 c\n4 9 6.2 d \n[1] \"Modified Dataframe\" \n col1 col2 col3 \n1 8 89.0 c\n2 9 6.2 d"
},
{
"code": null,
"e": 5832,
"s": 5825,
"text": "Picked"
},
{
"code": null,
"e": 5853,
"s": 5832,
"text": "R DataFrame-Programs"
},
{
"code": null,
"e": 5865,
"s": 5853,
"text": "R-DataFrame"
},
{
"code": null,
"e": 5876,
"s": 5865,
"text": "R Language"
},
{
"code": null,
"e": 5887,
"s": 5876,
"text": "R Programs"
},
{
"code": null,
"e": 5985,
"s": 5887,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6037,
"s": 5985,
"text": "Filter data by multiple conditions in R using Dplyr"
},
{
"code": null,
"e": 6069,
"s": 6037,
"text": "Printing Output of an R Program"
},
{
"code": null,
"e": 6104,
"s": 6069,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 6162,
"s": 6104,
"text": "How to Replace specific values in column in R DataFrame ?"
},
{
"code": null,
"e": 6211,
"s": 6162,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 6269,
"s": 6211,
"text": "How to Replace specific values in column in R DataFrame ?"
},
{
"code": null,
"e": 6318,
"s": 6269,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 6362,
"s": 6318,
"text": "How to change Row Names of DataFrame in R ?"
},
{
"code": null,
"e": 6420,
"s": 6362,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
}
] |
unique=True – Django Built-in Field Validation | 13 Feb, 2020
Built-in Field Validations in Django models are the validations that come predefined to all Django fields. Every field comes in with built-in validations from Django validators. One can also add more built-in field validations for applying or removing certain constraints on a particular field. unique=True sets the field to be unique i.e. once entered a value in a field, the same value can not be entered in any other instance of that model in any manner. It is generally used for fields like Roll Number, Employee Id, etc which should be unique.
Syntax
field_name = models.Field(unique=True)
Illustration of unique 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 ?
Enter the following code into models.py file of geeks app. We will be using CharField for experimenting for all field options.
from django.db import modelsfrom django.db.models import Model# Create your models here. class GeeksModel(Model): geeks_field = models.CharField( max_length = 200, unique = True )
After running makemigrations and migrate on Django and rendering the above model, let us create an instance from Django admin interface with string “a“. Now to show the constraint of unique=True, let us try to create one more instance of the model using same string. Now it will show this error.
This is enforced at the database level and by model validation. If you try to save a model with a duplicate value in a unique field, a django.db.IntegrityError will be raised by the model’s save() method.This option is valid on all field types except ManyToManyField and OneToOneField.Note that when unique is True, you don’t need to specify db_index, because unique implies the creation of an index.
NaveenArora
Django-models
Python Django
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": "\n13 Feb, 2020"
},
{
"code": null,
"e": 577,
"s": 28,
"text": "Built-in Field Validations in Django models are the validations that come predefined to all Django fields. Every field comes in with built-in validations from Django validators. One can also add more built-in field validations for applying or removing certain constraints on a particular field. unique=True sets the field to be unique i.e. once entered a value in a field, the same value can not be entered in any other instance of that model in any manner. It is generally used for fields like Roll Number, Employee Id, etc which should be unique."
},
{
"code": null,
"e": 584,
"s": 577,
"text": "Syntax"
},
{
"code": null,
"e": 623,
"s": 584,
"text": "field_name = models.Field(unique=True)"
},
{
"code": null,
"e": 730,
"s": 623,
"text": "Illustration of unique using an Example. Consider a project named geeksforgeeks having an app named geeks."
},
{
"code": null,
"e": 817,
"s": 730,
"text": "Refer to the following articles to check how to create a project and an app in Django."
},
{
"code": null,
"e": 868,
"s": 817,
"text": "How to Create a Basic Project using MVT in Django?"
},
{
"code": null,
"e": 901,
"s": 868,
"text": "How to Create an App in Django ?"
},
{
"code": null,
"e": 1028,
"s": 901,
"text": "Enter the following code into models.py file of geeks app. We will be using CharField for experimenting for all field options."
},
{
"code": "from django.db import modelsfrom django.db.models import Model# Create your models here. class GeeksModel(Model): geeks_field = models.CharField( max_length = 200, unique = True )",
"e": 1271,
"s": 1028,
"text": null
},
{
"code": null,
"e": 1567,
"s": 1271,
"text": "After running makemigrations and migrate on Django and rendering the above model, let us create an instance from Django admin interface with string “a“. Now to show the constraint of unique=True, let us try to create one more instance of the model using same string. Now it will show this error."
},
{
"code": null,
"e": 1968,
"s": 1567,
"text": "This is enforced at the database level and by model validation. If you try to save a model with a duplicate value in a unique field, a django.db.IntegrityError will be raised by the model’s save() method.This option is valid on all field types except ManyToManyField and OneToOneField.Note that when unique is True, you don’t need to specify db_index, because unique implies the creation of an index."
},
{
"code": null,
"e": 1980,
"s": 1968,
"text": "NaveenArora"
},
{
"code": null,
"e": 1994,
"s": 1980,
"text": "Django-models"
},
{
"code": null,
"e": 2008,
"s": 1994,
"text": "Python Django"
},
{
"code": null,
"e": 2015,
"s": 2008,
"text": "Python"
},
{
"code": null,
"e": 2113,
"s": 2015,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2145,
"s": 2113,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2172,
"s": 2145,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2193,
"s": 2172,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2216,
"s": 2193,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2272,
"s": 2216,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2303,
"s": 2272,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2345,
"s": 2303,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 2387,
"s": 2345,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 2426,
"s": 2387,
"text": "Python | Get unique values from a list"
}
] |
Why would you use the return statement in Python? | The print() function writes, i.e., "prints", a string or a number on the console. The return statement does not print out the value it returns when the function is called. It however causes the function to exit or terminate immediately, even if it is not the last statement of the function.
Functions that return values are sometimes called fruitful functions. In many other languages, a function that doesn’t return a value is called a procedure.
In the given code the value returned (that is 2) when function foo() is called is used in the function bar(). These return values are printed on console only when the print statements are used as shown below.
def foo():
print("Hello from within foo")
return 2
def bar():
return 10*foo()
print foo()
print bar()
Hello from within foo
2
Hello from within foo
20
We see that when foo() is called from bar(), 2 isn't written to the console. Instead it is used to calculate the value returned from bar(). | [
{
"code": null,
"e": 1478,
"s": 1187,
"text": "The print() function writes, i.e., \"prints\", a string or a number on the console. The return statement does not print out the value it returns when the function is called. It however causes the function to exit or terminate immediately, even if it is not the last statement of the function."
},
{
"code": null,
"e": 1635,
"s": 1478,
"text": "Functions that return values are sometimes called fruitful functions. In many other languages, a function that doesn’t return a value is called a procedure."
},
{
"code": null,
"e": 1844,
"s": 1635,
"text": "In the given code the value returned (that is 2) when function foo() is called is used in the function bar(). These return values are printed on console only when the print statements are used as shown below."
},
{
"code": null,
"e": 1958,
"s": 1844,
"text": "def foo():\n print(\"Hello from within foo\")\n return 2\ndef bar():\n return 10*foo()\nprint foo()\nprint bar()"
},
{
"code": null,
"e": 2007,
"s": 1958,
"text": "Hello from within foo\n2\nHello from within foo\n20"
},
{
"code": null,
"e": 2147,
"s": 2007,
"text": "We see that when foo() is called from bar(), 2 isn't written to the console. Instead it is used to calculate the value returned from bar()."
}
] |
Aptitude - Number System | In Decimal number system, there are ten symbols namely 0,1,2,3,4,5,6,7,8 and 9 called digits. A number is denoted by group of these digits called as numerals.
Face value of a digit in a numeral is value of the digit itself. For example in 321, face value of 1 is 1, face value of 2 is 2 and face value of 3 is 3.
Place value of a digit in a numeral is value of the digit multiplied by 10n where n starts from 0. For example in 321:
Place value of 1 = 1 x 100 = 1 x 1 = 1
Place value of 1 = 1 x 100 = 1 x 1 = 1
Place value of 2 = 2 x 101 = 2 x 10 = 20
Place value of 2 = 2 x 101 = 2 x 10 = 20
Place value of 3 = 3 x 102 = 3 x 100 = 300
Place value of 3 = 3 x 102 = 3 x 100 = 300
0th position digit is called unit digit and is the most commonly used topic in aptitude tests.
Natural Numbers - n > 0 where n is counting number; [1,2,3...]
Whole Numbers - n ≥ 0 where n is counting number; [0,1,2,3...].
0 is the only whole number which is not a natural number.
Every natural number is a whole number.
Integers - n ≥ 0 or n ≤ 0 where n is counting number;...,-3,-2,-1,0,1,2,3... are integers.
Positive Integers - n > 0; [1,2,3...]
Negative Integers - n < 0; [-1,-2,-3...]
Non-Positive Integers - n ≤ 0; [0,-1,-2,-3...]
Non-Negative Integers - n ≥ 0; [0,1,2,3...]
0 is neither positive nor negative integer.
Even Numbers - n / 2 = 0 where n is counting number; [0,2,4,...]
Odd Numbers - n / 2 ≠ 0 where n is counting number; [1,3,5,...]
Prime Numbers - Numbers which is divisible by themselves only apart from 1.
1 is not a prime number.
To test a number p to be prime, find a whole number k such that k > √p. Get all prime numbers less than or equal to k and divide p with each of these prime numbers. If no number divides p exactly then p is a prime number otherwise it is not a prime number.
Example: 191 is prime number or not?
Solution:
Step 1 - 14 > √191
Step 2 - Prime numbers less than 14 are 2,3,5,7,11 and 13.
Step 3 - 191 is not divisible by any above prime number.
Result - 191 is a prime number.
Example: 187 is prime number or not?
Solution:
Step 1 - 14 > √187
Step 2 - Prime numbers less than 14 are 2,3,5,7,11 and 13.
Step 3 - 187 is divisible by 11.
Result - 187 is not a prime number.
Composite Numbers - Non-prime numbers > 1. For example, 4,6,8,9 etc.
1 is neither a prime number nor a composite number.
2 is the only even prime number.
Co-Primes Numbers - Two natural numbers are co-primes if their H.C.F. is 1. For example, (2,3), (4,5) are co-primes.
Natural Numbers - n > 0 where n is counting number; [1,2,3...]
Natural Numbers - n > 0 where n is counting number; [1,2,3...]
Whole Numbers - n ≥ 0 where n is counting number; [0,1,2,3...].
Whole Numbers - n ≥ 0 where n is counting number; [0,1,2,3...].
0 is the only whole number which is not a natural number.
Every natural number is a whole number.
Integers - n ≥ 0 or n ≤ 0 where n is counting number;...,-3,-2,-1,0,1,2,3... are integers.
Positive Integers - n > 0; [1,2,3...]
Negative Integers - n < 0; [-1,-2,-3...]
Non-Positive Integers - n ≤ 0; [0,-1,-2,-3...]
Non-Negative Integers - n ≥ 0; [0,1,2,3...]
0 is neither positive nor negative integer.
Integers - n ≥ 0 or n ≤ 0 where n is counting number;...,-3,-2,-1,0,1,2,3... are integers.
Positive Integers - n > 0; [1,2,3...]
Positive Integers - n > 0; [1,2,3...]
Negative Integers - n < 0; [-1,-2,-3...]
Negative Integers - n < 0; [-1,-2,-3...]
Non-Positive Integers - n ≤ 0; [0,-1,-2,-3...]
Non-Positive Integers - n ≤ 0; [0,-1,-2,-3...]
Non-Negative Integers - n ≥ 0; [0,1,2,3...]
Non-Negative Integers - n ≥ 0; [0,1,2,3...]
0 is neither positive nor negative integer.
Even Numbers - n / 2 = 0 where n is counting number; [0,2,4,...]
Even Numbers - n / 2 = 0 where n is counting number; [0,2,4,...]
Odd Numbers - n / 2 ≠ 0 where n is counting number; [1,3,5,...]
Odd Numbers - n / 2 ≠ 0 where n is counting number; [1,3,5,...]
Prime Numbers - Numbers which is divisible by themselves only apart from 1.
Prime Numbers - Numbers which is divisible by themselves only apart from 1.
1 is not a prime number.
To test a number p to be prime, find a whole number k such that k > √p. Get all prime numbers less than or equal to k and divide p with each of these prime numbers. If no number divides p exactly then p is a prime number otherwise it is not a prime number.
Example: 191 is prime number or not?
Solution:
Step 1 - 14 > √191
Step 2 - Prime numbers less than 14 are 2,3,5,7,11 and 13.
Step 3 - 191 is not divisible by any above prime number.
Result - 191 is a prime number.
Example: 187 is prime number or not?
Solution:
Step 1 - 14 > √187
Step 2 - Prime numbers less than 14 are 2,3,5,7,11 and 13.
Step 3 - 187 is divisible by 11.
Result - 187 is not a prime number.
Composite Numbers - Non-prime numbers > 1. For example, 4,6,8,9 etc.
Composite Numbers - Non-prime numbers > 1. For example, 4,6,8,9 etc.
1 is neither a prime number nor a composite number.
2 is the only even prime number.
Co-Primes Numbers - Two natural numbers are co-primes if their H.C.F. is 1. For example, (2,3), (4,5) are co-primes.
Co-Primes Numbers - Two natural numbers are co-primes if their H.C.F. is 1. For example, (2,3), (4,5) are co-primes.
Following are tips to check divisibility of numbers.
Divisibility by 2 - A number is divisible by 2 if its unit digit is 0,2,4,6 or 8.
Example: 64578 is divisible by 2 or not?
Solution:
Step 1 - Unit digit is 8.
Result - 64578 is divisible by 2.
Example: 64575 is divisible by 2 or not?
Solution:
Step 1 - Unit digit is 5.
Result - 64575 is not divisible by 2.
Divisibility by 3 - A number is divisible by 3 if sum of its digits is completely divisible by 3.
Example: 64578 is divisible by 3 or not?
Solution:
Step 1 - Sum of its digits is 6 + 4 + 5 + 7 + 8 = 30
which is divisible by 3.
Result - 64578 is divisible by 3.
Example: 64576 is divisible by 3 or not?
Solution:
Step 1 - Sum of its digits is 6 + 4 + 5 + 7 + 6 = 28
which is not divisible by 3.
Result - 64576 is not divisible by 3.
Divisibility by 4 - A number is divisible by 4 if number formed using its last two digits is completely divisible by 4.
Example: 64578 is divisible by 4 or not?
Solution:
Step 1 - number formed using its last two digits is 78
which is not divisible by 4.
Result - 64578 is not divisible by 4.
Example: 64580 is divisible by 4 or not?
Solution:
Step 1 - number formed using its last two digits is 80
which is divisible by 4.
Result - 64580 is divisible by 4.
Divisibility by 5 - A number is divisible by 5 if its unit digit is 0 or 5.
Example: 64578 is divisible by 5 or not?
Solution:
Step 1 - Unit digit is 8.
Result - 64578 is not divisible by 5.
Example: 64575 is divisible by 5 or not?
Solution:
Step 1 - Unit digit is 5.
Result - 64575 is divisible by 5.
Divisibility by 6 - A number is divisible by 6 if the number is divisible by both 2 and 3.
Example: 64578 is divisible by 6 or not?
Solution:
Step 1 - Unit digit is 8. Number is divisible by 2.
Step 2 - Sum of its digits is 6 + 4 + 5 + 7 + 8 = 30
which is divisible by 3.
Result - 64578 is divisible by 6.
Example: 64576 is divisible by 6 or not?
Solution:
Step 1 - Unit digit is 8. Number is divisible by 2.
Step 2 - Sum of its digits is 6 + 4 + 5 + 7 + 6 = 28
which is not divisible by 3.
Result - 64576 is not divisible by 6.
Divisibility by 8 - A number is divisible by 8 if number formed using its last three digits is completely divisible by 8.
Example: 64578 is divisible by 8 or not?
Solution:
Step 1 - number formed using its last three digits is 578
which is not divisible by 8.
Result - 64578 is not divisible by 8.
Example: 64576 is divisible by 8 or not?
Solution:
Step 1 - number formed using its last three digits is 576
which is divisible by 8.
Result - 64576 is divisible by 8.
Divisibility by 9 - A number is divisible by 9 if sum of its digits is completely divisible by 9.
Example: 64579 is divisible by 9 or not?
Solution:
Step 1 - Sum of its digits is 6 + 4 + 5 + 7 + 9 = 31
which is not divisible by 9.
Result - 64579 is not divisible by 9.
Example: 64575 is divisible by 9 or not?
Solution:
Step 1 - Sum of its digits is 6 + 4 + 5 + 7 + 5 = 27
which is divisible by 9.
Result - 64575 is divisible by 9.
Divisibility by 10 - A number is divisible by 10 if its unit digit is 0.
Example: 64575 is divisible by 10 or not?
Solution:
Step 1 - Unit digit is 5.
Result - 64578 is not divisible by 10.
Example: 64570 is divisible by 10 or not?
Solution:
Step 1 - Unit digit is 0.
Result - 64570 is divisible by 10.
Divisibility by 11 - A number is divisible by 11 if difference between sum of digits at odd places and sum of digits at even places is either 0 or is divisible by 11.
Example: 64575 is divisible by 11 or not?
Solution:
Step 1 - difference between sum of digits at odd places
and sum of digits at even places = (6+5+5) - (4+7) = 5
which is not divisible by 11.
Result - 64575 is not divisible by 11.
Example: 64075 is divisible by 11 or not?
Solution:
Step 1 - difference between sum of digits at odd places
and sum of digits at even places = (6+0+5) - (4+7) = 0.
Result - 64075 is divisible by 11.
Divisibility by 2 - A number is divisible by 2 if its unit digit is 0,2,4,6 or 8.
Divisibility by 2 - A number is divisible by 2 if its unit digit is 0,2,4,6 or 8.
Example: 64578 is divisible by 2 or not?
Solution:
Step 1 - Unit digit is 8.
Result - 64578 is divisible by 2.
Example: 64575 is divisible by 2 or not?
Solution:
Step 1 - Unit digit is 5.
Result - 64575 is not divisible by 2.
Divisibility by 3 - A number is divisible by 3 if sum of its digits is completely divisible by 3.
Divisibility by 3 - A number is divisible by 3 if sum of its digits is completely divisible by 3.
Example: 64578 is divisible by 3 or not?
Solution:
Step 1 - Sum of its digits is 6 + 4 + 5 + 7 + 8 = 30
which is divisible by 3.
Result - 64578 is divisible by 3.
Example: 64576 is divisible by 3 or not?
Solution:
Step 1 - Sum of its digits is 6 + 4 + 5 + 7 + 6 = 28
which is not divisible by 3.
Result - 64576 is not divisible by 3.
Divisibility by 4 - A number is divisible by 4 if number formed using its last two digits is completely divisible by 4.
Divisibility by 4 - A number is divisible by 4 if number formed using its last two digits is completely divisible by 4.
Example: 64578 is divisible by 4 or not?
Solution:
Step 1 - number formed using its last two digits is 78
which is not divisible by 4.
Result - 64578 is not divisible by 4.
Example: 64580 is divisible by 4 or not?
Solution:
Step 1 - number formed using its last two digits is 80
which is divisible by 4.
Result - 64580 is divisible by 4.
Divisibility by 5 - A number is divisible by 5 if its unit digit is 0 or 5.
Divisibility by 5 - A number is divisible by 5 if its unit digit is 0 or 5.
Example: 64578 is divisible by 5 or not?
Solution:
Step 1 - Unit digit is 8.
Result - 64578 is not divisible by 5.
Example: 64575 is divisible by 5 or not?
Solution:
Step 1 - Unit digit is 5.
Result - 64575 is divisible by 5.
Divisibility by 6 - A number is divisible by 6 if the number is divisible by both 2 and 3.
Divisibility by 6 - A number is divisible by 6 if the number is divisible by both 2 and 3.
Example: 64578 is divisible by 6 or not?
Solution:
Step 1 - Unit digit is 8. Number is divisible by 2.
Step 2 - Sum of its digits is 6 + 4 + 5 + 7 + 8 = 30
which is divisible by 3.
Result - 64578 is divisible by 6.
Example: 64576 is divisible by 6 or not?
Solution:
Step 1 - Unit digit is 8. Number is divisible by 2.
Step 2 - Sum of its digits is 6 + 4 + 5 + 7 + 6 = 28
which is not divisible by 3.
Result - 64576 is not divisible by 6.
Divisibility by 8 - A number is divisible by 8 if number formed using its last three digits is completely divisible by 8.
Divisibility by 8 - A number is divisible by 8 if number formed using its last three digits is completely divisible by 8.
Example: 64578 is divisible by 8 or not?
Solution:
Step 1 - number formed using its last three digits is 578
which is not divisible by 8.
Result - 64578 is not divisible by 8.
Example: 64576 is divisible by 8 or not?
Solution:
Step 1 - number formed using its last three digits is 576
which is divisible by 8.
Result - 64576 is divisible by 8.
Divisibility by 9 - A number is divisible by 9 if sum of its digits is completely divisible by 9.
Divisibility by 9 - A number is divisible by 9 if sum of its digits is completely divisible by 9.
Example: 64579 is divisible by 9 or not?
Solution:
Step 1 - Sum of its digits is 6 + 4 + 5 + 7 + 9 = 31
which is not divisible by 9.
Result - 64579 is not divisible by 9.
Example: 64575 is divisible by 9 or not?
Solution:
Step 1 - Sum of its digits is 6 + 4 + 5 + 7 + 5 = 27
which is divisible by 9.
Result - 64575 is divisible by 9.
Divisibility by 10 - A number is divisible by 10 if its unit digit is 0.
Divisibility by 10 - A number is divisible by 10 if its unit digit is 0.
Example: 64575 is divisible by 10 or not?
Solution:
Step 1 - Unit digit is 5.
Result - 64578 is not divisible by 10.
Example: 64570 is divisible by 10 or not?
Solution:
Step 1 - Unit digit is 0.
Result - 64570 is divisible by 10.
Divisibility by 11 - A number is divisible by 11 if difference between sum of digits at odd places and sum of digits at even places is either 0 or is divisible by 11.
Divisibility by 11 - A number is divisible by 11 if difference between sum of digits at odd places and sum of digits at even places is either 0 or is divisible by 11.
Example: 64575 is divisible by 11 or not?
Solution:
Step 1 - difference between sum of digits at odd places
and sum of digits at even places = (6+5+5) - (4+7) = 5
which is not divisible by 11.
Result - 64575 is not divisible by 11.
Example: 64075 is divisible by 11 or not?
Solution:
Step 1 - difference between sum of digits at odd places
and sum of digits at even places = (6+0+5) - (4+7) = 0.
Result - 64075 is divisible by 11.
If a number n is divisible by two co-primes numbers a, b then n is divisible by ab.
(a-b) always divides (an - bn) if n is a natural number.
(a+b) always divides (an - bn) if n is an even number.
(a+b) always divides (an + bn) if n is an odd number.
If a number n is divisible by two co-primes numbers a, b then n is divisible by ab.
If a number n is divisible by two co-primes numbers a, b then n is divisible by ab.
(a-b) always divides (an - bn) if n is a natural number.
(a-b) always divides (an - bn) if n is a natural number.
(a+b) always divides (an - bn) if n is an even number.
(a+b) always divides (an - bn) if n is an even number.
(a+b) always divides (an + bn) if n is an odd number.
(a+b) always divides (an + bn) if n is an odd number.
When a number is divided by another number then
Following are formulaes for basic number series:
(1+2+3+...+n) = (1/2)n(n+1)
(12+22+32+...+n2) = (1/6)n(n+1)(2n+1)
(13+23+33+...+n3) = (1/4)n2(n+1)2
(1+2+3+...+n) = (1/2)n(n+1)
(1+2+3+...+n) = (1/2)n(n+1)
(12+22+32+...+n2) = (1/6)n(n+1)(2n+1)
(12+22+32+...+n2) = (1/6)n(n+1)(2n+1)
(13+23+33+...+n3) = (1/4)n2(n+1)2
(13+23+33+...+n3) = (1/4)n2(n+1)2
These are the basic formulae:
(a + b)2 = a2 + b2 + 2ab
(a - b)2 = a2 + b2 - 2ab
(a + b)2 - (a - b)2 = 4ab
(a + b)2 + (a - b)2 = 2(a2 + b2)
(a2 - b2) = (a + b)(a - b)
(a + b + c)2 = a2 + b2 + c2 + 2(ab + bc + ca)
(a3 + b3) = (a + b)(a2 - ab + b2)
(a3 - b3) = (a - b)(a2 + ab + b2)
(a3 + b3 + c3 - 3abc) = (a + b + c)(a2 + b2 + c2 - ab - bc - ca) | [
{
"code": null,
"e": 4185,
"s": 4026,
"text": "In Decimal number system, there are ten symbols namely 0,1,2,3,4,5,6,7,8 and 9 called digits. A number is denoted by group of these digits called as numerals."
},
{
"code": null,
"e": 4339,
"s": 4185,
"text": "Face value of a digit in a numeral is value of the digit itself. For example in 321, face value of 1 is 1, face value of 2 is 2 and face value of 3 is 3."
},
{
"code": null,
"e": 4458,
"s": 4339,
"text": "Place value of a digit in a numeral is value of the digit multiplied by 10n where n starts from 0. For example in 321:"
},
{
"code": null,
"e": 4497,
"s": 4458,
"text": "Place value of 1 = 1 x 100 = 1 x 1 = 1"
},
{
"code": null,
"e": 4536,
"s": 4497,
"text": "Place value of 1 = 1 x 100 = 1 x 1 = 1"
},
{
"code": null,
"e": 4577,
"s": 4536,
"text": "Place value of 2 = 2 x 101 = 2 x 10 = 20"
},
{
"code": null,
"e": 4618,
"s": 4577,
"text": "Place value of 2 = 2 x 101 = 2 x 10 = 20"
},
{
"code": null,
"e": 4661,
"s": 4618,
"text": "Place value of 3 = 3 x 102 = 3 x 100 = 300"
},
{
"code": null,
"e": 4704,
"s": 4661,
"text": "Place value of 3 = 3 x 102 = 3 x 100 = 300"
},
{
"code": null,
"e": 4799,
"s": 4704,
"text": "0th position digit is called unit digit and is the most commonly used topic in aptitude tests."
},
{
"code": null,
"e": 6513,
"s": 4799,
"text": "\nNatural Numbers - n > 0 where n is counting number; [1,2,3...]\nWhole Numbers - n ≥ 0 where n is counting number; [0,1,2,3...].\n\n0 is the only whole number which is not a natural number.\nEvery natural number is a whole number.\n\nIntegers - n ≥ 0 or n ≤ 0 where n is counting number;...,-3,-2,-1,0,1,2,3... are integers.\n\nPositive Integers - n > 0; [1,2,3...]\nNegative Integers - n < 0; [-1,-2,-3...]\nNon-Positive Integers - n ≤ 0; [0,-1,-2,-3...]\nNon-Negative Integers - n ≥ 0; [0,1,2,3...]\n\n\n0 is neither positive nor negative integer.\n\n\nEven Numbers - n / 2 = 0 where n is counting number; [0,2,4,...]\nOdd Numbers - n / 2 ≠ 0 where n is counting number; [1,3,5,...]\nPrime Numbers - Numbers which is divisible by themselves only apart from 1.\n\n1 is not a prime number.\nTo test a number p to be prime, find a whole number k such that k > √p. Get all prime numbers less than or equal to k and divide p with each of these prime numbers. If no number divides p exactly then p is a prime number otherwise it is not a prime number.\n\nExample: 191 is prime number or not?\nSolution: \nStep 1 - 14 > √191\nStep 2 - Prime numbers less than 14 are 2,3,5,7,11 and 13.\nStep 3 - 191 is not divisible by any above prime number.\nResult - 191 is a prime number.\n\nExample: 187 is prime number or not?\nSolution: \nStep 1 - 14 > √187\nStep 2 - Prime numbers less than 14 are 2,3,5,7,11 and 13.\nStep 3 - 187 is divisible by 11.\nResult - 187 is not a prime number.\n\nComposite Numbers - Non-prime numbers > 1. For example, 4,6,8,9 etc.\n\n1 is neither a prime number nor a composite number.\n2 is the only even prime number.\n\nCo-Primes Numbers - Two natural numbers are co-primes if their H.C.F. is 1. For example, (2,3), (4,5) are co-primes.\n"
},
{
"code": null,
"e": 6576,
"s": 6513,
"text": "Natural Numbers - n > 0 where n is counting number; [1,2,3...]"
},
{
"code": null,
"e": 6639,
"s": 6576,
"text": "Natural Numbers - n > 0 where n is counting number; [1,2,3...]"
},
{
"code": null,
"e": 6703,
"s": 6639,
"text": "Whole Numbers - n ≥ 0 where n is counting number; [0,1,2,3...]."
},
{
"code": null,
"e": 6767,
"s": 6703,
"text": "Whole Numbers - n ≥ 0 where n is counting number; [0,1,2,3...]."
},
{
"code": null,
"e": 6825,
"s": 6767,
"text": "0 is the only whole number which is not a natural number."
},
{
"code": null,
"e": 6865,
"s": 6825,
"text": "Every natural number is a whole number."
},
{
"code": null,
"e": 7175,
"s": 6865,
"text": "Integers - n ≥ 0 or n ≤ 0 where n is counting number;...,-3,-2,-1,0,1,2,3... are integers.\n\nPositive Integers - n > 0; [1,2,3...]\nNegative Integers - n < 0; [-1,-2,-3...]\nNon-Positive Integers - n ≤ 0; [0,-1,-2,-3...]\nNon-Negative Integers - n ≥ 0; [0,1,2,3...]\n\n\n0 is neither positive nor negative integer.\n\n"
},
{
"code": null,
"e": 7267,
"s": 7175,
"text": "Integers - n ≥ 0 or n ≤ 0 where n is counting number;...,-3,-2,-1,0,1,2,3... are integers.\n"
},
{
"code": null,
"e": 7305,
"s": 7267,
"text": "Positive Integers - n > 0; [1,2,3...]"
},
{
"code": null,
"e": 7343,
"s": 7305,
"text": "Positive Integers - n > 0; [1,2,3...]"
},
{
"code": null,
"e": 7384,
"s": 7343,
"text": "Negative Integers - n < 0; [-1,-2,-3...]"
},
{
"code": null,
"e": 7425,
"s": 7384,
"text": "Negative Integers - n < 0; [-1,-2,-3...]"
},
{
"code": null,
"e": 7472,
"s": 7425,
"text": "Non-Positive Integers - n ≤ 0; [0,-1,-2,-3...]"
},
{
"code": null,
"e": 7519,
"s": 7472,
"text": "Non-Positive Integers - n ≤ 0; [0,-1,-2,-3...]"
},
{
"code": null,
"e": 7563,
"s": 7519,
"text": "Non-Negative Integers - n ≥ 0; [0,1,2,3...]"
},
{
"code": null,
"e": 7607,
"s": 7563,
"text": "Non-Negative Integers - n ≥ 0; [0,1,2,3...]"
},
{
"code": null,
"e": 7651,
"s": 7607,
"text": "0 is neither positive nor negative integer."
},
{
"code": null,
"e": 7716,
"s": 7651,
"text": "Even Numbers - n / 2 = 0 where n is counting number; [0,2,4,...]"
},
{
"code": null,
"e": 7781,
"s": 7716,
"text": "Even Numbers - n / 2 = 0 where n is counting number; [0,2,4,...]"
},
{
"code": null,
"e": 7846,
"s": 7781,
"text": "Odd Numbers - n / 2 ≠ 0 where n is counting number; [1,3,5,...]"
},
{
"code": null,
"e": 7911,
"s": 7846,
"text": "Odd Numbers - n / 2 ≠ 0 where n is counting number; [1,3,5,...]"
},
{
"code": null,
"e": 7987,
"s": 7911,
"text": "Prime Numbers - Numbers which is divisible by themselves only apart from 1."
},
{
"code": null,
"e": 8063,
"s": 7987,
"text": "Prime Numbers - Numbers which is divisible by themselves only apart from 1."
},
{
"code": null,
"e": 8088,
"s": 8063,
"text": "1 is not a prime number."
},
{
"code": null,
"e": 8345,
"s": 8088,
"text": "To test a number p to be prime, find a whole number k such that k > √p. Get all prime numbers less than or equal to k and divide p with each of these prime numbers. If no number divides p exactly then p is a prime number otherwise it is not a prime number."
},
{
"code": null,
"e": 8757,
"s": 8345,
"text": "Example: 191 is prime number or not?\nSolution: \nStep 1 - 14 > √191\nStep 2 - Prime numbers less than 14 are 2,3,5,7,11 and 13.\nStep 3 - 191 is not divisible by any above prime number.\nResult - 191 is a prime number.\n\nExample: 187 is prime number or not?\nSolution: \nStep 1 - 14 > √187\nStep 2 - Prime numbers less than 14 are 2,3,5,7,11 and 13.\nStep 3 - 187 is divisible by 11.\nResult - 187 is not a prime number.\n"
},
{
"code": null,
"e": 8826,
"s": 8757,
"text": "Composite Numbers - Non-prime numbers > 1. For example, 4,6,8,9 etc."
},
{
"code": null,
"e": 8895,
"s": 8826,
"text": "Composite Numbers - Non-prime numbers > 1. For example, 4,6,8,9 etc."
},
{
"code": null,
"e": 8947,
"s": 8895,
"text": "1 is neither a prime number nor a composite number."
},
{
"code": null,
"e": 8980,
"s": 8947,
"text": "2 is the only even prime number."
},
{
"code": null,
"e": 9097,
"s": 8980,
"text": "Co-Primes Numbers - Two natural numbers are co-primes if their H.C.F. is 1. For example, (2,3), (4,5) are co-primes."
},
{
"code": null,
"e": 9214,
"s": 9097,
"text": "Co-Primes Numbers - Two natural numbers are co-primes if their H.C.F. is 1. For example, (2,3), (4,5) are co-primes."
},
{
"code": null,
"e": 9267,
"s": 9214,
"text": "Following are tips to check divisibility of numbers."
},
{
"code": null,
"e": 13146,
"s": 9267,
"text": "\nDivisibility by 2 - A number is divisible by 2 if its unit digit is 0,2,4,6 or 8.\nExample: 64578 is divisible by 2 or not?\nSolution: \nStep 1 - Unit digit is 8.\nResult - 64578 is divisible by 2.\n\nExample: 64575 is divisible by 2 or not?\nSolution: \nStep 1 - Unit digit is 5.\nResult - 64575 is not divisible by 2.\n\nDivisibility by 3 - A number is divisible by 3 if sum of its digits is completely divisible by 3.\nExample: 64578 is divisible by 3 or not?\nSolution: \nStep 1 - Sum of its digits is 6 + 4 + 5 + 7 + 8 = 30 \nwhich is divisible by 3.\nResult - 64578 is divisible by 3.\n\nExample: 64576 is divisible by 3 or not?\nSolution: \nStep 1 - Sum of its digits is 6 + 4 + 5 + 7 + 6 = 28 \nwhich is not divisible by 3.\nResult - 64576 is not divisible by 3.\n\nDivisibility by 4 - A number is divisible by 4 if number formed using its last two digits is completely divisible by 4.\nExample: 64578 is divisible by 4 or not?\nSolution: \nStep 1 - number formed using its last two digits is 78 \nwhich is not divisible by 4.\nResult - 64578 is not divisible by 4.\n\nExample: 64580 is divisible by 4 or not?\nSolution: \nStep 1 - number formed using its last two digits is 80 \nwhich is divisible by 4.\nResult - 64580 is divisible by 4.\n\nDivisibility by 5 - A number is divisible by 5 if its unit digit is 0 or 5.\nExample: 64578 is divisible by 5 or not?\nSolution: \nStep 1 - Unit digit is 8.\nResult - 64578 is not divisible by 5.\n\nExample: 64575 is divisible by 5 or not?\nSolution: \nStep 1 - Unit digit is 5.\nResult - 64575 is divisible by 5.\n\nDivisibility by 6 - A number is divisible by 6 if the number is divisible by both 2 and 3.\nExample: 64578 is divisible by 6 or not?\nSolution: \nStep 1 - Unit digit is 8. Number is divisible by 2.\nStep 2 - Sum of its digits is 6 + 4 + 5 + 7 + 8 = 30 \nwhich is divisible by 3.\nResult - 64578 is divisible by 6.\n\nExample: 64576 is divisible by 6 or not?\nSolution: \nStep 1 - Unit digit is 8. Number is divisible by 2.\nStep 2 - Sum of its digits is 6 + 4 + 5 + 7 + 6 = 28 \nwhich is not divisible by 3.\nResult - 64576 is not divisible by 6.\n\nDivisibility by 8 - A number is divisible by 8 if number formed using its last three digits is completely divisible by 8.\nExample: 64578 is divisible by 8 or not?\nSolution: \nStep 1 - number formed using its last three digits is 578 \nwhich is not divisible by 8.\nResult - 64578 is not divisible by 8.\n\nExample: 64576 is divisible by 8 or not?\nSolution: \nStep 1 - number formed using its last three digits is 576 \nwhich is divisible by 8.\nResult - 64576 is divisible by 8.\n\nDivisibility by 9 - A number is divisible by 9 if sum of its digits is completely divisible by 9.\nExample: 64579 is divisible by 9 or not?\nSolution: \nStep 1 - Sum of its digits is 6 + 4 + 5 + 7 + 9 = 31 \nwhich is not divisible by 9.\nResult - 64579 is not divisible by 9.\n\nExample: 64575 is divisible by 9 or not?\nSolution: \nStep 1 - Sum of its digits is 6 + 4 + 5 + 7 + 5 = 27 \nwhich is divisible by 9.\nResult - 64575 is divisible by 9.\n\nDivisibility by 10 - A number is divisible by 10 if its unit digit is 0.\nExample: 64575 is divisible by 10 or not?\nSolution: \nStep 1 - Unit digit is 5.\nResult - 64578 is not divisible by 10.\n\nExample: 64570 is divisible by 10 or not?\nSolution: \nStep 1 - Unit digit is 0.\nResult - 64570 is divisible by 10.\n\nDivisibility by 11 - A number is divisible by 11 if difference between sum of digits at odd places and sum of digits at even places is either 0 or is divisible by 11.\nExample: 64575 is divisible by 11 or not?\nSolution: \nStep 1 - difference between sum of digits at odd places \nand sum of digits at even places = (6+5+5) - (4+7) = 5 \nwhich is not divisible by 11.\nResult - 64575 is not divisible by 11.\n\nExample: 64075 is divisible by 11 or not?\nSolution: \nStep 1 - difference between sum of digits at odd places \nand sum of digits at even places = (6+0+5) - (4+7) = 0.\nResult - 64075 is divisible by 11.\n\n"
},
{
"code": null,
"e": 13228,
"s": 13146,
"text": "Divisibility by 2 - A number is divisible by 2 if its unit digit is 0,2,4,6 or 8."
},
{
"code": null,
"e": 13310,
"s": 13228,
"text": "Divisibility by 2 - A number is divisible by 2 if its unit digit is 0,2,4,6 or 8."
},
{
"code": null,
"e": 13540,
"s": 13310,
"text": "Example: 64578 is divisible by 2 or not?\nSolution: \nStep 1 - Unit digit is 8.\nResult - 64578 is divisible by 2.\n\nExample: 64575 is divisible by 2 or not?\nSolution: \nStep 1 - Unit digit is 5.\nResult - 64575 is not divisible by 2.\n"
},
{
"code": null,
"e": 13638,
"s": 13540,
"text": "Divisibility by 3 - A number is divisible by 3 if sum of its digits is completely divisible by 3."
},
{
"code": null,
"e": 13736,
"s": 13638,
"text": "Divisibility by 3 - A number is divisible by 3 if sum of its digits is completely divisible by 3."
},
{
"code": null,
"e": 14076,
"s": 13736,
"text": "Example: 64578 is divisible by 3 or not?\nSolution: \nStep 1 - Sum of its digits is 6 + 4 + 5 + 7 + 8 = 30 \nwhich is divisible by 3.\nResult - 64578 is divisible by 3.\n\nExample: 64576 is divisible by 3 or not?\nSolution: \nStep 1 - Sum of its digits is 6 + 4 + 5 + 7 + 6 = 28 \nwhich is not divisible by 3.\nResult - 64576 is not divisible by 3.\n"
},
{
"code": null,
"e": 14196,
"s": 14076,
"text": "Divisibility by 4 - A number is divisible by 4 if number formed using its last two digits is completely divisible by 4."
},
{
"code": null,
"e": 14316,
"s": 14196,
"text": "Divisibility by 4 - A number is divisible by 4 if number formed using its last two digits is completely divisible by 4."
},
{
"code": null,
"e": 14660,
"s": 14316,
"text": "Example: 64578 is divisible by 4 or not?\nSolution: \nStep 1 - number formed using its last two digits is 78 \nwhich is not divisible by 4.\nResult - 64578 is not divisible by 4.\n\nExample: 64580 is divisible by 4 or not?\nSolution: \nStep 1 - number formed using its last two digits is 80 \nwhich is divisible by 4.\nResult - 64580 is divisible by 4.\n"
},
{
"code": null,
"e": 14736,
"s": 14660,
"text": "Divisibility by 5 - A number is divisible by 5 if its unit digit is 0 or 5."
},
{
"code": null,
"e": 14812,
"s": 14736,
"text": "Divisibility by 5 - A number is divisible by 5 if its unit digit is 0 or 5."
},
{
"code": null,
"e": 15042,
"s": 14812,
"text": "Example: 64578 is divisible by 5 or not?\nSolution: \nStep 1 - Unit digit is 8.\nResult - 64578 is not divisible by 5.\n\nExample: 64575 is divisible by 5 or not?\nSolution: \nStep 1 - Unit digit is 5.\nResult - 64575 is divisible by 5.\n"
},
{
"code": null,
"e": 15133,
"s": 15042,
"text": "Divisibility by 6 - A number is divisible by 6 if the number is divisible by both 2 and 3."
},
{
"code": null,
"e": 15224,
"s": 15133,
"text": "Divisibility by 6 - A number is divisible by 6 if the number is divisible by both 2 and 3."
},
{
"code": null,
"e": 15668,
"s": 15224,
"text": "Example: 64578 is divisible by 6 or not?\nSolution: \nStep 1 - Unit digit is 8. Number is divisible by 2.\nStep 2 - Sum of its digits is 6 + 4 + 5 + 7 + 8 = 30 \nwhich is divisible by 3.\nResult - 64578 is divisible by 6.\n\nExample: 64576 is divisible by 6 or not?\nSolution: \nStep 1 - Unit digit is 8. Number is divisible by 2.\nStep 2 - Sum of its digits is 6 + 4 + 5 + 7 + 6 = 28 \nwhich is not divisible by 3.\nResult - 64576 is not divisible by 6.\n"
},
{
"code": null,
"e": 15790,
"s": 15668,
"text": "Divisibility by 8 - A number is divisible by 8 if number formed using its last three digits is completely divisible by 8."
},
{
"code": null,
"e": 15912,
"s": 15790,
"text": "Divisibility by 8 - A number is divisible by 8 if number formed using its last three digits is completely divisible by 8."
},
{
"code": null,
"e": 16262,
"s": 15912,
"text": "Example: 64578 is divisible by 8 or not?\nSolution: \nStep 1 - number formed using its last three digits is 578 \nwhich is not divisible by 8.\nResult - 64578 is not divisible by 8.\n\nExample: 64576 is divisible by 8 or not?\nSolution: \nStep 1 - number formed using its last three digits is 576 \nwhich is divisible by 8.\nResult - 64576 is divisible by 8.\n"
},
{
"code": null,
"e": 16360,
"s": 16262,
"text": "Divisibility by 9 - A number is divisible by 9 if sum of its digits is completely divisible by 9."
},
{
"code": null,
"e": 16458,
"s": 16360,
"text": "Divisibility by 9 - A number is divisible by 9 if sum of its digits is completely divisible by 9."
},
{
"code": null,
"e": 16798,
"s": 16458,
"text": "Example: 64579 is divisible by 9 or not?\nSolution: \nStep 1 - Sum of its digits is 6 + 4 + 5 + 7 + 9 = 31 \nwhich is not divisible by 9.\nResult - 64579 is not divisible by 9.\n\nExample: 64575 is divisible by 9 or not?\nSolution: \nStep 1 - Sum of its digits is 6 + 4 + 5 + 7 + 5 = 27 \nwhich is divisible by 9.\nResult - 64575 is divisible by 9.\n"
},
{
"code": null,
"e": 16871,
"s": 16798,
"text": "Divisibility by 10 - A number is divisible by 10 if its unit digit is 0."
},
{
"code": null,
"e": 16944,
"s": 16871,
"text": "Divisibility by 10 - A number is divisible by 10 if its unit digit is 0."
},
{
"code": null,
"e": 17178,
"s": 16944,
"text": "Example: 64575 is divisible by 10 or not?\nSolution: \nStep 1 - Unit digit is 5.\nResult - 64578 is not divisible by 10.\n\nExample: 64570 is divisible by 10 or not?\nSolution: \nStep 1 - Unit digit is 0.\nResult - 64570 is divisible by 10.\n"
},
{
"code": null,
"e": 17345,
"s": 17178,
"text": "Divisibility by 11 - A number is divisible by 11 if difference between sum of digits at odd places and sum of digits at even places is either 0 or is divisible by 11."
},
{
"code": null,
"e": 17512,
"s": 17345,
"text": "Divisibility by 11 - A number is divisible by 11 if difference between sum of digits at odd places and sum of digits at even places is either 0 or is divisible by 11."
},
{
"code": null,
"e": 17950,
"s": 17512,
"text": "Example: 64575 is divisible by 11 or not?\nSolution: \nStep 1 - difference between sum of digits at odd places \nand sum of digits at even places = (6+5+5) - (4+7) = 5 \nwhich is not divisible by 11.\nResult - 64575 is not divisible by 11.\n\nExample: 64075 is divisible by 11 or not?\nSolution: \nStep 1 - difference between sum of digits at odd places \nand sum of digits at even places = (6+0+5) - (4+7) = 0.\nResult - 64075 is divisible by 11.\n"
},
{
"code": null,
"e": 18202,
"s": 17950,
"text": "\nIf a number n is divisible by two co-primes numbers a, b then n is divisible by ab.\n(a-b) always divides (an - bn) if n is a natural number.\n(a+b) always divides (an - bn) if n is an even number.\n(a+b) always divides (an + bn) if n is an odd number.\n"
},
{
"code": null,
"e": 18286,
"s": 18202,
"text": "If a number n is divisible by two co-primes numbers a, b then n is divisible by ab."
},
{
"code": null,
"e": 18370,
"s": 18286,
"text": "If a number n is divisible by two co-primes numbers a, b then n is divisible by ab."
},
{
"code": null,
"e": 18427,
"s": 18370,
"text": "(a-b) always divides (an - bn) if n is a natural number."
},
{
"code": null,
"e": 18484,
"s": 18427,
"text": "(a-b) always divides (an - bn) if n is a natural number."
},
{
"code": null,
"e": 18539,
"s": 18484,
"text": "(a+b) always divides (an - bn) if n is an even number."
},
{
"code": null,
"e": 18594,
"s": 18539,
"text": "(a+b) always divides (an - bn) if n is an even number."
},
{
"code": null,
"e": 18648,
"s": 18594,
"text": "(a+b) always divides (an + bn) if n is an odd number."
},
{
"code": null,
"e": 18702,
"s": 18648,
"text": "(a+b) always divides (an + bn) if n is an odd number."
},
{
"code": null,
"e": 18750,
"s": 18702,
"text": "When a number is divided by another number then"
},
{
"code": null,
"e": 18799,
"s": 18750,
"text": "Following are formulaes for basic number series:"
},
{
"code": null,
"e": 18901,
"s": 18799,
"text": "\n(1+2+3+...+n) = (1/2)n(n+1)\n(12+22+32+...+n2) = (1/6)n(n+1)(2n+1)\n(13+23+33+...+n3) = (1/4)n2(n+1)2\n"
},
{
"code": null,
"e": 18929,
"s": 18901,
"text": "(1+2+3+...+n) = (1/2)n(n+1)"
},
{
"code": null,
"e": 18957,
"s": 18929,
"text": "(1+2+3+...+n) = (1/2)n(n+1)"
},
{
"code": null,
"e": 18995,
"s": 18957,
"text": "(12+22+32+...+n2) = (1/6)n(n+1)(2n+1)"
},
{
"code": null,
"e": 19033,
"s": 18995,
"text": "(12+22+32+...+n2) = (1/6)n(n+1)(2n+1)"
},
{
"code": null,
"e": 19067,
"s": 19033,
"text": "(13+23+33+...+n3) = (1/4)n2(n+1)2"
},
{
"code": null,
"e": 19101,
"s": 19067,
"text": "(13+23+33+...+n3) = (1/4)n2(n+1)2"
},
{
"code": null,
"e": 19131,
"s": 19101,
"text": "These are the basic formulae:"
}
] |
Python program to Count Uppercase, Lowercase, special character and numeric values using Regex | 19 Feb, 2022
Prerequisites: Regular Expression in PythonGiven a string. The task is to count the number of Uppercase, Lowercase, special character and numeric values present in the string using Regular expression in Python.Examples:
Input :
"ThisIsGeeksforGeeks!, 123"
Output :
No. of uppercase characters = 4
No. of lowercase characters = 15
No. of numerical characters = 3
No. of special characters = 2
Approach: The re.findall(pattern, string, flags=0) method can be used to find all non-overlapping matches of a pattern in the string. The return value is a list of strings.Below is the implementation.
Python3
import re string = "ThisIsGeeksforGeeks !, 123" # Creating separate lists using# the re.findall() method.uppercase_characters = re.findall(r"[A-Z]", string)lowercase_characters = re.findall(r"[a-z]", string)numerical_characters = re.findall(r"[0-9]", string)special_characters = re.findall(r"[, .!?]", string) print("The no. of uppercase characters is", len(uppercase_characters))print("The no. of lowercase characters is", len(lowercase_characters))print("The no. of numerical characters is", len(numerical_characters))print("The no. of special characters is", len(special_characters))
Output:
The no. of uppercase characters is 4
The no. of lowercase characters is 15
The no. of numerical characters is 3
The no. of special characters is 4
rithiksuthan123
Python Regex-programs
python-regex
Python
Python Programs
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()
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n19 Feb, 2022"
},
{
"code": null,
"e": 274,
"s": 52,
"text": "Prerequisites: Regular Expression in PythonGiven a string. The task is to count the number of Uppercase, Lowercase, special character and numeric values present in the string using Regular expression in Python.Examples: "
},
{
"code": null,
"e": 449,
"s": 274,
"text": "Input : \n\"ThisIsGeeksforGeeks!, 123\" \n\nOutput :\nNo. of uppercase characters = 4\nNo. of lowercase characters = 15\nNo. of numerical characters = 3\nNo. of special characters = 2"
},
{
"code": null,
"e": 652,
"s": 449,
"text": "Approach: The re.findall(pattern, string, flags=0) method can be used to find all non-overlapping matches of a pattern in the string. The return value is a list of strings.Below is the implementation. "
},
{
"code": null,
"e": 660,
"s": 652,
"text": "Python3"
},
{
"code": "import re string = \"ThisIsGeeksforGeeks !, 123\" # Creating separate lists using# the re.findall() method.uppercase_characters = re.findall(r\"[A-Z]\", string)lowercase_characters = re.findall(r\"[a-z]\", string)numerical_characters = re.findall(r\"[0-9]\", string)special_characters = re.findall(r\"[, .!?]\", string) print(\"The no. of uppercase characters is\", len(uppercase_characters))print(\"The no. of lowercase characters is\", len(lowercase_characters))print(\"The no. of numerical characters is\", len(numerical_characters))print(\"The no. of special characters is\", len(special_characters))",
"e": 1248,
"s": 660,
"text": null
},
{
"code": null,
"e": 1257,
"s": 1248,
"text": "Output: "
},
{
"code": null,
"e": 1404,
"s": 1257,
"text": "The no. of uppercase characters is 4\nThe no. of lowercase characters is 15\nThe no. of numerical characters is 3\nThe no. of special characters is 4"
},
{
"code": null,
"e": 1422,
"s": 1406,
"text": "rithiksuthan123"
},
{
"code": null,
"e": 1444,
"s": 1422,
"text": "Python Regex-programs"
},
{
"code": null,
"e": 1457,
"s": 1444,
"text": "python-regex"
},
{
"code": null,
"e": 1464,
"s": 1457,
"text": "Python"
},
{
"code": null,
"e": 1480,
"s": 1464,
"text": "Python Programs"
},
{
"code": null,
"e": 1578,
"s": 1480,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1596,
"s": 1578,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1638,
"s": 1596,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1660,
"s": 1638,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1695,
"s": 1660,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 1721,
"s": 1695,
"text": "Python String | replace()"
},
{
"code": null,
"e": 1764,
"s": 1721,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 1786,
"s": 1764,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 1825,
"s": 1786,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 1863,
"s": 1825,
"text": "Python | Convert a list to dictionary"
}
] |
Multiply Matrix by Vector in R | 26 Mar, 2021
A matrix is a 2-dimensional structure whereas a vector is a one-dimensional structure. In this article, we are going to multiply the given matrix by the given vector using R Programming Language. Multiplication between the two occurs when vector elements are multiplied with matrix elements column-wise.
Approach:
Create a matrix
Create a vector
Multiply them
Display result.
Method 1: Naive method
Once the structures are ready we directly multiply them using the multiplication operator(*).
Example:
R
# create a vector for matrix elementsvector1=c(1,2,3,4,5,6,7,8,9,10,11,12) # Create A matrix with 2 rows and 6 columnsmatrix1 <- matrix(vector1, nrow=2,ncol=6) # multiplication vectormul_vec=c(1,2,3,4) # print multiplication resultprint(matrix1*mul_vec)
Output:
Example 2:
R
# create a vector for matrix elementsvector1=c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16) # Create A matrix with 4 rows and 4 columnsmatrix1 <- matrix(vector1, nrow=4,ncol=4) print(matrix1) mul_vec=c(1,2,3,4) print("Result")print(matrix1*mul_vec)
Output:
Example 3:
This code has both matrix and vector has equal size
R
# create a vector for matrix elementsvector1=c(1,2,3,4) # Create A matrix with 2 rows and 2 columnsmatrix1 <- matrix(vector1,nrow=2,ncol=2) print(matrix1) mul_vec=c(1,2,3,4) print("Result")print(matrix1*mul_vec)
Output:
Method 2: Using sweep()
we can use sweep() method to multiply vectors to a matrix. sweep() function is used to apply the operation “+ or – or ‘*’ or ‘/’ ” to the row or column in the given matrix.
Syntax:
sweep(data, MARGIN, FUN)
Parameter:
data=input matrix
MARGIN: MARGIN = 2 means row; MARGIN = 1 means column.
FUN: The operation that has to be done (e.g. + or – or * or /)
Here, we are performing “*” operation
Example:
R
# create matrix with 15 elementsmatrix1 <- matrix(c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15), nrow=3,byrow=TRUE)print(matrix1)print("---------------") # create a vectorvector1 <- c(1,2,3,4,5) # apply sweep operation that multiplies row # wise(margin=2)print(sweep(matrix1, MARGIN=2,vector1, `*`))print("---------------") # create elements with vector 2vector2 <- c(1,2,3) # apply sweep operation that multiplies column# wise with vector 2(margin=1)print(sweep(matrix1, MARGIN=1,vector2, `*`))
Output:
Example 2:
R
# create matrix with 8 elementsmatrix1 <- matrix(c(1,2,3,4,5,6,7,8), nrow=2,byrow=TRUE)print(matrix1)print("---------------") # create a vectorvector1 <- c(1,2,3,4) # apply sweep operation that multiplies # row wise(margin=2)print(sweep(matrix1, MARGIN=2,vector1, `*`))print("---------------") # create elements with vector 2vector2 <- c(1,2) # apply sweep operation that multiplies column # wise with vector 2(margin=1)print(sweep(matrix1, MARGIN=1,vector2, `*`))
Output:
Picked
R Matrix-Programs
R-Matrix
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Filter data by multiple conditions in R using Dplyr
How to Replace specific values in column in R DataFrame ?
How to Split Column Into Multiple Columns in R DataFrame?
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to Replace specific values in column in R DataFrame ?
How to Split Column Into Multiple Columns in R DataFrame?
How to change Row Names of DataFrame in R ?
How to filter R DataFrame by values in a column?
Remove rows with NA in one column of R DataFrame | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 Mar, 2021"
},
{
"code": null,
"e": 332,
"s": 28,
"text": "A matrix is a 2-dimensional structure whereas a vector is a one-dimensional structure. In this article, we are going to multiply the given matrix by the given vector using R Programming Language. Multiplication between the two occurs when vector elements are multiplied with matrix elements column-wise."
},
{
"code": null,
"e": 342,
"s": 332,
"text": "Approach:"
},
{
"code": null,
"e": 358,
"s": 342,
"text": "Create a matrix"
},
{
"code": null,
"e": 374,
"s": 358,
"text": "Create a vector"
},
{
"code": null,
"e": 388,
"s": 374,
"text": "Multiply them"
},
{
"code": null,
"e": 404,
"s": 388,
"text": "Display result."
},
{
"code": null,
"e": 427,
"s": 404,
"text": "Method 1: Naive method"
},
{
"code": null,
"e": 521,
"s": 427,
"text": "Once the structures are ready we directly multiply them using the multiplication operator(*)."
},
{
"code": null,
"e": 530,
"s": 521,
"text": "Example:"
},
{
"code": null,
"e": 532,
"s": 530,
"text": "R"
},
{
"code": "# create a vector for matrix elementsvector1=c(1,2,3,4,5,6,7,8,9,10,11,12) # Create A matrix with 2 rows and 6 columnsmatrix1 <- matrix(vector1, nrow=2,ncol=6) # multiplication vectormul_vec=c(1,2,3,4) # print multiplication resultprint(matrix1*mul_vec)",
"e": 790,
"s": 532,
"text": null
},
{
"code": null,
"e": 798,
"s": 790,
"text": "Output:"
},
{
"code": null,
"e": 809,
"s": 798,
"text": "Example 2:"
},
{
"code": null,
"e": 811,
"s": 809,
"text": "R"
},
{
"code": "# create a vector for matrix elementsvector1=c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16) # Create A matrix with 4 rows and 4 columnsmatrix1 <- matrix(vector1, nrow=4,ncol=4) print(matrix1) mul_vec=c(1,2,3,4) print(\"Result\")print(matrix1*mul_vec)",
"e": 1058,
"s": 811,
"text": null
},
{
"code": null,
"e": 1066,
"s": 1058,
"text": "Output:"
},
{
"code": null,
"e": 1077,
"s": 1066,
"text": "Example 3:"
},
{
"code": null,
"e": 1129,
"s": 1077,
"text": "This code has both matrix and vector has equal size"
},
{
"code": null,
"e": 1131,
"s": 1129,
"text": "R"
},
{
"code": "# create a vector for matrix elementsvector1=c(1,2,3,4) # Create A matrix with 2 rows and 2 columnsmatrix1 <- matrix(vector1,nrow=2,ncol=2) print(matrix1) mul_vec=c(1,2,3,4) print(\"Result\")print(matrix1*mul_vec)",
"e": 1346,
"s": 1131,
"text": null
},
{
"code": null,
"e": 1354,
"s": 1346,
"text": "Output:"
},
{
"code": null,
"e": 1378,
"s": 1354,
"text": "Method 2: Using sweep()"
},
{
"code": null,
"e": 1551,
"s": 1378,
"text": "we can use sweep() method to multiply vectors to a matrix. sweep() function is used to apply the operation “+ or – or ‘*’ or ‘/’ ” to the row or column in the given matrix."
},
{
"code": null,
"e": 1559,
"s": 1551,
"text": "Syntax:"
},
{
"code": null,
"e": 1585,
"s": 1559,
"text": "sweep(data, MARGIN, FUN)"
},
{
"code": null,
"e": 1596,
"s": 1585,
"text": "Parameter:"
},
{
"code": null,
"e": 1614,
"s": 1596,
"text": "data=input matrix"
},
{
"code": null,
"e": 1669,
"s": 1614,
"text": "MARGIN: MARGIN = 2 means row; MARGIN = 1 means column."
},
{
"code": null,
"e": 1732,
"s": 1669,
"text": "FUN: The operation that has to be done (e.g. + or – or * or /)"
},
{
"code": null,
"e": 1770,
"s": 1732,
"text": "Here, we are performing “*” operation"
},
{
"code": null,
"e": 1779,
"s": 1770,
"text": "Example:"
},
{
"code": null,
"e": 1781,
"s": 1779,
"text": "R"
},
{
"code": "# create matrix with 15 elementsmatrix1 <- matrix(c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15), nrow=3,byrow=TRUE)print(matrix1)print(\"---------------\") # create a vectorvector1 <- c(1,2,3,4,5) # apply sweep operation that multiplies row # wise(margin=2)print(sweep(matrix1, MARGIN=2,vector1, `*`))print(\"---------------\") # create elements with vector 2vector2 <- c(1,2,3) # apply sweep operation that multiplies column# wise with vector 2(margin=1)print(sweep(matrix1, MARGIN=1,vector2, `*`))",
"e": 2291,
"s": 1781,
"text": null
},
{
"code": null,
"e": 2299,
"s": 2291,
"text": "Output:"
},
{
"code": null,
"e": 2310,
"s": 2299,
"text": "Example 2:"
},
{
"code": null,
"e": 2312,
"s": 2310,
"text": "R"
},
{
"code": "# create matrix with 8 elementsmatrix1 <- matrix(c(1,2,3,4,5,6,7,8), nrow=2,byrow=TRUE)print(matrix1)print(\"---------------\") # create a vectorvector1 <- c(1,2,3,4) # apply sweep operation that multiplies # row wise(margin=2)print(sweep(matrix1, MARGIN=2,vector1, `*`))print(\"---------------\") # create elements with vector 2vector2 <- c(1,2) # apply sweep operation that multiplies column # wise with vector 2(margin=1)print(sweep(matrix1, MARGIN=1,vector2, `*`))",
"e": 2798,
"s": 2312,
"text": null
},
{
"code": null,
"e": 2806,
"s": 2798,
"text": "Output:"
},
{
"code": null,
"e": 2813,
"s": 2806,
"text": "Picked"
},
{
"code": null,
"e": 2831,
"s": 2813,
"text": "R Matrix-Programs"
},
{
"code": null,
"e": 2840,
"s": 2831,
"text": "R-Matrix"
},
{
"code": null,
"e": 2851,
"s": 2840,
"text": "R Language"
},
{
"code": null,
"e": 2862,
"s": 2851,
"text": "R Programs"
},
{
"code": null,
"e": 2960,
"s": 2862,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3012,
"s": 2960,
"text": "Filter data by multiple conditions in R using Dplyr"
},
{
"code": null,
"e": 3070,
"s": 3012,
"text": "How to Replace specific values in column in R DataFrame ?"
},
{
"code": null,
"e": 3128,
"s": 3070,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 3180,
"s": 3128,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 3215,
"s": 3180,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 3273,
"s": 3215,
"text": "How to Replace specific values in column in R DataFrame ?"
},
{
"code": null,
"e": 3331,
"s": 3273,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 3375,
"s": 3331,
"text": "How to change Row Names of DataFrame in R ?"
},
{
"code": null,
"e": 3424,
"s": 3375,
"text": "How to filter R DataFrame by values in a column?"
}
] |
Python | Filter list by Boolean list | 27 Sep, 2019
Sometimes, while working with Python list, we can have a problem in which we have to filter a list. This can sometimes, come with variations. One such variation can be filtering by the use of Boolean list. Let’s discuss a way in which this task can be done.
Method : Using itertools.compress()The most elegant and straightforward method to perform this particular task is to use inbuilt functionality of compress() to filter out all the elements from list which exists at Truth positions with respect to index of other list.
# Python3 code to demonstrate working of# Filter list by Boolean list# Using itertools.compressfrom itertools import compress # initializing listtest_list = [6, 4, 8, 9, 10] # printing listprint("The original list : " + str(test_list)) # initializing Boolean listbool_list = [True, False, False, True, True] # printing boolean list print("The bool list is : " + str(bool_list)) # Filter list by Boolean list# Using itertools.compressres = list(compress(test_list, bool_list)) # Printing resultprint("List after filtering is : " + str(res))
The original list : [6, 4, 8, 9, 10]
The bool list is : [True, False, False, True, True]
List after filtering is : [6, 9, 10]
Python list-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": "\n27 Sep, 2019"
},
{
"code": null,
"e": 286,
"s": 28,
"text": "Sometimes, while working with Python list, we can have a problem in which we have to filter a list. This can sometimes, come with variations. One such variation can be filtering by the use of Boolean list. Let’s discuss a way in which this task can be done."
},
{
"code": null,
"e": 553,
"s": 286,
"text": "Method : Using itertools.compress()The most elegant and straightforward method to perform this particular task is to use inbuilt functionality of compress() to filter out all the elements from list which exists at Truth positions with respect to index of other list."
},
{
"code": "# Python3 code to demonstrate working of# Filter list by Boolean list# Using itertools.compressfrom itertools import compress # initializing listtest_list = [6, 4, 8, 9, 10] # printing listprint(\"The original list : \" + str(test_list)) # initializing Boolean listbool_list = [True, False, False, True, True] # printing boolean list print(\"The bool list is : \" + str(bool_list)) # Filter list by Boolean list# Using itertools.compressres = list(compress(test_list, bool_list)) # Printing resultprint(\"List after filtering is : \" + str(res))",
"e": 1099,
"s": 553,
"text": null
},
{
"code": null,
"e": 1228,
"s": 1099,
"text": " \nThe original list : [6, 4, 8, 9, 10]\nThe bool list is : [True, False, False, True, True]\nList after filtering is : [6, 9, 10]\n"
},
{
"code": null,
"e": 1249,
"s": 1228,
"text": "Python list-programs"
},
{
"code": null,
"e": 1256,
"s": 1249,
"text": "Python"
},
{
"code": null,
"e": 1272,
"s": 1256,
"text": "Python Programs"
}
] |
Given a sorted and rotated array, find if there is a pair with a given sum | 22 Jun, 2022
Given an array that is sorted and then rotated around an unknown point. Find if the array has a pair with a given sum ‘x’. It may be assumed that all elements in the array are distinct.
Examples :
Input: arr[] = {11, 15, 6, 8, 9, 10}, x = 16
Output: true
There is a pair (6, 10) with sum 16
Input: arr[] = {11, 15, 26, 38, 9, 10}, x = 35
Output: true
There is a pair (26, 9) with sum 35
Input: arr[] = {11, 15, 26, 38, 9, 10}, x = 45
Output: false
There is no pair with sum 45.
We have discussed a O(n) solution for a sorted array (See steps 2, 3 and 4 of Method 1). We can extend this solution for rotated array as well. The idea is to first find the largest element in array which is the pivot point also and the element just after largest is the smallest element. Once we have indexes largest and smallest elements, we use similar meet in middle algorithm (as discussed here in method 1) to find if there is a pair. The only thing new here is indexes are incremented and decremented in rotational manner using modular arithmetic.
Following is the implementation of above idea.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find a pair with a given sum in a sorted and// rotated array#include<iostream>using namespace std; // This function returns true if arr[0..n-1] has a pair// with sum equals to x.bool pairInSortedRotated(int arr[], int n, int x){ // Find the pivot element int i; for (i=0; i<n-1; i++) if (arr[i] > arr[i+1]) break; int l = (i+1)%n; // l is now index of smallest element int r = i; // r is now index of largest element // Keep moving either l or r till they meet while (l != r) { // If we find a pair with sum x, we return true if (arr[l] + arr[r] == x) return true; // If current pair sum is less, move to the higher sum if (arr[l] + arr[r] < x) l = (l + 1)%n; else // Move to the lower sum side r = (n + r - 1)%n; } return false;} /* Driver program to test above function */int main(){ int arr[] = {11, 15, 6, 8, 9, 10}; int sum = 16; int n = sizeof(arr)/sizeof(arr[0]); if (pairInSortedRotated(arr, n, sum)) cout << "Array has two elements with sum 16"; else cout << "Array doesn't have two elements with sum 16 "; return 0;}
// Java program to find a pair with a given// sum in a sorted and rotated arrayclass PairInSortedRotated{ // This function returns true if arr[0..n-1] // has a pair with sum equals to x. static boolean pairInSortedRotated(int arr[], int n, int x) { // Find the pivot element int i; for (i = 0; i < n - 1; i++) if (arr[i] > arr[i+1]) break; int l = (i + 1) % n; // l is now index of // smallest element int r = i; // r is now index of largest //element // Keep moving either l or r till they meet while (l != r) { // If we find a pair with sum x, we // return true if (arr[l] + arr[r] == x) return true; // If current pair sum is less, move // to the higher sum if (arr[l] + arr[r] < x) l = (l + 1) % n; else // Move to the lower sum side r = (n + r - 1) % n; } return false; } /* Driver program to test above function */ public static void main (String[] args) { int arr[] = {11, 15, 6, 8, 9, 10}; int sum = 16; int n = arr.length; if (pairInSortedRotated(arr, n, sum)) System.out.print("Array has two elements" + " with sum 16"); else System.out.print("Array doesn't have two" + " elements with sum 16 "); }}/*This code is contributed by Prakriti Gupta*/
# Python3 program to find a# pair with a given sum in# a sorted and rotated array # This function returns True# if arr[0..n-1] has a pair# with sum equals to x.def pairInSortedRotated( arr, n, x ): # Find the pivot element for i in range(0, n - 1): if (arr[i] > arr[i + 1]): break; # l is now index of smallest element l = (i + 1) % n # r is now index of largest element r = i # Keep moving either l # or r till they meet while (l != r): # If we find a pair with # sum x, we return True if (arr[l] + arr[r] == x): return True; # If current pair sum is less, # move to the higher sum if (arr[l] + arr[r] < x): l = (l + 1) % n; else: # Move to the lower sum side r = (n + r - 1) % n; return False; # Driver program to test above functionarr = [11, 15, 6, 8, 9, 10]sum = 16n = len(arr) if (pairInSortedRotated(arr, n, sum)): print ("Array has two elements with sum 16")else: print ("Array doesn't have two elements with sum 16 ") # This article contributed by saloni1297
// C# program to find a pair with a given// sum in a sorted and rotated arrayusing System; class PairInSortedRotated{ // This function returns true if arr[0..n-1] // has a pair with sum equals to x. static bool pairInSortedRotated(int []arr, int n, int x) { // Find the pivot element int i; for (i = 0; i < n - 1; i++) if (arr[i] > arr[i + 1]) break; // l is now index of smallest element int l = (i + 1) % n; // r is now index of largest element int r = i; // Keep moving either l or r till they meet while (l != r) { // If we find a pair with sum x, we // return true if (arr[l] + arr[r] == x) return true; // If current pair sum is less, // move to the higher sum if (arr[l] + arr[r] < x) l = (l + 1) % n; // Move to the lower sum side else r = (n + r - 1) % n; } return false; } // Driver Code public static void Main () { int []arr = {11, 15, 6, 8, 9, 10}; int sum = 16; int n = arr.Length; if (pairInSortedRotated(arr, n, sum)) Console.WriteLine("Array has two elements" + " with sum 16"); else Console.WriteLine("Array doesn't have two" + " elements with sum 16 "); }} // This code is contributed by vt_m.
<?php// PHP program to find a pair// with a given sum in a// sorted and rotated array // This function returns true// if arr[0..n-1] has a pair// with sum equals to x. function pairInSortedRotated($arr, $n, $x){ // Find the pivot element $i; for ($i = 0; $i < $n - 1; $i++) if ($arr[$i] > $arr[$i + 1]) break; // l is now index of // smallest element $l = ($i + 1) % $n; // r is now index of // largest element $r = $i; // Keep moving either l // or r till they meet while ($l != $r) { // If we find a pair with // sum x, we return true if ($arr[$l] + $arr[$r] == $x) return true; // If current pair sum is // less, move to the higher sum if ($arr[$l] + $arr[$r] < $x) $l = ($l + 1) % $n; // Move to the lower sum side else $r = ($n + $r - 1) % $n; } return false;} // Driver Code$arr = array(11, 15, 6, 8, 9, 10);$sum = 16;$n = sizeof($arr); if (pairInSortedRotated($arr, $n, $sum)) echo "Array has two elements ". "with sum 16";else echo "Array doesn't have two ". "elements with sum 16 "; // This code is contributed by aj_36?>
<script> // Javascript program to find a// pair with a given sum in a// sorted and rotated array // This function returns true if arr[0..n-1]// has a pair with sum equals to x.function pairInSortedRotated(arr, n, x){ // Find the pivot element let i; for(i = 0; i < n - 1; i++) if (arr[i] > arr[i + 1]) break; // l is now index of // smallest element let l = (i + 1) % n; // r is now index of largest // element let r = i; // Keep moving either l or // r till they meet while (l != r) { // If we find a pair with sum x, we // return true if (arr[l] + arr[r] == x) return true; // If current pair sum is less, move // to the higher sum if (arr[l] + arr[r] < x) l = (l + 1) % n; // Move to the lower sum side else r = (n + r - 1) % n; } return false;} // Driver codelet arr = [ 11, 15, 6, 8, 9, 10 ];let sum = 16;let n = arr.length; if (pairInSortedRotated(arr, n, sum)) document.write("Array has two elements" + " with sum 16");else document.write("Array doesn't have two" + " elements with sum 16 "); // This code is contributed by avanitrachhadiya2155 </script>
Output :
Array has two elements with sum 16
Time Complexity: O(n)
The step to find the pivot can be optimized to O(Logn) using the Binary Search approach discussed here.
Auxiliary Space: O(1)
As constant extra space is used.
How to count all pairs having sum x? The stepwise algorithm is:
Find the pivot element of the sorted and the rotated array. The pivot element is the largest element in the array. The smallest element will be adjacent to it.Use two pointers (say left and right) with the left pointer pointing to the smallest element and the right pointer pointing to largest element.Find the sum of the elements pointed by both the pointers.If the sum is equal to x, then increment the count. If the sum is less than x, then to increase sum move the left pointer to next position by incrementing it in a rotational manner. If the sum is greater than x, then to decrease sum move the right pointer to next position by decrementing it in rotational manner.Repeat step 3 and 4 until the left pointer is not equal to the right pointer or until the left pointer is not equal to right pointer – 1.Print final count.
Find the pivot element of the sorted and the rotated array. The pivot element is the largest element in the array. The smallest element will be adjacent to it.
Use two pointers (say left and right) with the left pointer pointing to the smallest element and the right pointer pointing to largest element.
Find the sum of the elements pointed by both the pointers.
If the sum is equal to x, then increment the count. If the sum is less than x, then to increase sum move the left pointer to next position by incrementing it in a rotational manner. If the sum is greater than x, then to decrease sum move the right pointer to next position by decrementing it in rotational manner.
Repeat step 3 and 4 until the left pointer is not equal to the right pointer or until the left pointer is not equal to right pointer – 1.
Print final count.
Below is implementation of above algorithm:
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find number of pairs with// a given sum in a sorted and rotated array.#include<bits/stdc++.h>using namespace std; // This function returns count of number of pairs// with sum equals to x.int pairsInSortedRotated(int arr[], int n, int x){ // Find the pivot element. Pivot element // is largest element of array. int i; for (i = 0; i < n-1; i++) if (arr[i] > arr[i+1]) break; // l is index of smallest element. int l = (i + 1) % n; // r is index of largest element. int r = i; // Variable to store count of number // of pairs. int cnt = 0; // Find sum of pair formed by arr[l] and // and arr[r] and update l, r and cnt // accordingly. while (l != r) { // If we find a pair with sum x, then // increment cnt, move l and r to // next element. if (arr[l] + arr[r] == x){ cnt++; // This condition is required to // be checked, otherwise l and r // will cross each other and loop // will never terminate. if(l == (r - 1 + n) % n){ return cnt; } l = (l + 1) % n; r = (r - 1 + n) % n; } // If current pair sum is less, move to // the higher sum side. else if (arr[l] + arr[r] < x) l = (l + 1) % n; // If current pair sum is greater, move // to the lower sum side. else r = (n + r - 1)%n; } return cnt;} /* Driver program to test above function */int main(){ int arr[] = {11, 15, 6, 7, 9, 10}; int sum = 16; int n = sizeof(arr)/sizeof(arr[0]); cout << pairsInSortedRotated(arr, n, sum); return 0;}
// Java program to find// number of pairs with// a given sum in a sorted// and rotated array.import java.io.*; class GFG{ // This function returns// count of number of pairs// with sum equals to x.static int pairsInSortedRotated(int arr[], int n, int x){ // Find the pivot element. // Pivot element is largest // element of array. int i; for (i = 0; i < n - 1; i++) if (arr[i] > arr[i + 1]) break; // l is index of // smallest element. int l = (i + 1) % n; // r is index of // largest element. int r = i; // Variable to store // count of number // of pairs. int cnt = 0; // Find sum of pair // formed by arr[l] // and arr[r] and // update l, r and // cnt accordingly. while (l != r) { // If we find a pair with // sum x, then increment // cnt, move l and r to // next element. if (arr[l] + arr[r] == x) { cnt++; // This condition is required // to be checked, otherwise // l and r will cross each // other and loop will never // terminate. if(l == (r - 1 + n) % n) { return cnt; } l = (l + 1) % n; r = (r - 1 + n) % n; } // If current pair sum // is less, move to // the higher sum side. else if (arr[l] + arr[r] < x) l = (l + 1) % n; // If current pair sum // is greater, move // to the lower sum side. else r = (n + r - 1) % n; } return cnt;} // Driver Codepublic static void main (String[] args){ int arr[] = {11, 15, 6, 7, 9, 10}; int sum = 16; int n = arr.length; System.out.println( pairsInSortedRotated(arr, n, sum));}} // This code is contributed by ajit
# Python program to find# number of pairs with# a given sum in a sorted# and rotated array. # This function returns# count of number of pairs# with sum equals to x.def pairsInSortedRotated(arr, n, x): # Find the pivot element. # Pivot element is largest # element of array. for i in range(n): if arr[i] > arr[i + 1]: break # l is index of # smallest element. l = (i + 1) % n # r is index of # largest element. r = i # Variable to store # count of number # of pairs. cnt = 0 # Find sum of pair # formed by arr[l] # and arr[r] and # update l, r and # cnt accordingly. while (l != r): # If we find a pair # with sum x, then # increment cnt, move # l and r to next element. if arr[l] + arr[r] == x: cnt += 1 # This condition is # required to be checked, # otherwise l and r will # cross each other and # loop will never terminate. if l == (r - 1 + n) % n: return cnt l = (l + 1) % n r = (r - 1 + n) % n # If current pair sum # is less, move to # the higher sum side. elif arr[l] + arr[r] < x: l = (l + 1) % n # If current pair sum # is greater, move to # the lower sum side. else: r = (n + r - 1) % n return cnt # Driver Codearr = [11, 15, 6, 7, 9, 10]s = 16 print(pairsInSortedRotated(arr, 6, s)) # This code is contributed# by ChitraNayal
// C# program to find// number of pairs with// a given sum in a sorted// and rotated array.using System; class GFG{ // This function returns// count of number of pairs// with sum equals to x.static int pairsInSortedRotated(int []arr, int n, int x){ // Find the pivot element. // Pivot element is largest // element of array. int i; for (i = 0; i < n - 1; i++) if (arr[i] > arr[i + 1]) break; // l is index of // smallest element. int l = (i + 1) % n; // r is index of // largest element. int r = i; // Variable to store // count of number // of pairs. int cnt = 0; // Find sum of pair // formed by arr[l] // and arr[r] and // update l, r and // cnt accordingly. while (l != r) { // If we find a pair with // sum x, then increment // cnt, move l and r to // next element. if (arr[l] + arr[r] == x) { cnt++; // This condition is required // to be checked, otherwise // l and r will cross each // other and loop will never // terminate. if(l == (r - 1 + n) % n) { return cnt; } l = (l + 1) % n; r = (r - 1 + n) % n; } // If current pair sum // is less, move to // the higher sum side. else if (arr[l] + arr[r] < x) l = (l + 1) % n; // If current pair sum // is greater, move // to the lower sum side. else r = (n + r - 1) % n; } return cnt;} // Driver Codestatic public void Main (){ int []arr = {11, 15, 6, 7, 9, 10}; int sum = 16; int n = arr.Length; Console.WriteLine( pairsInSortedRotated(arr, n, sum));}} // This code is contributed by akt_mit
<?php// PHP program to find number// of pairs with a given sum// in a sorted and rotated array. // This function returns count// of number of pairs with sum// equals to x.function pairsInSortedRotated($arr, $n, $x){ // Find the pivot element. // Pivot element is largest // element of array. $i; for ($i = 0; $i < $n - 1; $i++) if ($arr[$i] > $arr[$i + 1]) break; // l is index of // smallest element. $l = ($i + 1) % $n; // r is index of // largest element. $r = $i; // Variable to store // count of number // of pairs. $cnt = 0; // Find sum of pair formed // by arr[l] and arr[r] and // update l, r and cnt // accordingly. while ($l != $r) { // If we find a pair with // sum x, then increment // cnt, move l and r to // next element. if ($arr[$l] + $arr[$r] == $x) { $cnt++; // This condition is required // to be checked, otherwise l // and r will cross each other // and loop will never terminate. if($l == ($r - 1 + $n) % $n) { return $cnt; } $l = ($l + 1) % $n; $r = ($r - 1 + $n) % $n; } // If current pair sum // is less, move to // the higher sum side. else if ($arr[$l] + $arr[$r] < $x) $l = ($l + 1) % $n; // If current pair sum // is greater, move to // the lower sum side. else $r = ($n + $r - 1) % $n; } return $cnt;} // Driver Code$arr = array(11, 15, 6, 7, 9, 10);$sum = 16;$n = sizeof($arr) / sizeof($arr[0]); echo pairsInSortedRotated($arr, $n, $sum); // This code is contributed by ajit?>
<script>// Javascript program to find// number of pairs with// a given sum in a sorted// and rotated array. // This function returns // count of number of pairs // with sum equals to x. function pairsInSortedRotated(arr,n,x) { // Find the pivot element. // Pivot element is largest // element of array. let i; for (i = 0; i < n - 1; i++) if (arr[i] > arr[i + 1]) break; // l is index of // smallest element. let l = (i + 1) % n; // r is index of // largest element. let r = i; // Variable to store // count of number // of pairs. let cnt = 0; // Find sum of pair // formed by arr[l] // and arr[r] and // update l, r and // cnt accordingly. while (l != r) { // If we find a pair with // sum x, then increment // cnt, move l and r to // next element. if (arr[l] + arr[r] == x) { cnt++; // This condition is required // to be checked, otherwise // l and r will cross each // other and loop will never // terminate. if(l == (r - 1 + n) % n) { return cnt; } l = (l + 1) % n; r = (r - 1 + n) % n; } // If current pair sum // is less, move to // the higher sum side. else if (arr[l] + arr[r] < x) l = (l + 1) % n; // If current pair sum // is greater, move // to the lower sum side. else r = (n + r - 1) % n; } return cnt; } // Driver Code let arr = [11, 15, 6, 7, 9, 10]; let sum = 16; let n = arr.length; document.write(pairsInSortedRotated(arr, n, sum)); // This code is contributed by rag2127</script>
Output:
2
Time Complexity: O(n)
As we are performing linear operations on array.
Auxiliary Space: O(1)
As constant extra space is used.This method is suggested by Nikhil Jindal.
Find if there is a pair with a given sum in a sorted and rotated array | GeeksforGeeks - YouTubeGeeksforGeeks530K subscribersFind if there is a pair with a given sum in a sorted and rotated 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 / 1:53•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=8KuFojXysg0" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Exercise: 1) Extend the above solution to work for arrays with duplicates allowed.This article is contributed by Himanshu Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
jit_t
nik1996
ukasp
mukeshmk95
sagarudasi2
Stark17
avanitrachhadiya2155
rag2127
kargiloutlook
abhijeet19403
rotation
Searching
Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
K'th Smallest/Largest Element in Unsorted Array | Set 1
Search an element in a sorted and rotated array
Find the Missing Number
Search, insert and delete in an unsorted array
Program to find largest element in an array
k largest(or smallest) elements in an array
Given an array of size n and a number k, find all elements that appear more than n/k times
Two Pointers Technique
Find the missing and repeating number | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n22 Jun, 2022"
},
{
"code": null,
"e": 240,
"s": 54,
"text": "Given an array that is sorted and then rotated around an unknown point. Find if the array has a pair with a given sum ‘x’. It may be assumed that all elements in the array are distinct."
},
{
"code": null,
"e": 252,
"s": 240,
"text": "Examples : "
},
{
"code": null,
"e": 535,
"s": 252,
"text": "Input: arr[] = {11, 15, 6, 8, 9, 10}, x = 16\nOutput: true\nThere is a pair (6, 10) with sum 16\n\nInput: arr[] = {11, 15, 26, 38, 9, 10}, x = 35\nOutput: true\nThere is a pair (26, 9) with sum 35\n\nInput: arr[] = {11, 15, 26, 38, 9, 10}, x = 45\nOutput: false\nThere is no pair with sum 45."
},
{
"code": null,
"e": 1090,
"s": 535,
"text": "We have discussed a O(n) solution for a sorted array (See steps 2, 3 and 4 of Method 1). We can extend this solution for rotated array as well. The idea is to first find the largest element in array which is the pivot point also and the element just after largest is the smallest element. Once we have indexes largest and smallest elements, we use similar meet in middle algorithm (as discussed here in method 1) to find if there is a pair. The only thing new here is indexes are incremented and decremented in rotational manner using modular arithmetic."
},
{
"code": null,
"e": 1139,
"s": 1090,
"text": "Following is the implementation of above idea. "
},
{
"code": null,
"e": 1143,
"s": 1139,
"text": "C++"
},
{
"code": null,
"e": 1148,
"s": 1143,
"text": "Java"
},
{
"code": null,
"e": 1156,
"s": 1148,
"text": "Python3"
},
{
"code": null,
"e": 1159,
"s": 1156,
"text": "C#"
},
{
"code": null,
"e": 1163,
"s": 1159,
"text": "PHP"
},
{
"code": null,
"e": 1174,
"s": 1163,
"text": "Javascript"
},
{
"code": "// C++ program to find a pair with a given sum in a sorted and// rotated array#include<iostream>using namespace std; // This function returns true if arr[0..n-1] has a pair// with sum equals to x.bool pairInSortedRotated(int arr[], int n, int x){ // Find the pivot element int i; for (i=0; i<n-1; i++) if (arr[i] > arr[i+1]) break; int l = (i+1)%n; // l is now index of smallest element int r = i; // r is now index of largest element // Keep moving either l or r till they meet while (l != r) { // If we find a pair with sum x, we return true if (arr[l] + arr[r] == x) return true; // If current pair sum is less, move to the higher sum if (arr[l] + arr[r] < x) l = (l + 1)%n; else // Move to the lower sum side r = (n + r - 1)%n; } return false;} /* Driver program to test above function */int main(){ int arr[] = {11, 15, 6, 8, 9, 10}; int sum = 16; int n = sizeof(arr)/sizeof(arr[0]); if (pairInSortedRotated(arr, n, sum)) cout << \"Array has two elements with sum 16\"; else cout << \"Array doesn't have two elements with sum 16 \"; return 0;}",
"e": 2391,
"s": 1174,
"text": null
},
{
"code": "// Java program to find a pair with a given// sum in a sorted and rotated arrayclass PairInSortedRotated{ // This function returns true if arr[0..n-1] // has a pair with sum equals to x. static boolean pairInSortedRotated(int arr[], int n, int x) { // Find the pivot element int i; for (i = 0; i < n - 1; i++) if (arr[i] > arr[i+1]) break; int l = (i + 1) % n; // l is now index of // smallest element int r = i; // r is now index of largest //element // Keep moving either l or r till they meet while (l != r) { // If we find a pair with sum x, we // return true if (arr[l] + arr[r] == x) return true; // If current pair sum is less, move // to the higher sum if (arr[l] + arr[r] < x) l = (l + 1) % n; else // Move to the lower sum side r = (n + r - 1) % n; } return false; } /* Driver program to test above function */ public static void main (String[] args) { int arr[] = {11, 15, 6, 8, 9, 10}; int sum = 16; int n = arr.length; if (pairInSortedRotated(arr, n, sum)) System.out.print(\"Array has two elements\" + \" with sum 16\"); else System.out.print(\"Array doesn't have two\" + \" elements with sum 16 \"); }}/*This code is contributed by Prakriti Gupta*/",
"e": 4133,
"s": 2391,
"text": null
},
{
"code": "# Python3 program to find a# pair with a given sum in# a sorted and rotated array # This function returns True# if arr[0..n-1] has a pair# with sum equals to x.def pairInSortedRotated( arr, n, x ): # Find the pivot element for i in range(0, n - 1): if (arr[i] > arr[i + 1]): break; # l is now index of smallest element l = (i + 1) % n # r is now index of largest element r = i # Keep moving either l # or r till they meet while (l != r): # If we find a pair with # sum x, we return True if (arr[l] + arr[r] == x): return True; # If current pair sum is less, # move to the higher sum if (arr[l] + arr[r] < x): l = (l + 1) % n; else: # Move to the lower sum side r = (n + r - 1) % n; return False; # Driver program to test above functionarr = [11, 15, 6, 8, 9, 10]sum = 16n = len(arr) if (pairInSortedRotated(arr, n, sum)): print (\"Array has two elements with sum 16\")else: print (\"Array doesn't have two elements with sum 16 \") # This article contributed by saloni1297",
"e": 5325,
"s": 4133,
"text": null
},
{
"code": "// C# program to find a pair with a given// sum in a sorted and rotated arrayusing System; class PairInSortedRotated{ // This function returns true if arr[0..n-1] // has a pair with sum equals to x. static bool pairInSortedRotated(int []arr, int n, int x) { // Find the pivot element int i; for (i = 0; i < n - 1; i++) if (arr[i] > arr[i + 1]) break; // l is now index of smallest element int l = (i + 1) % n; // r is now index of largest element int r = i; // Keep moving either l or r till they meet while (l != r) { // If we find a pair with sum x, we // return true if (arr[l] + arr[r] == x) return true; // If current pair sum is less, // move to the higher sum if (arr[l] + arr[r] < x) l = (l + 1) % n; // Move to the lower sum side else r = (n + r - 1) % n; } return false; } // Driver Code public static void Main () { int []arr = {11, 15, 6, 8, 9, 10}; int sum = 16; int n = arr.Length; if (pairInSortedRotated(arr, n, sum)) Console.WriteLine(\"Array has two elements\" + \" with sum 16\"); else Console.WriteLine(\"Array doesn't have two\" + \" elements with sum 16 \"); }} // This code is contributed by vt_m.",
"e": 6942,
"s": 5325,
"text": null
},
{
"code": "<?php// PHP program to find a pair// with a given sum in a// sorted and rotated array // This function returns true// if arr[0..n-1] has a pair// with sum equals to x. function pairInSortedRotated($arr, $n, $x){ // Find the pivot element $i; for ($i = 0; $i < $n - 1; $i++) if ($arr[$i] > $arr[$i + 1]) break; // l is now index of // smallest element $l = ($i + 1) % $n; // r is now index of // largest element $r = $i; // Keep moving either l // or r till they meet while ($l != $r) { // If we find a pair with // sum x, we return true if ($arr[$l] + $arr[$r] == $x) return true; // If current pair sum is // less, move to the higher sum if ($arr[$l] + $arr[$r] < $x) $l = ($l + 1) % $n; // Move to the lower sum side else $r = ($n + $r - 1) % $n; } return false;} // Driver Code$arr = array(11, 15, 6, 8, 9, 10);$sum = 16;$n = sizeof($arr); if (pairInSortedRotated($arr, $n, $sum)) echo \"Array has two elements \". \"with sum 16\";else echo \"Array doesn't have two \". \"elements with sum 16 \"; // This code is contributed by aj_36?>",
"e": 8190,
"s": 6942,
"text": null
},
{
"code": "<script> // Javascript program to find a// pair with a given sum in a// sorted and rotated array // This function returns true if arr[0..n-1]// has a pair with sum equals to x.function pairInSortedRotated(arr, n, x){ // Find the pivot element let i; for(i = 0; i < n - 1; i++) if (arr[i] > arr[i + 1]) break; // l is now index of // smallest element let l = (i + 1) % n; // r is now index of largest // element let r = i; // Keep moving either l or // r till they meet while (l != r) { // If we find a pair with sum x, we // return true if (arr[l] + arr[r] == x) return true; // If current pair sum is less, move // to the higher sum if (arr[l] + arr[r] < x) l = (l + 1) % n; // Move to the lower sum side else r = (n + r - 1) % n; } return false;} // Driver codelet arr = [ 11, 15, 6, 8, 9, 10 ];let sum = 16;let n = arr.length; if (pairInSortedRotated(arr, n, sum)) document.write(\"Array has two elements\" + \" with sum 16\");else document.write(\"Array doesn't have two\" + \" elements with sum 16 \"); // This code is contributed by avanitrachhadiya2155 </script>",
"e": 9604,
"s": 8190,
"text": null
},
{
"code": null,
"e": 9614,
"s": 9604,
"text": "Output : "
},
{
"code": null,
"e": 9649,
"s": 9614,
"text": "Array has two elements with sum 16"
},
{
"code": null,
"e": 9671,
"s": 9649,
"text": "Time Complexity: O(n)"
},
{
"code": null,
"e": 9775,
"s": 9671,
"text": "The step to find the pivot can be optimized to O(Logn) using the Binary Search approach discussed here."
},
{
"code": null,
"e": 9797,
"s": 9775,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 9830,
"s": 9797,
"text": "As constant extra space is used."
},
{
"code": null,
"e": 9896,
"s": 9830,
"text": "How to count all pairs having sum x? The stepwise algorithm is: "
},
{
"code": null,
"e": 10725,
"s": 9896,
"text": "Find the pivot element of the sorted and the rotated array. The pivot element is the largest element in the array. The smallest element will be adjacent to it.Use two pointers (say left and right) with the left pointer pointing to the smallest element and the right pointer pointing to largest element.Find the sum of the elements pointed by both the pointers.If the sum is equal to x, then increment the count. If the sum is less than x, then to increase sum move the left pointer to next position by incrementing it in a rotational manner. If the sum is greater than x, then to decrease sum move the right pointer to next position by decrementing it in rotational manner.Repeat step 3 and 4 until the left pointer is not equal to the right pointer or until the left pointer is not equal to right pointer – 1.Print final count."
},
{
"code": null,
"e": 10885,
"s": 10725,
"text": "Find the pivot element of the sorted and the rotated array. The pivot element is the largest element in the array. The smallest element will be adjacent to it."
},
{
"code": null,
"e": 11029,
"s": 10885,
"text": "Use two pointers (say left and right) with the left pointer pointing to the smallest element and the right pointer pointing to largest element."
},
{
"code": null,
"e": 11088,
"s": 11029,
"text": "Find the sum of the elements pointed by both the pointers."
},
{
"code": null,
"e": 11402,
"s": 11088,
"text": "If the sum is equal to x, then increment the count. If the sum is less than x, then to increase sum move the left pointer to next position by incrementing it in a rotational manner. If the sum is greater than x, then to decrease sum move the right pointer to next position by decrementing it in rotational manner."
},
{
"code": null,
"e": 11540,
"s": 11402,
"text": "Repeat step 3 and 4 until the left pointer is not equal to the right pointer or until the left pointer is not equal to right pointer – 1."
},
{
"code": null,
"e": 11559,
"s": 11540,
"text": "Print final count."
},
{
"code": null,
"e": 11604,
"s": 11559,
"text": "Below is implementation of above algorithm: "
},
{
"code": null,
"e": 11608,
"s": 11604,
"text": "C++"
},
{
"code": null,
"e": 11613,
"s": 11608,
"text": "Java"
},
{
"code": null,
"e": 11621,
"s": 11613,
"text": "Python3"
},
{
"code": null,
"e": 11624,
"s": 11621,
"text": "C#"
},
{
"code": null,
"e": 11628,
"s": 11624,
"text": "PHP"
},
{
"code": null,
"e": 11639,
"s": 11628,
"text": "Javascript"
},
{
"code": "// C++ program to find number of pairs with// a given sum in a sorted and rotated array.#include<bits/stdc++.h>using namespace std; // This function returns count of number of pairs// with sum equals to x.int pairsInSortedRotated(int arr[], int n, int x){ // Find the pivot element. Pivot element // is largest element of array. int i; for (i = 0; i < n-1; i++) if (arr[i] > arr[i+1]) break; // l is index of smallest element. int l = (i + 1) % n; // r is index of largest element. int r = i; // Variable to store count of number // of pairs. int cnt = 0; // Find sum of pair formed by arr[l] and // and arr[r] and update l, r and cnt // accordingly. while (l != r) { // If we find a pair with sum x, then // increment cnt, move l and r to // next element. if (arr[l] + arr[r] == x){ cnt++; // This condition is required to // be checked, otherwise l and r // will cross each other and loop // will never terminate. if(l == (r - 1 + n) % n){ return cnt; } l = (l + 1) % n; r = (r - 1 + n) % n; } // If current pair sum is less, move to // the higher sum side. else if (arr[l] + arr[r] < x) l = (l + 1) % n; // If current pair sum is greater, move // to the lower sum side. else r = (n + r - 1)%n; } return cnt;} /* Driver program to test above function */int main(){ int arr[] = {11, 15, 6, 7, 9, 10}; int sum = 16; int n = sizeof(arr)/sizeof(arr[0]); cout << pairsInSortedRotated(arr, n, sum); return 0;}",
"e": 13408,
"s": 11639,
"text": null
},
{
"code": "// Java program to find// number of pairs with// a given sum in a sorted// and rotated array.import java.io.*; class GFG{ // This function returns// count of number of pairs// with sum equals to x.static int pairsInSortedRotated(int arr[], int n, int x){ // Find the pivot element. // Pivot element is largest // element of array. int i; for (i = 0; i < n - 1; i++) if (arr[i] > arr[i + 1]) break; // l is index of // smallest element. int l = (i + 1) % n; // r is index of // largest element. int r = i; // Variable to store // count of number // of pairs. int cnt = 0; // Find sum of pair // formed by arr[l] // and arr[r] and // update l, r and // cnt accordingly. while (l != r) { // If we find a pair with // sum x, then increment // cnt, move l and r to // next element. if (arr[l] + arr[r] == x) { cnt++; // This condition is required // to be checked, otherwise // l and r will cross each // other and loop will never // terminate. if(l == (r - 1 + n) % n) { return cnt; } l = (l + 1) % n; r = (r - 1 + n) % n; } // If current pair sum // is less, move to // the higher sum side. else if (arr[l] + arr[r] < x) l = (l + 1) % n; // If current pair sum // is greater, move // to the lower sum side. else r = (n + r - 1) % n; } return cnt;} // Driver Codepublic static void main (String[] args){ int arr[] = {11, 15, 6, 7, 9, 10}; int sum = 16; int n = arr.length; System.out.println( pairsInSortedRotated(arr, n, sum));}} // This code is contributed by ajit",
"e": 15340,
"s": 13408,
"text": null
},
{
"code": "# Python program to find# number of pairs with# a given sum in a sorted# and rotated array. # This function returns# count of number of pairs# with sum equals to x.def pairsInSortedRotated(arr, n, x): # Find the pivot element. # Pivot element is largest # element of array. for i in range(n): if arr[i] > arr[i + 1]: break # l is index of # smallest element. l = (i + 1) % n # r is index of # largest element. r = i # Variable to store # count of number # of pairs. cnt = 0 # Find sum of pair # formed by arr[l] # and arr[r] and # update l, r and # cnt accordingly. while (l != r): # If we find a pair # with sum x, then # increment cnt, move # l and r to next element. if arr[l] + arr[r] == x: cnt += 1 # This condition is # required to be checked, # otherwise l and r will # cross each other and # loop will never terminate. if l == (r - 1 + n) % n: return cnt l = (l + 1) % n r = (r - 1 + n) % n # If current pair sum # is less, move to # the higher sum side. elif arr[l] + arr[r] < x: l = (l + 1) % n # If current pair sum # is greater, move to # the lower sum side. else: r = (n + r - 1) % n return cnt # Driver Codearr = [11, 15, 6, 7, 9, 10]s = 16 print(pairsInSortedRotated(arr, 6, s)) # This code is contributed# by ChitraNayal",
"e": 16964,
"s": 15340,
"text": null
},
{
"code": "// C# program to find// number of pairs with// a given sum in a sorted// and rotated array.using System; class GFG{ // This function returns// count of number of pairs// with sum equals to x.static int pairsInSortedRotated(int []arr, int n, int x){ // Find the pivot element. // Pivot element is largest // element of array. int i; for (i = 0; i < n - 1; i++) if (arr[i] > arr[i + 1]) break; // l is index of // smallest element. int l = (i + 1) % n; // r is index of // largest element. int r = i; // Variable to store // count of number // of pairs. int cnt = 0; // Find sum of pair // formed by arr[l] // and arr[r] and // update l, r and // cnt accordingly. while (l != r) { // If we find a pair with // sum x, then increment // cnt, move l and r to // next element. if (arr[l] + arr[r] == x) { cnt++; // This condition is required // to be checked, otherwise // l and r will cross each // other and loop will never // terminate. if(l == (r - 1 + n) % n) { return cnt; } l = (l + 1) % n; r = (r - 1 + n) % n; } // If current pair sum // is less, move to // the higher sum side. else if (arr[l] + arr[r] < x) l = (l + 1) % n; // If current pair sum // is greater, move // to the lower sum side. else r = (n + r - 1) % n; } return cnt;} // Driver Codestatic public void Main (){ int []arr = {11, 15, 6, 7, 9, 10}; int sum = 16; int n = arr.Length; Console.WriteLine( pairsInSortedRotated(arr, n, sum));}} // This code is contributed by akt_mit",
"e": 18883,
"s": 16964,
"text": null
},
{
"code": "<?php// PHP program to find number// of pairs with a given sum// in a sorted and rotated array. // This function returns count// of number of pairs with sum// equals to x.function pairsInSortedRotated($arr, $n, $x){ // Find the pivot element. // Pivot element is largest // element of array. $i; for ($i = 0; $i < $n - 1; $i++) if ($arr[$i] > $arr[$i + 1]) break; // l is index of // smallest element. $l = ($i + 1) % $n; // r is index of // largest element. $r = $i; // Variable to store // count of number // of pairs. $cnt = 0; // Find sum of pair formed // by arr[l] and arr[r] and // update l, r and cnt // accordingly. while ($l != $r) { // If we find a pair with // sum x, then increment // cnt, move l and r to // next element. if ($arr[$l] + $arr[$r] == $x) { $cnt++; // This condition is required // to be checked, otherwise l // and r will cross each other // and loop will never terminate. if($l == ($r - 1 + $n) % $n) { return $cnt; } $l = ($l + 1) % $n; $r = ($r - 1 + $n) % $n; } // If current pair sum // is less, move to // the higher sum side. else if ($arr[$l] + $arr[$r] < $x) $l = ($l + 1) % $n; // If current pair sum // is greater, move to // the lower sum side. else $r = ($n + $r - 1) % $n; } return $cnt;} // Driver Code$arr = array(11, 15, 6, 7, 9, 10);$sum = 16;$n = sizeof($arr) / sizeof($arr[0]); echo pairsInSortedRotated($arr, $n, $sum); // This code is contributed by ajit?>",
"e": 20758,
"s": 18883,
"text": null
},
{
"code": "<script>// Javascript program to find// number of pairs with// a given sum in a sorted// and rotated array. // This function returns // count of number of pairs // with sum equals to x. function pairsInSortedRotated(arr,n,x) { // Find the pivot element. // Pivot element is largest // element of array. let i; for (i = 0; i < n - 1; i++) if (arr[i] > arr[i + 1]) break; // l is index of // smallest element. let l = (i + 1) % n; // r is index of // largest element. let r = i; // Variable to store // count of number // of pairs. let cnt = 0; // Find sum of pair // formed by arr[l] // and arr[r] and // update l, r and // cnt accordingly. while (l != r) { // If we find a pair with // sum x, then increment // cnt, move l and r to // next element. if (arr[l] + arr[r] == x) { cnt++; // This condition is required // to be checked, otherwise // l and r will cross each // other and loop will never // terminate. if(l == (r - 1 + n) % n) { return cnt; } l = (l + 1) % n; r = (r - 1 + n) % n; } // If current pair sum // is less, move to // the higher sum side. else if (arr[l] + arr[r] < x) l = (l + 1) % n; // If current pair sum // is greater, move // to the lower sum side. else r = (n + r - 1) % n; } return cnt; } // Driver Code let arr = [11, 15, 6, 7, 9, 10]; let sum = 16; let n = arr.length; document.write(pairsInSortedRotated(arr, n, sum)); // This code is contributed by rag2127</script>",
"e": 22884,
"s": 20758,
"text": null
},
{
"code": null,
"e": 22893,
"s": 22884,
"text": "Output: "
},
{
"code": null,
"e": 22895,
"s": 22893,
"text": "2"
},
{
"code": null,
"e": 22918,
"s": 22895,
"text": "Time Complexity: O(n) "
},
{
"code": null,
"e": 22967,
"s": 22918,
"text": "As we are performing linear operations on array."
},
{
"code": null,
"e": 22990,
"s": 22967,
"text": "Auxiliary Space: O(1) "
},
{
"code": null,
"e": 23066,
"s": 22990,
"text": "As constant extra space is used.This method is suggested by Nikhil Jindal. "
},
{
"code": null,
"e": 24024,
"s": 23066,
"text": "Find if there is a pair with a given sum in a sorted and rotated array | GeeksforGeeks - YouTubeGeeksforGeeks530K subscribersFind if there is a pair with a given sum in a sorted and rotated 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 / 1:53•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=8KuFojXysg0\" 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": 24278,
"s": 24024,
"text": "Exercise: 1) Extend the above solution to work for arrays with duplicates allowed.This article is contributed by Himanshu Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 24284,
"s": 24278,
"text": "jit_t"
},
{
"code": null,
"e": 24292,
"s": 24284,
"text": "nik1996"
},
{
"code": null,
"e": 24298,
"s": 24292,
"text": "ukasp"
},
{
"code": null,
"e": 24309,
"s": 24298,
"text": "mukeshmk95"
},
{
"code": null,
"e": 24321,
"s": 24309,
"text": "sagarudasi2"
},
{
"code": null,
"e": 24329,
"s": 24321,
"text": "Stark17"
},
{
"code": null,
"e": 24350,
"s": 24329,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 24358,
"s": 24350,
"text": "rag2127"
},
{
"code": null,
"e": 24372,
"s": 24358,
"text": "kargiloutlook"
},
{
"code": null,
"e": 24386,
"s": 24372,
"text": "abhijeet19403"
},
{
"code": null,
"e": 24395,
"s": 24386,
"text": "rotation"
},
{
"code": null,
"e": 24405,
"s": 24395,
"text": "Searching"
},
{
"code": null,
"e": 24415,
"s": 24405,
"text": "Searching"
},
{
"code": null,
"e": 24513,
"s": 24415,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 24581,
"s": 24513,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 24637,
"s": 24581,
"text": "K'th Smallest/Largest Element in Unsorted Array | Set 1"
},
{
"code": null,
"e": 24685,
"s": 24637,
"text": "Search an element in a sorted and rotated array"
},
{
"code": null,
"e": 24709,
"s": 24685,
"text": "Find the Missing Number"
},
{
"code": null,
"e": 24756,
"s": 24709,
"text": "Search, insert and delete in an unsorted array"
},
{
"code": null,
"e": 24800,
"s": 24756,
"text": "Program to find largest element in an array"
},
{
"code": null,
"e": 24844,
"s": 24800,
"text": "k largest(or smallest) elements in an array"
},
{
"code": null,
"e": 24935,
"s": 24844,
"text": "Given an array of size n and a number k, find all elements that appear more than n/k times"
},
{
"code": null,
"e": 24958,
"s": 24935,
"text": "Two Pointers Technique"
}
] |
Creating dialog boxes with the Dialog Tool in Linux | 22 Jun, 2022
The dialog package is a nifty little tool that was originally created by Savio Lam and is currently maintained by Thomas E. Dickey. This package actually recreates standard Windows dialog boxes in a text environment using ANSI escape control codes. These dialog boxes can be easily incorporated into your shell scripts to interact with your script users.
The dialog package isn’t installed in all Linux distributions by default, but it’s almost always included in the software repository. For Ubuntu Linux, the following command can be used to install the package.
sudo apt-get install dialog
It installs the dialog package plus the required libraries for the system.
The format for the box options is as follows
There are many dialog widgets. Among them, a few of them are:
1. Calendar – Provides a calendar to display the selected date
The format for this widget is
--calendar <text> <height> <width> <day> <month> <year>
The command which we wrote in the script file is
dialog --calendar 'calendar' 5 50 30 6 2021
calendar widget
After running the script, we get the calendar as shown below.
2. Checklist – Displays multiple entries where each entry can be turned on or off.
The format for this widget is
–checklist <text> <height> <width> <list height> <tag1> <item1> <status1>...
The command which we wrote in the script file is
dialog –checklist ‘checklist’ 15 10 10 ‘apple’ 5 ‘on’ ‘banana’ 2 ‘off’ ‘coco’ 3 ‘on’ ‘delta’ 4 ‘off’
checklist widget
After running the script, we get the checklist as shown below.
3. Form – This allows you to build a form with labels and text fields to be filled out.
The format for this widget is
–form <text> <height> <width> <form height> <label1> <l_y1> <l_x1> <item1> <i_y1> <i_x1> <flen1> <ilen1> ...
Here, flen is the length of the field, and ilen is the length of the field that allows input to move between fields.
The command which we wrote in the script file is
dialog –form “Please enter the information” 12 40 4 “Name :” 1 1 “” 1 12 15 0 “Age: ” 2 1 “” 2 12 15 0 “Mail id:” 3 1 “” 3 12 15 0
Form widget
After running the script, we get the form as shown below.
4. Gauge – Allows you to display the gauge progress window
The format for this widget is
--gauge <text> <height> <width> [<percent>]
The command which we wrote in the script file is
dialog --gauge "progress.." 10 20 40
gauge widget
After running the script, we get the window as shown below.
5. Message box – Displays a message and requires the user to select an OK button
The format for this widget is
-- msgbox <text> <height> <width>
The command which we wrote in the script file is
dialog --msgbox "This is a message" 10 25
message box widget
After running the script, we get the message box as shown below.
6. Fselect – Provides a file selection window to browse for a file.
The format for this widget is
-- fselect <filepath> <height> < width >
The command which we wrote in the script file is
dialog --title "fselect" --fselect /documents 15 40
fselect widget
After running the script, we get the window as shown below.
7. Infobox – Displays a message without waiting for a response.
The format for this widget is
--infobox <text> <height> <width>
The command which we wrote in the script file is
dialog --infobox "This is a message" 15 30
inforbox widget
After running the script, we get the information box as shown below.
8. Inputbox – Displays a single text form box for text entry.
The format for this widget is
--inputbox <text> <height> <width> [<init>]
The command which we wrote in the script file is
dialog --inputbox "Enter the name" 15 30 'enter here'
inputbox widget
After running the script, we get the input box as shown below.
9. Inputmenu – This widget provides an editable menu.
The format for this widget is
–inputmenu <text> <height> <width> <menu height> <tag1> <item1>...
The command which we wrote in the script file is
dialog –inputmenu “Edit if necessary” 12 45 25 1 “hello” 2 “good morning” 3 ” take care “
inputmenu widget
After running the script, we get the window to edit as shown below.
10. Menu – This widget displays a list of selections from which to choose.
The format for this widget is
–menu <text> <height> <width> <menu height> <tag1> <item1>...
The command which we wrote in the script file is
dialog –menu “Choose the option” 12 45 25 1 “apple” 2 “banana” 3 “mango”
menu widget
After running the script, we get the window to edit as shown below.
11. Pause – It displays a meter showing the status of a specified pause period.
The format for this widget is
--pause <text> <height> <width> <seconds>
The command which we wrote in the script file is
dialog --pause "pause" 20 40 30
Pause widget
After running the script, we get the window as shown below.
The timer starts running..... out of which two images are depicted below
12. Mixed form – This widget allows you to build a form with labels and text fields of different forms to be filled out.
The format for this widget is
–mixedform <text> <height> <width> <form height> <label1> <l_y1> <l_x1> <item1> <i_y1> <i_x1> <flen1> <ilen1> <itype>...
The command which we wrote in the script file is
dialog –mixedform “Please enter the information” 12 40 4 “Name :” 1 1 “” 1 12 15 0 a “Age: ” 2 1 “” 2 12 15 0 a “Mail id:” 3 1 “” 3 12 15 0 a
Mixed form widget
After running the script, we get the form as shown below.
13. Mixedgauge – allows you to display the gauge progress window with multiple items.
The format for this widget is
--mixedgauge <text> <height> <width> <percent> <tag1> <item1>...
The command which we wrote in the script file is
dialog --mixedgauge "Gauge box" 10 20 40 app one
Mixedgauge widget
After running the script, we get the window as shown below.
14. Password – This widget displays a single textbox that hides entered text.
The format for this widget is
--passwordbox <text> <height> <width> [<init>]
The command which we wrote in the script file is
dialog --passwordbox "Password" 10 20
Password widget
After running the script, we get the window as shown below.
15. Passwordform – This widget displays a form with labels and hidden text fields.
The format for this widget is
–passwordform <text> <height> <width> <form height> <label1> <l_y1> <l_x1> <item1> <i_y1> <i_x1> <flen1> <ilen1>...
The command which we wrote in the script file is
dialog –passwordform “Please enter the information” 12 40 4 “Password:” 1 1 “” 1 12 15 0 “otp: ” 2 1 “” 2 12 15 0 “secret key:” 3 1 “” 3 12 15 0
Passwordform widget
After running the script, we get the window as shown below.
16. Radiolist – This widget provides a group of menu items where only one item can be selected.
The format for this widget is
–radiolist <text> <height> <width> <list height> <tag1> <item1> <status1>...
The command which we wrote in the script file is
dialog –radiolist ‘radiolist’ 15 10 10 ‘apple’ 5 ‘off’ ‘banana’ 2 ‘off’ ‘coffee’ 3 ‘off’ ‘dessert’ 4 ‘off’
Radiolist widget
After running the script, we get the window as shown below.
17. Program box – This widget lets you display the output of the command in the dialog box.
The format for this widget is
--prgbox <text> <command> <height> <width>
The command which we wrote in the script file is
dialog --prgbox "command" "ls" 10 30
Program box widget
After running the script, we get the window as shown below.
18. Textbox – This widget displays the contents of a file in a scroll window
The format for this widget is
--textbox <file> <height> <width>
The command which we wrote in the script file is
dialog –textbox /etc/hosts 10 60
Textbox widget
After running the script, we get the window as shown below.
19. Tailbox – This widget displays text from a file in a scroll window using the tail command.
The format for this widget is
--tailbox <file> <height> <width>
The command which we wrote in the script file is
dialog --tailbox /etc/hosts 10 60
tailbox widget
After running the script, we get the window as shown below.
20. Yes no – This widget provides a simple message with Yes and No buttons.
The format for this widget is
--yesno <text> <height> <width>
The command which we wrote in the script file is
dialog --yesno "Do you want run the command" 10 30
yesno widgetimage widget
After running the script, we get the window as shown below.
sumitgumber28
nikhatkhan11
Linux-Tools
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n22 Jun, 2022"
},
{
"code": null,
"e": 407,
"s": 52,
"text": "The dialog package is a nifty little tool that was originally created by Savio Lam and is currently maintained by Thomas E. Dickey. This package actually recreates standard Windows dialog boxes in a text environment using ANSI escape control codes. These dialog boxes can be easily incorporated into your shell scripts to interact with your script users."
},
{
"code": null,
"e": 617,
"s": 407,
"text": "The dialog package isn’t installed in all Linux distributions by default, but it’s almost always included in the software repository. For Ubuntu Linux, the following command can be used to install the package."
},
{
"code": null,
"e": 646,
"s": 617,
"text": "sudo apt-get install dialog "
},
{
"code": null,
"e": 721,
"s": 646,
"text": "It installs the dialog package plus the required libraries for the system."
},
{
"code": null,
"e": 766,
"s": 721,
"text": "The format for the box options is as follows"
},
{
"code": null,
"e": 828,
"s": 766,
"text": "There are many dialog widgets. Among them, a few of them are:"
},
{
"code": null,
"e": 891,
"s": 828,
"text": "1. Calendar – Provides a calendar to display the selected date"
},
{
"code": null,
"e": 922,
"s": 891,
"text": " The format for this widget is"
},
{
"code": null,
"e": 982,
"s": 922,
"text": "--calendar <text> <height> <width> <day> <month> <year>"
},
{
"code": null,
"e": 1032,
"s": 982,
"text": "The command which we wrote in the script file is"
},
{
"code": null,
"e": 1077,
"s": 1032,
"text": "dialog --calendar 'calendar' 5 50 30 6 2021"
},
{
"code": null,
"e": 1093,
"s": 1077,
"text": "calendar widget"
},
{
"code": null,
"e": 1155,
"s": 1093,
"text": "After running the script, we get the calendar as shown below."
},
{
"code": null,
"e": 1238,
"s": 1155,
"text": "2. Checklist – Displays multiple entries where each entry can be turned on or off."
},
{
"code": null,
"e": 1268,
"s": 1238,
"text": "The format for this widget is"
},
{
"code": null,
"e": 1348,
"s": 1268,
"text": "–checklist <text> <height> <width> <list height> <tag1> <item1> <status1>..."
},
{
"code": null,
"e": 1399,
"s": 1348,
"text": "The command which we wrote in the script file is "
},
{
"code": null,
"e": 1501,
"s": 1399,
"text": "dialog –checklist ‘checklist’ 15 10 10 ‘apple’ 5 ‘on’ ‘banana’ 2 ‘off’ ‘coco’ 3 ‘on’ ‘delta’ 4 ‘off’"
},
{
"code": null,
"e": 1518,
"s": 1501,
"text": "checklist widget"
},
{
"code": null,
"e": 1581,
"s": 1518,
"text": "After running the script, we get the checklist as shown below."
},
{
"code": null,
"e": 1669,
"s": 1581,
"text": "3. Form – This allows you to build a form with labels and text fields to be filled out."
},
{
"code": null,
"e": 1699,
"s": 1669,
"text": "The format for this widget is"
},
{
"code": null,
"e": 1810,
"s": 1699,
"text": " –form <text> <height> <width> <form height> <label1> <l_y1> <l_x1> <item1> <i_y1> <i_x1> <flen1> <ilen1> ... "
},
{
"code": null,
"e": 1927,
"s": 1810,
"text": "Here, flen is the length of the field, and ilen is the length of the field that allows input to move between fields."
},
{
"code": null,
"e": 1977,
"s": 1927,
"text": "The command which we wrote in the script file is"
},
{
"code": null,
"e": 2111,
"s": 1977,
"text": " dialog –form “Please enter the information” 12 40 4 “Name :” 1 1 “” 1 12 15 0 “Age: ” 2 1 “” 2 12 15 0 “Mail id:” 3 1 “” 3 12 15 0"
},
{
"code": null,
"e": 2123,
"s": 2111,
"text": "Form widget"
},
{
"code": null,
"e": 2181,
"s": 2123,
"text": "After running the script, we get the form as shown below."
},
{
"code": null,
"e": 2240,
"s": 2181,
"text": "4. Gauge – Allows you to display the gauge progress window"
},
{
"code": null,
"e": 2270,
"s": 2240,
"text": "The format for this widget is"
},
{
"code": null,
"e": 2315,
"s": 2270,
"text": " --gauge <text> <height> <width> [<percent>]"
},
{
"code": null,
"e": 2365,
"s": 2315,
"text": "The command which we wrote in the script file is"
},
{
"code": null,
"e": 2403,
"s": 2365,
"text": "dialog --gauge \"progress..\" 10 20 40"
},
{
"code": null,
"e": 2416,
"s": 2403,
"text": "gauge widget"
},
{
"code": null,
"e": 2476,
"s": 2416,
"text": "After running the script, we get the window as shown below."
},
{
"code": null,
"e": 2558,
"s": 2476,
"text": " 5. Message box – Displays a message and requires the user to select an OK button"
},
{
"code": null,
"e": 2588,
"s": 2558,
"text": "The format for this widget is"
},
{
"code": null,
"e": 2622,
"s": 2588,
"text": "-- msgbox <text> <height> <width>"
},
{
"code": null,
"e": 2672,
"s": 2622,
"text": "The command which we wrote in the script file is"
},
{
"code": null,
"e": 2715,
"s": 2672,
"text": "dialog --msgbox \"This is a message\" 10 25"
},
{
"code": null,
"e": 2734,
"s": 2715,
"text": "message box widget"
},
{
"code": null,
"e": 2799,
"s": 2734,
"text": "After running the script, we get the message box as shown below."
},
{
"code": null,
"e": 2867,
"s": 2799,
"text": "6. Fselect – Provides a file selection window to browse for a file."
},
{
"code": null,
"e": 2897,
"s": 2867,
"text": "The format for this widget is"
},
{
"code": null,
"e": 2938,
"s": 2897,
"text": "-- fselect <filepath> <height> < width >"
},
{
"code": null,
"e": 2988,
"s": 2938,
"text": "The command which we wrote in the script file is"
},
{
"code": null,
"e": 3040,
"s": 2988,
"text": "dialog --title \"fselect\" --fselect /documents 15 40"
},
{
"code": null,
"e": 3055,
"s": 3040,
"text": "fselect widget"
},
{
"code": null,
"e": 3115,
"s": 3055,
"text": "After running the script, we get the window as shown below."
},
{
"code": null,
"e": 3179,
"s": 3115,
"text": "7. Infobox – Displays a message without waiting for a response."
},
{
"code": null,
"e": 3209,
"s": 3179,
"text": "The format for this widget is"
},
{
"code": null,
"e": 3248,
"s": 3209,
"text": "--infobox <text> <height> <width>"
},
{
"code": null,
"e": 3298,
"s": 3248,
"text": "The command which we wrote in the script file is"
},
{
"code": null,
"e": 3344,
"s": 3298,
"text": "dialog --infobox \"This is a message\" 15 30"
},
{
"code": null,
"e": 3360,
"s": 3344,
"text": "inforbox widget"
},
{
"code": null,
"e": 3429,
"s": 3360,
"text": "After running the script, we get the information box as shown below."
},
{
"code": null,
"e": 3491,
"s": 3429,
"text": "8. Inputbox – Displays a single text form box for text entry."
},
{
"code": null,
"e": 3521,
"s": 3491,
"text": "The format for this widget is"
},
{
"code": null,
"e": 3570,
"s": 3521,
"text": " --inputbox <text> <height> <width> [<init>]"
},
{
"code": null,
"e": 3620,
"s": 3570,
"text": "The command which we wrote in the script file is"
},
{
"code": null,
"e": 3675,
"s": 3620,
"text": "dialog --inputbox \"Enter the name\" 15 30 'enter here'"
},
{
"code": null,
"e": 3691,
"s": 3675,
"text": "inputbox widget"
},
{
"code": null,
"e": 3754,
"s": 3691,
"text": "After running the script, we get the input box as shown below."
},
{
"code": null,
"e": 3808,
"s": 3754,
"text": "9. Inputmenu – This widget provides an editable menu."
},
{
"code": null,
"e": 3838,
"s": 3808,
"text": "The format for this widget is"
},
{
"code": null,
"e": 3909,
"s": 3838,
"text": " –inputmenu <text> <height> <width> <menu height> <tag1> <item1>..."
},
{
"code": null,
"e": 3959,
"s": 3909,
"text": "The command which we wrote in the script file is"
},
{
"code": null,
"e": 4049,
"s": 3959,
"text": "dialog –inputmenu “Edit if necessary” 12 45 25 1 “hello” 2 “good morning” 3 ” take care “"
},
{
"code": null,
"e": 4066,
"s": 4049,
"text": "inputmenu widget"
},
{
"code": null,
"e": 4134,
"s": 4066,
"text": "After running the script, we get the window to edit as shown below."
},
{
"code": null,
"e": 4209,
"s": 4134,
"text": "10. Menu – This widget displays a list of selections from which to choose."
},
{
"code": null,
"e": 4239,
"s": 4209,
"text": "The format for this widget is"
},
{
"code": null,
"e": 4309,
"s": 4239,
"text": "–menu <text> <height> <width> <menu height> <tag1> <item1>..."
},
{
"code": null,
"e": 4359,
"s": 4309,
"text": "The command which we wrote in the script file is"
},
{
"code": null,
"e": 4432,
"s": 4359,
"text": "dialog –menu “Choose the option” 12 45 25 1 “apple” 2 “banana” 3 “mango”"
},
{
"code": null,
"e": 4444,
"s": 4432,
"text": "menu widget"
},
{
"code": null,
"e": 4512,
"s": 4444,
"text": "After running the script, we get the window to edit as shown below."
},
{
"code": null,
"e": 4592,
"s": 4512,
"text": "11. Pause – It displays a meter showing the status of a specified pause period."
},
{
"code": null,
"e": 4622,
"s": 4592,
"text": "The format for this widget is"
},
{
"code": null,
"e": 4664,
"s": 4622,
"text": "--pause <text> <height> <width> <seconds>"
},
{
"code": null,
"e": 4714,
"s": 4664,
"text": "The command which we wrote in the script file is"
},
{
"code": null,
"e": 4746,
"s": 4714,
"text": "dialog --pause \"pause\" 20 40 30"
},
{
"code": null,
"e": 4759,
"s": 4746,
"text": "Pause widget"
},
{
"code": null,
"e": 4819,
"s": 4759,
"text": "After running the script, we get the window as shown below."
},
{
"code": null,
"e": 4892,
"s": 4819,
"text": "The timer starts running..... out of which two images are depicted below"
},
{
"code": null,
"e": 5013,
"s": 4892,
"text": "12. Mixed form – This widget allows you to build a form with labels and text fields of different forms to be filled out."
},
{
"code": null,
"e": 5043,
"s": 5013,
"text": "The format for this widget is"
},
{
"code": null,
"e": 5167,
"s": 5043,
"text": "–mixedform <text> <height> <width> <form height> <label1> <l_y1> <l_x1> <item1> <i_y1> <i_x1> <flen1> <ilen1> <itype>..."
},
{
"code": null,
"e": 5217,
"s": 5167,
"text": "The command which we wrote in the script file is"
},
{
"code": null,
"e": 5361,
"s": 5217,
"text": "dialog –mixedform “Please enter the information” 12 40 4 “Name :” 1 1 “” 1 12 15 0 a “Age: ” 2 1 “” 2 12 15 0 a “Mail id:” 3 1 “” 3 12 15 0 a"
},
{
"code": null,
"e": 5379,
"s": 5361,
"text": "Mixed form widget"
},
{
"code": null,
"e": 5437,
"s": 5379,
"text": "After running the script, we get the form as shown below."
},
{
"code": null,
"e": 5523,
"s": 5437,
"text": "13. Mixedgauge – allows you to display the gauge progress window with multiple items."
},
{
"code": null,
"e": 5553,
"s": 5523,
"text": "The format for this widget is"
},
{
"code": null,
"e": 5620,
"s": 5553,
"text": "--mixedgauge <text> <height> <width> <percent> <tag1> <item1>..."
},
{
"code": null,
"e": 5670,
"s": 5620,
"text": "The command which we wrote in the script file is"
},
{
"code": null,
"e": 5723,
"s": 5670,
"text": "dialog --mixedgauge \"Gauge box\" 10 20 40 app one"
},
{
"code": null,
"e": 5741,
"s": 5723,
"text": "Mixedgauge widget"
},
{
"code": null,
"e": 5801,
"s": 5741,
"text": "After running the script, we get the window as shown below."
},
{
"code": null,
"e": 5879,
"s": 5801,
"text": "14. Password – This widget displays a single textbox that hides entered text."
},
{
"code": null,
"e": 5909,
"s": 5879,
"text": "The format for this widget is"
},
{
"code": null,
"e": 5957,
"s": 5909,
"text": "--passwordbox <text> <height> <width> [<init>]"
},
{
"code": null,
"e": 6007,
"s": 5957,
"text": "The command which we wrote in the script file is"
},
{
"code": null,
"e": 6049,
"s": 6007,
"text": "dialog --passwordbox \"Password\" 10 20"
},
{
"code": null,
"e": 6065,
"s": 6049,
"text": "Password widget"
},
{
"code": null,
"e": 6125,
"s": 6065,
"text": "After running the script, we get the window as shown below."
},
{
"code": null,
"e": 6208,
"s": 6125,
"text": "15. Passwordform – This widget displays a form with labels and hidden text fields."
},
{
"code": null,
"e": 6238,
"s": 6208,
"text": "The format for this widget is"
},
{
"code": null,
"e": 6354,
"s": 6238,
"text": "–passwordform <text> <height> <width> <form height> <label1> <l_y1> <l_x1> <item1> <i_y1> <i_x1> <flen1> <ilen1>..."
},
{
"code": null,
"e": 6404,
"s": 6354,
"text": "The command which we wrote in the script file is"
},
{
"code": null,
"e": 6551,
"s": 6404,
"text": "dialog –passwordform “Please enter the information” 12 40 4 “Password:” 1 1 “” 1 12 15 0 “otp: ” 2 1 “” 2 12 15 0 “secret key:” 3 1 “” 3 12 15 0"
},
{
"code": null,
"e": 6571,
"s": 6551,
"text": "Passwordform widget"
},
{
"code": null,
"e": 6631,
"s": 6571,
"text": "After running the script, we get the window as shown below."
},
{
"code": null,
"e": 6727,
"s": 6631,
"text": "16. Radiolist – This widget provides a group of menu items where only one item can be selected."
},
{
"code": null,
"e": 6757,
"s": 6727,
"text": "The format for this widget is"
},
{
"code": null,
"e": 6837,
"s": 6757,
"text": "–radiolist <text> <height> <width> <list height> <tag1> <item1> <status1>..."
},
{
"code": null,
"e": 6887,
"s": 6837,
"text": "The command which we wrote in the script file is"
},
{
"code": null,
"e": 6996,
"s": 6887,
"text": "dialog –radiolist ‘radiolist’ 15 10 10 ‘apple’ 5 ‘off’ ‘banana’ 2 ‘off’ ‘coffee’ 3 ‘off’ ‘dessert’ 4 ‘off’"
},
{
"code": null,
"e": 7013,
"s": 6996,
"text": "Radiolist widget"
},
{
"code": null,
"e": 7073,
"s": 7013,
"text": "After running the script, we get the window as shown below."
},
{
"code": null,
"e": 7165,
"s": 7073,
"text": "17. Program box – This widget lets you display the output of the command in the dialog box."
},
{
"code": null,
"e": 7195,
"s": 7165,
"text": "The format for this widget is"
},
{
"code": null,
"e": 7244,
"s": 7195,
"text": "--prgbox <text> <command> <height> <width>"
},
{
"code": null,
"e": 7294,
"s": 7244,
"text": "The command which we wrote in the script file is"
},
{
"code": null,
"e": 7334,
"s": 7294,
"text": "dialog --prgbox \"command\" \"ls\" 10 30"
},
{
"code": null,
"e": 7353,
"s": 7334,
"text": "Program box widget"
},
{
"code": null,
"e": 7413,
"s": 7353,
"text": "After running the script, we get the window as shown below."
},
{
"code": null,
"e": 7490,
"s": 7413,
"text": "18. Textbox – This widget displays the contents of a file in a scroll window"
},
{
"code": null,
"e": 7520,
"s": 7490,
"text": "The format for this widget is"
},
{
"code": null,
"e": 7559,
"s": 7520,
"text": "--textbox <file> <height> <width>"
},
{
"code": null,
"e": 7609,
"s": 7559,
"text": "The command which we wrote in the script file is"
},
{
"code": null,
"e": 7642,
"s": 7609,
"text": "dialog –textbox /etc/hosts 10 60"
},
{
"code": null,
"e": 7657,
"s": 7642,
"text": "Textbox widget"
},
{
"code": null,
"e": 7717,
"s": 7657,
"text": "After running the script, we get the window as shown below."
},
{
"code": null,
"e": 7812,
"s": 7717,
"text": "19. Tailbox – This widget displays text from a file in a scroll window using the tail command."
},
{
"code": null,
"e": 7842,
"s": 7812,
"text": "The format for this widget is"
},
{
"code": null,
"e": 7881,
"s": 7842,
"text": "--tailbox <file> <height> <width>"
},
{
"code": null,
"e": 7931,
"s": 7881,
"text": "The command which we wrote in the script file is"
},
{
"code": null,
"e": 7965,
"s": 7931,
"text": "dialog --tailbox /etc/hosts 10 60"
},
{
"code": null,
"e": 7980,
"s": 7965,
"text": "tailbox widget"
},
{
"code": null,
"e": 8040,
"s": 7980,
"text": "After running the script, we get the window as shown below."
},
{
"code": null,
"e": 8116,
"s": 8040,
"text": "20. Yes no – This widget provides a simple message with Yes and No buttons."
},
{
"code": null,
"e": 8146,
"s": 8116,
"text": "The format for this widget is"
},
{
"code": null,
"e": 8185,
"s": 8146,
"text": "--yesno <text> <height> <width>"
},
{
"code": null,
"e": 8235,
"s": 8185,
"text": "The command which we wrote in the script file is"
},
{
"code": null,
"e": 8286,
"s": 8235,
"text": "dialog --yesno \"Do you want run the command\" 10 30"
},
{
"code": null,
"e": 8311,
"s": 8286,
"text": "yesno widgetimage widget"
},
{
"code": null,
"e": 8371,
"s": 8311,
"text": "After running the script, we get the window as shown below."
},
{
"code": null,
"e": 8385,
"s": 8371,
"text": "sumitgumber28"
},
{
"code": null,
"e": 8398,
"s": 8385,
"text": "nikhatkhan11"
},
{
"code": null,
"e": 8410,
"s": 8398,
"text": "Linux-Tools"
},
{
"code": null,
"e": 8421,
"s": 8410,
"text": "Linux-Unix"
}
] |
What’s the yield keyword in JavaScript? | 20 Sep, 2019
yield keyword is used to resume or pause a generator function asynchronously. A generator function is just like a normal function but the difference is that whenever the function is returning any value, it does it with the help of ‘yield’ keyword instead of return it. Yield can’t be called from nested functions or from callbacks.
The yield expression returns an object with two properties, “value” which is the actual value and “done” which is a boolean value, it returns true when generator function is full completed else it returns false.
If we pause the yield expression, the generator function will also get paused and resumes only when we call the next() method. When the next() method is encountered the function keeps on working until it faces another yield or returns expression.
Example 1:
function* showPrices(i) { while (i < 3) { yield i++; }} //creating an object for our function showPricesconst gfg = showPrices(0); //return 0 because 0 value is passed to the showPrices yield expressionconsole.log(gfg.next().value); // return 1console.log(gfg.next().value); //return 2console.log(gfg.next().value);
Output:
Example 2:
function* geeksforGeeks() { /*expression paused here and return value is undefined as nothing is declared*/ yield; //wait for next() to finish gfg(yield "Welcome to GFG"); } function gfg(x) { console.log("Hello World ", x)} var generator = geeksforGeeks(); //return undefinedconsole.log(generator.next()); //return Welcome to GFG console.log(generator.next()); /*done remains false as we have not called next so that "Hello World" is still left there to process*/
Output:
Picked
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
How to append HTML code to a div using JavaScript ?
Difference Between PUT and PATCH Request
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n20 Sep, 2019"
},
{
"code": null,
"e": 360,
"s": 28,
"text": "yield keyword is used to resume or pause a generator function asynchronously. A generator function is just like a normal function but the difference is that whenever the function is returning any value, it does it with the help of ‘yield’ keyword instead of return it. Yield can’t be called from nested functions or from callbacks."
},
{
"code": null,
"e": 572,
"s": 360,
"text": "The yield expression returns an object with two properties, “value” which is the actual value and “done” which is a boolean value, it returns true when generator function is full completed else it returns false."
},
{
"code": null,
"e": 819,
"s": 572,
"text": "If we pause the yield expression, the generator function will also get paused and resumes only when we call the next() method. When the next() method is encountered the function keeps on working until it faces another yield or returns expression."
},
{
"code": null,
"e": 830,
"s": 819,
"text": "Example 1:"
},
{
"code": "function* showPrices(i) { while (i < 3) { yield i++; }} //creating an object for our function showPricesconst gfg = showPrices(0); //return 0 because 0 value is passed to the showPrices yield expressionconsole.log(gfg.next().value); // return 1console.log(gfg.next().value); //return 2console.log(gfg.next().value); ",
"e": 1167,
"s": 830,
"text": null
},
{
"code": null,
"e": 1175,
"s": 1167,
"text": "Output:"
},
{
"code": null,
"e": 1186,
"s": 1175,
"text": "Example 2:"
},
{
"code": "function* geeksforGeeks() { /*expression paused here and return value is undefined as nothing is declared*/ yield; //wait for next() to finish gfg(yield \"Welcome to GFG\"); } function gfg(x) { console.log(\"Hello World \", x)} var generator = geeksforGeeks(); //return undefinedconsole.log(generator.next()); //return Welcome to GFG console.log(generator.next()); /*done remains false as we have not called next so that \"Hello World\" is still left there to process*/",
"e": 1678,
"s": 1186,
"text": null
},
{
"code": null,
"e": 1686,
"s": 1678,
"text": "Output:"
},
{
"code": null,
"e": 1693,
"s": 1686,
"text": "Picked"
},
{
"code": null,
"e": 1704,
"s": 1693,
"text": "JavaScript"
},
{
"code": null,
"e": 1721,
"s": 1704,
"text": "Web Technologies"
},
{
"code": null,
"e": 1748,
"s": 1721,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 1846,
"s": 1748,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1907,
"s": 1846,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1979,
"s": 1907,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 2019,
"s": 1979,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 2071,
"s": 2019,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 2112,
"s": 2071,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 2174,
"s": 2112,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2207,
"s": 2174,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2268,
"s": 2207,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2318,
"s": 2268,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
C# Program to Get the Full Path of the Current Directory Using Environment Class - GeeksforGeeks | 01 Nov, 2021
In C#, Environment Class provides information about the current platform and manipulates, the current platform. It is useful for getting and setting various operating system-related information. We can use it in such a way that it retrieves command-line arguments information, exit codes information, environment variable settings information, contents of the call stack information, and time since the last system boot in milliseconds information. In this article, we will discuss how to get the full path of the current directory. So to solve this problem we use the CurrentDirectory property of the Environment Class. This property returns the complete path of the current working directory of your computer. This property also throws the following exceptions:
ArgumentException: This exception is thrown when the CurrentDirectory property tries to set to an empty string.
ArgumentNullException: This exception is thrown when the CurrentDirectory property tries to set to null.
IOException: This exception is thrown when the input/output error occurred.
DirectoryNoFoundException: This exception is thrown when the CurrentDirectory property tries to set a local path/address that cannot be found.
SecurityException: This exception is thrown when the caller does not have suitable permission.
Syntax:
Environment.CurrentDirectory
Return Type: The return type of this property is a string. And the returned string represents the current directory path.
Example:
C#
// C# program to find the current directory path// Using Environment Classusing System; class GFG{ static public void Main(){ // Declaring a string string resultPath = ""; // Get the complete path of the current // working directory. Using // CurrentDirectory property of // Environment class resultPath = Environment.CurrentDirectory; Console.WriteLine("System Directory:\n" + resultPath);}}
Output:
System Directory:
/Users/Projects/newprogram/
CSharp-programs
Picked
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 50 C# Interview Questions & Answers
Extension Method in C#
HashSet in C# with Examples
Partial Classes in C#
C# | Inheritance
Convert String to Character Array in C#
Linked List Implementation in C#
C# | How to insert an element in an Array?
C# | List Class
Difference between Hashtable and Dictionary in C# | [
{
"code": null,
"e": 23911,
"s": 23883,
"text": "\n01 Nov, 2021"
},
{
"code": null,
"e": 24675,
"s": 23911,
"text": "In C#, Environment Class provides information about the current platform and manipulates, the current platform. It is useful for getting and setting various operating system-related information. We can use it in such a way that it retrieves command-line arguments information, exit codes information, environment variable settings information, contents of the call stack information, and time since the last system boot in milliseconds information. In this article, we will discuss how to get the full path of the current directory. So to solve this problem we use the CurrentDirectory property of the Environment Class. This property returns the complete path of the current working directory of your computer. This property also throws the following exceptions:"
},
{
"code": null,
"e": 24787,
"s": 24675,
"text": "ArgumentException: This exception is thrown when the CurrentDirectory property tries to set to an empty string."
},
{
"code": null,
"e": 24892,
"s": 24787,
"text": "ArgumentNullException: This exception is thrown when the CurrentDirectory property tries to set to null."
},
{
"code": null,
"e": 24968,
"s": 24892,
"text": "IOException: This exception is thrown when the input/output error occurred."
},
{
"code": null,
"e": 25111,
"s": 24968,
"text": "DirectoryNoFoundException: This exception is thrown when the CurrentDirectory property tries to set a local path/address that cannot be found."
},
{
"code": null,
"e": 25206,
"s": 25111,
"text": "SecurityException: This exception is thrown when the caller does not have suitable permission."
},
{
"code": null,
"e": 25214,
"s": 25206,
"text": "Syntax:"
},
{
"code": null,
"e": 25243,
"s": 25214,
"text": "Environment.CurrentDirectory"
},
{
"code": null,
"e": 25365,
"s": 25243,
"text": "Return Type: The return type of this property is a string. And the returned string represents the current directory path."
},
{
"code": null,
"e": 25374,
"s": 25365,
"text": "Example:"
},
{
"code": null,
"e": 25377,
"s": 25374,
"text": "C#"
},
{
"code": "// C# program to find the current directory path// Using Environment Classusing System; class GFG{ static public void Main(){ // Declaring a string string resultPath = \"\"; // Get the complete path of the current // working directory. Using // CurrentDirectory property of // Environment class resultPath = Environment.CurrentDirectory; Console.WriteLine(\"System Directory:\\n\" + resultPath);}}",
"e": 25820,
"s": 25377,
"text": null
},
{
"code": null,
"e": 25828,
"s": 25820,
"text": "Output:"
},
{
"code": null,
"e": 25874,
"s": 25828,
"text": "System Directory:\n/Users/Projects/newprogram/"
},
{
"code": null,
"e": 25890,
"s": 25874,
"text": "CSharp-programs"
},
{
"code": null,
"e": 25897,
"s": 25890,
"text": "Picked"
},
{
"code": null,
"e": 25900,
"s": 25897,
"text": "C#"
},
{
"code": null,
"e": 25998,
"s": 25900,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26007,
"s": 25998,
"text": "Comments"
},
{
"code": null,
"e": 26020,
"s": 26007,
"text": "Old Comments"
},
{
"code": null,
"e": 26060,
"s": 26020,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 26083,
"s": 26060,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 26111,
"s": 26083,
"text": "HashSet in C# with Examples"
},
{
"code": null,
"e": 26133,
"s": 26111,
"text": "Partial Classes in C#"
},
{
"code": null,
"e": 26150,
"s": 26133,
"text": "C# | Inheritance"
},
{
"code": null,
"e": 26190,
"s": 26150,
"text": "Convert String to Character Array in C#"
},
{
"code": null,
"e": 26223,
"s": 26190,
"text": "Linked List Implementation in C#"
},
{
"code": null,
"e": 26266,
"s": 26223,
"text": "C# | How to insert an element in an Array?"
},
{
"code": null,
"e": 26282,
"s": 26266,
"text": "C# | List Class"
}
] |
PDFBox - Inserting Image | In the previous chapter, we have seen how to extract text from an existing PDF document. In this chapter, we will discuss how to insert image to a PDF document.
You can insert an image into a PDF document using the createFromFile() and drawImage() methods of the classes PDImageXObject and PDPageContentStream respectively.
Following are the steps to extract text from an existing PDF document.
Load an existing PDF document using the static method load() of the PDDocument class. This method accepts a file object as a parameter, since this is a static method you can invoke it using class name as shown below.
File file = new File("path of the document")
PDDocument doc = PDDocument.load(file);
Select a page in the PDF document and retrieve its page object using the getPage() method as shown below.
PDPage page = doc.getPage(0);
The class PDImageXObject in PDFBox library represents an image. It provides all the required methods to perform operations related to an image, such as, inserting an image, setting its height, setting its width etc.
We can create an object of this class using the method createFromFile(). To this method, we need to pass the path of the image which we want to add in the form of a string and the document object to which the image needs to be added.
PDImageXObject pdImage = PDImageXObject.createFromFile("C:/logo.png", doc);
You can insert various kinds of data elements using the object of the class named PDPageContentStream. You need to pass the document object and the page object to the constructor of this class therefore, instantiate this class by passing these two objects created in the previous steps as shown below.
PDPageContentStream contentStream = new PDPageContentStream(doc, page);
You can insert an image in the PDF document using the drawImage() method. To this method, you need to add the image object created in the above step and the required dimensions of the image (width and height) as shown below.
contentstream.drawImage(pdImage, 70, 250);
Close the PDPageContentStream object using the close() method as shown below.
contentstream.close();
After adding the required content, save the PDF document using the save() method of the PDDocument class as shown in the following code block.
doc.save("Path");
Finally, close the document using the close() method of the PDDocument class as shown below.
doc.close();
Suppose we have a PDF document named sample.pdf, in the path C:/PdfBox_Examples/ with empty pages as shown below.
This example demonstrates how to add image to a blank page of the above mentioned PDF document. Here, we will load the PDF document named sample.pdf and add image to it. Save this code in a file with name InsertingImage.java.
import java.io.File;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
public class InsertingImage {
public static void main(String args[]) throws Exception {
//Loading an existing document
File file = new File("C:/PdfBox_Examples/sample.pdf");
PDDocument doc = PDDocument.load(file);
//Retrieving the page
PDPage page = doc.getPage(0);
//Creating PDImageXObject object
PDImageXObject pdImage = PDImageXObject.createFromFile("C:/PdfBox_Examples/logo.png",doc);
//creating the PDPageContentStream object
PDPageContentStream contents = new PDPageContentStream(doc, page);
//Drawing the image in the PDF document
contents.drawImage(pdImage, 70, 250);
System.out.println("Image inserted");
//Closing the PDPageContentStream object
contents.close();
//Saving the document
doc.save("C:/PdfBox_Examples/sample.pdf");
//Closing the document
doc.close();
}
}
Compile and execute the saved Java file from the command prompt using the following commands.
javac InsertingImage.java
java InsertingImage
Upon execution, the above program inserts an image into the specified page of the given PDF document displaying the following message.
Image inserted
If you verify the document sample.pdf, you can observe that an image is inserted in it as shown below.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2188,
"s": 2027,
"text": "In the previous chapter, we have seen how to extract text from an existing PDF document. In this chapter, we will discuss how to insert image to a PDF document."
},
{
"code": null,
"e": 2351,
"s": 2188,
"text": "You can insert an image into a PDF document using the createFromFile() and drawImage() methods of the classes PDImageXObject and PDPageContentStream respectively."
},
{
"code": null,
"e": 2422,
"s": 2351,
"text": "Following are the steps to extract text from an existing PDF document."
},
{
"code": null,
"e": 2639,
"s": 2422,
"text": "Load an existing PDF document using the static method load() of the PDDocument class. This method accepts a file object as a parameter, since this is a static method you can invoke it using class name as shown below."
},
{
"code": null,
"e": 2725,
"s": 2639,
"text": "File file = new File(\"path of the document\")\nPDDocument doc = PDDocument.load(file);\n"
},
{
"code": null,
"e": 2831,
"s": 2725,
"text": "Select a page in the PDF document and retrieve its page object using the getPage() method as shown below."
},
{
"code": null,
"e": 2862,
"s": 2831,
"text": "PDPage page = doc.getPage(0);\n"
},
{
"code": null,
"e": 3078,
"s": 2862,
"text": "The class PDImageXObject in PDFBox library represents an image. It provides all the required methods to perform operations related to an image, such as, inserting an image, setting its height, setting its width etc."
},
{
"code": null,
"e": 3312,
"s": 3078,
"text": "We can create an object of this class using the method createFromFile(). To this method, we need to pass the path of the image which we want to add in the form of a string and the document object to which the image needs to be added."
},
{
"code": null,
"e": 3389,
"s": 3312,
"text": "PDImageXObject pdImage = PDImageXObject.createFromFile(\"C:/logo.png\", doc);\n"
},
{
"code": null,
"e": 3691,
"s": 3389,
"text": "You can insert various kinds of data elements using the object of the class named PDPageContentStream. You need to pass the document object and the page object to the constructor of this class therefore, instantiate this class by passing these two objects created in the previous steps as shown below."
},
{
"code": null,
"e": 3764,
"s": 3691,
"text": "PDPageContentStream contentStream = new PDPageContentStream(doc, page);\n"
},
{
"code": null,
"e": 3989,
"s": 3764,
"text": "You can insert an image in the PDF document using the drawImage() method. To this method, you need to add the image object created in the above step and the required dimensions of the image (width and height) as shown below."
},
{
"code": null,
"e": 4033,
"s": 3989,
"text": "contentstream.drawImage(pdImage, 70, 250);\n"
},
{
"code": null,
"e": 4111,
"s": 4033,
"text": "Close the PDPageContentStream object using the close() method as shown below."
},
{
"code": null,
"e": 4135,
"s": 4111,
"text": "contentstream.close();\n"
},
{
"code": null,
"e": 4278,
"s": 4135,
"text": "After adding the required content, save the PDF document using the save() method of the PDDocument class as shown in the following code block."
},
{
"code": null,
"e": 4297,
"s": 4278,
"text": "doc.save(\"Path\");\n"
},
{
"code": null,
"e": 4390,
"s": 4297,
"text": "Finally, close the document using the close() method of the PDDocument class as shown below."
},
{
"code": null,
"e": 4404,
"s": 4390,
"text": "doc.close();\n"
},
{
"code": null,
"e": 4518,
"s": 4404,
"text": "Suppose we have a PDF document named sample.pdf, in the path C:/PdfBox_Examples/ with empty pages as shown below."
},
{
"code": null,
"e": 4744,
"s": 4518,
"text": "This example demonstrates how to add image to a blank page of the above mentioned PDF document. Here, we will load the PDF document named sample.pdf and add image to it. Save this code in a file with name InsertingImage.java."
},
{
"code": null,
"e": 5926,
"s": 4744,
"text": "import java.io.File;\n \nimport org.apache.pdfbox.pdmodel.PDDocument; \nimport org.apache.pdfbox.pdmodel.PDPage;\nimport org.apache.pdfbox.pdmodel.PDPageContentStream;\nimport org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;\n\npublic class InsertingImage {\n\n public static void main(String args[]) throws Exception {\n //Loading an existing document\n File file = new File(\"C:/PdfBox_Examples/sample.pdf\");\n PDDocument doc = PDDocument.load(file);\n \n //Retrieving the page\n PDPage page = doc.getPage(0);\n \n //Creating PDImageXObject object\n PDImageXObject pdImage = PDImageXObject.createFromFile(\"C:/PdfBox_Examples/logo.png\",doc);\n \n //creating the PDPageContentStream object\n PDPageContentStream contents = new PDPageContentStream(doc, page);\n\n //Drawing the image in the PDF document\n contents.drawImage(pdImage, 70, 250);\n\n System.out.println(\"Image inserted\");\n \n //Closing the PDPageContentStream object\n contents.close();\t\t\n\t\t\n //Saving the document\n doc.save(\"C:/PdfBox_Examples/sample.pdf\");\n \n //Closing the document\n doc.close();\n \n }\n}"
},
{
"code": null,
"e": 6020,
"s": 5926,
"text": "Compile and execute the saved Java file from the command prompt using the following commands."
},
{
"code": null,
"e": 6068,
"s": 6020,
"text": "javac InsertingImage.java \njava InsertingImage\n"
},
{
"code": null,
"e": 6203,
"s": 6068,
"text": "Upon execution, the above program inserts an image into the specified page of the given PDF document displaying the following message."
},
{
"code": null,
"e": 6219,
"s": 6203,
"text": "Image inserted\n"
},
{
"code": null,
"e": 6322,
"s": 6219,
"text": "If you verify the document sample.pdf, you can observe that an image is inserted in it as shown below."
},
{
"code": null,
"e": 6329,
"s": 6322,
"text": " Print"
},
{
"code": null,
"e": 6340,
"s": 6329,
"text": " Add Notes"
}
] |
How to align checkboxes and their labels on cross-browsers using CSS ? - GeeksforGeeks | 21 Dec, 2020
For aligning the checkboxes or radio buttons with their labels can be achieved in many ways. Some of the simplest methods to achieve this are described below with proper code and output in different browsers. Now styling can be done in various ways to align the checkboxes and their labels. For this article, we are using internal stylesheet which is done under the style tag.
Method 1: By making the position of checkbox relative, set the vertical-align to the middle can align the checkboxes and their labels. Here, we have made the position of the checkbox relative to the label. So the checkboxes are aligned according to the label.
Example:
<!DOCTYPE html><html> <head> <title> Aligning Checkboxes consistently in cross browsers </title> <style> h1 { color: green; } input[type=checkbox] { vertical-align: middle; position: relative; bottom: 1px; } label { display: block; } </style></head> <body> <h1>Geeksforgeeks</h1> <form> <label> <input type="checkbox"> A Computer Science Portal for Geeks </label> <label> <input type="checkbox"> Just an Edutech Company to educate </label> </form> </body> </html>
Output:
Mozilla Firefox:
Google Chrome:
Internet Explorer:
Method 2: By using the flex display, as the display is set to flex and alignment is center so both the checkbox and label are aligned to the center of the cross-axis.
Example:
<!DOCTYPE html><html> <head> <title> Aligning Checkboxes consistently in cross browsers </title> <style> h1 { color: green; } label { display: flex; align-items: center; } input[type=checkbox]{ flex: none; } </style></head> <body> <h1>Geeksforgeeks</h1> <form> <label> <input type="checkbox"> A Computer Science Portal for Geeks </label> <label> <input type="checkbox"> Just an Edutech Company to educate </label> </form> </body> </html>
Output:
Mozilla Firefox:
Google Chrome:
Internet Explorer:
Method 3: By grouping the label and checkbox into the same block, we can align the checkbox and label consistently in cross-browsers.Example:
<!DOCTYPE html><html> <head> <title> Aligning Checkboxes consistently in cross browsers </title></head> <body> <h1 style="color: green;">Geeksforgeeks</h1> <form> <div> <label style="display: inline-block"> <input style="vertical-align: middle" type="checkbox" /> <span style="vertical-align: middle"> A Computer Science Portal for Geeks </span> </label> </div> <div> <label style="display: inline-block"> <input style="vertical-align: middle" type="checkbox" /> <span style="vertical-align: middle"> Just an Edutech Company to educate </span> </label> </div> </form></body> </html>
Output:
Mozilla Firefox:
Google Chrome:
Internet Explorer:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
arorakashish0911
CSS-Misc
HTML-Misc
Picked
CSS
HTML
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to create footer to stay at the bottom of a Web page?
Types of CSS (Cascading Style Sheet)
How to position a div at the bottom of its container using CSS?
Create a Responsive Navbar using ReactJS
Design a web page using HTML and CSS
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
Hide or show elements in HTML using display property
How to Insert Form Data into Database using PHP ?
REST API (Introduction) | [
{
"code": null,
"e": 25284,
"s": 25256,
"text": "\n21 Dec, 2020"
},
{
"code": null,
"e": 25661,
"s": 25284,
"text": "For aligning the checkboxes or radio buttons with their labels can be achieved in many ways. Some of the simplest methods to achieve this are described below with proper code and output in different browsers. Now styling can be done in various ways to align the checkboxes and their labels. For this article, we are using internal stylesheet which is done under the style tag."
},
{
"code": null,
"e": 25921,
"s": 25661,
"text": "Method 1: By making the position of checkbox relative, set the vertical-align to the middle can align the checkboxes and their labels. Here, we have made the position of the checkbox relative to the label. So the checkboxes are aligned according to the label."
},
{
"code": null,
"e": 25930,
"s": 25921,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> Aligning Checkboxes consistently in cross browsers </title> <style> h1 { color: green; } input[type=checkbox] { vertical-align: middle; position: relative; bottom: 1px; } label { display: block; } </style></head> <body> <h1>Geeksforgeeks</h1> <form> <label> <input type=\"checkbox\"> A Computer Science Portal for Geeks </label> <label> <input type=\"checkbox\"> Just an Edutech Company to educate </label> </form> </body> </html>",
"e": 26622,
"s": 25930,
"text": null
},
{
"code": null,
"e": 26630,
"s": 26622,
"text": "Output:"
},
{
"code": null,
"e": 26647,
"s": 26630,
"text": "Mozilla Firefox:"
},
{
"code": null,
"e": 26662,
"s": 26647,
"text": "Google Chrome:"
},
{
"code": null,
"e": 26681,
"s": 26662,
"text": "Internet Explorer:"
},
{
"code": null,
"e": 26848,
"s": 26681,
"text": "Method 2: By using the flex display, as the display is set to flex and alignment is center so both the checkbox and label are aligned to the center of the cross-axis."
},
{
"code": null,
"e": 26857,
"s": 26848,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> Aligning Checkboxes consistently in cross browsers </title> <style> h1 { color: green; } label { display: flex; align-items: center; } input[type=checkbox]{ flex: none; } </style></head> <body> <h1>Geeksforgeeks</h1> <form> <label> <input type=\"checkbox\"> A Computer Science Portal for Geeks </label> <label> <input type=\"checkbox\"> Just an Edutech Company to educate </label> </form> </body> </html>",
"e": 27502,
"s": 26857,
"text": null
},
{
"code": null,
"e": 27510,
"s": 27502,
"text": "Output:"
},
{
"code": null,
"e": 27527,
"s": 27510,
"text": "Mozilla Firefox:"
},
{
"code": null,
"e": 27542,
"s": 27527,
"text": "Google Chrome:"
},
{
"code": null,
"e": 27561,
"s": 27542,
"text": "Internet Explorer:"
},
{
"code": null,
"e": 27703,
"s": 27561,
"text": "Method 3: By grouping the label and checkbox into the same block, we can align the checkbox and label consistently in cross-browsers.Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> Aligning Checkboxes consistently in cross browsers </title></head> <body> <h1 style=\"color: green;\">Geeksforgeeks</h1> <form> <div> <label style=\"display: inline-block\"> <input style=\"vertical-align: middle\" type=\"checkbox\" /> <span style=\"vertical-align: middle\"> A Computer Science Portal for Geeks </span> </label> </div> <div> <label style=\"display: inline-block\"> <input style=\"vertical-align: middle\" type=\"checkbox\" /> <span style=\"vertical-align: middle\"> Just an Edutech Company to educate </span> </label> </div> </form></body> </html>",
"e": 28500,
"s": 27703,
"text": null
},
{
"code": null,
"e": 28508,
"s": 28500,
"text": "Output:"
},
{
"code": null,
"e": 28525,
"s": 28508,
"text": "Mozilla Firefox:"
},
{
"code": null,
"e": 28540,
"s": 28525,
"text": "Google Chrome:"
},
{
"code": null,
"e": 28559,
"s": 28540,
"text": "Internet Explorer:"
},
{
"code": null,
"e": 28696,
"s": 28559,
"text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course."
},
{
"code": null,
"e": 28713,
"s": 28696,
"text": "arorakashish0911"
},
{
"code": null,
"e": 28722,
"s": 28713,
"text": "CSS-Misc"
},
{
"code": null,
"e": 28732,
"s": 28722,
"text": "HTML-Misc"
},
{
"code": null,
"e": 28739,
"s": 28732,
"text": "Picked"
},
{
"code": null,
"e": 28743,
"s": 28739,
"text": "CSS"
},
{
"code": null,
"e": 28748,
"s": 28743,
"text": "HTML"
},
{
"code": null,
"e": 28765,
"s": 28748,
"text": "Web Technologies"
},
{
"code": null,
"e": 28792,
"s": 28765,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 28797,
"s": 28792,
"text": "HTML"
},
{
"code": null,
"e": 28895,
"s": 28797,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28904,
"s": 28895,
"text": "Comments"
},
{
"code": null,
"e": 28917,
"s": 28904,
"text": "Old Comments"
},
{
"code": null,
"e": 28975,
"s": 28917,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 29012,
"s": 28975,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 29076,
"s": 29012,
"text": "How to position a div at the bottom of its container using CSS?"
},
{
"code": null,
"e": 29117,
"s": 29076,
"text": "Create a Responsive Navbar using ReactJS"
},
{
"code": null,
"e": 29154,
"s": 29117,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 29214,
"s": 29154,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 29275,
"s": 29214,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 29328,
"s": 29275,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 29378,
"s": 29328,
"text": "How to Insert Form Data into Database using PHP ?"
}
] |
Ruby | Enumerable sum() function - GeeksforGeeks | 05 Dec, 2019
The sum() of enumerable is an inbuilt method in Ruby returns the sum of all the elements in the enumerable. If a block is given, the block is applied to the enumerable, then the sum is computed. If the enumerable is empty, it returns init.
Syntax: enu.sum { |obj| block }
Parameters: The function accepts a block.
Return Value: It returns the sum of the enumerable.
Example #1:
# Initialize enu = (1..5) # Prints enu.sum
Output:
15
Example #2:
# Ruby program for sum method in Enumerable # Initialize enu = [10, 13, 12, 11] # Prints enu.sum {|obj| obj * 5}
Output:
230
Ruby Enumerable-class
Ruby-Methods
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Ruby | Array select() function
Ruby | Enumerator each_with_index function
Global Variable in Ruby
Ruby | Hash delete() function
Include v/s Extend in Ruby
Ruby | String gsub! Method
Ruby | Case Statement
Ruby | Decision Making (if, if-else, if-else-if, ternary) | Set - 1
Ruby | Enumerable find() function
Ruby | Data Types | [
{
"code": null,
"e": 23600,
"s": 23572,
"text": "\n05 Dec, 2019"
},
{
"code": null,
"e": 23840,
"s": 23600,
"text": "The sum() of enumerable is an inbuilt method in Ruby returns the sum of all the elements in the enumerable. If a block is given, the block is applied to the enumerable, then the sum is computed. If the enumerable is empty, it returns init."
},
{
"code": null,
"e": 23872,
"s": 23840,
"text": "Syntax: enu.sum { |obj| block }"
},
{
"code": null,
"e": 23914,
"s": 23872,
"text": "Parameters: The function accepts a block."
},
{
"code": null,
"e": 23966,
"s": 23914,
"text": "Return Value: It returns the sum of the enumerable."
},
{
"code": null,
"e": 23978,
"s": 23966,
"text": "Example #1:"
},
{
"code": "# Initialize enu = (1..5) # Prints enu.sum",
"e": 24022,
"s": 23978,
"text": null
},
{
"code": null,
"e": 24030,
"s": 24022,
"text": "Output:"
},
{
"code": null,
"e": 24034,
"s": 24030,
"text": "15\n"
},
{
"code": null,
"e": 24046,
"s": 24034,
"text": "Example #2:"
},
{
"code": "# Ruby program for sum method in Enumerable # Initialize enu = [10, 13, 12, 11] # Prints enu.sum {|obj| obj * 5}",
"e": 24161,
"s": 24046,
"text": null
},
{
"code": null,
"e": 24169,
"s": 24161,
"text": "Output:"
},
{
"code": null,
"e": 24174,
"s": 24169,
"text": "230\n"
},
{
"code": null,
"e": 24196,
"s": 24174,
"text": "Ruby Enumerable-class"
},
{
"code": null,
"e": 24209,
"s": 24196,
"text": "Ruby-Methods"
},
{
"code": null,
"e": 24214,
"s": 24209,
"text": "Ruby"
},
{
"code": null,
"e": 24312,
"s": 24214,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 24321,
"s": 24312,
"text": "Comments"
},
{
"code": null,
"e": 24334,
"s": 24321,
"text": "Old Comments"
},
{
"code": null,
"e": 24365,
"s": 24334,
"text": "Ruby | Array select() function"
},
{
"code": null,
"e": 24408,
"s": 24365,
"text": "Ruby | Enumerator each_with_index function"
},
{
"code": null,
"e": 24432,
"s": 24408,
"text": "Global Variable in Ruby"
},
{
"code": null,
"e": 24462,
"s": 24432,
"text": "Ruby | Hash delete() function"
},
{
"code": null,
"e": 24489,
"s": 24462,
"text": "Include v/s Extend in Ruby"
},
{
"code": null,
"e": 24516,
"s": 24489,
"text": "Ruby | String gsub! Method"
},
{
"code": null,
"e": 24538,
"s": 24516,
"text": "Ruby | Case Statement"
},
{
"code": null,
"e": 24606,
"s": 24538,
"text": "Ruby | Decision Making (if, if-else, if-else-if, ternary) | Set - 1"
},
{
"code": null,
"e": 24640,
"s": 24606,
"text": "Ruby | Enumerable find() function"
}
] |
Java.lang.Integer class and its methods - GeeksforGeeks | 21 Jun, 2021
java.lang.Integer wraps integer data type to an object containing a single field having datatype is int. Constructors :
Integer (int arg) : Constructs integer object representing an int value.
Integer (String arg) : Constructs string object representing a string value.
Integer class methods:
toBinaryString() : java.lang.Integer.toBinaryString() method converts the integer value of argument its Binary representation as a string. Syntax
toBinaryString() : java.lang.Integer.toBinaryString() method converts the integer value of argument its Binary representation as a string. Syntax
public static String toBinaryString(int arg)
Parameters
arg : integer argument whose Binary representation we want
Return
Binary representation of the argument.
bitcount() : java.lang.Integer.bitCount() method converts the integer value of argument to Binary string and then returns the no. of 1’s present in it. Syntax
bitcount() : java.lang.Integer.bitCount() method converts the integer value of argument to Binary string and then returns the no. of 1’s present in it. Syntax
public static int bitCount(int arg)
Parameters
arg : integer argument whose no. of 1's bit we want
Return
no. of 1's bit present in the argument.
toHexString() : java.lang.Integer.toHexString() method converts the integer value of argument its Hexadecimal representation as a string. Syntax
toHexString() : java.lang.Integer.toHexString() method converts the integer value of argument its Hexadecimal representation as a string. Syntax
public static String toHexString(int arg)
Parameters
arg : integer argument whose Hexadecimal representation we want
Return
Hexadecimal representation of the argument.
toOctalString() : java.lang.Integer.toHexString() method converts the integer value of argument its Hexadecimal representation as a string. Syntax
toOctalString() : java.lang.Integer.toHexString() method converts the integer value of argument its Hexadecimal representation as a string. Syntax
public static String toHexString(int arg)
Parameters
arg : integer argument whose Hexadecimal representation we want
Return
Hexadecimal representation of the argument.
parsedatatype() : java.lang.Integer.parse__() method returns primitive data type of the argumented String value. Radix (r) means numbering format used is at base ‘r’ to the string. Syntax
parsedatatype() : java.lang.Integer.parse__() method returns primitive data type of the argumented String value. Radix (r) means numbering format used is at base ‘r’ to the string. Syntax
public static int parseInt(String arg)
or
public static int parseInt(String arg, int r)
Parameters
arg : argument passed
r : radix
Return
primitive data type of the argumented String value.
JAVA
// Java code explaining the Integer Class methods// bitcount(), toBinaryString(), toHexString(), toOctalString(), parse__()import java.lang.*;public class NewClass{ public static void main(String args[]) { int x = 15, count1, y = 128, count2; // Use of toBinaryString() method System.out.println("Binary string of 16 : " + Integer.toBinaryString(x)); System.out.println("Binary string of 100 : " + Integer.toBinaryString(y)); // Use of bitCount() method count1 = Integer.bitCount(x); System.out.println("\n 1's bit present in 16 : "+count1); count2 = Integer.bitCount(y); System.out.println(" 1's bit present in 100 : "+count2); // Use of toHexString() method System.out.println("\nHexadecimal string of 16 : " + Integer.toHexString(x)); System.out.println("Hexadecimal string of 100 : " + Integer.toHexString(y)); System.out.println(""); // Use of toOctalString() method System.out.println("Octal string of 16 : " + Integer.toOctalString(x)); System.out.println("Octal string of 100 : " + Integer.toOctalString(y) + "\n"); // Use of parseInt() method int i1 =Integer.parseInt("34"); int i2 = Integer.parseInt("15",8); double d = Double.parseDouble("54"); System.out.println(i1); System.out.println(i2); System.out.println(d); }}
Output:
Output:
Binary string of 16 : 1111
Binary string of 100 : 10000000
1's bit present in 16 : 4
1's bit present in 100 : 1
Hexadecimal string of 16 : f
Hexadecimal string of 100 : 80
Octal string of 16 : 17
Octal string of 100 : 200
34
13
54.0
hashCode() : java.lang.Integer.hashCode() method returns the hashCode value of the argument passed. Syntax:
hashCode() : java.lang.Integer.hashCode() method returns the hashCode value of the argument passed. Syntax:
public int hashCode(arg)
Parameters:
arg - the argument whose hashCode value we need
Returns:
hashCode value of arg
lowestOneBit() : java.lang.Integer.lowestOneBit() method first convert int to Binary, then it looks for set(1) bit present at lowest position then it reset rest of the bits e.g arg = 36 It,s Binary Representation = 0010 0100 It considers lowest bit(at 3) and now reset rest of the bits i.e. 0000 0100 so result = 0100 i.e. 4 Syntax:
lowestOneBit() : java.lang.Integer.lowestOneBit() method first convert int to Binary, then it looks for set(1) bit present at lowest position then it reset rest of the bits e.g arg = 36 It,s Binary Representation = 0010 0100 It considers lowest bit(at 3) and now reset rest of the bits i.e. 0000 0100 so result = 0100 i.e. 4 Syntax:
public static int lowestOneBit(int arg)
Parameters:
arg - argument passed
Returns:
integer value by only considering lowest 1 bit in the argument.
highestOneBit() : java.lang.Integer.highestOneBit() method first convert int to Binary, then it looks for set(1) bit present at lowest position then it reset rest of the bits e.g arg = 36 It,s Binary Representation = 0010 0100 It considers highest bit(at 6) and now reset rest of the bits i.e. 0001 0000 so result = 10000 i.e. 32 Syntax:
highestOneBit() : java.lang.Integer.highestOneBit() method first convert int to Binary, then it looks for set(1) bit present at lowest position then it reset rest of the bits e.g arg = 36 It,s Binary Representation = 0010 0100 It considers highest bit(at 6) and now reset rest of the bits i.e. 0001 0000 so result = 10000 i.e. 32 Syntax:
public static int highestOneBit(int arg)
Parameters:
arg - argument passed
Returns:
integer value by only considering highest 1 bit in the argument.
JAVA
// Java program explaining Integer class methods// hashcode(), lowestOneBit(), highestOneBit()import java.lang.*;public class NewClass{ public static void main(String[] args) { // Use of incrementExact() method int f1 = 30, f2 = -56; f1 = Integer.hashCode(f1); System.out.println("HashCode value of f1 : "+f1); f2 = Integer.hashCode(f2); System.out.println("HashCode value of f2 : "+f2); System.out.println("\nBinary representation of 30 : " + Integer.toBinaryString(f1)); // Use of lowestOneBit() method // Here it considers 00010 i.e. 2 System.out.println("lowestOneBit of 30 : " + Integer.lowestOneBit(f1)); // Use of highestOneBit() method // Here it considers 10000 i.e. 16 System.out.println("highestOneBit of 30 : " + Integer.highestOneBit(f1)); }}
Output:
Output:
HashCode value of f1 : 30
HashCode value of f2 : -56
Binary representation of 30 : 11110
lowestOneBit of 30 : 2
highestOneBit of 30 : 16
numberOfTrailingZeros() : java.lang.Integer.numberOfTrailingZeros() method converts int value to Binary then considers the lowest one bit and return no. of zero bits following it. e.g arg = 36 It,s Binary Representation = 0010 0100 It considers highest bit(at 6) i.e. 0001 0000 so result = 4 Syntax:
numberOfTrailingZeros() : java.lang.Integer.numberOfTrailingZeros() method converts int value to Binary then considers the lowest one bit and return no. of zero bits following it. e.g arg = 36 It,s Binary Representation = 0010 0100 It considers highest bit(at 6) i.e. 0001 0000 so result = 4 Syntax:
public static int numberOfTrailingZeros(int arg)
Parameters:
arg - the argument
Returns:
Number of zero bits following the 1 bit at lowest position
numberOfLeadingZeros() : java.lang.Integer.numberOfLeadingZeros() method converts int value to Binary then considers the highest one bit and return no. of zero bits preceding it. e.g arg = 36 It,s Binary Representation = 0010 0100 It considers highest bit(at 6) i.e. 0010 0000 so result = 32 – 6 i.e. 26 Syntax:
numberOfLeadingZeros() : java.lang.Integer.numberOfLeadingZeros() method converts int value to Binary then considers the highest one bit and return no. of zero bits preceding it. e.g arg = 36 It,s Binary Representation = 0010 0100 It considers highest bit(at 6) i.e. 0010 0000 so result = 32 – 6 i.e. 26 Syntax:
public static int numberOfLeadingZeros(int arg)
Parameters:
arg - the argument
Returns:
Number of zero bits preceding the 1 bit at highest position
reverse() : java.lang.Integer.reverse() method first find 2’s compliment of the argument passed and reverses the order of bits in the 2’s compliment. Syntax:
reverse() : java.lang.Integer.reverse() method first find 2’s compliment of the argument passed and reverses the order of bits in the 2’s compliment. Syntax:
public static int reverse(int arg)
Parameters:
arg - the argument
Returns:
int with reverse order of bits in 2's compliment of the passed argument
JAVA
// Java program explaining Integer class methods// numberOfTrailingZeros(), numberOfLeadingZeros(), reverse()import java.lang.*;public class NewClass{ public static void main(String[] args) { int f1 = 30; // Binary representation of int arg for your understanding System.out.println("Binary representation of 30 : " + Integer.toBinaryString(f1)); // Use of numberOfTrailingZeros() method // No. of zeros following 1 in 00010 = 1 System.out.println("\nNo. Of Trailing Zeros : " + Integer.numberOfTrailingZeros(f1)); // Use of highestOneBit() method // No. of zeros following 1 in 10000 i.e. 32 - 5 = 27 System.out.println("\nNo. Of Leading Zeros : " + Integer.numberOfLeadingZeros(f1)); // Use of Reverse() method System.out.println("\nReverse : " + Integer.reverse(f1)); }}
Output:
Output:
Binary representation of 30 : 11110
No. Of Trailing Zeros : 1
No. Of Leading Zeros : 27
Reverse : 2013265920
This article is contributed by Mohit Gupta. 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.
abhishek0719kadiyan
Java-lang package
Java-Library
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Functional Interfaces in Java
Stream In Java
Constructors in Java
Different ways of Reading a text file in Java
Exceptions in Java
Generics in Java
Comparator Interface in Java with Examples
Strings in Java
Difference between Abstract Class and Interface in Java
How to remove an element from ArrayList in Java? | [
{
"code": null,
"e": 23583,
"s": 23555,
"text": "\n21 Jun, 2021"
},
{
"code": null,
"e": 23705,
"s": 23583,
"text": "java.lang.Integer wraps integer data type to an object containing a single field having datatype is int. Constructors : "
},
{
"code": null,
"e": 23778,
"s": 23705,
"text": "Integer (int arg) : Constructs integer object representing an int value."
},
{
"code": null,
"e": 23855,
"s": 23778,
"text": "Integer (String arg) : Constructs string object representing a string value."
},
{
"code": null,
"e": 23880,
"s": 23855,
"text": "Integer class methods: "
},
{
"code": null,
"e": 24028,
"s": 23880,
"text": "toBinaryString() : java.lang.Integer.toBinaryString() method converts the integer value of argument its Binary representation as a string. Syntax "
},
{
"code": null,
"e": 24176,
"s": 24028,
"text": "toBinaryString() : java.lang.Integer.toBinaryString() method converts the integer value of argument its Binary representation as a string. Syntax "
},
{
"code": null,
"e": 24337,
"s": 24176,
"text": "public static String toBinaryString(int arg)\nParameters\narg : integer argument whose Binary representation we want\nReturn\nBinary representation of the argument."
},
{
"code": null,
"e": 24499,
"s": 24337,
"text": " bitcount() : java.lang.Integer.bitCount() method converts the integer value of argument to Binary string and then returns the no. of 1’s present in it. Syntax "
},
{
"code": null,
"e": 24662,
"s": 24501,
"text": "bitcount() : java.lang.Integer.bitCount() method converts the integer value of argument to Binary string and then returns the no. of 1’s present in it. Syntax "
},
{
"code": null,
"e": 24808,
"s": 24662,
"text": "public static int bitCount(int arg)\nParameters\narg : integer argument whose no. of 1's bit we want\nReturn\nno. of 1's bit present in the argument."
},
{
"code": null,
"e": 24956,
"s": 24808,
"text": " toHexString() : java.lang.Integer.toHexString() method converts the integer value of argument its Hexadecimal representation as a string. Syntax "
},
{
"code": null,
"e": 25105,
"s": 24958,
"text": "toHexString() : java.lang.Integer.toHexString() method converts the integer value of argument its Hexadecimal representation as a string. Syntax "
},
{
"code": null,
"e": 25273,
"s": 25105,
"text": "public static String toHexString(int arg)\nParameters\narg : integer argument whose Hexadecimal representation we want\nReturn\nHexadecimal representation of the argument."
},
{
"code": null,
"e": 25423,
"s": 25273,
"text": " toOctalString() : java.lang.Integer.toHexString() method converts the integer value of argument its Hexadecimal representation as a string. Syntax "
},
{
"code": null,
"e": 25574,
"s": 25425,
"text": "toOctalString() : java.lang.Integer.toHexString() method converts the integer value of argument its Hexadecimal representation as a string. Syntax "
},
{
"code": null,
"e": 25742,
"s": 25574,
"text": "public static String toHexString(int arg)\nParameters\narg : integer argument whose Hexadecimal representation we want\nReturn\nHexadecimal representation of the argument."
},
{
"code": null,
"e": 25933,
"s": 25742,
"text": " parsedatatype() : java.lang.Integer.parse__() method returns primitive data type of the argumented String value. Radix (r) means numbering format used is at base ‘r’ to the string. Syntax "
},
{
"code": null,
"e": 26125,
"s": 25935,
"text": "parsedatatype() : java.lang.Integer.parse__() method returns primitive data type of the argumented String value. Radix (r) means numbering format used is at base ‘r’ to the string. Syntax "
},
{
"code": null,
"e": 26329,
"s": 26125,
"text": "public static int parseInt(String arg)\n or\npublic static int parseInt(String arg, int r)\nParameters\narg : argument passed\nr : radix\nReturn\nprimitive data type of the argumented String value."
},
{
"code": null,
"e": 26338,
"s": 26333,
"text": "JAVA"
},
{
"code": "// Java code explaining the Integer Class methods// bitcount(), toBinaryString(), toHexString(), toOctalString(), parse__()import java.lang.*;public class NewClass{ public static void main(String args[]) { int x = 15, count1, y = 128, count2; // Use of toBinaryString() method System.out.println(\"Binary string of 16 : \" + Integer.toBinaryString(x)); System.out.println(\"Binary string of 100 : \" + Integer.toBinaryString(y)); // Use of bitCount() method count1 = Integer.bitCount(x); System.out.println(\"\\n 1's bit present in 16 : \"+count1); count2 = Integer.bitCount(y); System.out.println(\" 1's bit present in 100 : \"+count2); // Use of toHexString() method System.out.println(\"\\nHexadecimal string of 16 : \" + Integer.toHexString(x)); System.out.println(\"Hexadecimal string of 100 : \" + Integer.toHexString(y)); System.out.println(\"\"); // Use of toOctalString() method System.out.println(\"Octal string of 16 : \" + Integer.toOctalString(x)); System.out.println(\"Octal string of 100 : \" + Integer.toOctalString(y) + \"\\n\"); // Use of parseInt() method int i1 =Integer.parseInt(\"34\"); int i2 = Integer.parseInt(\"15\",8); double d = Double.parseDouble(\"54\"); System.out.println(i1); System.out.println(i2); System.out.println(d); }}",
"e": 27901,
"s": 26338,
"text": null
},
{
"code": null,
"e": 27911,
"s": 27901,
"text": "Output: "
},
{
"code": null,
"e": 27921,
"s": 27911,
"text": "Output: "
},
{
"code": null,
"e": 28172,
"s": 27921,
"text": "Binary string of 16 : 1111\nBinary string of 100 : 10000000\n\n 1's bit present in 16 : 4\n 1's bit present in 100 : 1\n\nHexadecimal string of 16 : f\nHexadecimal string of 100 : 80\n\nOctal string of 16 : 17\nOctal string of 100 : 200\n\n34\n13\n54.0"
},
{
"code": null,
"e": 28283,
"s": 28172,
"text": " hashCode() : java.lang.Integer.hashCode() method returns the hashCode value of the argument passed. Syntax: "
},
{
"code": null,
"e": 28395,
"s": 28285,
"text": "hashCode() : java.lang.Integer.hashCode() method returns the hashCode value of the argument passed. Syntax: "
},
{
"code": null,
"e": 28511,
"s": 28395,
"text": "public int hashCode(arg)\nParameters:\narg - the argument whose hashCode value we need\nReturns:\nhashCode value of arg"
},
{
"code": null,
"e": 28847,
"s": 28511,
"text": " lowestOneBit() : java.lang.Integer.lowestOneBit() method first convert int to Binary, then it looks for set(1) bit present at lowest position then it reset rest of the bits e.g arg = 36 It,s Binary Representation = 0010 0100 It considers lowest bit(at 3) and now reset rest of the bits i.e. 0000 0100 so result = 0100 i.e. 4 Syntax: "
},
{
"code": null,
"e": 29184,
"s": 28849,
"text": "lowestOneBit() : java.lang.Integer.lowestOneBit() method first convert int to Binary, then it looks for set(1) bit present at lowest position then it reset rest of the bits e.g arg = 36 It,s Binary Representation = 0010 0100 It considers lowest bit(at 3) and now reset rest of the bits i.e. 0000 0100 so result = 0100 i.e. 4 Syntax: "
},
{
"code": null,
"e": 29331,
"s": 29184,
"text": "public static int lowestOneBit(int arg)\nParameters:\narg - argument passed\nReturns:\ninteger value by only considering lowest 1 bit in the argument."
},
{
"code": null,
"e": 29672,
"s": 29331,
"text": " highestOneBit() : java.lang.Integer.highestOneBit() method first convert int to Binary, then it looks for set(1) bit present at lowest position then it reset rest of the bits e.g arg = 36 It,s Binary Representation = 0010 0100 It considers highest bit(at 6) and now reset rest of the bits i.e. 0001 0000 so result = 10000 i.e. 32 Syntax: "
},
{
"code": null,
"e": 30014,
"s": 29674,
"text": "highestOneBit() : java.lang.Integer.highestOneBit() method first convert int to Binary, then it looks for set(1) bit present at lowest position then it reset rest of the bits e.g arg = 36 It,s Binary Representation = 0010 0100 It considers highest bit(at 6) and now reset rest of the bits i.e. 0001 0000 so result = 10000 i.e. 32 Syntax: "
},
{
"code": null,
"e": 30163,
"s": 30014,
"text": "public static int highestOneBit(int arg)\nParameters:\narg - argument passed\nReturns:\ninteger value by only considering highest 1 bit in the argument."
},
{
"code": null,
"e": 30172,
"s": 30167,
"text": "JAVA"
},
{
"code": "// Java program explaining Integer class methods// hashcode(), lowestOneBit(), highestOneBit()import java.lang.*;public class NewClass{ public static void main(String[] args) { // Use of incrementExact() method int f1 = 30, f2 = -56; f1 = Integer.hashCode(f1); System.out.println(\"HashCode value of f1 : \"+f1); f2 = Integer.hashCode(f2); System.out.println(\"HashCode value of f2 : \"+f2); System.out.println(\"\\nBinary representation of 30 : \" + Integer.toBinaryString(f1)); // Use of lowestOneBit() method // Here it considers 00010 i.e. 2 System.out.println(\"lowestOneBit of 30 : \" + Integer.lowestOneBit(f1)); // Use of highestOneBit() method // Here it considers 10000 i.e. 16 System.out.println(\"highestOneBit of 30 : \" + Integer.highestOneBit(f1)); }}",
"e": 31112,
"s": 30172,
"text": null
},
{
"code": null,
"e": 31122,
"s": 31112,
"text": "Output: "
},
{
"code": null,
"e": 31132,
"s": 31122,
"text": "Output: "
},
{
"code": null,
"e": 31270,
"s": 31132,
"text": "HashCode value of f1 : 30\nHashCode value of f2 : -56\n\nBinary representation of 30 : 11110\nlowestOneBit of 30 : 2\nhighestOneBit of 30 : 16"
},
{
"code": null,
"e": 31573,
"s": 31270,
"text": " numberOfTrailingZeros() : java.lang.Integer.numberOfTrailingZeros() method converts int value to Binary then considers the lowest one bit and return no. of zero bits following it. e.g arg = 36 It,s Binary Representation = 0010 0100 It considers highest bit(at 6) i.e. 0001 0000 so result = 4 Syntax: "
},
{
"code": null,
"e": 31877,
"s": 31575,
"text": "numberOfTrailingZeros() : java.lang.Integer.numberOfTrailingZeros() method converts int value to Binary then considers the lowest one bit and return no. of zero bits following it. e.g arg = 36 It,s Binary Representation = 0010 0100 It considers highest bit(at 6) i.e. 0001 0000 so result = 4 Syntax: "
},
{
"code": null,
"e": 32025,
"s": 31877,
"text": "public static int numberOfTrailingZeros(int arg)\nParameters:\narg - the argument\nReturns:\nNumber of zero bits following the 1 bit at lowest position"
},
{
"code": null,
"e": 32340,
"s": 32025,
"text": " numberOfLeadingZeros() : java.lang.Integer.numberOfLeadingZeros() method converts int value to Binary then considers the highest one bit and return no. of zero bits preceding it. e.g arg = 36 It,s Binary Representation = 0010 0100 It considers highest bit(at 6) i.e. 0010 0000 so result = 32 – 6 i.e. 26 Syntax: "
},
{
"code": null,
"e": 32656,
"s": 32342,
"text": "numberOfLeadingZeros() : java.lang.Integer.numberOfLeadingZeros() method converts int value to Binary then considers the highest one bit and return no. of zero bits preceding it. e.g arg = 36 It,s Binary Representation = 0010 0100 It considers highest bit(at 6) i.e. 0010 0000 so result = 32 – 6 i.e. 26 Syntax: "
},
{
"code": null,
"e": 32804,
"s": 32656,
"text": "public static int numberOfLeadingZeros(int arg)\nParameters:\narg - the argument\nReturns:\nNumber of zero bits preceding the 1 bit at highest position"
},
{
"code": null,
"e": 32965,
"s": 32804,
"text": " reverse() : java.lang.Integer.reverse() method first find 2’s compliment of the argument passed and reverses the order of bits in the 2’s compliment. Syntax: "
},
{
"code": null,
"e": 33127,
"s": 32967,
"text": "reverse() : java.lang.Integer.reverse() method first find 2’s compliment of the argument passed and reverses the order of bits in the 2’s compliment. Syntax: "
},
{
"code": null,
"e": 33275,
"s": 33127,
"text": "public static int reverse(int arg)\nParameters:\narg - the argument \nReturns:\nint with reverse order of bits in 2's compliment of the passed argument"
},
{
"code": null,
"e": 33284,
"s": 33279,
"text": "JAVA"
},
{
"code": "// Java program explaining Integer class methods// numberOfTrailingZeros(), numberOfLeadingZeros(), reverse()import java.lang.*;public class NewClass{ public static void main(String[] args) { int f1 = 30; // Binary representation of int arg for your understanding System.out.println(\"Binary representation of 30 : \" + Integer.toBinaryString(f1)); // Use of numberOfTrailingZeros() method // No. of zeros following 1 in 00010 = 1 System.out.println(\"\\nNo. Of Trailing Zeros : \" + Integer.numberOfTrailingZeros(f1)); // Use of highestOneBit() method // No. of zeros following 1 in 10000 i.e. 32 - 5 = 27 System.out.println(\"\\nNo. Of Leading Zeros : \" + Integer.numberOfLeadingZeros(f1)); // Use of Reverse() method System.out.println(\"\\nReverse : \" + Integer.reverse(f1)); }}",
"e": 34226,
"s": 33284,
"text": null
},
{
"code": null,
"e": 34236,
"s": 34226,
"text": "Output: "
},
{
"code": null,
"e": 34246,
"s": 34236,
"text": "Output: "
},
{
"code": null,
"e": 34359,
"s": 34246,
"text": "Binary representation of 30 : 11110\n\nNo. Of Trailing Zeros : 1\n\nNo. Of Leading Zeros : 27\n\nReverse : 2013265920"
},
{
"code": null,
"e": 34783,
"s": 34363,
"text": "This article is contributed by Mohit Gupta. 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": 34803,
"s": 34783,
"text": "abhishek0719kadiyan"
},
{
"code": null,
"e": 34821,
"s": 34803,
"text": "Java-lang package"
},
{
"code": null,
"e": 34834,
"s": 34821,
"text": "Java-Library"
},
{
"code": null,
"e": 34839,
"s": 34834,
"text": "Java"
},
{
"code": null,
"e": 34844,
"s": 34839,
"text": "Java"
},
{
"code": null,
"e": 34942,
"s": 34844,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34951,
"s": 34942,
"text": "Comments"
},
{
"code": null,
"e": 34964,
"s": 34951,
"text": "Old Comments"
},
{
"code": null,
"e": 34994,
"s": 34964,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 35009,
"s": 34994,
"text": "Stream In Java"
},
{
"code": null,
"e": 35030,
"s": 35009,
"text": "Constructors in Java"
},
{
"code": null,
"e": 35076,
"s": 35030,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 35095,
"s": 35076,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 35112,
"s": 35095,
"text": "Generics in Java"
},
{
"code": null,
"e": 35155,
"s": 35112,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 35171,
"s": 35155,
"text": "Strings in Java"
},
{
"code": null,
"e": 35227,
"s": 35171,
"text": "Difference between Abstract Class and Interface in Java"
}
] |
Python - Divide and Conquer | In divide and conquer approach, the problem in hand, is divided into smaller sub-problems and then each problem is solved independently. When we keep on dividing the subproblems into even smaller sub-problems, we may eventually reach a stage where no more division is possible. Those "atomic" smallest possible sub-problem (fractions) are solved. The solution of all sub-problems is finally merged in order to obtain the solution of an original problem.
Broadly, we can understand divide-and-conquer approach in a three-step process.
This step involves breaking the problem into smaller sub-problems. Sub-problems should represent a part of the original problem. This step generally takes a recursive approach to divide the problem until no sub-problem is further divisible. At this stage, sub-problems become atomic in nature but still represent some part of the actual problem.
This step receives a lot of smaller sub-problems to be solved. Generally, at this level, the problems are considered 'solved' on their own.
When the smaller sub-problems are solved, this stage recursively combines them until they formulate a solution of the original problem. This algorithmic approach works recursively and conquer &s; merge steps works so close that they appear as one.
The following program is an example of divide-and-conquer programming approach where the binary search is implemented using python.
In binary search we take a sorted list of elements and start looking for an element at the middle of the list. If the search value matches with the middle value in the list we complete the search. Otherwise we eleminate half of the list of elements by choosing whether to procees with the right or left half of the list depending on the value of the item searched.
This is possible as the list is sorted and it is much quicker than linear search.Here we divide the given list and conquer by choosing the proper half of the list. We repeat this approcah till we find the element or conclude about it's absence in the list.
def bsearch(list, val):
list_size = len(list) - 1
idx0 = 0
idxn = list_size
# Find the middle most value
while idx0 <= idxn:
midval = (idx0 + idxn)// 2
if list[midval] == val:
return midval
# Compare the value the middle most value
if val > list[midval]:
idx0 = midval + 1
else:
idxn = midval - 1
if idx0 > idxn:
return None
# Initialize the sorted list
list = [2,7,19,34,53,72]
# Print the search result
print(bsearch(list,72))
print(bsearch(list,11))
When the above code is executed, it produces the following result −
5
None
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2781,
"s": 2327,
"text": "In divide and conquer approach, the problem in hand, is divided into smaller sub-problems and then each problem is solved independently. When we keep on dividing the subproblems into even smaller sub-problems, we may eventually reach a stage where no more division is possible. Those \"atomic\" smallest possible sub-problem (fractions) are solved. The solution of all sub-problems is finally merged in order to obtain the solution of an original problem."
},
{
"code": null,
"e": 2861,
"s": 2781,
"text": "Broadly, we can understand divide-and-conquer approach in a three-step process."
},
{
"code": null,
"e": 3207,
"s": 2861,
"text": "This step involves breaking the problem into smaller sub-problems. Sub-problems should represent a part of the original problem. This step generally takes a recursive approach to divide the problem until no sub-problem is further divisible. At this stage, sub-problems become atomic in nature but still represent some part of the actual problem."
},
{
"code": null,
"e": 3347,
"s": 3207,
"text": "This step receives a lot of smaller sub-problems to be solved. Generally, at this level, the problems are considered 'solved' on their own."
},
{
"code": null,
"e": 3595,
"s": 3347,
"text": "When the smaller sub-problems are solved, this stage recursively combines them until they formulate a solution of the original problem. This algorithmic approach works recursively and conquer &s; merge steps works so close that they appear as one."
},
{
"code": null,
"e": 3727,
"s": 3595,
"text": "The following program is an example of divide-and-conquer programming approach where the binary search is implemented using python."
},
{
"code": null,
"e": 4092,
"s": 3727,
"text": "In binary search we take a sorted list of elements and start looking for an element at the middle of the list. If the search value matches with the middle value in the list we complete the search. Otherwise we eleminate half of the list of elements by choosing whether to procees with the right or left half of the list depending on the value of the item searched."
},
{
"code": null,
"e": 4349,
"s": 4092,
"text": "This is possible as the list is sorted and it is much quicker than linear search.Here we divide the given list and conquer by choosing the proper half of the list. We repeat this approcah till we find the element or conclude about it's absence in the list."
},
{
"code": null,
"e": 4863,
"s": 4349,
"text": "def bsearch(list, val):\n list_size = len(list) - 1\n idx0 = 0\n idxn = list_size\n# Find the middle most value\n while idx0 <= idxn:\n midval = (idx0 + idxn)// 2\n if list[midval] == val:\n return midval\n# Compare the value the middle most value\n if val > list[midval]:\n idx0 = midval + 1\n else:\n idxn = midval - 1\n if idx0 > idxn:\n return None\n# Initialize the sorted list\nlist = [2,7,19,34,53,72]\n\n# Print the search result\nprint(bsearch(list,72))\nprint(bsearch(list,11))"
},
{
"code": null,
"e": 4931,
"s": 4863,
"text": "When the above code is executed, it produces the following result −"
},
{
"code": null,
"e": 4939,
"s": 4931,
"text": "5\nNone\n"
},
{
"code": null,
"e": 4976,
"s": 4939,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 4992,
"s": 4976,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 5025,
"s": 4992,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 5044,
"s": 5025,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 5079,
"s": 5044,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 5101,
"s": 5079,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 5135,
"s": 5101,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 5163,
"s": 5135,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 5198,
"s": 5163,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 5212,
"s": 5198,
"text": " Lets Kode It"
},
{
"code": null,
"e": 5245,
"s": 5212,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 5262,
"s": 5245,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 5269,
"s": 5262,
"text": " Print"
},
{
"code": null,
"e": 5280,
"s": 5269,
"text": " Add Notes"
}
] |
Set a border around navbar with CSS | To add a border around navbar, set border to <ul>
ul {
border: 2px solid blue;
}
You can try to run the following code to set border
Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
ul {
list-style-type: none;
margin: 0;
padding: 0;
width: 200px;
border: 2px solid blue;
}
li a {
display: block;
background-color: #F0E7E7;
}
.active {
background-color: #4CAF50;
color: white;
}
li {
text-align: center;
border-bottom: 1px solid #555;
}
</style>
</head>
<body>
<ul>
<li><a href = "#home">Home</a></li>
<li><a href = "#company" class = "active">Company</a></li>
<li><a href = "#product">Product</a></li>
<li><a href = "#services">Services</a></li>
<li><a href = "#contact">Contact</a></li>
</ul>
</body>
</html> | [
{
"code": null,
"e": 1112,
"s": 1062,
"text": "To add a border around navbar, set border to <ul>"
},
{
"code": null,
"e": 1146,
"s": 1112,
"text": "ul {\n border: 2px solid blue;\n}"
},
{
"code": null,
"e": 1198,
"s": 1146,
"text": "You can try to run the following code to set border"
},
{
"code": null,
"e": 1208,
"s": 1198,
"text": "Live Demo"
},
{
"code": null,
"e": 2059,
"s": 1208,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <style>\n ul {\n list-style-type: none;\n margin: 0;\n padding: 0;\n width: 200px;\n border: 2px solid blue;\n }\n li a {\n display: block;\n background-color: #F0E7E7;\n }\n .active {\n background-color: #4CAF50;\n color: white;\n }\n li {\n text-align: center;\n border-bottom: 1px solid #555;\n }\n </style>\n </head>\n <body>\n <ul>\n <li><a href = \"#home\">Home</a></li>\n <li><a href = \"#company\" class = \"active\">Company</a></li>\n <li><a href = \"#product\">Product</a></li>\n <li><a href = \"#services\">Services</a></li>\n <li><a href = \"#contact\">Contact</a></li>\n </ul>\n </body>\n</html>"
}
] |
Clustering: Why to Use it. As an new data science student who came... | by Robert Miller | Towards Data Science | As an new data science student who came from a no coding background, I like to explain complex topics in a simplified way. As if talking to myself before my program started. Well I hope you are all ready for some clustering.
Lets start with what is clustering? It is something that you have done, many times in fact. Its the act of looking for similarities and putting those similar points into a group (or cluster). Lets all think back to the last time we went out to eat. The first thing you want to find out is what type of food you want, Mexican, Chinese, Italian, ect. You are making clusters of multiple restaurants with those attributes.
Now to a more Data Science example, I am going to look at different attributes of seeds and see if clustering those attributes can help predict whether a seed is of a certain species or not.
Jumping right into the code, we need to import libraries in order to execute the following lines. I am also going to read in my dataset at the bottom
%matplotlib inline import pandas as pdimport numpy as npfrom sklearn import clusterfrom sklearn import metricsfrom sklearn.metrics import pairwise_distancesimport matplotlib.pyplot as pltimport matplotlibmatplotlib.style.use('ggplot') import seaborn as snsseeds = pd.read_csv("../assets/datasets/seeds.csv")
Just looking at the first few rows of my Dataframe, this is what it looks like. The code to look at this using pandas is seeds.head(), that will show the first 5 rows
seeds.species.nunique()
I then looked at the amount of unique values in my species column, which is are Target value column (the thing we are trying to predict). It turns out there are three species in our dataset
# Plot the Data to see the distributions/relationshipscols = seeds.columns[:-1]sns.pairplot(seeds, x_vars=cols, y_vars= cols, hue='species')
This is a scatter plot of how our different variables relate to each other, and the color (or hue which I set above) is each different species. So you can start to see that in general the seeds tend to cluster with their own species for the majority of our variables (predictors).
Since we have a Target value we could stop our clustering here, but many times that we will use clustering is when we don’t have a Target value. So I will drop our Target and see if our clustering will pick up on the differences and do a good job of predicting which seeds should be clustered together.
X = seeds.drop("species", axis = 1)from sklearn.metrics import pairwise_distancesfrom sklearn import cluster, datasets, preprocessing, metricsX_scaled = preprocessing.normalize(X,axis=0)
I dropped the Target value, I also imported a few more libraries from sklearn so I can normalize my data. Normalizing data is the process of organizing the attributes and relations of the database to scale all numeric variables in the range [0,1]. We do this so that columns like permiter with values of 15 don’t show more importance than columns like compactness which are below 1
from sklearn.cluster import KMeansk = 3kmeans = cluster.KMeans(n_clusters=k)kmeans.fit(X_scaled)
I am using kmeans clustering for this problem. It sets random centroids (center points for each group) and those centroids will continually shift until they are centered in a cluster of points to make the mean distance of all points as small as possible.
inertia = kmeans.inertia_print 'Silhouette Score:', metrics.silhouette_score(X_scaled, labels, metric='euclidean')
What I am doing above is looking at two different metrics to analyze how well our clustering method did. Inertia is the sum of squared error for each cluster. Therefore the smaller the inertia the denser the cluster(closer together all the points are)
The Silhouette Score is from -1 to 1 and show how close or far away the clusters are from each other and how dense the clusters are. The closer your silhouette score is to 1 the more distinct your clusters are. If your score is 1 think of your clusters as perfect little balls that are far away from each other with no miss classification.
Clustering can be used on many problems, whether you have a Target value or not, it is helpful to seek insights and see relationships. | [
{
"code": null,
"e": 397,
"s": 172,
"text": "As an new data science student who came from a no coding background, I like to explain complex topics in a simplified way. As if talking to myself before my program started. Well I hope you are all ready for some clustering."
},
{
"code": null,
"e": 817,
"s": 397,
"text": "Lets start with what is clustering? It is something that you have done, many times in fact. Its the act of looking for similarities and putting those similar points into a group (or cluster). Lets all think back to the last time we went out to eat. The first thing you want to find out is what type of food you want, Mexican, Chinese, Italian, ect. You are making clusters of multiple restaurants with those attributes."
},
{
"code": null,
"e": 1008,
"s": 817,
"text": "Now to a more Data Science example, I am going to look at different attributes of seeds and see if clustering those attributes can help predict whether a seed is of a certain species or not."
},
{
"code": null,
"e": 1158,
"s": 1008,
"text": "Jumping right into the code, we need to import libraries in order to execute the following lines. I am also going to read in my dataset at the bottom"
},
{
"code": null,
"e": 1466,
"s": 1158,
"text": "%matplotlib inline import pandas as pdimport numpy as npfrom sklearn import clusterfrom sklearn import metricsfrom sklearn.metrics import pairwise_distancesimport matplotlib.pyplot as pltimport matplotlibmatplotlib.style.use('ggplot') import seaborn as snsseeds = pd.read_csv(\"../assets/datasets/seeds.csv\")"
},
{
"code": null,
"e": 1633,
"s": 1466,
"text": "Just looking at the first few rows of my Dataframe, this is what it looks like. The code to look at this using pandas is seeds.head(), that will show the first 5 rows"
},
{
"code": null,
"e": 1657,
"s": 1633,
"text": "seeds.species.nunique()"
},
{
"code": null,
"e": 1847,
"s": 1657,
"text": "I then looked at the amount of unique values in my species column, which is are Target value column (the thing we are trying to predict). It turns out there are three species in our dataset"
},
{
"code": null,
"e": 1988,
"s": 1847,
"text": "# Plot the Data to see the distributions/relationshipscols = seeds.columns[:-1]sns.pairplot(seeds, x_vars=cols, y_vars= cols, hue='species')"
},
{
"code": null,
"e": 2269,
"s": 1988,
"text": "This is a scatter plot of how our different variables relate to each other, and the color (or hue which I set above) is each different species. So you can start to see that in general the seeds tend to cluster with their own species for the majority of our variables (predictors)."
},
{
"code": null,
"e": 2572,
"s": 2269,
"text": "Since we have a Target value we could stop our clustering here, but many times that we will use clustering is when we don’t have a Target value. So I will drop our Target and see if our clustering will pick up on the differences and do a good job of predicting which seeds should be clustered together."
},
{
"code": null,
"e": 2759,
"s": 2572,
"text": "X = seeds.drop(\"species\", axis = 1)from sklearn.metrics import pairwise_distancesfrom sklearn import cluster, datasets, preprocessing, metricsX_scaled = preprocessing.normalize(X,axis=0)"
},
{
"code": null,
"e": 3141,
"s": 2759,
"text": "I dropped the Target value, I also imported a few more libraries from sklearn so I can normalize my data. Normalizing data is the process of organizing the attributes and relations of the database to scale all numeric variables in the range [0,1]. We do this so that columns like permiter with values of 15 don’t show more importance than columns like compactness which are below 1"
},
{
"code": null,
"e": 3238,
"s": 3141,
"text": "from sklearn.cluster import KMeansk = 3kmeans = cluster.KMeans(n_clusters=k)kmeans.fit(X_scaled)"
},
{
"code": null,
"e": 3493,
"s": 3238,
"text": "I am using kmeans clustering for this problem. It sets random centroids (center points for each group) and those centroids will continually shift until they are centered in a cluster of points to make the mean distance of all points as small as possible."
},
{
"code": null,
"e": 3608,
"s": 3493,
"text": "inertia = kmeans.inertia_print 'Silhouette Score:', metrics.silhouette_score(X_scaled, labels, metric='euclidean')"
},
{
"code": null,
"e": 3860,
"s": 3608,
"text": "What I am doing above is looking at two different metrics to analyze how well our clustering method did. Inertia is the sum of squared error for each cluster. Therefore the smaller the inertia the denser the cluster(closer together all the points are)"
},
{
"code": null,
"e": 4200,
"s": 3860,
"text": "The Silhouette Score is from -1 to 1 and show how close or far away the clusters are from each other and how dense the clusters are. The closer your silhouette score is to 1 the more distinct your clusters are. If your score is 1 think of your clusters as perfect little balls that are far away from each other with no miss classification."
}
] |
Hyperparameters Optimization. An introduction on how to fine-tune... | by Pier Paolo Ippolito | Towards Data Science | 1
2
3
4
5
6
7
8
9
10
Powered by Play.ht
Create audio with Play.ht
Create Audio Narrations with Play.ht
Machine Learning models are composed of two different types of parameters:
Hyperparameters = are all the parameters which can be arbitrarily set by the user before starting training (eg. number of estimators in Random Forest).
Model parameters = are instead learned during the model training (eg. weights in Neural Networks, Linear Regression).
The model parameters define how to use input data to get the desired output and are learned at training time. Instead, Hyperparameters determine how our model is structured in the first place.
Machine Learning models tuning is a type of optimization problem. We have a set of hyperparameters and we aim to find the right combination of their values which can help us to find either the minimum (eg. loss) or the maximum (eg. accuracy) of a function (Figure 1).
This can be particularly important when comparing how different Machine Learning models performs on a dataset. In fact, it would be unfair for example to compare an SVM model with the best Hyperparameters against a Random Forest model which has not been optimized.
In this post, the following approaches to Hyperparameter optimization will be explained:
Manual SearchRandom SearchGrid SearchAutomated Hyperparameter Tuning (Bayesian Optimization, Genetic Algorithms)Artificial Neural Networks (ANNs) Tuning
Manual Search
Random Search
Grid Search
Automated Hyperparameter Tuning (Bayesian Optimization, Genetic Algorithms)
Artificial Neural Networks (ANNs) Tuning
In order to demonstrate how to perform Hyperparameters Optimization in Python, I decided to perform a complete Data Analysis of the Credit Card Fraud Detection Kaggle Dataset. Our objective in this article will be to correctly classify which credit card transactions should be labelled as fraudulent or genuine (binary classification). This Dataset has been anonymized before being distributed, therefore, the meaning of most of the features has not been disclosed.
In this case, I decided to use just a subset of the dataset, in order to speed up training times and make sure to achieve a perfect balance between the two different classes. Additionally, just a limited amount of features has been used to make the optimization tasks more challenging. The final dataset is shown in the figure below (Figure 2).
All the code used in this article (and more!) is available in my GitHub repository and Kaggle Profile.
First of all, we need to divide our dataset into training and test sets.
Throughout this article, we will use a Random Forest Classifier as our model to optimize.
Random Forest models are formed by a large number of uncorrelated decision trees, which joint together constitute an ensemble. In Random Forest, each decision tree makes its own prediction and the overall model output is selected to be the prediction which appeared most frequently.
We can now start by calculating our base model accuracy.
[[110 6] [ 6 118]] precision recall f1-score support 0 0.95 0.95 0.95 116 1 0.95 0.95 0.95 124 accuracy 0.95 240 macro avg 0.95 0.95 0.95 240weighted avg 0.95 0.95 0.95 240
Using the Random Forest Classifier with the default scikit-learn parameters lead to 95% overall accuracy. Let’s see now if applying some optimization techniques we can achieve better accuracy.
When using Manual Search, we choose some model hyperparameters based on our judgment/experience. We then train the model, evaluate its accuracy and start the process again. This loop is repeated until a satisfactory accuracy is scored.
The main parameters used by a Random Forest Classifier are:
criterion = the function used to evaluate the quality of a split.
max_depth = maximum number of levels allowed in each tree.
max_features = maximum number of features considered when splitting a node.
min_samples_leaf = minimum number of samples which can be stored in a tree leaf.
min_samples_split = minimum number of samples necessary in a node to cause node splitting.
n_estimators = number of trees in the ensemble.
More information about Random Forest parameters can be found on the scikit-learn Documentation.
As an example of Manual Search, I tried to specify the number of estimators in our model. Unfortunately, this didn’t lead to any improvement in accuracy.
[[110 6] [ 6 118]] precision recall f1-score support 0 0.95 0.95 0.95 116 1 0.95 0.95 0.95 124 accuracy 0.95 240 macro avg 0.95 0.95 0.95 240weighted avg 0.95 0.95 0.95 240
In Random Search, we create a grid of hyperparameters and train/test our model on just some random combination of these hyperparameters. In this example, I additionally decided to perform Cross-Validation on the training set.
When performing Machine Learning tasks, we generally divide our dataset in training and test sets. This is done so that to test our model after having trained it (in this way we can check it’s performances when working with unseen data). When using Cross-Validation, we divide our training set into N other partitions to make sure our model is not overfitting our data.
One of the most common used Cross-Validation methods is K-Fold Validation. In K-Fold, we divide our training set into N partitions and then iteratively train our model using N-1 partitions and test it with the left-over partition (at each iteration we change the left-over partition). Once having trained N times the model we then average the training results obtained in each iteration to obtain our overall training performance results (Figure 3).
Using Cross-Validation when implementing Hyperparameters optimization can be really important. In this way, we might avoid using some Hyperparameters which works really good on the training data but not so good with the test data.
We can now start implementing Random Search by first defying a grid of hyperparameters which will be randomly sampled when calling RandomizedSearchCV(). For this example, I decided to divide our training set into 4 Folds (cv = 4) and select 80 as the number of combinations to sample (n_iter = 80). Using the scikit-learn best_estimator_ attribute, we can then retrieve the set of hyperparameters which performed best during training to test our model.
Once trained our model, we can then visualize how changing some of its Hyperparameters can affect the overall model accuracy (Figure 4). In this case, I decided to observe how changing the number of estimators and the criterion can affect our Random Forest accuracy.
We can then take this a step further by making our visualization more interactive. In the chart below, we can examine (using the slider) how varying the number of estimators in our model can affect the overall accuracy of our model considered the selected min_split and min_leaf parameters.
Feel free to play with the graph below by changing the n_estimators parameters, zooming in and out of the graph, changing it’s orientation and hovering over the single data points to get additional information about them!
If you are interested in finding out more about how to create these animations using Plotly, my code is available here. Additionally, this has also been covered in an article written by Xoel López Barata.
We can now evaluate how our model performed using Random Search. In this case, using Random Search leads to a consistent increase in accuracy compared to our base model.
[[115 1] [ 6 118]] precision recall f1-score support 0 0.95 0.99 0.97 116 1 0.99 0.95 0.97 124 accuracy 0.97 240 macro avg 0.97 0.97 0.97 240weighted avg 0.97 0.97 0.97 240
In Grid Search, we set up a grid of hyperparameters and train/test our model on each of the possible combinations.
In order to choose the parameters to use in Grid Search, we can now look at which parameters worked best with Random Search and form a grid based on them to see if we can find a better combination.
Grid Search can be implemented in Python using scikit-learn GridSearchCV() function. Also on this occasion, I decided to divide our training set into 4 Folds (cv = 4).
When using Grid Search, all the possible combinations of the parameters in the grid are tried. In this case, 128000 combinations (2 × 10 × 4 × 4 × 4 × 10) will be used during training. Instead, in the Grid Search example before, just 80 combinations have been used.
[[115 1] [ 7 117]] precision recall f1-score support 0 0.94 0.99 0.97 116 1 0.99 0.94 0.97 124 accuracy 0.97 240 macro avg 0.97 0.97 0.97 240weighted avg 0.97 0.97 0.97 240
Grid Search is slower compared to Random Search but it can be overall more effective because it can go through the whole search space. Instead, Random Search can be faster fast but might miss some important points in the search space.
When using Automated Hyperparameter Tuning, the model hyperparameters to use are identified using techniques such as: Bayesian Optimization, Gradient Descent and Evolutionary Algorithms.
Bayesian Optimization can be performed in Python using the Hyperopt library. Bayesian optimization uses probability to find the minimum of a function. The final aim is to find the input value to a function which can give us the lowest possible output value.
Bayesian optimization has been proved to be more efficient than random, grid or manual search. Bayesian Optimization can, therefore, lead to better performance in the testing phase and reduced optimization time.
In Hyperopt, Bayesian Optimization can be implemented giving 3 three main parameters to the function fmin().
Objective Function = defines the loss function to minimize.
Domain Space = defines the range of input values to test (in Bayesian Optimization this space creates a probability distribution for each of the used Hyperparameters).
Optimization Algorithm = defines the search algorithm to use to select the best input values to use in each new iteration.
Additionally, can also be defined in fmin() the maximum number of evaluations to perform.
Bayesian Optimization can reduce the number of search iterations by choosing the input values bearing in mind the past outcomes. In this way, we can concentrate our search from the beginning on values which are closer to our desired output.
We can now run our Bayesian Optimizer using the fmin() function. A Trials() object is first created to make possible to visualize later what was going on while the fmin() function was running (eg. how the loss function was changing and how to used Hyperparameters were changing).
100%|██████████| 80/80 [03:07<00:00, 2.02s/it, best loss: -0.9339285714285713]{'criterion': 1, 'max_depth': 120.0, 'max_features': 2, 'min_samples_leaf': 0.0006380325074247448, 'min_samples_split': 0.06603114636418073, 'n_estimators': 1}
We can now retrieve the set of best parameters identified and test our model using the best dictionary created during training. Some of the parameters have been stored in the best dictionary numerically using indices, therefore, we need first to convert them back as strings before input them in our Random Forest.
The classification report using Bayesian Optimization is shown below.
[[114 2] [ 11 113]] precision recall f1-score support 0 0.91 0.98 0.95 116 1 0.98 0.91 0.95 124 accuracy 0.95 240 macro avg 0.95 0.95 0.95 240weighted avg 0.95 0.95 0.95 240
Genetic Algorithms tries to apply natural selection mechanisms to Machine Learning contexts. They are inspired by the Darwinian process of Natural Selection and they are therefore also usually called as Evolutionary Algorithms.
Let’s imagine we create a population of N Machine Learning models with some predefined Hyperparameters. We can then calculate the accuracy of each model and decide to keep just half of the models (the ones that perform best). We can now generate some offsprings having similar Hyperparameters to the ones of the best models so that to get again a population of N models. At this point, we can again calculate the accuracy of each model and repeat the cycle for a defined number of generations. In this way, just the best models will survive at the end of the process.
In order to implement Genetic Algorithms in Python, we can use the TPOT Auto Machine Learning library. TPOT is built on the scikit-learn library and it can be used for either regression or classification tasks.
The training report and the best parameters identified using Genetic Algorithms are shown in the following snippet.
Generation 1 - Current best internal CV score: 0.9392857142857143Generation 2 - Current best internal CV score: 0.9392857142857143Generation 3 - Current best internal CV score: 0.9392857142857143Generation 4 - Current best internal CV score: 0.9392857142857143Generation 5 - Current best internal CV score: 0.9392857142857143Best pipeline: RandomForestClassifier(CombineDFs(input_matrix, input_matrix), criterion=entropy, max_depth=406, max_features=log2, min_samples_leaf=4, min_samples_split=5, n_estimators=617)
The overall accuracy of our Random Forest Genetic Algorithm optimized model is shown below.
0.9708333333333333
Using KerasClassifier wrapper, it is possible to apply Grid Search and Random Search for Deep Learning models in the same way it was done when using scikit-learn Machine Learning models. In the following example, we will try to optimize some of our ANN parameters such as: how many neurons to use in each layer and which activation function and optimizer to use. More examples of Deep Learning Hyperparameters optimization are available here.
Max Accuracy Registred: 0.932 using {'activation': 'relu', 'neurons': 35, 'optimizer': 'Adam'}
The overall accuracy scored using our Artificial Neural Network (ANN) can be observed below.
[[115 1] [ 8 116]] precision recall f1-score support 0 0.93 0.99 0.96 116 1 0.99 0.94 0.96 124 accuracy 0.96 240 macro avg 0.96 0.96 0.96 240weighted avg 0.96 0.96 0.96 240
We can now compare how all the different optimization techniques performed on this given exercise. Overall, Random Search and Evolutionary Algorithms performed best.
Base Accuracy vs Manual Search 0.0000%.Base Accuracy vs Random Search 2.1930%.Base Accuracy vs Grid Search 1.7544%.Base Accuracy vs Bayesian Optimization Accuracy -0.4386%.Base Accuracy vs Evolutionary Algorithms 2.1930%.Base Accuracy vs Optimized ANN 1.3158%.
The results obtained, are highly dependent on the chosen grid space and dataset used. Therefore, in different situations, different optimization techniques will perform better than others.
I hope you enjoyed this article, thank you for reading!
If you want to keep updated with my latest articles and projects follow me on Medium and subscribe to my mailing list. These are some of my contacts details:
Linkedin
Personal Blog
Personal Website
Medium Profile
GitHub
Kaggle
[1] Hyperparameter optimization: Explanation of automatized algorithms, Dawid Kopczyk. Accessed at: https://dkopczyk.quantee.co.uk/hyperparameter-optimization/
[2] Model Selection, ethen8181. Accessed at: http://ethen8181.github.io/machine-learning/model_selection/model_selection.html | [
{
"code": null,
"e": 174,
"s": 172,
"text": "1"
},
{
"code": null,
"e": 176,
"s": 174,
"text": "2"
},
{
"code": null,
"e": 178,
"s": 176,
"text": "3"
},
{
"code": null,
"e": 180,
"s": 178,
"text": "4"
},
{
"code": null,
"e": 182,
"s": 180,
"text": "5"
},
{
"code": null,
"e": 184,
"s": 182,
"text": "6"
},
{
"code": null,
"e": 186,
"s": 184,
"text": "7"
},
{
"code": null,
"e": 188,
"s": 186,
"text": "8"
},
{
"code": null,
"e": 190,
"s": 188,
"text": "9"
},
{
"code": null,
"e": 193,
"s": 190,
"text": "10"
},
{
"code": null,
"e": 212,
"s": 193,
"text": "Powered by Play.ht"
},
{
"code": null,
"e": 238,
"s": 212,
"text": "Create audio with Play.ht"
},
{
"code": null,
"e": 275,
"s": 238,
"text": "Create Audio Narrations with Play.ht"
},
{
"code": null,
"e": 350,
"s": 275,
"text": "Machine Learning models are composed of two different types of parameters:"
},
{
"code": null,
"e": 502,
"s": 350,
"text": "Hyperparameters = are all the parameters which can be arbitrarily set by the user before starting training (eg. number of estimators in Random Forest)."
},
{
"code": null,
"e": 620,
"s": 502,
"text": "Model parameters = are instead learned during the model training (eg. weights in Neural Networks, Linear Regression)."
},
{
"code": null,
"e": 813,
"s": 620,
"text": "The model parameters define how to use input data to get the desired output and are learned at training time. Instead, Hyperparameters determine how our model is structured in the first place."
},
{
"code": null,
"e": 1081,
"s": 813,
"text": "Machine Learning models tuning is a type of optimization problem. We have a set of hyperparameters and we aim to find the right combination of their values which can help us to find either the minimum (eg. loss) or the maximum (eg. accuracy) of a function (Figure 1)."
},
{
"code": null,
"e": 1346,
"s": 1081,
"text": "This can be particularly important when comparing how different Machine Learning models performs on a dataset. In fact, it would be unfair for example to compare an SVM model with the best Hyperparameters against a Random Forest model which has not been optimized."
},
{
"code": null,
"e": 1435,
"s": 1346,
"text": "In this post, the following approaches to Hyperparameter optimization will be explained:"
},
{
"code": null,
"e": 1588,
"s": 1435,
"text": "Manual SearchRandom SearchGrid SearchAutomated Hyperparameter Tuning (Bayesian Optimization, Genetic Algorithms)Artificial Neural Networks (ANNs) Tuning"
},
{
"code": null,
"e": 1602,
"s": 1588,
"text": "Manual Search"
},
{
"code": null,
"e": 1616,
"s": 1602,
"text": "Random Search"
},
{
"code": null,
"e": 1628,
"s": 1616,
"text": "Grid Search"
},
{
"code": null,
"e": 1704,
"s": 1628,
"text": "Automated Hyperparameter Tuning (Bayesian Optimization, Genetic Algorithms)"
},
{
"code": null,
"e": 1745,
"s": 1704,
"text": "Artificial Neural Networks (ANNs) Tuning"
},
{
"code": null,
"e": 2211,
"s": 1745,
"text": "In order to demonstrate how to perform Hyperparameters Optimization in Python, I decided to perform a complete Data Analysis of the Credit Card Fraud Detection Kaggle Dataset. Our objective in this article will be to correctly classify which credit card transactions should be labelled as fraudulent or genuine (binary classification). This Dataset has been anonymized before being distributed, therefore, the meaning of most of the features has not been disclosed."
},
{
"code": null,
"e": 2556,
"s": 2211,
"text": "In this case, I decided to use just a subset of the dataset, in order to speed up training times and make sure to achieve a perfect balance between the two different classes. Additionally, just a limited amount of features has been used to make the optimization tasks more challenging. The final dataset is shown in the figure below (Figure 2)."
},
{
"code": null,
"e": 2659,
"s": 2556,
"text": "All the code used in this article (and more!) is available in my GitHub repository and Kaggle Profile."
},
{
"code": null,
"e": 2732,
"s": 2659,
"text": "First of all, we need to divide our dataset into training and test sets."
},
{
"code": null,
"e": 2822,
"s": 2732,
"text": "Throughout this article, we will use a Random Forest Classifier as our model to optimize."
},
{
"code": null,
"e": 3105,
"s": 2822,
"text": "Random Forest models are formed by a large number of uncorrelated decision trees, which joint together constitute an ensemble. In Random Forest, each decision tree makes its own prediction and the overall model output is selected to be the prediction which appeared most frequently."
},
{
"code": null,
"e": 3162,
"s": 3105,
"text": "We can now start by calculating our base model accuracy."
},
{
"code": null,
"e": 3502,
"s": 3162,
"text": "[[110 6] [ 6 118]] precision recall f1-score support 0 0.95 0.95 0.95 116 1 0.95 0.95 0.95 124 accuracy 0.95 240 macro avg 0.95 0.95 0.95 240weighted avg 0.95 0.95 0.95 240"
},
{
"code": null,
"e": 3695,
"s": 3502,
"text": "Using the Random Forest Classifier with the default scikit-learn parameters lead to 95% overall accuracy. Let’s see now if applying some optimization techniques we can achieve better accuracy."
},
{
"code": null,
"e": 3931,
"s": 3695,
"text": "When using Manual Search, we choose some model hyperparameters based on our judgment/experience. We then train the model, evaluate its accuracy and start the process again. This loop is repeated until a satisfactory accuracy is scored."
},
{
"code": null,
"e": 3991,
"s": 3931,
"text": "The main parameters used by a Random Forest Classifier are:"
},
{
"code": null,
"e": 4057,
"s": 3991,
"text": "criterion = the function used to evaluate the quality of a split."
},
{
"code": null,
"e": 4116,
"s": 4057,
"text": "max_depth = maximum number of levels allowed in each tree."
},
{
"code": null,
"e": 4192,
"s": 4116,
"text": "max_features = maximum number of features considered when splitting a node."
},
{
"code": null,
"e": 4273,
"s": 4192,
"text": "min_samples_leaf = minimum number of samples which can be stored in a tree leaf."
},
{
"code": null,
"e": 4364,
"s": 4273,
"text": "min_samples_split = minimum number of samples necessary in a node to cause node splitting."
},
{
"code": null,
"e": 4412,
"s": 4364,
"text": "n_estimators = number of trees in the ensemble."
},
{
"code": null,
"e": 4508,
"s": 4412,
"text": "More information about Random Forest parameters can be found on the scikit-learn Documentation."
},
{
"code": null,
"e": 4662,
"s": 4508,
"text": "As an example of Manual Search, I tried to specify the number of estimators in our model. Unfortunately, this didn’t lead to any improvement in accuracy."
},
{
"code": null,
"e": 5002,
"s": 4662,
"text": "[[110 6] [ 6 118]] precision recall f1-score support 0 0.95 0.95 0.95 116 1 0.95 0.95 0.95 124 accuracy 0.95 240 macro avg 0.95 0.95 0.95 240weighted avg 0.95 0.95 0.95 240"
},
{
"code": null,
"e": 5228,
"s": 5002,
"text": "In Random Search, we create a grid of hyperparameters and train/test our model on just some random combination of these hyperparameters. In this example, I additionally decided to perform Cross-Validation on the training set."
},
{
"code": null,
"e": 5598,
"s": 5228,
"text": "When performing Machine Learning tasks, we generally divide our dataset in training and test sets. This is done so that to test our model after having trained it (in this way we can check it’s performances when working with unseen data). When using Cross-Validation, we divide our training set into N other partitions to make sure our model is not overfitting our data."
},
{
"code": null,
"e": 6048,
"s": 5598,
"text": "One of the most common used Cross-Validation methods is K-Fold Validation. In K-Fold, we divide our training set into N partitions and then iteratively train our model using N-1 partitions and test it with the left-over partition (at each iteration we change the left-over partition). Once having trained N times the model we then average the training results obtained in each iteration to obtain our overall training performance results (Figure 3)."
},
{
"code": null,
"e": 6279,
"s": 6048,
"text": "Using Cross-Validation when implementing Hyperparameters optimization can be really important. In this way, we might avoid using some Hyperparameters which works really good on the training data but not so good with the test data."
},
{
"code": null,
"e": 6732,
"s": 6279,
"text": "We can now start implementing Random Search by first defying a grid of hyperparameters which will be randomly sampled when calling RandomizedSearchCV(). For this example, I decided to divide our training set into 4 Folds (cv = 4) and select 80 as the number of combinations to sample (n_iter = 80). Using the scikit-learn best_estimator_ attribute, we can then retrieve the set of hyperparameters which performed best during training to test our model."
},
{
"code": null,
"e": 6999,
"s": 6732,
"text": "Once trained our model, we can then visualize how changing some of its Hyperparameters can affect the overall model accuracy (Figure 4). In this case, I decided to observe how changing the number of estimators and the criterion can affect our Random Forest accuracy."
},
{
"code": null,
"e": 7290,
"s": 6999,
"text": "We can then take this a step further by making our visualization more interactive. In the chart below, we can examine (using the slider) how varying the number of estimators in our model can affect the overall accuracy of our model considered the selected min_split and min_leaf parameters."
},
{
"code": null,
"e": 7512,
"s": 7290,
"text": "Feel free to play with the graph below by changing the n_estimators parameters, zooming in and out of the graph, changing it’s orientation and hovering over the single data points to get additional information about them!"
},
{
"code": null,
"e": 7718,
"s": 7512,
"text": "If you are interested in finding out more about how to create these animations using Plotly, my code is available here. Additionally, this has also been covered in an article written by Xoel López Barata."
},
{
"code": null,
"e": 7888,
"s": 7718,
"text": "We can now evaluate how our model performed using Random Search. In this case, using Random Search leads to a consistent increase in accuracy compared to our base model."
},
{
"code": null,
"e": 8228,
"s": 7888,
"text": "[[115 1] [ 6 118]] precision recall f1-score support 0 0.95 0.99 0.97 116 1 0.99 0.95 0.97 124 accuracy 0.97 240 macro avg 0.97 0.97 0.97 240weighted avg 0.97 0.97 0.97 240"
},
{
"code": null,
"e": 8343,
"s": 8228,
"text": "In Grid Search, we set up a grid of hyperparameters and train/test our model on each of the possible combinations."
},
{
"code": null,
"e": 8541,
"s": 8343,
"text": "In order to choose the parameters to use in Grid Search, we can now look at which parameters worked best with Random Search and form a grid based on them to see if we can find a better combination."
},
{
"code": null,
"e": 8709,
"s": 8541,
"text": "Grid Search can be implemented in Python using scikit-learn GridSearchCV() function. Also on this occasion, I decided to divide our training set into 4 Folds (cv = 4)."
},
{
"code": null,
"e": 8975,
"s": 8709,
"text": "When using Grid Search, all the possible combinations of the parameters in the grid are tried. In this case, 128000 combinations (2 × 10 × 4 × 4 × 4 × 10) will be used during training. Instead, in the Grid Search example before, just 80 combinations have been used."
},
{
"code": null,
"e": 9315,
"s": 8975,
"text": "[[115 1] [ 7 117]] precision recall f1-score support 0 0.94 0.99 0.97 116 1 0.99 0.94 0.97 124 accuracy 0.97 240 macro avg 0.97 0.97 0.97 240weighted avg 0.97 0.97 0.97 240"
},
{
"code": null,
"e": 9550,
"s": 9315,
"text": "Grid Search is slower compared to Random Search but it can be overall more effective because it can go through the whole search space. Instead, Random Search can be faster fast but might miss some important points in the search space."
},
{
"code": null,
"e": 9737,
"s": 9550,
"text": "When using Automated Hyperparameter Tuning, the model hyperparameters to use are identified using techniques such as: Bayesian Optimization, Gradient Descent and Evolutionary Algorithms."
},
{
"code": null,
"e": 9995,
"s": 9737,
"text": "Bayesian Optimization can be performed in Python using the Hyperopt library. Bayesian optimization uses probability to find the minimum of a function. The final aim is to find the input value to a function which can give us the lowest possible output value."
},
{
"code": null,
"e": 10207,
"s": 9995,
"text": "Bayesian optimization has been proved to be more efficient than random, grid or manual search. Bayesian Optimization can, therefore, lead to better performance in the testing phase and reduced optimization time."
},
{
"code": null,
"e": 10316,
"s": 10207,
"text": "In Hyperopt, Bayesian Optimization can be implemented giving 3 three main parameters to the function fmin()."
},
{
"code": null,
"e": 10376,
"s": 10316,
"text": "Objective Function = defines the loss function to minimize."
},
{
"code": null,
"e": 10544,
"s": 10376,
"text": "Domain Space = defines the range of input values to test (in Bayesian Optimization this space creates a probability distribution for each of the used Hyperparameters)."
},
{
"code": null,
"e": 10667,
"s": 10544,
"text": "Optimization Algorithm = defines the search algorithm to use to select the best input values to use in each new iteration."
},
{
"code": null,
"e": 10757,
"s": 10667,
"text": "Additionally, can also be defined in fmin() the maximum number of evaluations to perform."
},
{
"code": null,
"e": 10998,
"s": 10757,
"text": "Bayesian Optimization can reduce the number of search iterations by choosing the input values bearing in mind the past outcomes. In this way, we can concentrate our search from the beginning on values which are closer to our desired output."
},
{
"code": null,
"e": 11278,
"s": 10998,
"text": "We can now run our Bayesian Optimizer using the fmin() function. A Trials() object is first created to make possible to visualize later what was going on while the fmin() function was running (eg. how the loss function was changing and how to used Hyperparameters were changing)."
},
{
"code": null,
"e": 11517,
"s": 11278,
"text": "100%|██████████| 80/80 [03:07<00:00, 2.02s/it, best loss: -0.9339285714285713]{'criterion': 1, 'max_depth': 120.0, 'max_features': 2, 'min_samples_leaf': 0.0006380325074247448, 'min_samples_split': 0.06603114636418073, 'n_estimators': 1}"
},
{
"code": null,
"e": 11832,
"s": 11517,
"text": "We can now retrieve the set of best parameters identified and test our model using the best dictionary created during training. Some of the parameters have been stored in the best dictionary numerically using indices, therefore, we need first to convert them back as strings before input them in our Random Forest."
},
{
"code": null,
"e": 11902,
"s": 11832,
"text": "The classification report using Bayesian Optimization is shown below."
},
{
"code": null,
"e": 12242,
"s": 11902,
"text": "[[114 2] [ 11 113]] precision recall f1-score support 0 0.91 0.98 0.95 116 1 0.98 0.91 0.95 124 accuracy 0.95 240 macro avg 0.95 0.95 0.95 240weighted avg 0.95 0.95 0.95 240"
},
{
"code": null,
"e": 12470,
"s": 12242,
"text": "Genetic Algorithms tries to apply natural selection mechanisms to Machine Learning contexts. They are inspired by the Darwinian process of Natural Selection and they are therefore also usually called as Evolutionary Algorithms."
},
{
"code": null,
"e": 13038,
"s": 12470,
"text": "Let’s imagine we create a population of N Machine Learning models with some predefined Hyperparameters. We can then calculate the accuracy of each model and decide to keep just half of the models (the ones that perform best). We can now generate some offsprings having similar Hyperparameters to the ones of the best models so that to get again a population of N models. At this point, we can again calculate the accuracy of each model and repeat the cycle for a defined number of generations. In this way, just the best models will survive at the end of the process."
},
{
"code": null,
"e": 13249,
"s": 13038,
"text": "In order to implement Genetic Algorithms in Python, we can use the TPOT Auto Machine Learning library. TPOT is built on the scikit-learn library and it can be used for either regression or classification tasks."
},
{
"code": null,
"e": 13365,
"s": 13249,
"text": "The training report and the best parameters identified using Genetic Algorithms are shown in the following snippet."
},
{
"code": null,
"e": 13880,
"s": 13365,
"text": "Generation 1 - Current best internal CV score: 0.9392857142857143Generation 2 - Current best internal CV score: 0.9392857142857143Generation 3 - Current best internal CV score: 0.9392857142857143Generation 4 - Current best internal CV score: 0.9392857142857143Generation 5 - Current best internal CV score: 0.9392857142857143Best pipeline: RandomForestClassifier(CombineDFs(input_matrix, input_matrix), criterion=entropy, max_depth=406, max_features=log2, min_samples_leaf=4, min_samples_split=5, n_estimators=617)"
},
{
"code": null,
"e": 13972,
"s": 13880,
"text": "The overall accuracy of our Random Forest Genetic Algorithm optimized model is shown below."
},
{
"code": null,
"e": 13991,
"s": 13972,
"text": "0.9708333333333333"
},
{
"code": null,
"e": 14434,
"s": 13991,
"text": "Using KerasClassifier wrapper, it is possible to apply Grid Search and Random Search for Deep Learning models in the same way it was done when using scikit-learn Machine Learning models. In the following example, we will try to optimize some of our ANN parameters such as: how many neurons to use in each layer and which activation function and optimizer to use. More examples of Deep Learning Hyperparameters optimization are available here."
},
{
"code": null,
"e": 14529,
"s": 14434,
"text": "Max Accuracy Registred: 0.932 using {'activation': 'relu', 'neurons': 35, 'optimizer': 'Adam'}"
},
{
"code": null,
"e": 14622,
"s": 14529,
"text": "The overall accuracy scored using our Artificial Neural Network (ANN) can be observed below."
},
{
"code": null,
"e": 14962,
"s": 14622,
"text": "[[115 1] [ 8 116]] precision recall f1-score support 0 0.93 0.99 0.96 116 1 0.99 0.94 0.96 124 accuracy 0.96 240 macro avg 0.96 0.96 0.96 240weighted avg 0.96 0.96 0.96 240"
},
{
"code": null,
"e": 15128,
"s": 14962,
"text": "We can now compare how all the different optimization techniques performed on this given exercise. Overall, Random Search and Evolutionary Algorithms performed best."
},
{
"code": null,
"e": 15389,
"s": 15128,
"text": "Base Accuracy vs Manual Search 0.0000%.Base Accuracy vs Random Search 2.1930%.Base Accuracy vs Grid Search 1.7544%.Base Accuracy vs Bayesian Optimization Accuracy -0.4386%.Base Accuracy vs Evolutionary Algorithms 2.1930%.Base Accuracy vs Optimized ANN 1.3158%."
},
{
"code": null,
"e": 15578,
"s": 15389,
"text": "The results obtained, are highly dependent on the chosen grid space and dataset used. Therefore, in different situations, different optimization techniques will perform better than others."
},
{
"code": null,
"e": 15634,
"s": 15578,
"text": "I hope you enjoyed this article, thank you for reading!"
},
{
"code": null,
"e": 15792,
"s": 15634,
"text": "If you want to keep updated with my latest articles and projects follow me on Medium and subscribe to my mailing list. These are some of my contacts details:"
},
{
"code": null,
"e": 15801,
"s": 15792,
"text": "Linkedin"
},
{
"code": null,
"e": 15815,
"s": 15801,
"text": "Personal Blog"
},
{
"code": null,
"e": 15832,
"s": 15815,
"text": "Personal Website"
},
{
"code": null,
"e": 15847,
"s": 15832,
"text": "Medium Profile"
},
{
"code": null,
"e": 15854,
"s": 15847,
"text": "GitHub"
},
{
"code": null,
"e": 15861,
"s": 15854,
"text": "Kaggle"
},
{
"code": null,
"e": 16021,
"s": 15861,
"text": "[1] Hyperparameter optimization: Explanation of automatized algorithms, Dawid Kopczyk. Accessed at: https://dkopczyk.quantee.co.uk/hyperparameter-optimization/"
}
] |
How to resize an image in Node Jimp? | NodeJS – Resize() is an inbuilt function that is used to resize the images to the desired size. We can use resize to set the height and width using a 2-pass bilinear algorithm. It can resize an image into any size as declared by the user. We can take input from the user or resize it into fixed Width*Height size.
resize(w, h, mode, cb)
w – This parameter is used to declare the width of the image. This is a required parameter.
w – This parameter is used to declare the width of the image. This is a required parameter.
h – This parameter is used to declare the height of the resized image. This parameter is also required.
h – This parameter is used to declare the height of the resized image. This parameter is also required.
mode – This is an optional parameter that is used to store the scaling method.
mode – This is an optional parameter that is used to store the scaling method.
cb – This is also an optional parameter that can be invoked after the compilation is complete.
cb – This is also an optional parameter that can be invoked after the compilation is complete.
Before proceeding to use resize() functions, please check that the following statements are already executed for setting up the environment.
npm init -y // Initialising the Node environment
npm init -y // Initialising the Node environment
npm install jimp --save // Installing the jimp dependency
npm install jimp --save // Installing the jimp dependency
Create a resize.js file and copy-paste the following code snippet in it.
Create a resize.js file and copy-paste the following code snippet in it.
Use node resize.js to run the code.
Use node resize.js to run the code.
Note – The method name should match with the JS file name. Only then it will be able to call the desired method.
const Jimp = require('jimp');
async function resize() { // Function name is same as of file name
// Reading Image
const image = await Jimp.read
('/home/jimp/tutorials_point_img.jpg');
image.resize(200,200, function(err){
if (err) throw err;
})
.write('/home/jimp/resize.jpeg');
}
resize(); // Calling the function here using async
console.log("Image is processed successfully");
const Jimp = require('jimp') ;
async function resize() {
// Reading Image
const image = await Jimp.read
('/home/jimp/tutorials_point_img.jpg');
// Used RESIZE_BEZIER as cb for finer images
image.resize(1024,768,Jimp.RESIZE_BEZIER, function(err){
if (err) throw err;
})
.write('/home/jimp/resize.jpeg');
}
resize();
console.log("Image is processed successfully"); | [
{
"code": null,
"e": 1376,
"s": 1062,
"text": "NodeJS – Resize() is an inbuilt function that is used to resize the images to the desired size. We can use resize to set the height and width using a 2-pass bilinear algorithm. It can resize an image into any size as declared by the user. We can take input from the user or resize it into fixed Width*Height size."
},
{
"code": null,
"e": 1399,
"s": 1376,
"text": "resize(w, h, mode, cb)"
},
{
"code": null,
"e": 1491,
"s": 1399,
"text": "w – This parameter is used to declare the width of the image. This is a required parameter."
},
{
"code": null,
"e": 1583,
"s": 1491,
"text": "w – This parameter is used to declare the width of the image. This is a required parameter."
},
{
"code": null,
"e": 1687,
"s": 1583,
"text": "h – This parameter is used to declare the height of the resized image. This parameter is also required."
},
{
"code": null,
"e": 1791,
"s": 1687,
"text": "h – This parameter is used to declare the height of the resized image. This parameter is also required."
},
{
"code": null,
"e": 1870,
"s": 1791,
"text": "mode – This is an optional parameter that is used to store the scaling method."
},
{
"code": null,
"e": 1949,
"s": 1870,
"text": "mode – This is an optional parameter that is used to store the scaling method."
},
{
"code": null,
"e": 2044,
"s": 1949,
"text": "cb – This is also an optional parameter that can be invoked after the compilation is complete."
},
{
"code": null,
"e": 2139,
"s": 2044,
"text": "cb – This is also an optional parameter that can be invoked after the compilation is complete."
},
{
"code": null,
"e": 2280,
"s": 2139,
"text": "Before proceeding to use resize() functions, please check that the following statements are already executed for setting up the environment."
},
{
"code": null,
"e": 2329,
"s": 2280,
"text": "npm init -y // Initialising the Node environment"
},
{
"code": null,
"e": 2378,
"s": 2329,
"text": "npm init -y // Initialising the Node environment"
},
{
"code": null,
"e": 2436,
"s": 2378,
"text": "npm install jimp --save // Installing the jimp dependency"
},
{
"code": null,
"e": 2494,
"s": 2436,
"text": "npm install jimp --save // Installing the jimp dependency"
},
{
"code": null,
"e": 2567,
"s": 2494,
"text": "Create a resize.js file and copy-paste the following code snippet in it."
},
{
"code": null,
"e": 2640,
"s": 2567,
"text": "Create a resize.js file and copy-paste the following code snippet in it."
},
{
"code": null,
"e": 2676,
"s": 2640,
"text": "Use node resize.js to run the code."
},
{
"code": null,
"e": 2712,
"s": 2676,
"text": "Use node resize.js to run the code."
},
{
"code": null,
"e": 2825,
"s": 2712,
"text": "Note – The method name should match with the JS file name. Only then it will be able to call the desired method."
},
{
"code": null,
"e": 3230,
"s": 2825,
"text": "const Jimp = require('jimp');\n\nasync function resize() { // Function name is same as of file name\n // Reading Image\n const image = await Jimp.read\n ('/home/jimp/tutorials_point_img.jpg');\n image.resize(200,200, function(err){\n if (err) throw err;\n })\n .write('/home/jimp/resize.jpeg');\n}\n\nresize(); // Calling the function here using async\nconsole.log(\"Image is processed successfully\");"
},
{
"code": null,
"e": 3621,
"s": 3230,
"text": "const Jimp = require('jimp') ;\nasync function resize() {\n // Reading Image\n const image = await Jimp.read\n ('/home/jimp/tutorials_point_img.jpg');\n // Used RESIZE_BEZIER as cb for finer images\n image.resize(1024,768,Jimp.RESIZE_BEZIER, function(err){\n if (err) throw err;\n })\n .write('/home/jimp/resize.jpeg');\n}\n\nresize();\nconsole.log(\"Image is processed successfully\");"
}
] |
Display Month in MMMM format in Java | The MMMM format for months is like entire month name: January, February, March, etc. We will use it like this.
SimpleDateFormat("MMM");
Let us see an example.
// displaying month in MMMM format SimpleDateFormat simpleformat = new SimpleDateFormat("MMMM");
String strMonth= simpleformat.format(new Date());
System.out.println("Month in MMMM format = "+strMonth);
Above, we have used the SimpleDateFormat class, therefore the following package is imported.
import java.text.SimpleDateFormat;
The following is an example.
Live Demo
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Calendar;
public class Demo {
public static void main(String[] args) throws Exception {
// displaying current date and time
Calendar cal = Calendar.getInstance();
SimpleDateFormat simpleformat = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss");
System.out.println("Date and time = "+simpleformat.format(cal.getTime()));
// displaying date
simpleformat = new SimpleDateFormat("dd/MMMM/yyyy");
String str = simpleformat.format(new Date());
System.out.println("Current Date = "+str);
// displaying month in MMMM format
simpleformat = new SimpleDateFormat("MMMM");
String strMonth= simpleformat.format(new Date());
System.out.println("Month in MMMM format = "+strMonth);
// current time
simpleformat = new SimpleDateFormat("HH.mm.ss");
String strTime = simpleformat.format(new Date());
System.out.println("Current Time = "+strTime);
}
}
Date and time = Mon, 26 Nov 2018 10:46:10
Current Date = 26/November/2018
Month in MMMM format = November
Current Time = 10.46.10 | [
{
"code": null,
"e": 1173,
"s": 1062,
"text": "The MMMM format for months is like entire month name: January, February, March, etc. We will use it like this."
},
{
"code": null,
"e": 1198,
"s": 1173,
"text": "SimpleDateFormat(\"MMM\");"
},
{
"code": null,
"e": 1221,
"s": 1198,
"text": "Let us see an example."
},
{
"code": null,
"e": 1424,
"s": 1221,
"text": "// displaying month in MMMM format SimpleDateFormat simpleformat = new SimpleDateFormat(\"MMMM\");\nString strMonth= simpleformat.format(new Date());\nSystem.out.println(\"Month in MMMM format = \"+strMonth);"
},
{
"code": null,
"e": 1517,
"s": 1424,
"text": "Above, we have used the SimpleDateFormat class, therefore the following package is imported."
},
{
"code": null,
"e": 1552,
"s": 1517,
"text": "import java.text.SimpleDateFormat;"
},
{
"code": null,
"e": 1581,
"s": 1552,
"text": "The following is an example."
},
{
"code": null,
"e": 1592,
"s": 1581,
"text": " Live Demo"
},
{
"code": null,
"e": 2626,
"s": 1592,
"text": "import java.text.Format;\nimport java.text.SimpleDateFormat;\nimport java.util.Date;\nimport java.util.Calendar;\npublic class Demo {\n public static void main(String[] args) throws Exception {\n // displaying current date and time\n Calendar cal = Calendar.getInstance();\n SimpleDateFormat simpleformat = new SimpleDateFormat(\"E, dd MMM yyyy HH:mm:ss\");\n System.out.println(\"Date and time = \"+simpleformat.format(cal.getTime()));\n // displaying date\n simpleformat = new SimpleDateFormat(\"dd/MMMM/yyyy\");\n String str = simpleformat.format(new Date());\n System.out.println(\"Current Date = \"+str);\n // displaying month in MMMM format\n simpleformat = new SimpleDateFormat(\"MMMM\");\n String strMonth= simpleformat.format(new Date());\n System.out.println(\"Month in MMMM format = \"+strMonth);\n // current time\n simpleformat = new SimpleDateFormat(\"HH.mm.ss\");\n String strTime = simpleformat.format(new Date());\n System.out.println(\"Current Time = \"+strTime);\n }\n}"
},
{
"code": null,
"e": 2756,
"s": 2626,
"text": "Date and time = Mon, 26 Nov 2018 10:46:10\nCurrent Date = 26/November/2018\nMonth in MMMM format = November\nCurrent Time = 10.46.10"
}
] |
Subsets and Splits