title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
Access Modifiers in C++
|
Access Modifiers are used to implement data hiding in object oriented programming. There are three types of access modifiers used in C++. These are public, private and protected. Details about these are given as follows.
The data members and member functions in a class that are declared public are available to everyone, including other classes. They can be accessed from any place in the program using the dot operator with the class object.
A program that demonstrates public access specifier is given as follows.
Live Demo
#include<iostream>
using namespace std;
class Add {
public:
int a, b;
void sum() {
cout<<"Sum of "<< a <<" and "<< b <<" is "<<a+b;
}
};
int main() {
Add obj;
obj.a = 2;
obj.b = 5;
obj.sum();
return 0;
}
Sum of 2 and 5 is 7
In the above program, the class Add has two public data members a and b. The function sum() displays the sum of a and b. This is seen below.
class Add {
public:
int a, b;
void sum() {
cout<<"Sum of "<< a <<" and "<< b <<" is "<<a+b;
}
};
In the function main(), the object of class Add is created. Then a and b are initialized in main(). This can be done because they are public data types. Finally sum() is called that displays the sum of a and b. This is shown below.
Add obj;
obj.a = 2;
obj.b = 5;
obj.sum();
The data members that are declared private are only accessible from the functions inside the class and not by any functions outside the class. Friend functions can also access the private data members of a class.
A program that demonstrates private access modifier is given as follows.
Live Demo
#include<iostream>
using namespace std;
class Add {
private:
int a, b;
public:
void setdata(int x, int y) {
a = x;
b = y;
}
void sum() {
cout<<"Sum of "<< a <<" and "<< b <<" is "<<a+b;
}
};
int main() {
Add obj;
obj.setdata(9,5);
obj.sum();
return 0;
}
Sum of 9 and 5 is 14
In the above program, the class Add has two private data members a and b. The function setdata() provides the values of a and b as they are private variables. The function sum() displays the sum of a and b. This is seen below.
class Add {
private:
int a, b;
public:
void setdata(int x, int y) {
a = x;
b = y;
}
void sum() {
cout<<"Sum of "<< a <<" and "<< b <<" is "<<a+b;
}
};
In the function main(), the object of class Add is created. Then the function setdata() is called to initialize a and b as they are private variables. Finally sum() is called that displays the sum of a and b. This is shown below.
Add obj;
obj.setdata(9,5);
obj.sum();
The data members of the class that are declared protected are similar to those declared private. They cannot be directly accessed outside the class but they can be accessed by the derived class of the base class.
A program that demonstrates protected access modifier in C++ is as follows β
Live Demo
#include<iostream>
using namespace std;
class Parent {
protected:
int a, b;
};
class Child: public Parent {
public:
void getdata(int x, int y) {
a=x;
b=y;
}
void putdata() {
cout<<"a = "<<a<<endl;
cout<<"b = "<<b<<endl;
}
};
int main() {
Child obj;
obj.getdata(9,1);
obj.putdata();
return 0;
}
a = 9
b = 1
In the above program, the parent class has two protected variables a and b. This is shown below.
class Parent {
protected:
int a, b;
};
The Child class has two functions getdata() and putdata() that take the values of a and b and display them respectively. These functions can do this as a and b are protected variables and Child is a derived class of Parent. The code snippet for this is given below β
class Child: public Parent {
public:
void getdata(int x, int y) {
a = x;
b = y;
}
void putdata() {
cout<<"a = "<<a<<endl;
cout<<"b = "<<b<<endl;
}
};
In the function main(), an object obj of Child class is created. Then the functions getdata() and putdata() are called. This is shown below.
Child obj;
obj.getdata(9,1);
obj.putdata();
|
[
{
"code": null,
"e": 1283,
"s": 1062,
"text": "Access Modifiers are used to implement data hiding in object oriented programming. There are three types of access modifiers used in C++. These are public, private and protected. Details about these are given as follows."
},
{
"code": null,
"e": 1506,
"s": 1283,
"text": "The data members and member functions in a class that are declared public are available to everyone, including other classes. They can be accessed from any place in the program using the dot operator with the class object."
},
{
"code": null,
"e": 1579,
"s": 1506,
"text": "A program that demonstrates public access specifier is given as follows."
},
{
"code": null,
"e": 1590,
"s": 1579,
"text": " Live Demo"
},
{
"code": null,
"e": 1827,
"s": 1590,
"text": "#include<iostream>\nusing namespace std;\nclass Add {\n public:\n int a, b;\n void sum() {\n cout<<\"Sum of \"<< a <<\" and \"<< b <<\" is \"<<a+b;\n }\n};\nint main() {\n Add obj;\n obj.a = 2;\n obj.b = 5;\n obj.sum();\n return 0;\n}"
},
{
"code": null,
"e": 1847,
"s": 1827,
"text": "Sum of 2 and 5 is 7"
},
{
"code": null,
"e": 1988,
"s": 1847,
"text": "In the above program, the class Add has two public data members a and b. The function sum() displays the sum of a and b. This is seen below."
},
{
"code": null,
"e": 2103,
"s": 1988,
"text": "class Add {\n public:\n int a, b;\n void sum() {\n cout<<\"Sum of \"<< a <<\" and \"<< b <<\" is \"<<a+b;\n }\n};"
},
{
"code": null,
"e": 2335,
"s": 2103,
"text": "In the function main(), the object of class Add is created. Then a and b are initialized in main(). This can be done because they are public data types. Finally sum() is called that displays the sum of a and b. This is shown below."
},
{
"code": null,
"e": 2378,
"s": 2335,
"text": "Add obj;\nobj.a = 2;\nobj.b = 5;\n\nobj.sum();"
},
{
"code": null,
"e": 2591,
"s": 2378,
"text": "The data members that are declared private are only accessible from the functions inside the class and not by any functions outside the class. Friend functions can also access the private data members of a class."
},
{
"code": null,
"e": 2664,
"s": 2591,
"text": "A program that demonstrates private access modifier is given as follows."
},
{
"code": null,
"e": 2675,
"s": 2664,
"text": " Live Demo"
},
{
"code": null,
"e": 2980,
"s": 2675,
"text": "#include<iostream>\nusing namespace std;\nclass Add {\n private:\n int a, b;\n public:\n void setdata(int x, int y) {\n a = x;\n b = y;\n }\n void sum() {\n cout<<\"Sum of \"<< a <<\" and \"<< b <<\" is \"<<a+b;\n }\n};\nint main() {\n Add obj;\n obj.setdata(9,5);\n obj.sum();\n return 0;\n}"
},
{
"code": null,
"e": 3001,
"s": 2980,
"text": "Sum of 9 and 5 is 14"
},
{
"code": null,
"e": 3228,
"s": 3001,
"text": "In the above program, the class Add has two private data members a and b. The function setdata() provides the values of a and b as they are private variables. The function sum() displays the sum of a and b. This is seen below."
},
{
"code": null,
"e": 3418,
"s": 3228,
"text": "class Add {\n private:\n int a, b;\n public:\n void setdata(int x, int y) {\n a = x;\n b = y;\n }\n void sum() {\n cout<<\"Sum of \"<< a <<\" and \"<< b <<\" is \"<<a+b;\n }\n};"
},
{
"code": null,
"e": 3648,
"s": 3418,
"text": "In the function main(), the object of class Add is created. Then the function setdata() is called to initialize a and b as they are private variables. Finally sum() is called that displays the sum of a and b. This is shown below."
},
{
"code": null,
"e": 3686,
"s": 3648,
"text": "Add obj;\nobj.setdata(9,5);\nobj.sum();"
},
{
"code": null,
"e": 3899,
"s": 3686,
"text": "The data members of the class that are declared protected are similar to those declared private. They cannot be directly accessed outside the class but they can be accessed by the derived class of the base class."
},
{
"code": null,
"e": 3976,
"s": 3899,
"text": "A program that demonstrates protected access modifier in C++ is as follows β"
},
{
"code": null,
"e": 3987,
"s": 3976,
"text": " Live Demo"
},
{
"code": null,
"e": 4338,
"s": 3987,
"text": "#include<iostream>\nusing namespace std;\nclass Parent {\n protected:\n int a, b;\n};\nclass Child: public Parent {\n public:\n void getdata(int x, int y) {\n a=x;\n b=y;\n }\n void putdata() {\n cout<<\"a = \"<<a<<endl;\n cout<<\"b = \"<<b<<endl;\n }\n};\nint main() {\n Child obj;\n obj.getdata(9,1);\n obj.putdata();\n return 0;\n}"
},
{
"code": null,
"e": 4350,
"s": 4338,
"text": "a = 9\nb = 1"
},
{
"code": null,
"e": 4447,
"s": 4350,
"text": "In the above program, the parent class has two protected variables a and b. This is shown below."
},
{
"code": null,
"e": 4492,
"s": 4447,
"text": "class Parent {\n protected:\n int a, b;\n};"
},
{
"code": null,
"e": 4759,
"s": 4492,
"text": "The Child class has two functions getdata() and putdata() that take the values of a and b and display them respectively. These functions can do this as a and b are protected variables and Child is a derived class of Parent. The code snippet for this is given below β"
},
{
"code": null,
"e": 4948,
"s": 4759,
"text": "class Child: public Parent {\n public:\n void getdata(int x, int y) {\n a = x;\n b = y;\n }\n void putdata() {\n cout<<\"a = \"<<a<<endl;\n cout<<\"b = \"<<b<<endl;\n }\n};"
},
{
"code": null,
"e": 5089,
"s": 4948,
"text": "In the function main(), an object obj of Child class is created. Then the functions getdata() and putdata() are called. This is shown below."
},
{
"code": null,
"e": 5133,
"s": 5089,
"text": "Child obj;\nobj.getdata(9,1);\nobj.putdata();"
}
] |
Binary String | Practice | GeeksforGeeks
|
Given a binary string S. The task is to count the number of substrings that start and end with 1. For example, if the input string is β00100101β, then there are three substrings β1001β, β100101β and β101β.
Example 1:
Input:
N = 4
S = 1111
Output: 6
Explanation: There are 6 substrings from
the given string. They are 11, 11, 11,
111, 111, 1111.
Example 2:
Input:
N = 5
S = 01101
Output: 3
Explanation: There 3 substrings from the
given string. They are 11, 101, 1101.
Your Task:
The task is to complete the function binarySubstring() which takes the length of binary string n and a binary string a as input parameter and counts the number of substrings starting and ending with 1 and returns the count.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(1).
Constraints:
1 β€ |S| β€ 104
+1
divyabhatia5191 week ago
public static int binarySubstring(int a, String str) { // Your code here int count=0; for(int i=0;i<a;i++){ if(str.charAt(i)=='1'){ count++; } } return (count*(count-1))/2; }
+1
visitant1 week ago
If you realize it is a combinatorics problem then you just need to count number of β1βs and return nC2 = n * (n-1)/2;
long binarySubstring(int n, string a){
// Your code here
int count = 0;
for(int i=0; i<n ; i++)
{
if(a[i]=='1')
{
count++;
}
}
return count*(count-1)/2;
}
+2
sunghunet1 month ago
# More pythonic way
# It takes 0.0 / 1.0 [Total Time Taken].
def binarySubstring(self,n,s):
cnt = s.count('1')
return cnt*(cnt-1) // 2
+1
jagannath23sahoo1 month ago
//Function to count the number of substrings that start and end with
long binarySubstring(int n, string a){
long c = 0;
//We need to select 2 1s out of count so nC2 n(n-1)/2;
for(auto x : a)
{
if(x == '1')
c++;
}
return (c*(c-1))/2;
}
+1
anuragraj5731 month ago
PYTHON SOLUTION:
class Solution: def binarySubstring(self,n,s): count = 0 for i in range(n): if(s[i]=='1'): count=count+1 return (count*(count-1))//2
0
rajhans1 month ago
its based on maths selection problem. in simple words we have to select two 1s out of total count for which maths formula is n C 2 = n(n-1)/2 int count=0; for(int i=0;i<a;i++){ if(str.charAt(i)=='1'){ count++; } } return (count*(count-1))/2;
+3
parthmalhotra2 months ago
JAVA Solution
Approach : If we consider an index i of the string where character at the index i is 1, all the 1s before it will contribute a substring that ends at the current index i.
So we keep counting the no of 1s occurring before the current index (i.e. the substrings ending at current index) and add that value to the result.
public static int binarySubstring(int a, String str)
{
//the result
int res = 0;
//count variable specifying how many 1s are there before the given 1
//initializing as -1, since for the first 1, value will become 0 on incrementing count
int count = -1;
//looping over the string
for(int i= 0; i<a; i++){
//if char '1' is found
if(str.charAt(i)=='1'){
//increment count
count++;
//add count to result
res+=count;
}
}
return res;
}
0
singhdipranjan672 months ago
class Solution
{
//Function to count the number of substrings that start and end with 1.
public static int binarySubstring(int a, String str)
{
int count=0;
for(int i=0; i<a; i++)
{
if(str.charAt(i)=='1')
count++;
}
return count*(count-1)/2;
}
}
0
ultradluffy82 months ago
based on discrete mathematics :
long binarySubstring(int n, string a){
// Your code here
int cnt=0;
for(auto x:a){
if(x == '1')cnt++;
}
return (cnt * (cnt-1))/2;
}
0
tarunkanade2 months ago
0.5/1.8
public static int binarySubstring(int a, String str)
{
// Your code here
int count1 = 0, res = 0;
for(int i = 0; i < a; i++){
if(str.charAt(i) == '1'){
res += count1;
count1++;
}
}
return res;
}
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
|
[
{
"code": null,
"e": 444,
"s": 238,
"text": "Given a binary string S. The task is to count the number of substrings that start and end with 1. For example, if the input string is β00100101β, then there are three substrings β1001β, β100101β and β101β."
},
{
"code": null,
"e": 455,
"s": 444,
"text": "Example 1:"
},
{
"code": null,
"e": 583,
"s": 455,
"text": "Input:\nN = 4\nS = 1111\nOutput: 6\nExplanation: There are 6 substrings from\nthe given string. They are 11, 11, 11,\n111, 111, 1111."
},
{
"code": null,
"e": 594,
"s": 583,
"text": "Example 2:"
},
{
"code": null,
"e": 706,
"s": 594,
"text": "Input:\nN = 5\nS = 01101\nOutput: 3\nExplanation: There 3 substrings from the\ngiven string. They are 11, 101, 1101."
},
{
"code": null,
"e": 941,
"s": 706,
"text": "Your Task:\nThe task is to complete the function binarySubstring() which takes the length of binary string n and a binary string a as input parameter and counts the number of substrings starting and ending with 1 and returns the count."
},
{
"code": null,
"e": 1005,
"s": 941,
"text": "Expected Time Complexity: O(N).\nExpected Auxiliary Space: O(1)."
},
{
"code": null,
"e": 1032,
"s": 1005,
"text": "Constraints:\n1 β€ |S| β€ 104"
},
{
"code": null,
"e": 1035,
"s": 1032,
"text": "+1"
},
{
"code": null,
"e": 1060,
"s": 1035,
"text": "divyabhatia5191 week ago"
},
{
"code": null,
"e": 1302,
"s": 1060,
"text": "public static int binarySubstring(int a, String str) { // Your code here int count=0; for(int i=0;i<a;i++){ if(str.charAt(i)=='1'){ count++; } } return (count*(count-1))/2; }"
},
{
"code": null,
"e": 1305,
"s": 1302,
"text": "+1"
},
{
"code": null,
"e": 1324,
"s": 1305,
"text": "visitant1 week ago"
},
{
"code": null,
"e": 1442,
"s": 1324,
"text": "If you realize it is a combinatorics problem then you just need to count number of β1βs and return nC2 = n * (n-1)/2;"
},
{
"code": null,
"e": 1719,
"s": 1442,
"text": "long binarySubstring(int n, string a){\n \n // Your code here\n int count = 0;\n for(int i=0; i<n ; i++)\n {\n if(a[i]=='1')\n {\n count++;\n }\n }\n return count*(count-1)/2;\n \n }"
},
{
"code": null,
"e": 1722,
"s": 1719,
"text": "+2"
},
{
"code": null,
"e": 1743,
"s": 1722,
"text": "sunghunet1 month ago"
},
{
"code": null,
"e": 1906,
"s": 1743,
"text": " # More pythonic way\n # It takes 0.0 / 1.0 [Total Time Taken].\n def binarySubstring(self,n,s):\n cnt = s.count('1')\n return cnt*(cnt-1) // 2"
},
{
"code": null,
"e": 1909,
"s": 1906,
"text": "+1"
},
{
"code": null,
"e": 1937,
"s": 1909,
"text": "jagannath23sahoo1 month ago"
},
{
"code": null,
"e": 2283,
"s": 1937,
"text": " //Function to count the number of substrings that start and end with \n long binarySubstring(int n, string a){\n \n long c = 0;\n //We need to select 2 1s out of count so nC2 n(n-1)/2;\n for(auto x : a)\n {\n if(x == '1') \n c++;\n }\n return (c*(c-1))/2;\n \n }"
},
{
"code": null,
"e": 2286,
"s": 2283,
"text": "+1"
},
{
"code": null,
"e": 2310,
"s": 2286,
"text": "anuragraj5731 month ago"
},
{
"code": null,
"e": 2327,
"s": 2310,
"text": "PYTHON SOLUTION:"
},
{
"code": null,
"e": 2504,
"s": 2327,
"text": "class Solution: def binarySubstring(self,n,s): count = 0 for i in range(n): if(s[i]=='1'): count=count+1 return (count*(count-1))//2"
},
{
"code": null,
"e": 2506,
"s": 2504,
"text": "0"
},
{
"code": null,
"e": 2525,
"s": 2506,
"text": "rajhans1 month ago"
},
{
"code": null,
"e": 2832,
"s": 2525,
"text": "its based on maths selection problem. in simple words we have to select two 1s out of total count for which maths formula is n C 2 = n(n-1)/2 int count=0; for(int i=0;i<a;i++){ if(str.charAt(i)=='1'){ count++; } } return (count*(count-1))/2;"
},
{
"code": null,
"e": 2835,
"s": 2832,
"text": "+3"
},
{
"code": null,
"e": 2861,
"s": 2835,
"text": "parthmalhotra2 months ago"
},
{
"code": null,
"e": 2875,
"s": 2861,
"text": "JAVA Solution"
},
{
"code": null,
"e": 3047,
"s": 2875,
"text": "Approach : If we consider an index i of the string where character at the index i is 1, all the 1s before it will contribute a substring that ends at the current index i. "
},
{
"code": null,
"e": 3195,
"s": 3047,
"text": "So we keep counting the no of 1s occurring before the current index (i.e. the substrings ending at current index) and add that value to the result."
},
{
"code": null,
"e": 3835,
"s": 3197,
"text": "public static int binarySubstring(int a, String str)\n {\n //the result \n int res = 0;\n \n //count variable specifying how many 1s are there before the given 1\n //initializing as -1, since for the first 1, value will become 0 on incrementing count\n int count = -1;\n \n //looping over the string\n for(int i= 0; i<a; i++){\n //if char '1' is found\n if(str.charAt(i)=='1'){\n //increment count\n count++;\n //add count to result\n res+=count;\n }\n }\n \n return res;\n }"
},
{
"code": null,
"e": 3837,
"s": 3835,
"text": "0"
},
{
"code": null,
"e": 3866,
"s": 3837,
"text": "singhdipranjan672 months ago"
},
{
"code": null,
"e": 4193,
"s": 3866,
"text": "class Solution\n{\n //Function to count the number of substrings that start and end with 1.\n public static int binarySubstring(int a, String str)\n {\n int count=0;\n for(int i=0; i<a; i++)\n {\n if(str.charAt(i)=='1')\n count++;\n }\n return count*(count-1)/2;\n \n }\n}"
},
{
"code": null,
"e": 4195,
"s": 4193,
"text": "0"
},
{
"code": null,
"e": 4220,
"s": 4195,
"text": "ultradluffy82 months ago"
},
{
"code": null,
"e": 4252,
"s": 4220,
"text": "based on discrete mathematics :"
},
{
"code": null,
"e": 4449,
"s": 4252,
"text": "long binarySubstring(int n, string a){\n \n // Your code here\n int cnt=0;\n for(auto x:a){\n if(x == '1')cnt++;\n }\n return (cnt * (cnt-1))/2;\n }"
},
{
"code": null,
"e": 4451,
"s": 4449,
"text": "0"
},
{
"code": null,
"e": 4475,
"s": 4451,
"text": "tarunkanade2 months ago"
},
{
"code": null,
"e": 4791,
"s": 4475,
"text": "0.5/1.8\npublic static int binarySubstring(int a, String str)\n {\n // Your code here\n int count1 = 0, res = 0;\n \n for(int i = 0; i < a; i++){\n if(str.charAt(i) == '1'){\n res += count1;\n count1++;\n }\n }\n return res;\n }"
},
{
"code": null,
"e": 4937,
"s": 4791,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 4973,
"s": 4937,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 4983,
"s": 4973,
"text": "\nProblem\n"
},
{
"code": null,
"e": 4993,
"s": 4983,
"text": "\nContest\n"
},
{
"code": null,
"e": 5056,
"s": 4993,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 5204,
"s": 5056,
"text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 5412,
"s": 5204,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints."
},
{
"code": null,
"e": 5518,
"s": 5412,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
C library function - fputs()
|
The C library function int fputs(const char *str, FILE *stream) writes a string to the specified stream up to but not including the null character.
Following is the declaration for fputs() function.
int fputs(const char *str, FILE *stream)
str β This is an array containing the null-terminated sequence of characters to be written.
str β This is an array containing the null-terminated sequence of characters to be written.
stream β This is the pointer to a FILE object that identifies the stream where the string is to be written.
stream β This is the pointer to a FILE object that identifies the stream where the string is to be written.
This function returns a non-negative value, or else on error it returns EOF.
The following example shows the usage of fputs() function.
#include <stdio.h>
int main () {
FILE *fp;
fp = fopen("file.txt", "w+");
fputs("This is c programming.", fp);
fputs("This is a system programming language.", fp);
fclose(fp);
return(0);
}
Let us compile and run the above program, this will create a file file.txt with the following content β
This is c programming.This is a system programming language.
Now let's see the content of the above file using the following program β
#include <stdio.h>
int main () {
FILE *fp;
int c;
fp = fopen("file.txt","r");
while(1) {
c = fgetc(fp);
if( feof(fp) ) {
break ;
}
printf("%c", c);
}
fclose(fp);
return(0);
}
Let us compile and run the above program to produce the following result.
This is c programming.This is a system programming language.
12 Lectures
2 hours
Nishant Malik
12 Lectures
2.5 hours
Nishant Malik
48 Lectures
6.5 hours
Asif Hussain
12 Lectures
2 hours
Richa Maheshwari
20 Lectures
3.5 hours
Vandana Annavaram
44 Lectures
1 hours
Amit Diwan
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2155,
"s": 2007,
"text": "The C library function int fputs(const char *str, FILE *stream) writes a string to the specified stream up to but not including the null character."
},
{
"code": null,
"e": 2206,
"s": 2155,
"text": "Following is the declaration for fputs() function."
},
{
"code": null,
"e": 2247,
"s": 2206,
"text": "int fputs(const char *str, FILE *stream)"
},
{
"code": null,
"e": 2339,
"s": 2247,
"text": "str β This is an array containing the null-terminated sequence of characters to be written."
},
{
"code": null,
"e": 2431,
"s": 2339,
"text": "str β This is an array containing the null-terminated sequence of characters to be written."
},
{
"code": null,
"e": 2539,
"s": 2431,
"text": "stream β This is the pointer to a FILE object that identifies the stream where the string is to be written."
},
{
"code": null,
"e": 2647,
"s": 2539,
"text": "stream β This is the pointer to a FILE object that identifies the stream where the string is to be written."
},
{
"code": null,
"e": 2724,
"s": 2647,
"text": "This function returns a non-negative value, or else on error it returns EOF."
},
{
"code": null,
"e": 2783,
"s": 2724,
"text": "The following example shows the usage of fputs() function."
},
{
"code": null,
"e": 2997,
"s": 2783,
"text": "#include <stdio.h>\n\nint main () {\n FILE *fp;\n\n fp = fopen(\"file.txt\", \"w+\");\n\n fputs(\"This is c programming.\", fp);\n fputs(\"This is a system programming language.\", fp);\n\n fclose(fp);\n \n return(0);\n}"
},
{
"code": null,
"e": 3101,
"s": 2997,
"text": "Let us compile and run the above program, this will create a file file.txt with the following content β"
},
{
"code": null,
"e": 3163,
"s": 3101,
"text": "This is c programming.This is a system programming language.\n"
},
{
"code": null,
"e": 3237,
"s": 3163,
"text": "Now let's see the content of the above file using the following program β"
},
{
"code": null,
"e": 3468,
"s": 3237,
"text": "#include <stdio.h>\n\nint main () {\n FILE *fp;\n int c;\n\n fp = fopen(\"file.txt\",\"r\");\n while(1) {\n c = fgetc(fp);\n if( feof(fp) ) {\n break ;\n }\n printf(\"%c\", c);\n }\n fclose(fp);\n return(0);\n}"
},
{
"code": null,
"e": 3542,
"s": 3468,
"text": "Let us compile and run the above program to produce the following result."
},
{
"code": null,
"e": 3604,
"s": 3542,
"text": "This is c programming.This is a system programming language.\n"
},
{
"code": null,
"e": 3637,
"s": 3604,
"text": "\n 12 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3652,
"s": 3637,
"text": " Nishant Malik"
},
{
"code": null,
"e": 3687,
"s": 3652,
"text": "\n 12 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3702,
"s": 3687,
"text": " Nishant Malik"
},
{
"code": null,
"e": 3737,
"s": 3702,
"text": "\n 48 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 3751,
"s": 3737,
"text": " Asif Hussain"
},
{
"code": null,
"e": 3784,
"s": 3751,
"text": "\n 12 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3802,
"s": 3784,
"text": " Richa Maheshwari"
},
{
"code": null,
"e": 3837,
"s": 3802,
"text": "\n 20 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 3856,
"s": 3837,
"text": " Vandana Annavaram"
},
{
"code": null,
"e": 3889,
"s": 3856,
"text": "\n 44 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3901,
"s": 3889,
"text": " Amit Diwan"
},
{
"code": null,
"e": 3908,
"s": 3901,
"text": " Print"
},
{
"code": null,
"e": 3919,
"s": 3908,
"text": " Add Notes"
}
] |
DAX Date & Time - DAY function
|
Returns the day of the month, a number from 1 to 31.
DAY (<date>)
date
A date in datetime format or a text representation of a date.
An integer indicating the day of the month.
The argument to the DAY function is the Date of the day. DAX handles the date values in datetime format.
You can specify Date as one of the following β
An output of another date function.
An output of another date function.
An expression that returns a date.
An expression that returns a date.
A date in a datetime format.
A date in a datetime format.
A date as text representation in one of the accepted string formats for dates.
A date as text representation in one of the accepted string formats for dates.
The DAY function uses the locale and date/time settings of the client computer to understand the text value in order to perform the conversion. For example,
If the current date/time settings represent dates in the format of Month/Day/Year, then the string, "1/8/2016" is understood as a datetime value equivalent to 8th January, 2016 and the function returns 8.
If the current date/time settings represent dates in the format of Month/Day/Year, then the string, "1/8/2016" is understood as a datetime value equivalent to 8th January, 2016 and the function returns 8.
If the current date/time settings represent dates in the format of Day/Month/Year, the same string would be understood as a datetime value equivalent to 1st August, 2016, and the function returns 1.
If the current date/time settings represent dates in the format of Day/Month/Year, the same string would be understood as a datetime value equivalent to 1st August, 2016, and the function returns 1.
= DAY ("8-Jan") returns 8.
= DAY ("3/5/2016") returns 5.
= DAY ("March 5, 2016") returns 5.
= DAY (TODAY ()) returns 16 if TODAY () returns 12/16/2016 12:00:00 AM.
= DAY ([Date]) returns a calculated column with day values.
53 Lectures
5.5 hours
Abhay Gadiya
24 Lectures
2 hours
Randy Minder
26 Lectures
4.5 hours
Randy Minder
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2054,
"s": 2001,
"text": "Returns the day of the month, a number from 1 to 31."
},
{
"code": null,
"e": 2069,
"s": 2054,
"text": "DAY (<date>) \n"
},
{
"code": null,
"e": 2074,
"s": 2069,
"text": "date"
},
{
"code": null,
"e": 2136,
"s": 2074,
"text": "A date in datetime format or a text representation of a date."
},
{
"code": null,
"e": 2180,
"s": 2136,
"text": "An integer indicating the day of the month."
},
{
"code": null,
"e": 2285,
"s": 2180,
"text": "The argument to the DAY function is the Date of the day. DAX handles the date values in datetime format."
},
{
"code": null,
"e": 2332,
"s": 2285,
"text": "You can specify Date as one of the following β"
},
{
"code": null,
"e": 2368,
"s": 2332,
"text": "An output of another date function."
},
{
"code": null,
"e": 2404,
"s": 2368,
"text": "An output of another date function."
},
{
"code": null,
"e": 2439,
"s": 2404,
"text": "An expression that returns a date."
},
{
"code": null,
"e": 2474,
"s": 2439,
"text": "An expression that returns a date."
},
{
"code": null,
"e": 2503,
"s": 2474,
"text": "A date in a datetime format."
},
{
"code": null,
"e": 2532,
"s": 2503,
"text": "A date in a datetime format."
},
{
"code": null,
"e": 2611,
"s": 2532,
"text": "A date as text representation in one of the accepted string formats for dates."
},
{
"code": null,
"e": 2690,
"s": 2611,
"text": "A date as text representation in one of the accepted string formats for dates."
},
{
"code": null,
"e": 2847,
"s": 2690,
"text": "The DAY function uses the locale and date/time settings of the client computer to understand the text value in order to perform the conversion. For example,"
},
{
"code": null,
"e": 3052,
"s": 2847,
"text": "If the current date/time settings represent dates in the format of Month/Day/Year, then the string, \"1/8/2016\" is understood as a datetime value equivalent to 8th January, 2016 and the function returns 8."
},
{
"code": null,
"e": 3257,
"s": 3052,
"text": "If the current date/time settings represent dates in the format of Month/Day/Year, then the string, \"1/8/2016\" is understood as a datetime value equivalent to 8th January, 2016 and the function returns 8."
},
{
"code": null,
"e": 3456,
"s": 3257,
"text": "If the current date/time settings represent dates in the format of Day/Month/Year, the same string would be understood as a datetime value equivalent to 1st August, 2016, and the function returns 1."
},
{
"code": null,
"e": 3655,
"s": 3456,
"text": "If the current date/time settings represent dates in the format of Day/Month/Year, the same string would be understood as a datetime value equivalent to 1st August, 2016, and the function returns 1."
},
{
"code": null,
"e": 3884,
"s": 3655,
"text": "= DAY (\"8-Jan\") returns 8. \n= DAY (\"3/5/2016\") returns 5. \n= DAY (\"March 5, 2016\") returns 5. \n= DAY (TODAY ()) returns 16 if TODAY () returns 12/16/2016 12:00:00 AM. \n= DAY ([Date]) returns a calculated column with day values. "
},
{
"code": null,
"e": 3919,
"s": 3884,
"text": "\n 53 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3933,
"s": 3919,
"text": " Abhay Gadiya"
},
{
"code": null,
"e": 3966,
"s": 3933,
"text": "\n 24 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3980,
"s": 3966,
"text": " Randy Minder"
},
{
"code": null,
"e": 4015,
"s": 3980,
"text": "\n 26 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 4029,
"s": 4015,
"text": " Randy Minder"
},
{
"code": null,
"e": 4036,
"s": 4029,
"text": " Print"
},
{
"code": null,
"e": 4047,
"s": 4036,
"text": " Add Notes"
}
] |
What kind of variables can we access in a lambda expression in Java?
|
The lambda expressions consist of two parts, one is parameter and another is an expression and these two parts have separated by an arrow (->) symbol. A lambda expression can access a variable of it's enclosing scope.
A Lambda expression has access to both instance and static variables of it's enclosing class and also it can access local variables which are effectively final or final.
( argument-list ) -> expression
interface TestInterface {
void print();
}
public class LambdaExpressionTest {
int a; // instance variable
static int b; // static variable
LambdaExpressionTest(int x) { // constructor to initialise instance variable
this.a = x;
}
void show() {
// lambda expression to define print() method
TestInterface testInterface = () -> {
// accessing of instance and static variable using lambda expression
System.out.println("Value of a is: "+ a);
System.out.println("Value of b is: "+ b);
};
testInterface.print();
}
public static void main(String arg[]) {
LambdaExpressionTest test = new LambdaExpressionTest(10);
test.show();
}
}
Value of a is: 10
Value of b is: 0
|
[
{
"code": null,
"e": 1281,
"s": 1062,
"text": "The lambda expressions consist of two parts, one is parameter and another is an expression and these two parts have separated by an arrow (->) symbol. A lambda expression can access a variable of it's enclosing scope. "
},
{
"code": null,
"e": 1451,
"s": 1281,
"text": "A Lambda expression has access to both instance and static variables of it's enclosing class and also it can access local variables which are effectively final or final."
},
{
"code": null,
"e": 1483,
"s": 1451,
"text": "( argument-list ) -> expression"
},
{
"code": null,
"e": 2203,
"s": 1483,
"text": "interface TestInterface {\n void print();\n}\npublic class LambdaExpressionTest {\n int a; // instance variable\n static int b; // static variable\n LambdaExpressionTest(int x) { // constructor to initialise instance variable\n this.a = x;\n }\n void show() {\n // lambda expression to define print() method\n TestInterface testInterface = () -> {\n // accessing of instance and static variable using lambda expression\n System.out.println(\"Value of a is: \"+ a);\n System.out.println(\"Value of b is: \"+ b);\n };\n testInterface.print();\n }\n public static void main(String arg[]) {\n LambdaExpressionTest test = new LambdaExpressionTest(10);\n test.show();\n }\n}"
},
{
"code": null,
"e": 2238,
"s": 2203,
"text": "Value of a is: 10\nValue of b is: 0"
}
] |
Vertically align numeric values in Java using Formatter
|
To vertically align numeric values in Java, use Formatter. For working with Formatter class, import the following package.
import java.util.Formatter;
Take an array β
double arr[] = { 2.5, 4.8, 5.7, 6.5, 9.4, 8.4, 9.5, 10.2, 11.5 };
While displaying this double array values, use the %f to set spaces β
for (double d : arr) {
f.format("%12.2f %12.2f %12.2f\n", d, Math.ceil(d), Math.floor(d));
}
Above, we have also set the decimal places i.e. 12.2f is for 2 decimal places.
The following is an example β
Live Demo
import java.util.Formatter;
public class Demo {
public static void main(String[] argv) throws Exception {
double arr[] = { 2.5, 4.8, 5.7, 6.5, 9.4, 8.4, 9.5, 10.2, 11.5 };
Formatter f = new Formatter();
f.format("%12s %12s %12s\n", "Points1", "Points2", "Points3");
System.out.println("The point list...\n");
for (double d : arr) {
f.format("%12.2f %12.2f %12.2f\n", d, Math.ceil(d), Math.floor(d));
}
System.out.println(f);
}
}
The point list...
Points1 Points2 Points3
2.50 3.00 2.00
4.80 5.00 4.00
5.70 6.00 5.00
6.50 7.00 6.00
9.40 10.00 9.00
8.40 9.00 8.00
9.50 10.00 9.00
10.20 11.00 10.00
11.50 12.00 11.00
|
[
{
"code": null,
"e": 1185,
"s": 1062,
"text": "To vertically align numeric values in Java, use Formatter. For working with Formatter class, import the following package."
},
{
"code": null,
"e": 1213,
"s": 1185,
"text": "import java.util.Formatter;"
},
{
"code": null,
"e": 1229,
"s": 1213,
"text": "Take an array β"
},
{
"code": null,
"e": 1295,
"s": 1229,
"text": "double arr[] = { 2.5, 4.8, 5.7, 6.5, 9.4, 8.4, 9.5, 10.2, 11.5 };"
},
{
"code": null,
"e": 1365,
"s": 1295,
"text": "While displaying this double array values, use the %f to set spaces β"
},
{
"code": null,
"e": 1461,
"s": 1365,
"text": "for (double d : arr) {\n f.format(\"%12.2f %12.2f %12.2f\\n\", d, Math.ceil(d), Math.floor(d));\n}"
},
{
"code": null,
"e": 1540,
"s": 1461,
"text": "Above, we have also set the decimal places i.e. 12.2f is for 2 decimal places."
},
{
"code": null,
"e": 1570,
"s": 1540,
"text": "The following is an example β"
},
{
"code": null,
"e": 1581,
"s": 1570,
"text": " Live Demo"
},
{
"code": null,
"e": 2067,
"s": 1581,
"text": "import java.util.Formatter;\npublic class Demo {\n public static void main(String[] argv) throws Exception {\n double arr[] = { 2.5, 4.8, 5.7, 6.5, 9.4, 8.4, 9.5, 10.2, 11.5 };\n Formatter f = new Formatter();\n f.format(\"%12s %12s %12s\\n\", \"Points1\", \"Points2\", \"Points3\");\n System.out.println(\"The point list...\\n\");\n for (double d : arr) {\n f.format(\"%12.2f %12.2f %12.2f\\n\", d, Math.ceil(d), Math.floor(d));\n }\n System.out.println(f);\n }\n}"
},
{
"code": null,
"e": 2320,
"s": 2067,
"text": "The point list...\nPoints1 Points2 Points3\n2.50 3.00 2.00\n4.80 5.00 4.00\n5.70 6.00 5.00\n6.50 7.00 6.00\n9.40 10.00 9.00\n8.40 9.00 8.00\n9.50 10.00 9.00\n10.20 11.00 10.00\n11.50 12.00 11.00"
}
] |
Batch Script - Logging
|
Logging in is possible in Batch Script by using the redirection command.
test.bat > testlog.txt 2> testerrors.txt
Create a file called test.bat and enter the following command in the file.
net statistics /Server
The above command has an error because the option to the net statistics command is given in the wrong way.
If the command with the above test.bat file is run as
test.bat > testlog.txt 2> testerrors.txt
And you open the file testerrors.txt, you will see the following error.
The option /SERVER is unknown.
The syntax of this command is β
NET STATISTICS
[WORKSTATION | SERVER]
More help is available by typing NET HELPMSG 3506.
If you open the file called testlog.txt, it will show you a log of what commands were executed.
C:\tp>net statistics /Server
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2242,
"s": 2169,
"text": "Logging in is possible in Batch Script by using the redirection command."
},
{
"code": null,
"e": 2284,
"s": 2242,
"text": "test.bat > testlog.txt 2> testerrors.txt\n"
},
{
"code": null,
"e": 2359,
"s": 2284,
"text": "Create a file called test.bat and enter the following command in the file."
},
{
"code": null,
"e": 2383,
"s": 2359,
"text": "net statistics /Server\n"
},
{
"code": null,
"e": 2490,
"s": 2383,
"text": "The above command has an error because the option to the net statistics command is given in the wrong way."
},
{
"code": null,
"e": 2544,
"s": 2490,
"text": "If the command with the above test.bat file is run as"
},
{
"code": null,
"e": 2586,
"s": 2544,
"text": "test.bat > testlog.txt 2> testerrors.txt\n"
},
{
"code": null,
"e": 2658,
"s": 2586,
"text": "And you open the file testerrors.txt, you will see the following error."
},
{
"code": null,
"e": 2690,
"s": 2658,
"text": "The option /SERVER is unknown.\n"
},
{
"code": null,
"e": 2722,
"s": 2690,
"text": "The syntax of this command is β"
},
{
"code": null,
"e": 2761,
"s": 2722,
"text": "NET STATISTICS\n[WORKSTATION | SERVER]\n"
},
{
"code": null,
"e": 2812,
"s": 2761,
"text": "More help is available by typing NET HELPMSG 3506."
},
{
"code": null,
"e": 2908,
"s": 2812,
"text": "If you open the file called testlog.txt, it will show you a log of what commands were executed."
},
{
"code": null,
"e": 2938,
"s": 2908,
"text": "C:\\tp>net statistics /Server\n"
},
{
"code": null,
"e": 2945,
"s": 2938,
"text": " Print"
},
{
"code": null,
"e": 2956,
"s": 2945,
"text": " Add Notes"
}
] |
How to handle swipe gestures in Kotlin?
|
This example demonstrates how to handle swipe gestures in an android device using Kotlin.
Step 1 β Create a new project in Android Studio, go to File β New Project and fill all required details to create a new project.
Step 2 β Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/relativeLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Swipe Left, right, up and down to detect Swipe Gesture"
android:textAlignment="center"
android:textSize="16sp"
android:textStyle="bold" />
</RelativeLayout>
Step 3 β Add the following code to src/MainActivity.kt
package app.com.kotlinapp
import android.os.Bundle
import android.widget.RelativeLayout
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
private lateinit var layout: RelativeLayout
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
layout = findViewById(R.id.relativeLayout)
layout.setOnTouchListener(object : OnSwipeTouchListener(this@MainActivity) {
override fun onSwipeLeft() {
super.onSwipeLeft()
Toast.makeText(this@MainActivity, "Swipe Left gesture detected",
Toast.LENGTH_SHORT)
.show()
}
override fun onSwipeRight() {
super.onSwipeRight()
Toast.makeText(
this@MainActivity,
"Swipe Right gesture detected",
Toast.LENGTH_SHORT
).show()
}
override fun onSwipeUp() {
super.onSwipeUp()
Toast.makeText(this@MainActivity, "Swipe up gesture detected", Toast.LENGTH_SHORT)
.show()
}
override fun onSwipeDown() {
super.onSwipeDown()
Toast.makeText(this@MainActivity, "Swipe down gesture detected", Toast.LENGTH_SHORT)
.show()
}
})
}
}
Step 4 β Add the following code to src/OnSwipeTouchListener.kt
package app.com.kotlinapp
import android.content.Context
import android.view.GestureDetector
import android.view.GestureDetector.SimpleOnGestureListener
import android.view.MotionEvent
import android.view.View
import android.view.View.OnTouchListener
import kotlin.math.abs
internal open class OnSwipeTouchListener(c: Context?) :
OnTouchListener {
private val gestureDetector: GestureDetector
override fun onTouch(view: View, motionEvent: MotionEvent): Boolean {
return gestureDetector.onTouchEvent(motionEvent)
}
private inner class GestureListener : SimpleOnGestureListener() {
private val SWIPE_THRESHOLD: Int = 100
private val SWIPE_VELOCITY_THRESHOLD: Int = 100
override fun onDown(e: MotionEvent): Boolean {
return true
}
override fun onSingleTapUp(e: MotionEvent): Boolean {
onClick()
return super.onSingleTapUp(e)
}
override fun onDoubleTap(e: MotionEvent): Boolean {
onDoubleClick()
return super.onDoubleTap(e)
}
override fun onLongPress(e: MotionEvent) {
onLongClick()
super.onLongPress(e)
}
override fun onFling(
e1: MotionEvent,
e2: MotionEvent,
velocityX: Float,
velocityY: Float
): Boolean {
try {
val diffY = e2.y - e1.y
val diffX = e2.x - e1.x
if (abs(diffX) > abs(diffY)) {
if (abs(diffX) > SWIPE_THRESHOLD && abs(
velocityX
) > SWIPE_VELOCITY_THRESHOLD
) {
if (diffX > 0) {
onSwipeRight()
}
else {
onSwipeLeft()
}
}
}
else {
if (abs(diffY) > SWIPE_THRESHOLD && abs(
velocityY
) > SWIPE_VELOCITY_THRESHOLD
) {
if (diffY < 0) {
onSwipeUp()
}
else {
onSwipeDown()
}
}
}
} catch (exception: Exception) {
exception.printStackTrace()
}
return false
}
}
open fun onSwipeRight() {}
open fun onSwipeLeft() {}
open fun onSwipeUp() {}
open fun onSwipeDown() {}
private fun onClick() {}
private fun onDoubleClick() {}
private fun onLongClick() {}
init {
gestureDetector = GestureDetector(c, GestureListener())
}
}
Step 5 β Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="app.com.kotlipapp">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen β
Click here to download the project code.
|
[
{
"code": null,
"e": 1152,
"s": 1062,
"text": "This example demonstrates how to handle swipe gestures in an android device using Kotlin."
},
{
"code": null,
"e": 1281,
"s": 1152,
"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": 1346,
"s": 1281,
"text": "Step 2 β Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 1995,
"s": 1346,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:id=\"@+id/relativeLayout\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"\n android:text=\"Swipe Left, right, up and down to detect Swipe Gesture\"\n android:textAlignment=\"center\"\n android:textSize=\"16sp\"\n android:textStyle=\"bold\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 2050,
"s": 1995,
"text": "Step 3 β Add the following code to src/MainActivity.kt"
},
{
"code": null,
"e": 3441,
"s": 2050,
"text": "package app.com.kotlinapp\nimport android.os.Bundle\nimport android.widget.RelativeLayout\nimport android.widget.Toast\nimport androidx.appcompat.app.AppCompatActivity\nclass MainActivity : AppCompatActivity() {\n private lateinit var layout: RelativeLayout\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n layout = findViewById(R.id.relativeLayout)\n layout.setOnTouchListener(object : OnSwipeTouchListener(this@MainActivity) {\n override fun onSwipeLeft() {\n super.onSwipeLeft()\n Toast.makeText(this@MainActivity, \"Swipe Left gesture detected\",\n Toast.LENGTH_SHORT)\n .show()\n }\n override fun onSwipeRight() {\n super.onSwipeRight()\n Toast.makeText(\n this@MainActivity,\n \"Swipe Right gesture detected\",\n Toast.LENGTH_SHORT\n ).show()\n }\n override fun onSwipeUp() {\n super.onSwipeUp()\n Toast.makeText(this@MainActivity, \"Swipe up gesture detected\", Toast.LENGTH_SHORT)\n .show()\n }\n override fun onSwipeDown() {\n super.onSwipeDown()\n Toast.makeText(this@MainActivity, \"Swipe down gesture detected\", Toast.LENGTH_SHORT)\n .show()\n }\n })\n }\n}"
},
{
"code": null,
"e": 3504,
"s": 3441,
"text": "Step 4 β Add the following code to src/OnSwipeTouchListener.kt"
},
{
"code": null,
"e": 5982,
"s": 3504,
"text": "package app.com.kotlinapp\nimport android.content.Context\nimport android.view.GestureDetector\nimport android.view.GestureDetector.SimpleOnGestureListener\nimport android.view.MotionEvent\nimport android.view.View\nimport android.view.View.OnTouchListener\nimport kotlin.math.abs\ninternal open class OnSwipeTouchListener(c: Context?) :\nOnTouchListener {\n private val gestureDetector: GestureDetector\n override fun onTouch(view: View, motionEvent: MotionEvent): Boolean {\n return gestureDetector.onTouchEvent(motionEvent)\n }\n private inner class GestureListener : SimpleOnGestureListener() {\n private val SWIPE_THRESHOLD: Int = 100\n private val SWIPE_VELOCITY_THRESHOLD: Int = 100\n override fun onDown(e: MotionEvent): Boolean {\n return true\n }\n override fun onSingleTapUp(e: MotionEvent): Boolean {\n onClick()\n return super.onSingleTapUp(e)\n }\n override fun onDoubleTap(e: MotionEvent): Boolean {\n onDoubleClick()\n return super.onDoubleTap(e)\n }\n override fun onLongPress(e: MotionEvent) {\n onLongClick()\n super.onLongPress(e)\n }\n override fun onFling(\n e1: MotionEvent,\n e2: MotionEvent,\n velocityX: Float,\n velocityY: Float\n ): Boolean {\n try {\n val diffY = e2.y - e1.y\n val diffX = e2.x - e1.x\n if (abs(diffX) > abs(diffY)) {\n if (abs(diffX) > SWIPE_THRESHOLD && abs(\n velocityX\n ) > SWIPE_VELOCITY_THRESHOLD\n ) {\n if (diffX > 0) {\n onSwipeRight()\n }\n else {\n onSwipeLeft()\n }\n }\n }\n else {\n if (abs(diffY) > SWIPE_THRESHOLD && abs(\n velocityY\n ) > SWIPE_VELOCITY_THRESHOLD\n ) {\n if (diffY < 0) {\n onSwipeUp()\n }\n else {\n onSwipeDown()\n }\n }\n }\n } catch (exception: Exception) {\n exception.printStackTrace()\n }\n return false\n }\n }\n open fun onSwipeRight() {}\n open fun onSwipeLeft() {}\n open fun onSwipeUp() {}\n open fun onSwipeDown() {}\n private fun onClick() {}\n private fun onDoubleClick() {}\n private fun onLongClick() {}\n init {\n gestureDetector = GestureDetector(c, GestureListener())\n }\n}"
},
{
"code": null,
"e": 6037,
"s": 5982,
"text": "Step 5 β Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 6713,
"s": 6037,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"app.com.kotlipapp\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 7064,
"s": 6713,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen β"
},
{
"code": null,
"e": 7105,
"s": 7064,
"text": "Click here to download the project code."
}
] |
VBScript Date Function
|
The Function returns the current system Date.
date()
<!DOCTYPE html>
<html>
<body>
<script language = "vbscript" type = "text/vbscript">
a = date()
document.write("The Value of a : " & a)
</script>
</body>
</html>
When you save it as .html and execute it in Internet Explorer, then the above script will produce the following result β
The Value of a : 19/07/2013
63 Lectures
4 hours
Frahaan Hussain
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2126,
"s": 2080,
"text": "The Function returns the current system Date."
},
{
"code": null,
"e": 2134,
"s": 2126,
"text": "date()\n"
},
{
"code": null,
"e": 2339,
"s": 2134,
"text": "<!DOCTYPE html>\n<html>\n <body>\n <script language = \"vbscript\" type = \"text/vbscript\">\n a = date()\n document.write(\"The Value of a : \" & a)\n \n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 2460,
"s": 2339,
"text": "When you save it as .html and execute it in Internet Explorer, then the above script will produce the following result β"
},
{
"code": null,
"e": 2490,
"s": 2460,
"text": "The Value of a : 19/07/2013 \n"
},
{
"code": null,
"e": 2523,
"s": 2490,
"text": "\n 63 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 2540,
"s": 2523,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 2547,
"s": 2540,
"text": " Print"
},
{
"code": null,
"e": 2558,
"s": 2547,
"text": " Add Notes"
}
] |
Check if a Queen can attack a given cell on chessboard in Python
|
Suppose we have two coordinates on a chessboard for queen and opponent. These points are Q and O respectively. We have to check whether the queen can attack the opponent or not. As we know that the queen can attack in the same row, same column and diagonally.
So, if the input is like Q = (1, 1) O = (4, 4), then the output will be True as Q can go (4, 4) diagonally.
To solve this, we will follow these steps β
if x of Q is same as x of O, thenreturn True
return True
if y of Q is same as y of O, thenreturn True
return True
if |x of Q - x of O| is same as |y of Q - y of O|, thenreturn True
return True
return False
Let us see the following implementation to get better understanding β
Live Demo
def solve(Q, O):
if Q[0] == O[0]:
return True
if Q[1] == O[1]:
return True
if abs(Q[0] - O[0]) == abs(Q[1] - O[1]):
return True
return False
Q = (1, 1)
O = (4, 4)
print(solve(Q, O))
(1, 1), (4, 4)
True
|
[
{
"code": null,
"e": 1322,
"s": 1062,
"text": "Suppose we have two coordinates on a chessboard for queen and opponent. These points are Q and O respectively. We have to check whether the queen can attack the opponent or not. As we know that the queen can attack in the same row, same column and diagonally."
},
{
"code": null,
"e": 1430,
"s": 1322,
"text": "So, if the input is like Q = (1, 1) O = (4, 4), then the output will be True as Q can go (4, 4) diagonally."
},
{
"code": null,
"e": 1474,
"s": 1430,
"text": "To solve this, we will follow these steps β"
},
{
"code": null,
"e": 1519,
"s": 1474,
"text": "if x of Q is same as x of O, thenreturn True"
},
{
"code": null,
"e": 1531,
"s": 1519,
"text": "return True"
},
{
"code": null,
"e": 1576,
"s": 1531,
"text": "if y of Q is same as y of O, thenreturn True"
},
{
"code": null,
"e": 1588,
"s": 1576,
"text": "return True"
},
{
"code": null,
"e": 1655,
"s": 1588,
"text": "if |x of Q - x of O| is same as |y of Q - y of O|, thenreturn True"
},
{
"code": null,
"e": 1667,
"s": 1655,
"text": "return True"
},
{
"code": null,
"e": 1680,
"s": 1667,
"text": "return False"
},
{
"code": null,
"e": 1750,
"s": 1680,
"text": "Let us see the following implementation to get better understanding β"
},
{
"code": null,
"e": 1761,
"s": 1750,
"text": " Live Demo"
},
{
"code": null,
"e": 1973,
"s": 1761,
"text": "def solve(Q, O):\n if Q[0] == O[0]:\n return True\n if Q[1] == O[1]:\n return True\n if abs(Q[0] - O[0]) == abs(Q[1] - O[1]):\n return True\n return False\nQ = (1, 1)\nO = (4, 4)\nprint(solve(Q, O))"
},
{
"code": null,
"e": 1988,
"s": 1973,
"text": "(1, 1), (4, 4)"
},
{
"code": null,
"e": 1993,
"s": 1988,
"text": "True"
}
] |
Data Pipeline in GCP: Cloud Function Basics | by Mostafa Varzaneh | Towards Data Science
|
Most Data Scientists, prefer to own the end to end data pipeline of their models, but owning a pipeline requires a lot of engineering effort.
In this article, I will talk about Cloud Function, which is a serverless, easy, and cost-effective option.
GCP provides a simple scheduling tool called βCloud Schedulerβ. From the navigation menu on the top left find Cloud Scheduler.
Give your job a name and description. Next, you need to provide the frequency of the schedule. If you ever worked with any scheduler including Cron Jobs, you will be fine here.
Select time zone and Pub/Sub as the target.
Once you click on Pub/Sub options for Topic and Payload appears. The topic name will be used later as the name of your Python function so keep in mind to use a topic that is acceptable as a function name in Python. Give payload some arbitrary string for now.
If you prefer to use the command line you can run the following:
gcloud alpha scheduler jobs create pubsub scheduler-name --schedule="0 8 * * *" --topic="my_pipeline_topic" --message-body=" "
You should now be able to see your scheduled job in Cloud Scheduler.
I recommend you to read Google's documentation about Pub/Sub. But in a brief sentence, Pub/Sub allows you to send messages between different applications. You can leverage Pub/Sub for batch and stream data pipelines.
Now use the topic to create a Pub/Sub topic
gcloud pubsub topics create my_pipeline_name
You have the option to create the Pub/Sub topic using UI:
You have the option to create your Cloud Function from UI but I do not recommend it. First, if there is a bug in your code you will lose your work. Second, you can easily lose track of your changes and versions.
As the first effort, let's create our functions locally and deploy them manually to GCP.
What do you need?
you need a βmain.pyβ function. This is the wrapper around all your functions and classes. Inside main.py there should be a function with our Cloud Function name.
your imports heredef my_pipeline_name(event,contex): your_code_here
Keep the rest of your functions in the same folder, it is easier!
Here is the definition of event and context according to Google:
event (dict): The dictionary with data specific to this type of event. The `data` field contains the PubsubMessage message. context (google.cloud.functions.Context): The Cloud Functions event `timestamp` field contains the publish time.
So leave them!
Create a .gcloudignore file. This file is like a .gitignore but for cloud deployment. You may include the files you do not want to deploy (like secret keys which you kept in your folder for local tests)
Create a requirements.txt file with the required packages.
during your run, you may need to save some files, but the root of your cloud function is read-only! You need to use /temp/ directory for your temporary and modifiable files.
It is time to deploy!
gcloud functions deploy my_pipeline_name --runtime python37--trigger-topic my_pipeline_topic --timeout 540
Here is a big limitation! The maximum timeout for cloud function is 9 minutes according to the documentation.
Check Zdenkoβs article and GitHub for more details.
Go to Cloud Functions on GCP UI and then click on the function name, it will redirect you to a new page called βfunction detailsβ which has the latest deploy version
In the general tab, you can find Invocation, Execution time, Memory usage, and Active instances. All of these are important factors for billing (I know Cloud Functions are cheap but it is good practice to keep track of the cost). You can refer you Rominβs Article about Cloud Function pricing.
You can click on edit on top middle and change memory, functions, or ...
Clicking on Source, you will find the deployed files and you can click on edit to modify them online (not recommended).
Go to the Testing tab and click on TEST THE FUNCTION the code will run and returns an error if there is any problem. But this is a test for Cloud Functions, what about Pub/Sub and Scheduler?
You can go to βCloud Schedulerβ from Navigation Menu and you will find a Run Now button in front of your job name. You may use it for testing and check the message under theResult column.
I am not comfortable with deploying my secret key with the code, here I will review my top two options for handling secrets.
The first one is to add environment variables to your Cloud Functions. You can either use UI or command line. This option is not my favorite since first the secret is sitting in the UI and second I have to deploy it for other functions again.
The second option is to use the secret manager on GCP. I will borrow some material from Dustinβs post on managing secrets in Cloud Functions.
Now you can use cloud shell. The icon is on top right next to the search bar.
Enable βSecret Manager APIβ:
gcloud services enable secretmanager.googleapis.com
Create a secret:
echo -n "your secret text here" | \ gcloud beta secrets create my-secret \ --data-file=- \ --replication-policy automatic
If you have double quotations in your secret file, use single quotations around it.
Write a function to retrieve your secrets:
import osfrom google.cloud import secretmanagerimport jsondef get_secret(secret_name): client = secretmanager.SecretManagerServiceClient() project_id = 'my_gcp_project' resource_name = f"projects/{project_id}/secrets/{secret_name}/versions/latest" response = client.access_secret_version(resource_name) secret_string = response.payload.data.decode('UTF-8') secret_string = json.loads(secret_string) return secret_string
You can call this function in the rest of your codes to retrieve your keys. Make sure to add βgoogle-cloud-secret-managerβ to your requirements file.
You are set! Go to the UI and test!
Even though you can deploy from your local, Google provides an option for deploying from a source control like GitHub or BitBucket. Letβs go through it step by step.
Mirror you repository
In the Google Cloud Console, open Cloud Source Repositories.Open Cloud Source RepositoriesClick Add repository.The Add a repository page opens.Select Connect external repository and click Continue.The Connect external repository page opens.In the Project drop-down list, select the Google Cloud project to which the mirrored repository belongs.In the Git provider drop-down list, select Bitbucket.Select the checkbox to authorize Cloud Source Repositories to store your credentials.Click Connect to Bitbucket.Sign in to Bitbucket with your machine user credentials.Click Authorize GoogleCloudPlatform.This option grants Google Cloud read access to your repository.When authorization finishes, youβre returned to the Connect external repository page. A list of repositories opens.From the list of repositories, select the repository you want to mirror.Click Connect Selected Repository.
In the Google Cloud Console, open Cloud Source Repositories.
Open Cloud Source Repositories
Click Add repository.
The Add a repository page opens.
Select Connect external repository and click Continue.
The Connect external repository page opens.
In the Project drop-down list, select the Google Cloud project to which the mirrored repository belongs.
In the Git provider drop-down list, select Bitbucket.
Select the checkbox to authorize Cloud Source Repositories to store your credentials.
Click Connect to Bitbucket.
Sign in to Bitbucket with your machine user credentials.
Click Authorize GoogleCloudPlatform.
This option grants Google Cloud read access to your repository.
When authorization finishes, youβre returned to the Connect external repository page. A list of repositories opens.
From the list of repositories, select the repository you want to mirror.
Click Connect Selected Repository.
On the top left below βCloud Source Repositoriesβ, you can find the name of your repo and also the active branch. Click on the drop-down menu and change see the rest of the branches.
Deploy From Cloud Repo
You can deploy to Cloud Function from Cloud Source Repository using the following commands:
gcloud functions deploy my_pipeline_name \ --source https://source.developers.google.com/projects/[gcp_project_name]/repos/[cloud_source_repository_root]/moveable-aliases/[branch]/paths/[folder_under_that_branch]/ \ --runtime python37 \ --trigger-topic my_pipeline_topic --timeout 540
Now check your could function, the version should be incremented. Go to theTESTING tab and enjoy passing the tests!
Now that you mirrored your repository to βCloud Source Repositoriesβ if you check the source of your cloud function you see that it points to your repo now!
This step may seem redundant since you can deploy from your local, but let's go to the next step.
So far we learned how to deploy from local and from cloud repo, letβs learn setting up a CI/CD!
You need to add a βcloudbuild.yamlβ to your directory and put the following content:
steps:- name: gcr.io/cloud-builders/gcloud args: - functions - deploy - my_pipeline_name - --source=https://source.developers.google.com/projects/[gcp_project_name]/repos/[cloud_source_repository_root]/moveable-aliases/[branch]/paths/google_ads/[folder_under_that_branch]/ - --trigger-topic=my_pipeline_topic - --runtime=python37 - --timeout=540
Now from GCPβs Navigation Menu go to cloud build, go to Triggers and click on βcreate newβ. It should be straight forward now!Give your trigger a name and description. I want to trigger the build every time I push to the branch, so will select that option. From the source section, I will find the mirrored repo from step 6 and enter the name of the branch.
Since the build configuration is saved in the cloudbuild, I will select the first option and copy and paste the path to the YAML file.
You are all set, click on create and enjoy your CI/CD pipeline!
|
[
{
"code": null,
"e": 314,
"s": 172,
"text": "Most Data Scientists, prefer to own the end to end data pipeline of their models, but owning a pipeline requires a lot of engineering effort."
},
{
"code": null,
"e": 421,
"s": 314,
"text": "In this article, I will talk about Cloud Function, which is a serverless, easy, and cost-effective option."
},
{
"code": null,
"e": 548,
"s": 421,
"text": "GCP provides a simple scheduling tool called βCloud Schedulerβ. From the navigation menu on the top left find Cloud Scheduler."
},
{
"code": null,
"e": 725,
"s": 548,
"text": "Give your job a name and description. Next, you need to provide the frequency of the schedule. If you ever worked with any scheduler including Cron Jobs, you will be fine here."
},
{
"code": null,
"e": 769,
"s": 725,
"text": "Select time zone and Pub/Sub as the target."
},
{
"code": null,
"e": 1028,
"s": 769,
"text": "Once you click on Pub/Sub options for Topic and Payload appears. The topic name will be used later as the name of your Python function so keep in mind to use a topic that is acceptable as a function name in Python. Give payload some arbitrary string for now."
},
{
"code": null,
"e": 1093,
"s": 1028,
"text": "If you prefer to use the command line you can run the following:"
},
{
"code": null,
"e": 1220,
"s": 1093,
"text": "gcloud alpha scheduler jobs create pubsub scheduler-name --schedule=\"0 8 * * *\" --topic=\"my_pipeline_topic\" --message-body=\" \""
},
{
"code": null,
"e": 1289,
"s": 1220,
"text": "You should now be able to see your scheduled job in Cloud Scheduler."
},
{
"code": null,
"e": 1506,
"s": 1289,
"text": "I recommend you to read Google's documentation about Pub/Sub. But in a brief sentence, Pub/Sub allows you to send messages between different applications. You can leverage Pub/Sub for batch and stream data pipelines."
},
{
"code": null,
"e": 1550,
"s": 1506,
"text": "Now use the topic to create a Pub/Sub topic"
},
{
"code": null,
"e": 1595,
"s": 1550,
"text": "gcloud pubsub topics create my_pipeline_name"
},
{
"code": null,
"e": 1653,
"s": 1595,
"text": "You have the option to create the Pub/Sub topic using UI:"
},
{
"code": null,
"e": 1865,
"s": 1653,
"text": "You have the option to create your Cloud Function from UI but I do not recommend it. First, if there is a bug in your code you will lose your work. Second, you can easily lose track of your changes and versions."
},
{
"code": null,
"e": 1954,
"s": 1865,
"text": "As the first effort, let's create our functions locally and deploy them manually to GCP."
},
{
"code": null,
"e": 1972,
"s": 1954,
"text": "What do you need?"
},
{
"code": null,
"e": 2134,
"s": 1972,
"text": "you need a βmain.pyβ function. This is the wrapper around all your functions and classes. Inside main.py there should be a function with our Cloud Function name."
},
{
"code": null,
"e": 2205,
"s": 2134,
"text": "your imports heredef my_pipeline_name(event,contex): your_code_here"
},
{
"code": null,
"e": 2271,
"s": 2205,
"text": "Keep the rest of your functions in the same folder, it is easier!"
},
{
"code": null,
"e": 2336,
"s": 2271,
"text": "Here is the definition of event and context according to Google:"
},
{
"code": null,
"e": 2590,
"s": 2336,
"text": "event (dict): The dictionary with data specific to this type of event. The `data` field contains the PubsubMessage message. context (google.cloud.functions.Context): The Cloud Functions event `timestamp` field contains the publish time."
},
{
"code": null,
"e": 2605,
"s": 2590,
"text": "So leave them!"
},
{
"code": null,
"e": 2808,
"s": 2605,
"text": "Create a .gcloudignore file. This file is like a .gitignore but for cloud deployment. You may include the files you do not want to deploy (like secret keys which you kept in your folder for local tests)"
},
{
"code": null,
"e": 2867,
"s": 2808,
"text": "Create a requirements.txt file with the required packages."
},
{
"code": null,
"e": 3041,
"s": 2867,
"text": "during your run, you may need to save some files, but the root of your cloud function is read-only! You need to use /temp/ directory for your temporary and modifiable files."
},
{
"code": null,
"e": 3063,
"s": 3041,
"text": "It is time to deploy!"
},
{
"code": null,
"e": 3171,
"s": 3063,
"text": "gcloud functions deploy my_pipeline_name --runtime python37--trigger-topic my_pipeline_topic --timeout 540"
},
{
"code": null,
"e": 3281,
"s": 3171,
"text": "Here is a big limitation! The maximum timeout for cloud function is 9 minutes according to the documentation."
},
{
"code": null,
"e": 3333,
"s": 3281,
"text": "Check Zdenkoβs article and GitHub for more details."
},
{
"code": null,
"e": 3499,
"s": 3333,
"text": "Go to Cloud Functions on GCP UI and then click on the function name, it will redirect you to a new page called βfunction detailsβ which has the latest deploy version"
},
{
"code": null,
"e": 3793,
"s": 3499,
"text": "In the general tab, you can find Invocation, Execution time, Memory usage, and Active instances. All of these are important factors for billing (I know Cloud Functions are cheap but it is good practice to keep track of the cost). You can refer you Rominβs Article about Cloud Function pricing."
},
{
"code": null,
"e": 3866,
"s": 3793,
"text": "You can click on edit on top middle and change memory, functions, or ..."
},
{
"code": null,
"e": 3986,
"s": 3866,
"text": "Clicking on Source, you will find the deployed files and you can click on edit to modify them online (not recommended)."
},
{
"code": null,
"e": 4177,
"s": 3986,
"text": "Go to the Testing tab and click on TEST THE FUNCTION the code will run and returns an error if there is any problem. But this is a test for Cloud Functions, what about Pub/Sub and Scheduler?"
},
{
"code": null,
"e": 4365,
"s": 4177,
"text": "You can go to βCloud Schedulerβ from Navigation Menu and you will find a Run Now button in front of your job name. You may use it for testing and check the message under theResult column."
},
{
"code": null,
"e": 4490,
"s": 4365,
"text": "I am not comfortable with deploying my secret key with the code, here I will review my top two options for handling secrets."
},
{
"code": null,
"e": 4733,
"s": 4490,
"text": "The first one is to add environment variables to your Cloud Functions. You can either use UI or command line. This option is not my favorite since first the secret is sitting in the UI and second I have to deploy it for other functions again."
},
{
"code": null,
"e": 4875,
"s": 4733,
"text": "The second option is to use the secret manager on GCP. I will borrow some material from Dustinβs post on managing secrets in Cloud Functions."
},
{
"code": null,
"e": 4953,
"s": 4875,
"text": "Now you can use cloud shell. The icon is on top right next to the search bar."
},
{
"code": null,
"e": 4982,
"s": 4953,
"text": "Enable βSecret Manager APIβ:"
},
{
"code": null,
"e": 5035,
"s": 4982,
"text": "gcloud services enable secretmanager.googleapis.com "
},
{
"code": null,
"e": 5052,
"s": 5035,
"text": "Create a secret:"
},
{
"code": null,
"e": 5187,
"s": 5052,
"text": "echo -n \"your secret text here\" | \\ gcloud beta secrets create my-secret \\ --data-file=- \\ --replication-policy automatic"
},
{
"code": null,
"e": 5271,
"s": 5187,
"text": "If you have double quotations in your secret file, use single quotations around it."
},
{
"code": null,
"e": 5314,
"s": 5271,
"text": "Write a function to retrieve your secrets:"
},
{
"code": null,
"e": 5755,
"s": 5314,
"text": "import osfrom google.cloud import secretmanagerimport jsondef get_secret(secret_name): client = secretmanager.SecretManagerServiceClient() project_id = 'my_gcp_project' resource_name = f\"projects/{project_id}/secrets/{secret_name}/versions/latest\" response = client.access_secret_version(resource_name) secret_string = response.payload.data.decode('UTF-8') secret_string = json.loads(secret_string) return secret_string"
},
{
"code": null,
"e": 5905,
"s": 5755,
"text": "You can call this function in the rest of your codes to retrieve your keys. Make sure to add βgoogle-cloud-secret-managerβ to your requirements file."
},
{
"code": null,
"e": 5941,
"s": 5905,
"text": "You are set! Go to the UI and test!"
},
{
"code": null,
"e": 6107,
"s": 5941,
"text": "Even though you can deploy from your local, Google provides an option for deploying from a source control like GitHub or BitBucket. Letβs go through it step by step."
},
{
"code": null,
"e": 6129,
"s": 6107,
"text": "Mirror you repository"
},
{
"code": null,
"e": 7015,
"s": 6129,
"text": "In the Google Cloud Console, open Cloud Source Repositories.Open Cloud Source RepositoriesClick Add repository.The Add a repository page opens.Select Connect external repository and click Continue.The Connect external repository page opens.In the Project drop-down list, select the Google Cloud project to which the mirrored repository belongs.In the Git provider drop-down list, select Bitbucket.Select the checkbox to authorize Cloud Source Repositories to store your credentials.Click Connect to Bitbucket.Sign in to Bitbucket with your machine user credentials.Click Authorize GoogleCloudPlatform.This option grants Google Cloud read access to your repository.When authorization finishes, youβre returned to the Connect external repository page. A list of repositories opens.From the list of repositories, select the repository you want to mirror.Click Connect Selected Repository."
},
{
"code": null,
"e": 7076,
"s": 7015,
"text": "In the Google Cloud Console, open Cloud Source Repositories."
},
{
"code": null,
"e": 7107,
"s": 7076,
"text": "Open Cloud Source Repositories"
},
{
"code": null,
"e": 7129,
"s": 7107,
"text": "Click Add repository."
},
{
"code": null,
"e": 7162,
"s": 7129,
"text": "The Add a repository page opens."
},
{
"code": null,
"e": 7217,
"s": 7162,
"text": "Select Connect external repository and click Continue."
},
{
"code": null,
"e": 7261,
"s": 7217,
"text": "The Connect external repository page opens."
},
{
"code": null,
"e": 7366,
"s": 7261,
"text": "In the Project drop-down list, select the Google Cloud project to which the mirrored repository belongs."
},
{
"code": null,
"e": 7420,
"s": 7366,
"text": "In the Git provider drop-down list, select Bitbucket."
},
{
"code": null,
"e": 7506,
"s": 7420,
"text": "Select the checkbox to authorize Cloud Source Repositories to store your credentials."
},
{
"code": null,
"e": 7534,
"s": 7506,
"text": "Click Connect to Bitbucket."
},
{
"code": null,
"e": 7591,
"s": 7534,
"text": "Sign in to Bitbucket with your machine user credentials."
},
{
"code": null,
"e": 7628,
"s": 7591,
"text": "Click Authorize GoogleCloudPlatform."
},
{
"code": null,
"e": 7692,
"s": 7628,
"text": "This option grants Google Cloud read access to your repository."
},
{
"code": null,
"e": 7808,
"s": 7692,
"text": "When authorization finishes, youβre returned to the Connect external repository page. A list of repositories opens."
},
{
"code": null,
"e": 7881,
"s": 7808,
"text": "From the list of repositories, select the repository you want to mirror."
},
{
"code": null,
"e": 7916,
"s": 7881,
"text": "Click Connect Selected Repository."
},
{
"code": null,
"e": 8099,
"s": 7916,
"text": "On the top left below βCloud Source Repositoriesβ, you can find the name of your repo and also the active branch. Click on the drop-down menu and change see the rest of the branches."
},
{
"code": null,
"e": 8122,
"s": 8099,
"text": "Deploy From Cloud Repo"
},
{
"code": null,
"e": 8214,
"s": 8122,
"text": "You can deploy to Cloud Function from Cloud Source Repository using the following commands:"
},
{
"code": null,
"e": 8502,
"s": 8214,
"text": "gcloud functions deploy my_pipeline_name \\ --source https://source.developers.google.com/projects/[gcp_project_name]/repos/[cloud_source_repository_root]/moveable-aliases/[branch]/paths/[folder_under_that_branch]/ \\ --runtime python37 \\ --trigger-topic my_pipeline_topic --timeout 540"
},
{
"code": null,
"e": 8618,
"s": 8502,
"text": "Now check your could function, the version should be incremented. Go to theTESTING tab and enjoy passing the tests!"
},
{
"code": null,
"e": 8775,
"s": 8618,
"text": "Now that you mirrored your repository to βCloud Source Repositoriesβ if you check the source of your cloud function you see that it points to your repo now!"
},
{
"code": null,
"e": 8873,
"s": 8775,
"text": "This step may seem redundant since you can deploy from your local, but let's go to the next step."
},
{
"code": null,
"e": 8969,
"s": 8873,
"text": "So far we learned how to deploy from local and from cloud repo, letβs learn setting up a CI/CD!"
},
{
"code": null,
"e": 9054,
"s": 8969,
"text": "You need to add a βcloudbuild.yamlβ to your directory and put the following content:"
},
{
"code": null,
"e": 9422,
"s": 9054,
"text": "steps:- name: gcr.io/cloud-builders/gcloud args: - functions - deploy - my_pipeline_name - --source=https://source.developers.google.com/projects/[gcp_project_name]/repos/[cloud_source_repository_root]/moveable-aliases/[branch]/paths/google_ads/[folder_under_that_branch]/ - --trigger-topic=my_pipeline_topic - --runtime=python37 - --timeout=540"
},
{
"code": null,
"e": 9780,
"s": 9422,
"text": "Now from GCPβs Navigation Menu go to cloud build, go to Triggers and click on βcreate newβ. It should be straight forward now!Give your trigger a name and description. I want to trigger the build every time I push to the branch, so will select that option. From the source section, I will find the mirrored repo from step 6 and enter the name of the branch."
},
{
"code": null,
"e": 9915,
"s": 9780,
"text": "Since the build configuration is saved in the cloudbuild, I will select the first option and copy and paste the path to the YAML file."
}
] |
Why I Use Plotly for Data Visualization | Towards Data Science
|
The amount of data in the world is growing every second. From sending a text to clicking a link, you are creating data points for companies to use. Insights that can be drawn from this collection of data can be extremely valuable. Every business has their own storage of data that they need to examine. One of the most important ways this examination is done is by visualizing the data.
Simply put β βa picture is worth a thousand wordsβ. In the entire history of business, data visualization has remained a necessary component. The reason it is so necessary is ultimately because we are visual creatures. Why else do you think a majority of us would prefer to watch a movie adaptation of a book than read the book itself? In terms of business presentations, a graph or chart of sales data may prove more insightful than just plain text. It is easy to draw insights from visual mediums rather than word documents.
By visualizing the data you are making the data more accessible to a wider audience. This can help draw more insights because someone else might have an insight or two that you may never have thought of. The more people that see your visualization, then the more insights can potentially be made.
Visualizations also play a key role when presenting to crucial decision makers such as board members or shareholders. As you are constructing your numerous graphs and plots to highlight key data points, the visuals you decide to make can help push these decision makers in one direction or another. If the data visuals are presented with a select narrative in mind, then these decision makers will be inclined to make specific decisions based on your presentation.
Sign up for a Medium Membership here to gain unlimited access and support content like mine! With your support I earn a small portion of the membership fee. Thanks!
Pie charts, bar charts, line graphs, and so on are all effective visuals when presenting data. These visuals are the tried and true forms for data presentation and we have made it even easier to create them. What we once use to do by hand can now be done with a couple of clicks on a computer.
Nowadays, we have access to multiple programs to construct beautiful looking charts and graphs. These tools range from more technically based applications of visualization like Pythonβs Matplotlib or Plotly to more user-friendly ones like Tableau or Microsoft Power BI. Data visualizations tools are now more accessible than ever before.
Within the realm of Python programming, there are many different libraries you could use to craft data visualizations. These libraries include, but are not limited, to Altair, Seaborn, and Plotly. There is no superior Python library because it all depends on what you are comfortable with and the problem or data you are trying to visualize.
One of the tools we mentioned before is called Plotly. Plotly is a graphing and plotting library in Python similar to Matplotlib. The difference between the two is the fact that Plotly creates dynamically, interactive charts and graphs.
To get started with Plotly, we will need data to graph or plot first. So letβs say for example you work for a business that sells clothing. They want you to chart the sales for their shirts and jeans over the course of one year and have provided you with the data to do so. This problem will help us begin working with Plotly.
In order to begin, we must first install Plotly by using the following command in your terminal:
$ pip install plotly
Or if you have Anaconda installed:
$ conda install -c plotly plotly
Now that you have Plotly installed, letβs open a new file and start importing the necessary libraries for our data visualization example:
import plotly.express as pximport calendar as calimport randomimport pandas as pd
Here we are using plotly.express, which is a module within Plotly that will quickly create graphs and charts for us.
Since we are not actually given real data, we will have to create our own:
data = {'Months': [cal.month_name[i] for i in range(1,13)], 'Shirts': [round(random.gauss(100, 15)) for _ in range(12)], 'Jeans': [round(random.gauss(50, 20)) for _ in range(12)]}
Plotly works very well with Pandas DataFrames so we will store our newly created data into a DF:
df = pd.DataFrame(data)
This new DF looks like this:
Now that we have our DF ready we can begin crafting our bar chart:
fig = px.bar(df, x='Months', y=['Shirts','Jeans'])fig.show()
Here we are using the .bar() method and inputting the DF of our data, and specifying the x and y axes. We are crafting a stacked bar chart by making a list for the columns: βShirtsβ and βJeansβ. Which weβll display by calling fig.show().
Success! That was simple enough. The cool thing about this Plotly chart is that you can start interacting with it by zooming in, panning, etc. But in regards to the overall chart, there are some things we would like to change to make this graph a little bit more descriptive like adding a title and renaming a few of the labels.
fig = px.bar(df, x='Months', y=['Shirts','Jeans'], title='Total Monthly Item Sales', labels={'variable': 'Item', 'value': 'Quantity Sold (in thousands)'})fig.show()
The difference between this code and the code before is the addition of the title= and labels={} argument. With these new arguments we are adding in a title for the chart and under the labels we are basically using a dictionary to replace the two current labels.
Now that the bar chart is properly labeled, we are basically finished with using Plotly for this data. But what if we wanted to do other kinds of charts or graphs in order to view different sides of the data?
Plotly allows us to create other types of visualizations too. We can easily create a line graph by using the code from before and just changing one thing:
fig = px.line(df, x='Months', y=['Shirts','Jeans'], title='Monthly Item Sales', labels={'variable': 'Item', 'value': 'Quantity Sold (in thousands)'})fig.show()
All we did here was change px.bar to px.line. This now displays the following:
Now we have a line graph! But wait thereβs more...
Letβs say we wanted to compare how many shirts were sold vs how many jeans were sold in the entire year.
First, we must change our data to show the total sum of all sales for shirts and jeans:
pie_df = df[['Shirts','Jeans']].sum()
Here weβre just getting the sum of both Shirts and Jeans from the DF. Then, we will need to use px.pie() using our new summed up DF.
fig = px.pie(values=pie_df.values, names=pie_df.index, title="Sales Percentage in a Year")fig.show()
The argument values is used to determine the sizes of each portion of the pie chart. The names are the labels for each of the portions.
Awesome! Now we have created three different types of visualizations for our data. But you donβt have to stop β there are more options available (see here for more) if you feel the need to continue experimenting with Plotly.
After visualizing our data, we would need to come to some sort of insight or conclusion based on the visuals. What can you tell based on these charts? Are there some obvious conclusions that can be drawn? What about some not so obvious ones?
Anyways, insights and conclusions are easier to see rather than read. If you are still wondering about the importance of visualizations, then just take a look back at the DF we created and compare it to any of the visuals we created with Plotly. Sometimes reading information is not as good as seeing the information.
|
[
{
"code": null,
"e": 559,
"s": 172,
"text": "The amount of data in the world is growing every second. From sending a text to clicking a link, you are creating data points for companies to use. Insights that can be drawn from this collection of data can be extremely valuable. Every business has their own storage of data that they need to examine. One of the most important ways this examination is done is by visualizing the data."
},
{
"code": null,
"e": 1086,
"s": 559,
"text": "Simply put β βa picture is worth a thousand wordsβ. In the entire history of business, data visualization has remained a necessary component. The reason it is so necessary is ultimately because we are visual creatures. Why else do you think a majority of us would prefer to watch a movie adaptation of a book than read the book itself? In terms of business presentations, a graph or chart of sales data may prove more insightful than just plain text. It is easy to draw insights from visual mediums rather than word documents."
},
{
"code": null,
"e": 1383,
"s": 1086,
"text": "By visualizing the data you are making the data more accessible to a wider audience. This can help draw more insights because someone else might have an insight or two that you may never have thought of. The more people that see your visualization, then the more insights can potentially be made."
},
{
"code": null,
"e": 1848,
"s": 1383,
"text": "Visualizations also play a key role when presenting to crucial decision makers such as board members or shareholders. As you are constructing your numerous graphs and plots to highlight key data points, the visuals you decide to make can help push these decision makers in one direction or another. If the data visuals are presented with a select narrative in mind, then these decision makers will be inclined to make specific decisions based on your presentation."
},
{
"code": null,
"e": 2013,
"s": 1848,
"text": "Sign up for a Medium Membership here to gain unlimited access and support content like mine! With your support I earn a small portion of the membership fee. Thanks!"
},
{
"code": null,
"e": 2307,
"s": 2013,
"text": "Pie charts, bar charts, line graphs, and so on are all effective visuals when presenting data. These visuals are the tried and true forms for data presentation and we have made it even easier to create them. What we once use to do by hand can now be done with a couple of clicks on a computer."
},
{
"code": null,
"e": 2645,
"s": 2307,
"text": "Nowadays, we have access to multiple programs to construct beautiful looking charts and graphs. These tools range from more technically based applications of visualization like Pythonβs Matplotlib or Plotly to more user-friendly ones like Tableau or Microsoft Power BI. Data visualizations tools are now more accessible than ever before."
},
{
"code": null,
"e": 2987,
"s": 2645,
"text": "Within the realm of Python programming, there are many different libraries you could use to craft data visualizations. These libraries include, but are not limited, to Altair, Seaborn, and Plotly. There is no superior Python library because it all depends on what you are comfortable with and the problem or data you are trying to visualize."
},
{
"code": null,
"e": 3224,
"s": 2987,
"text": "One of the tools we mentioned before is called Plotly. Plotly is a graphing and plotting library in Python similar to Matplotlib. The difference between the two is the fact that Plotly creates dynamically, interactive charts and graphs."
},
{
"code": null,
"e": 3551,
"s": 3224,
"text": "To get started with Plotly, we will need data to graph or plot first. So letβs say for example you work for a business that sells clothing. They want you to chart the sales for their shirts and jeans over the course of one year and have provided you with the data to do so. This problem will help us begin working with Plotly."
},
{
"code": null,
"e": 3648,
"s": 3551,
"text": "In order to begin, we must first install Plotly by using the following command in your terminal:"
},
{
"code": null,
"e": 3669,
"s": 3648,
"text": "$ pip install plotly"
},
{
"code": null,
"e": 3704,
"s": 3669,
"text": "Or if you have Anaconda installed:"
},
{
"code": null,
"e": 3737,
"s": 3704,
"text": "$ conda install -c plotly plotly"
},
{
"code": null,
"e": 3875,
"s": 3737,
"text": "Now that you have Plotly installed, letβs open a new file and start importing the necessary libraries for our data visualization example:"
},
{
"code": null,
"e": 3957,
"s": 3875,
"text": "import plotly.express as pximport calendar as calimport randomimport pandas as pd"
},
{
"code": null,
"e": 4074,
"s": 3957,
"text": "Here we are using plotly.express, which is a module within Plotly that will quickly create graphs and charts for us."
},
{
"code": null,
"e": 4149,
"s": 4074,
"text": "Since we are not actually given real data, we will have to create our own:"
},
{
"code": null,
"e": 4343,
"s": 4149,
"text": "data = {'Months': [cal.month_name[i] for i in range(1,13)], 'Shirts': [round(random.gauss(100, 15)) for _ in range(12)], 'Jeans': [round(random.gauss(50, 20)) for _ in range(12)]}"
},
{
"code": null,
"e": 4440,
"s": 4343,
"text": "Plotly works very well with Pandas DataFrames so we will store our newly created data into a DF:"
},
{
"code": null,
"e": 4464,
"s": 4440,
"text": "df = pd.DataFrame(data)"
},
{
"code": null,
"e": 4493,
"s": 4464,
"text": "This new DF looks like this:"
},
{
"code": null,
"e": 4560,
"s": 4493,
"text": "Now that we have our DF ready we can begin crafting our bar chart:"
},
{
"code": null,
"e": 4647,
"s": 4560,
"text": "fig = px.bar(df, x='Months', y=['Shirts','Jeans'])fig.show()"
},
{
"code": null,
"e": 4885,
"s": 4647,
"text": "Here we are using the .bar() method and inputting the DF of our data, and specifying the x and y axes. We are crafting a stacked bar chart by making a list for the columns: βShirtsβ and βJeansβ. Which weβll display by calling fig.show()."
},
{
"code": null,
"e": 5214,
"s": 4885,
"text": "Success! That was simple enough. The cool thing about this Plotly chart is that you can start interacting with it by zooming in, panning, etc. But in regards to the overall chart, there are some things we would like to change to make this graph a little bit more descriptive like adding a title and renaming a few of the labels."
},
{
"code": null,
"e": 5449,
"s": 5214,
"text": "fig = px.bar(df, x='Months', y=['Shirts','Jeans'], title='Total Monthly Item Sales', labels={'variable': 'Item', 'value': 'Quantity Sold (in thousands)'})fig.show()"
},
{
"code": null,
"e": 5712,
"s": 5449,
"text": "The difference between this code and the code before is the addition of the title= and labels={} argument. With these new arguments we are adding in a title for the chart and under the labels we are basically using a dictionary to replace the two current labels."
},
{
"code": null,
"e": 5921,
"s": 5712,
"text": "Now that the bar chart is properly labeled, we are basically finished with using Plotly for this data. But what if we wanted to do other kinds of charts or graphs in order to view different sides of the data?"
},
{
"code": null,
"e": 6076,
"s": 5921,
"text": "Plotly allows us to create other types of visualizations too. We can easily create a line graph by using the code from before and just changing one thing:"
},
{
"code": null,
"e": 6311,
"s": 6076,
"text": "fig = px.line(df, x='Months', y=['Shirts','Jeans'], title='Monthly Item Sales', labels={'variable': 'Item', 'value': 'Quantity Sold (in thousands)'})fig.show()"
},
{
"code": null,
"e": 6390,
"s": 6311,
"text": "All we did here was change px.bar to px.line. This now displays the following:"
},
{
"code": null,
"e": 6441,
"s": 6390,
"text": "Now we have a line graph! But wait thereβs more..."
},
{
"code": null,
"e": 6546,
"s": 6441,
"text": "Letβs say we wanted to compare how many shirts were sold vs how many jeans were sold in the entire year."
},
{
"code": null,
"e": 6634,
"s": 6546,
"text": "First, we must change our data to show the total sum of all sales for shirts and jeans:"
},
{
"code": null,
"e": 6672,
"s": 6634,
"text": "pie_df = df[['Shirts','Jeans']].sum()"
},
{
"code": null,
"e": 6805,
"s": 6672,
"text": "Here weβre just getting the sum of both Shirts and Jeans from the DF. Then, we will need to use px.pie() using our new summed up DF."
},
{
"code": null,
"e": 6932,
"s": 6805,
"text": "fig = px.pie(values=pie_df.values, names=pie_df.index, title=\"Sales Percentage in a Year\")fig.show()"
},
{
"code": null,
"e": 7068,
"s": 6932,
"text": "The argument values is used to determine the sizes of each portion of the pie chart. The names are the labels for each of the portions."
},
{
"code": null,
"e": 7293,
"s": 7068,
"text": "Awesome! Now we have created three different types of visualizations for our data. But you donβt have to stop β there are more options available (see here for more) if you feel the need to continue experimenting with Plotly."
},
{
"code": null,
"e": 7535,
"s": 7293,
"text": "After visualizing our data, we would need to come to some sort of insight or conclusion based on the visuals. What can you tell based on these charts? Are there some obvious conclusions that can be drawn? What about some not so obvious ones?"
}
] |
Hyperparameter Tuning to Reduce Overfitting β LightGBM | by Soner YΔ±ldΔ±rΔ±m | Towards Data Science
|
Easy access to an enormous amount of data and high computing power has made it possible to design complex machine learning algorithms. As the model complexity increases, the amount of data required to train it also increases.
Data is not the only factor in the performance of a model. Complex models have many hyperparameters that need to be correctly adjusted or tuned in order to make the most out of them.
For instance, the performance of XGBoost and LightGBM highly depend on the hyperparameter tuning. It would be like driving a Ferrari at a speed of 50 mph to implement these algorithms without carefully adjusting the hyperparameters.
In this post, we will experiment with how the performance of LightGBM changes based on hyperparameter values. The focus is on the parameters that help to generalize the models and thus reduce the risk of overfitting.
Letβs start with importing the libraries.
import pandas as pdfrom sklearn.model_selection import train_test_splitimport lightgbm as lgb
The dataset contains 60 k observations, 99 numerical features, and a target variable.
The target variable contains 9 values which makes it a multi-class classification task.
Our focus is hyperparameter tuning so we will skip the data wrangling part. The following code block splits the dataset into train and test subsets and converts them to a format suitable for LightGBM.
X = df.drop('target', axis=1)y = df['target']X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.33, random_state=42)lgb_train = lgb.Dataset(X_train, y_train)lgb_test = lgb.Dataset(X_test, y_test)
We will start with a basic set of new hyperparameters and introduce new ones step-by-step.
params = {'boosting_type': 'gbdt','objective': 'multiclass','metric': 'multi_logloss','num_class':9}
We can now train the model and see the results based on the specified evaluation metric.
gbm = lgb.train(params,lgb_train,num_boost_round=500,valid_sets=[lgb_train, lgb_test],early_stopping_rounds=10)
The evaluation metric is multi-class log loss. Here is the result of both training and validation sets.
The number of boosting rounds is set as 500 but early stopping occurred. The early_stopping_rounds stops the training if the performance does not improve in the specified number of rounds.
It seems like the model is highly overfitting to the training set because there is a significant difference between losses on training and validation sets.
The min_data_in_leaf parameter is a way to reduce overfitting. It requires each leaf to have the specified number of observations so that the model does not become too specific.
'min_data_in_leaf':300 #added to params dict
The validation loss is almost the same but the difference got smaller which means the degree of overfitting reduced.
Another parameter to prevent the model from being too specific is feature_fraction which indicates the ratio of features to be randomly selected at each iteration.
'feature_fraction':0.8 #added to params dict
Now the model uses 80% of the features at each iteration. Here is the result.
The overfitting further reduced.
Bagging_fraction allows using a randomly selected sample of rows to be used at each iteration. It is similar to feature_fraction but for rows. The bagging_freq specifies the iteration frequency to update selected rows.
#added to params dict'bagging_fraction':0.8,'bagging_freq':10
The difference between train and validation losses is decreasing which indicates we are on the right track.
LightGBM is an ensemble method using boosting technique to combine decision trees. The complexity of an individual tree is also a determining factor in overfitting. It can be controlled with the max_depth and num_leaves parameters. The max_depth determines the maximum depth of a tree while num_leaves limits the maximum number of leafs a tree can have. Since LightGBM adapts leaf-wise tree growth, it is important to adjust these two parameters together.
Another important parameter is the learning_rate. The smaller learning rates are usually better but it causes the model to learn slower.
We can also add a regularization term as a hyperparameter. LightGBM supports both L1 and L2 regularizations.
#added to params dict'max_depth':8,'num_leaves':70,'learning_rate':0.04
Weβve further decreased the difference between the train and validation loss which means less overfitting.
The number of iterations is also an important factor in model training. The more iterations cause the model to learn more and thus the model starts overfitting after a certain amount of iterations.
You may need to spend a good amount of time tuning the hyperparameters. Eventually, you will create your own way or strategy that will expedite the process of tuning.
There are lots of hyperparameters. Some are more important in terms of accuracy and speed. Some of them are mainly used to prevent overfitting.
Cross-validation can be used to reduce overfitting as well. It allows using each data point in both training and validation sets.
We have focused only on reducing the overfitting. However, eliminating the overfitting does not matter much if the accuracy or loss is not satisfying. You can also tune hyperparameters to increase the accuracy to some extent. Some ways to work on to increase the performance of a model are:
Feature engineering
Feature extraction
Ensembling multiple models
Thank you for reading. Please let me know if you have any feedback.
|
[
{
"code": null,
"e": 397,
"s": 171,
"text": "Easy access to an enormous amount of data and high computing power has made it possible to design complex machine learning algorithms. As the model complexity increases, the amount of data required to train it also increases."
},
{
"code": null,
"e": 580,
"s": 397,
"text": "Data is not the only factor in the performance of a model. Complex models have many hyperparameters that need to be correctly adjusted or tuned in order to make the most out of them."
},
{
"code": null,
"e": 813,
"s": 580,
"text": "For instance, the performance of XGBoost and LightGBM highly depend on the hyperparameter tuning. It would be like driving a Ferrari at a speed of 50 mph to implement these algorithms without carefully adjusting the hyperparameters."
},
{
"code": null,
"e": 1030,
"s": 813,
"text": "In this post, we will experiment with how the performance of LightGBM changes based on hyperparameter values. The focus is on the parameters that help to generalize the models and thus reduce the risk of overfitting."
},
{
"code": null,
"e": 1072,
"s": 1030,
"text": "Letβs start with importing the libraries."
},
{
"code": null,
"e": 1166,
"s": 1072,
"text": "import pandas as pdfrom sklearn.model_selection import train_test_splitimport lightgbm as lgb"
},
{
"code": null,
"e": 1252,
"s": 1166,
"text": "The dataset contains 60 k observations, 99 numerical features, and a target variable."
},
{
"code": null,
"e": 1340,
"s": 1252,
"text": "The target variable contains 9 values which makes it a multi-class classification task."
},
{
"code": null,
"e": 1541,
"s": 1340,
"text": "Our focus is hyperparameter tuning so we will skip the data wrangling part. The following code block splits the dataset into train and test subsets and converts them to a format suitable for LightGBM."
},
{
"code": null,
"e": 1758,
"s": 1541,
"text": "X = df.drop('target', axis=1)y = df['target']X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.33, random_state=42)lgb_train = lgb.Dataset(X_train, y_train)lgb_test = lgb.Dataset(X_test, y_test)"
},
{
"code": null,
"e": 1849,
"s": 1758,
"text": "We will start with a basic set of new hyperparameters and introduce new ones step-by-step."
},
{
"code": null,
"e": 1950,
"s": 1849,
"text": "params = {'boosting_type': 'gbdt','objective': 'multiclass','metric': 'multi_logloss','num_class':9}"
},
{
"code": null,
"e": 2039,
"s": 1950,
"text": "We can now train the model and see the results based on the specified evaluation metric."
},
{
"code": null,
"e": 2151,
"s": 2039,
"text": "gbm = lgb.train(params,lgb_train,num_boost_round=500,valid_sets=[lgb_train, lgb_test],early_stopping_rounds=10)"
},
{
"code": null,
"e": 2255,
"s": 2151,
"text": "The evaluation metric is multi-class log loss. Here is the result of both training and validation sets."
},
{
"code": null,
"e": 2444,
"s": 2255,
"text": "The number of boosting rounds is set as 500 but early stopping occurred. The early_stopping_rounds stops the training if the performance does not improve in the specified number of rounds."
},
{
"code": null,
"e": 2600,
"s": 2444,
"text": "It seems like the model is highly overfitting to the training set because there is a significant difference between losses on training and validation sets."
},
{
"code": null,
"e": 2778,
"s": 2600,
"text": "The min_data_in_leaf parameter is a way to reduce overfitting. It requires each leaf to have the specified number of observations so that the model does not become too specific."
},
{
"code": null,
"e": 2823,
"s": 2778,
"text": "'min_data_in_leaf':300 #added to params dict"
},
{
"code": null,
"e": 2940,
"s": 2823,
"text": "The validation loss is almost the same but the difference got smaller which means the degree of overfitting reduced."
},
{
"code": null,
"e": 3104,
"s": 2940,
"text": "Another parameter to prevent the model from being too specific is feature_fraction which indicates the ratio of features to be randomly selected at each iteration."
},
{
"code": null,
"e": 3149,
"s": 3104,
"text": "'feature_fraction':0.8 #added to params dict"
},
{
"code": null,
"e": 3227,
"s": 3149,
"text": "Now the model uses 80% of the features at each iteration. Here is the result."
},
{
"code": null,
"e": 3260,
"s": 3227,
"text": "The overfitting further reduced."
},
{
"code": null,
"e": 3479,
"s": 3260,
"text": "Bagging_fraction allows using a randomly selected sample of rows to be used at each iteration. It is similar to feature_fraction but for rows. The bagging_freq specifies the iteration frequency to update selected rows."
},
{
"code": null,
"e": 3541,
"s": 3479,
"text": "#added to params dict'bagging_fraction':0.8,'bagging_freq':10"
},
{
"code": null,
"e": 3649,
"s": 3541,
"text": "The difference between train and validation losses is decreasing which indicates we are on the right track."
},
{
"code": null,
"e": 4105,
"s": 3649,
"text": "LightGBM is an ensemble method using boosting technique to combine decision trees. The complexity of an individual tree is also a determining factor in overfitting. It can be controlled with the max_depth and num_leaves parameters. The max_depth determines the maximum depth of a tree while num_leaves limits the maximum number of leafs a tree can have. Since LightGBM adapts leaf-wise tree growth, it is important to adjust these two parameters together."
},
{
"code": null,
"e": 4242,
"s": 4105,
"text": "Another important parameter is the learning_rate. The smaller learning rates are usually better but it causes the model to learn slower."
},
{
"code": null,
"e": 4351,
"s": 4242,
"text": "We can also add a regularization term as a hyperparameter. LightGBM supports both L1 and L2 regularizations."
},
{
"code": null,
"e": 4423,
"s": 4351,
"text": "#added to params dict'max_depth':8,'num_leaves':70,'learning_rate':0.04"
},
{
"code": null,
"e": 4530,
"s": 4423,
"text": "Weβve further decreased the difference between the train and validation loss which means less overfitting."
},
{
"code": null,
"e": 4728,
"s": 4530,
"text": "The number of iterations is also an important factor in model training. The more iterations cause the model to learn more and thus the model starts overfitting after a certain amount of iterations."
},
{
"code": null,
"e": 4895,
"s": 4728,
"text": "You may need to spend a good amount of time tuning the hyperparameters. Eventually, you will create your own way or strategy that will expedite the process of tuning."
},
{
"code": null,
"e": 5039,
"s": 4895,
"text": "There are lots of hyperparameters. Some are more important in terms of accuracy and speed. Some of them are mainly used to prevent overfitting."
},
{
"code": null,
"e": 5169,
"s": 5039,
"text": "Cross-validation can be used to reduce overfitting as well. It allows using each data point in both training and validation sets."
},
{
"code": null,
"e": 5460,
"s": 5169,
"text": "We have focused only on reducing the overfitting. However, eliminating the overfitting does not matter much if the accuracy or loss is not satisfying. You can also tune hyperparameters to increase the accuracy to some extent. Some ways to work on to increase the performance of a model are:"
},
{
"code": null,
"e": 5480,
"s": 5460,
"text": "Feature engineering"
},
{
"code": null,
"e": 5499,
"s": 5480,
"text": "Feature extraction"
},
{
"code": null,
"e": 5526,
"s": 5499,
"text": "Ensembling multiple models"
}
] |
How to Rename SQL Server Schema? - GeeksforGeeks
|
29 Dec, 2021
In SQL, we cannot RENAME a SCHEMA. To achieve this, we need to create a new SCHEMA, transfer all the contents(objects) from the old schema to new schema and then finally delete the old schema using the DROP command. The same is depicted in the below article. For this article, we will be using the Microsoft SQL Server as our database.
Step 1: Display all the current existing schemas in the system.
Query:
SELECT * FROM SYS.SCHEMAS;
Output:
Step 2: Create a schema named OLDSCHEMA.
Syntax:
CREATE SCHEMA SCHEMA_NAME;
Query:
CREATE SCHEMA OLDSCHEMA;
Output:
Step 3: Display all the current existing schemas in the system.
Query:
SELECT * FROM SYS.SCHEMAS;
Note :The OLDSCHEMA should now be visible in the list of schemas.
Output:
Step 4: Create a table TABLE1 inside the schema OLDSCHEMA. This table has 2 columns namely ID and T_NAME containing the id number and name of the entities.
Query:
CREATE TABLE OLDSCHEMA.TABLE1(
ID INT,
TNAME VARCHAR(10)
);
Output:
Step 5: Create a table TABLE2 inside the schema OLDSCHEMA. This table has 2 columns namely ID and T_NAME containing the id number and name of the entities.
Query:
CREATE TABLE OLDSCHEMA.TABLE2(
ID INT,
TNAME VARCHAR(10)
);
Output:
Step 6: Display all the tables(or objects) inside the schema OLDSCHEMA. The schema name(SCHEMA_NAME), name(TABLE_NAME), the creation date(CREATE_DATE) and the last modified date(MODIFY_DATE) of the tables are selected and displayed. An alias of the SYS.TABLES named T is used to shorten the query.
Syntax:
SELECT SCHEMA_NAME(T.SCHEMA_ID)
AS SCHEMA_NAME,
T.NAME AS TABLE_NAME, T.CREATE_DATE,
T.MODIFY_DATE FROM SYS.TABLES T
WHERE SCHEMA_NAME(T.SCHEMA_ID)='SCHEMA_NAME'
ORDER BY TABLE_NAME;
Query:
SELECT SCHEMA_NAME(T.SCHEMA_ID)
AS SCHEMA_NAME,
T.NAME AS TABLE_NAME, T.CREATE_DATE,
T.MODIFY_DATE FROM SYS.TABLES T
WHERE SCHEMA_NAME(T.SCHEMA_ID)='OLDSCHEMA'
ORDER BY TABLE_NAME;
Note: The two newly created tables TABLE1 and TABLE2 are now visible in the OLDSCHEMA.
Output:
Step 7: Create a schema named NEWSCHEMA.
Query:
CREATE SCHEMA NEWSCHEMA;
Output:
Step 8: Display all the current existing schemas in the system.
Query:
SELECT * FROM SYS.SCHEMAS;
Note: Both the schemas i.e. the OLDSCHEMA and the NEWSCHEMA should now be visible in the list of schemas.
Output:
Step 9: Since it is impossible to rename a schema in SQL Server, we transfer all the objects of the old schema to the newly created schema and DROP the old schema. Here in this step, we transfer the TABLE1 table from OLDSCHEMA to NEWSCHEMA.
Syntax:
ALTER SCHEMA NEW_NAMED_SCHEMA
TRANSFER OLD_NAMED_SCHEMA.TABLE_NAME;
Query:
ALTER SCHEMA NEWSCHEMA
TRANSFER OLDSCHEMA.TABLE1;
Output:
Step 10: Here in this step, we transfer the TABLE2 table from OLDSCHEMA to NEWSCHEMA.
Query:
ALTER SCHEMA NEWSCHEMA
TRANSFER OLDSCHEMA.TABLE2;
Output:
Step 11: Display all the tables(or objects) inside the schema NEWSCHEMA. The schema name(SCHEMA_NAME), name(TABLE_NAME), the creation date(CREATE_DATE) and the last modified date(MODIFY_DATE) of the tables are selected and displayed. An alias of the SYS.TABLES named T is used to shorten the query.
Query:
SELECT SCHEMA_NAME(T.SCHEMA_ID)
AS SCHEMA_NAME,
T.NAME AS TABLE_NAME, T.CREATE_DATE,
T.MODIFY_DATE FROM SYS.TABLES T
WHERE SCHEMA_NAME(T.SCHEMA_ID)='NEWSCHEMA'
ORDER BY TABLE_NAME;
Note: The two tables TABLE1 and TABLE2 transferred from the OLDSCHEMA are now visible in the NEWSCHEMA.
Output:
Step 12: Now since we have successfully transferred the two tables TABLE1 and TABLE2 into the NEWSCHEMA, we no longer need the OLDSCHEMA. So, we delete the OLDSCHEMA using the DROP command.
Syntax:
DROP SCHEMA SCHEMA_NAME;
Query:
DROP SCHEMA OLDSCHEMA;
Output:
Step 13: Display all the current existing schemas in the system.
Query:
SELECT * FROM SYS.SCHEMAS;
Note: The OLDSCHEMA should not be visible now in the list of schemas, but the NEWSCHEMA must be visible.
Output:
Picked
SQL-Query
SQL-Server
How To
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install FFmpeg on Windows?
How to Set Git Username and Password in GitBash?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Install Jupyter Notebook on MacOS?
How to Check the OS Version in Linux?
SQL | DDL, DQL, DML, DCL and TCL Commands
SQL | Join (Inner, Left, Right and Full Joins)
SQL | WITH clause
How to find Nth highest salary from a table
SQL | ALTER (RENAME)
|
[
{
"code": null,
"e": 24952,
"s": 24924,
"text": "\n29 Dec, 2021"
},
{
"code": null,
"e": 25288,
"s": 24952,
"text": "In SQL, we cannot RENAME a SCHEMA. To achieve this, we need to create a new SCHEMA, transfer all the contents(objects) from the old schema to new schema and then finally delete the old schema using the DROP command. The same is depicted in the below article. For this article, we will be using the Microsoft SQL Server as our database."
},
{
"code": null,
"e": 25352,
"s": 25288,
"text": "Step 1: Display all the current existing schemas in the system."
},
{
"code": null,
"e": 25359,
"s": 25352,
"text": "Query:"
},
{
"code": null,
"e": 25386,
"s": 25359,
"text": "SELECT * FROM SYS.SCHEMAS;"
},
{
"code": null,
"e": 25394,
"s": 25386,
"text": "Output:"
},
{
"code": null,
"e": 25435,
"s": 25394,
"text": "Step 2: Create a schema named OLDSCHEMA."
},
{
"code": null,
"e": 25443,
"s": 25435,
"text": "Syntax:"
},
{
"code": null,
"e": 25470,
"s": 25443,
"text": "CREATE SCHEMA SCHEMA_NAME;"
},
{
"code": null,
"e": 25477,
"s": 25470,
"text": "Query:"
},
{
"code": null,
"e": 25502,
"s": 25477,
"text": "CREATE SCHEMA OLDSCHEMA;"
},
{
"code": null,
"e": 25510,
"s": 25502,
"text": "Output:"
},
{
"code": null,
"e": 25574,
"s": 25510,
"text": "Step 3: Display all the current existing schemas in the system."
},
{
"code": null,
"e": 25581,
"s": 25574,
"text": "Query:"
},
{
"code": null,
"e": 25608,
"s": 25581,
"text": "SELECT * FROM SYS.SCHEMAS;"
},
{
"code": null,
"e": 25674,
"s": 25608,
"text": "Note :The OLDSCHEMA should now be visible in the list of schemas."
},
{
"code": null,
"e": 25682,
"s": 25674,
"text": "Output:"
},
{
"code": null,
"e": 25838,
"s": 25682,
"text": "Step 4: Create a table TABLE1 inside the schema OLDSCHEMA. This table has 2 columns namely ID and T_NAME containing the id number and name of the entities."
},
{
"code": null,
"e": 25845,
"s": 25838,
"text": "Query:"
},
{
"code": null,
"e": 25905,
"s": 25845,
"text": "CREATE TABLE OLDSCHEMA.TABLE1(\nID INT,\nTNAME VARCHAR(10)\n);"
},
{
"code": null,
"e": 25913,
"s": 25905,
"text": "Output:"
},
{
"code": null,
"e": 26069,
"s": 25913,
"text": "Step 5: Create a table TABLE2 inside the schema OLDSCHEMA. This table has 2 columns namely ID and T_NAME containing the id number and name of the entities."
},
{
"code": null,
"e": 26076,
"s": 26069,
"text": "Query:"
},
{
"code": null,
"e": 26136,
"s": 26076,
"text": "CREATE TABLE OLDSCHEMA.TABLE2(\nID INT,\nTNAME VARCHAR(10)\n);"
},
{
"code": null,
"e": 26144,
"s": 26136,
"text": "Output:"
},
{
"code": null,
"e": 26442,
"s": 26144,
"text": "Step 6: Display all the tables(or objects) inside the schema OLDSCHEMA. The schema name(SCHEMA_NAME), name(TABLE_NAME), the creation date(CREATE_DATE) and the last modified date(MODIFY_DATE) of the tables are selected and displayed. An alias of the SYS.TABLES named T is used to shorten the query."
},
{
"code": null,
"e": 26450,
"s": 26442,
"text": "Syntax:"
},
{
"code": null,
"e": 26635,
"s": 26450,
"text": "SELECT SCHEMA_NAME(T.SCHEMA_ID)\nAS SCHEMA_NAME,\nT.NAME AS TABLE_NAME, T.CREATE_DATE, \nT.MODIFY_DATE FROM SYS.TABLES T\nWHERE SCHEMA_NAME(T.SCHEMA_ID)='SCHEMA_NAME' \nORDER BY TABLE_NAME;"
},
{
"code": null,
"e": 26642,
"s": 26635,
"text": "Query:"
},
{
"code": null,
"e": 26823,
"s": 26642,
"text": "SELECT SCHEMA_NAME(T.SCHEMA_ID)\nAS SCHEMA_NAME,\nT.NAME AS TABLE_NAME, T.CREATE_DATE,\nT.MODIFY_DATE FROM SYS.TABLES T\nWHERE SCHEMA_NAME(T.SCHEMA_ID)='OLDSCHEMA'\nORDER BY TABLE_NAME;"
},
{
"code": null,
"e": 26910,
"s": 26823,
"text": "Note: The two newly created tables TABLE1 and TABLE2 are now visible in the OLDSCHEMA."
},
{
"code": null,
"e": 26918,
"s": 26910,
"text": "Output:"
},
{
"code": null,
"e": 26959,
"s": 26918,
"text": "Step 7: Create a schema named NEWSCHEMA."
},
{
"code": null,
"e": 26966,
"s": 26959,
"text": "Query:"
},
{
"code": null,
"e": 26991,
"s": 26966,
"text": "CREATE SCHEMA NEWSCHEMA;"
},
{
"code": null,
"e": 26999,
"s": 26991,
"text": "Output:"
},
{
"code": null,
"e": 27063,
"s": 26999,
"text": "Step 8: Display all the current existing schemas in the system."
},
{
"code": null,
"e": 27070,
"s": 27063,
"text": "Query:"
},
{
"code": null,
"e": 27097,
"s": 27070,
"text": "SELECT * FROM SYS.SCHEMAS;"
},
{
"code": null,
"e": 27203,
"s": 27097,
"text": "Note: Both the schemas i.e. the OLDSCHEMA and the NEWSCHEMA should now be visible in the list of schemas."
},
{
"code": null,
"e": 27211,
"s": 27203,
"text": "Output:"
},
{
"code": null,
"e": 27452,
"s": 27211,
"text": "Step 9: Since it is impossible to rename a schema in SQL Server, we transfer all the objects of the old schema to the newly created schema and DROP the old schema. Here in this step, we transfer the TABLE1 table from OLDSCHEMA to NEWSCHEMA."
},
{
"code": null,
"e": 27460,
"s": 27452,
"text": "Syntax:"
},
{
"code": null,
"e": 27528,
"s": 27460,
"text": "ALTER SCHEMA NEW_NAMED_SCHEMA\nTRANSFER OLD_NAMED_SCHEMA.TABLE_NAME;"
},
{
"code": null,
"e": 27535,
"s": 27528,
"text": "Query:"
},
{
"code": null,
"e": 27585,
"s": 27535,
"text": "ALTER SCHEMA NEWSCHEMA\nTRANSFER OLDSCHEMA.TABLE1;"
},
{
"code": null,
"e": 27593,
"s": 27585,
"text": "Output:"
},
{
"code": null,
"e": 27679,
"s": 27593,
"text": "Step 10: Here in this step, we transfer the TABLE2 table from OLDSCHEMA to NEWSCHEMA."
},
{
"code": null,
"e": 27686,
"s": 27679,
"text": "Query:"
},
{
"code": null,
"e": 27737,
"s": 27686,
"text": "ALTER SCHEMA NEWSCHEMA \nTRANSFER OLDSCHEMA.TABLE2;"
},
{
"code": null,
"e": 27745,
"s": 27737,
"text": "Output:"
},
{
"code": null,
"e": 28044,
"s": 27745,
"text": "Step 11: Display all the tables(or objects) inside the schema NEWSCHEMA. The schema name(SCHEMA_NAME), name(TABLE_NAME), the creation date(CREATE_DATE) and the last modified date(MODIFY_DATE) of the tables are selected and displayed. An alias of the SYS.TABLES named T is used to shorten the query."
},
{
"code": null,
"e": 28051,
"s": 28044,
"text": "Query:"
},
{
"code": null,
"e": 28234,
"s": 28051,
"text": "SELECT SCHEMA_NAME(T.SCHEMA_ID) \nAS SCHEMA_NAME,\nT.NAME AS TABLE_NAME, T.CREATE_DATE,\nT.MODIFY_DATE FROM SYS.TABLES T\nWHERE SCHEMA_NAME(T.SCHEMA_ID)='NEWSCHEMA' \nORDER BY TABLE_NAME;"
},
{
"code": null,
"e": 28338,
"s": 28234,
"text": "Note: The two tables TABLE1 and TABLE2 transferred from the OLDSCHEMA are now visible in the NEWSCHEMA."
},
{
"code": null,
"e": 28346,
"s": 28338,
"text": "Output:"
},
{
"code": null,
"e": 28536,
"s": 28346,
"text": "Step 12: Now since we have successfully transferred the two tables TABLE1 and TABLE2 into the NEWSCHEMA, we no longer need the OLDSCHEMA. So, we delete the OLDSCHEMA using the DROP command."
},
{
"code": null,
"e": 28544,
"s": 28536,
"text": "Syntax:"
},
{
"code": null,
"e": 28569,
"s": 28544,
"text": "DROP SCHEMA SCHEMA_NAME;"
},
{
"code": null,
"e": 28576,
"s": 28569,
"text": "Query:"
},
{
"code": null,
"e": 28599,
"s": 28576,
"text": "DROP SCHEMA OLDSCHEMA;"
},
{
"code": null,
"e": 28607,
"s": 28599,
"text": "Output:"
},
{
"code": null,
"e": 28672,
"s": 28607,
"text": "Step 13: Display all the current existing schemas in the system."
},
{
"code": null,
"e": 28679,
"s": 28672,
"text": "Query:"
},
{
"code": null,
"e": 28706,
"s": 28679,
"text": "SELECT * FROM SYS.SCHEMAS;"
},
{
"code": null,
"e": 28811,
"s": 28706,
"text": "Note: The OLDSCHEMA should not be visible now in the list of schemas, but the NEWSCHEMA must be visible."
},
{
"code": null,
"e": 28819,
"s": 28811,
"text": "Output:"
},
{
"code": null,
"e": 28826,
"s": 28819,
"text": "Picked"
},
{
"code": null,
"e": 28836,
"s": 28826,
"text": "SQL-Query"
},
{
"code": null,
"e": 28847,
"s": 28836,
"text": "SQL-Server"
},
{
"code": null,
"e": 28854,
"s": 28847,
"text": "How To"
},
{
"code": null,
"e": 28858,
"s": 28854,
"text": "SQL"
},
{
"code": null,
"e": 28862,
"s": 28858,
"text": "SQL"
},
{
"code": null,
"e": 28960,
"s": 28862,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28994,
"s": 28960,
"text": "How to Install FFmpeg on Windows?"
},
{
"code": null,
"e": 29043,
"s": 28994,
"text": "How to Set Git Username and Password in GitBash?"
},
{
"code": null,
"e": 29101,
"s": 29043,
"text": "How to Add External JAR File to an IntelliJ IDEA Project?"
},
{
"code": null,
"e": 29143,
"s": 29101,
"text": "How to Install Jupyter Notebook on MacOS?"
},
{
"code": null,
"e": 29181,
"s": 29143,
"text": "How to Check the OS Version in Linux?"
},
{
"code": null,
"e": 29223,
"s": 29181,
"text": "SQL | DDL, DQL, DML, DCL and TCL Commands"
},
{
"code": null,
"e": 29270,
"s": 29223,
"text": "SQL | Join (Inner, Left, Right and Full Joins)"
},
{
"code": null,
"e": 29288,
"s": 29270,
"text": "SQL | WITH clause"
},
{
"code": null,
"e": 29332,
"s": 29288,
"text": "How to find Nth highest salary from a table"
}
] |
Adding Images to a Slide in a PPT using Java - GeeksforGeeks
|
28 Dec, 2020
In Java, using createPicture() method from XSLFSlide, images can be added to the PPT. Now the computer doesnβt understand, whatβs there in the picture, so internally, this method accepts the image in a byte array format β> (a series of non-understandable random numbers, letters, symbols, etc.) something like this, AGETRDYDC5545#$^NHVGCFFSFSFGSDF#@@?.0976*).
The syntax for an empty slideshow
XMLSlideShow ppt = new XMLSlideShow();
The syntax for creating slide
XSLFSlide slide = ppt.createSlide();
The next task is to read the image file, which we wish to insert, and then convert it into a byte array using IOUtils.toByteArray() β> IOUtils class.
Add image into the presentation, using addPicture():
Byte array format of the picture which is to be added(written in the code as byte[] photo)
A static variable, which represents the file format of the image.
Syntax:
int idx = ppt.addPicture(photo, XSLFPictureData.PICTURE_TYPE_PNG);
Insert the image to a slide, using createPicture().
XSLFPictureShape pic = slide.createPicture(idx);
Implementation:
Java
// Adding Images to a slide in a PPT using javaimport java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException; import org.apache.poi.util.IOUtils;import org.apache.poi.xslf.usermodel.XMLSlideShow;import org.apache.poi.xslf.usermodel.XSLFPictureData;import org.apache.poi.xslf.usermodel.XSLFPictureShape;import org.apache.poi.xslf.usermodel.XSLFSlide; public class InsertingImage { public static void main(String args[]) throws IOException { XMLSlideShow ppt = new XMLSlideShow(); XSLFSlide slide = ppt.createSlide(); File image = new File("C://Folder//codingisfun.png"); byte[] photo = IOUtils.toByteArray( new FileInputStream(image)); int idx = ppt.addPicture( photo, XSLFPictureData.PICTURE_TYPE_PNG); XSLFPictureShape pic = slide.createPicture(idx); // we are creating a file object File file = new File("insertingimg.pptx"); FileOutputStream out = new FileOutputStream(file); // saving the changes to the file we created ppt.write(out); System.out.println("image is inserted"); out.close(); }}
Commands for Compilation and Execution:
$javac InsertingImage.java
$java InsertingImage
Output:
Reordering of the slides is done.
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Initialize an ArrayList in Java
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Interfaces in Java
ArrayList in Java
Convert a String to Character array in Java
Initializing a List in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
|
[
{
"code": null,
"e": 24056,
"s": 24028,
"text": "\n28 Dec, 2020"
},
{
"code": null,
"e": 24416,
"s": 24056,
"text": "In Java, using createPicture() method from XSLFSlide, images can be added to the PPT. Now the computer doesnβt understand, whatβs there in the picture, so internally, this method accepts the image in a byte array format β> (a series of non-understandable random numbers, letters, symbols, etc.) something like this, AGETRDYDC5545#$^NHVGCFFSFSFGSDF#@@?.0976*)."
},
{
"code": null,
"e": 24450,
"s": 24416,
"text": "The syntax for an empty slideshow"
},
{
"code": null,
"e": 24489,
"s": 24450,
"text": "XMLSlideShow ppt = new XMLSlideShow();"
},
{
"code": null,
"e": 24519,
"s": 24489,
"text": "The syntax for creating slide"
},
{
"code": null,
"e": 24556,
"s": 24519,
"text": "XSLFSlide slide = ppt.createSlide();"
},
{
"code": null,
"e": 24706,
"s": 24556,
"text": "The next task is to read the image file, which we wish to insert, and then convert it into a byte array using IOUtils.toByteArray() β> IOUtils class."
},
{
"code": null,
"e": 24759,
"s": 24706,
"text": "Add image into the presentation, using addPicture():"
},
{
"code": null,
"e": 24850,
"s": 24759,
"text": "Byte array format of the picture which is to be added(written in the code as byte[] photo)"
},
{
"code": null,
"e": 24916,
"s": 24850,
"text": "A static variable, which represents the file format of the image."
},
{
"code": null,
"e": 24924,
"s": 24916,
"text": "Syntax:"
},
{
"code": null,
"e": 24991,
"s": 24924,
"text": "int idx = ppt.addPicture(photo, XSLFPictureData.PICTURE_TYPE_PNG);"
},
{
"code": null,
"e": 25043,
"s": 24991,
"text": "Insert the image to a slide, using createPicture()."
},
{
"code": null,
"e": 25092,
"s": 25043,
"text": "XSLFPictureShape pic = slide.createPicture(idx);"
},
{
"code": null,
"e": 25108,
"s": 25092,
"text": "Implementation:"
},
{
"code": null,
"e": 25113,
"s": 25108,
"text": "Java"
},
{
"code": "// Adding Images to a slide in a PPT using javaimport java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException; import org.apache.poi.util.IOUtils;import org.apache.poi.xslf.usermodel.XMLSlideShow;import org.apache.poi.xslf.usermodel.XSLFPictureData;import org.apache.poi.xslf.usermodel.XSLFPictureShape;import org.apache.poi.xslf.usermodel.XSLFSlide; public class InsertingImage { public static void main(String args[]) throws IOException { XMLSlideShow ppt = new XMLSlideShow(); XSLFSlide slide = ppt.createSlide(); File image = new File(\"C://Folder//codingisfun.png\"); byte[] photo = IOUtils.toByteArray( new FileInputStream(image)); int idx = ppt.addPicture( photo, XSLFPictureData.PICTURE_TYPE_PNG); XSLFPictureShape pic = slide.createPicture(idx); // we are creating a file object File file = new File(\"insertingimg.pptx\"); FileOutputStream out = new FileOutputStream(file); // saving the changes to the file we created ppt.write(out); System.out.println(\"image is inserted\"); out.close(); }}",
"e": 26318,
"s": 25113,
"text": null
},
{
"code": null,
"e": 26358,
"s": 26318,
"text": "Commands for Compilation and Execution:"
},
{
"code": null,
"e": 26406,
"s": 26358,
"text": "$javac InsertingImage.java\n$java InsertingImage"
},
{
"code": null,
"e": 26414,
"s": 26406,
"text": "Output:"
},
{
"code": null,
"e": 26448,
"s": 26414,
"text": "Reordering of the slides is done."
},
{
"code": null,
"e": 26455,
"s": 26448,
"text": "Picked"
},
{
"code": null,
"e": 26460,
"s": 26455,
"text": "Java"
},
{
"code": null,
"e": 26474,
"s": 26460,
"text": "Java Programs"
},
{
"code": null,
"e": 26479,
"s": 26474,
"text": "Java"
},
{
"code": null,
"e": 26577,
"s": 26479,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26609,
"s": 26577,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 26660,
"s": 26609,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 26690,
"s": 26660,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 26709,
"s": 26690,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 26727,
"s": 26709,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 26771,
"s": 26727,
"text": "Convert a String to Character array in Java"
},
{
"code": null,
"e": 26799,
"s": 26771,
"text": "Initializing a List in Java"
},
{
"code": null,
"e": 26825,
"s": 26799,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 26859,
"s": 26825,
"text": "Convert Double to Integer in Java"
}
] |
Pytest - Grouping the Tests
|
In this chapter, we will learn how to group the tests using markers.
Pytest allows us to use markers on test functions. Markers are used to set various features/attributes to test functions. Pytest provides many inbuilt markers such as xfail, skip and parametrize. Apart from that, users can create their own marker names. Markers are applied on the tests using the syntax given below β
@pytest.mark.<markername>
To use markers, we have to import pytest module in the test file. We can define our own marker names to the tests and run the tests having those marker names.
To run the marked tests, we can use the following syntax β
pytest -m <markername> -v
-m <markername> represents the marker name of the tests to be executed.
Update our test files test_compare.py and test_square.py with the following code. We are defining 3 markers β great, square, others.
import pytest
@pytest.mark.great
def test_greater():
num = 100
assert num > 100
@pytest.mark.great
def test_greater_equal():
num = 100
assert num >= 100
@pytest.mark.others
def test_less():
num = 100
assert num < 200
import pytest
import math
@pytest.mark.square
def test_sqrt():
num = 25
assert math.sqrt(num) == 5
@pytest.mark.square
def testsquare():
num = 7
assert 7*7 == 40
@pytest.mark.others
def test_equality():
assert 10 == 11
Now to run the tests marked as others, run the following command β
pytest -m others -v
See the result below. It ran the 2 tests marked as others.
test_compare.py::test_less PASSED
test_square.py::test_equality FAILED
============================================== FAILURES
==============================================
___________________________________________ test_equality
____________________________________________
@pytest.mark.others
def test_equality():
> assert 10 == 11
E assert 10 == 11
test_square.py:16: AssertionError
========================== 1 failed, 1 passed, 4 deselected in 0.08 seconds
==========================
Similarly, we can run tests with other markers also β great, compare
21 Lectures
4 hours
Lucian Musat
22 Lectures
1.5 hours
Fanuel Mapuwei
44 Lectures
3.5 hours
Rohit Dharaviya
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2111,
"s": 2042,
"text": "In this chapter, we will learn how to group the tests using markers."
},
{
"code": null,
"e": 2429,
"s": 2111,
"text": "Pytest allows us to use markers on test functions. Markers are used to set various features/attributes to test functions. Pytest provides many inbuilt markers such as xfail, skip and parametrize. Apart from that, users can create their own marker names. Markers are applied on the tests using the syntax given below β"
},
{
"code": null,
"e": 2456,
"s": 2429,
"text": "@pytest.mark.<markername>\n"
},
{
"code": null,
"e": 2615,
"s": 2456,
"text": "To use markers, we have to import pytest module in the test file. We can define our own marker names to the tests and run the tests having those marker names."
},
{
"code": null,
"e": 2674,
"s": 2615,
"text": "To run the marked tests, we can use the following syntax β"
},
{
"code": null,
"e": 2701,
"s": 2674,
"text": "pytest -m <markername> -v\n"
},
{
"code": null,
"e": 2773,
"s": 2701,
"text": "-m <markername> represents the marker name of the tests to be executed."
},
{
"code": null,
"e": 2906,
"s": 2773,
"text": "Update our test files test_compare.py and test_square.py with the following code. We are defining 3 markers β great, square, others."
},
{
"code": null,
"e": 3143,
"s": 2906,
"text": "import pytest\[email protected]\ndef test_greater():\n num = 100\n assert num > 100\n\[email protected]\ndef test_greater_equal():\n num = 100\n assert num >= 100\n\[email protected]\ndef test_less():\n num = 100\n assert num < 200"
},
{
"code": null,
"e": 3383,
"s": 3143,
"text": "import pytest\nimport math\n\[email protected]\ndef test_sqrt():\n num = 25\n assert math.sqrt(num) == 5\n\[email protected]\ndef testsquare():\n num = 7\n assert 7*7 == 40\n\[email protected]\n def test_equality():\n assert 10 == 11"
},
{
"code": null,
"e": 3450,
"s": 3383,
"text": "Now to run the tests marked as others, run the following command β"
},
{
"code": null,
"e": 3471,
"s": 3450,
"text": "pytest -m others -v\n"
},
{
"code": null,
"e": 3530,
"s": 3471,
"text": "See the result below. It ran the 2 tests marked as others."
},
{
"code": null,
"e": 4030,
"s": 3530,
"text": "test_compare.py::test_less PASSED\ntest_square.py::test_equality FAILED\n============================================== FAILURES\n==============================================\n___________________________________________ test_equality\n____________________________________________\n @pytest.mark.others\n def test_equality():\n> assert 10 == 11\nE assert 10 == 11\ntest_square.py:16: AssertionError\n========================== 1 failed, 1 passed, 4 deselected in 0.08 seconds\n==========================\n"
},
{
"code": null,
"e": 4099,
"s": 4030,
"text": "Similarly, we can run tests with other markers also β great, compare"
},
{
"code": null,
"e": 4132,
"s": 4099,
"text": "\n 21 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 4146,
"s": 4132,
"text": " Lucian Musat"
},
{
"code": null,
"e": 4181,
"s": 4146,
"text": "\n 22 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4197,
"s": 4181,
"text": " Fanuel Mapuwei"
},
{
"code": null,
"e": 4232,
"s": 4197,
"text": "\n 44 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 4249,
"s": 4232,
"text": " Rohit Dharaviya"
},
{
"code": null,
"e": 4256,
"s": 4249,
"text": " Print"
},
{
"code": null,
"e": 4267,
"s": 4256,
"text": " Add Notes"
}
] |
Anti Diagonal Traversal of Matrix | Practice | GeeksforGeeks
|
Give a N*N square matrix, return an array of its anti-diagonals. Look at the example for more details.
Example 1:
Input:
N = 2
matrix[][] = {{1,2},
{3,4}}
Output:
1 2 3 4
Explanation:
Matrix is as below:
1 2
3 4
Printing it in anti-diagonal form will lead
to the output as 1 2 3 4
Example 2:
Input:
N = 3
matrix[][] = {{1,2,3},
{4,5,6},
{7,8,9}}
Output:
1 2 4 3 5 7 6 8 9
Explanation:
Matrix is as below:
1 2 3
4 5 6
7 8 9
Printing it in anti-diagonal form will lead
to the output as 1 2 4 3 5 7 6 8 9
Your Task:
You dont need to read input or print anything. Complete the function antiDiagonalPattern() that takes matrix as input parameter and returns a list of integers in order of the values visited in the anti-Diagonal pattern.
Expected Time Complexity: O(N * N)
Expected Auxiliary Space: O(N * N) for the resultant list only.
Constraints:
1 <= N <= 100
1 <= mat[i][j] <= 100
0
anilcangulkaya72 weeks ago
// O(1) 0.03/1.6
vector<int> antiDiagonalPattern(vector<vector<int>> matrix)
{
// Code here
int submisionIndex = 0; // submition
vector<int> result(matrix.size() * matrix[0].size());
for (int i = 0; i < matrix[0].size(); ++i)
{
result[submisionIndex++] = matrix[0][i];
for (int j = i-1, k = 1; j >= 0; --j, k++)
{
result[submisionIndex++] = matrix[k][j];
}
}
const int lastMatrixIndex = matrix.size()-1;
submisionIndex = result.size()-1;
for (int i = matrix[lastMatrixIndex].size()-1; i > 0; --i)
{
result[submisionIndex--] = matrix[lastMatrixIndex][i];
for (int j = i+1, k = lastMatrixIndex-1; j < matrix.size(); ++j, --k)
{
result[submisionIndex--] = matrix[k][j];
}
}
return result;
}
+1
himanshuj701 month ago
//Easy C++ code
vector<int> antiDiagonalPattern(vector<vector<int>> matrix)
{
// Code here
int n=matrix.size();
vector<int> vec;
vec.push_back(matrix[0][0]);
if(n==1){
return vec;
}
int i=0, j=1;
while(j<n){
int x=i, y=j;
while(x!=j && y!=i){
vec.push_back(matrix[x][y]);
x++;
y--;
}
vec.push_back(matrix[x][y]);
j++;
}
i=1;
j=n-1;
while(i<n){
int x=i, y=j;
while(x!=j && y!=i){
vec.push_back(matrix[x][y]);
x++;
y--;
}
vec.push_back(matrix[x][y]);
i++;
}
return vec;
}
0
honeychopra061 month ago
Easy python solution
class Solution: def antiDiagonalPattern(self,matrix): # Code here n=len(matrix) l=[] for i in range(n): a=0 b=i while(a<=i and b>=0): l.append(matrix[a][b]) a=a+1 b=b-1 for j in range(1,n): a=j b=n-1 while(a<=n and b>=j): l.append(matrix[a][b]) a=a+1 b=b-1 return l
0
rajkumarchauhan844784 months ago
// c++ easy solution
vector<int> antiDiagonalPattern(vector<vector<int>> matrix) { // Code here vector<int>ans; int n=matrix.size(); for(int i=0;i<n;i++) { // { if(i>=n) // i=n-1; int k=i; for(int j=0;j<=i;j++) { if(k>=0 && j<n ) ans.push_back(matrix[j][k]); k--; } } for(int i=0;i<n-1;i++) { // { if(i>=n) // i=n-1; int k=n-1; for(int j=i+1;j<n;j++) { if(k>=0 && j<n ) ans.push_back(matrix[j][k]); k--; } } return ans; }};
0
imranwahid5 months ago
Easy C++ solution
0
anutiger7 months ago
int helper(vector<vector<int>> &mat,int x,int y){
if(x >= 0 and x < mat.size() and y >= 0 and y < mat[0].size() and mat[x][y] != -1){
int t = mat[x][y];
mat[x][y] = -1;
return t;
}
return -1;
}
vector<int> antiDiagonalPattern(vector<vector<int>> mat)
{
queue<pair<pair<int,int>,int>> q;
vector<int> res;
q.push({{0,0},mat[0][0]});
mat[0][0] = -1;
int dx[] = {0,0,-1,1};
int dy[] = {1,-1,0,0};
while(!q.empty()){
auto it = q.front();q.pop();
int x = it.first.first;
int y = it.first.second;
res.push_back(it.second);
for(int i = 0 ;i < 4 ; i++){
int t = helper(mat,x + dx[i],y + dy[i]);
if(t!= -1) q.push({{x + dx[i],y + dy[i]},t});
}
}
return res;
}
0
Suhaas Badada9 months ago
Suhaas Badada
https://pastebin.com/41mqNsB0
0
Tanay Gupta10 months ago
Tanay Gupta
If admin corrects the test cases for python:-
Below code will work fine:
matrix = [[1,2,3],[4,5,6],[7,8,9]]n = len(matrix)
m = len(matrix[0])
ans = [[] for i in range(n + m - 1)]
for i in range(m): for j in range(n): ans[i + j].append(matrix[i][j])ask =[]for i in range(len(ans)): for j in range(len(ans[i])): ask.append(ans[i][j])
return ask
0
Tanay Gupta10 months ago
Tanay Gupta
For python, Please correct the base test case.
For Input:31 2 3 4 5 6 7 8 9your output is: [] [1, 2, 3] [4, 5, 6]
Please correct all the test cases
0
Debojyoti Sinha10 months ago
Debojyoti Sinha
Correct Answer. β
Execution Time:0.05
class Solution{ public: vector<int> antiDiagonalPattern(vector<vector<int>> matrix) { map<int, vector<int="">> mp; for(int i = 0; i < matrix.size(); i++) { for(int j = 0; j < matrix[i].size(); j++) { mp[i + j].push_back(matrix[i][j]); } } vector<int> res; for(auto x: mp) { res.insert(res.end(), x.second.begin(), x.second.end()); } return res; }};
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
|
[
{
"code": null,
"e": 329,
"s": 226,
"text": "Give a N*N square matrix, return an array of its anti-diagonals. Look at the example for more details."
},
{
"code": null,
"e": 340,
"s": 329,
"text": "Example 1:"
},
{
"code": null,
"e": 521,
"s": 340,
"text": "Input:\nN = 2\nmatrix[][] = {{1,2},\n {3,4}}\nOutput:\n1 2 3 4\nExplanation:\nMatrix is as below:\n1 2\n3 4\nPrinting it in anti-diagonal form will lead\nto the output as 1 2 3 4"
},
{
"code": null,
"e": 533,
"s": 521,
"text": "\nExample 2:"
},
{
"code": null,
"e": 775,
"s": 533,
"text": "Input:\nN = 3\nmatrix[][] = {{1,2,3},\n\n {4,5,6},\n\n {7,8,9}}\nOutput:\n1 2 4 3 5 7 6 8 9\nExplanation: \nMatrix is as below:\n1 2 3\n4 5 6\n7 8 9\nPrinting it in anti-diagonal form will lead\nto the output as 1 2 4 3 5 7 6 8 9 "
},
{
"code": null,
"e": 1007,
"s": 775,
"text": "Your Task:\nYou dont need to read input or print anything. Complete the function antiDiagonalPattern() that takes matrix as input parameter and returns a list of integers in order of the values visited in the anti-Diagonal pattern. "
},
{
"code": null,
"e": 1108,
"s": 1007,
"text": "Expected Time Complexity: O(N * N)\nExpected Auxiliary Space: O(N * N) for the resultant list only.\n "
},
{
"code": null,
"e": 1157,
"s": 1108,
"text": "Constraints:\n1 <= N <= 100\n1 <= mat[i][j] <= 100"
},
{
"code": null,
"e": 1159,
"s": 1157,
"text": "0"
},
{
"code": null,
"e": 1186,
"s": 1159,
"text": "anilcangulkaya72 weeks ago"
},
{
"code": null,
"e": 2017,
"s": 1186,
"text": "// O(1) 0.03/1.6\nvector<int> antiDiagonalPattern(vector<vector<int>> matrix) \n{\n // Code here\n int submisionIndex = 0; // submition\n vector<int> result(matrix.size() * matrix[0].size()); \n \n for (int i = 0; i < matrix[0].size(); ++i)\n {\n result[submisionIndex++] = matrix[0][i];\n for (int j = i-1, k = 1; j >= 0; --j, k++)\n {\n result[submisionIndex++] = matrix[k][j]; \n }\n }\n \n const int lastMatrixIndex = matrix.size()-1;\n submisionIndex = result.size()-1;\n \n for (int i = matrix[lastMatrixIndex].size()-1; i > 0; --i)\n {\n result[submisionIndex--] = matrix[lastMatrixIndex][i];\n for (int j = i+1, k = lastMatrixIndex-1; j < matrix.size(); ++j, --k)\n {\n result[submisionIndex--] = matrix[k][j]; \n }\n }\n \n return result;\n}"
},
{
"code": null,
"e": 2020,
"s": 2017,
"text": "+1"
},
{
"code": null,
"e": 2043,
"s": 2020,
"text": "himanshuj701 month ago"
},
{
"code": null,
"e": 2862,
"s": 2043,
"text": "//Easy C++ code\nvector<int> antiDiagonalPattern(vector<vector<int>> matrix) \n {\n // Code here\n int n=matrix.size();\n vector<int> vec;\n vec.push_back(matrix[0][0]);\n if(n==1){\n return vec;\n }\n int i=0, j=1;\n while(j<n){\n int x=i, y=j;\n while(x!=j && y!=i){\n vec.push_back(matrix[x][y]);\n x++;\n y--;\n }\n vec.push_back(matrix[x][y]);\n j++;\n }\n i=1;\n j=n-1;\n while(i<n){\n int x=i, y=j;\n while(x!=j && y!=i){\n vec.push_back(matrix[x][y]);\n x++;\n y--;\n }\n vec.push_back(matrix[x][y]);\n i++;\n }\n return vec;\n }"
},
{
"code": null,
"e": 2864,
"s": 2862,
"text": "0"
},
{
"code": null,
"e": 2889,
"s": 2864,
"text": "honeychopra061 month ago"
},
{
"code": null,
"e": 2910,
"s": 2889,
"text": "Easy python solution"
},
{
"code": null,
"e": 3369,
"s": 2910,
"text": "class Solution: def antiDiagonalPattern(self,matrix): # Code here n=len(matrix) l=[] for i in range(n): a=0 b=i while(a<=i and b>=0): l.append(matrix[a][b]) a=a+1 b=b-1 for j in range(1,n): a=j b=n-1 while(a<=n and b>=j): l.append(matrix[a][b]) a=a+1 b=b-1 return l"
},
{
"code": null,
"e": 3371,
"s": 3369,
"text": "0"
},
{
"code": null,
"e": 3404,
"s": 3371,
"text": "rajkumarchauhan844784 months ago"
},
{
"code": null,
"e": 3429,
"s": 3404,
"text": "// c++ easy solution "
},
{
"code": null,
"e": 4100,
"s": 3429,
"text": "vector<int> antiDiagonalPattern(vector<vector<int>> matrix) { // Code here vector<int>ans; int n=matrix.size(); for(int i=0;i<n;i++) { // { if(i>=n) // i=n-1; int k=i; for(int j=0;j<=i;j++) { if(k>=0 && j<n ) ans.push_back(matrix[j][k]); k--; } } for(int i=0;i<n-1;i++) { // { if(i>=n) // i=n-1; int k=n-1; for(int j=i+1;j<n;j++) { if(k>=0 && j<n ) ans.push_back(matrix[j][k]); k--; } } return ans; }}; "
},
{
"code": null,
"e": 4102,
"s": 4100,
"text": "0"
},
{
"code": null,
"e": 4125,
"s": 4102,
"text": "imranwahid5 months ago"
},
{
"code": null,
"e": 4143,
"s": 4125,
"text": "Easy C++ solution"
},
{
"code": null,
"e": 4145,
"s": 4143,
"text": "0"
},
{
"code": null,
"e": 4166,
"s": 4145,
"text": "anutiger7 months ago"
},
{
"code": null,
"e": 5074,
"s": 4166,
"text": " int helper(vector<vector<int>> &mat,int x,int y){\n if(x >= 0 and x < mat.size() and y >= 0 and y < mat[0].size() and mat[x][y] != -1){\n int t = mat[x][y];\n mat[x][y] = -1;\n return t;\n }\n return -1;\n }\n vector<int> antiDiagonalPattern(vector<vector<int>> mat) \n {\n queue<pair<pair<int,int>,int>> q;\n vector<int> res;\n q.push({{0,0},mat[0][0]});\n mat[0][0] = -1;\n int dx[] = {0,0,-1,1};\n int dy[] = {1,-1,0,0};\n while(!q.empty()){\n auto it = q.front();q.pop();\n int x = it.first.first;\n int y = it.first.second;\n res.push_back(it.second);\n for(int i = 0 ;i < 4 ; i++){\n int t = helper(mat,x + dx[i],y + dy[i]);\n if(t!= -1) q.push({{x + dx[i],y + dy[i]},t});\n }\n }\n return res;\n }"
},
{
"code": null,
"e": 5076,
"s": 5074,
"text": "0"
},
{
"code": null,
"e": 5102,
"s": 5076,
"text": "Suhaas Badada9 months ago"
},
{
"code": null,
"e": 5116,
"s": 5102,
"text": "Suhaas Badada"
},
{
"code": null,
"e": 5146,
"s": 5116,
"text": "https://pastebin.com/41mqNsB0"
},
{
"code": null,
"e": 5148,
"s": 5146,
"text": "0"
},
{
"code": null,
"e": 5173,
"s": 5148,
"text": "Tanay Gupta10 months ago"
},
{
"code": null,
"e": 5185,
"s": 5173,
"text": "Tanay Gupta"
},
{
"code": null,
"e": 5231,
"s": 5185,
"text": "If admin corrects the test cases for python:-"
},
{
"code": null,
"e": 5258,
"s": 5231,
"text": "Below code will work fine:"
},
{
"code": null,
"e": 5308,
"s": 5258,
"text": "matrix = [[1,2,3],[4,5,6],[7,8,9]]n = len(matrix)"
},
{
"code": null,
"e": 5327,
"s": 5308,
"text": "m = len(matrix[0])"
},
{
"code": null,
"e": 5364,
"s": 5327,
"text": "ans = [[] for i in range(n + m - 1)]"
},
{
"code": null,
"e": 5537,
"s": 5364,
"text": "for i in range(m): for j in range(n): ans[i + j].append(matrix[i][j])ask =[]for i in range(len(ans)): for j in range(len(ans[i])): ask.append(ans[i][j])"
},
{
"code": null,
"e": 5548,
"s": 5537,
"text": "return ask"
},
{
"code": null,
"e": 5550,
"s": 5548,
"text": "0"
},
{
"code": null,
"e": 5575,
"s": 5550,
"text": "Tanay Gupta10 months ago"
},
{
"code": null,
"e": 5587,
"s": 5575,
"text": "Tanay Gupta"
},
{
"code": null,
"e": 5634,
"s": 5587,
"text": "For python, Please correct the base test case."
},
{
"code": null,
"e": 5701,
"s": 5634,
"text": "For Input:31 2 3 4 5 6 7 8 9your output is: [] [1, 2, 3] [4, 5, 6]"
},
{
"code": null,
"e": 5735,
"s": 5701,
"text": "Please correct all the test cases"
},
{
"code": null,
"e": 5737,
"s": 5735,
"text": "0"
},
{
"code": null,
"e": 5766,
"s": 5737,
"text": "Debojyoti Sinha10 months ago"
},
{
"code": null,
"e": 5782,
"s": 5766,
"text": "Debojyoti Sinha"
},
{
"code": null,
"e": 5819,
"s": 5782,
"text": "Correct Answer. β
Execution Time:0.05"
},
{
"code": null,
"e": 6335,
"s": 5819,
"text": "class Solution{ public: vector<int> antiDiagonalPattern(vector<vector<int>> matrix) { map<int, vector<int=\"\">> mp; for(int i = 0; i < matrix.size(); i++) { for(int j = 0; j < matrix[i].size(); j++) { mp[i + j].push_back(matrix[i][j]); } } vector<int> res; for(auto x: mp) { res.insert(res.end(), x.second.begin(), x.second.end()); } return res; }};"
},
{
"code": null,
"e": 6481,
"s": 6335,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 6517,
"s": 6481,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 6527,
"s": 6517,
"text": "\nProblem\n"
},
{
"code": null,
"e": 6537,
"s": 6527,
"text": "\nContest\n"
},
{
"code": null,
"e": 6600,
"s": 6537,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 6748,
"s": 6600,
"text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 6956,
"s": 6748,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints."
},
{
"code": null,
"e": 7062,
"s": 6956,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
How to check if a string is a subset of another string in R?
|
To check whether a string is a subset of another string we can use grepl function.
> Company <- "TutorialsPoint"
> Job <- "Tutor"
> grepl(Job, Company, fixed = TRUE)
[1] TRUE
Here we are getting TRUE because Tutor is a subset of TutorialsPoint.
> grepl(Company, Job, fixed = TRUE)
[1] FALSE
Here we are getting FALSE because TutorialsPoint is not a subset of Tutor.
|
[
{
"code": null,
"e": 1145,
"s": 1062,
"text": "To check whether a string is a subset of another string we can use grepl function."
},
{
"code": null,
"e": 1237,
"s": 1145,
"text": "> Company <- \"TutorialsPoint\"\n> Job <- \"Tutor\"\n> grepl(Job, Company, fixed = TRUE)\n[1] TRUE"
},
{
"code": null,
"e": 1307,
"s": 1237,
"text": "Here we are getting TRUE because Tutor is a subset of TutorialsPoint."
},
{
"code": null,
"e": 1353,
"s": 1307,
"text": "> grepl(Company, Job, fixed = TRUE)\n[1] FALSE"
},
{
"code": null,
"e": 1428,
"s": 1353,
"text": "Here we are getting FALSE because TutorialsPoint is not a subset of Tutor."
}
] |
JRadioButton | Java Swing - GeeksforGeeks
|
21 Aug, 2018
We use the JRadioButton class to create a radio button. Radio button is use to select one option from multiple options. It is used in filling forms, online objective papers and quiz.
We add radio buttons in a ButtonGroup so that we can select only one radio button at a time. We use βButtonGroupβ class to create a ButtonGroup and add radio button in a group.
Methods Used :
JRadioButton() : Creates a unselected RadioButton with no text.Example:JRadioButton j1 = new JRadioButton()
JButton(String s) : Creates a JButton with a specific text.Example:JButton b1 = new JButton("Button")
JLabel(String s) : Creates a JLabel with a specific text.Example:JLabel L = new JLabel("Label 1")
ButtonGroup() : Use to create a group, in which we can add JRadioButton. We can select only one JRadioButton in a ButtonGroup.Steps to Group the radio buttons together.Create a ButtonGroup instance by using βButtonGroup()β Method.ButtonGroup G = new ButtonGroup()
Now add buttons in a Group βGβ, with the help of βadd()β Method.Example:G.add(Button1);
G.add(Button2);
isSelected() : it will return a Boolean value true or false, if a JRadioButton is selected it Will return true otherwise false.Example:JRadioButton.isSelected()
Set(...) and Get(...) Methods :i) Set and get are used to replace directly accessing member variables from external classes.ii) Instead of accessing class member variables directly, you define get methods to access these variables, and set methods to modify them.
JRadioButton() : Creates a unselected RadioButton with no text.Example:JRadioButton j1 = new JRadioButton()
JRadioButton j1 = new JRadioButton()
JButton(String s) : Creates a JButton with a specific text.Example:JButton b1 = new JButton("Button")
JButton b1 = new JButton("Button")
JLabel(String s) : Creates a JLabel with a specific text.Example:JLabel L = new JLabel("Label 1")
JLabel L = new JLabel("Label 1")
ButtonGroup() : Use to create a group, in which we can add JRadioButton. We can select only one JRadioButton in a ButtonGroup.Steps to Group the radio buttons together.Create a ButtonGroup instance by using βButtonGroup()β Method.ButtonGroup G = new ButtonGroup()
Now add buttons in a Group βGβ, with the help of βadd()β Method.Example:G.add(Button1);
G.add(Button2);
Create a ButtonGroup instance by using βButtonGroup()β Method.ButtonGroup G = new ButtonGroup()
ButtonGroup G = new ButtonGroup()
Now add buttons in a Group βGβ, with the help of βadd()β Method.Example:G.add(Button1);
G.add(Button2);
Example:
G.add(Button1);
G.add(Button2);
isSelected() : it will return a Boolean value true or false, if a JRadioButton is selected it Will return true otherwise false.Example:JRadioButton.isSelected()
Example:
JRadioButton.isSelected()
Set(...) and Get(...) Methods :i) Set and get are used to replace directly accessing member variables from external classes.ii) Instead of accessing class member variables directly, you define get methods to access these variables, and set methods to modify them.
ii) Instead of accessing class member variables directly, you define get methods to access these variables, and set methods to modify them.
Description of some functions used in program, is given in this link : Functions Description
Program 1 : JRadioButton Without ActionListener
// Java program to show JRadioButton Example.// in java. Importing different Package.import java.awt.*;import javax.swing.*;import java.awt.event.*; class Demo extends JFrame { // Declaration of object of JRadioButton class. JRadioButton jRadioButton1; // Declaration of object of JRadioButton class. JRadioButton jRadioButton2; // Declaration of object of JButton class. JButton jButton; // Declaration of object of ButtonGroup class. ButtonGroup G1; // Declaration of object of JLabel class. JLabel L1; // Constructor of Demo class. public Demo() { // Setting layout as null of JFrame. this.setLayout(null); // Initialization of object of "JRadioButton" class. jRadioButton1 = new JRadioButton(); // Initialization of object of "JRadioButton" class. jRadioButton2 = new JRadioButton(); // Initialization of object of "JButton" class. jButton = new JButton("Click"); // Initialization of object of "ButtonGroup" class. G1 = new ButtonGroup(); // Initialization of object of " JLabel" class. L1 = new JLabel("Qualification"); // setText(...) function is used to set text of radio button. // Setting text of "jRadioButton2". jRadioButton1.setText("Under-Graduate"); // Setting text of "jRadioButton4". jRadioButton2.setText("Graduate"); // Setting Bounds of "jRadioButton2". jRadioButton1.setBounds(120, 30, 120, 50); // Setting Bounds of "jRadioButton4". jRadioButton2.setBounds(250, 30, 80, 50); // Setting Bounds of "jButton". jButton.setBounds(125, 90, 80, 30); // Setting Bounds of JLabel "L2". L1.setBounds(20, 30, 150, 50); // "this" keyword in java refers to current object. // Adding "jRadioButton2" on JFrame. this.add(jRadioButton1); // Adding "jRadioButton4" on JFrame. this.add(jRadioButton2); // Adding "jButton" on JFrame. this.add(jButton); // Adding JLabel "L2" on JFrame. this.add(L1); // Adding "jRadioButton1" and "jRadioButton3" in a Button Group "G2". G1.add(jRadioButton1); G1.add(jRadioButton2); }} class RadioButton { // Driver code. public static void main(String args[]) { // Creating object of demo class. Demo f = new Demo(); // Setting Bounds of JFrame. f.setBounds(100, 100, 400, 200); // Setting Title of frame. f.setTitle("RadioButtons"); // Setting Visible status of frame as true. f.setVisible(true); }}
Output:
Program 2 : JRadioButton With ActionListener
// Java program to show JRadioButton Example.// in java. Importing different Package.import java.awt.*;import javax.swing.*;import java.awt.event.*; class Demo extends JFrame { // Declaration of object of JRadioButton class. JRadioButton jRadioButton1; // Declaration of object of JRadioButton class. JRadioButton jRadioButton2; // Declaration of object of JButton class. JButton jButton; // Declaration of object of ButtonGroup class. ButtonGroup G1; // Declaration of object of JLabel class. JLabel L1; // Constructor of Demo class. public Demo() { // Setting layout as null of JFrame. this.setLayout(null); // Initialization of object of "JRadioButton" class. jRadioButton1 = new JRadioButton(); // Initialization of object of "JRadioButton" class. jRadioButton2 = new JRadioButton(); // Initialization of object of "JButton" class. jButton = new JButton("Click"); // Initialization of object of "ButtonGroup" class. G1 = new ButtonGroup(); // Initialization of object of " JLabel" class. L1 = new JLabel("Qualification"); // setText(...) function is used to set text of radio button. // Setting text of "jRadioButton2". jRadioButton1.setText("Under-Graduate"); // Setting text of "jRadioButton4". jRadioButton2.setText("Graduate"); // Setting Bounds of "jRadioButton2". jRadioButton1.setBounds(120, 30, 120, 50); // Setting Bounds of "jRadioButton4". jRadioButton2.setBounds(250, 30, 80, 50); // Setting Bounds of "jButton". jButton.setBounds(125, 90, 80, 30); // Setting Bounds of JLabel "L2". L1.setBounds(20, 30, 150, 50); // "this" keyword in java refers to current object. // Adding "jRadioButton2" on JFrame. this.add(jRadioButton1); // Adding "jRadioButton4" on JFrame. this.add(jRadioButton2); // Adding "jButton" on JFrame. this.add(jButton); // Adding JLabel "L2" on JFrame. this.add(L1); // Adding "jRadioButton1" and "jRadioButton3" in a Button Group "G2". G1.add(jRadioButton1); G1.add(jRadioButton2); // Adding Listener to JButton. jButton.addActionListener(new ActionListener() { // Anonymous class. public void actionPerformed(ActionEvent e) { // Override Method // Declaration of String class Objects. String qual = " "; // If condition to check if jRadioButton2 is selected. if (jRadioButton1.isSelected()) { qual = "Under-Graduate"; } else if (jRadioButton2.isSelected()) { qual = "Graduate"; } else { qual = "NO Button selected"; } // MessageDialog to show information selected radion buttons. JOptionPane.showMessageDialog(Demo.this, qual); } }); }} class RadioButton { // Driver code. public static void main(String args[]) { // Creating object of demo class. Demo f = new Demo(); // Setting Bounds of JFrame. f.setBounds(100, 100, 400, 200); // Setting Title of frame. f.setTitle("RadioButtons"); // Setting Visible status of frame as true. f.setVisible(true); }}
Output:
After pressing Button βclickβ.
Program 3 Program to create a simple group of radio buttons (with image )and add item listener to them
// Java Program to create a simple group of radio buttons // (with image )and add item listener to themimport java.awt.event.*;import java.awt.*;import javax.swing.*;class solve extends JFrame implements ItemListener { // frame static JFrame f; // radiobuttons static JRadioButton b, b1; // create a label static JLabel l1; // main class public static void main(String[] args) { // create a new frame f = new JFrame("frame"); // create a object solve s = new solve(); // create a panel JPanel p = new JPanel(); // create a new label JLabel l = new JLabel("which website do you like?"); l1 = new JLabel("geeksforgeeks selected"); // create Radio buttons b = new JRadioButton("geeksforgeeks", new ImageIcon("f:/gfg.jpg")); b1 = new JRadioButton("others"); // create a button group ButtonGroup bg = new ButtonGroup(); // add item listener b.addItemListener(s); b1.addItemListener(s); // add radio buttons to button group bg.add(b); bg.add(b1); b.setSelected(true); // add button and label to panel p.add(l); p.add(b); p.add(b1); p.add(l1); f.add(p); // set the size of frame f.setSize(400, 400); f.show(); } public void itemStateChanged(ItemEvent e) { if (e.getSource() == b) { if (e.getStateChange() == 1) { l1.setText("geeksforgeeks selected"); } } else { if (e.getStateChange() == 1) { l1.setText("others selected"); } } }}
Output :
Note : The following programs might not run in an online Compiler please use an Offline IDE.
andrew1234
java-swing
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Initialize an ArrayList in Java
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Interfaces in Java
How to iterate any Map in Java
ArrayList in Java
Multidimensional Arrays in Java
Stream In Java
Stack Class in Java
Singleton Class in Java
|
[
{
"code": null,
"e": 24560,
"s": 24532,
"text": "\n21 Aug, 2018"
},
{
"code": null,
"e": 24743,
"s": 24560,
"text": "We use the JRadioButton class to create a radio button. Radio button is use to select one option from multiple options. It is used in filling forms, online objective papers and quiz."
},
{
"code": null,
"e": 24920,
"s": 24743,
"text": "We add radio buttons in a ButtonGroup so that we can select only one radio button at a time. We use βButtonGroupβ class to create a ButtonGroup and add radio button in a group."
},
{
"code": null,
"e": 24935,
"s": 24920,
"text": "Methods Used :"
},
{
"code": null,
"e": 26039,
"s": 24935,
"text": "JRadioButton() : Creates a unselected RadioButton with no text.Example:JRadioButton j1 = new JRadioButton() \nJButton(String s) : Creates a JButton with a specific text.Example:JButton b1 = new JButton(\"Button\") \nJLabel(String s) : Creates a JLabel with a specific text.Example:JLabel L = new JLabel(\"Label 1\") \nButtonGroup() : Use to create a group, in which we can add JRadioButton. We can select only one JRadioButton in a ButtonGroup.Steps to Group the radio buttons together.Create a ButtonGroup instance by using βButtonGroup()β Method.ButtonGroup G = new ButtonGroup()\nNow add buttons in a Group βGβ, with the help of βadd()β Method.Example:G.add(Button1);\nG.add(Button2);\nisSelected() : it will return a Boolean value true or false, if a JRadioButton is selected it Will return true otherwise false.Example:JRadioButton.isSelected()\nSet(...) and Get(...) Methods :i) Set and get are used to replace directly accessing member variables from external classes.ii) Instead of accessing class member variables directly, you define get methods to access these variables, and set methods to modify them."
},
{
"code": null,
"e": 26149,
"s": 26039,
"text": "JRadioButton() : Creates a unselected RadioButton with no text.Example:JRadioButton j1 = new JRadioButton() \n"
},
{
"code": null,
"e": 26188,
"s": 26149,
"text": "JRadioButton j1 = new JRadioButton() \n"
},
{
"code": null,
"e": 26292,
"s": 26188,
"text": "JButton(String s) : Creates a JButton with a specific text.Example:JButton b1 = new JButton(\"Button\") \n"
},
{
"code": null,
"e": 26329,
"s": 26292,
"text": "JButton b1 = new JButton(\"Button\") \n"
},
{
"code": null,
"e": 26429,
"s": 26329,
"text": "JLabel(String s) : Creates a JLabel with a specific text.Example:JLabel L = new JLabel(\"Label 1\") \n"
},
{
"code": null,
"e": 26464,
"s": 26429,
"text": "JLabel L = new JLabel(\"Label 1\") \n"
},
{
"code": null,
"e": 26833,
"s": 26464,
"text": "ButtonGroup() : Use to create a group, in which we can add JRadioButton. We can select only one JRadioButton in a ButtonGroup.Steps to Group the radio buttons together.Create a ButtonGroup instance by using βButtonGroup()β Method.ButtonGroup G = new ButtonGroup()\nNow add buttons in a Group βGβ, with the help of βadd()β Method.Example:G.add(Button1);\nG.add(Button2);\n"
},
{
"code": null,
"e": 26930,
"s": 26833,
"text": "Create a ButtonGroup instance by using βButtonGroup()β Method.ButtonGroup G = new ButtonGroup()\n"
},
{
"code": null,
"e": 26965,
"s": 26930,
"text": "ButtonGroup G = new ButtonGroup()\n"
},
{
"code": null,
"e": 27070,
"s": 26965,
"text": "Now add buttons in a Group βGβ, with the help of βadd()β Method.Example:G.add(Button1);\nG.add(Button2);\n"
},
{
"code": null,
"e": 27079,
"s": 27070,
"text": "Example:"
},
{
"code": null,
"e": 27112,
"s": 27079,
"text": "G.add(Button1);\nG.add(Button2);\n"
},
{
"code": null,
"e": 27274,
"s": 27112,
"text": "isSelected() : it will return a Boolean value true or false, if a JRadioButton is selected it Will return true otherwise false.Example:JRadioButton.isSelected()\n"
},
{
"code": null,
"e": 27283,
"s": 27274,
"text": "Example:"
},
{
"code": null,
"e": 27310,
"s": 27283,
"text": "JRadioButton.isSelected()\n"
},
{
"code": null,
"e": 27574,
"s": 27310,
"text": "Set(...) and Get(...) Methods :i) Set and get are used to replace directly accessing member variables from external classes.ii) Instead of accessing class member variables directly, you define get methods to access these variables, and set methods to modify them."
},
{
"code": null,
"e": 27714,
"s": 27574,
"text": "ii) Instead of accessing class member variables directly, you define get methods to access these variables, and set methods to modify them."
},
{
"code": null,
"e": 27807,
"s": 27714,
"text": "Description of some functions used in program, is given in this link : Functions Description"
},
{
"code": null,
"e": 27855,
"s": 27807,
"text": "Program 1 : JRadioButton Without ActionListener"
},
{
"code": "// Java program to show JRadioButton Example.// in java. Importing different Package.import java.awt.*;import javax.swing.*;import java.awt.event.*; class Demo extends JFrame { // Declaration of object of JRadioButton class. JRadioButton jRadioButton1; // Declaration of object of JRadioButton class. JRadioButton jRadioButton2; // Declaration of object of JButton class. JButton jButton; // Declaration of object of ButtonGroup class. ButtonGroup G1; // Declaration of object of JLabel class. JLabel L1; // Constructor of Demo class. public Demo() { // Setting layout as null of JFrame. this.setLayout(null); // Initialization of object of \"JRadioButton\" class. jRadioButton1 = new JRadioButton(); // Initialization of object of \"JRadioButton\" class. jRadioButton2 = new JRadioButton(); // Initialization of object of \"JButton\" class. jButton = new JButton(\"Click\"); // Initialization of object of \"ButtonGroup\" class. G1 = new ButtonGroup(); // Initialization of object of \" JLabel\" class. L1 = new JLabel(\"Qualification\"); // setText(...) function is used to set text of radio button. // Setting text of \"jRadioButton2\". jRadioButton1.setText(\"Under-Graduate\"); // Setting text of \"jRadioButton4\". jRadioButton2.setText(\"Graduate\"); // Setting Bounds of \"jRadioButton2\". jRadioButton1.setBounds(120, 30, 120, 50); // Setting Bounds of \"jRadioButton4\". jRadioButton2.setBounds(250, 30, 80, 50); // Setting Bounds of \"jButton\". jButton.setBounds(125, 90, 80, 30); // Setting Bounds of JLabel \"L2\". L1.setBounds(20, 30, 150, 50); // \"this\" keyword in java refers to current object. // Adding \"jRadioButton2\" on JFrame. this.add(jRadioButton1); // Adding \"jRadioButton4\" on JFrame. this.add(jRadioButton2); // Adding \"jButton\" on JFrame. this.add(jButton); // Adding JLabel \"L2\" on JFrame. this.add(L1); // Adding \"jRadioButton1\" and \"jRadioButton3\" in a Button Group \"G2\". G1.add(jRadioButton1); G1.add(jRadioButton2); }} class RadioButton { // Driver code. public static void main(String args[]) { // Creating object of demo class. Demo f = new Demo(); // Setting Bounds of JFrame. f.setBounds(100, 100, 400, 200); // Setting Title of frame. f.setTitle(\"RadioButtons\"); // Setting Visible status of frame as true. f.setVisible(true); }}",
"e": 30511,
"s": 27855,
"text": null
},
{
"code": null,
"e": 30519,
"s": 30511,
"text": "Output:"
},
{
"code": null,
"e": 30566,
"s": 30521,
"text": "Program 2 : JRadioButton With ActionListener"
},
{
"code": "// Java program to show JRadioButton Example.// in java. Importing different Package.import java.awt.*;import javax.swing.*;import java.awt.event.*; class Demo extends JFrame { // Declaration of object of JRadioButton class. JRadioButton jRadioButton1; // Declaration of object of JRadioButton class. JRadioButton jRadioButton2; // Declaration of object of JButton class. JButton jButton; // Declaration of object of ButtonGroup class. ButtonGroup G1; // Declaration of object of JLabel class. JLabel L1; // Constructor of Demo class. public Demo() { // Setting layout as null of JFrame. this.setLayout(null); // Initialization of object of \"JRadioButton\" class. jRadioButton1 = new JRadioButton(); // Initialization of object of \"JRadioButton\" class. jRadioButton2 = new JRadioButton(); // Initialization of object of \"JButton\" class. jButton = new JButton(\"Click\"); // Initialization of object of \"ButtonGroup\" class. G1 = new ButtonGroup(); // Initialization of object of \" JLabel\" class. L1 = new JLabel(\"Qualification\"); // setText(...) function is used to set text of radio button. // Setting text of \"jRadioButton2\". jRadioButton1.setText(\"Under-Graduate\"); // Setting text of \"jRadioButton4\". jRadioButton2.setText(\"Graduate\"); // Setting Bounds of \"jRadioButton2\". jRadioButton1.setBounds(120, 30, 120, 50); // Setting Bounds of \"jRadioButton4\". jRadioButton2.setBounds(250, 30, 80, 50); // Setting Bounds of \"jButton\". jButton.setBounds(125, 90, 80, 30); // Setting Bounds of JLabel \"L2\". L1.setBounds(20, 30, 150, 50); // \"this\" keyword in java refers to current object. // Adding \"jRadioButton2\" on JFrame. this.add(jRadioButton1); // Adding \"jRadioButton4\" on JFrame. this.add(jRadioButton2); // Adding \"jButton\" on JFrame. this.add(jButton); // Adding JLabel \"L2\" on JFrame. this.add(L1); // Adding \"jRadioButton1\" and \"jRadioButton3\" in a Button Group \"G2\". G1.add(jRadioButton1); G1.add(jRadioButton2); // Adding Listener to JButton. jButton.addActionListener(new ActionListener() { // Anonymous class. public void actionPerformed(ActionEvent e) { // Override Method // Declaration of String class Objects. String qual = \" \"; // If condition to check if jRadioButton2 is selected. if (jRadioButton1.isSelected()) { qual = \"Under-Graduate\"; } else if (jRadioButton2.isSelected()) { qual = \"Graduate\"; } else { qual = \"NO Button selected\"; } // MessageDialog to show information selected radion buttons. JOptionPane.showMessageDialog(Demo.this, qual); } }); }} class RadioButton { // Driver code. public static void main(String args[]) { // Creating object of demo class. Demo f = new Demo(); // Setting Bounds of JFrame. f.setBounds(100, 100, 400, 200); // Setting Title of frame. f.setTitle(\"RadioButtons\"); // Setting Visible status of frame as true. f.setVisible(true); }}",
"e": 34095,
"s": 30566,
"text": null
},
{
"code": null,
"e": 34103,
"s": 34095,
"text": "Output:"
},
{
"code": null,
"e": 34136,
"s": 34105,
"text": "After pressing Button βclickβ."
},
{
"code": null,
"e": 34241,
"s": 34138,
"text": "Program 3 Program to create a simple group of radio buttons (with image )and add item listener to them"
},
{
"code": "// Java Program to create a simple group of radio buttons // (with image )and add item listener to themimport java.awt.event.*;import java.awt.*;import javax.swing.*;class solve extends JFrame implements ItemListener { // frame static JFrame f; // radiobuttons static JRadioButton b, b1; // create a label static JLabel l1; // main class public static void main(String[] args) { // create a new frame f = new JFrame(\"frame\"); // create a object solve s = new solve(); // create a panel JPanel p = new JPanel(); // create a new label JLabel l = new JLabel(\"which website do you like?\"); l1 = new JLabel(\"geeksforgeeks selected\"); // create Radio buttons b = new JRadioButton(\"geeksforgeeks\", new ImageIcon(\"f:/gfg.jpg\")); b1 = new JRadioButton(\"others\"); // create a button group ButtonGroup bg = new ButtonGroup(); // add item listener b.addItemListener(s); b1.addItemListener(s); // add radio buttons to button group bg.add(b); bg.add(b1); b.setSelected(true); // add button and label to panel p.add(l); p.add(b); p.add(b1); p.add(l1); f.add(p); // set the size of frame f.setSize(400, 400); f.show(); } public void itemStateChanged(ItemEvent e) { if (e.getSource() == b) { if (e.getStateChange() == 1) { l1.setText(\"geeksforgeeks selected\"); } } else { if (e.getStateChange() == 1) { l1.setText(\"others selected\"); } } }}",
"e": 35952,
"s": 34241,
"text": null
},
{
"code": null,
"e": 35961,
"s": 35952,
"text": "Output :"
},
{
"code": null,
"e": 36054,
"s": 35961,
"text": "Note : The following programs might not run in an online Compiler please use an Offline IDE."
},
{
"code": null,
"e": 36065,
"s": 36054,
"text": "andrew1234"
},
{
"code": null,
"e": 36076,
"s": 36065,
"text": "java-swing"
},
{
"code": null,
"e": 36081,
"s": 36076,
"text": "Java"
},
{
"code": null,
"e": 36086,
"s": 36081,
"text": "Java"
},
{
"code": null,
"e": 36184,
"s": 36086,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36216,
"s": 36184,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 36267,
"s": 36216,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 36297,
"s": 36267,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 36316,
"s": 36297,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 36347,
"s": 36316,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 36365,
"s": 36347,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 36397,
"s": 36365,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 36412,
"s": 36397,
"text": "Stream In Java"
},
{
"code": null,
"e": 36432,
"s": 36412,
"text": "Stack Class in Java"
}
] |
Ruby on Rails - Views
|
A Rails View is an ERb program that shares data with controllers through mutually accessible variables.
If you look in the app/views directory of the library application, you will see one subdirectory for each of the controllers, we have created: book. Each of these subdirectories was created automatically when the same-named controller was created with the generate script.
Rails let's you know that you need to create the view file for each new method. Each method you define in the controller needs to have a corresponding erb file, with the same name as the method, to display the data that the method is collecting.
So let's create view files for all the methods we have defined in the book_controller.rb. While executing these views, simultaneously check these actions are applicable into the database or not.
Create a file called list.html.erb using your favourite text editor and save it to app/views/book. After creating and saving the file, refresh your web browser. You should see a blank page; if you don't, check the spelling of your file and make sure that it is exactly the same as your controller's method.
Now, display the actual content. Let us put the following code into list.html.erb.
<% if @books.blank? %>
<p>There are not any books currently in the system.</p>
<% else %>
<p>These are the current books in our system</p>
<ul id = "books">
<% @books.each do |c| %>
<li><%= link_to c.title, {:action => 'show', :id => c.id} -%></li>
<% end %>
</ul>
<% end %>
<p><%= link_to "Add new Book", {:action => 'new' }%></p>
The code to be executed is to check whether the @books array has any objects in it. The .blank? method returns true if the array is empty, and false if it contains any objects. This @books object was created in controller inside the list method.
The code between the <%= %> tags is a link_to method call. The first parameter of link_to is the text to be displayed between the <a> tags. The second parameter is what action is called when the link is clicked. In this case, it is the show method. The final parameter is the id of the book that is passed via the params object.
Now, try refreshing your browser and you should get the following screen because we don't have any book in our library.
Till now, we don't have any book in our library. We have to create few books in the system. So, let us design a view corresponding to the new method defined in the book_controller.rb.
Create a file called new.html.erb using your favorite text editor and save it to app/views/book. Add the following code to the new.html.erb file.
<h1>Add new book</h1>
<%= form_tag :action => 'create' do %>
<p><label for = "book_title">Title</label>:
<%= text_field 'books', 'title' %></p>
<p><label for = "book_price">Price</label>:
<%= text_field 'books', 'price' %></p>
<p><label for = "book_subject_id">Subject</label>:
<%= collection_select(:books, :subject_id, @subjects, :id, :name, prompt: true) %></p>
<p><label for = "book_description">Description</label><br/>
<%= text_area 'books', 'description' %></p>
<%= submit_tag "Create" %>
<% end -%>
<%= link_to 'Back', {:action => 'list'} %>
Here form_tag method interprets the Ruby code into a regular HTML <form> tag using all the information supplied to it. This tag, for example, outputs the following HTML β
<form action = "/book/create" method = "post">
Next method is text_field that outputs an <input> text field. The parameters for text_field are object and field name. In this case, the object is book and the name is title.
Rails method called collection_select, creates an HTML select menu built from an array, such as the @books one. There are five parameters, which are as follows β
:book β The object you are manipulating. In this case, it's a book object.
:book β The object you are manipulating. In this case, it's a book object.
:subject_id β The field that is populated when the book is saved.
:subject_id β The field that is populated when the book is saved.
@books β The array you are working with.
@books β The array you are working with.
:id β The value that is stored in the database. In terms of HTML, this is the <option> tag's value parameter.
:id β The value that is stored in the database. In terms of HTML, this is the <option> tag's value parameter.
:name β The output that the user sees in the pull-down menu. This is the value between the <option> tags.
:name β The output that the user sees in the pull-down menu. This is the value between the <option> tags.
The next used is submit_tag, which outputs an <input> button that submits the form. Finally, there is the end method that simply translates into </form>.
Go to your browser and visit http://localhost:3000/book/new. This will give you the following screen.
Enter some data in this form and then click the Create button. Here i have added the following details into the fields β
Title: Advance Physics
Price: 390
Subject: Physics
Description: This is test to create new book
When you click the Create button, it will call the create method, which does not need any view because this method is using either list or new methods to view the results. So, when you click the Create button, the data should submit successfully and redirect you to the list page, in which you now have a single item listed as follows β
If you click the link, you should see another Template is missing error, since you haven't created the template file for show method yet.
This method will display the complete detail about any book available in the library. Create a show.html.erb file under app/views/book and populate it with the following code β
<h1><%= @book.title %></h1>
<p>
<strong>Price: </strong> $<%= @book.price %><br />
<strong>Subject :</strong> <%= @book.subject.name %><br />
<strong>Created Date:</strong> <%= @book.created_at %><br />
</p>
<p><%= @book.description %></p>
<hr />
<%= link_to 'Back', {:action => 'list'} %>
This is the first time you have taken the full advantage of associations, which enable you to easily pull data from related objects.
The format used is @variable.relatedObject.column. In this instance, you can pull the subject's name value through the @book variable using the belongs_to associations. If click on any listed record then it will show you the following screen.
Create a new file called edit.html.erb and save it in app/views/book. Populate it with the following code β
<h1>Edit Book Detail</h1>
<%= form_for @book, :url =>{:action => "update", :id =>@book} do |f| %>
<p>Title: <%= f.text_field 'title' %></p>
<p>Price: <%= f.text_field 'price' %></p>
<p>Subject: <%= f.collection_select :subject_id, Subject.all, :id, :name %></p>
<p>Description<br/>
<%= f.text_area 'description' %></p>
<%= f.submit "Save changes" %>
<% end %>
<%= link_to 'Back', {:action => 'list' } %>
This code is very similar to the new method except action to be updated instead of creating and defining an id.
In this scenario, we used form_for tag for the form action. It will perform better than form_tag. Why because it will create interaction with the Model easily. Therefore it is better to use form_for tag whenever you need interaction between the model and the form fields.
At this point, we need some modification in the list method's view file. Go to the <li></li> element and modify it to look like the following β
<li>
<%= link_to c.title, {:action => "show", :id => c.id} -%>
<b> <%= link_to 'Edit', {:action => "edit",
:id => c.id} %></b>
</li>
Now, try to browse books using the http://localhost:3000/book/list. It will give you the listing of all the books along with Edit option. When you click the Edit option, then you will have next screen as follows β
Now, you edit this information and then click the Save Changes button. This will result in a call to update method available in the controller file and it will update all the changed attribute. Notice that the update method does not need any view file because it's using either show or edit methods to show its results.
Removing information from a database using Ruby on Rails is almost too easy. You do not need to write any view code for the delete method because this method is using list method to display the result. So, let's just modify list.html.erb again and add a delete link.
Go to the <li></li> element and modify it to look like the following β
<li>
<%= link_to c.title, {:action => 'show', :id => c.id} -%>
<b> <%= link_to 'Edit', {:action => 'edit', :id => c.id} %></b>
<b> <%= link_to "Delete", {:action => 'delete', :id => c.id},
:confirm => "Are you sure you want to delete this item?" %></b>
</li>
The :confirm parameter presents a JavaScript confirmation box asking if you really want to perform the action. If the user clicks OK, the action proceeds, and the item is deleted.
Now, try browsing books using http://localhost:3000/book/list. It will give you listing of all the books along with Edit and Delete options as follows β
Now using the Delete option, you can delete any listed record.
Create a new file, show_subjects.html.erb, in the app/views/book directory and add the following code to it β
<h1><%= @subject.name -%></h1>
<ul>
<% @subject.books.each do |c| %>
<li><%= link_to c.title, :action => "show", :id => c.id -%></li>
<% end %>
</ul>
You are taking advantage of associations by iterating through a single subject's many books listings.
Now modify the Subject: line of show.html.erb so that the subject listing shows a link.
<strong>Subject: </strong> <%= link_to @book.subject.name,
:action => "show_subjects", :id => @book.subject.id %><br />
This will output a list of subject on the index page, so that users can access them directly.
Modify list.html.erb to add the following to the top of the file β
<ul id = "subjects">
<% Subject.find(:all).each do |c| %>
<li><%= link_to c.name, :action => "show_subjects", :id => c.id %></li>
<% end %>
</ul>
Now try browsing books using http://localhost:3000/book/list. It will display all subjects with links so that you can browse all the books related to that subject.
Hope now you are feeling comfortable with all the operations of Rails.
The next chapter explains how to use Layouts to put your data in a better way. We will show you how to use CSS in your Rails applications.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2207,
"s": 2103,
"text": "A Rails View is an ERb program that shares data with controllers through mutually accessible variables."
},
{
"code": null,
"e": 2480,
"s": 2207,
"text": "If you look in the app/views directory of the library application, you will see one subdirectory for each of the controllers, we have created: book. Each of these subdirectories was created automatically when the same-named controller was created with the generate script."
},
{
"code": null,
"e": 2726,
"s": 2480,
"text": "Rails let's you know that you need to create the view file for each new method. Each method you define in the controller needs to have a corresponding erb file, with the same name as the method, to display the data that the method is collecting."
},
{
"code": null,
"e": 2921,
"s": 2726,
"text": "So let's create view files for all the methods we have defined in the book_controller.rb. While executing these views, simultaneously check these actions are applicable into the database or not."
},
{
"code": null,
"e": 3228,
"s": 2921,
"text": "Create a file called list.html.erb using your favourite text editor and save it to app/views/book. After creating and saving the file, refresh your web browser. You should see a blank page; if you don't, check the spelling of your file and make sure that it is exactly the same as your controller's method."
},
{
"code": null,
"e": 3311,
"s": 3228,
"text": "Now, display the actual content. Let us put the following code into list.html.erb."
},
{
"code": null,
"e": 3654,
"s": 3311,
"text": "<% if @books.blank? %>\n<p>There are not any books currently in the system.</p>\n<% else %>\n<p>These are the current books in our system</p>\n\n<ul id = \"books\">\n <% @books.each do |c| %>\n <li><%= link_to c.title, {:action => 'show', :id => c.id} -%></li>\n <% end %>\n</ul>\n\n<% end %>\n<p><%= link_to \"Add new Book\", {:action => 'new' }%></p>"
},
{
"code": null,
"e": 3900,
"s": 3654,
"text": "The code to be executed is to check whether the @books array has any objects in it. The .blank? method returns true if the array is empty, and false if it contains any objects. This @books object was created in controller inside the list method."
},
{
"code": null,
"e": 4229,
"s": 3900,
"text": "The code between the <%= %> tags is a link_to method call. The first parameter of link_to is the text to be displayed between the <a> tags. The second parameter is what action is called when the link is clicked. In this case, it is the show method. The final parameter is the id of the book that is passed via the params object."
},
{
"code": null,
"e": 4349,
"s": 4229,
"text": "Now, try refreshing your browser and you should get the following screen because we don't have any book in our library."
},
{
"code": null,
"e": 4533,
"s": 4349,
"text": "Till now, we don't have any book in our library. We have to create few books in the system. So, let us design a view corresponding to the new method defined in the book_controller.rb."
},
{
"code": null,
"e": 4679,
"s": 4533,
"text": "Create a file called new.html.erb using your favorite text editor and save it to app/views/book. Add the following code to the new.html.erb file."
},
{
"code": null,
"e": 5235,
"s": 4679,
"text": "<h1>Add new book</h1>\n\n<%= form_tag :action => 'create' do %>\n<p><label for = \"book_title\">Title</label>:\n\n<%= text_field 'books', 'title' %></p>\n<p><label for = \"book_price\">Price</label>:\n\n<%= text_field 'books', 'price' %></p>\n<p><label for = \"book_subject_id\">Subject</label>:\n\n<%= collection_select(:books, :subject_id, @subjects, :id, :name, prompt: true) %></p>\n<p><label for = \"book_description\">Description</label><br/>\n\n<%= text_area 'books', 'description' %></p>\n<%= submit_tag \"Create\" %>\n\n<% end -%>\n<%= link_to 'Back', {:action => 'list'} %>"
},
{
"code": null,
"e": 5406,
"s": 5235,
"text": "Here form_tag method interprets the Ruby code into a regular HTML <form> tag using all the information supplied to it. This tag, for example, outputs the following HTML β"
},
{
"code": null,
"e": 5454,
"s": 5406,
"text": "<form action = \"/book/create\" method = \"post\">\n"
},
{
"code": null,
"e": 5629,
"s": 5454,
"text": "Next method is text_field that outputs an <input> text field. The parameters for text_field are object and field name. In this case, the object is book and the name is title."
},
{
"code": null,
"e": 5791,
"s": 5629,
"text": "Rails method called collection_select, creates an HTML select menu built from an array, such as the @books one. There are five parameters, which are as follows β"
},
{
"code": null,
"e": 5866,
"s": 5791,
"text": ":book β The object you are manipulating. In this case, it's a book object."
},
{
"code": null,
"e": 5941,
"s": 5866,
"text": ":book β The object you are manipulating. In this case, it's a book object."
},
{
"code": null,
"e": 6007,
"s": 5941,
"text": ":subject_id β The field that is populated when the book is saved."
},
{
"code": null,
"e": 6073,
"s": 6007,
"text": ":subject_id β The field that is populated when the book is saved."
},
{
"code": null,
"e": 6114,
"s": 6073,
"text": "@books β The array you are working with."
},
{
"code": null,
"e": 6155,
"s": 6114,
"text": "@books β The array you are working with."
},
{
"code": null,
"e": 6265,
"s": 6155,
"text": ":id β The value that is stored in the database. In terms of HTML, this is the <option> tag's value parameter."
},
{
"code": null,
"e": 6375,
"s": 6265,
"text": ":id β The value that is stored in the database. In terms of HTML, this is the <option> tag's value parameter."
},
{
"code": null,
"e": 6481,
"s": 6375,
"text": ":name β The output that the user sees in the pull-down menu. This is the value between the <option> tags."
},
{
"code": null,
"e": 6587,
"s": 6481,
"text": ":name β The output that the user sees in the pull-down menu. This is the value between the <option> tags."
},
{
"code": null,
"e": 6741,
"s": 6587,
"text": "The next used is submit_tag, which outputs an <input> button that submits the form. Finally, there is the end method that simply translates into </form>."
},
{
"code": null,
"e": 6843,
"s": 6741,
"text": "Go to your browser and visit http://localhost:3000/book/new. This will give you the following screen."
},
{
"code": null,
"e": 6964,
"s": 6843,
"text": "Enter some data in this form and then click the Create button. Here i have added the following details into the fields β"
},
{
"code": null,
"e": 7061,
"s": 6964,
"text": "Title: Advance Physics\nPrice: 390\nSubject: Physics\nDescription: This is test to create new book\n"
},
{
"code": null,
"e": 7398,
"s": 7061,
"text": "When you click the Create button, it will call the create method, which does not need any view because this method is using either list or new methods to view the results. So, when you click the Create button, the data should submit successfully and redirect you to the list page, in which you now have a single item listed as follows β"
},
{
"code": null,
"e": 7536,
"s": 7398,
"text": "If you click the link, you should see another Template is missing error, since you haven't created the template file for show method yet."
},
{
"code": null,
"e": 7713,
"s": 7536,
"text": "This method will display the complete detail about any book available in the library. Create a show.html.erb file under app/views/book and populate it with the following code β"
},
{
"code": null,
"e": 8016,
"s": 7713,
"text": "<h1><%= @book.title %></h1>\n\n<p>\n <strong>Price: </strong> $<%= @book.price %><br />\n <strong>Subject :</strong> <%= @book.subject.name %><br />\n <strong>Created Date:</strong> <%= @book.created_at %><br />\n</p>\n\n<p><%= @book.description %></p>\n\n<hr />\n\n<%= link_to 'Back', {:action => 'list'} %>"
},
{
"code": null,
"e": 8149,
"s": 8016,
"text": "This is the first time you have taken the full advantage of associations, which enable you to easily pull data from related objects."
},
{
"code": null,
"e": 8392,
"s": 8149,
"text": "The format used is @variable.relatedObject.column. In this instance, you can pull the subject's name value through the @book variable using the belongs_to associations. If click on any listed record then it will show you the following screen."
},
{
"code": null,
"e": 8500,
"s": 8392,
"text": "Create a new file called edit.html.erb and save it in app/views/book. Populate it with the following code β"
},
{
"code": null,
"e": 8909,
"s": 8500,
"text": "<h1>Edit Book Detail</h1>\n\n<%= form_for @book, :url =>{:action => \"update\", :id =>@book} do |f| %>\n\n<p>Title: <%= f.text_field 'title' %></p>\n<p>Price: <%= f.text_field 'price' %></p>\n<p>Subject: <%= f.collection_select :subject_id, Subject.all, :id, :name %></p>\n<p>Description<br/>\n\n<%= f.text_area 'description' %></p>\n<%= f.submit \"Save changes\" %>\n<% end %>\n\n<%= link_to 'Back', {:action => 'list' } %>"
},
{
"code": null,
"e": 9021,
"s": 8909,
"text": "This code is very similar to the new method except action to be updated instead of creating and defining an id."
},
{
"code": null,
"e": 9293,
"s": 9021,
"text": "In this scenario, we used form_for tag for the form action. It will perform better than form_tag. Why because it will create interaction with the Model easily. Therefore it is better to use form_for tag whenever you need interaction between the model and the form fields."
},
{
"code": null,
"e": 9437,
"s": 9293,
"text": "At this point, we need some modification in the list method's view file. Go to the <li></li> element and modify it to look like the following β"
},
{
"code": null,
"e": 9579,
"s": 9437,
"text": "<li>\n <%= link_to c.title, {:action => \"show\", :id => c.id} -%>\n <b> <%= link_to 'Edit', {:action => \"edit\",\n :id => c.id} %></b>\n</li>"
},
{
"code": null,
"e": 9793,
"s": 9579,
"text": "Now, try to browse books using the http://localhost:3000/book/list. It will give you the listing of all the books along with Edit option. When you click the Edit option, then you will have next screen as follows β"
},
{
"code": null,
"e": 10113,
"s": 9793,
"text": "Now, you edit this information and then click the Save Changes button. This will result in a call to update method available in the controller file and it will update all the changed attribute. Notice that the update method does not need any view file because it's using either show or edit methods to show its results."
},
{
"code": null,
"e": 10380,
"s": 10113,
"text": "Removing information from a database using Ruby on Rails is almost too easy. You do not need to write any view code for the delete method because this method is using list method to display the result. So, let's just modify list.html.erb again and add a delete link."
},
{
"code": null,
"e": 10451,
"s": 10380,
"text": "Go to the <li></li> element and modify it to look like the following β"
},
{
"code": null,
"e": 10725,
"s": 10451,
"text": "<li>\n <%= link_to c.title, {:action => 'show', :id => c.id} -%>\n <b> <%= link_to 'Edit', {:action => 'edit', :id => c.id} %></b>\n <b> <%= link_to \"Delete\", {:action => 'delete', :id => c.id},\n :confirm => \"Are you sure you want to delete this item?\" %></b>\n</li>"
},
{
"code": null,
"e": 10905,
"s": 10725,
"text": "The :confirm parameter presents a JavaScript confirmation box asking if you really want to perform the action. If the user clicks OK, the action proceeds, and the item is deleted."
},
{
"code": null,
"e": 11058,
"s": 10905,
"text": "Now, try browsing books using http://localhost:3000/book/list. It will give you listing of all the books along with Edit and Delete options as follows β"
},
{
"code": null,
"e": 11121,
"s": 11058,
"text": "Now using the Delete option, you can delete any listed record."
},
{
"code": null,
"e": 11231,
"s": 11121,
"text": "Create a new file, show_subjects.html.erb, in the app/views/book directory and add the following code to it β"
},
{
"code": null,
"e": 11391,
"s": 11231,
"text": "<h1><%= @subject.name -%></h1>\n\n<ul>\n <% @subject.books.each do |c| %>\n <li><%= link_to c.title, :action => \"show\", :id => c.id -%></li>\n <% end %>\n</ul>"
},
{
"code": null,
"e": 11493,
"s": 11391,
"text": "You are taking advantage of associations by iterating through a single subject's many books listings."
},
{
"code": null,
"e": 11581,
"s": 11493,
"text": "Now modify the Subject: line of show.html.erb so that the subject listing shows a link."
},
{
"code": null,
"e": 11701,
"s": 11581,
"text": "<strong>Subject: </strong> <%= link_to @book.subject.name,\n:action => \"show_subjects\", :id => @book.subject.id %><br />"
},
{
"code": null,
"e": 11795,
"s": 11701,
"text": "This will output a list of subject on the index page, so that users can access them directly."
},
{
"code": null,
"e": 11862,
"s": 11795,
"text": "Modify list.html.erb to add the following to the top of the file β"
},
{
"code": null,
"e": 12017,
"s": 11862,
"text": "<ul id = \"subjects\">\n <% Subject.find(:all).each do |c| %>\n <li><%= link_to c.name, :action => \"show_subjects\", :id => c.id %></li>\n <% end %>\n</ul>"
},
{
"code": null,
"e": 12181,
"s": 12017,
"text": "Now try browsing books using http://localhost:3000/book/list. It will display all subjects with links so that you can browse all the books related to that subject."
},
{
"code": null,
"e": 12252,
"s": 12181,
"text": "Hope now you are feeling comfortable with all the operations of Rails."
},
{
"code": null,
"e": 12391,
"s": 12252,
"text": "The next chapter explains how to use Layouts to put your data in a better way. We will show you how to use CSS in your Rails applications."
},
{
"code": null,
"e": 12398,
"s": 12391,
"text": " Print"
},
{
"code": null,
"e": 12409,
"s": 12398,
"text": " Add Notes"
}
] |
Can a C++ virtual functions have default parameters?
|
Yes, C++ virtual functions can have default parameters.
Live Demo
#include<iostream>
using namespace std;
class B {
public:
virtual void s(int a = 0) {
cout<<" In Base \n";
}
};
class D: public B {
public:
virtual void s(int a) {
cout<<"In Derived, a="<<a;
}
};
int main(void) {
D d; // An object of class D
B *b = &d;// A pointer of type B* pointing to d
b->s();// prints"D::s() called"
return 0;
}
In Derived, a=0
In this output, we observe that, s() of derived class is called and default value of base class s() is used.
Default arguments do not participate in signature of functions. So signatures of s() in base class and derived class are considered same, hence base classβs s() is overridden. Default value is used at compile time. When compiler checks that an argument is missing in a function call, it substitutes the default value given. Therefore, in the above program, value of x is substituted at compile time, and at run time derived classβs s() is called. Value of a is substituted at compile time, and at run time derived classβs s() is called.
|
[
{
"code": null,
"e": 1118,
"s": 1062,
"text": "Yes, C++ virtual functions can have default parameters."
},
{
"code": null,
"e": 1129,
"s": 1118,
"text": " Live Demo"
},
{
"code": null,
"e": 1525,
"s": 1129,
"text": "#include<iostream>\nusing namespace std;\nclass B {\n public:\n virtual void s(int a = 0) {\n cout<<\" In Base \\n\";\n }\n};\n\nclass D: public B {\n public:\n virtual void s(int a) {\n cout<<\"In Derived, a=\"<<a;\n }\n};\n\nint main(void) {\n D d; // An object of class D\n B *b = &d;// A pointer of type B* pointing to d\n b->s();// prints\"D::s() called\"\n return 0;\n}"
},
{
"code": null,
"e": 1541,
"s": 1525,
"text": "In Derived, a=0"
},
{
"code": null,
"e": 1650,
"s": 1541,
"text": "In this output, we observe that, s() of derived class is called and default value of base class s() is used."
},
{
"code": null,
"e": 2187,
"s": 1650,
"text": "Default arguments do not participate in signature of functions. So signatures of s() in base class and derived class are considered same, hence base classβs s() is overridden. Default value is used at compile time. When compiler checks that an argument is missing in a function call, it substitutes the default value given. Therefore, in the above program, value of x is substituted at compile time, and at run time derived classβs s() is called. Value of a is substituted at compile time, and at run time derived classβs s() is called."
}
] |
Reverse Geocoding in Android
|
15 Feb, 2022
Reverse-Geocoding is a process used to convert coordinates (latitude and longitude) to human-readable addresses. This is not exactly the opposite of Geocoding. In Geocoding, the Place is associated with a name and fixed coordinates. These coordinates are Double in nature. Negligible change in these coordinates may still refer to the same place, but we shall never get the place name as it is associated with only those fixed coordinates. Therefore, we shall definitely get the complete address in reverse geocoding, but the place name is not guaranteed. Through this article, we will show you an example of how to perform reverse-geocoding in Android. But before moving ahead, please refer to the below articles:
Google Cloud Platform β Creating Google Cloud Console Account & ProjectsGenerating API Keys For Using Any Google APIsHow to Hide API and Secret Keys in Android Studio?How to Implement Googleβs Places AutocompleteBar in Android?How to Implement Current Location Button Feature in Google Maps in Android?
Google Cloud Platform β Creating Google Cloud Console Account & Projects
Generating API Keys For Using Any Google APIs
How to Hide API and Secret Keys in Android Studio?
How to Implement Googleβs Places AutocompleteBar in Android?
How to Implement Current Location Button Feature in Google Maps in Android?
For reverse-geocoding, we will need latitude and longitude in Double data type. So we will implement a Google Map and consider its center as our primary latitude and longitude. We can easily get the center coordinates using the camera position (refer to main code). Whenever the Map is dragged, the center will change and cause a change in latitude and longitude. Once the Map is idle, i.e. it stops being dragged or moving, the reverse geocoding algorithm will consider the center coordinates and process them to get a complete address. This will then be instantly posted to a textView. This will confirm that reverse-geocoding works fine in the code. Follow the below steps to create this project.
Step 1: Create a New Project in Android Studio
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project.
Step 2: Get and hide API Key
Our application utilizes Googleβs Places API, so we need to get the Places API key from Google. To get an API key, please refer to Generating API Keys For Using Any Google APIs.Hiding an API key is essential and to do so, please refer to How to Hide API and Secret Keys in Android Studio?.
Our application utilizes Googleβs Places API, so we need to get the Places API key from Google. To get an API key, please refer to Generating API Keys For Using Any Google APIs.
Hiding an API key is essential and to do so, please refer to How to Hide API and Secret Keys in Android Studio?.
Step 3: Add these dependencies
This dependency will be required for reverse geocoding.
Kotlin
dependencies { implementation 'com.google.android.libraries.places:places:2.4.0'}
Step 4: Adding a Map fragment, a custom location marker, and a text view in the layout (activity_main.xml) file
XML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <!--Map Fragment--> <fragment xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/map" tools:context=".MapsActivity" android:name="com.google.android.gms.maps.SupportMapFragment" /> <!--This layout overlays the Map Fragment which matches parent width and height--> <!--We want to display our TextView over the Map with good aesthetics--> <LinearLayout android:layout_margin="20sp" android:id="@+id/ll1" android:layout_width="match_parent" android:layout_height="100sp" android:background="@drawable/shape" android:layout_alignBottom="@id/map" android:orientation="horizontal"> <!--TextView for displaying Lat and Lng along with Address--> <TextView android:id="@+id/tv" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="10sp" /> </LinearLayout> <!--This is only for reference to the center of the screen, can be any element--> <!--We have set fixed this element at the parent center, which is the actual centre of the screen--> <Button android:id="@+id/centerReferencePoint" android:layout_width="0sp" android:layout_height="0sp" android:layout_centerInParent="true"/> <!--This image is the Marker--> <ImageView android:id="@+id/marker" android:layout_width="30sp" android:layout_height="40sp" android:src="@drawable/marker" android:layout_centerInParent="true" android:layout_above="@id/centerReferencePoint" /> </RelativeLayout>
Marker:
We downloaded this image in PNG format from the internet. It has no background color and can be referred to as a transparent image. Once downloaded, you can directly copy it from wherever it is stored, open Android Studio, and paste it into the drawable folder present in the res folder. While doing this, we renamed it as βmarkerβ which you may find in the ImageView attributes in the activity_main.xml.
Shape.xml file (Background of the Linear Layout in activity_main.xml)
We have set a white background and corner radius with some value. This is to make the layout look better.
XML
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" > <solid android:color="#ffffff" > </solid> <corners android:radius="11dp" > </corners> </shape>
Preview of Shape.xml
Preview of activity_main.xml:
activity_main.xml preview
Step 5: Working on the backend (MainActivity.kt)
We take the coordinates of the place present at the center of the screen and convert them into text addresses. Once the screen is dragged, the center coordinates change and the address change respectively. Changes take place once the screen is idle and not in motion and thatβs why we implemented our reverse-geocoding algorithm in the setOnCameraIdleListener. The below code is quite easy to understand. We have provided some comments to help you understand better.
Kotlin
package org.geeksforgeeks.reversegeocoding import android.content.pm.ApplicationInfoimport android.content.pm.PackageManagerimport android.location.Addressimport android.location.Geocoderimport android.os.Bundleimport android.widget.TextViewimport android.widget.Toastimport androidx.appcompat.app.AppCompatActivityimport com.google.android.gms.maps.CameraUpdateFactoryimport com.google.android.gms.maps.GoogleMapimport com.google.android.gms.maps.GoogleMap.OnCameraIdleListenerimport com.google.android.gms.maps.OnMapReadyCallbackimport com.google.android.gms.maps.SupportMapFragmentimport com.google.android.gms.maps.model.LatLngimport com.google.android.libraries.places.api.Placesimport java.io.IOExceptionimport java.util.* class MainActivity : AppCompatActivity(), OnMapReadyCallback { private lateinit var mMap: GoogleMap override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Fetching API_KEY which we wrapped val ai: ApplicationInfo = applicationContext.packageManager.getApplicationInfo(applicationContext.packageName, PackageManager.GET_META_DATA) val value = ai.metaData["com.google.android.geo.API_KEY"] val apiKey = value.toString() // Initializing the Places API // with the help of our API_KEY if (!Places.isInitialized()) { Places.initialize(applicationContext, apiKey) } // Initializing map val mapFragment = supportFragmentManager.findFragmentById(R.id.map) as SupportMapFragment mapFragment.getMapAsync(this) } override fun onMapReady(p0: GoogleMap) { mMap = p0 // These are GeeksforGeeks Noida Office Coordinates. val india = LatLng(28.5021359, 77.4054901) mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(india,17F)) mMap.setOnCameraIdleListener { val lat = mMap.cameraPosition.target.latitude val lng = mMap.cameraPosition.target.longitude val addressTV = findViewById<TextView>(R.id.tv) // Initializing Geocoder val mGeocoder = Geocoder(applicationContext, Locale.getDefault()) var addressString= "" // Reverse-Geocoding starts try { val addressList: List<Address> = mGeocoder.getFromLocation(lat, lng, 1) // use your lat, long value here if (addressList != null && addressList.isNotEmpty()) { val address = addressList[0] val sb = StringBuilder() for (i in 0 until address.maxAddressLineIndex) { sb.append(address.getAddressLine(i)).append("\n") } // Various Parameters of an Address are appended // to generate a complete Address if (address.premises != null) sb.append(address.premises).append(", ") sb.append(address.subAdminArea).append("\n") sb.append(address.locality).append(", ") sb.append(address.adminArea).append(", ") sb.append(address.countryName).append(", ") sb.append(address.postalCode) // StringBuilder sb is converted into a string // and this value is assigned to the // initially declared addressString string. addressString = sb.toString() } } catch (e: IOException) { Toast.makeText(applicationContext,"Unable connect to Geocoder",Toast.LENGTH_LONG).show() } // Finally, the address string is posted in the textView with LatLng. addressTV.text = "Lat: $lat \nLng: $lng \nAddress: $addressString" } }}
Output:
Observe, the address changes with a change in lat-long values. Lat-long values change when the user drags the screen, as the center keeps changing.
clintra
Android
Google Cloud Platform
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference Between Implicit Intent and Explicit Intent in Android
Retrofit with Kotlin Coroutine in Android
Flutter - BoxShadow Widget
Bundle in Android with Example
Animation in Android with Example
Kubernetes vs Docker
Difference Between Google Cloud Compute Engine and App Engine
Google Cloud Platform - Introduction to PhoneInfoga an OSINT Reconnaissance Tool
Google Cloud Platform - Managing Access using IAM in BigQuery
How to Build G Suite Add-ons with Google Apps script?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n15 Feb, 2022"
},
{
"code": null,
"e": 743,
"s": 28,
"text": "Reverse-Geocoding is a process used to convert coordinates (latitude and longitude) to human-readable addresses. This is not exactly the opposite of Geocoding. In Geocoding, the Place is associated with a name and fixed coordinates. These coordinates are Double in nature. Negligible change in these coordinates may still refer to the same place, but we shall never get the place name as it is associated with only those fixed coordinates. Therefore, we shall definitely get the complete address in reverse geocoding, but the place name is not guaranteed. Through this article, we will show you an example of how to perform reverse-geocoding in Android. But before moving ahead, please refer to the below articles:"
},
{
"code": null,
"e": 1046,
"s": 743,
"text": "Google Cloud Platform β Creating Google Cloud Console Account & ProjectsGenerating API Keys For Using Any Google APIsHow to Hide API and Secret Keys in Android Studio?How to Implement Googleβs Places AutocompleteBar in Android?How to Implement Current Location Button Feature in Google Maps in Android?"
},
{
"code": null,
"e": 1119,
"s": 1046,
"text": "Google Cloud Platform β Creating Google Cloud Console Account & Projects"
},
{
"code": null,
"e": 1165,
"s": 1119,
"text": "Generating API Keys For Using Any Google APIs"
},
{
"code": null,
"e": 1216,
"s": 1165,
"text": "How to Hide API and Secret Keys in Android Studio?"
},
{
"code": null,
"e": 1277,
"s": 1216,
"text": "How to Implement Googleβs Places AutocompleteBar in Android?"
},
{
"code": null,
"e": 1353,
"s": 1277,
"text": "How to Implement Current Location Button Feature in Google Maps in Android?"
},
{
"code": null,
"e": 2053,
"s": 1353,
"text": "For reverse-geocoding, we will need latitude and longitude in Double data type. So we will implement a Google Map and consider its center as our primary latitude and longitude. We can easily get the center coordinates using the camera position (refer to main code). Whenever the Map is dragged, the center will change and cause a change in latitude and longitude. Once the Map is idle, i.e. it stops being dragged or moving, the reverse geocoding algorithm will consider the center coordinates and process them to get a complete address. This will then be instantly posted to a textView. This will confirm that reverse-geocoding works fine in the code. Follow the below steps to create this project."
},
{
"code": null,
"e": 2100,
"s": 2053,
"text": "Step 1: Create a New Project in Android Studio"
},
{
"code": null,
"e": 2339,
"s": 2100,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project."
},
{
"code": null,
"e": 2368,
"s": 2339,
"text": "Step 2: Get and hide API Key"
},
{
"code": null,
"e": 2658,
"s": 2368,
"text": "Our application utilizes Googleβs Places API, so we need to get the Places API key from Google. To get an API key, please refer to Generating API Keys For Using Any Google APIs.Hiding an API key is essential and to do so, please refer to How to Hide API and Secret Keys in Android Studio?."
},
{
"code": null,
"e": 2836,
"s": 2658,
"text": "Our application utilizes Googleβs Places API, so we need to get the Places API key from Google. To get an API key, please refer to Generating API Keys For Using Any Google APIs."
},
{
"code": null,
"e": 2949,
"s": 2836,
"text": "Hiding an API key is essential and to do so, please refer to How to Hide API and Secret Keys in Android Studio?."
},
{
"code": null,
"e": 2980,
"s": 2949,
"text": "Step 3: Add these dependencies"
},
{
"code": null,
"e": 3036,
"s": 2980,
"text": "This dependency will be required for reverse geocoding."
},
{
"code": null,
"e": 3043,
"s": 3036,
"text": "Kotlin"
},
{
"code": "dependencies { implementation 'com.google.android.libraries.places:places:2.4.0'}",
"e": 3128,
"s": 3043,
"text": null
},
{
"code": null,
"e": 3240,
"s": 3128,
"text": "Step 4: Adding a Map fragment, a custom location marker, and a text view in the layout (activity_main.xml) file"
},
{
"code": null,
"e": 3244,
"s": 3240,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <!--Map Fragment--> <fragment xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:id=\"@+id/map\" tools:context=\".MapsActivity\" android:name=\"com.google.android.gms.maps.SupportMapFragment\" /> <!--This layout overlays the Map Fragment which matches parent width and height--> <!--We want to display our TextView over the Map with good aesthetics--> <LinearLayout android:layout_margin=\"20sp\" android:id=\"@+id/ll1\" android:layout_width=\"match_parent\" android:layout_height=\"100sp\" android:background=\"@drawable/shape\" android:layout_alignBottom=\"@id/map\" android:orientation=\"horizontal\"> <!--TextView for displaying Lat and Lng along with Address--> <TextView android:id=\"@+id/tv\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_margin=\"10sp\" /> </LinearLayout> <!--This is only for reference to the center of the screen, can be any element--> <!--We have set fixed this element at the parent center, which is the actual centre of the screen--> <Button android:id=\"@+id/centerReferencePoint\" android:layout_width=\"0sp\" android:layout_height=\"0sp\" android:layout_centerInParent=\"true\"/> <!--This image is the Marker--> <ImageView android:id=\"@+id/marker\" android:layout_width=\"30sp\" android:layout_height=\"40sp\" android:src=\"@drawable/marker\" android:layout_centerInParent=\"true\" android:layout_above=\"@id/centerReferencePoint\" /> </RelativeLayout>",
"e": 5434,
"s": 3244,
"text": null
},
{
"code": null,
"e": 5442,
"s": 5434,
"text": "Marker:"
},
{
"code": null,
"e": 5847,
"s": 5442,
"text": "We downloaded this image in PNG format from the internet. It has no background color and can be referred to as a transparent image. Once downloaded, you can directly copy it from wherever it is stored, open Android Studio, and paste it into the drawable folder present in the res folder. While doing this, we renamed it as βmarkerβ which you may find in the ImageView attributes in the activity_main.xml."
},
{
"code": null,
"e": 5917,
"s": 5847,
"text": "Shape.xml file (Background of the Linear Layout in activity_main.xml)"
},
{
"code": null,
"e": 6023,
"s": 5917,
"text": "We have set a white background and corner radius with some value. This is to make the layout look better."
},
{
"code": null,
"e": 6027,
"s": 6023,
"text": "XML"
},
{
"code": "<shape xmlns:android=\"http://schemas.android.com/apk/res/android\" android:shape=\"rectangle\" > <solid android:color=\"#ffffff\" > </solid> <corners android:radius=\"11dp\" > </corners> </shape>",
"e": 6257,
"s": 6027,
"text": null
},
{
"code": null,
"e": 6278,
"s": 6257,
"text": "Preview of Shape.xml"
},
{
"code": null,
"e": 6308,
"s": 6278,
"text": "Preview of activity_main.xml:"
},
{
"code": null,
"e": 6334,
"s": 6308,
"text": "activity_main.xml preview"
},
{
"code": null,
"e": 6383,
"s": 6334,
"text": "Step 5: Working on the backend (MainActivity.kt)"
},
{
"code": null,
"e": 6850,
"s": 6383,
"text": "We take the coordinates of the place present at the center of the screen and convert them into text addresses. Once the screen is dragged, the center coordinates change and the address change respectively. Changes take place once the screen is idle and not in motion and thatβs why we implemented our reverse-geocoding algorithm in the setOnCameraIdleListener. The below code is quite easy to understand. We have provided some comments to help you understand better."
},
{
"code": null,
"e": 6857,
"s": 6850,
"text": "Kotlin"
},
{
"code": "package org.geeksforgeeks.reversegeocoding import android.content.pm.ApplicationInfoimport android.content.pm.PackageManagerimport android.location.Addressimport android.location.Geocoderimport android.os.Bundleimport android.widget.TextViewimport android.widget.Toastimport androidx.appcompat.app.AppCompatActivityimport com.google.android.gms.maps.CameraUpdateFactoryimport com.google.android.gms.maps.GoogleMapimport com.google.android.gms.maps.GoogleMap.OnCameraIdleListenerimport com.google.android.gms.maps.OnMapReadyCallbackimport com.google.android.gms.maps.SupportMapFragmentimport com.google.android.gms.maps.model.LatLngimport com.google.android.libraries.places.api.Placesimport java.io.IOExceptionimport java.util.* class MainActivity : AppCompatActivity(), OnMapReadyCallback { private lateinit var mMap: GoogleMap override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Fetching API_KEY which we wrapped val ai: ApplicationInfo = applicationContext.packageManager.getApplicationInfo(applicationContext.packageName, PackageManager.GET_META_DATA) val value = ai.metaData[\"com.google.android.geo.API_KEY\"] val apiKey = value.toString() // Initializing the Places API // with the help of our API_KEY if (!Places.isInitialized()) { Places.initialize(applicationContext, apiKey) } // Initializing map val mapFragment = supportFragmentManager.findFragmentById(R.id.map) as SupportMapFragment mapFragment.getMapAsync(this) } override fun onMapReady(p0: GoogleMap) { mMap = p0 // These are GeeksforGeeks Noida Office Coordinates. val india = LatLng(28.5021359, 77.4054901) mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(india,17F)) mMap.setOnCameraIdleListener { val lat = mMap.cameraPosition.target.latitude val lng = mMap.cameraPosition.target.longitude val addressTV = findViewById<TextView>(R.id.tv) // Initializing Geocoder val mGeocoder = Geocoder(applicationContext, Locale.getDefault()) var addressString= \"\" // Reverse-Geocoding starts try { val addressList: List<Address> = mGeocoder.getFromLocation(lat, lng, 1) // use your lat, long value here if (addressList != null && addressList.isNotEmpty()) { val address = addressList[0] val sb = StringBuilder() for (i in 0 until address.maxAddressLineIndex) { sb.append(address.getAddressLine(i)).append(\"\\n\") } // Various Parameters of an Address are appended // to generate a complete Address if (address.premises != null) sb.append(address.premises).append(\", \") sb.append(address.subAdminArea).append(\"\\n\") sb.append(address.locality).append(\", \") sb.append(address.adminArea).append(\", \") sb.append(address.countryName).append(\", \") sb.append(address.postalCode) // StringBuilder sb is converted into a string // and this value is assigned to the // initially declared addressString string. addressString = sb.toString() } } catch (e: IOException) { Toast.makeText(applicationContext,\"Unable connect to Geocoder\",Toast.LENGTH_LONG).show() } // Finally, the address string is posted in the textView with LatLng. addressTV.text = \"Lat: $lat \\nLng: $lng \\nAddress: $addressString\" } }}",
"e": 10814,
"s": 6857,
"text": null
},
{
"code": null,
"e": 10822,
"s": 10814,
"text": "Output:"
},
{
"code": null,
"e": 10970,
"s": 10822,
"text": "Observe, the address changes with a change in lat-long values. Lat-long values change when the user drags the screen, as the center keeps changing."
},
{
"code": null,
"e": 10978,
"s": 10970,
"text": "clintra"
},
{
"code": null,
"e": 10986,
"s": 10978,
"text": "Android"
},
{
"code": null,
"e": 11008,
"s": 10986,
"text": "Google Cloud Platform"
},
{
"code": null,
"e": 11015,
"s": 11008,
"text": "Kotlin"
},
{
"code": null,
"e": 11023,
"s": 11015,
"text": "Android"
},
{
"code": null,
"e": 11121,
"s": 11023,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 11187,
"s": 11121,
"text": "Difference Between Implicit Intent and Explicit Intent in Android"
},
{
"code": null,
"e": 11229,
"s": 11187,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 11256,
"s": 11229,
"text": "Flutter - BoxShadow Widget"
},
{
"code": null,
"e": 11287,
"s": 11256,
"text": "Bundle in Android with Example"
},
{
"code": null,
"e": 11321,
"s": 11287,
"text": "Animation in Android with Example"
},
{
"code": null,
"e": 11342,
"s": 11321,
"text": "Kubernetes vs Docker"
},
{
"code": null,
"e": 11404,
"s": 11342,
"text": "Difference Between Google Cloud Compute Engine and App Engine"
},
{
"code": null,
"e": 11485,
"s": 11404,
"text": "Google Cloud Platform - Introduction to PhoneInfoga an OSINT Reconnaissance Tool"
},
{
"code": null,
"e": 11547,
"s": 11485,
"text": "Google Cloud Platform - Managing Access using IAM in BigQuery"
}
] |
Apache POI | Getting Started
|
11 Jul, 2022
POI stands For βPoor Obfuscation Implementationβ. Apache POI is an API provided by Apache foundation which is a collection of different java libraries. These libraries gives the facility to read, write and manipulate different Microsoft files such as excel sheet, power-point, and word files. Itβs first version release on 30 December 2001.
Apache POI have different classes and method to work upon different MS Office Document.
POIFSItβs Stand for βPoor Obfuscation Implementation File Systemβ.This component is the basic factor of all other POI elements. It is used to read different files explicitly.
HSSFItβs Stand for βHorrible Spreadsheet Formatβ. It is used to read and write xls format of MS-Excel files.
XSSFItβs Stand for βXML Spreadsheet Formatβ. It is used for xlsx file format of MS-Excel.
HPSFItβs Stand for βHorrible Property Set Formatβ.It is used to extract property sets of the MS-Office files.
HWPFItβs Stand for βHorrible Word Processor Formatβ.It is used to read and write doc extension files of MS-Word.
XWPFItβs Stand for βXML Word Processor Formatβ.It is used to read and write docx extension files of MS-Word.
HSLFItβs Stand for βHorrible Slide Layout Formatβ.It is used for read, create, and edit PowerPoint presentations.
HDGFItβs Stand for βHorrible Diagram Formatβ.It contains classes and methods for MS-Visio binary files.
HPBFItβs Stand for βHorrible Publisher Formatβ. use for read and write MS-Publisher files.
Their are two ways for installing apache jar file depending upon the type of project:
Maven ProjectIf the project is MAVEN then add dependency in pom.xml file in the project.The dependency is to be added is as given below:<!-- https://mvnrepository.com/artifact/org.apache.poi/poi --><dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.12</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.12</version> </dependency>Steps to create a maven project in eclipse and add dependencyClick on file->new->maven projectA new window appears, Click on NextSelect maven-archetype-webappGive name of the projectA project is formed in the workspace and a pom.xml file automatically appearsOpen this file in the existing structure of pom.xml fileCopy apache poi dependency in pom.xml fileMaven dependency is added when the pom.xml file is saved after copying the maven dependency.Simple Java ProjectIf not using maven, then one can download maven jar files from POI download. Include following jar files minimum to run the sample code:poi-3.10-FINAL.jarpoi-ooxml-3.10-FINAL.jarcommons-codec-1.5.jarpoi-ooxml-schemas-3.10-FINAL.jarxml-apis-1.0.b2.jarstax-api-1.0.1.jarxmlbeans-2.3.0.jardom4j-1.6.1.jarFollow this Link to see how to add external jars in eclipse.
Maven ProjectIf the project is MAVEN then add dependency in pom.xml file in the project.The dependency is to be added is as given below:<!-- https://mvnrepository.com/artifact/org.apache.poi/poi --><dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.12</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.12</version> </dependency>Steps to create a maven project in eclipse and add dependencyClick on file->new->maven projectA new window appears, Click on NextSelect maven-archetype-webappGive name of the projectA project is formed in the workspace and a pom.xml file automatically appearsOpen this file in the existing structure of pom.xml fileCopy apache poi dependency in pom.xml fileMaven dependency is added when the pom.xml file is saved after copying the maven dependency.
If the project is MAVEN then add dependency in pom.xml file in the project.The dependency is to be added is as given below:
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi --><dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.12</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.12</version> </dependency>
Steps to create a maven project in eclipse and add dependency
Click on file->new->maven project
A new window appears, Click on Next
Select maven-archetype-webapp
Give name of the project
A project is formed in the workspace and a pom.xml file automatically appears
Open this file in the existing structure of pom.xml file
Copy apache poi dependency in pom.xml file
Maven dependency is added when the pom.xml file is saved after copying the maven dependency.
Simple Java ProjectIf not using maven, then one can download maven jar files from POI download. Include following jar files minimum to run the sample code:poi-3.10-FINAL.jarpoi-ooxml-3.10-FINAL.jarcommons-codec-1.5.jarpoi-ooxml-schemas-3.10-FINAL.jarxml-apis-1.0.b2.jarstax-api-1.0.1.jarxmlbeans-2.3.0.jardom4j-1.6.1.jarFollow this Link to see how to add external jars in eclipse.
If not using maven, then one can download maven jar files from POI download. Include following jar files minimum to run the sample code:
poi-3.10-FINAL.jarpoi-ooxml-3.10-FINAL.jarcommons-codec-1.5.jarpoi-ooxml-schemas-3.10-FINAL.jarxml-apis-1.0.b2.jarstax-api-1.0.1.jarxmlbeans-2.3.0.jardom4j-1.6.1.jar
Follow this Link to see how to add external jars in eclipse.
WorkbookItβs the super-interface of all classes that create or maintain Excel workbooks. Following are the two classes that implement this interface
HSSFWorkbookIt implements the Workbook interface and is used for Excel files in .xls format. Listed below are some of the methods and constructors under this class.Methods and ConstructorsHSSFWorkbook()HSSFWorkbook(DirectoryNode directory, boolean preserveNodes)HSSFWorkbook(DirectoryNode directory, POIFSFileSystem fs, boolean preserveNodes)HSSFWorkbook(java.io.InputStream s)HSSFWorkbook(java.io.InputStream s, boolean preserveNodes)HSSFWorkbook(POIFSFileSystem fs)HSSFWorkbook(POIFSFileSystem fs, boolean preserveNodes)where:directory-It is the POI filesystem directory to process from.fs -It is the POI filesystem that contains the workbook stream.preservenodes β This is an optional parameter that decides whether to preserve other nodes like macros. It consumes a lot of memory as it stores all the POIFileSystem in memory (if set).XSSFWorkbookIt is a class that is used to represent both high and low level Excel file formats. It belongs to the org.apache.xssf.usemodel package and implements the Workbook interface. Listed below are the methods and constructors under this class.ClassesXSSFWorkbook()XSSFWorkbook(java.io.File file)XSSFWorkbook(java.io.InputStream is)XSSFWorkbook(java.lang.String path)MethodscreateSheet()createSheet(java.lang.String sheetname)createFont()createCellStyle()createFont()setPrintArea(int sheetIndex, int startColumn, int endColumn, int startRow, int endRow)
HSSFWorkbookIt implements the Workbook interface and is used for Excel files in .xls format. Listed below are some of the methods and constructors under this class.Methods and ConstructorsHSSFWorkbook()HSSFWorkbook(DirectoryNode directory, boolean preserveNodes)HSSFWorkbook(DirectoryNode directory, POIFSFileSystem fs, boolean preserveNodes)HSSFWorkbook(java.io.InputStream s)HSSFWorkbook(java.io.InputStream s, boolean preserveNodes)HSSFWorkbook(POIFSFileSystem fs)HSSFWorkbook(POIFSFileSystem fs, boolean preserveNodes)where:directory-It is the POI filesystem directory to process from.fs -It is the POI filesystem that contains the workbook stream.preservenodes β This is an optional parameter that decides whether to preserve other nodes like macros. It consumes a lot of memory as it stores all the POIFileSystem in memory (if set).
Methods and ConstructorsHSSFWorkbook()HSSFWorkbook(DirectoryNode directory, boolean preserveNodes)HSSFWorkbook(DirectoryNode directory, POIFSFileSystem fs, boolean preserveNodes)HSSFWorkbook(java.io.InputStream s)HSSFWorkbook(java.io.InputStream s, boolean preserveNodes)HSSFWorkbook(POIFSFileSystem fs)HSSFWorkbook(POIFSFileSystem fs, boolean preserveNodes)where:directory-It is the POI filesystem directory to process from.fs -It is the POI filesystem that contains the workbook stream.preservenodes β This is an optional parameter that decides whether to preserve other nodes like macros. It consumes a lot of memory as it stores all the POIFileSystem in memory (if set).
HSSFWorkbook()HSSFWorkbook(DirectoryNode directory, boolean preserveNodes)HSSFWorkbook(DirectoryNode directory, POIFSFileSystem fs, boolean preserveNodes)HSSFWorkbook(java.io.InputStream s)HSSFWorkbook(java.io.InputStream s, boolean preserveNodes)HSSFWorkbook(POIFSFileSystem fs)HSSFWorkbook(POIFSFileSystem fs, boolean preserveNodes)
where:directory-It is the POI filesystem directory to process from.fs -It is the POI filesystem that contains the workbook stream.preservenodes β This is an optional parameter that decides whether to preserve other nodes like macros. It consumes a lot of memory as it stores all the POIFileSystem in memory (if set).
XSSFWorkbookIt is a class that is used to represent both high and low level Excel file formats. It belongs to the org.apache.xssf.usemodel package and implements the Workbook interface. Listed below are the methods and constructors under this class.ClassesXSSFWorkbook()XSSFWorkbook(java.io.File file)XSSFWorkbook(java.io.InputStream is)XSSFWorkbook(java.lang.String path)MethodscreateSheet()createSheet(java.lang.String sheetname)createFont()createCellStyle()createFont()setPrintArea(int sheetIndex, int startColumn, int endColumn, int startRow, int endRow)
ClassesXSSFWorkbook()XSSFWorkbook(java.io.File file)XSSFWorkbook(java.io.InputStream is)XSSFWorkbook(java.lang.String path)
XSSFWorkbook()XSSFWorkbook(java.io.File file)XSSFWorkbook(java.io.InputStream is)XSSFWorkbook(java.lang.String path)
MethodscreateSheet()createSheet(java.lang.String sheetname)createFont()createCellStyle()createFont()setPrintArea(int sheetIndex, int startColumn, int endColumn, int startRow, int endRow)
createSheet()createSheet(java.lang.String sheetname)createFont()createCellStyle()createFont()setPrintArea(int sheetIndex, int startColumn, int endColumn, int startRow, int endRow)
Itβs suitable for large files and use less memoryThe main advantage of apache poi is that itβs support both HSSFWorkbook and XSSFWorkbook.Itβs contain HSSF implementation of excel file format
Itβs suitable for large files and use less memory
The main advantage of apache poi is that itβs support both HSSFWorkbook and XSSFWorkbook.
Itβs contain HSSF implementation of excel file format
kk773572498
nandinigujral
Articles
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": "\n11 Jul, 2022"
},
{
"code": null,
"e": 369,
"s": 28,
"text": "POI stands For βPoor Obfuscation Implementationβ. Apache POI is an API provided by Apache foundation which is a collection of different java libraries. These libraries gives the facility to read, write and manipulate different Microsoft files such as excel sheet, power-point, and word files. Itβs first version release on 30 December 2001."
},
{
"code": null,
"e": 457,
"s": 369,
"text": "Apache POI have different classes and method to work upon different MS Office Document."
},
{
"code": null,
"e": 632,
"s": 457,
"text": "POIFSItβs Stand for βPoor Obfuscation Implementation File Systemβ.This component is the basic factor of all other POI elements. It is used to read different files explicitly."
},
{
"code": null,
"e": 741,
"s": 632,
"text": "HSSFItβs Stand for βHorrible Spreadsheet Formatβ. It is used to read and write xls format of MS-Excel files."
},
{
"code": null,
"e": 831,
"s": 741,
"text": "XSSFItβs Stand for βXML Spreadsheet Formatβ. It is used for xlsx file format of MS-Excel."
},
{
"code": null,
"e": 941,
"s": 831,
"text": "HPSFItβs Stand for βHorrible Property Set Formatβ.It is used to extract property sets of the MS-Office files."
},
{
"code": null,
"e": 1054,
"s": 941,
"text": "HWPFItβs Stand for βHorrible Word Processor Formatβ.It is used to read and write doc extension files of MS-Word."
},
{
"code": null,
"e": 1163,
"s": 1054,
"text": "XWPFItβs Stand for βXML Word Processor Formatβ.It is used to read and write docx extension files of MS-Word."
},
{
"code": null,
"e": 1277,
"s": 1163,
"text": "HSLFItβs Stand for βHorrible Slide Layout Formatβ.It is used for read, create, and edit PowerPoint presentations."
},
{
"code": null,
"e": 1381,
"s": 1277,
"text": "HDGFItβs Stand for βHorrible Diagram Formatβ.It contains classes and methods for MS-Visio binary files."
},
{
"code": null,
"e": 1472,
"s": 1381,
"text": "HPBFItβs Stand for βHorrible Publisher Formatβ. use for read and write MS-Publisher files."
},
{
"code": null,
"e": 1558,
"s": 1472,
"text": "Their are two ways for installing apache jar file depending upon the type of project:"
},
{
"code": null,
"e": 2858,
"s": 1558,
"text": "Maven ProjectIf the project is MAVEN then add dependency in pom.xml file in the project.The dependency is to be added is as given below:<!-- https://mvnrepository.com/artifact/org.apache.poi/poi --><dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.12</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.12</version> </dependency>Steps to create a maven project in eclipse and add dependencyClick on file->new->maven projectA new window appears, Click on NextSelect maven-archetype-webappGive name of the projectA project is formed in the workspace and a pom.xml file automatically appearsOpen this file in the existing structure of pom.xml fileCopy apache poi dependency in pom.xml fileMaven dependency is added when the pom.xml file is saved after copying the maven dependency.Simple Java ProjectIf not using maven, then one can download maven jar files from POI download. Include following jar files minimum to run the sample code:poi-3.10-FINAL.jarpoi-ooxml-3.10-FINAL.jarcommons-codec-1.5.jarpoi-ooxml-schemas-3.10-FINAL.jarxml-apis-1.0.b2.jarstax-api-1.0.1.jarxmlbeans-2.3.0.jardom4j-1.6.1.jarFollow this Link to see how to add external jars in eclipse."
},
{
"code": null,
"e": 3778,
"s": 2858,
"text": "Maven ProjectIf the project is MAVEN then add dependency in pom.xml file in the project.The dependency is to be added is as given below:<!-- https://mvnrepository.com/artifact/org.apache.poi/poi --><dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.12</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.12</version> </dependency>Steps to create a maven project in eclipse and add dependencyClick on file->new->maven projectA new window appears, Click on NextSelect maven-archetype-webappGive name of the projectA project is formed in the workspace and a pom.xml file automatically appearsOpen this file in the existing structure of pom.xml fileCopy apache poi dependency in pom.xml fileMaven dependency is added when the pom.xml file is saved after copying the maven dependency."
},
{
"code": null,
"e": 3902,
"s": 3778,
"text": "If the project is MAVEN then add dependency in pom.xml file in the project.The dependency is to be added is as given below:"
},
{
"code": "<!-- https://mvnrepository.com/artifact/org.apache.poi/poi --><dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.12</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.12</version> </dependency>",
"e": 4237,
"s": 3902,
"text": null
},
{
"code": null,
"e": 4299,
"s": 4237,
"text": "Steps to create a maven project in eclipse and add dependency"
},
{
"code": null,
"e": 4333,
"s": 4299,
"text": "Click on file->new->maven project"
},
{
"code": null,
"e": 4369,
"s": 4333,
"text": "A new window appears, Click on Next"
},
{
"code": null,
"e": 4399,
"s": 4369,
"text": "Select maven-archetype-webapp"
},
{
"code": null,
"e": 4424,
"s": 4399,
"text": "Give name of the project"
},
{
"code": null,
"e": 4502,
"s": 4424,
"text": "A project is formed in the workspace and a pom.xml file automatically appears"
},
{
"code": null,
"e": 4559,
"s": 4502,
"text": "Open this file in the existing structure of pom.xml file"
},
{
"code": null,
"e": 4602,
"s": 4559,
"text": "Copy apache poi dependency in pom.xml file"
},
{
"code": null,
"e": 4695,
"s": 4602,
"text": "Maven dependency is added when the pom.xml file is saved after copying the maven dependency."
},
{
"code": null,
"e": 5076,
"s": 4695,
"text": "Simple Java ProjectIf not using maven, then one can download maven jar files from POI download. Include following jar files minimum to run the sample code:poi-3.10-FINAL.jarpoi-ooxml-3.10-FINAL.jarcommons-codec-1.5.jarpoi-ooxml-schemas-3.10-FINAL.jarxml-apis-1.0.b2.jarstax-api-1.0.1.jarxmlbeans-2.3.0.jardom4j-1.6.1.jarFollow this Link to see how to add external jars in eclipse."
},
{
"code": null,
"e": 5213,
"s": 5076,
"text": "If not using maven, then one can download maven jar files from POI download. Include following jar files minimum to run the sample code:"
},
{
"code": null,
"e": 5379,
"s": 5213,
"text": "poi-3.10-FINAL.jarpoi-ooxml-3.10-FINAL.jarcommons-codec-1.5.jarpoi-ooxml-schemas-3.10-FINAL.jarxml-apis-1.0.b2.jarstax-api-1.0.1.jarxmlbeans-2.3.0.jardom4j-1.6.1.jar"
},
{
"code": null,
"e": 5440,
"s": 5379,
"text": "Follow this Link to see how to add external jars in eclipse."
},
{
"code": null,
"e": 5589,
"s": 5440,
"text": "WorkbookItβs the super-interface of all classes that create or maintain Excel workbooks. Following are the two classes that implement this interface"
},
{
"code": null,
"e": 6986,
"s": 5589,
"text": "HSSFWorkbookIt implements the Workbook interface and is used for Excel files in .xls format. Listed below are some of the methods and constructors under this class.Methods and ConstructorsHSSFWorkbook()HSSFWorkbook(DirectoryNode directory, boolean preserveNodes)HSSFWorkbook(DirectoryNode directory, POIFSFileSystem fs, boolean preserveNodes)HSSFWorkbook(java.io.InputStream s)HSSFWorkbook(java.io.InputStream s, boolean preserveNodes)HSSFWorkbook(POIFSFileSystem fs)HSSFWorkbook(POIFSFileSystem fs, boolean preserveNodes)where:directory-It is the POI filesystem directory to process from.fs -It is the POI filesystem that contains the workbook stream.preservenodes β This is an optional parameter that decides whether to preserve other nodes like macros. It consumes a lot of memory as it stores all the POIFileSystem in memory (if set).XSSFWorkbookIt is a class that is used to represent both high and low level Excel file formats. It belongs to the org.apache.xssf.usemodel package and implements the Workbook interface. Listed below are the methods and constructors under this class.ClassesXSSFWorkbook()XSSFWorkbook(java.io.File file)XSSFWorkbook(java.io.InputStream is)XSSFWorkbook(java.lang.String path)MethodscreateSheet()createSheet(java.lang.String sheetname)createFont()createCellStyle()createFont()setPrintArea(int sheetIndex, int startColumn, int endColumn, int startRow, int endRow)"
},
{
"code": null,
"e": 7825,
"s": 6986,
"text": "HSSFWorkbookIt implements the Workbook interface and is used for Excel files in .xls format. Listed below are some of the methods and constructors under this class.Methods and ConstructorsHSSFWorkbook()HSSFWorkbook(DirectoryNode directory, boolean preserveNodes)HSSFWorkbook(DirectoryNode directory, POIFSFileSystem fs, boolean preserveNodes)HSSFWorkbook(java.io.InputStream s)HSSFWorkbook(java.io.InputStream s, boolean preserveNodes)HSSFWorkbook(POIFSFileSystem fs)HSSFWorkbook(POIFSFileSystem fs, boolean preserveNodes)where:directory-It is the POI filesystem directory to process from.fs -It is the POI filesystem that contains the workbook stream.preservenodes β This is an optional parameter that decides whether to preserve other nodes like macros. It consumes a lot of memory as it stores all the POIFileSystem in memory (if set)."
},
{
"code": null,
"e": 8500,
"s": 7825,
"text": "Methods and ConstructorsHSSFWorkbook()HSSFWorkbook(DirectoryNode directory, boolean preserveNodes)HSSFWorkbook(DirectoryNode directory, POIFSFileSystem fs, boolean preserveNodes)HSSFWorkbook(java.io.InputStream s)HSSFWorkbook(java.io.InputStream s, boolean preserveNodes)HSSFWorkbook(POIFSFileSystem fs)HSSFWorkbook(POIFSFileSystem fs, boolean preserveNodes)where:directory-It is the POI filesystem directory to process from.fs -It is the POI filesystem that contains the workbook stream.preservenodes β This is an optional parameter that decides whether to preserve other nodes like macros. It consumes a lot of memory as it stores all the POIFileSystem in memory (if set)."
},
{
"code": null,
"e": 8835,
"s": 8500,
"text": "HSSFWorkbook()HSSFWorkbook(DirectoryNode directory, boolean preserveNodes)HSSFWorkbook(DirectoryNode directory, POIFSFileSystem fs, boolean preserveNodes)HSSFWorkbook(java.io.InputStream s)HSSFWorkbook(java.io.InputStream s, boolean preserveNodes)HSSFWorkbook(POIFSFileSystem fs)HSSFWorkbook(POIFSFileSystem fs, boolean preserveNodes)"
},
{
"code": null,
"e": 9152,
"s": 8835,
"text": "where:directory-It is the POI filesystem directory to process from.fs -It is the POI filesystem that contains the workbook stream.preservenodes β This is an optional parameter that decides whether to preserve other nodes like macros. It consumes a lot of memory as it stores all the POIFileSystem in memory (if set)."
},
{
"code": null,
"e": 9711,
"s": 9152,
"text": "XSSFWorkbookIt is a class that is used to represent both high and low level Excel file formats. It belongs to the org.apache.xssf.usemodel package and implements the Workbook interface. Listed below are the methods and constructors under this class.ClassesXSSFWorkbook()XSSFWorkbook(java.io.File file)XSSFWorkbook(java.io.InputStream is)XSSFWorkbook(java.lang.String path)MethodscreateSheet()createSheet(java.lang.String sheetname)createFont()createCellStyle()createFont()setPrintArea(int sheetIndex, int startColumn, int endColumn, int startRow, int endRow)"
},
{
"code": null,
"e": 9835,
"s": 9711,
"text": "ClassesXSSFWorkbook()XSSFWorkbook(java.io.File file)XSSFWorkbook(java.io.InputStream is)XSSFWorkbook(java.lang.String path)"
},
{
"code": null,
"e": 9952,
"s": 9835,
"text": "XSSFWorkbook()XSSFWorkbook(java.io.File file)XSSFWorkbook(java.io.InputStream is)XSSFWorkbook(java.lang.String path)"
},
{
"code": null,
"e": 10139,
"s": 9952,
"text": "MethodscreateSheet()createSheet(java.lang.String sheetname)createFont()createCellStyle()createFont()setPrintArea(int sheetIndex, int startColumn, int endColumn, int startRow, int endRow)"
},
{
"code": null,
"e": 10319,
"s": 10139,
"text": "createSheet()createSheet(java.lang.String sheetname)createFont()createCellStyle()createFont()setPrintArea(int sheetIndex, int startColumn, int endColumn, int startRow, int endRow)"
},
{
"code": null,
"e": 10511,
"s": 10319,
"text": "Itβs suitable for large files and use less memoryThe main advantage of apache poi is that itβs support both HSSFWorkbook and XSSFWorkbook.Itβs contain HSSF implementation of excel file format"
},
{
"code": null,
"e": 10561,
"s": 10511,
"text": "Itβs suitable for large files and use less memory"
},
{
"code": null,
"e": 10651,
"s": 10561,
"text": "The main advantage of apache poi is that itβs support both HSSFWorkbook and XSSFWorkbook."
},
{
"code": null,
"e": 10705,
"s": 10651,
"text": "Itβs contain HSSF implementation of excel file format"
},
{
"code": null,
"e": 10717,
"s": 10705,
"text": "kk773572498"
},
{
"code": null,
"e": 10731,
"s": 10717,
"text": "nandinigujral"
},
{
"code": null,
"e": 10740,
"s": 10731,
"text": "Articles"
},
{
"code": null,
"e": 10745,
"s": 10740,
"text": "Java"
},
{
"code": null,
"e": 10750,
"s": 10745,
"text": "Java"
}
] |
How are variables stored in Python β Stack or Heap?
|
30 Jan, 2020
Memory allocation can be defined as allocating a block of space in the computer memory to a program. In Python memory allocation and deallocation method is automatic as the Python developers created a garbage collector for Python so that the user does not have to do manual garbage collection.
Garbage collection is a process in which the interpreter frees up the memory when not in use to make it available for other objects.Assume a case where no reference is pointing to an object in memory i.e. it is not in use so, the virtual machine has a garbage collector that automatically deletes that object from the heap memory
Note: For more on garbage collection you can refer to this article.
Reference counting works by counting the number of times an object is referenced by other objects in the system. When references to an object are removed, the reference count for an object is decremented. When the reference count becomes zero, the object is deallocated.
For example, Letβs suppose there are two or more variables that have the same value, so, what Python virtual machine does is, rather than creating another object of the same value in the private heap, it actually makes the second variable point to that originally existing value in the private heap. Therefore, in the case of classes, having a number of references may occupy a large amount of space in the memory, in such a case referencing counting is highly beneficial to preserve the memory to be available for other objects
Example:
# Literal 9 is an object b = 9a = 4 # Reference count of object 9 # becomes 0 and reference count# of object 4 is incremented# by 1b = 4
There are two parts of memory:
stack memory
heap memory
The methods/method calls and the references are stored in stack memory and all the values objects are stored in a private heap.
The allocation happens on contiguous blocks of memory. We call it stack memory allocation because the allocation happens in the function call stack. The size of memory to be allocated is known to the compiler and whenever a function is called, its variables get memory allocated on the stack.
It is the memory that is only needed inside a particular function or method call. When a function is called, it is added onto the programβs call stack. Any local memory assignments such as variable initializations inside the particular functions are stored temporarily on the function call stack, where it is deleted once the function returns, and the call stack moves on to the next task. This allocation onto a contiguous block of memory is handled by the compiler using predefined routines, and developers do not need to worry about it.
Example:
def func(): # All these variables get memory # allocated on stack a = 20 b = [] c = ""
The memory is allocated during execution of instructions written by programmers. Note that the name heap has nothing to do with heap data structure. It is called heap because it is a pile of memory space available to programmers to allocated and de-allocate. The variables are needed outside of method or function calls or are shared within multiple functions globally are stored in Heap memory.
Example:
# This memory for 10 integers # is allocated on heap. a = [0]*10
Python-Miscellaneous
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Jan, 2020"
},
{
"code": null,
"e": 322,
"s": 28,
"text": "Memory allocation can be defined as allocating a block of space in the computer memory to a program. In Python memory allocation and deallocation method is automatic as the Python developers created a garbage collector for Python so that the user does not have to do manual garbage collection."
},
{
"code": null,
"e": 652,
"s": 322,
"text": "Garbage collection is a process in which the interpreter frees up the memory when not in use to make it available for other objects.Assume a case where no reference is pointing to an object in memory i.e. it is not in use so, the virtual machine has a garbage collector that automatically deletes that object from the heap memory"
},
{
"code": null,
"e": 720,
"s": 652,
"text": "Note: For more on garbage collection you can refer to this article."
},
{
"code": null,
"e": 991,
"s": 720,
"text": "Reference counting works by counting the number of times an object is referenced by other objects in the system. When references to an object are removed, the reference count for an object is decremented. When the reference count becomes zero, the object is deallocated."
},
{
"code": null,
"e": 1520,
"s": 991,
"text": "For example, Letβs suppose there are two or more variables that have the same value, so, what Python virtual machine does is, rather than creating another object of the same value in the private heap, it actually makes the second variable point to that originally existing value in the private heap. Therefore, in the case of classes, having a number of references may occupy a large amount of space in the memory, in such a case referencing counting is highly beneficial to preserve the memory to be available for other objects"
},
{
"code": null,
"e": 1529,
"s": 1520,
"text": "Example:"
},
{
"code": "# Literal 9 is an object b = 9a = 4 # Reference count of object 9 # becomes 0 and reference count# of object 4 is incremented# by 1b = 4",
"e": 1670,
"s": 1529,
"text": null
},
{
"code": null,
"e": 1701,
"s": 1670,
"text": "There are two parts of memory:"
},
{
"code": null,
"e": 1714,
"s": 1701,
"text": "stack memory"
},
{
"code": null,
"e": 1726,
"s": 1714,
"text": "heap memory"
},
{
"code": null,
"e": 1854,
"s": 1726,
"text": "The methods/method calls and the references are stored in stack memory and all the values objects are stored in a private heap."
},
{
"code": null,
"e": 2147,
"s": 1854,
"text": "The allocation happens on contiguous blocks of memory. We call it stack memory allocation because the allocation happens in the function call stack. The size of memory to be allocated is known to the compiler and whenever a function is called, its variables get memory allocated on the stack."
},
{
"code": null,
"e": 2687,
"s": 2147,
"text": "It is the memory that is only needed inside a particular function or method call. When a function is called, it is added onto the programβs call stack. Any local memory assignments such as variable initializations inside the particular functions are stored temporarily on the function call stack, where it is deleted once the function returns, and the call stack moves on to the next task. This allocation onto a contiguous block of memory is handled by the compiler using predefined routines, and developers do not need to worry about it."
},
{
"code": null,
"e": 2696,
"s": 2687,
"text": "Example:"
},
{
"code": "def func(): # All these variables get memory # allocated on stack a = 20 b = [] c = \"\"",
"e": 2806,
"s": 2696,
"text": null
},
{
"code": null,
"e": 3202,
"s": 2806,
"text": "The memory is allocated during execution of instructions written by programmers. Note that the name heap has nothing to do with heap data structure. It is called heap because it is a pile of memory space available to programmers to allocated and de-allocate. The variables are needed outside of method or function calls or are shared within multiple functions globally are stored in Heap memory."
},
{
"code": null,
"e": 3211,
"s": 3202,
"text": "Example:"
},
{
"code": "# This memory for 10 integers # is allocated on heap. a = [0]*10 ",
"e": 3277,
"s": 3211,
"text": null
},
{
"code": null,
"e": 3298,
"s": 3277,
"text": "Python-Miscellaneous"
},
{
"code": null,
"e": 3305,
"s": 3298,
"text": "Python"
},
{
"code": null,
"e": 3403,
"s": 3305,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3435,
"s": 3403,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3462,
"s": 3435,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3483,
"s": 3462,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 3506,
"s": 3483,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 3562,
"s": 3506,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 3593,
"s": 3562,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 3635,
"s": 3593,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 3677,
"s": 3635,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 3716,
"s": 3677,
"text": "Python | datetime.timedelta() function"
}
] |
Python OpenCV: Epipolar Geometry
|
26 Mar, 2020
The general setup of epipolar geometry. The gray region is the epipolar plane. The orange line is the baseline, while the two blue lines are the epipolar lines.
Often in multiple view geometry, there are interesting relationships between the multiple cameras, a 3D point, and that pointβs projections in each of the cameraβs image plane. The geometry that relates the cameras, points in 3D, and the corresponding observations is referred to as the epipolar geometry of a stereo pair.
The standard epipolar geometry setup involves two cameras observing the same 3D point P, whose projection in each of the image planes is located at p and pβ respectively. The camera centers are located at O1 and O2, and the line between them is referred to as the baseline. We call the plane defined by the two camera centers and P the epipolar plane. The locations of where the baseline intersects the two image planes are known as the epipoles e and eβ. Finally, the lines defined by the intersection of the epipolar plane and the two image planes are known as the epipolar lines. The epipolar lines have the property that they intersect the baseline at the respective epipoles in the image plane.
When the two image planes are parallel, then the epipoles e and eβ are located at infinity. Notice that the epipolar lines are parallel to u axis of each image plane.
An interesting case of epipolar geometry is shown in Figure 4, which occurs when the image planes are parallel to each other. When the image planes are parallel to each other, then the epipoles e and eβ will be located at infinity since the baseline joining the centers O1, O2 is parallel to the image planes. Another important byproduct of this case is that the epipolar lines are parallel to an axis of each image plane. This case is especially useful and will be covered in greater detail in the subsequent section on image rectification.
In real-world situations, however, we are not given the exact location of the 3D location P, but can determine its projection in one of the image planes p. We also should be able to know the cameraβs locations, orientations, and camera matrices. What can we do with this knowledge? With the knowledge of camera locations O1, O2 and the image point p, we can define the epipolar plane. With this epipolar plane, we can then determine the epipolar lines1. By definition, Pβs projection into the second image p0 must be located on the epipolar line of the second image. Thus, a basic understanding of epipolar geometry allows us to create a strong constraint between image pairs without knowing the 3D structure of the scene.
The setup for determining the essential and fundamental matrices, which help map points and epipolar lines across views.
We will now try to develop seamless ways to do map points and epipolar lines across views. If we take the setup given in the original epipolar geometry framework (Figure 5), then we shall further deneM andM0 to be the camera projection matrices that map 3D points into their respective 2D image plane locations. Let us assume that the world reference system is associated to the rst camera with the second camera oset rst by a rotation R and then by a translation T. This species the camera projection matrices to be:
M = K[I 0] M' = K'[R T]
Now we find Fundamental Matrix (F) and Essential Matrix (E). Essential Matrix contains the information regarding translation and rotation, that describes the location of the second camera relative to the first in global coordinates.
Fundamental Matrix contains equivalent information as Essential Matrix additionally to the knowledge about the intrinsics of both cameras in order that we will relate the 2 cameras in pixel coordinates. (If we are using rectified images and normalize the point by dividing by the focal lengths, F=E). In simple words, Fundamental Matrix F maps some extent in one image to a line (epiline) within the other image. This is calculated from matching points from both the pictures. A minimum of 8 such points is required to seek out the elemental matrix (while using the 8-point algorithm). More points are preferred and use RANSAC to urge a more robust result.
So first we need to find as many possible matches between two images to find the fundamental matrix. For this, we use SIFT descriptors with FLANN based matcher and ratio test.
import numpy as npimport cv2from matplotlib import pyplot as plt # Load the left and right images# in gray scaleimgLeft = cv2.imread('image_l.png', 0)imgRight = cv2.imread('image_r.png', 0) # Detect the SIFT key points and # compute the descriptors for the # two imagessift = cv2.xfeatures2d.SIFT_create()keyPointsLeft, descriptorsLeft = sift.detectAndCompute(imgLeft, None) keyPointsRight, descriptorsRight = sift.detectAndCompute(imgRight, None) # Create FLANN matcher objectFLANN_INDEX_KDTREE = 0indexParams = dict(algorithm=FLANN_INDEX_KDTREE, trees=5)searchParams = dict(checks=50)flann = cv2.FlannBasedMatcher(indexParams, searchParams) # Apply ratio testgoodMatches = []ptsLeft = []ptsRight = [] for m, n in matches: if m.distance < 0.8 * n.distance: goodMatches.append([m]) ptsLeft.append(keyPointsLeft[m.trainIdx].pt) ptsRight.append(keyPointsRight[n.trainIdx].pt)
Image LeftImage Right
Letβs notice the basic Matrix.
ptsLeft = np.int32(ptsLeft)ptsRight = np.int32(ptsRight)F, mask = cv2.findFundamentalMat(ptsLeft, ptsRight, cv2.FM_LMEDS) # We select only inlier pointsptsLeft = ptsLeft[mask.ravel() == 1]ptsRight = ptsRight[mask.ravel() == 1]
Next, we find the epilines. Epilines corresponding to the points in the first image is drawn on the second image. So mentioning correct images are important here. We get an array of lines. So we define a new function to draw these lines on the images.
def drawlines(img1, img2, lines, pts1, pts2): r, c = img1.shape img1 = cv2.cvtColor(img1, cv2.COLOR_GRAY2BGR) img2 = cv2.cvtColor(img2, cv2.COLOR_GRAY2BGR) for r, pt1, pt2 in zip(lines, pts1, pts2): color = tuple(np.random.randint(0, 255, 3).tolist()) x0, y0 = map(int, [0, -r[2] / r[1] ]) x1, y1 = map(int, [c, -(r[2] + r[0] * c) / r[1] ]) img1 = cv2.line(img1, (x0, y0), (x1, y1), color, 1) img1 = cv2.circle(img1, tuple(pt1), 5, color, -1) img2 = cv2.circle(img2, tuple(pt2), 5, color, -1) return img1, img2
Now we find the epilines in both the images and draw them.
# Find epilines corresponding to points# in right image (second image) and# drawing its lines on left imagelinesLeft = cv2.computeCorrespondEpilines(ptsRight.reshape(-1, 1, 2), 2, F)linesLeft = linesLeft.reshape(-1, 3)img5, img6 = drawlines(imgLeft, imgRight, linesLeft, ptsLeft, ptsRight) # Find epilines corresponding to # points in left image (first image) and# drawing its lines on right imagelinesRight = cv2.computeCorrespondEpilines(ptsLeft.reshape(-1, 1, 2), 1, F)linesRight = linesRight.reshape(-1, 3) img3, img4 = drawlines(imgRight, imgLeft, linesRight, ptsRight, ptsLeft) plt.subplot(121), plt.imshow(img5)plt.subplot(122), plt.imshow(img3)plt.show()
Output:
Python-OpenCV
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": 52,
"s": 24,
"text": "\n26 Mar, 2020"
},
{
"code": null,
"e": 213,
"s": 52,
"text": "The general setup of epipolar geometry. The gray region is the epipolar plane. The orange line is the baseline, while the two blue lines are the epipolar lines."
},
{
"code": null,
"e": 536,
"s": 213,
"text": "Often in multiple view geometry, there are interesting relationships between the multiple cameras, a 3D point, and that pointβs projections in each of the cameraβs image plane. The geometry that relates the cameras, points in 3D, and the corresponding observations is referred to as the epipolar geometry of a stereo pair."
},
{
"code": null,
"e": 1236,
"s": 536,
"text": "The standard epipolar geometry setup involves two cameras observing the same 3D point P, whose projection in each of the image planes is located at p and pβ respectively. The camera centers are located at O1 and O2, and the line between them is referred to as the baseline. We call the plane defined by the two camera centers and P the epipolar plane. The locations of where the baseline intersects the two image planes are known as the epipoles e and eβ. Finally, the lines defined by the intersection of the epipolar plane and the two image planes are known as the epipolar lines. The epipolar lines have the property that they intersect the baseline at the respective epipoles in the image plane."
},
{
"code": null,
"e": 1403,
"s": 1236,
"text": "When the two image planes are parallel, then the epipoles e and eβ are located at infinity. Notice that the epipolar lines are parallel to u axis of each image plane."
},
{
"code": null,
"e": 1945,
"s": 1403,
"text": "An interesting case of epipolar geometry is shown in Figure 4, which occurs when the image planes are parallel to each other. When the image planes are parallel to each other, then the epipoles e and eβ will be located at infinity since the baseline joining the centers O1, O2 is parallel to the image planes. Another important byproduct of this case is that the epipolar lines are parallel to an axis of each image plane. This case is especially useful and will be covered in greater detail in the subsequent section on image rectification."
},
{
"code": null,
"e": 2668,
"s": 1945,
"text": "In real-world situations, however, we are not given the exact location of the 3D location P, but can determine its projection in one of the image planes p. We also should be able to know the cameraβs locations, orientations, and camera matrices. What can we do with this knowledge? With the knowledge of camera locations O1, O2 and the image point p, we can define the epipolar plane. With this epipolar plane, we can then determine the epipolar lines1. By definition, Pβs projection into the second image p0 must be located on the epipolar line of the second image. Thus, a basic understanding of epipolar geometry allows us to create a strong constraint between image pairs without knowing the 3D structure of the scene."
},
{
"code": null,
"e": 2789,
"s": 2668,
"text": "The setup for determining the essential and fundamental matrices, which help map points and epipolar lines across views."
},
{
"code": null,
"e": 3307,
"s": 2789,
"text": "We will now try to develop seamless ways to do map points and epipolar lines across views. If we take the setup given in the original epipolar geometry framework (Figure 5), then we shall further deneM andM0 to be the camera projection matrices that map 3D points into their respective 2D image plane locations. Let us assume that the world reference system is associated to the rst camera with the second camera oset rst by a rotation R and then by a translation T. This species the camera projection matrices to be:"
},
{
"code": null,
"e": 3333,
"s": 3307,
"text": "M = K[I 0] M' = K'[R T]"
},
{
"code": null,
"e": 3566,
"s": 3333,
"text": "Now we find Fundamental Matrix (F) and Essential Matrix (E). Essential Matrix contains the information regarding translation and rotation, that describes the location of the second camera relative to the first in global coordinates."
},
{
"code": null,
"e": 4223,
"s": 3566,
"text": "Fundamental Matrix contains equivalent information as Essential Matrix additionally to the knowledge about the intrinsics of both cameras in order that we will relate the 2 cameras in pixel coordinates. (If we are using rectified images and normalize the point by dividing by the focal lengths, F=E). In simple words, Fundamental Matrix F maps some extent in one image to a line (epiline) within the other image. This is calculated from matching points from both the pictures. A minimum of 8 such points is required to seek out the elemental matrix (while using the 8-point algorithm). More points are preferred and use RANSAC to urge a more robust result."
},
{
"code": null,
"e": 4399,
"s": 4223,
"text": "So first we need to find as many possible matches between two images to find the fundamental matrix. For this, we use SIFT descriptors with FLANN based matcher and ratio test."
},
{
"code": "import numpy as npimport cv2from matplotlib import pyplot as plt # Load the left and right images# in gray scaleimgLeft = cv2.imread('image_l.png', 0)imgRight = cv2.imread('image_r.png', 0) # Detect the SIFT key points and # compute the descriptors for the # two imagessift = cv2.xfeatures2d.SIFT_create()keyPointsLeft, descriptorsLeft = sift.detectAndCompute(imgLeft, None) keyPointsRight, descriptorsRight = sift.detectAndCompute(imgRight, None) # Create FLANN matcher objectFLANN_INDEX_KDTREE = 0indexParams = dict(algorithm=FLANN_INDEX_KDTREE, trees=5)searchParams = dict(checks=50)flann = cv2.FlannBasedMatcher(indexParams, searchParams) # Apply ratio testgoodMatches = []ptsLeft = []ptsRight = [] for m, n in matches: if m.distance < 0.8 * n.distance: goodMatches.append([m]) ptsLeft.append(keyPointsLeft[m.trainIdx].pt) ptsRight.append(keyPointsRight[n.trainIdx].pt)",
"e": 5525,
"s": 4399,
"text": null
},
{
"code": null,
"e": 5547,
"s": 5525,
"text": "Image LeftImage Right"
},
{
"code": null,
"e": 5578,
"s": 5547,
"text": "Letβs notice the basic Matrix."
},
{
"code": " ptsLeft = np.int32(ptsLeft)ptsRight = np.int32(ptsRight)F, mask = cv2.findFundamentalMat(ptsLeft, ptsRight, cv2.FM_LMEDS) # We select only inlier pointsptsLeft = ptsLeft[mask.ravel() == 1]ptsRight = ptsRight[mask.ravel() == 1]",
"e": 5880,
"s": 5578,
"text": null
},
{
"code": null,
"e": 6132,
"s": 5880,
"text": "Next, we find the epilines. Epilines corresponding to the points in the first image is drawn on the second image. So mentioning correct images are important here. We get an array of lines. So we define a new function to draw these lines on the images."
},
{
"code": "def drawlines(img1, img2, lines, pts1, pts2): r, c = img1.shape img1 = cv2.cvtColor(img1, cv2.COLOR_GRAY2BGR) img2 = cv2.cvtColor(img2, cv2.COLOR_GRAY2BGR) for r, pt1, pt2 in zip(lines, pts1, pts2): color = tuple(np.random.randint(0, 255, 3).tolist()) x0, y0 = map(int, [0, -r[2] / r[1] ]) x1, y1 = map(int, [c, -(r[2] + r[0] * c) / r[1] ]) img1 = cv2.line(img1, (x0, y0), (x1, y1), color, 1) img1 = cv2.circle(img1, tuple(pt1), 5, color, -1) img2 = cv2.circle(img2, tuple(pt2), 5, color, -1) return img1, img2",
"e": 6875,
"s": 6132,
"text": null
},
{
"code": null,
"e": 6934,
"s": 6875,
"text": "Now we find the epilines in both the images and draw them."
},
{
"code": "# Find epilines corresponding to points# in right image (second image) and# drawing its lines on left imagelinesLeft = cv2.computeCorrespondEpilines(ptsRight.reshape(-1, 1, 2), 2, F)linesLeft = linesLeft.reshape(-1, 3)img5, img6 = drawlines(imgLeft, imgRight, linesLeft, ptsLeft, ptsRight) # Find epilines corresponding to # points in left image (first image) and# drawing its lines on right imagelinesRight = cv2.computeCorrespondEpilines(ptsLeft.reshape(-1, 1, 2), 1, F)linesRight = linesRight.reshape(-1, 3) img3, img4 = drawlines(imgRight, imgLeft, linesRight, ptsRight, ptsLeft) plt.subplot(121), plt.imshow(img5)plt.subplot(122), plt.imshow(img3)plt.show()",
"e": 7892,
"s": 6934,
"text": null
},
{
"code": null,
"e": 7900,
"s": 7892,
"text": "Output:"
},
{
"code": null,
"e": 7914,
"s": 7900,
"text": "Python-OpenCV"
},
{
"code": null,
"e": 7921,
"s": 7914,
"text": "Python"
},
{
"code": null,
"e": 8019,
"s": 7921,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8051,
"s": 8019,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 8078,
"s": 8051,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 8099,
"s": 8078,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 8122,
"s": 8099,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 8178,
"s": 8122,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 8209,
"s": 8178,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 8251,
"s": 8209,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 8293,
"s": 8251,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 8332,
"s": 8293,
"text": "Python | Get unique values from a list"
}
] |
Introduction to PySimpleGUI
|
10 May, 2020
It is easy to use with simple yet HIGHLY customizable features of GUI for Python. It is based solely on Tkinter. It is a Python GUI For Humans that Transforms Tkinter, PyQt, Remi, WxPython into portable user-friendly Pythonic interfaces.
The Steps for using the GUI package PySimpleGUI are:-
Install PySimpleGUI
pip install PySimpleGUI
Find a GUI that looks a lot similar to which you want to design and create.
Copy code from Cookbook.
Paste into your IDE and run.
Example: Sample Program to showcase PySimpleGUI layout.
import PySimpleGUI as sg sg.theme('BluePurple') layout = [[sg.Text('Your typed characters appear here:'), sg.Text(size=(15,1), key='-OUTPUT-')], [sg.Input(key='-IN-')], [sg.Button('Display'), sg.Button('Exit')]] window = sg.Window('Introduction', layout) while True: event, values = window.read() print(event, values) if event in (None, 'Exit'): break if event == 'Display': # Update the "output" text element # to be the value of "input" element window['-OUTPUT-'].update(values['-IN-']) window.close()
Output:
Python-gui
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n10 May, 2020"
},
{
"code": null,
"e": 266,
"s": 28,
"text": "It is easy to use with simple yet HIGHLY customizable features of GUI for Python. It is based solely on Tkinter. It is a Python GUI For Humans that Transforms Tkinter, PyQt, Remi, WxPython into portable user-friendly Pythonic interfaces."
},
{
"code": null,
"e": 320,
"s": 266,
"text": "The Steps for using the GUI package PySimpleGUI are:-"
},
{
"code": null,
"e": 340,
"s": 320,
"text": "Install PySimpleGUI"
},
{
"code": null,
"e": 365,
"s": 340,
"text": "pip install PySimpleGUI "
},
{
"code": null,
"e": 441,
"s": 365,
"text": "Find a GUI that looks a lot similar to which you want to design and create."
},
{
"code": null,
"e": 466,
"s": 441,
"text": "Copy code from Cookbook."
},
{
"code": null,
"e": 495,
"s": 466,
"text": "Paste into your IDE and run."
},
{
"code": null,
"e": 551,
"s": 495,
"text": "Example: Sample Program to showcase PySimpleGUI layout."
},
{
"code": "import PySimpleGUI as sg sg.theme('BluePurple') layout = [[sg.Text('Your typed characters appear here:'), sg.Text(size=(15,1), key='-OUTPUT-')], [sg.Input(key='-IN-')], [sg.Button('Display'), sg.Button('Exit')]] window = sg.Window('Introduction', layout) while True: event, values = window.read() print(event, values) if event in (None, 'Exit'): break if event == 'Display': # Update the \"output\" text element # to be the value of \"input\" element window['-OUTPUT-'].update(values['-IN-']) window.close()",
"e": 1149,
"s": 551,
"text": null
},
{
"code": null,
"e": 1157,
"s": 1149,
"text": "Output:"
},
{
"code": null,
"e": 1168,
"s": 1157,
"text": "Python-gui"
},
{
"code": null,
"e": 1175,
"s": 1168,
"text": "Python"
},
{
"code": null,
"e": 1273,
"s": 1175,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1291,
"s": 1273,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1333,
"s": 1291,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1355,
"s": 1333,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1390,
"s": 1355,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 1416,
"s": 1390,
"text": "Python String | replace()"
},
{
"code": null,
"e": 1448,
"s": 1416,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1477,
"s": 1448,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 1504,
"s": 1477,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1534,
"s": 1504,
"text": "Iterate over a list in Python"
}
] |
Python 3 - IF...ELIF...ELSE Statements
|
An else statement can be combined with an if statement. An else statement contains a block of code that executes if the conditional expression in the if statement resolves to 0 or a FALSE value.
The else statement is an optional statement and there could be at the most only one else statement following if.
The syntax of the if...else statement is β
if expression:
statement(s)
else:
statement(s)
#!/usr/bin/python3
amount = int(input("Enter amount: "))
if amount<1000:
discount = amount*0.05
print ("Discount",discount)
else:
discount = amount*0.10
print ("Discount",discount)
print ("Net payable:",amount-discount)
In the above example, discount is calculated on the input amount. Rate of discount is 5%, if the amount is less than 1000, and 10% if it is above 10000. When the above code is executed, it produces the following result β
Enter amount: 600
Discount 30.0
Net payable: 570.0
Enter amount: 1200
Discount 120.0
Net payable: 1080.0
The elif statement allows you to check multiple expressions for TRUE and execute a block of code as soon as one of the conditions evaluates to TRUE.
Similar to the else, the elif statement is optional. However, unlike else, for which there can be at the most one statement, there can be an arbitrary number of elif statements following an if.
if expression1:
statement(s)
elif expression2:
statement(s)
elif expression3:
statement(s)
else:
statement(s)
Core Python does not provide switch or case statements as in other languages, but we can use if..elif...statements to simulate switch case as follows β
#!/usr/bin/python3
amount = int(input("Enter amount: "))
if amount<1000:
discount = amount*0.05
print ("Discount",discount)
elif amount<5000:
discount = amount*0.10
print ("Discount",discount)
else:
discount = amount*0.15
print ("Discount",discount)
print ("Net payable:",amount-discount)
When the above code is executed, it produces the following result β
Enter amount: 600
Discount 30.0
Net payable: 570.0
Enter amount: 3000
Discount 300.0
Net payable: 2700.0
Enter amount: 6000
Discount 900.0
Net payable: 5100.0
|
[
{
"code": null,
"e": 2669,
"s": 2474,
"text": "An else statement can be combined with an if statement. An else statement contains a block of code that executes if the conditional expression in the if statement resolves to 0 or a FALSE value."
},
{
"code": null,
"e": 2782,
"s": 2669,
"text": "The else statement is an optional statement and there could be at the most only one else statement following if."
},
{
"code": null,
"e": 2825,
"s": 2782,
"text": "The syntax of the if...else statement is β"
},
{
"code": null,
"e": 2880,
"s": 2825,
"text": "if expression:\n statement(s)\n\nelse:\n statement(s)\n"
},
{
"code": null,
"e": 3119,
"s": 2880,
"text": "#!/usr/bin/python3\n\namount = int(input(\"Enter amount: \"))\n\nif amount<1000:\n discount = amount*0.05\n print (\"Discount\",discount)\nelse:\n discount = amount*0.10\n print (\"Discount\",discount)\n \nprint (\"Net payable:\",amount-discount)"
},
{
"code": null,
"e": 3340,
"s": 3119,
"text": "In the above example, discount is calculated on the input amount. Rate of discount is 5%, if the amount is less than 1000, and 10% if it is above 10000. When the above code is executed, it produces the following result β"
},
{
"code": null,
"e": 3447,
"s": 3340,
"text": "Enter amount: 600\nDiscount 30.0\nNet payable: 570.0\n\nEnter amount: 1200\nDiscount 120.0\nNet payable: 1080.0\n"
},
{
"code": null,
"e": 3596,
"s": 3447,
"text": "The elif statement allows you to check multiple expressions for TRUE and execute a block of code as soon as one of the conditions evaluates to TRUE."
},
{
"code": null,
"e": 3790,
"s": 3596,
"text": "Similar to the else, the elif statement is optional. However, unlike else, for which there can be at the most one statement, there can be an arbitrary number of elif statements following an if."
},
{
"code": null,
"e": 3913,
"s": 3790,
"text": "if expression1:\n statement(s)\nelif expression2:\n statement(s)\nelif expression3:\n statement(s)\nelse:\n statement(s)\n"
},
{
"code": null,
"e": 4065,
"s": 3913,
"text": "Core Python does not provide switch or case statements as in other languages, but we can use if..elif...statements to simulate switch case as follows β"
},
{
"code": null,
"e": 4379,
"s": 4065,
"text": "#!/usr/bin/python3\n\namount = int(input(\"Enter amount: \"))\n\nif amount<1000:\n discount = amount*0.05\n print (\"Discount\",discount)\nelif amount<5000:\n discount = amount*0.10\n print (\"Discount\",discount)\nelse:\n discount = amount*0.15\n print (\"Discount\",discount)\n \nprint (\"Net payable:\",amount-discount)"
},
{
"code": null,
"e": 4447,
"s": 4379,
"text": "When the above code is executed, it produces the following result β"
}
] |
Dart β Advance Concepts of Iterable Collections
|
07 Sep, 2021
In this article, we will look into some of the important concepts related to iterables in Dart.
In dart, there is no operator [ ] in Iterable. To better understand letβs take a look at the below example.
Example:
Dart
void main() { // invalid program Iterable<int> iterable = [1, 2, 3, 4, 5 ]; // line 1int value = iterable[1]; // line 2}
Output:
In this example, we have a list of 5 elements. What if we want to fetch the number from the particular index? In line 2 we tried to fetch numbers from the index by writing iterable[1] but the [ ] operator isnβt defined in the class. As you can see the above error we got.
So the question arises how do we fetch the number from a particular index in dart? To do that we use elementAt() in dart.
Syntax:
elementAt(index_number)
Here,
index_number: It is the index whose value is to be fetched.
Take a look at the below example.
Example:
Here we want to fetch the value at index 3. So letβs see how we can do that with the help of elementAt().
Dart
void main() { Iterable<int> iterable = [1, 2, 3, 4, 5]; print('Element at 3rd index is ${iterable.elementAt(3)}');}
Output:
Explanation: So here we passed index no 3 because we wanted the value stored at that index. So we got the result 4. This is how we can get the value stored at a particular index using elementAt().
We can map an existing iterable and derive modified values. To do so follow the below steps:
Take a collection
Transform all its items according to a condition.
Return a new collection
Example:
Dart
void main() { const list = [5,4,3,2,1]; final value = list.map((number) => number*2); print('new values are: ${value}');}
Output:
Itβs the ability to transform the process into a very short piece of code. Letβs see an example.
Same above code if we write using for loop then we can see below as it takes many lines of code.
Dart
void main() { const list = [5,4,3,2,1]; final element = []; for(var value in list){ element.add(value * 2); } print('new values are: ${element}');}
Output :
new values are: [10, 8, 6, 4, 2]
We see that although the output is the same, the lines of code are more. Thatβs why a map is powerful because using it we can write code in fewer lines and get the desired result.
According to the official docs, the map returns lazy Iterable.
Letβs take a look at the below code:
Dart
void main() { const list = [5,4,3,2,1]; final value = list.map((number) => number*2); print('new values are: ${value}');}
Here, the anonymous function isnβt evaluated until the result is used.
This means:
It means map will not evaluate the anonymous function if the result is not getting printed or itβs isnβt in any use anywhere.
Itβs a performance optimization technique ensuring that all the resulting items are only calculated when needed.
Blogathon-2021
Dart-Collection
Blogathon
Dart
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQL Query to Insert Multiple Rows
How to Connect Python with SQL Database?
How to Import JSON Data into SQL Server?
Difference Between Local Storage, Session Storage And Cookies
Data Mining - Cluster Analysis
Flutter - DropDownButton Widget
Listview.builder in Flutter
Flutter - Custom Bottom Navigation Bar
Splash Screen in Flutter
Flutter - Asset Image
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n07 Sep, 2021"
},
{
"code": null,
"e": 125,
"s": 28,
"text": "In this article, we will look into some of the important concepts related to iterables in Dart. "
},
{
"code": null,
"e": 233,
"s": 125,
"text": "In dart, there is no operator [ ] in Iterable. To better understand letβs take a look at the below example."
},
{
"code": null,
"e": 242,
"s": 233,
"text": "Example:"
},
{
"code": null,
"e": 247,
"s": 242,
"text": "Dart"
},
{
"code": "void main() { // invalid program Iterable<int> iterable = [1, 2, 3, 4, 5 ]; // line 1int value = iterable[1]; // line 2}",
"e": 374,
"s": 247,
"text": null
},
{
"code": null,
"e": 383,
"s": 374,
"text": "Output: "
},
{
"code": null,
"e": 657,
"s": 383,
"text": "In this example, we have a list of 5 elements. What if we want to fetch the number from the particular index? In line 2 we tried to fetch numbers from the index by writing iterable[1] but the [ ] operator isnβt defined in the class. As you can see the above error we got."
},
{
"code": null,
"e": 780,
"s": 657,
"text": "So the question arises how do we fetch the number from a particular index in dart? To do that we use elementAt() in dart. "
},
{
"code": null,
"e": 788,
"s": 780,
"text": "Syntax:"
},
{
"code": null,
"e": 812,
"s": 788,
"text": "elementAt(index_number)"
},
{
"code": null,
"e": 818,
"s": 812,
"text": "Here,"
},
{
"code": null,
"e": 878,
"s": 818,
"text": "index_number: It is the index whose value is to be fetched."
},
{
"code": null,
"e": 912,
"s": 878,
"text": "Take a look at the below example."
},
{
"code": null,
"e": 922,
"s": 912,
"text": "Example: "
},
{
"code": null,
"e": 1028,
"s": 922,
"text": "Here we want to fetch the value at index 3. So letβs see how we can do that with the help of elementAt()."
},
{
"code": null,
"e": 1033,
"s": 1028,
"text": "Dart"
},
{
"code": "void main() { Iterable<int> iterable = [1, 2, 3, 4, 5]; print('Element at 3rd index is ${iterable.elementAt(3)}');}",
"e": 1149,
"s": 1033,
"text": null
},
{
"code": null,
"e": 1157,
"s": 1149,
"text": "Output:"
},
{
"code": null,
"e": 1354,
"s": 1157,
"text": "Explanation: So here we passed index no 3 because we wanted the value stored at that index. So we got the result 4. This is how we can get the value stored at a particular index using elementAt()."
},
{
"code": null,
"e": 1447,
"s": 1354,
"text": "We can map an existing iterable and derive modified values. To do so follow the below steps:"
},
{
"code": null,
"e": 1465,
"s": 1447,
"text": "Take a collection"
},
{
"code": null,
"e": 1515,
"s": 1465,
"text": "Transform all its items according to a condition."
},
{
"code": null,
"e": 1539,
"s": 1515,
"text": "Return a new collection"
},
{
"code": null,
"e": 1549,
"s": 1539,
"text": "Example: "
},
{
"code": null,
"e": 1554,
"s": 1549,
"text": "Dart"
},
{
"code": "void main() { const list = [5,4,3,2,1]; final value = list.map((number) => number*2); print('new values are: ${value}');}",
"e": 1679,
"s": 1554,
"text": null
},
{
"code": null,
"e": 1687,
"s": 1679,
"text": "Output:"
},
{
"code": null,
"e": 1784,
"s": 1687,
"text": "Itβs the ability to transform the process into a very short piece of code. Letβs see an example."
},
{
"code": null,
"e": 1882,
"s": 1784,
"text": "Same above code if we write using for loop then we can see below as it takes many lines of code. "
},
{
"code": null,
"e": 1887,
"s": 1882,
"text": "Dart"
},
{
"code": "void main() { const list = [5,4,3,2,1]; final element = []; for(var value in list){ element.add(value * 2); } print('new values are: ${element}');}",
"e": 2048,
"s": 1887,
"text": null
},
{
"code": null,
"e": 2058,
"s": 2048,
"text": " Output :"
},
{
"code": null,
"e": 2091,
"s": 2058,
"text": "new values are: [10, 8, 6, 4, 2]"
},
{
"code": null,
"e": 2271,
"s": 2091,
"text": "We see that although the output is the same, the lines of code are more. Thatβs why a map is powerful because using it we can write code in fewer lines and get the desired result."
},
{
"code": null,
"e": 2334,
"s": 2271,
"text": "According to the official docs, the map returns lazy Iterable."
},
{
"code": null,
"e": 2371,
"s": 2334,
"text": "Letβs take a look at the below code:"
},
{
"code": null,
"e": 2376,
"s": 2371,
"text": "Dart"
},
{
"code": "void main() { const list = [5,4,3,2,1]; final value = list.map((number) => number*2); print('new values are: ${value}');}",
"e": 2504,
"s": 2376,
"text": null
},
{
"code": null,
"e": 2576,
"s": 2504,
"text": "Here, the anonymous function isnβt evaluated until the result is used. "
},
{
"code": null,
"e": 2588,
"s": 2576,
"text": "This means:"
},
{
"code": null,
"e": 2714,
"s": 2588,
"text": "It means map will not evaluate the anonymous function if the result is not getting printed or itβs isnβt in any use anywhere."
},
{
"code": null,
"e": 2827,
"s": 2714,
"text": "Itβs a performance optimization technique ensuring that all the resulting items are only calculated when needed."
},
{
"code": null,
"e": 2842,
"s": 2827,
"text": "Blogathon-2021"
},
{
"code": null,
"e": 2858,
"s": 2842,
"text": "Dart-Collection"
},
{
"code": null,
"e": 2868,
"s": 2858,
"text": "Blogathon"
},
{
"code": null,
"e": 2873,
"s": 2868,
"text": "Dart"
},
{
"code": null,
"e": 2971,
"s": 2873,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3005,
"s": 2971,
"text": "SQL Query to Insert Multiple Rows"
},
{
"code": null,
"e": 3046,
"s": 3005,
"text": "How to Connect Python with SQL Database?"
},
{
"code": null,
"e": 3087,
"s": 3046,
"text": "How to Import JSON Data into SQL Server?"
},
{
"code": null,
"e": 3149,
"s": 3087,
"text": "Difference Between Local Storage, Session Storage And Cookies"
},
{
"code": null,
"e": 3180,
"s": 3149,
"text": "Data Mining - Cluster Analysis"
},
{
"code": null,
"e": 3212,
"s": 3180,
"text": "Flutter - DropDownButton Widget"
},
{
"code": null,
"e": 3240,
"s": 3212,
"text": "Listview.builder in Flutter"
},
{
"code": null,
"e": 3279,
"s": 3240,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 3304,
"s": 3279,
"text": "Splash Screen in Flutter"
}
] |
Python | time.clock_settime() method
|
17 Sep, 2019
time.clock_settime() method of Time module is used to set the time (in seconds) of the specified clock clk_id. Basically, clk_id is a integer value which represents the id of the clock.
Syntax: time.clock_settime(clk_id, seconds)
Parameters:clk_id: A clk_id constant or an integer value representing clk_id of the clock.
Return type: This method does not return any value.
Code: Use of time.clock_settime() method
# Python program to explain time.clock_settime() method # importing time moduleimport time # clk_id for System-wide real-time clockclk_id = time.CLOCK_REALTIME # Get the current value of# system-wide real-time clock (in seconds)# using time.clock_gettime() methodt = time.clock_gettime(clk_id) print("Current value of system-wide real-time clock: % d seconds" % t) # Set the new value of# time (in seconds) for# System-wide real-time clock# using time.clock_settime() methodseconds = 10000000time.clock_settime(clk_id, seconds) print("\nTime modified") # Get the modified value of# system-wide real-time clock (in seconds)# using time.clock_gettime() methodt = time.clock_gettime(clk_id) print("\nCurrent value of system-wide real-time clock: % d seconds" % t)
Current value of system-wide real-time clock: 1568589568 seconds
Time modified
Current value of system-wide real-time clock: 10000000 seconds
Reference: https://docs.python.org/3/library/time.html#time.clock_settime
python-utility
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
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
Convert integer to string in Python
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n17 Sep, 2019"
},
{
"code": null,
"e": 214,
"s": 28,
"text": "time.clock_settime() method of Time module is used to set the time (in seconds) of the specified clock clk_id. Basically, clk_id is a integer value which represents the id of the clock."
},
{
"code": null,
"e": 258,
"s": 214,
"text": "Syntax: time.clock_settime(clk_id, seconds)"
},
{
"code": null,
"e": 349,
"s": 258,
"text": "Parameters:clk_id: A clk_id constant or an integer value representing clk_id of the clock."
},
{
"code": null,
"e": 401,
"s": 349,
"text": "Return type: This method does not return any value."
},
{
"code": null,
"e": 442,
"s": 401,
"text": "Code: Use of time.clock_settime() method"
},
{
"code": "# Python program to explain time.clock_settime() method # importing time moduleimport time # clk_id for System-wide real-time clockclk_id = time.CLOCK_REALTIME # Get the current value of# system-wide real-time clock (in seconds)# using time.clock_gettime() methodt = time.clock_gettime(clk_id) print(\"Current value of system-wide real-time clock: % d seconds\" % t) # Set the new value of# time (in seconds) for# System-wide real-time clock# using time.clock_settime() methodseconds = 10000000time.clock_settime(clk_id, seconds) print(\"\\nTime modified\") # Get the modified value of# system-wide real-time clock (in seconds)# using time.clock_gettime() methodt = time.clock_gettime(clk_id) print(\"\\nCurrent value of system-wide real-time clock: % d seconds\" % t)",
"e": 1218,
"s": 442,
"text": null
},
{
"code": null,
"e": 1364,
"s": 1218,
"text": "Current value of system-wide real-time clock: 1568589568 seconds\n\nTime modified\n\nCurrent value of system-wide real-time clock: 10000000 seconds\n"
},
{
"code": null,
"e": 1438,
"s": 1364,
"text": "Reference: https://docs.python.org/3/library/time.html#time.clock_settime"
},
{
"code": null,
"e": 1453,
"s": 1438,
"text": "python-utility"
},
{
"code": null,
"e": 1460,
"s": 1453,
"text": "Python"
},
{
"code": null,
"e": 1558,
"s": 1460,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1576,
"s": 1558,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1618,
"s": 1576,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1640,
"s": 1618,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1675,
"s": 1640,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 1707,
"s": 1675,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1736,
"s": 1707,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 1763,
"s": 1736,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1793,
"s": 1763,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 1814,
"s": 1793,
"text": "Python OOPs Concepts"
}
] |
Get timestamp date range with MySQL Select?
|
To select timestamp data range, use the below syntax β
SELECT *FROM yourTableName
where yourDataTimeField >= anyDateRange
and yourDataTimeField < anyDateRange
To understand the above syntax, let us create a table. The query to create a table is as follows β
mysql> create table DateRange
β> (
β> DueTime timestamp
β> );
Query OK, 0 rows affected (1.34 sec)
Insert some records in the table using insert command. The query is as follows β
mysql> insert into DateRange values('2016-11-13');
Query OK, 1 row affected (0.51 sec)
mysql> insert into DateRange values('2016-10-14');
Query OK, 1 row affected (0.23 sec)
mysql> insert into DateRange values('2017-01-23');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DateRange values('2017-05-14');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DateRange values('2017-08-25');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DateRange values('2018-09-28');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DateRange values('2018-11-17');
Query OK, 1 row affected (0.47 sec)
mysql> insert into DateRange values('2018-12-13');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DateRange values('2018-12-16');
Query OK, 1 row affected (0.27 sec)
Display all records from the table using select command. The query is as follows β
mysql> select *from DateRange;
The following is the output β
+---------------------+
| DueTime |
+---------------------+
| 2016-11-13 00:00:00 |
| 2016-10-14 00:00:00 |
| 2017-01-23 00:00:00 |
| 2017-05-14 00:00:00 |
| 2017-08-25 00:00:00 |
| 2018-09-28 00:00:00 |
| 2018-11-17 00:00:00 |
| 2018-12-13 00:00:00 |
| 2018-12-16 00:00:00 |
+---------------------+
9 rows in set (0.00 sec)
To select timestamp date range, use the following query β
mysql> select *from DateRange
β> where DueTime >= '2017-05-14'
β> and DueTime < '2018-12-17';
The following is the output β
+---------------------+
| DueTime |
+---------------------+
| 2017-05-14 00:00:00 |
| 2017-08-25 00:00:00 |
| 2018-09-28 00:00:00 |
| 2018-11-17 00:00:00 |
| 2018-12-13 00:00:00 |
| 2018-12-16 00:00:00 |
+---------------------+
6 rows in set (0.00 sec)
Suppose if your timestamp is in unix timestamp, then use the following syntax.
select *from yourTableName
where yourColumnName >= unix_timestamp('anyDateValueβ)
and yourColumnName < unix_timestamp('anyDateValueβ)
|
[
{
"code": null,
"e": 1242,
"s": 1187,
"text": "To select timestamp data range, use the below syntax β"
},
{
"code": null,
"e": 1346,
"s": 1242,
"text": "SELECT *FROM yourTableName\nwhere yourDataTimeField >= anyDateRange\nand yourDataTimeField < anyDateRange"
},
{
"code": null,
"e": 1445,
"s": 1346,
"text": "To understand the above syntax, let us create a table. The query to create a table is as follows β"
},
{
"code": null,
"e": 1553,
"s": 1445,
"text": "mysql> create table DateRange\n β> (\n β> DueTime timestamp\n β> );\nQuery OK, 0 rows affected (1.34 sec)"
},
{
"code": null,
"e": 1634,
"s": 1553,
"text": "Insert some records in the table using insert command. The query is as follows β"
},
{
"code": null,
"e": 2425,
"s": 1634,
"text": "mysql> insert into DateRange values('2016-11-13');\nQuery OK, 1 row affected (0.51 sec)\n\nmysql> insert into DateRange values('2016-10-14');\nQuery OK, 1 row affected (0.23 sec)\n\nmysql> insert into DateRange values('2017-01-23');\nQuery OK, 1 row affected (0.10 sec)\n\nmysql> insert into DateRange values('2017-05-14');\nQuery OK, 1 row affected (0.19 sec)\n\nmysql> insert into DateRange values('2017-08-25');\nQuery OK, 1 row affected (0.17 sec)\n\nmysql> insert into DateRange values('2018-09-28');\nQuery OK, 1 row affected (0.18 sec)\n\nmysql> insert into DateRange values('2018-11-17');\nQuery OK, 1 row affected (0.47 sec)\n\nmysql> insert into DateRange values('2018-12-13');\nQuery OK, 1 row affected (0.17 sec)\n\nmysql> insert into DateRange values('2018-12-16');\nQuery OK, 1 row affected (0.27 sec)"
},
{
"code": null,
"e": 2508,
"s": 2425,
"text": "Display all records from the table using select command. The query is as follows β"
},
{
"code": null,
"e": 2539,
"s": 2508,
"text": "mysql> select *from DateRange;"
},
{
"code": null,
"e": 2569,
"s": 2539,
"text": "The following is the output β"
},
{
"code": null,
"e": 2906,
"s": 2569,
"text": "+---------------------+\n| DueTime |\n+---------------------+\n| 2016-11-13 00:00:00 |\n| 2016-10-14 00:00:00 |\n| 2017-01-23 00:00:00 |\n| 2017-05-14 00:00:00 |\n| 2017-08-25 00:00:00 |\n| 2018-09-28 00:00:00 |\n| 2018-11-17 00:00:00 |\n| 2018-12-13 00:00:00 |\n| 2018-12-16 00:00:00 |\n+---------------------+\n9 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2964,
"s": 2906,
"text": "To select timestamp date range, use the following query β"
},
{
"code": null,
"e": 3064,
"s": 2964,
"text": "mysql> select *from DateRange\n β> where DueTime >= '2017-05-14'\n β> and DueTime < '2018-12-17';"
},
{
"code": null,
"e": 3094,
"s": 3064,
"text": "The following is the output β"
},
{
"code": null,
"e": 3359,
"s": 3094,
"text": "+---------------------+\n| DueTime |\n+---------------------+\n| 2017-05-14 00:00:00 |\n| 2017-08-25 00:00:00 |\n| 2018-09-28 00:00:00 |\n| 2018-11-17 00:00:00 |\n| 2018-12-13 00:00:00 |\n| 2018-12-16 00:00:00 |\n+---------------------+\n6 rows in set (0.00 sec)"
},
{
"code": null,
"e": 3438,
"s": 3359,
"text": "Suppose if your timestamp is in unix timestamp, then use the following syntax."
},
{
"code": null,
"e": 3572,
"s": 3438,
"text": "select *from yourTableName\nwhere yourColumnName >= unix_timestamp('anyDateValueβ)\nand yourColumnName < unix_timestamp('anyDateValueβ)"
}
] |
PLSQL | FLOOR Function
|
19 Feb, 2021
The FLOOR is an inbuilt function in PLSQL which is used to return the largest integer value which will be either equal to or less than from a given input number.
Syntax:
FLOOR(number)
Parameters Used: This function accepts a parameter number which is the input number on which FLOOR function is called.
Return Value: This function returns the largest integer value which will be either equal to or less than from a given input number.
Supported Versions of Oracle/PLSQL:
Oracle 12cOracle 11gOracle 10gOracle 9iOracle 8i
Oracle 12c
Oracle 11g
Oracle 10g
Oracle 9i
Oracle 8i
Letβs see some examples which illustrate the FLOOR function:
Example-1:
DECLARE
Test_Number number1 := 2.6;
BEGIN
dbms_output.put_line(FLOOR(Test_Number number1));
END;
Output:
2
In the above example, some parameter is taken. Like 2.6 is taken as the parameter and 2 is returned because 2 is the greatest whole number less than 2.6
Example-2:
DECLARE
Test_Number number1 := -2.6;
BEGIN
dbms_output.put_line(FLOOR(Test_Number number1));
END;
Output:
-3
In the above example, some parameter is taken. In the above example, -2.6 is taken as the parameter and -3 is returned because -3 is the greatest whole number less than -2.6
Advantage: This function is used to find out the largest integer value which will be either equal to or less than from a given input number.
arorakashish0911
SQL-PL/SQL
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
Window functions in SQL
What is Temporary Table in SQL?
SQL | Sub queries in From Clause
SQL using Python
RANK() Function in SQL Server
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL Query to Convert VARCHAR to INT
SQL Query to Compare Two Dates
How to Write a SQL Query For a Specific Date Range and Date Time?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Feb, 2021"
},
{
"code": null,
"e": 191,
"s": 28,
"text": "The FLOOR is an inbuilt function in PLSQL which is used to return the largest integer value which will be either equal to or less than from a given input number. "
},
{
"code": null,
"e": 201,
"s": 191,
"text": "Syntax: "
},
{
"code": null,
"e": 215,
"s": 201,
"text": "FLOOR(number)"
},
{
"code": null,
"e": 335,
"s": 215,
"text": "Parameters Used: This function accepts a parameter number which is the input number on which FLOOR function is called. "
},
{
"code": null,
"e": 468,
"s": 335,
"text": "Return Value: This function returns the largest integer value which will be either equal to or less than from a given input number. "
},
{
"code": null,
"e": 506,
"s": 468,
"text": "Supported Versions of Oracle/PLSQL: "
},
{
"code": null,
"e": 555,
"s": 506,
"text": "Oracle 12cOracle 11gOracle 10gOracle 9iOracle 8i"
},
{
"code": null,
"e": 566,
"s": 555,
"text": "Oracle 12c"
},
{
"code": null,
"e": 577,
"s": 566,
"text": "Oracle 11g"
},
{
"code": null,
"e": 588,
"s": 577,
"text": "Oracle 10g"
},
{
"code": null,
"e": 598,
"s": 588,
"text": "Oracle 9i"
},
{
"code": null,
"e": 608,
"s": 598,
"text": "Oracle 8i"
},
{
"code": null,
"e": 670,
"s": 608,
"text": "Letβs see some examples which illustrate the FLOOR function: "
},
{
"code": null,
"e": 683,
"s": 670,
"text": "Example-1: "
},
{
"code": null,
"e": 798,
"s": 683,
"text": "DECLARE \n Test_Number number1 := 2.6;\n \nBEGIN \n dbms_output.put_line(FLOOR(Test_Number number1)); \n \nEND; "
},
{
"code": null,
"e": 808,
"s": 798,
"text": "Output: "
},
{
"code": null,
"e": 810,
"s": 808,
"text": "2"
},
{
"code": null,
"e": 964,
"s": 810,
"text": "In the above example, some parameter is taken. Like 2.6 is taken as the parameter and 2 is returned because 2 is the greatest whole number less than 2.6 "
},
{
"code": null,
"e": 977,
"s": 964,
"text": "Example-2: "
},
{
"code": null,
"e": 1093,
"s": 977,
"text": "DECLARE \n Test_Number number1 := -2.6;\n \nBEGIN \n dbms_output.put_line(FLOOR(Test_Number number1)); \n \nEND; "
},
{
"code": null,
"e": 1103,
"s": 1093,
"text": "Output: "
},
{
"code": null,
"e": 1106,
"s": 1103,
"text": "-3"
},
{
"code": null,
"e": 1281,
"s": 1106,
"text": "In the above example, some parameter is taken. In the above example, -2.6 is taken as the parameter and -3 is returned because -3 is the greatest whole number less than -2.6 "
},
{
"code": null,
"e": 1423,
"s": 1281,
"text": "Advantage: This function is used to find out the largest integer value which will be either equal to or less than from a given input number. "
},
{
"code": null,
"e": 1440,
"s": 1423,
"text": "arorakashish0911"
},
{
"code": null,
"e": 1451,
"s": 1440,
"text": "SQL-PL/SQL"
},
{
"code": null,
"e": 1455,
"s": 1451,
"text": "SQL"
},
{
"code": null,
"e": 1459,
"s": 1455,
"text": "SQL"
},
{
"code": null,
"e": 1557,
"s": 1459,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1623,
"s": 1557,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 1647,
"s": 1623,
"text": "Window functions in SQL"
},
{
"code": null,
"e": 1679,
"s": 1647,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 1712,
"s": 1679,
"text": "SQL | Sub queries in From Clause"
},
{
"code": null,
"e": 1729,
"s": 1712,
"text": "SQL using Python"
},
{
"code": null,
"e": 1759,
"s": 1729,
"text": "RANK() Function in SQL Server"
},
{
"code": null,
"e": 1837,
"s": 1759,
"text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter"
},
{
"code": null,
"e": 1873,
"s": 1837,
"text": "SQL Query to Convert VARCHAR to INT"
},
{
"code": null,
"e": 1904,
"s": 1873,
"text": "SQL Query to Compare Two Dates"
}
] |
Spring Boot β Customize the Jackson ObjectMapper
|
07 Feb, 2022
When using JSON format, Spring Boot will use an ObjectMapper instance to serialize responses and deserialize requests. In this article, we will take a look at the most common ways to configure the serialization and deserialization options.
Let us do go through the default configuration. So by default, the Spring Boot configuration will be as follows:
Disable MapperFeature.DEFAULT_VIEW_INCLUSION
Disable DeserializationFeature. FAIL_ON_UNKNOWN_PROPERTIES
Disable SerializationFeature. WRITE_DATES_AS_TIMESTAMPS
Letβs start with a quicker example by implementing the same
Implementation:
The client sends a GET request to our/coffee?name=Lavazza
The controller will return a new Coffee object
Spring will use customization options by using String and LocalDateTime objects
It is as follows, so primarily we need to create a class named Coffee which is as follows:
// Class
public class Coffee {
// Getters and setters
private String name;
private String brand;
private LocalDateTime date;
}
Now we will also be defining a simple REST controller to demonstrate the serialization:
@GetMapping ("/coffee")
public Coffee getCoffee(
@RequestParam(required = false) String brand,
@RequiredParam(required = false) String name) {
return new Coffee()
.setBrand(brand)
.setDate(FIXED_DATE)
.setName(name);
}
By default, the response when calling GET http://localhost:8080/cofffee?brand=lavazza will be as follows:
{
"name": null,
"brand": Lavazza",
"date": "2020 - 11 - 16T10: 21: 35.974"
}
Now We would like to exclude null values and to have a custom date format (dd-MM-yyy HH:mm). The final response will be as follows:
{
"brand:" "Lavazza",
"date": "04-11-20202 10:34"
}
When using Spring Boot, we have the option to customize the default ObjectMapper or to override it. Weβll cover both of these options in the next sections.
Now let us roll to eccentric point in article by customizing the Default Object Mapper. Here. we will be discussing how to customize the default ObjectMapper that Spring Boot uses.
Application Properties and Custom Jackson Module
The simplest way to configure the mapper is via application properties. The general structure of the configuration is as follows:
spring.jackson.<category_name>.<feature_name>=true, false
As an example, if we want to disable SerializationFeature. WRITE_DATES_AS_TIMESTAMPS, weβll add:
spring.jackson.serialization.write-dates-as-timestamps=false
Besides the mentioned feature categories, we can also configure property inclusion:
spring.jackson.default-property-inclusion=always, non_null, non_absent, non_default, non_empty
Configuring the environment variables in the simplest approach. The downside of this approach is that we canβt customize advanced options like having a custom date format for LocalDateTime. At this point, weβll obtain the result which is shown below:
{
"brand": "Lavazza",
"date": "2020-11-16T10:35:34.593"
}
Now in order to achieve our goal, weβll register a new JavaTimeModule with our custom date format:
@Configuration
@PropertySource("classpath:coffee.properties")
// Class
public class CoffeeRegisterModuleConfig {
@Bean
public Module javaTimeModule() {
JavaTimeModule module = new JavaTimeModule();
module.addSerializer(LOCAL_DATETIME_SERIALIZER);
return module;
}
}
Jackson2ObjectMapperBuilderCustomizer
The purpose of this functional interface is to allow us to create configuration beans. They will be applied to the default ObjectMapper created via Jackson2ObjectMapperBuilder.
@Bean
public Jackson2ObjectMapperBuilderCustomizer jsonCustomizer() {
return builder ->
builder.serializationInclusion(JsonInclude.Include.NON_NULL)
.serializers(LOCAL_DATETIME_SERIALIZER);
}
The configuration beans are applied in a specific order, which we can control using the @Order annotations. This elegant approach is suitable if we want to configure the ObjectMapper from different configurations or modules.
Jackson2ObjectMapperBuilder
Another clean approach is to define a Jackson2ObjectMapperBuilder bean. Actually, Spring Boot is using this builder by default when building the ObjectMapper and will automatically pick up the defined one:
@Bean
public Jackson2ObjectMapperBuilder jackson2ObjectMapperBuilder() {
return new
Jackson2ObjectMapperBuilder().serializers(LOCAL_DATETIME_SERIALIZER)
.serializationInclusion(JsonInclude.Include.NON_NULL);
}
It will configure two options by default:
Disable MapperFeature.DEFAULT_VIEW_INCLUSION
Disable DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES
According to the Jackson2ObjectMapperBuilder documentation, it will also register some modules if theyβre present on the classpath:
jackson-datatype-jdk8:support for other Java 8 types like Optional
jackson-datatype-jsr310:support for Java 8 Date and Time API types
jackson-datatype-joda:support for Joda-Time types
jackson-module-kotlin:support for Kotlin classes and data classes
Note: The advantage of this approach is that the Jackson2ObjectMapperBuilder offers a simple and intuitive way to build an ObjectMapper.
We can just define a bean with the type MappingJackson2HttpMessageConverter, and Spring Boot will automatically use it:
@Bean
// Convertor method
public MappingJackson2HttpMessageConverter() {
Jackson2ObjectMapperBuilder builder = new
Jackson2ObjectMapperBuilder().serializers(LOCAL_DATE_SERIALIZER)
.serializationInclusion(JsonInclude.Include.NON_NULL);
return new MappingJackson2HttpMessageConverter(builder.build());
}
Note: Make sure to check out our Spring Http Message Converters article to learn more.
Testing the Configuration
Lastly, in order to test our configuration, weβll use TestRestTemplate and serialize the objects as String. In this way, we can validate that our Coffee object is serialized without null values and with the custom date format:
@Test
public void whenGetCoffee_thenSerializedWithDateAndNonNull() {
String formattedDate =
DateTimeFormatter.ofPattern(CoffeeConstants.dateTimeFormat).format(FIXED_DATE);
// Our strings
String brand = "Lavazza";
String url = "/coffee?branf=" + brand;
String response = restTemplate.getForObject(url, String.class);
assertThat(response).isEqualTo("{"brand\":\"" + brand +
"\",\"date\":\"" + formatedDate + "\"}");
}
Conclusion: We took a look at several methods to configure the JSON serialization options when using Spring Boot. Here we saw two different approaches:configuring the default options or overriding the default configuration.
manikarora059
anikaseth98
singghakshay
adnanirshad158
sagar0719kumar
sumitgumber28
Java-Spring-Boot
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Stream In Java
Collections in Java
Multidimensional Arrays in Java
Singleton Class in Java
Set in Java
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n07 Feb, 2022"
},
{
"code": null,
"e": 268,
"s": 28,
"text": "When using JSON format, Spring Boot will use an ObjectMapper instance to serialize responses and deserialize requests. In this article, we will take a look at the most common ways to configure the serialization and deserialization options."
},
{
"code": null,
"e": 381,
"s": 268,
"text": "Let us do go through the default configuration. So by default, the Spring Boot configuration will be as follows:"
},
{
"code": null,
"e": 426,
"s": 381,
"text": "Disable MapperFeature.DEFAULT_VIEW_INCLUSION"
},
{
"code": null,
"e": 485,
"s": 426,
"text": "Disable DeserializationFeature. FAIL_ON_UNKNOWN_PROPERTIES"
},
{
"code": null,
"e": 541,
"s": 485,
"text": "Disable SerializationFeature. WRITE_DATES_AS_TIMESTAMPS"
},
{
"code": null,
"e": 601,
"s": 541,
"text": "Letβs start with a quicker example by implementing the same"
},
{
"code": null,
"e": 618,
"s": 601,
"text": "Implementation: "
},
{
"code": null,
"e": 676,
"s": 618,
"text": "The client sends a GET request to our/coffee?name=Lavazza"
},
{
"code": null,
"e": 723,
"s": 676,
"text": "The controller will return a new Coffee object"
},
{
"code": null,
"e": 803,
"s": 723,
"text": "Spring will use customization options by using String and LocalDateTime objects"
},
{
"code": null,
"e": 894,
"s": 803,
"text": "It is as follows, so primarily we need to create a class named Coffee which is as follows:"
},
{
"code": null,
"e": 1030,
"s": 894,
"text": "// Class\npublic class Coffee {\n\n // Getters and setters\n private String name;\n private String brand;\n private LocalDateTime date;\n}"
},
{
"code": null,
"e": 1118,
"s": 1030,
"text": "Now we will also be defining a simple REST controller to demonstrate the serialization:"
},
{
"code": null,
"e": 1373,
"s": 1118,
"text": "@GetMapping (\"/coffee\")\n\npublic Coffee getCoffee(\n @RequestParam(required = false) String brand,\n @RequiredParam(required = false) String name) {\n\n return new Coffee()\n .setBrand(brand)\n .setDate(FIXED_DATE)\n .setName(name);\n}"
},
{
"code": null,
"e": 1479,
"s": 1373,
"text": "By default, the response when calling GET http://localhost:8080/cofffee?brand=lavazza will be as follows:"
},
{
"code": null,
"e": 1562,
"s": 1479,
"text": "{\n \"name\": null,\n \"brand\": Lavazza\",\n \"date\": \"2020 - 11 - 16T10: 21: 35.974\"\n}"
},
{
"code": null,
"e": 1694,
"s": 1562,
"text": "Now We would like to exclude null values and to have a custom date format (dd-MM-yyy HH:mm). The final response will be as follows:"
},
{
"code": null,
"e": 1750,
"s": 1694,
"text": "{\n \"brand:\" \"Lavazza\",\n \"date\": \"04-11-20202 10:34\"\n}"
},
{
"code": null,
"e": 1906,
"s": 1750,
"text": "When using Spring Boot, we have the option to customize the default ObjectMapper or to override it. Weβll cover both of these options in the next sections."
},
{
"code": null,
"e": 2087,
"s": 1906,
"text": "Now let us roll to eccentric point in article by customizing the Default Object Mapper. Here. we will be discussing how to customize the default ObjectMapper that Spring Boot uses."
},
{
"code": null,
"e": 2136,
"s": 2087,
"text": "Application Properties and Custom Jackson Module"
},
{
"code": null,
"e": 2267,
"s": 2136,
"text": "The simplest way to configure the mapper is via application properties. The general structure of the configuration is as follows:"
},
{
"code": null,
"e": 2327,
"s": 2267,
"text": " spring.jackson.<category_name>.<feature_name>=true, false"
},
{
"code": null,
"e": 2424,
"s": 2327,
"text": "As an example, if we want to disable SerializationFeature. WRITE_DATES_AS_TIMESTAMPS, weβll add:"
},
{
"code": null,
"e": 2485,
"s": 2424,
"text": "spring.jackson.serialization.write-dates-as-timestamps=false"
},
{
"code": null,
"e": 2569,
"s": 2485,
"text": "Besides the mentioned feature categories, we can also configure property inclusion:"
},
{
"code": null,
"e": 2664,
"s": 2569,
"text": "spring.jackson.default-property-inclusion=always, non_null, non_absent, non_default, non_empty"
},
{
"code": null,
"e": 2915,
"s": 2664,
"text": "Configuring the environment variables in the simplest approach. The downside of this approach is that we canβt customize advanced options like having a custom date format for LocalDateTime. At this point, weβll obtain the result which is shown below:"
},
{
"code": null,
"e": 2977,
"s": 2915,
"text": "{\n \"brand\": \"Lavazza\",\n \"date\": \"2020-11-16T10:35:34.593\"\n}"
},
{
"code": null,
"e": 3076,
"s": 2977,
"text": "Now in order to achieve our goal, weβll register a new JavaTimeModule with our custom date format:"
},
{
"code": null,
"e": 3365,
"s": 3076,
"text": "@Configuration\n@PropertySource(\"classpath:coffee.properties\")\n\n// Class\npublic class CoffeeRegisterModuleConfig {\n\n @Bean\n\n public Module javaTimeModule() {\n\n JavaTimeModule module = new JavaTimeModule();\n module.addSerializer(LOCAL_DATETIME_SERIALIZER);\n\n return module;\n }\n}"
},
{
"code": null,
"e": 3403,
"s": 3365,
"text": "Jackson2ObjectMapperBuilderCustomizer"
},
{
"code": null,
"e": 3580,
"s": 3403,
"text": "The purpose of this functional interface is to allow us to create configuration beans. They will be applied to the default ObjectMapper created via Jackson2ObjectMapperBuilder."
},
{
"code": null,
"e": 3792,
"s": 3580,
"text": "@Bean\npublic Jackson2ObjectMapperBuilderCustomizer jsonCustomizer() {\n return builder ->\n builder.serializationInclusion(JsonInclude.Include.NON_NULL)\n .serializers(LOCAL_DATETIME_SERIALIZER);\n}"
},
{
"code": null,
"e": 4017,
"s": 3792,
"text": "The configuration beans are applied in a specific order, which we can control using the @Order annotations. This elegant approach is suitable if we want to configure the ObjectMapper from different configurations or modules."
},
{
"code": null,
"e": 4045,
"s": 4017,
"text": "Jackson2ObjectMapperBuilder"
},
{
"code": null,
"e": 4251,
"s": 4045,
"text": "Another clean approach is to define a Jackson2ObjectMapperBuilder bean. Actually, Spring Boot is using this builder by default when building the ObjectMapper and will automatically pick up the defined one:"
},
{
"code": null,
"e": 4481,
"s": 4251,
"text": "@Bean\npublic Jackson2ObjectMapperBuilder jackson2ObjectMapperBuilder() {\n return new\n Jackson2ObjectMapperBuilder().serializers(LOCAL_DATETIME_SERIALIZER)\n .serializationInclusion(JsonInclude.Include.NON_NULL);\n}"
},
{
"code": null,
"e": 4523,
"s": 4481,
"text": "It will configure two options by default:"
},
{
"code": null,
"e": 4568,
"s": 4523,
"text": "Disable MapperFeature.DEFAULT_VIEW_INCLUSION"
},
{
"code": null,
"e": 4626,
"s": 4568,
"text": "Disable DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES"
},
{
"code": null,
"e": 4758,
"s": 4626,
"text": "According to the Jackson2ObjectMapperBuilder documentation, it will also register some modules if theyβre present on the classpath:"
},
{
"code": null,
"e": 4825,
"s": 4758,
"text": "jackson-datatype-jdk8:support for other Java 8 types like Optional"
},
{
"code": null,
"e": 4892,
"s": 4825,
"text": "jackson-datatype-jsr310:support for Java 8 Date and Time API types"
},
{
"code": null,
"e": 4942,
"s": 4892,
"text": "jackson-datatype-joda:support for Joda-Time types"
},
{
"code": null,
"e": 5008,
"s": 4942,
"text": "jackson-module-kotlin:support for Kotlin classes and data classes"
},
{
"code": null,
"e": 5145,
"s": 5008,
"text": "Note: The advantage of this approach is that the Jackson2ObjectMapperBuilder offers a simple and intuitive way to build an ObjectMapper."
},
{
"code": null,
"e": 5265,
"s": 5145,
"text": "We can just define a bean with the type MappingJackson2HttpMessageConverter, and Spring Boot will automatically use it:"
},
{
"code": null,
"e": 5578,
"s": 5265,
"text": "@Bean\n\n// Convertor method\npublic MappingJackson2HttpMessageConverter() {\n\n Jackson2ObjectMapperBuilder builder = new\n Jackson2ObjectMapperBuilder().serializers(LOCAL_DATE_SERIALIZER)\n .serializationInclusion(JsonInclude.Include.NON_NULL);\n\n return new MappingJackson2HttpMessageConverter(builder.build());\n}"
},
{
"code": null,
"e": 5665,
"s": 5578,
"text": "Note: Make sure to check out our Spring Http Message Converters article to learn more."
},
{
"code": null,
"e": 5691,
"s": 5665,
"text": "Testing the Configuration"
},
{
"code": null,
"e": 5918,
"s": 5691,
"text": "Lastly, in order to test our configuration, weβll use TestRestTemplate and serialize the objects as String. In this way, we can validate that our Coffee object is serialized without null values and with the custom date format:"
},
{
"code": null,
"e": 6384,
"s": 5918,
"text": "@Test\n\npublic void whenGetCoffee_thenSerializedWithDateAndNonNull() {\n\n String formattedDate =\n DateTimeFormatter.ofPattern(CoffeeConstants.dateTimeFormat).format(FIXED_DATE);\n\n// Our strings\n String brand = \"Lavazza\";\n String url = \"/coffee?branf=\" + brand;\n String response = restTemplate.getForObject(url, String.class);\n\n assertThat(response).isEqualTo(\"{\"brand\\\":\\\"\" + brand +\n \"\\\",\\\"date\\\":\\\"\" + formatedDate + \"\\\"}\");\n}"
},
{
"code": null,
"e": 6608,
"s": 6384,
"text": "Conclusion: We took a look at several methods to configure the JSON serialization options when using Spring Boot. Here we saw two different approaches:configuring the default options or overriding the default configuration."
},
{
"code": null,
"e": 6622,
"s": 6608,
"text": "manikarora059"
},
{
"code": null,
"e": 6634,
"s": 6622,
"text": "anikaseth98"
},
{
"code": null,
"e": 6647,
"s": 6634,
"text": "singghakshay"
},
{
"code": null,
"e": 6662,
"s": 6647,
"text": "adnanirshad158"
},
{
"code": null,
"e": 6677,
"s": 6662,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 6691,
"s": 6677,
"text": "sumitgumber28"
},
{
"code": null,
"e": 6708,
"s": 6691,
"text": "Java-Spring-Boot"
},
{
"code": null,
"e": 6713,
"s": 6708,
"text": "Java"
},
{
"code": null,
"e": 6718,
"s": 6713,
"text": "Java"
},
{
"code": null,
"e": 6816,
"s": 6718,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6867,
"s": 6816,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 6898,
"s": 6867,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 6917,
"s": 6898,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 6947,
"s": 6917,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 6965,
"s": 6947,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 6980,
"s": 6965,
"text": "Stream In Java"
},
{
"code": null,
"e": 7000,
"s": 6980,
"text": "Collections in Java"
},
{
"code": null,
"e": 7032,
"s": 7000,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 7056,
"s": 7032,
"text": "Singleton Class in Java"
}
] |
Efficient program to print all prime factors of a given number
|
11 Apr, 2022
Given a number n, write an efficient function to print all prime factors of n. For example, if the input number is 12, then the output should be β2 2 3β. And if the input number is 315, then the output should be β3 3 5 7β.
First Approach:
Following are the steps to find all prime factors. 1) While n is divisible by 2, print 2 and divide n by 2. 2) After step 1, n must be odd. Now start a loop from i = 3 to the square root of n. While i divides n, print i, and divide n by i. After i fails to divide n, increment i by 2 and continue. 3) If n is a prime number and is greater than 2, then n will not become 1 by the above two steps. So print n if it is greater than 2.
C++
C
Java
Python
C#
PHP
Javascript
// C++ program to print all prime factors#include <bits/stdc++.h>using namespace std; // A function to print all prime// factors of a given number nvoid primeFactors(int n){ // Print the number of 2s that divide n while (n % 2 == 0) { cout << 2 << " "; n = n/2; } // n must be odd at this point. So we can skip // one element (Note i = i +2) for (int i = 3; i <= sqrt(n); i = i + 2) { // While i divides n, print i and divide n while (n % i == 0) { cout << i << " "; n = n/i; } } // This condition is to handle the case when n // is a prime number greater than 2 if (n > 2) cout << n << " ";} /* Driver code */int main(){ int n = 315; primeFactors(n); return 0;} // This is code is contributed by rathbhupendra
// Program to print all prime factors# include <stdio.h># include <math.h> // A function to print all prime factors of a given number nvoid primeFactors(int n){ // Print the number of 2s that divide n while (n%2 == 0) { printf("%d ", 2); n = n/2; } // n must be odd at this point. So we can skip // one element (Note i = i +2) for (int i = 3; i <= sqrt(n); i = i+2) { // While i divides n, print i and divide n while (n%i == 0) { printf("%d ", i); n = n/i; } } // This condition is to handle the case when n // is a prime number greater than 2 if (n > 2) printf ("%d ", n);} /* Driver program to test above function */int main(){ int n = 315; primeFactors(n); return 0;}
// Program to print all prime factorsimport java.io.*;import java.lang.Math; class GFG{ // A function to print all prime factors // of a given number n public static void primeFactors(int n) { // Print the number of 2s that divide n while (n%2==0) { System.out.print(2 + " "); n /= 2; } // n must be odd at this point. So we can // skip one element (Note i = i +2) for (int i = 3; i <= Math.sqrt(n); i+= 2) { // While i divides n, print i and divide n while (n%i == 0) { System.out.print(i + " "); n /= i; } } // This condition is to handle the case when // n is a prime number greater than 2 if (n > 2) System.out.print(n); } public static void main (String[] args) { int n = 315; primeFactors(n); }}
# Python program to print prime factors import math # A function to print all prime factors of# a given number ndef primeFactors(n): # Print the number of two's that divide n while n % 2 == 0: print 2, n = n / 2 # n must be odd at this point # so a skip of 2 ( i = i + 2) can be used for i in range(3,int(math.sqrt(n))+1,2): # while i divides n , print i and divide n while n % i== 0: print i, n = n / i # Condition if n is a prime # number greater than 2 if n > 2: print n # Driver Program to test above function n = 315primeFactors(n) # This code is contributed by Harshit Agrawal
// C# Program to print all prime factorsusing System; namespace prime{public class GFG{ // A function to print all prime // factors of a given number n public static void primeFactors(int n) { // Print the number of 2s that divide n while (n % 2 == 0) { Console.Write(2 + " "); n /= 2; } // n must be odd at this point. So we can // skip one element (Note i = i +2) for (int i = 3; i <= Math.Sqrt(n); i+= 2) { // While i divides n, print i and divide n while (n % i == 0) { Console.Write(i + " "); n /= i; } } // This condition is to handle the case whien // n is a prime number greater than 2 if (n > 2) Console.Write(n); } // Driver Code public static void Main() { int n = 315; primeFactors(n); } }} // This code is contributed by Sam007
<?php// PHP Efficient program to print all// prime factors of a given number // function to print all prime// factors of a given number nfunction primeFactors($n){ // Print the number of // 2s that divide n while($n % 2 == 0) { echo 2," "; $n = $n / 2; } // n must be odd at this // point. So we can skip // one element (Note i = i +2) for ($i = 3; $i <= sqrt($n); $i = $i + 2) { // While i divides n, // print i and divide n while ($n % $i == 0) { echo $i," "; $n = $n / $i; } } // This condition is to // handle the case when n // is a prime number greater // than 2 if ($n > 2) echo $n," ";} // Driver Code $n = 315; primeFactors($n); // This code is contributed by aj_36?>
<script> // JavaScript program to print all prime factors // A function to print all prime// factors of a given number nfunction primeFactors(n){ // Print the number of 2s that divide n while (n % 2 == 0) { document.write(2 + " "); n = Math.floor(n / 2); } // n must be odd at this point. // So we can skip one element // (Note i = i +2) for(let i = 3; i <= Math.floor(Math.sqrt(n)); i = i + 2) { // While i divides n, print i // and divide n while (n % i == 0) { document.write(i + " "); n = Math.floor(n / i); } } // This condition is to handle the // case when n is a prime number // greater than 2 if (n > 2) document.write(n + " ");} // Driver codelet n = 315; primeFactors(n); // This code is contributed by Surbhi Tyagi. </script>
Output:
3 3 5 7
Time Complexity: O(n^(1/2) log n)
Since outer loop runs for sqrt(n) times and for every loop we are dividing n by i which gives us logarithmic time complexity.
Auxiliary Space: O(1)
How does this work? The steps 1 and 2 take care of composite numbers and step 3 takes care of prime numbers. To prove that the complete algorithm works, we need to prove that steps 1 and 2 actually take care of composite numbers. This is clear that step 1 takes care of even numbers. And after step 1, all remaining prime factors must be odd (difference of two prime factors must be at least 2), this explains why i is incremented by 2.
Now the main part is, the loop runs till the square root of n not till n. To prove that this optimization works, let us consider the following property of composite numbers.
Every composite number has at least one prime factor less than or equal to the square root of itself. This property can be proved using a counter statement. Let a and b be two factors of n such that a*b = n. If both are greater than βn, then a.b > βn, * βn, which contradicts the expression βa * b = nβ.
In step 2 of the above algorithm, we run a loop and do the following in loop a) Find the least prime factor i (must be less than βn,) b) Remove all occurrences i from n by repeatedly dividing n by i. c) Repeat steps a and b for divided n and i = i + 2. The steps a and b are repeated till n becomes either 1 or a prime number.
Second Approach: This approach is similar to Sieve of Eratosthenes.
We can achieve O(log n) for all composite numbers by consecutive dividing of the given number by an integer starting from 2 representing current factor of that number. This approach works on the fact that all composite numbers have factors in pairs other than 1 or number itself like 6=3 x 2 and 9=3 x 3 whereas for prime numbers there is no such pair other than 1 or the number itself.
Therefore if we start dividing the number by the smallest possible prime number (2) then all of its multiples or composite numbers will automatically be removed before we actually reach that number.
Example: We can divide 12 by 2 two times and remove that factors from 12 to get 3 thus making sure that composite number 4 (multiple of 2) does not occur at any later point of time.
Similarly, if we have a big number that is not divisible by any value of c=2 to n-1 means it is prime like 13 (not divisible from 2 to 12).
C++14
C
Java
C#
Python3
Javascript
#include <bits/stdc++.h>using namespace std; void primeFactors(int n){ int c=2; while(n>1) { if(n%c==0){ cout<<c<<" "; n/=c; } else c++; }} /* Driver code */int main(){ int n = 315; primeFactors(n); return 0;}
#include <stdio.h> void primeFactors(int n){ int c = 2; while (n > 1) { if (n % c == 0) { printf("%d ", c); n /= c; } else c++; }} /* Driver code */int main(){ int n = 315; primeFactors(n); return 0;} // This code is contributed by Rohit Pradhan
import java.util.*;class GFG { public static void primeFactors(int n) { int c = 2; while (n > 1) { if (n % c == 0) { System.out.print(c + " "); n /= c; } else c++; } } /* Driver code */ public static void main(String[] args) { int n = 315; primeFactors(n); }} // This code is contributed by Taranpreet
using System;class GFG { static void primeFactors(int n) { int c = 2; while (n > 1) { if (n % c == 0) { Console.Write(c + " "); n /= c; } else c++; } } /* Driver code */ public static int Main() { int n = 315; primeFactors(n); return 0; }}// This code is contributed by Taranpreet
def primeFactors(n): c = 2 while(n > 1): if(n % c == 0): print(c, end=" ") n = n / c else: c = c + 1 # Driver coden = 315primeFactors(n) # This code is contributed by Taranpreet
<script>function primeFactors(n){ let c = 2; while(n > 1) { if(n % c == 0){ document.write(c + " "); n /= c; } else c++; }} /* Driver code */let n = 315;primeFactors(n); // This code is contributed by singhh3010.</script>
Time Complexity: This Approach is best for all composite numbers and achieves O(log n) but is O(n) otherwise.
Auxiliary Space: O(1)
Related Article : Prime Factorization using Sieve O(log n) for multiple queriesThanks to Vishwas Garg for suggesting the above algorithm. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
jit_t
NehaChoutapelly
rathbhupendra
sudhanshubhogal30299
surbhityagi15
chauhandeepakdc9
ajaykathwate13
prophet1999
singhh3010
sumitgumber28
rohit768
combionatrics
Prime Number
prime-factor
sieve
Yahoo
Dynamic Programming
Mathematical
Yahoo
Dynamic Programming
Mathematical
Prime Number
sieve
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Floyd Warshall Algorithm | DP-16
Find if there is a path between two vertices in an undirected graph
Matrix Chain Multiplication | DP-8
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Find minimum number of coins that make a given value
Set in C++ Standard Template Library (STL)
Write a program to print all permutations of a given string
C++ Data Types
Merge two sorted arrays
Operators in C / C++
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n11 Apr, 2022"
},
{
"code": null,
"e": 275,
"s": 52,
"text": "Given a number n, write an efficient function to print all prime factors of n. For example, if the input number is 12, then the output should be β2 2 3β. And if the input number is 315, then the output should be β3 3 5 7β."
},
{
"code": null,
"e": 291,
"s": 275,
"text": "First Approach:"
},
{
"code": null,
"e": 724,
"s": 291,
"text": "Following are the steps to find all prime factors. 1) While n is divisible by 2, print 2 and divide n by 2. 2) After step 1, n must be odd. Now start a loop from i = 3 to the square root of n. While i divides n, print i, and divide n by i. After i fails to divide n, increment i by 2 and continue. 3) If n is a prime number and is greater than 2, then n will not become 1 by the above two steps. So print n if it is greater than 2. "
},
{
"code": null,
"e": 728,
"s": 724,
"text": "C++"
},
{
"code": null,
"e": 730,
"s": 728,
"text": "C"
},
{
"code": null,
"e": 735,
"s": 730,
"text": "Java"
},
{
"code": null,
"e": 742,
"s": 735,
"text": "Python"
},
{
"code": null,
"e": 745,
"s": 742,
"text": "C#"
},
{
"code": null,
"e": 749,
"s": 745,
"text": "PHP"
},
{
"code": null,
"e": 760,
"s": 749,
"text": "Javascript"
},
{
"code": "// C++ program to print all prime factors#include <bits/stdc++.h>using namespace std; // A function to print all prime// factors of a given number nvoid primeFactors(int n){ // Print the number of 2s that divide n while (n % 2 == 0) { cout << 2 << \" \"; n = n/2; } // n must be odd at this point. So we can skip // one element (Note i = i +2) for (int i = 3; i <= sqrt(n); i = i + 2) { // While i divides n, print i and divide n while (n % i == 0) { cout << i << \" \"; n = n/i; } } // This condition is to handle the case when n // is a prime number greater than 2 if (n > 2) cout << n << \" \";} /* Driver code */int main(){ int n = 315; primeFactors(n); return 0;} // This is code is contributed by rathbhupendra",
"e": 1589,
"s": 760,
"text": null
},
{
"code": "// Program to print all prime factors# include <stdio.h># include <math.h> // A function to print all prime factors of a given number nvoid primeFactors(int n){ // Print the number of 2s that divide n while (n%2 == 0) { printf(\"%d \", 2); n = n/2; } // n must be odd at this point. So we can skip // one element (Note i = i +2) for (int i = 3; i <= sqrt(n); i = i+2) { // While i divides n, print i and divide n while (n%i == 0) { printf(\"%d \", i); n = n/i; } } // This condition is to handle the case when n // is a prime number greater than 2 if (n > 2) printf (\"%d \", n);} /* Driver program to test above function */int main(){ int n = 315; primeFactors(n); return 0;}",
"e": 2379,
"s": 1589,
"text": null
},
{
"code": "// Program to print all prime factorsimport java.io.*;import java.lang.Math; class GFG{ // A function to print all prime factors // of a given number n public static void primeFactors(int n) { // Print the number of 2s that divide n while (n%2==0) { System.out.print(2 + \" \"); n /= 2; } // n must be odd at this point. So we can // skip one element (Note i = i +2) for (int i = 3; i <= Math.sqrt(n); i+= 2) { // While i divides n, print i and divide n while (n%i == 0) { System.out.print(i + \" \"); n /= i; } } // This condition is to handle the case when // n is a prime number greater than 2 if (n > 2) System.out.print(n); } public static void main (String[] args) { int n = 315; primeFactors(n); }}",
"e": 3314,
"s": 2379,
"text": null
},
{
"code": "# Python program to print prime factors import math # A function to print all prime factors of# a given number ndef primeFactors(n): # Print the number of two's that divide n while n % 2 == 0: print 2, n = n / 2 # n must be odd at this point # so a skip of 2 ( i = i + 2) can be used for i in range(3,int(math.sqrt(n))+1,2): # while i divides n , print i and divide n while n % i== 0: print i, n = n / i # Condition if n is a prime # number greater than 2 if n > 2: print n # Driver Program to test above function n = 315primeFactors(n) # This code is contributed by Harshit Agrawal",
"e": 4022,
"s": 3314,
"text": null
},
{
"code": "// C# Program to print all prime factorsusing System; namespace prime{public class GFG{ // A function to print all prime // factors of a given number n public static void primeFactors(int n) { // Print the number of 2s that divide n while (n % 2 == 0) { Console.Write(2 + \" \"); n /= 2; } // n must be odd at this point. So we can // skip one element (Note i = i +2) for (int i = 3; i <= Math.Sqrt(n); i+= 2) { // While i divides n, print i and divide n while (n % i == 0) { Console.Write(i + \" \"); n /= i; } } // This condition is to handle the case whien // n is a prime number greater than 2 if (n > 2) Console.Write(n); } // Driver Code public static void Main() { int n = 315; primeFactors(n); } }} // This code is contributed by Sam007",
"e": 5023,
"s": 4022,
"text": null
},
{
"code": "<?php// PHP Efficient program to print all// prime factors of a given number // function to print all prime// factors of a given number nfunction primeFactors($n){ // Print the number of // 2s that divide n while($n % 2 == 0) { echo 2,\" \"; $n = $n / 2; } // n must be odd at this // point. So we can skip // one element (Note i = i +2) for ($i = 3; $i <= sqrt($n); $i = $i + 2) { // While i divides n, // print i and divide n while ($n % $i == 0) { echo $i,\" \"; $n = $n / $i; } } // This condition is to // handle the case when n // is a prime number greater // than 2 if ($n > 2) echo $n,\" \";} // Driver Code $n = 315; primeFactors($n); // This code is contributed by aj_36?>",
"e": 5870,
"s": 5023,
"text": null
},
{
"code": "<script> // JavaScript program to print all prime factors // A function to print all prime// factors of a given number nfunction primeFactors(n){ // Print the number of 2s that divide n while (n % 2 == 0) { document.write(2 + \" \"); n = Math.floor(n / 2); } // n must be odd at this point. // So we can skip one element // (Note i = i +2) for(let i = 3; i <= Math.floor(Math.sqrt(n)); i = i + 2) { // While i divides n, print i // and divide n while (n % i == 0) { document.write(i + \" \"); n = Math.floor(n / i); } } // This condition is to handle the // case when n is a prime number // greater than 2 if (n > 2) document.write(n + \" \");} // Driver codelet n = 315; primeFactors(n); // This code is contributed by Surbhi Tyagi. </script>",
"e": 6766,
"s": 5870,
"text": null
},
{
"code": null,
"e": 6775,
"s": 6766,
"text": "Output: "
},
{
"code": null,
"e": 6783,
"s": 6775,
"text": "3 3 5 7"
},
{
"code": null,
"e": 6817,
"s": 6783,
"text": "Time Complexity: O(n^(1/2) log n)"
},
{
"code": null,
"e": 6943,
"s": 6817,
"text": "Since outer loop runs for sqrt(n) times and for every loop we are dividing n by i which gives us logarithmic time complexity."
},
{
"code": null,
"e": 6965,
"s": 6943,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 7403,
"s": 6965,
"text": "How does this work? The steps 1 and 2 take care of composite numbers and step 3 takes care of prime numbers. To prove that the complete algorithm works, we need to prove that steps 1 and 2 actually take care of composite numbers. This is clear that step 1 takes care of even numbers. And after step 1, all remaining prime factors must be odd (difference of two prime factors must be at least 2), this explains why i is incremented by 2. "
},
{
"code": null,
"e": 7578,
"s": 7403,
"text": "Now the main part is, the loop runs till the square root of n not till n. To prove that this optimization works, let us consider the following property of composite numbers. "
},
{
"code": null,
"e": 7883,
"s": 7578,
"text": "Every composite number has at least one prime factor less than or equal to the square root of itself. This property can be proved using a counter statement. Let a and b be two factors of n such that a*b = n. If both are greater than βn, then a.b > βn, * βn, which contradicts the expression βa * b = nβ. "
},
{
"code": null,
"e": 8210,
"s": 7883,
"text": "In step 2 of the above algorithm, we run a loop and do the following in loop a) Find the least prime factor i (must be less than βn,) b) Remove all occurrences i from n by repeatedly dividing n by i. c) Repeat steps a and b for divided n and i = i + 2. The steps a and b are repeated till n becomes either 1 or a prime number."
},
{
"code": null,
"e": 8278,
"s": 8210,
"text": "Second Approach: This approach is similar to Sieve of Eratosthenes."
},
{
"code": null,
"e": 8665,
"s": 8278,
"text": "We can achieve O(log n) for all composite numbers by consecutive dividing of the given number by an integer starting from 2 representing current factor of that number. This approach works on the fact that all composite numbers have factors in pairs other than 1 or number itself like 6=3 x 2 and 9=3 x 3 whereas for prime numbers there is no such pair other than 1 or the number itself."
},
{
"code": null,
"e": 8864,
"s": 8665,
"text": "Therefore if we start dividing the number by the smallest possible prime number (2) then all of its multiples or composite numbers will automatically be removed before we actually reach that number."
},
{
"code": null,
"e": 9046,
"s": 8864,
"text": "Example: We can divide 12 by 2 two times and remove that factors from 12 to get 3 thus making sure that composite number 4 (multiple of 2) does not occur at any later point of time."
},
{
"code": null,
"e": 9186,
"s": 9046,
"text": "Similarly, if we have a big number that is not divisible by any value of c=2 to n-1 means it is prime like 13 (not divisible from 2 to 12)."
},
{
"code": null,
"e": 9192,
"s": 9186,
"text": "C++14"
},
{
"code": null,
"e": 9194,
"s": 9192,
"text": "C"
},
{
"code": null,
"e": 9199,
"s": 9194,
"text": "Java"
},
{
"code": null,
"e": 9202,
"s": 9199,
"text": "C#"
},
{
"code": null,
"e": 9210,
"s": 9202,
"text": "Python3"
},
{
"code": null,
"e": 9221,
"s": 9210,
"text": "Javascript"
},
{
"code": "#include <bits/stdc++.h>using namespace std; void primeFactors(int n){ int c=2; while(n>1) { if(n%c==0){ cout<<c<<\" \"; n/=c; } else c++; }} /* Driver code */int main(){ int n = 315; primeFactors(n); return 0;}",
"e": 9487,
"s": 9221,
"text": null
},
{
"code": "#include <stdio.h> void primeFactors(int n){ int c = 2; while (n > 1) { if (n % c == 0) { printf(\"%d \", c); n /= c; } else c++; }} /* Driver code */int main(){ int n = 315; primeFactors(n); return 0;} // This code is contributed by Rohit Pradhan",
"e": 9763,
"s": 9487,
"text": null
},
{
"code": "import java.util.*;class GFG { public static void primeFactors(int n) { int c = 2; while (n > 1) { if (n % c == 0) { System.out.print(c + \" \"); n /= c; } else c++; } } /* Driver code */ public static void main(String[] args) { int n = 315; primeFactors(n); }} // This code is contributed by Taranpreet",
"e": 10200,
"s": 9763,
"text": null
},
{
"code": "using System;class GFG { static void primeFactors(int n) { int c = 2; while (n > 1) { if (n % c == 0) { Console.Write(c + \" \"); n /= c; } else c++; } } /* Driver code */ public static int Main() { int n = 315; primeFactors(n); return 0; }}// This code is contributed by Taranpreet",
"e": 10622,
"s": 10200,
"text": null
},
{
"code": "def primeFactors(n): c = 2 while(n > 1): if(n % c == 0): print(c, end=\" \") n = n / c else: c = c + 1 # Driver coden = 315primeFactors(n) # This code is contributed by Taranpreet",
"e": 10855,
"s": 10622,
"text": null
},
{
"code": "<script>function primeFactors(n){ let c = 2; while(n > 1) { if(n % c == 0){ document.write(c + \" \"); n /= c; } else c++; }} /* Driver code */let n = 315;primeFactors(n); // This code is contributed by singhh3010.</script>",
"e": 11132,
"s": 10855,
"text": null
},
{
"code": null,
"e": 11242,
"s": 11132,
"text": "Time Complexity: This Approach is best for all composite numbers and achieves O(log n) but is O(n) otherwise."
},
{
"code": null,
"e": 11264,
"s": 11242,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 11527,
"s": 11264,
"text": "Related Article : Prime Factorization using Sieve O(log n) for multiple queriesThanks to Vishwas Garg for suggesting the above algorithm. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 11533,
"s": 11527,
"text": "jit_t"
},
{
"code": null,
"e": 11549,
"s": 11533,
"text": "NehaChoutapelly"
},
{
"code": null,
"e": 11563,
"s": 11549,
"text": "rathbhupendra"
},
{
"code": null,
"e": 11584,
"s": 11563,
"text": "sudhanshubhogal30299"
},
{
"code": null,
"e": 11598,
"s": 11584,
"text": "surbhityagi15"
},
{
"code": null,
"e": 11615,
"s": 11598,
"text": "chauhandeepakdc9"
},
{
"code": null,
"e": 11630,
"s": 11615,
"text": "ajaykathwate13"
},
{
"code": null,
"e": 11642,
"s": 11630,
"text": "prophet1999"
},
{
"code": null,
"e": 11653,
"s": 11642,
"text": "singhh3010"
},
{
"code": null,
"e": 11667,
"s": 11653,
"text": "sumitgumber28"
},
{
"code": null,
"e": 11676,
"s": 11667,
"text": "rohit768"
},
{
"code": null,
"e": 11690,
"s": 11676,
"text": "combionatrics"
},
{
"code": null,
"e": 11703,
"s": 11690,
"text": "Prime Number"
},
{
"code": null,
"e": 11716,
"s": 11703,
"text": "prime-factor"
},
{
"code": null,
"e": 11722,
"s": 11716,
"text": "sieve"
},
{
"code": null,
"e": 11728,
"s": 11722,
"text": "Yahoo"
},
{
"code": null,
"e": 11748,
"s": 11728,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 11761,
"s": 11748,
"text": "Mathematical"
},
{
"code": null,
"e": 11767,
"s": 11761,
"text": "Yahoo"
},
{
"code": null,
"e": 11787,
"s": 11767,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 11800,
"s": 11787,
"text": "Mathematical"
},
{
"code": null,
"e": 11813,
"s": 11800,
"text": "Prime Number"
},
{
"code": null,
"e": 11819,
"s": 11813,
"text": "sieve"
},
{
"code": null,
"e": 11917,
"s": 11819,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 11950,
"s": 11917,
"text": "Floyd Warshall Algorithm | DP-16"
},
{
"code": null,
"e": 12018,
"s": 11950,
"text": "Find if there is a path between two vertices in an undirected graph"
},
{
"code": null,
"e": 12053,
"s": 12018,
"text": "Matrix Chain Multiplication | DP-8"
},
{
"code": null,
"e": 12121,
"s": 12053,
"text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)"
},
{
"code": null,
"e": 12174,
"s": 12121,
"text": "Find minimum number of coins that make a given value"
},
{
"code": null,
"e": 12217,
"s": 12174,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 12277,
"s": 12217,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 12292,
"s": 12277,
"text": "C++ Data Types"
},
{
"code": null,
"e": 12316,
"s": 12292,
"text": "Merge two sorted arrays"
}
] |
Python β Convert excel serial date to datetime
|
14 Sep, 2021
This article will discuss the conversion of an excel serial date to DateTime in Python.
The Excel βserial dateβ format is actually the number of days since 1900-01-00 i.e., January 1st, 1900. For example, the excel serial date number 43831 represents January 1st, 2020, and after converting 43831 to a DateTime becomes 2020-01-01.
By using xlrd.xldate_as_datetime() function this can be achieved. The xlrd.xldate_as_datetime() function is used to convert excel date/time number to datetime.datetime object.
Syntax: xldate_as_datetime (xldate, datemode)
Parameters: This function accepts two parameters that are illustrated below:
xldate: This is the specified excel date that will converted into datetime.
datemode: This is the specified datemode in which conversion will be performed.
Return values: This function returns the datetime.datetime object.
First, call xlrd.xldate_as_datetime(date, 0) function to convert the specified Excel date to a datetime.datetime object. Then, call datetime.datetime.date() function on the returned datetime.datetime object to return the date as a datetime.date object. Lastly, call datetime.date.isoformat() function to convert the returned datetime.date object to a ISO format date string.
Letβs see some examples to illustrate the above algorithm:
Example: Python program to convert excel serial date to string date
Python3
# Python3 code to illustrate the conversion# of excel serial date to datetime # Importing xlrd moduleimport xlrd # Initializing an excel serial datexl_date = 43831 # Calling the xldate_as_datetime() function to# convert the specified excel serial date into# datetime.datetime objectdatetime_date = xlrd.xldate_as_datetime(xl_date, 0) # Calling the datetime_date.date() function to convert# the above returned datetime.datetime object into# datetime.date objectdate_object = datetime_date.date() # Calling the isoformat() function to convert the# above returned datetime.date object into the# ISO format date stringstring_date = date_object.isoformat() # Getting the converted date string as outputprint(string_date) # Getting the type of returned date formatprint(type(string_date))
Output:
2020-01-01
<class 'str'>
Example 2: Python program to convert excel serial number to DateTime
Python3
# Python3 code to illustrate the conversion# of excel serial date to datetime # Importing xlrd moduleimport xlrd # Initializing an excel serial datexl_date = 43831 # Calling the xldate_as_datetime() function to# convert the specified excel serial date into# datetime.datetime objectdatetime_date = xlrd.xldate_as_datetime(xl_date, 0) # Calling the datetime_date.date() function to convert# the above returned datetime.datetime object into# datetime.date objectdate_object = datetime_date.date() # Getting the converted date date as outputprint(date_object) # Getting the type of returned date formatprint(type(date_object))
Output:
2020-01-01
<class 'datetime.date'>
Picked
Python-datetime
Python-excel
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": "\n14 Sep, 2021"
},
{
"code": null,
"e": 117,
"s": 28,
"text": "This article will discuss the conversion of an excel serial date to DateTime in Python. "
},
{
"code": null,
"e": 360,
"s": 117,
"text": "The Excel βserial dateβ format is actually the number of days since 1900-01-00 i.e., January 1st, 1900. For example, the excel serial date number 43831 represents January 1st, 2020, and after converting 43831 to a DateTime becomes 2020-01-01."
},
{
"code": null,
"e": 536,
"s": 360,
"text": "By using xlrd.xldate_as_datetime() function this can be achieved. The xlrd.xldate_as_datetime() function is used to convert excel date/time number to datetime.datetime object."
},
{
"code": null,
"e": 582,
"s": 536,
"text": "Syntax: xldate_as_datetime (xldate, datemode)"
},
{
"code": null,
"e": 659,
"s": 582,
"text": "Parameters: This function accepts two parameters that are illustrated below:"
},
{
"code": null,
"e": 735,
"s": 659,
"text": "xldate: This is the specified excel date that will converted into datetime."
},
{
"code": null,
"e": 815,
"s": 735,
"text": "datemode: This is the specified datemode in which conversion will be performed."
},
{
"code": null,
"e": 882,
"s": 815,
"text": "Return values: This function returns the datetime.datetime object."
},
{
"code": null,
"e": 1257,
"s": 882,
"text": "First, call xlrd.xldate_as_datetime(date, 0) function to convert the specified Excel date to a datetime.datetime object. Then, call datetime.datetime.date() function on the returned datetime.datetime object to return the date as a datetime.date object. Lastly, call datetime.date.isoformat() function to convert the returned datetime.date object to a ISO format date string."
},
{
"code": null,
"e": 1316,
"s": 1257,
"text": "Letβs see some examples to illustrate the above algorithm:"
},
{
"code": null,
"e": 1384,
"s": 1316,
"text": "Example: Python program to convert excel serial date to string date"
},
{
"code": null,
"e": 1392,
"s": 1384,
"text": "Python3"
},
{
"code": "# Python3 code to illustrate the conversion# of excel serial date to datetime # Importing xlrd moduleimport xlrd # Initializing an excel serial datexl_date = 43831 # Calling the xldate_as_datetime() function to# convert the specified excel serial date into# datetime.datetime objectdatetime_date = xlrd.xldate_as_datetime(xl_date, 0) # Calling the datetime_date.date() function to convert# the above returned datetime.datetime object into# datetime.date objectdate_object = datetime_date.date() # Calling the isoformat() function to convert the# above returned datetime.date object into the# ISO format date stringstring_date = date_object.isoformat() # Getting the converted date string as outputprint(string_date) # Getting the type of returned date formatprint(type(string_date))",
"e": 2182,
"s": 1392,
"text": null
},
{
"code": null,
"e": 2190,
"s": 2182,
"text": "Output:"
},
{
"code": null,
"e": 2215,
"s": 2190,
"text": "2020-01-01\n<class 'str'>"
},
{
"code": null,
"e": 2284,
"s": 2215,
"text": "Example 2: Python program to convert excel serial number to DateTime"
},
{
"code": null,
"e": 2292,
"s": 2284,
"text": "Python3"
},
{
"code": "# Python3 code to illustrate the conversion# of excel serial date to datetime # Importing xlrd moduleimport xlrd # Initializing an excel serial datexl_date = 43831 # Calling the xldate_as_datetime() function to# convert the specified excel serial date into# datetime.datetime objectdatetime_date = xlrd.xldate_as_datetime(xl_date, 0) # Calling the datetime_date.date() function to convert# the above returned datetime.datetime object into# datetime.date objectdate_object = datetime_date.date() # Getting the converted date date as outputprint(date_object) # Getting the type of returned date formatprint(type(date_object))",
"e": 2922,
"s": 2292,
"text": null
},
{
"code": null,
"e": 2930,
"s": 2922,
"text": "Output:"
},
{
"code": null,
"e": 2965,
"s": 2930,
"text": "2020-01-01\n<class 'datetime.date'>"
},
{
"code": null,
"e": 2972,
"s": 2965,
"text": "Picked"
},
{
"code": null,
"e": 2988,
"s": 2972,
"text": "Python-datetime"
},
{
"code": null,
"e": 3001,
"s": 2988,
"text": "Python-excel"
},
{
"code": null,
"e": 3008,
"s": 3001,
"text": "Python"
},
{
"code": null,
"e": 3106,
"s": 3008,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3138,
"s": 3106,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3165,
"s": 3138,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3186,
"s": 3165,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 3209,
"s": 3186,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 3240,
"s": 3209,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 3296,
"s": 3240,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 3338,
"s": 3296,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 3380,
"s": 3338,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 3419,
"s": 3380,
"text": "Python | Get unique values from a list"
}
] |
Systematic Sampling in Pandas
|
13 Sep, 2021
Sampling is the method where one can take subset (Sample) from the given data and will investigate on the sample without investigating each individual thing of data. For instance, suppose in a College, someone wants to check the average height of Students who are Studying in the college. One way is to Collect data of all student and will calculate that but this task is very time-consuming. Thus, sampling is used. So, the solution is that during the Recess, randomly choose Students from Canteen and measure their height and will calculate the average height from that Subset of Studentβs.
Types Of Sampling :
Sampling
Systematic Sampling is defined as the type of Probability Sampling where a researcher can research on a targeted data from large set of data. Targeted data is chosen by selecting random starting point and from that after certain interval next element is chosen for sample. In this a small subset (sample) is extracted from large data.
Suppose that size of Data is D and N will be the Size of Sample that we want to Select. So according to Systematic Sampling :
Interval = (D/N)
Suppose (D/N) = J
So when we choose first random element E from Data , the next element for Sample would be (E+J)
Example : Total Size of Data = 50 (1 to 50)
We want elements in Sample = 5
Interval = 50/5 = 10 .
It means in a sample we want gapping of 10 elements Systematically.
Suppose i randomly choose element first Sample Element = 5
So next would be 5+10 = 15
15+10= 25
25+ 10 =35
35+10 = 45
So,
Sample = { 5,15,25,35,45 }
Diagrammatically,
Approach:
Take Data.
Extract Systematic Sample from large Data.
Print the Average of Sample Data.
Program:
Python3
# Import in order to use inbuilt functionsimport numpy as npimport pandas as pd # Define total number of studentsnumber_of_students = 15 # Create data dictionarydata = {'Id': np.arange(1, number_of_students+1).tolist(), 'height': [159, 171, 158, 162, 162, 177, 160, 175, 168, 171, 178, 178, 173, 177, 164]} # Transform dictionary into a data framedf = pd.DataFrame(data) display(df) # Define systematic sampling functiondef systematic_sampling(df, step): indexes = np.arange(0, len(df), step=step) systematic_sample = df.iloc[indexes] return systematic_sample # Obtain a systematic sample and save it in a new variablesystematic_sample = systematic_sampling(df, 3) # View sampled data framedisplay(systematic_sample)
Output:
Example: Print Average of Sample Data
Python3
# Import in order to use inbuilt functionsimport numpy as npimport pandas as pd # Define total number of studentsnumber_of_students = 15 # Create data dictionarydata = {'Id': np.arange(1, number_of_students+1).tolist(), 'height': [159, 171, 158, 162, 162, 177, 160, 175, 168, 171, 178, 178, 173, 177, 164]} # Transform dictionary into a data framedf = pd.DataFrame(data) # Define systematic sampling functiondef systematic_sampling(df, step): indexes = np.arange(0, len(df), step=step) systematic_sample = df.iloc[indexes] return systematic_sample # Obtain a systematic sample and save it in a new variablesystematic_sample = systematic_sampling(df, 3) # View sampled data framedisplay(systematic_sample) # Empty Print Statement for new lineprint() # Save the sample data in a separate variablesystematic_data = round(systematic_sample['height'].mean())print("Average Height in cm: ", systematic_data)
Output:
Systematic Sampling is of three types as depicted below :
Types of Systematic Sampling
In systematic random Sampling, random starting point is chosen and after that from that random starting point systematic sampling is applied.
Approach:
Get data
Choose a random starting point
Apply systematic approach to the data
Perform operations as intended
Example:
Python3
# Import in order to use inbuilt functionsimport numpy as npimport pandas as pdimport random # Define total number of housenumber_of_house = 30 # Create data dictionarydata = {'house_number': [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], 'number_of_children': [2, 2, 1, 3, 2, 1, 4, 1, 3, 5, 4, 3, 5, 3, 2, 1, 2, 3, 4, 5, 3, 4, 5, 2, 2, 2, 2, 3, 2, 1]} # Transform dictionary into a data framedf = pd.DataFrame(data) # Defining Size of Systematic Samplesize_of_systematic_sample = 6 # Defining Interval(gap) in order to get required data.interval = (number_of_house // size_of_systematic_sample) # Choosing Random Numberrandom_number = random.randint(1, 30) # Define systematic sampling functiondef systematic_sampling(df, step): indexes = np.arange(random_number, len(df), step=step) systematic_sample = df.iloc[indexes] return systematic_sample # Obtain a systematic sample and save it in a new variablesystematic_sample = systematic_sampling(df, interval) # View sampled data framedisplay(systematic_sample) # Empty Print Statement for new lineprint() # Save the sample data in a separate variablesystematic_data = round(systematic_sample['number_of_children'].mean()) # Printing Average Number of Childrenprint("Average Number Of Childrens in Locality: ", systematic_data)
Output:
Linear Systematic Sampling is a type of systematic sampling where the sample are selected using linear approach. Linear approach in the sense that after particular interval the sample is selected from the large data and after that operations are performed on the Selected Sample.
The elements are chosen between the range starting_random_number to last_element -1.
Approach:
Get data
Select data from the dataset after a particular interval
Perform operations as intended
Example:
Python3
# Import in order to use inbuilt functionsimport numpy as npimport pandas as pdimport random # Define total number of boxesnumber_of_boxes = 30 # Create data dictionarydata = {'Box_Number': [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], 'Defective_Bulbs': [2, 2, 1, 0, 2, 1, 0, 1, 3, 5, 4, 3, 5, 3, 0, 1, 2, 0, 4, 5, 3, 4, 5, 2, 0, 3, 2, 0, 5, 4]} # Transform dictionary into a data framedf = pd.DataFrame(data) # Size of Systematic Samplesize_systematic_sample = 5 # Interval (Gap) takeninterval = (number_of_boxes // size_systematic_sample) # Choosing Random Starting Pointrandom_number = random.randint(1, 30) # Define systematic sampling functiondef systematic_sampling(df, step): indexes = np.arange(random_number, len(df)-1, step=step) systematic_sample = df.iloc[indexes] return systematic_sample # Obtain a systematic sample and save it in a new variablesystematic_sample = systematic_sampling(df, interval) # View sampled data framedisplay(systematic_sample) # Empty Print Statement for new lineprint() # Save the sample data in a separate variablesystematic_data = round(systematic_sample['Defective_Bulbs'].mean()) # Printing Average Number of Defective Bulbsprint("Average Number Of Defective Bulbs: ", systematic_data)
Output:
In Circular Systematic Sampling, a sample again starts from the same point after ending. Basically, while selecting samples systematically and when ending element is reached, once again the selecting of sample will start from the beginning until all the elements of sample are selected. It means operations are performed on all the data which is selected using Circular Systematic Sampling.
Approach:
Get data
Select samples systematically
Once end is reached, restart
Perform operations as intended
Program:
Python3
# Import in order to use inbuilt functionsimport numpy as npimport pandas as pdimport random # Define total number of housenumber_of_house = 30 # Create data dictionarydata = {'house_number': [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], 'number_of_Adults': [2, 2, 5, 3, 2, 8, 4, 7, 8, 5, 4, 9, 5, 4, 2, 3, 2, 3, 4, 5, 6, 4, 5, 4, 2, 6, 2, 3, 2, 2]} # Transform dictionary into a data framedf = pd.DataFrame(data) # Defining Size of Systematic Samplesize_of_systematic_sample = 6 # Defining Interval(gap) in order to get required data.interval = (number_of_house // size_of_systematic_sample) # Define systematic sampling functiondef systematic_sampling(df, step): indexes = np.arange(0, len(df), step=step) systematic_sample = df.iloc[indexes] return systematic_sample # Obtain a systematic sample and save it in a new variablesystematic_sample = systematic_sampling(df, interval) # View sampled data framedisplay(systematic_sample) # Empty Print Statement for new lineprint() # Save the sample data in a separate variablesystematic_data = round(systematic_sample['number_of_Adults'].mean()) # Printing Average Number of Childrenprint("Average Number Of Adults in Locality: ", systematic_data)
Output:
sagartomar9927
sumitgumber28
Picked
Python-pandas
Technical Scripter 2020
Python
Technical Scripter
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": 54,
"s": 26,
"text": "\n13 Sep, 2021"
},
{
"code": null,
"e": 647,
"s": 54,
"text": "Sampling is the method where one can take subset (Sample) from the given data and will investigate on the sample without investigating each individual thing of data. For instance, suppose in a College, someone wants to check the average height of Students who are Studying in the college. One way is to Collect data of all student and will calculate that but this task is very time-consuming. Thus, sampling is used. So, the solution is that during the Recess, randomly choose Students from Canteen and measure their height and will calculate the average height from that Subset of Studentβs."
},
{
"code": null,
"e": 667,
"s": 647,
"text": "Types Of Sampling :"
},
{
"code": null,
"e": 676,
"s": 667,
"text": "Sampling"
},
{
"code": null,
"e": 1011,
"s": 676,
"text": "Systematic Sampling is defined as the type of Probability Sampling where a researcher can research on a targeted data from large set of data. Targeted data is chosen by selecting random starting point and from that after certain interval next element is chosen for sample. In this a small subset (sample) is extracted from large data."
},
{
"code": null,
"e": 1137,
"s": 1011,
"text": "Suppose that size of Data is D and N will be the Size of Sample that we want to Select. So according to Systematic Sampling :"
},
{
"code": null,
"e": 1154,
"s": 1137,
"text": "Interval = (D/N)"
},
{
"code": null,
"e": 1172,
"s": 1154,
"text": "Suppose (D/N) = J"
},
{
"code": null,
"e": 1268,
"s": 1172,
"text": "So when we choose first random element E from Data , the next element for Sample would be (E+J)"
},
{
"code": null,
"e": 1313,
"s": 1268,
"text": "Example : Total Size of Data = 50 (1 to 50)"
},
{
"code": null,
"e": 1355,
"s": 1313,
"text": " We want elements in Sample = 5"
},
{
"code": null,
"e": 1388,
"s": 1355,
"text": " Interval = 50/5 = 10 ."
},
{
"code": null,
"e": 1456,
"s": 1388,
"text": "It means in a sample we want gapping of 10 elements Systematically."
},
{
"code": null,
"e": 1516,
"s": 1456,
"text": "Suppose i randomly choose element first Sample Element = 5"
},
{
"code": null,
"e": 1543,
"s": 1516,
"text": "So next would be 5+10 = 15"
},
{
"code": null,
"e": 1570,
"s": 1543,
"text": " 15+10= 25"
},
{
"code": null,
"e": 1598,
"s": 1570,
"text": " 25+ 10 =35"
},
{
"code": null,
"e": 1627,
"s": 1598,
"text": " 35+10 = 45"
},
{
"code": null,
"e": 1632,
"s": 1627,
"text": "So, "
},
{
"code": null,
"e": 1659,
"s": 1632,
"text": "Sample = { 5,15,25,35,45 }"
},
{
"code": null,
"e": 1678,
"s": 1659,
"text": "Diagrammatically, "
},
{
"code": null,
"e": 1688,
"s": 1678,
"text": "Approach:"
},
{
"code": null,
"e": 1699,
"s": 1688,
"text": "Take Data."
},
{
"code": null,
"e": 1742,
"s": 1699,
"text": "Extract Systematic Sample from large Data."
},
{
"code": null,
"e": 1776,
"s": 1742,
"text": "Print the Average of Sample Data."
},
{
"code": null,
"e": 1786,
"s": 1776,
"text": "Program: "
},
{
"code": null,
"e": 1794,
"s": 1786,
"text": "Python3"
},
{
"code": "# Import in order to use inbuilt functionsimport numpy as npimport pandas as pd # Define total number of studentsnumber_of_students = 15 # Create data dictionarydata = {'Id': np.arange(1, number_of_students+1).tolist(), 'height': [159, 171, 158, 162, 162, 177, 160, 175, 168, 171, 178, 178, 173, 177, 164]} # Transform dictionary into a data framedf = pd.DataFrame(data) display(df) # Define systematic sampling functiondef systematic_sampling(df, step): indexes = np.arange(0, len(df), step=step) systematic_sample = df.iloc[indexes] return systematic_sample # Obtain a systematic sample and save it in a new variablesystematic_sample = systematic_sampling(df, 3) # View sampled data framedisplay(systematic_sample)",
"e": 2547,
"s": 1794,
"text": null
},
{
"code": null,
"e": 2555,
"s": 2547,
"text": "Output:"
},
{
"code": null,
"e": 2593,
"s": 2555,
"text": "Example: Print Average of Sample Data"
},
{
"code": null,
"e": 2601,
"s": 2593,
"text": "Python3"
},
{
"code": "# Import in order to use inbuilt functionsimport numpy as npimport pandas as pd # Define total number of studentsnumber_of_students = 15 # Create data dictionarydata = {'Id': np.arange(1, number_of_students+1).tolist(), 'height': [159, 171, 158, 162, 162, 177, 160, 175, 168, 171, 178, 178, 173, 177, 164]} # Transform dictionary into a data framedf = pd.DataFrame(data) # Define systematic sampling functiondef systematic_sampling(df, step): indexes = np.arange(0, len(df), step=step) systematic_sample = df.iloc[indexes] return systematic_sample # Obtain a systematic sample and save it in a new variablesystematic_sample = systematic_sampling(df, 3) # View sampled data framedisplay(systematic_sample) # Empty Print Statement for new lineprint() # Save the sample data in a separate variablesystematic_data = round(systematic_sample['height'].mean())print(\"Average Height in cm: \", systematic_data)",
"e": 3540,
"s": 2601,
"text": null
},
{
"code": null,
"e": 3548,
"s": 3540,
"text": "Output:"
},
{
"code": null,
"e": 3606,
"s": 3548,
"text": "Systematic Sampling is of three types as depicted below :"
},
{
"code": null,
"e": 3635,
"s": 3606,
"text": "Types of Systematic Sampling"
},
{
"code": null,
"e": 3777,
"s": 3635,
"text": "In systematic random Sampling, random starting point is chosen and after that from that random starting point systematic sampling is applied."
},
{
"code": null,
"e": 3787,
"s": 3777,
"text": "Approach:"
},
{
"code": null,
"e": 3796,
"s": 3787,
"text": "Get data"
},
{
"code": null,
"e": 3827,
"s": 3796,
"text": "Choose a random starting point"
},
{
"code": null,
"e": 3865,
"s": 3827,
"text": "Apply systematic approach to the data"
},
{
"code": null,
"e": 3896,
"s": 3865,
"text": "Perform operations as intended"
},
{
"code": null,
"e": 3906,
"s": 3896,
"text": "Example: "
},
{
"code": null,
"e": 3914,
"s": 3906,
"text": "Python3"
},
{
"code": "# Import in order to use inbuilt functionsimport numpy as npimport pandas as pdimport random # Define total number of housenumber_of_house = 30 # Create data dictionarydata = {'house_number': [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], 'number_of_children': [2, 2, 1, 3, 2, 1, 4, 1, 3, 5, 4, 3, 5, 3, 2, 1, 2, 3, 4, 5, 3, 4, 5, 2, 2, 2, 2, 3, 2, 1]} # Transform dictionary into a data framedf = pd.DataFrame(data) # Defining Size of Systematic Samplesize_of_systematic_sample = 6 # Defining Interval(gap) in order to get required data.interval = (number_of_house // size_of_systematic_sample) # Choosing Random Numberrandom_number = random.randint(1, 30) # Define systematic sampling functiondef systematic_sampling(df, step): indexes = np.arange(random_number, len(df), step=step) systematic_sample = df.iloc[indexes] return systematic_sample # Obtain a systematic sample and save it in a new variablesystematic_sample = systematic_sampling(df, interval) # View sampled data framedisplay(systematic_sample) # Empty Print Statement for new lineprint() # Save the sample data in a separate variablesystematic_data = round(systematic_sample['number_of_children'].mean()) # Printing Average Number of Childrenprint(\"Average Number Of Childrens in Locality: \", systematic_data)",
"e": 5383,
"s": 3914,
"text": null
},
{
"code": null,
"e": 5391,
"s": 5383,
"text": "Output:"
},
{
"code": null,
"e": 5671,
"s": 5391,
"text": "Linear Systematic Sampling is a type of systematic sampling where the sample are selected using linear approach. Linear approach in the sense that after particular interval the sample is selected from the large data and after that operations are performed on the Selected Sample."
},
{
"code": null,
"e": 5756,
"s": 5671,
"text": "The elements are chosen between the range starting_random_number to last_element -1."
},
{
"code": null,
"e": 5766,
"s": 5756,
"text": "Approach:"
},
{
"code": null,
"e": 5775,
"s": 5766,
"text": "Get data"
},
{
"code": null,
"e": 5832,
"s": 5775,
"text": "Select data from the dataset after a particular interval"
},
{
"code": null,
"e": 5863,
"s": 5832,
"text": "Perform operations as intended"
},
{
"code": null,
"e": 5872,
"s": 5863,
"text": "Example:"
},
{
"code": null,
"e": 5880,
"s": 5872,
"text": "Python3"
},
{
"code": "# Import in order to use inbuilt functionsimport numpy as npimport pandas as pdimport random # Define total number of boxesnumber_of_boxes = 30 # Create data dictionarydata = {'Box_Number': [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], 'Defective_Bulbs': [2, 2, 1, 0, 2, 1, 0, 1, 3, 5, 4, 3, 5, 3, 0, 1, 2, 0, 4, 5, 3, 4, 5, 2, 0, 3, 2, 0, 5, 4]} # Transform dictionary into a data framedf = pd.DataFrame(data) # Size of Systematic Samplesize_systematic_sample = 5 # Interval (Gap) takeninterval = (number_of_boxes // size_systematic_sample) # Choosing Random Starting Pointrandom_number = random.randint(1, 30) # Define systematic sampling functiondef systematic_sampling(df, step): indexes = np.arange(random_number, len(df)-1, step=step) systematic_sample = df.iloc[indexes] return systematic_sample # Obtain a systematic sample and save it in a new variablesystematic_sample = systematic_sampling(df, interval) # View sampled data framedisplay(systematic_sample) # Empty Print Statement for new lineprint() # Save the sample data in a separate variablesystematic_data = round(systematic_sample['Defective_Bulbs'].mean()) # Printing Average Number of Defective Bulbsprint(\"Average Number Of Defective Bulbs: \", systematic_data)",
"e": 7304,
"s": 5880,
"text": null
},
{
"code": null,
"e": 7312,
"s": 7304,
"text": "Output:"
},
{
"code": null,
"e": 7703,
"s": 7312,
"text": "In Circular Systematic Sampling, a sample again starts from the same point after ending. Basically, while selecting samples systematically and when ending element is reached, once again the selecting of sample will start from the beginning until all the elements of sample are selected. It means operations are performed on all the data which is selected using Circular Systematic Sampling."
},
{
"code": null,
"e": 7713,
"s": 7703,
"text": "Approach:"
},
{
"code": null,
"e": 7722,
"s": 7713,
"text": "Get data"
},
{
"code": null,
"e": 7752,
"s": 7722,
"text": "Select samples systematically"
},
{
"code": null,
"e": 7781,
"s": 7752,
"text": "Once end is reached, restart"
},
{
"code": null,
"e": 7812,
"s": 7781,
"text": "Perform operations as intended"
},
{
"code": null,
"e": 7821,
"s": 7812,
"text": "Program:"
},
{
"code": null,
"e": 7829,
"s": 7821,
"text": "Python3"
},
{
"code": "# Import in order to use inbuilt functionsimport numpy as npimport pandas as pdimport random # Define total number of housenumber_of_house = 30 # Create data dictionarydata = {'house_number': [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], 'number_of_Adults': [2, 2, 5, 3, 2, 8, 4, 7, 8, 5, 4, 9, 5, 4, 2, 3, 2, 3, 4, 5, 6, 4, 5, 4, 2, 6, 2, 3, 2, 2]} # Transform dictionary into a data framedf = pd.DataFrame(data) # Defining Size of Systematic Samplesize_of_systematic_sample = 6 # Defining Interval(gap) in order to get required data.interval = (number_of_house // size_of_systematic_sample) # Define systematic sampling functiondef systematic_sampling(df, step): indexes = np.arange(0, len(df), step=step) systematic_sample = df.iloc[indexes] return systematic_sample # Obtain a systematic sample and save it in a new variablesystematic_sample = systematic_sampling(df, interval) # View sampled data framedisplay(systematic_sample) # Empty Print Statement for new lineprint() # Save the sample data in a separate variablesystematic_data = round(systematic_sample['number_of_Adults'].mean()) # Printing Average Number of Childrenprint(\"Average Number Of Adults in Locality: \", systematic_data)",
"e": 9214,
"s": 7829,
"text": null
},
{
"code": null,
"e": 9222,
"s": 9214,
"text": "Output:"
},
{
"code": null,
"e": 9237,
"s": 9222,
"text": "sagartomar9927"
},
{
"code": null,
"e": 9251,
"s": 9237,
"text": "sumitgumber28"
},
{
"code": null,
"e": 9258,
"s": 9251,
"text": "Picked"
},
{
"code": null,
"e": 9272,
"s": 9258,
"text": "Python-pandas"
},
{
"code": null,
"e": 9296,
"s": 9272,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 9303,
"s": 9296,
"text": "Python"
},
{
"code": null,
"e": 9322,
"s": 9303,
"text": "Technical Scripter"
},
{
"code": null,
"e": 9420,
"s": 9322,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 9452,
"s": 9420,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 9479,
"s": 9452,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 9500,
"s": 9479,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 9523,
"s": 9500,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 9579,
"s": 9523,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 9610,
"s": 9579,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 9652,
"s": 9610,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 9694,
"s": 9652,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 9733,
"s": 9694,
"text": "Python | Get unique values from a list"
}
] |
Python VLC MediaPlayer β Getting Media
|
11 Apr, 2022
In this article we will see how we can get media of the MediaPlayer object in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. MediaPlayer object is the basic object in vlc module for playing the video. We can create a MediaPlayer object with the help of MediaPlayer method. Media can be video or even audio that is supported by vlc, it can be set with the help of set_media method.
In order to do this we will use get_media method with the MediaPlayer object
Syntax : media_player.get_media()
Argument : It takes no argument
Return : It returns Media object
Below is the implementation
Python3
# importing vlc moduleimport vlc # importing time moduleimport time # creating vlc media player objectmedia_player = vlc.MediaPlayer() # media objectmedia = vlc.Media("death_note.mkv") # setting media to the media playermedia_player.set_media(media) # start playing videomedia_player.play() # wait so the video can be played for 5 seconds# irrespective for length of videotime.sleep(5) # getting mediavalue = media_player.get_media() # printing mediaprint("Media : ")print(value)
Output :
Media :
vlc.Media object at 0x00000254E3CE3408
Another example Below is the implementation
Python3
# importing vlc moduleimport vlc # importing time moduleimport time # creating vlc media player objectmedia_player = vlc.MediaPlayer() # media objectmedia = vlc.Media("1mp4.mkv") # setting media to the media playermedia_player.set_media(media) # start playing videomedia_player.play() # wait so the video can be played for 5 seconds# irrespective for length of videotime.sleep(5) # getting mediavalue = media_player.get_media() # printing mediaprint("Media : ")print(value)
Output :
Media :
vlc.Media object at 0x00000254E3CE3A06
simranarora5sos
Python vlc-library
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": "\n11 Apr, 2022"
},
{
"code": null,
"e": 536,
"s": 28,
"text": "In this article we will see how we can get media of the MediaPlayer object in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. MediaPlayer object is the basic object in vlc module for playing the video. We can create a MediaPlayer object with the help of MediaPlayer method. Media can be video or even audio that is supported by vlc, it can be set with the help of set_media method."
},
{
"code": null,
"e": 614,
"s": 536,
"text": "In order to do this we will use get_media method with the MediaPlayer object "
},
{
"code": null,
"e": 649,
"s": 614,
"text": "Syntax : media_player.get_media() "
},
{
"code": null,
"e": 682,
"s": 649,
"text": "Argument : It takes no argument "
},
{
"code": null,
"e": 715,
"s": 682,
"text": "Return : It returns Media object"
},
{
"code": null,
"e": 744,
"s": 715,
"text": "Below is the implementation "
},
{
"code": null,
"e": 752,
"s": 744,
"text": "Python3"
},
{
"code": "# importing vlc moduleimport vlc # importing time moduleimport time # creating vlc media player objectmedia_player = vlc.MediaPlayer() # media objectmedia = vlc.Media(\"death_note.mkv\") # setting media to the media playermedia_player.set_media(media) # start playing videomedia_player.play() # wait so the video can be played for 5 seconds# irrespective for length of videotime.sleep(5) # getting mediavalue = media_player.get_media() # printing mediaprint(\"Media : \")print(value)",
"e": 1234,
"s": 752,
"text": null
},
{
"code": null,
"e": 1244,
"s": 1234,
"text": "Output : "
},
{
"code": null,
"e": 1292,
"s": 1244,
"text": "Media : \nvlc.Media object at 0x00000254E3CE3408"
},
{
"code": null,
"e": 1337,
"s": 1292,
"text": "Another example Below is the implementation "
},
{
"code": null,
"e": 1345,
"s": 1337,
"text": "Python3"
},
{
"code": "# importing vlc moduleimport vlc # importing time moduleimport time # creating vlc media player objectmedia_player = vlc.MediaPlayer() # media objectmedia = vlc.Media(\"1mp4.mkv\") # setting media to the media playermedia_player.set_media(media) # start playing videomedia_player.play() # wait so the video can be played for 5 seconds# irrespective for length of videotime.sleep(5) # getting mediavalue = media_player.get_media() # printing mediaprint(\"Media : \")print(value)",
"e": 1821,
"s": 1345,
"text": null
},
{
"code": null,
"e": 1831,
"s": 1821,
"text": "Output : "
},
{
"code": null,
"e": 1879,
"s": 1831,
"text": "Media : \nvlc.Media object at 0x00000254E3CE3A06"
},
{
"code": null,
"e": 1895,
"s": 1879,
"text": "simranarora5sos"
},
{
"code": null,
"e": 1914,
"s": 1895,
"text": "Python vlc-library"
},
{
"code": null,
"e": 1921,
"s": 1914,
"text": "Python"
},
{
"code": null,
"e": 2019,
"s": 1921,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2037,
"s": 2019,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2079,
"s": 2037,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2101,
"s": 2079,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2136,
"s": 2101,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2162,
"s": 2136,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2194,
"s": 2162,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2223,
"s": 2194,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2253,
"s": 2223,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 2280,
"s": 2253,
"text": "Python Classes and Objects"
}
] |
Python | Pandas dataframe.quantile()
|
13 Jun, 2022
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.quantile() function return values at the given quantile over requested axis, a numpy.percentile. Note : In each of any set of values of a variate which divide a frequency distribution into equal groups, each containing the same fraction of the total population.
Syntax: DataFrame.quantile(q=0.5, axis=0, numeric_only=True, interpolation=βlinearβ)
Parameters : q : float or array-like, default 0.5 (50% quantile). 0 <= q <= 1, the quantile(s) to compute
axis : [{0, 1, βindexβ, βcolumnsβ} (default 0)] 0 or βindexβ for row-wise, 1 or βcolumnsβ for column-wise
numeric_only : If False, the quantile of datetime and timedelta data will be computed as well
interpolation : {βlinearβ, βlowerβ, βhigherβ, βmidpointβ, βnearestβ}
Returns : quantiles : Series or DataFrame -> If q is an array, a DataFrame will be returned where the index is q, the columns are the columns of self, and the values are the quantiles. -> If q is a float, a Series will be returned where the index is the columns of self and the values are the quantiles.
Example #1: Use quantile() function to find the value of β.2β quantile
Python3
# importing pandas as pdimport pandas as pd # Creating the dataframedf = pd.DataFrame({"A":[1, 5, 3, 4, 2], "B":[3, 2, 4, 3, 4], "C":[2, 2, 7, 3, 4], "D":[4, 3, 6, 12, 7]}) # Print the dataframedf
Letβs use the dataframe.quantile() function to find the quantile of β.2β for each column in the dataframe
Python3
# find the product over the index axisdf.quantile(.2, axis = 0)
Output :
Example #2: Use quantile() function to find the (.1, .25, .5, .75) quantiles along the index axis.
Python3
# importing pandas as pdimport pandas as pd # Creating the dataframedf = pd.DataFrame({"A":[1, 5, 3, 4, 2], "B":[3, 2, 4, 3, 4], "C":[2, 2, 7, 3, 4], "D":[4, 3, 6, 12, 7]}) # using quantile() function to# find the quantiles over the index axisdf.quantile([.1, .25, .5, .75], axis = 0)
Output :
vinayedula
Python pandas-dataFrame
Python pandas-dataFrame-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n13 Jun, 2022"
},
{
"code": null,
"e": 545,
"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. Pandas dataframe.quantile() function return values at the given quantile over requested axis, a numpy.percentile. Note : In each of any set of values of a variate which divide a frequency distribution into equal groups, each containing the same fraction of the total population."
},
{
"code": null,
"e": 631,
"s": 545,
"text": "Syntax: DataFrame.quantile(q=0.5, axis=0, numeric_only=True, interpolation=βlinearβ) "
},
{
"code": null,
"e": 738,
"s": 631,
"text": "Parameters : q : float or array-like, default 0.5 (50% quantile). 0 <= q <= 1, the quantile(s) to compute "
},
{
"code": null,
"e": 845,
"s": 738,
"text": "axis : [{0, 1, βindexβ, βcolumnsβ} (default 0)] 0 or βindexβ for row-wise, 1 or βcolumnsβ for column-wise "
},
{
"code": null,
"e": 940,
"s": 845,
"text": "numeric_only : If False, the quantile of datetime and timedelta data will be computed as well "
},
{
"code": null,
"e": 1010,
"s": 940,
"text": "interpolation : {βlinearβ, βlowerβ, βhigherβ, βmidpointβ, βnearestβ} "
},
{
"code": null,
"e": 1314,
"s": 1010,
"text": "Returns : quantiles : Series or DataFrame -> If q is an array, a DataFrame will be returned where the index is q, the columns are the columns of self, and the values are the quantiles. -> If q is a float, a Series will be returned where the index is the columns of self and the values are the quantiles."
},
{
"code": null,
"e": 1386,
"s": 1314,
"text": "Example #1: Use quantile() function to find the value of β.2β quantile "
},
{
"code": null,
"e": 1394,
"s": 1386,
"text": "Python3"
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the dataframedf = pd.DataFrame({\"A\":[1, 5, 3, 4, 2], \"B\":[3, 2, 4, 3, 4], \"C\":[2, 2, 7, 3, 4], \"D\":[4, 3, 6, 12, 7]}) # Print the dataframedf",
"e": 1645,
"s": 1394,
"text": null
},
{
"code": null,
"e": 1754,
"s": 1647,
"text": "Letβs use the dataframe.quantile() function to find the quantile of β.2β for each column in the dataframe "
},
{
"code": null,
"e": 1762,
"s": 1754,
"text": "Python3"
},
{
"code": "# find the product over the index axisdf.quantile(.2, axis = 0)",
"e": 1826,
"s": 1762,
"text": null
},
{
"code": null,
"e": 1835,
"s": 1826,
"text": "Output :"
},
{
"code": null,
"e": 1938,
"s": 1838,
"text": "Example #2: Use quantile() function to find the (.1, .25, .5, .75) quantiles along the index axis. "
},
{
"code": null,
"e": 1946,
"s": 1938,
"text": "Python3"
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the dataframedf = pd.DataFrame({\"A\":[1, 5, 3, 4, 2], \"B\":[3, 2, 4, 3, 4], \"C\":[2, 2, 7, 3, 4], \"D\":[4, 3, 6, 12, 7]}) # using quantile() function to# find the quantiles over the index axisdf.quantile([.1, .25, .5, .75], axis = 0)",
"e": 2285,
"s": 1946,
"text": null
},
{
"code": null,
"e": 2294,
"s": 2285,
"text": "Output :"
},
{
"code": null,
"e": 2307,
"s": 2296,
"text": "vinayedula"
},
{
"code": null,
"e": 2331,
"s": 2307,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 2363,
"s": 2331,
"text": "Python pandas-dataFrame-methods"
},
{
"code": null,
"e": 2377,
"s": 2363,
"text": "Python-pandas"
},
{
"code": null,
"e": 2384,
"s": 2377,
"text": "Python"
},
{
"code": null,
"e": 2482,
"s": 2384,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2500,
"s": 2482,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2542,
"s": 2500,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2564,
"s": 2542,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2599,
"s": 2564,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2625,
"s": 2599,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2657,
"s": 2625,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2686,
"s": 2657,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2713,
"s": 2686,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2743,
"s": 2713,
"text": "Iterate over a list in Python"
}
] |
PostgreSQL β REGEXP_REPLACE Function
|
16 Aug, 2021
The PostgreSQL REGEXP_REPLACE() function is used to replaces substrings that match a POSIX regular expression with a new substring.
Syntax: REGEXP_REPLACE(source, pattern, replacement_string, [, flags])
Letβs analyze the above syntax:
The source is a string where the search and replace operation in executed.
The pattern is a POSIX regular expression for matching substrings which is to be replaced.
The replacement_string is a string which replaces the substrings using match the regular expression pattern.
The flags argument is used to control the behaviour of the function for matching characters.
The PostgreSQL REGEXP_REPLACE() function returns the final string after the replacement of the original string with the substring.
Example 1:
For instance imagine you have a name of a person in the following format:
first_name last_name
And you want to rearrange the name as follows:
last_name, first_name
To do this, you can use the REGEXP_REPLACE() function as shown below:
SELECT REGEXP_REPLACE('Raju Kumar', '(.*) (.*)', '\2, \1');
Output:
Example 2:
Suppose you have data in the form of a string. This string is mixed with alphabets and digits as follows:
ABC12345xyz
The following query removes all alphabets e.g., A, B, C, etc from the source string:
SELECT REGEXP_REPLACE('ABC12345xyz', '[[:alpha:]]', '', 'g');
Output:
singghakshay
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PostgreSQL - LIMIT with OFFSET clause
PostgreSQL - Rename Table
PostgreSQL - Joins
PostgreSQL - ARRAY_AGG() Function
PostgreSQL - REPLACE Function
PostgreSQL - Introduction to Stored Procedures
PostgreSQL - DROP INDEX
PostgreSQL - INSERT
PostgreSQL - Create Auto-increment Column using SERIAL
PostgreSQL - Copy Table
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n16 Aug, 2021"
},
{
"code": null,
"e": 160,
"s": 28,
"text": "The PostgreSQL REGEXP_REPLACE() function is used to replaces substrings that match a POSIX regular expression with a new substring."
},
{
"code": null,
"e": 231,
"s": 160,
"text": "Syntax: REGEXP_REPLACE(source, pattern, replacement_string, [, flags])"
},
{
"code": null,
"e": 263,
"s": 231,
"text": "Letβs analyze the above syntax:"
},
{
"code": null,
"e": 338,
"s": 263,
"text": "The source is a string where the search and replace operation in executed."
},
{
"code": null,
"e": 429,
"s": 338,
"text": "The pattern is a POSIX regular expression for matching substrings which is to be replaced."
},
{
"code": null,
"e": 538,
"s": 429,
"text": "The replacement_string is a string which replaces the substrings using match the regular expression pattern."
},
{
"code": null,
"e": 631,
"s": 538,
"text": "The flags argument is used to control the behaviour of the function for matching characters."
},
{
"code": null,
"e": 762,
"s": 631,
"text": "The PostgreSQL REGEXP_REPLACE() function returns the final string after the replacement of the original string with the substring."
},
{
"code": null,
"e": 773,
"s": 762,
"text": "Example 1:"
},
{
"code": null,
"e": 847,
"s": 773,
"text": "For instance imagine you have a name of a person in the following format:"
},
{
"code": null,
"e": 868,
"s": 847,
"text": "first_name last_name"
},
{
"code": null,
"e": 915,
"s": 868,
"text": "And you want to rearrange the name as follows:"
},
{
"code": null,
"e": 937,
"s": 915,
"text": "last_name, first_name"
},
{
"code": null,
"e": 1007,
"s": 937,
"text": "To do this, you can use the REGEXP_REPLACE() function as shown below:"
},
{
"code": null,
"e": 1067,
"s": 1007,
"text": "SELECT REGEXP_REPLACE('Raju Kumar', '(.*) (.*)', '\\2, \\1');"
},
{
"code": null,
"e": 1075,
"s": 1067,
"text": "Output:"
},
{
"code": null,
"e": 1086,
"s": 1075,
"text": "Example 2:"
},
{
"code": null,
"e": 1192,
"s": 1086,
"text": "Suppose you have data in the form of a string. This string is mixed with alphabets and digits as follows:"
},
{
"code": null,
"e": 1204,
"s": 1192,
"text": "ABC12345xyz"
},
{
"code": null,
"e": 1289,
"s": 1204,
"text": "The following query removes all alphabets e.g., A, B, C, etc from the source string:"
},
{
"code": null,
"e": 1351,
"s": 1289,
"text": "SELECT REGEXP_REPLACE('ABC12345xyz', '[[:alpha:]]', '', 'g');"
},
{
"code": null,
"e": 1359,
"s": 1351,
"text": "Output:"
},
{
"code": null,
"e": 1372,
"s": 1359,
"text": "singghakshay"
},
{
"code": null,
"e": 1383,
"s": 1372,
"text": "PostgreSQL"
},
{
"code": null,
"e": 1481,
"s": 1383,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1519,
"s": 1481,
"text": "PostgreSQL - LIMIT with OFFSET clause"
},
{
"code": null,
"e": 1545,
"s": 1519,
"text": "PostgreSQL - Rename Table"
},
{
"code": null,
"e": 1564,
"s": 1545,
"text": "PostgreSQL - Joins"
},
{
"code": null,
"e": 1598,
"s": 1564,
"text": "PostgreSQL - ARRAY_AGG() Function"
},
{
"code": null,
"e": 1628,
"s": 1598,
"text": "PostgreSQL - REPLACE Function"
},
{
"code": null,
"e": 1675,
"s": 1628,
"text": "PostgreSQL - Introduction to Stored Procedures"
},
{
"code": null,
"e": 1699,
"s": 1675,
"text": "PostgreSQL - DROP INDEX"
},
{
"code": null,
"e": 1719,
"s": 1699,
"text": "PostgreSQL - INSERT"
},
{
"code": null,
"e": 1774,
"s": 1719,
"text": "PostgreSQL - Create Auto-increment Column using SERIAL"
}
] |
Replace nodes with duplicates in linked list
|
24 Jun, 2021
Given a linked list that contains some random integers from 1 to n with many duplicates. Replace each duplicate element that is present in the linked list with the values n+1, n+2, n+3 and so on(starting from left to right in the given linked list).
Examples:
Input : 1 3 1 4 4 2 1
Output : 1 3 5 4 6 2 7
Replace 2nd occurrence of 1 with 5 i.e. (4+1)
2nd occurrence of 4 with 6 i.e. (4+2)
3rd occurrence of 1 with 7 i.e. (4+3)
Input : 1 1 1 4 3 2 2
Output : 1 5 6 4 3 2 7
Approach : 1. Traverse the linked list, store the frequencies of every number present in linked list in a map and alongwith it find the maximum integer present in linked list i.e. maxNum. 2. Now, traverse the linked list again and if the frequency of any number is more than 1, set its value to -1 in map on its first occurrence. 3.The reason for this is that on next occurrence of this number we will find its value -1 which means this number has occurred before, change its data with maxNum + 1 and increment maxNum.
Below is the implementation of idea.
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; /* A linked list node */struct Node { int data; struct Node* next;}; // Utility function to create a new Nodestruct Node* newNode(int data){ Node* temp = new Node; temp->data = data; temp->next = NULL; return temp;} // Function to replace duplicates from a// linked listvoid replaceDuplicates(struct Node* head){ // map to store the frequency of numbers unordered_map<int, int> mymap; Node* temp = head; // variable to store the maximum number // in linked list int maxNum = 0; // traverse the linked list to store // the frequency of every number and // find the maximum integer while (temp) { mymap[temp->data]++; if (maxNum < temp->data) maxNum = temp->data; temp = temp->next; } // Traverse again the linked list while (head) { // Mark the node with frequency more // than 1 so that we can change the // 2nd occurrence of that number if (mymap[head->data] > 1) mymap[head->data] = -1; // -1 means number has occurred // before change its value else if (mymap[head->data] == -1) head->data = ++maxNum; head = head->next; }} /* Function to print nodes in a givenlinked list */void printList(struct Node* node){ while (node != NULL) { printf("%d ", node->data); node = node->next; } cout << endl;} /* Driver program to test above function */int main(){ /* The constructed linked list is: 1->3->1->4->4->2->1*/ struct Node* head = newNode(1); head->next = newNode(3); head->next->next = newNode(1); head->next->next->next = newNode(4); head->next->next->next->next = newNode(4); head->next->next->next->next-> next = newNode(2); head->next->next->next->next-> next->next = newNode(1); cout << "Linked list before replacing" << " duplicates\n"; printList(head); replaceDuplicates(head); cout << "Linked list after replacing" << " duplicates\n"; printList(head); return 0;}
// Java implementation of the approachimport java.util.*; class GFG{ // Representation of nodestatic class Node{ int data; Node next; Node(int d) { data = d; next = null; }}; // Function to insert a node at the beginningstatic Node insert(Node head, int item){ Node temp = new Node(0); temp.data = item; temp.next = head; head = temp; return head;} // Function to replace duplicates from a// linked liststatic void replaceDuplicates( Node head){ // map to store the frequency of numbers Map<Integer, Integer> mymap = new HashMap<>(); Node temp = head; // variable to store the maximum number // in linked list int maxNum = 0; // traverse the linked list to store // the frequency of every number and // find the maximum integer while (temp != null) { mymap.put(temp.data,(mymap.get(temp.data) == null?0:mymap.get(temp.data))+1); if (maxNum < temp.data) maxNum = temp.data; temp = temp.next; } // Traverse again the linked list while (head != null) { // Mark the node with frequency more // than 1 so that we can change the // 2nd occurrence of that number if (mymap.get(head.data) > 1) mymap.put(head.data, -1); // -1 means number has occurred // before change its value else if (mymap.get(head.data) == -1) head.data = ++maxNum; head = head.next; }} // Function to print nodes in a given//linked list /static void printList( Node node){ while (node != null) { System.out.printf("%d ", node.data); node = node.next; } System.out.println();} // Driver codepublic static void main(String args[]){ // The constructed linked list is: // 1->3->1->4->4->2->1/ Node head = new Node(1); head.next = new Node(3); head.next.next = new Node(1); head.next.next.next = new Node(4); head.next.next.next.next = new Node(4); head.next.next.next.next. next = new Node(2); head.next.next.next.next. next.next = new Node(1); System.out.println( "Linked list before replacing" + " duplicates\n"); printList(head); replaceDuplicates(head); System.out.println("Linked list after replacing" + " duplicates\n"); printList(head);}} // This code is contributed by Arnab Kundu
# Python3 implementation of the approach # A linked list nodeclass Node: def __init__(self, data): self.data = data self.next = None # Utility function to create a new Nodedef newNode(data): temp = Node(data) return temp # Function to replace duplicates from a# linked listdef replaceDuplicates(head): # Map to store the frequency of numbers mymap = dict() temp = head # Variable to store the maximum number # in linked list maxNum = 0 # Traverse the linked list to store # the frequency of every number and # find the maximum integer while (temp): if temp.data not in mymap: mymap[temp.data] = 0 mymap[temp.data] += 1 if (maxNum < temp.data): maxNum = temp.data temp = temp.next # Traverse again the linked list while (head): # Mark the node with frequency more # than 1 so that we can change the # 2nd occurrence of that number if (mymap[head.data] > 1): mymap[head.data] = -1 # -1 means number has occurred # before change its value elif (mymap[head.data] == -1): maxNum += 1 head.data = maxNum head = head.next # Function to print nodes in a given# linked listdef printList(node): while (node != None): print(node.data, end = ' ') node = node.next print() # Driver codeif __name__=='__main__': # The constructed linked list is: # 1.3.1.4.4.2.1 head = newNode(1) head.next = newNode(3) head.next.next = newNode(1) head.next.next.next = newNode(4) head.next.next.next.next = newNode(4) head.next.next.next.next.next = newNode(2) head.next.next.next.next.next.next = newNode(1) print("Linked list before replacing duplicates") printList(head) replaceDuplicates(head) print("Linked list after replacing duplicates") printList(head) # This code is contributed by rutvik_56
// C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ // Representation of nodeclass Node{ public int data; public Node next; public Node(int d) { data = d; next = null; }}; // Function to insert a node at the beginningstatic Node insert(Node head, int item){ Node temp = new Node(0); temp.data = item; temp.next = head; head = temp; return head;} // Function to replace duplicates from a// linked liststatic void replaceDuplicates( Node head){ // map to store the frequency of numbers Dictionary<int, int> mymap = new Dictionary<int, int>(); Node temp = head; // variable to store the maximum number // in linked list int maxNum = 0; // traverse the linked list to store // the frequency of every number and // find the maximum integer while (temp != null) { if(mymap.ContainsKey(temp.data)) mymap[temp.data] = mymap[temp.data] + 1; else mymap.Add(temp.data, 1); if (maxNum < temp.data) maxNum = temp.data; temp = temp.next; } // Traverse again the linked list while (head != null) { // Mark the node with frequency more // than 1 so that we can change the // 2nd occurrence of that number if (mymap[head.data] > 1) mymap[head.data] = -1; // -1 means number has occurred // before change its value else if (mymap[head.data] == -1) head.data = ++maxNum; head = head.next; }} // Function to print nodes in a given// linked liststatic void printList( Node node){ while (node != null) { Console.Write("{0} ", node.data); node = node.next; }} // Driver codepublic static void Main(String []args){ // The constructed linked list is: // 1->3->1->4->4->2->1/ Node head = new Node(1); head.next = new Node(3); head.next.next = new Node(1); head.next.next.next = new Node(4); head.next.next.next.next = new Node(4); head.next.next.next.next.next = new Node(2); head.next.next.next.next.next.next = new Node(1); Console.WriteLine("Linked list before" + " replacing duplicates"); printList(head); replaceDuplicates(head); Console.WriteLine("\nLinked list after" + " replacing duplicates"); printList(head);}} // This code is contributed by 29AjayKumar
<script> // JavaScript implementation of the approach // Representation of nodeclass Node{ constructor(d) { this.data = d; this.next = null; }} // Function to insert a node at the beginningfunction insert(head, item){ var temp = new Node(0); temp.data = item; temp.next = head; head = temp; return head;} // Function to replace duplicates from a// linked listfunction replaceDuplicates(head){ // Map to store the frequency of numbers var mymap = {}; var temp = head; // Variable to store the maximum number // in linked list var maxNum = 0; // Traverse the linked list to store // the frequency of every number and // find the maximum integer while (temp != null) { if (mymap.hasOwnProperty(temp.data)) mymap[temp.data] = mymap[temp.data] + 1; else mymap[temp.data] = 1; if (maxNum < temp.data) maxNum = temp.data; temp = temp.next; } // Traverse again the linked list while (head != null) { // Mark the node with frequency more // than 1 so that we can change the // 2nd occurrence of that number if (mymap[head.data] > 1) mymap[head.data] = -1; // -1 means number has occurred // before change its value else if (mymap[head.data] == -1) head.data = ++maxNum; head = head.next; }} // Function to print nodes in a given// linked listfunction printList(node){ while (node != null) { document.write(node.data + " "); node = node.next; }} // Driver code // The constructed linked list is:// 1->3->1->4->4->2->1/var head = new Node(1);head.next = new Node(3);head.next.next = new Node(1);head.next.next.next = new Node(4);head.next.next.next.next = new Node(4);head.next.next.next.next.next = new Node(2);head.next.next.next.next.next.next = new Node(1); document.write("Linked list before " + "replacing duplicates <br>");printList(head);replaceDuplicates(head); document.write("<br>Linked list after " + "replacing duplicates <br>");printList(head); // This code is contributed by rdtank </script>
Output:
Linked list before replacing duplicates
1 3 1 4 4 2 1
Linked list after replacing duplicates
1 3 5 4 6 2 7
This article is contributed by Chhavi. 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.
andrew1234
29AjayKumar
Akanksha_Rai
nidhi_biet
rutvik_56
rdtank
Linked List
Linked List
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n24 Jun, 2021"
},
{
"code": null,
"e": 304,
"s": 54,
"text": "Given a linked list that contains some random integers from 1 to n with many duplicates. Replace each duplicate element that is present in the linked list with the values n+1, n+2, n+3 and so on(starting from left to right in the given linked list)."
},
{
"code": null,
"e": 316,
"s": 304,
"text": "Examples: "
},
{
"code": null,
"e": 545,
"s": 316,
"text": "Input : 1 3 1 4 4 2 1\nOutput : 1 3 5 4 6 2 7\nReplace 2nd occurrence of 1 with 5 i.e. (4+1)\n 2nd occurrence of 4 with 6 i.e. (4+2)\n 3rd occurrence of 1 with 7 i.e. (4+3)\n\nInput : 1 1 1 4 3 2 2\nOutput : 1 5 6 4 3 2 7"
},
{
"code": null,
"e": 1064,
"s": 545,
"text": "Approach : 1. Traverse the linked list, store the frequencies of every number present in linked list in a map and alongwith it find the maximum integer present in linked list i.e. maxNum. 2. Now, traverse the linked list again and if the frequency of any number is more than 1, set its value to -1 in map on its first occurrence. 3.The reason for this is that on next occurrence of this number we will find its value -1 which means this number has occurred before, change its data with maxNum + 1 and increment maxNum."
},
{
"code": null,
"e": 1103,
"s": 1064,
"text": "Below is the implementation of idea. "
},
{
"code": null,
"e": 1107,
"s": 1103,
"text": "C++"
},
{
"code": null,
"e": 1112,
"s": 1107,
"text": "Java"
},
{
"code": null,
"e": 1120,
"s": 1112,
"text": "Python3"
},
{
"code": null,
"e": 1123,
"s": 1120,
"text": "C#"
},
{
"code": null,
"e": 1134,
"s": 1123,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; /* A linked list node */struct Node { int data; struct Node* next;}; // Utility function to create a new Nodestruct Node* newNode(int data){ Node* temp = new Node; temp->data = data; temp->next = NULL; return temp;} // Function to replace duplicates from a// linked listvoid replaceDuplicates(struct Node* head){ // map to store the frequency of numbers unordered_map<int, int> mymap; Node* temp = head; // variable to store the maximum number // in linked list int maxNum = 0; // traverse the linked list to store // the frequency of every number and // find the maximum integer while (temp) { mymap[temp->data]++; if (maxNum < temp->data) maxNum = temp->data; temp = temp->next; } // Traverse again the linked list while (head) { // Mark the node with frequency more // than 1 so that we can change the // 2nd occurrence of that number if (mymap[head->data] > 1) mymap[head->data] = -1; // -1 means number has occurred // before change its value else if (mymap[head->data] == -1) head->data = ++maxNum; head = head->next; }} /* Function to print nodes in a givenlinked list */void printList(struct Node* node){ while (node != NULL) { printf(\"%d \", node->data); node = node->next; } cout << endl;} /* Driver program to test above function */int main(){ /* The constructed linked list is: 1->3->1->4->4->2->1*/ struct Node* head = newNode(1); head->next = newNode(3); head->next->next = newNode(1); head->next->next->next = newNode(4); head->next->next->next->next = newNode(4); head->next->next->next->next-> next = newNode(2); head->next->next->next->next-> next->next = newNode(1); cout << \"Linked list before replacing\" << \" duplicates\\n\"; printList(head); replaceDuplicates(head); cout << \"Linked list after replacing\" << \" duplicates\\n\"; printList(head); return 0;}",
"e": 3330,
"s": 1134,
"text": null
},
{
"code": "// Java implementation of the approachimport java.util.*; class GFG{ // Representation of nodestatic class Node{ int data; Node next; Node(int d) { data = d; next = null; }}; // Function to insert a node at the beginningstatic Node insert(Node head, int item){ Node temp = new Node(0); temp.data = item; temp.next = head; head = temp; return head;} // Function to replace duplicates from a// linked liststatic void replaceDuplicates( Node head){ // map to store the frequency of numbers Map<Integer, Integer> mymap = new HashMap<>(); Node temp = head; // variable to store the maximum number // in linked list int maxNum = 0; // traverse the linked list to store // the frequency of every number and // find the maximum integer while (temp != null) { mymap.put(temp.data,(mymap.get(temp.data) == null?0:mymap.get(temp.data))+1); if (maxNum < temp.data) maxNum = temp.data; temp = temp.next; } // Traverse again the linked list while (head != null) { // Mark the node with frequency more // than 1 so that we can change the // 2nd occurrence of that number if (mymap.get(head.data) > 1) mymap.put(head.data, -1); // -1 means number has occurred // before change its value else if (mymap.get(head.data) == -1) head.data = ++maxNum; head = head.next; }} // Function to print nodes in a given//linked list /static void printList( Node node){ while (node != null) { System.out.printf(\"%d \", node.data); node = node.next; } System.out.println();} // Driver codepublic static void main(String args[]){ // The constructed linked list is: // 1->3->1->4->4->2->1/ Node head = new Node(1); head.next = new Node(3); head.next.next = new Node(1); head.next.next.next = new Node(4); head.next.next.next.next = new Node(4); head.next.next.next.next. next = new Node(2); head.next.next.next.next. next.next = new Node(1); System.out.println( \"Linked list before replacing\" + \" duplicates\\n\"); printList(head); replaceDuplicates(head); System.out.println(\"Linked list after replacing\" + \" duplicates\\n\"); printList(head);}} // This code is contributed by Arnab Kundu",
"e": 5737,
"s": 3330,
"text": null
},
{
"code": "# Python3 implementation of the approach # A linked list nodeclass Node: def __init__(self, data): self.data = data self.next = None # Utility function to create a new Nodedef newNode(data): temp = Node(data) return temp # Function to replace duplicates from a# linked listdef replaceDuplicates(head): # Map to store the frequency of numbers mymap = dict() temp = head # Variable to store the maximum number # in linked list maxNum = 0 # Traverse the linked list to store # the frequency of every number and # find the maximum integer while (temp): if temp.data not in mymap: mymap[temp.data] = 0 mymap[temp.data] += 1 if (maxNum < temp.data): maxNum = temp.data temp = temp.next # Traverse again the linked list while (head): # Mark the node with frequency more # than 1 so that we can change the # 2nd occurrence of that number if (mymap[head.data] > 1): mymap[head.data] = -1 # -1 means number has occurred # before change its value elif (mymap[head.data] == -1): maxNum += 1 head.data = maxNum head = head.next # Function to print nodes in a given# linked listdef printList(node): while (node != None): print(node.data, end = ' ') node = node.next print() # Driver codeif __name__=='__main__': # The constructed linked list is: # 1.3.1.4.4.2.1 head = newNode(1) head.next = newNode(3) head.next.next = newNode(1) head.next.next.next = newNode(4) head.next.next.next.next = newNode(4) head.next.next.next.next.next = newNode(2) head.next.next.next.next.next.next = newNode(1) print(\"Linked list before replacing duplicates\") printList(head) replaceDuplicates(head) print(\"Linked list after replacing duplicates\") printList(head) # This code is contributed by rutvik_56",
"e": 7786,
"s": 5737,
"text": null
},
{
"code": "// C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ // Representation of nodeclass Node{ public int data; public Node next; public Node(int d) { data = d; next = null; }}; // Function to insert a node at the beginningstatic Node insert(Node head, int item){ Node temp = new Node(0); temp.data = item; temp.next = head; head = temp; return head;} // Function to replace duplicates from a// linked liststatic void replaceDuplicates( Node head){ // map to store the frequency of numbers Dictionary<int, int> mymap = new Dictionary<int, int>(); Node temp = head; // variable to store the maximum number // in linked list int maxNum = 0; // traverse the linked list to store // the frequency of every number and // find the maximum integer while (temp != null) { if(mymap.ContainsKey(temp.data)) mymap[temp.data] = mymap[temp.data] + 1; else mymap.Add(temp.data, 1); if (maxNum < temp.data) maxNum = temp.data; temp = temp.next; } // Traverse again the linked list while (head != null) { // Mark the node with frequency more // than 1 so that we can change the // 2nd occurrence of that number if (mymap[head.data] > 1) mymap[head.data] = -1; // -1 means number has occurred // before change its value else if (mymap[head.data] == -1) head.data = ++maxNum; head = head.next; }} // Function to print nodes in a given// linked liststatic void printList( Node node){ while (node != null) { Console.Write(\"{0} \", node.data); node = node.next; }} // Driver codepublic static void Main(String []args){ // The constructed linked list is: // 1->3->1->4->4->2->1/ Node head = new Node(1); head.next = new Node(3); head.next.next = new Node(1); head.next.next.next = new Node(4); head.next.next.next.next = new Node(4); head.next.next.next.next.next = new Node(2); head.next.next.next.next.next.next = new Node(1); Console.WriteLine(\"Linked list before\" + \" replacing duplicates\"); printList(head); replaceDuplicates(head); Console.WriteLine(\"\\nLinked list after\" + \" replacing duplicates\"); printList(head);}} // This code is contributed by 29AjayKumar",
"e": 10286,
"s": 7786,
"text": null
},
{
"code": "<script> // JavaScript implementation of the approach // Representation of nodeclass Node{ constructor(d) { this.data = d; this.next = null; }} // Function to insert a node at the beginningfunction insert(head, item){ var temp = new Node(0); temp.data = item; temp.next = head; head = temp; return head;} // Function to replace duplicates from a// linked listfunction replaceDuplicates(head){ // Map to store the frequency of numbers var mymap = {}; var temp = head; // Variable to store the maximum number // in linked list var maxNum = 0; // Traverse the linked list to store // the frequency of every number and // find the maximum integer while (temp != null) { if (mymap.hasOwnProperty(temp.data)) mymap[temp.data] = mymap[temp.data] + 1; else mymap[temp.data] = 1; if (maxNum < temp.data) maxNum = temp.data; temp = temp.next; } // Traverse again the linked list while (head != null) { // Mark the node with frequency more // than 1 so that we can change the // 2nd occurrence of that number if (mymap[head.data] > 1) mymap[head.data] = -1; // -1 means number has occurred // before change its value else if (mymap[head.data] == -1) head.data = ++maxNum; head = head.next; }} // Function to print nodes in a given// linked listfunction printList(node){ while (node != null) { document.write(node.data + \" \"); node = node.next; }} // Driver code // The constructed linked list is:// 1->3->1->4->4->2->1/var head = new Node(1);head.next = new Node(3);head.next.next = new Node(1);head.next.next.next = new Node(4);head.next.next.next.next = new Node(4);head.next.next.next.next.next = new Node(2);head.next.next.next.next.next.next = new Node(1); document.write(\"Linked list before \" + \"replacing duplicates <br>\");printList(head);replaceDuplicates(head); document.write(\"<br>Linked list after \" + \"replacing duplicates <br>\");printList(head); // This code is contributed by rdtank </script>",
"e": 12510,
"s": 10286,
"text": null
},
{
"code": null,
"e": 12519,
"s": 12510,
"text": "Output: "
},
{
"code": null,
"e": 12627,
"s": 12519,
"text": "Linked list before replacing duplicates\n1 3 1 4 4 2 1 \nLinked list after replacing duplicates\n1 3 5 4 6 2 7"
},
{
"code": null,
"e": 13042,
"s": 12627,
"text": "This article is contributed by Chhavi. 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": 13053,
"s": 13042,
"text": "andrew1234"
},
{
"code": null,
"e": 13065,
"s": 13053,
"text": "29AjayKumar"
},
{
"code": null,
"e": 13078,
"s": 13065,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 13089,
"s": 13078,
"text": "nidhi_biet"
},
{
"code": null,
"e": 13099,
"s": 13089,
"text": "rutvik_56"
},
{
"code": null,
"e": 13106,
"s": 13099,
"text": "rdtank"
},
{
"code": null,
"e": 13118,
"s": 13106,
"text": "Linked List"
},
{
"code": null,
"e": 13130,
"s": 13118,
"text": "Linked List"
}
] |
Construction of Longest Increasing Subsequence(LIS) and printing LIS sequence - GeeksforGeeks
|
25 Apr, 2022
Java code:
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}.
C++
Java
Python3
C#
Javascript
#include <bits/stdc++.h>using namespace std; void LIS(int a[], int n){ vector<int> list; vector<int> longestlist; // Highest count int hc = 0; // Current max int cm; for(int i = 0; i < n; i++) { cm = INT_MIN; for(int j = i; j < n; j++) { if (a[j] > cm) { list.push_back(a[j]); cm = a[j]; } } // Compare previous highest subsequence if (hc < list.size()) { hc = list.size(); for(int k = 0; k < list.size(); k++) { longestlist.push_back(list[k]); } } list.clear(); } for(int i = 0; i < longestlist.size(); i++) { cout << longestlist[i] << ' '; } cout << endl; cout << "length of longestlist is " << hc;} // Driver codeint main(){ int a[] = { 10, 22, 9, 33, 21, 50, 41, 60, 80 }; int n = sizeof(a) / sizeof(a[0]); LIS(a, n); return 0;} // This code is contributed by Harshit Srivastava
package BIT; import java.util.ArrayList;import java.util.Iterator; public class LongestIncreasingSubsequence { public static void main(String[] args) {// int array[] = {10, 22, 9, 33, 21, 50, 41, 60, 80};// int array[] = {10, 2, 9, 3, 5, 4, 6, 8}; int array[] = {10, 9, 8, 6, 5, 4}; ArrayList list = new ArrayList(); ArrayList longestList = new ArrayList(); int currentMax; int highestCount = 0; for(int i = 0; i < array.length;i++) { currentMax = Integer.MIN_VALUE; for(int j = i;j < array.length; j++) { if(array[j] > currentMax) { list.add(array[j]); currentMax = array[j]; } } //Compare previous highest subsequence if(highestCount < list.size()) { highestCount = list.size(); longestList = new ArrayList(list); } list.clear(); } System.out.println(); //Print list Iterator itr = longestList.iterator(); System.out.println("The Longest subsequence"); while(itr.hasNext()) { System.out.print(itr.next() + " "); } System.out.println(); System.out.println("Length of LIS: " + highestCount); } }
import sys def LIS(a, n): list = [] longestlist = [] # Highest count hc = 0 # Current max for i in range(n): cm = -sys.maxsize -1 for j in range(i,n): if (a[j] > cm): list.append(a[j]) cm = a[j] # Compare previous highest subsequence if (hc < len(list)): hc = len(list) for k in range(len(list)): longestlist.append(list[k]) list = [] for i in range(len(longestlist)): print(longestlist[i] ,end = ' ') print() print("length of longestlist is " + str(hc)) # Driver code a = [ 10, 22, 9, 33, 21, 50, 41, 60, 80 ]n = len(a)LIS(a, n) # This code is contributed by shinjanpatra
using System;using System.Collections.Generic; class longestIncreasingSubsequence{ public static void Main(String[] args) { int []array = {10, 22, 9, 33, 21, 50, 41, 60, 80}; // int []array = {10, 2, 9, 3, 5, 4, 6, 8}; //int []array = {10, 9, 8, 6, 5, 4}; List<int> list = new List<int>(); List<int> longestList = new List<int>(); int currentMax; int highestCount = 0; for(int i = 0; i < array.Length;i++) { currentMax = int.MinValue; for(int j = i;j < array.Length; j++) { if(array[j] > currentMax) { list.Add(array[j]); currentMax = array[j]; } } // Compare previous highest subsequence if(highestCount < list.Count) { highestCount = list.Count; longestList = new List<int>(list); } list.Clear(); } Console.WriteLine(); // Print list Console.WriteLine("The longest subsequence"); foreach(int itr in longestList) { Console.Write(itr + " "); } Console.WriteLine(); Console.WriteLine("Length of LIS: " + highestCount); }} // This code is contributed by 29AjayKumar
<script>function LIS(a, n){ let list = []; let longestlist = []; // Highest count let hc = 0; // Current max let cm; for(let i = 0; i < n; i++) { cm = Number.MIN_VALUE; for(let j = i; j < n; j++) { if (a[j] > cm) { list.push(a[j]); cm = a[j]; } } // Compare previous highest subsequence if (hc < list.length) { hc = list.length; for(let k = 0; k < list.length; k++) { longestlist.push(list[k]); } } list = []; } for(let i = 0; i < longestlist.length; i++) { document.write(longestlist[i] + ' '); } document.write("</br>") document.write("length of longestlist is " + hc);} // Driver code let a = [ 10, 22, 9, 33, 21, 50, 41, 60, 80 ];let n = a.length;LIS(a, n); // This code is contributed by shinjanpatra</script>
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.
Examples:
Input: [10, 22, 9, 33, 21, 50, 41, 60, 80]
Output: [10, 22, 33, 50, 60, 80]
OR [10 22 33 41 60 80] or any other LIS of same length.
In the previous post, we have discussed The Longest Increasing Subsequence problem. However, the post only covered code related to the querying size of LIS, but not the construction of LIS. In this post, we will discuss how to print LIS using a similar DP solution discussed earlier.Let arr[0..n-1] be the input array. We define vector L such that L[i] is itself is a vector that stores LIS of arr that ends with arr[i]. For example, for array [3, 2, 6, 4, 5, 1],
L[0]: 3
L[1]: 2
L[2]: 2 6
L[3]: 2 4
L[4]: 2 4 5
L[5]: 1
Therefore, for index i, L[i] can be recursively written as β
L[0] = {arr[O]}
L[i] = {Max(L[j])} + arr[i]
where j < i and arr[j] < arr[i] and if there is no such j then L[i] = arr[i]
Below is the implementation of the above idea β
C++
Java
Python3
C#
/* Dynamic Programming solution to construct Longest Increasing Subsequence */#include <iostream>#include <vector>using namespace std; // Utility function to print LISvoid printLIS(vector<int>& arr){ for (int x : arr) cout << x << " "; cout << endl;} // Function to construct and print Longest Increasing// Subsequencevoid constructPrintLIS(int arr[], int n){ // L[i] - The longest increasing sub-sequence // ends with arr[i] vector<vector<int> > L(n); // L[0] is equal to arr[0] L[0].push_back(arr[0]); // start from index 1 for (int i = 1; i < n; i++) { // do for every j less than i for (int j = 0; j < i; j++) { /* L[i] = {Max(L[j])} + arr[i] where j < i and arr[j] < arr[i] */ if ((arr[i] > arr[j]) && (L[i].size() < L[j].size() + 1)) L[i] = L[j]; } // L[i] ends with arr[i] L[i].push_back(arr[i]); } // L[i] now stores increasing sub-sequence of // arr[0..i] that ends with arr[i] vector<int> max = L[0]; // LIS will be max of all increasing sub- // sequences of arr for (vector<int> x : L) if (x.size() > max.size()) max = x; // max will contain LIS printLIS(max);} // Driver functionint main(){ int arr[] = { 3, 2, 6, 4, 5, 1 }; int n = sizeof(arr) / sizeof(arr[0]); // construct and print LIS of arr constructPrintLIS(arr, n); return 0;}
// Java program for// the above approach // Dynamic Programming// solution to conLongest// Increasing Subsequenceimport java.util.*;class GFG{ // Utility function to print LISstatic void printLIS(Vector<Integer> arr){ for (int x : arr) System.out.print(x + " "); System.out.println();} // Function to conand print// Longest Increasing Subsequencestatic void constructPrintLIS(int arr[], int n){ // L[i] - The longest increasing // sub-sequence ends with arr[i] Vector<Integer> L[] = new Vector[n]; for (int i = 0; i < L.length; i++) L[i] = new Vector<Integer>(); // L[0] is equal to arr[0] L[0].add(arr[0]); // Start from index 1 for (int i = 1; i < n; i++) { // Do for every j less than i for (int j = 0; j < i; j++) { //L[i] = {Max(L[j])} + arr[i] // where j < i and arr[j] < arr[i] if ((arr[i] > arr[j]) && (L[i].size() < L[j].size() + 1)) L[i] = (Vector<Integer>) L[j].clone(); //deep copy } // L[i] ends with arr[i] L[i].add(arr[i]); } // L[i] now stores increasing sub-sequence of // arr[0..i] that ends with arr[i] Vector<Integer> max = L[0]; // LIS will be max of all increasing sub- // sequences of arr for (Vector<Integer> x : L) if (x.size() > max.size()) max = x; // max will contain LIS printLIS(max);} // Driver functionpublic static void main(String[] args){ int arr[] = {3, 2, 4, 5, 1}; int n = arr.length; // print LIS of arr constructPrintLIS(arr, n);}} // This code is contributed by gauravrajput1
# Dynamic Programming solution to construct Longest# Increasing Subsequence # Utility function to print LISdef printLIS(arr: list): for x in arr: print(x, end=" ") print() # Function to construct and print Longest Increasing# Subsequencedef constructPrintLIS(arr: list, n: int): # L[i] - The longest increasing sub-sequence # ends with arr[i] l = [[] for i in range(n)] # L[0] is equal to arr[0] l[0].append(arr[0]) # start from index 1 for i in range(1, n): # do for every j less than i for j in range(i): # L[i] = {Max(L[j])} + arr[i] # where j < i and arr[j] < arr[i] if arr[i] > arr[j] and (len(l[i]) < len(l[j]) + 1): l[i] = l[j].copy() # L[i] ends with arr[i] l[i].append(arr[i]) # L[i] now stores increasing sub-sequence of # arr[0..i] that ends with arr[i] maxx = l[0] # LIS will be max of all increasing sub- # sequences of arr for x in l: if len(x) > len(maxx): maxx = x # max will contain LIS printLIS(maxx) # Driver Codeif __name__ == "__main__": arr = [3, 2, 6, 4, 5, 1] n = len(arr) # construct and print LIS of arr constructPrintLIS(arr, n) # This code is contributed by# sanjeev2552
// Dynamic Programming solution to construct Longest// Increasing Subsequenceusing System;using System.Collections.Generic;class GFG{ // Utility function to print LIS static void printLIS(List<int> arr) { foreach(int x in arr) { Console.Write(x + " "); } Console.WriteLine(); } // Function to construct and print Longest Increasing // Subsequence static void constructPrintLIS(int[] arr, int n) { // L[i] - The longest increasing sub-sequence // ends with arr[i] List<List<int>> L = new List<List<int>>(); for(int i = 0; i < n; i++) { L.Add(new List<int>()); } // L[0] is equal to arr[0] L[0].Add(arr[0]); // start from index 1 for (int i = 1; i < n; i++) { // do for every j less than i for (int j = 0; j < i; j++) { /* L[i] = {Max(L[j])} + arr[i] where j < i and arr[j] < arr[i] */ if ((arr[i] > arr[j]) && (L[i].Count < L[j].Count + 1)) L[i] = L[j]; } // L[i] ends with arr[i] L[i].Add(arr[i]); } // L[i] now stores increasing sub-sequence of // arr[0..i] that ends with arr[i] List<int> max = L[0]; // LIS will be max of all increasing sub- // sequences of arr foreach(List<int> x in L) { if (x.Count > max.Count) { max = x; } } // max will contain LIS printLIS(max); } // Driver code static void Main() { int[] arr = { 3, 2, 4, 5, 1 }; int n = arr.Length; // construct and print LIS of arr constructPrintLIS(arr, n); }} // This code is contributed by divyesh072019
Output:
2 4 5
Note that the time complexity of the above Dynamic Programming (DP) solution is O(n^2) and there is a O(n Log n) non-DP solution for the LIS problem. See below post for O(n Log n) solution.
Construction of Longest Monotonically Increasing Subsequence (N log N)
This article is contributed by Aditya Goel. 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.
AbdulMajeed1
sanjeev2552
29AjayKumar
GauravRajput1
divyesh072019
srivastavaharshit848
deepak_bansal_dk
shinjanpatra
LIS
subsequence
Dynamic Programming
Dynamic Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
BellmanβFord Algorithm | DP-23
Floyd Warshall Algorithm | DP-16
Matrix Chain Multiplication | DP-8
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Edit Distance | DP-5
Overlapping Subproblems Property in Dynamic Programming | DP-1
Efficient program to print all prime factors of a given number
Find minimum number of coins that make a given value
Minimum number of jumps to reach end
Tabulation vs Memoization
|
[
{
"code": null,
"e": 24924,
"s": 24896,
"text": "\n25 Apr, 2022"
},
{
"code": null,
"e": 24936,
"s": 24924,
"text": "Java code: "
},
{
"code": null,
"e": 25128,
"s": 24936,
"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."
},
{
"code": null,
"e": 25241,
"s": 25128,
"text": "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}."
},
{
"code": null,
"e": 25245,
"s": 25241,
"text": "C++"
},
{
"code": null,
"e": 25250,
"s": 25245,
"text": "Java"
},
{
"code": null,
"e": 25258,
"s": 25250,
"text": "Python3"
},
{
"code": null,
"e": 25261,
"s": 25258,
"text": "C#"
},
{
"code": null,
"e": 25272,
"s": 25261,
"text": "Javascript"
},
{
"code": "#include <bits/stdc++.h>using namespace std; void LIS(int a[], int n){ vector<int> list; vector<int> longestlist; // Highest count int hc = 0; // Current max int cm; for(int i = 0; i < n; i++) { cm = INT_MIN; for(int j = i; j < n; j++) { if (a[j] > cm) { list.push_back(a[j]); cm = a[j]; } } // Compare previous highest subsequence if (hc < list.size()) { hc = list.size(); for(int k = 0; k < list.size(); k++) { longestlist.push_back(list[k]); } } list.clear(); } for(int i = 0; i < longestlist.size(); i++) { cout << longestlist[i] << ' '; } cout << endl; cout << \"length of longestlist is \" << hc;} // Driver codeint main(){ int a[] = { 10, 22, 9, 33, 21, 50, 41, 60, 80 }; int n = sizeof(a) / sizeof(a[0]); LIS(a, n); return 0;} // This code is contributed by Harshit Srivastava",
"e": 26337,
"s": 25272,
"text": null
},
{
"code": "package BIT; import java.util.ArrayList;import java.util.Iterator; public class LongestIncreasingSubsequence { public static void main(String[] args) {// int array[] = {10, 22, 9, 33, 21, 50, 41, 60, 80};// int array[] = {10, 2, 9, 3, 5, 4, 6, 8}; int array[] = {10, 9, 8, 6, 5, 4}; ArrayList list = new ArrayList(); ArrayList longestList = new ArrayList(); int currentMax; int highestCount = 0; for(int i = 0; i < array.length;i++) { currentMax = Integer.MIN_VALUE; for(int j = i;j < array.length; j++) { if(array[j] > currentMax) { list.add(array[j]); currentMax = array[j]; } } //Compare previous highest subsequence if(highestCount < list.size()) { highestCount = list.size(); longestList = new ArrayList(list); } list.clear(); } System.out.println(); //Print list Iterator itr = longestList.iterator(); System.out.println(\"The Longest subsequence\"); while(itr.hasNext()) { System.out.print(itr.next() + \" \"); } System.out.println(); System.out.println(\"Length of LIS: \" + highestCount); } }",
"e": 27724,
"s": 26337,
"text": null
},
{
"code": "import sys def LIS(a, n): list = [] longestlist = [] # Highest count hc = 0 # Current max for i in range(n): cm = -sys.maxsize -1 for j in range(i,n): if (a[j] > cm): list.append(a[j]) cm = a[j] # Compare previous highest subsequence if (hc < len(list)): hc = len(list) for k in range(len(list)): longestlist.append(list[k]) list = [] for i in range(len(longestlist)): print(longestlist[i] ,end = ' ') print() print(\"length of longestlist is \" + str(hc)) # Driver code a = [ 10, 22, 9, 33, 21, 50, 41, 60, 80 ]n = len(a)LIS(a, n) # This code is contributed by shinjanpatra",
"e": 28467,
"s": 27724,
"text": null
},
{
"code": "using System;using System.Collections.Generic; class longestIncreasingSubsequence{ public static void Main(String[] args) { int []array = {10, 22, 9, 33, 21, 50, 41, 60, 80}; // int []array = {10, 2, 9, 3, 5, 4, 6, 8}; //int []array = {10, 9, 8, 6, 5, 4}; List<int> list = new List<int>(); List<int> longestList = new List<int>(); int currentMax; int highestCount = 0; for(int i = 0; i < array.Length;i++) { currentMax = int.MinValue; for(int j = i;j < array.Length; j++) { if(array[j] > currentMax) { list.Add(array[j]); currentMax = array[j]; } } // Compare previous highest subsequence if(highestCount < list.Count) { highestCount = list.Count; longestList = new List<int>(list); } list.Clear(); } Console.WriteLine(); // Print list Console.WriteLine(\"The longest subsequence\"); foreach(int itr in longestList) { Console.Write(itr + \" \"); } Console.WriteLine(); Console.WriteLine(\"Length of LIS: \" + highestCount); }} // This code is contributed by 29AjayKumar",
"e": 29811,
"s": 28467,
"text": null
},
{
"code": "<script>function LIS(a, n){ let list = []; let longestlist = []; // Highest count let hc = 0; // Current max let cm; for(let i = 0; i < n; i++) { cm = Number.MIN_VALUE; for(let j = i; j < n; j++) { if (a[j] > cm) { list.push(a[j]); cm = a[j]; } } // Compare previous highest subsequence if (hc < list.length) { hc = list.length; for(let k = 0; k < list.length; k++) { longestlist.push(list[k]); } } list = []; } for(let i = 0; i < longestlist.length; i++) { document.write(longestlist[i] + ' '); } document.write(\"</br>\") document.write(\"length of longestlist is \" + hc);} // Driver code let a = [ 10, 22, 9, 33, 21, 50, 41, 60, 80 ];let n = a.length;LIS(a, n); // This code is contributed by shinjanpatra</script>",
"e": 30780,
"s": 29811,
"text": null
},
{
"code": null,
"e": 30972,
"s": 30780,
"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."
},
{
"code": null,
"e": 30984,
"s": 30972,
"text": "Examples: "
},
{
"code": null,
"e": 31118,
"s": 30984,
"text": "Input: [10, 22, 9, 33, 21, 50, 41, 60, 80]\nOutput: [10, 22, 33, 50, 60, 80] \nOR [10 22 33 41 60 80] or any other LIS of same length."
},
{
"code": null,
"e": 31583,
"s": 31118,
"text": "In the previous post, we have discussed The Longest Increasing Subsequence problem. However, the post only covered code related to the querying size of LIS, but not the construction of LIS. In this post, we will discuss how to print LIS using a similar DP solution discussed earlier.Let arr[0..n-1] be the input array. We define vector L such that L[i] is itself is a vector that stores LIS of arr that ends with arr[i]. For example, for array [3, 2, 6, 4, 5, 1], "
},
{
"code": null,
"e": 31639,
"s": 31583,
"text": "L[0]: 3\nL[1]: 2\nL[2]: 2 6\nL[3]: 2 4\nL[4]: 2 4 5\nL[5]: 1"
},
{
"code": null,
"e": 31701,
"s": 31639,
"text": "Therefore, for index i, L[i] can be recursively written as β "
},
{
"code": null,
"e": 31823,
"s": 31701,
"text": "L[0] = {arr[O]}\nL[i] = {Max(L[j])} + arr[i] \nwhere j < i and arr[j] < arr[i] and if there is no such j then L[i] = arr[i]"
},
{
"code": null,
"e": 31872,
"s": 31823,
"text": "Below is the implementation of the above idea β "
},
{
"code": null,
"e": 31876,
"s": 31872,
"text": "C++"
},
{
"code": null,
"e": 31881,
"s": 31876,
"text": "Java"
},
{
"code": null,
"e": 31889,
"s": 31881,
"text": "Python3"
},
{
"code": null,
"e": 31892,
"s": 31889,
"text": "C#"
},
{
"code": "/* Dynamic Programming solution to construct Longest Increasing Subsequence */#include <iostream>#include <vector>using namespace std; // Utility function to print LISvoid printLIS(vector<int>& arr){ for (int x : arr) cout << x << \" \"; cout << endl;} // Function to construct and print Longest Increasing// Subsequencevoid constructPrintLIS(int arr[], int n){ // L[i] - The longest increasing sub-sequence // ends with arr[i] vector<vector<int> > L(n); // L[0] is equal to arr[0] L[0].push_back(arr[0]); // start from index 1 for (int i = 1; i < n; i++) { // do for every j less than i for (int j = 0; j < i; j++) { /* L[i] = {Max(L[j])} + arr[i] where j < i and arr[j] < arr[i] */ if ((arr[i] > arr[j]) && (L[i].size() < L[j].size() + 1)) L[i] = L[j]; } // L[i] ends with arr[i] L[i].push_back(arr[i]); } // L[i] now stores increasing sub-sequence of // arr[0..i] that ends with arr[i] vector<int> max = L[0]; // LIS will be max of all increasing sub- // sequences of arr for (vector<int> x : L) if (x.size() > max.size()) max = x; // max will contain LIS printLIS(max);} // Driver functionint main(){ int arr[] = { 3, 2, 6, 4, 5, 1 }; int n = sizeof(arr) / sizeof(arr[0]); // construct and print LIS of arr constructPrintLIS(arr, n); return 0;}",
"e": 33355,
"s": 31892,
"text": null
},
{
"code": "// Java program for// the above approach // Dynamic Programming// solution to conLongest// Increasing Subsequenceimport java.util.*;class GFG{ // Utility function to print LISstatic void printLIS(Vector<Integer> arr){ for (int x : arr) System.out.print(x + \" \"); System.out.println();} // Function to conand print// Longest Increasing Subsequencestatic void constructPrintLIS(int arr[], int n){ // L[i] - The longest increasing // sub-sequence ends with arr[i] Vector<Integer> L[] = new Vector[n]; for (int i = 0; i < L.length; i++) L[i] = new Vector<Integer>(); // L[0] is equal to arr[0] L[0].add(arr[0]); // Start from index 1 for (int i = 1; i < n; i++) { // Do for every j less than i for (int j = 0; j < i; j++) { //L[i] = {Max(L[j])} + arr[i] // where j < i and arr[j] < arr[i] if ((arr[i] > arr[j]) && (L[i].size() < L[j].size() + 1)) L[i] = (Vector<Integer>) L[j].clone(); //deep copy } // L[i] ends with arr[i] L[i].add(arr[i]); } // L[i] now stores increasing sub-sequence of // arr[0..i] that ends with arr[i] Vector<Integer> max = L[0]; // LIS will be max of all increasing sub- // sequences of arr for (Vector<Integer> x : L) if (x.size() > max.size()) max = x; // max will contain LIS printLIS(max);} // Driver functionpublic static void main(String[] args){ int arr[] = {3, 2, 4, 5, 1}; int n = arr.length; // print LIS of arr constructPrintLIS(arr, n);}} // This code is contributed by gauravrajput1",
"e": 34900,
"s": 33355,
"text": null
},
{
"code": "# Dynamic Programming solution to construct Longest# Increasing Subsequence # Utility function to print LISdef printLIS(arr: list): for x in arr: print(x, end=\" \") print() # Function to construct and print Longest Increasing# Subsequencedef constructPrintLIS(arr: list, n: int): # L[i] - The longest increasing sub-sequence # ends with arr[i] l = [[] for i in range(n)] # L[0] is equal to arr[0] l[0].append(arr[0]) # start from index 1 for i in range(1, n): # do for every j less than i for j in range(i): # L[i] = {Max(L[j])} + arr[i] # where j < i and arr[j] < arr[i] if arr[i] > arr[j] and (len(l[i]) < len(l[j]) + 1): l[i] = l[j].copy() # L[i] ends with arr[i] l[i].append(arr[i]) # L[i] now stores increasing sub-sequence of # arr[0..i] that ends with arr[i] maxx = l[0] # LIS will be max of all increasing sub- # sequences of arr for x in l: if len(x) > len(maxx): maxx = x # max will contain LIS printLIS(maxx) # Driver Codeif __name__ == \"__main__\": arr = [3, 2, 6, 4, 5, 1] n = len(arr) # construct and print LIS of arr constructPrintLIS(arr, n) # This code is contributed by# sanjeev2552",
"e": 36174,
"s": 34900,
"text": null
},
{
"code": "// Dynamic Programming solution to construct Longest// Increasing Subsequenceusing System;using System.Collections.Generic;class GFG{ // Utility function to print LIS static void printLIS(List<int> arr) { foreach(int x in arr) { Console.Write(x + \" \"); } Console.WriteLine(); } // Function to construct and print Longest Increasing // Subsequence static void constructPrintLIS(int[] arr, int n) { // L[i] - The longest increasing sub-sequence // ends with arr[i] List<List<int>> L = new List<List<int>>(); for(int i = 0; i < n; i++) { L.Add(new List<int>()); } // L[0] is equal to arr[0] L[0].Add(arr[0]); // start from index 1 for (int i = 1; i < n; i++) { // do for every j less than i for (int j = 0; j < i; j++) { /* L[i] = {Max(L[j])} + arr[i] where j < i and arr[j] < arr[i] */ if ((arr[i] > arr[j]) && (L[i].Count < L[j].Count + 1)) L[i] = L[j]; } // L[i] ends with arr[i] L[i].Add(arr[i]); } // L[i] now stores increasing sub-sequence of // arr[0..i] that ends with arr[i] List<int> max = L[0]; // LIS will be max of all increasing sub- // sequences of arr foreach(List<int> x in L) { if (x.Count > max.Count) { max = x; } } // max will contain LIS printLIS(max); } // Driver code static void Main() { int[] arr = { 3, 2, 4, 5, 1 }; int n = arr.Length; // construct and print LIS of arr constructPrintLIS(arr, n); }} // This code is contributed by divyesh072019",
"e": 38026,
"s": 36174,
"text": null
},
{
"code": null,
"e": 38035,
"s": 38026,
"text": "Output: "
},
{
"code": null,
"e": 38041,
"s": 38035,
"text": "2 4 5"
},
{
"code": null,
"e": 38231,
"s": 38041,
"text": "Note that the time complexity of the above Dynamic Programming (DP) solution is O(n^2) and there is a O(n Log n) non-DP solution for the LIS problem. See below post for O(n Log n) solution."
},
{
"code": null,
"e": 38302,
"s": 38231,
"text": "Construction of Longest Monotonically Increasing Subsequence (N log N)"
},
{
"code": null,
"e": 38721,
"s": 38302,
"text": "This article is contributed by Aditya Goel. 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": 38734,
"s": 38721,
"text": "AbdulMajeed1"
},
{
"code": null,
"e": 38746,
"s": 38734,
"text": "sanjeev2552"
},
{
"code": null,
"e": 38758,
"s": 38746,
"text": "29AjayKumar"
},
{
"code": null,
"e": 38772,
"s": 38758,
"text": "GauravRajput1"
},
{
"code": null,
"e": 38786,
"s": 38772,
"text": "divyesh072019"
},
{
"code": null,
"e": 38807,
"s": 38786,
"text": "srivastavaharshit848"
},
{
"code": null,
"e": 38824,
"s": 38807,
"text": "deepak_bansal_dk"
},
{
"code": null,
"e": 38837,
"s": 38824,
"text": "shinjanpatra"
},
{
"code": null,
"e": 38841,
"s": 38837,
"text": "LIS"
},
{
"code": null,
"e": 38853,
"s": 38841,
"text": "subsequence"
},
{
"code": null,
"e": 38873,
"s": 38853,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 38893,
"s": 38873,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 38991,
"s": 38893,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 39022,
"s": 38991,
"text": "BellmanβFord Algorithm | DP-23"
},
{
"code": null,
"e": 39055,
"s": 39022,
"text": "Floyd Warshall Algorithm | DP-16"
},
{
"code": null,
"e": 39090,
"s": 39055,
"text": "Matrix Chain Multiplication | DP-8"
},
{
"code": null,
"e": 39158,
"s": 39090,
"text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)"
},
{
"code": null,
"e": 39179,
"s": 39158,
"text": "Edit Distance | DP-5"
},
{
"code": null,
"e": 39242,
"s": 39179,
"text": "Overlapping Subproblems Property in Dynamic Programming | DP-1"
},
{
"code": null,
"e": 39305,
"s": 39242,
"text": "Efficient program to print all prime factors of a given number"
},
{
"code": null,
"e": 39358,
"s": 39305,
"text": "Find minimum number of coins that make a given value"
},
{
"code": null,
"e": 39395,
"s": 39358,
"text": "Minimum number of jumps to reach end"
}
] |
export - Unix, Linux Command
|
export - Set export attribute for shell variables.
export [-fn] [name[=value] ...] or export -p
export- command is one of the bash shell BUILTINS commands, which means it is part of your shell.
The export command is fairly simple to use as it has straightforward syntax with only three available command options.
In general, the export command marks an environment variable to be exported with any newly forked child processes and thus it allows a
child process to inherit all marked variables.
Example-1:
To view all the exported variables.
$ export
output:
declare -x EDITOR="/usr/bin/vim"declare -x HOME="/home/ubuntu"declare -x LANG="en_US.UTF-8"declare -x LESSCLOSE="/usr/bin/lesspipe %s %s"declare -x LESSOPEN="| /usr/bin/lesspipe %s"declare -x LOGNAME="ubuntu"declare -x LS_COLORS="rs=0:di=01;34:ln=01;36:mh=00:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01:su=37;41:sg=30;43:ca=30;41:tw=30;42:ow=34;42:st=37;44:ex=01;32:*.tar=01;31:*.tgz=01;31:*.arj=01;31:*.taz=01;31:*.lzh=01;31:*.lzma=01;31:*.tlz=01;31:*.txz=01;31:*.zip=01;31:*.z=01;31:*.Z=01;31:*.dz=01;31:*.gz=01;31:*.lz=01;31:*.xz=01;31:*.bz2=01;31:*.bz=01;31:*.tbz=01;31:*.tbz2=01;31:*.tz=01;31:*.deb=01;31:*.rpm=01;31:*.jar=01;31:*.war=01;31:*.ear=01;31:*.sar=01;31:*.rar=01;31:*.ace=01;31:*.zoo=01;31:*.cpio=01;31:*.7z=01;31:*.rz=01;31:*.jpg=01;35:*.jpeg=01;35:*.gif=01;35:*.bmp=01;35:*.pbm=01;35:*.pgm=01;35:*.ppm=01;35:*.tga=01;35:*.xbm=01;35:*.xpm=01;35:*.tif=01;35:*.tiff=01;35:*.png=01;35:*.svg=01;35:*.svgz=01;35:*.mng=01;35:*.pcx=01;35:*.mov=01;35:*.mpg=01;35:*.mpeg=01;35:*.m2v=01;35:*.mkv=01;35:*.webm=01;35:*.ogm=01;35:*.mp4=01;35:*.m4v=01;35:*.mp4v=01;35:*.vob=01;35:*.qt=01;35:*.nuv=01;35:*.wmv=01;35:*.asf=01;35:*.rm=01;35:*.rmvb=01;35:*.flc=01;35:*.avi=01;35:*.fli=01;35:*.flv=01;35:*.gl=01;35:*.dl=01;35:*.xcf=01;35:*.xwd=01;35:*.yuv=01;35:*.cgm=01;35:*.emf=01;35:*.axv=01;35:*.anx=01;35:*.ogv=01;35:*.ogx=01;35:*.aac=00;36:*.au=00;36:*.flac=00;36:*.mid=00;36:*.midi=00;36:*.mka=00;36:*.mp3=00;36:*.mpc=00;36:*.ogg=00;36:*.ra=00;36:*.wav=00;36:*.axa=00;36:*.oga=00;36:*.spx=00;36:*.xspf=00;36:"declare -x MAIL="/var/mail/ubuntu"declare -x OLDPWDdeclare -x PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games"declare -x PWD="/home/ubuntu"declare -x SHELL="/bin/bash"declare -x SHLVL="1"declare -x SSH_CLIENT="192.168.134.1 56073 22"declare -x SSH_CONNECTION="192.168.134.1 56073 192.168.134.128 22"declare -x SSH_TTY="/dev/pts/0"declare -x TERM="xterm"declare -x USER="ubuntu"declare -x XDG_RUNTIME_DIR="/run/user/1000"declare -x XDG_SESSION_ID="1"
Example-2:
user can also use -p option to view all exported variables on current shell.
$ export -p
output:
declare -x EDITOR="/usr/bin/vim"declare -x HOME="/home/ubuntu"declare -x LANG="en_US.UTF-8"declare -x LESSCLOSE="/usr/bin/lesspipe %s %s"declare -x LESSOPEN="| /usr/bin/lesspipe %s"declare -x LOGNAME="ubuntu"declare -x LS_COLORS="rs=0:di=01;34:ln=01;36:mh=00:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01:su=37;41:sg=30;43:ca=30;41:tw=30;42:ow=34;42:st=37;44:ex=01;32:*.tar=01;31:*.tgz=01;31:*.arj=01;31:*.taz=01;31:*.lzh=01;31:*.lzma=01;31:*.tlz=01;31:*.txz=01;31:*.zip=01;31:*.z=01;31:*.Z=01;31:*.dz=01;31:*.gz=01;31:*.lz=01;31:*.xz=01;31:*.bz2=01;31:*.bz=01;31:*.tbz=01;31:*.tbz2=01;31:*.tz=01;31:*.deb=01;31:*.rpm=01;31:*.jar=01;31:*.war=01;31:*.ear=01;31:*.sar=01;31:*.rar=01;31:*.ace=01;31:*.zoo=01;31:*.cpio=01;31:*.7z=01;31:*.rz=01;31:*.jpg=01;35:*.jpeg=01;35:*.gif=01;35:*.bmp=01;35:*.pbm=01;35:*.pgm=01;35:*.ppm=01;35:*.tga=01;35:*.xbm=01;35:*.xpm=01;35:*.tif=01;35:*.tiff=01;35:*.png=01;35:*.svg=01;35:*.svgz=01;35:*.mng=01;35:*.pcx=01;35:*.mov=01;35:*.mpg=01;35:*.mpeg=01;35:*.m2v=01;35:*.mkv=01;35:*.webm=01;35:*.ogm=01;35:*.mp4=01;35:*.m4v=01;35:*.mp4v=01;35:*.vob=01;35:*.qt=01;35:*.nuv=01;35:*.wmv=01;35:*.asf=01;35:*.rm=01;35:*.rmvb=01;35:*.flc=01;35:*.avi=01;35:*.fli=01;35:*.flv=01;35:*.gl=01;35:*.dl=01;35:*.xcf=01;35:*.xwd=01;35:*.yuv=01;35:*.cgm=01;35:*.emf=01;35:*.axv=01;35:*.anx=01;35:*.ogv=01;35:*.ogx=01;35:*.aac=00;36:*.au=00;36:*.flac=00;36:*.mid=00;36:*.midi=00;36:*.mka=00;36:*.mp3=00;36:*.mpc=00;36:*.ogg=00;36:*.ra=00;36:*.wav=00;36:*.axa=00;36:*.oga=00;36:*.spx=00;36:*.xspf=00;36:"declare -x MAIL="/var/mail/ubuntu"declare -x OLDPWDdeclare -x PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games"declare -x PWD="/home/ubuntu"declare -x SHELL="/bin/bash"declare -x SHLVL="1"declare -x SSH_CLIENT="192.168.134.1 56073 22"declare -x SSH_CONNECTION="192.168.134.1 56073 192.168.134.128 22"declare -x SSH_TTY="/dev/pts/0"declare -x TERM="xterm"declare -x USER="ubuntu"declare -x XDG_RUNTIME_DIR="/run/user/1000"declare -x XDG_SESSION_ID="1"
Example-3:
To set vim as a text editor
$ export EDITOR=/usr/bin/vim
output:no ouput will be seen on screen , to see exported variable grep from exported ones.
$ export | grep EDITORdeclare -x EDITOR="/usr/bin/vim"
Example-4:
To set colorful prompt
$ export PS1='\[\e[1;32m\][\u@\h \W]\$\[\e[0m\] '
output:
the colour of prompt will change to green.
Example-5:
To Set JAVA_HOME:
$ export JAVA_HOME=/usr/local/jdk
output:
no ouput will be seen on screen , to see exported variable grep from exported ones.
$ export | grep JAVA_HOMEdeclare -x JAVA_HOME=/usr/local/jdk"
Example-6:
To export shell function:
$ name () { echo "tutorialspoint"; }
$ export -f printname
output:
$ nametutorialspoint
Example-7:
To remove names from exported list, use -n option
$ export -n EDITOR
note: in Example-3 we have set EDITOR=/usr/bin/vim, and have seen it in exported list.
output:
$ export | grep EDITOR
note: no output after grepping all exported varables, as EDITOR exported variable is removed from exported list.
129 Lectures
23 hours
Eduonix Learning Solutions
5 Lectures
4.5 hours
Frahaan Hussain
35 Lectures
2 hours
Pradeep D
41 Lectures
2.5 hours
Musab Zayadneh
46 Lectures
4 hours
GUHARAJANM
6 Lectures
4 hours
Uplatz
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 10628,
"s": 10577,
"text": "export - Set export attribute for shell variables."
},
{
"code": null,
"e": 10673,
"s": 10628,
"text": "export [-fn] [name[=value] ...] or export -p"
},
{
"code": null,
"e": 11075,
"s": 10673,
"text": "export- command is one of the bash shell BUILTINS commands, which means it is part of your shell. \nThe export command is fairly simple to use as it has straightforward syntax with only three available command options. \nIn general, the export command marks an environment variable to be exported with any newly forked child processes and thus it allows a\n child process to inherit all marked variables."
},
{
"code": null,
"e": 11086,
"s": 11075,
"text": "Example-1:"
},
{
"code": null,
"e": 11122,
"s": 11086,
"text": "To view all the exported variables."
},
{
"code": null,
"e": 11131,
"s": 11122,
"text": "$ export"
},
{
"code": null,
"e": 11139,
"s": 11131,
"text": "output:"
},
{
"code": null,
"e": 13169,
"s": 11139,
"text": "declare -x EDITOR=\"/usr/bin/vim\"declare -x HOME=\"/home/ubuntu\"declare -x LANG=\"en_US.UTF-8\"declare -x LESSCLOSE=\"/usr/bin/lesspipe %s %s\"declare -x LESSOPEN=\"| /usr/bin/lesspipe %s\"declare -x LOGNAME=\"ubuntu\"declare -x LS_COLORS=\"rs=0:di=01;34:ln=01;36:mh=00:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01:su=37;41:sg=30;43:ca=30;41:tw=30;42:ow=34;42:st=37;44:ex=01;32:*.tar=01;31:*.tgz=01;31:*.arj=01;31:*.taz=01;31:*.lzh=01;31:*.lzma=01;31:*.tlz=01;31:*.txz=01;31:*.zip=01;31:*.z=01;31:*.Z=01;31:*.dz=01;31:*.gz=01;31:*.lz=01;31:*.xz=01;31:*.bz2=01;31:*.bz=01;31:*.tbz=01;31:*.tbz2=01;31:*.tz=01;31:*.deb=01;31:*.rpm=01;31:*.jar=01;31:*.war=01;31:*.ear=01;31:*.sar=01;31:*.rar=01;31:*.ace=01;31:*.zoo=01;31:*.cpio=01;31:*.7z=01;31:*.rz=01;31:*.jpg=01;35:*.jpeg=01;35:*.gif=01;35:*.bmp=01;35:*.pbm=01;35:*.pgm=01;35:*.ppm=01;35:*.tga=01;35:*.xbm=01;35:*.xpm=01;35:*.tif=01;35:*.tiff=01;35:*.png=01;35:*.svg=01;35:*.svgz=01;35:*.mng=01;35:*.pcx=01;35:*.mov=01;35:*.mpg=01;35:*.mpeg=01;35:*.m2v=01;35:*.mkv=01;35:*.webm=01;35:*.ogm=01;35:*.mp4=01;35:*.m4v=01;35:*.mp4v=01;35:*.vob=01;35:*.qt=01;35:*.nuv=01;35:*.wmv=01;35:*.asf=01;35:*.rm=01;35:*.rmvb=01;35:*.flc=01;35:*.avi=01;35:*.fli=01;35:*.flv=01;35:*.gl=01;35:*.dl=01;35:*.xcf=01;35:*.xwd=01;35:*.yuv=01;35:*.cgm=01;35:*.emf=01;35:*.axv=01;35:*.anx=01;35:*.ogv=01;35:*.ogx=01;35:*.aac=00;36:*.au=00;36:*.flac=00;36:*.mid=00;36:*.midi=00;36:*.mka=00;36:*.mp3=00;36:*.mpc=00;36:*.ogg=00;36:*.ra=00;36:*.wav=00;36:*.axa=00;36:*.oga=00;36:*.spx=00;36:*.xspf=00;36:\"declare -x MAIL=\"/var/mail/ubuntu\"declare -x OLDPWDdeclare -x PATH=\"/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games\"declare -x PWD=\"/home/ubuntu\"declare -x SHELL=\"/bin/bash\"declare -x SHLVL=\"1\"declare -x SSH_CLIENT=\"192.168.134.1 56073 22\"declare -x SSH_CONNECTION=\"192.168.134.1 56073 192.168.134.128 22\"declare -x SSH_TTY=\"/dev/pts/0\"declare -x TERM=\"xterm\"declare -x USER=\"ubuntu\"declare -x XDG_RUNTIME_DIR=\"/run/user/1000\"declare -x XDG_SESSION_ID=\"1\""
},
{
"code": null,
"e": 13180,
"s": 13169,
"text": "Example-2:"
},
{
"code": null,
"e": 13257,
"s": 13180,
"text": "user can also use -p option to view all exported variables on current shell."
},
{
"code": null,
"e": 13269,
"s": 13257,
"text": "$ export -p"
},
{
"code": null,
"e": 13277,
"s": 13269,
"text": "output:"
},
{
"code": null,
"e": 15307,
"s": 13277,
"text": "declare -x EDITOR=\"/usr/bin/vim\"declare -x HOME=\"/home/ubuntu\"declare -x LANG=\"en_US.UTF-8\"declare -x LESSCLOSE=\"/usr/bin/lesspipe %s %s\"declare -x LESSOPEN=\"| /usr/bin/lesspipe %s\"declare -x LOGNAME=\"ubuntu\"declare -x LS_COLORS=\"rs=0:di=01;34:ln=01;36:mh=00:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01:su=37;41:sg=30;43:ca=30;41:tw=30;42:ow=34;42:st=37;44:ex=01;32:*.tar=01;31:*.tgz=01;31:*.arj=01;31:*.taz=01;31:*.lzh=01;31:*.lzma=01;31:*.tlz=01;31:*.txz=01;31:*.zip=01;31:*.z=01;31:*.Z=01;31:*.dz=01;31:*.gz=01;31:*.lz=01;31:*.xz=01;31:*.bz2=01;31:*.bz=01;31:*.tbz=01;31:*.tbz2=01;31:*.tz=01;31:*.deb=01;31:*.rpm=01;31:*.jar=01;31:*.war=01;31:*.ear=01;31:*.sar=01;31:*.rar=01;31:*.ace=01;31:*.zoo=01;31:*.cpio=01;31:*.7z=01;31:*.rz=01;31:*.jpg=01;35:*.jpeg=01;35:*.gif=01;35:*.bmp=01;35:*.pbm=01;35:*.pgm=01;35:*.ppm=01;35:*.tga=01;35:*.xbm=01;35:*.xpm=01;35:*.tif=01;35:*.tiff=01;35:*.png=01;35:*.svg=01;35:*.svgz=01;35:*.mng=01;35:*.pcx=01;35:*.mov=01;35:*.mpg=01;35:*.mpeg=01;35:*.m2v=01;35:*.mkv=01;35:*.webm=01;35:*.ogm=01;35:*.mp4=01;35:*.m4v=01;35:*.mp4v=01;35:*.vob=01;35:*.qt=01;35:*.nuv=01;35:*.wmv=01;35:*.asf=01;35:*.rm=01;35:*.rmvb=01;35:*.flc=01;35:*.avi=01;35:*.fli=01;35:*.flv=01;35:*.gl=01;35:*.dl=01;35:*.xcf=01;35:*.xwd=01;35:*.yuv=01;35:*.cgm=01;35:*.emf=01;35:*.axv=01;35:*.anx=01;35:*.ogv=01;35:*.ogx=01;35:*.aac=00;36:*.au=00;36:*.flac=00;36:*.mid=00;36:*.midi=00;36:*.mka=00;36:*.mp3=00;36:*.mpc=00;36:*.ogg=00;36:*.ra=00;36:*.wav=00;36:*.axa=00;36:*.oga=00;36:*.spx=00;36:*.xspf=00;36:\"declare -x MAIL=\"/var/mail/ubuntu\"declare -x OLDPWDdeclare -x PATH=\"/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games\"declare -x PWD=\"/home/ubuntu\"declare -x SHELL=\"/bin/bash\"declare -x SHLVL=\"1\"declare -x SSH_CLIENT=\"192.168.134.1 56073 22\"declare -x SSH_CONNECTION=\"192.168.134.1 56073 192.168.134.128 22\"declare -x SSH_TTY=\"/dev/pts/0\"declare -x TERM=\"xterm\"declare -x USER=\"ubuntu\"declare -x XDG_RUNTIME_DIR=\"/run/user/1000\"declare -x XDG_SESSION_ID=\"1\""
},
{
"code": null,
"e": 15318,
"s": 15307,
"text": "Example-3:"
},
{
"code": null,
"e": 15346,
"s": 15318,
"text": "To set vim as a text editor"
},
{
"code": null,
"e": 15375,
"s": 15346,
"text": "$ export EDITOR=/usr/bin/vim"
},
{
"code": null,
"e": 15466,
"s": 15375,
"text": "output:no ouput will be seen on screen , to see exported variable grep from exported ones."
},
{
"code": null,
"e": 15521,
"s": 15466,
"text": "$ export | grep EDITORdeclare -x EDITOR=\"/usr/bin/vim\""
},
{
"code": null,
"e": 15532,
"s": 15521,
"text": "Example-4:"
},
{
"code": null,
"e": 15555,
"s": 15532,
"text": "To set colorful prompt"
},
{
"code": null,
"e": 15605,
"s": 15555,
"text": "$ export PS1='\\[\\e[1;32m\\][\\u@\\h \\W]\\$\\[\\e[0m\\] '"
},
{
"code": null,
"e": 15613,
"s": 15605,
"text": "output:"
},
{
"code": null,
"e": 15656,
"s": 15613,
"text": "the colour of prompt will change to green."
},
{
"code": null,
"e": 15667,
"s": 15656,
"text": "Example-5:"
},
{
"code": null,
"e": 15685,
"s": 15667,
"text": "To Set JAVA_HOME:"
},
{
"code": null,
"e": 15719,
"s": 15685,
"text": "$ export JAVA_HOME=/usr/local/jdk"
},
{
"code": null,
"e": 15727,
"s": 15719,
"text": "output:"
},
{
"code": null,
"e": 15811,
"s": 15727,
"text": "no ouput will be seen on screen , to see exported variable grep from exported ones."
},
{
"code": null,
"e": 15873,
"s": 15811,
"text": "$ export | grep JAVA_HOMEdeclare -x JAVA_HOME=/usr/local/jdk\""
},
{
"code": null,
"e": 15884,
"s": 15873,
"text": "Example-6:"
},
{
"code": null,
"e": 15910,
"s": 15884,
"text": "To export shell function:"
},
{
"code": null,
"e": 15947,
"s": 15910,
"text": "$ name () { echo \"tutorialspoint\"; }"
},
{
"code": null,
"e": 15969,
"s": 15947,
"text": "$ export -f printname"
},
{
"code": null,
"e": 15977,
"s": 15969,
"text": "output:"
},
{
"code": null,
"e": 15998,
"s": 15977,
"text": "$ nametutorialspoint"
},
{
"code": null,
"e": 16009,
"s": 15998,
"text": "Example-7:"
},
{
"code": null,
"e": 16059,
"s": 16009,
"text": "To remove names from exported list, use -n option"
},
{
"code": null,
"e": 16078,
"s": 16059,
"text": "$ export -n EDITOR"
},
{
"code": null,
"e": 16165,
"s": 16078,
"text": "note: in Example-3 we have set EDITOR=/usr/bin/vim, and have seen it in exported list."
},
{
"code": null,
"e": 16173,
"s": 16165,
"text": "output:"
},
{
"code": null,
"e": 16196,
"s": 16173,
"text": "$ export | grep EDITOR"
},
{
"code": null,
"e": 16309,
"s": 16196,
"text": "note: no output after grepping all exported varables, as EDITOR exported variable is removed from exported list."
},
{
"code": null,
"e": 16344,
"s": 16309,
"text": "\n 129 Lectures \n 23 hours \n"
},
{
"code": null,
"e": 16372,
"s": 16344,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 16406,
"s": 16372,
"text": "\n 5 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 16423,
"s": 16406,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 16456,
"s": 16423,
"text": "\n 35 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 16467,
"s": 16456,
"text": " Pradeep D"
},
{
"code": null,
"e": 16502,
"s": 16467,
"text": "\n 41 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 16518,
"s": 16502,
"text": " Musab Zayadneh"
},
{
"code": null,
"e": 16551,
"s": 16518,
"text": "\n 46 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 16563,
"s": 16551,
"text": " GUHARAJANM"
},
{
"code": null,
"e": 16595,
"s": 16563,
"text": "\n 6 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 16603,
"s": 16595,
"text": " Uplatz"
},
{
"code": null,
"e": 16610,
"s": 16603,
"text": " Print"
},
{
"code": null,
"e": 16621,
"s": 16610,
"text": " Add Notes"
}
] |
Tryit Editor v3.6 - Show Python
|
mydb = mysql.connector.connect(
host="localhost",
user="myusername",
password="mypassword",
database="mydatabase"
)
β
mycursor = mydb.cursor()
|
[
{
"code": null,
"e": 57,
"s": 25,
"text": "mydb = mysql.connector.connect("
},
{
"code": null,
"e": 77,
"s": 57,
"text": " host=\"localhost\","
},
{
"code": null,
"e": 98,
"s": 77,
"text": " user=\"myusername\","
},
{
"code": null,
"e": 123,
"s": 98,
"text": " password=\"mypassword\","
},
{
"code": null,
"e": 147,
"s": 123,
"text": " database=\"mydatabase\""
},
{
"code": null,
"e": 149,
"s": 147,
"text": ")"
},
{
"code": null,
"e": 151,
"s": 149,
"text": "β"
}
] |
Autowire by Constructor in Spring | Spring Autowiring Example
|
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
In this tutorial, we are going to learn about the Spring bean autowire by the constructor. In the previous tutorial, we had a discussion about bean autowire byType example.
Generally, if we want to inject the dependencies to a bean, we need to wire the dependencies explicitly by using the ref attribute as below:
<bean id="travelBean" class="Travel">
<property name="car" ref="carBean" />
</bean>
<bean id="carBean" class="Car">
<property name="carName" value="BMW"></property>
</bean>
By making use of the autowire mechanism in spring, we no need to wire the dependencies explicitly. Just by using the autowire strategies, spring will automatically injects the dependencies.
<bean id="travelBean" class="Travel" autowire="constructor">
</bean>
<bean id="carBean" class="Car">
<property name="carName" value="BMW"></property>
</bean>
Autowire by the constructor is one of the strategies in spring autowiring. In this strategy, the spring container verifies the property type in bean and bean class in the XML file are matched or not. If both were matched then the injection will happen, otherwise, the property will not be injected.
Note: In the case of autowire by a constructor, the Spring container injects the dependencies by using the constructor injection.
The only difference between autowire byType and constructor is: byType injects the dependencies by using setter injection and constructor injects the dependencies by using constructor injection.
Create a Travel Bean :
public class Travel {
private String name;
private Car car;
public Travel(Car car) {
this.car = car;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Car getCar() {
return car;
}
public void setCar(Car car) {
this.car = car;
}
}
Create a Car Bean :
public class Car {
private String carName;
public String getCarName() {
return carName;
}
public void setCarName(String carName) {
this.carName = carName;
}
}
Create spring configuration :
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<bean id="travelBean" class="Travel" autowire="constructor">
<property name="name" value="Kesineni" />
</bean>
<bean id="car" class="Car">
<property name="carName" value="BMW"></property>
</bean>
</beans>
Test the application :
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
public final class Main {
public static final void main(String[] args) {
BeanFactory factory = new XmlBeanFactory(new ClassPathResource("spring.xml"));
Travel travel = (Travel)factory.getBean("travelBean");
System.out.println("Travel Name: "+travel.getName());
System.out.println("Car Name : "+travel.getCar().getCarName());
}
}
Output :
Travel Name: Kesineni
Car Name : BMW
Spring Autowiring by Type
Spring autowiring
The complete example is available for download Spring-Autowiring-Constructor
Happy Learning π
Spring-Autowiring-Constructor
File size: 10 KB
Downloads: 697
Spring Bean Autowire ByName Example
Spring Bean Autowire ByType Example
Types of Spring Bean Scopes Example
@Autowired,@Qualifier,@Value annotations in Spring
@Qualifier annotation example in Spring
Dependency Injection (IoC) in spring with Example
Spring Java Configuration Example
What is spring circular dependency problem ?
Spring Collection Map Dependency Example
Spring Collection Dependency List Example
What is Java Constructor and Types of Constructors
BeanFactory Example in Spring
Spring JdbcTemplate CRUD Application
Spring AOP Around Advice Example XML
spring expression language example
Spring Bean Autowire ByName Example
Spring Bean Autowire ByType Example
Types of Spring Bean Scopes Example
@Autowired,@Qualifier,@Value annotations in Spring
@Qualifier annotation example in Spring
Dependency Injection (IoC) in spring with Example
Spring Java Configuration Example
What is spring circular dependency problem ?
Spring Collection Map Dependency Example
Spring Collection Dependency List Example
What is Java Constructor and Types of Constructors
BeanFactory Example in Spring
Spring JdbcTemplate CRUD Application
Spring AOP Around Advice Example XML
spring expression language example
|
[
{
"code": null,
"e": 158,
"s": 123,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 172,
"s": 158,
"text": "Java Examples"
},
{
"code": null,
"e": 183,
"s": 172,
"text": "C Examples"
},
{
"code": null,
"e": 195,
"s": 183,
"text": "C Tutorials"
},
{
"code": null,
"e": 199,
"s": 195,
"text": "aws"
},
{
"code": null,
"e": 234,
"s": 199,
"text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC"
},
{
"code": null,
"e": 245,
"s": 234,
"text": "EXCEPTIONS"
},
{
"code": null,
"e": 257,
"s": 245,
"text": "COLLECTIONS"
},
{
"code": null,
"e": 263,
"s": 257,
"text": "SWING"
},
{
"code": null,
"e": 268,
"s": 263,
"text": "JDBC"
},
{
"code": null,
"e": 275,
"s": 268,
"text": "JAVA 8"
},
{
"code": null,
"e": 282,
"s": 275,
"text": "SPRING"
},
{
"code": null,
"e": 294,
"s": 282,
"text": "SPRING BOOT"
},
{
"code": null,
"e": 304,
"s": 294,
"text": "HIBERNATE"
},
{
"code": null,
"e": 311,
"s": 304,
"text": "PYTHON"
},
{
"code": null,
"e": 315,
"s": 311,
"text": "PHP"
},
{
"code": null,
"e": 322,
"s": 315,
"text": "JQUERY"
},
{
"code": null,
"e": 357,
"s": 322,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 371,
"s": 357,
"text": "Java Examples"
},
{
"code": null,
"e": 382,
"s": 371,
"text": "C Examples"
},
{
"code": null,
"e": 394,
"s": 382,
"text": "C Tutorials"
},
{
"code": null,
"e": 398,
"s": 394,
"text": "aws"
},
{
"code": null,
"e": 571,
"s": 398,
"text": "In this tutorial, we are going to learn about the Spring bean autowire by the constructor. In the previous tutorial, we had a discussion about bean autowire byType example."
},
{
"code": null,
"e": 712,
"s": 571,
"text": "Generally, if we want to inject the dependencies to a bean, we need to wire the dependencies explicitly by using the ref attribute as below:"
},
{
"code": null,
"e": 889,
"s": 712,
"text": "<bean id=\"travelBean\" class=\"Travel\">\n <property name=\"car\" ref=\"carBean\" />\n</bean>\n<bean id=\"carBean\" class=\"Car\">\n <property name=\"carName\" value=\"BMW\"></property>\n</bean>"
},
{
"code": null,
"e": 1079,
"s": 889,
"text": "By making use of the autowire mechanism in spring, we no need to wire the dependencies explicitly. Just by using the autowire strategies, spring will automatically injects the dependencies."
},
{
"code": null,
"e": 1239,
"s": 1079,
"text": "<bean id=\"travelBean\" class=\"Travel\" autowire=\"constructor\">\n</bean>\n<bean id=\"carBean\" class=\"Car\">\n <property name=\"carName\" value=\"BMW\"></property>\n</bean>"
},
{
"code": null,
"e": 1538,
"s": 1239,
"text": "Autowire by the constructor is one of the strategies in spring autowiring. In this strategy, the spring container verifies the property type in bean and bean class in the XML file are matched or not. If both were matched then the injection will happen, otherwise, the property will not be injected."
},
{
"code": null,
"e": 1668,
"s": 1538,
"text": "Note: In the case of autowire by a constructor, the Spring container injects the dependencies by using the constructor injection."
},
{
"code": null,
"e": 1863,
"s": 1668,
"text": "The only difference between autowire byType and constructor is: byType injects the dependencies by using setter injection and constructor injects the dependencies by using constructor injection."
},
{
"code": null,
"e": 1886,
"s": 1863,
"text": "Create a Travel Bean :"
},
{
"code": null,
"e": 2265,
"s": 1886,
"text": "public class Travel {\n private String name;\n private Car car;\n\n public Travel(Car car) {\n this.car = car;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public Car getCar() {\n return car;\n }\n\n public void setCar(Car car) {\n this.car = car;\n }\n\n}"
},
{
"code": null,
"e": 2285,
"s": 2265,
"text": "Create a Car Bean :"
},
{
"code": null,
"e": 2483,
"s": 2285,
"text": "public class Car {\n private String carName;\n\n public String getCarName() {\n return carName;\n }\n\n public void setCarName(String carName) {\n this.carName = carName;\n }\n\n}"
},
{
"code": null,
"e": 2513,
"s": 2483,
"text": "Create spring configuration :"
},
{
"code": null,
"e": 3226,
"s": 2513,
"text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<beans xmlns=\"http://www.springframework.org/schema/beans\"\n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:context=\"http://www.springframework.org/schema/context\"\n xsi:schemaLocation=\"http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd\n http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd\">\n <bean id=\"travelBean\" class=\"Travel\" autowire=\"constructor\">\n <property name=\"name\" value=\"Kesineni\" />\n </bean>\n <bean id=\"car\" class=\"Car\">\n <property name=\"carName\" value=\"BMW\"></property>\n </bean>\n</beans>"
},
{
"code": null,
"e": 3249,
"s": 3226,
"text": "Test the application :"
},
{
"code": null,
"e": 3789,
"s": 3249,
"text": "import org.springframework.beans.factory.BeanFactory;\nimport org.springframework.beans.factory.xml.XmlBeanFactory;\nimport org.springframework.core.io.ClassPathResource;\n\npublic final class Main {\n\n public static final void main(String[] args) {\n BeanFactory factory = new XmlBeanFactory(new ClassPathResource(\"spring.xml\"));\n Travel travel = (Travel)factory.getBean(\"travelBean\");\n System.out.println(\"Travel Name: \"+travel.getName());\n System.out.println(\"Car Name : \"+travel.getCar().getCarName());\n }\n}"
},
{
"code": null,
"e": 3798,
"s": 3789,
"text": "Output :"
},
{
"code": null,
"e": 3835,
"s": 3798,
"text": "Travel Name: Kesineni\nCar Name : BMW"
},
{
"code": null,
"e": 3861,
"s": 3835,
"text": "Spring Autowiring by Type"
},
{
"code": null,
"e": 3879,
"s": 3861,
"text": "Spring autowiring"
},
{
"code": null,
"e": 3956,
"s": 3879,
"text": "The complete example is available for download Spring-Autowiring-Constructor"
},
{
"code": null,
"e": 3973,
"s": 3956,
"text": "Happy Learning π"
},
{
"code": null,
"e": 4039,
"s": 3973,
"text": "\n\nSpring-Autowiring-Constructor\n\nFile size: 10 KB\nDownloads: 697\n"
},
{
"code": null,
"e": 4642,
"s": 4039,
"text": "\nSpring Bean Autowire ByName Example\nSpring Bean Autowire ByType Example\nTypes of Spring Bean Scopes Example\n@Autowired,@Qualifier,@Value annotations in Spring\n@Qualifier annotation example in Spring\nDependency Injection (IoC) in spring with Example\nSpring Java Configuration Example\nWhat is spring circular dependency problem ?\nSpring Collection Map Dependency Example\nSpring Collection Dependency List Example\nWhat is Java Constructor and Types of Constructors\nBeanFactory Example in Spring\nSpring JdbcTemplate CRUD Application\nSpring AOP Around Advice Example XML\nspring expression language example\n"
},
{
"code": null,
"e": 4678,
"s": 4642,
"text": "Spring Bean Autowire ByName Example"
},
{
"code": null,
"e": 4714,
"s": 4678,
"text": "Spring Bean Autowire ByType Example"
},
{
"code": null,
"e": 4750,
"s": 4714,
"text": "Types of Spring Bean Scopes Example"
},
{
"code": null,
"e": 4801,
"s": 4750,
"text": "@Autowired,@Qualifier,@Value annotations in Spring"
},
{
"code": null,
"e": 4841,
"s": 4801,
"text": "@Qualifier annotation example in Spring"
},
{
"code": null,
"e": 4891,
"s": 4841,
"text": "Dependency Injection (IoC) in spring with Example"
},
{
"code": null,
"e": 4925,
"s": 4891,
"text": "Spring Java Configuration Example"
},
{
"code": null,
"e": 4970,
"s": 4925,
"text": "What is spring circular dependency problem ?"
},
{
"code": null,
"e": 5011,
"s": 4970,
"text": "Spring Collection Map Dependency Example"
},
{
"code": null,
"e": 5053,
"s": 5011,
"text": "Spring Collection Dependency List Example"
},
{
"code": null,
"e": 5104,
"s": 5053,
"text": "What is Java Constructor and Types of Constructors"
},
{
"code": null,
"e": 5134,
"s": 5104,
"text": "BeanFactory Example in Spring"
},
{
"code": null,
"e": 5171,
"s": 5134,
"text": "Spring JdbcTemplate CRUD Application"
},
{
"code": null,
"e": 5208,
"s": 5171,
"text": "Spring AOP Around Advice Example XML"
}
] |
GATE | GATE CS 2013 | Question 25 - GeeksforGeeks
|
28 Jun, 2021
Which of the following statements is/are TRUE for undirected graphs?
P: Number of odd degree vertices is even.
Q: Sum of degrees of all vertices is even.
(A) P only(B) Q only(C) Both P and Q(D) Neither P nor QAnswer: (C)Explanation: See https://www.geeksforgeeks.org/data-structures-graph-question-27/Quiz of this Question
GATE-CS-2013
GATE-GATE CS 2013
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-CS-2014-(Set-1) | Question 30
GATE | GATE-CS-2015 (Set 1) | Question 65
GATE | GATE CS 2010 | Question 45
GATE | GATE-CS-2004 | Question 3
GATE | GATE-CS-2015 (Set 3) | Question 65
C++ Program to count Vowels in a string using Pointer
GATE | GATE CS 2012 | Question 40
GATE | GATE-CS-2006 | Question 49
GATE | GATE-CS-2015 (Set 1) | Question 42
GATE | GATE-CS-2014-(Set-3) | Question 65
|
[
{
"code": null,
"e": 24100,
"s": 24072,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 24169,
"s": 24100,
"text": "Which of the following statements is/are TRUE for undirected graphs?"
},
{
"code": null,
"e": 24255,
"s": 24169,
"text": "P: Number of odd degree vertices is even.\nQ: Sum of degrees of all vertices is even. "
},
{
"code": null,
"e": 24424,
"s": 24255,
"text": "(A) P only(B) Q only(C) Both P and Q(D) Neither P nor QAnswer: (C)Explanation: See https://www.geeksforgeeks.org/data-structures-graph-question-27/Quiz of this Question"
},
{
"code": null,
"e": 24437,
"s": 24424,
"text": "GATE-CS-2013"
},
{
"code": null,
"e": 24455,
"s": 24437,
"text": "GATE-GATE CS 2013"
},
{
"code": null,
"e": 24460,
"s": 24455,
"text": "GATE"
},
{
"code": null,
"e": 24558,
"s": 24460,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 24567,
"s": 24558,
"text": "Comments"
},
{
"code": null,
"e": 24580,
"s": 24567,
"text": "Old Comments"
},
{
"code": null,
"e": 24622,
"s": 24580,
"text": "GATE | GATE-CS-2014-(Set-1) | Question 30"
},
{
"code": null,
"e": 24664,
"s": 24622,
"text": "GATE | GATE-CS-2015 (Set 1) | Question 65"
},
{
"code": null,
"e": 24698,
"s": 24664,
"text": "GATE | GATE CS 2010 | Question 45"
},
{
"code": null,
"e": 24731,
"s": 24698,
"text": "GATE | GATE-CS-2004 | Question 3"
},
{
"code": null,
"e": 24773,
"s": 24731,
"text": "GATE | GATE-CS-2015 (Set 3) | Question 65"
},
{
"code": null,
"e": 24827,
"s": 24773,
"text": "C++ Program to count Vowels in a string using Pointer"
},
{
"code": null,
"e": 24861,
"s": 24827,
"text": "GATE | GATE CS 2012 | Question 40"
},
{
"code": null,
"e": 24895,
"s": 24861,
"text": "GATE | GATE-CS-2006 | Question 49"
},
{
"code": null,
"e": 24937,
"s": 24895,
"text": "GATE | GATE-CS-2015 (Set 1) | Question 42"
}
] |
Manage Files and Database Connections in Python Like a Pro | by Anna Geller | Towards Data Science
|
In data engineering and data science, we frequently need to retrieve data from databases or flat files. However, using data from external resources without closing the connections to the underlying databases or files may lead to unwanted consequences. In this article, we discuss how to build custom context managers that help us work with those resources in a secure and efficient way.
Thanks to the context managers, we can read data from external resources and rest assured that the connections to underlying databases or files are closed, even if we encounter some unhandled exceptions in our code.
βTypical uses of context managers include saving and restoring various kinds of global state, locking and unlocking resources, closing opened files, etc.β [1]
Closing resources is crucial because there is a limit to how many files or database connections can be opened at the same time. The number of files that can be simultaneously opened depends on how many file descriptors are allowed by the respective OS. On Linux and macOS, we can examine this number by using ulimit -n[2]:
β ~ ulimit -n256
Similarly, there is a limit to the number of concurrent database connections. For instance, the maximum number of open PostgreSQL connections is, by default, limited to 100 [3].
The code below shows the typical use of a context manager to:
write data to a file
read data from the same file:
You may ask: why not just write and read the data directly to the file without this with addition? We could write the same code as follows:
But imagine what would happen if we would encounter an error while writing to this file? The connection would never be closed. We could improve this by enclosing the code inside of try-finally blocks, as follows:
But this can be tedious to write, and our code becomes verbose. Therefore, context managers are great β we can accomplish more within just 2 lines and our code becomes more readable.
To sum it up, the reasons for context managers are:
ensuring that the resources are released even if we encounter some unhandled exceptions
readability
convenience β we make it easier for ourselves, as we will no longer forget to close the connections to external resources.
There are two ways of defining context managers: with a custom class, or with a generator [4]. Letβs look at the generator option to create a context manager that will let us manage a MySQL database connection.
The logic is similar to the one with try-finally block, except that we yield the connection object, rather than return it β this is due to the nature of a generator that lazily returns the objects when they are needed (i.e., when we iterate over them). In our example, the context manager will yield a single value β the connection object.
Note that all we have to do is to add a decorator @contextlib.contextmanager, and use yield in the try block.
To use this context manager in order to retrieve the data from MySQL into a pandas data frame, we just import and apply this function with our context manager:
Note how much simpler our bus_logic.py script became!
The try-block could include any custom setup code, such as retrieving configuration details and credentials from secrets manager, environment variables, or config files. In the same way, inside of the finally-block, you can define any teardown logic, such as deleting temporary files, closing connections, or changing back the working directory. This is what weβll do next.
Imagine that you are in the src directory, but when you download files from S3, you want to store them within the data directory. In this case, we may want to temporarily change the working directory to the data folder and change it back to the previous directory, when the function is completed. The following context manager can achieve that:
By using the above context manager, we can ensure that we are in the proper directory (data) when downloading files. Then, once the download is finished, we change back to the original working directory.
In this article, we looked at context managers in Python that let us handle external resources in a more elegant way. They also prevent mistakes that may happen when unhandled exceptions cause our script to end before the teardown code would have the chance to be executed. This way, context managers prevent leaving locked resources, open files, or database connections. Finally, they make our code much more readable by abstracting away the setup and teardown code.
Thank you for reading! If this article was helpful, feel free to follow me for the next articles.
|
[
{
"code": null,
"e": 559,
"s": 172,
"text": "In data engineering and data science, we frequently need to retrieve data from databases or flat files. However, using data from external resources without closing the connections to the underlying databases or files may lead to unwanted consequences. In this article, we discuss how to build custom context managers that help us work with those resources in a secure and efficient way."
},
{
"code": null,
"e": 775,
"s": 559,
"text": "Thanks to the context managers, we can read data from external resources and rest assured that the connections to underlying databases or files are closed, even if we encounter some unhandled exceptions in our code."
},
{
"code": null,
"e": 934,
"s": 775,
"text": "βTypical uses of context managers include saving and restoring various kinds of global state, locking and unlocking resources, closing opened files, etc.β [1]"
},
{
"code": null,
"e": 1257,
"s": 934,
"text": "Closing resources is crucial because there is a limit to how many files or database connections can be opened at the same time. The number of files that can be simultaneously opened depends on how many file descriptors are allowed by the respective OS. On Linux and macOS, we can examine this number by using ulimit -n[2]:"
},
{
"code": null,
"e": 1275,
"s": 1257,
"text": "β ~ ulimit -n256"
},
{
"code": null,
"e": 1453,
"s": 1275,
"text": "Similarly, there is a limit to the number of concurrent database connections. For instance, the maximum number of open PostgreSQL connections is, by default, limited to 100 [3]."
},
{
"code": null,
"e": 1515,
"s": 1453,
"text": "The code below shows the typical use of a context manager to:"
},
{
"code": null,
"e": 1536,
"s": 1515,
"text": "write data to a file"
},
{
"code": null,
"e": 1566,
"s": 1536,
"text": "read data from the same file:"
},
{
"code": null,
"e": 1706,
"s": 1566,
"text": "You may ask: why not just write and read the data directly to the file without this with addition? We could write the same code as follows:"
},
{
"code": null,
"e": 1919,
"s": 1706,
"text": "But imagine what would happen if we would encounter an error while writing to this file? The connection would never be closed. We could improve this by enclosing the code inside of try-finally blocks, as follows:"
},
{
"code": null,
"e": 2102,
"s": 1919,
"text": "But this can be tedious to write, and our code becomes verbose. Therefore, context managers are great β we can accomplish more within just 2 lines and our code becomes more readable."
},
{
"code": null,
"e": 2154,
"s": 2102,
"text": "To sum it up, the reasons for context managers are:"
},
{
"code": null,
"e": 2242,
"s": 2154,
"text": "ensuring that the resources are released even if we encounter some unhandled exceptions"
},
{
"code": null,
"e": 2254,
"s": 2242,
"text": "readability"
},
{
"code": null,
"e": 2377,
"s": 2254,
"text": "convenience β we make it easier for ourselves, as we will no longer forget to close the connections to external resources."
},
{
"code": null,
"e": 2588,
"s": 2377,
"text": "There are two ways of defining context managers: with a custom class, or with a generator [4]. Letβs look at the generator option to create a context manager that will let us manage a MySQL database connection."
},
{
"code": null,
"e": 2928,
"s": 2588,
"text": "The logic is similar to the one with try-finally block, except that we yield the connection object, rather than return it β this is due to the nature of a generator that lazily returns the objects when they are needed (i.e., when we iterate over them). In our example, the context manager will yield a single value β the connection object."
},
{
"code": null,
"e": 3038,
"s": 2928,
"text": "Note that all we have to do is to add a decorator @contextlib.contextmanager, and use yield in the try block."
},
{
"code": null,
"e": 3198,
"s": 3038,
"text": "To use this context manager in order to retrieve the data from MySQL into a pandas data frame, we just import and apply this function with our context manager:"
},
{
"code": null,
"e": 3252,
"s": 3198,
"text": "Note how much simpler our bus_logic.py script became!"
},
{
"code": null,
"e": 3626,
"s": 3252,
"text": "The try-block could include any custom setup code, such as retrieving configuration details and credentials from secrets manager, environment variables, or config files. In the same way, inside of the finally-block, you can define any teardown logic, such as deleting temporary files, closing connections, or changing back the working directory. This is what weβll do next."
},
{
"code": null,
"e": 3971,
"s": 3626,
"text": "Imagine that you are in the src directory, but when you download files from S3, you want to store them within the data directory. In this case, we may want to temporarily change the working directory to the data folder and change it back to the previous directory, when the function is completed. The following context manager can achieve that:"
},
{
"code": null,
"e": 4175,
"s": 3971,
"text": "By using the above context manager, we can ensure that we are in the proper directory (data) when downloading files. Then, once the download is finished, we change back to the original working directory."
},
{
"code": null,
"e": 4643,
"s": 4175,
"text": "In this article, we looked at context managers in Python that let us handle external resources in a more elegant way. They also prevent mistakes that may happen when unhandled exceptions cause our script to end before the teardown code would have the chance to be executed. This way, context managers prevent leaving locked resources, open files, or database connections. Finally, they make our code much more readable by abstracting away the setup and teardown code."
}
] |
Heap queue (or heapq) in Python - GeeksforGeeks
|
11 Sep, 2020
Heap data structure is mainly used to represent a priority queue. In Python, it is available using βheapqβ module. The property of this data structure in Python is that each time the smallest of heap element is popped(min heap). Whenever elements are pushed or popped, heap structure in maintained. The heap[0] element also returns the smallest element each time.
Letβs see various Operations on heap :
heapify(iterable) :- This function is used to convert the iterable into a heap data structure. i.e. in heap order.
heappush(heap, ele) :- This function is used to insert the element mentioned in its arguments into heap. The order is adjusted, so as heap structure is maintained.
heappop(heap) :- This function is used to remove and return the smallest element from heap. The order is adjusted, so as heap structure is maintained.
# Python code to demonstrate working of # heapify(), heappush() and heappop() # importing "heapq" to implement heap queueimport heapq # initializing listli = [5, 7, 9, 1, 3] # using heapify to convert list into heapheapq.heapify(li) # printing created heapprint ("The created heap is : ",end="")print (list(li)) # using heappush() to push elements into heap# pushes 4heapq.heappush(li,4) # printing modified heapprint ("The modified heap after push is : ",end="")print (list(li)) # using heappop() to pop smallest elementprint ("The popped and smallest element is : ",end="")print (heapq.heappop(li))
Output :
The created heap is : [1, 3, 9, 7, 5]
The modified heap after push is : [1, 3, 4, 7, 5, 9]
The popped and smallest element is : 1
heappushpop(heap, ele) :- This function combines the functioning of both push and pop operations in one statement, increasing efficiency. Heap order is maintained after this operation.
heapreplace(heap, ele) :- This function also inserts and pops element in one statement, but it is different from above function. In this, element is first popped, then the element is pushed.i.e, the value larger than the pushed value can be returned. heapreplace() returns the smallest value originally in heap regardless of the pushed element as opposed to heappushpop().
# Python code to demonstrate working of # heappushpop() and heapreplce() # importing "heapq" to implement heap queueimport heapq # initializing list 1li1 = [5, 7, 9, 4, 3] # initializing list 2li2 = [5, 7, 9, 4, 3] # using heapify() to convert list into heapheapq.heapify(li1)heapq.heapify(li2) # using heappushpop() to push and pop items simultaneously# pops 2print ("The popped item using heappushpop() is : ",end="")print (heapq.heappushpop(li1, 2)) # using heapreplace() to push and pop items simultaneously# pops 3print ("The popped item using heapreplace() is : ",end="")print (heapq.heapreplace(li2, 2))
Output :
The popped item using heappushpop() is : 2
The popped item using heapreplace() is : 3
nlargest(k, iterable, key = fun) :- This function is used to return the k largest elements from the iterable specified and satisfying the key if mentioned.
nsmallest(k, iterable, key = fun) :- This function is used to return the k smallest elements from the iterable specified and satisfying the key if mentioned.
# Python code to demonstrate working of # nlargest() and nsmallest() # importing "heapq" to implement heap queueimport heapq # initializing list li1 = [6, 7, 9, 4, 3, 5, 8, 10, 1] # using heapify() to convert list into heapheapq.heapify(li1) # using nlargest to print 3 largest numbers# prints 10, 9 and 8print("The 3 largest numbers in list are : ",end="")print(heapq.nlargest(3, li1)) # using nsmallest to print 3 smallest numbers# prints 1, 3 and 4print("The 3 smallest numbers in list are : ",end="")print(heapq.nsmallest(3, li1))
Output :
The 3 largest numbers in list are : [10, 9, 8]
The 3 smallest numbers in list are : [1, 3, 4]
YouTubeGeeksforGeeks502K subscribersPython Programming Tutorial | Heap in Python | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:51β’Liveβ’<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=nXp7lg2SVQo" 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 Manjeet Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
shreyashagrawal
priority-queue
Python
priority-queue
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
|
[
{
"code": null,
"e": 41552,
"s": 41524,
"text": "\n11 Sep, 2020"
},
{
"code": null,
"e": 41916,
"s": 41552,
"text": "Heap data structure is mainly used to represent a priority queue. In Python, it is available using βheapqβ module. The property of this data structure in Python is that each time the smallest of heap element is popped(min heap). Whenever elements are pushed or popped, heap structure in maintained. The heap[0] element also returns the smallest element each time."
},
{
"code": null,
"e": 41955,
"s": 41916,
"text": "Letβs see various Operations on heap :"
},
{
"code": null,
"e": 42070,
"s": 41955,
"text": "heapify(iterable) :- This function is used to convert the iterable into a heap data structure. i.e. in heap order."
},
{
"code": null,
"e": 42234,
"s": 42070,
"text": "heappush(heap, ele) :- This function is used to insert the element mentioned in its arguments into heap. The order is adjusted, so as heap structure is maintained."
},
{
"code": null,
"e": 42385,
"s": 42234,
"text": "heappop(heap) :- This function is used to remove and return the smallest element from heap. The order is adjusted, so as heap structure is maintained."
},
{
"code": "# Python code to demonstrate working of # heapify(), heappush() and heappop() # importing \"heapq\" to implement heap queueimport heapq # initializing listli = [5, 7, 9, 1, 3] # using heapify to convert list into heapheapq.heapify(li) # printing created heapprint (\"The created heap is : \",end=\"\")print (list(li)) # using heappush() to push elements into heap# pushes 4heapq.heappush(li,4) # printing modified heapprint (\"The modified heap after push is : \",end=\"\")print (list(li)) # using heappop() to pop smallest elementprint (\"The popped and smallest element is : \",end=\"\")print (heapq.heappop(li))",
"e": 42993,
"s": 42385,
"text": null
},
{
"code": null,
"e": 43002,
"s": 42993,
"text": "Output :"
},
{
"code": null,
"e": 43133,
"s": 43002,
"text": "The created heap is : [1, 3, 9, 7, 5]\nThe modified heap after push is : [1, 3, 4, 7, 5, 9]\nThe popped and smallest element is : 1\n"
},
{
"code": null,
"e": 43318,
"s": 43133,
"text": "heappushpop(heap, ele) :- This function combines the functioning of both push and pop operations in one statement, increasing efficiency. Heap order is maintained after this operation."
},
{
"code": null,
"e": 43691,
"s": 43318,
"text": "heapreplace(heap, ele) :- This function also inserts and pops element in one statement, but it is different from above function. In this, element is first popped, then the element is pushed.i.e, the value larger than the pushed value can be returned. heapreplace() returns the smallest value originally in heap regardless of the pushed element as opposed to heappushpop()."
},
{
"code": "# Python code to demonstrate working of # heappushpop() and heapreplce() # importing \"heapq\" to implement heap queueimport heapq # initializing list 1li1 = [5, 7, 9, 4, 3] # initializing list 2li2 = [5, 7, 9, 4, 3] # using heapify() to convert list into heapheapq.heapify(li1)heapq.heapify(li2) # using heappushpop() to push and pop items simultaneously# pops 2print (\"The popped item using heappushpop() is : \",end=\"\")print (heapq.heappushpop(li1, 2)) # using heapreplace() to push and pop items simultaneously# pops 3print (\"The popped item using heapreplace() is : \",end=\"\")print (heapq.heapreplace(li2, 2))",
"e": 44308,
"s": 43691,
"text": null
},
{
"code": null,
"e": 44317,
"s": 44308,
"text": "Output :"
},
{
"code": null,
"e": 44404,
"s": 44317,
"text": "The popped item using heappushpop() is : 2\nThe popped item using heapreplace() is : 3\n"
},
{
"code": null,
"e": 44560,
"s": 44404,
"text": "nlargest(k, iterable, key = fun) :- This function is used to return the k largest elements from the iterable specified and satisfying the key if mentioned."
},
{
"code": null,
"e": 44718,
"s": 44560,
"text": "nsmallest(k, iterable, key = fun) :- This function is used to return the k smallest elements from the iterable specified and satisfying the key if mentioned."
},
{
"code": "# Python code to demonstrate working of # nlargest() and nsmallest() # importing \"heapq\" to implement heap queueimport heapq # initializing list li1 = [6, 7, 9, 4, 3, 5, 8, 10, 1] # using heapify() to convert list into heapheapq.heapify(li1) # using nlargest to print 3 largest numbers# prints 10, 9 and 8print(\"The 3 largest numbers in list are : \",end=\"\")print(heapq.nlargest(3, li1)) # using nsmallest to print 3 smallest numbers# prints 1, 3 and 4print(\"The 3 smallest numbers in list are : \",end=\"\")print(heapq.nsmallest(3, li1))",
"e": 45258,
"s": 44718,
"text": null
},
{
"code": null,
"e": 45267,
"s": 45258,
"text": "Output :"
},
{
"code": null,
"e": 45362,
"s": 45267,
"text": "The 3 largest numbers in list are : [10, 9, 8]\nThe 3 smallest numbers in list are : [1, 3, 4]\n"
},
{
"code": null,
"e": 46505,
"s": 45362,
"text": "YouTubeGeeksforGeeks502K subscribersPython Programming Tutorial | Heap in Python | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:51β’Liveβ’<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=nXp7lg2SVQo\" 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 Manjeet Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 46630,
"s": 46505,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 46646,
"s": 46630,
"text": "shreyashagrawal"
},
{
"code": null,
"e": 46661,
"s": 46646,
"text": "priority-queue"
},
{
"code": null,
"e": 46668,
"s": 46661,
"text": "Python"
},
{
"code": null,
"e": 46683,
"s": 46668,
"text": "priority-queue"
},
{
"code": null,
"e": 46781,
"s": 46683,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 46809,
"s": 46781,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 46859,
"s": 46809,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 46881,
"s": 46859,
"text": "Python map() function"
},
{
"code": null,
"e": 46925,
"s": 46881,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 46960,
"s": 46925,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 46982,
"s": 46960,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 47014,
"s": 46982,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 47044,
"s": 47014,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 47086,
"s": 47044,
"text": "Different ways to create Pandas Dataframe"
}
] |
Threads Intercommunication
|
In real life, if a team of people is working on a common task then there should be communication between them for finishing the task properly. The same analogy is applicable to threads also. In programming, to reduce the ideal time of the processor we create multiple threads and assign different sub tasks to every thread. Hence, there must be a communication facility and they should interact with each other to finish the job in a synchronized manner.
Consider the following important points related to thread intercommunication β
No performance gain β If we cannot achieve proper communication between threads and processes then the performance gains from concurrency and parallelism is of no use.
No performance gain β If we cannot achieve proper communication between threads and processes then the performance gains from concurrency and parallelism is of no use.
Accomplish task properly β Without proper intercommunication mechanism between threads, the assigned task cannot be completed properly.
Accomplish task properly β Without proper intercommunication mechanism between threads, the assigned task cannot be completed properly.
More efficient than inter-process communication β Inter-thread communication is more efficient and easy to use than inter-process communication because all threads within a process share same address space and they need not use shared memory.
More efficient than inter-process communication β Inter-thread communication is more efficient and easy to use than inter-process communication because all threads within a process share same address space and they need not use shared memory.
Multithreaded code comes up with a problem of passing information from one thread to another thread. The standard communication primitives do not solve this issue. Hence, we need to implement our own composite object in order to share objects between threads to make the communication thread-safe. Following are a few data structures, which provide thread-safe communication after making some changes in them β
For using set data structure in a thread-safe manner, we need to extend the set class to implement our own locking mechanism.
Here is a Python example of extending the class β
class extend_class(set):
def __init__(self, *args, **kwargs):
self._lock = Lock()
super(extend_class, self).__init__(*args, **kwargs)
def add(self, elem):
self._lock.acquire()
try:
super(extend_class, self).add(elem)
finally:
self._lock.release()
def delete(self, elem):
self._lock.acquire()
try:
super(extend_class, self).delete(elem)
finally:
self._lock.release()
In the above example, a class object named extend_class has been defined which is further inherited from the Python set class. A lock object is created within the constructor of this class. Now, there are two functions - add() and delete(). These functions are defined and are thread-safe. They both rely on the super class functionality with one key exception.
This is another key method for thread-safe communication is the use of decorators.
Consider a Python example that shows how to use decorators &mminus;
def lock_decorator(method):
def new_deco_method(self, *args, **kwargs):
with self._lock:
return method(self, *args, **kwargs)
return new_deco_method
class Decorator_class(set):
def __init__(self, *args, **kwargs):
self._lock = Lock()
super(Decorator_class, self).__init__(*args, **kwargs)
@lock_decorator
def add(self, *args, **kwargs):
return super(Decorator_class, self).add(elem)
@lock_decorator
def delete(self, *args, **kwargs):
return super(Decorator_class, self).delete(elem)
In the above example, a decorator method named lock_decorator has been defined which is further inherited from the Python method class. Then a lock object is created within the constructor of this class. Now, there are two functions - add() and delete(). These functions are defined and are thread-safe. They both rely on super class functionality with one key exception.
The list data structure is thread-safe, quick as well as easy structure for temporary, in-memory storage. In Cpython, the GIL protects against concurrent access to them. As we came to know that lists are thread-safe but what about the data lying in them. Actually, the listβs data is not protected. For example, L.append(x) is not guarantee to return the expected result if another thread is trying to do the same thing. This is because, although append() is an atomic operation and thread-safe but the other thread is trying to modify the listβs data in concurrent fashion hence we can see the side effects of race conditions on the output.
To resolve this kind of issue and safely modify the data, we must implement a proper locking mechanism, which further ensures that multiple threads cannot potentially run into race conditions. To implement proper locking mechanism, we can extend the class as we did in the previous examples.
Some other atomic operations on lists are as follows β
L.append(x)
L1.extend(L2)
x = L[i]
x = L.pop()
L1[i:j] = L2
L.sort()
x = y
x.field = y
D[x] = y
D1.update(D2)
D.keys()
Here β
L,L1,L2 all are lists
D,D1,D2 are dicts
x,y are objects
i, j are ints
If the listβs data is not protected, we might have to face the consequences. We may get or delete wrong data item, of race conditions. That is why it is recommended to use the queue data structure. A real-world example of queue can be a single-lane one-way road, where the vehicle enters first, exits first. More real-world examples can be seen of the queues at the ticket windows and bus-stops.
Queues are by default, thread-safe data structure and we need not worry about implementing complex locking mechanism. Python provides us the module to use different types of queues in our application.
In this section, we will earn about the different types of queues. Python provides three options of queues to use from the <queue> module β
Normal Queues (FIFO, First in First out)
LIFO, Last in First Out
Priority
We will learn about the different queues in the subsequent sections.
It is most commonly used queue implementations offered by Python. In this queuing mechanism whosoever will come first, will get the service first. FIFO is also called normal queues. FIFO queues can be represented as follows β
In python, FIFO queue can be implemented with single thread as well as multithreads.
For implementing FIFO queue with single thread, the Queue class will implement a basic first-in, first-out container. Elements will be added to one βendβ of the sequence using put(), and removed from the other end using get().
Following is a Python program for implementation of FIFO queue with single thread β
import queue
q = queue.Queue()
for i in range(8):
q.put("item-" + str(i))
while not q.empty():
print (q.get(), end = " ")
item-0 item-1 item-2 item-3 item-4 item-5 item-6 item-7
The output shows that above program uses a single thread to illustrate that the elements are removed from the queue in the same order they are inserted.
For implementing FIFO with multiple threads, we need to define the myqueue() function, which is extended from the queue module. The working of get() and put() methods are same as discussed above while implementing FIFO queue with single thread. Then to make it multithreaded, we need to declare and instantiate the threads. These threads will consume the queue in FIFO manner.
Following is a Python program for implementation of FIFO queue with multiple threads
import threading
import queue
import random
import time
def myqueue(queue):
while not queue.empty():
item = queue.get()
if item is None:
break
print("{} removed {} from the queue".format(threading.current_thread(), item))
queue.task_done()
time.sleep(2)
q = queue.Queue()
for i in range(5):
q.put(i)
threads = []
for i in range(4):
thread = threading.Thread(target=myqueue, args=(q,))
thread.start()
threads.append(thread)
for thread in threads:
thread.join()
<Thread(Thread-3654, started 5044)> removed 0 from the queue
<Thread(Thread-3655, started 3144)> removed 1 from the queue
<Thread(Thread-3656, started 6996)> removed 2 from the queue
<Thread(Thread-3657, started 2672)> removed 3 from the queue
<Thread(Thread-3654, started 5044)> removed 4 from the queue
This queue uses totally opposite analogy than FIFO(First in First Out) queues. In this queuing mechanism, the one who comes last, will get the service first. This is similar to implement stack data structure. LIFO queues prove useful while implementing Depth-first search like algorithms of artificial intelligence.
In python, LIFO queue can be implemented with single thread as well as multithreads.
For implementing LIFO queue with single thread, the Queue class will implement a basic last-in, first-out container by using the structure Queue.LifoQueue. Now, on calling put(), the elements are added in the head of the container and removed from the head also on using get().
Following is a Python program for implementation of the LIFO queue with single thread β
import queue
q = queue.LifoQueue()
for i in range(8):
q.put("item-" + str(i))
while not q.empty():
print (q.get(), end=" ")
Output:
item-7 item-6 item-5 item-4 item-3 item-2 item-1 item-0
The output shows that the above program uses a single thread to illustrate that elements are removed from the queue in the opposite order they are inserted.
The implementation is similar as we have done the implementation of FIFO queues with multiple threads. The only difference is that we need to use the Queue class that will implement a basic last-in, first-out container by using the structure Queue.LifoQueue.
Following is a Python program for implementation of LIFO queue with multiple threads β
import threading
import queue
import random
import time
def myqueue(queue):
while not queue.empty():
item = queue.get()
if item is None:
break
print("{} removed {} from the queue".format(threading.current_thread(), item))
queue.task_done()
time.sleep(2)
q = queue.LifoQueue()
for i in range(5):
q.put(i)
threads = []
for i in range(4):
thread = threading.Thread(target=myqueue, args=(q,))
thread.start()
threads.append(thread)
for thread in threads:
thread.join()
<Thread(Thread-3882, started 4928)> removed 4 from the queue
<Thread(Thread-3883, started 4364)> removed 3 from the queue
<Thread(Thread-3884, started 6908)> removed 2 from the queue
<Thread(Thread-3885, started 3584)> removed 1 from the queue
<Thread(Thread-3882, started 4928)> removed 0 from the queue
In FIFO and LIFO queues, the order of items are related to the order of insertion. However, there are many cases when the priority is more important than the order of insertion. Let us consider a real world example. Suppose the security at the airport is checking people of different categories. People of the VVIP, airline staff, custom officer, categories may be checked on priority instead of being checked on the basis of arrival like it is for the commoners.
Another important aspect that needs to be considered for priority queue is how to develop a task scheduler. One common design is to serve the most agent task on priority basis in the queue. This data structure can be used to pick up the items from the queue based on their priority value.
In python, priority queue can be implemented with single thread as well as multithreads.
For implementing priority queue with single thread, the Queue class will implement a task on priority container by using the structure Queue.PriorityQueue. Now, on calling put(), the elements are added with a value where the lowest value will have the highest priority and hence retrieved first by using get().
Consider the following Python program for implementation of Priority queue with single thread β
import queue as Q
p_queue = Q.PriorityQueue()
p_queue.put((2, 'Urgent'))
p_queue.put((1, 'Most Urgent'))
p_queue.put((10, 'Nothing important'))
prio_queue.put((5, 'Important'))
while not p_queue.empty():
item = p_queue.get()
print('%s - %s' % item)
1 β Most Urgent
2 - Urgent
5 - Important
10 β Nothing important
In the above output, we can see that the queue has stored the items based on priority β less value is having high priority.
The implementation is similar to the implementation of FIFO and LIFO queues with multiple threads. The only difference is that we need to use the Queue class for initializing the priority by using the structure Queue.PriorityQueue. Another difference is with the way the queue would be generated. In the example given below, it will be generated with two identical data sets.
The following Python program helps in the implementation of priority queue with multiple threads β
import threading
import queue
import random
import time
def myqueue(queue):
while not queue.empty():
item = queue.get()
if item is None:
break
print("{} removed {} from the queue".format(threading.current_thread(), item))
queue.task_done()
time.sleep(1)
q = queue.PriorityQueue()
for i in range(5):
q.put(i,1)
for i in range(5):
q.put(i,1)
threads = []
for i in range(2):
thread = threading.Thread(target=myqueue, args=(q,))
thread.start()
threads.append(thread)
for thread in threads:
thread.join()
<Thread(Thread-4939, started 2420)> removed 0 from the queue
<Thread(Thread-4940, started 3284)> removed 0 from the queue
<Thread(Thread-4939, started 2420)> removed 1 from the queue
<Thread(Thread-4940, started 3284)> removed 1 from the queue
<Thread(Thread-4939, started 2420)> removed 2 from the queue
<Thread(Thread-4940, started 3284)> removed 2 from the queue
<Thread(Thread-4939, started 2420)> removed 3 from the queue
<Thread(Thread-4940, started 3284)> removed 3 from the queue
<Thread(Thread-4939, started 2420)> removed 4 from the queue
<Thread(Thread-4940, started 3284)> removed 4 from the queue
57 Lectures
8 hours
Denis Tishkov
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2377,
"s": 1922,
"text": "In real life, if a team of people is working on a common task then there should be communication between them for finishing the task properly. The same analogy is applicable to threads also. In programming, to reduce the ideal time of the processor we create multiple threads and assign different sub tasks to every thread. Hence, there must be a communication facility and they should interact with each other to finish the job in a synchronized manner."
},
{
"code": null,
"e": 2456,
"s": 2377,
"text": "Consider the following important points related to thread intercommunication β"
},
{
"code": null,
"e": 2624,
"s": 2456,
"text": "No performance gain β If we cannot achieve proper communication between threads and processes then the performance gains from concurrency and parallelism is of no use."
},
{
"code": null,
"e": 2792,
"s": 2624,
"text": "No performance gain β If we cannot achieve proper communication between threads and processes then the performance gains from concurrency and parallelism is of no use."
},
{
"code": null,
"e": 2928,
"s": 2792,
"text": "Accomplish task properly β Without proper intercommunication mechanism between threads, the assigned task cannot be completed properly."
},
{
"code": null,
"e": 3064,
"s": 2928,
"text": "Accomplish task properly β Without proper intercommunication mechanism between threads, the assigned task cannot be completed properly."
},
{
"code": null,
"e": 3307,
"s": 3064,
"text": "More efficient than inter-process communication β Inter-thread communication is more efficient and easy to use than inter-process communication because all threads within a process share same address space and they need not use shared memory."
},
{
"code": null,
"e": 3550,
"s": 3307,
"text": "More efficient than inter-process communication β Inter-thread communication is more efficient and easy to use than inter-process communication because all threads within a process share same address space and they need not use shared memory."
},
{
"code": null,
"e": 3961,
"s": 3550,
"text": "Multithreaded code comes up with a problem of passing information from one thread to another thread. The standard communication primitives do not solve this issue. Hence, we need to implement our own composite object in order to share objects between threads to make the communication thread-safe. Following are a few data structures, which provide thread-safe communication after making some changes in them β"
},
{
"code": null,
"e": 4087,
"s": 3961,
"text": "For using set data structure in a thread-safe manner, we need to extend the set class to implement our own locking mechanism."
},
{
"code": null,
"e": 4137,
"s": 4087,
"text": "Here is a Python example of extending the class β"
},
{
"code": null,
"e": 4585,
"s": 4137,
"text": "class extend_class(set):\n def __init__(self, *args, **kwargs):\n self._lock = Lock()\n super(extend_class, self).__init__(*args, **kwargs)\n\n def add(self, elem):\n self._lock.acquire()\n\t try:\n super(extend_class, self).add(elem)\n finally:\n self._lock.release()\n \n def delete(self, elem):\n self._lock.acquire()\n try:\n super(extend_class, self).delete(elem)\n finally:\n self._lock.release()"
},
{
"code": null,
"e": 4947,
"s": 4585,
"text": "In the above example, a class object named extend_class has been defined which is further inherited from the Python set class. A lock object is created within the constructor of this class. Now, there are two functions - add() and delete(). These functions are defined and are thread-safe. They both rely on the super class functionality with one key exception."
},
{
"code": null,
"e": 5030,
"s": 4947,
"text": "This is another key method for thread-safe communication is the use of decorators."
},
{
"code": null,
"e": 5098,
"s": 5030,
"text": "Consider a Python example that shows how to use decorators &mminus;"
},
{
"code": null,
"e": 5641,
"s": 5098,
"text": "def lock_decorator(method):\n\n def new_deco_method(self, *args, **kwargs):\n with self._lock:\n return method(self, *args, **kwargs)\nreturn new_deco_method\n\nclass Decorator_class(set):\n def __init__(self, *args, **kwargs):\n self._lock = Lock()\n super(Decorator_class, self).__init__(*args, **kwargs)\n\n @lock_decorator\n def add(self, *args, **kwargs):\n return super(Decorator_class, self).add(elem)\n @lock_decorator\n def delete(self, *args, **kwargs):\n return super(Decorator_class, self).delete(elem)"
},
{
"code": null,
"e": 6013,
"s": 5641,
"text": "In the above example, a decorator method named lock_decorator has been defined which is further inherited from the Python method class. Then a lock object is created within the constructor of this class. Now, there are two functions - add() and delete(). These functions are defined and are thread-safe. They both rely on super class functionality with one key exception."
},
{
"code": null,
"e": 6655,
"s": 6013,
"text": "The list data structure is thread-safe, quick as well as easy structure for temporary, in-memory storage. In Cpython, the GIL protects against concurrent access to them. As we came to know that lists are thread-safe but what about the data lying in them. Actually, the listβs data is not protected. For example, L.append(x) is not guarantee to return the expected result if another thread is trying to do the same thing. This is because, although append() is an atomic operation and thread-safe but the other thread is trying to modify the listβs data in concurrent fashion hence we can see the side effects of race conditions on the output."
},
{
"code": null,
"e": 6947,
"s": 6655,
"text": "To resolve this kind of issue and safely modify the data, we must implement a proper locking mechanism, which further ensures that multiple threads cannot potentially run into race conditions. To implement proper locking mechanism, we can extend the class as we did in the previous examples."
},
{
"code": null,
"e": 7002,
"s": 6947,
"text": "Some other atomic operations on lists are as follows β"
},
{
"code": null,
"e": 7121,
"s": 7002,
"text": "L.append(x)\nL1.extend(L2)\nx = L[i]\nx = L.pop()\nL1[i:j] = L2\nL.sort()\nx = y\nx.field = y\nD[x] = y\nD1.update(D2)\nD.keys()"
},
{
"code": null,
"e": 7128,
"s": 7121,
"text": "Here β"
},
{
"code": null,
"e": 7150,
"s": 7128,
"text": "L,L1,L2 all are lists"
},
{
"code": null,
"e": 7168,
"s": 7150,
"text": "D,D1,D2 are dicts"
},
{
"code": null,
"e": 7184,
"s": 7168,
"text": "x,y are objects"
},
{
"code": null,
"e": 7198,
"s": 7184,
"text": "i, j are ints"
},
{
"code": null,
"e": 7594,
"s": 7198,
"text": "If the listβs data is not protected, we might have to face the consequences. We may get or delete wrong data item, of race conditions. That is why it is recommended to use the queue data structure. A real-world example of queue can be a single-lane one-way road, where the vehicle enters first, exits first. More real-world examples can be seen of the queues at the ticket windows and bus-stops."
},
{
"code": null,
"e": 7796,
"s": 7594,
"text": "Queues are by default, thread-safe data structure and we need not worry about implementing complex locking mechanism. Python provides us the module to use different types of queues in our application."
},
{
"code": null,
"e": 7936,
"s": 7796,
"text": "In this section, we will earn about the different types of queues. Python provides three options of queues to use from the <queue> module β"
},
{
"code": null,
"e": 7977,
"s": 7936,
"text": "Normal Queues (FIFO, First in First out)"
},
{
"code": null,
"e": 8001,
"s": 7977,
"text": "LIFO, Last in First Out"
},
{
"code": null,
"e": 8010,
"s": 8001,
"text": "Priority"
},
{
"code": null,
"e": 8079,
"s": 8010,
"text": "We will learn about the different queues in the subsequent sections."
},
{
"code": null,
"e": 8305,
"s": 8079,
"text": "It is most commonly used queue implementations offered by Python. In this queuing mechanism whosoever will come first, will get the service first. FIFO is also called normal queues. FIFO queues can be represented as follows β"
},
{
"code": null,
"e": 8390,
"s": 8305,
"text": "In python, FIFO queue can be implemented with single thread as well as multithreads."
},
{
"code": null,
"e": 8617,
"s": 8390,
"text": "For implementing FIFO queue with single thread, the Queue class will implement a basic first-in, first-out container. Elements will be added to one βendβ of the sequence using put(), and removed from the other end using get()."
},
{
"code": null,
"e": 8701,
"s": 8617,
"text": "Following is a Python program for implementation of FIFO queue with single thread β"
},
{
"code": null,
"e": 8832,
"s": 8701,
"text": "import queue\n\nq = queue.Queue()\n\nfor i in range(8):\n q.put(\"item-\" + str(i))\n\nwhile not q.empty():\n print (q.get(), end = \" \")"
},
{
"code": null,
"e": 8889,
"s": 8832,
"text": "item-0 item-1 item-2 item-3 item-4 item-5 item-6 item-7\n"
},
{
"code": null,
"e": 9042,
"s": 8889,
"text": "The output shows that above program uses a single thread to illustrate that the elements are removed from the queue in the same order they are inserted."
},
{
"code": null,
"e": 9419,
"s": 9042,
"text": "For implementing FIFO with multiple threads, we need to define the myqueue() function, which is extended from the queue module. The working of get() and put() methods are same as discussed above while implementing FIFO queue with single thread. Then to make it multithreaded, we need to declare and instantiate the threads. These threads will consume the queue in FIFO manner."
},
{
"code": null,
"e": 9504,
"s": 9419,
"text": "Following is a Python program for implementation of FIFO queue with multiple threads"
},
{
"code": null,
"e": 10000,
"s": 9504,
"text": "import threading\nimport queue\nimport random\nimport time\ndef myqueue(queue):\n while not queue.empty():\n item = queue.get()\n if item is None:\n break\n print(\"{} removed {} from the queue\".format(threading.current_thread(), item))\n queue.task_done()\n time.sleep(2)\nq = queue.Queue()\nfor i in range(5):\n q.put(i)\nthreads = []\nfor i in range(4):\n thread = threading.Thread(target=myqueue, args=(q,))\n thread.start()\n threads.append(thread)\nfor thread in threads:\n thread.join()"
},
{
"code": null,
"e": 10306,
"s": 10000,
"text": "<Thread(Thread-3654, started 5044)> removed 0 from the queue\n<Thread(Thread-3655, started 3144)> removed 1 from the queue\n<Thread(Thread-3656, started 6996)> removed 2 from the queue\n<Thread(Thread-3657, started 2672)> removed 3 from the queue\n<Thread(Thread-3654, started 5044)> removed 4 from the queue\n"
},
{
"code": null,
"e": 10622,
"s": 10306,
"text": "This queue uses totally opposite analogy than FIFO(First in First Out) queues. In this queuing mechanism, the one who comes last, will get the service first. This is similar to implement stack data structure. LIFO queues prove useful while implementing Depth-first search like algorithms of artificial intelligence."
},
{
"code": null,
"e": 10707,
"s": 10622,
"text": "In python, LIFO queue can be implemented with single thread as well as multithreads."
},
{
"code": null,
"e": 10985,
"s": 10707,
"text": "For implementing LIFO queue with single thread, the Queue class will implement a basic last-in, first-out container by using the structure Queue.LifoQueue. Now, on calling put(), the elements are added in the head of the container and removed from the head also on using get()."
},
{
"code": null,
"e": 11073,
"s": 10985,
"text": "Following is a Python program for implementation of the LIFO queue with single thread β"
},
{
"code": null,
"e": 11270,
"s": 11073,
"text": "import queue\n\nq = queue.LifoQueue()\n\nfor i in range(8):\n q.put(\"item-\" + str(i))\n\nwhile not q.empty():\n print (q.get(), end=\" \")\nOutput:\nitem-7 item-6 item-5 item-4 item-3 item-2 item-1 item-0"
},
{
"code": null,
"e": 11427,
"s": 11270,
"text": "The output shows that the above program uses a single thread to illustrate that elements are removed from the queue in the opposite order they are inserted."
},
{
"code": null,
"e": 11686,
"s": 11427,
"text": "The implementation is similar as we have done the implementation of FIFO queues with multiple threads. The only difference is that we need to use the Queue class that will implement a basic last-in, first-out container by using the structure Queue.LifoQueue."
},
{
"code": null,
"e": 11773,
"s": 11686,
"text": "Following is a Python program for implementation of LIFO queue with multiple threads β"
},
{
"code": null,
"e": 12289,
"s": 11773,
"text": "import threading\nimport queue\nimport random\nimport time\ndef myqueue(queue):\n while not queue.empty():\n item = queue.get()\n if item is None:\n break\n\t print(\"{} removed {} from the queue\".format(threading.current_thread(), item))\n queue.task_done()\n time.sleep(2)\nq = queue.LifoQueue()\nfor i in range(5):\n q.put(i)\nthreads = []\nfor i in range(4):\n thread = threading.Thread(target=myqueue, args=(q,))\n thread.start()\n threads.append(thread)\nfor thread in threads:\n thread.join() "
},
{
"code": null,
"e": 12595,
"s": 12289,
"text": "<Thread(Thread-3882, started 4928)> removed 4 from the queue\n<Thread(Thread-3883, started 4364)> removed 3 from the queue\n<Thread(Thread-3884, started 6908)> removed 2 from the queue\n<Thread(Thread-3885, started 3584)> removed 1 from the queue\n<Thread(Thread-3882, started 4928)> removed 0 from the queue\n"
},
{
"code": null,
"e": 13059,
"s": 12595,
"text": "In FIFO and LIFO queues, the order of items are related to the order of insertion. However, there are many cases when the priority is more important than the order of insertion. Let us consider a real world example. Suppose the security at the airport is checking people of different categories. People of the VVIP, airline staff, custom officer, categories may be checked on priority instead of being checked on the basis of arrival like it is for the commoners."
},
{
"code": null,
"e": 13348,
"s": 13059,
"text": "Another important aspect that needs to be considered for priority queue is how to develop a task scheduler. One common design is to serve the most agent task on priority basis in the queue. This data structure can be used to pick up the items from the queue based on their priority value."
},
{
"code": null,
"e": 13437,
"s": 13348,
"text": "In python, priority queue can be implemented with single thread as well as multithreads."
},
{
"code": null,
"e": 13748,
"s": 13437,
"text": "For implementing priority queue with single thread, the Queue class will implement a task on priority container by using the structure Queue.PriorityQueue. Now, on calling put(), the elements are added with a value where the lowest value will have the highest priority and hence retrieved first by using get()."
},
{
"code": null,
"e": 13844,
"s": 13748,
"text": "Consider the following Python program for implementation of Priority queue with single thread β"
},
{
"code": null,
"e": 14101,
"s": 13844,
"text": "import queue as Q\np_queue = Q.PriorityQueue()\n\np_queue.put((2, 'Urgent'))\np_queue.put((1, 'Most Urgent'))\np_queue.put((10, 'Nothing important'))\nprio_queue.put((5, 'Important'))\n\nwhile not p_queue.empty():\n item = p_queue.get()\n print('%s - %s' % item)"
},
{
"code": null,
"e": 14166,
"s": 14101,
"text": "1 β Most Urgent\n2 - Urgent\n5 - Important\n10 β Nothing important\n"
},
{
"code": null,
"e": 14290,
"s": 14166,
"text": "In the above output, we can see that the queue has stored the items based on priority β less value is having high priority."
},
{
"code": null,
"e": 14666,
"s": 14290,
"text": "The implementation is similar to the implementation of FIFO and LIFO queues with multiple threads. The only difference is that we need to use the Queue class for initializing the priority by using the structure Queue.PriorityQueue. Another difference is with the way the queue would be generated. In the example given below, it will be generated with two identical data sets."
},
{
"code": null,
"e": 14765,
"s": 14666,
"text": "The following Python program helps in the implementation of priority queue with multiple threads β"
},
{
"code": null,
"e": 15324,
"s": 14765,
"text": "import threading\nimport queue\nimport random\nimport time\ndef myqueue(queue):\n while not queue.empty():\n item = queue.get()\n if item is None:\n break\n print(\"{} removed {} from the queue\".format(threading.current_thread(), item))\n queue.task_done()\n time.sleep(1)\nq = queue.PriorityQueue()\nfor i in range(5):\n q.put(i,1)\n\nfor i in range(5):\n q.put(i,1)\n\nthreads = []\nfor i in range(2):\n thread = threading.Thread(target=myqueue, args=(q,))\n thread.start()\n threads.append(thread)\nfor thread in threads:\n thread.join()"
},
{
"code": null,
"e": 15935,
"s": 15324,
"text": "<Thread(Thread-4939, started 2420)> removed 0 from the queue\n<Thread(Thread-4940, started 3284)> removed 0 from the queue\n<Thread(Thread-4939, started 2420)> removed 1 from the queue\n<Thread(Thread-4940, started 3284)> removed 1 from the queue\n<Thread(Thread-4939, started 2420)> removed 2 from the queue\n<Thread(Thread-4940, started 3284)> removed 2 from the queue\n<Thread(Thread-4939, started 2420)> removed 3 from the queue\n<Thread(Thread-4940, started 3284)> removed 3 from the queue\n<Thread(Thread-4939, started 2420)> removed 4 from the queue\n<Thread(Thread-4940, started 3284)> removed 4 from the queue\n"
},
{
"code": null,
"e": 15968,
"s": 15935,
"text": "\n 57 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 15983,
"s": 15968,
"text": " Denis Tishkov"
},
{
"code": null,
"e": 15990,
"s": 15983,
"text": " Print"
},
{
"code": null,
"e": 16001,
"s": 15990,
"text": " Add Notes"
}
] |
How to create a bookmark link in HTML?
|
To create a bookmark link in HTML, you need to create a bookmark using the <a> tag name attribute. Now, add a link to the bookmark. Bookmarks are also known as named anchors. This is quite useful to take readers to a specific section of the web page.
Just keep in mind the <a> tag name attribute deprecated in HTML5. Do not use.
You can try to run the following code to create a bookmark link in HTML.
Live Demo
<html>
<head>
<title>HTML Bookmark Link</title>
</head>
<body>
<h1>Tutorials</h1>
<p>
<a href="#z">Learn about Scripting Languages</a>
</p>
<h2>Programming</h2>
<p>Here are the tutorials on Programming.</p>
<h2>Mobile</h2>
<p>Here are the tutorials on App Development</p>
<h2>Design</h2>
<p>Here are the tutorials on Website Designing</p>
<h2>Databases</h2>
<p>Here are the tutorials on Databases.</p>
<h2>Networking</h2>
<p>Here are the tutorials on Networking</p>
<h2>Java Technologies</h2>
<p>Here are the tutorials on Java Technologies.</p>
<h2>Digital Marketing</h2>
<p>Here are the tutorials on Digital Marketing.</p>
<h2>
<a name="z">Scripting Languages</a>
</h2>
<p>Here are the tutorials on Scripting Languages.</p>
</body>
</html>
|
[
{
"code": null,
"e": 1313,
"s": 1062,
"text": "To create a bookmark link in HTML, you need to create a bookmark using the <a> tag name attribute. Now, add a link to the bookmark. Bookmarks are also known as named anchors. This is quite useful to take readers to a specific section of the web page."
},
{
"code": null,
"e": 1391,
"s": 1313,
"text": "Just keep in mind the <a> tag name attribute deprecated in HTML5. Do not use."
},
{
"code": null,
"e": 1464,
"s": 1391,
"text": "You can try to run the following code to create a bookmark link in HTML."
},
{
"code": null,
"e": 1474,
"s": 1464,
"text": "Live Demo"
},
{
"code": null,
"e": 2371,
"s": 1474,
"text": "<html>\n <head>\n <title>HTML Bookmark Link</title>\n </head>\n <body>\n <h1>Tutorials</h1>\n <p>\n <a href=\"#z\">Learn about Scripting Languages</a>\n </p>\n <h2>Programming</h2>\n <p>Here are the tutorials on Programming.</p>\n <h2>Mobile</h2>\n <p>Here are the tutorials on App Development</p>\n <h2>Design</h2>\n <p>Here are the tutorials on Website Designing</p>\n <h2>Databases</h2>\n <p>Here are the tutorials on Databases.</p>\n <h2>Networking</h2>\n <p>Here are the tutorials on Networking</p>\n <h2>Java Technologies</h2>\n <p>Here are the tutorials on Java Technologies.</p>\n <h2>Digital Marketing</h2>\n <p>Here are the tutorials on Digital Marketing.</p>\n <h2>\n <a name=\"z\">Scripting Languages</a>\n </h2>\n <p>Here are the tutorials on Scripting Languages.</p>\n </body>\n</html>"
}
] |
How do I get a parent HTML Tag with Selenium WebDriver using Java?
|
We can get a parent HTML tag with Selenium webdriver. First of all we need to identify the child element with help of any of the locators like id, class, name, xpath or css. Then we have to identify the parent with the findElement(By.xpath()) method.
We can identify the parent from the child, by localizing it with the child and then passing (parent::*) as a parameter to the findElement(By.xpath()). Next to get the tagname of the parent, we have to use the getTagName() method.
child.findElement(By.xpath("parent::*"));
Let us identify tagname of parent of child element li in below html codeβ
The tagname of the parent should be ul.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class ParentTagname{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver","C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.get("https://www.tutorialspoint.com/about/about_careers.htm");
// identify element
WebElement p=driver.findElement(By.xpath("//li[@class='heading']"));
//identify parent from child element
WebElement t= p.findElement(By.xpath("parent::*"));
//getTagName() to get parent element tag
System.out.println("Parent tagname: " + t.getTagName());
driver.close();
}
}
|
[
{
"code": null,
"e": 1313,
"s": 1062,
"text": "We can get a parent HTML tag with Selenium webdriver. First of all we need to identify the child element with help of any of the locators like id, class, name, xpath or css. Then we have to identify the parent with the findElement(By.xpath()) method."
},
{
"code": null,
"e": 1543,
"s": 1313,
"text": "We can identify the parent from the child, by localizing it with the child and then passing (parent::*) as a parameter to the findElement(By.xpath()). Next to get the tagname of the parent, we have to use the getTagName() method."
},
{
"code": null,
"e": 1585,
"s": 1543,
"text": "child.findElement(By.xpath(\"parent::*\"));"
},
{
"code": null,
"e": 1659,
"s": 1585,
"text": "Let us identify tagname of parent of child element li in below html codeβ"
},
{
"code": null,
"e": 1699,
"s": 1659,
"text": "The tagname of the parent should be ul."
},
{
"code": null,
"e": 2599,
"s": 1699,
"text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport java.util.concurrent.TimeUnit;\n\npublic class ParentTagname{\n public static void main(String[] args) {\nSystem.setProperty(\"webdriver.chrome.driver\",\"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);\n driver.get(\"https://www.tutorialspoint.com/about/about_careers.htm\");\n // identify element\n WebElement p=driver.findElement(By.xpath(\"//li[@class='heading']\"));\n //identify parent from child element\n WebElement t= p.findElement(By.xpath(\"parent::*\"));\n //getTagName() to get parent element tag\n System.out.println(\"Parent tagname: \" + t.getTagName());\n driver.close();\n }\n}"
}
] |
How to create an image gallery with CSS
|
To create an image gallery with CSS is quite easy. You can try to run the following code to achieve this. A gallery of 3 images is created here,
Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
div.myGallery {
margin: 3px;
border: 2px solid orange;
float: left;
width: 220px;
}
div.myGallery:hover {
border: 1px solid blue;
}
div.myGallery img {
width: 100%;
height: auto;
}
div.desc {
padding: 20px;
text-align: center;
}
</style>
</head>
<body>
<div class = "myGallery">
<a target = "_blank" href="https://www.tutorialspoint.com/assets/videotutorials/courses/3d_animation_online_training/380_course_211_image.jpg">
<img src = "https://www.tutorialspoint.com/assets/videotutorials/courses/3d_animation_online_training/380_course_211_image.jpg" alt="3D Animation Tutorial" width="600" height="500">
</a>
<div class = "mydiv">3D Animation Tutorial</div>
</div>
<div class = "myGallery">
<a target="_blank" href="https://www.tutorialspoint.com/assets/videotutorials/courses/swift_4_online_training/380_course_210_image.jpg">
<img src = "https://www.tutorialspoint.com/assets/videotutorials/courses/swift_4_online_training/380_course_210_image.jpg" alt="Swift Video Tutorial" width="600" height="500">
</a>
<div class = "mydiv">Swift Video Tutorial</div>
</div>
<div class = "myGallery">
<a target = "_blank" href = "https://www.tutorialspoint.com/assets/videotutorials/courses/css_online_training/380_course_215_image.jpg">
<img src = "https://www.tutorialspoint.com/assets/videotutorials/courses/css_online_training/380_course_215_image.jpg" alt="CSS Video Tutorial" width="600" height="500">
</a>
<div class = "mydiv">CSS Tutorial</div>
</div>
</body>
</html>
|
[
{
"code": null,
"e": 1207,
"s": 1062,
"text": "To create an image gallery with CSS is quite easy. You can try to run the following code to achieve this. A gallery of 3 images is created here,"
},
{
"code": null,
"e": 1217,
"s": 1207,
"text": "Live Demo"
},
{
"code": null,
"e": 3078,
"s": 1217,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <style>\n div.myGallery {\n margin: 3px;\n border: 2px solid orange;\n float: left;\n width: 220px;\n }\n div.myGallery:hover {\n border: 1px solid blue;\n }\n div.myGallery img {\n width: 100%;\n height: auto;\n }\n div.desc {\n padding: 20px;\n text-align: center;\n }\n </style>\n </head>\n <body>\n <div class = \"myGallery\">\n <a target = \"_blank\" href=\"https://www.tutorialspoint.com/assets/videotutorials/courses/3d_animation_online_training/380_course_211_image.jpg\">\n <img src = \"https://www.tutorialspoint.com/assets/videotutorials/courses/3d_animation_online_training/380_course_211_image.jpg\" alt=\"3D Animation Tutorial\" width=\"600\" height=\"500\">\n </a>\n <div class = \"mydiv\">3D Animation Tutorial</div>\n </div>\n <div class = \"myGallery\">\n <a target=\"_blank\" href=\"https://www.tutorialspoint.com/assets/videotutorials/courses/swift_4_online_training/380_course_210_image.jpg\">\n <img src = \"https://www.tutorialspoint.com/assets/videotutorials/courses/swift_4_online_training/380_course_210_image.jpg\" alt=\"Swift Video Tutorial\" width=\"600\" height=\"500\">\n </a>\n <div class = \"mydiv\">Swift Video Tutorial</div>\n </div>\n <div class = \"myGallery\">\n <a target = \"_blank\" href = \"https://www.tutorialspoint.com/assets/videotutorials/courses/css_online_training/380_course_215_image.jpg\">\n <img src = \"https://www.tutorialspoint.com/assets/videotutorials/courses/css_online_training/380_course_215_image.jpg\" alt=\"CSS Video Tutorial\" width=\"600\" height=\"500\">\n </a>\n <div class = \"mydiv\">CSS Tutorial</div>\n </div>\n </body>\n</html>"
}
] |
C# | Copy the Stack to an Array - GeeksforGeeks
|
01 Feb, 2019
Stack<T>.CopyTo(T[], Int32) Method is used to copy the Stack<T> to an existing 1-D Array which starts from the specified array index.
Properties:
The capacity of a Stack<T>is the number of elements the Stack<T> can hold. As elements are added to a Stack<T> , the capacity is automatically increased as required through reallocation.
If Count is less than the capacity of the Stack<T> , Push is an O(1) operation. If the capacity needs to be increased to accommodate the new element, Push becomes an O(n) operation, where n is Count. Pop is an O(1) operation.
Stack accepts null as a valid value and allows duplicate elements.
Syntax:
public void CopyTo (T[] array, int arrayIndex);
Parameters:
array: The one-dimensional Array that is the destination of the elements copied from Stack<T>. The Array must have zero-based indexing.
arrayIndex: The zero-based index in array at which copying begins.
Exceptions:
ArgumentNullException : If an array is null.
ArgumentOutOfRangeException : If the arrayIndex is less than zero.
ArgumentException : The number of elements in the source Stack<T> is greater than the available space from arrayIndex to the end of the destination array.
Below given are some examples to understand the implementation in a better way:
Example 1:
// C# code to Copy the Stack to an Arrayusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a Stack of strings Stack<string> myStack = new Stack<string>(); // Inserting the elements into the Stack myStack.Push("Geeks"); myStack.Push("Geeks Classes"); myStack.Push("Noida"); myStack.Push("Data Structures"); myStack.Push("GeeksforGeeks"); // Creating a string array arr string[] arr = new string[myStack.Count]; // Copying the elements of stack into array arr myStack.CopyTo(arr, 0); // Displaying the elements in array arr foreach(string str in arr) { Console.WriteLine(str); } }}
GeeksforGeeks
Data Structures
Noida
Geeks Classes
Geeks
Example 2:
// C# code to Copy the Stack to an Arrayusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a Stack of Integers Stack<int> myStack = new Stack<int>(); // Inserting the elements into the Stack myStack.Push(2); myStack.Push(3); myStack.Push(4); myStack.Push(5); myStack.Push(6); // Creating an Integer array arr int[] arr = new int[myStack.Count]; // Copying the elements of stack into array arr myStack.CopyTo(arr, 0); // Displaying the elements in array arr foreach(int i in arr) { Console.WriteLine(i); } }}
6
5
4
3
2
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.stack-1.copyto?view=netframework-4.7.2
CSharp-Generic-Namespace
CSharp-Generic-Stack
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Extension Method in C#
Top 50 C# Interview Questions & Answers
HashSet in C# with Examples
C# | How to insert an element in an Array?
Partial Classes in C#
C# | Inheritance
C# | List Class
Lambda Expressions in C#
Difference between Hashtable and Dictionary in C#
Convert String to Character Array in C#
|
[
{
"code": null,
"e": 24302,
"s": 24274,
"text": "\n01 Feb, 2019"
},
{
"code": null,
"e": 24436,
"s": 24302,
"text": "Stack<T>.CopyTo(T[], Int32) Method is used to copy the Stack<T> to an existing 1-D Array which starts from the specified array index."
},
{
"code": null,
"e": 24448,
"s": 24436,
"text": "Properties:"
},
{
"code": null,
"e": 24635,
"s": 24448,
"text": "The capacity of a Stack<T>is the number of elements the Stack<T> can hold. As elements are added to a Stack<T> , the capacity is automatically increased as required through reallocation."
},
{
"code": null,
"e": 24861,
"s": 24635,
"text": "If Count is less than the capacity of the Stack<T> , Push is an O(1) operation. If the capacity needs to be increased to accommodate the new element, Push becomes an O(n) operation, where n is Count. Pop is an O(1) operation."
},
{
"code": null,
"e": 24928,
"s": 24861,
"text": "Stack accepts null as a valid value and allows duplicate elements."
},
{
"code": null,
"e": 24936,
"s": 24928,
"text": "Syntax:"
},
{
"code": null,
"e": 24985,
"s": 24936,
"text": "public void CopyTo (T[] array, int arrayIndex);\n"
},
{
"code": null,
"e": 24997,
"s": 24985,
"text": "Parameters:"
},
{
"code": null,
"e": 25133,
"s": 24997,
"text": "array: The one-dimensional Array that is the destination of the elements copied from Stack<T>. The Array must have zero-based indexing."
},
{
"code": null,
"e": 25200,
"s": 25133,
"text": "arrayIndex: The zero-based index in array at which copying begins."
},
{
"code": null,
"e": 25212,
"s": 25200,
"text": "Exceptions:"
},
{
"code": null,
"e": 25257,
"s": 25212,
"text": "ArgumentNullException : If an array is null."
},
{
"code": null,
"e": 25324,
"s": 25257,
"text": "ArgumentOutOfRangeException : If the arrayIndex is less than zero."
},
{
"code": null,
"e": 25479,
"s": 25324,
"text": "ArgumentException : The number of elements in the source Stack<T> is greater than the available space from arrayIndex to the end of the destination array."
},
{
"code": null,
"e": 25559,
"s": 25479,
"text": "Below given are some examples to understand the implementation in a better way:"
},
{
"code": null,
"e": 25570,
"s": 25559,
"text": "Example 1:"
},
{
"code": "// C# code to Copy the Stack to an Arrayusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a Stack of strings Stack<string> myStack = new Stack<string>(); // Inserting the elements into the Stack myStack.Push(\"Geeks\"); myStack.Push(\"Geeks Classes\"); myStack.Push(\"Noida\"); myStack.Push(\"Data Structures\"); myStack.Push(\"GeeksforGeeks\"); // Creating a string array arr string[] arr = new string[myStack.Count]; // Copying the elements of stack into array arr myStack.CopyTo(arr, 0); // Displaying the elements in array arr foreach(string str in arr) { Console.WriteLine(str); } }}",
"e": 26361,
"s": 25570,
"text": null
},
{
"code": null,
"e": 26418,
"s": 26361,
"text": "GeeksforGeeks\nData Structures\nNoida\nGeeks Classes\nGeeks\n"
},
{
"code": null,
"e": 26429,
"s": 26418,
"text": "Example 2:"
},
{
"code": "// C# code to Copy the Stack to an Arrayusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a Stack of Integers Stack<int> myStack = new Stack<int>(); // Inserting the elements into the Stack myStack.Push(2); myStack.Push(3); myStack.Push(4); myStack.Push(5); myStack.Push(6); // Creating an Integer array arr int[] arr = new int[myStack.Count]; // Copying the elements of stack into array arr myStack.CopyTo(arr, 0); // Displaying the elements in array arr foreach(int i in arr) { Console.WriteLine(i); } }}",
"e": 27148,
"s": 26429,
"text": null
},
{
"code": null,
"e": 27159,
"s": 27148,
"text": "6\n5\n4\n3\n2\n"
},
{
"code": null,
"e": 27170,
"s": 27159,
"text": "Reference:"
},
{
"code": null,
"e": 27280,
"s": 27170,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.stack-1.copyto?view=netframework-4.7.2"
},
{
"code": null,
"e": 27305,
"s": 27280,
"text": "CSharp-Generic-Namespace"
},
{
"code": null,
"e": 27326,
"s": 27305,
"text": "CSharp-Generic-Stack"
},
{
"code": null,
"e": 27340,
"s": 27326,
"text": "CSharp-method"
},
{
"code": null,
"e": 27343,
"s": 27340,
"text": "C#"
},
{
"code": null,
"e": 27441,
"s": 27343,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27450,
"s": 27441,
"text": "Comments"
},
{
"code": null,
"e": 27463,
"s": 27450,
"text": "Old Comments"
},
{
"code": null,
"e": 27486,
"s": 27463,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 27526,
"s": 27486,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 27554,
"s": 27526,
"text": "HashSet in C# with Examples"
},
{
"code": null,
"e": 27597,
"s": 27554,
"text": "C# | How to insert an element in an Array?"
},
{
"code": null,
"e": 27619,
"s": 27597,
"text": "Partial Classes in C#"
},
{
"code": null,
"e": 27636,
"s": 27619,
"text": "C# | Inheritance"
},
{
"code": null,
"e": 27652,
"s": 27636,
"text": "C# | List Class"
},
{
"code": null,
"e": 27677,
"s": 27652,
"text": "Lambda Expressions in C#"
},
{
"code": null,
"e": 27727,
"s": 27677,
"text": "Difference between Hashtable and Dictionary in C#"
}
] |
What happens if loop till Maximum of Signed and Unsigned in C/C++? - GeeksforGeeks
|
31 Mar, 2020
Let us have a look at following code snippet in C/C++.
C++
C
// An Unsigned char example#include <iostream>using namespace std;void fun1(){ unsigned char i; for (i = 0; i < 256; i++) cout << i << " ";} int main(){ fun1(); return 0;} // This code is contributed by shubhamsingh10
// An Unsigned char example#include<stdio.h>void fun1(){ unsigned char i; for (i = 0; i < 256; i++) printf("%d ", i);} int main(){ fun1(); return 0;}
Infinite Loop
Explanation:
We know that the size of the character variable is 8 bits or 1 byte. Hence by base 2 representation of decimal numbers, the maximum number in 8 bits is 11111111.This is because the range of unsigned numbers in 8 bits ranges from 0 to 28-1
Now (11111111)2 = (255)10
If we drive the loop upto 255 starting from 0, it will execute the statement in the loop 256 times (both 0 and 255 inclusive). As the loop reaches to (255)10, After executing it, the variable βiβ is incremented by 1 i.e. going by the 2s complement arithmetic,
(11111111)2 + (00000001)2 = (00000000)10
Note: the end carry is discarded in this case; hence the final incremented number is 0, which results in re-execution of the loop, hence the loop runs for the infinite times. Therefore the above condition can be avoided if we put limit to unsigned char i to be lesser than 255 rather than 256.
Now consider below program:
C++
C
// A signed char example#include <iostream>using namespace std; void fun2(){ signed char i; for (i = 0; i < 128; i++) cout << i <<" ";} int main(){ fun2(); return 0;} // This code is contributed by shubhamsingh10
// A signed char example#include<stdio.h> void fun2(){ signed char i; for (i=0; i<128; i++) printf("%d ",i);} int main(){ fun2(); return 0;}
Infinite Loop
Signed char range belongs from -27 to 27-1, hence it also goes for the infinite execution if the limit is <128.
Note that the 2s complement of (127)10 is (01111111)2 adding 1 to which will give us (10000000)2, which is β(128)10 when calculated from 2s complement form.
So how to loop from 0 to max (255 or 128 or any other max limit)?One way of doing this is below.
// One way of looping till maximum of unsigned in C/C++#include<stdio.h>void fun1(){ unsigned char i = 0; do { printf("%d ", i); i++; } while (i > 0);}int main(){ fun1(); return 0;}
Output: Numbers from 0 to 255
// One way of looping till maximum of signed in C/C++// (Same as above except first statement)#include<stdio.h>void fun2(){ signed char i = 0; do { printf("%d ", i); i++; } while (i > 0);}int main(){ fun2(); return 0;}
Output in GCC: Numbers from 0 to 127
Note: In C, signed overflow is undefined behavior, hence the above solution may not work on all machines for signed numbers. Also, the output shown above for signed may not be same on all machines. The behavior is well defined for unsigned numbers.
Following are mentioned in C99 here.
About Unsigned:A computation involving unsigned operands can never overflow, because a result that cannot be represented by the resulting unsigned integer type is reduced modulo the number that is one greater than the largest value that can be represented by the resulting type
About Signed:An example of undefined behavior is the behavior on integer overflow.
This article is contributed by Pranjal Mathur. 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
SHUBHAMSINGH10
cpp-data-types
large-numbers
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Multidimensional Arrays in C / C++
Left Shift and Right Shift Operators in C/C++
Core Dump (Segmentation fault) in C/C++
rand() and srand() in C/C++
Substring in C++
Vector in C++ STL
Inheritance in C++
Initialize a vector in C++ (6 different ways)
Map in C++ Standard Template Library (STL)
Virtual Function in C++
|
[
{
"code": null,
"e": 25727,
"s": 25699,
"text": "\n31 Mar, 2020"
},
{
"code": null,
"e": 25782,
"s": 25727,
"text": "Let us have a look at following code snippet in C/C++."
},
{
"code": null,
"e": 25786,
"s": 25782,
"text": "C++"
},
{
"code": null,
"e": 25788,
"s": 25786,
"text": "C"
},
{
"code": "// An Unsigned char example#include <iostream>using namespace std;void fun1(){ unsigned char i; for (i = 0; i < 256; i++) cout << i << \" \";} int main(){ fun1(); return 0;} // This code is contributed by shubhamsingh10",
"e": 26027,
"s": 25788,
"text": null
},
{
"code": "// An Unsigned char example#include<stdio.h>void fun1(){ unsigned char i; for (i = 0; i < 256; i++) printf(\"%d \", i);} int main(){ fun1(); return 0;}",
"e": 26197,
"s": 26027,
"text": null
},
{
"code": null,
"e": 26213,
"s": 26197,
"text": " Infinite Loop "
},
{
"code": null,
"e": 26226,
"s": 26213,
"text": "Explanation:"
},
{
"code": null,
"e": 26465,
"s": 26226,
"text": "We know that the size of the character variable is 8 bits or 1 byte. Hence by base 2 representation of decimal numbers, the maximum number in 8 bits is 11111111.This is because the range of unsigned numbers in 8 bits ranges from 0 to 28-1"
},
{
"code": null,
"e": 26491,
"s": 26465,
"text": "Now (11111111)2 = (255)10"
},
{
"code": null,
"e": 26751,
"s": 26491,
"text": "If we drive the loop upto 255 starting from 0, it will execute the statement in the loop 256 times (both 0 and 255 inclusive). As the loop reaches to (255)10, After executing it, the variable βiβ is incremented by 1 i.e. going by the 2s complement arithmetic,"
},
{
"code": null,
"e": 26792,
"s": 26751,
"text": "(11111111)2 + (00000001)2 = (00000000)10"
},
{
"code": null,
"e": 27086,
"s": 26792,
"text": "Note: the end carry is discarded in this case; hence the final incremented number is 0, which results in re-execution of the loop, hence the loop runs for the infinite times. Therefore the above condition can be avoided if we put limit to unsigned char i to be lesser than 255 rather than 256."
},
{
"code": null,
"e": 27114,
"s": 27086,
"text": "Now consider below program:"
},
{
"code": null,
"e": 27118,
"s": 27114,
"text": "C++"
},
{
"code": null,
"e": 27120,
"s": 27118,
"text": "C"
},
{
"code": "// A signed char example#include <iostream>using namespace std; void fun2(){ signed char i; for (i = 0; i < 128; i++) cout << i <<\" \";} int main(){ fun2(); return 0;} // This code is contributed by shubhamsingh10",
"e": 27355,
"s": 27120,
"text": null
},
{
"code": "// A signed char example#include<stdio.h> void fun2(){ signed char i; for (i=0; i<128; i++) printf(\"%d \",i);} int main(){ fun2(); return 0;}",
"e": 27517,
"s": 27355,
"text": null
},
{
"code": null,
"e": 27534,
"s": 27517,
"text": " Infinite Loop "
},
{
"code": null,
"e": 27646,
"s": 27534,
"text": "Signed char range belongs from -27 to 27-1, hence it also goes for the infinite execution if the limit is <128."
},
{
"code": null,
"e": 27803,
"s": 27646,
"text": "Note that the 2s complement of (127)10 is (01111111)2 adding 1 to which will give us (10000000)2, which is β(128)10 when calculated from 2s complement form."
},
{
"code": null,
"e": 27900,
"s": 27803,
"text": "So how to loop from 0 to max (255 or 128 or any other max limit)?One way of doing this is below."
},
{
"code": "// One way of looping till maximum of unsigned in C/C++#include<stdio.h>void fun1(){ unsigned char i = 0; do { printf(\"%d \", i); i++; } while (i > 0);}int main(){ fun1(); return 0;}",
"e": 28117,
"s": 27900,
"text": null
},
{
"code": null,
"e": 28147,
"s": 28117,
"text": "Output: Numbers from 0 to 255"
},
{
"code": "// One way of looping till maximum of signed in C/C++// (Same as above except first statement)#include<stdio.h>void fun2(){ signed char i = 0; do { printf(\"%d \", i); i++; } while (i > 0);}int main(){ fun2(); return 0;}",
"e": 28401,
"s": 28147,
"text": null
},
{
"code": null,
"e": 28438,
"s": 28401,
"text": "Output in GCC: Numbers from 0 to 127"
},
{
"code": null,
"e": 28687,
"s": 28438,
"text": "Note: In C, signed overflow is undefined behavior, hence the above solution may not work on all machines for signed numbers. Also, the output shown above for signed may not be same on all machines. The behavior is well defined for unsigned numbers."
},
{
"code": null,
"e": 28724,
"s": 28687,
"text": "Following are mentioned in C99 here."
},
{
"code": null,
"e": 29002,
"s": 28724,
"text": "About Unsigned:A computation involving unsigned operands can never overflow, because a result that cannot be represented by the resulting unsigned integer type is reduced modulo the number that is one greater than the largest value that can be represented by the resulting type"
},
{
"code": null,
"e": 29085,
"s": 29002,
"text": "About Signed:An example of undefined behavior is the behavior on integer overflow."
},
{
"code": null,
"e": 29353,
"s": 29085,
"text": "This article is contributed by Pranjal Mathur. 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": 29477,
"s": 29353,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above"
},
{
"code": null,
"e": 29492,
"s": 29477,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 29507,
"s": 29492,
"text": "cpp-data-types"
},
{
"code": null,
"e": 29521,
"s": 29507,
"text": "large-numbers"
},
{
"code": null,
"e": 29532,
"s": 29521,
"text": "C Language"
},
{
"code": null,
"e": 29536,
"s": 29532,
"text": "C++"
},
{
"code": null,
"e": 29540,
"s": 29536,
"text": "CPP"
},
{
"code": null,
"e": 29638,
"s": 29540,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29673,
"s": 29638,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 29719,
"s": 29673,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 29759,
"s": 29719,
"text": "Core Dump (Segmentation fault) in C/C++"
},
{
"code": null,
"e": 29787,
"s": 29759,
"text": "rand() and srand() in C/C++"
},
{
"code": null,
"e": 29804,
"s": 29787,
"text": "Substring in C++"
},
{
"code": null,
"e": 29822,
"s": 29804,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 29841,
"s": 29822,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 29887,
"s": 29841,
"text": "Initialize a vector in C++ (6 different ways)"
},
{
"code": null,
"e": 29930,
"s": 29887,
"text": "Map in C++ Standard Template Library (STL)"
}
] |
Lua - Error Handling
|
Error handling is quite critical since real-world operations often require the use of complex operations, which includes file operations, database transactions and web service calls.
In any programming, there is always a requirement for error handling. Errors can be of two types which includes,
Syntax errors
Run time errors
Syntax errors occur due to improper use of various program components like operators and expressions. A simple example for syntax error is shown below.
a == 2
As you know, there is a difference between the use of a single "equal to" and double "equal to". Using one instead of the other can lead to an error. One "equal to" refers to assignment while a double "equal to" refers to comparison. Similarly, we have expressions and functions having their predefined ways of implementation.
Another example for syntax error is shown below β
for a= 1,10
print(a)
end
When we run the above program, we will get the following output β
lua: test2.lua:2: 'do' expected near 'print'
Syntax errors are much easier to handle than run time errors since, the Lua interpreter locates the error more clearly than in case of runtime error. From the above error, we can know easily that adding a do statement before print statement is required as per the Lua structure.
In case of runtime errors, the program executes successfully, but it can result in runtime errors due to mistakes in input or mishandled functions. A simple example to show run time error is shown below.
function add(a,b)
return a+b
end
add(10)
When we build the program, it will build successfully and run. Once it runs, shows a run time error.
lua: test2.lua:2: attempt to perform arithmetic on local 'b' (a nil value)
stack traceback:
test2.lua:2: in function 'add'
test2.lua:5: in main chunk
[C]: ?
This is a runtime error, which had occurred due to not passing two variables. The b parameter is expected and here it is nil and produces an error.
In order to handle errors, we often use two functions β assert and error. A simple example is shown below.
local function add(a,b)
assert(type(a) == "number", "a is not a number")
assert(type(b) == "number", "b is not a number")
return a+b
end
add(10)
When we run the above program, we will get the following error output.
lua: test2.lua:3: b is not a number
stack traceback:
[C]: in function 'assert'
test2.lua:3: in function 'add'
test2.lua:6: in main chunk
[C]: ?
The error (message [, level]) terminates the last protected function called and returns message as the error message. This function error never returns. Usually, error adds some information about the error position at the beginning of the message. The level argument specifies how to get the error position. With level 1 (the default), the error position is where the error function was called. Level 2 points the error to where the function that called error was called; and so on. Passing a level 0 avoids the addition of error position information to the message.
In Lua programming, in order to avoid throwing these errors and handling errors, we need to use the functions pcall or xpcall.
The pcall (f, arg1, ...) function calls the requested function in protected mode. If some error occurs in function f, it does not throw an error. It just returns the status of error. A simple example using pcall is shown below.
function myfunction ()
n = n/nil
end
if pcall(myfunction) then
print("Success")
else
print("Failure")
end
When we run the above program, we will get the following output.
Failure
The xpcall (f, err) function calls the requested function and also sets the error handler. Any error inside f is not propagated; instead, xpcall catches the error, calls the err function with the original error object, and returns a status code.
A simple example for xpcall is shown below.
function myfunction ()
n = n/nil
end
function myerrorhandler( err )
print( "ERROR:", err )
end
status = xpcall( myfunction, myerrorhandler )
print( status)
When we run the above program, we will get the following output.
ERROR: test2.lua:2: attempt to perform arithmetic on global 'n' (a nil value)
false
As a programmer, it is most important to ensure that you take care of proper error handling in the programs you write. Using error handling can ensure that unexpected conditions beyond the boundary conditions are handled without disturbing the user of the program.
12 Lectures
2 hours
Manish Gupta
80 Lectures
3 hours
Sanjeev Mittal
54 Lectures
3.5 hours
Mehmet GOKTEPE
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2286,
"s": 2103,
"text": "Error handling is quite critical since real-world operations often require the use of complex operations, which includes file operations, database transactions and web service calls."
},
{
"code": null,
"e": 2399,
"s": 2286,
"text": "In any programming, there is always a requirement for error handling. Errors can be of two types which includes,"
},
{
"code": null,
"e": 2413,
"s": 2399,
"text": "Syntax errors"
},
{
"code": null,
"e": 2429,
"s": 2413,
"text": "Run time errors"
},
{
"code": null,
"e": 2581,
"s": 2429,
"text": "Syntax errors occur due to improper use of various program components like operators and expressions. A simple example for syntax error is shown below."
},
{
"code": null,
"e": 2589,
"s": 2581,
"text": "a == 2\n"
},
{
"code": null,
"e": 2916,
"s": 2589,
"text": "As you know, there is a difference between the use of a single \"equal to\" and double \"equal to\". Using one instead of the other can lead to an error. One \"equal to\" refers to assignment while a double \"equal to\" refers to comparison. Similarly, we have expressions and functions having their predefined ways of implementation."
},
{
"code": null,
"e": 2966,
"s": 2916,
"text": "Another example for syntax error is shown below β"
},
{
"code": null,
"e": 2994,
"s": 2966,
"text": "for a= 1,10\n print(a)\nend"
},
{
"code": null,
"e": 3060,
"s": 2994,
"text": "When we run the above program, we will get the following output β"
},
{
"code": null,
"e": 3106,
"s": 3060,
"text": "lua: test2.lua:2: 'do' expected near 'print'\n"
},
{
"code": null,
"e": 3385,
"s": 3106,
"text": "Syntax errors are much easier to handle than run time errors since, the Lua interpreter locates the error more clearly than in case of runtime error. From the above error, we can know easily that adding a do statement before print statement is required as per the Lua structure."
},
{
"code": null,
"e": 3589,
"s": 3385,
"text": "In case of runtime errors, the program executes successfully, but it can result in runtime errors due to mistakes in input or mishandled functions. A simple example to show run time error is shown below."
},
{
"code": null,
"e": 3634,
"s": 3589,
"text": "function add(a,b)\n return a+b\nend\n\nadd(10)"
},
{
"code": null,
"e": 3735,
"s": 3634,
"text": "When we build the program, it will build successfully and run. Once it runs, shows a run time error."
},
{
"code": null,
"e": 3896,
"s": 3735,
"text": "lua: test2.lua:2: attempt to perform arithmetic on local 'b' (a nil value)\nstack traceback:\n\ttest2.lua:2: in function 'add'\n\ttest2.lua:5: in main chunk\n\t[C]: ?\n"
},
{
"code": null,
"e": 4044,
"s": 3896,
"text": "This is a runtime error, which had occurred due to not passing two variables. The b parameter is expected and here it is nil and produces an error."
},
{
"code": null,
"e": 4151,
"s": 4044,
"text": "In order to handle errors, we often use two functions β assert and error. A simple example is shown below."
},
{
"code": null,
"e": 4306,
"s": 4151,
"text": "local function add(a,b)\n assert(type(a) == \"number\", \"a is not a number\")\n assert(type(b) == \"number\", \"b is not a number\")\n return a+b\nend\n\nadd(10)"
},
{
"code": null,
"e": 4377,
"s": 4306,
"text": "When we run the above program, we will get the following error output."
},
{
"code": null,
"e": 4526,
"s": 4377,
"text": "lua: test2.lua:3: b is not a number\nstack traceback:\n\t[C]: in function 'assert'\n\ttest2.lua:3: in function 'add'\n\ttest2.lua:6: in main chunk\n\t[C]: ?\n"
},
{
"code": null,
"e": 5093,
"s": 4526,
"text": "The error (message [, level]) terminates the last protected function called and returns message as the error message. This function error never returns. Usually, error adds some information about the error position at the beginning of the message. The level argument specifies how to get the error position. With level 1 (the default), the error position is where the error function was called. Level 2 points the error to where the function that called error was called; and so on. Passing a level 0 avoids the addition of error position information to the message."
},
{
"code": null,
"e": 5220,
"s": 5093,
"text": "In Lua programming, in order to avoid throwing these errors and handling errors, we need to use the functions pcall or xpcall."
},
{
"code": null,
"e": 5448,
"s": 5220,
"text": "The pcall (f, arg1, ...) function calls the requested function in protected mode. If some error occurs in function f, it does not throw an error. It just returns the status of error. A simple example using pcall is shown below."
},
{
"code": null,
"e": 5562,
"s": 5448,
"text": "function myfunction ()\n n = n/nil\nend\n\nif pcall(myfunction) then\n print(\"Success\")\nelse\n\tprint(\"Failure\")\nend"
},
{
"code": null,
"e": 5627,
"s": 5562,
"text": "When we run the above program, we will get the following output."
},
{
"code": null,
"e": 5636,
"s": 5627,
"text": "Failure\n"
},
{
"code": null,
"e": 5882,
"s": 5636,
"text": "The xpcall (f, err) function calls the requested function and also sets the error handler. Any error inside f is not propagated; instead, xpcall catches the error, calls the err function with the original error object, and returns a status code."
},
{
"code": null,
"e": 5926,
"s": 5882,
"text": "A simple example for xpcall is shown below."
},
{
"code": null,
"e": 6090,
"s": 5926,
"text": "function myfunction ()\n n = n/nil\nend\n\nfunction myerrorhandler( err )\n print( \"ERROR:\", err )\nend\n\nstatus = xpcall( myfunction, myerrorhandler )\nprint( status)"
},
{
"code": null,
"e": 6155,
"s": 6090,
"text": "When we run the above program, we will get the following output."
},
{
"code": null,
"e": 6240,
"s": 6155,
"text": "ERROR:\ttest2.lua:2: attempt to perform arithmetic on global 'n' (a nil value)\nfalse\n"
},
{
"code": null,
"e": 6505,
"s": 6240,
"text": "As a programmer, it is most important to ensure that you take care of proper error handling in the programs you write. Using error handling can ensure that unexpected conditions beyond the boundary conditions are handled without disturbing the user of the program."
},
{
"code": null,
"e": 6538,
"s": 6505,
"text": "\n 12 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 6552,
"s": 6538,
"text": " Manish Gupta"
},
{
"code": null,
"e": 6585,
"s": 6552,
"text": "\n 80 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 6601,
"s": 6585,
"text": " Sanjeev Mittal"
},
{
"code": null,
"e": 6636,
"s": 6601,
"text": "\n 54 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 6652,
"s": 6636,
"text": " Mehmet GOKTEPE"
},
{
"code": null,
"e": 6659,
"s": 6652,
"text": " Print"
},
{
"code": null,
"e": 6670,
"s": 6659,
"text": " Add Notes"
}
] |
Python program to find average score of each students from dictionary of scores
|
Suppose we have a dictionary of students marks. The keys are names and the marks are list of numbers. We have to find the average of each students.
So, if the input is like scores = {'Amal' : [25,36,47,45],'Bimal' : [85,74,69,47],'Tarun' : [65,35,87,14],'Akash' : [74,12,36,75]}, then the output will be [38.25, 68.75, 50.25, 49.25] so 38.25 is average score for Amal, 68.75 is average score for Bimal and so on.
To solve this, we will follow these steps β
avg_scores := a new map
for each name in scores dictionary, doavg_scores[name] := average of scores present in the list scores[name]
avg_scores[name] := average of scores present in the list scores[name]
return list of all values of avg_scores
Let us see the following implementation to get better understanding
def solve(scores):
avg_scores = dict()
for name in scores:
avg_scores[name] = sum(scores[name])/len(scores[name])
return list(avg_scores.values())
scores = {'Amal' : [25,36,47,45],'Bimal' : [85,74,69,47],'Tarun' : [65,35,87,14],'Akash' : [74,12,36,75]}
print(solve(scores))
[['Amal',37],['Bimal',37],['Tarun',36],['Akash',41],['Himadri',39]]
[38, 68, 50, 49]
|
[
{
"code": null,
"e": 1210,
"s": 1062,
"text": "Suppose we have a dictionary of students marks. The keys are names and the marks are list of numbers. We have to find the average of each students."
},
{
"code": null,
"e": 1475,
"s": 1210,
"text": "So, if the input is like scores = {'Amal' : [25,36,47,45],'Bimal' : [85,74,69,47],'Tarun' : [65,35,87,14],'Akash' : [74,12,36,75]}, then the output will be [38.25, 68.75, 50.25, 49.25] so 38.25 is average score for Amal, 68.75 is average score for Bimal and so on."
},
{
"code": null,
"e": 1519,
"s": 1475,
"text": "To solve this, we will follow these steps β"
},
{
"code": null,
"e": 1543,
"s": 1519,
"text": "avg_scores := a new map"
},
{
"code": null,
"e": 1652,
"s": 1543,
"text": "for each name in scores dictionary, doavg_scores[name] := average of scores present in the list scores[name]"
},
{
"code": null,
"e": 1723,
"s": 1652,
"text": "avg_scores[name] := average of scores present in the list scores[name]"
},
{
"code": null,
"e": 1763,
"s": 1723,
"text": "return list of all values of avg_scores"
},
{
"code": null,
"e": 1831,
"s": 1763,
"text": "Let us see the following implementation to get better understanding"
},
{
"code": null,
"e": 2119,
"s": 1831,
"text": "def solve(scores):\n avg_scores = dict()\n for name in scores:\n avg_scores[name] = sum(scores[name])/len(scores[name])\n\nreturn list(avg_scores.values())\n\nscores = {'Amal' : [25,36,47,45],'Bimal' : [85,74,69,47],'Tarun' : [65,35,87,14],'Akash' : [74,12,36,75]}\nprint(solve(scores))"
},
{
"code": null,
"e": 2187,
"s": 2119,
"text": "[['Amal',37],['Bimal',37],['Tarun',36],['Akash',41],['Himadri',39]]"
},
{
"code": null,
"e": 2204,
"s": 2187,
"text": "[38, 68, 50, 49]"
}
] |
Model Parameters and Hyperparameters in Machine Learning β What is the difference? | by Benjamin Obi Tayo Ph.D. | Towards Data Science
|
In a machine learning model, there are 2 types of parameters:
Model Parameters: These are the parameters in the model that must be determined using the training data set. These are the fitted parameters.Hyperparameters: These are adjustable parameters that must be tuned in order to obtain a model with optimal performance.
Model Parameters: These are the parameters in the model that must be determined using the training data set. These are the fitted parameters.
Hyperparameters: These are adjustable parameters that must be tuned in order to obtain a model with optimal performance.
For example, suppose you want to build a simple linear regression model using an m-dimensional training data set. Then your model can be written as:
where X is the predictor matrix, and w are the weights. Here w_0, w_1, w_2, ...,w_m are the model parameters. If the model uses the gradient descent algorithm to minimize the objective function in order to determine the weights w_0, w_1, w_2, ...,w_m, then we can have an optimizer such as GradientDescent(eta, n_iter). Here eta (learning rate) and n_iter (number of iterations) are the hyperparameters that would have to be adjusted in order to obtain the best values for the model parameters w_0, w_1, w_2, ...,w_m. For more information about this, see the following example: Machine Learning: Python Linear Regression Estimator Using Gradient Descent.
Perceptron Classifier
Perceptron Classifier
Perceptron(n_iter=40, eta0=0.1, random_state=0)
Here, n_iter is the number of iterations, eta0 is the learning rate, and random_state is the seed of the pseudo random number generator to use when shuffling the data.
2. Train, Test Split Estimator
train_test_split( X, y, test_size=0.4, random_state=0)
Here, test_size represents the proportion of the dataset to include in the test split, and random_state is the seed used by the random number generator.
3. Logistic Regression Classifier
LogisticRegression(C=1000.0, random_state=0)
Here, C is the inverse of regularization strength, and random_state is the seed of the pseudo random number generator to use when shuffling the data.
4. KNN (k-Nearest Neighbors) Classifier
KNeighborsClassifier(n_neighbors=5, p=2, metric='minkowski')
Here, n_neighbors is the number of neighbors to use, p is the power parameter for the Minkowski metric. When p = 1, this is equivalent to using manhattan_distance, and euclidean_distance for p = 2.
5. Support Vector Machine Classifier
SVC(kernel='linear', C=1.0, random_state=0)
Here, kernel specifies the kernel type to be used in the algorithm, for example kernel = βlinearβ, for linear classification, or kernel = βrbfβ for non-linear classification. C is the penalty parameter of the error term, and random_state is the seed of the pseudo random number generator used when shuffling the data for probability estimates.
6. Decision Tree Classifier
DecisionTreeClassifier(criterion='entropy', max_depth=3, random_state=0)
Here, criterion is the function to measure the quality of a split, max_depth is the maximum depth of the tree, and random_state is the seed used by the random number generator.
7. Lasso Regression
Lasso(alpha = 0.1)
Here, alpha is the regularization parameter.
8. Principal Component Analysis
PCA(n_components = 4)
Here, n_components is the number of components to keep. If n_components is not set all components are kept.
It is important that during model building, these hyperparameters be fine-tuned in order to obtain the model with the highest quality. A good example of how the predictive power of a model depends on hyperparameters can be found from the figure below (source: Bad and Good Regression Analysis).
From the figure above, we see that the reliability of our model depends on hyperparameter tuning. If we just pick a random value for the learning rate such as eta = 0.1, this would lead to a poor model. Choosing a value for eta too small, such as eta = 0.00001 also produces a bad model. Our analysis shows that the best choice is when eta = 0.0001, as can be seen from the R-square values.
What makes the difference between a good and a bad machine learning model depends on oneβs ability to understand all the details of the model including knowledge about different hyperparameters and how these parameters can be tuned in order to obtain the model with the best performance. Using any machine learning model as a black box without fully understanding the intricacies of the model will lead to a falsified model.
βPython Machine Learningβ, 2nd Edition, Sebastian Raschka.Machine Learning: Python Linear Regression Estimator Using Gradient Descent.Bad and Good Regression Analysis.
βPython Machine Learningβ, 2nd Edition, Sebastian Raschka.
Machine Learning: Python Linear Regression Estimator Using Gradient Descent.
Bad and Good Regression Analysis.
|
[
{
"code": null,
"e": 234,
"s": 172,
"text": "In a machine learning model, there are 2 types of parameters:"
},
{
"code": null,
"e": 496,
"s": 234,
"text": "Model Parameters: These are the parameters in the model that must be determined using the training data set. These are the fitted parameters.Hyperparameters: These are adjustable parameters that must be tuned in order to obtain a model with optimal performance."
},
{
"code": null,
"e": 638,
"s": 496,
"text": "Model Parameters: These are the parameters in the model that must be determined using the training data set. These are the fitted parameters."
},
{
"code": null,
"e": 759,
"s": 638,
"text": "Hyperparameters: These are adjustable parameters that must be tuned in order to obtain a model with optimal performance."
},
{
"code": null,
"e": 908,
"s": 759,
"text": "For example, suppose you want to build a simple linear regression model using an m-dimensional training data set. Then your model can be written as:"
},
{
"code": null,
"e": 1563,
"s": 908,
"text": "where X is the predictor matrix, and w are the weights. Here w_0, w_1, w_2, ...,w_m are the model parameters. If the model uses the gradient descent algorithm to minimize the objective function in order to determine the weights w_0, w_1, w_2, ...,w_m, then we can have an optimizer such as GradientDescent(eta, n_iter). Here eta (learning rate) and n_iter (number of iterations) are the hyperparameters that would have to be adjusted in order to obtain the best values for the model parameters w_0, w_1, w_2, ...,w_m. For more information about this, see the following example: Machine Learning: Python Linear Regression Estimator Using Gradient Descent."
},
{
"code": null,
"e": 1585,
"s": 1563,
"text": "Perceptron Classifier"
},
{
"code": null,
"e": 1607,
"s": 1585,
"text": "Perceptron Classifier"
},
{
"code": null,
"e": 1655,
"s": 1607,
"text": "Perceptron(n_iter=40, eta0=0.1, random_state=0)"
},
{
"code": null,
"e": 1823,
"s": 1655,
"text": "Here, n_iter is the number of iterations, eta0 is the learning rate, and random_state is the seed of the pseudo random number generator to use when shuffling the data."
},
{
"code": null,
"e": 1854,
"s": 1823,
"text": "2. Train, Test Split Estimator"
},
{
"code": null,
"e": 1909,
"s": 1854,
"text": "train_test_split( X, y, test_size=0.4, random_state=0)"
},
{
"code": null,
"e": 2062,
"s": 1909,
"text": "Here, test_size represents the proportion of the dataset to include in the test split, and random_state is the seed used by the random number generator."
},
{
"code": null,
"e": 2096,
"s": 2062,
"text": "3. Logistic Regression Classifier"
},
{
"code": null,
"e": 2141,
"s": 2096,
"text": "LogisticRegression(C=1000.0, random_state=0)"
},
{
"code": null,
"e": 2291,
"s": 2141,
"text": "Here, C is the inverse of regularization strength, and random_state is the seed of the pseudo random number generator to use when shuffling the data."
},
{
"code": null,
"e": 2331,
"s": 2291,
"text": "4. KNN (k-Nearest Neighbors) Classifier"
},
{
"code": null,
"e": 2392,
"s": 2331,
"text": "KNeighborsClassifier(n_neighbors=5, p=2, metric='minkowski')"
},
{
"code": null,
"e": 2590,
"s": 2392,
"text": "Here, n_neighbors is the number of neighbors to use, p is the power parameter for the Minkowski metric. When p = 1, this is equivalent to using manhattan_distance, and euclidean_distance for p = 2."
},
{
"code": null,
"e": 2627,
"s": 2590,
"text": "5. Support Vector Machine Classifier"
},
{
"code": null,
"e": 2671,
"s": 2627,
"text": "SVC(kernel='linear', C=1.0, random_state=0)"
},
{
"code": null,
"e": 3015,
"s": 2671,
"text": "Here, kernel specifies the kernel type to be used in the algorithm, for example kernel = βlinearβ, for linear classification, or kernel = βrbfβ for non-linear classification. C is the penalty parameter of the error term, and random_state is the seed of the pseudo random number generator used when shuffling the data for probability estimates."
},
{
"code": null,
"e": 3043,
"s": 3015,
"text": "6. Decision Tree Classifier"
},
{
"code": null,
"e": 3139,
"s": 3043,
"text": "DecisionTreeClassifier(criterion='entropy', max_depth=3, random_state=0)"
},
{
"code": null,
"e": 3316,
"s": 3139,
"text": "Here, criterion is the function to measure the quality of a split, max_depth is the maximum depth of the tree, and random_state is the seed used by the random number generator."
},
{
"code": null,
"e": 3336,
"s": 3316,
"text": "7. Lasso Regression"
},
{
"code": null,
"e": 3355,
"s": 3336,
"text": "Lasso(alpha = 0.1)"
},
{
"code": null,
"e": 3400,
"s": 3355,
"text": "Here, alpha is the regularization parameter."
},
{
"code": null,
"e": 3432,
"s": 3400,
"text": "8. Principal Component Analysis"
},
{
"code": null,
"e": 3454,
"s": 3432,
"text": "PCA(n_components = 4)"
},
{
"code": null,
"e": 3562,
"s": 3454,
"text": "Here, n_components is the number of components to keep. If n_components is not set all components are kept."
},
{
"code": null,
"e": 3857,
"s": 3562,
"text": "It is important that during model building, these hyperparameters be fine-tuned in order to obtain the model with the highest quality. A good example of how the predictive power of a model depends on hyperparameters can be found from the figure below (source: Bad and Good Regression Analysis)."
},
{
"code": null,
"e": 4248,
"s": 3857,
"text": "From the figure above, we see that the reliability of our model depends on hyperparameter tuning. If we just pick a random value for the learning rate such as eta = 0.1, this would lead to a poor model. Choosing a value for eta too small, such as eta = 0.00001 also produces a bad model. Our analysis shows that the best choice is when eta = 0.0001, as can be seen from the R-square values."
},
{
"code": null,
"e": 4673,
"s": 4248,
"text": "What makes the difference between a good and a bad machine learning model depends on oneβs ability to understand all the details of the model including knowledge about different hyperparameters and how these parameters can be tuned in order to obtain the model with the best performance. Using any machine learning model as a black box without fully understanding the intricacies of the model will lead to a falsified model."
},
{
"code": null,
"e": 4841,
"s": 4673,
"text": "βPython Machine Learningβ, 2nd Edition, Sebastian Raschka.Machine Learning: Python Linear Regression Estimator Using Gradient Descent.Bad and Good Regression Analysis."
},
{
"code": null,
"e": 4900,
"s": 4841,
"text": "βPython Machine Learningβ, 2nd Edition, Sebastian Raschka."
},
{
"code": null,
"e": 4977,
"s": 4900,
"text": "Machine Learning: Python Linear Regression Estimator Using Gradient Descent."
}
] |
How to use <jsp:getProperty> action in JSP?
|
The getProperty action is used to retrieve the value of a given property and converts it to a string, and finally inserts it into the output.
The getProperty action has only two attributes, both of which are required. The syntax of the getProperty action is as follows β
<jsp:useBean id = "myName" ... />
...
<jsp:getProperty name = "myName" property = "someProperty" .../>
Following table lists out the required attributes associated with the getProperty action β
Let us define a test bean that will further be used in our example β
/* File: TestBean.java */
package action;
public class TestBean {
private String message = "No message specified";
public String getMessage() {
return(message);
}
public void setMessage(String message) {
this.message = message;
}
}
Compile the above code to the generated TestBean.class file and make sure that you copied the TestBean.class in C:\apache-tomcat-7.0.2\webapps\WEB-INF\classes\action folder and the CLASSPATH variable should also be set to this folder β
Now use the following code in main.jsp file. This loads the bean and sets/gets a simple String parameter β
<html>
<head>
<title>Using JavaBeans in JSP</title>
</head>
<body>
<center>
<h2>Using JavaBeans in JSP</h2>
<jsp:useBean id = "test" class = "action.TestBean" />
<jsp:setProperty name = "test" property = "message" value = "Hello JSP..." />
<p>Got message....</p>
<jsp:getProperty name = "test" property = "message" />
</center>
</body>
</html>
Let us now try to access main.jsp, it would display the following result β
Got message....
Hello JSP...
|
[
{
"code": null,
"e": 1204,
"s": 1062,
"text": "The getProperty action is used to retrieve the value of a given property and converts it to a string, and finally inserts it into the output."
},
{
"code": null,
"e": 1333,
"s": 1204,
"text": "The getProperty action has only two attributes, both of which are required. The syntax of the getProperty action is as follows β"
},
{
"code": null,
"e": 1436,
"s": 1333,
"text": "<jsp:useBean id = \"myName\" ... />\n...\n<jsp:getProperty name = \"myName\" property = \"someProperty\" .../>"
},
{
"code": null,
"e": 1527,
"s": 1436,
"text": "Following table lists out the required attributes associated with the getProperty action β"
},
{
"code": null,
"e": 1596,
"s": 1527,
"text": "Let us define a test bean that will further be used in our example β"
},
{
"code": null,
"e": 1857,
"s": 1596,
"text": "/* File: TestBean.java */\npackage action;\n\npublic class TestBean {\n private String message = \"No message specified\";\n\n public String getMessage() {\n return(message);\n }\n public void setMessage(String message) {\n this.message = message;\n }\n}"
},
{
"code": null,
"e": 2093,
"s": 1857,
"text": "Compile the above code to the generated TestBean.class file and make sure that you copied the TestBean.class in C:\\apache-tomcat-7.0.2\\webapps\\WEB-INF\\classes\\action folder and the CLASSPATH variable should also be set to this folder β"
},
{
"code": null,
"e": 2200,
"s": 2093,
"text": "Now use the following code in main.jsp file. This loads the bean and sets/gets a simple String parameter β"
},
{
"code": null,
"e": 2619,
"s": 2200,
"text": "<html>\n <head>\n <title>Using JavaBeans in JSP</title>\n </head>\n <body>\n <center>\n <h2>Using JavaBeans in JSP</h2>\n <jsp:useBean id = \"test\" class = \"action.TestBean\" />\n <jsp:setProperty name = \"test\" property = \"message\" value = \"Hello JSP...\" />\n <p>Got message....</p>\n <jsp:getProperty name = \"test\" property = \"message\" />\n </center>\n </body>\n</html>"
},
{
"code": null,
"e": 2694,
"s": 2619,
"text": "Let us now try to access main.jsp, it would display the following result β"
},
{
"code": null,
"e": 2723,
"s": 2694,
"text": "Got message....\nHello JSP..."
}
] |
Easily Query ORC Data in Python with PySpark | by Holly Emblem | Towards Data Science
|
Optimized Row Columnar, or ORC, is an column-oriented data storage format, that is part of the Apache Hadoop family. While ORC files and processing them might not be typically within the wheelhouse of a data scientist, there are occasions where youβll need to pull these files out and handle them using the data munging libraries of your choice.
Recently, I hit a situation where I wanted to process some object data, stored in the ORC format. When reading this out, I was unable to directly write it to a dataframe. I wanted to share some tips on taking data in an ORC format and converting it into something a little more palatable, such as a Pandas dataframe or CSV.
To do so, weβll utilise Pyspark. If youβre just getting started with Pyspark, there is a great introduction here. For this tutorial, weβll take a quick walkthrough of the PySpark library and show how we can read in an ORC file, and read it out into Pandas.
Weβll install the PySpark library from within the Terminal
Pip install pyspark
From here, weβll then pull into two parts of the PySpark library, SparkContext and SQLContext. If youβre new to Spark, then I recommend this tutorial. You can think of the SparkContext as the entry point into all of the Apache Spark services, and the heart of our Spark application. SQLContext is considered the entry point into Spark SQL functionality, and using SQLContext allows you to query Spark data in a familiar, SQL-like way.
from pyspark import SparkContext, SQLContextsc = SparkContext(βlocalβ, βSQL Appβ)sqlContext = SQLContext(sc)
You can see in the code above we have also declared some details for our SparkContext. In this instance, we say that our code is running locally, and we give it an appName, which we have called βSQL Appβ in this instance.
Once we have created our SparkContext, known as sc here, we then pass it to our SQLContext class to initialise our SparkSQL.
At this point, we have installed PySpark and created a Spark and SQL Context. Now to the important bit, reading and converting ORC data! Letβs say we have our data stored in the same folder as our python script, and itβs called βobjectHolderβ. To read it into a PySpark dataframe, we simply run the following:
df = sqlContext.read.format(βorcβ).load(βobjectHolderβ)
If we then want to convert this dataframe into a Pandas dataframe, we can simply do the following:
pandas_df = df.toPandas()
Putting it all together, our code is as follows:
from pyspark import SparkContext, SQLContextsc = SparkContext(βlocalβ, βSQL Appβ)sqlContext = SQLContext(sc)df = sqlContext.read.format(βorcβ).load(βobjectHolderβ)pandas_df = df.toPandas()
And there we have it. In just a few lines we can read a local orc file and convert it into a format weβre more used to, in this example, a Pandas dataframe.
|
[
{
"code": null,
"e": 518,
"s": 172,
"text": "Optimized Row Columnar, or ORC, is an column-oriented data storage format, that is part of the Apache Hadoop family. While ORC files and processing them might not be typically within the wheelhouse of a data scientist, there are occasions where youβll need to pull these files out and handle them using the data munging libraries of your choice."
},
{
"code": null,
"e": 842,
"s": 518,
"text": "Recently, I hit a situation where I wanted to process some object data, stored in the ORC format. When reading this out, I was unable to directly write it to a dataframe. I wanted to share some tips on taking data in an ORC format and converting it into something a little more palatable, such as a Pandas dataframe or CSV."
},
{
"code": null,
"e": 1099,
"s": 842,
"text": "To do so, weβll utilise Pyspark. If youβre just getting started with Pyspark, there is a great introduction here. For this tutorial, weβll take a quick walkthrough of the PySpark library and show how we can read in an ORC file, and read it out into Pandas."
},
{
"code": null,
"e": 1158,
"s": 1099,
"text": "Weβll install the PySpark library from within the Terminal"
},
{
"code": null,
"e": 1178,
"s": 1158,
"text": "Pip install pyspark"
},
{
"code": null,
"e": 1613,
"s": 1178,
"text": "From here, weβll then pull into two parts of the PySpark library, SparkContext and SQLContext. If youβre new to Spark, then I recommend this tutorial. You can think of the SparkContext as the entry point into all of the Apache Spark services, and the heart of our Spark application. SQLContext is considered the entry point into Spark SQL functionality, and using SQLContext allows you to query Spark data in a familiar, SQL-like way."
},
{
"code": null,
"e": 1722,
"s": 1613,
"text": "from pyspark import SparkContext, SQLContextsc = SparkContext(βlocalβ, βSQL Appβ)sqlContext = SQLContext(sc)"
},
{
"code": null,
"e": 1944,
"s": 1722,
"text": "You can see in the code above we have also declared some details for our SparkContext. In this instance, we say that our code is running locally, and we give it an appName, which we have called βSQL Appβ in this instance."
},
{
"code": null,
"e": 2069,
"s": 1944,
"text": "Once we have created our SparkContext, known as sc here, we then pass it to our SQLContext class to initialise our SparkSQL."
},
{
"code": null,
"e": 2379,
"s": 2069,
"text": "At this point, we have installed PySpark and created a Spark and SQL Context. Now to the important bit, reading and converting ORC data! Letβs say we have our data stored in the same folder as our python script, and itβs called βobjectHolderβ. To read it into a PySpark dataframe, we simply run the following:"
},
{
"code": null,
"e": 2435,
"s": 2379,
"text": "df = sqlContext.read.format(βorcβ).load(βobjectHolderβ)"
},
{
"code": null,
"e": 2534,
"s": 2435,
"text": "If we then want to convert this dataframe into a Pandas dataframe, we can simply do the following:"
},
{
"code": null,
"e": 2560,
"s": 2534,
"text": "pandas_df = df.toPandas()"
},
{
"code": null,
"e": 2609,
"s": 2560,
"text": "Putting it all together, our code is as follows:"
},
{
"code": null,
"e": 2798,
"s": 2609,
"text": "from pyspark import SparkContext, SQLContextsc = SparkContext(βlocalβ, βSQL Appβ)sqlContext = SQLContext(sc)df = sqlContext.read.format(βorcβ).load(βobjectHolderβ)pandas_df = df.toPandas()"
}
] |
Apex - For Loop
|
A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times. Consider a business case wherein, we are required to process or update the 100 records in one go. This is where the Loop syntax helps and makes work easier.
for (variable : list_or_set) { code_block }
Consider that we have an Invoice object which stores information of the daily invoices like CreatedDate, Status, etc. In this example, we will be fetching the invoices created today and have the status as Paid.
Note β Before executing this example, create at least one record in Invoice Object.
// Initializing the custom object records list to store the Invoice Records created today
List<apex_invoice__c> PaidInvoiceNumberList = new List<apex_invoice__c>();
// SOQL query which will fetch the invoice records which has been created today
PaidInvoiceNumberList = [SELECT Id,Name, APEX_Status__c FROM APEX_Invoice__c WHERE
CreatedDate = today];
// List to store the Invoice Number of Paid invoices
List<string> InvoiceNumberList = new List<string>();
// This loop will iterate on the List PaidInvoiceNumberList and will process each record
for (APEX_Invoice__c objInvoice: PaidInvoiceNumberList) {
// Condition to check the current record in context values
if (objInvoice.APEX_Status__c == 'Paid') {
// current record on which loop is iterating
System.debug('Value of Current Record on which Loop is iterating is'+objInvoice);
// if Status value is paid then it will the invoice number into List of String
InvoiceNumberList.add(objInvoice.Name);
}
}
System.debug('Value of InvoiceNumberList '+InvoiceNumberList);
14 Lectures
2 hours
Vijay Thapa
7 Lectures
2 hours
Uplatz
29 Lectures
6 hours
Ramnarayan Ramakrishnan
49 Lectures
3 hours
Ali Saleh Ali
10 Lectures
4 hours
Soham Ghosh
48 Lectures
4.5 hours
GUHARAJANM
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2348,
"s": 2052,
"text": "A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times. Consider a business case wherein, we are required to process or update the 100 records in one go. This is where the Loop syntax helps and makes work easier."
},
{
"code": null,
"e": 2393,
"s": 2348,
"text": "for (variable : list_or_set) { code_block }\n"
},
{
"code": null,
"e": 2604,
"s": 2393,
"text": "Consider that we have an Invoice object which stores information of the daily invoices like CreatedDate, Status, etc. In this example, we will be fetching the invoices created today and have the status as Paid."
},
{
"code": null,
"e": 2688,
"s": 2604,
"text": "Note β Before executing this example, create at least one record in Invoice Object."
},
{
"code": null,
"e": 3764,
"s": 2688,
"text": "// Initializing the custom object records list to store the Invoice Records created today\nList<apex_invoice__c> PaidInvoiceNumberList = new List<apex_invoice__c>();\n\n// SOQL query which will fetch the invoice records which has been created today\nPaidInvoiceNumberList = [SELECT Id,Name, APEX_Status__c FROM APEX_Invoice__c WHERE\n CreatedDate = today];\n\n// List to store the Invoice Number of Paid invoices\nList<string> InvoiceNumberList = new List<string>();\n\n// This loop will iterate on the List PaidInvoiceNumberList and will process each record\nfor (APEX_Invoice__c objInvoice: PaidInvoiceNumberList) {\n \n // Condition to check the current record in context values\n if (objInvoice.APEX_Status__c == 'Paid') {\n \n // current record on which loop is iterating\n System.debug('Value of Current Record on which Loop is iterating is'+objInvoice);\n \n // if Status value is paid then it will the invoice number into List of String\n InvoiceNumberList.add(objInvoice.Name);\n }\n}\n\nSystem.debug('Value of InvoiceNumberList '+InvoiceNumberList);"
},
{
"code": null,
"e": 3797,
"s": 3764,
"text": "\n 14 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3810,
"s": 3797,
"text": " Vijay Thapa"
},
{
"code": null,
"e": 3842,
"s": 3810,
"text": "\n 7 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3850,
"s": 3842,
"text": " Uplatz"
},
{
"code": null,
"e": 3883,
"s": 3850,
"text": "\n 29 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3908,
"s": 3883,
"text": " Ramnarayan Ramakrishnan"
},
{
"code": null,
"e": 3941,
"s": 3908,
"text": "\n 49 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 3956,
"s": 3941,
"text": " Ali Saleh Ali"
},
{
"code": null,
"e": 3989,
"s": 3956,
"text": "\n 10 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 4002,
"s": 3989,
"text": " Soham Ghosh"
},
{
"code": null,
"e": 4037,
"s": 4002,
"text": "\n 48 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 4049,
"s": 4037,
"text": " GUHARAJANM"
},
{
"code": null,
"e": 4056,
"s": 4049,
"text": " Print"
},
{
"code": null,
"e": 4067,
"s": 4056,
"text": " Add Notes"
}
] |
Solving Sudoku with AI. Iβm currently a teaching assistant for... | by Justin Svegliato | Towards Data Science
|
Iβm currently a teaching assistant for the graduate-level AI class taught by my advisor Shlomo Zilberstein at UMass Amherst. In one of the homework assignments, the students had to write some code that solves sudoku puzzles. This means Iβve been talking about how to use AI algorithms to solve sudoku way too much lately. Because itβs fresh on my mind, I figured Iβd write a quick and dirty blog post that discusses how we can use a simple AI algorithm to solve sudoku puzzles and similar games.
Before getting to sudoku, letβs go over a traditional example in AI, which is a rite of passage at this point. Suppose we have to color a map with different colors where no two neighboring regions can have the same color. Simply put, we just need to paint each region of the map a different color and none of the regions that neighbor each other can have the same color. For example, letβs say we want to color the paradigmatic example of Australia thatβs used in practically every AI class:
Now, if we had to color this map three different colors, say red, green and blue, this would be a valid solution to our map coloring problem:
As a quick aside, to turn this map into a representation that can be understood by an algorithm, we can turn it into a graph where each node represents a region and each edge represents whether or not two regions neighbor each other like this:
Notice how the region Tasmania isnβt connected to any other region. This means that we can color that region whatever we want. On the other hand, since the region Southern Australia is connected to several other regions, we have to be careful there.
More broadly, the map coloring problem that weβve discussed here is an instance of what we call a constraint satisfaction problem in AI. We usually refer to it as a CSP though. Formally, a CSP has a few attributes:
A set of n variables X = {X1, X2, ..., Xn} where each variable X1 needs to be assigned a value.
A set of n domains D = {D1, D2, ..., Dn} where each domain Di = {V1, V2, ..., Vm} has m possible values for each variable Xi. In other words, each variable has a domain, and each domain has every possible (though perhaps invalid) value for that variable.
A set of p constraints C = {C1, C2, ..., Cp} where each constraint C1 constrains some of the variables.
In short, we have a set of variables that we need to find values for, a set of domains that tell us all of the possible values for each variable, and a set of constraints that constrain the values in some way.
Once weβve specified a CSP, the goal is to find a solution that assigns a value to each of the variables but satisfies every constraint. Thatβs it!
Now, if we were to go back to our map coloring problem for Australia from before, we can easily specify a CSP that looks like this:
Variables. X = {WA, NT, SA, Q, NSW, V, T}. Each variable represents a region of Australia.
Domains. D = {{Red, Green, Blue}, ..., {Red, Green, Blue}}. Each domain just has the colors red, green, and blue.
Constraints. C = {WA != NT, WA != SA, NT != SA, NT != Q, SA != Q, SA = NSW, SA != Q, SA != NSW, SA != V, Q != NSW, NSW != V}. Each constraint makes sure no neighboring regions have the same color.
While itβs awesome that weβve represented the map coloring problem as a CSP, how do we even solve it? Thatβs where backtracking search comes in. Backtracking search is just a search algorithm that finds some assignment that satisfies a CSP. At a very high level, the algorithm assigns a value to each variable one-by-one until either reaching a valid assignment or an invalid assignment that violates some constraint, at which point it backtracks to a place in the search where there are no violations yet. To give you a little more detail, after taking in a CSP and an empty assignment as parameters, backtracking search does this:
If the assignment is complete, return the assignment.Select a variable from the CSP that hasnβt been assigned a value yet.For each value in the domain of the variable that satisfies the constraints, perform the following steps.β Add the value to the assignment.β Call the backtracking search with the partial assignment recursively.βIf the backtracking search returns a valid assignment, return it.βElse, remove the value from the assignment.Return false.
If the assignment is complete, return the assignment.
Select a variable from the CSP that hasnβt been assigned a value yet.
For each value in the domain of the variable that satisfies the constraints, perform the following steps.
β Add the value to the assignment.
β Call the backtracking search with the partial assignment recursively.
βIf the backtracking search returns a valid assignment, return it.
βElse, remove the value from the assignment.
Return false.
To give you another perspective, backtracking search just ends up being a search tree. Each level of the search tree is associated with a single variable and its valid values. At the final level of the search tree, if itβs even possible to get there, there will be an assignment such that each variable is assigned a valid value. This means that the assignment is the answer to our CSP. Visually, we can illustrate backtracking search in the following way:
Hereβs the pseudocode of backtracking search if youβre into that:
function recursiveBacktrackingSearch(assignment, csp): if assignment.isComplete(): return assignment variable = selectUnassignedVariable(csp.variables()) for each value in orderDomainValues(csp.domain()): if assignment.isConsistentWith(csp.constraints()): assignment.add(variable, value) result = recursiveBacktrackingSearch(assignment, csp) if result is false: return result assignment.remove(variable, value); return false
Thatβs it! Thatβll give us an assignment that solves our CSP. But can we do better than that? It turns out that there are some optimizations that make backtracking search more efficient. Letβs go over each one of those now.
Take a look at the selectUnassignedVariable(csp.variables()) function in the pseudocode. Notice how we didnβt actually describe how that function works. Does it select an unassigned variable randomly? Does it pick an unassigned variable in some sort of order? Or does it do something even more complex than either of those things? In short, we can use a few heuristics to select our unassigned variables in a decent order. These heuristics typically cut out huge regions of the state space (or a huge number of assignments that would normally be tried out), making backtracking search much faster.
The first heuristic is called the minimum-remaining-values heuristic. Just as the name implies, this heuristic picks the unassigned variable that has the fewest legal values remaining. This enables the backtracking search to select an unassigned value that will most likely cause a failure soon. By the way, itβs sometimes called the most-constrained-variable heuristic. Call it whatever you want though.
What happens if there are two unassigned variables that have the same number of fewest legal values remaining? Thatβs where the degree heuristic comes in. If thereβs a tie between two unassigned variables, we can simply pick the unassigned variable thatβs involved in the most constraints. The goal of this is to reduce the branching factor of backtracking search as much as possible. Itβs also referred to as the most-constraining-variable heuristic. Just rolls right off the tongue...
Now that weβve ordered the unassigned variables in a better way, we can think about how to order the values of an unassigned variable thatβs just about to be assigned a value. In the pseudocode, youβll see that this happens in the orderDomainValues(csp.domain()) function. A good way to order the values of an unassigned variable is to use the least-constraining-value heuristic. This heuristic just selects the value that rules out the fewest choices for the variables that are constrained by the unassigned variable. Why would we want to do this? While the heuristics for ordering variables try to cause failures as quickly as possible, the heuristic for ordering values aims to give backtracking search as much flexibility as possible for the other unassigned variables that will be assigned a value in the future.
Last but not least, weβll discuss one more really important way to improve backtracking search. Consider the following situation. Suppose the algorithm just assigned a value to some unassigned variable. This unassigned variable in turn constrains some other unassigned variable in our CSP. For example, in the map coloring problem, letβs say we marked the variable Western Australia down as red. What does this mean for the variables Northern Territory and Southern Australia? It means that they both canβt be red now. In fact, they could only be green and blue. While backtracking search doesnβt currently account for this type of inference, we could certainly add it. When we add the ability for backtracking search to modify the domains of other unassigned variables when it assigns a value to some variable, weβre implementing what we call constraint propagation.
Although there are many sophisticated forms of constraint propagation, weβll only talk about the simplest one in this post: forward checking. In forward checking, when some variable is assigned value, backtracking search does the following two things:
It calculates each unassigned variable that neighbors that variable.It deletes every value from the domain of each neighboring variable thatβs inconsistent with the new value of that variable.
It calculates each unassigned variable that neighbors that variable.
It deletes every value from the domain of each neighboring variable thatβs inconsistent with the new value of that variable.
To illustrate this idea, itβs time to go back to the map coloring problem again. Suppose backtracking search just started to solve the map coloring problem. In other words, backtracking search hasnβt assigned a value to any of the variables yet like this:
Letβs say we assign red to the variable Western Australia. By using forward checking, backtracking search can modify the domains of the neighboring unassigned variables Northern Territory and Southern Australia like what we see below. Youβll notice that both of those unassigned neighboring variables no longer have the color red in their domains. Why? Itβs because the variable Western Australia has been assigned the color red, which means the variables Northern Territory and Southern Australia canβt be red.
Letβs go one step further by assigning the color green to the variable Queensland. What does forward checking do now? It eliminates the color green from the domains of the variables Northern Territory, Southern Australia, and New South Wales.
Letβs talk about why this would make backtracking search faster. Basically, it does two things. First, it causes failures early because if one of the domains of the unassigned variables becomes empty, we can immediately backtrack. Second, it reduces the number of assignments that backtracking search has to try out. Simply put, by eliminating values from the domains of each unassigned variable, backtracking search naturally has to try less values.
Itβs finally time to explain how we can solve sudoku by using a CSP. Itβs surprising super easy. Like any CSP, we have to come up with the set of variables, the set of domains, and the set of constraints. Letβs do that now.
Variables. X = {A1, A2, ..., I8, I9}. Weβll just have a variable for each cell in the sudoku puzzle for a total of 81 variables. To give you a sense of what this notation means, the variable A1 is just a variable that represents the cell in the Ath row and the 1st column. For any cell thatβs filled in with a value already, weβll just automatically set those to that value. Easy.
Domains. D = {1, 2, 3, 4, 5, 6, 7, 8, 9}. For the domain of each variable, weβll just start with all of the numbers from 1 to 9. Keep in mind that forward checking will trim these domains over time. Note that, for a cell that has a number already, itβll just have a domain with a single number.
Constraints. Weβll have three types of constraints here: a constraint that says all of the variables in each column has to differ, all of the variables in each row has to differ, and all of the variables in each square has to differ. Nothing too tricky. Letβs formalize these types of constraints below.
Column Constraints. AllDiff(A1, B1, C1, D1, E1, F1, G1, H1, I1), ..., AllDiff(A9, B9, C9, D9, E9, F9, G9, H9, I9). There will be a total of 9 column constraints because there are 9 columns.Row Constraints. AllDiff(A1, A2, A3, A4, A5, A6, A7, A8, A9), ..., AllDiff(I1, I2, I3, I4, I5, I6, I7, I8, I9). Again, weβll have a total of 9 row constraints because there are 9 rows.Square Constraints. AllDiff(A1, A2, A3, B1, B2, B3, C1, C2, C3) ..., AllDiff(G7, G8, G9, H7, H8, H9, I7, I8, I9). And, surprise, weβll have 9 square constraints because there are 9 squares.
Column Constraints. AllDiff(A1, B1, C1, D1, E1, F1, G1, H1, I1), ..., AllDiff(A9, B9, C9, D9, E9, F9, G9, H9, I9). There will be a total of 9 column constraints because there are 9 columns.
Row Constraints. AllDiff(A1, A2, A3, A4, A5, A6, A7, A8, A9), ..., AllDiff(I1, I2, I3, I4, I5, I6, I7, I8, I9). Again, weβll have a total of 9 row constraints because there are 9 rows.
Square Constraints. AllDiff(A1, A2, A3, B1, B2, B3, C1, C2, C3) ..., AllDiff(G7, G8, G9, H7, H8, H9, I7, I8, I9). And, surprise, weβll have 9 square constraints because there are 9 squares.
Once youβve defined sudoku as a CSP, youβre done! All you have to do now is feed the CSP into your backtracking search algorithm to get the answer to any sudoku puzzle. Youβd be surprised how fast it is too. Even the hardest sudoku puzzles for a person can be solved in way less than a second.
|
[
{
"code": null,
"e": 667,
"s": 171,
"text": "Iβm currently a teaching assistant for the graduate-level AI class taught by my advisor Shlomo Zilberstein at UMass Amherst. In one of the homework assignments, the students had to write some code that solves sudoku puzzles. This means Iβve been talking about how to use AI algorithms to solve sudoku way too much lately. Because itβs fresh on my mind, I figured Iβd write a quick and dirty blog post that discusses how we can use a simple AI algorithm to solve sudoku puzzles and similar games."
},
{
"code": null,
"e": 1159,
"s": 667,
"text": "Before getting to sudoku, letβs go over a traditional example in AI, which is a rite of passage at this point. Suppose we have to color a map with different colors where no two neighboring regions can have the same color. Simply put, we just need to paint each region of the map a different color and none of the regions that neighbor each other can have the same color. For example, letβs say we want to color the paradigmatic example of Australia thatβs used in practically every AI class:"
},
{
"code": null,
"e": 1301,
"s": 1159,
"text": "Now, if we had to color this map three different colors, say red, green and blue, this would be a valid solution to our map coloring problem:"
},
{
"code": null,
"e": 1545,
"s": 1301,
"text": "As a quick aside, to turn this map into a representation that can be understood by an algorithm, we can turn it into a graph where each node represents a region and each edge represents whether or not two regions neighbor each other like this:"
},
{
"code": null,
"e": 1795,
"s": 1545,
"text": "Notice how the region Tasmania isnβt connected to any other region. This means that we can color that region whatever we want. On the other hand, since the region Southern Australia is connected to several other regions, we have to be careful there."
},
{
"code": null,
"e": 2010,
"s": 1795,
"text": "More broadly, the map coloring problem that weβve discussed here is an instance of what we call a constraint satisfaction problem in AI. We usually refer to it as a CSP though. Formally, a CSP has a few attributes:"
},
{
"code": null,
"e": 2106,
"s": 2010,
"text": "A set of n variables X = {X1, X2, ..., Xn} where each variable X1 needs to be assigned a value."
},
{
"code": null,
"e": 2361,
"s": 2106,
"text": "A set of n domains D = {D1, D2, ..., Dn} where each domain Di = {V1, V2, ..., Vm} has m possible values for each variable Xi. In other words, each variable has a domain, and each domain has every possible (though perhaps invalid) value for that variable."
},
{
"code": null,
"e": 2465,
"s": 2361,
"text": "A set of p constraints C = {C1, C2, ..., Cp} where each constraint C1 constrains some of the variables."
},
{
"code": null,
"e": 2675,
"s": 2465,
"text": "In short, we have a set of variables that we need to find values for, a set of domains that tell us all of the possible values for each variable, and a set of constraints that constrain the values in some way."
},
{
"code": null,
"e": 2823,
"s": 2675,
"text": "Once weβve specified a CSP, the goal is to find a solution that assigns a value to each of the variables but satisfies every constraint. Thatβs it!"
},
{
"code": null,
"e": 2955,
"s": 2823,
"text": "Now, if we were to go back to our map coloring problem for Australia from before, we can easily specify a CSP that looks like this:"
},
{
"code": null,
"e": 3046,
"s": 2955,
"text": "Variables. X = {WA, NT, SA, Q, NSW, V, T}. Each variable represents a region of Australia."
},
{
"code": null,
"e": 3160,
"s": 3046,
"text": "Domains. D = {{Red, Green, Blue}, ..., {Red, Green, Blue}}. Each domain just has the colors red, green, and blue."
},
{
"code": null,
"e": 3357,
"s": 3160,
"text": "Constraints. C = {WA != NT, WA != SA, NT != SA, NT != Q, SA != Q, SA = NSW, SA != Q, SA != NSW, SA != V, Q != NSW, NSW != V}. Each constraint makes sure no neighboring regions have the same color."
},
{
"code": null,
"e": 3990,
"s": 3357,
"text": "While itβs awesome that weβve represented the map coloring problem as a CSP, how do we even solve it? Thatβs where backtracking search comes in. Backtracking search is just a search algorithm that finds some assignment that satisfies a CSP. At a very high level, the algorithm assigns a value to each variable one-by-one until either reaching a valid assignment or an invalid assignment that violates some constraint, at which point it backtracks to a place in the search where there are no violations yet. To give you a little more detail, after taking in a CSP and an empty assignment as parameters, backtracking search does this:"
},
{
"code": null,
"e": 4446,
"s": 3990,
"text": "If the assignment is complete, return the assignment.Select a variable from the CSP that hasnβt been assigned a value yet.For each value in the domain of the variable that satisfies the constraints, perform the following steps.β Add the value to the assignment.β Call the backtracking search with the partial assignment recursively.βIf the backtracking search returns a valid assignment, return it.βElse, remove the value from the assignment.Return false."
},
{
"code": null,
"e": 4500,
"s": 4446,
"text": "If the assignment is complete, return the assignment."
},
{
"code": null,
"e": 4570,
"s": 4500,
"text": "Select a variable from the CSP that hasnβt been assigned a value yet."
},
{
"code": null,
"e": 4676,
"s": 4570,
"text": "For each value in the domain of the variable that satisfies the constraints, perform the following steps."
},
{
"code": null,
"e": 4711,
"s": 4676,
"text": "β Add the value to the assignment."
},
{
"code": null,
"e": 4783,
"s": 4711,
"text": "β Call the backtracking search with the partial assignment recursively."
},
{
"code": null,
"e": 4850,
"s": 4783,
"text": "βIf the backtracking search returns a valid assignment, return it."
},
{
"code": null,
"e": 4895,
"s": 4850,
"text": "βElse, remove the value from the assignment."
},
{
"code": null,
"e": 4909,
"s": 4895,
"text": "Return false."
},
{
"code": null,
"e": 5366,
"s": 4909,
"text": "To give you another perspective, backtracking search just ends up being a search tree. Each level of the search tree is associated with a single variable and its valid values. At the final level of the search tree, if itβs even possible to get there, there will be an assignment such that each variable is assigned a valid value. This means that the assignment is the answer to our CSP. Visually, we can illustrate backtracking search in the following way:"
},
{
"code": null,
"e": 5432,
"s": 5366,
"text": "Hereβs the pseudocode of backtracking search if youβre into that:"
},
{
"code": null,
"e": 5894,
"s": 5432,
"text": "function recursiveBacktrackingSearch(assignment, csp): if assignment.isComplete(): return assignment variable = selectUnassignedVariable(csp.variables()) for each value in orderDomainValues(csp.domain()): if assignment.isConsistentWith(csp.constraints()): assignment.add(variable, value) result = recursiveBacktrackingSearch(assignment, csp) if result is false: return result assignment.remove(variable, value); return false"
},
{
"code": null,
"e": 6118,
"s": 5894,
"text": "Thatβs it! Thatβll give us an assignment that solves our CSP. But can we do better than that? It turns out that there are some optimizations that make backtracking search more efficient. Letβs go over each one of those now."
},
{
"code": null,
"e": 6716,
"s": 6118,
"text": "Take a look at the selectUnassignedVariable(csp.variables()) function in the pseudocode. Notice how we didnβt actually describe how that function works. Does it select an unassigned variable randomly? Does it pick an unassigned variable in some sort of order? Or does it do something even more complex than either of those things? In short, we can use a few heuristics to select our unassigned variables in a decent order. These heuristics typically cut out huge regions of the state space (or a huge number of assignments that would normally be tried out), making backtracking search much faster."
},
{
"code": null,
"e": 7121,
"s": 6716,
"text": "The first heuristic is called the minimum-remaining-values heuristic. Just as the name implies, this heuristic picks the unassigned variable that has the fewest legal values remaining. This enables the backtracking search to select an unassigned value that will most likely cause a failure soon. By the way, itβs sometimes called the most-constrained-variable heuristic. Call it whatever you want though."
},
{
"code": null,
"e": 7608,
"s": 7121,
"text": "What happens if there are two unassigned variables that have the same number of fewest legal values remaining? Thatβs where the degree heuristic comes in. If thereβs a tie between two unassigned variables, we can simply pick the unassigned variable thatβs involved in the most constraints. The goal of this is to reduce the branching factor of backtracking search as much as possible. Itβs also referred to as the most-constraining-variable heuristic. Just rolls right off the tongue..."
},
{
"code": null,
"e": 8426,
"s": 7608,
"text": "Now that weβve ordered the unassigned variables in a better way, we can think about how to order the values of an unassigned variable thatβs just about to be assigned a value. In the pseudocode, youβll see that this happens in the orderDomainValues(csp.domain()) function. A good way to order the values of an unassigned variable is to use the least-constraining-value heuristic. This heuristic just selects the value that rules out the fewest choices for the variables that are constrained by the unassigned variable. Why would we want to do this? While the heuristics for ordering variables try to cause failures as quickly as possible, the heuristic for ordering values aims to give backtracking search as much flexibility as possible for the other unassigned variables that will be assigned a value in the future."
},
{
"code": null,
"e": 9294,
"s": 8426,
"text": "Last but not least, weβll discuss one more really important way to improve backtracking search. Consider the following situation. Suppose the algorithm just assigned a value to some unassigned variable. This unassigned variable in turn constrains some other unassigned variable in our CSP. For example, in the map coloring problem, letβs say we marked the variable Western Australia down as red. What does this mean for the variables Northern Territory and Southern Australia? It means that they both canβt be red now. In fact, they could only be green and blue. While backtracking search doesnβt currently account for this type of inference, we could certainly add it. When we add the ability for backtracking search to modify the domains of other unassigned variables when it assigns a value to some variable, weβre implementing what we call constraint propagation."
},
{
"code": null,
"e": 9546,
"s": 9294,
"text": "Although there are many sophisticated forms of constraint propagation, weβll only talk about the simplest one in this post: forward checking. In forward checking, when some variable is assigned value, backtracking search does the following two things:"
},
{
"code": null,
"e": 9739,
"s": 9546,
"text": "It calculates each unassigned variable that neighbors that variable.It deletes every value from the domain of each neighboring variable thatβs inconsistent with the new value of that variable."
},
{
"code": null,
"e": 9808,
"s": 9739,
"text": "It calculates each unassigned variable that neighbors that variable."
},
{
"code": null,
"e": 9933,
"s": 9808,
"text": "It deletes every value from the domain of each neighboring variable thatβs inconsistent with the new value of that variable."
},
{
"code": null,
"e": 10189,
"s": 9933,
"text": "To illustrate this idea, itβs time to go back to the map coloring problem again. Suppose backtracking search just started to solve the map coloring problem. In other words, backtracking search hasnβt assigned a value to any of the variables yet like this:"
},
{
"code": null,
"e": 10701,
"s": 10189,
"text": "Letβs say we assign red to the variable Western Australia. By using forward checking, backtracking search can modify the domains of the neighboring unassigned variables Northern Territory and Southern Australia like what we see below. Youβll notice that both of those unassigned neighboring variables no longer have the color red in their domains. Why? Itβs because the variable Western Australia has been assigned the color red, which means the variables Northern Territory and Southern Australia canβt be red."
},
{
"code": null,
"e": 10944,
"s": 10701,
"text": "Letβs go one step further by assigning the color green to the variable Queensland. What does forward checking do now? It eliminates the color green from the domains of the variables Northern Territory, Southern Australia, and New South Wales."
},
{
"code": null,
"e": 11395,
"s": 10944,
"text": "Letβs talk about why this would make backtracking search faster. Basically, it does two things. First, it causes failures early because if one of the domains of the unassigned variables becomes empty, we can immediately backtrack. Second, it reduces the number of assignments that backtracking search has to try out. Simply put, by eliminating values from the domains of each unassigned variable, backtracking search naturally has to try less values."
},
{
"code": null,
"e": 11619,
"s": 11395,
"text": "Itβs finally time to explain how we can solve sudoku by using a CSP. Itβs surprising super easy. Like any CSP, we have to come up with the set of variables, the set of domains, and the set of constraints. Letβs do that now."
},
{
"code": null,
"e": 12000,
"s": 11619,
"text": "Variables. X = {A1, A2, ..., I8, I9}. Weβll just have a variable for each cell in the sudoku puzzle for a total of 81 variables. To give you a sense of what this notation means, the variable A1 is just a variable that represents the cell in the Ath row and the 1st column. For any cell thatβs filled in with a value already, weβll just automatically set those to that value. Easy."
},
{
"code": null,
"e": 12295,
"s": 12000,
"text": "Domains. D = {1, 2, 3, 4, 5, 6, 7, 8, 9}. For the domain of each variable, weβll just start with all of the numbers from 1 to 9. Keep in mind that forward checking will trim these domains over time. Note that, for a cell that has a number already, itβll just have a domain with a single number."
},
{
"code": null,
"e": 12599,
"s": 12295,
"text": "Constraints. Weβll have three types of constraints here: a constraint that says all of the variables in each column has to differ, all of the variables in each row has to differ, and all of the variables in each square has to differ. Nothing too tricky. Letβs formalize these types of constraints below."
},
{
"code": null,
"e": 13162,
"s": 12599,
"text": "Column Constraints. AllDiff(A1, B1, C1, D1, E1, F1, G1, H1, I1), ..., AllDiff(A9, B9, C9, D9, E9, F9, G9, H9, I9). There will be a total of 9 column constraints because there are 9 columns.Row Constraints. AllDiff(A1, A2, A3, A4, A5, A6, A7, A8, A9), ..., AllDiff(I1, I2, I3, I4, I5, I6, I7, I8, I9). Again, weβll have a total of 9 row constraints because there are 9 rows.Square Constraints. AllDiff(A1, A2, A3, B1, B2, B3, C1, C2, C3) ..., AllDiff(G7, G8, G9, H7, H8, H9, I7, I8, I9). And, surprise, weβll have 9 square constraints because there are 9 squares."
},
{
"code": null,
"e": 13352,
"s": 13162,
"text": "Column Constraints. AllDiff(A1, B1, C1, D1, E1, F1, G1, H1, I1), ..., AllDiff(A9, B9, C9, D9, E9, F9, G9, H9, I9). There will be a total of 9 column constraints because there are 9 columns."
},
{
"code": null,
"e": 13537,
"s": 13352,
"text": "Row Constraints. AllDiff(A1, A2, A3, A4, A5, A6, A7, A8, A9), ..., AllDiff(I1, I2, I3, I4, I5, I6, I7, I8, I9). Again, weβll have a total of 9 row constraints because there are 9 rows."
},
{
"code": null,
"e": 13727,
"s": 13537,
"text": "Square Constraints. AllDiff(A1, A2, A3, B1, B2, B3, C1, C2, C3) ..., AllDiff(G7, G8, G9, H7, H8, H9, I7, I8, I9). And, surprise, weβll have 9 square constraints because there are 9 squares."
}
] |
βlateinitβ Variable in Kotlin
|
24 Jan, 2022
In Kotlin, there are some tokens that cannot be used as identifiers for naming variables, etc. Such tokens are known as keywords. In simple words, keywords are reserved and have special meaning to the compiler, hence they canβt be used as identifiers. For example,
as
break
class
continue
lateinit
βlateinitβ keyword:
The βlateinitβ keyword in Kotlin as the name suggests is used to declare those variables that are guaranteed to be initialized in the future.
βlateinitβ variable:
A variable that is declared using βlateinitβ keyword is known as βlateinitβ variable.
Syntax:
lateinit var myVariable: Int
This article focuses on how to check whether βlateinitβ variable is initialized.
In Kotlin 1.2 version some changes were made using which we can check whether βlateinitβ variable is initialized with the help of isInitialized method.
Syntax:
myVariable.isInitialized
Return value:
false: If myVariable is not initialized yet
true: If myVariable is initialized
Example 1:
In the below program we have declared βmyVariableβ using βlateinitβ keyword. Before initialization, we have checked whether this variable is initialized using isInitialized method. Later we have initialized it as βGFGβ. Now we are checking again whether this variable is initialized.
Kotlin
// Kotlin program to demonstrate how to check// whether lateinit variable is initialized or notclass GFG { // Declaring a lateinit variable of Int type lateinit var myVariable: String fun initializeName() { // Check using isInitialized method println("Is myVariable initialized? " + this::myVariable.isInitialized) // initializing myVariable myVariable = "GFG" // Check using isInitialized method println("Is myVariable initialized? " + this::myVariable.isInitialized) }} fun main(args: Array<String>) { // Calling method GFG().initializeName()}
Output:
Example 2:
In the below program we have declared βmyVariableβ using βlateinitβ keyword. Before initialization, we have checked whether this variable is initialized using isInitialized method. Later we have initialized it as βGeeksforGeeksβ. Now we are checking again whether this variable is initialized.
Kotlin
// Kotlin program to demonstrate how to check// whether lateinit variable is initialized or notclass GFG { // Declaring a lateinit variable lateinit var myVariable: String fun initializeName() { // Check using isInitialized method println("Is myVariable initialized? " + this::myVariable.isInitialized) // initializing myVariable myVariable = "GeeksforGeeks" // Check using isInitialized method println("Is myVariable initialized? " + this::myVariable.isInitialized) }} fun main(args: Array<String>) { // Calling method GFG().initializeName()}
Output:
simmytarika5
Picked
Kotlin
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n24 Jan, 2022"
},
{
"code": null,
"e": 293,
"s": 28,
"text": "In Kotlin, there are some tokens that cannot be used as identifiers for naming variables, etc. Such tokens are known as keywords. In simple words, keywords are reserved and have special meaning to the compiler, hence they canβt be used as identifiers. For example,"
},
{
"code": null,
"e": 296,
"s": 293,
"text": "as"
},
{
"code": null,
"e": 302,
"s": 296,
"text": "break"
},
{
"code": null,
"e": 308,
"s": 302,
"text": "class"
},
{
"code": null,
"e": 317,
"s": 308,
"text": "continue"
},
{
"code": null,
"e": 326,
"s": 317,
"text": "lateinit"
},
{
"code": null,
"e": 346,
"s": 326,
"text": "βlateinitβ keyword:"
},
{
"code": null,
"e": 488,
"s": 346,
"text": "The βlateinitβ keyword in Kotlin as the name suggests is used to declare those variables that are guaranteed to be initialized in the future."
},
{
"code": null,
"e": 510,
"s": 488,
"text": "βlateinitβ variable: "
},
{
"code": null,
"e": 596,
"s": 510,
"text": "A variable that is declared using βlateinitβ keyword is known as βlateinitβ variable."
},
{
"code": null,
"e": 604,
"s": 596,
"text": "Syntax:"
},
{
"code": null,
"e": 633,
"s": 604,
"text": "lateinit var myVariable: Int"
},
{
"code": null,
"e": 714,
"s": 633,
"text": "This article focuses on how to check whether βlateinitβ variable is initialized."
},
{
"code": null,
"e": 866,
"s": 714,
"text": "In Kotlin 1.2 version some changes were made using which we can check whether βlateinitβ variable is initialized with the help of isInitialized method."
},
{
"code": null,
"e": 874,
"s": 866,
"text": "Syntax:"
},
{
"code": null,
"e": 899,
"s": 874,
"text": "myVariable.isInitialized"
},
{
"code": null,
"e": 913,
"s": 899,
"text": "Return value:"
},
{
"code": null,
"e": 957,
"s": 913,
"text": "false: If myVariable is not initialized yet"
},
{
"code": null,
"e": 992,
"s": 957,
"text": "true: If myVariable is initialized"
},
{
"code": null,
"e": 1003,
"s": 992,
"text": "Example 1:"
},
{
"code": null,
"e": 1287,
"s": 1003,
"text": "In the below program we have declared βmyVariableβ using βlateinitβ keyword. Before initialization, we have checked whether this variable is initialized using isInitialized method. Later we have initialized it as βGFGβ. Now we are checking again whether this variable is initialized."
},
{
"code": null,
"e": 1294,
"s": 1287,
"text": "Kotlin"
},
{
"code": "// Kotlin program to demonstrate how to check// whether lateinit variable is initialized or notclass GFG { // Declaring a lateinit variable of Int type lateinit var myVariable: String fun initializeName() { // Check using isInitialized method println(\"Is myVariable initialized? \" + this::myVariable.isInitialized) // initializing myVariable myVariable = \"GFG\" // Check using isInitialized method println(\"Is myVariable initialized? \" + this::myVariable.isInitialized) }} fun main(args: Array<String>) { // Calling method GFG().initializeName()}",
"e": 1953,
"s": 1294,
"text": null
},
{
"code": null,
"e": 1961,
"s": 1953,
"text": "Output:"
},
{
"code": null,
"e": 1972,
"s": 1961,
"text": "Example 2:"
},
{
"code": null,
"e": 2266,
"s": 1972,
"text": "In the below program we have declared βmyVariableβ using βlateinitβ keyword. Before initialization, we have checked whether this variable is initialized using isInitialized method. Later we have initialized it as βGeeksforGeeksβ. Now we are checking again whether this variable is initialized."
},
{
"code": null,
"e": 2273,
"s": 2266,
"text": "Kotlin"
},
{
"code": "// Kotlin program to demonstrate how to check// whether lateinit variable is initialized or notclass GFG { // Declaring a lateinit variable lateinit var myVariable: String fun initializeName() { // Check using isInitialized method println(\"Is myVariable initialized? \" + this::myVariable.isInitialized) // initializing myVariable myVariable = \"GeeksforGeeks\" // Check using isInitialized method println(\"Is myVariable initialized? \" + this::myVariable.isInitialized) }} fun main(args: Array<String>) { // Calling method GFG().initializeName()}",
"e": 2929,
"s": 2273,
"text": null
},
{
"code": null,
"e": 2937,
"s": 2929,
"text": "Output:"
},
{
"code": null,
"e": 2950,
"s": 2937,
"text": "simmytarika5"
},
{
"code": null,
"e": 2957,
"s": 2950,
"text": "Picked"
},
{
"code": null,
"e": 2964,
"s": 2957,
"text": "Kotlin"
}
] |
Python | Pandas dataframe.pow()
|
22 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.pow() function calculates the exponential power of dataframe and other, element-wise (binary operator pow). This function is essentially same as the dataframe ** other but with a support to fill the missing values in one of the input data.
Syntax: DataFrame.pow(other, axis=βcolumnsβ, level=None, fill_value=None)
Parameters :other : Series, DataFrame, or constantaxis : For Series input, axis to match Series index onlevel : Broadcast across a level, matching Index values on the passed MultiIndex levelfill_value : Fill existing missing (NaN) values, and any new element needed for successful DataFrame alignment, with this value before computation. If data in both corresponding DataFrame locations is missing the result will be missing.**kwargs : Additional keyword arguments are passed into DataFrame.shift or Series.shift.
Returns : result : DataFrame
Example #1: Use pow() function to find the power of each element in the dataframe. Raise each element in a row to a different power using a series.
# importing pandas as pdimport pandas as pd # Creating the dataframe df1 = pd.DataFrame({"A":[14, 4, 5, 4, 1], "B":[5, 2, 54, 3, 2], "C":[20, 20, 7, 3, 8], "D":[14, 3, 6, 2, 6]}) # Print the dataframedf
Letβs create a Series
# importing pandas as pdimport pandas as pd # Create the Seriessr = pd.Series([2, 3, 4, 2], index =["A", "B", "C", "D"]) # Print the seriessr
Now, letβs use the dataframe.pow() function to raise each element in a row to different power.
# find the powerdf.pow(sr, axis = 1)
Output : Example #2: Use pow() function to raise each element of first data frame to the power of corresponding element in the other dataframe.
# importing pandas as pdimport pandas as pd # Creating the first dataframe df1 = pd.DataFrame({"A":[14, 4, 5, 4, 1], "B":[5, 2, 54, 3, 2], "C":[20, 20, 7, 3, 8], "D":[14, 3, 6, 2, 6]}) # Creating the second dataframedf2 = pd.DataFrame({"A":[1, 5, 3, 4, 2], "B":[3, 2, 4, 3, 4], "C":[2, 2, 7, 3, 4], "D":[4, 3, 6, 12, 7]}) # using pow() function to raise each element# in df1 to the power of corresponding element in df2df1.pow(df2)
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
Python OOPs Concepts
Convert integer to string in Python
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Nov, 2018"
},
{
"code": null,
"e": 242,
"s": 28,
"text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier."
},
{
"code": null,
"e": 499,
"s": 242,
"text": "Pandas dataframe.pow() function calculates the exponential power of dataframe and other, element-wise (binary operator pow). This function is essentially same as the dataframe ** other but with a support to fill the missing values in one of the input data."
},
{
"code": null,
"e": 573,
"s": 499,
"text": "Syntax: DataFrame.pow(other, axis=βcolumnsβ, level=None, fill_value=None)"
},
{
"code": null,
"e": 1088,
"s": 573,
"text": "Parameters :other : Series, DataFrame, or constantaxis : For Series input, axis to match Series index onlevel : Broadcast across a level, matching Index values on the passed MultiIndex levelfill_value : Fill existing missing (NaN) values, and any new element needed for successful DataFrame alignment, with this value before computation. If data in both corresponding DataFrame locations is missing the result will be missing.**kwargs : Additional keyword arguments are passed into DataFrame.shift or Series.shift."
},
{
"code": null,
"e": 1117,
"s": 1088,
"text": "Returns : result : DataFrame"
},
{
"code": null,
"e": 1265,
"s": 1117,
"text": "Example #1: Use pow() function to find the power of each element in the dataframe. Raise each element in a row to a different power using a series."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the dataframe df1 = pd.DataFrame({\"A\":[14, 4, 5, 4, 1], \"B\":[5, 2, 54, 3, 2], \"C\":[20, 20, 7, 3, 8], \"D\":[14, 3, 6, 2, 6]}) # Print the dataframedf",
"e": 1527,
"s": 1265,
"text": null
},
{
"code": null,
"e": 1549,
"s": 1527,
"text": "Letβs create a Series"
},
{
"code": "# importing pandas as pdimport pandas as pd # Create the Seriessr = pd.Series([2, 3, 4, 2], index =[\"A\", \"B\", \"C\", \"D\"]) # Print the seriessr",
"e": 1693,
"s": 1549,
"text": null
},
{
"code": null,
"e": 1788,
"s": 1693,
"text": "Now, letβs use the dataframe.pow() function to raise each element in a row to different power."
},
{
"code": "# find the powerdf.pow(sr, axis = 1)",
"e": 1825,
"s": 1788,
"text": null
},
{
"code": null,
"e": 1969,
"s": 1825,
"text": "Output : Example #2: Use pow() function to raise each element of first data frame to the power of corresponding element in the other dataframe."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the first dataframe df1 = pd.DataFrame({\"A\":[14, 4, 5, 4, 1], \"B\":[5, 2, 54, 3, 2], \"C\":[20, 20, 7, 3, 8], \"D\":[14, 3, 6, 2, 6]}) # Creating the second dataframedf2 = pd.DataFrame({\"A\":[1, 5, 3, 4, 2], \"B\":[3, 2, 4, 3, 4], \"C\":[2, 2, 7, 3, 4], \"D\":[4, 3, 6, 12, 7]}) # using pow() function to raise each element# in df1 to the power of corresponding element in df2df1.pow(df2)",
"e": 2519,
"s": 1969,
"text": null
},
{
"code": null,
"e": 2528,
"s": 2519,
"text": "Output :"
},
{
"code": null,
"e": 2552,
"s": 2528,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 2584,
"s": 2552,
"text": "Python pandas-dataFrame-methods"
},
{
"code": null,
"e": 2598,
"s": 2584,
"text": "Python-pandas"
},
{
"code": null,
"e": 2605,
"s": 2598,
"text": "Python"
},
{
"code": null,
"e": 2703,
"s": 2605,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2721,
"s": 2703,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2763,
"s": 2721,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2785,
"s": 2763,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2817,
"s": 2785,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2846,
"s": 2817,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2873,
"s": 2846,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2894,
"s": 2873,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2930,
"s": 2894,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 2953,
"s": 2930,
"text": "Introduction To PYTHON"
}
] |
Working with Titles and Heading β Python docx Module
|
03 Jan, 2021
Prerequisites: docx
Word documents contain formatted text wrapped within three object levels. The Lowest level- run objects, middle level- paragraph objects and highest level- document object. So, we cannot work with these documents using normal text editors. But, we can manipulate these word documents in python using the python-docx module.
Python docx module allows user to manipulate docs by either manipulating the existing one or creating a new empty document and manipulating it. It is a powerful tool as it helps you to manipulate the document to a very large extend. To add a title or heading we will use the inbuilt .add_heading() method of the document object.
Syntax: doc.add_heading(String s, level)
Parameters:
String s: It is the string data that is to be added as a heading or a title.
level: It is an integer number in the range 0-9. It raises ValueError if any value other than from this range is given as input.
When the level is set to 0, the string is printed as the title of the document. For all other values it prints a heading. The size of heading decreases as the level increases. If no level is set, by default its value is always 1.
Pip command to install this module is:
pip install python-docx
Import module
Declare docx object
Use add_heading() with appropriate parameters to add heading
Save doc file.
Program:
Python3
# Import docx NOT python-docximport docx # Create an instance of a word documentdoc = docx.Document() # Add a heading of level 0 (Also called Title)doc.add_heading('Title for the document', 0) # Add a heading of level 1doc.add_heading('Heading level 1', 1) # Add a heading of level 2doc.add_heading('Heading level 2', 2) # Add a heading of level 3doc.add_heading('Heading level 3', 3) # Add a heading of level 4doc.add_heading('Heading level 4', 4) # Add a heading of level 5doc.add_heading('Heading level 5', 5) # Add a heading of level 6doc.add_heading('Heading level 6', 6) # Add a heading of level 7doc.add_heading('Heading level 7', 7) # Add a heading of level 8doc.add_heading('Heading level 8', 8) # Add a heading of level 9doc.add_heading('Heading level 9', 9) # Now save the document to a locationdoc.save('gfg.docx')
Output:
Document gfg.docx
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n03 Jan, 2021"
},
{
"code": null,
"e": 48,
"s": 28,
"text": "Prerequisites: docx"
},
{
"code": null,
"e": 373,
"s": 48,
"text": "Word documents contain formatted text wrapped within three object levels. The Lowest level- run objects, middle level- paragraph objects and highest level- document object. So, we cannot work with these documents using normal text editors. But, we can manipulate these word documents in python using the python-docx module. "
},
{
"code": null,
"e": 702,
"s": 373,
"text": "Python docx module allows user to manipulate docs by either manipulating the existing one or creating a new empty document and manipulating it. It is a powerful tool as it helps you to manipulate the document to a very large extend. To add a title or heading we will use the inbuilt .add_heading() method of the document object."
},
{
"code": null,
"e": 743,
"s": 702,
"text": "Syntax: doc.add_heading(String s, level)"
},
{
"code": null,
"e": 755,
"s": 743,
"text": "Parameters:"
},
{
"code": null,
"e": 832,
"s": 755,
"text": "String s: It is the string data that is to be added as a heading or a title."
},
{
"code": null,
"e": 961,
"s": 832,
"text": "level: It is an integer number in the range 0-9. It raises ValueError if any value other than from this range is given as input."
},
{
"code": null,
"e": 1191,
"s": 961,
"text": "When the level is set to 0, the string is printed as the title of the document. For all other values it prints a heading. The size of heading decreases as the level increases. If no level is set, by default its value is always 1."
},
{
"code": null,
"e": 1230,
"s": 1191,
"text": "Pip command to install this module is:"
},
{
"code": null,
"e": 1254,
"s": 1230,
"text": "pip install python-docx"
},
{
"code": null,
"e": 1268,
"s": 1254,
"text": "Import module"
},
{
"code": null,
"e": 1288,
"s": 1268,
"text": "Declare docx object"
},
{
"code": null,
"e": 1349,
"s": 1288,
"text": "Use add_heading() with appropriate parameters to add heading"
},
{
"code": null,
"e": 1364,
"s": 1349,
"text": "Save doc file."
},
{
"code": null,
"e": 1373,
"s": 1364,
"text": "Program:"
},
{
"code": null,
"e": 1381,
"s": 1373,
"text": "Python3"
},
{
"code": "# Import docx NOT python-docximport docx # Create an instance of a word documentdoc = docx.Document() # Add a heading of level 0 (Also called Title)doc.add_heading('Title for the document', 0) # Add a heading of level 1doc.add_heading('Heading level 1', 1) # Add a heading of level 2doc.add_heading('Heading level 2', 2) # Add a heading of level 3doc.add_heading('Heading level 3', 3) # Add a heading of level 4doc.add_heading('Heading level 4', 4) # Add a heading of level 5doc.add_heading('Heading level 5', 5) # Add a heading of level 6doc.add_heading('Heading level 6', 6) # Add a heading of level 7doc.add_heading('Heading level 7', 7) # Add a heading of level 8doc.add_heading('Heading level 8', 8) # Add a heading of level 9doc.add_heading('Heading level 9', 9) # Now save the document to a locationdoc.save('gfg.docx')",
"e": 2220,
"s": 1381,
"text": null
},
{
"code": null,
"e": 2228,
"s": 2220,
"text": "Output:"
},
{
"code": null,
"e": 2246,
"s": 2228,
"text": "Document gfg.docx"
},
{
"code": null,
"e": 2270,
"s": 2246,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 2277,
"s": 2270,
"text": "Python"
},
{
"code": null,
"e": 2296,
"s": 2277,
"text": "Technical Scripter"
}
] |
iOS - Location Handling
|
We can easily locate the user's current location in iOS, provided the user allows the application to access the information with the help of the core location framework.
Step 1 β Create a simple View based application.
Step 2 β Select your project file, then select targets and then add CoreLocation.framework as shown below β
Step 3 β Add two labels in ViewController.xib and create ibOutlets naming the labels as latitudeLabel and longitudeLabel respectively.
Step 4 β Create a new file by selecting File β New β File... β select Objective C class and click next.
Step 5 β Name the class as LocationHandler with "sub class of" as NSObject.
Step 6 β Select create.
Step 7 β Update LocationHandler.h as follows β
#import <Foundation/Foundation.h>
#import <CoreLocation/CoreLocation.h>
@protocol LocationHandlerDelegate <NSObject>
@required
-(void) didUpdateToLocation:(CLLocation*)newLocation
fromLocation:(CLLocation*)oldLocation;
@end
@interface LocationHandler : NSObject<CLLocationManagerDelegate> {
CLLocationManager *locationManager;
}
@property(nonatomic,strong) id<LocationHandlerDelegate> delegate;
+(id)getSharedInstance;
-(void)startUpdating;
-(void) stopUpdating;
@end
Step 8 β Update LocationHandler.m as follows β
#import "LocationHandler.h"
static LocationHandler *DefaultManager = nil;
@interface LocationHandler()
-(void)initiate;
@end
@implementation LocationHandler
+(id)getSharedInstance{
if (!DefaultManager) {
DefaultManager = [[self allocWithZone:NULL]init];
[DefaultManager initiate];
}
return DefaultManager;
}
-(void)initiate {
locationManager = [[CLLocationManager alloc]init];
locationManager.delegate = self;
}
-(void)startUpdating{
[locationManager startUpdatingLocation];
}
-(void) stopUpdating {
[locationManager stopUpdatingLocation];
}
-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:
(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
if ([self.delegate respondsToSelector:@selector
(didUpdateToLocation:fromLocation:)]) {
[self.delegate didUpdateToLocation:oldLocation
fromLocation:newLocation];
}
}
@end
Step 9 β Update ViewController.h as follows where we have implemented the LocationHandler delegate and create two ibOutlets β
#import <UIKit/UIKit.h>
#import "LocationHandler.h"
@interface ViewController : UIViewController<LocationHandlerDelegate> {
IBOutlet UILabel *latitudeLabel;
IBOutlet UILabel *longitudeLabel;
}
@end
Step 10 β Update ViewController.m as follows β
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[[LocationHandler getSharedInstance]setDelegate:self];
[[LocationHandler getSharedInstance]startUpdating];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation {
[latitudeLabel setText:[NSString stringWithFormat:
@"Latitude: %f",newLocation.coordinate.latitude]];
[longitudeLabel setText:[NSString stringWithFormat:
@"Longitude: %f",newLocation.coordinate.longitude]];
}
@end
When we run the application, we'll get the following output β
23 Lectures
1.5 hours
Ashish Sharma
9 Lectures
1 hours
Abhilash Nelson
14 Lectures
1.5 hours
Abhilash Nelson
15 Lectures
1.5 hours
Abhilash Nelson
10 Lectures
1 hours
Abhilash Nelson
69 Lectures
4 hours
Frahaan Hussain
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2261,
"s": 2091,
"text": "We can easily locate the user's current location in iOS, provided the user allows the application to access the information with the help of the core location framework."
},
{
"code": null,
"e": 2310,
"s": 2261,
"text": "Step 1 β Create a simple View based application."
},
{
"code": null,
"e": 2418,
"s": 2310,
"text": "Step 2 β Select your project file, then select targets and then add CoreLocation.framework as shown below β"
},
{
"code": null,
"e": 2553,
"s": 2418,
"text": "Step 3 β Add two labels in ViewController.xib and create ibOutlets naming the labels as latitudeLabel and longitudeLabel respectively."
},
{
"code": null,
"e": 2657,
"s": 2553,
"text": "Step 4 β Create a new file by selecting File β New β File... β select Objective C class and click next."
},
{
"code": null,
"e": 2733,
"s": 2657,
"text": "Step 5 β Name the class as LocationHandler with \"sub class of\" as NSObject."
},
{
"code": null,
"e": 2757,
"s": 2733,
"text": "Step 6 β Select create."
},
{
"code": null,
"e": 2804,
"s": 2757,
"text": "Step 7 β Update LocationHandler.h as follows β"
},
{
"code": null,
"e": 3284,
"s": 2804,
"text": "#import <Foundation/Foundation.h>\n#import <CoreLocation/CoreLocation.h>\n\n@protocol LocationHandlerDelegate <NSObject>\n\n@required\n-(void) didUpdateToLocation:(CLLocation*)newLocation \n fromLocation:(CLLocation*)oldLocation;\n@end\n\n@interface LocationHandler : NSObject<CLLocationManagerDelegate> {\n CLLocationManager *locationManager;\n}\n@property(nonatomic,strong) id<LocationHandlerDelegate> delegate;\n\n+(id)getSharedInstance;\n-(void)startUpdating;\n-(void) stopUpdating;\n\n@end"
},
{
"code": null,
"e": 3331,
"s": 3284,
"text": "Step 8 β Update LocationHandler.m as follows β"
},
{
"code": null,
"e": 4251,
"s": 3331,
"text": "#import \"LocationHandler.h\"\nstatic LocationHandler *DefaultManager = nil;\n\n@interface LocationHandler()\n\n-(void)initiate;\n\n@end\n\n@implementation LocationHandler\n\n+(id)getSharedInstance{\n if (!DefaultManager) {\n DefaultManager = [[self allocWithZone:NULL]init];\n [DefaultManager initiate];\n }\n return DefaultManager;\n}\n\n-(void)initiate {\n locationManager = [[CLLocationManager alloc]init];\n locationManager.delegate = self;\n}\n\n-(void)startUpdating{\n [locationManager startUpdatingLocation];\n}\n\n-(void) stopUpdating {\n [locationManager stopUpdatingLocation];\n}\n\n-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:\n (CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {\n if ([self.delegate respondsToSelector:@selector\n (didUpdateToLocation:fromLocation:)]) {\n [self.delegate didUpdateToLocation:oldLocation \n fromLocation:newLocation];\n }\n}\n@end"
},
{
"code": null,
"e": 4377,
"s": 4251,
"text": "Step 9 β Update ViewController.h as follows where we have implemented the LocationHandler delegate and create two ibOutlets β"
},
{
"code": null,
"e": 4582,
"s": 4377,
"text": "#import <UIKit/UIKit.h>\n#import \"LocationHandler.h\"\n\n@interface ViewController : UIViewController<LocationHandlerDelegate> {\n IBOutlet UILabel *latitudeLabel;\n IBOutlet UILabel *longitudeLabel;\n}\n@end"
},
{
"code": null,
"e": 4629,
"s": 4582,
"text": "Step 10 β Update ViewController.m as follows β"
},
{
"code": null,
"e": 5335,
"s": 4629,
"text": "#import \"ViewController.h\"\n\n@interface ViewController ()\n@end\n\n@implementation ViewController\n\n- (void)viewDidLoad {\n [super viewDidLoad];\n [[LocationHandler getSharedInstance]setDelegate:self];\n [[LocationHandler getSharedInstance]startUpdating];\n}\n\n- (void)didReceiveMemoryWarning {\n [super didReceiveMemoryWarning];\n // Dispose of any resources that can be recreated.\n}\n\n-(void)didUpdateToLocation:(CLLocation *)newLocation \n fromLocation:(CLLocation *)oldLocation {\n [latitudeLabel setText:[NSString stringWithFormat:\n @\"Latitude: %f\",newLocation.coordinate.latitude]];\n [longitudeLabel setText:[NSString stringWithFormat:\n @\"Longitude: %f\",newLocation.coordinate.longitude]];\n}\n@end"
},
{
"code": null,
"e": 5397,
"s": 5335,
"text": "When we run the application, we'll get the following output β"
},
{
"code": null,
"e": 5432,
"s": 5397,
"text": "\n 23 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5447,
"s": 5432,
"text": " Ashish Sharma"
},
{
"code": null,
"e": 5479,
"s": 5447,
"text": "\n 9 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5496,
"s": 5479,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 5531,
"s": 5496,
"text": "\n 14 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5548,
"s": 5531,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 5583,
"s": 5548,
"text": "\n 15 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5600,
"s": 5583,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 5633,
"s": 5600,
"text": "\n 10 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5650,
"s": 5633,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 5683,
"s": 5650,
"text": "\n 69 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 5700,
"s": 5683,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 5707,
"s": 5700,
"text": " Print"
},
{
"code": null,
"e": 5718,
"s": 5707,
"text": " Add Notes"
}
] |
Box Plot using Plotly in Python - GeeksforGeeks
|
20 Sep, 2021
Plotly is a Python library which is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library.
A box plot is a demographic representation of numerical data through their quartiles. The end and upper quartiles are represented in box, while the median (second quartile) is notable by a line inside the box. Plotly.express is convenient,high-ranked interface to plotly which operates on variet of data and produce a easy-to-style figure.Box are much beneficial for comparing the groups of data. Box plot divide approx. 25% of section data into sets which helps ion quickly identifying values, the dispersion of the data set, and signs of skewness.
Syntax: plotly.express.box(data_frame=None, x=None, y=None, color=None, facet_row=None, facet_col=None, facet_col_wrap=0, hover_name=None, hover_data=None, custom_data=None, animation_frame=None, animation_group=None, category_orders={}, labels={}, color_discrete_sequence=None, color_discrete_map={}, orientation=None, boxmode=None, log_x=False, log_y=False, range_x=None, range_y=None, points=None, notched=False, title=None, template=None, width=None, height=None)
Parameters:
Example 1: Using Iris Dataset
Python3
import plotly.express as px df = px.data.iris() fig = px.box(df, x="sepal_width", y="sepal_length") fig.show()
Output:
Example 2: Using Tips Dataset
Python3
import plotly.express as px df = px.data.tips() fig = px.box(df, x = "sex", y="total_bill")fig.show()
Output:
In the above examples, letβs take the first box plot of the figure and understand these statistical things:
Bottom horizontal line of box plot is minimum value
First horizontal line of rectangle shape of box plot is First quartile or 25%
Second horizontal line of rectangle shape of box plot is Second quartile or 50% or median.
Third horizontal line of rectangle shape of box plot is third quartile or 75%
Top horizontal line of rectangle shape of box plot is maximum value.
Small diamond shape of blue box plot is outlier data or erroneous data.
The algorithm to choose quartiles can also be selected in plotly. It is computed by using linear algorithm by default. However, it provides two more algorithms for doing the same i.e. inclusive and exclusive.
Example 1: Using inclusive algorithm
Python3
import plotly.express as px df = px.data.tips() fig = px.box(df, x = "sex", y="total_bill", points="all")fig.update_traces(quartilemethod="inclusive") fig.show()
Output:
Example 2: Using exclusive algorithm
Python3
import plotly.express as px df = px.data.tips() fig = px.box(df, x = "sex", y="total_bill", points="all")fig.update_traces(quartilemethod="exclusive") fig.show()
Output:
Underlying data can be shows using the points arguments. The value of this argument can be of three types β
all for all points
outliers for outliers only
false for none of the above
Example 1: Passing all as argument
Python3
import plotly.express as px df = px.data.tips() fig = px.box(df, x = "sex", y="total_bill", points="all")fig.show()
Output:
Example 2:
Python3
import plotly.express as px df = px.data.tips() fig = px.box(df, x = "sex", y="total_bill", points="outliers")fig.show()
Output:
Boxplot comes with various styling options. Letβs see one such option in the below example.
Example:
Python3
import plotly.express as px df = px.data.tips() fig = px.box(df, x = "sex", y="total_bill", points="all", notched=True)fig.update_traces(quartilemethod="exclusive") fig.show()
Output:
sooda367
akshaysingh98088
Python-Plotly
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python Dictionary
Taking input in Python
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
|
[
{
"code": null,
"e": 23677,
"s": 23649,
"text": "\n20 Sep, 2021"
},
{
"code": null,
"e": 23979,
"s": 23677,
"text": "Plotly is a Python library which is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library."
},
{
"code": null,
"e": 24531,
"s": 23979,
"text": "A box plot is a demographic representation of numerical data through their quartiles. The end and upper quartiles are represented in box, while the median (second quartile) is notable by a line inside the box. Plotly.express is convenient,high-ranked interface to plotly which operates on variet of data and produce a easy-to-style figure.Box are much beneficial for comparing the groups of data. Box plot divide approx. 25% of section data into sets which helps ion quickly identifying values, the dispersion of the data set, and signs of skewness."
},
{
"code": null,
"e": 24999,
"s": 24531,
"text": "Syntax: plotly.express.box(data_frame=None, x=None, y=None, color=None, facet_row=None, facet_col=None, facet_col_wrap=0, hover_name=None, hover_data=None, custom_data=None, animation_frame=None, animation_group=None, category_orders={}, labels={}, color_discrete_sequence=None, color_discrete_map={}, orientation=None, boxmode=None, log_x=False, log_y=False, range_x=None, range_y=None, points=None, notched=False, title=None, template=None, width=None, height=None)"
},
{
"code": null,
"e": 25011,
"s": 24999,
"text": "Parameters:"
},
{
"code": null,
"e": 25041,
"s": 25011,
"text": "Example 1: Using Iris Dataset"
},
{
"code": null,
"e": 25049,
"s": 25041,
"text": "Python3"
},
{
"code": "import plotly.express as px df = px.data.iris() fig = px.box(df, x=\"sepal_width\", y=\"sepal_length\") fig.show()",
"e": 25160,
"s": 25049,
"text": null
},
{
"code": null,
"e": 25168,
"s": 25160,
"text": "Output:"
},
{
"code": null,
"e": 25198,
"s": 25168,
"text": "Example 2: Using Tips Dataset"
},
{
"code": null,
"e": 25206,
"s": 25198,
"text": "Python3"
},
{
"code": "import plotly.express as px df = px.data.tips() fig = px.box(df, x = \"sex\", y=\"total_bill\")fig.show()",
"e": 25308,
"s": 25206,
"text": null
},
{
"code": null,
"e": 25317,
"s": 25308,
"text": "Output: "
},
{
"code": null,
"e": 25427,
"s": 25319,
"text": "In the above examples, letβs take the first box plot of the figure and understand these statistical things:"
},
{
"code": null,
"e": 25479,
"s": 25427,
"text": "Bottom horizontal line of box plot is minimum value"
},
{
"code": null,
"e": 25557,
"s": 25479,
"text": "First horizontal line of rectangle shape of box plot is First quartile or 25%"
},
{
"code": null,
"e": 25648,
"s": 25557,
"text": "Second horizontal line of rectangle shape of box plot is Second quartile or 50% or median."
},
{
"code": null,
"e": 25726,
"s": 25648,
"text": "Third horizontal line of rectangle shape of box plot is third quartile or 75%"
},
{
"code": null,
"e": 25795,
"s": 25726,
"text": "Top horizontal line of rectangle shape of box plot is maximum value."
},
{
"code": null,
"e": 25867,
"s": 25795,
"text": "Small diamond shape of blue box plot is outlier data or erroneous data."
},
{
"code": null,
"e": 26076,
"s": 25867,
"text": "The algorithm to choose quartiles can also be selected in plotly. It is computed by using linear algorithm by default. However, it provides two more algorithms for doing the same i.e. inclusive and exclusive."
},
{
"code": null,
"e": 26113,
"s": 26076,
"text": "Example 1: Using inclusive algorithm"
},
{
"code": null,
"e": 26121,
"s": 26113,
"text": "Python3"
},
{
"code": "import plotly.express as px df = px.data.tips() fig = px.box(df, x = \"sex\", y=\"total_bill\", points=\"all\")fig.update_traces(quartilemethod=\"inclusive\") fig.show()",
"e": 26283,
"s": 26121,
"text": null
},
{
"code": null,
"e": 26291,
"s": 26283,
"text": "Output:"
},
{
"code": null,
"e": 26328,
"s": 26291,
"text": "Example 2: Using exclusive algorithm"
},
{
"code": null,
"e": 26336,
"s": 26328,
"text": "Python3"
},
{
"code": "import plotly.express as px df = px.data.tips() fig = px.box(df, x = \"sex\", y=\"total_bill\", points=\"all\")fig.update_traces(quartilemethod=\"exclusive\") fig.show()",
"e": 26498,
"s": 26336,
"text": null
},
{
"code": null,
"e": 26506,
"s": 26498,
"text": "Output:"
},
{
"code": null,
"e": 26615,
"s": 26506,
"text": "Underlying data can be shows using the points arguments. The value of this argument can be of three types β "
},
{
"code": null,
"e": 26634,
"s": 26615,
"text": "all for all points"
},
{
"code": null,
"e": 26661,
"s": 26634,
"text": "outliers for outliers only"
},
{
"code": null,
"e": 26689,
"s": 26661,
"text": "false for none of the above"
},
{
"code": null,
"e": 26724,
"s": 26689,
"text": "Example 1: Passing all as argument"
},
{
"code": null,
"e": 26732,
"s": 26724,
"text": "Python3"
},
{
"code": "import plotly.express as px df = px.data.tips() fig = px.box(df, x = \"sex\", y=\"total_bill\", points=\"all\")fig.show()",
"e": 26848,
"s": 26732,
"text": null
},
{
"code": null,
"e": 26856,
"s": 26848,
"text": "Output:"
},
{
"code": null,
"e": 26867,
"s": 26856,
"text": "Example 2:"
},
{
"code": null,
"e": 26875,
"s": 26867,
"text": "Python3"
},
{
"code": "import plotly.express as px df = px.data.tips() fig = px.box(df, x = \"sex\", y=\"total_bill\", points=\"outliers\")fig.show()",
"e": 26996,
"s": 26875,
"text": null
},
{
"code": null,
"e": 27005,
"s": 26996,
"text": "Output: "
},
{
"code": null,
"e": 27097,
"s": 27005,
"text": "Boxplot comes with various styling options. Letβs see one such option in the below example."
},
{
"code": null,
"e": 27106,
"s": 27097,
"text": "Example:"
},
{
"code": null,
"e": 27114,
"s": 27106,
"text": "Python3"
},
{
"code": "import plotly.express as px df = px.data.tips() fig = px.box(df, x = \"sex\", y=\"total_bill\", points=\"all\", notched=True)fig.update_traces(quartilemethod=\"exclusive\") fig.show()",
"e": 27290,
"s": 27114,
"text": null
},
{
"code": null,
"e": 27298,
"s": 27290,
"text": "Output:"
},
{
"code": null,
"e": 27307,
"s": 27298,
"text": "sooda367"
},
{
"code": null,
"e": 27324,
"s": 27307,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 27338,
"s": 27324,
"text": "Python-Plotly"
},
{
"code": null,
"e": 27345,
"s": 27338,
"text": "Python"
},
{
"code": null,
"e": 27443,
"s": 27345,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27452,
"s": 27443,
"text": "Comments"
},
{
"code": null,
"e": 27465,
"s": 27452,
"text": "Old Comments"
},
{
"code": null,
"e": 27493,
"s": 27465,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 27543,
"s": 27493,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 27565,
"s": 27543,
"text": "Python map() function"
},
{
"code": null,
"e": 27609,
"s": 27565,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 27627,
"s": 27609,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27650,
"s": 27627,
"text": "Taking input in Python"
},
{
"code": null,
"e": 27685,
"s": 27650,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 27707,
"s": 27685,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27739,
"s": 27707,
"text": "How to Install PIP on Windows ?"
}
] |
Java Examples - Display different shapes
|
How to draw a solid rectangle using GUI?
Following example demonstrates how to display a solid rectangle using fillRect() method of Graphics class.
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Main extends JPanel {
public static void main(String[] a) {
JFrame f = new JFrame();
f.setSize(400, 400);
f.add(new Main());
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
public void paint(Graphics g) {
g.fillRect (5, 15, 50, 75);
}
}
The above code sample will produce the following result.
Solid rectangle is created.
The following is an example to draw a solid rectangle using GUI.
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Panel extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(new Color(31, 21, 1));
g2d.fillRect(250, 195, 90, 60);
}
public static void main(String[] args) {
Panel rects = new Panel();
JFrame frame = new JFrame("Rectangles");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(rects);
frame.setSize(360, 300);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
The above code sample will produce the following result.
Solid rectangle is created.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2109,
"s": 2068,
"text": "How to draw a solid rectangle using GUI?"
},
{
"code": null,
"e": 2216,
"s": 2109,
"text": "Following example demonstrates how to display a solid rectangle using fillRect() method of Graphics class."
},
{
"code": null,
"e": 2619,
"s": 2216,
"text": "import java.awt.Graphics;\nimport javax.swing.JFrame;\nimport javax.swing.JPanel;\n\npublic class Main extends JPanel {\n public static void main(String[] a) {\n JFrame f = new JFrame();\n f.setSize(400, 400);\n f.add(new Main());\n f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n f.setVisible(true);\n }\n public void paint(Graphics g) {\n g.fillRect (5, 15, 50, 75);\n }\n}"
},
{
"code": null,
"e": 2676,
"s": 2619,
"text": "The above code sample will produce the following result."
},
{
"code": null,
"e": 2705,
"s": 2676,
"text": "Solid rectangle is created.\n"
},
{
"code": null,
"e": 2770,
"s": 2705,
"text": "The following is an example to draw a solid rectangle using GUI."
},
{
"code": null,
"e": 3455,
"s": 2770,
"text": "import java.awt.Color;\nimport java.awt.Graphics;\nimport java.awt.Graphics2D;\nimport javax.swing.JFrame;\nimport javax.swing.JPanel;\n\npublic class Panel extends JPanel {\n public void paintComponent(Graphics g) {\n super.paintComponent(g);\n Graphics2D g2d = (Graphics2D) g;\n g2d.setColor(new Color(31, 21, 1));\n g2d.fillRect(250, 195, 90, 60);\n } \n public static void main(String[] args) {\n Panel rects = new Panel();\n JFrame frame = new JFrame(\"Rectangles\");\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n frame.add(rects);\n frame.setSize(360, 300);\n frame.setLocationRelativeTo(null);\n frame.setVisible(true);\n }\n}"
},
{
"code": null,
"e": 3512,
"s": 3455,
"text": "The above code sample will produce the following result."
},
{
"code": null,
"e": 3541,
"s": 3512,
"text": "Solid rectangle is created.\n"
},
{
"code": null,
"e": 3548,
"s": 3541,
"text": " Print"
},
{
"code": null,
"e": 3559,
"s": 3548,
"text": " Add Notes"
}
] |
C++ ios Library - Boolalpha Function
|
It is used to sets the boolalpha format flag for the str stream. When the boolalpha format flag is set, bool values are inserted/extracted by their textual representation: either true or false, instead of integral values.
Following is the declaration for std::boolalpha function.
ios_base& boolalpha (ios_base& str);
str β Stream object whose format flag is affected.
It returns Argument str.
Basic guarantee β if an exception is thrown, str is in a valid state.
It modifies str. Concurrent access to the same stream object may cause data races.
In below example explains about std::boolalpha function.
#include <iostream>
int main () {
bool b = true;
std::cout << std::boolalpha << b << '\n';
std::cout << std::noboolalpha << b << '\n';
return 0;
}
Let us compile and run the above program, this will produce the following result β
true
1
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2825,
"s": 2603,
"text": "It is used to sets the boolalpha format flag for the str stream. When the boolalpha format flag is set, bool values are inserted/extracted by their textual representation: either true or false, instead of integral values."
},
{
"code": null,
"e": 2883,
"s": 2825,
"text": "Following is the declaration for std::boolalpha function."
},
{
"code": null,
"e": 2920,
"s": 2883,
"text": "ios_base& boolalpha (ios_base& str);"
},
{
"code": null,
"e": 2971,
"s": 2920,
"text": "str β Stream object whose format flag is affected."
},
{
"code": null,
"e": 2996,
"s": 2971,
"text": "It returns Argument str."
},
{
"code": null,
"e": 3066,
"s": 2996,
"text": "Basic guarantee β if an exception is thrown, str is in a valid state."
},
{
"code": null,
"e": 3149,
"s": 3066,
"text": "It modifies str. Concurrent access to the same stream object may cause data races."
},
{
"code": null,
"e": 3206,
"s": 3149,
"text": "In below example explains about std::boolalpha function."
},
{
"code": null,
"e": 3371,
"s": 3206,
"text": "#include <iostream> \n\nint main () {\n bool b = true;\n std::cout << std::boolalpha << b << '\\n';\n std::cout << std::noboolalpha << b << '\\n';\n return 0;\n}"
},
{
"code": null,
"e": 3454,
"s": 3371,
"text": "Let us compile and run the above program, this will produce the following result β"
},
{
"code": null,
"e": 3462,
"s": 3454,
"text": "true\n1\n"
},
{
"code": null,
"e": 3469,
"s": 3462,
"text": " Print"
},
{
"code": null,
"e": 3480,
"s": 3469,
"text": " Add Notes"
}
] |
What Bias-Variance Bulls-Eye Diagram Really Represents | by Angela Shi | Towards Data Science
|
When looking for Bias-Variance tradeoff, we can see the following bulls-eye diagram:
They seem intuitive and eye-catching to represent the bias and the variance, with some blue dots. But what do they really mean? The central point represents the target, but what do the blue dots really represent? And how these bulls-eyes are related to underfitting and overfitting?
The bias-variance tradeoff is related to the notions of overfitting and underfitting. To illustrate, we can take the example of Polynomial Regression. In the following example, the real relationship between x and y is quadratic
So if we use a simple linear regression, the model is underfitted;
If the degree of the polynomial is too high (8 for example), then the model is overfitted.
And the optimal model is of degree 2.
Now if we go back to the bulls-eye diagram, the relationship is stated as follows:
The optimal model corresponds to low variance and low bias. (OK, understandable)
Overfitting corresponds to high variance and low bias. (But why? how is it related to 8th-degree polynomial regression as seen in the previous digram?)
Underfitting corresponds to high bias and low variance. (But why? how is it related to the simple regression as seen in the previous diagram?)
And what about high variance and high bias? What model would lead to this situation?
If we put them together, how can we relate the dots in the bulls-eye to the data points in the graphics of the regressions?
At the first glance, the bulls-eye diagram is quite intuitive and eye-catching. But if we really try to ask this question to ourselves: each prediction point has two coordinates? What are the two dimensions?
Then we realize that the eyes are just an artistic representation of the target variable values. Because we usually have only one target variable. So if we want to be more accurate, we should only show one dimension.
The red dot on the middle is the real value (of one specific observation) we try to predict. And the blue dots are the predictions of different models we build.
So if we want to describe the comparison between the target value and the predictions more accurately, the bulls-eye would become only one axis, which represents the target variable.
Now, what do they really represent, how can we create a concrete example of model? Letβs code.
We are going to create multiple models to illustrate the relationship between (underfitting and overfitting) and (bias-variance tradeoff), in the following process:
First, we choose to generate some simple data from a known function.
Then we can try to create models
For one or multiple new observations, we can do the prediction and see the variance and bias.
We can generate some data that has a true relationship that is quadratic.
import numpy as npimport pandas as pdn = 20x = np.linspace(0,7,n) + np.random.randn(n)*0.1def f(x): return (x-3)**2y = f(x)+np.random.randn(n)
And we can plot the data, with the real function that is red.
To create underfitted models with the previous data, we can create simple linear regression. With some training data chosen from the original dataset, we can create some models.
for i in range(20): model = make_pipeline(PolynomialFeatures(1), LinearRegression()) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.5) model.fit(X_train, y_train) y_plot = model.predict(X_seq) plt.plot(X_seq, y_plot,c=βcβ) plt.scatter(4, model.predict([[4]]),s=300,c=βcβ)
If we do predictions for the value of 4, we can get the following plot:
the red dot is the real target value
the blue dots are the predictions of the models (simple linear regressions) created by samples of training data.
Now, we can clearly see the bias. And we can do the predictions for several values
And now, letβs do a recap for different illustrations:
For overfitting, we can create the same comparison, by changing the degree of the polynomial.
for i in range(20): model = make_pipeline(PolynomialFeatures(8), LinearRegression()) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.5) model.fit(X_train, y_train) y_plot = model.predict(X_seq) plt.plot(X_seq, y_plot,c=βcβ) plt.scatter(4, model.predict([[4]]),s=300,c=βcβ)
When the degree of the polynomial is 2, we can can clearly that the predictions of the models have low biais and low variance.
We can also illustrate with a regression tree
I hope that now you see the bias-variance bulls-eye in a more accurate way.
If so, one last thing: what is the model that could have high variance and high biais?
|
[
{
"code": null,
"e": 256,
"s": 171,
"text": "When looking for Bias-Variance tradeoff, we can see the following bulls-eye diagram:"
},
{
"code": null,
"e": 539,
"s": 256,
"text": "They seem intuitive and eye-catching to represent the bias and the variance, with some blue dots. But what do they really mean? The central point represents the target, but what do the blue dots really represent? And how these bulls-eyes are related to underfitting and overfitting?"
},
{
"code": null,
"e": 767,
"s": 539,
"text": "The bias-variance tradeoff is related to the notions of overfitting and underfitting. To illustrate, we can take the example of Polynomial Regression. In the following example, the real relationship between x and y is quadratic"
},
{
"code": null,
"e": 834,
"s": 767,
"text": "So if we use a simple linear regression, the model is underfitted;"
},
{
"code": null,
"e": 925,
"s": 834,
"text": "If the degree of the polynomial is too high (8 for example), then the model is overfitted."
},
{
"code": null,
"e": 963,
"s": 925,
"text": "And the optimal model is of degree 2."
},
{
"code": null,
"e": 1046,
"s": 963,
"text": "Now if we go back to the bulls-eye diagram, the relationship is stated as follows:"
},
{
"code": null,
"e": 1127,
"s": 1046,
"text": "The optimal model corresponds to low variance and low bias. (OK, understandable)"
},
{
"code": null,
"e": 1279,
"s": 1127,
"text": "Overfitting corresponds to high variance and low bias. (But why? how is it related to 8th-degree polynomial regression as seen in the previous digram?)"
},
{
"code": null,
"e": 1422,
"s": 1279,
"text": "Underfitting corresponds to high bias and low variance. (But why? how is it related to the simple regression as seen in the previous diagram?)"
},
{
"code": null,
"e": 1507,
"s": 1422,
"text": "And what about high variance and high bias? What model would lead to this situation?"
},
{
"code": null,
"e": 1631,
"s": 1507,
"text": "If we put them together, how can we relate the dots in the bulls-eye to the data points in the graphics of the regressions?"
},
{
"code": null,
"e": 1839,
"s": 1631,
"text": "At the first glance, the bulls-eye diagram is quite intuitive and eye-catching. But if we really try to ask this question to ourselves: each prediction point has two coordinates? What are the two dimensions?"
},
{
"code": null,
"e": 2056,
"s": 1839,
"text": "Then we realize that the eyes are just an artistic representation of the target variable values. Because we usually have only one target variable. So if we want to be more accurate, we should only show one dimension."
},
{
"code": null,
"e": 2217,
"s": 2056,
"text": "The red dot on the middle is the real value (of one specific observation) we try to predict. And the blue dots are the predictions of different models we build."
},
{
"code": null,
"e": 2400,
"s": 2217,
"text": "So if we want to describe the comparison between the target value and the predictions more accurately, the bulls-eye would become only one axis, which represents the target variable."
},
{
"code": null,
"e": 2495,
"s": 2400,
"text": "Now, what do they really represent, how can we create a concrete example of model? Letβs code."
},
{
"code": null,
"e": 2660,
"s": 2495,
"text": "We are going to create multiple models to illustrate the relationship between (underfitting and overfitting) and (bias-variance tradeoff), in the following process:"
},
{
"code": null,
"e": 2729,
"s": 2660,
"text": "First, we choose to generate some simple data from a known function."
},
{
"code": null,
"e": 2762,
"s": 2729,
"text": "Then we can try to create models"
},
{
"code": null,
"e": 2856,
"s": 2762,
"text": "For one or multiple new observations, we can do the prediction and see the variance and bias."
},
{
"code": null,
"e": 2930,
"s": 2856,
"text": "We can generate some data that has a true relationship that is quadratic."
},
{
"code": null,
"e": 3076,
"s": 2930,
"text": "import numpy as npimport pandas as pdn = 20x = np.linspace(0,7,n) + np.random.randn(n)*0.1def f(x): return (x-3)**2y = f(x)+np.random.randn(n)"
},
{
"code": null,
"e": 3138,
"s": 3076,
"text": "And we can plot the data, with the real function that is red."
},
{
"code": null,
"e": 3316,
"s": 3138,
"text": "To create underfitted models with the previous data, we can create simple linear regression. With some training data chosen from the original dataset, we can create some models."
},
{
"code": null,
"e": 3629,
"s": 3316,
"text": "for i in range(20): model = make_pipeline(PolynomialFeatures(1), LinearRegression()) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.5) model.fit(X_train, y_train) y_plot = model.predict(X_seq) plt.plot(X_seq, y_plot,c=βcβ) plt.scatter(4, model.predict([[4]]),s=300,c=βcβ)"
},
{
"code": null,
"e": 3701,
"s": 3629,
"text": "If we do predictions for the value of 4, we can get the following plot:"
},
{
"code": null,
"e": 3738,
"s": 3701,
"text": "the red dot is the real target value"
},
{
"code": null,
"e": 3851,
"s": 3738,
"text": "the blue dots are the predictions of the models (simple linear regressions) created by samples of training data."
},
{
"code": null,
"e": 3934,
"s": 3851,
"text": "Now, we can clearly see the bias. And we can do the predictions for several values"
},
{
"code": null,
"e": 3989,
"s": 3934,
"text": "And now, letβs do a recap for different illustrations:"
},
{
"code": null,
"e": 4083,
"s": 3989,
"text": "For overfitting, we can create the same comparison, by changing the degree of the polynomial."
},
{
"code": null,
"e": 4396,
"s": 4083,
"text": "for i in range(20): model = make_pipeline(PolynomialFeatures(8), LinearRegression()) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.5) model.fit(X_train, y_train) y_plot = model.predict(X_seq) plt.plot(X_seq, y_plot,c=βcβ) plt.scatter(4, model.predict([[4]]),s=300,c=βcβ)"
},
{
"code": null,
"e": 4523,
"s": 4396,
"text": "When the degree of the polynomial is 2, we can can clearly that the predictions of the models have low biais and low variance."
},
{
"code": null,
"e": 4569,
"s": 4523,
"text": "We can also illustrate with a regression tree"
},
{
"code": null,
"e": 4645,
"s": 4569,
"text": "I hope that now you see the bias-variance bulls-eye in a more accurate way."
}
] |
Maximum value of an integer for which factorial can be calculated on a machine - GeeksforGeeks
|
26 Jun, 2021
Program to find maximum value of an integer for which factorial can be calculated on a machine, assuming that factorial is stored using basic data type like long long int.
The idea is based on that fact that, in most of the machines, when we cross limit of integer, the values becomes negative.
C
Java
Python3
C#
PHP
Javascript
// C program to find maximum value of// an integer for which factorial can// be calculated on your system#include <stdio.h> int findMaxValue(){ int res = 2; long long int fact = 2; while (1) { // when fact crosses its size, // it gives negative value if (fact < 0) break; res++; fact = fact * res; } return res - 1;} // Driver Codeint main(){ printf ("Maximum value of integer : %d\n", findMaxValue()); return 0;}
// Java program to find maximum value of// an integer for which factorial can be// calculated on your systemimport java.io.*;import java.util.*; class GFG{ public static int findMaxValue() { int res = 2; long fact = 2; while (true) { // when fact crosses its size, // it gives negative value if (fact < 0) break; res++; fact = fact * res; } return res - 1; } // Driver Code public static void main(String[] args) { System.out.println("Maximum value of"+ " integer " + findMaxValue()); }}
# Python3 program to find maximum value of# an integer for which factorial can be# calculated on your systemimport sysdef findMaxValue(): res = 2; fact = 2; while (True): # when fact crosses its size # it gives negative value if (fact < 0 or fact > sys.maxsize): break; res += 1; fact = fact * res; return res - 1; # Driver Codeif __name__ == '__main__': print("Maximum value of integer:", findMaxValue()); # This code is contributed by 29AjayKumar
// C# program to find maximum value of// an integer for which factorial can// be calculated on your systemusing System; class GFG{ public static int findMaxValue() { int res = 2; long fact = 2; while (true) { // when fact crosses its size, // it gives negative value if (fact < 0) break; res++; fact = fact * res; } return res - 1; } // Driver Code public static void Main() { Console.Write("Maximum value of"+ " integer " + findMaxValue()); }} // This code is contributed by nitin mittal
<?php// PHP program to find maximum// value of an integer for which// factorial can be calculated// on your systemfunction findMaxValue(){ $res = 2; $fact = 2; $pos = -1; while (true) { // when fact crosses its size, // it gives negative value $mystring = $fact; $pos = strpos($mystring, 'E'); if ($pos > 0) break; $res++; $fact = $fact * $res; } return $res - 1;} // Driver Codeecho "Maximum value of". " integer " . findMaxValue(); // This code is contributed by Sam007?>
<script> // Javascript program to find maximum// value of an integer for which factorial// can be calculated on your systemfunction findMaxValue(){ let res = 2; let fact = 2; while (true) { // When fact crosses its size, // it gives negative value if (fact < 0 || fact > 9223372036854775807) break; res++; fact = fact * res; } return res - 1;} // Driver Codedocument.write("Maximum value of"+ " integer " + findMaxValue()); // This code is contributed by rag2127 </script>
Output :
Maximum value of integer : 20
This article is contributed by Pramod 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.
nitin mittal
Sam007
29AjayKumar
rag2127
factorial
Mathematical
Mathematical
factorial
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Algorithm to solve Rubik's Cube
Modular multiplicative inverse
Program to multiply two matrices
Program to convert a given number to words
Count ways to reach the n'th stair
Fizz Buzz Implementation
Program to print prime numbers from 1 to N.
Singular Value Decomposition (SVD)
Find first and last digits of a number
Check if a number is Palindrome
|
[
{
"code": null,
"e": 24638,
"s": 24610,
"text": "\n26 Jun, 2021"
},
{
"code": null,
"e": 24810,
"s": 24638,
"text": "Program to find maximum value of an integer for which factorial can be calculated on a machine, assuming that factorial is stored using basic data type like long long int."
},
{
"code": null,
"e": 24934,
"s": 24810,
"text": "The idea is based on that fact that, in most of the machines, when we cross limit of integer, the values becomes negative. "
},
{
"code": null,
"e": 24936,
"s": 24934,
"text": "C"
},
{
"code": null,
"e": 24941,
"s": 24936,
"text": "Java"
},
{
"code": null,
"e": 24949,
"s": 24941,
"text": "Python3"
},
{
"code": null,
"e": 24952,
"s": 24949,
"text": "C#"
},
{
"code": null,
"e": 24956,
"s": 24952,
"text": "PHP"
},
{
"code": null,
"e": 24967,
"s": 24956,
"text": "Javascript"
},
{
"code": "// C program to find maximum value of// an integer for which factorial can// be calculated on your system#include <stdio.h> int findMaxValue(){ int res = 2; long long int fact = 2; while (1) { // when fact crosses its size, // it gives negative value if (fact < 0) break; res++; fact = fact * res; } return res - 1;} // Driver Codeint main(){ printf (\"Maximum value of integer : %d\\n\", findMaxValue()); return 0;}",
"e": 25483,
"s": 24967,
"text": null
},
{
"code": "// Java program to find maximum value of// an integer for which factorial can be// calculated on your systemimport java.io.*;import java.util.*; class GFG{ public static int findMaxValue() { int res = 2; long fact = 2; while (true) { // when fact crosses its size, // it gives negative value if (fact < 0) break; res++; fact = fact * res; } return res - 1; } // Driver Code public static void main(String[] args) { System.out.println(\"Maximum value of\"+ \" integer \" + findMaxValue()); }}",
"e": 26173,
"s": 25483,
"text": null
},
{
"code": "# Python3 program to find maximum value of# an integer for which factorial can be# calculated on your systemimport sysdef findMaxValue(): res = 2; fact = 2; while (True): # when fact crosses its size # it gives negative value if (fact < 0 or fact > sys.maxsize): break; res += 1; fact = fact * res; return res - 1; # Driver Codeif __name__ == '__main__': print(\"Maximum value of integer:\", findMaxValue()); # This code is contributed by 29AjayKumar",
"e": 26723,
"s": 26173,
"text": null
},
{
"code": "// C# program to find maximum value of// an integer for which factorial can// be calculated on your systemusing System; class GFG{ public static int findMaxValue() { int res = 2; long fact = 2; while (true) { // when fact crosses its size, // it gives negative value if (fact < 0) break; res++; fact = fact * res; } return res - 1; } // Driver Code public static void Main() { Console.Write(\"Maximum value of\"+ \" integer \" + findMaxValue()); }} // This code is contributed by nitin mittal",
"e": 27404,
"s": 26723,
"text": null
},
{
"code": "<?php// PHP program to find maximum// value of an integer for which// factorial can be calculated// on your systemfunction findMaxValue(){ $res = 2; $fact = 2; $pos = -1; while (true) { // when fact crosses its size, // it gives negative value $mystring = $fact; $pos = strpos($mystring, 'E'); if ($pos > 0) break; $res++; $fact = $fact * $res; } return $res - 1;} // Driver Codeecho \"Maximum value of\". \" integer \" . findMaxValue(); // This code is contributed by Sam007?>",
"e": 27986,
"s": 27404,
"text": null
},
{
"code": "<script> // Javascript program to find maximum// value of an integer for which factorial// can be calculated on your systemfunction findMaxValue(){ let res = 2; let fact = 2; while (true) { // When fact crosses its size, // it gives negative value if (fact < 0 || fact > 9223372036854775807) break; res++; fact = fact * res; } return res - 1;} // Driver Codedocument.write(\"Maximum value of\"+ \" integer \" + findMaxValue()); // This code is contributed by rag2127 </script>",
"e": 28564,
"s": 27986,
"text": null
},
{
"code": null,
"e": 28574,
"s": 28564,
"text": "Output : "
},
{
"code": null,
"e": 28604,
"s": 28574,
"text": "Maximum value of integer : 20"
},
{
"code": null,
"e": 29025,
"s": 28604,
"text": "This article is contributed by Pramod 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": 29038,
"s": 29025,
"text": "nitin mittal"
},
{
"code": null,
"e": 29045,
"s": 29038,
"text": "Sam007"
},
{
"code": null,
"e": 29057,
"s": 29045,
"text": "29AjayKumar"
},
{
"code": null,
"e": 29065,
"s": 29057,
"text": "rag2127"
},
{
"code": null,
"e": 29075,
"s": 29065,
"text": "factorial"
},
{
"code": null,
"e": 29088,
"s": 29075,
"text": "Mathematical"
},
{
"code": null,
"e": 29101,
"s": 29088,
"text": "Mathematical"
},
{
"code": null,
"e": 29111,
"s": 29101,
"text": "factorial"
},
{
"code": null,
"e": 29209,
"s": 29111,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29218,
"s": 29209,
"text": "Comments"
},
{
"code": null,
"e": 29231,
"s": 29218,
"text": "Old Comments"
},
{
"code": null,
"e": 29263,
"s": 29231,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 29294,
"s": 29263,
"text": "Modular multiplicative inverse"
},
{
"code": null,
"e": 29327,
"s": 29294,
"text": "Program to multiply two matrices"
},
{
"code": null,
"e": 29370,
"s": 29327,
"text": "Program to convert a given number to words"
},
{
"code": null,
"e": 29405,
"s": 29370,
"text": "Count ways to reach the n'th stair"
},
{
"code": null,
"e": 29430,
"s": 29405,
"text": "Fizz Buzz Implementation"
},
{
"code": null,
"e": 29474,
"s": 29430,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 29509,
"s": 29474,
"text": "Singular Value Decomposition (SVD)"
},
{
"code": null,
"e": 29548,
"s": 29509,
"text": "Find first and last digits of a number"
}
] |
How to Conditionally Remove Rows in R DataFrame? - GeeksforGeeks
|
19 Dec, 2021
In this article, we will discuss how to conditionally remove rows from a dataframe in the R Programming Language. We need to remove some rows of data from the dataframe conditionally to prepare the data. For that, we use logical conditions on the basis of which data that doesnβt follow the condition is removed.
To remove rows of data from a dataframe based on a single conditional statement we use square brackets [ ] with the dataframe and put the conditional statement inside it. This slices the dataframe and removes all the rows that do not satisfy the given condition.
Syntax:
df[ conditional-statement ]
where,
df: determines the dataframe to be used.conditional-statement: determines the condition for filtering data.
df: determines the dataframe to be used.
conditional-statement: determines the condition for filtering data.
Example:
In this example. all data points where x variable is less than zero are removed.
R
# create sample datasample_data <- data.frame( x = rnorm(10), y=rnorm(10,20) )# print dataprint("Sample Data:")sample_data # filter datanew_data = sample_data[sample_data$x > 0, ] # print dataprint("Filtered Data:")new_data
Output:
Sample Data:
x y
1 1.0356175 19.36691
2 -0.2071733 21.38060
3 -1.3449463 19.56191
4 -0.5313073 19.49135
5 1.7880192 19.52463
6 -0.7151556 19.93802
7 1.5074344 20.82541
8 -1.0754972 20.59427
9 -0.2483219 19.21103
10 -0.8892829 18.93114
Filtered Data:
x y
1 1.035617 19.36691
5 1.788019 19.52463
7 1.507434 20.82541
10 1.0460800 20.05319
To remove rows of data from a dataframe based on multiple conditional statements. We use square brackets [ ] with the dataframe and put multiple conditional statements along with AND or OR operator inside it. This slices the dataframe and removes all the rows that do not satisfy the given conditions.
Syntax:
df[ conditional-statement & / | conditional-statement ]
where,
df: determines the dataframe to be used.
conditional-statement: determines the condition for filtering data.
Example:
In this example. all data points where the x variable is less than zero and the y variable is less than 19 are removed.
R
# create sample datasample_data <- data.frame( x = rnorm(10), y=rnorm(10,20) )# print dataprint("Sample Data:")sample_data # filter datanew_data = sample_data[sample_data$x > 0 & sample_data$y > 0.4, ] # print dataprint("Filtered Data:")new_data
Output:
Sample Data:
x y
1 -1.091923406 21.14056
2 0.870826346 20.83627
3 0.285727039 20.89009
4 -0.224661613 20.04137
5 0.653407459 19.01530
6 0.001760769 18.36436
7 -0.572623161 19.72691
8 -0.092852143 19.58567
9 -0.423781311 19.99482
10 -1.332091619 19.36539
Filtered Data:
x y
2 0.870826346 20.83627
3 0.285727039 20.89009
5 0.653407459 19.01530
6 0.001760769 18.36436
The subset() function creates a subset of a given dataframe based on certain conditions. This helps us to remove or select the rows of data with single or multiple conditional statements. The subset() function is an inbuilt function of the R Language and does not need any third-party package to be imported.
Syntax:
subset( df, Conditional-statement )
where,
df: determines the dataframe to be used.
conditional-statement: determines the condition for filtering data.
Example:
In this example. all data points where the x variable is less than 19 and the y variable is greater than 50 are removed using the subset function.
R
# create sample datasample_data <- data.frame( x = rnorm(10,20), y=rnorm(10,50) )# print dataprint("Sample Data:")sample_data # filter datanew_data = subset(sample_data, sample_data$x > 19 & sample_data$y < 49 ) # print dataprint("Filtered Data:")new_data
Output:
Sample Data:
x y
1 20.38324 51.02714
2 20.36595 50.64125
3 20.44204 52.28653
4 20.34413 50.08981
5 20.51478 49.53950
6 20.35667 48.88035
7 19.89415 49.78139
8 21.61003 49.43653
9 20.66579 49.14877
10 20.70246 50.06486
Filtered Data:
x y
6 20.35667 48.88035
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.
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 multiple conditions?
How to filter R DataFrame by values in a column?
Convert Matrix to Dataframe in R
|
[
{
"code": null,
"e": 26597,
"s": 26569,
"text": "\n19 Dec, 2021"
},
{
"code": null,
"e": 26911,
"s": 26597,
"text": "In this article, we will discuss how to conditionally remove rows from a dataframe in the R Programming Language. We need to remove some rows of data from the dataframe conditionally to prepare the data. For that, we use logical conditions on the basis of which data that doesnβt follow the condition is removed. "
},
{
"code": null,
"e": 27174,
"s": 26911,
"text": "To remove rows of data from a dataframe based on a single conditional statement we use square brackets [ ] with the dataframe and put the conditional statement inside it. This slices the dataframe and removes all the rows that do not satisfy the given condition."
},
{
"code": null,
"e": 27182,
"s": 27174,
"text": "Syntax:"
},
{
"code": null,
"e": 27210,
"s": 27182,
"text": "df[ conditional-statement ]"
},
{
"code": null,
"e": 27217,
"s": 27210,
"text": "where,"
},
{
"code": null,
"e": 27325,
"s": 27217,
"text": "df: determines the dataframe to be used.conditional-statement: determines the condition for filtering data."
},
{
"code": null,
"e": 27366,
"s": 27325,
"text": "df: determines the dataframe to be used."
},
{
"code": null,
"e": 27434,
"s": 27366,
"text": "conditional-statement: determines the condition for filtering data."
},
{
"code": null,
"e": 27443,
"s": 27434,
"text": "Example:"
},
{
"code": null,
"e": 27524,
"s": 27443,
"text": "In this example. all data points where x variable is less than zero are removed."
},
{
"code": null,
"e": 27526,
"s": 27524,
"text": "R"
},
{
"code": "# create sample datasample_data <- data.frame( x = rnorm(10), y=rnorm(10,20) )# print dataprint(\"Sample Data:\")sample_data # filter datanew_data = sample_data[sample_data$x > 0, ] # print dataprint(\"Filtered Data:\")new_data",
"e": 27777,
"s": 27526,
"text": null
},
{
"code": null,
"e": 27785,
"s": 27777,
"text": "Output:"
},
{
"code": null,
"e": 28167,
"s": 27785,
"text": "Sample Data:\n x y\n1 1.0356175 19.36691\n2 -0.2071733 21.38060\n3 -1.3449463 19.56191\n4 -0.5313073 19.49135\n5 1.7880192 19.52463\n6 -0.7151556 19.93802\n7 1.5074344 20.82541\n8 -1.0754972 20.59427\n9 -0.2483219 19.21103\n10 -0.8892829 18.93114\nFiltered Data:\n x y\n1 1.035617 19.36691\n5 1.788019 19.52463\n7 1.507434 20.82541\n10 1.0460800 20.05319"
},
{
"code": null,
"e": 28469,
"s": 28167,
"text": "To remove rows of data from a dataframe based on multiple conditional statements. We use square brackets [ ] with the dataframe and put multiple conditional statements along with AND or OR operator inside it. This slices the dataframe and removes all the rows that do not satisfy the given conditions."
},
{
"code": null,
"e": 28477,
"s": 28469,
"text": "Syntax:"
},
{
"code": null,
"e": 28533,
"s": 28477,
"text": "df[ conditional-statement & / | conditional-statement ]"
},
{
"code": null,
"e": 28540,
"s": 28533,
"text": "where,"
},
{
"code": null,
"e": 28581,
"s": 28540,
"text": "df: determines the dataframe to be used."
},
{
"code": null,
"e": 28649,
"s": 28581,
"text": "conditional-statement: determines the condition for filtering data."
},
{
"code": null,
"e": 28658,
"s": 28649,
"text": "Example:"
},
{
"code": null,
"e": 28778,
"s": 28658,
"text": "In this example. all data points where the x variable is less than zero and the y variable is less than 19 are removed."
},
{
"code": null,
"e": 28780,
"s": 28778,
"text": "R"
},
{
"code": "# create sample datasample_data <- data.frame( x = rnorm(10), y=rnorm(10,20) )# print dataprint(\"Sample Data:\")sample_data # filter datanew_data = sample_data[sample_data$x > 0 & sample_data$y > 0.4, ] # print dataprint(\"Filtered Data:\")new_data",
"e": 29053,
"s": 28780,
"text": null
},
{
"code": null,
"e": 29061,
"s": 29053,
"text": "Output:"
},
{
"code": null,
"e": 29479,
"s": 29061,
"text": "Sample Data:\n x y\n1 -1.091923406 21.14056\n2 0.870826346 20.83627\n3 0.285727039 20.89009\n4 -0.224661613 20.04137\n5 0.653407459 19.01530\n6 0.001760769 18.36436\n7 -0.572623161 19.72691\n8 -0.092852143 19.58567\n9 -0.423781311 19.99482\n10 -1.332091619 19.36539\nFiltered Data:\n x y\n2 0.870826346 20.83627\n3 0.285727039 20.89009\n5 0.653407459 19.01530\n6 0.001760769 18.36436"
},
{
"code": null,
"e": 29788,
"s": 29479,
"text": "The subset() function creates a subset of a given dataframe based on certain conditions. This helps us to remove or select the rows of data with single or multiple conditional statements. The subset() function is an inbuilt function of the R Language and does not need any third-party package to be imported."
},
{
"code": null,
"e": 29796,
"s": 29788,
"text": "Syntax:"
},
{
"code": null,
"e": 29832,
"s": 29796,
"text": "subset( df, Conditional-statement )"
},
{
"code": null,
"e": 29839,
"s": 29832,
"text": "where,"
},
{
"code": null,
"e": 29880,
"s": 29839,
"text": "df: determines the dataframe to be used."
},
{
"code": null,
"e": 29948,
"s": 29880,
"text": "conditional-statement: determines the condition for filtering data."
},
{
"code": null,
"e": 29957,
"s": 29948,
"text": "Example:"
},
{
"code": null,
"e": 30104,
"s": 29957,
"text": "In this example. all data points where the x variable is less than 19 and the y variable is greater than 50 are removed using the subset function."
},
{
"code": null,
"e": 30106,
"s": 30104,
"text": "R"
},
{
"code": "# create sample datasample_data <- data.frame( x = rnorm(10,20), y=rnorm(10,50) )# print dataprint(\"Sample Data:\")sample_data # filter datanew_data = subset(sample_data, sample_data$x > 19 & sample_data$y < 49 ) # print dataprint(\"Filtered Data:\")new_data",
"e": 30389,
"s": 30106,
"text": null
},
{
"code": null,
"e": 30397,
"s": 30389,
"text": "Output:"
},
{
"code": null,
"e": 30696,
"s": 30397,
"text": "Sample Data:\n x y\n1 20.38324 51.02714\n2 20.36595 50.64125\n3 20.44204 52.28653\n4 20.34413 50.08981\n5 20.51478 49.53950\n6 20.35667 48.88035\n7 19.89415 49.78139\n8 21.61003 49.43653\n9 20.66579 49.14877\n10 20.70246 50.06486\nFiltered Data:\n x y\n6 20.35667 48.88035"
},
{
"code": null,
"e": 30703,
"s": 30696,
"text": "Picked"
},
{
"code": null,
"e": 30724,
"s": 30703,
"text": "R DataFrame-Programs"
},
{
"code": null,
"e": 30736,
"s": 30724,
"text": "R-DataFrame"
},
{
"code": null,
"e": 30747,
"s": 30736,
"text": "R Language"
},
{
"code": null,
"e": 30758,
"s": 30747,
"text": "R Programs"
},
{
"code": null,
"e": 30856,
"s": 30758,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30908,
"s": 30856,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 30943,
"s": 30908,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 31001,
"s": 30943,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 31039,
"s": 31001,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 31082,
"s": 31039,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 31140,
"s": 31082,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 31183,
"s": 31140,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 31233,
"s": 31183,
"text": "How to filter R dataframe by multiple conditions?"
},
{
"code": null,
"e": 31282,
"s": 31233,
"text": "How to filter R DataFrame by values in a column?"
}
] |
How to set background drawable programmatically in android?
|
This example demonstrates how do I set background drawable programmatically in android.
Step 1 β Create a new project in Android Studio, go to File β New Project and fill all required details to create a new project.
Step 2 β Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/rl"
tools:context=".MainActivity">
<Button
android:text="Set Drawable"
android:id="@+id/btnSetDrawable"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"/>
</RelativeLayout>
Step 3 β Add the following code to src/MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
public class MainActivity extends AppCompatActivity {
Button button;
RelativeLayout relativeLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
relativeLayout = findViewById(R.id.rl);
button = findViewById(R.id.btnSetDrawable);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
relativeLayout.setBackgroundResource(R.drawable.image);
}
});
}
}
Step 4 β Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen β
Click here to download the project code.
|
[
{
"code": null,
"e": 1150,
"s": 1062,
"text": "This example demonstrates how do I set background drawable programmatically in android."
},
{
"code": null,
"e": 1279,
"s": 1150,
"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": 1344,
"s": 1279,
"text": "Step 2 β Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 1917,
"s": 1344,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:id=\"@+id/rl\"\n tools:context=\".MainActivity\">\n <Button\n android:text=\"Set Drawable\"\n android:id=\"@+id/btnSetDrawable\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginTop=\"10dp\"/>\n</RelativeLayout>"
},
{
"code": null,
"e": 1974,
"s": 1917,
"text": "Step 3 β Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 2719,
"s": 1974,
"text": "import android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.RelativeLayout;\npublic class MainActivity extends AppCompatActivity {\n Button button;\n RelativeLayout relativeLayout;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n relativeLayout = findViewById(R.id.rl);\n button = findViewById(R.id.btnSetDrawable);\n button.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n relativeLayout.setBackgroundResource(R.drawable.image);\n } \n });\n }\n}"
},
{
"code": null,
"e": 2774,
"s": 2719,
"text": "Step 4 β Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 3444,
"s": 2774,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 3791,
"s": 3444,
"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": 3832,
"s": 3791,
"text": "Click here to download the project code."
}
] |
Angular PrimeNG TriCheckbox Component - GeeksforGeeks
|
24 Aug, 2021
Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will know how to use the TriCheckbox component in Angular PrimeNG.
TriCheckbox component: It allows a user to make a checkbox with three states ie, true, false & null conditions.
Properties:
name: It is used to give the name of the element. It is of string data type, the default value is null.
label: It is used to give the Label of the element. It is of string data type, the default value is null.
disabled: It is used to disable the element. It is of the boolean datatype, the default value is false.
tabindex: It is used to set the Index of the element in tabbing order. It is of number datatype, the default value is null.
inputId: It is an ID identifier of the underlying input element. It is of string data type, the default value is null.
ariaLabelledBy: It is the ariaLabelBy property that establishes relationships between the component and label(s) where its value should be one or more element IDs. It is of string data type, the default value is null.
style: It is used to give the Inline style of the component. It is of object data type, the default value is null.
styleClass: It is the Style class of the component. It is of string data type, the default value is null.
readonly: it specifies that the component cannot be edited. It is of the boolean datatype, the default value is false.
checkboxTrueIcon: It is used to set the specified icon for checkbox true value. It is of string data type, the default value is pi pi-check.
checkboxFalseIcon: It is used to set the specifies the icon for checkbox false value. It is of string data type, the default value is pi pi-check.
Event:
onChange: It is a callback that is fired on value change.
Styling:
p-chkbox: It is a container element.
p-tristatechkbox: It is a container element.
p-chkbox-box: It is a container of the icon.
p-chkbox-icon: It is an icon element.
Creating Angular application & module installation:
Step 1: Create an Angular application using the following command.ng new appname
Step 1: Create an Angular application using the following command.
ng new appname
Step 2: After creating your project folder i.e. appname, move to it using the following command.cd appname
Step 2: After creating your project folder i.e. appname, move to it using the following command.
cd appname
Step 3: Install PrimeNG in your given directory.npm install primeng --save
npm install primeicons --save
Step 3: Install PrimeNG in your given directory.
npm install primeng --save
npm install primeicons --save
Project Structure: It will look like the following:
Example 1: This is the basic example that shows how to use the TriCheckbox component.
app.component.html
<h2>GeeksforGeeks</h2><h5>PrimeNG TriCheckbox component</h5><p-triStateCheckbox label="Enabled Checkbox"></p-triStateCheckbox> <p-triStateCheckbox disabled="true" label="Disabled Checkbox"></p-triStateCheckbox>
app.module.ts
import { NgModule } from "@angular/core";import { BrowserModule } from "@angular/platform-browser";import { FormsModule } from "@angular/forms";import { BrowserAnimationsModule } from "@angular/platform-browser/animations"; import { AppComponent } from "./app.component";import { TriStateCheckboxModule } from "primeng/tristatecheckbox"; @NgModule({ imports: [ BrowserModule, BrowserAnimationsModule, TriStateCheckboxModule, FormsModule, ], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {}
Output:
Example 2: In this example, we will know how to use readonly and style property in the triCheckbox component.
app.component.html
<h2>GeeksforGeeks</h2><h5>PrimeNG TriCheckbox component</h5><p-triStateCheckbox label="Enabled Checkbox"></p-triStateCheckbox> <p-triStateCheckbox readonly="true" label="Readonly Checkbox"></p-triStateCheckbox> <p-triStateCheckbox readonly="true" style="border: 5px dotted"></p-triStateCheckbox>
app.module.ts
import { NgModule } from "@angular/core";import { BrowserModule } from "@angular/platform-browser";import { FormsModule } from "@angular/forms";import { BrowserAnimationsModule } from "@angular/platform-browser/animations"; import { AppComponent } from "./app.component";import { TriStateCheckboxModule } from "primeng/tristatecheckbox"; @NgModule({ imports: [ BrowserModule, BrowserAnimationsModule, TriStateCheckboxModule, FormsModule, ], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {}
Output:
Reference: https://primefaces.org/primeng/showcase/#/tristatecheckbox
Angular-PrimeNG
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Angular PrimeNG Dropdown Component
Angular PrimeNG Calendar Component
Angular PrimeNG Messages Component
Angular 10 (blur) Event
How to make a Bootstrap Modal Popup in Angular 9/8 ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 26464,
"s": 26436,
"text": "\n24 Aug, 2021"
},
{
"code": null,
"e": 26751,
"s": 26464,
"text": "Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will know how to use the TriCheckbox component in Angular PrimeNG."
},
{
"code": null,
"e": 26863,
"s": 26751,
"text": "TriCheckbox component: It allows a user to make a checkbox with three states ie, true, false & null conditions."
},
{
"code": null,
"e": 26875,
"s": 26863,
"text": "Properties:"
},
{
"code": null,
"e": 26979,
"s": 26875,
"text": "name: It is used to give the name of the element. It is of string data type, the default value is null."
},
{
"code": null,
"e": 27085,
"s": 26979,
"text": "label: It is used to give the Label of the element. It is of string data type, the default value is null."
},
{
"code": null,
"e": 27189,
"s": 27085,
"text": "disabled: It is used to disable the element. It is of the boolean datatype, the default value is false."
},
{
"code": null,
"e": 27313,
"s": 27189,
"text": "tabindex: It is used to set the Index of the element in tabbing order. It is of number datatype, the default value is null."
},
{
"code": null,
"e": 27432,
"s": 27313,
"text": "inputId: It is an ID identifier of the underlying input element. It is of string data type, the default value is null."
},
{
"code": null,
"e": 27650,
"s": 27432,
"text": "ariaLabelledBy: It is the ariaLabelBy property that establishes relationships between the component and label(s) where its value should be one or more element IDs. It is of string data type, the default value is null."
},
{
"code": null,
"e": 27765,
"s": 27650,
"text": "style: It is used to give the Inline style of the component. It is of object data type, the default value is null."
},
{
"code": null,
"e": 27871,
"s": 27765,
"text": "styleClass: It is the Style class of the component. It is of string data type, the default value is null."
},
{
"code": null,
"e": 27990,
"s": 27871,
"text": "readonly: it specifies that the component cannot be edited. It is of the boolean datatype, the default value is false."
},
{
"code": null,
"e": 28131,
"s": 27990,
"text": "checkboxTrueIcon: It is used to set the specified icon for checkbox true value. It is of string data type, the default value is pi pi-check."
},
{
"code": null,
"e": 28278,
"s": 28131,
"text": "checkboxFalseIcon: It is used to set the specifies the icon for checkbox false value. It is of string data type, the default value is pi pi-check."
},
{
"code": null,
"e": 28285,
"s": 28278,
"text": "Event:"
},
{
"code": null,
"e": 28343,
"s": 28285,
"text": "onChange: It is a callback that is fired on value change."
},
{
"code": null,
"e": 28354,
"s": 28345,
"text": "Styling:"
},
{
"code": null,
"e": 28391,
"s": 28354,
"text": "p-chkbox: It is a container element."
},
{
"code": null,
"e": 28436,
"s": 28391,
"text": "p-tristatechkbox: It is a container element."
},
{
"code": null,
"e": 28481,
"s": 28436,
"text": "p-chkbox-box: It is a container of the icon."
},
{
"code": null,
"e": 28519,
"s": 28481,
"text": "p-chkbox-icon: It is an icon element."
},
{
"code": null,
"e": 28571,
"s": 28519,
"text": "Creating Angular application & module installation:"
},
{
"code": null,
"e": 28652,
"s": 28571,
"text": "Step 1: Create an Angular application using the following command.ng new appname"
},
{
"code": null,
"e": 28719,
"s": 28652,
"text": "Step 1: Create an Angular application using the following command."
},
{
"code": null,
"e": 28734,
"s": 28719,
"text": "ng new appname"
},
{
"code": null,
"e": 28841,
"s": 28734,
"text": "Step 2: After creating your project folder i.e. appname, move to it using the following command.cd appname"
},
{
"code": null,
"e": 28938,
"s": 28841,
"text": "Step 2: After creating your project folder i.e. appname, move to it using the following command."
},
{
"code": null,
"e": 28949,
"s": 28938,
"text": "cd appname"
},
{
"code": null,
"e": 29054,
"s": 28949,
"text": "Step 3: Install PrimeNG in your given directory.npm install primeng --save\nnpm install primeicons --save"
},
{
"code": null,
"e": 29103,
"s": 29054,
"text": "Step 3: Install PrimeNG in your given directory."
},
{
"code": null,
"e": 29160,
"s": 29103,
"text": "npm install primeng --save\nnpm install primeicons --save"
},
{
"code": null,
"e": 29212,
"s": 29160,
"text": "Project Structure: It will look like the following:"
},
{
"code": null,
"e": 29301,
"s": 29214,
"text": "Example 1: This is the basic example that shows how to use the TriCheckbox component. "
},
{
"code": null,
"e": 29320,
"s": 29301,
"text": "app.component.html"
},
{
"code": "<h2>GeeksforGeeks</h2><h5>PrimeNG TriCheckbox component</h5><p-triStateCheckbox label=\"Enabled Checkbox\"></p-triStateCheckbox> <p-triStateCheckbox disabled=\"true\" label=\"Disabled Checkbox\"></p-triStateCheckbox>",
"e": 29534,
"s": 29320,
"text": null
},
{
"code": null,
"e": 29548,
"s": 29534,
"text": "app.module.ts"
},
{
"code": "import { NgModule } from \"@angular/core\";import { BrowserModule } from \"@angular/platform-browser\";import { FormsModule } from \"@angular/forms\";import { BrowserAnimationsModule } from \"@angular/platform-browser/animations\"; import { AppComponent } from \"./app.component\";import { TriStateCheckboxModule } from \"primeng/tristatecheckbox\"; @NgModule({ imports: [ BrowserModule, BrowserAnimationsModule, TriStateCheckboxModule, FormsModule, ], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {}",
"e": 30099,
"s": 29548,
"text": null
},
{
"code": null,
"e": 30107,
"s": 30099,
"text": "Output:"
},
{
"code": null,
"e": 30217,
"s": 30107,
"text": "Example 2: In this example, we will know how to use readonly and style property in the triCheckbox component."
},
{
"code": null,
"e": 30236,
"s": 30217,
"text": "app.component.html"
},
{
"code": "<h2>GeeksforGeeks</h2><h5>PrimeNG TriCheckbox component</h5><p-triStateCheckbox label=\"Enabled Checkbox\"></p-triStateCheckbox> <p-triStateCheckbox readonly=\"true\" label=\"Readonly Checkbox\"></p-triStateCheckbox> <p-triStateCheckbox readonly=\"true\" style=\"border: 5px dotted\"></p-triStateCheckbox>",
"e": 30538,
"s": 30236,
"text": null
},
{
"code": null,
"e": 30552,
"s": 30538,
"text": "app.module.ts"
},
{
"code": "import { NgModule } from \"@angular/core\";import { BrowserModule } from \"@angular/platform-browser\";import { FormsModule } from \"@angular/forms\";import { BrowserAnimationsModule } from \"@angular/platform-browser/animations\"; import { AppComponent } from \"./app.component\";import { TriStateCheckboxModule } from \"primeng/tristatecheckbox\"; @NgModule({ imports: [ BrowserModule, BrowserAnimationsModule, TriStateCheckboxModule, FormsModule, ], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {}",
"e": 31103,
"s": 30552,
"text": null
},
{
"code": null,
"e": 31111,
"s": 31103,
"text": "Output:"
},
{
"code": null,
"e": 31181,
"s": 31111,
"text": "Reference: https://primefaces.org/primeng/showcase/#/tristatecheckbox"
},
{
"code": null,
"e": 31197,
"s": 31181,
"text": "Angular-PrimeNG"
},
{
"code": null,
"e": 31207,
"s": 31197,
"text": "AngularJS"
},
{
"code": null,
"e": 31224,
"s": 31207,
"text": "Web Technologies"
},
{
"code": null,
"e": 31322,
"s": 31224,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31357,
"s": 31322,
"text": "Angular PrimeNG Dropdown Component"
},
{
"code": null,
"e": 31392,
"s": 31357,
"text": "Angular PrimeNG Calendar Component"
},
{
"code": null,
"e": 31427,
"s": 31392,
"text": "Angular PrimeNG Messages Component"
},
{
"code": null,
"e": 31451,
"s": 31427,
"text": "Angular 10 (blur) Event"
},
{
"code": null,
"e": 31504,
"s": 31451,
"text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?"
},
{
"code": null,
"e": 31544,
"s": 31504,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 31577,
"s": 31544,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 31622,
"s": 31577,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 31665,
"s": 31622,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
How to change the Text Color of a Substring in android using SpannableString class? - GeeksforGeeks
|
23 Feb, 2021
In this article, we will learn about how to change the text color of a substring of a string. It is easy to change the color of the whole string but to change the color of a substring we have to use a special class SpannableString. But SpannableString class is not really helpful when it comes to change the background color of the text. So for that, we have to use SpannableStringBuilder class.
Approach:
Add the following code in activity_main.xml file. This will add two textviews in the activity_main layout.activity_main.xmlactivity_main.xml <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:gravity="center" tools:context=".MainActivity"> <TextView android:id="@+id/text_view" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="10dp" android:textAlignment="center" android:text="GeeksForGeeks A Computer Science Portal for Geeks" android:textSize="20sp" /> <TextView android:id="@+id/text_view2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="10dp" android:textAlignment="center" android:text="Learn Algorithm." android:textSize="20sp" /></LinearLayout>Now add the following code in the MainActivity.java file. In this code we will change the color of substrings of first textview with SpannableString class and add a background color in second textview with SpannableStringBuilder. Create the objects of the classes with the texts you want to display and use setSpan function to change the color of the substring.MainActivity.javaMainActivity.javapackage org.geeksforgeeks.gfgspannablestring; import android.graphics.Color;import android.os.Bundle;import android.text.SpannableString;import android.text.SpannableStringBuilder;import android.text.Spanned;import android.text.style.BackgroundColorSpan;import android.text.style.ForegroundColorSpan;import android.widget.TextView;import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TextView textView = findViewById(R.id.text_view); TextView textView2 = findViewById(R.id.text_view2); String text = "GeeksForGeeks A Computer Science Portal for Geeks"; String text2 = "Learn Algorithm."; SpannableString spannableString = new SpannableString(text); // we can only use backgroundcolor // span with a spannableStringBuilder. SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(text2); // It is used to set foreground color. ForegroundColorSpan green = new ForegroundColorSpan(Color.GREEN); ForegroundColorSpan cyan = new ForegroundColorSpan(Color.CYAN); // It is used to set background color. BackgroundColorSpan yellow = new BackgroundColorSpan(Color.YELLOW); // It is used to set the span to the string spannableString.setSpan(green, 0, 13, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); spannableString.setSpan(cyan, 40, 43, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); spannableStringBuilder.setSpan(yellow, 0, 16, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); textView.setText(spannableString); textView2.setText(spannableStringBuilder); }}
Add the following code in activity_main.xml file. This will add two textviews in the activity_main layout.activity_main.xmlactivity_main.xml <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:gravity="center" tools:context=".MainActivity"> <TextView android:id="@+id/text_view" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="10dp" android:textAlignment="center" android:text="GeeksForGeeks A Computer Science Portal for Geeks" android:textSize="20sp" /> <TextView android:id="@+id/text_view2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="10dp" android:textAlignment="center" android:text="Learn Algorithm." android:textSize="20sp" /></LinearLayout>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:gravity="center" tools:context=".MainActivity"> <TextView android:id="@+id/text_view" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="10dp" android:textAlignment="center" android:text="GeeksForGeeks A Computer Science Portal for Geeks" android:textSize="20sp" /> <TextView android:id="@+id/text_view2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="10dp" android:textAlignment="center" android:text="Learn Algorithm." android:textSize="20sp" /></LinearLayout>
Now add the following code in the MainActivity.java file. In this code we will change the color of substrings of first textview with SpannableString class and add a background color in second textview with SpannableStringBuilder. Create the objects of the classes with the texts you want to display and use setSpan function to change the color of the substring.MainActivity.javaMainActivity.javapackage org.geeksforgeeks.gfgspannablestring; import android.graphics.Color;import android.os.Bundle;import android.text.SpannableString;import android.text.SpannableStringBuilder;import android.text.Spanned;import android.text.style.BackgroundColorSpan;import android.text.style.ForegroundColorSpan;import android.widget.TextView;import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TextView textView = findViewById(R.id.text_view); TextView textView2 = findViewById(R.id.text_view2); String text = "GeeksForGeeks A Computer Science Portal for Geeks"; String text2 = "Learn Algorithm."; SpannableString spannableString = new SpannableString(text); // we can only use backgroundcolor // span with a spannableStringBuilder. SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(text2); // It is used to set foreground color. ForegroundColorSpan green = new ForegroundColorSpan(Color.GREEN); ForegroundColorSpan cyan = new ForegroundColorSpan(Color.CYAN); // It is used to set background color. BackgroundColorSpan yellow = new BackgroundColorSpan(Color.YELLOW); // It is used to set the span to the string spannableString.setSpan(green, 0, 13, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); spannableString.setSpan(cyan, 40, 43, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); spannableStringBuilder.setSpan(yellow, 0, 16, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); textView.setText(spannableString); textView2.setText(spannableStringBuilder); }}
MainActivity.java
package org.geeksforgeeks.gfgspannablestring; import android.graphics.Color;import android.os.Bundle;import android.text.SpannableString;import android.text.SpannableStringBuilder;import android.text.Spanned;import android.text.style.BackgroundColorSpan;import android.text.style.ForegroundColorSpan;import android.widget.TextView;import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TextView textView = findViewById(R.id.text_view); TextView textView2 = findViewById(R.id.text_view2); String text = "GeeksForGeeks A Computer Science Portal for Geeks"; String text2 = "Learn Algorithm."; SpannableString spannableString = new SpannableString(text); // we can only use backgroundcolor // span with a spannableStringBuilder. SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(text2); // It is used to set foreground color. ForegroundColorSpan green = new ForegroundColorSpan(Color.GREEN); ForegroundColorSpan cyan = new ForegroundColorSpan(Color.CYAN); // It is used to set background color. BackgroundColorSpan yellow = new BackgroundColorSpan(Color.YELLOW); // It is used to set the span to the string spannableString.setSpan(green, 0, 13, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); spannableString.setSpan(cyan, 40, 43, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); spannableStringBuilder.setSpan(yellow, 0, 16, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); textView.setText(spannableString); textView2.setText(spannableStringBuilder); }}
Output:
Android-Animation
Android
Java
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Flutter - Custom Bottom Navigation Bar
Retrofit with Kotlin Coroutine in Android
How to Read Data from SQLite Database in Android?
Android Listview in Java with Example
How to Change the Background Color After Clicking the Button in Android?
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
|
[
{
"code": null,
"e": 25116,
"s": 25088,
"text": "\n23 Feb, 2021"
},
{
"code": null,
"e": 25512,
"s": 25116,
"text": "In this article, we will learn about how to change the text color of a substring of a string. It is easy to change the color of the whole string but to change the color of a substring we have to use a special class SpannableString. But SpannableString class is not really helpful when it comes to change the background color of the text. So for that, we have to use SpannableStringBuilder class."
},
{
"code": null,
"e": 25522,
"s": 25512,
"text": "Approach:"
},
{
"code": null,
"e": 28973,
"s": 25522,
"text": "Add the following code in activity_main.xml file. This will add two textviews in the activity_main layout.activity_main.xmlactivity_main.xml <?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\" android:gravity=\"center\" tools:context=\".MainActivity\"> <TextView android:id=\"@+id/text_view\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_margin=\"10dp\" android:textAlignment=\"center\" android:text=\"GeeksForGeeks A Computer Science Portal for Geeks\" android:textSize=\"20sp\" /> <TextView android:id=\"@+id/text_view2\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_margin=\"10dp\" android:textAlignment=\"center\" android:text=\"Learn Algorithm.\" android:textSize=\"20sp\" /></LinearLayout>Now add the following code in the MainActivity.java file. In this code we will change the color of substrings of first textview with SpannableString class and add a background color in second textview with SpannableStringBuilder. Create the objects of the classes with the texts you want to display and use setSpan function to change the color of the substring.MainActivity.javaMainActivity.javapackage org.geeksforgeeks.gfgspannablestring; import android.graphics.Color;import android.os.Bundle;import android.text.SpannableString;import android.text.SpannableStringBuilder;import android.text.Spanned;import android.text.style.BackgroundColorSpan;import android.text.style.ForegroundColorSpan;import android.widget.TextView;import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TextView textView = findViewById(R.id.text_view); TextView textView2 = findViewById(R.id.text_view2); String text = \"GeeksForGeeks A Computer Science Portal for Geeks\"; String text2 = \"Learn Algorithm.\"; SpannableString spannableString = new SpannableString(text); // we can only use backgroundcolor // span with a spannableStringBuilder. SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(text2); // It is used to set foreground color. ForegroundColorSpan green = new ForegroundColorSpan(Color.GREEN); ForegroundColorSpan cyan = new ForegroundColorSpan(Color.CYAN); // It is used to set background color. BackgroundColorSpan yellow = new BackgroundColorSpan(Color.YELLOW); // It is used to set the span to the string spannableString.setSpan(green, 0, 13, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); spannableString.setSpan(cyan, 40, 43, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); spannableStringBuilder.setSpan(yellow, 0, 16, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); textView.setText(spannableString); textView2.setText(spannableStringBuilder); }}"
},
{
"code": null,
"e": 30103,
"s": 28973,
"text": "Add the following code in activity_main.xml file. This will add two textviews in the activity_main layout.activity_main.xmlactivity_main.xml <?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\" android:gravity=\"center\" tools:context=\".MainActivity\"> <TextView android:id=\"@+id/text_view\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_margin=\"10dp\" android:textAlignment=\"center\" android:text=\"GeeksForGeeks A Computer Science Portal for Geeks\" android:textSize=\"20sp\" /> <TextView android:id=\"@+id/text_view2\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_margin=\"10dp\" android:textAlignment=\"center\" android:text=\"Learn Algorithm.\" android:textSize=\"20sp\" /></LinearLayout>"
},
{
"code": null,
"e": 30121,
"s": 30103,
"text": "activity_main.xml"
},
{
"code": " <?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\" android:gravity=\"center\" tools:context=\".MainActivity\"> <TextView android:id=\"@+id/text_view\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_margin=\"10dp\" android:textAlignment=\"center\" android:text=\"GeeksForGeeks A Computer Science Portal for Geeks\" android:textSize=\"20sp\" /> <TextView android:id=\"@+id/text_view2\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_margin=\"10dp\" android:textAlignment=\"center\" android:text=\"Learn Algorithm.\" android:textSize=\"20sp\" /></LinearLayout>",
"e": 31111,
"s": 30121,
"text": null
},
{
"code": null,
"e": 33433,
"s": 31111,
"text": "Now add the following code in the MainActivity.java file. In this code we will change the color of substrings of first textview with SpannableString class and add a background color in second textview with SpannableStringBuilder. Create the objects of the classes with the texts you want to display and use setSpan function to change the color of the substring.MainActivity.javaMainActivity.javapackage org.geeksforgeeks.gfgspannablestring; import android.graphics.Color;import android.os.Bundle;import android.text.SpannableString;import android.text.SpannableStringBuilder;import android.text.Spanned;import android.text.style.BackgroundColorSpan;import android.text.style.ForegroundColorSpan;import android.widget.TextView;import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TextView textView = findViewById(R.id.text_view); TextView textView2 = findViewById(R.id.text_view2); String text = \"GeeksForGeeks A Computer Science Portal for Geeks\"; String text2 = \"Learn Algorithm.\"; SpannableString spannableString = new SpannableString(text); // we can only use backgroundcolor // span with a spannableStringBuilder. SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(text2); // It is used to set foreground color. ForegroundColorSpan green = new ForegroundColorSpan(Color.GREEN); ForegroundColorSpan cyan = new ForegroundColorSpan(Color.CYAN); // It is used to set background color. BackgroundColorSpan yellow = new BackgroundColorSpan(Color.YELLOW); // It is used to set the span to the string spannableString.setSpan(green, 0, 13, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); spannableString.setSpan(cyan, 40, 43, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); spannableStringBuilder.setSpan(yellow, 0, 16, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); textView.setText(spannableString); textView2.setText(spannableStringBuilder); }}"
},
{
"code": null,
"e": 33451,
"s": 33433,
"text": "MainActivity.java"
},
{
"code": "package org.geeksforgeeks.gfgspannablestring; import android.graphics.Color;import android.os.Bundle;import android.text.SpannableString;import android.text.SpannableStringBuilder;import android.text.Spanned;import android.text.style.BackgroundColorSpan;import android.text.style.ForegroundColorSpan;import android.widget.TextView;import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TextView textView = findViewById(R.id.text_view); TextView textView2 = findViewById(R.id.text_view2); String text = \"GeeksForGeeks A Computer Science Portal for Geeks\"; String text2 = \"Learn Algorithm.\"; SpannableString spannableString = new SpannableString(text); // we can only use backgroundcolor // span with a spannableStringBuilder. SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(text2); // It is used to set foreground color. ForegroundColorSpan green = new ForegroundColorSpan(Color.GREEN); ForegroundColorSpan cyan = new ForegroundColorSpan(Color.CYAN); // It is used to set background color. BackgroundColorSpan yellow = new BackgroundColorSpan(Color.YELLOW); // It is used to set the span to the string spannableString.setSpan(green, 0, 13, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); spannableString.setSpan(cyan, 40, 43, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); spannableStringBuilder.setSpan(yellow, 0, 16, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); textView.setText(spannableString); textView2.setText(spannableStringBuilder); }}",
"e": 35378,
"s": 33451,
"text": null
},
{
"code": null,
"e": 35386,
"s": 35378,
"text": "Output:"
},
{
"code": null,
"e": 35404,
"s": 35386,
"text": "Android-Animation"
},
{
"code": null,
"e": 35412,
"s": 35404,
"text": "Android"
},
{
"code": null,
"e": 35417,
"s": 35412,
"text": "Java"
},
{
"code": null,
"e": 35422,
"s": 35417,
"text": "Java"
},
{
"code": null,
"e": 35430,
"s": 35422,
"text": "Android"
},
{
"code": null,
"e": 35528,
"s": 35430,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35567,
"s": 35528,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 35609,
"s": 35567,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 35659,
"s": 35609,
"text": "How to Read Data from SQLite Database in Android?"
},
{
"code": null,
"e": 35697,
"s": 35659,
"text": "Android Listview in Java with Example"
},
{
"code": null,
"e": 35770,
"s": 35697,
"text": "How to Change the Background Color After Clicking the Button in Android?"
},
{
"code": null,
"e": 35785,
"s": 35770,
"text": "Arrays in Java"
},
{
"code": null,
"e": 35829,
"s": 35785,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 35851,
"s": 35829,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 35887,
"s": 35851,
"text": "Arrays.sort() in Java with examples"
}
] |
How to get the last N records in MongoDB?
|
To get the last N records in MongoDB, you need to use limit(). The syntax is as follows:
db.yourCollectionName.find().sort({$natural:-1}).limit(yourValue);
To understand the above syntax, let us create a collection with document. The query to create a collection with document is as follows:
> db.getLastNRecordsDemo.insertOne({"EmployeeName":"Maxwell"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c6ecf3d6fd07954a4890689")
}
> db.getLastNRecordsDemo.insertOne({"EmployeeName":"Carol"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c6ecf496fd07954a489068a")
}
> db.getLastNRecordsDemo.insertOne({"EmployeeName":"Bob"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c6ecf4e6fd07954a489068b")
}
> db.getLastNRecordsDemo.insertOne({"EmployeeName":"Sam"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c6ecf546fd07954a489068c")
}
> db.getLastNRecordsDemo.insertOne({"EmployeeName":"Robert"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c6ecf596fd07954a489068d")
}
> db.getLastNRecordsDemo.insertOne({"EmployeeName":"Mike"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c6ecf606fd07954a489068e")
}
> db.getLastNRecordsDemo.insertOne({"EmployeeName":"Chris"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c6ecf686fd07954a489068f")
}
> db.getLastNRecordsDemo.insertOne({"EmployeeName":"James"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c6ecf6f6fd07954a4890690")
}
> db.getLastNRecordsDemo.insertOne({"EmployeeName":"Jace"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c6ecf756fd07954a4890691")
}
> db.getLastNRecordsDemo.insertOne({"EmployeeName":"Ramit"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c6ecf7d6fd07954a4890692")
}
> db.getLastNRecordsDemo.insertOne({"EmployeeName":"David"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c6ecf8d6fd07954a4890693")
}
Display all documents from a collection with the help of find() method. The query is as follows:
> db.getLastNRecordsDemo.find().pretty();
The following is the output:
{ "_id" : ObjectId("5c6ecf3d6fd07954a4890689"), "EmployeeName" : "Maxwell" }
{ "_id" : ObjectId("5c6ecf496fd07954a489068a"), "EmployeeName" : "Carol" }
{ "_id" : ObjectId("5c6ecf4e6fd07954a489068b"), "EmployeeName" : "Bob" }
{ "_id" : ObjectId("5c6ecf546fd07954a489068c"), "EmployeeName" : "Sam" }
{ "_id" : ObjectId("5c6ecf596fd07954a489068d"), "EmployeeName" : "Robert" }
{ "_id" : ObjectId("5c6ecf606fd07954a489068e"), "EmployeeName" : "Mike" }
{ "_id" : ObjectId("5c6ecf686fd07954a489068f"), "EmployeeName" : "Chris" }
{ "_id" : ObjectId("5c6ecf6f6fd07954a4890690"), "EmployeeName" : "James" }
{ "_id" : ObjectId("5c6ecf756fd07954a4890691"), "EmployeeName" : "Jace" }
{ "_id" : ObjectId("5c6ecf7d6fd07954a4890692"), "EmployeeName" : "Ramit" }
{ "_id" : ObjectId("5c6ecf8d6fd07954a4890693"), "EmployeeName" : "David" }
Here is the query to get last N records from a collection with the help of $natural and limit():
> db.getLastNRecordsDemo.find().sort({$natural:-1}).limit(7);
The following is the output:
{ "_id" : ObjectId("5c6ecf8d6fd07954a4890693"), "EmployeeName" : "David" }
{ "_id" : ObjectId("5c6ecf7d6fd07954a4890692"), "EmployeeName" : "Ramit" }
{ "_id" : ObjectId("5c6ecf756fd07954a4890691"), "EmployeeName" : "Jace" }
{ "_id" : ObjectId("5c6ecf6f6fd07954a4890690"), "EmployeeName" : "James" }
{ "_id" : ObjectId("5c6ecf686fd07954a489068f"), "EmployeeName" : "Chris" }
{ "_id" : ObjectId("5c6ecf606fd07954a489068e"), "EmployeeName" : "Mike" }
{ "_id" : ObjectId("5c6ecf596fd07954a489068d"), "EmployeeName" : "Robert" }
|
[
{
"code": null,
"e": 1151,
"s": 1062,
"text": "To get the last N records in MongoDB, you need to use limit(). The syntax is as follows:"
},
{
"code": null,
"e": 1218,
"s": 1151,
"text": "db.yourCollectionName.find().sort({$natural:-1}).limit(yourValue);"
},
{
"code": null,
"e": 1354,
"s": 1218,
"text": "To understand the above syntax, let us create a collection with document. The query to create a collection with document is as follows:"
},
{
"code": null,
"e": 2965,
"s": 1354,
"text": "> db.getLastNRecordsDemo.insertOne({\"EmployeeName\":\"Maxwell\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c6ecf3d6fd07954a4890689\")\n}\n> db.getLastNRecordsDemo.insertOne({\"EmployeeName\":\"Carol\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c6ecf496fd07954a489068a\")\n}\n> db.getLastNRecordsDemo.insertOne({\"EmployeeName\":\"Bob\"});\n{\n\"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c6ecf4e6fd07954a489068b\")\n}\n> db.getLastNRecordsDemo.insertOne({\"EmployeeName\":\"Sam\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c6ecf546fd07954a489068c\")\n}\n> db.getLastNRecordsDemo.insertOne({\"EmployeeName\":\"Robert\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c6ecf596fd07954a489068d\")\n}\n> db.getLastNRecordsDemo.insertOne({\"EmployeeName\":\"Mike\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c6ecf606fd07954a489068e\")\n}\n> db.getLastNRecordsDemo.insertOne({\"EmployeeName\":\"Chris\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c6ecf686fd07954a489068f\")\n}\n> db.getLastNRecordsDemo.insertOne({\"EmployeeName\":\"James\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c6ecf6f6fd07954a4890690\")\n}\n> db.getLastNRecordsDemo.insertOne({\"EmployeeName\":\"Jace\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c6ecf756fd07954a4890691\")\n}\n> db.getLastNRecordsDemo.insertOne({\"EmployeeName\":\"Ramit\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c6ecf7d6fd07954a4890692\")\n}\n> db.getLastNRecordsDemo.insertOne({\"EmployeeName\":\"David\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c6ecf8d6fd07954a4890693\")\n}"
},
{
"code": null,
"e": 3062,
"s": 2965,
"text": "Display all documents from a collection with the help of find() method. The query is as follows:"
},
{
"code": null,
"e": 3104,
"s": 3062,
"text": "> db.getLastNRecordsDemo.find().pretty();"
},
{
"code": null,
"e": 3133,
"s": 3104,
"text": "The following is the output:"
},
{
"code": null,
"e": 3955,
"s": 3133,
"text": "{ \"_id\" : ObjectId(\"5c6ecf3d6fd07954a4890689\"), \"EmployeeName\" : \"Maxwell\" }\n{ \"_id\" : ObjectId(\"5c6ecf496fd07954a489068a\"), \"EmployeeName\" : \"Carol\" }\n{ \"_id\" : ObjectId(\"5c6ecf4e6fd07954a489068b\"), \"EmployeeName\" : \"Bob\" }\n{ \"_id\" : ObjectId(\"5c6ecf546fd07954a489068c\"), \"EmployeeName\" : \"Sam\" }\n{ \"_id\" : ObjectId(\"5c6ecf596fd07954a489068d\"), \"EmployeeName\" : \"Robert\" }\n{ \"_id\" : ObjectId(\"5c6ecf606fd07954a489068e\"), \"EmployeeName\" : \"Mike\" }\n{ \"_id\" : ObjectId(\"5c6ecf686fd07954a489068f\"), \"EmployeeName\" : \"Chris\" }\n{ \"_id\" : ObjectId(\"5c6ecf6f6fd07954a4890690\"), \"EmployeeName\" : \"James\" }\n{ \"_id\" : ObjectId(\"5c6ecf756fd07954a4890691\"), \"EmployeeName\" : \"Jace\" }\n{ \"_id\" : ObjectId(\"5c6ecf7d6fd07954a4890692\"), \"EmployeeName\" : \"Ramit\" }\n{ \"_id\" : ObjectId(\"5c6ecf8d6fd07954a4890693\"), \"EmployeeName\" : \"David\" }"
},
{
"code": null,
"e": 4052,
"s": 3955,
"text": "Here is the query to get last N records from a collection with the help of $natural and limit():"
},
{
"code": null,
"e": 4114,
"s": 4052,
"text": "> db.getLastNRecordsDemo.find().sort({$natural:-1}).limit(7);"
},
{
"code": null,
"e": 4143,
"s": 4114,
"text": "The following is the output:"
},
{
"code": null,
"e": 4667,
"s": 4143,
"text": "{ \"_id\" : ObjectId(\"5c6ecf8d6fd07954a4890693\"), \"EmployeeName\" : \"David\" }\n{ \"_id\" : ObjectId(\"5c6ecf7d6fd07954a4890692\"), \"EmployeeName\" : \"Ramit\" }\n{ \"_id\" : ObjectId(\"5c6ecf756fd07954a4890691\"), \"EmployeeName\" : \"Jace\" }\n{ \"_id\" : ObjectId(\"5c6ecf6f6fd07954a4890690\"), \"EmployeeName\" : \"James\" }\n{ \"_id\" : ObjectId(\"5c6ecf686fd07954a489068f\"), \"EmployeeName\" : \"Chris\" }\n{ \"_id\" : ObjectId(\"5c6ecf606fd07954a489068e\"), \"EmployeeName\" : \"Mike\" }\n{ \"_id\" : ObjectId(\"5c6ecf596fd07954a489068d\"), \"EmployeeName\" : \"Robert\" }"
}
] |
Display time zone with SimpleDateFormat(βzβ) in Java
|
You can display timezone easily in Java using SimpleDateFormat(βzβ).
Firstly, to work with SimpleDateFormat class in Java, import the following package β
import java.text.SimpleDateFormat;
Now, set the format with SimpleDateFormat(βzβ) to display timezone β
Format f = new SimpleDateFormat(βzβ);
Now, get the timezone in a string β
String strTimeZone = f.format(new Date());
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("dd/MMMM/yyyy hh:mm:s z");
System.out.println("Today's date = "+simpleformat.format(cal.getTime()));
// displaying hour
Format f = new SimpleDateFormat("H");
String strHour = f.format(new Date());
System.out.println("Current Hour = "+strHour);
// displaying minutes
f = new SimpleDateFormat("mm");
String strMinute = f.format(new Date());
System.out.println("Current Minutes = "+strMinute);
// displaying seconds in two-digits
f = new SimpleDateFormat("ss");
String strSeconds = f.format(new Date());
System.out.println("Current Seconds = "+strSeconds);
f = new SimpleDateFormat("a");
String strMarker = f.format(new Date());
System.out.println("Current AM/PM Marker = "+strMarker);
// display timezone
f = new SimpleDateFormat("z");
String strTimeZone = f.format(new Date());
System.out.println("TimeZone = "+strTimeZone);
}
}
Today's date = 26/November/2018 08:11:21 UTC
Current Hour = 8
Current Minutes = 11
Current Seconds = 21
Current AM/PM Marker = AM
TimeZone = UTC
|
[
{
"code": null,
"e": 1131,
"s": 1062,
"text": "You can display timezone easily in Java using SimpleDateFormat(βzβ)."
},
{
"code": null,
"e": 1216,
"s": 1131,
"text": "Firstly, to work with SimpleDateFormat class in Java, import the following package β"
},
{
"code": null,
"e": 1251,
"s": 1216,
"text": "import java.text.SimpleDateFormat;"
},
{
"code": null,
"e": 1320,
"s": 1251,
"text": "Now, set the format with SimpleDateFormat(βzβ) to display timezone β"
},
{
"code": null,
"e": 1358,
"s": 1320,
"text": "Format f = new SimpleDateFormat(βzβ);"
},
{
"code": null,
"e": 1394,
"s": 1358,
"text": "Now, get the timezone in a string β"
},
{
"code": null,
"e": 1437,
"s": 1394,
"text": "String strTimeZone = f.format(new Date());"
},
{
"code": null,
"e": 1467,
"s": 1437,
"text": "The following is an example β"
},
{
"code": null,
"e": 1478,
"s": 1467,
"text": " Live Demo"
},
{
"code": null,
"e": 2766,
"s": 1478,
"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(\"dd/MMMM/yyyy hh:mm:s z\");\n System.out.println(\"Today's date = \"+simpleformat.format(cal.getTime()));\n // displaying hour\n Format f = new SimpleDateFormat(\"H\");\n String strHour = f.format(new Date());\n System.out.println(\"Current Hour = \"+strHour);\n // displaying minutes\n f = new SimpleDateFormat(\"mm\");\n String strMinute = f.format(new Date());\n System.out.println(\"Current Minutes = \"+strMinute);\n // displaying seconds in two-digits\n f = new SimpleDateFormat(\"ss\");\n String strSeconds = f.format(new Date());\n System.out.println(\"Current Seconds = \"+strSeconds);\n f = new SimpleDateFormat(\"a\");\n String strMarker = f.format(new Date());\n System.out.println(\"Current AM/PM Marker = \"+strMarker);\n // display timezone\n f = new SimpleDateFormat(\"z\");\n String strTimeZone = f.format(new Date());\n System.out.println(\"TimeZone = \"+strTimeZone);\n }\n}"
},
{
"code": null,
"e": 2911,
"s": 2766,
"text": "Today's date = 26/November/2018 08:11:21 UTC\nCurrent Hour = 8\nCurrent Minutes = 11\nCurrent Seconds = 21\nCurrent AM/PM Marker = AM\nTimeZone = UTC"
}
] |
Apache Bench - Environment Setup
|
In this chapter, we will guide you how to set up your environment for Apache Bench on your VPS.
Memory β 128 MB
Memory β 128 MB
Disk Space β No minimum requirement
Disk Space β No minimum requirement
Operating System β No minimum requirement
Operating System β No minimum requirement
Apache Bench is a stand-alone application, and has no dependencies on the Apache web server installation. The following is a two-step process to install Apache Bench.
Step 1 β Update package database.
# apt-get update
Please note that symbol # before a terminal command means that root user is issuing that command.
Step 2 β Install apache2 utils package to get access to Apache Bench.
# apt-get install apache2-utils
Apache Bench is now installed. If you want to test a web application hosted on the same VPS, then it is enough to install the Apache web server only β
# apt-get install apache2
Being an Apache utility, Apache Bench is automatically installed on installation of the Apache web server.
Let us now see how to verify Apache Bench Installation. The following code will help verify the installation β
# ab -V
Output
This is ApacheBench, Version 2.3 <$Revision: 1604373 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/
When you see the above terminal output, it means you have successfully installed Apache Bench.
From the safety point of view, it is considered a good practice for system administrator to create a sudo user instead of working as root. We will create a test user, named test, for the purpose β
# useradd -m -d /home/test -g sudo test
Let us set the password for the new user β
# passwd test
System will prompt for a new password for the user test. You can enter a simple password as we are just testing, and not deploying to the production server. Usually the sudo command will prompt you to provide the sudo user password; it is recommended not to use complicated password as the process becomes cumbersome.
Output
Enter new UNIX password:
Retype new UNIX password:
passwd: password updated successfully
In this section, we will test the Apache.org Website. Let us first switch to the sudo user test β
# su test
To begin with, we will test the website of Apache organization, https://www.apache.org/. We will first run the command, and then understand the output β
$ ab -n 100 -c 10 https://www.apache.org/
Here -n is the number of requests to perform for the benchmarking session. The default is to just perform a single request which usually leads to non-representative benchmarking results.
And -c is the concurrency and denotes the number of multiple requests to perform at a time. Default is one request at a time.
So in this test, Apache Bench will make 100 requests with concurrency 10 to the Apache organization server.
Output
This is ApacheBench, Version 2.3 <$Revision: 1604373 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/
Benchmarking www.apache.org (be patient).....done
Server Software: Apache/2.4.7
Server Hostname: www.apache.org
Server Port: 443
SSL/TLS Protocol: TLSv1.2,ECDHE-RSA-AES256-GCM-SHA384,2048,256
Document Path: /
Document Length: 58769 bytes
Concurrency Level: 10
Time taken for tests: 1.004 seconds
Complete requests: 100
Failed requests: 0
Total transferred: 5911100 bytes
HTML transferred: 5876900 bytes
Requests per second: 99.56 [#/sec] (mean)
Time per request: 100.444 [ms] (mean)
Time per request: 10.044 [ms] (mean, across all concurrent requests)
Transfer rate: 5747.06 [Kbytes/sec] received
Connection Times (ms)
min mean[+/-sd] median max
Connect: 39 46 30.9 41 263
Processing: 37 40 21.7 38 255
Waiting: 12 15 21.7 13 230
Total: 77 86 37.5 79 301
Percentage of the requests served within a certain time (ms)
50% 79
66% 79
75% 80
80% 80
90% 82
95% 84
98% 296
99% 301
100% 301 (longest request)
Having run our first test, it will be easy to recognize the pattern of use for this command which is as follows β
# ab [options .....] URL
where,
ab β Apache Bench command
ab β Apache Bench command
options β flags for particular task we want to perform
options β flags for particular task we want to perform
URL β path url we want to test
URL β path url we want to test
We need to understand the different metrics to understand the various output values returned by ab. Here goes the list β
Server Software β It is the name of the web server returned in the HTTP header of the first successful return.
Server Software β It is the name of the web server returned in the HTTP header of the first successful return.
Server Hostname β It is the DNS or IP address given on the command line.
Server Hostname β It is the DNS or IP address given on the command line.
Server Port β It is the port to which ab is connecting. If no port is given on the command line, this will default to 80 for http and 443 for https.
Server Port β It is the port to which ab is connecting. If no port is given on the command line, this will default to 80 for http and 443 for https.
SSL/TLS Protocol β This is the protocol parameter negotiated between the client and server. This will only be printed if SSL is used.
SSL/TLS Protocol β This is the protocol parameter negotiated between the client and server. This will only be printed if SSL is used.
Document Path β This is the request URI parsed from the command line string.
Document Path β This is the request URI parsed from the command line string.
Document Length β It is the size in bytes of the first successfully returned document. If the document length changes during testing, the response is considered an error.
Document Length β It is the size in bytes of the first successfully returned document. If the document length changes during testing, the response is considered an error.
Concurrency Level β This is the number of concurrent clients (equivalent to web browsers) used during the test.
Concurrency Level β This is the number of concurrent clients (equivalent to web browsers) used during the test.
Time Taken for Tests β This is the time taken from the moment the first socket connection is created to the moment the last response is received.
Time Taken for Tests β This is the time taken from the moment the first socket connection is created to the moment the last response is received.
Complete Requests β The number of successful responses received.
Complete Requests β The number of successful responses received.
Failed Requests β The number of requests that were considered a failure. If the number is greater than zero, another line will be printed showing the number of requests that failed due to connecting, reading, incorrect content length, or exceptions.
Failed Requests β The number of requests that were considered a failure. If the number is greater than zero, another line will be printed showing the number of requests that failed due to connecting, reading, incorrect content length, or exceptions.
Total Transferred β The total number of bytes received from the server. This number is essentially the number of bytes sent over the wire.
Total Transferred β The total number of bytes received from the server. This number is essentially the number of bytes sent over the wire.
HTML Transferred β The total number of document bytes received from the server. This number excludes bytes received in HTTP headers
HTML Transferred β The total number of document bytes received from the server. This number excludes bytes received in HTTP headers
Requests per second β This is the number of requests per second. This value is the result of dividing the number of requests by the total time taken.
Requests per second β This is the number of requests per second. This value is the result of dividing the number of requests by the total time taken.
Time per request β The average time spent per request. The first value is calculated with the formula concurrency * timetaken * 1000 / done while the second value is calculated with the formula timetaken * 1000 / done
Time per request β The average time spent per request. The first value is calculated with the formula concurrency * timetaken * 1000 / done while the second value is calculated with the formula timetaken * 1000 / done
Transfer rate β The rate of transfer as calculated by the formula totalread / 1024 / timetaken.
Transfer rate β The rate of transfer as calculated by the formula totalread / 1024 / timetaken.
Having learned about the headings of the output values from the ab command, let us try to analyze and understand the output values for our initial test β
Apache organisation is using their own web Server Software β Apache (version 2.4.7)
Apache organisation is using their own web Server Software β Apache (version 2.4.7)
Server is listening on Port 443 because of https. Had it been http, it would have been 80 (default).
Server is listening on Port 443 because of https. Had it been http, it would have been 80 (default).
Total data transferred is 58769 bytes for 100 requests.
Total data transferred is 58769 bytes for 100 requests.
Test completed in 1.004 seconds. There are no failed requests.
Test completed in 1.004 seconds. There are no failed requests.
Requests per seconds β 99.56. This is considered a pretty good number.
Requests per seconds β 99.56. This is considered a pretty good number.
Time per request β 100.444 ms (for 10 concurrent requests). So across all requests, it is 100.444 ms/10 = 10.044 ms.
Time per request β 100.444 ms (for 10 concurrent requests). So across all requests, it is 100.444 ms/10 = 10.044 ms.
Transfer rate β 1338.39 [Kbytes/sec] received.
Transfer rate β 1338.39 [Kbytes/sec] received.
In connection time statistics, you can observe that many requests had to wait for few seconds. This may be due to apache web server putting requests in wait queue.
In connection time statistics, you can observe that many requests had to wait for few seconds. This may be due to apache web server putting requests in wait queue.
In our first test, we had tested an application (i.e., www.apache.org) hosted on a different server. In the later part of the tutorial, we will be testing our sample web-applications hosted on the same server from which we will be running the ab tests. This is for the ease of learning and demonstration purpose. Ideally, the host node and testing node should be different for accurate measurement.
To better learn ab, you should compare and observe how the output values vary for different cases as we move forward in this tutorial.
Here we will plot the relevant outcome to see how much time the server takes as the number of requests increases. For that, we will add the -g option in the previous command followed by the file name (here out.data) in which the ab output data will be saved β
$ ab -n 100 -c 10 -g out.data https://www.apache.org/
Let us now see the out.data before we create a plot β
$ less out.data
Output
starttime seconds ctime dtime ttime wait
Tue May 30 12:11:37 2017 1496160697 40 38 77 13
Tue May 30 12:11:37 2017 1496160697 42 38 79 13
Tue May 30 12:11:37 2017 1496160697 41 38 80 13
...
Let us now understand the column headers in the out.data file β
starttime β This is the date and time at which the call started.
starttime β This is the date and time at which the call started.
seconds β Same as starttime but in the Unix timestamp format (date -d @1496160697 returns starttime output).
seconds β Same as starttime but in the Unix timestamp format (date -d @1496160697 returns starttime output).
ctime β This is the Connection Time.
ctime β This is the Connection Time.
dtime β This is the Processing Time.
dtime β This is the Processing Time.
ttime β This is the Total Time (it is the sum of ctime and dtime, mathematically ttime = ctime + dtime).
ttime β This is the Total Time (it is the sum of ctime and dtime, mathematically ttime = ctime + dtime).
wait β This is the Waiting Time.
wait β This is the Waiting Time.
For a pictorial visualization of how these multiple items are related to each other, take a look at the following image β
If we are working over terminal or where graphics are not available, gnuplot is a great option. We will quickly understand it by going through the following steps.
Let us install and launch gnuplot β
$ sudo apt-get install gnuplot
$ gnuplot
Output
G N U P L O T
Version 4.6 patchlevel 6 last modified September 2014
Build System: Linux x86_64
Copyright (C) 1986-1993, 1998, 2004, 2007-2014
Thomas Williams, Colin Kelley and many others
gnuplot home: http://www.gnuplot.info
faq, bugs, etc: type "help FAQ"
immediate help: type "help" (plot window: hit 'h')
Terminal type set to 'qt'
gnuplot>
As we are working over terminal and supposing that graphics are not available, we can choose the dumb terminal which will give output in ASCII over the terminal itself. This helps us get an idea what our plot looks like with this quick tool. Let us now prepare the terminal for ASCII plot.
gnuplot> set terminal dumb
Output
Terminal type set to 'dumb'
Options are 'feed size 79, 24'
As, our gnuplot terminal is now ready for ASCII plot, let us plot the data from the out.data file β
gnuplot> plot "out.data" using 9 w l
Output
1400 ++-----+------+-----+------+------+------+------+-----+------+-----++
+ + + + + + +"out.data" using 9 ****** +
| |
1200 ++ ********************************************
| ******************* |
1000 ++ * ++
| * |
| * |
800 ++ * ++
| * |
| * |
600 ++ * ++
| * |
| * |
400 ++ * ++
| * |
200 ++ * ++
| * |
+**** + + + + + + + + + +
0 ++-----+------+-----+------+------+------+------+-----+------+-----++
0 10 20 30 40 50 60 70 80 90 100
We have plotted the ttime, total time (in ms) from column 9, with respect to the number of requests. We can notice that for the initial ten requests, the total time was in the nearly 100 ms, for next 30 requests (from 10th to 40th), it increased to 1100 ms, and so on. Your plot must be different depending on your out.data.
46 Lectures
3.5 hours
Arnab Chakraborty
23 Lectures
1.5 hours
Mukund Kumar Mishra
16 Lectures
1 hours
Nilay Mehta
52 Lectures
1.5 hours
Bigdata Engineer
14 Lectures
1 hours
Bigdata Engineer
23 Lectures
1 hours
Bigdata Engineer
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 1930,
"s": 1834,
"text": "In this chapter, we will guide you how to set up your environment for Apache Bench on your VPS."
},
{
"code": null,
"e": 1946,
"s": 1930,
"text": "Memory β 128 MB"
},
{
"code": null,
"e": 1962,
"s": 1946,
"text": "Memory β 128 MB"
},
{
"code": null,
"e": 1998,
"s": 1962,
"text": "Disk Space β No minimum requirement"
},
{
"code": null,
"e": 2034,
"s": 1998,
"text": "Disk Space β No minimum requirement"
},
{
"code": null,
"e": 2076,
"s": 2034,
"text": "Operating System β No minimum requirement"
},
{
"code": null,
"e": 2118,
"s": 2076,
"text": "Operating System β No minimum requirement"
},
{
"code": null,
"e": 2285,
"s": 2118,
"text": "Apache Bench is a stand-alone application, and has no dependencies on the Apache web server installation. The following is a two-step process to install Apache Bench."
},
{
"code": null,
"e": 2319,
"s": 2285,
"text": "Step 1 β Update package database."
},
{
"code": null,
"e": 2337,
"s": 2319,
"text": "# apt-get update\n"
},
{
"code": null,
"e": 2435,
"s": 2337,
"text": "Please note that symbol # before a terminal command means that root user is issuing that command."
},
{
"code": null,
"e": 2505,
"s": 2435,
"text": "Step 2 β Install apache2 utils package to get access to Apache Bench."
},
{
"code": null,
"e": 2538,
"s": 2505,
"text": "# apt-get install apache2-utils\n"
},
{
"code": null,
"e": 2689,
"s": 2538,
"text": "Apache Bench is now installed. If you want to test a web application hosted on the same VPS, then it is enough to install the Apache web server only β"
},
{
"code": null,
"e": 2716,
"s": 2689,
"text": "# apt-get install apache2\n"
},
{
"code": null,
"e": 2823,
"s": 2716,
"text": "Being an Apache utility, Apache Bench is automatically installed on installation of the Apache web server."
},
{
"code": null,
"e": 2934,
"s": 2823,
"text": "Let us now see how to verify Apache Bench Installation. The following code will help verify the installation β"
},
{
"code": null,
"e": 2943,
"s": 2934,
"text": "# ab -V\n"
},
{
"code": null,
"e": 2950,
"s": 2943,
"text": "Output"
},
{
"code": null,
"e": 3147,
"s": 2950,
"text": "This is ApacheBench, Version 2.3 <$Revision: 1604373 $>\nCopyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/\nLicensed to The Apache Software Foundation, http://www.apache.org/\n"
},
{
"code": null,
"e": 3242,
"s": 3147,
"text": "When you see the above terminal output, it means you have successfully installed Apache Bench."
},
{
"code": null,
"e": 3439,
"s": 3242,
"text": "From the safety point of view, it is considered a good practice for system administrator to create a sudo user instead of working as root. We will create a test user, named test, for the purpose β"
},
{
"code": null,
"e": 3480,
"s": 3439,
"text": "# useradd -m -d /home/test -g sudo test\n"
},
{
"code": null,
"e": 3523,
"s": 3480,
"text": "Let us set the password for the new user β"
},
{
"code": null,
"e": 3538,
"s": 3523,
"text": "# passwd test\n"
},
{
"code": null,
"e": 3856,
"s": 3538,
"text": "System will prompt for a new password for the user test. You can enter a simple password as we are just testing, and not deploying to the production server. Usually the sudo command will prompt you to provide the sudo user password; it is recommended not to use complicated password as the process becomes cumbersome."
},
{
"code": null,
"e": 3863,
"s": 3856,
"text": "Output"
},
{
"code": null,
"e": 3956,
"s": 3863,
"text": "Enter new UNIX password:\nRetype new UNIX password: \npasswd: password updated successfully\n"
},
{
"code": null,
"e": 4054,
"s": 3956,
"text": "In this section, we will test the Apache.org Website. Let us first switch to the sudo user test β"
},
{
"code": null,
"e": 4065,
"s": 4054,
"text": "# su test\n"
},
{
"code": null,
"e": 4218,
"s": 4065,
"text": "To begin with, we will test the website of Apache organization, https://www.apache.org/. We will first run the command, and then understand the output β"
},
{
"code": null,
"e": 4261,
"s": 4218,
"text": "$ ab -n 100 -c 10 https://www.apache.org/\n"
},
{
"code": null,
"e": 4448,
"s": 4261,
"text": "Here -n is the number of requests to perform for the benchmarking session. The default is to just perform a single request which usually leads to non-representative benchmarking results."
},
{
"code": null,
"e": 4574,
"s": 4448,
"text": "And -c is the concurrency and denotes the number of multiple requests to perform at a time. Default is one request at a time."
},
{
"code": null,
"e": 4682,
"s": 4574,
"text": "So in this test, Apache Bench will make 100 requests with concurrency 10 to the Apache organization server."
},
{
"code": null,
"e": 4689,
"s": 4682,
"text": "Output"
},
{
"code": null,
"e": 6028,
"s": 4689,
"text": "This is ApacheBench, Version 2.3 <$Revision: 1604373 $>\nCopyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/\nLicensed to The Apache Software Foundation, http://www.apache.org/\n\nBenchmarking www.apache.org (be patient).....done\n\nServer Software: Apache/2.4.7\nServer Hostname: www.apache.org\nServer Port: 443\nSSL/TLS Protocol: TLSv1.2,ECDHE-RSA-AES256-GCM-SHA384,2048,256\n\nDocument Path: /\nDocument Length: 58769 bytes\n\nConcurrency Level: 10\nTime taken for tests: 1.004 seconds\nComplete requests: 100\nFailed requests: 0\nTotal transferred: 5911100 bytes\nHTML transferred: 5876900 bytes\nRequests per second: 99.56 [#/sec] (mean)\nTime per request: 100.444 [ms] (mean)\nTime per request: 10.044 [ms] (mean, across all concurrent requests)\nTransfer rate: 5747.06 [Kbytes/sec] received\n\nConnection Times (ms)\n min mean[+/-sd] median max\nConnect: 39 46 30.9 41 263\nProcessing: 37 40 21.7 38 255\nWaiting: 12 15 21.7 13 230\nTotal: 77 86 37.5 79 301\n\nPercentage of the requests served within a certain time (ms)\n 50% 79\n 66% 79\n 75% 80\n 80% 80\n 90% 82\n 95% 84\n 98% 296\n 99% 301\n 100% 301 (longest request)\n"
},
{
"code": null,
"e": 6142,
"s": 6028,
"text": "Having run our first test, it will be easy to recognize the pattern of use for this command which is as follows β"
},
{
"code": null,
"e": 6169,
"s": 6142,
"text": "# ab [options .....] URL\n"
},
{
"code": null,
"e": 6176,
"s": 6169,
"text": "where,"
},
{
"code": null,
"e": 6202,
"s": 6176,
"text": "ab β Apache Bench command"
},
{
"code": null,
"e": 6228,
"s": 6202,
"text": "ab β Apache Bench command"
},
{
"code": null,
"e": 6283,
"s": 6228,
"text": "options β flags for particular task we want to perform"
},
{
"code": null,
"e": 6338,
"s": 6283,
"text": "options β flags for particular task we want to perform"
},
{
"code": null,
"e": 6369,
"s": 6338,
"text": "URL β path url we want to test"
},
{
"code": null,
"e": 6400,
"s": 6369,
"text": "URL β path url we want to test"
},
{
"code": null,
"e": 6521,
"s": 6400,
"text": "We need to understand the different metrics to understand the various output values returned by ab. Here goes the list β"
},
{
"code": null,
"e": 6632,
"s": 6521,
"text": "Server Software β It is the name of the web server returned in the HTTP header of the first successful return."
},
{
"code": null,
"e": 6743,
"s": 6632,
"text": "Server Software β It is the name of the web server returned in the HTTP header of the first successful return."
},
{
"code": null,
"e": 6816,
"s": 6743,
"text": "Server Hostname β It is the DNS or IP address given on the command line."
},
{
"code": null,
"e": 6889,
"s": 6816,
"text": "Server Hostname β It is the DNS or IP address given on the command line."
},
{
"code": null,
"e": 7038,
"s": 6889,
"text": "Server Port β It is the port to which ab is connecting. If no port is given on the command line, this will default to 80 for http and 443 for https."
},
{
"code": null,
"e": 7187,
"s": 7038,
"text": "Server Port β It is the port to which ab is connecting. If no port is given on the command line, this will default to 80 for http and 443 for https."
},
{
"code": null,
"e": 7321,
"s": 7187,
"text": "SSL/TLS Protocol β This is the protocol parameter negotiated between the client and server. This will only be printed if SSL is used."
},
{
"code": null,
"e": 7455,
"s": 7321,
"text": "SSL/TLS Protocol β This is the protocol parameter negotiated between the client and server. This will only be printed if SSL is used."
},
{
"code": null,
"e": 7532,
"s": 7455,
"text": "Document Path β This is the request URI parsed from the command line string."
},
{
"code": null,
"e": 7609,
"s": 7532,
"text": "Document Path β This is the request URI parsed from the command line string."
},
{
"code": null,
"e": 7780,
"s": 7609,
"text": "Document Length β It is the size in bytes of the first successfully returned document. If the document length changes during testing, the response is considered an error."
},
{
"code": null,
"e": 7951,
"s": 7780,
"text": "Document Length β It is the size in bytes of the first successfully returned document. If the document length changes during testing, the response is considered an error."
},
{
"code": null,
"e": 8063,
"s": 7951,
"text": "Concurrency Level β This is the number of concurrent clients (equivalent to web browsers) used during the test."
},
{
"code": null,
"e": 8175,
"s": 8063,
"text": "Concurrency Level β This is the number of concurrent clients (equivalent to web browsers) used during the test."
},
{
"code": null,
"e": 8321,
"s": 8175,
"text": "Time Taken for Tests β This is the time taken from the moment the first socket connection is created to the moment the last response is received."
},
{
"code": null,
"e": 8467,
"s": 8321,
"text": "Time Taken for Tests β This is the time taken from the moment the first socket connection is created to the moment the last response is received."
},
{
"code": null,
"e": 8532,
"s": 8467,
"text": "Complete Requests β The number of successful responses received."
},
{
"code": null,
"e": 8597,
"s": 8532,
"text": "Complete Requests β The number of successful responses received."
},
{
"code": null,
"e": 8847,
"s": 8597,
"text": "Failed Requests β The number of requests that were considered a failure. If the number is greater than zero, another line will be printed showing the number of requests that failed due to connecting, reading, incorrect content length, or exceptions."
},
{
"code": null,
"e": 9097,
"s": 8847,
"text": "Failed Requests β The number of requests that were considered a failure. If the number is greater than zero, another line will be printed showing the number of requests that failed due to connecting, reading, incorrect content length, or exceptions."
},
{
"code": null,
"e": 9236,
"s": 9097,
"text": "Total Transferred β The total number of bytes received from the server. This number is essentially the number of bytes sent over the wire."
},
{
"code": null,
"e": 9375,
"s": 9236,
"text": "Total Transferred β The total number of bytes received from the server. This number is essentially the number of bytes sent over the wire."
},
{
"code": null,
"e": 9507,
"s": 9375,
"text": "HTML Transferred β The total number of document bytes received from the server. This number excludes bytes received in HTTP headers"
},
{
"code": null,
"e": 9639,
"s": 9507,
"text": "HTML Transferred β The total number of document bytes received from the server. This number excludes bytes received in HTTP headers"
},
{
"code": null,
"e": 9789,
"s": 9639,
"text": "Requests per second β This is the number of requests per second. This value is the result of dividing the number of requests by the total time taken."
},
{
"code": null,
"e": 9939,
"s": 9789,
"text": "Requests per second β This is the number of requests per second. This value is the result of dividing the number of requests by the total time taken."
},
{
"code": null,
"e": 10157,
"s": 9939,
"text": "Time per request β The average time spent per request. The first value is calculated with the formula concurrency * timetaken * 1000 / done while the second value is calculated with the formula timetaken * 1000 / done"
},
{
"code": null,
"e": 10375,
"s": 10157,
"text": "Time per request β The average time spent per request. The first value is calculated with the formula concurrency * timetaken * 1000 / done while the second value is calculated with the formula timetaken * 1000 / done"
},
{
"code": null,
"e": 10471,
"s": 10375,
"text": "Transfer rate β The rate of transfer as calculated by the formula totalread / 1024 / timetaken."
},
{
"code": null,
"e": 10567,
"s": 10471,
"text": "Transfer rate β The rate of transfer as calculated by the formula totalread / 1024 / timetaken."
},
{
"code": null,
"e": 10721,
"s": 10567,
"text": "Having learned about the headings of the output values from the ab command, let us try to analyze and understand the output values for our initial test β"
},
{
"code": null,
"e": 10805,
"s": 10721,
"text": "Apache organisation is using their own web Server Software β Apache (version 2.4.7)"
},
{
"code": null,
"e": 10889,
"s": 10805,
"text": "Apache organisation is using their own web Server Software β Apache (version 2.4.7)"
},
{
"code": null,
"e": 10990,
"s": 10889,
"text": "Server is listening on Port 443 because of https. Had it been http, it would have been 80 (default)."
},
{
"code": null,
"e": 11091,
"s": 10990,
"text": "Server is listening on Port 443 because of https. Had it been http, it would have been 80 (default)."
},
{
"code": null,
"e": 11147,
"s": 11091,
"text": "Total data transferred is 58769 bytes for 100 requests."
},
{
"code": null,
"e": 11203,
"s": 11147,
"text": "Total data transferred is 58769 bytes for 100 requests."
},
{
"code": null,
"e": 11266,
"s": 11203,
"text": "Test completed in 1.004 seconds. There are no failed requests."
},
{
"code": null,
"e": 11329,
"s": 11266,
"text": "Test completed in 1.004 seconds. There are no failed requests."
},
{
"code": null,
"e": 11400,
"s": 11329,
"text": "Requests per seconds β 99.56. This is considered a pretty good number."
},
{
"code": null,
"e": 11471,
"s": 11400,
"text": "Requests per seconds β 99.56. This is considered a pretty good number."
},
{
"code": null,
"e": 11588,
"s": 11471,
"text": "Time per request β 100.444 ms (for 10 concurrent requests). So across all requests, it is 100.444 ms/10 = 10.044 ms."
},
{
"code": null,
"e": 11705,
"s": 11588,
"text": "Time per request β 100.444 ms (for 10 concurrent requests). So across all requests, it is 100.444 ms/10 = 10.044 ms."
},
{
"code": null,
"e": 11752,
"s": 11705,
"text": "Transfer rate β 1338.39 [Kbytes/sec] received."
},
{
"code": null,
"e": 11799,
"s": 11752,
"text": "Transfer rate β 1338.39 [Kbytes/sec] received."
},
{
"code": null,
"e": 11963,
"s": 11799,
"text": "In connection time statistics, you can observe that many requests had to wait for few seconds. This may be due to apache web server putting requests in wait queue."
},
{
"code": null,
"e": 12127,
"s": 11963,
"text": "In connection time statistics, you can observe that many requests had to wait for few seconds. This may be due to apache web server putting requests in wait queue."
},
{
"code": null,
"e": 12526,
"s": 12127,
"text": "In our first test, we had tested an application (i.e., www.apache.org) hosted on a different server. In the later part of the tutorial, we will be testing our sample web-applications hosted on the same server from which we will be running the ab tests. This is for the ease of learning and demonstration purpose. Ideally, the host node and testing node should be different for accurate measurement."
},
{
"code": null,
"e": 12661,
"s": 12526,
"text": "To better learn ab, you should compare and observe how the output values vary for different cases as we move forward in this tutorial."
},
{
"code": null,
"e": 12921,
"s": 12661,
"text": "Here we will plot the relevant outcome to see how much time the server takes as the number of requests increases. For that, we will add the -g option in the previous command followed by the file name (here out.data) in which the ab output data will be saved β"
},
{
"code": null,
"e": 12976,
"s": 12921,
"text": "$ ab -n 100 -c 10 -g out.data https://www.apache.org/\n"
},
{
"code": null,
"e": 13030,
"s": 12976,
"text": "Let us now see the out.data before we create a plot β"
},
{
"code": null,
"e": 13047,
"s": 13030,
"text": "$ less out.data\n"
},
{
"code": null,
"e": 13054,
"s": 13047,
"text": "Output"
},
{
"code": null,
"e": 13337,
"s": 13054,
"text": "starttime seconds ctime dtime ttime wait\nTue May 30 12:11:37 2017 1496160697 40 38 77 13\nTue May 30 12:11:37 2017 1496160697 42 38 79 13\nTue May 30 12:11:37 2017 1496160697 41 38 80 13\n...\n"
},
{
"code": null,
"e": 13401,
"s": 13337,
"text": "Let us now understand the column headers in the out.data file β"
},
{
"code": null,
"e": 13466,
"s": 13401,
"text": "starttime β This is the date and time at which the call started."
},
{
"code": null,
"e": 13531,
"s": 13466,
"text": "starttime β This is the date and time at which the call started."
},
{
"code": null,
"e": 13640,
"s": 13531,
"text": "seconds β Same as starttime but in the Unix timestamp format (date -d @1496160697 returns starttime output)."
},
{
"code": null,
"e": 13749,
"s": 13640,
"text": "seconds β Same as starttime but in the Unix timestamp format (date -d @1496160697 returns starttime output)."
},
{
"code": null,
"e": 13786,
"s": 13749,
"text": "ctime β This is the Connection Time."
},
{
"code": null,
"e": 13823,
"s": 13786,
"text": "ctime β This is the Connection Time."
},
{
"code": null,
"e": 13860,
"s": 13823,
"text": "dtime β This is the Processing Time."
},
{
"code": null,
"e": 13897,
"s": 13860,
"text": "dtime β This is the Processing Time."
},
{
"code": null,
"e": 14002,
"s": 13897,
"text": "ttime β This is the Total Time (it is the sum of ctime and dtime, mathematically ttime = ctime + dtime)."
},
{
"code": null,
"e": 14107,
"s": 14002,
"text": "ttime β This is the Total Time (it is the sum of ctime and dtime, mathematically ttime = ctime + dtime)."
},
{
"code": null,
"e": 14140,
"s": 14107,
"text": "wait β This is the Waiting Time."
},
{
"code": null,
"e": 14173,
"s": 14140,
"text": "wait β This is the Waiting Time."
},
{
"code": null,
"e": 14295,
"s": 14173,
"text": "For a pictorial visualization of how these multiple items are related to each other, take a look at the following image β"
},
{
"code": null,
"e": 14459,
"s": 14295,
"text": "If we are working over terminal or where graphics are not available, gnuplot is a great option. We will quickly understand it by going through the following steps."
},
{
"code": null,
"e": 14495,
"s": 14459,
"text": "Let us install and launch gnuplot β"
},
{
"code": null,
"e": 14539,
"s": 14495,
"text": "$ sudo apt-get install gnuplot \n$ gnuplot\n"
},
{
"code": null,
"e": 14546,
"s": 14539,
"text": "Output"
},
{
"code": null,
"e": 14906,
"s": 14546,
"text": "G N U P L O T\nVersion 4.6 patchlevel 6 last modified September 2014\nBuild System: Linux x86_64\n\nCopyright (C) 1986-1993, 1998, 2004, 2007-2014\nThomas Williams, Colin Kelley and many others\n\ngnuplot home: http://www.gnuplot.info\nfaq, bugs, etc: type \"help FAQ\"\nimmediate help: type \"help\" (plot window: hit 'h')\n\nTerminal type set to 'qt'\ngnuplot>\n"
},
{
"code": null,
"e": 15196,
"s": 14906,
"text": "As we are working over terminal and supposing that graphics are not available, we can choose the dumb terminal which will give output in ASCII over the terminal itself. This helps us get an idea what our plot looks like with this quick tool. Let us now prepare the terminal for ASCII plot."
},
{
"code": null,
"e": 15224,
"s": 15196,
"text": "gnuplot> set terminal dumb\n"
},
{
"code": null,
"e": 15231,
"s": 15224,
"text": "Output"
},
{
"code": null,
"e": 15292,
"s": 15231,
"text": "Terminal type set to 'dumb'\nOptions are 'feed size 79, 24'\n"
},
{
"code": null,
"e": 15392,
"s": 15292,
"text": "As, our gnuplot terminal is now ready for ASCII plot, let us plot the data from the out.data file β"
},
{
"code": null,
"e": 15431,
"s": 15392,
"text": "gnuplot> plot \"out.data\" using 9 w l\n"
},
{
"code": null,
"e": 15438,
"s": 15431,
"text": "Output"
},
{
"code": null,
"e": 17057,
"s": 15438,
"text": " 1400 ++-----+------+-----+------+------+------+------+-----+------+-----++\n + + + + + + +\"out.data\" using 9 ****** +\n | |\n 1200 ++ ********************************************\n | ******************* |\n 1000 ++ * ++\n | * |\n | * |\n 800 ++ * ++\n | * |\n | * |\n 600 ++ * ++\n | * |\n | * |\n 400 ++ * ++\n | * |\n 200 ++ * ++\n | * |\n +**** + + + + + + + + + +\n 0 ++-----+------+-----+------+------+------+------+-----+------+-----++\n 0 10 20 30 40 50 60 70 80 90 100\n"
},
{
"code": null,
"e": 17382,
"s": 17057,
"text": "We have plotted the ttime, total time (in ms) from column 9, with respect to the number of requests. We can notice that for the initial ten requests, the total time was in the nearly 100 ms, for next 30 requests (from 10th to 40th), it increased to 1100 ms, and so on. Your plot must be different depending on your out.data."
},
{
"code": null,
"e": 17417,
"s": 17382,
"text": "\n 46 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 17436,
"s": 17417,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 17471,
"s": 17436,
"text": "\n 23 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 17492,
"s": 17471,
"text": " Mukund Kumar Mishra"
},
{
"code": null,
"e": 17525,
"s": 17492,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 17538,
"s": 17525,
"text": " Nilay Mehta"
},
{
"code": null,
"e": 17573,
"s": 17538,
"text": "\n 52 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 17591,
"s": 17573,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 17624,
"s": 17591,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 17642,
"s": 17624,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 17675,
"s": 17642,
"text": "\n 23 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 17693,
"s": 17675,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 17700,
"s": 17693,
"text": " Print"
},
{
"code": null,
"e": 17711,
"s": 17700,
"text": " Add Notes"
}
] |
How to install the specific version of the PowerShell module version?
|
To install the specific version of the PowerShell module, we need to use the -RequiredVersion parameter with the Install-Module command.
To find which module versions are available, we can use the Find-Module command with the -AllVersions parameter which retrieves all the versions of the module available in the PSGallery.
In this example, we will use the 7Zip4PowerShell module.
Find-Module 7zip4PowerShell -AllVersions | ft -AutoSize
When you run this command, you can see there are multiple versions available for this module.
Version Name Repository
------- ---- ----------
1.13.0 7Zip4Powershell PSGallery
1.12.0 7Zip4Powershell PSGallery
1.11.0 7Zip4Powershell PSGallery
1.10.0.0 7Zip4Powershell PSGallery
1.9.0 7Zip4Powershell PSGallery
1.8.0 7Zip4Powershell PSGallery
1.7.1 7Zip4Powershell PSGallery
We need to install here version 1.9.0 for all the users, so we will use the below command.
Install-Module 7Zip4PowerShell -RequiredVersion 1.8.0 -Scope AllUsers -Force -Verbose
To install PowerShell module on the remote server, use the below command,
Invoke-Command -ComputerName RemoteMachine1 -ScriptBlock {Install-Module 7Zip4PowerShell -RequiredVersion 1.8.0 -Scope AllUsers -Force -Verbose}
|
[
{
"code": null,
"e": 1199,
"s": 1062,
"text": "To install the specific version of the PowerShell module, we need to use the -RequiredVersion parameter with the Install-Module command."
},
{
"code": null,
"e": 1386,
"s": 1199,
"text": "To find which module versions are available, we can use the Find-Module command with the -AllVersions parameter which retrieves all the versions of the module available in the PSGallery."
},
{
"code": null,
"e": 1443,
"s": 1386,
"text": "In this example, we will use the 7Zip4PowerShell module."
},
{
"code": null,
"e": 1499,
"s": 1443,
"text": "Find-Module 7zip4PowerShell -AllVersions | ft -AutoSize"
},
{
"code": null,
"e": 1593,
"s": 1499,
"text": "When you run this command, you can see there are multiple versions available for this module."
},
{
"code": null,
"e": 1910,
"s": 1593,
"text": "Version Name Repository\n------- ---- ----------\n1.13.0 7Zip4Powershell PSGallery\n1.12.0 7Zip4Powershell PSGallery\n1.11.0 7Zip4Powershell PSGallery\n1.10.0.0 7Zip4Powershell PSGallery\n1.9.0 7Zip4Powershell PSGallery\n1.8.0 7Zip4Powershell PSGallery\n1.7.1 7Zip4Powershell PSGallery"
},
{
"code": null,
"e": 2001,
"s": 1910,
"text": "We need to install here version 1.9.0 for all the users, so we will use the below command."
},
{
"code": null,
"e": 2087,
"s": 2001,
"text": "Install-Module 7Zip4PowerShell -RequiredVersion 1.8.0 -Scope AllUsers -Force -Verbose"
},
{
"code": null,
"e": 2161,
"s": 2087,
"text": "To install PowerShell module on the remote server, use the below command,"
},
{
"code": null,
"e": 2306,
"s": 2161,
"text": "Invoke-Command -ComputerName RemoteMachine1 -ScriptBlock {Install-Module 7Zip4PowerShell -RequiredVersion 1.8.0 -Scope AllUsers -Force -Verbose}"
}
] |
MapStruct - Using defaultValue
|
Using Mapstruct we can pass the default value in case source property is null using defaultValue attribute of @Mapping annotation.
@Mapping(target = "target-property", source="source-property"
defaultValue = "default-value")
Here
default-value β target-property will be set as default-value in case source-property is null.
default-value β target-property will be set as default-value in case source-property is null.
Following example demonstrates the same.
Open project mapping as updated in Mapping Using Constant chapter in Eclipse.
Update CarEntity.java with following code β
CarEntity.java
package com.tutorialspoint.entity;
import java.util.GregorianCalendar;
public class CarEntity {
private int id;
private double price;
private GregorianCalendar manufacturingDate;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public GregorianCalendar getManufacturingDate() {
return manufacturingDate;
}
public void setManufacturingDate(GregorianCalendar manufacturingDate) {
this.manufacturingDate = manufacturingDate;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Update Car.java with following code β
Car.java
package com.tutorialspoint.model;
public class Car {
private int id;
private String price;
private String manufacturingDate;
private String brand;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getManufacturingDate() {
return manufacturingDate;
}
public void setManufacturingDate(String manufacturingDate) {
this.manufacturingDate = manufacturingDate;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Update CarMapper.java with following code β
CarMapper.java
package com.tutorialspoint.mapper;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import com.tutorialspoint.entity.CarEntity;
import com.tutorialspoint.model.Car;
@Mapper
public interface CarMapper {
@Mapping(source = "name", target = "name", defaultValue = "Sample")
@Mapping(target = "brand", constant = "BMW")
@Mapping(source = "price", target = "price", numberFormat = "$#.00")
@Mapping(source = "manufacturingDate", target = "manufacturingDate", dateFormat = "dd.MM.yyyy")
Car getModelFromEntity(CarEntity carEntity);
}
Update CarMapperTest.java with following code β
CarMapperTest.java
package com.tutorialspoint.mapping;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.GregorianCalendar;
import org.junit.jupiter.api.Test;
import org.mapstruct.factory.Mappers;
import com.tutorialspoint.entity.CarEntity;
import com.tutorialspoint.mapper.CarMapper;
import com.tutorialspoint.model.Car;
public class CarMapperTest {
private CarMapper carMapper = Mappers.getMapper(CarMapper.class);
@Test
public void testEntityToModel() {
CarEntity entity = new CarEntity();
entity.setPrice(345000);
entity.setId(1);
entity.setManufacturingDate(new GregorianCalendar(2015, 3, 5));
Car model = carMapper.getModelFromEntity(entity);
assertEquals(model.getPrice(), "$345000.00");
assertEquals(entity.getId(), model.getId());
assertEquals("05.04.2015", model.getManufacturingDate());
assertEquals("Sample", model.getName());
assertEquals("BMW", model.getBrand());
}
}
Run the following command to test the mappings.
mvn clean test
Once command is successful. Verify the output.
mvn clean test
[INFO] Scanning for projects...
...
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ mapping ---
[INFO] Surefire report directory: \mvn\mapping\target\surefire-reports
-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.tutorialspoint.mapping.CarMapperTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.035 sec
Running com.tutorialspoint.mapping.DeliveryAddressMapperTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0 sec
Running com.tutorialspoint.mapping.StudentMapperTest
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.001 sec
Results :
Tests run: 4, Failures: 0, Errors: 0, Skipped: 0
...
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2391,
"s": 2260,
"text": "Using Mapstruct we can pass the default value in case source property is null using defaultValue attribute of @Mapping annotation."
},
{
"code": null,
"e": 2490,
"s": 2391,
"text": "@Mapping(target = \"target-property\", source=\"source-property\" \n defaultValue = \"default-value\")\n"
},
{
"code": null,
"e": 2495,
"s": 2490,
"text": "Here"
},
{
"code": null,
"e": 2589,
"s": 2495,
"text": "default-value β target-property will be set as default-value in case source-property is null."
},
{
"code": null,
"e": 2683,
"s": 2589,
"text": "default-value β target-property will be set as default-value in case source-property is null."
},
{
"code": null,
"e": 2724,
"s": 2683,
"text": "Following example demonstrates the same."
},
{
"code": null,
"e": 2802,
"s": 2724,
"text": "Open project mapping as updated in Mapping Using Constant chapter in Eclipse."
},
{
"code": null,
"e": 2846,
"s": 2802,
"text": "Update CarEntity.java with following code β"
},
{
"code": null,
"e": 2861,
"s": 2846,
"text": "CarEntity.java"
},
{
"code": null,
"e": 3644,
"s": 2861,
"text": "package com.tutorialspoint.entity;\nimport java.util.GregorianCalendar;\n\npublic class CarEntity {\n private int id;\n private double price;\n private GregorianCalendar manufacturingDate;\n private String name;\n public int getId() {\n return id;\n }\n public void setId(int id) {\n this.id = id;\n }\n public double getPrice() {\n return price;\n }\n public void setPrice(double price) {\n this.price = price;\n }\n public GregorianCalendar getManufacturingDate() {\n return manufacturingDate;\n }\n public void setManufacturingDate(GregorianCalendar manufacturingDate) {\n this.manufacturingDate = manufacturingDate;\n }\n public String getName() {\n return name;\n }\n public void setName(String name) {\n this.name = name;\n }\n}"
},
{
"code": null,
"e": 3682,
"s": 3644,
"text": "Update Car.java with following code β"
},
{
"code": null,
"e": 3691,
"s": 3682,
"text": "Car.java"
},
{
"code": null,
"e": 4549,
"s": 3691,
"text": "package com.tutorialspoint.model;\n\npublic class Car {\n private int id;\n private String price;\n private String manufacturingDate;\n private String brand;\n private String name;\n public int getId() {\n return id;\n }\n public void setId(int id) {\n this.id = id;\n }\n public String getPrice() {\n return price;\n }\n public void setPrice(String price) {\n this.price = price;\n }\n public String getManufacturingDate() {\n return manufacturingDate;\n }\n public void setManufacturingDate(String manufacturingDate) {\n this.manufacturingDate = manufacturingDate;\n }\n public String getBrand() {\n return brand;\n }\n public void setBrand(String brand) {\n this.brand = brand;\n }\n public String getName() {\n return name;\n }\n public void setName(String name) {\n this.name = name;\n }\n}"
},
{
"code": null,
"e": 4593,
"s": 4549,
"text": "Update CarMapper.java with following code β"
},
{
"code": null,
"e": 4608,
"s": 4593,
"text": "CarMapper.java"
},
{
"code": null,
"e": 5162,
"s": 4608,
"text": "package com.tutorialspoint.mapper;\n\nimport org.mapstruct.Mapper;\nimport org.mapstruct.Mapping;\nimport com.tutorialspoint.entity.CarEntity;\nimport com.tutorialspoint.model.Car;\n\n@Mapper\npublic interface CarMapper {\n @Mapping(source = \"name\", target = \"name\", defaultValue = \"Sample\")\n @Mapping(target = \"brand\", constant = \"BMW\")\n @Mapping(source = \"price\", target = \"price\", numberFormat = \"$#.00\")\n @Mapping(source = \"manufacturingDate\", target = \"manufacturingDate\", dateFormat = \"dd.MM.yyyy\")\n Car getModelFromEntity(CarEntity carEntity);\n}"
},
{
"code": null,
"e": 5210,
"s": 5162,
"text": "Update CarMapperTest.java with following code β"
},
{
"code": null,
"e": 5229,
"s": 5210,
"text": "CarMapperTest.java"
},
{
"code": null,
"e": 6195,
"s": 5229,
"text": "package com.tutorialspoint.mapping;\n\nimport static org.junit.jupiter.api.Assertions.assertEquals;\nimport java.util.GregorianCalendar;\nimport org.junit.jupiter.api.Test;\nimport org.mapstruct.factory.Mappers;\nimport com.tutorialspoint.entity.CarEntity;\nimport com.tutorialspoint.mapper.CarMapper;\nimport com.tutorialspoint.model.Car;\n\npublic class CarMapperTest {\n private CarMapper carMapper = Mappers.getMapper(CarMapper.class);\n\n @Test\n public void testEntityToModel() {\n CarEntity entity = new CarEntity();\n entity.setPrice(345000);\n entity.setId(1);\n entity.setManufacturingDate(new GregorianCalendar(2015, 3, 5));\n Car model = carMapper.getModelFromEntity(entity);\n assertEquals(model.getPrice(), \"$345000.00\");\n assertEquals(entity.getId(), model.getId());\n assertEquals(\"05.04.2015\", model.getManufacturingDate());\n assertEquals(\"Sample\", model.getName());\n assertEquals(\"BMW\", model.getBrand());\n }\n}"
},
{
"code": null,
"e": 6243,
"s": 6195,
"text": "Run the following command to test the mappings."
},
{
"code": null,
"e": 6259,
"s": 6243,
"text": "mvn clean test\n"
},
{
"code": null,
"e": 6306,
"s": 6259,
"text": "Once command is successful. Verify the output."
},
{
"code": null,
"e": 7073,
"s": 6306,
"text": "mvn clean test\n[INFO] Scanning for projects...\n...\n[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ mapping ---\n[INFO] Surefire report directory: \\mvn\\mapping\\target\\surefire-reports\n\n-------------------------------------------------------\n T E S T S\n-------------------------------------------------------\nRunning com.tutorialspoint.mapping.CarMapperTest\nTests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.035 sec\nRunning com.tutorialspoint.mapping.DeliveryAddressMapperTest\nTests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0 sec\nRunning com.tutorialspoint.mapping.StudentMapperTest\nTests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.001 sec\n\nResults :\n\nTests run: 4, Failures: 0, Errors: 0, Skipped: 0\n...\n"
},
{
"code": null,
"e": 7080,
"s": 7073,
"text": " Print"
},
{
"code": null,
"e": 7091,
"s": 7080,
"text": " Add Notes"
}
] |
Predicting the impact of social media advertising on sales with linear regression | by Sonali Verghese | Towards Data Science
|
This article will detail the steps involved in performing a simple linear regression using the package R. It will also cover relevant and essential introductory statistics.
A linear regression measures the relationship between a response variable Y and a predictor variable X. Does Y increase with a unit increase in X? Or does it decrease with a unit increase in X? We want to predict the Y variable from X using a linear relationship. We can understand how two variables might be related to or influenced by each other.
For example, suppose Y is the number of stabbings per 1000 people in different neighbourhoods across London β the larger the number of stabbings, the greater the rate of crime. If X is the median house value of different neighbourhoods, we can use linear regression to test if neighbourhoods with lower median house values have a larger crime rates or vice versa.
Mathematically, a linear regression can be expressed as follows:
Y=Ξ²1+Ξ²2X+Ξ΅
The response (dependent) variable Y is what we are trying to predict.
The predictor (independent) variable X is used to predict the response.
Ξ²1 is the intercept and is a constant value. If X = 0, then Y will depend entirely on Ξ²1.
Ξ²2 is the slope of the regression line. We refer to these terms as coefficients.
Ξ΅ is the residual error term. This will show how much of Y can be explained by X. The error term has mean value of 0.
Letβs visualise this with an example.
We will use the marketing data set included with the datarium package, which contains the advertising budgets (in thousands of US dollars) for three media (Facebook, YouTube and newspapers) of a fictional company and sales data for that company.
Formulating a research question can be a useful method to guide the exploratory data analysis process. It can help to clean the data set and prepare it for rigorous analysis by eliminating unwanted variables, dealing with missing values etc. Our general question will be:
What is the effect of Facebook advertising on the companyβs sales, given the effects of YouTube and newspaper advertising?
We want to develop a linear model to explain the relationship between the predictor variablefacebook and the numeric response variable sales. In this article, we will use the package R to perform only a simple linear regression. Hereβs a simple linear regression equation:
Sales=Ξ²0+Ξ²1*Facebook+Ξ΅
A multiple regression, which involves more than one predictor variable, will be performed and explained in another article (coming soon!). For example, if we want to test the effects of Facebook advertising on company sales given the advertising budgets for YouTube and newspaper advertising, our multiple regression equation will look like this:
Sales=Ξ²0+Ξ²1*Facebook+ Ξ²2*YouTube +Ξ²3*Newspaper+Ξ΅
We will first begin with a simple linear regression to find the best line to predict the response sales as a function of the predictor facebook.
First, install the tidyverse, ggpubrand datarium packages in R Studio. Import the marketingdata set from the datarium package.
library(tidyverse)library(ggpubr)data(βmarketingβ, package = βdatariumβ)
To start with, we will use the str() function to get a snapshot view of the structure of our data. We can see there are 200 rows of data and 4 variables β youtube, facebook, newspaper and sales. We can also see the first few individual values for each variable. Additionally, we can see the classes of each column of variables β each of our variables is classed as βnumericβ.
> str(marketing)'data.frame': 200 obs. of 4 variables: $ youtube : num 276.1 53.4 20.6 181.8 217 ... $ facebook : num 45.4 47.2 55.1 49.6 13 ... $ newspaper: num 83 54.1 83.2 70.2 70.1 ... $ sales : num 26.5 12.5 11.2 22.2 15.5 ...
We can also use dim() to understand the dimensions of the data frame i.e. the number of rows and columns.
> dim(marketing)[1] 200 4
Next, we will use the head() function to get a glimpse of our raw data. By default, this function will return the first six rows but we can view any number of rows, depending on our preferences. We want to see the first 10 rows:
> head(marketing, 10) youtube facebook newspaper sales1 276.12 45.36 83.04 26.522 53.40 47.16 54.12 12.483 20.64 55.08 83.16 11.164 181.80 49.56 70.20 22.205 216.96 12.96 70.08 15.486 10.44 58.68 90.00 8.647 69.00 39.36 28.20 14.168 144.24 23.52 13.92 15.849 10.32 2.52 1.20 5.7610 239.76 3.12 25.44 12.72
Letβs look at the end of our data set as well with tail. This is very useful simply because, in some data sets, the last few columns may contain totals or summaries of the data, which can be irrelevant.
> tail(marketing) youtube facebook newspaper sales195 179.64 42.72 7.20 20.76196 45.84 4.44 16.56 9.12197 113.04 5.88 9.72 11.64198 212.40 11.16 7.68 15.36199 340.32 50.40 79.44 30.60200 278.52 10.32 10.44 16.08
Now, I want to pull up some summary statistics using summary.
> summary(marketing)youtube facebook newspaper Min. : 0.84 Min. : 0.00 Min. : 0.36 1st Qu.: 89.25 1st Qu.:11.97 1st Qu.: 15.30 Median :179.70 Median :27.48 Median : 30.90 Mean :176.45 Mean :27.92 Mean : 36.66 3rd Qu.:262.59 3rd Qu.:43.83 3rd Qu.: 54.12 Max. :355.68 Max. :59.52 Max. :136.80 sales Min. : 1.92 1st Qu.:12.45 Median :15.48 Mean :16.83 3rd Qu.:20.88 Max. :32.40
We must understand what these important terms and numbers represent.
Mean: The sum of all the values divided by the total number of values. In our example data set, mean budget for YouTube advertising is 176.45 or $176,450. The average Facebook advertising budget, on the other hand, is much lower at 27.92 or $27,920.
Median: The middle number in a sorted list with odd numbers. In a list with even numbers, the median is average of the two numbers that divide the sorted data into upper and lower halves.
Min: This is the lowest number value for each variable.
Max: This is the highest number value for each variable.
So weβve already gleaned some interesting information about our data set. We know the company spends more, on average, on YouTube advertising than on Facebook or newspaper advertising.
We can get a deeper insight into the distributions of data with quantile.
> quantile(marketing$facebook) 0% 25% 50% 75% 100% 0.00 11.97 27.48 43.83 59.52
Great! So we have some preliminary information about our data set and now we can plot some graphs. We will use the ggplot() function available in the ggpubr() package. First, to demonstrate why we use the ggpubr package to plot our graphs, we will use plot(), Rβs inbuilt plot function with basic graphics.
> plot(marketing$sales, marketing$facebook)
Now, we will use ggplot().
> ggplot(marketing, aes(x = facebook, y=sales)) + geom_point() + stat_smooth()
Facebook vs Sales
ggplot() allows for a more aesthetically-pleasing way to plot graphs. Here, the plot is the marketing data set with βaesβ or aesthetic mappings, which are derived from the facebook and sales variables, a set of points and a smoother.
The (publication-ready) graph above suggests a positive, linear relationship between the sales and facebook variables. This would suggest that an increase in the advertising budget would result in an increase in the companyβs sales. Out of curiosity, we can also visualise the relationships between sales and YouTube advertising and sales and newspaper advertising as well.
YouTube vs Sales
Newspaper vs Sales
Interestingly, while the relationship between sales and youtube advertising is also linear and positive, the relationship between salesand newspaper advertising is not β it is a curved line which actually begins to negatively slope at very low and very high levels of newspaper advertising.
What about the correlations between the independent and dependent variables? Correlation analysis will determine the strength of a relationship between two continuous variables. We must compute the correlation coefficient to perform this analysis. Correlations take values between +1 and -1. A value close to 0 suggests a weak correlation between two variables.
In our example data set, the variables will be positively correlated if high values of sales go with high values of Facebook advertising and vice versa. As weβve already seen in the graphs, there is a positive correlation between sales and Facebook advertising. However, there is a stronger positive correlation between sales and YouTube advertising.
The correlation between sales and newspaper advertising is the weakest. This suggests that much of the variation in sales (Y) is unexplained by newspaper advertising (X). To measure a significant variation in sales, we would need an explanatory variable with a strong correlation i.e. YouTube or Facebook.
> cor(marketing$sales, marketing$facebook)[1] 0.5762226> cor(marketing$sales, marketing$youtube)[1] 0.7822244> cor(marketing$sales, marketing$youtube)[1] 0.7822244
To perform a simple linear regression in R, we will use lm().
> model1 = lm(sales ~ facebook, data = marketing)> model1Call:lm(formula = sales ~ facebook, data = marketing)Coefficients:(Intercept) facebook 11.1740 0.2025
Now, letβs generate a graph for our regression. The regression line will try to minimise the sum of squared residual values (RSS or residual sum of squares).
> ggplot(marketing, aes(facebook, sales)) + geom_point() + stat_smooth(method = lm)
Regression concepts:
Fitted values and residuals: In general, real world data will not fall exactly on the regression line which is why the regression equation contains an error term Ξ΅. The fitted/predicted values are are denoted with ^. If Ξ² is denoted with a ^, then the coefficient is estimated. Statistics differentiates between estimates and known values because estimates are uncertain and known values are fixed. The error term Ξ΅ will contain this difference between estimated values and known values.
Least squares: In a simple regression, we would use the OLS or ordinary least squares method to estimate how well our regression model fits the data. The coefficients denoted with ^ are the values that minimise RSS. However, in a multiple regression we would use maximum likelihood to estimate model fit.
The estimated regression line is:
Sales=11.174+0.2025*Facebook+Ξ΅
The intercept (Ξ²0) is 11.174 and can be interpreted as the predicted dollar sales value for a Facebook advertising budget value of zero. So for a Facebook advertising budget equal to zero, we can expect sales of 11.174 *1000 = $11,174.
The regression coefficient (Ξ²1) shows that for a Facebook advertising budget equal to 1000 dollars, we can expect an increase of 202.5 units (0.2025*1000) in sales i.e.sales = 11.174 + 0.2025*1000 = 56.44 units. This represents a sales of $213,670.
Now that we have our regression model, we need to understand how to interpret it. It is not enough to create a regression model. We must check if (a) we have a statistically significant relationship for our regression to hold, and (b) our model fits the data well. A regression model that fits the data well is such that changes in X lead to changes in Y.
Before proceeding any further, we must understand standard errors and hypothesis testing.
Standard errors:
The standard error measures how much our coefficient estimates vary from the actual average value of our response variable. The standard error can be used to compute the confidence intervals. Confidence intervals quantify uncertainty around regression coefficients. By using the confint() function, we learn that there is a 95% chance that the interval [0.12,0.24] will contain the true value of Ξ²1.
> confint(model1) 2.5 % 97.5 %(Intercept) 9.8419062 12.5060253facebook 0.1622443 0.2427472
Hypothesis testing:
Standard errors can be used to perform hypothesis tests on the regression coefficients. The most common hypothesis test would be testing the null hypothesis versus the alternative hypothesis.
The null hypothesis (H0): The coefficients are equal to zero i.e., there is no relationship between the predictor and response variables.
The alternate hypothesis (H1): The coefficients are not equal to zero i.e., there is a relationship between the predictor and response variables.
To test the null hypothesis, we have to determine whether our estimate for Ξ²1 is sufficiently far from zero such that Ξ²1 is non-zero. If the standard error of our estimate of Ξ²1 is sufficiently small, then even small values of our estimate of Ξ²1 will provide evidence against the null hypothesis.
How do we measure how far our estimate of Ξ²1 is from zero? The t-statistic will measure the number of standard deviations our estimate of Ξ²1 is away from 0. We need to use the regression model to reject the null hypothesis and prove there is a relationship between the sales and facebook variables.
To interpret our linear regression, we will display a statistical summary of our model. To do this, we use summary().
> summary(model1)Call:lm(formula = sales ~ facebook, data = marketing)Residuals: Min 1Q Median 3Q Max -18.8766 -2.5589 0.9248 3.3330 9.8173 Coefficients: Estimate Std. Error t value Pr(>|t|) (Intercept) 11.17397 0.67548 16.542 <2e-16 ***facebook 0.20250 0.02041 9.921 <2e-16 ***---Signif. codes: 0 β***β 0.001 β**β 0.01 β*β 0.05 β.β 0.1 β β 1Residual standard error: 5.13 on 198 degrees of freedomMultiple R-squared: 0.332, Adjusted R-squared: 0.3287 F-statistic: 98.42 on 1 and 198 DF, p-value: < 2.2e-16
Letβs break down this summary output:
Residuals: As mentioned before, the residuals are the estimated coefficients denoted by ^. Residuals are the difference between the actual and estimated values. The distribution of our residuals should ideally be symmetrical.
Coefficients: Our coefficients Ξ²0 and Ξ²1 represent the intercept and slope respectively. We have already interpreted these coefficients in the section above.
The coefficient standard error, as mentioned above, measures how much our coefficient estimates vary from the actual average value of our response variable. In other words, it measures the accuracy of coefficient estimates. The closer our standard error is to zero, the better.
The coefficient t-value measures how far (in standard deviations) our coefficient estimate is from 0. A large t-value, relative to standard error, would provide evidence against the null hypothesis and indicate that a relationships exists between the predictor and response variables. Predictors with low t-statistics can be dropped. Ideally, the t-value should be greater than 1.96 for a p-value to be less than 0.05.
The coefficient β Pr(>t) represents the p-value or the probability of observing a value larger than t. The smaller the p-value, the more likely we are to reject the null hypothesis. Typically, a p-value of 5% or less is a good cut-off point. Note the βSignif. Codesβ associated to each estimate, in our example. Three asterisks represent a highly significant p-value. Since the relationship between sales and Facebook advertising is highly significant, we can reject our null hypothesis.
Residual standard error: This measures the quality of our regression fit. It is the average amount the sales variable will vary from the true regression line.
Multiple R-squared: Besides the t-statistic and p-value, this is our most important metric for measuring regression model fit. R2 measures the linear relationship between our predictor variable (sales) and our response / target variable (Facebook advertising). It always lies between 0 and 1. A number near 0 represents a regression that does not explain the variance in the response variable well and a number close to 1 does explain the observed variance in the response variable. In our example, the adjusted R2 (which adjusts for degrees of freedom) is 0.3287 β only 32.87% of an increase in sales can be explained by Facebook advertising. If we perform a multiple regression, we will find that the R2 will increase with an increase in the number of response variables. (Note: the relationship between YouTube advertising budgets and company sales is stronger, with an R2 of 0.612. Therefore, YouTube advertising is a better predictor of company sales data, when compared to Facebook advertising)
F-statistic: This is a good indicator of whether there is a relationship between Y and X. The further our F-statistic is away from 1, the better our regression model. In our example, the F-statistic is 98.42, which is relatively larger than 1 given the size of our data set (200 observations). The F-statistic is more relevant in a multiple regression model.
So the four key indicators of model fit we would need to primarily focus on are the t-statistic, p-value, R2 and F-statistic. The larger our t-statistic, the smaller the p-value. The smaller the p-value, the greater the odds of a relationship between X and Y. R2 measures how well a model fits the data β if R2 is close to 1, then this indicates that a large proportion of the variation in Y can be explained by X. The F-statistic shows the overall significance of the model. A large F-statistic will correspond to a statistically significant p-value (p < 0.05).
To summarise, we have performed a simple linear regression and have covered some basic introductory statistics as well. This is by no means a comprehensive analysis of the marketing data set but simply an example of how to perform and interpret a simple linear regression with R. Itβs a good starting point, especially when attempting to understand the relevance of important statistical concepts like t-statistic, p-value and standard error. In the next article, we will work on a multiple regression of this same data set, in continuation of this article. The multiple regression exercise will be a step towards a comprehensive data analysis project.
|
[
{
"code": null,
"e": 345,
"s": 172,
"text": "This article will detail the steps involved in performing a simple linear regression using the package R. It will also cover relevant and essential introductory statistics."
},
{
"code": null,
"e": 694,
"s": 345,
"text": "A linear regression measures the relationship between a response variable Y and a predictor variable X. Does Y increase with a unit increase in X? Or does it decrease with a unit increase in X? We want to predict the Y variable from X using a linear relationship. We can understand how two variables might be related to or influenced by each other."
},
{
"code": null,
"e": 1058,
"s": 694,
"text": "For example, suppose Y is the number of stabbings per 1000 people in different neighbourhoods across London β the larger the number of stabbings, the greater the rate of crime. If X is the median house value of different neighbourhoods, we can use linear regression to test if neighbourhoods with lower median house values have a larger crime rates or vice versa."
},
{
"code": null,
"e": 1123,
"s": 1058,
"text": "Mathematically, a linear regression can be expressed as follows:"
},
{
"code": null,
"e": 1134,
"s": 1123,
"text": "Y=Ξ²1+Ξ²2X+Ξ΅"
},
{
"code": null,
"e": 1204,
"s": 1134,
"text": "The response (dependent) variable Y is what we are trying to predict."
},
{
"code": null,
"e": 1276,
"s": 1204,
"text": "The predictor (independent) variable X is used to predict the response."
},
{
"code": null,
"e": 1366,
"s": 1276,
"text": "Ξ²1 is the intercept and is a constant value. If X = 0, then Y will depend entirely on Ξ²1."
},
{
"code": null,
"e": 1447,
"s": 1366,
"text": "Ξ²2 is the slope of the regression line. We refer to these terms as coefficients."
},
{
"code": null,
"e": 1565,
"s": 1447,
"text": "Ξ΅ is the residual error term. This will show how much of Y can be explained by X. The error term has mean value of 0."
},
{
"code": null,
"e": 1603,
"s": 1565,
"text": "Letβs visualise this with an example."
},
{
"code": null,
"e": 1849,
"s": 1603,
"text": "We will use the marketing data set included with the datarium package, which contains the advertising budgets (in thousands of US dollars) for three media (Facebook, YouTube and newspapers) of a fictional company and sales data for that company."
},
{
"code": null,
"e": 2121,
"s": 1849,
"text": "Formulating a research question can be a useful method to guide the exploratory data analysis process. It can help to clean the data set and prepare it for rigorous analysis by eliminating unwanted variables, dealing with missing values etc. Our general question will be:"
},
{
"code": null,
"e": 2244,
"s": 2121,
"text": "What is the effect of Facebook advertising on the companyβs sales, given the effects of YouTube and newspaper advertising?"
},
{
"code": null,
"e": 2517,
"s": 2244,
"text": "We want to develop a linear model to explain the relationship between the predictor variablefacebook and the numeric response variable sales. In this article, we will use the package R to perform only a simple linear regression. Hereβs a simple linear regression equation:"
},
{
"code": null,
"e": 2540,
"s": 2517,
"text": "Sales=Ξ²0+Ξ²1*Facebook+Ξ΅"
},
{
"code": null,
"e": 2887,
"s": 2540,
"text": "A multiple regression, which involves more than one predictor variable, will be performed and explained in another article (coming soon!). For example, if we want to test the effects of Facebook advertising on company sales given the advertising budgets for YouTube and newspaper advertising, our multiple regression equation will look like this:"
},
{
"code": null,
"e": 2936,
"s": 2887,
"text": "Sales=Ξ²0+Ξ²1*Facebook+ Ξ²2*YouTube +Ξ²3*Newspaper+Ξ΅"
},
{
"code": null,
"e": 3081,
"s": 2936,
"text": "We will first begin with a simple linear regression to find the best line to predict the response sales as a function of the predictor facebook."
},
{
"code": null,
"e": 3208,
"s": 3081,
"text": "First, install the tidyverse, ggpubrand datarium packages in R Studio. Import the marketingdata set from the datarium package."
},
{
"code": null,
"e": 3281,
"s": 3208,
"text": "library(tidyverse)library(ggpubr)data(βmarketingβ, package = βdatariumβ)"
},
{
"code": null,
"e": 3657,
"s": 3281,
"text": "To start with, we will use the str() function to get a snapshot view of the structure of our data. We can see there are 200 rows of data and 4 variables β youtube, facebook, newspaper and sales. We can also see the first few individual values for each variable. Additionally, we can see the classes of each column of variables β each of our variables is classed as βnumericβ."
},
{
"code": null,
"e": 3898,
"s": 3657,
"text": "> str(marketing)'data.frame':\t200 obs. of 4 variables: $ youtube : num 276.1 53.4 20.6 181.8 217 ... $ facebook : num 45.4 47.2 55.1 49.6 13 ... $ newspaper: num 83 54.1 83.2 70.2 70.1 ... $ sales : num 26.5 12.5 11.2 22.2 15.5 ..."
},
{
"code": null,
"e": 4004,
"s": 3898,
"text": "We can also use dim() to understand the dimensions of the data frame i.e. the number of rows and columns."
},
{
"code": null,
"e": 4030,
"s": 4004,
"text": "> dim(marketing)[1] 200 4"
},
{
"code": null,
"e": 4259,
"s": 4030,
"text": "Next, we will use the head() function to get a glimpse of our raw data. By default, this function will return the first six rows but we can view any number of rows, depending on our preferences. We want to see the first 10 rows:"
},
{
"code": null,
"e": 4666,
"s": 4259,
"text": "> head(marketing, 10) youtube facebook newspaper sales1 276.12 45.36 83.04 26.522 53.40 47.16 54.12 12.483 20.64 55.08 83.16 11.164 181.80 49.56 70.20 22.205 216.96 12.96 70.08 15.486 10.44 58.68 90.00 8.647 69.00 39.36 28.20 14.168 144.24 23.52 13.92 15.849 10.32 2.52 1.20 5.7610 239.76 3.12 25.44 12.72"
},
{
"code": null,
"e": 4869,
"s": 4666,
"text": "Letβs look at the end of our data set as well with tail. This is very useful simply because, in some data sets, the last few columns may contain totals or summaries of the data, which can be irrelevant."
},
{
"code": null,
"e": 5139,
"s": 4869,
"text": "> tail(marketing) youtube facebook newspaper sales195 179.64 42.72 7.20 20.76196 45.84 4.44 16.56 9.12197 113.04 5.88 9.72 11.64198 212.40 11.16 7.68 15.36199 340.32 50.40 79.44 30.60200 278.52 10.32 10.44 16.08"
},
{
"code": null,
"e": 5201,
"s": 5139,
"text": "Now, I want to pull up some summary statistics using summary."
},
{
"code": null,
"e": 5678,
"s": 5201,
"text": "> summary(marketing)youtube facebook newspaper Min. : 0.84 Min. : 0.00 Min. : 0.36 1st Qu.: 89.25 1st Qu.:11.97 1st Qu.: 15.30 Median :179.70 Median :27.48 Median : 30.90 Mean :176.45 Mean :27.92 Mean : 36.66 3rd Qu.:262.59 3rd Qu.:43.83 3rd Qu.: 54.12 Max. :355.68 Max. :59.52 Max. :136.80 sales Min. : 1.92 1st Qu.:12.45 Median :15.48 Mean :16.83 3rd Qu.:20.88 Max. :32.40"
},
{
"code": null,
"e": 5747,
"s": 5678,
"text": "We must understand what these important terms and numbers represent."
},
{
"code": null,
"e": 5997,
"s": 5747,
"text": "Mean: The sum of all the values divided by the total number of values. In our example data set, mean budget for YouTube advertising is 176.45 or $176,450. The average Facebook advertising budget, on the other hand, is much lower at 27.92 or $27,920."
},
{
"code": null,
"e": 6185,
"s": 5997,
"text": "Median: The middle number in a sorted list with odd numbers. In a list with even numbers, the median is average of the two numbers that divide the sorted data into upper and lower halves."
},
{
"code": null,
"e": 6241,
"s": 6185,
"text": "Min: This is the lowest number value for each variable."
},
{
"code": null,
"e": 6298,
"s": 6241,
"text": "Max: This is the highest number value for each variable."
},
{
"code": null,
"e": 6483,
"s": 6298,
"text": "So weβve already gleaned some interesting information about our data set. We know the company spends more, on average, on YouTube advertising than on Facebook or newspaper advertising."
},
{
"code": null,
"e": 6557,
"s": 6483,
"text": "We can get a deeper insight into the distributions of data with quantile."
},
{
"code": null,
"e": 6647,
"s": 6557,
"text": "> quantile(marketing$facebook) 0% 25% 50% 75% 100% 0.00 11.97 27.48 43.83 59.52"
},
{
"code": null,
"e": 6954,
"s": 6647,
"text": "Great! So we have some preliminary information about our data set and now we can plot some graphs. We will use the ggplot() function available in the ggpubr() package. First, to demonstrate why we use the ggpubr package to plot our graphs, we will use plot(), Rβs inbuilt plot function with basic graphics."
},
{
"code": null,
"e": 6998,
"s": 6954,
"text": "> plot(marketing$sales, marketing$facebook)"
},
{
"code": null,
"e": 7025,
"s": 6998,
"text": "Now, we will use ggplot()."
},
{
"code": null,
"e": 7104,
"s": 7025,
"text": "> ggplot(marketing, aes(x = facebook, y=sales)) + geom_point() + stat_smooth()"
},
{
"code": null,
"e": 7122,
"s": 7104,
"text": "Facebook vs Sales"
},
{
"code": null,
"e": 7356,
"s": 7122,
"text": "ggplot() allows for a more aesthetically-pleasing way to plot graphs. Here, the plot is the marketing data set with βaesβ or aesthetic mappings, which are derived from the facebook and sales variables, a set of points and a smoother."
},
{
"code": null,
"e": 7730,
"s": 7356,
"text": "The (publication-ready) graph above suggests a positive, linear relationship between the sales and facebook variables. This would suggest that an increase in the advertising budget would result in an increase in the companyβs sales. Out of curiosity, we can also visualise the relationships between sales and YouTube advertising and sales and newspaper advertising as well."
},
{
"code": null,
"e": 7747,
"s": 7730,
"text": "YouTube vs Sales"
},
{
"code": null,
"e": 7766,
"s": 7747,
"text": "Newspaper vs Sales"
},
{
"code": null,
"e": 8057,
"s": 7766,
"text": "Interestingly, while the relationship between sales and youtube advertising is also linear and positive, the relationship between salesand newspaper advertising is not β it is a curved line which actually begins to negatively slope at very low and very high levels of newspaper advertising."
},
{
"code": null,
"e": 8419,
"s": 8057,
"text": "What about the correlations between the independent and dependent variables? Correlation analysis will determine the strength of a relationship between two continuous variables. We must compute the correlation coefficient to perform this analysis. Correlations take values between +1 and -1. A value close to 0 suggests a weak correlation between two variables."
},
{
"code": null,
"e": 8770,
"s": 8419,
"text": "In our example data set, the variables will be positively correlated if high values of sales go with high values of Facebook advertising and vice versa. As weβve already seen in the graphs, there is a positive correlation between sales and Facebook advertising. However, there is a stronger positive correlation between sales and YouTube advertising."
},
{
"code": null,
"e": 9076,
"s": 8770,
"text": "The correlation between sales and newspaper advertising is the weakest. This suggests that much of the variation in sales (Y) is unexplained by newspaper advertising (X). To measure a significant variation in sales, we would need an explanatory variable with a strong correlation i.e. YouTube or Facebook."
},
{
"code": null,
"e": 9240,
"s": 9076,
"text": "> cor(marketing$sales, marketing$facebook)[1] 0.5762226> cor(marketing$sales, marketing$youtube)[1] 0.7822244> cor(marketing$sales, marketing$youtube)[1] 0.7822244"
},
{
"code": null,
"e": 9302,
"s": 9240,
"text": "To perform a simple linear regression in R, we will use lm()."
},
{
"code": null,
"e": 9476,
"s": 9302,
"text": "> model1 = lm(sales ~ facebook, data = marketing)> model1Call:lm(formula = sales ~ facebook, data = marketing)Coefficients:(Intercept) facebook 11.1740 0.2025"
},
{
"code": null,
"e": 9634,
"s": 9476,
"text": "Now, letβs generate a graph for our regression. The regression line will try to minimise the sum of squared residual values (RSS or residual sum of squares)."
},
{
"code": null,
"e": 9718,
"s": 9634,
"text": "> ggplot(marketing, aes(facebook, sales)) + geom_point() + stat_smooth(method = lm)"
},
{
"code": null,
"e": 9739,
"s": 9718,
"text": "Regression concepts:"
},
{
"code": null,
"e": 10227,
"s": 9739,
"text": "Fitted values and residuals: In general, real world data will not fall exactly on the regression line which is why the regression equation contains an error term Ξ΅. The fitted/predicted values are are denoted with ^. If Ξ² is denoted with a ^, then the coefficient is estimated. Statistics differentiates between estimates and known values because estimates are uncertain and known values are fixed. The error term Ξ΅ will contain this difference between estimated values and known values."
},
{
"code": null,
"e": 10532,
"s": 10227,
"text": "Least squares: In a simple regression, we would use the OLS or ordinary least squares method to estimate how well our regression model fits the data. The coefficients denoted with ^ are the values that minimise RSS. However, in a multiple regression we would use maximum likelihood to estimate model fit."
},
{
"code": null,
"e": 10566,
"s": 10532,
"text": "The estimated regression line is:"
},
{
"code": null,
"e": 10597,
"s": 10566,
"text": "Sales=11.174+0.2025*Facebook+Ξ΅"
},
{
"code": null,
"e": 10833,
"s": 10597,
"text": "The intercept (Ξ²0) is 11.174 and can be interpreted as the predicted dollar sales value for a Facebook advertising budget value of zero. So for a Facebook advertising budget equal to zero, we can expect sales of 11.174 *1000 = $11,174."
},
{
"code": null,
"e": 11082,
"s": 10833,
"text": "The regression coefficient (Ξ²1) shows that for a Facebook advertising budget equal to 1000 dollars, we can expect an increase of 202.5 units (0.2025*1000) in sales i.e.sales = 11.174 + 0.2025*1000 = 56.44 units. This represents a sales of $213,670."
},
{
"code": null,
"e": 11438,
"s": 11082,
"text": "Now that we have our regression model, we need to understand how to interpret it. It is not enough to create a regression model. We must check if (a) we have a statistically significant relationship for our regression to hold, and (b) our model fits the data well. A regression model that fits the data well is such that changes in X lead to changes in Y."
},
{
"code": null,
"e": 11528,
"s": 11438,
"text": "Before proceeding any further, we must understand standard errors and hypothesis testing."
},
{
"code": null,
"e": 11545,
"s": 11528,
"text": "Standard errors:"
},
{
"code": null,
"e": 11945,
"s": 11545,
"text": "The standard error measures how much our coefficient estimates vary from the actual average value of our response variable. The standard error can be used to compute the confidence intervals. Confidence intervals quantify uncertainty around regression coefficients. By using the confint() function, we learn that there is a 95% chance that the interval [0.12,0.24] will contain the true value of Ξ²1."
},
{
"code": null,
"e": 12059,
"s": 11945,
"text": "> confint(model1) 2.5 % 97.5 %(Intercept) 9.8419062 12.5060253facebook 0.1622443 0.2427472"
},
{
"code": null,
"e": 12079,
"s": 12059,
"text": "Hypothesis testing:"
},
{
"code": null,
"e": 12271,
"s": 12079,
"text": "Standard errors can be used to perform hypothesis tests on the regression coefficients. The most common hypothesis test would be testing the null hypothesis versus the alternative hypothesis."
},
{
"code": null,
"e": 12409,
"s": 12271,
"text": "The null hypothesis (H0): The coefficients are equal to zero i.e., there is no relationship between the predictor and response variables."
},
{
"code": null,
"e": 12555,
"s": 12409,
"text": "The alternate hypothesis (H1): The coefficients are not equal to zero i.e., there is a relationship between the predictor and response variables."
},
{
"code": null,
"e": 12852,
"s": 12555,
"text": "To test the null hypothesis, we have to determine whether our estimate for Ξ²1 is sufficiently far from zero such that Ξ²1 is non-zero. If the standard error of our estimate of Ξ²1 is sufficiently small, then even small values of our estimate of Ξ²1 will provide evidence against the null hypothesis."
},
{
"code": null,
"e": 13151,
"s": 12852,
"text": "How do we measure how far our estimate of Ξ²1 is from zero? The t-statistic will measure the number of standard deviations our estimate of Ξ²1 is away from 0. We need to use the regression model to reject the null hypothesis and prove there is a relationship between the sales and facebook variables."
},
{
"code": null,
"e": 13269,
"s": 13151,
"text": "To interpret our linear regression, we will display a statistical summary of our model. To do this, we use summary()."
},
{
"code": null,
"e": 13840,
"s": 13269,
"text": "> summary(model1)Call:lm(formula = sales ~ facebook, data = marketing)Residuals: Min 1Q Median 3Q Max -18.8766 -2.5589 0.9248 3.3330 9.8173 Coefficients: Estimate Std. Error t value Pr(>|t|) (Intercept) 11.17397 0.67548 16.542 <2e-16 ***facebook 0.20250 0.02041 9.921 <2e-16 ***---Signif. codes: 0 β***β 0.001 β**β 0.01 β*β 0.05 β.β 0.1 β β 1Residual standard error: 5.13 on 198 degrees of freedomMultiple R-squared: 0.332,\tAdjusted R-squared: 0.3287 F-statistic: 98.42 on 1 and 198 DF, p-value: < 2.2e-16"
},
{
"code": null,
"e": 13878,
"s": 13840,
"text": "Letβs break down this summary output:"
},
{
"code": null,
"e": 14104,
"s": 13878,
"text": "Residuals: As mentioned before, the residuals are the estimated coefficients denoted by ^. Residuals are the difference between the actual and estimated values. The distribution of our residuals should ideally be symmetrical."
},
{
"code": null,
"e": 14262,
"s": 14104,
"text": "Coefficients: Our coefficients Ξ²0 and Ξ²1 represent the intercept and slope respectively. We have already interpreted these coefficients in the section above."
},
{
"code": null,
"e": 14540,
"s": 14262,
"text": "The coefficient standard error, as mentioned above, measures how much our coefficient estimates vary from the actual average value of our response variable. In other words, it measures the accuracy of coefficient estimates. The closer our standard error is to zero, the better."
},
{
"code": null,
"e": 14959,
"s": 14540,
"text": "The coefficient t-value measures how far (in standard deviations) our coefficient estimate is from 0. A large t-value, relative to standard error, would provide evidence against the null hypothesis and indicate that a relationships exists between the predictor and response variables. Predictors with low t-statistics can be dropped. Ideally, the t-value should be greater than 1.96 for a p-value to be less than 0.05."
},
{
"code": null,
"e": 15447,
"s": 14959,
"text": "The coefficient β Pr(>t) represents the p-value or the probability of observing a value larger than t. The smaller the p-value, the more likely we are to reject the null hypothesis. Typically, a p-value of 5% or less is a good cut-off point. Note the βSignif. Codesβ associated to each estimate, in our example. Three asterisks represent a highly significant p-value. Since the relationship between sales and Facebook advertising is highly significant, we can reject our null hypothesis."
},
{
"code": null,
"e": 15606,
"s": 15447,
"text": "Residual standard error: This measures the quality of our regression fit. It is the average amount the sales variable will vary from the true regression line."
},
{
"code": null,
"e": 16607,
"s": 15606,
"text": "Multiple R-squared: Besides the t-statistic and p-value, this is our most important metric for measuring regression model fit. R2 measures the linear relationship between our predictor variable (sales) and our response / target variable (Facebook advertising). It always lies between 0 and 1. A number near 0 represents a regression that does not explain the variance in the response variable well and a number close to 1 does explain the observed variance in the response variable. In our example, the adjusted R2 (which adjusts for degrees of freedom) is 0.3287 β only 32.87% of an increase in sales can be explained by Facebook advertising. If we perform a multiple regression, we will find that the R2 will increase with an increase in the number of response variables. (Note: the relationship between YouTube advertising budgets and company sales is stronger, with an R2 of 0.612. Therefore, YouTube advertising is a better predictor of company sales data, when compared to Facebook advertising)"
},
{
"code": null,
"e": 16966,
"s": 16607,
"text": "F-statistic: This is a good indicator of whether there is a relationship between Y and X. The further our F-statistic is away from 1, the better our regression model. In our example, the F-statistic is 98.42, which is relatively larger than 1 given the size of our data set (200 observations). The F-statistic is more relevant in a multiple regression model."
},
{
"code": null,
"e": 17529,
"s": 16966,
"text": "So the four key indicators of model fit we would need to primarily focus on are the t-statistic, p-value, R2 and F-statistic. The larger our t-statistic, the smaller the p-value. The smaller the p-value, the greater the odds of a relationship between X and Y. R2 measures how well a model fits the data β if R2 is close to 1, then this indicates that a large proportion of the variation in Y can be explained by X. The F-statistic shows the overall significance of the model. A large F-statistic will correspond to a statistically significant p-value (p < 0.05)."
}
] |
amixer command in Linux with Examples - GeeksforGeeks
|
15 Apr, 2019
amixer is a command-line mixer for ALSA(Advanced Linux Sound Architecture) sound-card driver. amixer can support multiple soundcards. amixer with no arguments will display the current mixer settings for the default soundcard as well as the device. This is a good way to see a list of the simple mixer controls that you can use.
Syntax:
amixer [-option] [command]
Commands and Options:
-h or βhelp : Displays help and then exits.
βinfo : Displays the info and then exits.
βscontols : Displays a complete list of simple controls and then exits.
βscontents : Shows a complete list of simple mixer controls and their contents as well.
set or sset : Sets the contents of the simple mixer.
get or sget : Shows the control contents of the simple mixer.
controls : Displays a complete list of the card controls.
contents : Displays a complete list of the card controls with their contents as well.
cset : Is used to set the card controls.
cget : It shows the card control contents. The identifier has the same syntax as for the cset command.
-c : Selects the card number that needs to be controlled.
-D : Selects the device name that needs to be controlled.
-s or βstdin : Read from stdin and execute each command sequentially.
-q : Does not display the result of the changes.
-R : Uses the raw value for evaluating the percentage representation which is also the default mode.
-M : Uses the mapped volume for evaluating the percentage representation like alsamixer, to be more natural for the human ear.
-v : Displays the version.
linux-command
Linux-misc-commands
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Thread functions in C/C++
Array Basics in Shell Scripting | Set 1
scp command in Linux with Examples
chown command in Linux with Examples
nohup Command in Linux with Examples
Named Pipe or FIFO with example C program
mv command in Linux with examples
SED command in Linux | Set 2
Basic Operators in Shell Scripting
Start/Stop/Restart Services Using Systemctl in Linux
|
[
{
"code": null,
"e": 24326,
"s": 24298,
"text": "\n15 Apr, 2019"
},
{
"code": null,
"e": 24654,
"s": 24326,
"text": "amixer is a command-line mixer for ALSA(Advanced Linux Sound Architecture) sound-card driver. amixer can support multiple soundcards. amixer with no arguments will display the current mixer settings for the default soundcard as well as the device. This is a good way to see a list of the simple mixer controls that you can use."
},
{
"code": null,
"e": 24662,
"s": 24654,
"text": "Syntax:"
},
{
"code": null,
"e": 24689,
"s": 24662,
"text": "amixer [-option] [command]"
},
{
"code": null,
"e": 24711,
"s": 24689,
"text": "Commands and Options:"
},
{
"code": null,
"e": 24755,
"s": 24711,
"text": "-h or βhelp : Displays help and then exits."
},
{
"code": null,
"e": 24797,
"s": 24755,
"text": "βinfo : Displays the info and then exits."
},
{
"code": null,
"e": 24869,
"s": 24797,
"text": "βscontols : Displays a complete list of simple controls and then exits."
},
{
"code": null,
"e": 24957,
"s": 24869,
"text": "βscontents : Shows a complete list of simple mixer controls and their contents as well."
},
{
"code": null,
"e": 25010,
"s": 24957,
"text": "set or sset : Sets the contents of the simple mixer."
},
{
"code": null,
"e": 25072,
"s": 25010,
"text": "get or sget : Shows the control contents of the simple mixer."
},
{
"code": null,
"e": 25130,
"s": 25072,
"text": "controls : Displays a complete list of the card controls."
},
{
"code": null,
"e": 25216,
"s": 25130,
"text": "contents : Displays a complete list of the card controls with their contents as well."
},
{
"code": null,
"e": 25257,
"s": 25216,
"text": "cset : Is used to set the card controls."
},
{
"code": null,
"e": 25360,
"s": 25257,
"text": "cget : It shows the card control contents. The identifier has the same syntax as for the cset command."
},
{
"code": null,
"e": 25418,
"s": 25360,
"text": "-c : Selects the card number that needs to be controlled."
},
{
"code": null,
"e": 25476,
"s": 25418,
"text": "-D : Selects the device name that needs to be controlled."
},
{
"code": null,
"e": 25546,
"s": 25476,
"text": "-s or βstdin : Read from stdin and execute each command sequentially."
},
{
"code": null,
"e": 25595,
"s": 25546,
"text": "-q : Does not display the result of the changes."
},
{
"code": null,
"e": 25696,
"s": 25595,
"text": "-R : Uses the raw value for evaluating the percentage representation which is also the default mode."
},
{
"code": null,
"e": 25823,
"s": 25696,
"text": "-M : Uses the mapped volume for evaluating the percentage representation like alsamixer, to be more natural for the human ear."
},
{
"code": null,
"e": 25850,
"s": 25823,
"text": "-v : Displays the version."
},
{
"code": null,
"e": 25864,
"s": 25850,
"text": "linux-command"
},
{
"code": null,
"e": 25884,
"s": 25864,
"text": "Linux-misc-commands"
},
{
"code": null,
"e": 25891,
"s": 25884,
"text": "Picked"
},
{
"code": null,
"e": 25902,
"s": 25891,
"text": "Linux-Unix"
},
{
"code": null,
"e": 26000,
"s": 25902,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26009,
"s": 26000,
"text": "Comments"
},
{
"code": null,
"e": 26022,
"s": 26009,
"text": "Old Comments"
},
{
"code": null,
"e": 26048,
"s": 26022,
"text": "Thread functions in C/C++"
},
{
"code": null,
"e": 26088,
"s": 26048,
"text": "Array Basics in Shell Scripting | Set 1"
},
{
"code": null,
"e": 26123,
"s": 26088,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 26160,
"s": 26123,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 26197,
"s": 26160,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 26239,
"s": 26197,
"text": "Named Pipe or FIFO with example C program"
},
{
"code": null,
"e": 26273,
"s": 26239,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 26302,
"s": 26273,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 26337,
"s": 26302,
"text": "Basic Operators in Shell Scripting"
}
] |
Animate CSS margin-left property
|
To implement animation on margin-left property in CSS, you can try to run the following code
Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
div {
background-color: gray;
animation: myanim 3s infinite;
color: white;
}
@keyframes myanim {
30% {
margin-left: 20px;
}
}
</style>
</head>
<body>
<h2>Heading One</h2>
<div>
This is demo text.
</div>
</body>
</html>
|
[
{
"code": null,
"e": 1155,
"s": 1062,
"text": "To implement animation on margin-left property in CSS, you can try to run the following code"
},
{
"code": null,
"e": 1165,
"s": 1155,
"text": "Live Demo"
},
{
"code": null,
"e": 1584,
"s": 1165,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <style>\n div {\n background-color: gray;\n animation: myanim 3s infinite;\n color: white;\n }\n @keyframes myanim {\n 30% {\n margin-left: 20px;\n }\n }\n </style>\n </head>\n <body>\n <h2>Heading One</h2>\n <div>\n This is demo text.\n </div>\n </body>\n</html>"
}
] |
MS SQL Server - Assign Permissions
|
Permissions refer to the rules governing the levels of access that principals have to securables. You can grant, revoke and deny permissions in MS SQL Server.
To assign permissions either of the following two methods can be used.
Use <database name>
Grant <permission name> on <object name> to <username\principle>
To assign select permission to a user called 'TestUser' on object called 'TestTable' in 'TestDB' database, run the following query.
USE TestDB
GO
Grant select on TestTable to TestUser
Step 1 β Connect to instance and expand folders as shown in the following snapshot.
Step 2 β Right-click on TestUser and click Properties. The following screen appears.
Step 3 Click Search and select specific options. Click Object types, select tables and click browse. Select 'TestTable' and click OK. The following screen appears.
Step 4 Select checkbox for Grant column under Select permission and click OK as shown in the above snapshot.
Step 5 Select permission on 'TestTable' of TestDB database granted to 'TestUser'. Click OK.
32 Lectures
2.5 hours
Pavan Lalwani
18 Lectures
1.5 hours
Dr. Saatya Prasad
102 Lectures
10 hours
Pavan Lalwani
52 Lectures
4 hours
Pavan Lalwani
239 Lectures
33 hours
Gowthami Swarna
53 Lectures
5 hours
Akshay Magre
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2394,
"s": 2235,
"text": "Permissions refer to the rules governing the levels of access that principals have to securables. You can grant, revoke and deny permissions in MS SQL Server."
},
{
"code": null,
"e": 2465,
"s": 2394,
"text": "To assign permissions either of the following two methods can be used."
},
{
"code": null,
"e": 2551,
"s": 2465,
"text": "Use <database name>\nGrant <permission name> on <object name> to <username\\principle>\n"
},
{
"code": null,
"e": 2683,
"s": 2551,
"text": "To assign select permission to a user called 'TestUser' on object called 'TestTable' in 'TestDB' database, run the following query."
},
{
"code": null,
"e": 2736,
"s": 2683,
"text": "USE TestDB\nGO\nGrant select on TestTable to TestUser\n"
},
{
"code": null,
"e": 2820,
"s": 2736,
"text": "Step 1 β Connect to instance and expand folders as shown in the following snapshot."
},
{
"code": null,
"e": 2905,
"s": 2820,
"text": "Step 2 β Right-click on TestUser and click Properties. The following screen appears."
},
{
"code": null,
"e": 3069,
"s": 2905,
"text": "Step 3 Click Search and select specific options. Click Object types, select tables and click browse. Select 'TestTable' and click OK. The following screen appears."
},
{
"code": null,
"e": 3178,
"s": 3069,
"text": "Step 4 Select checkbox for Grant column under Select permission and click OK as shown in the above snapshot."
},
{
"code": null,
"e": 3270,
"s": 3178,
"text": "Step 5 Select permission on 'TestTable' of TestDB database granted to 'TestUser'. Click OK."
},
{
"code": null,
"e": 3305,
"s": 3270,
"text": "\n 32 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3320,
"s": 3305,
"text": " Pavan Lalwani"
},
{
"code": null,
"e": 3355,
"s": 3320,
"text": "\n 18 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3374,
"s": 3355,
"text": " Dr. Saatya Prasad"
},
{
"code": null,
"e": 3409,
"s": 3374,
"text": "\n 102 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 3424,
"s": 3409,
"text": " Pavan Lalwani"
},
{
"code": null,
"e": 3457,
"s": 3424,
"text": "\n 52 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 3472,
"s": 3457,
"text": " Pavan Lalwani"
},
{
"code": null,
"e": 3507,
"s": 3472,
"text": "\n 239 Lectures \n 33 hours \n"
},
{
"code": null,
"e": 3524,
"s": 3507,
"text": " Gowthami Swarna"
},
{
"code": null,
"e": 3557,
"s": 3524,
"text": "\n 53 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 3571,
"s": 3557,
"text": " Akshay Magre"
},
{
"code": null,
"e": 3578,
"s": 3571,
"text": " Print"
},
{
"code": null,
"e": 3589,
"s": 3578,
"text": " Add Notes"
}
] |
C++ Program For Flattening A Multilevel Linked List - GeeksforGeeks
|
22 Dec, 2021
Given a linked list where in addition to the next pointer, each node has a child pointer, which may or may not point to a separate list. These child lists may have one or more children of their own, and so on, to produce a multilevel data structure, as shown below figure. You are given the head of the first level of the list. Flatten the list so that all the nodes appear in a single-level linked list. You need to flatten the list in a way that all nodes at the first level should come first, then nodes of the second level, and so on.
The above list should be converted to 10->5->12->7->11->4->20->13->17->6->2->16->9->8->3->19->15
The problem clearly says that we need to flatten level by level. The idea of a solution is, we start from the first level, process all nodes one by one, if a node has a child, then we append the child at the end of the list, otherwise, we donβt do anything. After the first level is processed, all next-level nodes will be appended after the first level. The same process is followed for the appended nodes.
1) Take the "cur" pointer, which will point to the head
of the first level of the list
2) Take the "tail" pointer, which will point to the end of the
first level of the list
3) Repeat the below procedure while "curr" is not NULL.
I) If the current node has a child then
a) Append this new child list to the "tail"
tail->next = cur->child
b) Find the last node of the new child list and update
the "tail"
tmp = cur->child;
while (tmp->next != NULL)
tmp = tmp->next;
tail = tmp;
II) Move to the next node. i.e. cur = cur->next
Following is the implementation of the above algorithm.
C++
// C++ Program to flatten list with// next and child pointers #include <bits/stdc++.h>using namespace std; // Macro to find number of elements // in array #define SIZE(arr) (sizeof(arr) / sizeof(arr[0])) // A linked list node has data, // next pointer and child pointer class Node { public: int data; Node *next; Node *child; }; // A utility function to create a linked list// with n nodes. The data of nodes is taken // from arr[]. All child pointers are set as NULL Node *createList(int *arr, int n) { Node *head = NULL; Node *p; int i; for (i = 0; i < n; ++i) { if (head == NULL) head = p = new Node(); else { p->next = new Node(); p = p->next; } p->data = arr[i]; p->next = p->child = NULL; } return head; } // A utility function to print // all nodes of a linked list void printList(Node *head) { while (head != NULL) { cout << head->data << " "; head = head->next; } cout<<endl; } // This function creates the input // list. The created list is same // as shown in the above figure Node *createList(void) { int arr1[] = {10, 5, 12, 7, 11}; int arr2[] = {4, 20, 13}; int arr3[] = {17, 6}; int arr4[] = {9, 8}; int arr5[] = {19, 15}; int arr6[] = {2}; int arr7[] = {16}; int arr8[] = {3}; // Create 8 linked lists Node *head1 = createList(arr1, SIZE(arr1)); Node *head2 = createList(arr2, SIZE(arr2)); Node *head3 = createList(arr3, SIZE(arr3)); Node *head4 = createList(arr4, SIZE(arr4)); Node *head5 = createList(arr5, SIZE(arr5)); Node *head6 = createList(arr6, SIZE(arr6)); Node *head7 = createList(arr7, SIZE(arr7)); Node *head8 = createList(arr8, SIZE(arr8)); /* Modify child pointers to create the list shown above */ head1->child = head2; head1->next->next->next->child = head3; head3->child = head4; head4->child = head5; head2->next->child = head6; head2->next->next->child = head7; head7->child = head8; /* Return head pointer of first linked list. Note that all nodes are reachable from head1 */ return head1; } /* The main function that flattens a multilevel linked list */void flattenList(Node *head) { // Base case if (head == NULL) return; Node *tmp; /* Find tail node of first level linked list */ Node *tail = head; while (tail->next != NULL) tail = tail->next; // One by one traverse through // all nodes of first level // linked list till we reach // the tail node Node *cur = head; while (cur != tail) { // If current node has a child if (cur->child) { // Then append the child at the // end of current list tail->next = cur->child; // And update the tail to new // last node tmp = cur->child; while (tmp->next) tmp = tmp->next; tail = tmp; } // Change current node cur = cur->next; } } // Driver codeint main(void) { Node *head = NULL; head = createList(); flattenList(head); printList(head); return 0; } // This code is contributed by rathbhupendra
Output:
10 5 12 7 11 4 20 13 17 6 2 16 9 8 3 19 15
Time Complexity: Since every node is visited at most twice, the time complexity is O(n) where n is the number of nodes in given linked list.
Please refer complete article on Flatten a multilevel linked list for more details!
Linked Lists
C++
C++ Programs
Linked List
Linked List
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Operator Overloading in C++
Iterators in C++ STL
Friend class and function in C++
Polymorphism in C++
Sorting a vector in C++
Header files in C/C++ and its uses
C++ Program for QuickSort
How to return multiple values from a function in C or C++?
CSV file management using C++
Program to print ASCII Value of a character
|
[
{
"code": null,
"e": 24096,
"s": 24068,
"text": "\n22 Dec, 2021"
},
{
"code": null,
"e": 24635,
"s": 24096,
"text": "Given a linked list where in addition to the next pointer, each node has a child pointer, which may or may not point to a separate list. These child lists may have one or more children of their own, and so on, to produce a multilevel data structure, as shown below figure. You are given the head of the first level of the list. Flatten the list so that all the nodes appear in a single-level linked list. You need to flatten the list in a way that all nodes at the first level should come first, then nodes of the second level, and so on."
},
{
"code": null,
"e": 24732,
"s": 24635,
"text": "The above list should be converted to 10->5->12->7->11->4->20->13->17->6->2->16->9->8->3->19->15"
},
{
"code": null,
"e": 25141,
"s": 24732,
"text": "The problem clearly says that we need to flatten level by level. The idea of a solution is, we start from the first level, process all nodes one by one, if a node has a child, then we append the child at the end of the list, otherwise, we donβt do anything. After the first level is processed, all next-level nodes will be appended after the first level. The same process is followed for the appended nodes. "
},
{
"code": null,
"e": 25747,
"s": 25141,
"text": "1) Take the \"cur\" pointer, which will point to the head \n of the first level of the list\n2) Take the \"tail\" pointer, which will point to the end of the \n first level of the list\n3) Repeat the below procedure while \"curr\" is not NULL.\n I) If the current node has a child then\n a) Append this new child list to the \"tail\"\n tail->next = cur->child\n b) Find the last node of the new child list and update \n the \"tail\"\n tmp = cur->child;\n while (tmp->next != NULL)\n tmp = tmp->next;\n tail = tmp;\n II) Move to the next node. i.e. cur = cur->next"
},
{
"code": null,
"e": 25804,
"s": 25747,
"text": "Following is the implementation of the above algorithm. "
},
{
"code": null,
"e": 25808,
"s": 25804,
"text": "C++"
},
{
"code": "// C++ Program to flatten list with// next and child pointers #include <bits/stdc++.h>using namespace std; // Macro to find number of elements // in array #define SIZE(arr) (sizeof(arr) / sizeof(arr[0])) // A linked list node has data, // next pointer and child pointer class Node { public: int data; Node *next; Node *child; }; // A utility function to create a linked list// with n nodes. The data of nodes is taken // from arr[]. All child pointers are set as NULL Node *createList(int *arr, int n) { Node *head = NULL; Node *p; int i; for (i = 0; i < n; ++i) { if (head == NULL) head = p = new Node(); else { p->next = new Node(); p = p->next; } p->data = arr[i]; p->next = p->child = NULL; } return head; } // A utility function to print // all nodes of a linked list void printList(Node *head) { while (head != NULL) { cout << head->data << \" \"; head = head->next; } cout<<endl; } // This function creates the input // list. The created list is same // as shown in the above figure Node *createList(void) { int arr1[] = {10, 5, 12, 7, 11}; int arr2[] = {4, 20, 13}; int arr3[] = {17, 6}; int arr4[] = {9, 8}; int arr5[] = {19, 15}; int arr6[] = {2}; int arr7[] = {16}; int arr8[] = {3}; // Create 8 linked lists Node *head1 = createList(arr1, SIZE(arr1)); Node *head2 = createList(arr2, SIZE(arr2)); Node *head3 = createList(arr3, SIZE(arr3)); Node *head4 = createList(arr4, SIZE(arr4)); Node *head5 = createList(arr5, SIZE(arr5)); Node *head6 = createList(arr6, SIZE(arr6)); Node *head7 = createList(arr7, SIZE(arr7)); Node *head8 = createList(arr8, SIZE(arr8)); /* Modify child pointers to create the list shown above */ head1->child = head2; head1->next->next->next->child = head3; head3->child = head4; head4->child = head5; head2->next->child = head6; head2->next->next->child = head7; head7->child = head8; /* Return head pointer of first linked list. Note that all nodes are reachable from head1 */ return head1; } /* The main function that flattens a multilevel linked list */void flattenList(Node *head) { // Base case if (head == NULL) return; Node *tmp; /* Find tail node of first level linked list */ Node *tail = head; while (tail->next != NULL) tail = tail->next; // One by one traverse through // all nodes of first level // linked list till we reach // the tail node Node *cur = head; while (cur != tail) { // If current node has a child if (cur->child) { // Then append the child at the // end of current list tail->next = cur->child; // And update the tail to new // last node tmp = cur->child; while (tmp->next) tmp = tmp->next; tail = tmp; } // Change current node cur = cur->next; } } // Driver codeint main(void) { Node *head = NULL; head = createList(); flattenList(head); printList(head); return 0; } // This code is contributed by rathbhupendra",
"e": 29409,
"s": 25808,
"text": null
},
{
"code": null,
"e": 29417,
"s": 29409,
"text": "Output:"
},
{
"code": null,
"e": 29460,
"s": 29417,
"text": "10 5 12 7 11 4 20 13 17 6 2 16 9 8 3 19 15"
},
{
"code": null,
"e": 29601,
"s": 29460,
"text": "Time Complexity: Since every node is visited at most twice, the time complexity is O(n) where n is the number of nodes in given linked list."
},
{
"code": null,
"e": 29685,
"s": 29601,
"text": "Please refer complete article on Flatten a multilevel linked list for more details!"
},
{
"code": null,
"e": 29698,
"s": 29685,
"text": "Linked Lists"
},
{
"code": null,
"e": 29702,
"s": 29698,
"text": "C++"
},
{
"code": null,
"e": 29715,
"s": 29702,
"text": "C++ Programs"
},
{
"code": null,
"e": 29727,
"s": 29715,
"text": "Linked List"
},
{
"code": null,
"e": 29739,
"s": 29727,
"text": "Linked List"
},
{
"code": null,
"e": 29743,
"s": 29739,
"text": "CPP"
},
{
"code": null,
"e": 29841,
"s": 29743,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29850,
"s": 29841,
"text": "Comments"
},
{
"code": null,
"e": 29863,
"s": 29850,
"text": "Old Comments"
},
{
"code": null,
"e": 29891,
"s": 29863,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 29912,
"s": 29891,
"text": "Iterators in C++ STL"
},
{
"code": null,
"e": 29945,
"s": 29912,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 29965,
"s": 29945,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 29989,
"s": 29965,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 30024,
"s": 29989,
"text": "Header files in C/C++ and its uses"
},
{
"code": null,
"e": 30050,
"s": 30024,
"text": "C++ Program for QuickSort"
},
{
"code": null,
"e": 30109,
"s": 30050,
"text": "How to return multiple values from a function in C or C++?"
},
{
"code": null,
"e": 30139,
"s": 30109,
"text": "CSV file management using C++"
}
] |
Insert in Middle of Linked List | Practice | GeeksforGeeks
|
Given a linked list of size N and a key. The task is to insert the key in the middle of the linked list.
Example 1:
Input:
LinkedList = 1->2->4
key = 3
Output: 1 2 3 4
Explanation: The new element is inserted
after the current middle element in the
linked list.
Example 2:
Input:
LinkedList = 10->20->40->50
key = 30
Output: 10 20 30 40 50
Explanation: The new element is inserted
after the current middle element in the
linked list and Hence, the output is
10 20 30 40 50.
Your Task:
The task is to complete the function insertInMiddle() which takes head reference and element to be inserted as the arguments. The printing is done automatically by the driver code.
Expected Time Complexity : O(N)
Expected Auxilliary Space : O(1)
Constraints:
1 <= N <= 104
0
2019sushilkumarkori3 days ago
Node* insertInMiddle(Node* head, int x)
{
// Code here
Node* temp = head;
int n=0;
while(temp!=NULL){
n++;
temp = temp->next;
}
temp = head;
int i=1;
if(n%2 == 0){
while(temp!=NULL){
if (i==n/2){
Node* next = temp->next;
temp->next = new Node(x);
temp->next->next = next;
return head;
}
temp = temp->next;
i++;
}
}
else{
while(temp!=NULL){
if (i==(n/2)+1){
Node* next = temp->next;
temp->next = new Node(x);
temp->next->next = next;
return head;
}
temp = temp->next;
i++;
}
}
}
0
neelasatyasai935 days ago
#PYTHON
def insertInMid(head,node):
#code here
import math
temp=head
c=0
while temp!=None:
c+=1
temp=temp.next
if c%2==0:
index=c/2
else:
index=math.ceil(c/2)
c=1
temp=head
while c!=index:
c+=1
temp=temp.next
node.next=temp.next
temp.next=node
+1
shahabuddinbravo402 weeks ago
Node* insertInMiddle(Node* head, int x){ Node *ptr1=head,*ptr2=head->next; while(ptr2!=NULL && ptr2->next!=NULL ){ ptr2=ptr2->next->next; ptr1=ptr1->next; } Node *new_node=new Node(x); new_node->next=ptr1->next; ptr1->next=new_node; return head; // int count=0; // while(ptr1!=NULL){ // ptr1=ptr1->next; // count++; // } // int index=1; // while(true){ // if(index==ceil((float)count/2)){ // Node *new_node=new Node(x); // new_node->next=ptr2->next; // ptr2->next=new_node; // return head; // } // index++; // ptr2=ptr2->next; // } }
0
iamhunter4222 weeks ago
Node* insertInMiddle(Node* head, int x)
{
Node *t=head;
Node *data=new Node(x);
vector<Node *>a;
while(t!=NULL){
a.push_back(t);
t=t->next;
}
int s=a.size();
if(s%2==0){
Node* t=a[(s/2)-1];
data->next=t->next;
t->next=data;
}
else{
Node *t=a[(s/2)];
data->next=t->next;
t->next=data;
}
return head;
}
0
hharshit81183 weeks ago
Node* insertInMiddle(Node* head, int x){ if(!head){ return NULL; } Node *slow = head, *fast = head->next, *ptr = NULL; while(fast && fast->next){ slow = slow->next; fast = fast->next->next; } Node *temp = new Node(x); temp->next = slow->next; slow->next = temp; return head;}
+1
kumaramresh5943 weeks ago
Node* insertInMiddle(Node* head, int x){ Node *slow=head; Node *fast=head->next; while(fast!=NULL && fast->next!=NULL){ slow=slow->next; fast=fast->next->next; } Node *temp= new Node(x); temp->next=slow->next; slow->next=temp; return head; }
0
19bcs18694 weeks ago
public Node insertInMid(Node head, int data){ //Insert code here, return the head of modified linked list Node temp= new Node(data); if(head==null) return temp; Node slw=head,fst=head.next; while(fst!=null && fst.next!=null) { slw=slw.next; fst=fst.next.next; } temp.next=slw.next; slw.next=temp; return head; }
0
bhaskarkumarpro1 month ago
Node* insertInMiddle(Node* head, int x)
{
// Cpde here
Node *fast=head;
Node *slow=head;
while(fast->next and fast->next->next){
slow=slow->next;
fast=fast->next->next;
}
Node *temp=new Node(x);
temp->next=slow->next;
slow->next=temp;
return head;
}
0
siddiquerahil191 month ago
Node* insertInMiddle(Node* head, int x)
{
Node * temp = new Node(x);
Node * slow = head;
Node * fast = head ->next;
while(fast and fast->next){
slow = slow->next;
fast = fast->next->next;
}
temp->next = slow ->next;
slow->next= temp;
return head;
}
0
subhammahanty2351 month ago
C++ Code , easy to understand ;
int len(Node * head){ //function to get the length of linked list
Node* temp = head;
int c= 0;
while(temp->next!= NULL){
c++;
temp = temp->next;
}
return c;
}
Node* insertInMiddle(Node* head, int x)
{
int length = len(head);
int pos = length/2;
int i =0;
Node* temp = head;
while(i<pos){
temp= temp->next;
i++;
}
Node* new_node = new Node(x);
new_node->next = temp->next;
temp->next = new_node;
return head;
}
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
|
[
{
"code": null,
"e": 343,
"s": 238,
"text": "Given a linked list of size N and a key. The task is to insert the key in the middle of the linked list."
},
{
"code": null,
"e": 354,
"s": 343,
"text": "Example 1:"
},
{
"code": null,
"e": 500,
"s": 354,
"text": "Input:\nLinkedList = 1->2->4\nkey = 3\nOutput: 1 2 3 4\nExplanation: The new element is inserted\nafter the current middle element in the\nlinked list."
},
{
"code": null,
"e": 511,
"s": 500,
"text": "Example 2:"
},
{
"code": null,
"e": 712,
"s": 511,
"text": "Input:\nLinkedList = 10->20->40->50\nkey = 30\nOutput: 10 20 30 40 50\nExplanation: The new element is inserted\nafter the current middle element in the\nlinked list and Hence, the output is\n10 20 30 40 50."
},
{
"code": null,
"e": 906,
"s": 714,
"text": "Your Task:\nThe task is to complete the function insertInMiddle() which takes head reference and element to be inserted as the arguments. The printing is done automatically by the driver code."
},
{
"code": null,
"e": 971,
"s": 906,
"text": "Expected Time Complexity : O(N)\nExpected Auxilliary Space : O(1)"
},
{
"code": null,
"e": 998,
"s": 971,
"text": "Constraints:\n1 <= N <= 104"
},
{
"code": null,
"e": 1002,
"s": 1000,
"text": "0"
},
{
"code": null,
"e": 1032,
"s": 1002,
"text": "2019sushilkumarkori3 days ago"
},
{
"code": null,
"e": 1664,
"s": 1032,
"text": "Node* insertInMiddle(Node* head, int x)\n{\n\t// Code here\n\tNode* temp = head;\n\tint n=0;\n\twhile(temp!=NULL){\n\t n++;\n\t temp = temp->next;\n\t}\n\ttemp = head;\n\tint i=1;\n\tif(n%2 == 0){\n\t while(temp!=NULL){\n\t if (i==n/2){\n\t Node* next = temp->next;\n\t temp->next = new Node(x);\n\t temp->next->next = next;\n\t return head;\n\t }\n\t temp = temp->next;\n\t i++;\n\t }\n\t}\n\telse{\n\t while(temp!=NULL){\n\t if (i==(n/2)+1){\n\t Node* next = temp->next;\n\t temp->next = new Node(x);\n\t temp->next->next = next;\n\t return head;\n\t }\n\t temp = temp->next;\n\t i++;\n\t }\n\t}\n}"
},
{
"code": null,
"e": 1666,
"s": 1664,
"text": "0"
},
{
"code": null,
"e": 1692,
"s": 1666,
"text": "neelasatyasai935 days ago"
},
{
"code": null,
"e": 2019,
"s": 1692,
"text": "#PYTHON\ndef insertInMid(head,node):\n #code here\n import math\n temp=head\n c=0\n while temp!=None:\n c+=1\n temp=temp.next\n if c%2==0:\n index=c/2\n else:\n index=math.ceil(c/2) \n \n c=1\n temp=head\n while c!=index:\n c+=1\n temp=temp.next\n node.next=temp.next\n temp.next=node"
},
{
"code": null,
"e": 2022,
"s": 2019,
"text": "+1"
},
{
"code": null,
"e": 2052,
"s": 2022,
"text": "shahabuddinbravo402 weeks ago"
},
{
"code": null,
"e": 2753,
"s": 2052,
"text": "Node* insertInMiddle(Node* head, int x){ Node *ptr1=head,*ptr2=head->next; while(ptr2!=NULL && ptr2->next!=NULL ){ ptr2=ptr2->next->next; ptr1=ptr1->next; } Node *new_node=new Node(x); new_node->next=ptr1->next; ptr1->next=new_node; return head; // int count=0; // while(ptr1!=NULL){ // ptr1=ptr1->next; // count++; // } // int index=1; // while(true){ // if(index==ceil((float)count/2)){ // Node *new_node=new Node(x); // new_node->next=ptr2->next; // ptr2->next=new_node; // return head; // } // index++; // ptr2=ptr2->next; // } }"
},
{
"code": null,
"e": 2755,
"s": 2753,
"text": "0"
},
{
"code": null,
"e": 2779,
"s": 2755,
"text": "iamhunter4222 weeks ago"
},
{
"code": null,
"e": 3145,
"s": 2779,
"text": "Node* insertInMiddle(Node* head, int x)\n{\nNode *t=head;\nNode *data=new Node(x);\nvector<Node *>a;\nwhile(t!=NULL){\n a.push_back(t);\n t=t->next;\n \n \n}\nint s=a.size();\nif(s%2==0){\n Node* t=a[(s/2)-1];\n data->next=t->next;\n t->next=data;\n \n \n}\nelse{\n \n Node *t=a[(s/2)];\n data->next=t->next;\n t->next=data;\n \n}\nreturn head;\n\n\n\n}"
},
{
"code": null,
"e": 3147,
"s": 3145,
"text": "0"
},
{
"code": null,
"e": 3171,
"s": 3147,
"text": "hharshit81183 weeks ago"
},
{
"code": null,
"e": 3482,
"s": 3171,
"text": "Node* insertInMiddle(Node* head, int x){ if(!head){ return NULL; } Node *slow = head, *fast = head->next, *ptr = NULL; while(fast && fast->next){ slow = slow->next; fast = fast->next->next; } Node *temp = new Node(x); temp->next = slow->next; slow->next = temp; return head;}"
},
{
"code": null,
"e": 3485,
"s": 3482,
"text": "+1"
},
{
"code": null,
"e": 3511,
"s": 3485,
"text": "kumaramresh5943 weeks ago"
},
{
"code": null,
"e": 3798,
"s": 3511,
"text": "Node* insertInMiddle(Node* head, int x){ Node *slow=head; Node *fast=head->next; while(fast!=NULL && fast->next!=NULL){ slow=slow->next; fast=fast->next->next; } Node *temp= new Node(x); temp->next=slow->next; slow->next=temp; return head; }"
},
{
"code": null,
"e": 3800,
"s": 3798,
"text": "0"
},
{
"code": null,
"e": 3821,
"s": 3800,
"text": "19bcs18694 weeks ago"
},
{
"code": null,
"e": 4219,
"s": 3821,
"text": "public Node insertInMid(Node head, int data){ //Insert code here, return the head of modified linked list Node temp= new Node(data); if(head==null) return temp; Node slw=head,fst=head.next; while(fst!=null && fst.next!=null) { slw=slw.next; fst=fst.next.next; } temp.next=slw.next; slw.next=temp; return head; }"
},
{
"code": null,
"e": 4223,
"s": 4221,
"text": "0"
},
{
"code": null,
"e": 4250,
"s": 4223,
"text": "bhaskarkumarpro1 month ago"
},
{
"code": null,
"e": 4523,
"s": 4250,
"text": "Node* insertInMiddle(Node* head, int x)\n{\n\t// Cpde here\n\tNode *fast=head;\n\tNode *slow=head;\n\twhile(fast->next and fast->next->next){\n\t slow=slow->next;\n\t fast=fast->next->next;\n\t}\n\t\n\tNode *temp=new Node(x);\n\ttemp->next=slow->next;\n\tslow->next=temp;\n\treturn head;\n}"
},
{
"code": null,
"e": 4525,
"s": 4523,
"text": "0"
},
{
"code": null,
"e": 4552,
"s": 4525,
"text": "siddiquerahil191 month ago"
},
{
"code": null,
"e": 4875,
"s": 4552,
"text": "Node* insertInMiddle(Node* head, int x)\n{\n Node * temp = new Node(x);\n Node * slow = head;\n Node * fast = head ->next;\n \n while(fast and fast->next){\n slow = slow->next;\n fast = fast->next->next;\n \n }\n temp->next = slow ->next;\n slow->next= temp;\n return head;\n\t\n\t \n\t \n\t\n}"
},
{
"code": null,
"e": 4877,
"s": 4875,
"text": "0"
},
{
"code": null,
"e": 4905,
"s": 4877,
"text": "subhammahanty2351 month ago"
},
{
"code": null,
"e": 4937,
"s": 4905,
"text": "C++ Code , easy to understand ;"
},
{
"code": null,
"e": 5408,
"s": 4937,
"text": "int len(Node * head){ //function to get the length of linked list \n\n Node* temp = head;\n int c= 0;\n while(temp->next!= NULL){\n c++;\n temp = temp->next;\n }\n return c;\n}\nNode* insertInMiddle(Node* head, int x)\n{\n\tint length = len(head);\n\tint pos = length/2;\n\tint i =0;\n\tNode* temp = head;\n\twhile(i<pos){\n\t temp= temp->next;\n\t i++;\n\t}\n\tNode* new_node = new Node(x);\n\tnew_node->next = temp->next;\n\ttemp->next = new_node;\n\n\treturn head;\n}"
},
{
"code": null,
"e": 5554,
"s": 5408,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 5590,
"s": 5554,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 5600,
"s": 5590,
"text": "\nProblem\n"
},
{
"code": null,
"e": 5610,
"s": 5600,
"text": "\nContest\n"
},
{
"code": null,
"e": 5673,
"s": 5610,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 5821,
"s": 5673,
"text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 6029,
"s": 5821,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints."
},
{
"code": null,
"e": 6135,
"s": 6029,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
What is Cross-Validation?. Testing your machine learning models... | by Mohammed Alhamid | Towards Data Science
|
Cross-Validation (CV) is one of the key topics around testing your learning models. Although the subject is widely known, I still find some misconceptions cover some of its aspects. When we train a model, we split the dataset into two main sets: training and testing. The training set represents all the examples that a model is learning from, while the testing set simulates the testing examples as in Figure 1.
CV provides the ability to estimate model performance on unseen data not used while training.
Data scientists rely on several reasons for using cross-validation during their building process of Machine Learning (ML) models. For instance, tuning the model hyperparameters, testing different properties of the overall datasets, and iterate the training process. Also, in cases where your training dataset is small, and the ability to split them into training, validation, and testing will significantly affect training accuracy. The following main points can summarize the reason we use a CV, but they overlap. Hence, the list is presented here in a simplified way:
One of the critical pillars of validating a learning model before putting them in production is making accurate predictions on unseen data. The unseen data is all types of data that a model has never learned before. Ideally, the testing data is supposed to flow directly to the model in many testing iterations. However, in reality, access to such data is limited or not yet available in a new environment.
The typical 80β20 rule of splitting data into training and testing can still be vulnerable to accidentally ending up in a perfect split that boosts the model accuracy while limiting it from performing the same in a real environment. Sometimes, the accuracy calculated this way is mostly a matter of luck! The 80β20 is not an actual rule per se, and you will find alternative ratios that range between 25~30% for testing and 70~75% for training.
Finding the best combination of model parameters is a common step to tune an algorithm toward learning the datasetβs hidden patterns. But, doing this step on a simple training-testing split is typically not recommended. The model performance is usually very sensitive to such parameters, and adjusting those based on a predefined dataset split should be avoided. It can cause the model to overfit and reduce its ability to generalize.
For parameter tuning and avoid model overfitting, you might find some recommendations around splitting the dataset into three partitions: training, testing, and validation. For instance, 70% of the data is used for training, 20% for validation, and the remaining 10% is used for testing. In cases where the actual dataset is small, we might need to invest in using the maximum amount of data to train the model. In other instances, splitting into such three partitions could create bias in the training process where some significant examples are kept in training or validation splits. Hence, CV can become handy to resolve this issue.
Sometimes the splits of training-testing data can be very tricky. The properties of the testing data are not similar to the properties of the training. Although randomness ensures that each sample can have the same chance to be selected in the testing set, the process of a single split can still bring instability when the experiment is repeated with a new division.
Cross-Validation has two main steps: splitting the data into subsets (called folds) and rotating the training and validation among them. The splitting technique commonly has the following properties:
Each fold has approximately the same size.
Data can be randomly selected in each fold or stratified.
All folds are used to train the model except one, which is used for validation. That validation fold should be rotated until all folds have become a validation fold once and only once.
Each example is recommended to be contained in one and only one fold.
K-fold and CV are two terms that are used interchangeably. K-fold is just describing how many folds you want to split your dataset into. Many libraries use k=10 as a default value representing 90% going to training and 10% going to the validation set. The next figure describes the process of iterating over the picked ten folds of the dataset.
Figure 2 shows how one fold in each step iteratively is held out for testing while the remaining folds are used to build the model. Each step calculates the prediction error. Upon the completion of the final step, a list of computed error are produced of which we can take the mean.
Figure 3 shows the change in the training and validation setsβ size when using different values for k. The training set size increases whenever we increase the number of folds while the validation set decreases. Typically, the smaller the validation set, the likelihood that the randomness rises with a high noise variation. Increasing the training set size will increase such randomness and bring more reliable performance metrics.
One of the advantages of CV is observing the model predictions against all the instances in the dataset. It ensures that the model has been tested on the full data without testing them simultaneously. Variations are expected in each step of the validation; therefore, computing the mean and standard deviation can reduce the information into a few comparing values.
There are other techniques on how to implement cross-validation. Letβs jump into some of those:
LOOCV is the an exhaustive holdout splitting approach that k-fold enhances. It has one additional step of building k models tested with each example. This approach is quite expensive and requires each holdout example to be tested using a model. It also might increase the overall error rate and becomes computationally costly if the dataset size is large. Usually, it is recommended when the dataset size is small. Figure 4 demonstrates the overall process of a simple dataset containing ten examples.
It is another exhaustive technique for performing CV. We can define in each iteration how many examples shall be used for testing the model and how many shall be left for training. The process is repeated for all possible combinations of pairs in the dataset. Note that LOOCV is a LOPCV technique where p =1.
Letβs refresh our minds on how to split the data using the Sklearn library. The following code divides the dataset into two splits: training and testing. We defined here that 1/3 of the dataset should be used for testing.
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=1)
We will then build a function to show how k-fold works compared to the single split in the previous code.
def k_Fold_Split(data, n_splits, shuffle, random_state, verbose=False): # Creating k-fold splitting kfold = KFold(n_splits, shuffle, random_state) sizes = [0 , 0] for train, test in kfold.split(data): if verbose: print('train: indexes %s, val: indexes %s, size (training) %d, (val) %d' % (train, test, train.shape[0], test.shape[0])) sizes[0] += train.shape[0] sizes[1] += test.shape[0] return int(sizes[0]/n_splits), int(sizes[1]/n_splits)
The `k_fold_split` function shows the indexes and the size of each partition. It enables you to track how much data is dedicated for each fold and the chosen indexes.
Using LOOCV as a splitting strategy is pretty straight forward. We will use again Sklearn library to perform the cross-validation.
from sklearn.model_selection import LeaveOneOutcv_strategy = LeaveOneOut()# cross_val_score will evaluate the model scores = cross_val_score(estimator, X, y, scoring='accuracy', cv=cv_strategy, n_jobs=-1)
Cross-validation is a great way to ensure the training dataset does not have an implicit type of ordering. However, some cases require the order to be preserved, such as time-series use cases. We can still use cross-validation for time-series datasets using some other technique such as time-based folds.
Dealing with cross-validation in an unbalanced dataset can be tricky as well. If oversampling is used, the leaking of the oversampled examples can mislead the CV results. One way to consider is the use of stratified sampling instead of splitting randomly. Here is a fantastic blog article discussing how to handle this situation.
CV measures the generalization of the model, but it cannot avoid bias altogether. Nested cross-validation focuses on ensuring the modelβs hyperparameters are not overfitting the dataset. The nested keyword comes to hint at the use of double cross-validation on each fold. The hyperparameter tuning validation is achieved using another k-fold splits on the folds used to train the model.
As mentioned earlier, CV is used to measure if a learning model can generalize on unseen data. We rely on using a validation dataset for early stopping and parameter tuning different from the testing set during the building of models. There are a couple of research papers recently suggesting the use of CV to measure overfitting as well. In this case, the direct application would be the use of CV as a validation set for a learning model.
Cross-validation is a procedure to evaluate the performance of learning models. Datasets are typically split in a random or stratified strategy. The splitting technique can be varied and chosen based on the dataβs size and the ultimate objective. Also, the computational cost plays a role in implementing the CV technique. Regression and classification problems can use CV, but careful consideration must be paid for some types of datasets such as time-series. A complete example of the code can be found on my Github.
|
[
{
"code": null,
"e": 460,
"s": 47,
"text": "Cross-Validation (CV) is one of the key topics around testing your learning models. Although the subject is widely known, I still find some misconceptions cover some of its aspects. When we train a model, we split the dataset into two main sets: training and testing. The training set represents all the examples that a model is learning from, while the testing set simulates the testing examples as in Figure 1."
},
{
"code": null,
"e": 554,
"s": 460,
"text": "CV provides the ability to estimate model performance on unseen data not used while training."
},
{
"code": null,
"e": 1124,
"s": 554,
"text": "Data scientists rely on several reasons for using cross-validation during their building process of Machine Learning (ML) models. For instance, tuning the model hyperparameters, testing different properties of the overall datasets, and iterate the training process. Also, in cases where your training dataset is small, and the ability to split them into training, validation, and testing will significantly affect training accuracy. The following main points can summarize the reason we use a CV, but they overlap. Hence, the list is presented here in a simplified way:"
},
{
"code": null,
"e": 1531,
"s": 1124,
"text": "One of the critical pillars of validating a learning model before putting them in production is making accurate predictions on unseen data. The unseen data is all types of data that a model has never learned before. Ideally, the testing data is supposed to flow directly to the model in many testing iterations. However, in reality, access to such data is limited or not yet available in a new environment."
},
{
"code": null,
"e": 1976,
"s": 1531,
"text": "The typical 80β20 rule of splitting data into training and testing can still be vulnerable to accidentally ending up in a perfect split that boosts the model accuracy while limiting it from performing the same in a real environment. Sometimes, the accuracy calculated this way is mostly a matter of luck! The 80β20 is not an actual rule per se, and you will find alternative ratios that range between 25~30% for testing and 70~75% for training."
},
{
"code": null,
"e": 2411,
"s": 1976,
"text": "Finding the best combination of model parameters is a common step to tune an algorithm toward learning the datasetβs hidden patterns. But, doing this step on a simple training-testing split is typically not recommended. The model performance is usually very sensitive to such parameters, and adjusting those based on a predefined dataset split should be avoided. It can cause the model to overfit and reduce its ability to generalize."
},
{
"code": null,
"e": 3047,
"s": 2411,
"text": "For parameter tuning and avoid model overfitting, you might find some recommendations around splitting the dataset into three partitions: training, testing, and validation. For instance, 70% of the data is used for training, 20% for validation, and the remaining 10% is used for testing. In cases where the actual dataset is small, we might need to invest in using the maximum amount of data to train the model. In other instances, splitting into such three partitions could create bias in the training process where some significant examples are kept in training or validation splits. Hence, CV can become handy to resolve this issue."
},
{
"code": null,
"e": 3415,
"s": 3047,
"text": "Sometimes the splits of training-testing data can be very tricky. The properties of the testing data are not similar to the properties of the training. Although randomness ensures that each sample can have the same chance to be selected in the testing set, the process of a single split can still bring instability when the experiment is repeated with a new division."
},
{
"code": null,
"e": 3615,
"s": 3415,
"text": "Cross-Validation has two main steps: splitting the data into subsets (called folds) and rotating the training and validation among them. The splitting technique commonly has the following properties:"
},
{
"code": null,
"e": 3658,
"s": 3615,
"text": "Each fold has approximately the same size."
},
{
"code": null,
"e": 3716,
"s": 3658,
"text": "Data can be randomly selected in each fold or stratified."
},
{
"code": null,
"e": 3901,
"s": 3716,
"text": "All folds are used to train the model except one, which is used for validation. That validation fold should be rotated until all folds have become a validation fold once and only once."
},
{
"code": null,
"e": 3971,
"s": 3901,
"text": "Each example is recommended to be contained in one and only one fold."
},
{
"code": null,
"e": 4316,
"s": 3971,
"text": "K-fold and CV are two terms that are used interchangeably. K-fold is just describing how many folds you want to split your dataset into. Many libraries use k=10 as a default value representing 90% going to training and 10% going to the validation set. The next figure describes the process of iterating over the picked ten folds of the dataset."
},
{
"code": null,
"e": 4599,
"s": 4316,
"text": "Figure 2 shows how one fold in each step iteratively is held out for testing while the remaining folds are used to build the model. Each step calculates the prediction error. Upon the completion of the final step, a list of computed error are produced of which we can take the mean."
},
{
"code": null,
"e": 5032,
"s": 4599,
"text": "Figure 3 shows the change in the training and validation setsβ size when using different values for k. The training set size increases whenever we increase the number of folds while the validation set decreases. Typically, the smaller the validation set, the likelihood that the randomness rises with a high noise variation. Increasing the training set size will increase such randomness and bring more reliable performance metrics."
},
{
"code": null,
"e": 5398,
"s": 5032,
"text": "One of the advantages of CV is observing the model predictions against all the instances in the dataset. It ensures that the model has been tested on the full data without testing them simultaneously. Variations are expected in each step of the validation; therefore, computing the mean and standard deviation can reduce the information into a few comparing values."
},
{
"code": null,
"e": 5494,
"s": 5398,
"text": "There are other techniques on how to implement cross-validation. Letβs jump into some of those:"
},
{
"code": null,
"e": 5996,
"s": 5494,
"text": "LOOCV is the an exhaustive holdout splitting approach that k-fold enhances. It has one additional step of building k models tested with each example. This approach is quite expensive and requires each holdout example to be tested using a model. It also might increase the overall error rate and becomes computationally costly if the dataset size is large. Usually, it is recommended when the dataset size is small. Figure 4 demonstrates the overall process of a simple dataset containing ten examples."
},
{
"code": null,
"e": 6305,
"s": 5996,
"text": "It is another exhaustive technique for performing CV. We can define in each iteration how many examples shall be used for testing the model and how many shall be left for training. The process is repeated for all possible combinations of pairs in the dataset. Note that LOOCV is a LOPCV technique where p =1."
},
{
"code": null,
"e": 6527,
"s": 6305,
"text": "Letβs refresh our minds on how to split the data using the Sklearn library. The following code divides the dataset into two splits: training and testing. We defined here that 1/3 of the dataset should be used for testing."
},
{
"code": null,
"e": 6617,
"s": 6527,
"text": "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=1)"
},
{
"code": null,
"e": 6723,
"s": 6617,
"text": "We will then build a function to show how k-fold works compared to the single split in the previous code."
},
{
"code": null,
"e": 7220,
"s": 6723,
"text": "def k_Fold_Split(data, n_splits, shuffle, random_state, verbose=False): # Creating k-fold splitting kfold = KFold(n_splits, shuffle, random_state) sizes = [0 , 0] for train, test in kfold.split(data): if verbose: print('train: indexes %s, val: indexes %s, size (training) %d, (val) %d' % (train, test, train.shape[0], test.shape[0])) sizes[0] += train.shape[0] sizes[1] += test.shape[0] return int(sizes[0]/n_splits), int(sizes[1]/n_splits)"
},
{
"code": null,
"e": 7387,
"s": 7220,
"text": "The `k_fold_split` function shows the indexes and the size of each partition. It enables you to track how much data is dedicated for each fold and the chosen indexes."
},
{
"code": null,
"e": 7518,
"s": 7387,
"text": "Using LOOCV as a splitting strategy is pretty straight forward. We will use again Sklearn library to perform the cross-validation."
},
{
"code": null,
"e": 7723,
"s": 7518,
"text": "from sklearn.model_selection import LeaveOneOutcv_strategy = LeaveOneOut()# cross_val_score will evaluate the model scores = cross_val_score(estimator, X, y, scoring='accuracy', cv=cv_strategy, n_jobs=-1)"
},
{
"code": null,
"e": 8028,
"s": 7723,
"text": "Cross-validation is a great way to ensure the training dataset does not have an implicit type of ordering. However, some cases require the order to be preserved, such as time-series use cases. We can still use cross-validation for time-series datasets using some other technique such as time-based folds."
},
{
"code": null,
"e": 8358,
"s": 8028,
"text": "Dealing with cross-validation in an unbalanced dataset can be tricky as well. If oversampling is used, the leaking of the oversampled examples can mislead the CV results. One way to consider is the use of stratified sampling instead of splitting randomly. Here is a fantastic blog article discussing how to handle this situation."
},
{
"code": null,
"e": 8745,
"s": 8358,
"text": "CV measures the generalization of the model, but it cannot avoid bias altogether. Nested cross-validation focuses on ensuring the modelβs hyperparameters are not overfitting the dataset. The nested keyword comes to hint at the use of double cross-validation on each fold. The hyperparameter tuning validation is achieved using another k-fold splits on the folds used to train the model."
},
{
"code": null,
"e": 9186,
"s": 8745,
"text": "As mentioned earlier, CV is used to measure if a learning model can generalize on unseen data. We rely on using a validation dataset for early stopping and parameter tuning different from the testing set during the building of models. There are a couple of research papers recently suggesting the use of CV to measure overfitting as well. In this case, the direct application would be the use of CV as a validation set for a learning model."
}
] |
Bootstrap 4 .justify-content-*-around class
|
Use the justify-content-*-around class in Bootstrap to align flex items around on different screen sizes β
justify-content-sm-around : Justify content on small screen size
justify-content-md-around : Justify content on medium screen size
justify-content-lg-around : Justify content on large screen size
For an example, let us see how to align flex items for medium screen device (justify-content-md-around) β
<div class="d-flex justify-content-md-around bg-warning mb-5">
<div class="p-2 bg-danger">RANK 1</div>
<div class="p-2 bg-info">RANK 2</div>
<div class="p-2 bg-secondary">RANK 3</div>
</div>
You can try to run the following code to implement the justify-content-* β
Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container mt-3">
<div class="d-flex justify-content-around bg-warning mb-5">
<div class="p-2 bg-danger">RANK 1</div>
<div class="p-2 bg-info">RANK 2</div>
<div class="p-2 bg-secondary">RANK 3</div>
</div>
<div class="d-flex justify-content-sm-around bg-warning mb-5">
<div class="p-2 bg-danger">RANK 1</div>
<div class="p-2 bg-info">RANK 2</div>
<div class="p-2 bg-secondary">RANK 3</div>
</div>
<div class="d-flex justify-content-md-around bg-warning mb-5">
<div class="p-2 bg-danger">RANK 1</div>
<div class="p-2 bg-info">RANK 2</div>
<div class="p-2 bg-secondary">RANK 3</div>
</div>
<div class="d-flex justify-content-lg-around bg-warning mb-5">
<div class="p-2 bg-danger">RANK 1</div>
<div class="p-2 bg-info">RANK 2</div>
<div class="p-2 bg-secondary">RANK 3</div>
</div>
</div>
</body>
</html>
|
[
{
"code": null,
"e": 1169,
"s": 1062,
"text": "Use the justify-content-*-around class in Bootstrap to align flex items around on different screen sizes β"
},
{
"code": null,
"e": 1365,
"s": 1169,
"text": "justify-content-sm-around : Justify content on small screen size\njustify-content-md-around : Justify content on medium screen size\njustify-content-lg-around : Justify content on large screen size"
},
{
"code": null,
"e": 1471,
"s": 1365,
"text": "For an example, let us see how to align flex items for medium screen device (justify-content-md-around) β"
},
{
"code": null,
"e": 1668,
"s": 1471,
"text": "<div class=\"d-flex justify-content-md-around bg-warning mb-5\">\n <div class=\"p-2 bg-danger\">RANK 1</div>\n <div class=\"p-2 bg-info\">RANK 2</div>\n <div class=\"p-2 bg-secondary\">RANK 3</div>\n</div>"
},
{
"code": null,
"e": 1743,
"s": 1668,
"text": "You can try to run the following code to implement the justify-content-* β"
},
{
"code": null,
"e": 1753,
"s": 1743,
"text": "Live Demo"
},
{
"code": null,
"e": 3167,
"s": 1753,
"text": "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <title>Bootstrap Example</title>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css\">\n <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js\"></script>\n </head>\n\n<body>\n\n <div class=\"container mt-3\">\n <div class=\"d-flex justify-content-around bg-warning mb-5\">\n <div class=\"p-2 bg-danger\">RANK 1</div>\n <div class=\"p-2 bg-info\">RANK 2</div>\n <div class=\"p-2 bg-secondary\">RANK 3</div>\n </div>\n <div class=\"d-flex justify-content-sm-around bg-warning mb-5\">\n <div class=\"p-2 bg-danger\">RANK 1</div>\n <div class=\"p-2 bg-info\">RANK 2</div>\n <div class=\"p-2 bg-secondary\">RANK 3</div>\n </div>\n <div class=\"d-flex justify-content-md-around bg-warning mb-5\">\n <div class=\"p-2 bg-danger\">RANK 1</div>\n <div class=\"p-2 bg-info\">RANK 2</div>\n <div class=\"p-2 bg-secondary\">RANK 3</div>\n </div>\n <div class=\"d-flex justify-content-lg-around bg-warning mb-5\">\n <div class=\"p-2 bg-danger\">RANK 1</div>\n <div class=\"p-2 bg-info\">RANK 2</div>\n <div class=\"p-2 bg-secondary\">RANK 3</div>\n </div>\n </div>\n\n</body>\n</html>"
}
] |
Calendar in Python Program
|
Python has a built-in module called calendar to work with calendars. We are going to learn about the calendar module in this article.
The week in the calendar modules starts on Monday and ends on Sunday. The module calendar follows the Gregorian calendar. Let's see some useful methods of the calendar module.
If you have to get the calendar of the specific year, then create the instance of the class calendar.calendar(year) and print it. Let's see one example.
Live Demo
# importing the calendar module
import calendar
# initializing the year
year = 2019
# printing the calendar
print(calendar.calendar(2019))
If you run the above code, you will get the following results.
We can get different types of outputs using the calendar.calendar(year) instance. Try to learn those methods using the dir().
If you have to get the calendar of the specific month, then use the method calendar.month(year, month_number) and print it. Let's see one example.
Live Demo
# importing the calendar module
import calendar
# initializing the yearn and month number
year = 2000
month = 1
# getting the calendar of the month
print(calendar.month(year, month))
If you run the above program, you will get the following results.
January 2000
Mo Tu We Th Fr Sa Su
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
If you are having any trouble following the tutorial, comment below.
|
[
{
"code": null,
"e": 1196,
"s": 1062,
"text": "Python has a built-in module called calendar to work with calendars. We are going to learn about the calendar module in this article."
},
{
"code": null,
"e": 1372,
"s": 1196,
"text": "The week in the calendar modules starts on Monday and ends on Sunday. The module calendar follows the Gregorian calendar. Let's see some useful methods of the calendar module."
},
{
"code": null,
"e": 1525,
"s": 1372,
"text": "If you have to get the calendar of the specific year, then create the instance of the class calendar.calendar(year) and print it. Let's see one example."
},
{
"code": null,
"e": 1536,
"s": 1525,
"text": " Live Demo"
},
{
"code": null,
"e": 1675,
"s": 1536,
"text": "# importing the calendar module\nimport calendar\n# initializing the year\nyear = 2019\n# printing the calendar\nprint(calendar.calendar(2019))"
},
{
"code": null,
"e": 1738,
"s": 1675,
"text": "If you run the above code, you will get the following results."
},
{
"code": null,
"e": 1864,
"s": 1738,
"text": "We can get different types of outputs using the calendar.calendar(year) instance. Try to learn those methods using the dir()."
},
{
"code": null,
"e": 2011,
"s": 1864,
"text": "If you have to get the calendar of the specific month, then use the method calendar.month(year, month_number) and print it. Let's see one example."
},
{
"code": null,
"e": 2022,
"s": 2011,
"text": " Live Demo"
},
{
"code": null,
"e": 2205,
"s": 2022,
"text": "# importing the calendar module\nimport calendar\n# initializing the yearn and month number\nyear = 2000\nmonth = 1\n# getting the calendar of the month\nprint(calendar.month(year, month))"
},
{
"code": null,
"e": 2271,
"s": 2205,
"text": "If you run the above program, you will get the following results."
},
{
"code": null,
"e": 2413,
"s": 2271,
"text": "January 2000\nMo Tu We Th Fr Sa Su\n 1 2\n 3 4 5 6 7 8 9\n10 11 12 13 14 15 16\n17 18 19 20 21 22 23\n24 25 26 27 28 29 30\n31"
},
{
"code": null,
"e": 2482,
"s": 2413,
"text": "If you are having any trouble following the tutorial, comment below."
}
] |
Multi-selection of Checkboxes on button click in jQuery?
|
For this, use jQuery() with id property. Following is the code β
Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
<title>Document</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fontawesome/4.7.0/css/font-awesome.min.css">
<style>
.changeColor {
color: red
};
</style>
</head>
<body>
<input type="button" id="selectDemo" value="Want To Select All
Values" />
<table>
<tr>
<td>
<input type="checkbox" id="CheckBoxId1"
class="isSelected" /> Javascript
</td>
</tr>
<tr>
<td>
<input type="checkbox" id="CheckBoxId2"
class="isSelected" /> MySQL
</td>
</tr>
<tr>
<td>
<input type="checkbox" id="CheckBoxId3"
class="isSelected" /> MongoDB
</td>
</tr>
<tr>
<td>
<input type="checkbox" id="CheckBoxId4"
class="isSelected" /> Python
</td>
</tr>
</table>
<script>
jQuery("#selectDemo").click(function () {
jQuery(this).toggleClass("changeColor");
if (jQuery(this).hasClass("changeColor")) {
jQuery(".isSelected").prop("checked", true);
jQuery(this).val("Want To UnSelect All Values");
} else {
jQuery(this).removeClass("changeColor");
jQuery(".isSelected").prop("checked", false);
jQuery(this).val("Want To Select All Values");
}
});
</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 β
Now I am going to click the above button βWant To Select All Valuesβ β
Click the above button βWant To UnSelect All Valuesβ β
|
[
{
"code": null,
"e": 1127,
"s": 1062,
"text": "For this, use jQuery() with id property. Following is the code β"
},
{
"code": null,
"e": 1138,
"s": 1127,
"text": " Live Demo"
},
{
"code": null,
"e": 2641,
"s": 1138,
"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<link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/fontawesome/4.7.0/css/font-awesome.min.css\">\n<style>\n .changeColor {\n color: red\n };\n</style>\n</head>\n<body>\n<input type=\"button\" id=\"selectDemo\" value=\"Want To Select All\nValues\" />\n<table>\n<tr>\n<td>\n<input type=\"checkbox\" id=\"CheckBoxId1\"\nclass=\"isSelected\" /> Javascript\n</td>\n</tr>\n<tr>\n<td>\n<input type=\"checkbox\" id=\"CheckBoxId2\"\nclass=\"isSelected\" /> MySQL\n</td>\n</tr>\n<tr>\n<td>\n<input type=\"checkbox\" id=\"CheckBoxId3\"\nclass=\"isSelected\" /> MongoDB\n</td>\n</tr>\n<tr>\n<td>\n<input type=\"checkbox\" id=\"CheckBoxId4\"\nclass=\"isSelected\" /> Python\n</td>\n</tr>\n</table>\n<script>\n jQuery(\"#selectDemo\").click(function () {\n jQuery(this).toggleClass(\"changeColor\");\n if (jQuery(this).hasClass(\"changeColor\")) {\n jQuery(\".isSelected\").prop(\"checked\", true);\n jQuery(this).val(\"Want To UnSelect All Values\");\n } else {\n jQuery(this).removeClass(\"changeColor\");\n jQuery(\".isSelected\").prop(\"checked\", false);\n jQuery(this).val(\"Want To Select All Values\");\n }\n });\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 2803,
"s": 2641,
"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": 2844,
"s": 2803,
"text": "This will produce the following output β"
},
{
"code": null,
"e": 2915,
"s": 2844,
"text": "Now I am going to click the above button βWant To Select All Valuesβ β"
},
{
"code": null,
"e": 2970,
"s": 2915,
"text": "Click the above button βWant To UnSelect All Valuesβ β"
}
] |
How to rearrange MySQL columns?
|
To rearrange the MySQL columns, check the column arrangement with the help of show create command. The syntax is as follows β
show create table yourTableName;
The syntax to rearrange the MySQL columns is as follows β
alter table yourTableName change column yourColumnName yourColumnName dataType first
For the same purpose, you can use the after keyword. The syntax is as follows β
alter table yourTableName change column yourColumnName yourColumnName dataType after yourSpecificColumnName;
Let us first check the column arrangement for the already created table βAddColumnβ β
mysql> show create table AddColumn;
The following is the output β
+-----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table | Create Table |
+-----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| AddColumn | CREATE TABLE `addcolumn` (`StudentId` varchar(50) DEFAULT NULL, `StudentName` varchar(300) DEFAULT NULL ) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci|
+-----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)
Now you can rearrange the StudentName column before StudentId. The query is as follows β
mysql> alter table AddColumn change StudentName StudentName varchar(300) first;
Query OK, 0 rows affected (1.28 sec)
Records: 0 Duplicates: 0 Warnings: 0
Here is the query that can be used to check the StudentName is first column or not β
mysql> desc AddColumn;
The following is the output displaying that the columns are successfully rearranged β
+-------------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------------+--------------+------+-----+---------+-------+
| StudentName | varchar(300) | YES | | NULL | |
| StudentId | varchar(50) | YES | | NULL | |
+-------------+--------------+------+-----+---------+-------+
2 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1188,
"s": 1062,
"text": "To rearrange the MySQL columns, check the column arrangement with the help of show create command. The syntax is as follows β"
},
{
"code": null,
"e": 1221,
"s": 1188,
"text": "show create table yourTableName;"
},
{
"code": null,
"e": 1279,
"s": 1221,
"text": "The syntax to rearrange the MySQL columns is as follows β"
},
{
"code": null,
"e": 1364,
"s": 1279,
"text": "alter table yourTableName change column yourColumnName yourColumnName dataType first"
},
{
"code": null,
"e": 1444,
"s": 1364,
"text": "For the same purpose, you can use the after keyword. The syntax is as follows β"
},
{
"code": null,
"e": 1553,
"s": 1444,
"text": "alter table yourTableName change column yourColumnName yourColumnName dataType after yourSpecificColumnName;"
},
{
"code": null,
"e": 1639,
"s": 1553,
"text": "Let us first check the column arrangement for the already created table βAddColumnβ β"
},
{
"code": null,
"e": 1675,
"s": 1639,
"text": "mysql> show create table AddColumn;"
},
{
"code": null,
"e": 1705,
"s": 1675,
"text": "The following is the output β"
},
{
"code": null,
"e": 2689,
"s": 1705,
"text": "+-----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+\n| Table | Create Table |\n+-----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+\n| AddColumn | CREATE TABLE `addcolumn` (`StudentId` varchar(50) DEFAULT NULL, `StudentName` varchar(300) DEFAULT NULL ) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci|\n+-----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 2778,
"s": 2689,
"text": "Now you can rearrange the StudentName column before StudentId. The query is as follows β"
},
{
"code": null,
"e": 2932,
"s": 2778,
"text": "mysql> alter table AddColumn change StudentName StudentName varchar(300) first;\nQuery OK, 0 rows affected (1.28 sec)\nRecords: 0 Duplicates: 0 Warnings: 0"
},
{
"code": null,
"e": 3017,
"s": 2932,
"text": "Here is the query that can be used to check the StudentName is first column or not β"
},
{
"code": null,
"e": 3040,
"s": 3017,
"text": "mysql> desc AddColumn;"
},
{
"code": null,
"e": 3126,
"s": 3040,
"text": "The following is the output displaying that the columns are successfully rearranged β"
},
{
"code": null,
"e": 3523,
"s": 3126,
"text": "+-------------+--------------+------+-----+---------+-------+\n| Field | Type | Null | Key | Default | Extra |\n+-------------+--------------+------+-----+---------+-------+\n| StudentName | varchar(300) | YES | | NULL | |\n| StudentId | varchar(50) | YES | | NULL | |\n+-------------+--------------+------+-----+---------+-------+\n2 rows in set (0.00 sec)"
}
] |
Tryit Editor v3.7
|
Tryit: Responsive image
|
[] |
Count the number of times a Bulb switches its state - GeeksforGeeks
|
19 Oct, 2021
Given two arrays switch[], consisting of binary integers denoting whether a switch is ON(0) or OFF(1), and query[], where query[i] denotes the switch to be toggled. The task after completing all the switch toggles is to print the number of times the bulb changes its state, i.e. from ON to OFF or vice-versa.
Examples :
Input: switch[] ={1, 1, 0}, query[] = {3, 2, 1} Output : 1Explanation:Initial state of switches {1, 1, 0}. Since the count of 1βs = 2 (>= ceil(N / 2)), the bulb glows.query[0] = 3Next state of switches {1, 1, 1}. Since the count of 1βs = 3 (>= ceil(N / 2)), the bulb glows.query[1] = 2Next state of switches {1, 0, 1}. Since the count of 1βs = 2 (>= ceil(N / 2)), the bulb glows.query[2] = 1Next state of switches {0, 0, 1}.. Since the count of 1βs = 1 (< ceil(N / 2)), the bulb turns off.Therefore, the bulb witches from glowing to non-glowing state only once.
Input : switch[] = { 1, 1, 0, 0, 1, 1 } query[] = { 4, 3, 6 }Output: 0
Approach : Follow the steps below to solve the problem:
Traverse the array arr[].Count the number of 1s to keep track of the initial state of the bulb.Traverse the array query[].For every query[i], update arr[] and the count of 1s. Check for the current state of the bulb accordingly.If the previous and the current states are found to be different, then increment count.Finally, print the value of count.
Traverse the array arr[].
Count the number of 1s to keep track of the initial state of the bulb.
Traverse the array query[].
For every query[i], update arr[] and the count of 1s. Check for the current state of the bulb accordingly.
If the previous and the current states are found to be different, then increment count.
Finally, print the value of count.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the number of// times a bulb switches its stateint solve(int A[], int n, int Q[], int q){ // Count of 1s int one = 0; // Traverse the array for (int i = 0; i < n; i++) // Update count of 1s if (A[i] == 1) one++; // Update the status of bulb int glows = 0, count = 0; if (one >= ceil(n / 2)) glows = 1; // Traverse the array Q[] for (int i = 0; i < q; i++) { // Stores previous state // of the bulb int prev = glows; // Toggle the switch and // update count of 1s if (A[Q[i] - 1] == 1) one--; if (A[Q[i] - 1] == 0) one++; A[Q[i] - 1] ^= 1; if (one >= ceil(n / 2.0)) { glows = 1; } else { glows = 0; } // If the bulb switches state if (prev != glows) count++; } // Return count return count;} // Driver Codeint main(){ // Input int n = 3; int arr[] = { 1, 1, 0 }; int q = 3; // Queries int Q[] = { 3, 2, 1 }; // Function call to find number // of times the bulb toggles cout << solve(arr, n, Q, q); return 0;} // This code is contributed by splevel62.
// Java implementation of// the above approach import java.util.*;public class Main { // Function to find the number of // times a bulb switches its state static int solve(int[] A, int n, int Q[], int q) { // Count of 1s int one = 0; // Traverse the array for (int i = 0; i < n; i++) // Update count of 1s if (A[i] == 1) one++; // Update the status of bulb int glows = 0, count = 0; if (one >= (int)Math.ceil(n / 2)) glows = 1; // Traverse the array Q[] for (int i = 0; i < q; i++) { // Stores previous state // of the bulb int prev = glows; // Toggle the switch and // update count of 1s if (A[Q[i] - 1] == 1) one--; if (A[Q[i] - 1] == 0) one++; A[Q[i] - 1] ^= 1; if (one >= (int)Math.ceil(n / 2.0)) { glows = 1; } else { glows = 0; } // If the bulb switches state if (prev != glows) count++; } // Return count return count; } // Driver Code public static void main(String args[]) { // Input int n = 3; int arr[] = { 1, 1, 0 }; int q = 3; // Queries int Q[] = { 3, 2, 1 }; // Function call to find number // of times the bulb toggles System.out.println( solve(arr, n, Q, q)); }}
# Python program for# the above approachimport math # Function to find the number of# times a bulb switches its statedef solve(A, n, Q, q): # count of 1's one = 0 # Traverse the array for i in range(0, n): # update the array if (A[i] == 1): one += 1 # update the status of bulb glows = 0 count = 0 if (one >= int(math.ceil(n / 2))): glows = 1 # Traverse the array Q[] for i in range(0, q): # stores previous state of # the bulb prev = glows # Toggle the switch and # update the count of 1's if (A[Q[i] - 1] == 1): one -= 1 if (A[Q[i] - 1] == 0): one += 1 A[Q[i] - 1] ^= 1 if (one >= int(math.ceil(n/2.0))): glows = 1 else: glows = 0 # if the bulb switches state if (prev != glows): count += 1 # Return count return count # Driver code # Inputn = 3arr = [1, 1, 0]q = 3 # QueriesQ = [3, 2, 1] # Function call to find number# of times the bulb togglesprint(solve(arr, n, Q, q)) # This code id contributed by Virusbuddah
// C# program for the above approachusing System;class GFG{ // Function to find the number of // times a bulb switches its state static int solve(int[] A, int n, int[] Q, int q) { // Count of 1s int one = 0; // Traverse the array for (int i = 0; i < n; i++) // Update count of 1s if (A[i] == 1) one++; // Update the status of bulb int glows = 0, count = 0; if (one >= (int)Math.Ceiling((double)n / 2)) glows = 1; // Traverse the array Q[] for (int i = 0; i < q; i++) { // Stores previous state // of the bulb int prev = glows; // Toggle the switch and // update count of 1s if (A[Q[i] - 1] == 1) one--; if (A[Q[i] - 1] == 0) one++; A[Q[i] - 1] ^= 1; if (one >= (int)Math.Ceiling((double)n / 2.0)) { glows = 1; } else { glows = 0; } // If the bulb switches state if (prev != glows) count++; } // Return count return count; } // Driver Code static public void Main () { // Input int n = 3; int[] arr = { 1, 1, 0 }; int q = 3; // Queries int[] Q = { 3, 2, 1 }; // Function call to find number // of times the bulb toggles Console.WriteLine( solve(arr, n, Q, q)); }} // This code is contributed by susmitakundugoaldanga.
<script> // Javascript program for the above approach // Function to find the number of// times a bulb switches its statefunction solve(A, n, Q, q){ // Count of 1s var one = 0; // Traverse the array for (var i = 0; i < n; i++) // Update count of 1s if (A[i] == 1) one++; // Update the status of bulb var glows = 0, count = 0; if (one >= Math.ceil(n / 2)) glows = 1; // Traverse the array Q[] for (var i = 0; i < q; i++) { // Stores previous state // of the bulb var prev = glows; // Toggle the switch and // update count of 1s if (A[Q[i] - 1] == 1) one--; if (A[Q[i] - 1] == 0) one++; A[Q[i] - 1] ^= 1; if (one >= Math.ceil(n / 2.0)) { glows = 1; } else { glows = 0; } // If the bulb switches state if (prev != glows) count++; } // Return count return count;} // Driver Code// Inputvar n = 3;var arr = [1, 1, 0];var q = 3; // Queriesvar Q = [3, 2, 1]; // Function call to find number// of times the bulb togglesdocument.write( solve(arr, n, Q, q)); // This code is contributed by noob2000.</script>
1
Time Complexity: O(N)Auxiliary Space: O(1)
virusbuddha
susmitakundugoaldanga
splevel62
noob2000
ruhelaa48
frequency-counting
Arrays
Mathematical
Arrays
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Window Sliding Technique
Program to find sum of elements in a given array
Reversal algorithm for array rotation
Trapping Rain Water
Move all negative numbers to beginning and positive to end with constant extra space
Program for Fibonacci numbers
C++ Data Types
Write a program to print all permutations of a given string
Set in C++ Standard Template Library (STL)
Program to find GCD or HCF of two numbers
|
[
{
"code": null,
"e": 24822,
"s": 24794,
"text": "\n19 Oct, 2021"
},
{
"code": null,
"e": 25131,
"s": 24822,
"text": "Given two arrays switch[], consisting of binary integers denoting whether a switch is ON(0) or OFF(1), and query[], where query[i] denotes the switch to be toggled. The task after completing all the switch toggles is to print the number of times the bulb changes its state, i.e. from ON to OFF or vice-versa."
},
{
"code": null,
"e": 25143,
"s": 25131,
"text": " Examples :"
},
{
"code": null,
"e": 25705,
"s": 25143,
"text": "Input: switch[] ={1, 1, 0}, query[] = {3, 2, 1} Output : 1Explanation:Initial state of switches {1, 1, 0}. Since the count of 1βs = 2 (>= ceil(N / 2)), the bulb glows.query[0] = 3Next state of switches {1, 1, 1}. Since the count of 1βs = 3 (>= ceil(N / 2)), the bulb glows.query[1] = 2Next state of switches {1, 0, 1}. Since the count of 1βs = 2 (>= ceil(N / 2)), the bulb glows.query[2] = 1Next state of switches {0, 0, 1}.. Since the count of 1βs = 1 (< ceil(N / 2)), the bulb turns off.Therefore, the bulb witches from glowing to non-glowing state only once."
},
{
"code": null,
"e": 25788,
"s": 25705,
"text": "Input : switch[] = { 1, 1, 0, 0, 1, 1 } query[] = { 4, 3, 6 }Output: 0 "
},
{
"code": null,
"e": 25844,
"s": 25788,
"text": "Approach : Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 26194,
"s": 25844,
"text": "Traverse the array arr[].Count the number of 1s to keep track of the initial state of the bulb.Traverse the array query[].For every query[i], update arr[] and the count of 1s. Check for the current state of the bulb accordingly.If the previous and the current states are found to be different, then increment count.Finally, print the value of count."
},
{
"code": null,
"e": 26220,
"s": 26194,
"text": "Traverse the array arr[]."
},
{
"code": null,
"e": 26291,
"s": 26220,
"text": "Count the number of 1s to keep track of the initial state of the bulb."
},
{
"code": null,
"e": 26319,
"s": 26291,
"text": "Traverse the array query[]."
},
{
"code": null,
"e": 26426,
"s": 26319,
"text": "For every query[i], update arr[] and the count of 1s. Check for the current state of the bulb accordingly."
},
{
"code": null,
"e": 26514,
"s": 26426,
"text": "If the previous and the current states are found to be different, then increment count."
},
{
"code": null,
"e": 26549,
"s": 26514,
"text": "Finally, print the value of count."
},
{
"code": null,
"e": 26600,
"s": 26549,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 26604,
"s": 26600,
"text": "C++"
},
{
"code": null,
"e": 26609,
"s": 26604,
"text": "Java"
},
{
"code": null,
"e": 26617,
"s": 26609,
"text": "Python3"
},
{
"code": null,
"e": 26620,
"s": 26617,
"text": "C#"
},
{
"code": null,
"e": 26631,
"s": 26620,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the number of// times a bulb switches its stateint solve(int A[], int n, int Q[], int q){ // Count of 1s int one = 0; // Traverse the array for (int i = 0; i < n; i++) // Update count of 1s if (A[i] == 1) one++; // Update the status of bulb int glows = 0, count = 0; if (one >= ceil(n / 2)) glows = 1; // Traverse the array Q[] for (int i = 0; i < q; i++) { // Stores previous state // of the bulb int prev = glows; // Toggle the switch and // update count of 1s if (A[Q[i] - 1] == 1) one--; if (A[Q[i] - 1] == 0) one++; A[Q[i] - 1] ^= 1; if (one >= ceil(n / 2.0)) { glows = 1; } else { glows = 0; } // If the bulb switches state if (prev != glows) count++; } // Return count return count;} // Driver Codeint main(){ // Input int n = 3; int arr[] = { 1, 1, 0 }; int q = 3; // Queries int Q[] = { 3, 2, 1 }; // Function call to find number // of times the bulb toggles cout << solve(arr, n, Q, q); return 0;} // This code is contributed by splevel62.",
"e": 27815,
"s": 26631,
"text": null
},
{
"code": "// Java implementation of// the above approach import java.util.*;public class Main { // Function to find the number of // times a bulb switches its state static int solve(int[] A, int n, int Q[], int q) { // Count of 1s int one = 0; // Traverse the array for (int i = 0; i < n; i++) // Update count of 1s if (A[i] == 1) one++; // Update the status of bulb int glows = 0, count = 0; if (one >= (int)Math.ceil(n / 2)) glows = 1; // Traverse the array Q[] for (int i = 0; i < q; i++) { // Stores previous state // of the bulb int prev = glows; // Toggle the switch and // update count of 1s if (A[Q[i] - 1] == 1) one--; if (A[Q[i] - 1] == 0) one++; A[Q[i] - 1] ^= 1; if (one >= (int)Math.ceil(n / 2.0)) { glows = 1; } else { glows = 0; } // If the bulb switches state if (prev != glows) count++; } // Return count return count; } // Driver Code public static void main(String args[]) { // Input int n = 3; int arr[] = { 1, 1, 0 }; int q = 3; // Queries int Q[] = { 3, 2, 1 }; // Function call to find number // of times the bulb toggles System.out.println( solve(arr, n, Q, q)); }}",
"e": 29392,
"s": 27815,
"text": null
},
{
"code": "# Python program for# the above approachimport math # Function to find the number of# times a bulb switches its statedef solve(A, n, Q, q): # count of 1's one = 0 # Traverse the array for i in range(0, n): # update the array if (A[i] == 1): one += 1 # update the status of bulb glows = 0 count = 0 if (one >= int(math.ceil(n / 2))): glows = 1 # Traverse the array Q[] for i in range(0, q): # stores previous state of # the bulb prev = glows # Toggle the switch and # update the count of 1's if (A[Q[i] - 1] == 1): one -= 1 if (A[Q[i] - 1] == 0): one += 1 A[Q[i] - 1] ^= 1 if (one >= int(math.ceil(n/2.0))): glows = 1 else: glows = 0 # if the bulb switches state if (prev != glows): count += 1 # Return count return count # Driver code # Inputn = 3arr = [1, 1, 0]q = 3 # QueriesQ = [3, 2, 1] # Function call to find number# of times the bulb togglesprint(solve(arr, n, Q, q)) # This code id contributed by Virusbuddah",
"e": 30562,
"s": 29392,
"text": null
},
{
"code": "// C# program for the above approachusing System;class GFG{ // Function to find the number of // times a bulb switches its state static int solve(int[] A, int n, int[] Q, int q) { // Count of 1s int one = 0; // Traverse the array for (int i = 0; i < n; i++) // Update count of 1s if (A[i] == 1) one++; // Update the status of bulb int glows = 0, count = 0; if (one >= (int)Math.Ceiling((double)n / 2)) glows = 1; // Traverse the array Q[] for (int i = 0; i < q; i++) { // Stores previous state // of the bulb int prev = glows; // Toggle the switch and // update count of 1s if (A[Q[i] - 1] == 1) one--; if (A[Q[i] - 1] == 0) one++; A[Q[i] - 1] ^= 1; if (one >= (int)Math.Ceiling((double)n / 2.0)) { glows = 1; } else { glows = 0; } // If the bulb switches state if (prev != glows) count++; } // Return count return count; } // Driver Code static public void Main () { // Input int n = 3; int[] arr = { 1, 1, 0 }; int q = 3; // Queries int[] Q = { 3, 2, 1 }; // Function call to find number // of times the bulb toggles Console.WriteLine( solve(arr, n, Q, q)); }} // This code is contributed by susmitakundugoaldanga.",
"e": 31918,
"s": 30562,
"text": null
},
{
"code": "<script> // Javascript program for the above approach // Function to find the number of// times a bulb switches its statefunction solve(A, n, Q, q){ // Count of 1s var one = 0; // Traverse the array for (var i = 0; i < n; i++) // Update count of 1s if (A[i] == 1) one++; // Update the status of bulb var glows = 0, count = 0; if (one >= Math.ceil(n / 2)) glows = 1; // Traverse the array Q[] for (var i = 0; i < q; i++) { // Stores previous state // of the bulb var prev = glows; // Toggle the switch and // update count of 1s if (A[Q[i] - 1] == 1) one--; if (A[Q[i] - 1] == 0) one++; A[Q[i] - 1] ^= 1; if (one >= Math.ceil(n / 2.0)) { glows = 1; } else { glows = 0; } // If the bulb switches state if (prev != glows) count++; } // Return count return count;} // Driver Code// Inputvar n = 3;var arr = [1, 1, 0];var q = 3; // Queriesvar Q = [3, 2, 1]; // Function call to find number// of times the bulb togglesdocument.write( solve(arr, n, Q, q)); // This code is contributed by noob2000.</script>",
"e": 33024,
"s": 31918,
"text": null
},
{
"code": null,
"e": 33029,
"s": 33027,
"text": "1"
},
{
"code": null,
"e": 33075,
"s": 33031,
"text": "Time Complexity: O(N)Auxiliary Space: O(1) "
},
{
"code": null,
"e": 33087,
"s": 33075,
"text": "virusbuddha"
},
{
"code": null,
"e": 33109,
"s": 33087,
"text": "susmitakundugoaldanga"
},
{
"code": null,
"e": 33119,
"s": 33109,
"text": "splevel62"
},
{
"code": null,
"e": 33128,
"s": 33119,
"text": "noob2000"
},
{
"code": null,
"e": 33138,
"s": 33128,
"text": "ruhelaa48"
},
{
"code": null,
"e": 33157,
"s": 33138,
"text": "frequency-counting"
},
{
"code": null,
"e": 33164,
"s": 33157,
"text": "Arrays"
},
{
"code": null,
"e": 33177,
"s": 33164,
"text": "Mathematical"
},
{
"code": null,
"e": 33184,
"s": 33177,
"text": "Arrays"
},
{
"code": null,
"e": 33197,
"s": 33184,
"text": "Mathematical"
},
{
"code": null,
"e": 33295,
"s": 33197,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33304,
"s": 33295,
"text": "Comments"
},
{
"code": null,
"e": 33317,
"s": 33304,
"text": "Old Comments"
},
{
"code": null,
"e": 33342,
"s": 33317,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 33391,
"s": 33342,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 33429,
"s": 33391,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 33449,
"s": 33429,
"text": "Trapping Rain Water"
},
{
"code": null,
"e": 33534,
"s": 33449,
"text": "Move all negative numbers to beginning and positive to end with constant extra space"
},
{
"code": null,
"e": 33564,
"s": 33534,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 33579,
"s": 33564,
"text": "C++ Data Types"
},
{
"code": null,
"e": 33639,
"s": 33579,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 33682,
"s": 33639,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
Calculate the Sum of GCD over all subarrays - GeeksforGeeks
|
10 Jun, 2021
Given an array of integers, the task is to calculate the sum of GCD of all the subarrays of an array. GCD of an array is defined as the GCD of all the elements present in it. More formally, . Summation of all the GCDs can be defined as where denotes the subarray starting from ith index and ending at jth index.Examples:
Input 1: N = 5, A = {1,2,3,4,5} Output 1: 25Explanation: The subarrays of length one are [1], [2], [3], [4], [5] and the sum of their GCDs is 15, similarly subarrays of length 2, are [1, 2], [2, 3], [3, 4], [4, 5], and the sum of their GCDs is 4, similarly for length 3, the sum is 3, similarly for length 4, the sum is 2, similarly for length 5, the sum is 1. The total sum becomes 25.Input 2: N = 6, A = {2,2,2,3,5,5} Output 2: 41
Pre-Requisites Binary Search Segment Tree approach for calculating GCD in an index range Sparse Table for calculating GCD in an index range
Naive Approach (O(n^3) complexity)We can find out every subarray in O(n^2) complexity and can traverse it for finding the GCD of that subarray and add it to the total answer.Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to find// Sum of GCD over all subarrays. #include <bits/stdc++.h>using namespace std; // Utility function to calculate// sum of gcd of all sub-arrays. int findGCDSum(int n, int a[]){ int GCDSum = 0; int tempGCD = 0; for (int i = 0; i < n; i++) { // Fixing the starting index of a subarray for (int j = i; j < n; j++) { // Fixing the ending index of a subarray tempGCD = 0; for (int k = i; k <= j; k++) { // Finding the GCD of this subarray tempGCD = __gcd(tempGCD, a[k]); } // Adding this GCD in our sum GCDSum += tempGCD; } } return GCDSum;} // Driver Codeint main(){ int n = 5; int a[] = { 1, 2, 3, 4, 5 }; int totalSum = findGCDSum(n, a); cout << totalSum << "\n";}
// Java program to find// Sum of GCD over all subarrays.class GFG{ // Utility function to calculate// sum of gcd of all sub-arrays.static int findGCDSum(int n, int a[]){ int GCDSum = 0; int tempGCD = 0; for (int i = 0; i < n; i++) { // Fixing the starting index of a subarray for (int j = i; j < n; j++) { // Fixing the ending index of a subarray tempGCD = 0; for (int k = i; k <= j; k++) { // Finding the GCD of this subarray tempGCD = __gcd(tempGCD, a[k]); } // Adding this GCD in our sum GCDSum += tempGCD; } } return GCDSum;} static int __gcd(int a, int b){ return b == 0 ? a : __gcd(b, a % b); } // Driver Codepublic static void main(String[] args){ int n = 5; int a[] = { 1, 2, 3, 4, 5 }; int totalSum = findGCDSum(n, a); System.out.print(totalSum + "\n");}} // This code is contributed by 29AjayKumar
# Python3 program to find# Sum of GCD over all subarrays. # Utility function to calculate# sum of gcd of all sub-arrays.def findGCDSum(n, a): GCDSum = 0; tempGCD = 0; for i in range(n): # Fixing the starting index of a subarray for j in range(i, n): # Fixing the ending index of a subarray tempGCD = 0; for k in range(i, j + 1): # Finding the GCD of this subarray tempGCD = __gcd(tempGCD, a[k]); # Adding this GCD in our sum GCDSum += tempGCD; return GCDSum; def __gcd(a, b): return a if(b == 0 ) else __gcd(b, a % b); # Driver Codeif __name__ == '__main__': n = 5; a = [1, 2, 3, 4, 5]; totalSum = findGCDSum(n, a); print(totalSum); # This code is contributed by PrinciRaj1992
// C# program to find// Sum of GCD over all subarrays.using System; class GFG{ // Utility function to calculate// sum of gcd of all sub-arrays.static int findGCDSum(int n, int []a){ int GCDSum = 0; int tempGCD = 0; for (int i = 0; i < n; i++) { // Fixing the starting index of a subarray for (int j = i; j < n; j++) { // Fixing the ending index of a subarray tempGCD = 0; for (int k = i; k <= j; k++) { // Finding the GCD of this subarray tempGCD = __gcd(tempGCD, a[k]); } // Adding this GCD in our sum GCDSum += tempGCD; } } return GCDSum;} static int __gcd(int a, int b){ return b == 0 ? a : __gcd(b, a % b); } // Driver Codepublic static void Main(String[] args){ int n = 5; int []a = { 1, 2, 3, 4, 5 }; int totalSum = findGCDSum(n, a); Console.Write(totalSum + "\n");}} // This code is contributed by Rajput-Ji
<script>// javascript program to find// Sum of GCD over all subarrays. // Utility function to calculate // sum of gcd of all sub-arrays. function findGCDSum(n , a) { var GCDSum = 0; var tempGCD = 0; for (i = 0; i < n; i++) { // Fixing the starting index of a subarray for (j = i; j < n; j++) { // Fixing the ending index of a subarray tempGCD = 0; for (k = i; k <= j; k++) { // Finding the GCD of this subarray tempGCD = __gcd(tempGCD, a[k]); } // Adding this GCD in our sum GCDSum += tempGCD; } } return GCDSum; } function __gcd(a , b) { return b == 0 ? a : __gcd(b, a % b); } // Driver Code var n = 5; var a = [ 1, 2, 3, 4, 5 ]; var totalSum = findGCDSum(n, a); document.write(totalSum + "<br/>"); // This code is contributed by umadevi9616</script>
25
We can optimize the part where you calculate GCD of a subarray, We can use a segment tree or a sparse table to optimize the complexity to O(n^2 * logn) (for segment trees) or to O(n^2) (for sparse table)Efficient Approach (O(n*(logn)^2) complexity):This approach takes advantage of the observation that upon adding a new element to an array, the new GCD of the array will always be either less or equal to the previous GCD of the array before the addition of the element.We create three pointers, lets call them startPointer, endPointer and prevEndPointer. Initially all three of them point to the first element of our array. We initialize a variable tempGCD with the value of the first element. We will now find the sum of GCDs of all the subarrays starting with first element. Now according to our previous observation, if we move the endPointer to the right by one position, and calculate the GCD of these two elements which are pointed by startPointer and endPointer, it will always be less than or equal to tempGCD. So if we want to find out how many subarrays have the GCD as tempGCD, we need to find a suitable position of endPointer, where the subarray starting at startPointer and ending at endPointer will have the value of itβs GCD less than tempGCD, and the value of endPointer should be as minimal as possible, then the difference of prevEndPointer and endPointer will give us the number of subarrays which have their GCD as tempGCD. Now, we can add this value (tempGCD*(endPointer-prevEndPointer)), which denotes the sum of the GCD for these particular group of subarrays, into our variable finalAns which stores the sum of the GCD of all subarrays. Now the question remains, how will we find the suitable position of endPointer where the GCD decreases? Thatβs where Binary Search comes into use, we have the starting point of our array fixed, and we need to vary the ending point, letβs call them L and R, so for any R. We initialize high as N and low as prevEndPointer, and mid as (high+low)/2, now if we check the value of GCD[L, mid], we compare it to the value of tempGCD, and if it is less than it, then R might be a suitable position for endPointer, but it might be the case that some smaller value may become our answer, so we change high to be mid-1, and if GCD[L, mid] is found to be equal to tempGCD, then we should change low to be mid+1, and the value of mid+1 might be the answer, so we store the value of mid in a variable nextPos. At last we return the value of nextPos+1. Value of GCD[L, mid] can be efficiently calculated using a Segment Tree in O(logN) complexity or using a Sparse Table in O(1) complexity. This type of binary search finds us the suitable position of endPointer. After finding out this position, and adding to finalAns, we change prevEndPointer to endPointer, and tempGCD to GCD[startPointer, endPointer], and again start the process of finding next endPointer. This will stop once the value of endPointer becomes N, and then we need to move startPointer to the right, which will count the sum of GCD of all subarrays starting with second element. This will continue till the value of startPointer becomes N.Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to find Sum// of GCD over all subarrays #include <bits/stdc++.h>using namespace std; //int a[100001];int SparseTable[100001][51]; // Build Sparse Tablevoid buildSparseTable(int a[], int n){ for (int i = 0; i < n; i++) { SparseTable[i][0] = a[i]; } // Building the Sparse Table for GCD[L, R] Queries for (int j = 1; j <= 19; j++) { for (int i = 0; i <= n - (1 << j); i++) { SparseTable[i][j] = __gcd(SparseTable[i][j - 1], SparseTable[i + (1 << (j - 1))][j - 1]); } }} // Utility Function to calculate GCD in range [L,R]int queryForGCD(int L, int R){ int returnValue; // Calculating where the answer is // stored in our Sparse Table int j = int(log2(R - L + 1)); returnValue = __gcd(SparseTable[L][j], SparseTable[R - (1 << j) + 1][j]); return returnValue;} // Utility Function to find next-farther// position where gcd is sameint nextPosition(int tempGCD, int startPointer, int prevEndPointer, int n){ int high = n - 1; int low = prevEndPointer; int mid = prevEndPointer; int nextPos = prevEndPointer; // BinarySearch for Next Position // for EndPointer while (high >= low) { mid = ((high + low) >> 1); if (queryForGCD(startPointer, mid) == tempGCD) { nextPos = mid; low = mid + 1; } else { high = mid - 1; } } return nextPos + 1;} // Utility function to calculate// sum of gcdint calculateSum(int a[], int n){ buildSparseTable(a, n); int endPointer, startPointer, prevEndPointer, tempGCD; int tempAns = 0; for (int i = 0; i < n; i++) { // Initializing all the values endPointer = i; startPointer = i; prevEndPointer = i; tempGCD = a[i]; while (endPointer < n) { // Finding the next position for endPointer endPointer = nextPosition(tempGCD, startPointer, prevEndPointer, n); // Adding the suitable sum to our answer tempAns += ((endPointer - prevEndPointer) * tempGCD); // Changing prevEndPointer prevEndPointer = endPointer; if (endPointer < n) { // Recalculating tempGCD tempGCD = __gcd(tempGCD, a[endPointer]); } } } return tempAns;} // Driver Codeint main(){ int n = 6; int a[] = {2, 2, 2, 3, 5, 5}; cout << calculateSum(a, n) << "\n"; return 0;}
// Java program to find Sum// of GCD over all subarraysclass GFG{ //int a[100001];static int [][]SparseTable = new int[100001][51]; // Build Sparse Tablestatic void buildSparseTable(int a[], int n){ for (int i = 0; i < n; i++) { SparseTable[i][0] = a[i]; } // Building the Sparse Table // for GCD[L, R] Queries for (int j = 1; j <= 19; j++) { for (int i = 0; i <= n - (1 << j); i++) { SparseTable[i][j] = __gcd(SparseTable[i][j - 1], SparseTable[i + (1 << (j - 1))][j - 1]); } }} // Utility Function to calculate GCD in range [L,R]static int queryForGCD(int L, int R){ int returnValue; // Calculating where the answer is // stored in our Sparse Table int j = (int) (Math.log(R - L + 1)); returnValue = __gcd(SparseTable[L][j], SparseTable[R - (1 << j) + 1][j]); return returnValue;} // Utility Function to find next-farther// position where gcd is samestatic int nextPosition(int tempGCD, int startPointer, int prevEndPointer, int n){ int high = n - 1; int low = prevEndPointer; int mid = prevEndPointer; int nextPos = prevEndPointer; // BinarySearch for Next Position // for EndPointer while (high >= low) { mid = ((high + low) >> 1); if (queryForGCD(startPointer, mid) == tempGCD) { nextPos = mid; low = mid + 1; } else { high = mid - 1; } } return nextPos + 1;} // Utility function to calculate// sum of gcdstatic int calculateSum(int a[], int n){ buildSparseTable(a, n); int endPointer, startPointer, prevEndPointer, tempGCD; int tempAns = 0; for (int i = 0; i < n; i++) { // Initializing all the values endPointer = i; startPointer = i; prevEndPointer = i; tempGCD = a[i]; while (endPointer < n) { // Finding the next position for endPointer endPointer = nextPosition(tempGCD, startPointer, prevEndPointer, n); // Adding the suitable sum to our answer tempAns += ((endPointer - prevEndPointer) * tempGCD); // Changing prevEndPointer prevEndPointer = endPointer; if (endPointer < n) { // Recalculating tempGCD tempGCD = __gcd(tempGCD, a[endPointer]); } } } return tempAns;} static int __gcd(int a, int b){ return b == 0? a:__gcd(b, a % b); } // Driver codepublic static void main(String[] args){ int n = 6; int a[] = {2, 2, 2, 3, 5, 5}; System.out.println(calculateSum(a, n));}} // This code is contributed by PrinciRaj1992
# Python3 program to find Sum# of GCD over all subarraysfrom math import gcd as __gcd,log,floorSparseTable = [ [0 for i in range(51)] for i in range(100001)] # Build Sparse Tabledef buildSparseTable(a, n): for i in range(n): SparseTable[i][0] = a[i] # Building the Sparse Table for GCD[L, R] Queries for j in range(1,20): for i in range(n - (1 << j)+1): SparseTable[i][j] = __gcd(SparseTable[i][j - 1], SparseTable[i + (1 << (j - 1))][j - 1]) # Utility Function to calculate GCD in range [L,R]def queryForGCD(L, R): # Calculating where the answer is # stored in our Sparse Table j = floor(log(R - L + 1, 2)) returnValue = __gcd(SparseTable[L][j], SparseTable[R - (1 << j) + 1][j]) return returnValue # Utility Function to find next-farther# position where gcd is samedef nextPosition(tempGCD, startPointer,prevEndPointer, n): high = n - 1 low = prevEndPointer mid = prevEndPointer nextPos = prevEndPointer # BinarySearch for Next Position # for EndPointer while (high >= low): mid = ((high + low) >> 1) if (queryForGCD(startPointer, mid) == tempGCD): nextPos = mid low = mid + 1 else: high = mid - 1 return nextPos + 1 # Utility function to calculate# sum of gcddef calculateSum(a, n): buildSparseTable(a, n) tempAns = 0 for i in range(n): # Initializing all the values endPointer = i startPointer = i prevEndPointer = i tempGCD = a[i] while (endPointer < n): # Finding the next position for endPointer endPointer = nextPosition(tempGCD, startPointer,prevEndPointer, n) # Adding the suitable sum to our answer tempAns += ((endPointer - prevEndPointer) * tempGCD) # Changing prevEndPointer prevEndPointer = endPointer if (endPointer < n): # Recalculating tempGCD tempGCD = __gcd(tempGCD, a[endPointer]) return tempAns # Driver codeif __name__ == '__main__': n = 6 a = [2, 2, 2, 3, 5, 5] print(calculateSum(a, n)) # This code is contributed by mohit kumar 29
// C# program to find Sum// of GCD over all subarraysusing System; class GFG{ //int a[100001];static int [,]SparseTable = new int[100001,51]; // Build Sparse Tablestatic void buildSparseTable(int []a, int n){ for (int i = 0; i < n; i++) { SparseTable[i,0] = a[i]; } // Building the Sparse Table // for GCD[L, R] Queries for (int j = 1; j <= 19; j++) { for (int i = 0; i <= n - (1 << j); i++) { SparseTable[i,j] = __gcd(SparseTable[i,j - 1], SparseTable[i + (1 << (j - 1)),j - 1]); } }} // Utility Function to calculate GCD in range [L,R]static int queryForGCD(int L, int R){ int returnValue; // Calculating where the answer is // stored in our Sparse Table int j = (int) (Math.Log(R - L + 1)); returnValue = __gcd(SparseTable[L,j], SparseTable[R - (1 << j) + 1,j]); return returnValue;} // Utility Function to find next-farther// position where gcd is samestatic int nextPosition(int tempGCD, int startPointer, int prevEndPointer, int n){ int high = n - 1; int low = prevEndPointer; int mid = prevEndPointer; int nextPos = prevEndPointer; // BinarySearch for Next Position // for EndPointer while (high >= low) { mid = ((high + low) >> 1); if (queryForGCD(startPointer, mid) == tempGCD) { nextPos = mid; low = mid + 1; } else { high = mid - 1; } } return nextPos + 1;} // Utility function to calculate// sum of gcdstatic int calculateSum(int []a, int n){ buildSparseTable(a, n); int endPointer, startPointer, prevEndPointer, tempGCD; int tempAns = 0; for (int i = 0; i < n; i++) { // Initializing all the values endPointer = i; startPointer = i; prevEndPointer = i; tempGCD = a[i]; while (endPointer < n) { // Finding the next position for endPointer endPointer = nextPosition(tempGCD, startPointer, prevEndPointer, n); // Adding the suitable sum to our answer tempAns += ((endPointer - prevEndPointer) * tempGCD); // Changing prevEndPointer prevEndPointer = endPointer; if (endPointer < n) { // Recalculating tempGCD tempGCD = __gcd(tempGCD, a[endPointer]); } } } return tempAns;} static int __gcd(int a, int b){ return b == 0? a:__gcd(b, a % b); } // Driver codepublic static void Main(String[] args){ int n = 6; int []a = {2, 2, 2, 3, 5, 5}; Console.WriteLine(calculateSum(a, n));}} // This code contributed by PrinciRaj1992
<script> // JavaScript program to find Sum// of GCD over all subarrays // int a[100001];let SparseTable = new Array(100001);for(let i=0;i<100001;i++){ SparseTable[i]=new Array(51); for(let j=0;j<51;j++) { SparseTable[i][j]=0; }} // Build Sparse Tablefunction buildSparseTable(a,n){ for (let i = 0; i < n; i++) { SparseTable[i][0] = a[i]; } // Building the Sparse Table // for GCD[L, R] Queries for (let j = 1; j <= 19; j++) { for (let i = 0; i <= n - (1 << j); i++) { SparseTable[i][j] = __gcd(SparseTable[i][j - 1], SparseTable[i + (1 << (j - 1))][j - 1]); } }} // Utility Function to calculate GCD in range [L,R]function queryForGCD(L,R){ let returnValue; // Calculating where the answer is // stored in our Sparse Table let j = Math.floor(Math.log(R - L + 1)); returnValue = __gcd(SparseTable[L][j], SparseTable[R - (1 << j) + 1][j]); return returnValue;} // Utility Function to find next-farther// position where gcd is samefunction nextPosition(tempGCD,startPointer,prevEndPointer,n){ let high = n - 1; let low = prevEndPointer; let mid = prevEndPointer; let nextPos = prevEndPointer; // BinarySearch for Next Position // for EndPointer while (high >= low) { mid = ((high + low) >> 1); if (queryForGCD(startPointer, mid) == tempGCD) { nextPos = mid; low = mid + 1; } else { high = mid - 1; } } return nextPos + 1;} // Utility function to calculate// sum of gcdfunction calculateSum(a,n){ buildSparseTable(a, n); let endPointer, startPointer, prevEndPointer, tempGCD; let tempAns = 0; for (let i = 0; i < n; i++) { // Initializing all the values endPointer = i; startPointer = i; prevEndPointer = i; tempGCD = a[i]; while (endPointer < n) { // Finding the next position for endPointer endPointer = nextPosition(tempGCD, startPointer, prevEndPointer, n); // Adding the suitable sum to our answer tempAns += ((endPointer - prevEndPointer) * tempGCD); // Changing prevEndPointer prevEndPointer = endPointer; if (endPointer < n) { // Recalculating tempGCD tempGCD = __gcd(tempGCD, a[endPointer]); } } } return tempAns;} function __gcd(a,b){ return b == 0? a: __gcd(b, a % b);} // Driver codelet n = 6;let a=[2, 2, 2, 3, 5, 5];document.write(calculateSum(a, n)); // This code is contributed by patel2127 </script>
41
Time Complexity: O(N * log(max(A[i]) * log(N)) The time complexity of the above solution includes the knowledge of knowing how many times the binary search will be called, and hence we need to know how many times value of endPointer may change. This value comes out to be approximately log(A[i]), because, for any number X, the number of times itβs GCD can decrease upon being clubbed with other number is the value of highest power of any of itβs prime divisors. So the total time complexity becomes approximately O(N * log(max(A[i]) * log(N)) where another logN factor comes due to Binary search. This is the case when we use Sparse Table, if we use Segment Tree for GCD queries, another term of log(N) will appear.
princiraj1992
29AjayKumar
Rajput-Ji
mohit kumar 29
umadevi9616
arorakashish0911
patel2127
GCD-LCM
Segment-Tree
subarray
subarray-sum
Advanced Data Structure
Arrays
Competitive Programming
Searching
Arrays
Searching
Segment-Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
2-3 Trees | (Search, Insert and Deletion)
Extendible Hashing (Dynamic approach to DBMS)
Advantages of Trie Data Structure
Cartesian Tree
Proof that Dominant Set of a Graph is NP-Complete
Arrays in Java
Arrays in C/C++
Program for array rotation
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews
|
[
{
"code": null,
"e": 24406,
"s": 24378,
"text": "\n10 Jun, 2021"
},
{
"code": null,
"e": 24729,
"s": 24406,
"text": "Given an array of integers, the task is to calculate the sum of GCD of all the subarrays of an array. GCD of an array is defined as the GCD of all the elements present in it. More formally, . Summation of all the GCDs can be defined as where denotes the subarray starting from ith index and ending at jth index.Examples: "
},
{
"code": null,
"e": 25164,
"s": 24729,
"text": "Input 1: N = 5, A = {1,2,3,4,5} Output 1: 25Explanation: The subarrays of length one are [1], [2], [3], [4], [5] and the sum of their GCDs is 15, similarly subarrays of length 2, are [1, 2], [2, 3], [3, 4], [4, 5], and the sum of their GCDs is 4, similarly for length 3, the sum is 3, similarly for length 4, the sum is 2, similarly for length 5, the sum is 1. The total sum becomes 25.Input 2: N = 6, A = {2,2,2,3,5,5} Output 2: 41 "
},
{
"code": null,
"e": 25305,
"s": 25164,
"text": "Pre-Requisites Binary Search Segment Tree approach for calculating GCD in an index range Sparse Table for calculating GCD in an index range "
},
{
"code": null,
"e": 25532,
"s": 25305,
"text": "Naive Approach (O(n^3) complexity)We can find out every subarray in O(n^2) complexity and can traverse it for finding the GCD of that subarray and add it to the total answer.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 25536,
"s": 25532,
"text": "C++"
},
{
"code": null,
"e": 25541,
"s": 25536,
"text": "Java"
},
{
"code": null,
"e": 25549,
"s": 25541,
"text": "Python3"
},
{
"code": null,
"e": 25552,
"s": 25549,
"text": "C#"
},
{
"code": null,
"e": 25563,
"s": 25552,
"text": "Javascript"
},
{
"code": "// C++ program to find// Sum of GCD over all subarrays. #include <bits/stdc++.h>using namespace std; // Utility function to calculate// sum of gcd of all sub-arrays. int findGCDSum(int n, int a[]){ int GCDSum = 0; int tempGCD = 0; for (int i = 0; i < n; i++) { // Fixing the starting index of a subarray for (int j = i; j < n; j++) { // Fixing the ending index of a subarray tempGCD = 0; for (int k = i; k <= j; k++) { // Finding the GCD of this subarray tempGCD = __gcd(tempGCD, a[k]); } // Adding this GCD in our sum GCDSum += tempGCD; } } return GCDSum;} // Driver Codeint main(){ int n = 5; int a[] = { 1, 2, 3, 4, 5 }; int totalSum = findGCDSum(n, a); cout << totalSum << \"\\n\";}",
"e": 26391,
"s": 25563,
"text": null
},
{
"code": "// Java program to find// Sum of GCD over all subarrays.class GFG{ // Utility function to calculate// sum of gcd of all sub-arrays.static int findGCDSum(int n, int a[]){ int GCDSum = 0; int tempGCD = 0; for (int i = 0; i < n; i++) { // Fixing the starting index of a subarray for (int j = i; j < n; j++) { // Fixing the ending index of a subarray tempGCD = 0; for (int k = i; k <= j; k++) { // Finding the GCD of this subarray tempGCD = __gcd(tempGCD, a[k]); } // Adding this GCD in our sum GCDSum += tempGCD; } } return GCDSum;} static int __gcd(int a, int b){ return b == 0 ? a : __gcd(b, a % b); } // Driver Codepublic static void main(String[] args){ int n = 5; int a[] = { 1, 2, 3, 4, 5 }; int totalSum = findGCDSum(n, a); System.out.print(totalSum + \"\\n\");}} // This code is contributed by 29AjayKumar",
"e": 27383,
"s": 26391,
"text": null
},
{
"code": "# Python3 program to find# Sum of GCD over all subarrays. # Utility function to calculate# sum of gcd of all sub-arrays.def findGCDSum(n, a): GCDSum = 0; tempGCD = 0; for i in range(n): # Fixing the starting index of a subarray for j in range(i, n): # Fixing the ending index of a subarray tempGCD = 0; for k in range(i, j + 1): # Finding the GCD of this subarray tempGCD = __gcd(tempGCD, a[k]); # Adding this GCD in our sum GCDSum += tempGCD; return GCDSum; def __gcd(a, b): return a if(b == 0 ) else __gcd(b, a % b); # Driver Codeif __name__ == '__main__': n = 5; a = [1, 2, 3, 4, 5]; totalSum = findGCDSum(n, a); print(totalSum); # This code is contributed by PrinciRaj1992",
"e": 28247,
"s": 27383,
"text": null
},
{
"code": "// C# program to find// Sum of GCD over all subarrays.using System; class GFG{ // Utility function to calculate// sum of gcd of all sub-arrays.static int findGCDSum(int n, int []a){ int GCDSum = 0; int tempGCD = 0; for (int i = 0; i < n; i++) { // Fixing the starting index of a subarray for (int j = i; j < n; j++) { // Fixing the ending index of a subarray tempGCD = 0; for (int k = i; k <= j; k++) { // Finding the GCD of this subarray tempGCD = __gcd(tempGCD, a[k]); } // Adding this GCD in our sum GCDSum += tempGCD; } } return GCDSum;} static int __gcd(int a, int b){ return b == 0 ? a : __gcd(b, a % b); } // Driver Codepublic static void Main(String[] args){ int n = 5; int []a = { 1, 2, 3, 4, 5 }; int totalSum = findGCDSum(n, a); Console.Write(totalSum + \"\\n\");}} // This code is contributed by Rajput-Ji",
"e": 29246,
"s": 28247,
"text": null
},
{
"code": "<script>// javascript program to find// Sum of GCD over all subarrays. // Utility function to calculate // sum of gcd of all sub-arrays. function findGCDSum(n , a) { var GCDSum = 0; var tempGCD = 0; for (i = 0; i < n; i++) { // Fixing the starting index of a subarray for (j = i; j < n; j++) { // Fixing the ending index of a subarray tempGCD = 0; for (k = i; k <= j; k++) { // Finding the GCD of this subarray tempGCD = __gcd(tempGCD, a[k]); } // Adding this GCD in our sum GCDSum += tempGCD; } } return GCDSum; } function __gcd(a , b) { return b == 0 ? a : __gcd(b, a % b); } // Driver Code var n = 5; var a = [ 1, 2, 3, 4, 5 ]; var totalSum = findGCDSum(n, a); document.write(totalSum + \"<br/>\"); // This code is contributed by umadevi9616</script>",
"e": 30331,
"s": 29246,
"text": null
},
{
"code": null,
"e": 30334,
"s": 30331,
"text": "25"
},
{
"code": null,
"e": 33548,
"s": 30336,
"text": "We can optimize the part where you calculate GCD of a subarray, We can use a segment tree or a sparse table to optimize the complexity to O(n^2 * logn) (for segment trees) or to O(n^2) (for sparse table)Efficient Approach (O(n*(logn)^2) complexity):This approach takes advantage of the observation that upon adding a new element to an array, the new GCD of the array will always be either less or equal to the previous GCD of the array before the addition of the element.We create three pointers, lets call them startPointer, endPointer and prevEndPointer. Initially all three of them point to the first element of our array. We initialize a variable tempGCD with the value of the first element. We will now find the sum of GCDs of all the subarrays starting with first element. Now according to our previous observation, if we move the endPointer to the right by one position, and calculate the GCD of these two elements which are pointed by startPointer and endPointer, it will always be less than or equal to tempGCD. So if we want to find out how many subarrays have the GCD as tempGCD, we need to find a suitable position of endPointer, where the subarray starting at startPointer and ending at endPointer will have the value of itβs GCD less than tempGCD, and the value of endPointer should be as minimal as possible, then the difference of prevEndPointer and endPointer will give us the number of subarrays which have their GCD as tempGCD. Now, we can add this value (tempGCD*(endPointer-prevEndPointer)), which denotes the sum of the GCD for these particular group of subarrays, into our variable finalAns which stores the sum of the GCD of all subarrays. Now the question remains, how will we find the suitable position of endPointer where the GCD decreases? Thatβs where Binary Search comes into use, we have the starting point of our array fixed, and we need to vary the ending point, letβs call them L and R, so for any R. We initialize high as N and low as prevEndPointer, and mid as (high+low)/2, now if we check the value of GCD[L, mid], we compare it to the value of tempGCD, and if it is less than it, then R might be a suitable position for endPointer, but it might be the case that some smaller value may become our answer, so we change high to be mid-1, and if GCD[L, mid] is found to be equal to tempGCD, then we should change low to be mid+1, and the value of mid+1 might be the answer, so we store the value of mid in a variable nextPos. At last we return the value of nextPos+1. Value of GCD[L, mid] can be efficiently calculated using a Segment Tree in O(logN) complexity or using a Sparse Table in O(1) complexity. This type of binary search finds us the suitable position of endPointer. After finding out this position, and adding to finalAns, we change prevEndPointer to endPointer, and tempGCD to GCD[startPointer, endPointer], and again start the process of finding next endPointer. This will stop once the value of endPointer becomes N, and then we need to move startPointer to the right, which will count the sum of GCD of all subarrays starting with second element. This will continue till the value of startPointer becomes N.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 33552,
"s": 33548,
"text": "C++"
},
{
"code": null,
"e": 33557,
"s": 33552,
"text": "Java"
},
{
"code": null,
"e": 33565,
"s": 33557,
"text": "Python3"
},
{
"code": null,
"e": 33568,
"s": 33565,
"text": "C#"
},
{
"code": null,
"e": 33579,
"s": 33568,
"text": "Javascript"
},
{
"code": "// C++ program to find Sum// of GCD over all subarrays #include <bits/stdc++.h>using namespace std; //int a[100001];int SparseTable[100001][51]; // Build Sparse Tablevoid buildSparseTable(int a[], int n){ for (int i = 0; i < n; i++) { SparseTable[i][0] = a[i]; } // Building the Sparse Table for GCD[L, R] Queries for (int j = 1; j <= 19; j++) { for (int i = 0; i <= n - (1 << j); i++) { SparseTable[i][j] = __gcd(SparseTable[i][j - 1], SparseTable[i + (1 << (j - 1))][j - 1]); } }} // Utility Function to calculate GCD in range [L,R]int queryForGCD(int L, int R){ int returnValue; // Calculating where the answer is // stored in our Sparse Table int j = int(log2(R - L + 1)); returnValue = __gcd(SparseTable[L][j], SparseTable[R - (1 << j) + 1][j]); return returnValue;} // Utility Function to find next-farther// position where gcd is sameint nextPosition(int tempGCD, int startPointer, int prevEndPointer, int n){ int high = n - 1; int low = prevEndPointer; int mid = prevEndPointer; int nextPos = prevEndPointer; // BinarySearch for Next Position // for EndPointer while (high >= low) { mid = ((high + low) >> 1); if (queryForGCD(startPointer, mid) == tempGCD) { nextPos = mid; low = mid + 1; } else { high = mid - 1; } } return nextPos + 1;} // Utility function to calculate// sum of gcdint calculateSum(int a[], int n){ buildSparseTable(a, n); int endPointer, startPointer, prevEndPointer, tempGCD; int tempAns = 0; for (int i = 0; i < n; i++) { // Initializing all the values endPointer = i; startPointer = i; prevEndPointer = i; tempGCD = a[i]; while (endPointer < n) { // Finding the next position for endPointer endPointer = nextPosition(tempGCD, startPointer, prevEndPointer, n); // Adding the suitable sum to our answer tempAns += ((endPointer - prevEndPointer) * tempGCD); // Changing prevEndPointer prevEndPointer = endPointer; if (endPointer < n) { // Recalculating tempGCD tempGCD = __gcd(tempGCD, a[endPointer]); } } } return tempAns;} // Driver Codeint main(){ int n = 6; int a[] = {2, 2, 2, 3, 5, 5}; cout << calculateSum(a, n) << \"\\n\"; return 0;}",
"e": 36204,
"s": 33579,
"text": null
},
{
"code": "// Java program to find Sum// of GCD over all subarraysclass GFG{ //int a[100001];static int [][]SparseTable = new int[100001][51]; // Build Sparse Tablestatic void buildSparseTable(int a[], int n){ for (int i = 0; i < n; i++) { SparseTable[i][0] = a[i]; } // Building the Sparse Table // for GCD[L, R] Queries for (int j = 1; j <= 19; j++) { for (int i = 0; i <= n - (1 << j); i++) { SparseTable[i][j] = __gcd(SparseTable[i][j - 1], SparseTable[i + (1 << (j - 1))][j - 1]); } }} // Utility Function to calculate GCD in range [L,R]static int queryForGCD(int L, int R){ int returnValue; // Calculating where the answer is // stored in our Sparse Table int j = (int) (Math.log(R - L + 1)); returnValue = __gcd(SparseTable[L][j], SparseTable[R - (1 << j) + 1][j]); return returnValue;} // Utility Function to find next-farther// position where gcd is samestatic int nextPosition(int tempGCD, int startPointer, int prevEndPointer, int n){ int high = n - 1; int low = prevEndPointer; int mid = prevEndPointer; int nextPos = prevEndPointer; // BinarySearch for Next Position // for EndPointer while (high >= low) { mid = ((high + low) >> 1); if (queryForGCD(startPointer, mid) == tempGCD) { nextPos = mid; low = mid + 1; } else { high = mid - 1; } } return nextPos + 1;} // Utility function to calculate// sum of gcdstatic int calculateSum(int a[], int n){ buildSparseTable(a, n); int endPointer, startPointer, prevEndPointer, tempGCD; int tempAns = 0; for (int i = 0; i < n; i++) { // Initializing all the values endPointer = i; startPointer = i; prevEndPointer = i; tempGCD = a[i]; while (endPointer < n) { // Finding the next position for endPointer endPointer = nextPosition(tempGCD, startPointer, prevEndPointer, n); // Adding the suitable sum to our answer tempAns += ((endPointer - prevEndPointer) * tempGCD); // Changing prevEndPointer prevEndPointer = endPointer; if (endPointer < n) { // Recalculating tempGCD tempGCD = __gcd(tempGCD, a[endPointer]); } } } return tempAns;} static int __gcd(int a, int b){ return b == 0? a:__gcd(b, a % b); } // Driver codepublic static void main(String[] args){ int n = 6; int a[] = {2, 2, 2, 3, 5, 5}; System.out.println(calculateSum(a, n));}} // This code is contributed by PrinciRaj1992",
"e": 39064,
"s": 36204,
"text": null
},
{
"code": "# Python3 program to find Sum# of GCD over all subarraysfrom math import gcd as __gcd,log,floorSparseTable = [ [0 for i in range(51)] for i in range(100001)] # Build Sparse Tabledef buildSparseTable(a, n): for i in range(n): SparseTable[i][0] = a[i] # Building the Sparse Table for GCD[L, R] Queries for j in range(1,20): for i in range(n - (1 << j)+1): SparseTable[i][j] = __gcd(SparseTable[i][j - 1], SparseTable[i + (1 << (j - 1))][j - 1]) # Utility Function to calculate GCD in range [L,R]def queryForGCD(L, R): # Calculating where the answer is # stored in our Sparse Table j = floor(log(R - L + 1, 2)) returnValue = __gcd(SparseTable[L][j], SparseTable[R - (1 << j) + 1][j]) return returnValue # Utility Function to find next-farther# position where gcd is samedef nextPosition(tempGCD, startPointer,prevEndPointer, n): high = n - 1 low = prevEndPointer mid = prevEndPointer nextPos = prevEndPointer # BinarySearch for Next Position # for EndPointer while (high >= low): mid = ((high + low) >> 1) if (queryForGCD(startPointer, mid) == tempGCD): nextPos = mid low = mid + 1 else: high = mid - 1 return nextPos + 1 # Utility function to calculate# sum of gcddef calculateSum(a, n): buildSparseTable(a, n) tempAns = 0 for i in range(n): # Initializing all the values endPointer = i startPointer = i prevEndPointer = i tempGCD = a[i] while (endPointer < n): # Finding the next position for endPointer endPointer = nextPosition(tempGCD, startPointer,prevEndPointer, n) # Adding the suitable sum to our answer tempAns += ((endPointer - prevEndPointer) * tempGCD) # Changing prevEndPointer prevEndPointer = endPointer if (endPointer < n): # Recalculating tempGCD tempGCD = __gcd(tempGCD, a[endPointer]) return tempAns # Driver codeif __name__ == '__main__': n = 6 a = [2, 2, 2, 3, 5, 5] print(calculateSum(a, n)) # This code is contributed by mohit kumar 29",
"e": 41331,
"s": 39064,
"text": null
},
{
"code": "// C# program to find Sum// of GCD over all subarraysusing System; class GFG{ //int a[100001];static int [,]SparseTable = new int[100001,51]; // Build Sparse Tablestatic void buildSparseTable(int []a, int n){ for (int i = 0; i < n; i++) { SparseTable[i,0] = a[i]; } // Building the Sparse Table // for GCD[L, R] Queries for (int j = 1; j <= 19; j++) { for (int i = 0; i <= n - (1 << j); i++) { SparseTable[i,j] = __gcd(SparseTable[i,j - 1], SparseTable[i + (1 << (j - 1)),j - 1]); } }} // Utility Function to calculate GCD in range [L,R]static int queryForGCD(int L, int R){ int returnValue; // Calculating where the answer is // stored in our Sparse Table int j = (int) (Math.Log(R - L + 1)); returnValue = __gcd(SparseTable[L,j], SparseTable[R - (1 << j) + 1,j]); return returnValue;} // Utility Function to find next-farther// position where gcd is samestatic int nextPosition(int tempGCD, int startPointer, int prevEndPointer, int n){ int high = n - 1; int low = prevEndPointer; int mid = prevEndPointer; int nextPos = prevEndPointer; // BinarySearch for Next Position // for EndPointer while (high >= low) { mid = ((high + low) >> 1); if (queryForGCD(startPointer, mid) == tempGCD) { nextPos = mid; low = mid + 1; } else { high = mid - 1; } } return nextPos + 1;} // Utility function to calculate// sum of gcdstatic int calculateSum(int []a, int n){ buildSparseTable(a, n); int endPointer, startPointer, prevEndPointer, tempGCD; int tempAns = 0; for (int i = 0; i < n; i++) { // Initializing all the values endPointer = i; startPointer = i; prevEndPointer = i; tempGCD = a[i]; while (endPointer < n) { // Finding the next position for endPointer endPointer = nextPosition(tempGCD, startPointer, prevEndPointer, n); // Adding the suitable sum to our answer tempAns += ((endPointer - prevEndPointer) * tempGCD); // Changing prevEndPointer prevEndPointer = endPointer; if (endPointer < n) { // Recalculating tempGCD tempGCD = __gcd(tempGCD, a[endPointer]); } } } return tempAns;} static int __gcd(int a, int b){ return b == 0? a:__gcd(b, a % b); } // Driver codepublic static void Main(String[] args){ int n = 6; int []a = {2, 2, 2, 3, 5, 5}; Console.WriteLine(calculateSum(a, n));}} // This code contributed by PrinciRaj1992",
"e": 44187,
"s": 41331,
"text": null
},
{
"code": "<script> // JavaScript program to find Sum// of GCD over all subarrays // int a[100001];let SparseTable = new Array(100001);for(let i=0;i<100001;i++){ SparseTable[i]=new Array(51); for(let j=0;j<51;j++) { SparseTable[i][j]=0; }} // Build Sparse Tablefunction buildSparseTable(a,n){ for (let i = 0; i < n; i++) { SparseTable[i][0] = a[i]; } // Building the Sparse Table // for GCD[L, R] Queries for (let j = 1; j <= 19; j++) { for (let i = 0; i <= n - (1 << j); i++) { SparseTable[i][j] = __gcd(SparseTable[i][j - 1], SparseTable[i + (1 << (j - 1))][j - 1]); } }} // Utility Function to calculate GCD in range [L,R]function queryForGCD(L,R){ let returnValue; // Calculating where the answer is // stored in our Sparse Table let j = Math.floor(Math.log(R - L + 1)); returnValue = __gcd(SparseTable[L][j], SparseTable[R - (1 << j) + 1][j]); return returnValue;} // Utility Function to find next-farther// position where gcd is samefunction nextPosition(tempGCD,startPointer,prevEndPointer,n){ let high = n - 1; let low = prevEndPointer; let mid = prevEndPointer; let nextPos = prevEndPointer; // BinarySearch for Next Position // for EndPointer while (high >= low) { mid = ((high + low) >> 1); if (queryForGCD(startPointer, mid) == tempGCD) { nextPos = mid; low = mid + 1; } else { high = mid - 1; } } return nextPos + 1;} // Utility function to calculate// sum of gcdfunction calculateSum(a,n){ buildSparseTable(a, n); let endPointer, startPointer, prevEndPointer, tempGCD; let tempAns = 0; for (let i = 0; i < n; i++) { // Initializing all the values endPointer = i; startPointer = i; prevEndPointer = i; tempGCD = a[i]; while (endPointer < n) { // Finding the next position for endPointer endPointer = nextPosition(tempGCD, startPointer, prevEndPointer, n); // Adding the suitable sum to our answer tempAns += ((endPointer - prevEndPointer) * tempGCD); // Changing prevEndPointer prevEndPointer = endPointer; if (endPointer < n) { // Recalculating tempGCD tempGCD = __gcd(tempGCD, a[endPointer]); } } } return tempAns;} function __gcd(a,b){ return b == 0? a: __gcd(b, a % b);} // Driver codelet n = 6;let a=[2, 2, 2, 3, 5, 5];document.write(calculateSum(a, n)); // This code is contributed by patel2127 </script>",
"e": 47022,
"s": 44187,
"text": null
},
{
"code": null,
"e": 47025,
"s": 47022,
"text": "41"
},
{
"code": null,
"e": 47746,
"s": 47027,
"text": "Time Complexity: O(N * log(max(A[i]) * log(N)) The time complexity of the above solution includes the knowledge of knowing how many times the binary search will be called, and hence we need to know how many times value of endPointer may change. This value comes out to be approximately log(A[i]), because, for any number X, the number of times itβs GCD can decrease upon being clubbed with other number is the value of highest power of any of itβs prime divisors. So the total time complexity becomes approximately O(N * log(max(A[i]) * log(N)) where another logN factor comes due to Binary search. This is the case when we use Sparse Table, if we use Segment Tree for GCD queries, another term of log(N) will appear. "
},
{
"code": null,
"e": 47760,
"s": 47746,
"text": "princiraj1992"
},
{
"code": null,
"e": 47772,
"s": 47760,
"text": "29AjayKumar"
},
{
"code": null,
"e": 47782,
"s": 47772,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 47797,
"s": 47782,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 47809,
"s": 47797,
"text": "umadevi9616"
},
{
"code": null,
"e": 47826,
"s": 47809,
"text": "arorakashish0911"
},
{
"code": null,
"e": 47836,
"s": 47826,
"text": "patel2127"
},
{
"code": null,
"e": 47844,
"s": 47836,
"text": "GCD-LCM"
},
{
"code": null,
"e": 47857,
"s": 47844,
"text": "Segment-Tree"
},
{
"code": null,
"e": 47866,
"s": 47857,
"text": "subarray"
},
{
"code": null,
"e": 47879,
"s": 47866,
"text": "subarray-sum"
},
{
"code": null,
"e": 47903,
"s": 47879,
"text": "Advanced Data Structure"
},
{
"code": null,
"e": 47910,
"s": 47903,
"text": "Arrays"
},
{
"code": null,
"e": 47934,
"s": 47910,
"text": "Competitive Programming"
},
{
"code": null,
"e": 47944,
"s": 47934,
"text": "Searching"
},
{
"code": null,
"e": 47951,
"s": 47944,
"text": "Arrays"
},
{
"code": null,
"e": 47961,
"s": 47951,
"text": "Searching"
},
{
"code": null,
"e": 47974,
"s": 47961,
"text": "Segment-Tree"
},
{
"code": null,
"e": 48072,
"s": 47974,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 48081,
"s": 48072,
"text": "Comments"
},
{
"code": null,
"e": 48094,
"s": 48081,
"text": "Old Comments"
},
{
"code": null,
"e": 48136,
"s": 48094,
"text": "2-3 Trees | (Search, Insert and Deletion)"
},
{
"code": null,
"e": 48182,
"s": 48136,
"text": "Extendible Hashing (Dynamic approach to DBMS)"
},
{
"code": null,
"e": 48216,
"s": 48182,
"text": "Advantages of Trie Data Structure"
},
{
"code": null,
"e": 48231,
"s": 48216,
"text": "Cartesian Tree"
},
{
"code": null,
"e": 48281,
"s": 48231,
"text": "Proof that Dominant Set of a Graph is NP-Complete"
},
{
"code": null,
"e": 48296,
"s": 48281,
"text": "Arrays in Java"
},
{
"code": null,
"e": 48312,
"s": 48296,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 48339,
"s": 48312,
"text": "Program for array rotation"
},
{
"code": null,
"e": 48387,
"s": 48339,
"text": "Stack Data Structure (Introduction and Program)"
}
] |
What is JDBC Blob data type? how to store and read data from it?
|
A BLOB is binary large object that can hold a variable amount of data with a maximum length of 65535 characters.
These are used to store large amounts of binary data, such as images or other types of files. Fields defined as TEXT also hold large amounts of data. The difference between the two is that the sorts and comparisons on the stored data are case sensitive on BLOBs and are not case sensitive in TEXT fields. You do not specify a length with BLOB or TEXT.
To store Blob datatype to database, using JDBC program follow the steps given below
Step 1: Connect to the database
You can connect to a database using the getConnection() method of the DriverManager class.
Connect to the MySQL database by passing the MySQL URL which is jdbc:mysql://localhost/sampleDB (where sampleDB is the database name), username and password as parameters to the getConnection() method.
String mysqlUrl = "jdbc:mysql://localhost/sampleDB";
Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
Step 2: Create a Prepared statement
Create a PreparedStatement object using the prepareStatement() method of the Connection interface. To this method pass the insert query (with place holders) as a parameter.
PreparedStatement pstmt = con.prepareStatement("INSERT INTO MyTableVALUES(?, ?)");
Step 3: Set values to the place holders
Set the values to the place holders using the setter methods of the PreparedStatement interface. Chose the methods according to the datatype of the column. For Example if the column is of VARCHAR type use setString() method and if it is of INT type you can use setInt() method.
And if it is of Blob type you can set value to it using the setBinaryStream() or setBlob() methods. To these methods pass an integer variable representing the parameter index and an object of InputStream class as parameters.
pstmt.setString(1, "sample image");
//Inserting Blob type
InputStream in = new FileInputStream("E:\\images\\cat.jpg");
pstmt.setBlob(2, in);
Step 4: Execute the statement
Execute the above created PreparedStatement object using the execute() method of the PreparedStatement interface.
The getBlob() method of the ResultSet interface accepts an integer representing the index of the column (or, a String value representing the name of the column) and retrieves the value at the specified column and returns it in the form of a Blob object.
while(rs.next()) {
rs.getString("Name");
rs.getString("Type");
Blob blob = rs.getBlob("Logo");
}
The getBytes() method of the Blob Interface retrieves the contents of the current Blob object and returns as a byte array.
Using the getBlob() method you can get the contents of the blob in to a byte array and create an image using the write() method of the FileOutputStream object.
byte byteArray[] = blob.getBytes(1,(int)blob.length());
FileOutputStream outPutStream = new FileOutputStream("path");
outPutStream.write(byteArray);
Following example creates a table in MySQL database with blob datatype, inserts image to it. Retrieves it back and stores in the local file system.
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
public class BlobExample {
public static void main(String args[]) throws Exception {
//Registering the Driver
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
//Getting the connection
String mysqlUrl = "jdbc:mysql://localhost/sampleDB";
Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
System.out.println("Connection established......");
//Creating a table
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE SampleTable( Name VARCHAR(255), Image BLOB)");
System.out.println("Table Created");
//Inserting values
String query = "INSERT INTO SampleTable(Name,image) VALUES (?, ?)";
PreparedStatement pstmt = con.prepareStatement(query);
pstmt.setString(1, "sample image");
FileInputStream fin = new FileInputStream("E:\\images\\cat.jpg");
pstmt.setBlob(2, fin);
pstmt.execute();
//Retrieving the data
ResultSet rs = stmt.executeQuery("select * from SampleTable");
int i = 1;
System.out.println("Contents of the table are: ");
while(rs.next()) {
System.out.println(rs.getString("Name"));
Blob blob = rs.getBlob("Image");
byte byteArray[] = blob.getBytes(1,(int)blob.length());
FileOutputStream outPutStream = new
FileOutputStream("E:\\images\\blob_output"+i+".jpg");
outPutStream.write(byteArray);
System.out.println("E:\\images\\blob_output"+i+".jpg");
System.out.println();
i++;
}
}
}
Connection established......
Table Created
Contents of the table are:
sample image
E:\images\blob_output1.jpg
|
[
{
"code": null,
"e": 1175,
"s": 1062,
"text": "A BLOB is binary large object that can hold a variable amount of data with a maximum length of 65535 characters."
},
{
"code": null,
"e": 1527,
"s": 1175,
"text": "These are used to store large amounts of binary data, such as images or other types of files. Fields defined as TEXT also hold large amounts of data. The difference between the two is that the sorts and comparisons on the stored data are case sensitive on BLOBs and are not case sensitive in TEXT fields. You do not specify a length with BLOB or TEXT."
},
{
"code": null,
"e": 1611,
"s": 1527,
"text": "To store Blob datatype to database, using JDBC program follow the steps given below"
},
{
"code": null,
"e": 1643,
"s": 1611,
"text": "Step 1: Connect to the database"
},
{
"code": null,
"e": 1734,
"s": 1643,
"text": "You can connect to a database using the getConnection() method of the DriverManager class."
},
{
"code": null,
"e": 1936,
"s": 1734,
"text": "Connect to the MySQL database by passing the MySQL URL which is jdbc:mysql://localhost/sampleDB (where sampleDB is the database name), username and password as parameters to the getConnection() method."
},
{
"code": null,
"e": 2065,
"s": 1936,
"text": "String mysqlUrl = \"jdbc:mysql://localhost/sampleDB\";\nConnection con = DriverManager.getConnection(mysqlUrl, \"root\", \"password\");"
},
{
"code": null,
"e": 2101,
"s": 2065,
"text": "Step 2: Create a Prepared statement"
},
{
"code": null,
"e": 2274,
"s": 2101,
"text": "Create a PreparedStatement object using the prepareStatement() method of the Connection interface. To this method pass the insert query (with place holders) as a parameter."
},
{
"code": null,
"e": 2357,
"s": 2274,
"text": "PreparedStatement pstmt = con.prepareStatement(\"INSERT INTO MyTableVALUES(?, ?)\");"
},
{
"code": null,
"e": 2397,
"s": 2357,
"text": "Step 3: Set values to the place holders"
},
{
"code": null,
"e": 2676,
"s": 2397,
"text": "Set the values to the place holders using the setter methods of the PreparedStatement interface. Chose the methods according to the datatype of the column. For Example if the column is of VARCHAR type use setString() method and if it is of INT type you can use setInt() method."
},
{
"code": null,
"e": 2901,
"s": 2676,
"text": "And if it is of Blob type you can set value to it using the setBinaryStream() or setBlob() methods. To these methods pass an integer variable representing the parameter index and an object of InputStream class as parameters."
},
{
"code": null,
"e": 3042,
"s": 2901,
"text": "pstmt.setString(1, \"sample image\");\n//Inserting Blob type\nInputStream in = new FileInputStream(\"E:\\\\images\\\\cat.jpg\");\npstmt.setBlob(2, in);"
},
{
"code": null,
"e": 3072,
"s": 3042,
"text": "Step 4: Execute the statement"
},
{
"code": null,
"e": 3186,
"s": 3072,
"text": "Execute the above created PreparedStatement object using the execute() method of the PreparedStatement interface."
},
{
"code": null,
"e": 3440,
"s": 3186,
"text": "The getBlob() method of the ResultSet interface accepts an integer representing the index of the column (or, a String value representing the name of the column) and retrieves the value at the specified column and returns it in the form of a Blob object."
},
{
"code": null,
"e": 3546,
"s": 3440,
"text": "while(rs.next()) {\n rs.getString(\"Name\");\n rs.getString(\"Type\");\n Blob blob = rs.getBlob(\"Logo\");\n}"
},
{
"code": null,
"e": 3669,
"s": 3546,
"text": "The getBytes() method of the Blob Interface retrieves the contents of the current Blob object and returns as a byte array."
},
{
"code": null,
"e": 3829,
"s": 3669,
"text": "Using the getBlob() method you can get the contents of the blob in to a byte array and create an image using the write() method of the FileOutputStream object."
},
{
"code": null,
"e": 3978,
"s": 3829,
"text": "byte byteArray[] = blob.getBytes(1,(int)blob.length());\nFileOutputStream outPutStream = new FileOutputStream(\"path\");\noutPutStream.write(byteArray);"
},
{
"code": null,
"e": 4126,
"s": 3978,
"text": "Following example creates a table in MySQL database with blob datatype, inserts image to it. Retrieves it back and stores in the local file system."
},
{
"code": null,
"e": 5922,
"s": 4126,
"text": "import java.io.FileInputStream;\nimport java.io.FileOutputStream;\nimport java.sql.Blob;\nimport java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.PreparedStatement;\nimport java.sql.ResultSet;\nimport java.sql.Statement;\npublic class BlobExample {\n public static void main(String args[]) throws Exception {\n //Registering the Driver\n DriverManager.registerDriver(new com.mysql.jdbc.Driver());\n //Getting the connection\n String mysqlUrl = \"jdbc:mysql://localhost/sampleDB\";\n Connection con = DriverManager.getConnection(mysqlUrl, \"root\", \"password\");\n System.out.println(\"Connection established......\");\n //Creating a table\n Statement stmt = con.createStatement();\n stmt.execute(\"CREATE TABLE SampleTable( Name VARCHAR(255), Image BLOB)\");\n System.out.println(\"Table Created\");\n //Inserting values\n String query = \"INSERT INTO SampleTable(Name,image) VALUES (?, ?)\";\n PreparedStatement pstmt = con.prepareStatement(query);\n pstmt.setString(1, \"sample image\");\n FileInputStream fin = new FileInputStream(\"E:\\\\images\\\\cat.jpg\");\n pstmt.setBlob(2, fin);\n pstmt.execute();\n //Retrieving the data\n ResultSet rs = stmt.executeQuery(\"select * from SampleTable\");\n int i = 1;\n System.out.println(\"Contents of the table are: \");\n while(rs.next()) {\n System.out.println(rs.getString(\"Name\"));\n Blob blob = rs.getBlob(\"Image\");\n byte byteArray[] = blob.getBytes(1,(int)blob.length());\n FileOutputStream outPutStream = new\n FileOutputStream(\"E:\\\\images\\\\blob_output\"+i+\".jpg\");\n outPutStream.write(byteArray);\n System.out.println(\"E:\\\\images\\\\blob_output\"+i+\".jpg\");\n System.out.println();\n i++;\n }\n }\n}"
},
{
"code": null,
"e": 6032,
"s": 5922,
"text": "Connection established......\nTable Created\nContents of the table are:\nsample image\nE:\\images\\blob_output1.jpg"
}
] |
MATLAB - Numbers
|
MATLAB supports various numeric classes that include signed and unsigned integers and single-precision and double-precision floating-point numbers. By default, MATLAB stores all numeric values as double-precision floating point numbers.
You can choose to store any number or array of numbers as integers or as single-precision numbers.
All numeric types support basic array operations and mathematical operations.
MATLAB provides the following functions to convert to various numeric data types β
Create a script file and type the following code β
x = single([5.32 3.47 6.28]) .* 7.5
x = double([5.32 3.47 6.28]) .* 7.5
x = int8([5.32 3.47 6.28]) .* 7.5
x = int16([5.32 3.47 6.28]) .* 7.5
x = int32([5.32 3.47 6.28]) .* 7.5
x = int64([5.32 3.47 6.28]) .* 7.5
When you run the file, it shows the following result β
x =
39.900 26.025 47.100
x =
39.900 26.025 47.100
x =
38 23 45
x =
38 23 45
x =
38 23 45
x =
38 23 45
Let us extend the previous example a little more. Create a script file and type the following code β
x = int32([5.32 3.47 6.28]) .* 7.5
x = int64([5.32 3.47 6.28]) .* 7.5
x = num2cell(x)
When you run the file, it shows the following result β
x =
38 23 45
x =
38 23 45
x =
{
[1,1] = 38
[1,2] = 23
[1,3] = 45
}
The functions intmax() and intmin() return the maximum and minimum values that can be represented with all types of integer numbers.
Both the functions take the integer data type as the argument, for example, intmax(int8) or intmin(int64) and return the maximum and minimum values that you can represent with the integer data type.
The following example illustrates how to obtain the smallest and largest values of integers. Create a script file and write the following code in it β
% displaying the smallest and largest signed integer data
str = 'The range for int8 is:\n\t%d to %d ';
sprintf(str, intmin('int8'), intmax('int8'))
str = 'The range for int16 is:\n\t%d to %d ';
sprintf(str, intmin('int16'), intmax('int16'))
str = 'The range for int32 is:\n\t%d to %d ';
sprintf(str, intmin('int32'), intmax('int32'))
str = 'The range for int64 is:\n\t%d to %d ';
sprintf(str, intmin('int64'), intmax('int64'))
% displaying the smallest and largest unsigned integer data
str = 'The range for uint8 is:\n\t%d to %d ';
sprintf(str, intmin('uint8'), intmax('uint8'))
str = 'The range for uint16 is:\n\t%d to %d ';
sprintf(str, intmin('uint16'), intmax('uint16'))
str = 'The range for uint32 is:\n\t%d to %d ';
sprintf(str, intmin('uint32'), intmax('uint32'))
str = 'The range for uint64 is:\n\t%d to %d ';
sprintf(str, intmin('uint64'), intmax('uint64'))
When you run the file, it shows the following result β
ans = The range for int8 is:
-128 to 127
ans = The range for int16 is:
-32768 to 32767
ans = The range for int32 is:
-2147483648 to 2147483647
ans = The range for int64 is:
0 to 0
ans = The range for uint8 is:
0 to 255
ans = The range for uint16 is:
0 to 65535
ans = The range for uint32 is:
0 to -1
ans = The range for uint64 is:
0 to 18446744073709551616
The functions realmax() and realmin() return the maximum and minimum values that can be represented with floating point numbers.
Both the functions when called with the argument 'single', return the maximum and minimum values that you can represent with the single-precision data type and when called with the argument 'double', return the maximum and minimum values that you can represent with the double-precision data type.
The following example illustrates how to obtain the smallest and largest floating point numbers. Create a script file and write the following code in it β
% displaying the smallest and largest single-precision
% floating point number
str = 'The range for single is:\n\t%g to %g and\n\t %g to %g';
sprintf(str, -realmax('single'), -realmin('single'), ...
realmin('single'), realmax('single'))
% displaying the smallest and largest double-precision
% floating point number
str = 'The range for double is:\n\t%g to %g and\n\t %g to %g';
sprintf(str, -realmax('double'), -realmin('double'), ...
realmin('double'), realmax('double'))
When you run the file, it displays the following result β
ans = The range for single is:
-3.40282e+38 to -1.17549e-38 and
1.17549e-38 to 3.40282e+38
ans = The range for double is:
-1.79769e+308 to -2.22507e-308 and
2.22507e-308 to 1.79769e+308
30 Lectures
4 hours
Nouman Azam
127 Lectures
12 hours
Nouman Azam
17 Lectures
3 hours
Sanjeev
37 Lectures
5 hours
TELCOMA Global
22 Lectures
4 hours
TELCOMA Global
18 Lectures
3 hours
Phinite Academy
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2378,
"s": 2141,
"text": "MATLAB supports various numeric classes that include signed and unsigned integers and single-precision and double-precision floating-point numbers. By default, MATLAB stores all numeric values as double-precision floating point numbers."
},
{
"code": null,
"e": 2477,
"s": 2378,
"text": "You can choose to store any number or array of numbers as integers or as single-precision numbers."
},
{
"code": null,
"e": 2555,
"s": 2477,
"text": "All numeric types support basic array operations and mathematical operations."
},
{
"code": null,
"e": 2638,
"s": 2555,
"text": "MATLAB provides the following functions to convert to various numeric data types β"
},
{
"code": null,
"e": 2689,
"s": 2638,
"text": "Create a script file and type the following code β"
},
{
"code": null,
"e": 2900,
"s": 2689,
"text": "x = single([5.32 3.47 6.28]) .* 7.5\nx = double([5.32 3.47 6.28]) .* 7.5\nx = int8([5.32 3.47 6.28]) .* 7.5\nx = int16([5.32 3.47 6.28]) .* 7.5\nx = int32([5.32 3.47 6.28]) .* 7.5\nx = int64([5.32 3.47 6.28]) .* 7.5"
},
{
"code": null,
"e": 2955,
"s": 2900,
"text": "When you run the file, it shows the following result β"
},
{
"code": null,
"e": 3103,
"s": 2955,
"text": "x =\n\n 39.900 26.025 47.100\n\nx =\n\n 39.900 26.025 47.100\n\nx =\n\n 38 23 45\n\nx =\n\n 38 23 45\n\nx =\n\n 38 23 45\n\nx =\n\n 38 23 45\n"
},
{
"code": null,
"e": 3204,
"s": 3103,
"text": "Let us extend the previous example a little more. Create a script file and type the following code β"
},
{
"code": null,
"e": 3290,
"s": 3204,
"text": "x = int32([5.32 3.47 6.28]) .* 7.5\nx = int64([5.32 3.47 6.28]) .* 7.5\nx = num2cell(x)"
},
{
"code": null,
"e": 3345,
"s": 3290,
"text": "When you run the file, it shows the following result β"
},
{
"code": null,
"e": 3437,
"s": 3345,
"text": "x =\n\n 38 23 45\n\nx =\n\n 38 23 45\n\nx = \n{\n [1,1] = 38\n [1,2] = 23\n [1,3] = 45\n}\n"
},
{
"code": null,
"e": 3570,
"s": 3437,
"text": "The functions intmax() and intmin() return the maximum and minimum values that can be represented with all types of integer numbers."
},
{
"code": null,
"e": 3769,
"s": 3570,
"text": "Both the functions take the integer data type as the argument, for example, intmax(int8) or intmin(int64) and return the maximum and minimum values that you can represent with the integer data type."
},
{
"code": null,
"e": 3920,
"s": 3769,
"text": "The following example illustrates how to obtain the smallest and largest values of integers. Create a script file and write the following code in it β"
},
{
"code": null,
"e": 4796,
"s": 3920,
"text": "% displaying the smallest and largest signed integer data\nstr = 'The range for int8 is:\\n\\t%d to %d ';\nsprintf(str, intmin('int8'), intmax('int8'))\n\nstr = 'The range for int16 is:\\n\\t%d to %d ';\nsprintf(str, intmin('int16'), intmax('int16'))\n\nstr = 'The range for int32 is:\\n\\t%d to %d ';\nsprintf(str, intmin('int32'), intmax('int32'))\n\nstr = 'The range for int64 is:\\n\\t%d to %d ';\nsprintf(str, intmin('int64'), intmax('int64'))\n \n% displaying the smallest and largest unsigned integer data\nstr = 'The range for uint8 is:\\n\\t%d to %d ';\nsprintf(str, intmin('uint8'), intmax('uint8'))\n\nstr = 'The range for uint16 is:\\n\\t%d to %d ';\nsprintf(str, intmin('uint16'), intmax('uint16'))\n\nstr = 'The range for uint32 is:\\n\\t%d to %d ';\nsprintf(str, intmin('uint32'), intmax('uint32'))\n\nstr = 'The range for uint64 is:\\n\\t%d to %d ';\nsprintf(str, intmin('uint64'), intmax('uint64'))"
},
{
"code": null,
"e": 4851,
"s": 4796,
"text": "When you run the file, it shows the following result β"
},
{
"code": null,
"e": 5225,
"s": 4851,
"text": "ans = The range for int8 is:\n\t-128 to 127 \nans = The range for int16 is:\n\t-32768 to 32767 \nans = The range for int32 is:\n\t-2147483648 to 2147483647 \nans = The range for int64 is:\n\t0 to 0 \nans = The range for uint8 is:\n\t0 to 255 \nans = The range for uint16 is:\n\t0 to 65535 \nans = The range for uint32 is:\n\t0 to -1 \nans = The range for uint64 is:\n\t0 to 18446744073709551616 \n"
},
{
"code": null,
"e": 5354,
"s": 5225,
"text": "The functions realmax() and realmin() return the maximum and minimum values that can be represented with floating point numbers."
},
{
"code": null,
"e": 5652,
"s": 5354,
"text": "Both the functions when called with the argument 'single', return the maximum and minimum values that you can represent with the single-precision data type and when called with the argument 'double', return the maximum and minimum values that you can represent with the double-precision data type."
},
{
"code": null,
"e": 5807,
"s": 5652,
"text": "The following example illustrates how to obtain the smallest and largest floating point numbers. Create a script file and write the following code in it β"
},
{
"code": null,
"e": 6292,
"s": 5807,
"text": "% displaying the smallest and largest single-precision \n% floating point number\nstr = 'The range for single is:\\n\\t%g to %g and\\n\\t %g to %g';\nsprintf(str, -realmax('single'), -realmin('single'), ...\n realmin('single'), realmax('single'))\n\n% displaying the smallest and largest double-precision \n% floating point number\nstr = 'The range for double is:\\n\\t%g to %g and\\n\\t %g to %g';\nsprintf(str, -realmax('double'), -realmin('double'), ...\n realmin('double'), realmax('double'))"
},
{
"code": null,
"e": 6350,
"s": 6292,
"text": "When you run the file, it displays the following result β"
},
{
"code": null,
"e": 6795,
"s": 6350,
"text": "ans = The range for single is: \n -3.40282e+38 to -1.17549e-38 and \n 1.17549e-38 to 3.40282e+38 \nans = The range for double is: \n -1.79769e+308 to -2.22507e-308 and \n 2.22507e-308 to 1.79769e+308\n"
},
{
"code": null,
"e": 6828,
"s": 6795,
"text": "\n 30 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 6841,
"s": 6828,
"text": " Nouman Azam"
},
{
"code": null,
"e": 6876,
"s": 6841,
"text": "\n 127 Lectures \n 12 hours \n"
},
{
"code": null,
"e": 6889,
"s": 6876,
"text": " Nouman Azam"
},
{
"code": null,
"e": 6922,
"s": 6889,
"text": "\n 17 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 6931,
"s": 6922,
"text": " Sanjeev"
},
{
"code": null,
"e": 6964,
"s": 6931,
"text": "\n 37 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 6980,
"s": 6964,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 7013,
"s": 6980,
"text": "\n 22 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 7029,
"s": 7013,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 7062,
"s": 7029,
"text": "\n 18 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 7079,
"s": 7062,
"text": " Phinite Academy"
},
{
"code": null,
"e": 7086,
"s": 7079,
"text": " Print"
},
{
"code": null,
"e": 7097,
"s": 7086,
"text": " Add Notes"
}
] |
Build a Restricted Boltzmann Machine (RBM) as a recommendation system for Movie Review | Towards Data Science
|
This article is Part 2 of how to build a Restricted Boltzmann Machine (RBM) as a recommendation system.
In Part 1, we focus on data processing, and here the focus is on model creation. What you will learn is how to create an RBM model from scratch. It is split into 3 parts.
Model buildingModel trainingModel testing
Model building
Model training
Model testing
π£π£ This is a technical-driven article. Now letβs begin the journey πββοΈπββοΈ.
Model building
Model building
Essentially, RBM is a probabilistic graphical model.
To build the model architecture, we will create a class for RBM. In the class, define all parameters for RBM, including the number of hidden nodes, the weights, and bias for the probability of the visible nodes and the hidden node.
There are 4 functions, 1st is to initialize the class, 2nd function is to sample the probabilities of hidden nodes given visible nodes, and 3rd function is to sample the probabilities of visible nodes given hidden nodes, the final one is to train the model.
1.1 __init__ function
Inside the __init__ function, we will initialize all parameters that need to be optimized. Note, nv and nh are the numbers of visible nodes and the number of hidden nodes, respectively. W is the weights for the visible nodes and hidden nodes. We use a normal distribution with mean 0 and variance 1 to initialize weights and bias. a is the bias for the probability of hidden nodes given visible node, and b is the bias for the probability of visible nodes given hidden nodes. Note we added a dimension for the batch because the function we will use in Pytorch cannot accept vectors with only 1 dimension.
class RBM(): def __init__(self, nv, nh): self.W = torch.randn(nh, nv) self.a = torch.randn(1, nh) self.b = torch.randn(1, nb)
1.2 Hidden node sampling function
This function is about sampling hidden nodes given the probabilities of visible nodes. Why do we need this? Because we need the probabilities to sample the activation of the hidden nodes.
Suppose we have 100 hidden nodes, this function will sample the activation of the hidden nodes, namely activating them based on certain probability p_h_given_v. p_h_given_v is the probability of hidden nodes equal to one (activated) given the values of v.
Note the function takes argument x, which is the value of visible nodes. We use v to calculate the probability of hidden nodes. Remember, the probability of h given v (p_h_given_v) is the sigmoid activation of v. Thus, we multiply the value of visible nodes with the weights, plus the bias of the hidden nodes. We expanded the dimension for bias a to have the same dimension as wx, so that bias is added to each line of wx.
def sample_h(self, x): wx = torch.mm(x, self.W.t()) activation = wx + self.a.expand(wx) p_h_given_v =torch.sigmoid(activation) reutrn p_h_given_v, torch.bernoulli(p_h_given_v)
Note what is returned is p_h_given_v, and the sampled hidden nodes. Here, we are making a Bernoulli RBM, as we are predicting a binary outcome, that is, users like or not like a movie. Assuming there are 100 hidden nodes, p_h_given_v is a vector of 100 elements, with each element as the probability of each hidden node being activated, given the values of visible nodes (namely, movie ratings by a user). But the question is how to activate the hidden nodes? Here we use Bernoulli sampling. Suppose, for a hidden node, its probability in p_h_given_v is 70%. We take a random number between 0 and 1. If it is below 70%, we will not activate the hidden node. By repeating Bernoulli sampling for all hidden nodes in p_h_given_v, we get a vector of zeros and ones with one corresponding to hidden nodes to be activated.
This is the first function we need for Gibbs sampling β¨β¨.
1.3 Visible node sampling function
Following the same logic, we create the function to sample visible nodes. Given the values of hidden nodes (1 or 0, activated or not), we estimate the probabilities of visible nodes p_v_given_h, which is the probabilities of each visible node equal to 1 (being activated).
Since there are 1682 movies and thus1682 visible nodes, we have a vector of 1682 probabilities, each corresponding to visible node equal to one, given the activation of the hidden nodes. We use Bernoulli sampling to decide if this visible node will be sampled or not. In the end, the function returns probabilities of visible nodes p_v_given_h, and a vector of ones and zeros with one corresponding to visible nodes to be activated.
def sample_v(self, y): wy = torch.mm(y, self.W) activation = wy + self.b.expand(wy) p_v_given_h =torch.sigmoid(activation) reutrn p_v_given_h, torch.bernoulli(p_v_given_h)
1.4 Contrastive divergence function
RBM is an energy-based model which means we need to minimize the energy function.
The energy function depends on the weights of the model, and thus we need to optimize the weights. On the other hand, RBM can be taken as a probabilistic graphical model, which requires maximizing the log-likelihood of the training set. Obviously, for any neural network, to minimize the energy or maximize the log-likelihood, we need to compute the gradient. Here we use Contrastive Divergence to approximate the likelihood gradient.
Contrastive divergence is about approximating the log-likelihood gradient. Instead of direct computation of gradient which requires heavy computation resources, we approximate the gradient. During training, we adjust the weights in the direction of minimizing energy. Similar to minimizing loss function through gradient descent where we update the weights to minimize the loss, the only difference is we approximate the gradient using an algorithm, Contrastive Divergence.
Specifically, we start with input vector v0, based on the probability of p_h_given_v, we sample the first set of hidden nodes at the first iteration and use these sampled hidden nodes to sample visible nodes v1 with p_v_given_h. Repeat this process K times, and that is all about k-step Contrastive Divergence.
In this function, we will update the weights, the bias for visible nodes, and for hidden nodes using the algorithm outlined in this paper. I strongly recommend this RBM paper if you like a more in-depth understanding.
Inside the function, v0 is the input vector containing the ratings of all movies by a user. vk is the visible nodes obtained after k samplings from visible nodes to hidden nodes. ph0 is the vector of probabilities of hidden node equal to one at the first iteration given v0. phk is the probabilities of hidden nodes given visible nodes vk at the kth iteration.
def train(self, v0, vk, ph0, phk): self.W += torch.mm(v0.t(), ph0) β torch.mm(vk.t(), phk) self.b += torch.sum((v0 β vk), 0) self.a += torch.sum((ph0 β phk), 0)
1.5 RBM object creation
To initialize the RBM, we create an object of RBM class. First, we need the number of visible nodes, which is the number of total movies. The number of hidden nodes corresponds to the number of features we want to detect from the movies. It is hard to tell the optimal number of features. But this parameter is tunable, so we start with 100. We also define the batch size, which is the number of observations in a batch we use to update the weights. Again we start with 100.
nv = len(training_set[0]) nh = 100 batch_size = 100 rbm = RBM(nv, nh)
2. Model training
Congratulations if you made through Part 1 as that is the most difficult part ππ. Now letβs train the RBM model.
We set nb_epoch as 10 to start with. For each epoch, all observations will go into the network and update the weights after each batch passed through the network. In the end, we get final visible nodes with new ratings for the movies which were not rated originally. Inside each batch, we will make the k steps contrastive divergence to predict the visible nodes after k steps of random walks. Thus, we will have 3 for loops, one for epoch iteration and one for batch iteration, and a final one for contrastive divergence.
For the loss function, we will measure the difference between the predicted ratings and the real ratings in the training set. There are a few options, including RMSE which is the root of the mean of the square difference between the predicted ratings and the real ratings, and the absolute difference between the predicted ratings and the real ratings. We will take an absolute difference here.
Inside the batch loop, we have input vector vk, which will be updated through contrastive divergence and as the output of Gibbs sampling after k steps of a random walk. But at the start, vk is the input batch of all ratings of the users in a batch. v0 is the target which will be compared with predictions, which are the ratings that were rated already by the users in the batch. ph0 is the initial probabilities of hidden nodes given visible nodes v0.
Inside the contrastive divergence loop, we will make the Gibbs sampling. Basically, it consists of making Gibbs chain which is several round trips from the visible nodes to the hidden nodes. In each round, visible nodes are updated to get a good prediction. Starting from the visible nodes vk, we sample the hidden nodes with a Bernoulli sampling. At the end of 10 random walks, we get the 10th sampled visible nodes. Note, we will not train RBM on ratings that were -1 which are not existing as real rating at the beginning.
With v0, vk, ph0, phk, we can apply the train function to update the weights and biases. Eventually, the probabilities that are most relevant to the movie features will get the largest weights, leading to correct predictions. At the end of each batch, we log the training loss. Again, we only record the loss on ratings that were existent.
nb_epoch = 10for epoch in range(1, nb_epoch+1): train_loss = 0 s = 0. for id_user in range(0, nb_users β batch_size, 100): vk = training_set[id_user: id_user+batch_size] v0 = training_set[id_user: id_user+batch_size] ph0, = rbm.sample_h(v0) for k in range(10): _, hk = rbm.sample_h(vk) _, vk = rbm.sample_v(hk) vk[v0<0] = v0[v0<0] phk, _ = rbm.sample_h(vk) rbm.train(v0, vk, ph0, phk) train_loss += torch.mean(torch.abs(v0[v0>0]-vk[v0>0])) s += 1 print(βepoch: β+str(epoch)+β loss: β+str(train_loss/s))
After 10 epoch iteration of training, we got a loss of 0.15. Quite a decent accuracy ββ.
3. Model testing
Compared to the training loops, we remove the epoch iteration and batch iteration. We will loop each observation through the RBM and make a prediction one by one, accumulating the loss for each prediction.
Note below, we use the training_set as the input to activate the RBM, the same training set used to train the RBM. But the difference is that in the testing stage, we did not remove ratings which were not rated by the user originally, because these are unknown inputs for a model for testing purpose. Also notice, we did not perform 10 steps of random walks as in the training stage. This is because for testing to obtain the best prediction, 1 step is better than 10 iterations.
test_loss = 0s = 0.for id_user in range(0, nb_users): v_input = training_set[id_user: id_user+1] v_target = test_set[id_user: id_user+1] if len(v_target(v_target>=0)): _, h = rbm.sample_h(v_input) _, v_input = rbm.sample_v(h) test_loss += torch.mean(torch.abs(v_target[v_target>0]- v_input[v_target>0])) s += 1print(βtest loss: β +str(test_loss/s))
Great. We obtained a loss of 0.16, close to the training loss, indicating a minor over-fitting.
Thatβs all. Hopefully, this gives a sense of how to create an RBM as a recommendation system. If you need the source code, visit my Github page π€π€.
|
[
{
"code": null,
"e": 276,
"s": 172,
"text": "This article is Part 2 of how to build a Restricted Boltzmann Machine (RBM) as a recommendation system."
},
{
"code": null,
"e": 447,
"s": 276,
"text": "In Part 1, we focus on data processing, and here the focus is on model creation. What you will learn is how to create an RBM model from scratch. It is split into 3 parts."
},
{
"code": null,
"e": 489,
"s": 447,
"text": "Model buildingModel trainingModel testing"
},
{
"code": null,
"e": 504,
"s": 489,
"text": "Model building"
},
{
"code": null,
"e": 519,
"s": 504,
"text": "Model training"
},
{
"code": null,
"e": 533,
"s": 519,
"text": "Model testing"
},
{
"code": null,
"e": 610,
"s": 533,
"text": "π£π£ This is a technical-driven article. Now letβs begin the journey πββοΈπββοΈ."
},
{
"code": null,
"e": 625,
"s": 610,
"text": "Model building"
},
{
"code": null,
"e": 640,
"s": 625,
"text": "Model building"
},
{
"code": null,
"e": 693,
"s": 640,
"text": "Essentially, RBM is a probabilistic graphical model."
},
{
"code": null,
"e": 925,
"s": 693,
"text": "To build the model architecture, we will create a class for RBM. In the class, define all parameters for RBM, including the number of hidden nodes, the weights, and bias for the probability of the visible nodes and the hidden node."
},
{
"code": null,
"e": 1183,
"s": 925,
"text": "There are 4 functions, 1st is to initialize the class, 2nd function is to sample the probabilities of hidden nodes given visible nodes, and 3rd function is to sample the probabilities of visible nodes given hidden nodes, the final one is to train the model."
},
{
"code": null,
"e": 1205,
"s": 1183,
"text": "1.1 __init__ function"
},
{
"code": null,
"e": 1810,
"s": 1205,
"text": "Inside the __init__ function, we will initialize all parameters that need to be optimized. Note, nv and nh are the numbers of visible nodes and the number of hidden nodes, respectively. W is the weights for the visible nodes and hidden nodes. We use a normal distribution with mean 0 and variance 1 to initialize weights and bias. a is the bias for the probability of hidden nodes given visible node, and b is the bias for the probability of visible nodes given hidden nodes. Note we added a dimension for the batch because the function we will use in Pytorch cannot accept vectors with only 1 dimension."
},
{
"code": null,
"e": 1960,
"s": 1810,
"text": "class RBM(): def __init__(self, nv, nh): self.W = torch.randn(nh, nv) self.a = torch.randn(1, nh) self.b = torch.randn(1, nb)"
},
{
"code": null,
"e": 1994,
"s": 1960,
"text": "1.2 Hidden node sampling function"
},
{
"code": null,
"e": 2182,
"s": 1994,
"text": "This function is about sampling hidden nodes given the probabilities of visible nodes. Why do we need this? Because we need the probabilities to sample the activation of the hidden nodes."
},
{
"code": null,
"e": 2438,
"s": 2182,
"text": "Suppose we have 100 hidden nodes, this function will sample the activation of the hidden nodes, namely activating them based on certain probability p_h_given_v. p_h_given_v is the probability of hidden nodes equal to one (activated) given the values of v."
},
{
"code": null,
"e": 2862,
"s": 2438,
"text": "Note the function takes argument x, which is the value of visible nodes. We use v to calculate the probability of hidden nodes. Remember, the probability of h given v (p_h_given_v) is the sigmoid activation of v. Thus, we multiply the value of visible nodes with the weights, plus the bias of the hidden nodes. We expanded the dimension for bias a to have the same dimension as wx, so that bias is added to each line of wx."
},
{
"code": null,
"e": 3050,
"s": 2862,
"text": "def sample_h(self, x): wx = torch.mm(x, self.W.t()) activation = wx + self.a.expand(wx) p_h_given_v =torch.sigmoid(activation) reutrn p_h_given_v, torch.bernoulli(p_h_given_v)"
},
{
"code": null,
"e": 3867,
"s": 3050,
"text": "Note what is returned is p_h_given_v, and the sampled hidden nodes. Here, we are making a Bernoulli RBM, as we are predicting a binary outcome, that is, users like or not like a movie. Assuming there are 100 hidden nodes, p_h_given_v is a vector of 100 elements, with each element as the probability of each hidden node being activated, given the values of visible nodes (namely, movie ratings by a user). But the question is how to activate the hidden nodes? Here we use Bernoulli sampling. Suppose, for a hidden node, its probability in p_h_given_v is 70%. We take a random number between 0 and 1. If it is below 70%, we will not activate the hidden node. By repeating Bernoulli sampling for all hidden nodes in p_h_given_v, we get a vector of zeros and ones with one corresponding to hidden nodes to be activated."
},
{
"code": null,
"e": 3925,
"s": 3867,
"text": "This is the first function we need for Gibbs sampling β¨β¨."
},
{
"code": null,
"e": 3960,
"s": 3925,
"text": "1.3 Visible node sampling function"
},
{
"code": null,
"e": 4233,
"s": 3960,
"text": "Following the same logic, we create the function to sample visible nodes. Given the values of hidden nodes (1 or 0, activated or not), we estimate the probabilities of visible nodes p_v_given_h, which is the probabilities of each visible node equal to 1 (being activated)."
},
{
"code": null,
"e": 4666,
"s": 4233,
"text": "Since there are 1682 movies and thus1682 visible nodes, we have a vector of 1682 probabilities, each corresponding to visible node equal to one, given the activation of the hidden nodes. We use Bernoulli sampling to decide if this visible node will be sampled or not. In the end, the function returns probabilities of visible nodes p_v_given_h, and a vector of ones and zeros with one corresponding to visible nodes to be activated."
},
{
"code": null,
"e": 4850,
"s": 4666,
"text": "def sample_v(self, y): wy = torch.mm(y, self.W) activation = wy + self.b.expand(wy) p_v_given_h =torch.sigmoid(activation) reutrn p_v_given_h, torch.bernoulli(p_v_given_h)"
},
{
"code": null,
"e": 4886,
"s": 4850,
"text": "1.4 Contrastive divergence function"
},
{
"code": null,
"e": 4968,
"s": 4886,
"text": "RBM is an energy-based model which means we need to minimize the energy function."
},
{
"code": null,
"e": 5403,
"s": 4968,
"text": "The energy function depends on the weights of the model, and thus we need to optimize the weights. On the other hand, RBM can be taken as a probabilistic graphical model, which requires maximizing the log-likelihood of the training set. Obviously, for any neural network, to minimize the energy or maximize the log-likelihood, we need to compute the gradient. Here we use Contrastive Divergence to approximate the likelihood gradient."
},
{
"code": null,
"e": 5877,
"s": 5403,
"text": "Contrastive divergence is about approximating the log-likelihood gradient. Instead of direct computation of gradient which requires heavy computation resources, we approximate the gradient. During training, we adjust the weights in the direction of minimizing energy. Similar to minimizing loss function through gradient descent where we update the weights to minimize the loss, the only difference is we approximate the gradient using an algorithm, Contrastive Divergence."
},
{
"code": null,
"e": 6188,
"s": 5877,
"text": "Specifically, we start with input vector v0, based on the probability of p_h_given_v, we sample the first set of hidden nodes at the first iteration and use these sampled hidden nodes to sample visible nodes v1 with p_v_given_h. Repeat this process K times, and that is all about k-step Contrastive Divergence."
},
{
"code": null,
"e": 6406,
"s": 6188,
"text": "In this function, we will update the weights, the bias for visible nodes, and for hidden nodes using the algorithm outlined in this paper. I strongly recommend this RBM paper if you like a more in-depth understanding."
},
{
"code": null,
"e": 6767,
"s": 6406,
"text": "Inside the function, v0 is the input vector containing the ratings of all movies by a user. vk is the visible nodes obtained after k samplings from visible nodes to hidden nodes. ph0 is the vector of probabilities of hidden node equal to one at the first iteration given v0. phk is the probabilities of hidden nodes given visible nodes vk at the kth iteration."
},
{
"code": null,
"e": 6937,
"s": 6767,
"text": "def train(self, v0, vk, ph0, phk): self.W += torch.mm(v0.t(), ph0) β torch.mm(vk.t(), phk) self.b += torch.sum((v0 β vk), 0) self.a += torch.sum((ph0 β phk), 0)"
},
{
"code": null,
"e": 6961,
"s": 6937,
"text": "1.5 RBM object creation"
},
{
"code": null,
"e": 7436,
"s": 6961,
"text": "To initialize the RBM, we create an object of RBM class. First, we need the number of visible nodes, which is the number of total movies. The number of hidden nodes corresponds to the number of features we want to detect from the movies. It is hard to tell the optimal number of features. But this parameter is tunable, so we start with 100. We also define the batch size, which is the number of observations in a batch we use to update the weights. Again we start with 100."
},
{
"code": null,
"e": 7506,
"s": 7436,
"text": "nv = len(training_set[0]) nh = 100 batch_size = 100 rbm = RBM(nv, nh)"
},
{
"code": null,
"e": 7524,
"s": 7506,
"text": "2. Model training"
},
{
"code": null,
"e": 7637,
"s": 7524,
"text": "Congratulations if you made through Part 1 as that is the most difficult part ππ. Now letβs train the RBM model."
},
{
"code": null,
"e": 8160,
"s": 7637,
"text": "We set nb_epoch as 10 to start with. For each epoch, all observations will go into the network and update the weights after each batch passed through the network. In the end, we get final visible nodes with new ratings for the movies which were not rated originally. Inside each batch, we will make the k steps contrastive divergence to predict the visible nodes after k steps of random walks. Thus, we will have 3 for loops, one for epoch iteration and one for batch iteration, and a final one for contrastive divergence."
},
{
"code": null,
"e": 8555,
"s": 8160,
"text": "For the loss function, we will measure the difference between the predicted ratings and the real ratings in the training set. There are a few options, including RMSE which is the root of the mean of the square difference between the predicted ratings and the real ratings, and the absolute difference between the predicted ratings and the real ratings. We will take an absolute difference here."
},
{
"code": null,
"e": 9008,
"s": 8555,
"text": "Inside the batch loop, we have input vector vk, which will be updated through contrastive divergence and as the output of Gibbs sampling after k steps of a random walk. But at the start, vk is the input batch of all ratings of the users in a batch. v0 is the target which will be compared with predictions, which are the ratings that were rated already by the users in the batch. ph0 is the initial probabilities of hidden nodes given visible nodes v0."
},
{
"code": null,
"e": 9534,
"s": 9008,
"text": "Inside the contrastive divergence loop, we will make the Gibbs sampling. Basically, it consists of making Gibbs chain which is several round trips from the visible nodes to the hidden nodes. In each round, visible nodes are updated to get a good prediction. Starting from the visible nodes vk, we sample the hidden nodes with a Bernoulli sampling. At the end of 10 random walks, we get the 10th sampled visible nodes. Note, we will not train RBM on ratings that were -1 which are not existing as real rating at the beginning."
},
{
"code": null,
"e": 9874,
"s": 9534,
"text": "With v0, vk, ph0, phk, we can apply the train function to update the weights and biases. Eventually, the probabilities that are most relevant to the movie features will get the largest weights, leading to correct predictions. At the end of each batch, we log the training loss. Again, we only record the loss on ratings that were existent."
},
{
"code": null,
"e": 10472,
"s": 9874,
"text": "nb_epoch = 10for epoch in range(1, nb_epoch+1): train_loss = 0 s = 0. for id_user in range(0, nb_users β batch_size, 100): vk = training_set[id_user: id_user+batch_size] v0 = training_set[id_user: id_user+batch_size] ph0, = rbm.sample_h(v0) for k in range(10): _, hk = rbm.sample_h(vk) _, vk = rbm.sample_v(hk) vk[v0<0] = v0[v0<0] phk, _ = rbm.sample_h(vk) rbm.train(v0, vk, ph0, phk) train_loss += torch.mean(torch.abs(v0[v0>0]-vk[v0>0])) s += 1 print(βepoch: β+str(epoch)+β loss: β+str(train_loss/s))"
},
{
"code": null,
"e": 10561,
"s": 10472,
"text": "After 10 epoch iteration of training, we got a loss of 0.15. Quite a decent accuracy ββ."
},
{
"code": null,
"e": 10578,
"s": 10561,
"text": "3. Model testing"
},
{
"code": null,
"e": 10784,
"s": 10578,
"text": "Compared to the training loops, we remove the epoch iteration and batch iteration. We will loop each observation through the RBM and make a prediction one by one, accumulating the loss for each prediction."
},
{
"code": null,
"e": 11264,
"s": 10784,
"text": "Note below, we use the training_set as the input to activate the RBM, the same training set used to train the RBM. But the difference is that in the testing stage, we did not remove ratings which were not rated by the user originally, because these are unknown inputs for a model for testing purpose. Also notice, we did not perform 10 steps of random walks as in the training stage. This is because for testing to obtain the best prediction, 1 step is better than 10 iterations."
},
{
"code": null,
"e": 11692,
"s": 11264,
"text": "test_loss = 0s = 0.for id_user in range(0, nb_users): v_input = training_set[id_user: id_user+1] v_target = test_set[id_user: id_user+1] if len(v_target(v_target>=0)): _, h = rbm.sample_h(v_input) _, v_input = rbm.sample_v(h) test_loss += torch.mean(torch.abs(v_target[v_target>0]- v_input[v_target>0])) s += 1print(βtest loss: β +str(test_loss/s))"
},
{
"code": null,
"e": 11788,
"s": 11692,
"text": "Great. We obtained a loss of 0.16, close to the training loss, indicating a minor over-fitting."
}
] |
How to perform back and refresh in a browser in Selenium with python?
|
We can perform back and refresh in the browser in Selenium.
For performing back operation in the browser, the back method is to be used.
For refreshing the browser, refresh method is to be used.
Both these methods can be used for testing browser navigations and reloading of web pages.
Code Implementation
from selenium import webdriver
#browser exposes an executable file
#Through Selenium test we will invoke the executable file which will then #invoke actual browser
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
# to maximize the browser window
driver.maximize_window()
#get method to launch the URL
driver.get("https://www.tutorialspoint.com/index.htm")
# to print the page title in console
print(driver.title)
# to print the current URL in console
print(driver.current_url)
#get method to launch another URL
driver.get("https://www.tutorialspoint.com/questions/index.php")
# to go back to the previous URL
driver.back()
#to refresh the browser
driver.refresh()
#to close the browser
driver.close()
|
[
{
"code": null,
"e": 1122,
"s": 1062,
"text": "We can perform back and refresh in the browser in Selenium."
},
{
"code": null,
"e": 1199,
"s": 1122,
"text": "For performing back operation in the browser, the back method is to be used."
},
{
"code": null,
"e": 1257,
"s": 1199,
"text": "For refreshing the browser, refresh method is to be used."
},
{
"code": null,
"e": 1348,
"s": 1257,
"text": "Both these methods can be used for testing browser navigations and reloading of web pages."
},
{
"code": null,
"e": 1368,
"s": 1348,
"text": "Code Implementation"
},
{
"code": null,
"e": 2086,
"s": 1368,
"text": "from selenium import webdriver\n#browser exposes an executable file\n#Through Selenium test we will invoke the executable file which will then #invoke actual browser\ndriver = webdriver.Chrome(executable_path=\"C:\\\\chromedriver.exe\")\n# to maximize the browser window\ndriver.maximize_window()\n#get method to launch the URL\ndriver.get(\"https://www.tutorialspoint.com/index.htm\")\n# to print the page title in console\nprint(driver.title)\n# to print the current URL in console\nprint(driver.current_url)\n#get method to launch another URL\ndriver.get(\"https://www.tutorialspoint.com/questions/index.php\")\n# to go back to the previous URL\ndriver.back()\n#to refresh the browser\ndriver.refresh()\n#to close the browser\ndriver.close()"
}
] |
Python | Working with date and time using Pandas - GeeksforGeeks
|
10 Mar, 2022
While working with data, encountering time series data is very usual. Pandas is a very useful tool while working with time series data.
Pandas provide a different set of tools using which we can perform all the necessary tasks on date-time data. Letβs try to understand with the examples discussed below.
Code #1: Create a dates dataframe
Python3
import pandas as pd # Create dates dataframe with frequency data = pd.date_range('1/1/2011', periods = 10, freq ='H') data
Output:
Code #2: Create range of dates and show basic features
Python3
# Create date and time with dataframedata = pd.date_range('1/1/2011', periods = 10, freq ='H') x = pd.datetime.now()x.month, x.year
Output:
(9, 2018)
Datetime features can be divided into two categories. The first one time moments in a period and second the time passed since a particular period. These features can be very useful to understand the patterns in the data.
Divide a given date into features β
pandas.Series.dt.year returns the year of the date time. pandas.Series.dt.month returns the month of the date time. pandas.Series.dt.day returns the day of the date time. pandas.Series.dt.hour returns the hour of the date time. pandas.Series.dt.minute returns the minute of the date time.Refer all datetime properties from here.
Code #3: Break date and time into separate features
Python3
# Create date and time with dataframerng = pd.DataFrame()rng['date'] = pd.date_range('1/1/2011', periods = 72, freq ='H') # Print the dates in dd-mm-yy formatrng[:5] # Create features for year, month, day, hour, and minuterng['year'] = rng['date'].dt.yearrng['month'] = rng['date'].dt.monthrng['day'] = rng['date'].dt.dayrng['hour'] = rng['date'].dt.hourrng['minute'] = rng['date'].dt.minute # Print the dates divided into featuresrng.head(3)
Output:
Code #4: To get the present time, use Timestamp.now() and then convert timestamp to datetime and directly access year, month or day.
Python3
# Input present datetime using Timestampt = pandas.tslib.Timestamp.now()t
Timestamp('2018-09-18 17:18:49.101496')
Python3
# Convert timestamp to datetimet.to_datetime()
datetime.datetime(2018, 9, 18, 17, 18, 49, 101496)
Python3
# Directly access and print the featurest.yeart.montht.dayt.hourt.minutet.second
2018
8
25
15
53
Letβs analyze this problem on a real dataset uforeports.
Python3
import pandas as pd url = 'http://bit.ly/uforeports' # read csv filedf = pd.read_csv(url) df.head()
Output:
Python3
# Convert the Time column to datetime formatdf['Time'] = pd.to_datetime(df.Time) df.head()
Python3
# shows the type of each column datadf.dtypes
City object
Colors Reported object
Shape Reported object
State object
Time datetime64[ns]
dtype: object
Python3
# Get hour detail from time datadf.Time.dt.hour.head()
0 22
1 20
2 14
3 13
4 19
Name: Time, dtype: int64
Python3
# Get name of each datedf.Time.dt.weekday_name.head()
0 Sunday
1 Monday
2 Sunday
3 Monday
4 Tuesday
Name: Time, dtype: object
Python3
# Get ordinal day of the yeardf.Time.dt.dayofyear.head()
0 152
1 181
2 46
3 152
4 108
Name: Time, dtype: int64
Akanksha_Rai
simmytarika5
tarunkmkumar
Python pandas-datetime
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
|
[
{
"code": null,
"e": 41163,
"s": 41135,
"text": "\n10 Mar, 2022"
},
{
"code": null,
"e": 41300,
"s": 41163,
"text": "While working with data, encountering time series data is very usual. Pandas is a very useful tool while working with time series data. "
},
{
"code": null,
"e": 41469,
"s": 41300,
"text": "Pandas provide a different set of tools using which we can perform all the necessary tasks on date-time data. Letβs try to understand with the examples discussed below."
},
{
"code": null,
"e": 41504,
"s": 41469,
"text": "Code #1: Create a dates dataframe "
},
{
"code": null,
"e": 41512,
"s": 41504,
"text": "Python3"
},
{
"code": "import pandas as pd # Create dates dataframe with frequency data = pd.date_range('1/1/2011', periods = 10, freq ='H') data",
"e": 41635,
"s": 41512,
"text": null
},
{
"code": null,
"e": 41644,
"s": 41635,
"text": "Output: "
},
{
"code": null,
"e": 41701,
"s": 41644,
"text": " Code #2: Create range of dates and show basic features "
},
{
"code": null,
"e": 41709,
"s": 41701,
"text": "Python3"
},
{
"code": "# Create date and time with dataframedata = pd.date_range('1/1/2011', periods = 10, freq ='H') x = pd.datetime.now()x.month, x.year",
"e": 41841,
"s": 41709,
"text": null
},
{
"code": null,
"e": 41849,
"s": 41841,
"text": "Output:"
},
{
"code": null,
"e": 41859,
"s": 41849,
"text": "(9, 2018)"
},
{
"code": null,
"e": 42080,
"s": 41859,
"text": "Datetime features can be divided into two categories. The first one time moments in a period and second the time passed since a particular period. These features can be very useful to understand the patterns in the data."
},
{
"code": null,
"e": 42117,
"s": 42080,
"text": "Divide a given date into features β "
},
{
"code": null,
"e": 42446,
"s": 42117,
"text": "pandas.Series.dt.year returns the year of the date time. pandas.Series.dt.month returns the month of the date time. pandas.Series.dt.day returns the day of the date time. pandas.Series.dt.hour returns the hour of the date time. pandas.Series.dt.minute returns the minute of the date time.Refer all datetime properties from here."
},
{
"code": null,
"e": 42500,
"s": 42446,
"text": "Code #3: Break date and time into separate features "
},
{
"code": null,
"e": 42508,
"s": 42500,
"text": "Python3"
},
{
"code": "# Create date and time with dataframerng = pd.DataFrame()rng['date'] = pd.date_range('1/1/2011', periods = 72, freq ='H') # Print the dates in dd-mm-yy formatrng[:5] # Create features for year, month, day, hour, and minuterng['year'] = rng['date'].dt.yearrng['month'] = rng['date'].dt.monthrng['day'] = rng['date'].dt.dayrng['hour'] = rng['date'].dt.hourrng['minute'] = rng['date'].dt.minute # Print the dates divided into featuresrng.head(3)",
"e": 42951,
"s": 42508,
"text": null
},
{
"code": null,
"e": 42960,
"s": 42951,
"text": "Output: "
},
{
"code": null,
"e": 43093,
"s": 42960,
"text": "Code #4: To get the present time, use Timestamp.now() and then convert timestamp to datetime and directly access year, month or day."
},
{
"code": null,
"e": 43101,
"s": 43093,
"text": "Python3"
},
{
"code": "# Input present datetime using Timestampt = pandas.tslib.Timestamp.now()t",
"e": 43175,
"s": 43101,
"text": null
},
{
"code": null,
"e": 43215,
"s": 43175,
"text": "Timestamp('2018-09-18 17:18:49.101496')"
},
{
"code": null,
"e": 43223,
"s": 43215,
"text": "Python3"
},
{
"code": "# Convert timestamp to datetimet.to_datetime()",
"e": 43270,
"s": 43223,
"text": null
},
{
"code": null,
"e": 43321,
"s": 43270,
"text": "datetime.datetime(2018, 9, 18, 17, 18, 49, 101496)"
},
{
"code": null,
"e": 43329,
"s": 43321,
"text": "Python3"
},
{
"code": "# Directly access and print the featurest.yeart.montht.dayt.hourt.minutet.second",
"e": 43410,
"s": 43329,
"text": null
},
{
"code": null,
"e": 43426,
"s": 43410,
"text": "2018\n8\n25\n15\n53"
},
{
"code": null,
"e": 43484,
"s": 43426,
"text": "Letβs analyze this problem on a real dataset uforeports. "
},
{
"code": null,
"e": 43492,
"s": 43484,
"text": "Python3"
},
{
"code": "import pandas as pd url = 'http://bit.ly/uforeports' # read csv filedf = pd.read_csv(url) df.head()",
"e": 43601,
"s": 43492,
"text": null
},
{
"code": null,
"e": 43610,
"s": 43601,
"text": "Output: "
},
{
"code": null,
"e": 43618,
"s": 43610,
"text": "Python3"
},
{
"code": "# Convert the Time column to datetime formatdf['Time'] = pd.to_datetime(df.Time) df.head()",
"e": 43709,
"s": 43618,
"text": null
},
{
"code": null,
"e": 43717,
"s": 43709,
"text": "Python3"
},
{
"code": "# shows the type of each column datadf.dtypes",
"e": 43763,
"s": 43717,
"text": null
},
{
"code": null,
"e": 43947,
"s": 43763,
"text": "City object\nColors Reported object\nShape Reported object\nState object\nTime datetime64[ns]\ndtype: object"
},
{
"code": null,
"e": 43955,
"s": 43947,
"text": "Python3"
},
{
"code": "# Get hour detail from time datadf.Time.dt.hour.head()",
"e": 44010,
"s": 43955,
"text": null
},
{
"code": null,
"e": 44075,
"s": 44010,
"text": "0 22\n1 20\n2 14\n3 13\n4 19\nName: Time, dtype: int64"
},
{
"code": null,
"e": 44083,
"s": 44075,
"text": "Python3"
},
{
"code": "# Get name of each datedf.Time.dt.weekday_name.head()",
"e": 44137,
"s": 44083,
"text": null
},
{
"code": null,
"e": 44228,
"s": 44137,
"text": "0 Sunday\n1 Monday\n2 Sunday\n3 Monday\n4 Tuesday\nName: Time, dtype: object"
},
{
"code": null,
"e": 44236,
"s": 44228,
"text": "Python3"
},
{
"code": "# Get ordinal day of the yeardf.Time.dt.dayofyear.head()",
"e": 44293,
"s": 44236,
"text": null
},
{
"code": null,
"e": 44363,
"s": 44293,
"text": "0 152\n1 181\n2 46\n3 152\n4 108\nName: Time, dtype: int64"
},
{
"code": null,
"e": 44376,
"s": 44363,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 44389,
"s": 44376,
"text": "simmytarika5"
},
{
"code": null,
"e": 44402,
"s": 44389,
"text": "tarunkmkumar"
},
{
"code": null,
"e": 44425,
"s": 44402,
"text": "Python pandas-datetime"
},
{
"code": null,
"e": 44439,
"s": 44425,
"text": "Python-pandas"
},
{
"code": null,
"e": 44446,
"s": 44439,
"text": "Python"
},
{
"code": null,
"e": 44544,
"s": 44446,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 44553,
"s": 44544,
"text": "Comments"
},
{
"code": null,
"e": 44566,
"s": 44553,
"text": "Old Comments"
},
{
"code": null,
"e": 44594,
"s": 44566,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 44644,
"s": 44594,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 44666,
"s": 44644,
"text": "Python map() function"
},
{
"code": null,
"e": 44710,
"s": 44666,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 44745,
"s": 44710,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 44767,
"s": 44745,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 44799,
"s": 44767,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 44829,
"s": 44799,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 44871,
"s": 44829,
"text": "Different ways to create Pandas Dataframe"
}
] |
while and do while Loop in Scala - GeeksforGeeks
|
11 Aug, 2021
Looping in programming languages is a feature which facilitates the execution of a set of instructions/functions repeatedly while some condition evaluates to true. Loops make the programmers task simpler. Scala provides the different types of loops but in this article we understand while and do-while loops.
While programming there might be situation which we need to repeat until and unless a condition is met. In these cases, while loop is used. A while loop generally takes a condition in parenthesis. If the condition is True then the code within the body of the while loop is executed. A while loop is used when we donβt know the number of times we want the loop to be executed however we know the termination condition of the loop. The condition at which loop stops is called breaking condition.Syntax:
while (condition)
{
// Code to be executed
}
Flowchart:
Example : Execution of While loop
Scala
// Scala program of while loop // Creating objectobject GFG{ // Main method def main(args: Array[String]) { // variable declaration (assigning 5 to a) var a = 5 // loop execution while (a > 0) { println("a is : " + a) a = a - 1; } }}
Output:
a is : 5
a is : 4
a is : 3
a is : 2
a is : 1
Example : Finding element in an Array
Scala
// Scala program of while loop // Creating objectobject GFG{ // Main method def main(args: Array[String]) { // variable declaration (assigning 5 to a) var a = Array("do_while", "for", "while") var index = 0 // loop execution while (index < a.length) { if(a(index) == "while") println("index of while is " + index) index = index + 1 } }}
Output:
index of while is 2
Note: To execute following commands use Intellij. save this program in format file_name.scala and run it using scala in Intellij.
A do..while loop is almost same as a while loop. The only difference is that do..while loop runs at least one time. The condition is checked after the first execution. A do..while loop is used when we want the loop to run at least one time. It is also known as the exit controlled loop as the condition is checked after executing the loop. In while loop condition is placed at top of loop Whereas in do while loop condition is placed at end, due to this positioning of condition all statements under do while gets executes at least once.Syntax:
do {
// statements to be Executed
} while(condition);
Flowchart:
Example : Execution of do while loop
Scala
// Scala program of do-while loop // Creating objectobject GFG{ // Main method def main(args: Array[String]) { // variable declaration (assigning 5 to a) var a = 5; // loop execution do { println("a is : " + a); a = a - 1; } while (a > 0); }}
Output:
a is : 5
a is : 4
a is : 3
a is : 2
a is : 1
Example : Running loop until we encounter a string in Array
Scala
// Scala program for do-while loop // Creating objectobject GFG{ // Main method def main(args: Array[String]) { // Declaring an array var a = Array("hello", "This", "is", "geeksforgeeks", "bye") var str = "bye" var i = 0 // loop execution do { println("program is saying " + a(i)); i = i + 1; } while (a(i) != str); }}
Output:
program is saying hello
program is saying This
program is saying is
program is saying geeksforgeeks
In above code, bye wonβt be printed.
Akanksha_Rai
saurabh1990aror
sagar0719kumar
Picked
Scala
Scala-Basics
Scala-Decision-Making
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Scala Map
Scala Lists
Scala Tutorial β Learn Scala with Step By Step Guide
Scala | Arrays
How to get the first element of List in Scala
Scala String replace() method with example
Scala | Traits
Scala Map get() method with example
Throw Keyword in Scala
Enumeration in Scala
|
[
{
"code": null,
"e": 25117,
"s": 25089,
"text": "\n11 Aug, 2021"
},
{
"code": null,
"e": 25428,
"s": 25117,
"text": "Looping in programming languages is a feature which facilitates the execution of a set of instructions/functions repeatedly while some condition evaluates to true. Loops make the programmers task simpler. Scala provides the different types of loops but in this article we understand while and do-while loops. "
},
{
"code": null,
"e": 25931,
"s": 25428,
"text": "While programming there might be situation which we need to repeat until and unless a condition is met. In these cases, while loop is used. A while loop generally takes a condition in parenthesis. If the condition is True then the code within the body of the while loop is executed. A while loop is used when we donβt know the number of times we want the loop to be executed however we know the termination condition of the loop. The condition at which loop stops is called breaking condition.Syntax: "
},
{
"code": null,
"e": 25980,
"s": 25931,
"text": "while (condition)\n{\n // Code to be executed\n}"
},
{
"code": null,
"e": 25992,
"s": 25980,
"text": "Flowchart: "
},
{
"code": null,
"e": 26028,
"s": 25992,
"text": "Example : Execution of While loop "
},
{
"code": null,
"e": 26034,
"s": 26028,
"text": "Scala"
},
{
"code": "// Scala program of while loop // Creating objectobject GFG{ // Main method def main(args: Array[String]) { // variable declaration (assigning 5 to a) var a = 5 // loop execution while (a > 0) { println(\"a is : \" + a) a = a - 1; } }}",
"e": 26345,
"s": 26034,
"text": null
},
{
"code": null,
"e": 26355,
"s": 26345,
"text": "Output: "
},
{
"code": null,
"e": 26400,
"s": 26355,
"text": "a is : 5\na is : 4\na is : 3\na is : 2\na is : 1"
},
{
"code": null,
"e": 26440,
"s": 26400,
"text": "Example : Finding element in an Array "
},
{
"code": null,
"e": 26446,
"s": 26440,
"text": "Scala"
},
{
"code": "// Scala program of while loop // Creating objectobject GFG{ // Main method def main(args: Array[String]) { // variable declaration (assigning 5 to a) var a = Array(\"do_while\", \"for\", \"while\") var index = 0 // loop execution while (index < a.length) { if(a(index) == \"while\") println(\"index of while is \" + index) index = index + 1 } }}",
"e": 26875,
"s": 26446,
"text": null
},
{
"code": null,
"e": 26885,
"s": 26875,
"text": "Output: "
},
{
"code": null,
"e": 26905,
"s": 26885,
"text": "index of while is 2"
},
{
"code": null,
"e": 27037,
"s": 26905,
"text": "Note: To execute following commands use Intellij. save this program in format file_name.scala and run it using scala in Intellij. "
},
{
"code": null,
"e": 27584,
"s": 27037,
"text": "A do..while loop is almost same as a while loop. The only difference is that do..while loop runs at least one time. The condition is checked after the first execution. A do..while loop is used when we want the loop to run at least one time. It is also known as the exit controlled loop as the condition is checked after executing the loop. In while loop condition is placed at top of loop Whereas in do while loop condition is placed at end, due to this positioning of condition all statements under do while gets executes at least once.Syntax: "
},
{
"code": null,
"e": 27640,
"s": 27584,
"text": "do {\n\n// statements to be Executed\n\n} while(condition);"
},
{
"code": null,
"e": 27652,
"s": 27640,
"text": "Flowchart: "
},
{
"code": null,
"e": 27691,
"s": 27652,
"text": "Example : Execution of do while loop "
},
{
"code": null,
"e": 27697,
"s": 27691,
"text": "Scala"
},
{
"code": "// Scala program of do-while loop // Creating objectobject GFG{ // Main method def main(args: Array[String]) { // variable declaration (assigning 5 to a) var a = 5; // loop execution do { println(\"a is : \" + a); a = a - 1; } while (a > 0); }}",
"e": 28024,
"s": 27697,
"text": null
},
{
"code": null,
"e": 28034,
"s": 28024,
"text": "Output: "
},
{
"code": null,
"e": 28079,
"s": 28034,
"text": "a is : 5\na is : 4\na is : 3\na is : 2\na is : 1"
},
{
"code": null,
"e": 28141,
"s": 28079,
"text": "Example : Running loop until we encounter a string in Array "
},
{
"code": null,
"e": 28147,
"s": 28141,
"text": "Scala"
},
{
"code": "// Scala program for do-while loop // Creating objectobject GFG{ // Main method def main(args: Array[String]) { // Declaring an array var a = Array(\"hello\", \"This\", \"is\", \"geeksforgeeks\", \"bye\") var str = \"bye\" var i = 0 // loop execution do { println(\"program is saying \" + a(i)); i = i + 1; } while (a(i) != str); }}",
"e": 28572,
"s": 28147,
"text": null
},
{
"code": null,
"e": 28582,
"s": 28572,
"text": "Output: "
},
{
"code": null,
"e": 28682,
"s": 28582,
"text": "program is saying hello\nprogram is saying This\nprogram is saying is\nprogram is saying geeksforgeeks"
},
{
"code": null,
"e": 28720,
"s": 28682,
"text": "In above code, bye wonβt be printed. "
},
{
"code": null,
"e": 28733,
"s": 28720,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 28749,
"s": 28733,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 28764,
"s": 28749,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 28771,
"s": 28764,
"text": "Picked"
},
{
"code": null,
"e": 28777,
"s": 28771,
"text": "Scala"
},
{
"code": null,
"e": 28790,
"s": 28777,
"text": "Scala-Basics"
},
{
"code": null,
"e": 28812,
"s": 28790,
"text": "Scala-Decision-Making"
},
{
"code": null,
"e": 28818,
"s": 28812,
"text": "Scala"
},
{
"code": null,
"e": 28916,
"s": 28818,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28926,
"s": 28916,
"text": "Scala Map"
},
{
"code": null,
"e": 28938,
"s": 28926,
"text": "Scala Lists"
},
{
"code": null,
"e": 28991,
"s": 28938,
"text": "Scala Tutorial β Learn Scala with Step By Step Guide"
},
{
"code": null,
"e": 29006,
"s": 28991,
"text": "Scala | Arrays"
},
{
"code": null,
"e": 29052,
"s": 29006,
"text": "How to get the first element of List in Scala"
},
{
"code": null,
"e": 29095,
"s": 29052,
"text": "Scala String replace() method with example"
},
{
"code": null,
"e": 29110,
"s": 29095,
"text": "Scala | Traits"
},
{
"code": null,
"e": 29146,
"s": 29110,
"text": "Scala Map get() method with example"
},
{
"code": null,
"e": 29169,
"s": 29146,
"text": "Throw Keyword in Scala"
}
] |
Python | numpy.copyto() function - GeeksforGeeks
|
12 Apr, 2019
With the help of Numpy numpy.copyto() method, we can make a copy of all the data elements that is present in numpy array. If we change any data element in the copy, it will not affect the original numpy array.
Syntax : numpy.copyto(destination, source)
Return : Return copy of an array
Example #1 :In this example we can see that with the help of numpy.copyto() method we are making the copy of an elements in a destination array.
# import the important module in pythonimport numpy as np # make an array with numpygfg = np.array([1, 2, 3])geeks = [4, 5, 6] # applying numpy.copyto() methodnp.copyto(gfg, geeks) print(gfg)
[4 5 6]
Example #2 :
# import the important module in pythonimport numpy as np # make an array with numpygfg = np.array([[1, 2, 3], [4, 5, 6]])geeks = [[4, 5, 6], [7, 8, 9]] # applying numpy.copyto() methodnp.copyto(gfg, geeks) print(gfg)
[[4 5 6]
[7 8 9]]
Python numpy-arrayManipulation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n12 Apr, 2019"
},
{
"code": null,
"e": 25747,
"s": 25537,
"text": "With the help of Numpy numpy.copyto() method, we can make a copy of all the data elements that is present in numpy array. If we change any data element in the copy, it will not affect the original numpy array."
},
{
"code": null,
"e": 25790,
"s": 25747,
"text": "Syntax : numpy.copyto(destination, source)"
},
{
"code": null,
"e": 25823,
"s": 25790,
"text": "Return : Return copy of an array"
},
{
"code": null,
"e": 25968,
"s": 25823,
"text": "Example #1 :In this example we can see that with the help of numpy.copyto() method we are making the copy of an elements in a destination array."
},
{
"code": "# import the important module in pythonimport numpy as np # make an array with numpygfg = np.array([1, 2, 3])geeks = [4, 5, 6] # applying numpy.copyto() methodnp.copyto(gfg, geeks) print(gfg)",
"e": 26178,
"s": 25968,
"text": null
},
{
"code": null,
"e": 26187,
"s": 26178,
"text": "[4 5 6]\n"
},
{
"code": null,
"e": 26200,
"s": 26187,
"text": "Example #2 :"
},
{
"code": "# import the important module in pythonimport numpy as np # make an array with numpygfg = np.array([[1, 2, 3], [4, 5, 6]])geeks = [[4, 5, 6], [7, 8, 9]] # applying numpy.copyto() methodnp.copyto(gfg, geeks) print(gfg)",
"e": 26436,
"s": 26200,
"text": null
},
{
"code": null,
"e": 26456,
"s": 26436,
"text": "[[4 5 6]\n [7 8 9]]\n"
},
{
"code": null,
"e": 26487,
"s": 26456,
"text": "Python numpy-arrayManipulation"
},
{
"code": null,
"e": 26500,
"s": 26487,
"text": "Python-numpy"
},
{
"code": null,
"e": 26507,
"s": 26500,
"text": "Python"
},
{
"code": null,
"e": 26605,
"s": 26507,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26637,
"s": 26605,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26679,
"s": 26637,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26721,
"s": 26679,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26748,
"s": 26721,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 26804,
"s": 26748,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26826,
"s": 26804,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26865,
"s": 26826,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 26896,
"s": 26865,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 26925,
"s": 26896,
"text": "Create a directory in Python"
}
] |
Find Index of 0 to be replaced with 1 to get longest continuous sequence of 1s in a binary array - GeeksforGeeks
|
15 Apr, 2021
Given an array of 0s and 1s, find the position of 0 to be replaced with 1 to get longest continuous sequence of 1s. Expected time complexity is O(n) and auxiliary space is O(1).
Example:
Input:
arr[] = {1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1}
Output:
Index 9
Assuming array index starts from 0, replacing 0 with 1 at index 9 causes
the maximum continuous sequence of 1s.
Input:
arr[] = {1, 1, 1, 1, 0}
Output:
Index 4
We strongly recommend to minimize the browser and try this yourself first.A Simple Solution is to traverse the array, for every 0, count the number of 1s on both sides of it. Keep track of maximum count for any 0. Finally return index of the 0 with maximum number of 1s around it. The time complexity of this solution is O(n2).
Using an Efficient Solution, the problem can solved in O(n) time. The idea is to keep track of three indexes, current index (curr), previous zero index (prev_zero) and previous to previous zero index (prev_prev_zero). Traverse the array, if current element is 0, calculate the difference between curr and prev_prev_zero (This difference minus one is the number of 1s around the prev_zero). If the difference between curr and prev_prev_zero is more than maximum so far, then update the maximum. Finally return index of the prev_zero with maximum difference.
Following are the implementations of the above algorithm.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find Index of 0 to be replaced with 1 to get// longest continuous sequence of 1s in a binary array#include<iostream>using namespace std; // Returns index of 0 to be replaced with 1 to get longest// continuous sequence of 1s. If there is no 0 in array, then// it returns -1.int maxOnesIndex(bool arr[], int n){ int max_count = 0; // for maximum number of 1 around a zero int max_index; // for storing result int prev_zero = -1; // index of previous zero int prev_prev_zero = -1; // index of previous to previous zero // Traverse the input array for (int curr=0; curr<n; ++curr) { // If current element is 0, then calculate the difference // between curr and prev_prev_zero if (arr[curr] == 0) { // Update result if count of 1s around prev_zero is more if (curr - prev_prev_zero > max_count) { max_count = curr - prev_prev_zero; max_index = prev_zero; } // Update for next iteration prev_prev_zero = prev_zero; prev_zero = curr; } } // Check for the last encountered zero if (n-prev_prev_zero > max_count) max_index = prev_zero; return max_index;} // Driver programint main(){ bool arr[] = {1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1}; int n = sizeof(arr)/sizeof(arr[0]); cout << "Index of 0 to be replaced is " << maxOnesIndex(arr, n); return 0;}
// Java program to find Index of 0 to be replaced with 1 to get// longest continuous sequence of 1s in a binary array import java.io.*; class Binary{ // Returns index of 0 to be replaced with 1 to get longest // continuous sequence of 1s. If there is no 0 in array, then // it returns -1. static int maxOnesIndex(int arr[], int n) { int max_count = 0; // for maximum number of 1 around a zero int max_index=0; // for storing result int prev_zero = -1; // index of previous zero int prev_prev_zero = -1; // index of previous to previous zero // Traverse the input array for (int curr=0; curr<n; ++curr) { // If current element is 0, then calculate the difference // between curr and prev_prev_zero if (arr[curr] == 0) { // Update result if count of 1s around prev_zero is more if (curr - prev_prev_zero > max_count) { max_count = curr - prev_prev_zero; max_index = prev_zero; } // Update for next iteration prev_prev_zero = prev_zero; prev_zero = curr; } } // Check for the last encountered zero if (n-prev_prev_zero > max_count) max_index = prev_zero; return max_index; } // Driver program to test above function public static void main(String[] args) { int arr[] = {1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1}; int n = arr.length; System.out.println("Index of 0 to be replaced is "+ maxOnesIndex(arr, n)); }}/* This code is contributed by Devesh Agrawal */
# Python program to find Index# of 0 to be replaced with 1 to get# longest continuous sequence# of 1s in a binary array # Returns index of 0 to be# replaced with 1 to get longest# continuous sequence of 1s.# If there is no 0 in array, then# it returns -1.def maxOnesIndex(arr,n): # for maximum number of 1 around a zero max_count = 0 # for storing result max_index =0 # index of previous zero prev_zero = -1 # index of previous to previous zero prev_prev_zero = -1 # Traverse the input array for curr in range(n): # If current element is 0, # then calculate the difference # between curr and prev_prev_zero if (arr[curr] == 0): # Update result if count of # 1s around prev_zero is more if (curr - prev_prev_zero > max_count): max_count = curr - prev_prev_zero max_index = prev_zero # Update for next iteration prev_prev_zero = prev_zero prev_zero = curr # Check for the last encountered zero if (n-prev_prev_zero > max_count): max_index = prev_zero return max_index # Driver program arr = [1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1]n = len(arr) print("Index of 0 to be replaced is ", maxOnesIndex(arr, n)) # This code is contributed# by Anant Agarwal.
// C# program to find Index of 0 to be replaced// with 1 to get longest continuous sequence of// 1s in a binary arrayusing System; class GFG { // Returns index of 0 to be replaced with // 1 to get longest continuous sequence of // 1s. If there is no 0 in array, then it // returns -1. static int maxOnesIndex(int []arr, int n) { // for maximum number of 1 around a zero int max_count = 0; // for storing result int max_index = 0; // index of previous zero int prev_zero = -1; // index of previous to previous zero int prev_prev_zero = -1; // Traverse the input array for (int curr = 0; curr < n; ++curr) { // If current element is 0, then // calculate the difference // between curr and prev_prev_zero if (arr[curr] == 0) { // Update result if count of 1s // around prev_zero is more if (curr - prev_prev_zero > max_count) { max_count = curr - prev_prev_zero; max_index = prev_zero; } // Update for next iteration prev_prev_zero = prev_zero; prev_zero = curr; } } // Check for the last encountered zero if (n-prev_prev_zero > max_count) max_index = prev_zero; return max_index; } // Driver program to test above function public static void Main() { int []arr = {1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1}; int n = arr.Length; Console.Write("Index of 0 to be replaced is " + maxOnesIndex(arr, n)); }} // This code is contributed by nitin mittal.
<?php// PHP program to find Index of 0 to be// replaced with 1 to get longest continuous// sequence of 1s in a binary array // Returns index of 0 to be replaced with// 1 to get longest continuous sequence of 1s.// If there is no 0 in array, then it returns -1.function maxOnesIndex( $arr, $n){ $max_count = 0; // for maximum number of // 1 around a zero $max_index; // for storing result $prev_zero = -1; // index of previous zero $prev_prev_zero = -1; // index of previous to // previous zero // Traverse the input array for ($curr = 0; $curr < $n; ++$curr) { // If current element is 0, then // calculate the difference // between curr and prev_prev_zero if ($arr[$curr] == 0) { // Update result if count of 1s // around prev_zero is more if ($curr - $prev_prev_zero > $max_count) { $max_count = $curr - $prev_prev_zero; $max_index = $prev_zero; } // Update for next iteration $prev_prev_zero = $prev_zero; $prev_zero = $curr; } } // Check for the last encountered zero if ($n - $prev_prev_zero > $max_count) $max_index = $prev_zero; return $max_index;} // Driver Code$arr = array(1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1);$n = sizeof($arr);echo "Index of 0 to be replaced is ", maxOnesIndex($arr, $n); // This code is contributed by ajit?>
<script> // Javascript program to find Index of 0 to// be replaced with 1 to get longest continuous// sequence of 1s in a binary array // Returns index of 0 to be replaced with// 1 to get longest continuous sequence of// 1s. If there is no 0 in array, then it// returns -1.function maxOnesIndex(arr, n){ // for maximum number of 1 around a zero let max_count = 0; // for storing result let max_index = 0; // index of previous zero let prev_zero = -1; // index of previous to previous zero let prev_prev_zero = -1; // Traverse the input array for(let curr = 0; curr < n; ++curr) { // If current element is 0, then // calculate the difference // between curr and prev_prev_zero if (arr[curr] == 0) { // Update result if count of 1s // around prev_zero is more if (curr - prev_prev_zero > max_count) { max_count = curr - prev_prev_zero; max_index = prev_zero; } // Update for next iteration prev_prev_zero = prev_zero; prev_zero = curr; } } // Check for the last encountered zero if (n - prev_prev_zero > max_count) max_index = prev_zero; return max_index;} // Driver codelet arr = [ 1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1 ];let n = arr.length;document.write("Index of 0 to be replaced is " + maxOnesIndex(arr, n)); // This code is contributed by divyesh072019 </script>
Output:
Index of 0 to be replaced is 9
Time Complexity: O(n) Auxiliary Space: O(1)This article is contributed by Ankur Singh. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
nitin mittal
jit_t
divyesh072019
Arrays
Arrays
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
Introduction to Arrays
Multidimensional Arrays in Java
Linear Search
Linked List vs Array
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Python | Using 2D arrays/lists the right way
Search an element in a sorted and rotated array
Array of Strings in C++ (5 Different Ways to Create)
Queue | Set 1 (Introduction and Array Implementation)
|
[
{
"code": null,
"e": 26007,
"s": 25979,
"text": "\n15 Apr, 2021"
},
{
"code": null,
"e": 26186,
"s": 26007,
"text": "Given an array of 0s and 1s, find the position of 0 to be replaced with 1 to get longest continuous sequence of 1s. Expected time complexity is O(n) and auxiliary space is O(1). "
},
{
"code": null,
"e": 26196,
"s": 26186,
"text": "Example: "
},
{
"code": null,
"e": 26441,
"s": 26196,
"text": "Input: \n arr[] = {1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1}\nOutput:\n Index 9\nAssuming array index starts from 0, replacing 0 with 1 at index 9 causes\nthe maximum continuous sequence of 1s.\n\nInput: \n arr[] = {1, 1, 1, 1, 0}\nOutput:\n Index 4"
},
{
"code": null,
"e": 26769,
"s": 26441,
"text": "We strongly recommend to minimize the browser and try this yourself first.A Simple Solution is to traverse the array, for every 0, count the number of 1s on both sides of it. Keep track of maximum count for any 0. Finally return index of the 0 with maximum number of 1s around it. The time complexity of this solution is O(n2)."
},
{
"code": null,
"e": 27326,
"s": 26769,
"text": "Using an Efficient Solution, the problem can solved in O(n) time. The idea is to keep track of three indexes, current index (curr), previous zero index (prev_zero) and previous to previous zero index (prev_prev_zero). Traverse the array, if current element is 0, calculate the difference between curr and prev_prev_zero (This difference minus one is the number of 1s around the prev_zero). If the difference between curr and prev_prev_zero is more than maximum so far, then update the maximum. Finally return index of the prev_zero with maximum difference."
},
{
"code": null,
"e": 27385,
"s": 27326,
"text": "Following are the implementations of the above algorithm. "
},
{
"code": null,
"e": 27389,
"s": 27385,
"text": "C++"
},
{
"code": null,
"e": 27394,
"s": 27389,
"text": "Java"
},
{
"code": null,
"e": 27402,
"s": 27394,
"text": "Python3"
},
{
"code": null,
"e": 27405,
"s": 27402,
"text": "C#"
},
{
"code": null,
"e": 27409,
"s": 27405,
"text": "PHP"
},
{
"code": null,
"e": 27420,
"s": 27409,
"text": "Javascript"
},
{
"code": "// C++ program to find Index of 0 to be replaced with 1 to get// longest continuous sequence of 1s in a binary array#include<iostream>using namespace std; // Returns index of 0 to be replaced with 1 to get longest// continuous sequence of 1s. If there is no 0 in array, then// it returns -1.int maxOnesIndex(bool arr[], int n){ int max_count = 0; // for maximum number of 1 around a zero int max_index; // for storing result int prev_zero = -1; // index of previous zero int prev_prev_zero = -1; // index of previous to previous zero // Traverse the input array for (int curr=0; curr<n; ++curr) { // If current element is 0, then calculate the difference // between curr and prev_prev_zero if (arr[curr] == 0) { // Update result if count of 1s around prev_zero is more if (curr - prev_prev_zero > max_count) { max_count = curr - prev_prev_zero; max_index = prev_zero; } // Update for next iteration prev_prev_zero = prev_zero; prev_zero = curr; } } // Check for the last encountered zero if (n-prev_prev_zero > max_count) max_index = prev_zero; return max_index;} // Driver programint main(){ bool arr[] = {1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1}; int n = sizeof(arr)/sizeof(arr[0]); cout << \"Index of 0 to be replaced is \" << maxOnesIndex(arr, n); return 0;}",
"e": 28888,
"s": 27420,
"text": null
},
{
"code": "// Java program to find Index of 0 to be replaced with 1 to get// longest continuous sequence of 1s in a binary array import java.io.*; class Binary{ // Returns index of 0 to be replaced with 1 to get longest // continuous sequence of 1s. If there is no 0 in array, then // it returns -1. static int maxOnesIndex(int arr[], int n) { int max_count = 0; // for maximum number of 1 around a zero int max_index=0; // for storing result int prev_zero = -1; // index of previous zero int prev_prev_zero = -1; // index of previous to previous zero // Traverse the input array for (int curr=0; curr<n; ++curr) { // If current element is 0, then calculate the difference // between curr and prev_prev_zero if (arr[curr] == 0) { // Update result if count of 1s around prev_zero is more if (curr - prev_prev_zero > max_count) { max_count = curr - prev_prev_zero; max_index = prev_zero; } // Update for next iteration prev_prev_zero = prev_zero; prev_zero = curr; } } // Check for the last encountered zero if (n-prev_prev_zero > max_count) max_index = prev_zero; return max_index; } // Driver program to test above function public static void main(String[] args) { int arr[] = {1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1}; int n = arr.length; System.out.println(\"Index of 0 to be replaced is \"+ maxOnesIndex(arr, n)); }}/* This code is contributed by Devesh Agrawal */",
"e": 30636,
"s": 28888,
"text": null
},
{
"code": "# Python program to find Index# of 0 to be replaced with 1 to get# longest continuous sequence# of 1s in a binary array # Returns index of 0 to be# replaced with 1 to get longest# continuous sequence of 1s.# If there is no 0 in array, then# it returns -1.def maxOnesIndex(arr,n): # for maximum number of 1 around a zero max_count = 0 # for storing result max_index =0 # index of previous zero prev_zero = -1 # index of previous to previous zero prev_prev_zero = -1 # Traverse the input array for curr in range(n): # If current element is 0, # then calculate the difference # between curr and prev_prev_zero if (arr[curr] == 0): # Update result if count of # 1s around prev_zero is more if (curr - prev_prev_zero > max_count): max_count = curr - prev_prev_zero max_index = prev_zero # Update for next iteration prev_prev_zero = prev_zero prev_zero = curr # Check for the last encountered zero if (n-prev_prev_zero > max_count): max_index = prev_zero return max_index # Driver program arr = [1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1]n = len(arr) print(\"Index of 0 to be replaced is \", maxOnesIndex(arr, n)) # This code is contributed# by Anant Agarwal.",
"e": 32018,
"s": 30636,
"text": null
},
{
"code": "// C# program to find Index of 0 to be replaced// with 1 to get longest continuous sequence of// 1s in a binary arrayusing System; class GFG { // Returns index of 0 to be replaced with // 1 to get longest continuous sequence of // 1s. If there is no 0 in array, then it // returns -1. static int maxOnesIndex(int []arr, int n) { // for maximum number of 1 around a zero int max_count = 0; // for storing result int max_index = 0; // index of previous zero int prev_zero = -1; // index of previous to previous zero int prev_prev_zero = -1; // Traverse the input array for (int curr = 0; curr < n; ++curr) { // If current element is 0, then // calculate the difference // between curr and prev_prev_zero if (arr[curr] == 0) { // Update result if count of 1s // around prev_zero is more if (curr - prev_prev_zero > max_count) { max_count = curr - prev_prev_zero; max_index = prev_zero; } // Update for next iteration prev_prev_zero = prev_zero; prev_zero = curr; } } // Check for the last encountered zero if (n-prev_prev_zero > max_count) max_index = prev_zero; return max_index; } // Driver program to test above function public static void Main() { int []arr = {1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1}; int n = arr.Length; Console.Write(\"Index of 0 to be replaced is \" + maxOnesIndex(arr, n)); }} // This code is contributed by nitin mittal.",
"e": 33893,
"s": 32018,
"text": null
},
{
"code": "<?php// PHP program to find Index of 0 to be// replaced with 1 to get longest continuous// sequence of 1s in a binary array // Returns index of 0 to be replaced with// 1 to get longest continuous sequence of 1s.// If there is no 0 in array, then it returns -1.function maxOnesIndex( $arr, $n){ $max_count = 0; // for maximum number of // 1 around a zero $max_index; // for storing result $prev_zero = -1; // index of previous zero $prev_prev_zero = -1; // index of previous to // previous zero // Traverse the input array for ($curr = 0; $curr < $n; ++$curr) { // If current element is 0, then // calculate the difference // between curr and prev_prev_zero if ($arr[$curr] == 0) { // Update result if count of 1s // around prev_zero is more if ($curr - $prev_prev_zero > $max_count) { $max_count = $curr - $prev_prev_zero; $max_index = $prev_zero; } // Update for next iteration $prev_prev_zero = $prev_zero; $prev_zero = $curr; } } // Check for the last encountered zero if ($n - $prev_prev_zero > $max_count) $max_index = $prev_zero; return $max_index;} // Driver Code$arr = array(1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1);$n = sizeof($arr);echo \"Index of 0 to be replaced is \", maxOnesIndex($arr, $n); // This code is contributed by ajit?>",
"e": 35394,
"s": 33893,
"text": null
},
{
"code": "<script> // Javascript program to find Index of 0 to// be replaced with 1 to get longest continuous// sequence of 1s in a binary array // Returns index of 0 to be replaced with// 1 to get longest continuous sequence of// 1s. If there is no 0 in array, then it// returns -1.function maxOnesIndex(arr, n){ // for maximum number of 1 around a zero let max_count = 0; // for storing result let max_index = 0; // index of previous zero let prev_zero = -1; // index of previous to previous zero let prev_prev_zero = -1; // Traverse the input array for(let curr = 0; curr < n; ++curr) { // If current element is 0, then // calculate the difference // between curr and prev_prev_zero if (arr[curr] == 0) { // Update result if count of 1s // around prev_zero is more if (curr - prev_prev_zero > max_count) { max_count = curr - prev_prev_zero; max_index = prev_zero; } // Update for next iteration prev_prev_zero = prev_zero; prev_zero = curr; } } // Check for the last encountered zero if (n - prev_prev_zero > max_count) max_index = prev_zero; return max_index;} // Driver codelet arr = [ 1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1 ];let n = arr.length;document.write(\"Index of 0 to be replaced is \" + maxOnesIndex(arr, n)); // This code is contributed by divyesh072019 </script>",
"e": 36966,
"s": 35394,
"text": null
},
{
"code": null,
"e": 36975,
"s": 36966,
"text": "Output: "
},
{
"code": null,
"e": 37006,
"s": 36975,
"text": "Index of 0 to be replaced is 9"
},
{
"code": null,
"e": 37219,
"s": 37006,
"text": "Time Complexity: O(n) Auxiliary Space: O(1)This article is contributed by Ankur Singh. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 37232,
"s": 37219,
"text": "nitin mittal"
},
{
"code": null,
"e": 37238,
"s": 37232,
"text": "jit_t"
},
{
"code": null,
"e": 37252,
"s": 37238,
"text": "divyesh072019"
},
{
"code": null,
"e": 37259,
"s": 37252,
"text": "Arrays"
},
{
"code": null,
"e": 37266,
"s": 37259,
"text": "Arrays"
},
{
"code": null,
"e": 37364,
"s": 37266,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37432,
"s": 37364,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 37455,
"s": 37432,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 37487,
"s": 37455,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 37501,
"s": 37487,
"text": "Linear Search"
},
{
"code": null,
"e": 37522,
"s": 37501,
"text": "Linked List vs Array"
},
{
"code": null,
"e": 37607,
"s": 37522,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 37652,
"s": 37607,
"text": "Python | Using 2D arrays/lists the right way"
},
{
"code": null,
"e": 37700,
"s": 37652,
"text": "Search an element in a sorted and rotated array"
},
{
"code": null,
"e": 37753,
"s": 37700,
"text": "Array of Strings in C++ (5 Different Ways to Create)"
}
] |
PostgreSQL - Connect To PostgreSQL Database Server in Python - GeeksforGeeks
|
29 Aug, 2020
The psycopg database adapter is used to connect with PostgreSQL database server through python.
Installing psycopg:
First, use the following command line from the terminal:
pip install psycopg
If you have downloaded the source package into your computer, you can use the setup.py as follows:
python setup.py build
sudo python setup.py install
First, log in to the PostgreSQL database server using any client tool such as pgAdmin or psql.
Second, use the following statement to create a new database named suppliers in the PostgreSQL database server.
CREATE DATABASE suppliers;
To connect to the suppliers database, you use the connect() function of the psycopg2 module.
The connect() function creates a new database session and returns a new instance of the connection class. By using the connection object, you can create a new cursor to execute any SQL statements.
To call the connect() function, you specify the PostgreSQL database parameters as a connection string and pass it to the function like this:
conn = psycopg2.connect("dbname=suppliers user=postgres password=postgres")
Or you can use a list of keyword arguments:
conn = psycopg2.connect(
host="localhost",
database="suppliers",
user="postgres",
password="Abcd1234")
The following is the list of the connection parameters:
database: the name of the database that you want to connect.
user: the username used to authenticate.
password: password used to authenticate.
host: database server address e.g., localhost or an IP address.
port: the port number that defaults to 5432 if it is not provided.
To make it more convenient, you can use a configuration file to store all connection parameters.
The following shows the contents of the database.ini file:
[postgresql]
host=localhost
database=suppliers
user=postgres
password=SecurePas$1
By using the database.ini, you can change the PostgreSQL connection parameters when you move the code to the production environment without modifying the code.
Notice that if you git, you need to add the database.ini to the .gitignore file to not committing the sensitive information to the public repo like github. The .gitignore file will be like this:
database.ini
The following config() function read the database.ini file and returns connection parameters. The config() function is placed in the config.py file:
#!/usr/bin/python
from configparser import ConfigParser
def config(filename='database.ini', section='postgresql'):
# create a parser
parser = ConfigParser()
# read config file
parser.read(filename)
# get section, default to postgresql
db = {}
if parser.has_section(section):
params = parser.items(section)
for param in params:
db[param[0]] = param[1]
else:
raise Exception('Section {0} not found in the {1} file'.format(section, filename))
return db
The following connect() function connects to the suppliers database and prints out the PostgreSQL database version.
#!/usr/bin/python
import psycopg2
from config import config
def connect():
""" Connect to the PostgreSQL database server """
conn = None
try:
# read connection parameters
params = config()
# connect to the PostgreSQL server
print('Connecting to the PostgreSQL database...')
conn = psycopg2.connect(**params)
# create a cursor
cur = conn.cursor()
# execute a statement
print('PostgreSQL database version:')
cur.execute('SELECT version()')
# display the PostgreSQL database server version
db_version = cur.fetchone()
print(db_version)
# close the communication with the PostgreSQL
cur.close()
except (Exception, psycopg2.DatabaseError) as error:
print(error)
finally:
if conn is not None:
conn.close()
print('Database connection closed.')
if __name__ == '__main__':
connect()
How it works.
First, read database connection parameters from the database.ini file.
Next, create a new database connection by calling the connect() function.
Then, create a new cursor and execute an SQL statement to get the PostgreSQL database version.
After that, read the result set by calling the fetchone() method of the cursor object.
Finally, close the communication with the database server by calling the close() method of the cursor and connection objects.
To execute the connect.py file, you use the following command:
python connect.py
You will see the following output:
Connecting to the PostgreSQL database...
PostgreSQL database version:
('PostgreSQL 12.3, compiled by Visual C++ build 1914, 64-bit', )
Database connection closed.
The connect() function raises the DatabaseError exception if an error occurred. To see how it works, you can change the connection parameters in the database.ini file.
For example, if you change the host to localhosts, the program will output the following message:
Connecting to the PostgreSQL database...
could not translate host name "localhosts" to address: Unknown host
The following displays error message when you change the database to a database that does not exist e.g., supplier:
Connecting to the PostgreSQL database...
FATAL: database "supplier" does not exist
If you change the user to postgress, it will not be authenticated successfully as follows:
Connecting to the PostgreSQL database...
FATAL: password authentication failed for user "postgress"
PostgreSQL
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PostgreSQL - CREATE PROCEDURE
PostgreSQL - GROUP BY clause
PostgreSQL - DROP INDEX
PostgreSQL - TIME Data Type
PostgreSQL - REPLACE Function
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
|
[
{
"code": null,
"e": 25503,
"s": 25475,
"text": "\n29 Aug, 2020"
},
{
"code": null,
"e": 25599,
"s": 25503,
"text": "The psycopg database adapter is used to connect with PostgreSQL database server through python."
},
{
"code": null,
"e": 25619,
"s": 25599,
"text": "Installing psycopg:"
},
{
"code": null,
"e": 25676,
"s": 25619,
"text": "First, use the following command line from the terminal:"
},
{
"code": null,
"e": 25697,
"s": 25676,
"text": "pip install psycopg\n"
},
{
"code": null,
"e": 25796,
"s": 25697,
"text": "If you have downloaded the source package into your computer, you can use the setup.py as follows:"
},
{
"code": null,
"e": 25847,
"s": 25796,
"text": "python setup.py build\nsudo python setup.py install"
},
{
"code": null,
"e": 25942,
"s": 25847,
"text": "First, log in to the PostgreSQL database server using any client tool such as pgAdmin or psql."
},
{
"code": null,
"e": 26054,
"s": 25942,
"text": "Second, use the following statement to create a new database named suppliers in the PostgreSQL database server."
},
{
"code": null,
"e": 26081,
"s": 26054,
"text": "CREATE DATABASE suppliers;"
},
{
"code": null,
"e": 26174,
"s": 26081,
"text": "To connect to the suppliers database, you use the connect() function of the psycopg2 module."
},
{
"code": null,
"e": 26371,
"s": 26174,
"text": "The connect() function creates a new database session and returns a new instance of the connection class. By using the connection object, you can create a new cursor to execute any SQL statements."
},
{
"code": null,
"e": 26512,
"s": 26371,
"text": "To call the connect() function, you specify the PostgreSQL database parameters as a connection string and pass it to the function like this:"
},
{
"code": null,
"e": 26588,
"s": 26512,
"text": "conn = psycopg2.connect(\"dbname=suppliers user=postgres password=postgres\")"
},
{
"code": null,
"e": 26632,
"s": 26588,
"text": "Or you can use a list of keyword arguments:"
},
{
"code": null,
"e": 26751,
"s": 26632,
"text": "conn = psycopg2.connect(\n host=\"localhost\",\n database=\"suppliers\",\n user=\"postgres\",\n password=\"Abcd1234\")"
},
{
"code": null,
"e": 26807,
"s": 26751,
"text": "The following is the list of the connection parameters:"
},
{
"code": null,
"e": 26871,
"s": 26807,
"text": " database: the name of the database that you want to connect."
},
{
"code": null,
"e": 26915,
"s": 26871,
"text": " user: the username used to authenticate."
},
{
"code": null,
"e": 26959,
"s": 26915,
"text": " password: password used to authenticate."
},
{
"code": null,
"e": 27026,
"s": 26959,
"text": " host: database server address e.g., localhost or an IP address."
},
{
"code": null,
"e": 27096,
"s": 27026,
"text": " port: the port number that defaults to 5432 if it is not provided."
},
{
"code": null,
"e": 27193,
"s": 27096,
"text": "To make it more convenient, you can use a configuration file to store all connection parameters."
},
{
"code": null,
"e": 27252,
"s": 27193,
"text": "The following shows the contents of the database.ini file:"
},
{
"code": null,
"e": 27334,
"s": 27252,
"text": "[postgresql]\nhost=localhost\ndatabase=suppliers\nuser=postgres\npassword=SecurePas$1"
},
{
"code": null,
"e": 27494,
"s": 27334,
"text": "By using the database.ini, you can change the PostgreSQL connection parameters when you move the code to the production environment without modifying the code."
},
{
"code": null,
"e": 27689,
"s": 27494,
"text": "Notice that if you git, you need to add the database.ini to the .gitignore file to not committing the sensitive information to the public repo like github. The .gitignore file will be like this:"
},
{
"code": null,
"e": 27702,
"s": 27689,
"text": "database.ini"
},
{
"code": null,
"e": 27851,
"s": 27702,
"text": "The following config() function read the database.ini file and returns connection parameters. The config() function is placed in the config.py file:"
},
{
"code": null,
"e": 28377,
"s": 27851,
"text": "#!/usr/bin/python\nfrom configparser import ConfigParser\n\n\ndef config(filename='database.ini', section='postgresql'):\n # create a parser\n parser = ConfigParser()\n # read config file\n parser.read(filename)\n\n # get section, default to postgresql\n db = {}\n if parser.has_section(section):\n params = parser.items(section)\n for param in params:\n db[param[0]] = param[1]\n else:\n raise Exception('Section {0} not found in the {1} file'.format(section, filename))\n\n return db"
},
{
"code": null,
"e": 28493,
"s": 28377,
"text": "The following connect() function connects to the suppliers database and prints out the PostgreSQL database version."
},
{
"code": null,
"e": 29474,
"s": 28493,
"text": "#!/usr/bin/python\nimport psycopg2\nfrom config import config\n\ndef connect():\n \"\"\" Connect to the PostgreSQL database server \"\"\"\n conn = None\n try:\n # read connection parameters\n params = config()\n\n # connect to the PostgreSQL server\n print('Connecting to the PostgreSQL database...')\n conn = psycopg2.connect(**params)\n \n # create a cursor\n cur = conn.cursor()\n \n # execute a statement\n print('PostgreSQL database version:')\n cur.execute('SELECT version()')\n\n # display the PostgreSQL database server version\n db_version = cur.fetchone()\n print(db_version)\n \n # close the communication with the PostgreSQL\n cur.close()\n except (Exception, psycopg2.DatabaseError) as error:\n print(error)\n finally:\n if conn is not None:\n conn.close()\n print('Database connection closed.')\n\n\nif __name__ == '__main__':\n connect()"
},
{
"code": null,
"e": 29488,
"s": 29474,
"text": "How it works."
},
{
"code": null,
"e": 29562,
"s": 29488,
"text": " First, read database connection parameters from the database.ini file."
},
{
"code": null,
"e": 29639,
"s": 29562,
"text": " Next, create a new database connection by calling the connect() function."
},
{
"code": null,
"e": 29737,
"s": 29639,
"text": " Then, create a new cursor and execute an SQL statement to get the PostgreSQL database version."
},
{
"code": null,
"e": 29828,
"s": 29737,
"text": " After that, read the result set by calling the fetchone() method of the cursor object."
},
{
"code": null,
"e": 29957,
"s": 29828,
"text": " Finally, close the communication with the database server by calling the close() method of the cursor and connection objects."
},
{
"code": null,
"e": 30020,
"s": 29957,
"text": "To execute the connect.py file, you use the following command:"
},
{
"code": null,
"e": 30038,
"s": 30020,
"text": "python connect.py"
},
{
"code": null,
"e": 30073,
"s": 30038,
"text": "You will see the following output:"
},
{
"code": null,
"e": 30236,
"s": 30073,
"text": "Connecting to the PostgreSQL database...\nPostgreSQL database version:\n('PostgreSQL 12.3, compiled by Visual C++ build 1914, 64-bit', )\nDatabase connection closed."
},
{
"code": null,
"e": 30404,
"s": 30236,
"text": "The connect() function raises the DatabaseError exception if an error occurred. To see how it works, you can change the connection parameters in the database.ini file."
},
{
"code": null,
"e": 30502,
"s": 30404,
"text": "For example, if you change the host to localhosts, the program will output the following message:"
},
{
"code": null,
"e": 30611,
"s": 30502,
"text": "Connecting to the PostgreSQL database...\ncould not translate host name \"localhosts\" to address: Unknown host"
},
{
"code": null,
"e": 30727,
"s": 30611,
"text": "The following displays error message when you change the database to a database that does not exist e.g., supplier:"
},
{
"code": null,
"e": 30810,
"s": 30727,
"text": "Connecting to the PostgreSQL database...\nFATAL: database \"supplier\" does not exist"
},
{
"code": null,
"e": 30902,
"s": 30810,
"text": "If you change the user to postgress, it will not be authenticated successfully as follows:"
},
{
"code": null,
"e": 31002,
"s": 30902,
"text": "Connecting to the PostgreSQL database...\nFATAL: password authentication failed for user \"postgress\""
},
{
"code": null,
"e": 31013,
"s": 31002,
"text": "PostgreSQL"
},
{
"code": null,
"e": 31020,
"s": 31013,
"text": "Python"
},
{
"code": null,
"e": 31118,
"s": 31020,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31148,
"s": 31118,
"text": "PostgreSQL - CREATE PROCEDURE"
},
{
"code": null,
"e": 31177,
"s": 31148,
"text": "PostgreSQL - GROUP BY clause"
},
{
"code": null,
"e": 31201,
"s": 31177,
"text": "PostgreSQL - DROP INDEX"
},
{
"code": null,
"e": 31229,
"s": 31201,
"text": "PostgreSQL - TIME Data Type"
},
{
"code": null,
"e": 31259,
"s": 31229,
"text": "PostgreSQL - REPLACE Function"
},
{
"code": null,
"e": 31287,
"s": 31259,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 31337,
"s": 31287,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 31359,
"s": 31337,
"text": "Python map() function"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.