title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
PHP mysqli_query() Function | The mysqli_query() function accepts a string value representing a query as one of the parameters and, executes/performs the given query on the database.
mysqli_query($con, query)
con(Mandatory)
This is an object representing a connection to MySQL Server.
query(Mandatory)
This is a string value representing the query to be executed.
mode(Optional)
This is a integer value representing the result mode. You can pass MYSQLI_USE_RESULT or MYSQLI_STORE_RESULT as values to this parameter.
For SELECT, SHOW, DESCRIBE and EXPLAIN queries this function returns a mysqli_result object holding the result of the query in case of success and, false if failed.
For other queries this function returns an boolean value which is, true if the operation/query is successful and, false if not.
This function was first introduced in PHP Version 5 and works works in all the later versions.
Following example demonstrates the usage of the mysqli_query() function (in procedural style) −
<?php
$con = mysqli_connect("localhost", "root", "password", "mydb");
mysqli_query($con, "CREATE TABLE IF NOT EXISTS my_team(ID INT, First_Name VARCHAR(255), Last_Name VARCHAR(255), Place_Of_Birth VARCHAR(255), Country VARCHAR(255))");
print("Table Created ..."."\n");
//Inserting a records into the my_team table
mysqli_query($con, "insert into my_team values(1, 'Shikhar', 'Dhawan', 'Delhi', 'India')");
mysqli_query($con, "insert into my_team values(2, 'Jonathan', 'Trott', 'CapeTown', 'SouthAfrica')");
mysqli_query($con, "insert into my_team values(3, 'Kumara', 'Sangakkara', 'Matale', 'Srilanka')");
mysqli_query($con, "insert into my_team values(4, 'Virat', 'Kohli', 'Delhi', 'India')");
print("Records Inserted ..."."\n");
//Closing the connection
mysqli_close($con);
?>
This will produce following result −
Table Created ...
Records Inserted ...
If you observe the contents of the table in the database you can see the inserted records as shown below −
mysql> select * from my_team;
+------+------------+------------+----------------+-------------+
| ID | First_Name | Last_Name | Place_Of_Birth | Country |
+------+------------+------------+----------------+-------------+
| 1 | Shikhar | Dhawan | Delhi | India |
| 2 | Jonathan | Trott | CapeTown | SouthAfrica |
| 3 | Kumara | Sangakkara | Matale | Srilanka |
| 4 | Virat | Kohli | Delhi | India |
+------+------------+------------+----------------+-------------+
4 rows in set (0.00 sec)
In object oriented style the syntax of this function is $con->query(); Following is the example of this function in object oriented style $minus;
<?php
$con = new mysqli("localhost", "root", "password", "mydb");
//Inserting a records into the players table
$con->query("CREATE TABLE IF NOT EXISTS players(First_Name VARCHAR(255), Last_Name VARCHAR(255), Country VARCHAR(255))");
$con->query("insert into players values('Shikhar', 'Dhawan', 'India')");
$con->query("insert into players values('Jonathan', 'Trott', 'SouthAfrica')");
print("Data Created......");
//Closing the connection
$res = $con -> close();
?>
This will produce following result −
Data Created......
If you observe the contents of the table in the database you can see the inserted records as shown below −
mysql> select * from players;
+------------+-----------+-------------+
| First_Name | Last_Name | Country |
+------------+-----------+-------------+
| Shikhar | Dhawan | India |
| Jonathan | Trott | SouthAfrica |
+------------+-----------+-------------+
2 rows in set (0.00 sec)
Following example prints the results of INSERT and SELECT queries −
<?php
//Creating a connection
$con = mysqli_connect("localhost", "root", "password", "mydb");
mysqli_query($con, "CREATE TABLE IF NOT EXISTS my_team(ID INT, First_Name VARCHAR(255), Last_Name VARCHAR(255), Place_Of_Birth VARCHAR(255), Country VARCHAR(255))");
print("Table Created ..."."\n");
//Inserting a records into the my_team table
$res = mysqli_query($con, "insert into my_team values(1, 'Shikhar', 'Dhawan', 'Delhi', 'India')");
print("Result of Insert Query: ".$res."\n");
$res = mysqli_query($con, "insert into my_team values(2, 'Jonathan', 'Trott', 'CapeTown', 'SouthAfrica')");
print("Result of Insert Query: ".$res);
$res = mysqli_query($con, "SELECT * FROM my_team");
print("Result of the SELECT query: ");
print_r($res);
//Closing the connection
mysqli_close($con);
?>
This will produce following result −
Table Created ...
Result of Insert Query: 1
Result of Insert Query: 1Result of the SELECT query: mysqli_result Object
(
[current_field] => 0
[field_count] => 5
[lengths] =>
[num_rows] => 2
[type] => 0
)
Assume we have created a table players in the database and populated it, as shown below −
CREATE TABLE Players (Name VARCHAR(255), Age INT, Score INT);
insert into Players values('Dhavan', 33, 90),('Rohit', 28, 26),('Kohli', 25, 50);
Following example retrieves the resultset from a
mysqli_multi_query
<?php
//Creating a connection
$con = mysqli_connect("localhost", "root", "password", "mydb");
//Executing the multi query
$query = "SELECT * FROM players";
//Retrieving the records
$res = mysqli_query($con, $query, MYSQLI_USE_RESULT);
if ($res) {
while ($row = mysqli_fetch_row($res)) {
print("Name: ".$row[0]."\n");
print("Age: ".$row[1]."\n");
}
}
//Closing the connection
mysqli_close($con);
?>
This will produce following result −
Name: Dhavan
Age: 33
Name: Rohit
Age: 28
Name: Kohli
Age: 25
45 Lectures
9 hours
Malhar Lathkar
34 Lectures
4 hours
Syed Raza
84 Lectures
5.5 hours
Frahaan Hussain
17 Lectures
1 hours
Nivedita Jain
100 Lectures
34 hours
Azaz Patel
43 Lectures
5.5 hours
Vijay Kumar Parvatha Reddy
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2910,
"s": 2757,
"text": "The mysqli_query() function accepts a string value representing a query as one of the parameters and, executes/performs the given query on the database."
},
{
"code": null,
"e": 2937,
"s": 2910,
"text": "mysqli_query($con, query)\n"
},
{
"code": null,
"e": 2952,
"s": 2937,
"text": "con(Mandatory)"
},
{
"code": null,
"e": 3013,
"s": 2952,
"text": "This is an object representing a connection to MySQL Server."
},
{
"code": null,
"e": 3030,
"s": 3013,
"text": "query(Mandatory)"
},
{
"code": null,
"e": 3092,
"s": 3030,
"text": "This is a string value representing the query to be executed."
},
{
"code": null,
"e": 3107,
"s": 3092,
"text": "mode(Optional)"
},
{
"code": null,
"e": 3245,
"s": 3107,
"text": "This is a integer value representing the result mode. You can pass MYSQLI_USE_RESULT or MYSQLI_STORE_RESULT as values to this parameter."
},
{
"code": null,
"e": 3410,
"s": 3245,
"text": "For SELECT, SHOW, DESCRIBE and EXPLAIN queries this function returns a mysqli_result object holding the result of the query in case of success and, false if failed."
},
{
"code": null,
"e": 3539,
"s": 3410,
"text": "For other queries this function returns an boolean value which is, true if the operation/query is successful and, false if not."
},
{
"code": null,
"e": 3634,
"s": 3539,
"text": "This function was first introduced in PHP Version 5 and works works in all the later versions."
},
{
"code": null,
"e": 3730,
"s": 3634,
"text": "Following example demonstrates the usage of the mysqli_query() function (in procedural style) −"
},
{
"code": null,
"e": 4548,
"s": 3730,
"text": "<?php\n $con = mysqli_connect(\"localhost\", \"root\", \"password\", \"mydb\");\n\n mysqli_query($con, \"CREATE TABLE IF NOT EXISTS my_team(ID INT, First_Name VARCHAR(255), Last_Name VARCHAR(255), Place_Of_Birth VARCHAR(255), Country VARCHAR(255))\");\n print(\"Table Created ...\".\"\\n\");\n\n //Inserting a records into the my_team table\n mysqli_query($con, \"insert into my_team values(1, 'Shikhar', 'Dhawan', 'Delhi', 'India')\");\n mysqli_query($con, \"insert into my_team values(2, 'Jonathan', 'Trott', 'CapeTown', 'SouthAfrica')\");\n mysqli_query($con, \"insert into my_team values(3, 'Kumara', 'Sangakkara', 'Matale', 'Srilanka')\");\n mysqli_query($con, \"insert into my_team values(4, 'Virat', 'Kohli', 'Delhi', 'India')\");\n\n print(\"Records Inserted ...\".\"\\n\");\n \n //Closing the connection\n mysqli_close($con);\n?>"
},
{
"code": null,
"e": 4585,
"s": 4548,
"text": "This will produce following result −"
},
{
"code": null,
"e": 4625,
"s": 4585,
"text": "Table Created ...\nRecords Inserted ...\n"
},
{
"code": null,
"e": 4732,
"s": 4625,
"text": "If you observe the contents of the table in the database you can see the inserted records as shown below −"
},
{
"code": null,
"e": 5316,
"s": 4732,
"text": "mysql> select * from my_team;\n+------+------------+------------+----------------+-------------+\n| ID | First_Name | Last_Name | Place_Of_Birth | Country |\n+------+------------+------------+----------------+-------------+\n| 1 | Shikhar | Dhawan | Delhi | India |\n| 2 | Jonathan | Trott | CapeTown | SouthAfrica |\n| 3 | Kumara | Sangakkara | Matale | Srilanka |\n| 4 | Virat | Kohli | Delhi | India |\n+------+------------+------------+----------------+-------------+\n4 rows in set (0.00 sec)\n"
},
{
"code": null,
"e": 5462,
"s": 5316,
"text": "In object oriented style the syntax of this function is $con->query(); Following is the example of this function in object oriented style $minus;"
},
{
"code": null,
"e": 5954,
"s": 5462,
"text": "<?php\n $con = new mysqli(\"localhost\", \"root\", \"password\", \"mydb\");\n\n //Inserting a records into the players table\n $con->query(\"CREATE TABLE IF NOT EXISTS players(First_Name VARCHAR(255), Last_Name VARCHAR(255), Country VARCHAR(255))\");\n $con->query(\"insert into players values('Shikhar', 'Dhawan', 'India')\");\n $con->query(\"insert into players values('Jonathan', 'Trott', 'SouthAfrica')\");\n\n print(\"Data Created......\");\n //Closing the connection\n $res = $con -> close();\n?>"
},
{
"code": null,
"e": 5991,
"s": 5954,
"text": "This will produce following result −"
},
{
"code": null,
"e": 6011,
"s": 5991,
"text": "Data Created......\n"
},
{
"code": null,
"e": 6118,
"s": 6011,
"text": "If you observe the contents of the table in the database you can see the inserted records as shown below −"
},
{
"code": null,
"e": 6419,
"s": 6118,
"text": "mysql> select * from players;\n+------------+-----------+-------------+\n| First_Name | Last_Name | Country |\n+------------+-----------+-------------+\n| Shikhar | Dhawan | India |\n| Jonathan | Trott | SouthAfrica |\n+------------+-----------+-------------+\n2 rows in set (0.00 sec)"
},
{
"code": null,
"e": 6487,
"s": 6419,
"text": "Following example prints the results of INSERT and SELECT queries −"
},
{
"code": null,
"e": 7317,
"s": 6487,
"text": "<?php\n //Creating a connection\n $con = mysqli_connect(\"localhost\", \"root\", \"password\", \"mydb\");\n\n mysqli_query($con, \"CREATE TABLE IF NOT EXISTS my_team(ID INT, First_Name VARCHAR(255), Last_Name VARCHAR(255), Place_Of_Birth VARCHAR(255), Country VARCHAR(255))\");\n print(\"Table Created ...\".\"\\n\");\n\n //Inserting a records into the my_team table\n $res = mysqli_query($con, \"insert into my_team values(1, 'Shikhar', 'Dhawan', 'Delhi', 'India')\");\n print(\"Result of Insert Query: \".$res.\"\\n\");\n $res = mysqli_query($con, \"insert into my_team values(2, 'Jonathan', 'Trott', 'CapeTown', 'SouthAfrica')\");\n print(\"Result of Insert Query: \".$res);\n\n $res = mysqli_query($con, \"SELECT * FROM my_team\");\n print(\"Result of the SELECT query: \");\n print_r($res);\n\n //Closing the connection\n mysqli_close($con);\n?>"
},
{
"code": null,
"e": 7354,
"s": 7317,
"text": "This will produce following result −"
},
{
"code": null,
"e": 7578,
"s": 7354,
"text": "Table Created ...\nResult of Insert Query: 1\nResult of Insert Query: 1Result of the SELECT query: mysqli_result Object\n(\n [current_field] => 0\n [field_count] => 5\n [lengths] =>\n [num_rows] => 2\n [type] => 0\n)\n"
},
{
"code": null,
"e": 7668,
"s": 7578,
"text": "Assume we have created a table players in the database and populated it, as shown below −"
},
{
"code": null,
"e": 7815,
"s": 7668,
"text": "CREATE TABLE Players (Name VARCHAR(255), Age INT, Score INT);\n insert into Players values('Dhavan', 33, 90),('Rohit', 28, 26),('Kohli', 25, 50);"
},
{
"code": null,
"e": 7865,
"s": 7815,
"text": "Following example retrieves the resultset from a "
},
{
"code": null,
"e": 7884,
"s": 7865,
"text": "mysqli_multi_query"
},
{
"code": null,
"e": 8346,
"s": 7884,
"text": "<?php\n //Creating a connection\n $con = mysqli_connect(\"localhost\", \"root\", \"password\", \"mydb\");\n\n //Executing the multi query\n $query = \"SELECT * FROM players\";\n \n //Retrieving the records\n $res = mysqli_query($con, $query, MYSQLI_USE_RESULT);\n if ($res) {\n while ($row = mysqli_fetch_row($res)) {\n print(\"Name: \".$row[0].\"\\n\");\n print(\"Age: \".$row[1].\"\\n\");\n }\n }\n\n //Closing the connection\n mysqli_close($con);\n?>"
},
{
"code": null,
"e": 8383,
"s": 8346,
"text": "This will produce following result −"
},
{
"code": null,
"e": 8445,
"s": 8383,
"text": "Name: Dhavan\nAge: 33\nName: Rohit\nAge: 28\nName: Kohli\nAge: 25\n"
},
{
"code": null,
"e": 8478,
"s": 8445,
"text": "\n 45 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 8494,
"s": 8478,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 8527,
"s": 8494,
"text": "\n 34 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 8538,
"s": 8527,
"text": " Syed Raza"
},
{
"code": null,
"e": 8573,
"s": 8538,
"text": "\n 84 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 8590,
"s": 8573,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 8623,
"s": 8590,
"text": "\n 17 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8638,
"s": 8623,
"text": " Nivedita Jain"
},
{
"code": null,
"e": 8673,
"s": 8638,
"text": "\n 100 Lectures \n 34 hours \n"
},
{
"code": null,
"e": 8685,
"s": 8673,
"text": " Azaz Patel"
},
{
"code": null,
"e": 8720,
"s": 8685,
"text": "\n 43 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 8748,
"s": 8720,
"text": " Vijay Kumar Parvatha Reddy"
},
{
"code": null,
"e": 8755,
"s": 8748,
"text": " Print"
},
{
"code": null,
"e": 8766,
"s": 8755,
"text": " Add Notes"
}
] |
Kth largest element in BST | Practice | GeeksforGeeks | Given a Binary search tree. Your task is to complete the function which will return the Kth largest element without doing any modification in Binary Search Tree.
Example 1:
Input:
4
/ \
2 9
k = 2
Output: 4
Example 2:
Input:
9
\
10
K = 1
Output: 10
Your Task:
You don't need to read input or print anything. Your task is to complete the function kthLargest() which takes the root of the BST and an integer K as inputs and returns the Kth largest element in the given BST.
Expected Time Complexity: O(H + K).
Expected Auxiliary Space: O(H)
Constraints:
1 <= N <= 1000
1 <= K <= N
0
18pa1a04771 day ago
without using extra space
def morri(root,ans,ans2=None,val=None):
cur=root
while(cur!=None):
if cur.left==None:
ans[0]+=1
# print(ans[0],val)
if ans[0]==val:
ans2.append(cur.data)
break
cur=cur.right
else:
pre=cur.left
while(pre.right!=None and pre.right!=cur):
pre=pre.right
if pre.right==cur:
ans[0]+=1
# print(ans[0],val)
if ans[0]==val:
ans2.append(cur.data)
break
cur=cur.right
pre.right=None
else:
pre.right=cur
cur=cur.left
class Solution:
def kthLargest(self,root, k):
ans=[0]
ans2=[]
morri(root,ans)
val=ans[0]-k+1
ans=[0]
morri(root,ans,ans2,val)
return ans2[0]
0
csedeepak4 days ago
simple cpp solution:
void inorder(Node *curr,vector<int> &ans){ if(curr==NULL) return; inorder(curr->left,ans); ans.push_back(curr->data); inorder(curr->right,ans);; } int kthLargest(Node *root, int K) { //Your code here vector<int> ans; inorder(root,ans); return ans[ans.size()-K]; }
0
utkarsh061 week ago
JUST DO REVERSE INORDER TRAVERSAL :)
void inorder(Node* root, int &K, int &ans)
{
if(!root) return;
inorder(root->right,K,ans);
K--;
if(K==0)
{
ans = root->data;
return;
}
inorder(root->left,K,ans);
}
int kthLargest(Node *root, int K)
{
int ans = -1;
inorder(root,K,ans);
return ans;
}
0
vishalsavade1 week ago
//Using property of BST Inorder traversal of BST is sorted list - 0.31/1.37
Solution 1: Using N extra space
void inorder(Node *root, vector<int> &v){
if(root == NULL) return;
if(root->left)inorder(root->left, v);
v.push_back(root->data);
if(root->right)inorder(root->right, v);
}
int kthLargest(Node *root, int k)
{
//Your code here
vector<int> v;
inorder(root, v);
return v[v.size() - k];
}
Solution 2: Using 1 extra space - 0.31/1.37
void inorder(Node *root, int &k, int &ans){
if(root == NULL) return;
if(root->right)inorder(root->right, k, ans);
k--;
if(k == 0)
ans = root->data;
if(root->left)inorder(root->left, k, ans);
}
int kthLargest(Node *root, int k)
{
//Your code here
int ans = -1;
inorder(root, k, ans);
return ans;
}
+2
ashishbhattacharyya52 weeks ago
Easy solution in java
class Solution{ // return the Kth largest element in the given BST rooted at 'root' ArrayList<Integer> array =new ArrayList<>(); public int kthLargest(Node root,int k) { //Your code here solve(root); return array.get(k-1); } void solve(Node root){ if(root==null){ return ; } solve(root.right); array.add(root.data); solve(root.left); }}
0
himanshu567842 weeks ago
class Solution{ void inorder(Node *root,vector<int>& ans) { if(!root)return; inorder(root->left,ans); ans.push_back(root->data); inorder(root->right,ans); } public: int kthLargest(Node *root, int K) { vector<int> ans; inorder(root,ans); return ans.at(ans.size()-K); }};
+1
anshulgupta966262 weeks ago
void inordertraversal(Node* root, int &k, int &ans) {
if(root == NULL){
return;
}
else{
inordertraversal(root->right, k, ans);
k--;
if(k == 0){
ans = root->data;
}
inordertraversal(root->left, k, ans);
}
}
int kthLargest(Node *root, int K)
{
//Your code here
int ans = -1;
inordertraversal(root, K, ans);
return ans;
}
0
f201900382 weeks ago
class Solution
{
public:
void inordertraversal(Node* root, int &k, int &ans) {
if(root) {
inordertraversal(root->right, k, ans);
k--;
if(k==0) {
ans = root->data;
}
inordertraversal(root->left, k, ans);
}
}
int kthLargest(Node *root, int K)
{
int ans = -1;
inordertraversal(root, K, ans);
return ans;
}
};
+1
nothades3 weeks ago
TC: O(n) SC = O(n)
vector<int> v;
void inorder(Node* root)
{
if (root==NULL)
return;
inorder(root->left);
v.push_back(root->data);
inorder(root->right);
}
int kthLargest(Node *root, int k)
{
inorder(root);
int n = v.size();
return v[n-k];
}
0
arankeparth19123 weeks ago
without using extra array:
class Solution{ public: void solve(Node*root,int k,int& place,int *ans) { if(root!=NULL) { solve(root->right,k,place,ans); if(place==k && *ans!=-1) *ans=root->data; place++; solve(root->left,k,place,ans); }
} int kthLargest(Node *root, int K) { int ans=0; int place=1; solve(root,K,place, &ans); return ans; }};
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab. | [
{
"code": null,
"e": 400,
"s": 238,
"text": "Given a Binary search tree. Your task is to complete the function which will return the Kth largest element without doing any modification in Binary Search Tree."
},
{
"code": null,
"e": 412,
"s": 400,
"text": "\nExample 1:"
},
{
"code": null,
"e": 466,
"s": 412,
"text": "Input:\n 4\n / \\\n 2 9\nk = 2 \nOutput: 4\n"
},
{
"code": null,
"e": 478,
"s": 466,
"text": "\nExample 2:"
},
{
"code": null,
"e": 536,
"s": 478,
"text": "Input:\n 9\n \\ \n 10\nK = 1\nOutput: 10\n"
},
{
"code": null,
"e": 760,
"s": 536,
"text": "\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function kthLargest() which takes the root of the BST and an integer K as inputs and returns the Kth largest element in the given BST."
},
{
"code": null,
"e": 828,
"s": 760,
"text": "\nExpected Time Complexity: O(H + K).\nExpected Auxiliary Space: O(H)"
},
{
"code": null,
"e": 869,
"s": 828,
"text": "\nConstraints:\n1 <= N <= 1000\n1 <= K <= N"
},
{
"code": null,
"e": 871,
"s": 869,
"text": "0"
},
{
"code": null,
"e": 891,
"s": 871,
"text": "18pa1a04771 day ago"
},
{
"code": null,
"e": 1843,
"s": 891,
"text": "without using extra space\ndef morri(root,ans,ans2=None,val=None):\n cur=root\n while(cur!=None):\n if cur.left==None:\n ans[0]+=1\n # print(ans[0],val)\n if ans[0]==val:\n ans2.append(cur.data)\n break\n cur=cur.right\n else:\n pre=cur.left\n while(pre.right!=None and pre.right!=cur):\n pre=pre.right\n if pre.right==cur:\n ans[0]+=1\n # print(ans[0],val)\n if ans[0]==val:\n ans2.append(cur.data)\n break\n cur=cur.right\n pre.right=None\n else:\n pre.right=cur\n cur=cur.left\nclass Solution:\n def kthLargest(self,root, k):\n ans=[0]\n ans2=[]\n morri(root,ans)\n val=ans[0]-k+1\n ans=[0]\n morri(root,ans,ans2,val)\n return ans2[0]"
},
{
"code": null,
"e": 1845,
"s": 1843,
"text": "0"
},
{
"code": null,
"e": 1865,
"s": 1845,
"text": "csedeepak4 days ago"
},
{
"code": null,
"e": 1886,
"s": 1865,
"text": "simple cpp solution:"
},
{
"code": null,
"e": 2222,
"s": 1886,
"text": "void inorder(Node *curr,vector<int> &ans){ if(curr==NULL) return; inorder(curr->left,ans); ans.push_back(curr->data); inorder(curr->right,ans);; } int kthLargest(Node *root, int K) { //Your code here vector<int> ans; inorder(root,ans); return ans[ans.size()-K]; }"
},
{
"code": null,
"e": 2224,
"s": 2222,
"text": "0"
},
{
"code": null,
"e": 2244,
"s": 2224,
"text": "utkarsh061 week ago"
},
{
"code": null,
"e": 2877,
"s": 2244,
"text": "JUST DO REVERSE INORDER TRAVERSAL :) \n void inorder(Node* root, int &K, int &ans)\n {\n if(!root) return;\n \n inorder(root->right,K,ans);\n \n K--;\n if(K==0)\n {\n ans = root->data;\n return;\n }\n \n inorder(root->left,K,ans);\n }\n \n int kthLargest(Node *root, int K)\n {\n int ans = -1;\n inorder(root,K,ans);\n return ans;\n }"
},
{
"code": null,
"e": 2879,
"s": 2877,
"text": "0"
},
{
"code": null,
"e": 2902,
"s": 2879,
"text": "vishalsavade1 week ago"
},
{
"code": null,
"e": 3831,
"s": 2902,
"text": "//Using property of BST Inorder traversal of BST is sorted list - 0.31/1.37\nSolution 1: Using N extra space\nvoid inorder(Node *root, vector<int> &v){\n if(root == NULL) return;\n if(root->left)inorder(root->left, v);\n v.push_back(root->data);\n if(root->right)inorder(root->right, v);\n }\n int kthLargest(Node *root, int k)\n {\n //Your code here\n vector<int> v;\n inorder(root, v);\n return v[v.size() - k];\n }\n \n Solution 2: Using 1 extra space - 0.31/1.37\n void inorder(Node *root, int &k, int &ans){\n if(root == NULL) return;\n if(root->right)inorder(root->right, k, ans);\n k--;\n if(k == 0)\n ans = root->data;\n if(root->left)inorder(root->left, k, ans);\n \n }\n int kthLargest(Node *root, int k)\n {\n //Your code here\n int ans = -1;\n inorder(root, k, ans);\n return ans;\n }"
},
{
"code": null,
"e": 3834,
"s": 3831,
"text": "+2"
},
{
"code": null,
"e": 3866,
"s": 3834,
"text": "ashishbhattacharyya52 weeks ago"
},
{
"code": null,
"e": 3890,
"s": 3868,
"text": "Easy solution in java"
},
{
"code": null,
"e": 4321,
"s": 3890,
"text": "class Solution{ // return the Kth largest element in the given BST rooted at 'root' ArrayList<Integer> array =new ArrayList<>(); public int kthLargest(Node root,int k) { //Your code here solve(root); return array.get(k-1); } void solve(Node root){ if(root==null){ return ; } solve(root.right); array.add(root.data); solve(root.left); }}"
},
{
"code": null,
"e": 4323,
"s": 4321,
"text": "0"
},
{
"code": null,
"e": 4348,
"s": 4323,
"text": "himanshu567842 weeks ago"
},
{
"code": null,
"e": 4675,
"s": 4348,
"text": "class Solution{ void inorder(Node *root,vector<int>& ans) { if(!root)return; inorder(root->left,ans); ans.push_back(root->data); inorder(root->right,ans); } public: int kthLargest(Node *root, int K) { vector<int> ans; inorder(root,ans); return ans.at(ans.size()-K); }};"
},
{
"code": null,
"e": 4678,
"s": 4675,
"text": "+1"
},
{
"code": null,
"e": 4706,
"s": 4678,
"text": "anshulgupta966262 weeks ago"
},
{
"code": null,
"e": 5203,
"s": 4706,
"text": "void inordertraversal(Node* root, int &k, int &ans) {\n if(root == NULL){\n return;\n }\n else{\n inordertraversal(root->right, k, ans);\n k--;\n if(k == 0){\n ans = root->data;\n }\n inordertraversal(root->left, k, ans);\n }\n }\n \n int kthLargest(Node *root, int K)\n {\n //Your code here\n int ans = -1;\n inordertraversal(root, K, ans);\n return ans;\n }\n "
},
{
"code": null,
"e": 5205,
"s": 5203,
"text": "0"
},
{
"code": null,
"e": 5226,
"s": 5205,
"text": "f201900382 weeks ago"
},
{
"code": null,
"e": 5682,
"s": 5226,
"text": "class Solution\n{\n public:\n \n void inordertraversal(Node* root, int &k, int &ans) {\n if(root) {\n inordertraversal(root->right, k, ans);\n k--;\n if(k==0) {\n ans = root->data;\n }\n inordertraversal(root->left, k, ans);\n }\n }\n \n int kthLargest(Node *root, int K)\n {\n int ans = -1;\n inordertraversal(root, K, ans);\n return ans;\n }\n};"
},
{
"code": null,
"e": 5685,
"s": 5682,
"text": "+1"
},
{
"code": null,
"e": 5705,
"s": 5685,
"text": "nothades3 weeks ago"
},
{
"code": null,
"e": 6054,
"s": 5705,
"text": "TC: O(n) SC = O(n)\n \n\tvector<int> v;\n \n void inorder(Node* root)\n {\n if (root==NULL)\n return;\n \tinorder(root->left);\n \tv.push_back(root->data);\n \tinorder(root->right);\n }\n \n int kthLargest(Node *root, int k)\n {\n inorder(root);\n int n = v.size();\n return v[n-k];\n }\n\n\n"
},
{
"code": null,
"e": 6056,
"s": 6054,
"text": "0"
},
{
"code": null,
"e": 6083,
"s": 6056,
"text": "arankeparth19123 weeks ago"
},
{
"code": null,
"e": 6110,
"s": 6083,
"text": "without using extra array:"
},
{
"code": null,
"e": 6423,
"s": 6110,
"text": "class Solution{ public: void solve(Node*root,int k,int& place,int *ans) { if(root!=NULL) { solve(root->right,k,place,ans); if(place==k && *ans!=-1) *ans=root->data; place++; solve(root->left,k,place,ans); }"
},
{
"code": null,
"e": 6563,
"s": 6423,
"text": " } int kthLargest(Node *root, int K) { int ans=0; int place=1; solve(root,K,place, &ans); return ans; }};"
},
{
"code": null,
"e": 6709,
"s": 6563,
"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": 6745,
"s": 6709,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 6755,
"s": 6745,
"text": "\nProblem\n"
},
{
"code": null,
"e": 6765,
"s": 6755,
"text": "\nContest\n"
},
{
"code": null,
"e": 6828,
"s": 6765,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 6976,
"s": 6828,
"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": 7184,
"s": 6976,
"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": 7290,
"s": 7184,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
C# | Adding new node or value at the end of LinkedList<T> - GeeksforGeeks | 01 Feb, 2019
LinkedList<T>.AddLast Method is used to add a new node or value at the end of the LinkedList<T>. There are 2 methods in the overload list of this method as follows:
AddLast(LinkedList<T>)AddLast(T)
AddLast(LinkedList<T>)
AddLast(T)
This method is used to add the specified new node at the end of the LinkedList<T>.
Syntax:
public void AddLast (System.Collections.Generic.LinkedListNode<T> node);
Here, node is the new LinkedListNode<T> to add at the end of the LinkedList<T>.
Exceptions:
ArgumentNullException : If the node is null.
InvalidOperationException : If the node belongs to another LinkedList<T>.
Example:
// C# code to add new node// at the end of LinkedListusing System;using System.Collections;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a LinkedList of Integers LinkedList<int> myList = new LinkedList<int>(); // Adding nodes in LinkedList myList.AddLast(2); myList.AddLast(4); myList.AddLast(6); myList.AddLast(6); myList.AddLast(6); myList.AddLast(8); // To get the count of nodes in LinkedList // before removing all the nodes Console.WriteLine("Total nodes in myList are : " + myList.Count); // Displaying the nodes in LinkedList foreach(int i in myList) { Console.WriteLine(i); } // Adding new node at the end of LinkedList // This will give error as node is null myList.AddLast(null); // To get the count of nodes in LinkedList // after removing all the nodes Console.WriteLine("Total nodes in myList are : " + myList.Count); // Displaying the nodes in LinkedList foreach(int i in myList) { Console.WriteLine(i); } }}
Runtime Error:
Unhandled Exception:System.ArgumentNullException: Value cannot be null.Parameter name: node
Note:
LinkedList<T> accepts null as a valid Value for reference types and allows duplicate values.
If the LinkedList<T> is empty, the new node becomes the First and the Last.
This method is an O(1) operation.
This method is used to add a new node containing the specified value at the end of the LinkedList<T>.
Syntax:
public System.Collections.Generic.LinkedListNode<T> AddLast (T value);
Here, value is the value to add at the end of the LinkedList<T>.
Return Value: The new LinkedListNode<T> containing value.
Example:
// C# code to add new node containing// the specified value at the end// of LinkedListusing System;using System.Collections;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a LinkedList of Integers LinkedList<int> myList = new LinkedList<int>(); // Adding nodes in LinkedList myList.AddLast(2); myList.AddLast(4); myList.AddLast(6); myList.AddLast(6); myList.AddLast(6); myList.AddLast(8); // To get the count of nodes in LinkedList // before removing all the nodes Console.WriteLine("Total nodes in myList are : " + myList.Count); // Displaying the nodes in LinkedList foreach(int i in myList) { Console.WriteLine(i); } // Adding new node containing the // specified value at the end of LinkedList myList.AddLast(20); // To get the count of nodes in LinkedList // after removing all the nodes Console.WriteLine("Total nodes in myList are : " + myList.Count); // Displaying the nodes in LinkedList foreach(int i in myList) { Console.WriteLine(i); } }}
Output:
Total nodes in myList are : 6
2
4
6
6
6
8
Total nodes in myList are : 7
2
4
6
6
6
8
20
Note:
LinkedList<T> accepts null as a valid Value for reference types and allows duplicate values.
If the LinkedList<T> is empty, the new node becomes the First and the Last.
This method is an O(1) operation.
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.linkedlist-1.addlast?view=netframework-4.7.2
CSharp-Generic-Namespace
CSharp-LinkedList
CSharp-LinkedList-Methods
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between Ref and Out keywords in C#
C# | Delegates
Top 50 C# Interview Questions & Answers
Introduction to .NET Framework
C# | Constructors
Extension Method in C#
C# | Class and Object
C# | Abstract Classes
Common Language Runtime (CLR) in C#
C# | Encapsulation | [
{
"code": null,
"e": 24127,
"s": 24099,
"text": "\n01 Feb, 2019"
},
{
"code": null,
"e": 24292,
"s": 24127,
"text": "LinkedList<T>.AddLast Method is used to add a new node or value at the end of the LinkedList<T>. There are 2 methods in the overload list of this method as follows:"
},
{
"code": null,
"e": 24325,
"s": 24292,
"text": "AddLast(LinkedList<T>)AddLast(T)"
},
{
"code": null,
"e": 24348,
"s": 24325,
"text": "AddLast(LinkedList<T>)"
},
{
"code": null,
"e": 24359,
"s": 24348,
"text": "AddLast(T)"
},
{
"code": null,
"e": 24442,
"s": 24359,
"text": "This method is used to add the specified new node at the end of the LinkedList<T>."
},
{
"code": null,
"e": 24450,
"s": 24442,
"text": "Syntax:"
},
{
"code": null,
"e": 24524,
"s": 24450,
"text": "public void AddLast (System.Collections.Generic.LinkedListNode<T> node);\n"
},
{
"code": null,
"e": 24604,
"s": 24524,
"text": "Here, node is the new LinkedListNode<T> to add at the end of the LinkedList<T>."
},
{
"code": null,
"e": 24616,
"s": 24604,
"text": "Exceptions:"
},
{
"code": null,
"e": 24661,
"s": 24616,
"text": "ArgumentNullException : If the node is null."
},
{
"code": null,
"e": 24735,
"s": 24661,
"text": "InvalidOperationException : If the node belongs to another LinkedList<T>."
},
{
"code": null,
"e": 24744,
"s": 24735,
"text": "Example:"
},
{
"code": "// C# code to add new node// at the end of LinkedListusing System;using System.Collections;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a LinkedList of Integers LinkedList<int> myList = new LinkedList<int>(); // Adding nodes in LinkedList myList.AddLast(2); myList.AddLast(4); myList.AddLast(6); myList.AddLast(6); myList.AddLast(6); myList.AddLast(8); // To get the count of nodes in LinkedList // before removing all the nodes Console.WriteLine(\"Total nodes in myList are : \" + myList.Count); // Displaying the nodes in LinkedList foreach(int i in myList) { Console.WriteLine(i); } // Adding new node at the end of LinkedList // This will give error as node is null myList.AddLast(null); // To get the count of nodes in LinkedList // after removing all the nodes Console.WriteLine(\"Total nodes in myList are : \" + myList.Count); // Displaying the nodes in LinkedList foreach(int i in myList) { Console.WriteLine(i); } }}",
"e": 25954,
"s": 24744,
"text": null
},
{
"code": null,
"e": 25969,
"s": 25954,
"text": "Runtime Error:"
},
{
"code": null,
"e": 26061,
"s": 25969,
"text": "Unhandled Exception:System.ArgumentNullException: Value cannot be null.Parameter name: node"
},
{
"code": null,
"e": 26067,
"s": 26061,
"text": "Note:"
},
{
"code": null,
"e": 26160,
"s": 26067,
"text": "LinkedList<T> accepts null as a valid Value for reference types and allows duplicate values."
},
{
"code": null,
"e": 26236,
"s": 26160,
"text": "If the LinkedList<T> is empty, the new node becomes the First and the Last."
},
{
"code": null,
"e": 26270,
"s": 26236,
"text": "This method is an O(1) operation."
},
{
"code": null,
"e": 26372,
"s": 26270,
"text": "This method is used to add a new node containing the specified value at the end of the LinkedList<T>."
},
{
"code": null,
"e": 26380,
"s": 26372,
"text": "Syntax:"
},
{
"code": null,
"e": 26452,
"s": 26380,
"text": "public System.Collections.Generic.LinkedListNode<T> AddLast (T value);\n"
},
{
"code": null,
"e": 26517,
"s": 26452,
"text": "Here, value is the value to add at the end of the LinkedList<T>."
},
{
"code": null,
"e": 26575,
"s": 26517,
"text": "Return Value: The new LinkedListNode<T> containing value."
},
{
"code": null,
"e": 26584,
"s": 26575,
"text": "Example:"
},
{
"code": "// C# code to add new node containing// the specified value at the end// of LinkedListusing System;using System.Collections;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a LinkedList of Integers LinkedList<int> myList = new LinkedList<int>(); // Adding nodes in LinkedList myList.AddLast(2); myList.AddLast(4); myList.AddLast(6); myList.AddLast(6); myList.AddLast(6); myList.AddLast(8); // To get the count of nodes in LinkedList // before removing all the nodes Console.WriteLine(\"Total nodes in myList are : \" + myList.Count); // Displaying the nodes in LinkedList foreach(int i in myList) { Console.WriteLine(i); } // Adding new node containing the // specified value at the end of LinkedList myList.AddLast(20); // To get the count of nodes in LinkedList // after removing all the nodes Console.WriteLine(\"Total nodes in myList are : \" + myList.Count); // Displaying the nodes in LinkedList foreach(int i in myList) { Console.WriteLine(i); } }}",
"e": 27819,
"s": 26584,
"text": null
},
{
"code": null,
"e": 27827,
"s": 27819,
"text": "Output:"
},
{
"code": null,
"e": 27915,
"s": 27827,
"text": "Total nodes in myList are : 6\n2\n4\n6\n6\n6\n8\nTotal nodes in myList are : 7\n2\n4\n6\n6\n6\n8\n20\n"
},
{
"code": null,
"e": 27921,
"s": 27915,
"text": "Note:"
},
{
"code": null,
"e": 28014,
"s": 27921,
"text": "LinkedList<T> accepts null as a valid Value for reference types and allows duplicate values."
},
{
"code": null,
"e": 28090,
"s": 28014,
"text": "If the LinkedList<T> is empty, the new node becomes the First and the Last."
},
{
"code": null,
"e": 28124,
"s": 28090,
"text": "This method is an O(1) operation."
},
{
"code": null,
"e": 28135,
"s": 28124,
"text": "Reference:"
},
{
"code": null,
"e": 28251,
"s": 28135,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.linkedlist-1.addlast?view=netframework-4.7.2"
},
{
"code": null,
"e": 28276,
"s": 28251,
"text": "CSharp-Generic-Namespace"
},
{
"code": null,
"e": 28294,
"s": 28276,
"text": "CSharp-LinkedList"
},
{
"code": null,
"e": 28320,
"s": 28294,
"text": "CSharp-LinkedList-Methods"
},
{
"code": null,
"e": 28323,
"s": 28320,
"text": "C#"
},
{
"code": null,
"e": 28421,
"s": 28323,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28430,
"s": 28421,
"text": "Comments"
},
{
"code": null,
"e": 28443,
"s": 28430,
"text": "Old Comments"
},
{
"code": null,
"e": 28489,
"s": 28443,
"text": "Difference between Ref and Out keywords in C#"
},
{
"code": null,
"e": 28504,
"s": 28489,
"text": "C# | Delegates"
},
{
"code": null,
"e": 28544,
"s": 28504,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 28575,
"s": 28544,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 28593,
"s": 28575,
"text": "C# | Constructors"
},
{
"code": null,
"e": 28616,
"s": 28593,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 28638,
"s": 28616,
"text": "C# | Class and Object"
},
{
"code": null,
"e": 28660,
"s": 28638,
"text": "C# | Abstract Classes"
},
{
"code": null,
"e": 28696,
"s": 28660,
"text": "Common Language Runtime (CLR) in C#"
}
] |
Matplotlib.pyplot.gcf() in Python - GeeksforGeeks | 23 Jan, 2022
Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack.
matplotlib.pyplot.gcf() is primarily used to get the current figure. If no current figure is available then one is created with the help of the figure() function.Syntax:
matplotlib.pyplot.gcf()
Example 1:
Python3
import numpy as npfrom matplotlib.backends.backend_agg import FigureCanvasAggimport matplotlib.pyplot as plot plot.plot([2, 3, 4]) # implementation of the# matplotlib.pyplot.gcf()# functionfigure = plot.gcf().canvas ag = figure.switch_backends(FigureCanvasAgg)ag.draw()A = np.asarray(ag.buffer_rgba()) # Pass off to PIL.from PIL import Imageimg = Image.fromarray(A) # show imageimg.show()
Output:
Example 2:
Python3
import matplotlib.pyplot as pltfrom matplotlib.tri import Triangulationfrom matplotlib.patches import Polygonimport numpy as np # helper function to update# the polygondef polygon_updater(tr): if tr == -1: points = [0, 0, 0] else: points = tri.triangles[tr] x_axis = tri.x[points] y_axis = tri.y[points] polygon.set_xy(np.column_stack([x_axis, y_axis])) # helper function to set the motion# of polygondef motion_handler(e): if e.inaxes is None: tr = -1 else: tr = trifinder(e.xdata, e.ydata) polygon_updater(tr) e.canvas.draw() # Making the Triangulation.all_angles = 16all_radii = 5minimum_radii = 0.25radii = np.linspace(minimum_radii, 0.95, all_radii)triangulation_angles = np.linspace(0, 2 * np.pi, all_angles, endpoint = False) triangulation_angles = np.repeat(triangulation_angles[..., np.newaxis], all_radii, axis = 1) triangulation_angles[:, 1::2] += np.pi / all_anglesa = (radii * np.cos(triangulation_angles)).flatten()b = (radii * np.sin(triangulation_angles)).flatten()tri = Triangulation(a, b)tri.set_mask(np.hypot(a[tri.triangles].mean(axis = 1), b[tri.triangles].mean(axis = 1)) < minimum_radii) # Using TriFinder object from# Triangulationtrifinder = tri.get_trifinder() # Setting up the plot and the callbacks.plt.subplot(111, aspect ='equal')plt.triplot(tri, 'g-') # dummy data for (x-axis, y-axis)polygon = Polygon([[0, 0], [0, 0]], facecolor ='b')polygon_updater(-1)plt.gca().add_patch(polygon) # implementation of the matplotlib.pyplot.gcf() functionplt.gcf().canvas.mpl_connect('motion_notification', motion_handler)plt.show()
Output:
saurabh1990aror
Python-matplotlib
Python
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Convert integer to string in Python
Convert string to integer in Python
Python infinity
How to set input type date in dd-mm-yyyy format using HTML ?
Matplotlib.pyplot.title() in Python | [
{
"code": null,
"e": 23979,
"s": 23951,
"text": "\n23 Jan, 2022"
},
{
"code": null,
"e": 24192,
"s": 23979,
"text": "Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. "
},
{
"code": null,
"e": 24363,
"s": 24192,
"text": "matplotlib.pyplot.gcf() is primarily used to get the current figure. If no current figure is available then one is created with the help of the figure() function.Syntax: "
},
{
"code": null,
"e": 24387,
"s": 24363,
"text": "matplotlib.pyplot.gcf()"
},
{
"code": null,
"e": 24398,
"s": 24387,
"text": "Example 1:"
},
{
"code": null,
"e": 24406,
"s": 24398,
"text": "Python3"
},
{
"code": "import numpy as npfrom matplotlib.backends.backend_agg import FigureCanvasAggimport matplotlib.pyplot as plot plot.plot([2, 3, 4]) # implementation of the# matplotlib.pyplot.gcf()# functionfigure = plot.gcf().canvas ag = figure.switch_backends(FigureCanvasAgg)ag.draw()A = np.asarray(ag.buffer_rgba()) # Pass off to PIL.from PIL import Imageimg = Image.fromarray(A) # show imageimg.show()",
"e": 24795,
"s": 24406,
"text": null
},
{
"code": null,
"e": 24805,
"s": 24795,
"text": "Output: "
},
{
"code": null,
"e": 24818,
"s": 24805,
"text": "Example 2: "
},
{
"code": null,
"e": 24826,
"s": 24818,
"text": "Python3"
},
{
"code": "import matplotlib.pyplot as pltfrom matplotlib.tri import Triangulationfrom matplotlib.patches import Polygonimport numpy as np # helper function to update# the polygondef polygon_updater(tr): if tr == -1: points = [0, 0, 0] else: points = tri.triangles[tr] x_axis = tri.x[points] y_axis = tri.y[points] polygon.set_xy(np.column_stack([x_axis, y_axis])) # helper function to set the motion# of polygondef motion_handler(e): if e.inaxes is None: tr = -1 else: tr = trifinder(e.xdata, e.ydata) polygon_updater(tr) e.canvas.draw() # Making the Triangulation.all_angles = 16all_radii = 5minimum_radii = 0.25radii = np.linspace(minimum_radii, 0.95, all_radii)triangulation_angles = np.linspace(0, 2 * np.pi, all_angles, endpoint = False) triangulation_angles = np.repeat(triangulation_angles[..., np.newaxis], all_radii, axis = 1) triangulation_angles[:, 1::2] += np.pi / all_anglesa = (radii * np.cos(triangulation_angles)).flatten()b = (radii * np.sin(triangulation_angles)).flatten()tri = Triangulation(a, b)tri.set_mask(np.hypot(a[tri.triangles].mean(axis = 1), b[tri.triangles].mean(axis = 1)) < minimum_radii) # Using TriFinder object from# Triangulationtrifinder = tri.get_trifinder() # Setting up the plot and the callbacks.plt.subplot(111, aspect ='equal')plt.triplot(tri, 'g-') # dummy data for (x-axis, y-axis)polygon = Polygon([[0, 0], [0, 0]], facecolor ='b')polygon_updater(-1)plt.gca().add_patch(polygon) # implementation of the matplotlib.pyplot.gcf() functionplt.gcf().canvas.mpl_connect('motion_notification', motion_handler)plt.show()",
"e": 26670,
"s": 24826,
"text": null
},
{
"code": null,
"e": 26680,
"s": 26670,
"text": "Output: "
},
{
"code": null,
"e": 26698,
"s": 26682,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 26716,
"s": 26698,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 26723,
"s": 26716,
"text": "Python"
},
{
"code": null,
"e": 26739,
"s": 26723,
"text": "Write From Home"
},
{
"code": null,
"e": 26837,
"s": 26739,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26846,
"s": 26837,
"text": "Comments"
},
{
"code": null,
"e": 26859,
"s": 26846,
"text": "Old Comments"
},
{
"code": null,
"e": 26877,
"s": 26859,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26912,
"s": 26877,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 26944,
"s": 26912,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26986,
"s": 26944,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27012,
"s": 26986,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27048,
"s": 27012,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 27084,
"s": 27048,
"text": "Convert string to integer in Python"
},
{
"code": null,
"e": 27100,
"s": 27084,
"text": "Python infinity"
},
{
"code": null,
"e": 27161,
"s": 27100,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
}
] |
Predictive Analytics: Bayesian Linear Regression in Python | by Niousha Rasifaghihi | Towards Data Science | In this post, I would like to focus more on the Bayesian Linear Regression theory and implement the modelling in Python for a data science project. The whole project is about forecasting urban water consumption under the impact of climate change in the next three decades. The complete version of the code is available as a Jupyter Notebook on GitHub and I encourage you to check it out. Also, the result is published in Sustainable Cities and Societies.
Statistics have two main branches, descriptive statistics and inferential statistics. Descriptive statistics provide a concise summary of data, while inferential statistics find patterns and make inferences about the data. But why am I talking about these two terms? 😀 Well, there are two general “philosophies” in inferential statistics that are important for us; frequentism and Bayesianism.
Frequentist statistics and Bayesian statistics divide the statistics world by two different approaches to define probability. In Frequentist statistics, the probability is related to the frequencies of the repeated events, whereas, in Bayesian statistics, the probability is related to our own certainty and uncertainty. Therefore, the consequence is that frequentists believe models are fixed, and data vary around them, but Bayesians talk about observed data being fixed, and the models can vary around them.
So the answer to this question “why Bayesian Statistics?” is, with Bayesian statistics, we can use probabilities to represent the uncertainty in any event or hypothesis.
Bayes theorem is the key rule in Bayesian statistics [1]. If H is a hypothesis and D is observed data, the Bayes theorem is as follows
where P(H|D) represents the posterior probability of the hypothesis given the condition that D occurs. P(H) is the prior probability of the hypothesis, P(D) is the marginal (total) probability of observed data and is effectively a normalizing constant, and P(D|H) is the probability (likelihood) of data given hypothesis.
The city of Brossard, Quebec, Canada, is chosen as a study site. I obtained a time series of daily urban water consumption, q, over the time period of January 2011 to October 2015. For the same time period, I also obtained time series of climatic variables: daily minimum temperature θ, daily maximum temperature t, and total precipitation p. Measurements of these climatic variables were made from an Environment Canada station in the Pierre Elliott Trudeau International Airport (YUL).
Bayesian statistics is a powerful technique for probabilistic modelling that has been adopted in a wide range of statistical modelling, including Linear Regression models to make a prediction about a system [2,3,4,5]. A Linear Regression model is expressed as
where q is the dependent (target) variable, β_0 is the intercept; β_1, β_2, and β_3 are the weights (known as the model parameters); θ, t and p are called the predictor variables; and ε is an error term representing random noise or the effect of variables not included in the model equation. The equation can be rewritten as
where β= (β_0, β_1, β_2, β_3); and X = (1, q, Q, p) [2,6]. The Linear Regression is formulated using probability distributions rather than point estimates to predict q. Therefore, q is not estimated as a single value but is assumed to be drawn from a probability distribution. The model for Bayesian Linear Regression with the response sampled from a normal (Gaussian) distribution N is
The output, q, is generated from a normal distribution characterized by a mean and variance. The mean for the normal distribution is the regression coefficient matrix (β) multiplied by the predictor matrix (X). The variance is the square of the standard deviation, σ.
The Bayesian Linear Regression model provides the representation of the uncertainties in predictor variables and determines the posterior distribution for the model parameters. Not only is the response generated from a probability distribution, but the model parameters are assumed to come from distribution as well. The posterior probability of the model parameters comes from Bayes theorem:
where P(β|q,X) is the posterior probability distribution of the model parameter given the predictors and the independent variable; P(q|β,X) is the likelihood of data; P(β |X) is the prior probability of parameters and the denominator of the equation is the marginal probability that can be found as per the law of total probability.
In practice, it is difficult to compute the marginal likelihood for continuous values; it is intractable to calculate the exact posterior distribution. As a solution, a sampling method Markov Chain Monte Carlo is involved in approximating the posterior without computing the marginal likelihood [3,5,7]. Monte Carlo is a general technique of drawing random samples, and Markov Chain means the next sample drawn is based only on the previous sample value. By bringing more samples, the approximation of the posterior will eventually converge on the actual posterior distribution for β_1, β_2, and β_3.
As the starting point in applying Markov Chain Monte Carlo, define parameter space covering all the possible values for β_1, β_2, and β_3. Then, define the prior probability for each of the parameters as a normal distribution. Next, compute the likelihood for each possible parameter. Last, compute prior × likelihood for any given point in parameter space.
Markov Chain Monte Carlo is implemented using the No-U-Turn algorithm [8]. This algorithm is efficient when the variables involved are continuous and there is no need to set the number of steps. This is an advantage over Hamiltonian Monte Carlo, which takes a series of steps informed by first-order gradient information, and is sensitive to the number of steps.
A set of parameter values for accepted moves are generated (if the proposed move is not accepted, the previous value is repeated) and after many repetitions, the empirical approximation of the distribution is found. Eventually, the result of performing Bayesian Linear Regression is the probability density function of possible model parameters based on the data and the prior.
The entire dataset is split into training and testing sets. The training set contains 75% of data and used to build the model; while, the testing set contains 25% and is utilized for verifying the accuracy of prediction. Also, two goodness-of-fit measures are used to evaluate the performance of models developed in this study. These measures are Mean Absolute Error and Root Mean Squared Error. Mean Absolute Error is the average of the absolute value of the difference between predictions and the actual values, and Root Mean Squared Error is the square root of the average of the squared differences between the predictions and the actual values.
As I mentioned before, my focus in this post is on the Bayesian Linear Regression model. Therefore, I skip the data pre-processing step. The input dataset to the Bayesian Linear Regression model is as follow
UWC: Urban water consumption
Max_T: Maximum temperature
Min_T: Minimum temperature
T_P: Total precipitation
⚠️ Prior to model creation, make sure you have handled missing values because the Bayesian Linear Regression model does not take data with missing points.
First, I use sklearn library to split the pre-processed dataset (df) as 75% training and 25% testing.
Note: X_train and X_test include the target variable, UWC.
from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(df, df['UWC'],test_size = 0.25,random_state = 42)
In this project, I create the Bayesian Linear Regression Model in PyMC3. Let a Markov Chain Monte Carlo algorithm draw samples from the posterior to approximate the posterior for each of the model parameters.
To create the model, I pass the Linear Regression formula, the family which is the prior for the parameters and the data to GLM. To perform Markov Chain Monte Carlo sampling, I specify the number of samples, 2000, the number of chains, 2, and the number of tuning steps, 500.
import pymc3 as pmfrom pymc3 import traceplot# Formula for Bayesian Linear Regression formula = ‘UWC ~ ‘ + ‘ + ‘.join([‘%s’ % variable for variable in X_train.columns[1:]])print(formula)# Context for the modelwith pm.Model() as normal_model: # The prior for the model parameters will be a normal distribution family = pm.glm.families.Normal()# Creating the model requires a formula and data (and optionally a family) pm.GLM.from_formula(formula, data = X_train, family = family)# Perform Markov Chain Monte Carlo sampling normal_trace = pm.sample(draws=2000, chains = 2, tune = 500)
So, UWC is a function of maximum temperature, minimum temperature and total precipitation.
pm.plot_posterior(normal_trace)
The results are illustrated as posterior histograms for β_0, β_1, β_2, β_3, and σ. The histograms show 95% Highest Posterior Density (HPD), which is a credible interval for the parameters. A credible interval in Bayesian statistics is an equivalent of a confidence interval. For example, the probability of 0.034 <σ< 0.037 is 95%.
To calculate MAE and RMSE, I take the median of the probability distribution for UWC and give it as the prediction to evaluate_prediction function.
# Define a function to calculate MAE and RMSEdef evaluate_prediction(prediction, true): mae = np.mean(abs(predictions - true)) rmse = np.sqrt(np.mean((predictions - true) ** 2)) return mae, rmsemedian_pred = X_train['UWC'].median()median_preds = [median_pred for _ in range(len(X_test))]true = X_test['UWC']# Display mae and rmsemae, rmse = evaluate_prediction(median_preds, true)print('Mean Absolute Error: {:.4f}'.format(mae))print('Root Mean Square Error: {:.4f}'.format(rmse))
The assessment of model performance shows that the predictor model has good accuracy.
This post was a very brief overview of Bayesian Linear Regression for a data science project. I hope it helped you to better understand Bayesian Linear Regression fundamentals.😊
Your feedback is greatly appreciated. You can reach me on LinkedIn.
[1] Heckerman, D., Geiger, D., & Chickering, D. M. (1995). Learning Bayesian Networks: The Combination of Knowledge and Statistical Data. Machine Learning, 20(3), 197–243. https://doi.org/10.1023/A:1022623210503
[2] Han, Jiawei and Pei, Jian and Kamber, M. (2011). Data mining: concepts and techniques. Retrieved from http://myweb.sabanciuniv.edu/rdehkharghani/files/2016/02/The-Morgan-Kaufmann-Series-in-Data-Management-Systems-Jiawei-Han-Micheline-Kamber-Jian-Pei-Data-Mining.-Concepts-and-Techniques-3rd-Edition-Morgan-Kaufmann-2011.pdf
[3] Mudgal, A., Hallmark, S., Carriquiry, A., & Gkritza, K. (2014). Driving behavior at a roundabout: A hierarchical Bayesian regression analysis. Transportation Research Part D: Transport and Environment, 26, 20–26. https://doi.org/10.1016/j.trd.2013.10.003
[4] Raftery, A. E., Madigan, D., & Hoeting, J. A. (1997). Bayesian Model Averaging for Linear Regression Models. Journal of the American Statistical Association, 92(437), 179–191. Retrieved from https://www.tandfonline.com/doi/abs/10.1080/01621459.1997.10473615
[5] Yuan, X. C., Sun, X., Zhao, W., Mi, Z., Wang, B., & Wei, Y. M. (2017). Forecasting China’s regional energy demand by 2030: A Bayesian approach. Resources, Conservation and Recycling, 127(May), 85–95. https://doi.org/10.1016/j.resconrec.2017.08.016
[6] Taleb, T., & Kaddour, M. (2017). Hierarchical agglomerative clustering schemes for energy-efficiency in wireless sensor networks. Transport and Telecommunication, 18(2), 128–138. https://doi.org/10.1515/ttj-2017-0012
[7] Godsill, S. J. (2001). On the relationship between markov chain monte carlo methods for model uncertainty. Journal of Computational and Graphical Statistics, 10(2), 230–248. https://doi.org/10.1198/10618600152627924
[8] Hoffman, M. D., & Gelman, A. (2011). The No-U-Turn Sampler: Adaptively Setting Path Lengths in Hamiltonian Monte Carlo. (2008), 1–30. Retrieved from http://arxiv.org/abs/1111.4246 | [
{
"code": null,
"e": 626,
"s": 171,
"text": "In this post, I would like to focus more on the Bayesian Linear Regression theory and implement the modelling in Python for a data science project. The whole project is about forecasting urban water consumption under the impact of climate change in the next three decades. The complete version of the code is available as a Jupyter Notebook on GitHub and I encourage you to check it out. Also, the result is published in Sustainable Cities and Societies."
},
{
"code": null,
"e": 1020,
"s": 626,
"text": "Statistics have two main branches, descriptive statistics and inferential statistics. Descriptive statistics provide a concise summary of data, while inferential statistics find patterns and make inferences about the data. But why am I talking about these two terms? 😀 Well, there are two general “philosophies” in inferential statistics that are important for us; frequentism and Bayesianism."
},
{
"code": null,
"e": 1531,
"s": 1020,
"text": "Frequentist statistics and Bayesian statistics divide the statistics world by two different approaches to define probability. In Frequentist statistics, the probability is related to the frequencies of the repeated events, whereas, in Bayesian statistics, the probability is related to our own certainty and uncertainty. Therefore, the consequence is that frequentists believe models are fixed, and data vary around them, but Bayesians talk about observed data being fixed, and the models can vary around them."
},
{
"code": null,
"e": 1701,
"s": 1531,
"text": "So the answer to this question “why Bayesian Statistics?” is, with Bayesian statistics, we can use probabilities to represent the uncertainty in any event or hypothesis."
},
{
"code": null,
"e": 1836,
"s": 1701,
"text": "Bayes theorem is the key rule in Bayesian statistics [1]. If H is a hypothesis and D is observed data, the Bayes theorem is as follows"
},
{
"code": null,
"e": 2158,
"s": 1836,
"text": "where P(H|D) represents the posterior probability of the hypothesis given the condition that D occurs. P(H) is the prior probability of the hypothesis, P(D) is the marginal (total) probability of observed data and is effectively a normalizing constant, and P(D|H) is the probability (likelihood) of data given hypothesis."
},
{
"code": null,
"e": 2646,
"s": 2158,
"text": "The city of Brossard, Quebec, Canada, is chosen as a study site. I obtained a time series of daily urban water consumption, q, over the time period of January 2011 to October 2015. For the same time period, I also obtained time series of climatic variables: daily minimum temperature θ, daily maximum temperature t, and total precipitation p. Measurements of these climatic variables were made from an Environment Canada station in the Pierre Elliott Trudeau International Airport (YUL)."
},
{
"code": null,
"e": 2906,
"s": 2646,
"text": "Bayesian statistics is a powerful technique for probabilistic modelling that has been adopted in a wide range of statistical modelling, including Linear Regression models to make a prediction about a system [2,3,4,5]. A Linear Regression model is expressed as"
},
{
"code": null,
"e": 3231,
"s": 2906,
"text": "where q is the dependent (target) variable, β_0 is the intercept; β_1, β_2, and β_3 are the weights (known as the model parameters); θ, t and p are called the predictor variables; and ε is an error term representing random noise or the effect of variables not included in the model equation. The equation can be rewritten as"
},
{
"code": null,
"e": 3618,
"s": 3231,
"text": "where β= (β_0, β_1, β_2, β_3); and X = (1, q, Q, p) [2,6]. The Linear Regression is formulated using probability distributions rather than point estimates to predict q. Therefore, q is not estimated as a single value but is assumed to be drawn from a probability distribution. The model for Bayesian Linear Regression with the response sampled from a normal (Gaussian) distribution N is"
},
{
"code": null,
"e": 3886,
"s": 3618,
"text": "The output, q, is generated from a normal distribution characterized by a mean and variance. The mean for the normal distribution is the regression coefficient matrix (β) multiplied by the predictor matrix (X). The variance is the square of the standard deviation, σ."
},
{
"code": null,
"e": 4279,
"s": 3886,
"text": "The Bayesian Linear Regression model provides the representation of the uncertainties in predictor variables and determines the posterior distribution for the model parameters. Not only is the response generated from a probability distribution, but the model parameters are assumed to come from distribution as well. The posterior probability of the model parameters comes from Bayes theorem:"
},
{
"code": null,
"e": 4612,
"s": 4279,
"text": "where P(β|q,X) is the posterior probability distribution of the model parameter given the predictors and the independent variable; P(q|β,X) is the likelihood of data; P(β |X) is the prior probability of parameters and the denominator of the equation is the marginal probability that can be found as per the law of total probability."
},
{
"code": null,
"e": 5213,
"s": 4612,
"text": "In practice, it is difficult to compute the marginal likelihood for continuous values; it is intractable to calculate the exact posterior distribution. As a solution, a sampling method Markov Chain Monte Carlo is involved in approximating the posterior without computing the marginal likelihood [3,5,7]. Monte Carlo is a general technique of drawing random samples, and Markov Chain means the next sample drawn is based only on the previous sample value. By bringing more samples, the approximation of the posterior will eventually converge on the actual posterior distribution for β_1, β_2, and β_3."
},
{
"code": null,
"e": 5571,
"s": 5213,
"text": "As the starting point in applying Markov Chain Monte Carlo, define parameter space covering all the possible values for β_1, β_2, and β_3. Then, define the prior probability for each of the parameters as a normal distribution. Next, compute the likelihood for each possible parameter. Last, compute prior × likelihood for any given point in parameter space."
},
{
"code": null,
"e": 5934,
"s": 5571,
"text": "Markov Chain Monte Carlo is implemented using the No-U-Turn algorithm [8]. This algorithm is efficient when the variables involved are continuous and there is no need to set the number of steps. This is an advantage over Hamiltonian Monte Carlo, which takes a series of steps informed by first-order gradient information, and is sensitive to the number of steps."
},
{
"code": null,
"e": 6312,
"s": 5934,
"text": "A set of parameter values for accepted moves are generated (if the proposed move is not accepted, the previous value is repeated) and after many repetitions, the empirical approximation of the distribution is found. Eventually, the result of performing Bayesian Linear Regression is the probability density function of possible model parameters based on the data and the prior."
},
{
"code": null,
"e": 6962,
"s": 6312,
"text": "The entire dataset is split into training and testing sets. The training set contains 75% of data and used to build the model; while, the testing set contains 25% and is utilized for verifying the accuracy of prediction. Also, two goodness-of-fit measures are used to evaluate the performance of models developed in this study. These measures are Mean Absolute Error and Root Mean Squared Error. Mean Absolute Error is the average of the absolute value of the difference between predictions and the actual values, and Root Mean Squared Error is the square root of the average of the squared differences between the predictions and the actual values."
},
{
"code": null,
"e": 7170,
"s": 6962,
"text": "As I mentioned before, my focus in this post is on the Bayesian Linear Regression model. Therefore, I skip the data pre-processing step. The input dataset to the Bayesian Linear Regression model is as follow"
},
{
"code": null,
"e": 7199,
"s": 7170,
"text": "UWC: Urban water consumption"
},
{
"code": null,
"e": 7226,
"s": 7199,
"text": "Max_T: Maximum temperature"
},
{
"code": null,
"e": 7253,
"s": 7226,
"text": "Min_T: Minimum temperature"
},
{
"code": null,
"e": 7278,
"s": 7253,
"text": "T_P: Total precipitation"
},
{
"code": null,
"e": 7433,
"s": 7278,
"text": "⚠️ Prior to model creation, make sure you have handled missing values because the Bayesian Linear Regression model does not take data with missing points."
},
{
"code": null,
"e": 7535,
"s": 7433,
"text": "First, I use sklearn library to split the pre-processed dataset (df) as 75% training and 25% testing."
},
{
"code": null,
"e": 7594,
"s": 7535,
"text": "Note: X_train and X_test include the target variable, UWC."
},
{
"code": null,
"e": 7748,
"s": 7594,
"text": "from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(df, df['UWC'],test_size = 0.25,random_state = 42)"
},
{
"code": null,
"e": 7957,
"s": 7748,
"text": "In this project, I create the Bayesian Linear Regression Model in PyMC3. Let a Markov Chain Monte Carlo algorithm draw samples from the posterior to approximate the posterior for each of the model parameters."
},
{
"code": null,
"e": 8233,
"s": 7957,
"text": "To create the model, I pass the Linear Regression formula, the family which is the prior for the parameters and the data to GLM. To perform Markov Chain Monte Carlo sampling, I specify the number of samples, 2000, the number of chains, 2, and the number of tuning steps, 500."
},
{
"code": null,
"e": 8836,
"s": 8233,
"text": "import pymc3 as pmfrom pymc3 import traceplot# Formula for Bayesian Linear Regression formula = ‘UWC ~ ‘ + ‘ + ‘.join([‘%s’ % variable for variable in X_train.columns[1:]])print(formula)# Context for the modelwith pm.Model() as normal_model: # The prior for the model parameters will be a normal distribution family = pm.glm.families.Normal()# Creating the model requires a formula and data (and optionally a family) pm.GLM.from_formula(formula, data = X_train, family = family)# Perform Markov Chain Monte Carlo sampling normal_trace = pm.sample(draws=2000, chains = 2, tune = 500)"
},
{
"code": null,
"e": 8927,
"s": 8836,
"text": "So, UWC is a function of maximum temperature, minimum temperature and total precipitation."
},
{
"code": null,
"e": 8959,
"s": 8927,
"text": "pm.plot_posterior(normal_trace)"
},
{
"code": null,
"e": 9290,
"s": 8959,
"text": "The results are illustrated as posterior histograms for β_0, β_1, β_2, β_3, and σ. The histograms show 95% Highest Posterior Density (HPD), which is a credible interval for the parameters. A credible interval in Bayesian statistics is an equivalent of a confidence interval. For example, the probability of 0.034 <σ< 0.037 is 95%."
},
{
"code": null,
"e": 9438,
"s": 9290,
"text": "To calculate MAE and RMSE, I take the median of the probability distribution for UWC and give it as the prediction to evaluate_prediction function."
},
{
"code": null,
"e": 9932,
"s": 9438,
"text": "# Define a function to calculate MAE and RMSEdef evaluate_prediction(prediction, true): mae = np.mean(abs(predictions - true)) rmse = np.sqrt(np.mean((predictions - true) ** 2)) return mae, rmsemedian_pred = X_train['UWC'].median()median_preds = [median_pred for _ in range(len(X_test))]true = X_test['UWC']# Display mae and rmsemae, rmse = evaluate_prediction(median_preds, true)print('Mean Absolute Error: {:.4f}'.format(mae))print('Root Mean Square Error: {:.4f}'.format(rmse))"
},
{
"code": null,
"e": 10018,
"s": 9932,
"text": "The assessment of model performance shows that the predictor model has good accuracy."
},
{
"code": null,
"e": 10196,
"s": 10018,
"text": "This post was a very brief overview of Bayesian Linear Regression for a data science project. I hope it helped you to better understand Bayesian Linear Regression fundamentals.😊"
},
{
"code": null,
"e": 10264,
"s": 10196,
"text": "Your feedback is greatly appreciated. You can reach me on LinkedIn."
},
{
"code": null,
"e": 10476,
"s": 10264,
"text": "[1] Heckerman, D., Geiger, D., & Chickering, D. M. (1995). Learning Bayesian Networks: The Combination of Knowledge and Statistical Data. Machine Learning, 20(3), 197–243. https://doi.org/10.1023/A:1022623210503"
},
{
"code": null,
"e": 10804,
"s": 10476,
"text": "[2] Han, Jiawei and Pei, Jian and Kamber, M. (2011). Data mining: concepts and techniques. Retrieved from http://myweb.sabanciuniv.edu/rdehkharghani/files/2016/02/The-Morgan-Kaufmann-Series-in-Data-Management-Systems-Jiawei-Han-Micheline-Kamber-Jian-Pei-Data-Mining.-Concepts-and-Techniques-3rd-Edition-Morgan-Kaufmann-2011.pdf"
},
{
"code": null,
"e": 11063,
"s": 10804,
"text": "[3] Mudgal, A., Hallmark, S., Carriquiry, A., & Gkritza, K. (2014). Driving behavior at a roundabout: A hierarchical Bayesian regression analysis. Transportation Research Part D: Transport and Environment, 26, 20–26. https://doi.org/10.1016/j.trd.2013.10.003"
},
{
"code": null,
"e": 11325,
"s": 11063,
"text": "[4] Raftery, A. E., Madigan, D., & Hoeting, J. A. (1997). Bayesian Model Averaging for Linear Regression Models. Journal of the American Statistical Association, 92(437), 179–191. Retrieved from https://www.tandfonline.com/doi/abs/10.1080/01621459.1997.10473615"
},
{
"code": null,
"e": 11577,
"s": 11325,
"text": "[5] Yuan, X. C., Sun, X., Zhao, W., Mi, Z., Wang, B., & Wei, Y. M. (2017). Forecasting China’s regional energy demand by 2030: A Bayesian approach. Resources, Conservation and Recycling, 127(May), 85–95. https://doi.org/10.1016/j.resconrec.2017.08.016"
},
{
"code": null,
"e": 11798,
"s": 11577,
"text": "[6] Taleb, T., & Kaddour, M. (2017). Hierarchical agglomerative clustering schemes for energy-efficiency in wireless sensor networks. Transport and Telecommunication, 18(2), 128–138. https://doi.org/10.1515/ttj-2017-0012"
},
{
"code": null,
"e": 12018,
"s": 11798,
"text": "[7] Godsill, S. J. (2001). On the relationship between markov chain monte carlo methods for model uncertainty. Journal of Computational and Graphical Statistics, 10(2), 230–248. https://doi.org/10.1198/10618600152627924"
}
] |
Let’s Forecast Your Time Series using Classical Approaches | by Ajay Tiwari | Towards Data Science | We learned various data preparation techniques and also set up a robust evaluation framework in my previous articles. Now, we are ready to explore different forecasting techniques.
With the availability of many machine learning models, often we forget the power of our classical algorithms. It is a good idea to start with classical approaches. Even though the classical approaches are focused on the linear relationship, they perform well on a wide range of problems assuming the data is suitably prepared.
Here is the list of techniques that are going to be discussed in the current article. We will also discuss their Python implementation.
1. Univariate Time Series Forecasting1.1. Autoregression1.2. Moving Average1.3. Autoregressive Moving Average1.4. Autoregressive Integrated Moving Average1.5. Seasonal Autoregressive Integrated Moving Average2. Multivariate Time Series Forecasting2.1. Vector Auto-Regression2.2. Vector Moving Average2.3. Vector Auto Regression Moving Average3. Time Series Forecasting with Exogenous Variables3.1. SARIMA with Exogenous Variables3.2. Vector Autoregression Moving-Average with Exogenous Regressors 4. Time Series Forecasting with Smoothing Techniques4.1. Moving Average Smoothing4.2. Single Exponential Smoothing4.3. Double Exponential Smoothing4.4. Triple Exponential Smoothing
These are datasets where only a single variable is observed at each time, such as temperature each hour. The univariate time series is modeled as a linear combination of its lags. That is, the past values of the series are used to forecast the current and future.
Autoregression models an output (value at the next step) based on the linear combination of input variables (values at prior time steps). For example, in linear regression y-hat is the prediction, β0 and β1 are coefficients calculated by the model on training data, and X is an input value.
Similarly, in time series we can predict the value at the next time step given the observations at current and previous time steps.
‘p’ is the auto-regressive trend parameter, the ideal value for p can be determined from an autocorrelation plot.
The method is suitable for time series without trend and seasonal components.
Python Implementation — AR
# Import librariesfrom statsmodels.tsa.ar_model import AutoRegfrom random import random# Generate a sample datasetdata = [x + random() for x in range(1, 100)]# fit modelmodel = AutoReg(data, lags=1)model_fit = model.fit()# make predictionyhat = model_fit.predict(len(data), len(data))print(yhat)
The difference between observed and predicted values is called the residual error. These errors from forecasts on a time series provide another source of information that we can model. It is calculated as:
residual error = observed — predicted
Therefore, the moving average method is also called the model of residual error, this method models the next step in the sequence as a linear function of the residual errors. You can observe this difference in the following equation.
‘q’ is the moving-average trend parameter, ideal value for q can be determined from the partial auto-correlation plot.
The method is suitable for time series without trend and seasonal components.
Python Implementation — MA
# Import librariesfrom statsmodels.tsa.arima_model import ARMAfrom random import random# Generate a sample datasetdata = [x + random() for x in range(1, 100)]# fit modelmodel = ARMA(data, order=(0, 1))model_fit = model.fit(disp=False)# make predictionyhat = model_fit.predict(len(data), len(data))print(yhat)
The Autoregressive Moving Average (ARMA) method uses both the above information (original observations and residual errors) for forecasting, it as an advancement over individual AR and MA models.
Therefore, this method models the next step in the sequence as a linear function of the observations and residual errors at prior time steps.
Modelers have to specify both the parameters p and q for both components of the model, i.e., autoregressive (AR) and moving average (MA).
The method is suitable for time series without trend and seasonal components.
Python Implementation — ARMA
# Import librariesfrom statsmodels.tsa.arima_model import ARMAfrom random import random# Generate a sample datasetdata = [random() for x in range(1, 100)]# fit modelmodel = ARMA(data, order=(2, 1))model_fit = model.fit(disp=False)# make predictionyhat = model_fit.predict(len(data), len(data))print(yhat)
The statistical models we have discussed so far assume the time series to be stationary, but in reality, most of the time series is not stationary, i.e the statistical properties of a series like mean, variance changes over time.
Therefore, we can add one more step as a pre-processing step, i.e., differencing (‘d’) the time series to make it stationary.
Now, we have a method that combines both Autoregression (AR) and Moving Average (MA) models as well as a differencing pre-processing step of the sequence to make the sequence stationary, called integration (I).
Therefore, we need to find out whether the time series we are dealing with is stationary or not. We can diagnose stationarity by looking at seasonality and trend in time series plots, checking the difference in mean and variance for various periods, and the Augmented Dickey-Fuller (ADF) test. You can find these techniques in detail in my previous article ‘Build Foundation for Time Series Forecasting’.
The method is suitable for time series with trend and without seasonal components.
Python Implementation — ARIMA
# Import librariesfrom statsmodels.tsa.arima_model import ARIMAfrom random import random# Generate a sample datasetdata = [x + random() for x in range(1, 100)]# fit modelmodel = ARIMA(data, order=(1, 1, 1))model_fit = model.fit(disp=False)# make predictionyhat = model_fit.predict(len(data), len(data), typ='levels')print(yhat)
This method is an extension of the ARIMA model to deal with seasonal data. It models seasonal and non-seasonal components of the series separately.
There are four other seasonal parameters added to this approach in addition to three trend related parameters used in the ARIMA approach.
Non-seasonal parameters same as ARIMA
p: Autoregressive orderd: Differencing orderq: Moving average order
Seasonal parameters
P: Seasonal autoregressive orderD: Seasonal differencing orderQ: Seasonal moving average orderm: Number of time steps for a single seasonal period
The method is suitable for time series with trend and/or seasonal components.
Python Implementation — SARIMA
# Import librariesfrom statsmodels.tsa.statespace.sarimax import SARIMAXfrom random import random# Generate a sample datasetdata = [x + random() for x in range(1, 100)]# fit modelmodel = SARIMAX(data, order=(1, 1, 1), seasonal_order=(1, 1, 1, 1))model_fit = model.fit(disp=False)# make predictionyhat = model_fit.predict(len(data), len(data))print(yhat)
These are datasets where two or more variables are observed at each time. In multivariate time series, each variable is modeled as a linear combination of past values of itself and the past values of other variables in the system.
It is a generalized version of the autoregression model to forecast multiple parallel stationary time series. It comprises one equation per variable in the system. The right-hand side of each equation includes a constant and lags of all of the variables in the system.
There are two decisions we have to make when using a VAR to forecast, namely how many variables (K) and how many lags (p) should be included in the system.
The number of coefficients to be estimated in a VAR is equal to K+pK2 (or 1+pK per equation). For example, for a VAR with K=5 variables and p=2 lags, there are 11 coefficients per equation, giving a total of 55 coefficients to be estimated. The more coefficients that need to be estimated, the larger the estimation error.
Therefore, it is advisable to keep K small and include only variables that are correlated with each other, and therefore useful in forecasting each other. Information criteria are commonly used to select the number of lags (p) to be included.
Python Implementation — VAR
# Import librariesfrom statsmodels.tsa.vector_ar.var_model import VARfrom random import random# Generate a sample dataset with correlated variablesdata = list()for i in range(100): v1 = i + random() v2 = v1 + random() row = [v1, v2] data.append(row)# fit modelmodel = VAR(data)model_fit = model.fit()# make predictionyhat = model_fit.forecast(model_fit.y, steps=1)print(yhat)
The VAR can also be implemented using VARMAX function in Statsmodels which allows estimation of VAR, VMA, VARMA, and VARMAX models through the order argument.
It is a generalized version of the moving average model to forecast multiple parallel stationary time series.
Python Implementation — VMA
# Import librariesfrom statsmodels.tsa.statespace.varmax import VARMAXfrom random import random# Generate a sample dataset with correlated variablesdata = list()for i in range(100): v1 = i+ random() v2 = v1 + random() row = [v1, v2] data.append(row)# fit VMA model by setting the ‘p’ parameter as 0.model = VARMAX(data, order=(0, 1))model_fit = model.fit(disp=False)# make predictionyhat = model_fit.forecast()print(yhat)
It is the combination of VAR and VMA and a generalized version of the ARMA model to forecast multiple parallel stationary time series.
This method requires ‘p’ and ‘q’ parameters and is also capable of acting like a VAR model by setting the ‘q’ parameter as 0 and as a VMA model by setting the ‘p’ parameter as 0.
Python Implementation — VARMA
# Import librariesfrom statsmodels.tsa.statespace.varmax import VARMAXfrom random import random# Generate a sample dataset with correlated variablesdata = list()for i in range(100): v1 = random() v2 = v1 + random() row = [v1, v2] data.append(row)# fit modelmodel = VARMAX(data, order=(1, 1))model_fit = model.fit(disp=False)# make predictionyhat = model_fit.forecast()print(yhat)
The Seasonal Autoregressive Integrated Moving-Average with Exogenous Regressors (SARIMAX) is an extension of the SARIMA model that also includes the modeling of exogenous variables.
Before moving ahead let’s understand endogenous and exogenous variables.
An exogenous variable is one whose value is determined outside the model and is imposed on the model. Here, X is an exogenous variable
An endogenous variable is a variable whose value is determined by the model. Here, main series to be forecasted is an endogenous variable.
In time series, the exogenous variable is a parallel time series that are not modeled directly but is used as a weighted input to the model.
The method is suitable for univariate time series with trend and/or seasonal components and exogenous variables.
Python Implementation — SARIMAX
# Import librariesfrom statsmodels.tsa.statespace.sarimax import SARIMAXfrom random import random# Generate a sample dataset with independent exogenous variabledata1 = [x + random() for x in range(1, 100)]data2 = [x + random() for x in range(101, 200)]# fit modelmodel = SARIMAX(data1, exog=data2, order=(1, 1, 1), seasonal_order=(0, 0, 0, 0))model_fit = model.fit(disp=False)# make predictionexog2 = [200 + random()]yhat = model_fit.predict(len(data1), len(data1), exog=[exog2])print(yhat)
The SARIMAX method can also be used to model the other variations with exogenous variables, such as ARX, MAX, ARMAX, and ARIMAX by including an exogenous variable.
This method is an extension of the VARMA model that also includes the modeling of exogenous variables. It is a multivariate version of the ARMAX method.
The method is suitable for multivariate time series without trend and seasonal components with exogenous variables.
Python Implementation — VARMAX
# Import librariesfrom statsmodels.tsa.statespace.varmax import VARMAXfrom random import random# Generate a sample dataset with correlated multiple time series and an independent exogenous variabledata = list()for i in range(100): v1 = random() v2 = v1 + random() row = [v1, v2] data.append(row)data_exog = [x + random() for x in range(100)]# fit modelmodel = VARMAX(data, exog=data_exog, order=(1, 1))model_fit = model.fit(disp=False)# make predictiondata_exog2 = [[100]]yhat = model_fit.forecast(exog=data_exog2)print(yhat)
Moving average smoothing is a simple and effective technique in time series forecasting. The same name but very different from the moving average model which we discussed in the beginning. The earlier version of the moving average (MA) is a model of residual errors, whereas this smoothing technique consists of averaging values across a window of consecutive periods.
In general, there are two types of moving averages are used:
The value at the time (t) is calculated as the average value of current, before and after the time (t). For example, a centered moving average with window width 3:
centered_ma(t) = mean(obs(t+1), obs(t), obs(t-1))
Centered moving average requires the availability of future values, often we find this method impractical to use for forecasting.
The value at the time (t) is calculated as the average value of current and before the time (t). For example, a trailing moving average with window width 3:
trail_ma(t) = mean(obs(t), obs(t-1), obs(t-2))
Trailing moving averages uses only current and historical observations to predict the future.
This method mainly used in feature engineering, it can also be used in making predictions. We can use the newly created series of ‘moving average values’ to forecast the next step using a naive model. Before forecasting, we assume that the trend and seasonality components of the time series have already been removed or adjusted for.
There is no python function available for this approach, instead, we can create a custom function, you can refer naive model implementation in my previous article.
Exponential smoothing is a time series forecasting method for univariate data. It is a close alternative to the popular Box-Jenkins ARIMA class of methods.
Both approaches predict a weighted sum of past observations, here is the important difference to be noted.
ARIMA family develops a model where the prediction is a weighted linear sum of recent past observations or lags, whereas exponential smoothing explicitly uses an exponentially decreasing weight for past observations.
This method is also called Simple Exponential Smoothing, suitable for forecasting data with no clear trend or seasonal pattern. Mathematically,
where, alpha, a smoothing parameter falls between 0 and 1. A large value means the model pays importance to the most recent observation, whereas smaller value means the oldest observations are more significant.
Python Implementation — SES
# Import librariesfrom statsmodels.tsa.holtwinters import SimpleExpSmoothingfrom random import random# Generate a sample datasetdata = [x + random() for x in range(1, 100)]# fit modelmodel = SimpleExpSmoothing(data)model_fit = model.fit()# make predictionyhat = model_fit.predict(len(data), len(data))print(yhat)
Double exponential smoothing is an extension to the above approach (SES), this method allows the forecasting of data with a trend. Mathematically,
In addition to the alpha, a smoothing factor for the level, an additional smoothing factor is added to control the decay of the influence of the change in a trend called beta.
These methods tend to over-forecast, especially for longer forecast horizons. Motivated by this observation, Gardner & McKenzie (1985) introduced a parameter that “dampens” the trend to a flat line sometime in the future.
Therefore, in conjunction with the smoothing parameters α and β (with values between 0 and 1), this method also includes a damping parameter φ which also ranges between 0 and 1.
Python Implementation — Double Exponential Smoothing
# Import librariesfrom statsmodels.tsa.holtwinters import ExponentialSmoothingfrom random import random# Generate a sample datasetdata = [x + random() for x in range(1, 100)]# fit modelmodel = ExponentialSmoothing(data,trend='add', seasonal=None, damped=True)model_fit = model.fit()# make predictionyhat = model_fit.predict(len(data), len(data))print(yhat)
Triple Exponential Smoothing is the most advanced variation in the family, this method is also known as Holt-Winters Exponential Smoothing, named for two contributors to the method: Charles Holt and Peter Winters.
In addition to the alpha and beta smoothing factors, a new parameter is added called gamma (g) that controls the influence on the seasonal component.
Damping is possible with both additive and multiplicative Holt-Winters’ methods. A method that often provides accurate and robust forecasts for seasonal data.
Python Implementation — Holt-Winters Exponential Smoothing
# Import librariesfrom statsmodels.tsa.holtwinters import ExponentialSmoothingfrom random import random# Generate a sample datasetdata = [x + random() for x in range(1, 100)]# fit modelmodel = ExponentialSmoothing(data,trend="add", seasonal="add", seasonal_periods=12, damped=True)model_fit = model.fit()# make predictionyhat = model_fit.predict(len(data), len(data))print(yhat)
In this article, you discovered all the important classical forecasting techniques that can help you in getting started with your forecasting problems. You can deep dive into the suitable techniques and tune it further as per your need. To build a robust forecasting model, you must start by performing the right data transformation, set up an evaluation strategy, and have ready with a persistence (benchmark) model.
Thanks for reading! Please feel free to share any comments or feedback.
Hope you found this article informative, in the next few articles I will discuss some of the commonly used techniques in detail.
[1] Galit Shmueli and Kenneth Lichtendahl, Practical Time Series Forecasting with R: A Hands-On Guide, 2016.
[2] Jason Brownlee, https://machinelearningmastery.com/ | [
{
"code": null,
"e": 353,
"s": 172,
"text": "We learned various data preparation techniques and also set up a robust evaluation framework in my previous articles. Now, we are ready to explore different forecasting techniques."
},
{
"code": null,
"e": 680,
"s": 353,
"text": "With the availability of many machine learning models, often we forget the power of our classical algorithms. It is a good idea to start with classical approaches. Even though the classical approaches are focused on the linear relationship, they perform well on a wide range of problems assuming the data is suitably prepared."
},
{
"code": null,
"e": 816,
"s": 680,
"text": "Here is the list of techniques that are going to be discussed in the current article. We will also discuss their Python implementation."
},
{
"code": null,
"e": 1494,
"s": 816,
"text": "1. Univariate Time Series Forecasting1.1. Autoregression1.2. Moving Average1.3. Autoregressive Moving Average1.4. Autoregressive Integrated Moving Average1.5. Seasonal Autoregressive Integrated Moving Average2. Multivariate Time Series Forecasting2.1. Vector Auto-Regression2.2. Vector Moving Average2.3. Vector Auto Regression Moving Average3. Time Series Forecasting with Exogenous Variables3.1. SARIMA with Exogenous Variables3.2. Vector Autoregression Moving-Average with Exogenous Regressors 4. Time Series Forecasting with Smoothing Techniques4.1. Moving Average Smoothing4.2. Single Exponential Smoothing4.3. Double Exponential Smoothing4.4. Triple Exponential Smoothing"
},
{
"code": null,
"e": 1758,
"s": 1494,
"text": "These are datasets where only a single variable is observed at each time, such as temperature each hour. The univariate time series is modeled as a linear combination of its lags. That is, the past values of the series are used to forecast the current and future."
},
{
"code": null,
"e": 2049,
"s": 1758,
"text": "Autoregression models an output (value at the next step) based on the linear combination of input variables (values at prior time steps). For example, in linear regression y-hat is the prediction, β0 and β1 are coefficients calculated by the model on training data, and X is an input value."
},
{
"code": null,
"e": 2181,
"s": 2049,
"text": "Similarly, in time series we can predict the value at the next time step given the observations at current and previous time steps."
},
{
"code": null,
"e": 2295,
"s": 2181,
"text": "‘p’ is the auto-regressive trend parameter, the ideal value for p can be determined from an autocorrelation plot."
},
{
"code": null,
"e": 2373,
"s": 2295,
"text": "The method is suitable for time series without trend and seasonal components."
},
{
"code": null,
"e": 2400,
"s": 2373,
"text": "Python Implementation — AR"
},
{
"code": null,
"e": 2696,
"s": 2400,
"text": "# Import librariesfrom statsmodels.tsa.ar_model import AutoRegfrom random import random# Generate a sample datasetdata = [x + random() for x in range(1, 100)]# fit modelmodel = AutoReg(data, lags=1)model_fit = model.fit()# make predictionyhat = model_fit.predict(len(data), len(data))print(yhat)"
},
{
"code": null,
"e": 2902,
"s": 2696,
"text": "The difference between observed and predicted values is called the residual error. These errors from forecasts on a time series provide another source of information that we can model. It is calculated as:"
},
{
"code": null,
"e": 2940,
"s": 2902,
"text": "residual error = observed — predicted"
},
{
"code": null,
"e": 3174,
"s": 2940,
"text": "Therefore, the moving average method is also called the model of residual error, this method models the next step in the sequence as a linear function of the residual errors. You can observe this difference in the following equation."
},
{
"code": null,
"e": 3293,
"s": 3174,
"text": "‘q’ is the moving-average trend parameter, ideal value for q can be determined from the partial auto-correlation plot."
},
{
"code": null,
"e": 3371,
"s": 3293,
"text": "The method is suitable for time series without trend and seasonal components."
},
{
"code": null,
"e": 3398,
"s": 3371,
"text": "Python Implementation — MA"
},
{
"code": null,
"e": 3707,
"s": 3398,
"text": "# Import librariesfrom statsmodels.tsa.arima_model import ARMAfrom random import random# Generate a sample datasetdata = [x + random() for x in range(1, 100)]# fit modelmodel = ARMA(data, order=(0, 1))model_fit = model.fit(disp=False)# make predictionyhat = model_fit.predict(len(data), len(data))print(yhat)"
},
{
"code": null,
"e": 3903,
"s": 3707,
"text": "The Autoregressive Moving Average (ARMA) method uses both the above information (original observations and residual errors) for forecasting, it as an advancement over individual AR and MA models."
},
{
"code": null,
"e": 4045,
"s": 3903,
"text": "Therefore, this method models the next step in the sequence as a linear function of the observations and residual errors at prior time steps."
},
{
"code": null,
"e": 4183,
"s": 4045,
"text": "Modelers have to specify both the parameters p and q for both components of the model, i.e., autoregressive (AR) and moving average (MA)."
},
{
"code": null,
"e": 4261,
"s": 4183,
"text": "The method is suitable for time series without trend and seasonal components."
},
{
"code": null,
"e": 4290,
"s": 4261,
"text": "Python Implementation — ARMA"
},
{
"code": null,
"e": 4595,
"s": 4290,
"text": "# Import librariesfrom statsmodels.tsa.arima_model import ARMAfrom random import random# Generate a sample datasetdata = [random() for x in range(1, 100)]# fit modelmodel = ARMA(data, order=(2, 1))model_fit = model.fit(disp=False)# make predictionyhat = model_fit.predict(len(data), len(data))print(yhat)"
},
{
"code": null,
"e": 4825,
"s": 4595,
"text": "The statistical models we have discussed so far assume the time series to be stationary, but in reality, most of the time series is not stationary, i.e the statistical properties of a series like mean, variance changes over time."
},
{
"code": null,
"e": 4951,
"s": 4825,
"text": "Therefore, we can add one more step as a pre-processing step, i.e., differencing (‘d’) the time series to make it stationary."
},
{
"code": null,
"e": 5162,
"s": 4951,
"text": "Now, we have a method that combines both Autoregression (AR) and Moving Average (MA) models as well as a differencing pre-processing step of the sequence to make the sequence stationary, called integration (I)."
},
{
"code": null,
"e": 5567,
"s": 5162,
"text": "Therefore, we need to find out whether the time series we are dealing with is stationary or not. We can diagnose stationarity by looking at seasonality and trend in time series plots, checking the difference in mean and variance for various periods, and the Augmented Dickey-Fuller (ADF) test. You can find these techniques in detail in my previous article ‘Build Foundation for Time Series Forecasting’."
},
{
"code": null,
"e": 5650,
"s": 5567,
"text": "The method is suitable for time series with trend and without seasonal components."
},
{
"code": null,
"e": 5680,
"s": 5650,
"text": "Python Implementation — ARIMA"
},
{
"code": null,
"e": 6008,
"s": 5680,
"text": "# Import librariesfrom statsmodels.tsa.arima_model import ARIMAfrom random import random# Generate a sample datasetdata = [x + random() for x in range(1, 100)]# fit modelmodel = ARIMA(data, order=(1, 1, 1))model_fit = model.fit(disp=False)# make predictionyhat = model_fit.predict(len(data), len(data), typ='levels')print(yhat)"
},
{
"code": null,
"e": 6156,
"s": 6008,
"text": "This method is an extension of the ARIMA model to deal with seasonal data. It models seasonal and non-seasonal components of the series separately."
},
{
"code": null,
"e": 6294,
"s": 6156,
"text": "There are four other seasonal parameters added to this approach in addition to three trend related parameters used in the ARIMA approach."
},
{
"code": null,
"e": 6332,
"s": 6294,
"text": "Non-seasonal parameters same as ARIMA"
},
{
"code": null,
"e": 6400,
"s": 6332,
"text": "p: Autoregressive orderd: Differencing orderq: Moving average order"
},
{
"code": null,
"e": 6420,
"s": 6400,
"text": "Seasonal parameters"
},
{
"code": null,
"e": 6567,
"s": 6420,
"text": "P: Seasonal autoregressive orderD: Seasonal differencing orderQ: Seasonal moving average orderm: Number of time steps for a single seasonal period"
},
{
"code": null,
"e": 6645,
"s": 6567,
"text": "The method is suitable for time series with trend and/or seasonal components."
},
{
"code": null,
"e": 6676,
"s": 6645,
"text": "Python Implementation — SARIMA"
},
{
"code": null,
"e": 7030,
"s": 6676,
"text": "# Import librariesfrom statsmodels.tsa.statespace.sarimax import SARIMAXfrom random import random# Generate a sample datasetdata = [x + random() for x in range(1, 100)]# fit modelmodel = SARIMAX(data, order=(1, 1, 1), seasonal_order=(1, 1, 1, 1))model_fit = model.fit(disp=False)# make predictionyhat = model_fit.predict(len(data), len(data))print(yhat)"
},
{
"code": null,
"e": 7261,
"s": 7030,
"text": "These are datasets where two or more variables are observed at each time. In multivariate time series, each variable is modeled as a linear combination of past values of itself and the past values of other variables in the system."
},
{
"code": null,
"e": 7530,
"s": 7261,
"text": "It is a generalized version of the autoregression model to forecast multiple parallel stationary time series. It comprises one equation per variable in the system. The right-hand side of each equation includes a constant and lags of all of the variables in the system."
},
{
"code": null,
"e": 7686,
"s": 7530,
"text": "There are two decisions we have to make when using a VAR to forecast, namely how many variables (K) and how many lags (p) should be included in the system."
},
{
"code": null,
"e": 8009,
"s": 7686,
"text": "The number of coefficients to be estimated in a VAR is equal to K+pK2 (or 1+pK per equation). For example, for a VAR with K=5 variables and p=2 lags, there are 11 coefficients per equation, giving a total of 55 coefficients to be estimated. The more coefficients that need to be estimated, the larger the estimation error."
},
{
"code": null,
"e": 8252,
"s": 8009,
"text": "Therefore, it is advisable to keep K small and include only variables that are correlated with each other, and therefore useful in forecasting each other. Information criteria are commonly used to select the number of lags (p) to be included."
},
{
"code": null,
"e": 8280,
"s": 8252,
"text": "Python Implementation — VAR"
},
{
"code": null,
"e": 8668,
"s": 8280,
"text": "# Import librariesfrom statsmodels.tsa.vector_ar.var_model import VARfrom random import random# Generate a sample dataset with correlated variablesdata = list()for i in range(100): v1 = i + random() v2 = v1 + random() row = [v1, v2] data.append(row)# fit modelmodel = VAR(data)model_fit = model.fit()# make predictionyhat = model_fit.forecast(model_fit.y, steps=1)print(yhat)"
},
{
"code": null,
"e": 8827,
"s": 8668,
"text": "The VAR can also be implemented using VARMAX function in Statsmodels which allows estimation of VAR, VMA, VARMA, and VARMAX models through the order argument."
},
{
"code": null,
"e": 8937,
"s": 8827,
"text": "It is a generalized version of the moving average model to forecast multiple parallel stationary time series."
},
{
"code": null,
"e": 8965,
"s": 8937,
"text": "Python Implementation — VMA"
},
{
"code": null,
"e": 9399,
"s": 8965,
"text": "# Import librariesfrom statsmodels.tsa.statespace.varmax import VARMAXfrom random import random# Generate a sample dataset with correlated variablesdata = list()for i in range(100): v1 = i+ random() v2 = v1 + random() row = [v1, v2] data.append(row)# fit VMA model by setting the ‘p’ parameter as 0.model = VARMAX(data, order=(0, 1))model_fit = model.fit(disp=False)# make predictionyhat = model_fit.forecast()print(yhat)"
},
{
"code": null,
"e": 9534,
"s": 9399,
"text": "It is the combination of VAR and VMA and a generalized version of the ARMA model to forecast multiple parallel stationary time series."
},
{
"code": null,
"e": 9713,
"s": 9534,
"text": "This method requires ‘p’ and ‘q’ parameters and is also capable of acting like a VAR model by setting the ‘q’ parameter as 0 and as a VMA model by setting the ‘p’ parameter as 0."
},
{
"code": null,
"e": 9743,
"s": 9713,
"text": "Python Implementation — VARMA"
},
{
"code": null,
"e": 10135,
"s": 9743,
"text": "# Import librariesfrom statsmodels.tsa.statespace.varmax import VARMAXfrom random import random# Generate a sample dataset with correlated variablesdata = list()for i in range(100): v1 = random() v2 = v1 + random() row = [v1, v2] data.append(row)# fit modelmodel = VARMAX(data, order=(1, 1))model_fit = model.fit(disp=False)# make predictionyhat = model_fit.forecast()print(yhat)"
},
{
"code": null,
"e": 10317,
"s": 10135,
"text": "The Seasonal Autoregressive Integrated Moving-Average with Exogenous Regressors (SARIMAX) is an extension of the SARIMA model that also includes the modeling of exogenous variables."
},
{
"code": null,
"e": 10390,
"s": 10317,
"text": "Before moving ahead let’s understand endogenous and exogenous variables."
},
{
"code": null,
"e": 10525,
"s": 10390,
"text": "An exogenous variable is one whose value is determined outside the model and is imposed on the model. Here, X is an exogenous variable"
},
{
"code": null,
"e": 10664,
"s": 10525,
"text": "An endogenous variable is a variable whose value is determined by the model. Here, main series to be forecasted is an endogenous variable."
},
{
"code": null,
"e": 10805,
"s": 10664,
"text": "In time series, the exogenous variable is a parallel time series that are not modeled directly but is used as a weighted input to the model."
},
{
"code": null,
"e": 10918,
"s": 10805,
"text": "The method is suitable for univariate time series with trend and/or seasonal components and exogenous variables."
},
{
"code": null,
"e": 10950,
"s": 10918,
"text": "Python Implementation — SARIMAX"
},
{
"code": null,
"e": 11441,
"s": 10950,
"text": "# Import librariesfrom statsmodels.tsa.statespace.sarimax import SARIMAXfrom random import random# Generate a sample dataset with independent exogenous variabledata1 = [x + random() for x in range(1, 100)]data2 = [x + random() for x in range(101, 200)]# fit modelmodel = SARIMAX(data1, exog=data2, order=(1, 1, 1), seasonal_order=(0, 0, 0, 0))model_fit = model.fit(disp=False)# make predictionexog2 = [200 + random()]yhat = model_fit.predict(len(data1), len(data1), exog=[exog2])print(yhat)"
},
{
"code": null,
"e": 11605,
"s": 11441,
"text": "The SARIMAX method can also be used to model the other variations with exogenous variables, such as ARX, MAX, ARMAX, and ARIMAX by including an exogenous variable."
},
{
"code": null,
"e": 11758,
"s": 11605,
"text": "This method is an extension of the VARMA model that also includes the modeling of exogenous variables. It is a multivariate version of the ARMAX method."
},
{
"code": null,
"e": 11874,
"s": 11758,
"text": "The method is suitable for multivariate time series without trend and seasonal components with exogenous variables."
},
{
"code": null,
"e": 11905,
"s": 11874,
"text": "Python Implementation — VARMAX"
},
{
"code": null,
"e": 12443,
"s": 11905,
"text": "# Import librariesfrom statsmodels.tsa.statespace.varmax import VARMAXfrom random import random# Generate a sample dataset with correlated multiple time series and an independent exogenous variabledata = list()for i in range(100): v1 = random() v2 = v1 + random() row = [v1, v2] data.append(row)data_exog = [x + random() for x in range(100)]# fit modelmodel = VARMAX(data, exog=data_exog, order=(1, 1))model_fit = model.fit(disp=False)# make predictiondata_exog2 = [[100]]yhat = model_fit.forecast(exog=data_exog2)print(yhat)"
},
{
"code": null,
"e": 12812,
"s": 12443,
"text": "Moving average smoothing is a simple and effective technique in time series forecasting. The same name but very different from the moving average model which we discussed in the beginning. The earlier version of the moving average (MA) is a model of residual errors, whereas this smoothing technique consists of averaging values across a window of consecutive periods."
},
{
"code": null,
"e": 12873,
"s": 12812,
"text": "In general, there are two types of moving averages are used:"
},
{
"code": null,
"e": 13037,
"s": 12873,
"text": "The value at the time (t) is calculated as the average value of current, before and after the time (t). For example, a centered moving average with window width 3:"
},
{
"code": null,
"e": 13087,
"s": 13037,
"text": "centered_ma(t) = mean(obs(t+1), obs(t), obs(t-1))"
},
{
"code": null,
"e": 13217,
"s": 13087,
"text": "Centered moving average requires the availability of future values, often we find this method impractical to use for forecasting."
},
{
"code": null,
"e": 13374,
"s": 13217,
"text": "The value at the time (t) is calculated as the average value of current and before the time (t). For example, a trailing moving average with window width 3:"
},
{
"code": null,
"e": 13421,
"s": 13374,
"text": "trail_ma(t) = mean(obs(t), obs(t-1), obs(t-2))"
},
{
"code": null,
"e": 13515,
"s": 13421,
"text": "Trailing moving averages uses only current and historical observations to predict the future."
},
{
"code": null,
"e": 13850,
"s": 13515,
"text": "This method mainly used in feature engineering, it can also be used in making predictions. We can use the newly created series of ‘moving average values’ to forecast the next step using a naive model. Before forecasting, we assume that the trend and seasonality components of the time series have already been removed or adjusted for."
},
{
"code": null,
"e": 14014,
"s": 13850,
"text": "There is no python function available for this approach, instead, we can create a custom function, you can refer naive model implementation in my previous article."
},
{
"code": null,
"e": 14170,
"s": 14014,
"text": "Exponential smoothing is a time series forecasting method for univariate data. It is a close alternative to the popular Box-Jenkins ARIMA class of methods."
},
{
"code": null,
"e": 14277,
"s": 14170,
"text": "Both approaches predict a weighted sum of past observations, here is the important difference to be noted."
},
{
"code": null,
"e": 14494,
"s": 14277,
"text": "ARIMA family develops a model where the prediction is a weighted linear sum of recent past observations or lags, whereas exponential smoothing explicitly uses an exponentially decreasing weight for past observations."
},
{
"code": null,
"e": 14638,
"s": 14494,
"text": "This method is also called Simple Exponential Smoothing, suitable for forecasting data with no clear trend or seasonal pattern. Mathematically,"
},
{
"code": null,
"e": 14849,
"s": 14638,
"text": "where, alpha, a smoothing parameter falls between 0 and 1. A large value means the model pays importance to the most recent observation, whereas smaller value means the oldest observations are more significant."
},
{
"code": null,
"e": 14877,
"s": 14849,
"text": "Python Implementation — SES"
},
{
"code": null,
"e": 15190,
"s": 14877,
"text": "# Import librariesfrom statsmodels.tsa.holtwinters import SimpleExpSmoothingfrom random import random# Generate a sample datasetdata = [x + random() for x in range(1, 100)]# fit modelmodel = SimpleExpSmoothing(data)model_fit = model.fit()# make predictionyhat = model_fit.predict(len(data), len(data))print(yhat)"
},
{
"code": null,
"e": 15337,
"s": 15190,
"text": "Double exponential smoothing is an extension to the above approach (SES), this method allows the forecasting of data with a trend. Mathematically,"
},
{
"code": null,
"e": 15513,
"s": 15337,
"text": "In addition to the alpha, a smoothing factor for the level, an additional smoothing factor is added to control the decay of the influence of the change in a trend called beta."
},
{
"code": null,
"e": 15735,
"s": 15513,
"text": "These methods tend to over-forecast, especially for longer forecast horizons. Motivated by this observation, Gardner & McKenzie (1985) introduced a parameter that “dampens” the trend to a flat line sometime in the future."
},
{
"code": null,
"e": 15913,
"s": 15735,
"text": "Therefore, in conjunction with the smoothing parameters α and β (with values between 0 and 1), this method also includes a damping parameter φ which also ranges between 0 and 1."
},
{
"code": null,
"e": 15966,
"s": 15913,
"text": "Python Implementation — Double Exponential Smoothing"
},
{
"code": null,
"e": 16323,
"s": 15966,
"text": "# Import librariesfrom statsmodels.tsa.holtwinters import ExponentialSmoothingfrom random import random# Generate a sample datasetdata = [x + random() for x in range(1, 100)]# fit modelmodel = ExponentialSmoothing(data,trend='add', seasonal=None, damped=True)model_fit = model.fit()# make predictionyhat = model_fit.predict(len(data), len(data))print(yhat)"
},
{
"code": null,
"e": 16537,
"s": 16323,
"text": "Triple Exponential Smoothing is the most advanced variation in the family, this method is also known as Holt-Winters Exponential Smoothing, named for two contributors to the method: Charles Holt and Peter Winters."
},
{
"code": null,
"e": 16687,
"s": 16537,
"text": "In addition to the alpha and beta smoothing factors, a new parameter is added called gamma (g) that controls the influence on the seasonal component."
},
{
"code": null,
"e": 16846,
"s": 16687,
"text": "Damping is possible with both additive and multiplicative Holt-Winters’ methods. A method that often provides accurate and robust forecasts for seasonal data."
},
{
"code": null,
"e": 16905,
"s": 16846,
"text": "Python Implementation — Holt-Winters Exponential Smoothing"
},
{
"code": null,
"e": 17284,
"s": 16905,
"text": "# Import librariesfrom statsmodels.tsa.holtwinters import ExponentialSmoothingfrom random import random# Generate a sample datasetdata = [x + random() for x in range(1, 100)]# fit modelmodel = ExponentialSmoothing(data,trend=\"add\", seasonal=\"add\", seasonal_periods=12, damped=True)model_fit = model.fit()# make predictionyhat = model_fit.predict(len(data), len(data))print(yhat)"
},
{
"code": null,
"e": 17702,
"s": 17284,
"text": "In this article, you discovered all the important classical forecasting techniques that can help you in getting started with your forecasting problems. You can deep dive into the suitable techniques and tune it further as per your need. To build a robust forecasting model, you must start by performing the right data transformation, set up an evaluation strategy, and have ready with a persistence (benchmark) model."
},
{
"code": null,
"e": 17774,
"s": 17702,
"text": "Thanks for reading! Please feel free to share any comments or feedback."
},
{
"code": null,
"e": 17903,
"s": 17774,
"text": "Hope you found this article informative, in the next few articles I will discuss some of the commonly used techniques in detail."
},
{
"code": null,
"e": 18012,
"s": 17903,
"text": "[1] Galit Shmueli and Kenneth Lichtendahl, Practical Time Series Forecasting with R: A Hands-On Guide, 2016."
}
] |
How to reset selected value to default using jQuery ? - GeeksforGeeks | 23 Aug, 2021
The task is to reset the value of the select element to its default value with the help of jQuery. There are two approaches that are discussed below:Approach 1: First select the options using jQuery selectors then use prop() method to get access to its properties. If the property is selected then return the default value by using defaultSelected property.
Example:
html
<!DOCTYPE HTML><html> <head> <title> Reset select value to default with JQuery </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP"></p> <select id="select"> <option value="GFG_1">GFG_1</option> <option value="GFG_2" selected="selected"> GFG_2 </option> <option value="GFG_3">GFG_3</option> </select> <button onclick="GFG_Fun()"> Click Here </button> <p id="GFG_DOWN"></p> <script> var el_up = document.getElementById('GFG_UP'); var el_down = document.getElementById('GFG_DOWN'); el_up.innerHTML = "Select a different option " + "and then click on the button to " + "perform the operation"; function GFG_Fun() { $('#select option').prop('selected', function () { return this.defaultSelected; }); el_down.innerHTML = "Default selected"; } </script></body> </html>
Output:
Approach 2: First, select the options using jQuery selectors then use each() method to get access to its properties. If the property is selected then return the default value by defaultSelected property.
Example:
html
<!DOCTYPE HTML><html> <head> <title> Reset select value to default with JQuery </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP"></p> <select id="select"> <option value="GFG_1">GFG_1</option> <option value="GFG_2" selected="selected"> GFG_2 </option> <option value="GFG_3">GFG_3</option> </select> <button onclick="GFG_Fun()"> Click Here </button> <p id="GFG_DOWN"></p> <script> var el_up = document.getElementById('GFG_UP'); var el_down = document.getElementById('GFG_DOWN'); el_up.innerHTML = "Select a different option " + "and then click on the button to " + "perform the operation"; function GFG_Fun() { $('#select option').each(function () { if (this.defaultSelected) { this.selected = true; return false; } }); el_down.innerHTML = "Default selected"; } </script></body> </html>
Output:
jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”. You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples.
surinderdawra388
CSS-Misc
HTML-Misc
jQuery-Misc
CSS
HTML
JavaScript
JQuery
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to apply style to parent if it has child with CSS?
How to set space between the flexbox ?
Design a web page using HTML and CSS
Create a Responsive Navbar using ReactJS
Form validation using jQuery
Hide or show elements in HTML using display property
How to set input type date in dd-mm-yyyy format using HTML ?
REST API (Introduction)
How to Insert Form Data into Database using PHP ?
HTML | <img> align Attribute | [
{
"code": null,
"e": 26476,
"s": 26448,
"text": "\n23 Aug, 2021"
},
{
"code": null,
"e": 26836,
"s": 26476,
"text": "The task is to reset the value of the select element to its default value with the help of jQuery. There are two approaches that are discussed below:Approach 1: First select the options using jQuery selectors then use prop() method to get access to its properties. If the property is selected then return the default value by using defaultSelected property. "
},
{
"code": null,
"e": 26847,
"s": 26836,
"text": "Example: "
},
{
"code": null,
"e": 26852,
"s": 26847,
"text": "html"
},
{
"code": "<!DOCTYPE HTML><html> <head> <title> Reset select value to default with JQuery </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js\"> </script></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\"></p> <select id=\"select\"> <option value=\"GFG_1\">GFG_1</option> <option value=\"GFG_2\" selected=\"selected\"> GFG_2 </option> <option value=\"GFG_3\">GFG_3</option> </select> <button onclick=\"GFG_Fun()\"> Click Here </button> <p id=\"GFG_DOWN\"></p> <script> var el_up = document.getElementById('GFG_UP'); var el_down = document.getElementById('GFG_DOWN'); el_up.innerHTML = \"Select a different option \" + \"and then click on the button to \" + \"perform the operation\"; function GFG_Fun() { $('#select option').prop('selected', function () { return this.defaultSelected; }); el_down.innerHTML = \"Default selected\"; } </script></body> </html>",
"e": 28015,
"s": 26852,
"text": null
},
{
"code": null,
"e": 28025,
"s": 28015,
"text": "Output: "
},
{
"code": null,
"e": 28230,
"s": 28025,
"text": "Approach 2: First, select the options using jQuery selectors then use each() method to get access to its properties. If the property is selected then return the default value by defaultSelected property. "
},
{
"code": null,
"e": 28241,
"s": 28230,
"text": "Example: "
},
{
"code": null,
"e": 28246,
"s": 28241,
"text": "html"
},
{
"code": "<!DOCTYPE HTML><html> <head> <title> Reset select value to default with JQuery </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js\"> </script></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\"></p> <select id=\"select\"> <option value=\"GFG_1\">GFG_1</option> <option value=\"GFG_2\" selected=\"selected\"> GFG_2 </option> <option value=\"GFG_3\">GFG_3</option> </select> <button onclick=\"GFG_Fun()\"> Click Here </button> <p id=\"GFG_DOWN\"></p> <script> var el_up = document.getElementById('GFG_UP'); var el_down = document.getElementById('GFG_DOWN'); el_up.innerHTML = \"Select a different option \" + \"and then click on the button to \" + \"perform the operation\"; function GFG_Fun() { $('#select option').each(function () { if (this.defaultSelected) { this.selected = true; return false; } }); el_down.innerHTML = \"Default selected\"; } </script></body> </html>",
"e": 29483,
"s": 28246,
"text": null
},
{
"code": null,
"e": 29493,
"s": 29483,
"text": "Output: "
},
{
"code": null,
"e": 29764,
"s": 29495,
"text": "jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”. You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples."
},
{
"code": null,
"e": 29783,
"s": 29766,
"text": "surinderdawra388"
},
{
"code": null,
"e": 29792,
"s": 29783,
"text": "CSS-Misc"
},
{
"code": null,
"e": 29802,
"s": 29792,
"text": "HTML-Misc"
},
{
"code": null,
"e": 29814,
"s": 29802,
"text": "jQuery-Misc"
},
{
"code": null,
"e": 29818,
"s": 29814,
"text": "CSS"
},
{
"code": null,
"e": 29823,
"s": 29818,
"text": "HTML"
},
{
"code": null,
"e": 29834,
"s": 29823,
"text": "JavaScript"
},
{
"code": null,
"e": 29841,
"s": 29834,
"text": "JQuery"
},
{
"code": null,
"e": 29858,
"s": 29841,
"text": "Web Technologies"
},
{
"code": null,
"e": 29885,
"s": 29858,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 29890,
"s": 29885,
"text": "HTML"
},
{
"code": null,
"e": 29988,
"s": 29890,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30043,
"s": 29988,
"text": "How to apply style to parent if it has child with CSS?"
},
{
"code": null,
"e": 30082,
"s": 30043,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 30119,
"s": 30082,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 30160,
"s": 30119,
"text": "Create a Responsive Navbar using ReactJS"
},
{
"code": null,
"e": 30189,
"s": 30160,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 30242,
"s": 30189,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 30303,
"s": 30242,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 30327,
"s": 30303,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 30377,
"s": 30327,
"text": "How to Insert Form Data into Database using PHP ?"
}
] |
builtin command in Linux with examples - GeeksforGeeks | 15 May, 2019
builtin command is used to run a shell builtin, passing it arguments(args), and also to get the exit status. The main use of this command is to define a shell function having the same name as the shell builtin by keeping the functionality of the builtin within the function.
Syntax:
builtin [shell-builtin [arg ..]]
Example: Here, we are creating a function to replace the ‘cd’ command. When you will use cd() function it will change the directory to the desktop directly.
builtin –help Command: It displays help information.
linux-command
Linux-Shell-Commands
Picked
Technical Scripter 2018
Linux-Unix
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
scp command in Linux with Examples
mv command in Linux with examples
Docker - COPY Instruction
SED command in Linux | Set 2
chown command in Linux with Examples
nohup Command in Linux with Examples
Named Pipe or FIFO with example C program
Thread functions in C/C++
uniq Command in LINUX with examples
Start/Stop/Restart Services Using Systemctl in Linux | [
{
"code": null,
"e": 25651,
"s": 25623,
"text": "\n15 May, 2019"
},
{
"code": null,
"e": 25926,
"s": 25651,
"text": "builtin command is used to run a shell builtin, passing it arguments(args), and also to get the exit status. The main use of this command is to define a shell function having the same name as the shell builtin by keeping the functionality of the builtin within the function."
},
{
"code": null,
"e": 25934,
"s": 25926,
"text": "Syntax:"
},
{
"code": null,
"e": 25967,
"s": 25934,
"text": "builtin [shell-builtin [arg ..]]"
},
{
"code": null,
"e": 26124,
"s": 25967,
"text": "Example: Here, we are creating a function to replace the ‘cd’ command. When you will use cd() function it will change the directory to the desktop directly."
},
{
"code": null,
"e": 26177,
"s": 26124,
"text": "builtin –help Command: It displays help information."
},
{
"code": null,
"e": 26191,
"s": 26177,
"text": "linux-command"
},
{
"code": null,
"e": 26212,
"s": 26191,
"text": "Linux-Shell-Commands"
},
{
"code": null,
"e": 26219,
"s": 26212,
"text": "Picked"
},
{
"code": null,
"e": 26243,
"s": 26219,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 26254,
"s": 26243,
"text": "Linux-Unix"
},
{
"code": null,
"e": 26273,
"s": 26254,
"text": "Technical Scripter"
},
{
"code": null,
"e": 26371,
"s": 26273,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26406,
"s": 26371,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 26440,
"s": 26406,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 26466,
"s": 26440,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 26495,
"s": 26466,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 26532,
"s": 26495,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 26569,
"s": 26532,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 26611,
"s": 26569,
"text": "Named Pipe or FIFO with example C program"
},
{
"code": null,
"e": 26637,
"s": 26611,
"text": "Thread functions in C/C++"
},
{
"code": null,
"e": 26673,
"s": 26637,
"text": "uniq Command in LINUX with examples"
}
] |
How to select all elements without a given class using jQuery ? - GeeksforGeeks | 07 Nov, 2019
All elements that do not match the given selector can be selected using jQuery( “:not(selector)” ). For example, the first example selects all the <li> elements which are not active.
Example 1: This example selects <li> elements which does not contains the class active.
<!DOCTYPE html><html> <head> <title> How to select all elements without a given class using jQuery ? </title> <meta charset="utf-8"> <script src= "https://code.jquery.com/jquery-1.10.2.js"> </script></head> <body> <h1 style="color:green">GeeksforGeeks</h1> <b> Select all elements without a<br> given class using jQuery </b> <ul> <li class="active">element 1</li> <li>element 2</li> <li>element 3</li> <li>element 4</li> </ul> <script> $("li:not(.active)").css( "background-color", "yellow" ); </script></body> </html>
Output:
It can also be done using .not(selector).
Example 2: This example selects <div> elements which does not contains the class green or id blue.
<!DOCTYPE html><html> <head> <meta charset="utf-8"> <script src= "https://code.jquery.com/jquery-1.10.2.js"> </script> <style> div { width: 50px; height: 50px; margin: 10px; float: left; border: 2px solid black; } .green { background: #8f8; } .orange { background: orange; } #blue { background: #99f; } </style></head> <body> <h1 style="color:green">GeeksforGeeks</h1> <b> Select all elements without a given class using jQuery </b> <br><br> <div></div> <div id="blue"></div> <div></div> <div class="green"></div> <div class="green"></div> <div class="orange"></div> <div></div> <script> $("div").not(".green, #blue") .css("border-color", "red"); </script></body> </html>
Output:
jQuery-Misc
Picked
JQuery
Technical Scripter
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Scroll to the top of the page using JavaScript/jQuery
jQuery | children() with Examples
How to Show and Hide div elements using radio buttons?
How to prevent Body from scrolling when a modal is opened using jQuery ?
How to redirect to a particular section of a page using HTML or jQuery?
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 ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills | [
{
"code": null,
"e": 26202,
"s": 26174,
"text": "\n07 Nov, 2019"
},
{
"code": null,
"e": 26385,
"s": 26202,
"text": "All elements that do not match the given selector can be selected using jQuery( “:not(selector)” ). For example, the first example selects all the <li> elements which are not active."
},
{
"code": null,
"e": 26473,
"s": 26385,
"text": "Example 1: This example selects <li> elements which does not contains the class active."
},
{
"code": "<!DOCTYPE html><html> <head> <title> How to select all elements without a given class using jQuery ? </title> <meta charset=\"utf-8\"> <script src= \"https://code.jquery.com/jquery-1.10.2.js\"> </script></head> <body> <h1 style=\"color:green\">GeeksforGeeks</h1> <b> Select all elements without a<br> given class using jQuery </b> <ul> <li class=\"active\">element 1</li> <li>element 2</li> <li>element 3</li> <li>element 4</li> </ul> <script> $(\"li:not(.active)\").css( \"background-color\", \"yellow\" ); </script></body> </html>",
"e": 27150,
"s": 26473,
"text": null
},
{
"code": null,
"e": 27158,
"s": 27150,
"text": "Output:"
},
{
"code": null,
"e": 27200,
"s": 27158,
"text": "It can also be done using .not(selector)."
},
{
"code": null,
"e": 27299,
"s": 27200,
"text": "Example 2: This example selects <div> elements which does not contains the class green or id blue."
},
{
"code": "<!DOCTYPE html><html> <head> <meta charset=\"utf-8\"> <script src= \"https://code.jquery.com/jquery-1.10.2.js\"> </script> <style> div { width: 50px; height: 50px; margin: 10px; float: left; border: 2px solid black; } .green { background: #8f8; } .orange { background: orange; } #blue { background: #99f; } </style></head> <body> <h1 style=\"color:green\">GeeksforGeeks</h1> <b> Select all elements without a given class using jQuery </b> <br><br> <div></div> <div id=\"blue\"></div> <div></div> <div class=\"green\"></div> <div class=\"green\"></div> <div class=\"orange\"></div> <div></div> <script> $(\"div\").not(\".green, #blue\") .css(\"border-color\", \"red\"); </script></body> </html>",
"e": 28237,
"s": 27299,
"text": null
},
{
"code": null,
"e": 28245,
"s": 28237,
"text": "Output:"
},
{
"code": null,
"e": 28257,
"s": 28245,
"text": "jQuery-Misc"
},
{
"code": null,
"e": 28264,
"s": 28257,
"text": "Picked"
},
{
"code": null,
"e": 28271,
"s": 28264,
"text": "JQuery"
},
{
"code": null,
"e": 28290,
"s": 28271,
"text": "Technical Scripter"
},
{
"code": null,
"e": 28307,
"s": 28290,
"text": "Web Technologies"
},
{
"code": null,
"e": 28334,
"s": 28307,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 28432,
"s": 28334,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28486,
"s": 28432,
"text": "Scroll to the top of the page using JavaScript/jQuery"
},
{
"code": null,
"e": 28520,
"s": 28486,
"text": "jQuery | children() with Examples"
},
{
"code": null,
"e": 28575,
"s": 28520,
"text": "How to Show and Hide div elements using radio buttons?"
},
{
"code": null,
"e": 28648,
"s": 28575,
"text": "How to prevent Body from scrolling when a modal is opened using jQuery ?"
},
{
"code": null,
"e": 28720,
"s": 28648,
"text": "How to redirect to a particular section of a page using HTML or jQuery?"
},
{
"code": null,
"e": 28760,
"s": 28720,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28793,
"s": 28760,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28838,
"s": 28793,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28881,
"s": 28838,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Python | Get a set of places according to search query using Google Places API - GeeksforGeeks | 27 Nov, 2019
Google Places API Web Service allow the user to query for place information on a variety of categories, such as establishments, prominent points of interest, geographic locations, and more. One can search for places either by proximity or a text string. A Place Search returns a list of places along with summary information about each place; additional information is available via a Place Details query.
Text Search Service of Google Places Api is used here, which is a web service that returns information about a set of places based on a string. For example “Hotels in Delhi” or “shoe stores near Oshawa”. The service responds with a list of places matching the text string and any location bias that has been set.
To use this service, the user must need an API key, which one can get form here.
Let’s try to use this API service using Python. The modules which will be used are requests and json.
Below is the implementation :
# Python program to get a set of # places according to your search # query using Google Places API # importing required modulesimport requests, json # enter your api key hereapi_key = 'Your_API_key' # url variable store urlurl = "https://maps.googleapis.com/maps/api/place/textsearch/json?" # The text string on which to searchquery = input('Search query: ') # get method of requests module# return response objectr = requests.get(url + 'query=' + query + '&key=' + api_key) # json method of response object convert# json format data into python format datax = r.json() # now x contains list of nested dictionaries# we know dictionary contain key value pair# store the value of result key in variable yy = x['results'] # keep looping upto length of yfor i in range(len(y)): # Print value corresponding to the # 'name' key at the ith index of y print(y[i]['name'])
Output :
Search query: Hotels in delhi
ITC Maurya
Le Meridien New Delhi
The Imperial New Delhi
Radisson Blu Hotel New Delhi Paschim Vihar
The Lalit New Delhi
Crowne Plaza New Delhi Rohini
Shangri-La's Eros Hotel, New Delhi
Pride Plaza Hotel Aerocity, New Delhi
The Claridges
The Leela Ambience Convention Hotel, Delhi
Radisson Blu Plaza Delhi Airport
Hotel City Park
Radisson Blu New Delhi Dwarka
The Ashok Hotel
Novotel New Delhi Aerocity
Mapple Emerald
The Metropolitan Hotel and Spa
The Umrao
Pullman New Delhi Aerocity
Welcome Hotel Dwarka
ManasChhabra2
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary | [
{
"code": null,
"e": 26307,
"s": 26279,
"text": "\n27 Nov, 2019"
},
{
"code": null,
"e": 26713,
"s": 26307,
"text": "Google Places API Web Service allow the user to query for place information on a variety of categories, such as establishments, prominent points of interest, geographic locations, and more. One can search for places either by proximity or a text string. A Place Search returns a list of places along with summary information about each place; additional information is available via a Place Details query."
},
{
"code": null,
"e": 27026,
"s": 26713,
"text": "Text Search Service of Google Places Api is used here, which is a web service that returns information about a set of places based on a string. For example “Hotels in Delhi” or “shoe stores near Oshawa”. The service responds with a list of places matching the text string and any location bias that has been set."
},
{
"code": null,
"e": 27107,
"s": 27026,
"text": "To use this service, the user must need an API key, which one can get form here."
},
{
"code": null,
"e": 27209,
"s": 27107,
"text": "Let’s try to use this API service using Python. The modules which will be used are requests and json."
},
{
"code": null,
"e": 27239,
"s": 27209,
"text": "Below is the implementation :"
},
{
"code": "# Python program to get a set of # places according to your search # query using Google Places API # importing required modulesimport requests, json # enter your api key hereapi_key = 'Your_API_key' # url variable store urlurl = \"https://maps.googleapis.com/maps/api/place/textsearch/json?\" # The text string on which to searchquery = input('Search query: ') # get method of requests module# return response objectr = requests.get(url + 'query=' + query + '&key=' + api_key) # json method of response object convert# json format data into python format datax = r.json() # now x contains list of nested dictionaries# we know dictionary contain key value pair# store the value of result key in variable yy = x['results'] # keep looping upto length of yfor i in range(len(y)): # Print value corresponding to the # 'name' key at the ith index of y print(y[i]['name'])",
"e": 28150,
"s": 27239,
"text": null
},
{
"code": null,
"e": 28159,
"s": 28150,
"text": "Output :"
},
{
"code": null,
"e": 28696,
"s": 28159,
"text": "Search query: Hotels in delhi\n\nITC Maurya\nLe Meridien New Delhi\nThe Imperial New Delhi\nRadisson Blu Hotel New Delhi Paschim Vihar\nThe Lalit New Delhi\nCrowne Plaza New Delhi Rohini\nShangri-La's Eros Hotel, New Delhi\nPride Plaza Hotel Aerocity, New Delhi\nThe Claridges\nThe Leela Ambience Convention Hotel, Delhi\nRadisson Blu Plaza Delhi Airport\nHotel City Park\nRadisson Blu New Delhi Dwarka\nThe Ashok Hotel\nNovotel New Delhi Aerocity\nMapple Emerald\nThe Metropolitan Hotel and Spa\nThe Umrao\nPullman New Delhi Aerocity\nWelcome Hotel Dwarka\n"
},
{
"code": null,
"e": 28710,
"s": 28696,
"text": "ManasChhabra2"
},
{
"code": null,
"e": 28717,
"s": 28710,
"text": "Python"
},
{
"code": null,
"e": 28733,
"s": 28717,
"text": "Python Programs"
},
{
"code": null,
"e": 28831,
"s": 28733,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28849,
"s": 28831,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28881,
"s": 28849,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28903,
"s": 28881,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28945,
"s": 28903,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28971,
"s": 28945,
"text": "Python String | replace()"
},
{
"code": null,
"e": 29014,
"s": 28971,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 29036,
"s": 29014,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 29075,
"s": 29036,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 29121,
"s": 29075,
"text": "Python | Split string into list of characters"
}
] |
Output of Python program | Set 17 - GeeksforGeeks | 11 Aug, 2021
Prerequisite – Tuples and Dictionaryin Python Predict the output of the following Python programs.
1.What is the output of the following program?
Python
numberGames = {}numberGames[(1,2,4)] = 8numberGames[(4,2,1)] = 10numberGames[(1,2)] = 12 sum = 0for k in numberGames: sum += numberGames[k] print len(numberGames) + sum
Output:
33
Explanation: Tuples can be used for keys into dictionary. The tuples can have mixed length and the order of the items in the tuple is considered when comparing the equality of the keys.
2.What is the output of the following program?
Python
my_tuple = (1, 2, 3, 4)my_tuple.append( (5, 6, 7) )print len(my_tuple)
Output:
Error !
Explanation: Tuples are immutable and don’t have an append method as in case of Lists.Hence an error is thrown in this case.
3.What is the output of the following program?
Python
t = (1, 2)print 2 * t
Output:
(1, 2, 1, 2)
Explanation: Asterick Operator (*) operator concatenates tuple.
4.What is the output of the following program?
Python3
d1 = {"john":40, "peter":45}d2 = {"john":466, "peter":45}print (d1 > d2)
Output:
TypeError
Explanation: The ‘>’ operator is not supported between instances of ‘dict’ and ‘dict’.
5.What is the output of the following program?
Python
my_tuple = (6, 9, 0, 0)my_tuple1 = (5, 2, 3, 4)print my_tuple > my_tuple1
Output:
True
Explanation: Each elements of the tuples are compared one by one and if maximum number of elements are there in tuple1 which are greater of equal to corresponding element of tuple2 then tuple1 is said to be greater than tuple2.
This article is contributed by Avinash Kumar Singh. 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.
surinderdawra388
sooda367
Python-Output
Program Output
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Output of Java program | Set 18 (Overriding)
Output of Java Program | Set 11
Output of Java programs | Set 13 (Collections)
Output of C++ programs | Set 34 (File Handling)
Different ways to copy a string in C/C++
Output of Java Program | Set 3
Runtime Errors
Output of Java program | Set 28
Output of Java program | Set 5
Output of Java Programs | Set 12 | [
{
"code": null,
"e": 25861,
"s": 25833,
"text": "\n11 Aug, 2021"
},
{
"code": null,
"e": 25961,
"s": 25861,
"text": "Prerequisite – Tuples and Dictionaryin Python Predict the output of the following Python programs. "
},
{
"code": null,
"e": 26009,
"s": 25961,
"text": "1.What is the output of the following program? "
},
{
"code": null,
"e": 26016,
"s": 26009,
"text": "Python"
},
{
"code": "numberGames = {}numberGames[(1,2,4)] = 8numberGames[(4,2,1)] = 10numberGames[(1,2)] = 12 sum = 0for k in numberGames: sum += numberGames[k] print len(numberGames) + sum",
"e": 26190,
"s": 26016,
"text": null
},
{
"code": null,
"e": 26199,
"s": 26190,
"text": "Output: "
},
{
"code": null,
"e": 26202,
"s": 26199,
"text": "33"
},
{
"code": null,
"e": 26390,
"s": 26202,
"text": "Explanation: Tuples can be used for keys into dictionary. The tuples can have mixed length and the order of the items in the tuple is considered when comparing the equality of the keys. "
},
{
"code": null,
"e": 26438,
"s": 26390,
"text": "2.What is the output of the following program? "
},
{
"code": null,
"e": 26445,
"s": 26438,
"text": "Python"
},
{
"code": "my_tuple = (1, 2, 3, 4)my_tuple.append( (5, 6, 7) )print len(my_tuple)",
"e": 26516,
"s": 26445,
"text": null
},
{
"code": null,
"e": 26525,
"s": 26516,
"text": "Output: "
},
{
"code": null,
"e": 26533,
"s": 26525,
"text": "Error !"
},
{
"code": null,
"e": 26660,
"s": 26533,
"text": "Explanation: Tuples are immutable and don’t have an append method as in case of Lists.Hence an error is thrown in this case. "
},
{
"code": null,
"e": 26708,
"s": 26660,
"text": "3.What is the output of the following program? "
},
{
"code": null,
"e": 26715,
"s": 26708,
"text": "Python"
},
{
"code": "t = (1, 2)print 2 * t",
"e": 26737,
"s": 26715,
"text": null
},
{
"code": null,
"e": 26746,
"s": 26737,
"text": "Output: "
},
{
"code": null,
"e": 26759,
"s": 26746,
"text": "(1, 2, 1, 2)"
},
{
"code": null,
"e": 26824,
"s": 26759,
"text": "Explanation: Asterick Operator (*) operator concatenates tuple. "
},
{
"code": null,
"e": 26872,
"s": 26824,
"text": "4.What is the output of the following program? "
},
{
"code": null,
"e": 26880,
"s": 26872,
"text": "Python3"
},
{
"code": "d1 = {\"john\":40, \"peter\":45}d2 = {\"john\":466, \"peter\":45}print (d1 > d2)",
"e": 26953,
"s": 26880,
"text": null
},
{
"code": null,
"e": 26962,
"s": 26953,
"text": "Output: "
},
{
"code": null,
"e": 26972,
"s": 26962,
"text": "TypeError"
},
{
"code": null,
"e": 27061,
"s": 26972,
"text": "Explanation: The ‘>’ operator is not supported between instances of ‘dict’ and ‘dict’. "
},
{
"code": null,
"e": 27110,
"s": 27061,
"text": "5.What is the output of the following program? "
},
{
"code": null,
"e": 27117,
"s": 27110,
"text": "Python"
},
{
"code": "my_tuple = (6, 9, 0, 0)my_tuple1 = (5, 2, 3, 4)print my_tuple > my_tuple1",
"e": 27191,
"s": 27117,
"text": null
},
{
"code": null,
"e": 27200,
"s": 27191,
"text": "Output: "
},
{
"code": null,
"e": 27205,
"s": 27200,
"text": "True"
},
{
"code": null,
"e": 27434,
"s": 27205,
"text": "Explanation: Each elements of the tuples are compared one by one and if maximum number of elements are there in tuple1 which are greater of equal to corresponding element of tuple2 then tuple1 is said to be greater than tuple2. "
},
{
"code": null,
"e": 27862,
"s": 27434,
"text": "This article is contributed by Avinash Kumar Singh. 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": 27879,
"s": 27862,
"text": "surinderdawra388"
},
{
"code": null,
"e": 27888,
"s": 27879,
"text": "sooda367"
},
{
"code": null,
"e": 27902,
"s": 27888,
"text": "Python-Output"
},
{
"code": null,
"e": 27917,
"s": 27902,
"text": "Program Output"
},
{
"code": null,
"e": 28015,
"s": 27917,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28060,
"s": 28015,
"text": "Output of Java program | Set 18 (Overriding)"
},
{
"code": null,
"e": 28092,
"s": 28060,
"text": "Output of Java Program | Set 11"
},
{
"code": null,
"e": 28139,
"s": 28092,
"text": "Output of Java programs | Set 13 (Collections)"
},
{
"code": null,
"e": 28187,
"s": 28139,
"text": "Output of C++ programs | Set 34 (File Handling)"
},
{
"code": null,
"e": 28228,
"s": 28187,
"text": "Different ways to copy a string in C/C++"
},
{
"code": null,
"e": 28259,
"s": 28228,
"text": "Output of Java Program | Set 3"
},
{
"code": null,
"e": 28274,
"s": 28259,
"text": "Runtime Errors"
},
{
"code": null,
"e": 28306,
"s": 28274,
"text": "Output of Java program | Set 28"
},
{
"code": null,
"e": 28337,
"s": 28306,
"text": "Output of Java program | Set 5"
}
] |
Implementing Checksum using Python - GeeksforGeeks | 03 May, 2022
The checksum is a kind of error Detection method in Computer Networks. This method used by the higher layer protocols and makes use of Checksum Generator on the Sender side and Checksum Checker on the Receiver side. In this article, we will be implementing the checksum algorithm in Python.
Refer to the below articles to get detailed information about the checksum
Error Detection in Computer Networks
Error Detection Code – Checksum
Steps to implement the algorithm.
The message is divided into 4 sections, each of k bits.All the sections are added together to get the sum.The sum is complemented and becomes the Checksum.The checksum is sent with the data.
The message is divided into 4 sections, each of k bits.
All the sections are added together to get the sum.
The sum is complemented and becomes the Checksum.
The checksum is sent with the data.
The message is divided into 4 sections of k bits.All sections are added together to get the sum.The generated checksum is added to the sum of all sections.The resulting sum is complemented.
The message is divided into 4 sections of k bits.
All sections are added together to get the sum.
The generated checksum is added to the sum of all sections.
The resulting sum is complemented.
After following these steps, if the checksum of receiver side and the checker side are added and complemented and the result is equal to zero, the data is correct and is therefore accepted. Otherwise, an error is detected and the data is rejected.
Below is the implementation of the above approach:
Python3
# Function to find the Checksum of Sent Messagedef findChecksum(SentMessage, k): # Dividing sent message in packets of k bits. c1 = SentMessage[0:k] c2 = SentMessage[k:2*k] c3 = SentMessage[2*k:3*k] c4 = SentMessage[3*k:4*k] # Calculating the binary sum of packets Sum = bin(int(c1, 2)+int(c2, 2)+int(c3, 2)+int(c4, 2))[2:] # Adding the overflow bits if(len(Sum) > k): x = len(Sum)-k Sum = bin(int(Sum[0:x], 2)+int(Sum[x:], 2))[2:] if(len(Sum) < k): Sum = '0'*(k-len(Sum))+Sum # Calculating the complement of sum Checksum = '' for i in Sum: if(i == '1'): Checksum += '0' else: Checksum += '1' return Checksum # Function to find the Complement of binary addition of# k bit packets of the Received Message + Checksumdef checkReceiverChecksum(ReceivedMessage, k, Checksum): # Dividing sent message in packets of k bits. c1 = ReceivedMessage[0:k] c2 = ReceivedMessage[k:2*k] c3 = ReceivedMessage[2*k:3*k] c4 = ReceivedMessage[3*k:4*k] # Calculating the binary sum of packets + checksum ReceiverSum = bin(int(c1, 2)+int(c2, 2)+int(Checksum, 2) + int(c3, 2)+int(c4, 2)+int(Checksum, 2))[2:] # Adding the overflow bits if(len(ReceiverSum) > k): x = len(ReceiverSum)-k ReceiverSum = bin(int(ReceiverSum[0:x], 2)+int(ReceiverSum[x:], 2))[2:] # Calculating the complement of sum ReceiverChecksum = '' for i in ReceiverSum: if(i == '1'): ReceiverChecksum += '0' else: ReceiverChecksum += '1' return ReceiverChecksum # Driver CodeSentMessage = "10010101011000111001010011101100"k = 8#ReceivedMessage = "10000101011000111001010011101101"ReceivedMessage = "10010101011000111001010011101100"# Calling the findChecksum() functionChecksum = findChecksum(SentMessage, k) # Calling thr checkReceiverChecksum() functionReceiverChecksum = checkReceiverChecksum(ReceivedMessage, k, Checksum) # Printing Checksumprint("SENDER SIDE CHECKSUM: ", Checksum)print("RECEIVER SIDE CHECKSUM: ", ReceiverChecksum)finalsum=bin(int(Checksum,2)+int(ReceiverChecksum,2))[2:] # Finding the sum of checksum and received checksumfinalcomp=''for i in finalsum: if(i == '1'): finalcomp += '0' else: finalcomp += '1' # If sum = 0, No error is detectedif(int(finalcomp,2) == 0): print("Receiver Checksum is equal to 0. Therefore,") print("STATUS: ACCEPTED") # Otherwise, Error is detectedelse: print("Receiver Checksum is not equal to 0. Therefore,") print("STATUS: ERROR DETECTED")
SENDER SIDE CHECKSUM: 10000101
RECEIVER SIDE CHECKSUM: 01111010
Receiver Checksum is equal to 0. Therefore,
STATUS: ACCEPTED
sagartomar9927
metalsrivastav
Computer Networks
Python
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Advanced Encryption Standard (AES)
Intrusion Detection System (IDS)
Introduction and IPv4 Datagram Header
Secure Socket Layer (SSL)
Cryptography and its Types
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": 25755,
"s": 25727,
"text": "\n03 May, 2022"
},
{
"code": null,
"e": 26046,
"s": 25755,
"text": "The checksum is a kind of error Detection method in Computer Networks. This method used by the higher layer protocols and makes use of Checksum Generator on the Sender side and Checksum Checker on the Receiver side. In this article, we will be implementing the checksum algorithm in Python."
},
{
"code": null,
"e": 26121,
"s": 26046,
"text": "Refer to the below articles to get detailed information about the checksum"
},
{
"code": null,
"e": 26158,
"s": 26121,
"text": "Error Detection in Computer Networks"
},
{
"code": null,
"e": 26190,
"s": 26158,
"text": "Error Detection Code – Checksum"
},
{
"code": null,
"e": 26224,
"s": 26190,
"text": "Steps to implement the algorithm."
},
{
"code": null,
"e": 26415,
"s": 26224,
"text": "The message is divided into 4 sections, each of k bits.All the sections are added together to get the sum.The sum is complemented and becomes the Checksum.The checksum is sent with the data."
},
{
"code": null,
"e": 26471,
"s": 26415,
"text": "The message is divided into 4 sections, each of k bits."
},
{
"code": null,
"e": 26523,
"s": 26471,
"text": "All the sections are added together to get the sum."
},
{
"code": null,
"e": 26573,
"s": 26523,
"text": "The sum is complemented and becomes the Checksum."
},
{
"code": null,
"e": 26609,
"s": 26573,
"text": "The checksum is sent with the data."
},
{
"code": null,
"e": 26799,
"s": 26609,
"text": "The message is divided into 4 sections of k bits.All sections are added together to get the sum.The generated checksum is added to the sum of all sections.The resulting sum is complemented."
},
{
"code": null,
"e": 26849,
"s": 26799,
"text": "The message is divided into 4 sections of k bits."
},
{
"code": null,
"e": 26897,
"s": 26849,
"text": "All sections are added together to get the sum."
},
{
"code": null,
"e": 26957,
"s": 26897,
"text": "The generated checksum is added to the sum of all sections."
},
{
"code": null,
"e": 26992,
"s": 26957,
"text": "The resulting sum is complemented."
},
{
"code": null,
"e": 27241,
"s": 26992,
"text": "After following these steps, if the checksum of receiver side and the checker side are added and complemented and the result is equal to zero, the data is correct and is therefore accepted. Otherwise, an error is detected and the data is rejected. "
},
{
"code": null,
"e": 27293,
"s": 27241,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 27301,
"s": 27293,
"text": "Python3"
},
{
"code": "# Function to find the Checksum of Sent Messagedef findChecksum(SentMessage, k): # Dividing sent message in packets of k bits. c1 = SentMessage[0:k] c2 = SentMessage[k:2*k] c3 = SentMessage[2*k:3*k] c4 = SentMessage[3*k:4*k] # Calculating the binary sum of packets Sum = bin(int(c1, 2)+int(c2, 2)+int(c3, 2)+int(c4, 2))[2:] # Adding the overflow bits if(len(Sum) > k): x = len(Sum)-k Sum = bin(int(Sum[0:x], 2)+int(Sum[x:], 2))[2:] if(len(Sum) < k): Sum = '0'*(k-len(Sum))+Sum # Calculating the complement of sum Checksum = '' for i in Sum: if(i == '1'): Checksum += '0' else: Checksum += '1' return Checksum # Function to find the Complement of binary addition of# k bit packets of the Received Message + Checksumdef checkReceiverChecksum(ReceivedMessage, k, Checksum): # Dividing sent message in packets of k bits. c1 = ReceivedMessage[0:k] c2 = ReceivedMessage[k:2*k] c3 = ReceivedMessage[2*k:3*k] c4 = ReceivedMessage[3*k:4*k] # Calculating the binary sum of packets + checksum ReceiverSum = bin(int(c1, 2)+int(c2, 2)+int(Checksum, 2) + int(c3, 2)+int(c4, 2)+int(Checksum, 2))[2:] # Adding the overflow bits if(len(ReceiverSum) > k): x = len(ReceiverSum)-k ReceiverSum = bin(int(ReceiverSum[0:x], 2)+int(ReceiverSum[x:], 2))[2:] # Calculating the complement of sum ReceiverChecksum = '' for i in ReceiverSum: if(i == '1'): ReceiverChecksum += '0' else: ReceiverChecksum += '1' return ReceiverChecksum # Driver CodeSentMessage = \"10010101011000111001010011101100\"k = 8#ReceivedMessage = \"10000101011000111001010011101101\"ReceivedMessage = \"10010101011000111001010011101100\"# Calling the findChecksum() functionChecksum = findChecksum(SentMessage, k) # Calling thr checkReceiverChecksum() functionReceiverChecksum = checkReceiverChecksum(ReceivedMessage, k, Checksum) # Printing Checksumprint(\"SENDER SIDE CHECKSUM: \", Checksum)print(\"RECEIVER SIDE CHECKSUM: \", ReceiverChecksum)finalsum=bin(int(Checksum,2)+int(ReceiverChecksum,2))[2:] # Finding the sum of checksum and received checksumfinalcomp=''for i in finalsum: if(i == '1'): finalcomp += '0' else: finalcomp += '1' # If sum = 0, No error is detectedif(int(finalcomp,2) == 0): print(\"Receiver Checksum is equal to 0. Therefore,\") print(\"STATUS: ACCEPTED\") # Otherwise, Error is detectedelse: print(\"Receiver Checksum is not equal to 0. Therefore,\") print(\"STATUS: ERROR DETECTED\")",
"e": 29899,
"s": 27301,
"text": null
},
{
"code": null,
"e": 30027,
"s": 29899,
"text": "SENDER SIDE CHECKSUM: 10000101\nRECEIVER SIDE CHECKSUM: 01111010\nReceiver Checksum is equal to 0. Therefore,\nSTATUS: ACCEPTED\n"
},
{
"code": null,
"e": 30042,
"s": 30027,
"text": "sagartomar9927"
},
{
"code": null,
"e": 30057,
"s": 30042,
"text": "metalsrivastav"
},
{
"code": null,
"e": 30075,
"s": 30057,
"text": "Computer Networks"
},
{
"code": null,
"e": 30082,
"s": 30075,
"text": "Python"
},
{
"code": null,
"e": 30100,
"s": 30082,
"text": "Computer Networks"
},
{
"code": null,
"e": 30198,
"s": 30100,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30233,
"s": 30198,
"text": "Advanced Encryption Standard (AES)"
},
{
"code": null,
"e": 30266,
"s": 30233,
"text": "Intrusion Detection System (IDS)"
},
{
"code": null,
"e": 30304,
"s": 30266,
"text": "Introduction and IPv4 Datagram Header"
},
{
"code": null,
"e": 30330,
"s": 30304,
"text": "Secure Socket Layer (SSL)"
},
{
"code": null,
"e": 30357,
"s": 30330,
"text": "Cryptography and its Types"
},
{
"code": null,
"e": 30385,
"s": 30357,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 30435,
"s": 30385,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 30457,
"s": 30435,
"text": "Python map() function"
}
] |
Slide Down a Navigation Bar on Scroll using HTML, CSS and JavaScript - GeeksforGeeks | 27 Sep, 2021
To create a slide down navigation bar you need to use HTML, CSS, and JavaScript. HTML will make the structure of the body, CSS will make it looks good. This kind of sliding navbar looks attractive on a site. By using JavaScript you can easily make the navigation bar slideable when the user scrolls down.
Creating Structure: In this section, we will create a basic website structure for the slide down navbar when the user scrolls down the page it will display the effect.
HTML code to make the structure:
HTML
<!DOCTYPE html><html> <head> <title> Slide Down a Navigation Bar on Scroll using HTML CSS and JavaScript </title> <meta name="viewport" content="width=device-width, initial-scale=1"></head> <body> <!-- logo with tag --> <article> <h1 style="color:green;"> GeeksforGeeks </h1> <b> A Computer Science Portal for Geeks </b> <p> How many times were you frustrated while looking out for a good collection of programming/algorithm/interview questions? What did you expect and what did you get? This portal has been created to provide well written, well thought and well explained solutions for selected questions. </p> </article> <!-- Navbar items --> <div id="navlist"> <a href="#">Home</a> <a href="#">About Us</a> <a href="#">Our Products</a> <a href="#">Careers</a> <a href="#">Contact Us</a> </div> <!-- for creating scroll --> <div class="scrollable" style="padding:15px 15px 4500px;"> </div></body> </html>
Designing Structure: In the previous section, we have created the structure of the basic website. In this section, we will design the structure for the navigation bar and then scroll down the effect on the navbar using JavaScript.
CSS code to look good the structure:
CSS
<style> /* styling article tag component */ article { position: fixed; margin-left: 10px; } /* styling navlist */ #navlist { background-color: #0074D9; position: fixed; left: 45%; top: -60px; width: auto; display: block; transition: top 0.3s; } /* styling navlist anchor element */ #navlist a { float: left; display: block; color: #f2f2f2; text-align: center; padding: 12px; text-decoration: none; font-size: 15px; } /* hover effect of navlist anchor element */ #navlist a:hover { background-color: #ddd; color: black; }</style>
JavaScript code for the animation on the menu:
JavaScript
<script> // When the user scrolls down then // slide down the navbar window.onscroll = function() { scroll() }; function scroll() { if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) { document.getElementById("navlist").style.top = "0"; } else { document.getElementById("navlist").style.top = "-60px"; } }</script>
Combining the HTML, CSS, and JavaScript code: This example is the combination of the above sections.
HTML
<!DOCTYPE html><html> <head> <title> Slide Down a Navigation Bar on Scroll using HTML CSS and JavaScript </title> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> /* styling article tag component */ article { position: fixed; margin-left: 10px; } /* styling navlist */ #navlist { background-color: #0074D9; position: fixed; left: 45%; top: -60px; width: auto; display: block; transition: top 0.3s; } /* styling navlist anchor element */ #navlist a { float: left; display: block; color: #f2f2f2; text-align: center; padding: 12px; text-decoration: none; font-size: 15px; } /* hover effect of navlist anchor element */ #navlist a:hover { background-color: #ddd; color: black; } </style></head> <body> <!-- logo with tag --> <article> <h1 style="color:green;"> GeeksforGeeks </h1> <b> A Computer Science Portal for Geeks </b> <p> How many times were you frustrated while looking out for a good collection of programming/algorithm/interview questions? What did you expect and what did you get? This portal has been created to provide well written, well thought and well explained solutions for selected questions. </p> </article> <!-- Navbar items --> <div id="navlist"> <a href="#">Home</a> <a href="#">About Us</a> <a href="#">Our Products</a> <a href="#">Careers</a> <a href="#">Contact Us</a> </div> <!-- for creating scroll --> <div class="scrollable" style="padding:15px 15px 4500px;"> </div> <script> // When the user scrolls down then // slide down the navbar window.onscroll = function() { scroll() }; function scroll() { if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) { document.getElementById("navlist").style.top = "0"; } else { document.getElementById("navlist").style.top = "-60px"; } } </script></body> </html>
Output:
arorakashish0911
CSS-Misc
HTML-Misc
JavaScript-Misc
CSS
HTML
JavaScript
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a web page using HTML and CSS
How to set space between the flexbox ?
Form validation using jQuery
Search Bar using HTML, CSS and JavaScript
How to style a checkbox using CSS?
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
How to set input type date in dd-mm-yyyy format using HTML ?
REST API (Introduction)
How to Insert Form Data into Database using PHP ? | [
{
"code": null,
"e": 26621,
"s": 26593,
"text": "\n27 Sep, 2021"
},
{
"code": null,
"e": 26926,
"s": 26621,
"text": "To create a slide down navigation bar you need to use HTML, CSS, and JavaScript. HTML will make the structure of the body, CSS will make it looks good. This kind of sliding navbar looks attractive on a site. By using JavaScript you can easily make the navigation bar slideable when the user scrolls down."
},
{
"code": null,
"e": 27096,
"s": 26926,
"text": "Creating Structure: In this section, we will create a basic website structure for the slide down navbar when the user scrolls down the page it will display the effect. "
},
{
"code": null,
"e": 27130,
"s": 27096,
"text": "HTML code to make the structure: "
},
{
"code": null,
"e": 27135,
"s": 27130,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title> Slide Down a Navigation Bar on Scroll using HTML CSS and JavaScript </title> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"></head> <body> <!-- logo with tag --> <article> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <b> A Computer Science Portal for Geeks </b> <p> How many times were you frustrated while looking out for a good collection of programming/algorithm/interview questions? What did you expect and what did you get? This portal has been created to provide well written, well thought and well explained solutions for selected questions. </p> </article> <!-- Navbar items --> <div id=\"navlist\"> <a href=\"#\">Home</a> <a href=\"#\">About Us</a> <a href=\"#\">Our Products</a> <a href=\"#\">Careers</a> <a href=\"#\">Contact Us</a> </div> <!-- for creating scroll --> <div class=\"scrollable\" style=\"padding:15px 15px 4500px;\"> </div></body> </html>",
"e": 28330,
"s": 27135,
"text": null
},
{
"code": null,
"e": 28562,
"s": 28330,
"text": "Designing Structure: In the previous section, we have created the structure of the basic website. In this section, we will design the structure for the navigation bar and then scroll down the effect on the navbar using JavaScript. "
},
{
"code": null,
"e": 28600,
"s": 28562,
"text": "CSS code to look good the structure: "
},
{
"code": null,
"e": 28604,
"s": 28600,
"text": "CSS"
},
{
"code": "<style> /* styling article tag component */ article { position: fixed; margin-left: 10px; } /* styling navlist */ #navlist { background-color: #0074D9; position: fixed; left: 45%; top: -60px; width: auto; display: block; transition: top 0.3s; } /* styling navlist anchor element */ #navlist a { float: left; display: block; color: #f2f2f2; text-align: center; padding: 12px; text-decoration: none; font-size: 15px; } /* hover effect of navlist anchor element */ #navlist a:hover { background-color: #ddd; color: black; }</style>",
"e": 29331,
"s": 28604,
"text": null
},
{
"code": null,
"e": 29379,
"s": 29331,
"text": "JavaScript code for the animation on the menu: "
},
{
"code": null,
"e": 29390,
"s": 29379,
"text": "JavaScript"
},
{
"code": "<script> // When the user scrolls down then // slide down the navbar window.onscroll = function() { scroll() }; function scroll() { if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) { document.getElementById(\"navlist\").style.top = \"0\"; } else { document.getElementById(\"navlist\").style.top = \"-60px\"; } }</script>",
"e": 29846,
"s": 29390,
"text": null
},
{
"code": null,
"e": 29948,
"s": 29846,
"text": "Combining the HTML, CSS, and JavaScript code: This example is the combination of the above sections. "
},
{
"code": null,
"e": 29953,
"s": 29948,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title> Slide Down a Navigation Bar on Scroll using HTML CSS and JavaScript </title> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <style> /* styling article tag component */ article { position: fixed; margin-left: 10px; } /* styling navlist */ #navlist { background-color: #0074D9; position: fixed; left: 45%; top: -60px; width: auto; display: block; transition: top 0.3s; } /* styling navlist anchor element */ #navlist a { float: left; display: block; color: #f2f2f2; text-align: center; padding: 12px; text-decoration: none; font-size: 15px; } /* hover effect of navlist anchor element */ #navlist a:hover { background-color: #ddd; color: black; } </style></head> <body> <!-- logo with tag --> <article> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <b> A Computer Science Portal for Geeks </b> <p> How many times were you frustrated while looking out for a good collection of programming/algorithm/interview questions? What did you expect and what did you get? This portal has been created to provide well written, well thought and well explained solutions for selected questions. </p> </article> <!-- Navbar items --> <div id=\"navlist\"> <a href=\"#\">Home</a> <a href=\"#\">About Us</a> <a href=\"#\">Our Products</a> <a href=\"#\">Careers</a> <a href=\"#\">Contact Us</a> </div> <!-- for creating scroll --> <div class=\"scrollable\" style=\"padding:15px 15px 4500px;\"> </div> <script> // When the user scrolls down then // slide down the navbar window.onscroll = function() { scroll() }; function scroll() { if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) { document.getElementById(\"navlist\").style.top = \"0\"; } else { document.getElementById(\"navlist\").style.top = \"-60px\"; } } </script></body> </html>",
"e": 32569,
"s": 29953,
"text": null
},
{
"code": null,
"e": 32578,
"s": 32569,
"text": "Output: "
},
{
"code": null,
"e": 32597,
"s": 32580,
"text": "arorakashish0911"
},
{
"code": null,
"e": 32606,
"s": 32597,
"text": "CSS-Misc"
},
{
"code": null,
"e": 32616,
"s": 32606,
"text": "HTML-Misc"
},
{
"code": null,
"e": 32632,
"s": 32616,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 32636,
"s": 32632,
"text": "CSS"
},
{
"code": null,
"e": 32641,
"s": 32636,
"text": "HTML"
},
{
"code": null,
"e": 32652,
"s": 32641,
"text": "JavaScript"
},
{
"code": null,
"e": 32669,
"s": 32652,
"text": "Web Technologies"
},
{
"code": null,
"e": 32696,
"s": 32669,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 32701,
"s": 32696,
"text": "HTML"
},
{
"code": null,
"e": 32799,
"s": 32701,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32836,
"s": 32799,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 32875,
"s": 32836,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 32904,
"s": 32875,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 32946,
"s": 32904,
"text": "Search Bar using HTML, CSS and JavaScript"
},
{
"code": null,
"e": 32981,
"s": 32946,
"text": "How to style a checkbox using CSS?"
},
{
"code": null,
"e": 33041,
"s": 32981,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 33094,
"s": 33041,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 33155,
"s": 33094,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 33179,
"s": 33155,
"text": "REST API (Introduction)"
}
] |
Python Program to Find Numbers Divisible by 7 and Multiple of 5 in a Given Range - GeeksforGeeks | 04 Dec, 2020
Given a range of numbers, the task is to write a Python program to find numbers divisible by 7 and multiple of 5.
Example:
Input:Enter minimum 100
Enter maximum 200
Output:
105 is divisible by 7 and 5.
140 is divisible by 7 and 5.
175 is divisible by 7 and 5.
Input:Input:Enter minimum 29
Enter maximum 36
Output:
35 is divisible by 7 and 5.
A set of integers can be checked for divisibility by 7 and 5 by performing the modulo operation of the number with 7 and 5 respectively, and then checking the remainder. This can be done in the following ways :
Python3
# enter the starting range numberstart_num = int(29) # enter the ending range numberend_num = int(36) # initialise counter with starting numbercnt = start_num # check until end of the range is achievedwhile cnt <= end_num: # if number divisible by 7 and 5 if cnt % 7 == 0 and cnt % 5 == 0: print(cnt, " is divisible by 7 and 5.") # increment counter cnt += 1
Output:
35 is divisible by 7 and 5.
This can also be done by checking if the number is divisible by 35, since the LCM of 7 and 5 is 35 and any number divisible by 35 is divisible by 7 and 5 and vice versa also.
Python3
# enter the starting range numberstart_num = int(68) # enter the ending range numberend_num = int(167) # initialise counter with starting numbercnt = start_num # check until end of the range is achievedwhile cnt <= end_num: # check if number is divisible by 7 and 5 if(cnt % 35 == 0): print(cnt, "is divisible by 7 and 5.") # incrementing counter cnt += 1
Output:
70 is divisible by 7 and 5.
105 is divisible by 7 and 5.
140 is divisible by 7 and 5.
Numbers
Python
Python Programs
Numbers
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python? | [
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n04 Dec, 2020"
},
{
"code": null,
"e": 25651,
"s": 25537,
"text": "Given a range of numbers, the task is to write a Python program to find numbers divisible by 7 and multiple of 5."
},
{
"code": null,
"e": 25660,
"s": 25651,
"text": "Example:"
},
{
"code": null,
"e": 25887,
"s": 25660,
"text": "Input:Enter minimum 100\nEnter maximum 200\n\nOutput:\n105 is divisible by 7 and 5.\n140 is divisible by 7 and 5.\n175 is divisible by 7 and 5.\n\n\nInput:Input:Enter minimum 29\nEnter maximum 36\n\nOutput:\n35 is divisible by 7 and 5."
},
{
"code": null,
"e": 26099,
"s": 25887,
"text": "A set of integers can be checked for divisibility by 7 and 5 by performing the modulo operation of the number with 7 and 5 respectively, and then checking the remainder. This can be done in the following ways : "
},
{
"code": null,
"e": 26107,
"s": 26099,
"text": "Python3"
},
{
"code": "# enter the starting range numberstart_num = int(29) # enter the ending range numberend_num = int(36) # initialise counter with starting numbercnt = start_num # check until end of the range is achievedwhile cnt <= end_num: # if number divisible by 7 and 5 if cnt % 7 == 0 and cnt % 5 == 0: print(cnt, \" is divisible by 7 and 5.\") # increment counter cnt += 1",
"e": 26502,
"s": 26107,
"text": null
},
{
"code": null,
"e": 26510,
"s": 26502,
"text": "Output:"
},
{
"code": null,
"e": 26539,
"s": 26510,
"text": "35 is divisible by 7 and 5."
},
{
"code": null,
"e": 26715,
"s": 26539,
"text": "This can also be done by checking if the number is divisible by 35, since the LCM of 7 and 5 is 35 and any number divisible by 35 is divisible by 7 and 5 and vice versa also. "
},
{
"code": null,
"e": 26723,
"s": 26715,
"text": "Python3"
},
{
"code": "# enter the starting range numberstart_num = int(68) # enter the ending range numberend_num = int(167) # initialise counter with starting numbercnt = start_num # check until end of the range is achievedwhile cnt <= end_num: # check if number is divisible by 7 and 5 if(cnt % 35 == 0): print(cnt, \"is divisible by 7 and 5.\") # incrementing counter cnt += 1",
"e": 27105,
"s": 26723,
"text": null
},
{
"code": null,
"e": 27113,
"s": 27105,
"text": "Output:"
},
{
"code": null,
"e": 27199,
"s": 27113,
"text": "70 is divisible by 7 and 5.\n105 is divisible by 7 and 5.\n140 is divisible by 7 and 5."
},
{
"code": null,
"e": 27207,
"s": 27199,
"text": "Numbers"
},
{
"code": null,
"e": 27214,
"s": 27207,
"text": "Python"
},
{
"code": null,
"e": 27230,
"s": 27214,
"text": "Python Programs"
},
{
"code": null,
"e": 27238,
"s": 27230,
"text": "Numbers"
},
{
"code": null,
"e": 27336,
"s": 27238,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27368,
"s": 27336,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27410,
"s": 27368,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27452,
"s": 27410,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27508,
"s": 27452,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27535,
"s": 27508,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27557,
"s": 27535,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27596,
"s": 27557,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 27642,
"s": 27596,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 27680,
"s": 27642,
"text": "Python | Convert a list to dictionary"
}
] |
HTTP headers | X-DNS-Prefetch-Control - GeeksforGeeks | 30 Dec, 2019
The X-DNS-Prefetch-Control is an HTTP response type header that informs the browser whether DNS prefetch to be executed or not. Turning it on may not work as many browsers may not support it in all the situations. Turning it off should disable in all supported browsers. Most of the browsers will ignore this header as they don’t do DNS prefetching.
File objects like style sheets, images, JavaScript, etc are pre-fetched in the background. Pre-fetching is done in the background as it is possible that the DNS will be handled by the time the specified items are needed or the user clicks a URL, this reduces latency.
Syntax:
X-DNS-Prefetch-Control: on
X-DNS-Prefetch-Control: on
X-DNS-Prefetch-Control: off
X-DNS-Prefetch-Control: off
Directives: This header accepts two directives as mentioned above and described below:
on: This directive enables pre-fetching of the DNS. This is what browsers do when this header is not available, if they support the function.
off: This directive disables pre-fetching of DNS. This is useful if you don’t monitor the pages reference, or if you know that you don’t want to leak information to those websites.
Examples:
Specific hostnames force lookup: By using the rel attribute on the <link> component with a link type of DNS-Prefetch, you can force the lookup of certain hostnames without providing specific anchors. In this example, the domain name “www.geeksforgeeks.org” will be pre-resolved.<link rel="dns-prefetch" href="https://www.geeksforgeeks.org/">Likewise, the link component is used to resolve hostnames without having a full URL, but only by adding dual slashes before the hostname:<link rel="dns-prefetch" href="//www.geeksforgeeks.org/">
<link rel="dns-prefetch" href="https://www.geeksforgeeks.org/">
Likewise, the link component is used to resolve hostnames without having a full URL, but only by adding dual slashes before the hostname:
<link rel="dns-prefetch" href="//www.geeksforgeeks.org/">
Turning on and off prefetching: You can also use the HTTP-Equiv parameter on the component to send the X-DNS-Prefetch-Control headers server-side or from individual files. Forced prefetching of hostnames could be helpful, for instance, on a site’s homepage to compel pre-resolution of domain names often cited throughout the site even though they are not used on the home page itself.<meta http-equiv="x-dns-prefetch-control" content="off"><meta http-equiv="x-dns-prefetch-control" content="on">
<meta http-equiv="x-dns-prefetch-control" content="off">
<meta http-equiv="x-dns-prefetch-control" content="on">
Note: DNS requests are very small in terms of bandwidth, but latency can be very high for mobile networks.
Supported Browsers: The browsers supported by X-DNS-Prefetch-Control header are listed below:
Google Chrome
Firefox
Opera
HTTP-headers
Picked
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to create footer to stay at the bottom of a Web page?
Differences between Functional Components and Class Components in React
Node.js fs.readFileSync() Method | [
{
"code": null,
"e": 25883,
"s": 25855,
"text": "\n30 Dec, 2019"
},
{
"code": null,
"e": 26233,
"s": 25883,
"text": "The X-DNS-Prefetch-Control is an HTTP response type header that informs the browser whether DNS prefetch to be executed or not. Turning it on may not work as many browsers may not support it in all the situations. Turning it off should disable in all supported browsers. Most of the browsers will ignore this header as they don’t do DNS prefetching."
},
{
"code": null,
"e": 26501,
"s": 26233,
"text": "File objects like style sheets, images, JavaScript, etc are pre-fetched in the background. Pre-fetching is done in the background as it is possible that the DNS will be handled by the time the specified items are needed or the user clicks a URL, this reduces latency."
},
{
"code": null,
"e": 26509,
"s": 26501,
"text": "Syntax:"
},
{
"code": null,
"e": 26536,
"s": 26509,
"text": "X-DNS-Prefetch-Control: on"
},
{
"code": null,
"e": 26563,
"s": 26536,
"text": "X-DNS-Prefetch-Control: on"
},
{
"code": null,
"e": 26591,
"s": 26563,
"text": "X-DNS-Prefetch-Control: off"
},
{
"code": null,
"e": 26619,
"s": 26591,
"text": "X-DNS-Prefetch-Control: off"
},
{
"code": null,
"e": 26706,
"s": 26619,
"text": "Directives: This header accepts two directives as mentioned above and described below:"
},
{
"code": null,
"e": 26848,
"s": 26706,
"text": "on: This directive enables pre-fetching of the DNS. This is what browsers do when this header is not available, if they support the function."
},
{
"code": null,
"e": 27029,
"s": 26848,
"text": "off: This directive disables pre-fetching of DNS. This is useful if you don’t monitor the pages reference, or if you know that you don’t want to leak information to those websites."
},
{
"code": null,
"e": 27039,
"s": 27029,
"text": "Examples:"
},
{
"code": null,
"e": 27575,
"s": 27039,
"text": "Specific hostnames force lookup: By using the rel attribute on the <link> component with a link type of DNS-Prefetch, you can force the lookup of certain hostnames without providing specific anchors. In this example, the domain name “www.geeksforgeeks.org” will be pre-resolved.<link rel=\"dns-prefetch\" href=\"https://www.geeksforgeeks.org/\">Likewise, the link component is used to resolve hostnames without having a full URL, but only by adding dual slashes before the hostname:<link rel=\"dns-prefetch\" href=\"//www.geeksforgeeks.org/\">"
},
{
"code": null,
"e": 27639,
"s": 27575,
"text": "<link rel=\"dns-prefetch\" href=\"https://www.geeksforgeeks.org/\">"
},
{
"code": null,
"e": 27777,
"s": 27639,
"text": "Likewise, the link component is used to resolve hostnames without having a full URL, but only by adding dual slashes before the hostname:"
},
{
"code": null,
"e": 27835,
"s": 27777,
"text": "<link rel=\"dns-prefetch\" href=\"//www.geeksforgeeks.org/\">"
},
{
"code": null,
"e": 28331,
"s": 27835,
"text": "Turning on and off prefetching: You can also use the HTTP-Equiv parameter on the component to send the X-DNS-Prefetch-Control headers server-side or from individual files. Forced prefetching of hostnames could be helpful, for instance, on a site’s homepage to compel pre-resolution of domain names often cited throughout the site even though they are not used on the home page itself.<meta http-equiv=\"x-dns-prefetch-control\" content=\"off\"><meta http-equiv=\"x-dns-prefetch-control\" content=\"on\">"
},
{
"code": null,
"e": 28388,
"s": 28331,
"text": "<meta http-equiv=\"x-dns-prefetch-control\" content=\"off\">"
},
{
"code": null,
"e": 28444,
"s": 28388,
"text": "<meta http-equiv=\"x-dns-prefetch-control\" content=\"on\">"
},
{
"code": null,
"e": 28551,
"s": 28444,
"text": "Note: DNS requests are very small in terms of bandwidth, but latency can be very high for mobile networks."
},
{
"code": null,
"e": 28645,
"s": 28551,
"text": "Supported Browsers: The browsers supported by X-DNS-Prefetch-Control header are listed below:"
},
{
"code": null,
"e": 28659,
"s": 28645,
"text": "Google Chrome"
},
{
"code": null,
"e": 28667,
"s": 28659,
"text": "Firefox"
},
{
"code": null,
"e": 28673,
"s": 28667,
"text": "Opera"
},
{
"code": null,
"e": 28686,
"s": 28673,
"text": "HTTP-headers"
},
{
"code": null,
"e": 28693,
"s": 28686,
"text": "Picked"
},
{
"code": null,
"e": 28712,
"s": 28693,
"text": "Technical Scripter"
},
{
"code": null,
"e": 28729,
"s": 28712,
"text": "Web Technologies"
},
{
"code": null,
"e": 28827,
"s": 28729,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28867,
"s": 28827,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28900,
"s": 28867,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28945,
"s": 28900,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28988,
"s": 28945,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 29038,
"s": 28988,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 29099,
"s": 29038,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 29161,
"s": 29099,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 29219,
"s": 29161,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 29291,
"s": 29219,
"text": "Differences between Functional Components and Class Components in React"
}
] |
How not to delete a function inside an object when JSON.stringify() method is operated? | JSON.stringify() method not only stringifies an object but also removes any function if found inside that object. So to make the function not to be deleted it should be converted into a string and then only JSON.stringify() method should be applied.
In the following example since the function is not converted into a string, it is deleted when operated by JSON.stringify() method and other properties were displayed as shown in the output.
Live Demo
<html>
<body>
<p id="stringify"></p>
<script>
var person = { name: function () {return Ram + Rahim;},
designation:"Developer" , city: "Hyderabad" };
var myJSON = JSON.stringify(person);
document.getElementById("stringify").innerHTML = myJSON;
</script>
</body>
</html>
{"designation":"Developer","city":"Hyderabad"}
In the following example, before getting operated by JSON.stringify() method, the function was converted to a string using toString() method. So the function was not deleted when operated by JSON.stringify() method.
Live Demo
<html>
<body>
<p id="stringify"></p>
<script>
var obj = { name: function () {return Ram + Rahim;},
designation:"Developer" , city: "Hyderabad" };
obj.name = obj.name.toString();
var myJSON = JSON.stringify(obj);
document.getElementById("stringify").innerHTML = myJSON;
</script>
</body>
</html>
{"name":"function () {return Ram + Rahim;}","designation":"Developer","city":"Hyderabad"} | [
{
"code": null,
"e": 1312,
"s": 1062,
"text": "JSON.stringify() method not only stringifies an object but also removes any function if found inside that object. So to make the function not to be deleted it should be converted into a string and then only JSON.stringify() method should be applied."
},
{
"code": null,
"e": 1503,
"s": 1312,
"text": "In the following example since the function is not converted into a string, it is deleted when operated by JSON.stringify() method and other properties were displayed as shown in the output."
},
{
"code": null,
"e": 1513,
"s": 1503,
"text": "Live Demo"
},
{
"code": null,
"e": 1794,
"s": 1513,
"text": "<html>\n<body>\n<p id=\"stringify\"></p>\n<script>\n var person = { name: function () {return Ram + Rahim;},\n designation:\"Developer\" , city: \"Hyderabad\" };\n var myJSON = JSON.stringify(person);\n document.getElementById(\"stringify\").innerHTML = myJSON;\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 1841,
"s": 1794,
"text": "{\"designation\":\"Developer\",\"city\":\"Hyderabad\"}"
},
{
"code": null,
"e": 2059,
"s": 1843,
"text": "In the following example, before getting operated by JSON.stringify() method, the function was converted to a string using toString() method. So the function was not deleted when operated by JSON.stringify() method."
},
{
"code": null,
"e": 2069,
"s": 2059,
"text": "Live Demo"
},
{
"code": null,
"e": 2379,
"s": 2069,
"text": "<html>\n<body>\n<p id=\"stringify\"></p>\n<script>\n var obj = { name: function () {return Ram + Rahim;},\n designation:\"Developer\" , city: \"Hyderabad\" };\n obj.name = obj.name.toString();\n var myJSON = JSON.stringify(obj);\n document.getElementById(\"stringify\").innerHTML = myJSON;\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 2469,
"s": 2379,
"text": "{\"name\":\"function () {return Ram + Rahim;}\",\"designation\":\"Developer\",\"city\":\"Hyderabad\"}"
}
] |
How can I extract minute from time in BigQuery in MySQL? | Extract using extract() method along with cast(). Following is the syntax −
select extract(minute from cast(yourColumnName as time)) as anyAliasName from yourTableName;
Let us create a table −
mysql> create table demo15
−> (
−> value time
−> );
Query OK, 0 rows affected (2.11 sec)
Insert some records into the table with the help of insert command −
mysql> insert into demo15 values('10:30:45');
Query OK, 1 row affected (0.09 sec)
mysql> insert into demo15 values('06:34:55');
Query OK, 1 row affected (0.17 sec)
Display records from the table using select statement −
mysql> select *from demo15;
This will produce the following output −
+----------+
| value |
+----------+
| 10:30:45 |
| 06:34:55 |
+----------+
2 rows in set (0.00 sec)
Following is the query to extract minute from time −
mysql> select extract(minute from cast(value as time)) as Minute from demo15;
This will produce the following output −
+--------+
| Minute |
+--------+
| 30 |
| 34 |
+--------+
2 rows in set (0.00 sec) | [
{
"code": null,
"e": 1138,
"s": 1062,
"text": "Extract using extract() method along with cast(). Following is the syntax −"
},
{
"code": null,
"e": 1231,
"s": 1138,
"text": "select extract(minute from cast(yourColumnName as time)) as anyAliasName from yourTableName;"
},
{
"code": null,
"e": 1255,
"s": 1231,
"text": "Let us create a table −"
},
{
"code": null,
"e": 1344,
"s": 1255,
"text": "mysql> create table demo15\n−> (\n−> value time\n−> );\nQuery OK, 0 rows affected (2.11 sec)"
},
{
"code": null,
"e": 1413,
"s": 1344,
"text": "Insert some records into the table with the help of insert command −"
},
{
"code": null,
"e": 1578,
"s": 1413,
"text": "mysql> insert into demo15 values('10:30:45');\nQuery OK, 1 row affected (0.09 sec)\n\nmysql> insert into demo15 values('06:34:55');\nQuery OK, 1 row affected (0.17 sec)"
},
{
"code": null,
"e": 1634,
"s": 1578,
"text": "Display records from the table using select statement −"
},
{
"code": null,
"e": 1662,
"s": 1634,
"text": "mysql> select *from demo15;"
},
{
"code": null,
"e": 1703,
"s": 1662,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1806,
"s": 1703,
"text": "+----------+\n| value |\n+----------+\n| 10:30:45 |\n| 06:34:55 |\n+----------+\n2 rows in set (0.00 sec)"
},
{
"code": null,
"e": 1859,
"s": 1806,
"text": "Following is the query to extract minute from time −"
},
{
"code": null,
"e": 1937,
"s": 1859,
"text": "mysql> select extract(minute from cast(value as time)) as Minute from demo15;"
},
{
"code": null,
"e": 1978,
"s": 1937,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2069,
"s": 1978,
"text": "+--------+\n| Minute |\n+--------+\n| 30 |\n| 34 |\n+--------+\n2 rows in set (0.00 sec)"
}
] |
Java Swing | JList with examples - GeeksforGeeks | 16 Apr, 2021
JList is part of Java Swing package . JList is a component that displays a set of Objects and allows the user to select one or more items . JList inherits JComponent class. JList is a easy way to display an array of Vectors .Constructor for JList are :
JList(): creates an empty blank listJList(E [ ] l) : creates an new list with the elements of the array.JList(ListModel d): creates a new list with the specified List ModelJList(Vector l) : creates a new list with the elements of the vector
JList(): creates an empty blank list
JList(E [ ] l) : creates an new list with the elements of the array.
JList(ListModel d): creates a new list with the specified List Model
JList(Vector l) : creates a new list with the elements of the vector
Commonly used methods are :
The Following programs will illustrate the use of JLists 1. Program to create a simple JList
Java
// java Program to create a simple JListimport java.awt.event.*;import java.awt.*;import javax.swing.*;class solve extends JFrame{ //frame static JFrame f; //lists static JList b; //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("select the day of the week"); //String array to store weekdays String week[]= { "Monday","Tuesday","Wednesday", "Thursday","Friday","Saturday","Sunday"}; //create list b= new JList(week); //set a selected index b.setSelectedIndex(2); //add list to panel p.add(b); f.add(p); //set the size of frame f.setSize(400,400); f.show(); } }
Output :
2. Program to create a list and add itemListener to it (program to select your birthday using lists) .
Java
// java Program to create a list and add itemListener to it// (program to select your birthday using lists) .import javax.swing.event.*;import java.awt.*;import javax.swing.*;class solve extends JFrame implements ListSelectionListener{ //frame static JFrame f; //lists static JList b,b1,b2; //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("select your birthday"); l1= new JLabel(); //String array to store weekdays String month[]= { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}; //create a array for months and year String date[]=new String[31],year[]=new String[31]; //add month number and year to list for(int i=0;i<31;i++) { date[i]=""+(int)(i+1); year[i]=""+(int)(2018-i); } //create lists b= new JList(date); b1= new JList(month); b2= new JList(year); //set a selected index b.setSelectedIndex(2); b1.setSelectedIndex(1); b2.setSelectedIndex(2); l1.setText(b.getSelectedValue()+" "+b1.getSelectedValue() +" "+b2.getSelectedValue()); //add item listener b.addListSelectionListener(s); b1.addListSelectionListener(s); b2.addListSelectionListener(s); //add list to panel p.add(l); p.add(b); p.add(b1); p.add(b2); p.add(l1); f.add(p); //set the size of frame f.setSize(500,600); f.show(); } public void valueChanged(ListSelectionEvent e) { //set the text of the label to the selected value of lists l1.setText(b.getSelectedValue()+" "+b1.getSelectedValue() +" "+b2.getSelectedValue()); } }
Output :
Note : The above programs might not run in an Online compiler please use an Offline IDE
ManasChhabra2
sweetyty
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": 24534,
"s": 24506,
"text": "\n16 Apr, 2021"
},
{
"code": null,
"e": 24789,
"s": 24534,
"text": "JList is part of Java Swing package . JList is a component that displays a set of Objects and allows the user to select one or more items . JList inherits JComponent class. JList is a easy way to display an array of Vectors .Constructor for JList are : "
},
{
"code": null,
"e": 25030,
"s": 24789,
"text": "JList(): creates an empty blank listJList(E [ ] l) : creates an new list with the elements of the array.JList(ListModel d): creates a new list with the specified List ModelJList(Vector l) : creates a new list with the elements of the vector"
},
{
"code": null,
"e": 25067,
"s": 25030,
"text": "JList(): creates an empty blank list"
},
{
"code": null,
"e": 25136,
"s": 25067,
"text": "JList(E [ ] l) : creates an new list with the elements of the array."
},
{
"code": null,
"e": 25205,
"s": 25136,
"text": "JList(ListModel d): creates a new list with the specified List Model"
},
{
"code": null,
"e": 25274,
"s": 25205,
"text": "JList(Vector l) : creates a new list with the elements of the vector"
},
{
"code": null,
"e": 25303,
"s": 25274,
"text": "Commonly used methods are : "
},
{
"code": null,
"e": 25399,
"s": 25305,
"text": "The Following programs will illustrate the use of JLists 1. Program to create a simple JList "
},
{
"code": null,
"e": 25404,
"s": 25399,
"text": "Java"
},
{
"code": "// java Program to create a simple JListimport java.awt.event.*;import java.awt.*;import javax.swing.*;class solve extends JFrame{ //frame static JFrame f; //lists static JList b; //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(\"select the day of the week\"); //String array to store weekdays String week[]= { \"Monday\",\"Tuesday\",\"Wednesday\", \"Thursday\",\"Friday\",\"Saturday\",\"Sunday\"}; //create list b= new JList(week); //set a selected index b.setSelectedIndex(2); //add list to panel p.add(b); f.add(p); //set the size of frame f.setSize(400,400); f.show(); } }",
"e": 26423,
"s": 25404,
"text": null
},
{
"code": null,
"e": 26434,
"s": 26423,
"text": "Output : "
},
{
"code": null,
"e": 26539,
"s": 26434,
"text": "2. Program to create a list and add itemListener to it (program to select your birthday using lists) . "
},
{
"code": null,
"e": 26544,
"s": 26539,
"text": "Java"
},
{
"code": "// java Program to create a list and add itemListener to it// (program to select your birthday using lists) .import javax.swing.event.*;import java.awt.*;import javax.swing.*;class solve extends JFrame implements ListSelectionListener{ //frame static JFrame f; //lists static JList b,b1,b2; //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(\"select your birthday\"); l1= new JLabel(); //String array to store weekdays String month[]= { \"January\", \"February\", \"March\", \"April\", \"May\", \"June\", \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"}; //create a array for months and year String date[]=new String[31],year[]=new String[31]; //add month number and year to list for(int i=0;i<31;i++) { date[i]=\"\"+(int)(i+1); year[i]=\"\"+(int)(2018-i); } //create lists b= new JList(date); b1= new JList(month); b2= new JList(year); //set a selected index b.setSelectedIndex(2); b1.setSelectedIndex(1); b2.setSelectedIndex(2); l1.setText(b.getSelectedValue()+\" \"+b1.getSelectedValue() +\" \"+b2.getSelectedValue()); //add item listener b.addListSelectionListener(s); b1.addListSelectionListener(s); b2.addListSelectionListener(s); //add list to panel p.add(l); p.add(b); p.add(b1); p.add(b2); p.add(l1); f.add(p); //set the size of frame f.setSize(500,600); f.show(); } public void valueChanged(ListSelectionEvent e) { //set the text of the label to the selected value of lists l1.setText(b.getSelectedValue()+\" \"+b1.getSelectedValue() +\" \"+b2.getSelectedValue()); } }",
"e": 28785,
"s": 26544,
"text": null
},
{
"code": null,
"e": 28796,
"s": 28785,
"text": "Output : "
},
{
"code": null,
"e": 28885,
"s": 28796,
"text": "Note : The above programs might not run in an Online compiler please use an Offline IDE "
},
{
"code": null,
"e": 28899,
"s": 28885,
"text": "ManasChhabra2"
},
{
"code": null,
"e": 28908,
"s": 28899,
"text": "sweetyty"
},
{
"code": null,
"e": 28919,
"s": 28908,
"text": "java-swing"
},
{
"code": null,
"e": 28924,
"s": 28919,
"text": "Java"
},
{
"code": null,
"e": 28929,
"s": 28924,
"text": "Java"
},
{
"code": null,
"e": 29027,
"s": 28929,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29059,
"s": 29027,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 29110,
"s": 29059,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 29140,
"s": 29110,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 29159,
"s": 29140,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 29190,
"s": 29159,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 29208,
"s": 29190,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 29240,
"s": 29208,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 29255,
"s": 29240,
"text": "Stream In Java"
},
{
"code": null,
"e": 29275,
"s": 29255,
"text": "Stack Class in Java"
}
] |
GeoSpark (Apache Sedona) stands out for processing geospatial data at Scale | by Mo Sarwat | Towards Data Science | In the past decade, the volume of available geospatial data increased tremendously. Such data includes but not limited to: weather maps, socio-economic data, and geo-tagged social media. For example, spacecrafts from NASA keep monitoring the status of the earth, including land temperature, atmosphere humidity. As of today, NASA has released over 22PB satellite data. Today, we have close 5 billion mobile devices all around the world. In consequence, Mobile Apps generate tons of gesoaptial data. For instance, Lyft, Uber, and Mobike collect terabytes of GPS data from millions of riders every day. In fact, everything we do on our mobile devices leaves digital traces on the surface of the Earth. Moreover, the unprecedented popularity of GPS-equipped mobile devices and Internet of Things (IoT) sensors has led to continuously generating large-scale location information combined with the status of surrounding environments. For example, several cities have started installing sensors across the road intersections to monitor the environment, traffic and air quality.
Making sense of the rich geospatial properties hidden in the data may greatly transform our society. This includes many subjects undergoing intense study, such as climate change analysis, study of deforestation, population migration, analyzing pandemic spread, urban planning, transportation, commerce and advertisement. These data-intensive geospatial analytics applications highly rely on the underlying data management systems (DBMSs) to efficiently retrieve, process, wrangle and manage data.
Apache Sedona (Formerly GeoSpark) (http://sedona.apache.org) is a cluster computing framework that can process geospatial data at scale. GeoSpark extends the Resilient Distributed Dataset (RDD), the core data structure in Apache Spark, to accommodate big geospatial data in a cluster. A SpatialRDD consists of data partitions that are distributed across the Spark cluster. A Spatial RDD can be created by RDD transformation or be loaded from a file that is stored on permanent storage. This layer provides a number of APIs which allow users to read heterogeneous spatial object from various data formats.
GeoSpark allows users to issue queries using the out-of-box Spatial SQL API and RDD API. The RDD API provides a set of interfaces written in operational programming languages including Scala, Java, Python and R. The Spatial SQL interfaces offers a declarative language interface to the users so they can enjoy more flexibility when creating their own applications. These SQL API implements the SQL/MM Part 3 standard which is widely used in many existing spatial databases such as PostGIS (on top of PostgreSQL). Next, we show how to use GeoSpark.
In the past, researchers and practitioners have developed a number of geospatial data formats for different purposes. However, the heterogeneous sources make it extremely difficult to integrate geospatial data together. For example, WKT format is a widely used spatial data format that stores data in a human readable tab-separated-value file. Shapefile is a spatial database file which includes several sub-files such as index file, and non-spatial attribute file. In addition, geospatial data usually possess different shapes such as points, polygons and trajectories.
Currently, Sedona (GeoSpark) can read WKT, WKB, GeoJSON, Shapefile, and NetCDF / HDF format data from different external storage systems such as local disk, Amazon S3 and Hadoop Distributed File System (HDFS) to Spatial RDDs. Spatial RDDs now can accommodate seven types of spatial data including Point, Multi-Point, Polygon, Multi-Polygon, Line String, Multi-Line String, GeometryCollection, and Circle. Moreover, spatial objects that have different shapes can co-exist in the same Spatial RDD because Sedona adopts a flexible design which generalizes the geometrical computation interfaces of different spatial objects.
Spatial RDD built-in geometrical library: It is quite common that spatial data scientists need to exploit some geometrical attributes of spatial objects in Apache Sedona, such as perimeter, area and intersection. Spatial RDD equips a built-in geometrical library to perform geometrical operations at scale so the users will not be involved into sophisticated computational geometry problems. Currently, the system provides over 20 different functions in this library and put them in two separate categories
Regular geometry functions are applied to every single spatial object in a Spatial RDD. For every object, it generates a corresponding result such as perimeter or area. The output must be either a regular RDD or Spatial RDD.
Geometry aggregation functions are applied to a Spatial RDD for producing an aggregate value. It only generates a single value or spatial object for the entire Spatial RDD. For example, the system can compute the bounding box or polygonal union of the entire Spatial RDD.
Here, we outline the steps to create Spatial RDDs and run spatial queries using GeoSpark RDD APIs. The example code is written in Scala but also works for Java.
Setup Dependencies: Before starting to use Apache Sedona (i.e., GeoSpark), users must add the corresponding package to their projects as a dependency. For the ease of managing dependencies, the binary packages of GeoSpark are hosted on the Maven Central Repository which includes all JVM based packages from the entire world. As long as the projects are managed by popular project management tools such as Apache Maven and sbt, users can easily add Apache Sedona by adding the artifact id in the project specification file such as POM.xml and build.sbt.
Initialize Spark Context: Any RDD in Spark or Apache Sedona must be created by SparkContext. Therefore, the first task in a GeoSpark application is to initiate a SparkContext. The code snippet below gives an example. In order to use custom spatial object and index serializer, users must enable them in the SparkContext.
val conf = new SparkConf()conf.setAppName(“GeoSparkExample”)// Enable GeoSpark custom Kryo serializerconf.set(“spark.serializer”, classOf[KryoSerializer].getName)conf.set(“spark.kryo.registrator”, classOf[GeoSparkKryoRegistrator].getName)val sc = new SparkContext(conf)
Create a Spatial RDD: Spatial objects in a SpatialRDD is not typed to a certain geometry type and open to more scenarios. It allows an input data file which contains mixed types of geometries. For instance, a WKT file might include three types of spatial objects, such as LineString, Polygon and MultiPolygon. Currently, the system can load data in many different data formats. This is done by a set of file readers such as WktReader and GeoJsonReader. For example, users can call ShapefileReader to read ESRI Shapefiles.
val spatialRDD = ShapefileReader.readToGeometryRDD(sc, filePath)
Transform the coordinate reference system: Apache Sedona doesn’t control the coordinate unit (i.e., degree-based or meter-based) of objects in a Spatial RDD. When calculating the distance between two coordinates, GeoSpark simply computes the euclidean distance. In practice, if users want to obtain the accurate geospatial distance, they need to transform coordinates from the degree-based coordinate reference system (CRS), i.e., WGS84, to a planar coordinate reference system (i.e., EPSG: 3857). GeoSpark provides this function to the users such that they can perform this transformation to every object in a Spatial RDD and scale out the workload using a cluster.
// epsg:4326: is WGS84, the most common degree-based CRSval sourceCrsCode = “epsg:4326" // epsg:3857: The most common meter-based CRSval targetCrsCode = “epsg:3857"objectRDD.CRSTransform(sourceCrsCode, targetCrsCode)
Build a spatial index: Users can call APIs to build a distributed spatial index on the Spatial RDD. Currently, the system provides two types of spatial indexes, Quad-Tree and R-Tree, as the local index on each partition. The code of this step is as follows:
spatialRDD.buildIndex(IndexType.QUADTREE, false) // Set to true only if the index will be used join query
Write a spatial range query: A spatial range query returns all spatial objects that lie within a geographical region. For example, a range query may find all parks in the Phoenix metropolitan area or return all restaurants within one mile of the user’s current location. In terms of the format, a spatial range query takes a set of spatial objects and a polygonal query window as input and returns all the spatial objects which lie in the query area. A spatial range query takes as input a range query window and a Spatial RDD and returns all geometries that intersect/are fully covered by the query window. Assume the user has a Spatial RDD. He or she can use the following code to issue a spatial range query on this Spatial RDD. The output format of the spatial range query is another Spatial RDD.
val rangeQueryWindow = new Envelope(-90.01, -80.01, 30.01, 40.01) /*If true, return gemeotries intersect or are fully covered by the window; If false, only return the latter. */val considerIntersect = false// If true, it will leverage the distributed spatial index to speed up the query executionval usingIndex = falsevar queryResult = RangeQuery.SpatialRangeQuery(spatialRDD, rangeQueryWindow, considerIntersect, usingIndex)
Write a spatial K Nearnest Neighbor query: takes as input a K, a query point and a Spatial RDD and finds the K geometries in the RDD which are the closest to the query point. If the user has a Spatial RDD, he or she then can perform the query as follows. The output format of the spatial KNN query is a list which contains K spatial objects.
val geometryFactory = new GeometryFactory()val pointObject = geometryFactory.createPoint(new Coordinate(-84.01, 34.01)) // query pointval K = 1000 // K Nearest Neighborsval usingIndex = falseval result = KNNQuery.SpatialKnnQuery(objectRDD, pointObject, K, usingIndex)
Write a spatial join query: Spatial join queries are queries that combine two datasets or more with a spatial predicate, such as distance and containment relations. There are also some real scenarios in life: tell me all the parks which have lakes and tell me all of the gas stations which have grocery stores within 500 feet. Spatial join query needs two sets of spatial objects as inputs. It finds a subset from the cross product of these two datasets such that every record satisfies the given spatial predicate. In Sedona, a spatial join query takes as input two Spatial RDDs A and B. For each object in A, finds the objects (from B) covered/intersected by it. A and B can be any geometry type and are not necessary to have the same geometry type. Spatial RDD spatial partitioning can significantly speed up the join query. Three spatial partitioning methods are available: KDB-Tree, Quad-Tree and R-Tree. Two Spatial RDDs must be partitioned by the same spatial partitioning grid file. In other words, If the user first partitions Spatial RDD A, then he or she must use the data partitioner of A to partition B. The example code is as follows:
// Perform the spatial partitioningobjectRDD.spatialPartitioning(joinQueryPartitioningType)queryWindowRDD.spatialPartitioning(objectRDD.getPartitioner)// Build the spatial indexval usingIndex = truequeryWindowRDD.buildIndex(IndexType.QUADTREE, true) // Set to true only if the index will be used join queryval result = JoinQuery.SpatialJoinQueryFlat(objectRDD, queryWindowRDD, usingIndex, considerBoundaryIntersection)
Here, we outline the steps to manage spatial data using the Spatial SQL interface of GeoSpark. The SQL interface follows SQL/MM Part3 Spatial SQL Standard. In particular, GeoSpark put the available Spatial SQL functions into three categories: (1) Constructors: create a geometry type column (2) Predicates: evaluate whether a spatial condition is true or false. Predicates are usually used in WHERE clauses, HAVING clauses and so on (3) Geometrical functions: perform a specific geometrical operation on the given inputs. These functions can produce geometries or numerical values such as area or perimeter.
In order to use the system, users need to add GeoSpark as the dependency of their projects, as mentioned in the previous section.
Initiate SparkSession: Any SQL query in Spark or Sedona must be issued by SparkSession, which is the central scheduler of a cluster. To initiate a SparkSession, the user should use the code as follows:
var sparkSession = SparkSession.builder().appName(“GeoSparkExample”)// Enable GeoSpark custom Kryo serializer.config(“spark.serializer”, classOf[KryoSerializer].getName).config(“spark.kryo.registrator”, classOf[GeoSparkKryoRegistrator].getName).getOrCreate()
Register SQL functions: GeoSpark adds new SQL API functions and optimization strategies to the catalyst optimizer of Spark. In order to enable these functionalities, the users need to explicitly register GeoSpark to the Spark Session using the code as follows.
GeoSparkSQLRegistrator.registerAll(sparkSession)
Create a geometry type column: Apache Spark offers a couple of format parsers to load data from disk to a Spark DataFrame (a structured RDD). After obtaining a DataFrame, users who want to run Spatial SQL queries will have to first create a geometry type column on this DataFrame because every attribute must have a type in a relational data system. This can be done via some constructors functions such as ST\_GeomFromWKT. After this step, the users will obtain a Spatial DataFrame. The following example shows the usage of this function.
SELECT ST_GeomFromWKT(wkt_text) AS geom_col, name, addressFROM input
Transform the coordinate reference system: Similar to the RDD APIs, the Spatial SQL APIs also provide a function, namely ST_Transform, to transform the coordinate reference system of spatial objects. It works as follows:
SELECT ST_Transform(geom_col, “epsg:4326", “epsg:3857") AS geom_colFROM spatial_data_frame
Write a spatial range query: GeoSpark Spatial SQL APIs have a set of predicates which evaluate whether a spatial condition is true or false. ST\_Contains is a classical function that takes as input two objects A and returns true if A contains B. In a given SQL query, if A is a single spatial object and B is a column, this becomes a spatial range query in GeoSpark (see the code below).
SELECT *FROM spatial_data_frameWHERE ST_Contains (ST_Envelope(1.0,10.0,100.0,110.0), geom_col)
Write a spatial KNN query: To perform a spatial KNN query using the SQL APIs, the user needs to first compute the distance between the query point and other spatial objects, rank the distances in an ascending order and take the top K objects. The following code finds the 5 nearest neighbors of Point(1, 1).
SELECT name, ST_Distance(ST_Point(1.0, 1.0), geom_col) AS distanceFROM spatial_data_frameORDER BY distance ASCLIMIT 5
Write a spatial join query: A spatial join query in Spatial SQL also uses the aforementioned spatial predicates which evaluate spatial conditions. However, to trigger a join query, the inputs of a spatial predicate must involve at least two geometry type columns which can be from two different DataFrames or the same DataFrame. The following query involves two Spatial DataFrames, one polygon column and one point column. It finds every possible pair of $<$polygon, point$>$ such that the polygon contains the point.
SELECT *FROM spatial_data_frame1 df1, spatial_data_frame2 df2WHERE ST_Contains(df1.polygon_col, df2.point_col)
Perform geometrical operations: GeoSpark provides over 15 SQL functions. for geometrical computation. Users can easily call these functions in their Spatial SQL query and GeoSpark will run the query in parallel. For instance, a very simple query to get the area of every spatial object is as follows:
SELECT ST_Area(geom_col)FROM spatial_data_frame
Aggregate functions for spatial objects are also available in the system. They usually take as input all spatial objects in the DataFrame and yield a single value. For example, the code below computes the union of all polygons in the Data Frame.
SELECT ST_Union_Aggr(geom_col)FROM spatial_data_frame
Although Spark bundles interactive Scala and SQL shells in every release, these shells are not user-friendly and not possible to do complex analysis and charts. Data scientists tend to run programs and draw charts interactively using a graphic interface. Starting from 1.2.0, GeoSpark (Apache Sedona) provides a Helium plugin tailored for Apache Zeppelin web-based notebook. Users can perform spatial analytics on Zeppelin web notebook and Zeppelin will send the tasks to the underlying Spark cluster.
Users can create a new paragraph on a Zeppelin notebook and write code in Scala, Python or SQL to interact with GeoSpark. Moreover, users can click different options available on the interface and ask GeoSpark to render different charts such as bar, line and pie over the query results. For example, Zeppelin can visualize the result of the following query as a bar chart and show that the number of landmarks in every US county.
SELECT C.name, count(*)FROM US_county C, US_landmark LWHERE ST_Contains(C.geom_col, L.geom_col)GROUPBY C.name
Another example is to find the area of each US county and visualize it on a bar chart. The corresponding query is as follows. This actually leverages the geometrical functions offered in GeoSpark.
SELECT C.name, ST_Area(C.geom_col) AS areaFROM US_county C
Moreover, Spatial RDDs equip distributed spatial indices and distributed spatial partitioning to speed up spatial queries. The adopted data partitioning method is tailored to spatial data processing in a cluster. Data in Spatial RDDs are partitioned according to the spatial data distribution and nearby spatial objects are very likely to be put into the same partition. The effect of spatial partitioning is two-fold: (1) when running spatial queries that target at particular spatial regions, GeoSpark can speed up queries by avoiding the unnecessary computation on partitions that are not spatially close. (2) it can chop a Spatial RDD to a number of data partitions which have similar number of records per partition. This way, the system can ensure the load balance and avoid stragglers when performing computation in the cluster.
Sedona employs a distributed spatial index to index Spatial RDDs in the cluster. This distributed index consists of two parts (1) global index: is stored on the master machine and generated during the spatial partitioning phase. It indexes the bounding box of partitions in Spatial RDDs. The purpose of having such a global index is to prune partitions that are guaranteed to have no qualified spatial objects. (2) local index: is built on each partition of a Spatial RDD. Since each local index only works on the data in its own partition, it can have a small index size. Given a spatial query, the local indices in the Spatial RDD can speed up queries in parallel.
Sedona provides a customized serializer for spatial objects and spatial indexes. The proposed serializer can serialize spatial objects and indices into compressed byte arrays. This serializer is faster than the widely used kryo serializer and has a smaller memory footprint when running complex spatial operations, e.g., spatial join query. When converting spatial objects to a byte array, the serializer follows the encoding and decoding specification of Shapefile.
The serializer can also serialize and deserialize local spatial indices, such as Quad-Tree and R-Tree. For serialization, it uses the Depth-First Search (DFS) to traverse each tree node following the pre-order strategy (first write current node information then write its children nodes). For de-serialization, it will follow the same strategy used in the serialization phase. The de-serialization is also a recursive procedure. When serialize or de-serialize every tree node, the index serializer will call the spatial object serializer to deal with individual spatial objects.
In Conclusion, Apache Sedona provides an easy to use interface for data scientists to process geospatial data at scale. Currently, the system supports SQL, Python, R, and Scala as well as so many spatial data formats, e.g., ShapeFiles, ESRI, GeoJSON, NASA formats. Here is a link to the GitHub repository:
sedona.apache.org
GeoSpark has a small active community of developers from both industry and academia. You can also try more coding examples here:
github.com
If you have more questions please feel free to message me on Twitter | [
{
"code": null,
"e": 1244,
"s": 172,
"text": "In the past decade, the volume of available geospatial data increased tremendously. Such data includes but not limited to: weather maps, socio-economic data, and geo-tagged social media. For example, spacecrafts from NASA keep monitoring the status of the earth, including land temperature, atmosphere humidity. As of today, NASA has released over 22PB satellite data. Today, we have close 5 billion mobile devices all around the world. In consequence, Mobile Apps generate tons of gesoaptial data. For instance, Lyft, Uber, and Mobike collect terabytes of GPS data from millions of riders every day. In fact, everything we do on our mobile devices leaves digital traces on the surface of the Earth. Moreover, the unprecedented popularity of GPS-equipped mobile devices and Internet of Things (IoT) sensors has led to continuously generating large-scale location information combined with the status of surrounding environments. For example, several cities have started installing sensors across the road intersections to monitor the environment, traffic and air quality."
},
{
"code": null,
"e": 1741,
"s": 1244,
"text": "Making sense of the rich geospatial properties hidden in the data may greatly transform our society. This includes many subjects undergoing intense study, such as climate change analysis, study of deforestation, population migration, analyzing pandemic spread, urban planning, transportation, commerce and advertisement. These data-intensive geospatial analytics applications highly rely on the underlying data management systems (DBMSs) to efficiently retrieve, process, wrangle and manage data."
},
{
"code": null,
"e": 2346,
"s": 1741,
"text": "Apache Sedona (Formerly GeoSpark) (http://sedona.apache.org) is a cluster computing framework that can process geospatial data at scale. GeoSpark extends the Resilient Distributed Dataset (RDD), the core data structure in Apache Spark, to accommodate big geospatial data in a cluster. A SpatialRDD consists of data partitions that are distributed across the Spark cluster. A Spatial RDD can be created by RDD transformation or be loaded from a file that is stored on permanent storage. This layer provides a number of APIs which allow users to read heterogeneous spatial object from various data formats."
},
{
"code": null,
"e": 2894,
"s": 2346,
"text": "GeoSpark allows users to issue queries using the out-of-box Spatial SQL API and RDD API. The RDD API provides a set of interfaces written in operational programming languages including Scala, Java, Python and R. The Spatial SQL interfaces offers a declarative language interface to the users so they can enjoy more flexibility when creating their own applications. These SQL API implements the SQL/MM Part 3 standard which is widely used in many existing spatial databases such as PostGIS (on top of PostgreSQL). Next, we show how to use GeoSpark."
},
{
"code": null,
"e": 3465,
"s": 2894,
"text": "In the past, researchers and practitioners have developed a number of geospatial data formats for different purposes. However, the heterogeneous sources make it extremely difficult to integrate geospatial data together. For example, WKT format is a widely used spatial data format that stores data in a human readable tab-separated-value file. Shapefile is a spatial database file which includes several sub-files such as index file, and non-spatial attribute file. In addition, geospatial data usually possess different shapes such as points, polygons and trajectories."
},
{
"code": null,
"e": 4087,
"s": 3465,
"text": "Currently, Sedona (GeoSpark) can read WKT, WKB, GeoJSON, Shapefile, and NetCDF / HDF format data from different external storage systems such as local disk, Amazon S3 and Hadoop Distributed File System (HDFS) to Spatial RDDs. Spatial RDDs now can accommodate seven types of spatial data including Point, Multi-Point, Polygon, Multi-Polygon, Line String, Multi-Line String, GeometryCollection, and Circle. Moreover, spatial objects that have different shapes can co-exist in the same Spatial RDD because Sedona adopts a flexible design which generalizes the geometrical computation interfaces of different spatial objects."
},
{
"code": null,
"e": 4594,
"s": 4087,
"text": "Spatial RDD built-in geometrical library: It is quite common that spatial data scientists need to exploit some geometrical attributes of spatial objects in Apache Sedona, such as perimeter, area and intersection. Spatial RDD equips a built-in geometrical library to perform geometrical operations at scale so the users will not be involved into sophisticated computational geometry problems. Currently, the system provides over 20 different functions in this library and put them in two separate categories"
},
{
"code": null,
"e": 4819,
"s": 4594,
"text": "Regular geometry functions are applied to every single spatial object in a Spatial RDD. For every object, it generates a corresponding result such as perimeter or area. The output must be either a regular RDD or Spatial RDD."
},
{
"code": null,
"e": 5091,
"s": 4819,
"text": "Geometry aggregation functions are applied to a Spatial RDD for producing an aggregate value. It only generates a single value or spatial object for the entire Spatial RDD. For example, the system can compute the bounding box or polygonal union of the entire Spatial RDD."
},
{
"code": null,
"e": 5252,
"s": 5091,
"text": "Here, we outline the steps to create Spatial RDDs and run spatial queries using GeoSpark RDD APIs. The example code is written in Scala but also works for Java."
},
{
"code": null,
"e": 5806,
"s": 5252,
"text": "Setup Dependencies: Before starting to use Apache Sedona (i.e., GeoSpark), users must add the corresponding package to their projects as a dependency. For the ease of managing dependencies, the binary packages of GeoSpark are hosted on the Maven Central Repository which includes all JVM based packages from the entire world. As long as the projects are managed by popular project management tools such as Apache Maven and sbt, users can easily add Apache Sedona by adding the artifact id in the project specification file such as POM.xml and build.sbt."
},
{
"code": null,
"e": 6127,
"s": 5806,
"text": "Initialize Spark Context: Any RDD in Spark or Apache Sedona must be created by SparkContext. Therefore, the first task in a GeoSpark application is to initiate a SparkContext. The code snippet below gives an example. In order to use custom spatial object and index serializer, users must enable them in the SparkContext."
},
{
"code": null,
"e": 6397,
"s": 6127,
"text": "val conf = new SparkConf()conf.setAppName(“GeoSparkExample”)// Enable GeoSpark custom Kryo serializerconf.set(“spark.serializer”, classOf[KryoSerializer].getName)conf.set(“spark.kryo.registrator”, classOf[GeoSparkKryoRegistrator].getName)val sc = new SparkContext(conf)"
},
{
"code": null,
"e": 6919,
"s": 6397,
"text": "Create a Spatial RDD: Spatial objects in a SpatialRDD is not typed to a certain geometry type and open to more scenarios. It allows an input data file which contains mixed types of geometries. For instance, a WKT file might include three types of spatial objects, such as LineString, Polygon and MultiPolygon. Currently, the system can load data in many different data formats. This is done by a set of file readers such as WktReader and GeoJsonReader. For example, users can call ShapefileReader to read ESRI Shapefiles."
},
{
"code": null,
"e": 6984,
"s": 6919,
"text": "val spatialRDD = ShapefileReader.readToGeometryRDD(sc, filePath)"
},
{
"code": null,
"e": 7651,
"s": 6984,
"text": "Transform the coordinate reference system: Apache Sedona doesn’t control the coordinate unit (i.e., degree-based or meter-based) of objects in a Spatial RDD. When calculating the distance between two coordinates, GeoSpark simply computes the euclidean distance. In practice, if users want to obtain the accurate geospatial distance, they need to transform coordinates from the degree-based coordinate reference system (CRS), i.e., WGS84, to a planar coordinate reference system (i.e., EPSG: 3857). GeoSpark provides this function to the users such that they can perform this transformation to every object in a Spatial RDD and scale out the workload using a cluster."
},
{
"code": null,
"e": 7868,
"s": 7651,
"text": "// epsg:4326: is WGS84, the most common degree-based CRSval sourceCrsCode = “epsg:4326\" // epsg:3857: The most common meter-based CRSval targetCrsCode = “epsg:3857\"objectRDD.CRSTransform(sourceCrsCode, targetCrsCode)"
},
{
"code": null,
"e": 8126,
"s": 7868,
"text": "Build a spatial index: Users can call APIs to build a distributed spatial index on the Spatial RDD. Currently, the system provides two types of spatial indexes, Quad-Tree and R-Tree, as the local index on each partition. The code of this step is as follows:"
},
{
"code": null,
"e": 8232,
"s": 8126,
"text": "spatialRDD.buildIndex(IndexType.QUADTREE, false) // Set to true only if the index will be used join query"
},
{
"code": null,
"e": 9033,
"s": 8232,
"text": "Write a spatial range query: A spatial range query returns all spatial objects that lie within a geographical region. For example, a range query may find all parks in the Phoenix metropolitan area or return all restaurants within one mile of the user’s current location. In terms of the format, a spatial range query takes a set of spatial objects and a polygonal query window as input and returns all the spatial objects which lie in the query area. A spatial range query takes as input a range query window and a Spatial RDD and returns all geometries that intersect/are fully covered by the query window. Assume the user has a Spatial RDD. He or she can use the following code to issue a spatial range query on this Spatial RDD. The output format of the spatial range query is another Spatial RDD."
},
{
"code": null,
"e": 9459,
"s": 9033,
"text": "val rangeQueryWindow = new Envelope(-90.01, -80.01, 30.01, 40.01) /*If true, return gemeotries intersect or are fully covered by the window; If false, only return the latter. */val considerIntersect = false// If true, it will leverage the distributed spatial index to speed up the query executionval usingIndex = falsevar queryResult = RangeQuery.SpatialRangeQuery(spatialRDD, rangeQueryWindow, considerIntersect, usingIndex)"
},
{
"code": null,
"e": 9801,
"s": 9459,
"text": "Write a spatial K Nearnest Neighbor query: takes as input a K, a query point and a Spatial RDD and finds the K geometries in the RDD which are the closest to the query point. If the user has a Spatial RDD, he or she then can perform the query as follows. The output format of the spatial KNN query is a list which contains K spatial objects."
},
{
"code": null,
"e": 10069,
"s": 9801,
"text": "val geometryFactory = new GeometryFactory()val pointObject = geometryFactory.createPoint(new Coordinate(-84.01, 34.01)) // query pointval K = 1000 // K Nearest Neighborsval usingIndex = falseval result = KNNQuery.SpatialKnnQuery(objectRDD, pointObject, K, usingIndex)"
},
{
"code": null,
"e": 11218,
"s": 10069,
"text": "Write a spatial join query: Spatial join queries are queries that combine two datasets or more with a spatial predicate, such as distance and containment relations. There are also some real scenarios in life: tell me all the parks which have lakes and tell me all of the gas stations which have grocery stores within 500 feet. Spatial join query needs two sets of spatial objects as inputs. It finds a subset from the cross product of these two datasets such that every record satisfies the given spatial predicate. In Sedona, a spatial join query takes as input two Spatial RDDs A and B. For each object in A, finds the objects (from B) covered/intersected by it. A and B can be any geometry type and are not necessary to have the same geometry type. Spatial RDD spatial partitioning can significantly speed up the join query. Three spatial partitioning methods are available: KDB-Tree, Quad-Tree and R-Tree. Two Spatial RDDs must be partitioned by the same spatial partitioning grid file. In other words, If the user first partitions Spatial RDD A, then he or she must use the data partitioner of A to partition B. The example code is as follows:"
},
{
"code": null,
"e": 11637,
"s": 11218,
"text": "// Perform the spatial partitioningobjectRDD.spatialPartitioning(joinQueryPartitioningType)queryWindowRDD.spatialPartitioning(objectRDD.getPartitioner)// Build the spatial indexval usingIndex = truequeryWindowRDD.buildIndex(IndexType.QUADTREE, true) // Set to true only if the index will be used join queryval result = JoinQuery.SpatialJoinQueryFlat(objectRDD, queryWindowRDD, usingIndex, considerBoundaryIntersection)"
},
{
"code": null,
"e": 12245,
"s": 11637,
"text": "Here, we outline the steps to manage spatial data using the Spatial SQL interface of GeoSpark. The SQL interface follows SQL/MM Part3 Spatial SQL Standard. In particular, GeoSpark put the available Spatial SQL functions into three categories: (1) Constructors: create a geometry type column (2) Predicates: evaluate whether a spatial condition is true or false. Predicates are usually used in WHERE clauses, HAVING clauses and so on (3) Geometrical functions: perform a specific geometrical operation on the given inputs. These functions can produce geometries or numerical values such as area or perimeter."
},
{
"code": null,
"e": 12375,
"s": 12245,
"text": "In order to use the system, users need to add GeoSpark as the dependency of their projects, as mentioned in the previous section."
},
{
"code": null,
"e": 12577,
"s": 12375,
"text": "Initiate SparkSession: Any SQL query in Spark or Sedona must be issued by SparkSession, which is the central scheduler of a cluster. To initiate a SparkSession, the user should use the code as follows:"
},
{
"code": null,
"e": 12836,
"s": 12577,
"text": "var sparkSession = SparkSession.builder().appName(“GeoSparkExample”)// Enable GeoSpark custom Kryo serializer.config(“spark.serializer”, classOf[KryoSerializer].getName).config(“spark.kryo.registrator”, classOf[GeoSparkKryoRegistrator].getName).getOrCreate()"
},
{
"code": null,
"e": 13097,
"s": 12836,
"text": "Register SQL functions: GeoSpark adds new SQL API functions and optimization strategies to the catalyst optimizer of Spark. In order to enable these functionalities, the users need to explicitly register GeoSpark to the Spark Session using the code as follows."
},
{
"code": null,
"e": 13146,
"s": 13097,
"text": "GeoSparkSQLRegistrator.registerAll(sparkSession)"
},
{
"code": null,
"e": 13686,
"s": 13146,
"text": "Create a geometry type column: Apache Spark offers a couple of format parsers to load data from disk to a Spark DataFrame (a structured RDD). After obtaining a DataFrame, users who want to run Spatial SQL queries will have to first create a geometry type column on this DataFrame because every attribute must have a type in a relational data system. This can be done via some constructors functions such as ST\\_GeomFromWKT. After this step, the users will obtain a Spatial DataFrame. The following example shows the usage of this function."
},
{
"code": null,
"e": 13755,
"s": 13686,
"text": "SELECT ST_GeomFromWKT(wkt_text) AS geom_col, name, addressFROM input"
},
{
"code": null,
"e": 13976,
"s": 13755,
"text": "Transform the coordinate reference system: Similar to the RDD APIs, the Spatial SQL APIs also provide a function, namely ST_Transform, to transform the coordinate reference system of spatial objects. It works as follows:"
},
{
"code": null,
"e": 14067,
"s": 13976,
"text": "SELECT ST_Transform(geom_col, “epsg:4326\", “epsg:3857\") AS geom_colFROM spatial_data_frame"
},
{
"code": null,
"e": 14455,
"s": 14067,
"text": "Write a spatial range query: GeoSpark Spatial SQL APIs have a set of predicates which evaluate whether a spatial condition is true or false. ST\\_Contains is a classical function that takes as input two objects A and returns true if A contains B. In a given SQL query, if A is a single spatial object and B is a column, this becomes a spatial range query in GeoSpark (see the code below)."
},
{
"code": null,
"e": 14550,
"s": 14455,
"text": "SELECT *FROM spatial_data_frameWHERE ST_Contains (ST_Envelope(1.0,10.0,100.0,110.0), geom_col)"
},
{
"code": null,
"e": 14858,
"s": 14550,
"text": "Write a spatial KNN query: To perform a spatial KNN query using the SQL APIs, the user needs to first compute the distance between the query point and other spatial objects, rank the distances in an ascending order and take the top K objects. The following code finds the 5 nearest neighbors of Point(1, 1)."
},
{
"code": null,
"e": 14976,
"s": 14858,
"text": "SELECT name, ST_Distance(ST_Point(1.0, 1.0), geom_col) AS distanceFROM spatial_data_frameORDER BY distance ASCLIMIT 5"
},
{
"code": null,
"e": 15494,
"s": 14976,
"text": "Write a spatial join query: A spatial join query in Spatial SQL also uses the aforementioned spatial predicates which evaluate spatial conditions. However, to trigger a join query, the inputs of a spatial predicate must involve at least two geometry type columns which can be from two different DataFrames or the same DataFrame. The following query involves two Spatial DataFrames, one polygon column and one point column. It finds every possible pair of $<$polygon, point$>$ such that the polygon contains the point."
},
{
"code": null,
"e": 15605,
"s": 15494,
"text": "SELECT *FROM spatial_data_frame1 df1, spatial_data_frame2 df2WHERE ST_Contains(df1.polygon_col, df2.point_col)"
},
{
"code": null,
"e": 15906,
"s": 15605,
"text": "Perform geometrical operations: GeoSpark provides over 15 SQL functions. for geometrical computation. Users can easily call these functions in their Spatial SQL query and GeoSpark will run the query in parallel. For instance, a very simple query to get the area of every spatial object is as follows:"
},
{
"code": null,
"e": 15954,
"s": 15906,
"text": "SELECT ST_Area(geom_col)FROM spatial_data_frame"
},
{
"code": null,
"e": 16200,
"s": 15954,
"text": "Aggregate functions for spatial objects are also available in the system. They usually take as input all spatial objects in the DataFrame and yield a single value. For example, the code below computes the union of all polygons in the Data Frame."
},
{
"code": null,
"e": 16254,
"s": 16200,
"text": "SELECT ST_Union_Aggr(geom_col)FROM spatial_data_frame"
},
{
"code": null,
"e": 16756,
"s": 16254,
"text": "Although Spark bundles interactive Scala and SQL shells in every release, these shells are not user-friendly and not possible to do complex analysis and charts. Data scientists tend to run programs and draw charts interactively using a graphic interface. Starting from 1.2.0, GeoSpark (Apache Sedona) provides a Helium plugin tailored for Apache Zeppelin web-based notebook. Users can perform spatial analytics on Zeppelin web notebook and Zeppelin will send the tasks to the underlying Spark cluster."
},
{
"code": null,
"e": 17186,
"s": 16756,
"text": "Users can create a new paragraph on a Zeppelin notebook and write code in Scala, Python or SQL to interact with GeoSpark. Moreover, users can click different options available on the interface and ask GeoSpark to render different charts such as bar, line and pie over the query results. For example, Zeppelin can visualize the result of the following query as a bar chart and show that the number of landmarks in every US county."
},
{
"code": null,
"e": 17296,
"s": 17186,
"text": "SELECT C.name, count(*)FROM US_county C, US_landmark LWHERE ST_Contains(C.geom_col, L.geom_col)GROUPBY C.name"
},
{
"code": null,
"e": 17493,
"s": 17296,
"text": "Another example is to find the area of each US county and visualize it on a bar chart. The corresponding query is as follows. This actually leverages the geometrical functions offered in GeoSpark."
},
{
"code": null,
"e": 17552,
"s": 17493,
"text": "SELECT C.name, ST_Area(C.geom_col) AS areaFROM US_county C"
},
{
"code": null,
"e": 18388,
"s": 17552,
"text": "Moreover, Spatial RDDs equip distributed spatial indices and distributed spatial partitioning to speed up spatial queries. The adopted data partitioning method is tailored to spatial data processing in a cluster. Data in Spatial RDDs are partitioned according to the spatial data distribution and nearby spatial objects are very likely to be put into the same partition. The effect of spatial partitioning is two-fold: (1) when running spatial queries that target at particular spatial regions, GeoSpark can speed up queries by avoiding the unnecessary computation on partitions that are not spatially close. (2) it can chop a Spatial RDD to a number of data partitions which have similar number of records per partition. This way, the system can ensure the load balance and avoid stragglers when performing computation in the cluster."
},
{
"code": null,
"e": 19055,
"s": 18388,
"text": "Sedona employs a distributed spatial index to index Spatial RDDs in the cluster. This distributed index consists of two parts (1) global index: is stored on the master machine and generated during the spatial partitioning phase. It indexes the bounding box of partitions in Spatial RDDs. The purpose of having such a global index is to prune partitions that are guaranteed to have no qualified spatial objects. (2) local index: is built on each partition of a Spatial RDD. Since each local index only works on the data in its own partition, it can have a small index size. Given a spatial query, the local indices in the Spatial RDD can speed up queries in parallel."
},
{
"code": null,
"e": 19522,
"s": 19055,
"text": "Sedona provides a customized serializer for spatial objects and spatial indexes. The proposed serializer can serialize spatial objects and indices into compressed byte arrays. This serializer is faster than the widely used kryo serializer and has a smaller memory footprint when running complex spatial operations, e.g., spatial join query. When converting spatial objects to a byte array, the serializer follows the encoding and decoding specification of Shapefile."
},
{
"code": null,
"e": 20101,
"s": 19522,
"text": "The serializer can also serialize and deserialize local spatial indices, such as Quad-Tree and R-Tree. For serialization, it uses the Depth-First Search (DFS) to traverse each tree node following the pre-order strategy (first write current node information then write its children nodes). For de-serialization, it will follow the same strategy used in the serialization phase. The de-serialization is also a recursive procedure. When serialize or de-serialize every tree node, the index serializer will call the spatial object serializer to deal with individual spatial objects."
},
{
"code": null,
"e": 20407,
"s": 20101,
"text": "In Conclusion, Apache Sedona provides an easy to use interface for data scientists to process geospatial data at scale. Currently, the system supports SQL, Python, R, and Scala as well as so many spatial data formats, e.g., ShapeFiles, ESRI, GeoJSON, NASA formats. Here is a link to the GitHub repository:"
},
{
"code": null,
"e": 20425,
"s": 20407,
"text": "sedona.apache.org"
},
{
"code": null,
"e": 20554,
"s": 20425,
"text": "GeoSpark has a small active community of developers from both industry and academia. You can also try more coding examples here:"
},
{
"code": null,
"e": 20565,
"s": 20554,
"text": "github.com"
}
] |
How to find mean and standard deviation from frequency table in R? | To find the mean and standard deviation from frequency table, we would need to apply the formula for mean and standard deviation for frequency data. For example, if we have a data frame called df that contains a column x for units and frequency for counts then the mean and standard deviation can be calculated as −
Mean = sum(df$x*df$frequency)/sum(df$frequency)
SD = sqrt(sum((df$x−Mean)**2*df$frequency)/(sum(df$frequency)−1)) respectively.
Live Demo
x<−rpois(20,5)
frequency<−sample(1:100,20)
df1<−data.frame(x,frequency)
df1
x frequency
1 6 4
2 7 26
3 1 86
4 2 6
5 4 52
6 4 61
7 1 55
8 4 23
9 8 38
10 3 40
11 8 54
12 10 56
13 7 74
14 9 70
15 7 59
16 16 95
17 4 20
18 5 9
19 4 82
20 9 45
Mean=sum(df1$x*df1$frequency)/sum(df1$frequency)
Mean
[1] 6.55288
SD=sqrt(sum((df1$x−Mean)**2*df1$frequency)/(sum(df1$frequency)−1))
SD
[1] 4.172396
Live Demo
y<−rnorm(20,25,3.24)
frequency<−rpois(20,10)
df2<−data.frame(y,frequency)
df2
y frequency
1 27.44960 7
2 25.80343 5
3 22.64088 8
4 22.39061 7
5 24.55087 7
6 24.41826 16
7 23.24647 11
8 25.61511 9
9 22.42244 11
10 26.77522 14
11 21.89209 11
12 22.95852 8
13 25.79808 16
14 22.39654 6
15 21.20728 12
16 28.25911 17
17 26.67983 8
18 25.24964 12
19 20.92070 8
20 28.25806 7
Mean=sum(df2$y*df2$frequency)/sum(df2$frequency)
Mean
[1] 24.58724
SD=sqrt(sum((df2$y−Mean)**2*df2$frequency)/(sum(df2$frequency)−1))
SD
[1] 2.284964 | [
{
"code": null,
"e": 1378,
"s": 1062,
"text": "To find the mean and standard deviation from frequency table, we would need to apply the formula for mean and standard deviation for frequency data. For example, if we have a data frame called df that contains a column x for units and frequency for counts then the mean and standard deviation can be calculated as −"
},
{
"code": null,
"e": 1506,
"s": 1378,
"text": "Mean = sum(df$x*df$frequency)/sum(df$frequency)\nSD = sqrt(sum((df$x−Mean)**2*df$frequency)/(sum(df$frequency)−1)) respectively."
},
{
"code": null,
"e": 1517,
"s": 1506,
"text": " Live Demo"
},
{
"code": null,
"e": 1593,
"s": 1517,
"text": "x<−rpois(20,5)\nfrequency<−sample(1:100,20)\ndf1<−data.frame(x,frequency)\ndf1"
},
{
"code": null,
"e": 1770,
"s": 1593,
"text": " x frequency\n1 6 4\n2 7 26\n3 1 86\n4 2 6\n5 4 52\n6 4 61\n7 1 55\n8 4 23\n9 8 38\n10 3 40\n11 8 54\n12 10 56\n13 7 74\n14 9 70\n15 7 59\n16 16 95\n17 4 20\n18 5 9\n19 4 82\n20 9 45"
},
{
"code": null,
"e": 1824,
"s": 1770,
"text": "Mean=sum(df1$x*df1$frequency)/sum(df1$frequency)\nMean"
},
{
"code": null,
"e": 1836,
"s": 1824,
"text": "[1] 6.55288"
},
{
"code": null,
"e": 1906,
"s": 1836,
"text": "SD=sqrt(sum((df1$x−Mean)**2*df1$frequency)/(sum(df1$frequency)−1))\nSD"
},
{
"code": null,
"e": 1919,
"s": 1906,
"text": "[1] 4.172396"
},
{
"code": null,
"e": 1930,
"s": 1919,
"text": " Live Demo"
},
{
"code": null,
"e": 2008,
"s": 1930,
"text": "y<−rnorm(20,25,3.24)\nfrequency<−rpois(20,10)\ndf2<−data.frame(y,frequency)\ndf2"
},
{
"code": null,
"e": 2300,
"s": 2008,
"text": "y frequency\n1 27.44960 7\n2 25.80343 5\n3 22.64088 8\n4 22.39061 7\n5 24.55087 7\n6 24.41826 16\n7 23.24647 11\n8 25.61511 9\n9 22.42244 11\n10 26.77522 14\n11 21.89209 11\n12 22.95852 8\n13 25.79808 16\n14 22.39654 6\n15 21.20728 12\n16 28.25911 17\n17 26.67983 8\n18 25.24964 12\n19 20.92070 8\n20 28.25806 7"
},
{
"code": null,
"e": 2354,
"s": 2300,
"text": "Mean=sum(df2$y*df2$frequency)/sum(df2$frequency)\nMean"
},
{
"code": null,
"e": 2367,
"s": 2354,
"text": "[1] 24.58724"
},
{
"code": null,
"e": 2437,
"s": 2367,
"text": "SD=sqrt(sum((df2$y−Mean)**2*df2$frequency)/(sum(df2$frequency)−1))\nSD"
},
{
"code": null,
"e": 2450,
"s": 2437,
"text": "[1] 2.284964"
}
] |
Break a Palindrome in C++ | Suppose we have a palindromic string palindrome, we have to replace exactly one character by any lowercase English letter so that the string becomes the lexicographically smallest possible string that isn't a palindrome. Now after doing so, we have to find the final string. If there is no way to do so, then return the empty string. So if the input is like “abccba”, then the output will be “aaccba”.
To solve this, we will follow these steps −
changed := false
changed := false
if the size of a string is 1, then return a blank string
if the size of a string is 1, then return a blank string
i := 0 and j := length of s – 1
i := 0 and j := length of s – 1
leftA := True and rightA := True
leftA := True and rightA := True
while i < j −if s[i] is not ‘a’, then set s[i] as ‘a’ and return sincrease i by 1 and decrease j by 1
while i < j −
if s[i] is not ‘a’, then set s[i] as ‘a’ and return s
if s[i] is not ‘a’, then set s[i] as ‘a’ and return s
increase i by 1 and decrease j by 1
increase i by 1 and decrease j by 1
s[size of s - 1] := ‘b’
s[size of s - 1] := ‘b’
return s
return s
Let us see the following implementation to get a better understanding −
Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
string breakPalindrome(string s) {
bool changed = false;
if(s.size() == 1)return "";
int i = 0, j = s.size() - 1;
bool leftA = true;
bool rightA= true;
while(i < j){
if(s[i] != 'a'){
s[i] = 'a';
return s;
}
i++;
j--;
}
s[s.size() - 1] = 'b';
return s;
}
};
main(){
Solution ob;
cout << (ob.breakPalindrome("abccba"));
}
"abccba"
aaccba | [
{
"code": null,
"e": 1464,
"s": 1062,
"text": "Suppose we have a palindromic string palindrome, we have to replace exactly one character by any lowercase English letter so that the string becomes the lexicographically smallest possible string that isn't a palindrome. Now after doing so, we have to find the final string. If there is no way to do so, then return the empty string. So if the input is like “abccba”, then the output will be “aaccba”."
},
{
"code": null,
"e": 1508,
"s": 1464,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1525,
"s": 1508,
"text": "changed := false"
},
{
"code": null,
"e": 1542,
"s": 1525,
"text": "changed := false"
},
{
"code": null,
"e": 1599,
"s": 1542,
"text": "if the size of a string is 1, then return a blank string"
},
{
"code": null,
"e": 1656,
"s": 1599,
"text": "if the size of a string is 1, then return a blank string"
},
{
"code": null,
"e": 1688,
"s": 1656,
"text": "i := 0 and j := length of s – 1"
},
{
"code": null,
"e": 1720,
"s": 1688,
"text": "i := 0 and j := length of s – 1"
},
{
"code": null,
"e": 1753,
"s": 1720,
"text": "leftA := True and rightA := True"
},
{
"code": null,
"e": 1786,
"s": 1753,
"text": "leftA := True and rightA := True"
},
{
"code": null,
"e": 1889,
"s": 1786,
"text": " while i < j −if s[i] is not ‘a’, then set s[i] as ‘a’ and return sincrease i by 1 and decrease j by 1"
},
{
"code": null,
"e": 1904,
"s": 1889,
"text": " while i < j −"
},
{
"code": null,
"e": 1958,
"s": 1904,
"text": "if s[i] is not ‘a’, then set s[i] as ‘a’ and return s"
},
{
"code": null,
"e": 2012,
"s": 1958,
"text": "if s[i] is not ‘a’, then set s[i] as ‘a’ and return s"
},
{
"code": null,
"e": 2048,
"s": 2012,
"text": "increase i by 1 and decrease j by 1"
},
{
"code": null,
"e": 2084,
"s": 2048,
"text": "increase i by 1 and decrease j by 1"
},
{
"code": null,
"e": 2108,
"s": 2084,
"text": "s[size of s - 1] := ‘b’"
},
{
"code": null,
"e": 2132,
"s": 2108,
"text": "s[size of s - 1] := ‘b’"
},
{
"code": null,
"e": 2141,
"s": 2132,
"text": "return s"
},
{
"code": null,
"e": 2150,
"s": 2141,
"text": "return s"
},
{
"code": null,
"e": 2222,
"s": 2150,
"text": "Let us see the following implementation to get a better understanding −"
},
{
"code": null,
"e": 2233,
"s": 2222,
"text": " Live Demo"
},
{
"code": null,
"e": 2750,
"s": 2233,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nclass Solution {\npublic:\n string breakPalindrome(string s) {\n bool changed = false;\n if(s.size() == 1)return \"\";\n int i = 0, j = s.size() - 1;\n bool leftA = true;\n bool rightA= true;\n while(i < j){\n if(s[i] != 'a'){\n s[i] = 'a';\n return s;\n }\n i++;\n j--;\n }\n s[s.size() - 1] = 'b';\n return s;\n }\n};\nmain(){\n Solution ob;\n cout << (ob.breakPalindrome(\"abccba\"));\n}"
},
{
"code": null,
"e": 2759,
"s": 2750,
"text": "\"abccba\""
},
{
"code": null,
"e": 2766,
"s": 2759,
"text": "aaccba"
}
] |
Python - Append Dictionary Keys and Values ( In order ) in dictionary - GeeksforGeeks | 01 Aug, 2020
Given a dictionary, perform append of keys followed by values in list.
Input : test_dict = {“Gfg” : 1, “is” : 2, “Best” : 3}Output : [‘Gfg’, ‘is’, ‘Best’, 1, 2, 3]Explanation : All the keys before all the values in list.
Input : test_dict = {“Gfg” : 1, “Best” : 3}Output : [‘Gfg’, ‘Best’, 1, 3]Explanation : All the keys before all the values in list.
Method #1 : Using list() + keys() + values()
This is one of the ways in which this task can be performed. In this, we extract keys and values using keys() and values(), convert then to list using list() and perform append in order.
Python3
# Python3 code to demonstrate working of # Append Dictionary Keys and Values ( In order ) in dictionary# Using values() + keys() + list() # initializing dictionarytest_dict = {"Gfg" : 1, "is" : 3, "Best" : 2} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # + operator is used to perform adding keys and valuesres = list(test_dict.keys()) + list(test_dict.values()) # printing result print("The ordered keys and values : " + str(res))
The original dictionary is : {'Gfg': 1, 'is': 3, 'Best': 2}
The ordered keys and values : ['Gfg', 'is', 'Best', 1, 3, 2]
Method #2 : Using chain() + keys() + values()
This is one of the ways in which this task can be performed. In this, we bind keys with values together in order using chain().
Python3
# Python3 code to demonstrate working of # Append Dictionary Keys and Values ( In order ) in dictionary# Using chain() + keys() + values()from itertools import chain # initializing dictionarytest_dict = {"Gfg" : 1, "is" : 3, "Best" : 2} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # chain() is used for concatenationres = list(chain(test_dict.keys(), test_dict.values())) # printing result print("The ordered keys and values : " + str(res))
The original dictionary is : {'Gfg': 1, 'is': 3, 'Best': 2}
The ordered keys and values : ['Gfg', 'is', 'Best', 1, 3, 2]
Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
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 program to convert a list to string
Defaultdict in Python
Python | Split string into list of characters
Python | Get dictionary keys as a list
Python | Convert a list to dictionary | [
{
"code": null,
"e": 24455,
"s": 24427,
"text": "\n01 Aug, 2020"
},
{
"code": null,
"e": 24526,
"s": 24455,
"text": "Given a dictionary, perform append of keys followed by values in list."
},
{
"code": null,
"e": 24676,
"s": 24526,
"text": "Input : test_dict = {“Gfg” : 1, “is” : 2, “Best” : 3}Output : [‘Gfg’, ‘is’, ‘Best’, 1, 2, 3]Explanation : All the keys before all the values in list."
},
{
"code": null,
"e": 24807,
"s": 24676,
"text": "Input : test_dict = {“Gfg” : 1, “Best” : 3}Output : [‘Gfg’, ‘Best’, 1, 3]Explanation : All the keys before all the values in list."
},
{
"code": null,
"e": 24852,
"s": 24807,
"text": "Method #1 : Using list() + keys() + values()"
},
{
"code": null,
"e": 25039,
"s": 24852,
"text": "This is one of the ways in which this task can be performed. In this, we extract keys and values using keys() and values(), convert then to list using list() and perform append in order."
},
{
"code": null,
"e": 25047,
"s": 25039,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of # Append Dictionary Keys and Values ( In order ) in dictionary# Using values() + keys() + list() # initializing dictionarytest_dict = {\"Gfg\" : 1, \"is\" : 3, \"Best\" : 2} # printing original dictionaryprint(\"The original dictionary is : \" + str(test_dict)) # + operator is used to perform adding keys and valuesres = list(test_dict.keys()) + list(test_dict.values()) # printing result print(\"The ordered keys and values : \" + str(res)) ",
"e": 25527,
"s": 25047,
"text": null
},
{
"code": null,
"e": 25649,
"s": 25527,
"text": "The original dictionary is : {'Gfg': 1, 'is': 3, 'Best': 2}\nThe ordered keys and values : ['Gfg', 'is', 'Best', 1, 3, 2]\n"
},
{
"code": null,
"e": 25695,
"s": 25649,
"text": "Method #2 : Using chain() + keys() + values()"
},
{
"code": null,
"e": 25823,
"s": 25695,
"text": "This is one of the ways in which this task can be performed. In this, we bind keys with values together in order using chain()."
},
{
"code": null,
"e": 25831,
"s": 25823,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of # Append Dictionary Keys and Values ( In order ) in dictionary# Using chain() + keys() + values()from itertools import chain # initializing dictionarytest_dict = {\"Gfg\" : 1, \"is\" : 3, \"Best\" : 2} # printing original dictionaryprint(\"The original dictionary is : \" + str(test_dict)) # chain() is used for concatenationres = list(chain(test_dict.keys(), test_dict.values())) # printing result print(\"The ordered keys and values : \" + str(res)) ",
"e": 26320,
"s": 25831,
"text": null
},
{
"code": null,
"e": 26442,
"s": 26320,
"text": "The original dictionary is : {'Gfg': 1, 'is': 3, 'Best': 2}\nThe ordered keys and values : ['Gfg', 'is', 'Best', 1, 3, 2]\n"
},
{
"code": null,
"e": 26469,
"s": 26442,
"text": "Python dictionary-programs"
},
{
"code": null,
"e": 26476,
"s": 26469,
"text": "Python"
},
{
"code": null,
"e": 26492,
"s": 26476,
"text": "Python Programs"
},
{
"code": null,
"e": 26590,
"s": 26492,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26625,
"s": 26590,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 26647,
"s": 26625,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 26679,
"s": 26647,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26709,
"s": 26679,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 26751,
"s": 26709,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 26794,
"s": 26751,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 26816,
"s": 26794,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26862,
"s": 26816,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 26901,
"s": 26862,
"text": "Python | Get dictionary keys as a list"
}
] |
How to make ajax call from JavaScript ? - GeeksforGeeks | 07 Jan, 2022
Ajax stands for Asynchronous JavaScript and XML. It is used to make asynchronous communication with the server. Ajax is used to read data from the server and update the page or send data to the server without affecting the current client page. Ajax is a programming concept.
Below are some ways to make Ajax call in JavaScript.
Approach 1: In this approach, we will use the XMLHttpRequest object to make Ajax call. The XMLHttpRequest() method which create XMLHttpRequest object which is used to make request with server.
Syntax:
var xhttp = new XMLHttpRequest();
Above syntax is used to create XMLHttpRequest object. This object has many different methods which are used to interact with the server to send, receive or interrupt responses from the server. In the response, we get a string from the server that we print.
Example:
Javascript
<script> function run() { // Creating Our XMLHttpRequest object var xhr = new XMLHttpRequest(); // Making our connection var url = 'https://jsonplaceholder.typicode.com/todos/1'; xhr.open("GET", url, true); // function execute after request is successful xhr.onreadystatechange = function () { if (this.readyState == 4 && this.status == 200) { console.log(this.responseText); } } // Sending our request xhr.send(); } run();</script>
Output:
"{
"userId": 1,
"id": 1,
"title": "delectus aut autem",
"completed": false
}"
Approach 2: In this approach, we will use jQuery to make an ajax call. The ajax() method is used in jQuery to make ajax calls. It is used as a replacement for all approaches which are not working to make ajax calls.
Syntax:
$.ajax({arg1: value, arg2: value, ... });
Parameter: It takes a configuration file that configures the URL, type, function to call when we get our response or if error, etc.
Example:
HTML
<!DOCTYPE HTML><html> <head> <script src="https://code.jquery.com/jquery-3.6.0.min.js"> </script></head> <body> <script> function ajaxCall() { $.ajax({ // Our sample url to make request url: 'https://jsonplaceholder.typicode.com/todos/1', // Type of Request type: "GET", // Function to call when to // request is ok success: function (data) { var x = JSON.stringify(data); console.log(x); }, // Error handling error: function (error) { console.log(`Error ${error}`); } }); } ajaxCall(); </script></body> </html>
Output:
{
"userId": 1,
"id": 1,
"title": "delectus aut autem",
"completed": false
}
Approach 3: In this approach, we will use fetch() API which is used to make XMLHttpRequest with the server. Because of its flexible structure, it is easy to use. This API makes a request to the server and gets the result as a promise which is resolved to the string.
Syntax:
fetch(url, {config}).then().catch();
Parameter: It takes URL and config of request as parameters.
We will configure the data required and make the request to the server. Since it is a resolved promise we use then() function and catch() function to create output for the result. In response, we get the string that we print.
Example:
Javascript
<script> // Url for the request var url = 'https://jsonplaceholder.typicode.com/todos/1'; // Making our request fetch(url, { method: 'GET' }) .then(Result => Result.json()) .then(string => { // Printing our response console.log(string); // Printing our field of our response console.log(`Title of our response : ${string.title}`); }) .catch(errorMsg => { console.log(errorMsg); });</script>
Output:
{ userId:1 ,id:1 ,title : "delectus aut autem" ,completed : false
__proto__:Object }
Title of our response : delectus aut autem
rajeev0719singh
JavaScript-Methods
javascript-object
JavaScript-Questions
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
Remove elements from a JavaScript Array
How to get character array from string in JavaScript?
How to filter object array based on attributes?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 25300,
"s": 25272,
"text": "\n07 Jan, 2022"
},
{
"code": null,
"e": 25576,
"s": 25300,
"text": "Ajax stands for Asynchronous JavaScript and XML. It is used to make asynchronous communication with the server. Ajax is used to read data from the server and update the page or send data to the server without affecting the current client page. Ajax is a programming concept. "
},
{
"code": null,
"e": 25629,
"s": 25576,
"text": "Below are some ways to make Ajax call in JavaScript."
},
{
"code": null,
"e": 25824,
"s": 25629,
"text": "Approach 1: In this approach, we will use the XMLHttpRequest object to make Ajax call. The XMLHttpRequest() method which create XMLHttpRequest object which is used to make request with server. "
},
{
"code": null,
"e": 25833,
"s": 25824,
"text": "Syntax: "
},
{
"code": null,
"e": 25867,
"s": 25833,
"text": "var xhttp = new XMLHttpRequest();"
},
{
"code": null,
"e": 26125,
"s": 25867,
"text": "Above syntax is used to create XMLHttpRequest object. This object has many different methods which are used to interact with the server to send, receive or interrupt responses from the server. In the response, we get a string from the server that we print. "
},
{
"code": null,
"e": 26135,
"s": 26125,
"text": "Example: "
},
{
"code": null,
"e": 26146,
"s": 26135,
"text": "Javascript"
},
{
"code": "<script> function run() { // Creating Our XMLHttpRequest object var xhr = new XMLHttpRequest(); // Making our connection var url = 'https://jsonplaceholder.typicode.com/todos/1'; xhr.open(\"GET\", url, true); // function execute after request is successful xhr.onreadystatechange = function () { if (this.readyState == 4 && this.status == 200) { console.log(this.responseText); } } // Sending our request xhr.send(); } run();</script>",
"e": 26706,
"s": 26146,
"text": null
},
{
"code": null,
"e": 26715,
"s": 26706,
"text": "Output: "
},
{
"code": null,
"e": 26801,
"s": 26715,
"text": "\"{\n \"userId\": 1,\n \"id\": 1,\n \"title\": \"delectus aut autem\",\n \"completed\": false\n}\""
},
{
"code": null,
"e": 27018,
"s": 26801,
"text": "Approach 2: In this approach, we will use jQuery to make an ajax call. The ajax() method is used in jQuery to make ajax calls. It is used as a replacement for all approaches which are not working to make ajax calls. "
},
{
"code": null,
"e": 27026,
"s": 27018,
"text": "Syntax:"
},
{
"code": null,
"e": 27068,
"s": 27026,
"text": "$.ajax({arg1: value, arg2: value, ... });"
},
{
"code": null,
"e": 27200,
"s": 27068,
"text": "Parameter: It takes a configuration file that configures the URL, type, function to call when we get our response or if error, etc."
},
{
"code": null,
"e": 27210,
"s": 27200,
"text": "Example: "
},
{
"code": null,
"e": 27215,
"s": 27210,
"text": "HTML"
},
{
"code": "<!DOCTYPE HTML><html> <head> <script src=\"https://code.jquery.com/jquery-3.6.0.min.js\"> </script></head> <body> <script> function ajaxCall() { $.ajax({ // Our sample url to make request url: 'https://jsonplaceholder.typicode.com/todos/1', // Type of Request type: \"GET\", // Function to call when to // request is ok success: function (data) { var x = JSON.stringify(data); console.log(x); }, // Error handling error: function (error) { console.log(`Error ${error}`); } }); } ajaxCall(); </script></body> </html>",
"e": 28026,
"s": 27215,
"text": null
},
{
"code": null,
"e": 28035,
"s": 28026,
"text": "Output: "
},
{
"code": null,
"e": 28119,
"s": 28035,
"text": "{\n \"userId\": 1,\n \"id\": 1,\n \"title\": \"delectus aut autem\",\n \"completed\": false\n}"
},
{
"code": null,
"e": 28386,
"s": 28119,
"text": "Approach 3: In this approach, we will use fetch() API which is used to make XMLHttpRequest with the server. Because of its flexible structure, it is easy to use. This API makes a request to the server and gets the result as a promise which is resolved to the string."
},
{
"code": null,
"e": 28395,
"s": 28386,
"text": "Syntax: "
},
{
"code": null,
"e": 28432,
"s": 28395,
"text": "fetch(url, {config}).then().catch();"
},
{
"code": null,
"e": 28494,
"s": 28432,
"text": "Parameter: It takes URL and config of request as parameters. "
},
{
"code": null,
"e": 28721,
"s": 28494,
"text": "We will configure the data required and make the request to the server. Since it is a resolved promise we use then() function and catch() function to create output for the result. In response, we get the string that we print. "
},
{
"code": null,
"e": 28731,
"s": 28721,
"text": "Example: "
},
{
"code": null,
"e": 28742,
"s": 28731,
"text": "Javascript"
},
{
"code": "<script> // Url for the request var url = 'https://jsonplaceholder.typicode.com/todos/1'; // Making our request fetch(url, { method: 'GET' }) .then(Result => Result.json()) .then(string => { // Printing our response console.log(string); // Printing our field of our response console.log(`Title of our response : ${string.title}`); }) .catch(errorMsg => { console.log(errorMsg); });</script>",
"e": 29241,
"s": 28742,
"text": null
},
{
"code": null,
"e": 29250,
"s": 29241,
"text": "Output: "
},
{
"code": null,
"e": 29379,
"s": 29250,
"text": "{ userId:1 ,id:1 ,title : \"delectus aut autem\" ,completed : false\n__proto__:Object }\nTitle of our response : delectus aut autem"
},
{
"code": null,
"e": 29395,
"s": 29379,
"text": "rajeev0719singh"
},
{
"code": null,
"e": 29414,
"s": 29395,
"text": "JavaScript-Methods"
},
{
"code": null,
"e": 29432,
"s": 29414,
"text": "javascript-object"
},
{
"code": null,
"e": 29453,
"s": 29432,
"text": "JavaScript-Questions"
},
{
"code": null,
"e": 29460,
"s": 29453,
"text": "Picked"
},
{
"code": null,
"e": 29471,
"s": 29460,
"text": "JavaScript"
},
{
"code": null,
"e": 29488,
"s": 29471,
"text": "Web Technologies"
},
{
"code": null,
"e": 29586,
"s": 29488,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29647,
"s": 29586,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 29688,
"s": 29647,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 29728,
"s": 29688,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29782,
"s": 29728,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 29830,
"s": 29782,
"text": "How to filter object array based on attributes?"
},
{
"code": null,
"e": 29872,
"s": 29830,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 29905,
"s": 29872,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 29948,
"s": 29905,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 30010,
"s": 29948,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
] |
Matplotlib.axes.Axes.matshow() in Python - GeeksforGeeks | 13 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute.
The Axes.matshow() function in axes module of matplotlib library is also used to plot the values of a 2D matrix or array as color-coded image.
Syntax:
Axes.matshow(self, Z, **kwargs)
Parameters: This method accept the following parameters that are described below:
z: This parameter contains the matrix which is to be displayed.
Returns: This returns the following:
image : This returns the AxesImage
Below examples illustrate the matplotlib.axes.Axes.imshow() function in matplotlib.axes:
Example-1:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as npfrom matplotlib.colors import LogNorm dx, dy = 0.015, 0.05y, x = np.mgrid[slice(-4, 4 + dy, dy), slice(-4, 4 + dx, dx)]z = (1 - x / 3. + x ** 5 + y ** 5) * np.exp(-x ** 2 - y ** 2)z = z[:-1, :-1] z_min, z_max = -np.abs(z).max(),np.abs(z).max() fig, ax = plt.subplots() c = ax.matshow(z, cmap ='Greens', vmin = z_min, vmax = z_max, extent =[x.min(), x.max(), y.min(), y.max()], interpolation ='nearest', origin ='lower') fig.colorbar(c, ax = ax)ax.set_title('matplotlib.axes.Axes.matshow() Examples\n')plt.show()
Output:
Example-2:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np def samplemat(dims): """Make a matrix with all zeros and increasing elements on the diagonal""" aa = np.zeros(dims) for i in range(min(dims)): aa[i, i] = np.sin(i**3)**2 + i**3 return aa # Display matrix fig, ax = plt.subplots()ax.matshow(samplemat((9, 9)), cmap ="Accent") ax.set_title('matplotlib.axes.Axes.matshow() Examples\n')plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python
*args and **kwargs in Python | [
{
"code": null,
"e": 24580,
"s": 24552,
"text": "\n13 Apr, 2020"
},
{
"code": null,
"e": 24880,
"s": 24580,
"text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute."
},
{
"code": null,
"e": 25023,
"s": 24880,
"text": "The Axes.matshow() function in axes module of matplotlib library is also used to plot the values of a 2D matrix or array as color-coded image."
},
{
"code": null,
"e": 25031,
"s": 25023,
"text": "Syntax:"
},
{
"code": null,
"e": 25063,
"s": 25031,
"text": "Axes.matshow(self, Z, **kwargs)"
},
{
"code": null,
"e": 25145,
"s": 25063,
"text": "Parameters: This method accept the following parameters that are described below:"
},
{
"code": null,
"e": 25209,
"s": 25145,
"text": "z: This parameter contains the matrix which is to be displayed."
},
{
"code": null,
"e": 25246,
"s": 25209,
"text": "Returns: This returns the following:"
},
{
"code": null,
"e": 25281,
"s": 25246,
"text": "image : This returns the AxesImage"
},
{
"code": null,
"e": 25370,
"s": 25281,
"text": "Below examples illustrate the matplotlib.axes.Axes.imshow() function in matplotlib.axes:"
},
{
"code": null,
"e": 25381,
"s": 25370,
"text": "Example-1:"
},
{
"code": "# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as npfrom matplotlib.colors import LogNorm dx, dy = 0.015, 0.05y, x = np.mgrid[slice(-4, 4 + dy, dy), slice(-4, 4 + dx, dx)]z = (1 - x / 3. + x ** 5 + y ** 5) * np.exp(-x ** 2 - y ** 2)z = z[:-1, :-1] z_min, z_max = -np.abs(z).max(),np.abs(z).max() fig, ax = plt.subplots() c = ax.matshow(z, cmap ='Greens', vmin = z_min, vmax = z_max, extent =[x.min(), x.max(), y.min(), y.max()], interpolation ='nearest', origin ='lower') fig.colorbar(c, ax = ax)ax.set_title('matplotlib.axes.Axes.matshow() Examples\\n')plt.show()",
"e": 26146,
"s": 25381,
"text": null
},
{
"code": null,
"e": 26154,
"s": 26146,
"text": "Output:"
},
{
"code": null,
"e": 26165,
"s": 26154,
"text": "Example-2:"
},
{
"code": "# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np def samplemat(dims): \"\"\"Make a matrix with all zeros and increasing elements on the diagonal\"\"\" aa = np.zeros(dims) for i in range(min(dims)): aa[i, i] = np.sin(i**3)**2 + i**3 return aa # Display matrix fig, ax = plt.subplots()ax.matshow(samplemat((9, 9)), cmap =\"Accent\") ax.set_title('matplotlib.axes.Axes.matshow() Examples\\n')plt.show()",
"e": 26632,
"s": 26165,
"text": null
},
{
"code": null,
"e": 26640,
"s": 26632,
"text": "Output:"
},
{
"code": null,
"e": 26658,
"s": 26640,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 26665,
"s": 26658,
"text": "Python"
},
{
"code": null,
"e": 26763,
"s": 26665,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26781,
"s": 26763,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26816,
"s": 26781,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 26838,
"s": 26816,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 26870,
"s": 26838,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26900,
"s": 26870,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 26942,
"s": 26900,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 26968,
"s": 26942,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27005,
"s": 26968,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 27049,
"s": 27005,
"text": "Reading and Writing to text files in Python"
}
] |
N-ary Tree Preorder Traversal in C++ | Suppose we have one n-ary tree, we have to find the preorder traversal of its nodes.
So, if the input is like
then the output will be [1,3,5,6,2,4]
To solve this, we will follow these steps −
Define an array ans
Define an array ans
Define a method called preorder(), this will take root
Define a method called preorder(), this will take root
if root is null, then −return empty list
if root is null, then −
return empty list
return empty list
insert value of root at the end of ans
insert value of root at the end of ans
for all child i in children array of rootpreorder(i)
for all child i in children array of root
preorder(i)
preorder(i)
return ans
return ans
Let us see the following implementation to get a better understanding −
Live Demo
#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<auto> v){
cout << "[";
for(int i = 0; i<v.size(); i++){
cout << v[i] << ", ";
}
cout << "]"<<endl;
}
class Node {
public:
int val;
vector<Node*> children;
Node() {}
Node(int _val) {
val = _val;
}
Node(int _val, vector<Node*> _children) {
val = _val;
children = _children;
}
};
class Solution {
public:
vector<int&g; ans;
vector<int> preorder(Node* root) {
if (!root)
return {};
ans.emplace_back(root->val);
for (auto i : root->children)
preorder(i);
return ans;
}
};
main(){
Solution ob;
Node *node5 = new Node(5), *node6 = new Node(6);
vector<Node*> child_of_3 = {node5, node6};
Node* node3 = new Node(3, child_of_3);
Node *node2 = new Node(2), *node4 = new Node(4);l
vector<Node*> child_of_1 = {node3, node2, node4};
Node *node1 = new Node(1, child_of_1);
print_vector(ob.preorder(node1));
}
Node *node5 = new Node(5), *node6 = new Node(6);
vector<Node*> child_of_3 = {node5, node6};
Node* node3 = new Node(3, child_of_3);
Node *node2 = new Node(2), *node4 = new Node(4);
vector<Node*> child_of_1 = {node3, node2, node4};
Node *node1 = new Node(1, child_of_1);
[1, 3, 5, 6, 2, 4, ] | [
{
"code": null,
"e": 1147,
"s": 1062,
"text": "Suppose we have one n-ary tree, we have to find the preorder traversal of its nodes."
},
{
"code": null,
"e": 1172,
"s": 1147,
"text": "So, if the input is like"
},
{
"code": null,
"e": 1210,
"s": 1172,
"text": "then the output will be [1,3,5,6,2,4]"
},
{
"code": null,
"e": 1254,
"s": 1210,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1274,
"s": 1254,
"text": "Define an array ans"
},
{
"code": null,
"e": 1294,
"s": 1274,
"text": "Define an array ans"
},
{
"code": null,
"e": 1349,
"s": 1294,
"text": "Define a method called preorder(), this will take root"
},
{
"code": null,
"e": 1404,
"s": 1349,
"text": "Define a method called preorder(), this will take root"
},
{
"code": null,
"e": 1445,
"s": 1404,
"text": "if root is null, then −return empty list"
},
{
"code": null,
"e": 1469,
"s": 1445,
"text": "if root is null, then −"
},
{
"code": null,
"e": 1487,
"s": 1469,
"text": "return empty list"
},
{
"code": null,
"e": 1505,
"s": 1487,
"text": "return empty list"
},
{
"code": null,
"e": 1544,
"s": 1505,
"text": "insert value of root at the end of ans"
},
{
"code": null,
"e": 1583,
"s": 1544,
"text": "insert value of root at the end of ans"
},
{
"code": null,
"e": 1636,
"s": 1583,
"text": "for all child i in children array of rootpreorder(i)"
},
{
"code": null,
"e": 1678,
"s": 1636,
"text": "for all child i in children array of root"
},
{
"code": null,
"e": 1690,
"s": 1678,
"text": "preorder(i)"
},
{
"code": null,
"e": 1702,
"s": 1690,
"text": "preorder(i)"
},
{
"code": null,
"e": 1713,
"s": 1702,
"text": "return ans"
},
{
"code": null,
"e": 1724,
"s": 1713,
"text": "return ans"
},
{
"code": null,
"e": 1796,
"s": 1724,
"text": "Let us see the following implementation to get a better understanding −"
},
{
"code": null,
"e": 1807,
"s": 1796,
"text": " Live Demo"
},
{
"code": null,
"e": 2804,
"s": 1807,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nvoid print_vector(vector<auto> v){\n cout << \"[\";\n for(int i = 0; i<v.size(); i++){\n cout << v[i] << \", \";\n }\n cout << \"]\"<<endl;\n}\nclass Node {\npublic:\n int val;\n vector<Node*> children;\n Node() {}\n Node(int _val) {\n val = _val;\n }\n Node(int _val, vector<Node*> _children) {\n val = _val;\n children = _children;\n }\n};\nclass Solution {\npublic:\n vector<int&g; ans;\n vector<int> preorder(Node* root) {\n if (!root)\n return {};\n ans.emplace_back(root->val);\n for (auto i : root->children)\n preorder(i);\n return ans;\n }\n};\nmain(){\n Solution ob;\n Node *node5 = new Node(5), *node6 = new Node(6);\n vector<Node*> child_of_3 = {node5, node6};\n Node* node3 = new Node(3, child_of_3);\n Node *node2 = new Node(2), *node4 = new Node(4);l\n vector<Node*> child_of_1 = {node3, node2, node4};\n Node *node1 = new Node(1, child_of_1);\n print_vector(ob.preorder(node1));\n}"
},
{
"code": null,
"e": 3073,
"s": 2804,
"text": "Node *node5 = new Node(5), *node6 = new Node(6);\nvector<Node*> child_of_3 = {node5, node6};\nNode* node3 = new Node(3, child_of_3);\nNode *node2 = new Node(2), *node4 = new Node(4);\nvector<Node*> child_of_1 = {node3, node2, node4};\nNode *node1 = new Node(1, child_of_1);"
},
{
"code": null,
"e": 3094,
"s": 3073,
"text": "[1, 3, 5, 6, 2, 4, ]"
}
] |
Difference Between PHP and JavaScript | In this post, we will understand the differences between PHP and JavaScript −
JavaScript
It helps work with frond end as well as back end
It is asynchronous, which means it doesn't wait for the input and output operations.
It can be run in browsers and since 'Node' has been released, JavaScript can also run be run on the command line.
It can be combined with HTML, AJAX and XML.
It is a single threaded language which is event-driven. This means it doesn't block everything and runs concurrently.
The statements are placed within the <script> and </script> tags.
These tags can be present anywhere within the webpage, but it is recommended to keep them within the <head> tags.
The <head> tag tells the browser to start the interpretation of text within these tags as JavaScript code.
A sample JavaScript code −
Live Demo
<!DOCTYPE html>
<html>
<body>
<h2> JavaScript code</h2>
<script>
var n;
n=2;
for(var i=0; i<n; i++){
document.write("Hi " +"<br>");
}
</script>
</body>
</html>
JavaScript code
Hi
Hi
It can be written in HTML code, as well as within the .php file.
PHP requires a server to run.
XAMPP or a local server application can be installed to run PHP.
The code in PHP starts with <?php and ends with ?>.
This tells the server that PHP code begins here.
A sample PHP code −
Live Demo
<!DOCTYPE html>
<html>
<body>
<h1>PHP Code </h1>
<?php
$str= "Hi";
$x = 2;
for( $i = 0; $i<2; $i++ ) {
echo ("Hi");
}
?>
</body>
</html>
Hi
Hi
Conclusion
In this post, we understood about the significant differences between PHP and Javascript. | [
{
"code": null,
"e": 1140,
"s": 1062,
"text": "In this post, we will understand the differences between PHP and JavaScript −"
},
{
"code": null,
"e": 1151,
"s": 1140,
"text": "JavaScript"
},
{
"code": null,
"e": 1200,
"s": 1151,
"text": "It helps work with frond end as well as back end"
},
{
"code": null,
"e": 1285,
"s": 1200,
"text": "It is asynchronous, which means it doesn't wait for the input and output operations."
},
{
"code": null,
"e": 1399,
"s": 1285,
"text": "It can be run in browsers and since 'Node' has been released, JavaScript can also run be run on the command line."
},
{
"code": null,
"e": 1443,
"s": 1399,
"text": "It can be combined with HTML, AJAX and XML."
},
{
"code": null,
"e": 1561,
"s": 1443,
"text": "It is a single threaded language which is event-driven. This means it doesn't block everything and runs concurrently."
},
{
"code": null,
"e": 1627,
"s": 1561,
"text": "The statements are placed within the <script> and </script> tags."
},
{
"code": null,
"e": 1741,
"s": 1627,
"text": "These tags can be present anywhere within the webpage, but it is recommended to keep them within the <head> tags."
},
{
"code": null,
"e": 1848,
"s": 1741,
"text": "The <head> tag tells the browser to start the interpretation of text within these tags as JavaScript code."
},
{
"code": null,
"e": 1875,
"s": 1848,
"text": "A sample JavaScript code −"
},
{
"code": null,
"e": 1885,
"s": 1875,
"text": "Live Demo"
},
{
"code": null,
"e": 2063,
"s": 1885,
"text": "<!DOCTYPE html>\n<html>\n<body>\n<h2> JavaScript code</h2>\n<script>\n var n;\n n=2;\n for(var i=0; i<n; i++){\n document.write(\"Hi \" +\"<br>\");\n }\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 2085,
"s": 2063,
"text": "JavaScript code\nHi\nHi"
},
{
"code": null,
"e": 2150,
"s": 2085,
"text": "It can be written in HTML code, as well as within the .php file."
},
{
"code": null,
"e": 2180,
"s": 2150,
"text": "PHP requires a server to run."
},
{
"code": null,
"e": 2245,
"s": 2180,
"text": "XAMPP or a local server application can be installed to run PHP."
},
{
"code": null,
"e": 2297,
"s": 2245,
"text": "The code in PHP starts with <?php and ends with ?>."
},
{
"code": null,
"e": 2346,
"s": 2297,
"text": "This tells the server that PHP code begins here."
},
{
"code": null,
"e": 2366,
"s": 2346,
"text": "A sample PHP code −"
},
{
"code": null,
"e": 2376,
"s": 2366,
"text": "Live Demo"
},
{
"code": null,
"e": 2531,
"s": 2376,
"text": "<!DOCTYPE html>\n<html>\n<body>\n<h1>PHP Code </h1>\n<?php\n $str= \"Hi\";\n $x = 2;\n for( $i = 0; $i<2; $i++ ) {\n echo (\"Hi\");\n }\n?>\n</body>\n</html>"
},
{
"code": null,
"e": 2537,
"s": 2531,
"text": "Hi\nHi"
},
{
"code": null,
"e": 2548,
"s": 2537,
"text": "Conclusion"
},
{
"code": null,
"e": 2638,
"s": 2548,
"text": "In this post, we understood about the significant differences between PHP and Javascript."
}
] |
Unit Testing in Android using Mockito - GeeksforGeeks | 26 Nov, 2021
Most classes have dependencies, and methods frequently delegate work to other methods in other classes, which we refer to as class dependencies. If we just utilized JUnit to unit test these methods, our tests would likewise be dependent on them. All additional dependencies should be independent of the unit tests. As a result, we simply mock the dependency class and test the Main Class. Mockito is a mocking framework with a delicious flavor. It has a clean and simple API that allows you to construct beautiful tests. The tests in Mockito are very readable and provide clear verification errors, so you won’t get a hangover. Now, let’s look at an example of how to use mockito.
We begin by adding the dependency to the app. file gradle:
testImplementation 'junit:junit:4.12'
testImplementation 'org.mockito:mockito-core:2.19.0'
Image #1: Creating the new project
object Operators {
add(m: Int, n: Int): Int = m + n
subtract(n: Int, m: Int): Int = n - m
multiply(c: Int, a: Int): Int = c * a
divide(l: Int, d: Int): Int = l / d
}
Also below is the calculator class:
Kotlin
class GfGCalculator(private val operators: Operators) { fun addTwoNumbers(ab: Int, ba: Int): Int = operators.add(ab, ba) fun subtractTwoNumbers(ac: Int, bc: Int): Int = operators.subtract(ac, bc) fun multiplyTwoNumbers(ad: Int, bd: Int): Int = operators.multiply(ad, bd) fun divideTwoNumbers(aa: Int, ba: Int): Int = operators.divide(aa, ba)}
The primary function Object() { [native code] } of Calculator takes operator object as an argument. As a result, the functions in the Calculator class return operator function as a return param. Now, Let’s get started testing the Calculator Class. We’ll build a package called calculator in the test folder, just like we did in the java folder.
Image #2: The calculator test.
Kotlin
@RunWith(MockitoJUnitRunner::class)class CalculatorTestGfG {}
We haven’t developed OperatorsTest because we simply need to test CalculatorTest here. MockitoJUnitRunner::class is annotated here, which signifies it offers a Runner to run the test. We’ll now set up the calculator class.
Kotlin
@RunWith(MockitoJUnitRunner::class)class CalculatorTestGfG { lateinit var calc: Calculator @Before fun someSetup() { calc = Calculator(/** your operators here **/) }}
The operators must be passed in construct. As a result, we will not create an operator object as, we want to run the test in isolation so that if the Operators crash, it won’t affect the CalculatorTest test. We only need to use the Operator class’s invoke methods to communicate with the outside world. Also, @Before implies that we must set up the dependency even before running the test.
Kotlin
@RunWith(MockitoJUnitRunner::class)class CalculatorTestGfG { @Mock lateinit var ops: Operators lateinit var calc: Calculator @Before fun someSetup() { calc = Calculator(operators) }}
Using the @Mock annotation, we can mock any class in Mockito. By mocking a specific class, we create a mock object of that class. Operators are mocked in the above code to provide A Calculator with a dependency. Now we’ll make two variables, a and b, with the values 12,21, and call them.
calc.addTwoNumbers(ab, ba)
We’ll only use, to see if the right function was called or not from the mocked class.
verify(operators).add(ab, ba)
Verify indicates that you want to see if a particular method of a mock object has been called or not.
Image #3: The context menu
This will execute the test and produce an output indicating if the test passed or failed. The test passed in our case since we used the right function. Our test will fail because we are calling addNumbers from the Calculator class, then subtracting from fake Operators.
Image #4: Error running the test
This is how we can utilize Mockito in our app to perform unit testing. Now, in order to test all of the functions, write and run the code below
Kotlin
package com.geeksforgeeks.calc import org.junit.Beforeimport org.junit.Testimport org.junit.runner.RunWithimport org.mockito.Mockimport org.mockito.Mockito.verifyimport org.mockito.junit.MockitoJUnitRunner @RunWith(MockitoJUnitRunner::class)class CalculatorTest { @Mock lateinit var ops: Operators lateinit var calc: Calculator @Before fun someSetup() { calc = Calculator(ops) } @Test fun givenValidInput_whenAdd_shouldCallAddOperator() { val aa = 11 val ba = 21 calculator.addTwoNumbers(aa, ba) verify(operators).add(aa, ba) } @Test fun givenValidInput_whenSubtract_shouldCallSubtractOperator() { val ac = 11 val bc = 21 calc.subtractTwoNumbers(ac, bc) verify(ops).subtract(ac, bc) } @Test fun givenValidInput_whenMultiply_shouldCallMultiplyOperator() { val av = 11 val bv = 21 calc.multiplyTwoNumbers(av, bv) verify(ops).multiply(av, bv) } @Test fun givenValidInput_whenDivide_shouldCallDivideOperator() { val ap = 11 val bp = 21 calc.divideTwoNumbers(ap, bp) verify(ops).divide(ap, bp) }}
GeekTip: Mockito cannot directly test final/static classes because all Kotlin classes are final. We need to set up mockito-extensions in order to run tests on final classes.
Picked
Android
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Flutter - Custom Bottom Navigation Bar
How to Read Data from SQLite Database in Android?
Android Listview in Java with Example
How to Post Data to API using Retrofit in Android?
Retrofit with Kotlin Coroutine in Android
How to Add Image to Drawable Folder in Android Studio?
How to Change the Background Color After Clicking the Button in Android?
How to Retrieve Data from the Firebase Realtime Database in Android?
GridView in Android with Example
ImageView in Android with Example | [
{
"code": null,
"e": 24725,
"s": 24697,
"text": "\n26 Nov, 2021"
},
{
"code": null,
"e": 25406,
"s": 24725,
"text": "Most classes have dependencies, and methods frequently delegate work to other methods in other classes, which we refer to as class dependencies. If we just utilized JUnit to unit test these methods, our tests would likewise be dependent on them. All additional dependencies should be independent of the unit tests. As a result, we simply mock the dependency class and test the Main Class. Mockito is a mocking framework with a delicious flavor. It has a clean and simple API that allows you to construct beautiful tests. The tests in Mockito are very readable and provide clear verification errors, so you won’t get a hangover. Now, let’s look at an example of how to use mockito."
},
{
"code": null,
"e": 25465,
"s": 25406,
"text": "We begin by adding the dependency to the app. file gradle:"
},
{
"code": null,
"e": 25556,
"s": 25465,
"text": "testImplementation 'junit:junit:4.12'\ntestImplementation 'org.mockito:mockito-core:2.19.0'"
},
{
"code": null,
"e": 25591,
"s": 25556,
"text": "Image #1: Creating the new project"
},
{
"code": null,
"e": 25773,
"s": 25591,
"text": "object Operators {\n add(m: Int, n: Int): Int = m + n\n subtract(n: Int, m: Int): Int = n - m\n multiply(c: Int, a: Int): Int = c * a\n divide(l: Int, d: Int): Int = l / d\n}"
},
{
"code": null,
"e": 25809,
"s": 25773,
"text": "Also below is the calculator class:"
},
{
"code": null,
"e": 25816,
"s": 25809,
"text": "Kotlin"
},
{
"code": "class GfGCalculator(private val operators: Operators) { fun addTwoNumbers(ab: Int, ba: Int): Int = operators.add(ab, ba) fun subtractTwoNumbers(ac: Int, bc: Int): Int = operators.subtract(ac, bc) fun multiplyTwoNumbers(ad: Int, bd: Int): Int = operators.multiply(ad, bd) fun divideTwoNumbers(aa: Int, ba: Int): Int = operators.divide(aa, ba)}",
"e": 26171,
"s": 25816,
"text": null
},
{
"code": null,
"e": 26516,
"s": 26171,
"text": "The primary function Object() { [native code] } of Calculator takes operator object as an argument. As a result, the functions in the Calculator class return operator function as a return param. Now, Let’s get started testing the Calculator Class. We’ll build a package called calculator in the test folder, just like we did in the java folder."
},
{
"code": null,
"e": 26547,
"s": 26516,
"text": "Image #2: The calculator test."
},
{
"code": null,
"e": 26554,
"s": 26547,
"text": "Kotlin"
},
{
"code": "@RunWith(MockitoJUnitRunner::class)class CalculatorTestGfG {}",
"e": 26616,
"s": 26554,
"text": null
},
{
"code": null,
"e": 26839,
"s": 26616,
"text": "We haven’t developed OperatorsTest because we simply need to test CalculatorTest here. MockitoJUnitRunner::class is annotated here, which signifies it offers a Runner to run the test. We’ll now set up the calculator class."
},
{
"code": null,
"e": 26846,
"s": 26839,
"text": "Kotlin"
},
{
"code": "@RunWith(MockitoJUnitRunner::class)class CalculatorTestGfG { lateinit var calc: Calculator @Before fun someSetup() { calc = Calculator(/** your operators here **/) }}",
"e": 27032,
"s": 26846,
"text": null
},
{
"code": null,
"e": 27422,
"s": 27032,
"text": "The operators must be passed in construct. As a result, we will not create an operator object as, we want to run the test in isolation so that if the Operators crash, it won’t affect the CalculatorTest test. We only need to use the Operator class’s invoke methods to communicate with the outside world. Also, @Before implies that we must set up the dependency even before running the test."
},
{
"code": null,
"e": 27429,
"s": 27422,
"text": "Kotlin"
},
{
"code": "@RunWith(MockitoJUnitRunner::class)class CalculatorTestGfG { @Mock lateinit var ops: Operators lateinit var calc: Calculator @Before fun someSetup() { calc = Calculator(operators) }}",
"e": 27637,
"s": 27429,
"text": null
},
{
"code": null,
"e": 27926,
"s": 27637,
"text": "Using the @Mock annotation, we can mock any class in Mockito. By mocking a specific class, we create a mock object of that class. Operators are mocked in the above code to provide A Calculator with a dependency. Now we’ll make two variables, a and b, with the values 12,21, and call them."
},
{
"code": null,
"e": 27953,
"s": 27926,
"text": "calc.addTwoNumbers(ab, ba)"
},
{
"code": null,
"e": 28039,
"s": 27953,
"text": "We’ll only use, to see if the right function was called or not from the mocked class."
},
{
"code": null,
"e": 28070,
"s": 28039,
"text": "verify(operators).add(ab, ba) "
},
{
"code": null,
"e": 28172,
"s": 28070,
"text": "Verify indicates that you want to see if a particular method of a mock object has been called or not."
},
{
"code": null,
"e": 28199,
"s": 28172,
"text": "Image #3: The context menu"
},
{
"code": null,
"e": 28469,
"s": 28199,
"text": "This will execute the test and produce an output indicating if the test passed or failed. The test passed in our case since we used the right function. Our test will fail because we are calling addNumbers from the Calculator class, then subtracting from fake Operators."
},
{
"code": null,
"e": 28502,
"s": 28469,
"text": "Image #4: Error running the test"
},
{
"code": null,
"e": 28646,
"s": 28502,
"text": "This is how we can utilize Mockito in our app to perform unit testing. Now, in order to test all of the functions, write and run the code below"
},
{
"code": null,
"e": 28653,
"s": 28646,
"text": "Kotlin"
},
{
"code": "package com.geeksforgeeks.calc import org.junit.Beforeimport org.junit.Testimport org.junit.runner.RunWithimport org.mockito.Mockimport org.mockito.Mockito.verifyimport org.mockito.junit.MockitoJUnitRunner @RunWith(MockitoJUnitRunner::class)class CalculatorTest { @Mock lateinit var ops: Operators lateinit var calc: Calculator @Before fun someSetup() { calc = Calculator(ops) } @Test fun givenValidInput_whenAdd_shouldCallAddOperator() { val aa = 11 val ba = 21 calculator.addTwoNumbers(aa, ba) verify(operators).add(aa, ba) } @Test fun givenValidInput_whenSubtract_shouldCallSubtractOperator() { val ac = 11 val bc = 21 calc.subtractTwoNumbers(ac, bc) verify(ops).subtract(ac, bc) } @Test fun givenValidInput_whenMultiply_shouldCallMultiplyOperator() { val av = 11 val bv = 21 calc.multiplyTwoNumbers(av, bv) verify(ops).multiply(av, bv) } @Test fun givenValidInput_whenDivide_shouldCallDivideOperator() { val ap = 11 val bp = 21 calc.divideTwoNumbers(ap, bp) verify(ops).divide(ap, bp) }}",
"e": 29836,
"s": 28653,
"text": null
},
{
"code": null,
"e": 30010,
"s": 29836,
"text": "GeekTip: Mockito cannot directly test final/static classes because all Kotlin classes are final. We need to set up mockito-extensions in order to run tests on final classes."
},
{
"code": null,
"e": 30017,
"s": 30010,
"text": "Picked"
},
{
"code": null,
"e": 30025,
"s": 30017,
"text": "Android"
},
{
"code": null,
"e": 30033,
"s": 30025,
"text": "Android"
},
{
"code": null,
"e": 30131,
"s": 30033,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30140,
"s": 30131,
"text": "Comments"
},
{
"code": null,
"e": 30153,
"s": 30140,
"text": "Old Comments"
},
{
"code": null,
"e": 30192,
"s": 30153,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 30242,
"s": 30192,
"text": "How to Read Data from SQLite Database in Android?"
},
{
"code": null,
"e": 30280,
"s": 30242,
"text": "Android Listview in Java with Example"
},
{
"code": null,
"e": 30331,
"s": 30280,
"text": "How to Post Data to API using Retrofit in Android?"
},
{
"code": null,
"e": 30373,
"s": 30331,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 30428,
"s": 30373,
"text": "How to Add Image to Drawable Folder in Android Studio?"
},
{
"code": null,
"e": 30501,
"s": 30428,
"text": "How to Change the Background Color After Clicking the Button in Android?"
},
{
"code": null,
"e": 30570,
"s": 30501,
"text": "How to Retrieve Data from the Firebase Realtime Database in Android?"
},
{
"code": null,
"e": 30603,
"s": 30570,
"text": "GridView in Android with Example"
}
] |
How to show soft Keyboard based on Android EditText is focused? | This example demonstrates how do I show soft keyboard based on Android EditText is focused.
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"
tools:context=".MainActivity">
<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.java
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
EditText editText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = findViewById(R.id.editText);
showSoftKeyboard(editText);
}
public void showSoftKeyboard(View view) {
if(view.requestFocus()){
InputMethodManager imm =(InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(view,InputMethodManager.SHOW_IMPLICIT);
}
}
}
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 − | [
{
"code": null,
"e": 1154,
"s": 1062,
"text": "This example demonstrates how do I show soft keyboard based on Android EditText is focused."
},
{
"code": null,
"e": 1283,
"s": 1154,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1348,
"s": 1283,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 1823,
"s": 1348,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout\n 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 tools:context=\".MainActivity\">\n <EditText\n android:id=\"@+id/editText\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 1880,
"s": 1823,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 2684,
"s": 1880,
"text": "import android.content.Context;\nimport android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.view.inputmethod.InputMethodManager;\nimport android.widget.EditText;\npublic class MainActivity extends AppCompatActivity {\n EditText editText;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n editText = findViewById(R.id.editText);\n showSoftKeyboard(editText);\n }\n public void showSoftKeyboard(View view) {\n if(view.requestFocus()){\n InputMethodManager imm =(InputMethodManager)\n getSystemService(Context.INPUT_METHOD_SERVICE);\n imm.showSoftInput(view,InputMethodManager.SHOW_IMPLICIT);\n }\n }\n}"
},
{
"code": null,
"e": 2739,
"s": 2684,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 3446,
"s": 2739,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest\n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"app.com.sample\">\n\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\n android:name=\"android.intent.action.MAIN\" />\n <category\n android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 3793,
"s": 3446,
"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 −"
}
] |
Difference Between EnumMap and HashMap - GeeksforGeeks | 28 Dec, 2020
EnumMap and HashMap both are the classes that implement the Map interface. But there are some differences that exist between them. So we have tried to list out the differences between EnumMap and HashMap.
1. EnumMap: EnumMap is a specialized implementation of the Map interface for enumeration types. It extends AbstractMap and implements the Map interface in Java. Few important points of EnumMap are as follows:
EnumMap class is a member of the Java Collections Framework and it is not synchronized.
EnumMap is an ordered collection, and they are maintained in the natural order of their keys(the natural order of keys means the order on which enum constant are declared inside enum type).
EnumMap is much faster than HashMap.
All keys of each EnumMap instance must be keys of the same enum type.
EnumMap doesn’t allow inserting null key if we try to insert the null key, it will throw NullPointerException.
EnumMap is internally represented as arrays therefore it gives the better performance.
EnumMap Demo:
Java
// Java program to illustrate working// of EnumMap import java.util.*; class EnumMapExample { public enum Days { Sunday, Monday, Tuesday, Wendensday; } public static void main(String[] args) { // Creating an EnumMap of the Days enum EnumMap<Days, Integer> enumMap = new EnumMap<>(Days.class); // Insert using put() method enumMap.put(Days.Sunday, 1); enumMap.put(Days.Monday, 2); enumMap.put(Days.Tuesday, 3); enumMap.put(Days.Wendensday, 4); // Printing size of EnumMap System.out.println("Size of EnumMap: " + enumMap.size()); // Printing the EnumMap for (Map.Entry m : enumMap.entrySet()) { System.out.println(m.getKey() + " " + m.getValue()); } }}
Size of EnumMap: 4
Sunday 1
Monday 2
Tuesday 3
Wendensday 4
2. HashMap: HashMap is a class that implements the Map interface. It stores the data in the key and value pair, where the key should be unique. If you try to insert the duplicate key, it will replace the element of the corresponding key. It allows to store the null keys as well as null values, but there should be only one null key and multiple null values. Java HashMap is similar to HashTable, but it is synchronized. HashMap doesn’t maintain the order that means it doesn’t guarantee any specific order of the elements.
HashMap Demo:
Java
// Java program to illustrate// the working of HashMap import java.util.*; public class GFG { public static void main(String[] args) { // Create an empty hash map HashMap<Integer, String> map = new HashMap<>(); // Adding elements to the map map.put(10, "Geeks"); map.put(20, "Ram"); map.put(30, "Shyam"); // Printing size of the map System.out.println("Size of map is: " + map.size()); // Iterating the map for (Map.Entry m : map.entrySet()) { System.out.println(m.getKey() + " " + m.getValue()); } }}
Size of map is: 3
20 Ram
10 Geeks
30 Shyam
Java-Collections
Java-EnumMap
Java-HashMap
Technical Scripter 2020
Difference Between
Java
Technical Scripter
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Difference between Informed and Uninformed Search in AI
Difference between HashMap and HashSet
Difference between Internal and External fragmentation
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Reverse a string in Java
Arrays.sort() in Java with examples | [
{
"code": null,
"e": 24467,
"s": 24439,
"text": "\n28 Dec, 2020"
},
{
"code": null,
"e": 24672,
"s": 24467,
"text": "EnumMap and HashMap both are the classes that implement the Map interface. But there are some differences that exist between them. So we have tried to list out the differences between EnumMap and HashMap."
},
{
"code": null,
"e": 24882,
"s": 24672,
"text": "1. EnumMap: EnumMap is a specialized implementation of the Map interface for enumeration types. It extends AbstractMap and implements the Map interface in Java. Few important points of EnumMap are as follows: "
},
{
"code": null,
"e": 24970,
"s": 24882,
"text": "EnumMap class is a member of the Java Collections Framework and it is not synchronized."
},
{
"code": null,
"e": 25160,
"s": 24970,
"text": "EnumMap is an ordered collection, and they are maintained in the natural order of their keys(the natural order of keys means the order on which enum constant are declared inside enum type)."
},
{
"code": null,
"e": 25197,
"s": 25160,
"text": "EnumMap is much faster than HashMap."
},
{
"code": null,
"e": 25267,
"s": 25197,
"text": "All keys of each EnumMap instance must be keys of the same enum type."
},
{
"code": null,
"e": 25378,
"s": 25267,
"text": "EnumMap doesn’t allow inserting null key if we try to insert the null key, it will throw NullPointerException."
},
{
"code": null,
"e": 25465,
"s": 25378,
"text": "EnumMap is internally represented as arrays therefore it gives the better performance."
},
{
"code": null,
"e": 25479,
"s": 25465,
"text": "EnumMap Demo:"
},
{
"code": null,
"e": 25484,
"s": 25479,
"text": "Java"
},
{
"code": "// Java program to illustrate working// of EnumMap import java.util.*; class EnumMapExample { public enum Days { Sunday, Monday, Tuesday, Wendensday; } public static void main(String[] args) { // Creating an EnumMap of the Days enum EnumMap<Days, Integer> enumMap = new EnumMap<>(Days.class); // Insert using put() method enumMap.put(Days.Sunday, 1); enumMap.put(Days.Monday, 2); enumMap.put(Days.Tuesday, 3); enumMap.put(Days.Wendensday, 4); // Printing size of EnumMap System.out.println(\"Size of EnumMap: \" + enumMap.size()); // Printing the EnumMap for (Map.Entry m : enumMap.entrySet()) { System.out.println(m.getKey() + \" \" + m.getValue()); } }}",
"e": 26351,
"s": 25484,
"text": null
},
{
"code": null,
"e": 26411,
"s": 26351,
"text": "Size of EnumMap: 4\nSunday 1\nMonday 2\nTuesday 3\nWendensday 4"
},
{
"code": null,
"e": 26935,
"s": 26411,
"text": "2. HashMap: HashMap is a class that implements the Map interface. It stores the data in the key and value pair, where the key should be unique. If you try to insert the duplicate key, it will replace the element of the corresponding key. It allows to store the null keys as well as null values, but there should be only one null key and multiple null values. Java HashMap is similar to HashTable, but it is synchronized. HashMap doesn’t maintain the order that means it doesn’t guarantee any specific order of the elements."
},
{
"code": null,
"e": 26949,
"s": 26935,
"text": "HashMap Demo:"
},
{
"code": null,
"e": 26954,
"s": 26949,
"text": "Java"
},
{
"code": "// Java program to illustrate// the working of HashMap import java.util.*; public class GFG { public static void main(String[] args) { // Create an empty hash map HashMap<Integer, String> map = new HashMap<>(); // Adding elements to the map map.put(10, \"Geeks\"); map.put(20, \"Ram\"); map.put(30, \"Shyam\"); // Printing size of the map System.out.println(\"Size of map is: \" + map.size()); // Iterating the map for (Map.Entry m : map.entrySet()) { System.out.println(m.getKey() + \" \" + m.getValue()); } }}",
"e": 27593,
"s": 26954,
"text": null
},
{
"code": null,
"e": 27636,
"s": 27593,
"text": "Size of map is: 3\n20 Ram\n10 Geeks\n30 Shyam"
},
{
"code": null,
"e": 27653,
"s": 27636,
"text": "Java-Collections"
},
{
"code": null,
"e": 27666,
"s": 27653,
"text": "Java-EnumMap"
},
{
"code": null,
"e": 27679,
"s": 27666,
"text": "Java-HashMap"
},
{
"code": null,
"e": 27703,
"s": 27679,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 27722,
"s": 27703,
"text": "Difference Between"
},
{
"code": null,
"e": 27727,
"s": 27722,
"text": "Java"
},
{
"code": null,
"e": 27746,
"s": 27727,
"text": "Technical Scripter"
},
{
"code": null,
"e": 27751,
"s": 27746,
"text": "Java"
},
{
"code": null,
"e": 27768,
"s": 27751,
"text": "Java-Collections"
},
{
"code": null,
"e": 27866,
"s": 27768,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27875,
"s": 27866,
"text": "Comments"
},
{
"code": null,
"e": 27888,
"s": 27875,
"text": "Old Comments"
},
{
"code": null,
"e": 27949,
"s": 27888,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 28017,
"s": 27949,
"text": "Difference Between Method Overloading and Method Overriding in Java"
},
{
"code": null,
"e": 28073,
"s": 28017,
"text": "Difference between Informed and Uninformed Search in AI"
},
{
"code": null,
"e": 28112,
"s": 28073,
"text": "Difference between HashMap and HashSet"
},
{
"code": null,
"e": 28167,
"s": 28112,
"text": "Difference between Internal and External fragmentation"
},
{
"code": null,
"e": 28182,
"s": 28167,
"text": "Arrays in Java"
},
{
"code": null,
"e": 28226,
"s": 28182,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 28248,
"s": 28226,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 28273,
"s": 28248,
"text": "Reverse a string in Java"
}
] |
Check if the Object is a Data Frame in R Programming - is.data.frame() Function - GeeksforGeeks | 12 Jun, 2020
is.data.frame() function in R Language is used to return TRUE if the specified data type is a data frame else return FALSE. R data.frame is a powerful data type, especially when processing table (.csv). It can store the data as row and columns according to the table.
Syntax: is.data.frame(x)
Parameters:x: specified data.frame
Example 1:
# R program to illustrate# is.data.frame function # Specifying "Biochemical oxygen demand"# data setx <- BOD # Calling is.data.frame() functionis.data.frame(x)
Output:
[1] TRUE
Example 2:
# R program to illustrate# is.data.frame function # Calling is.data.frame() function # over different data typesis.data.frame(4)is.data.frame("34")is.data.frame("a")is.data.frame(2.7)
Output:
[1] FALSE
[1] FALSE
[1] FALSE
[1] FALSE
R DataFrame-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Filter data by multiple conditions in R using Dplyr
Loops in R (for, while, repeat)
Change Color of Bars in Barchart using ggplot2 in R
How to change Row Names of DataFrame in R ?
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to Split Column Into Multiple Columns in R DataFrame?
K-Means Clustering in R Programming
Replace Specific Characters in String in R
Remove rows with NA in one column of R DataFrame | [
{
"code": null,
"e": 26163,
"s": 26135,
"text": "\n12 Jun, 2020"
},
{
"code": null,
"e": 26431,
"s": 26163,
"text": "is.data.frame() function in R Language is used to return TRUE if the specified data type is a data frame else return FALSE. R data.frame is a powerful data type, especially when processing table (.csv). It can store the data as row and columns according to the table."
},
{
"code": null,
"e": 26456,
"s": 26431,
"text": "Syntax: is.data.frame(x)"
},
{
"code": null,
"e": 26491,
"s": 26456,
"text": "Parameters:x: specified data.frame"
},
{
"code": null,
"e": 26502,
"s": 26491,
"text": "Example 1:"
},
{
"code": "# R program to illustrate# is.data.frame function # Specifying \"Biochemical oxygen demand\"# data setx <- BOD # Calling is.data.frame() functionis.data.frame(x)",
"e": 26664,
"s": 26502,
"text": null
},
{
"code": null,
"e": 26672,
"s": 26664,
"text": "Output:"
},
{
"code": null,
"e": 26682,
"s": 26672,
"text": "[1] TRUE\n"
},
{
"code": null,
"e": 26693,
"s": 26682,
"text": "Example 2:"
},
{
"code": "# R program to illustrate# is.data.frame function # Calling is.data.frame() function # over different data typesis.data.frame(4)is.data.frame(\"34\")is.data.frame(\"a\")is.data.frame(2.7)",
"e": 26878,
"s": 26693,
"text": null
},
{
"code": null,
"e": 26886,
"s": 26878,
"text": "Output:"
},
{
"code": null,
"e": 26927,
"s": 26886,
"text": "[1] FALSE\n[1] FALSE\n[1] FALSE\n[1] FALSE\n"
},
{
"code": null,
"e": 26948,
"s": 26927,
"text": "R DataFrame-Function"
},
{
"code": null,
"e": 26959,
"s": 26948,
"text": "R Language"
},
{
"code": null,
"e": 27057,
"s": 26959,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27109,
"s": 27057,
"text": "Filter data by multiple conditions in R using Dplyr"
},
{
"code": null,
"e": 27141,
"s": 27109,
"text": "Loops in R (for, while, repeat)"
},
{
"code": null,
"e": 27193,
"s": 27141,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 27237,
"s": 27193,
"text": "How to change Row Names of DataFrame in R ?"
},
{
"code": null,
"e": 27272,
"s": 27237,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 27310,
"s": 27272,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 27368,
"s": 27310,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 27404,
"s": 27368,
"text": "K-Means Clustering in R Programming"
},
{
"code": null,
"e": 27447,
"s": 27404,
"text": "Replace Specific Characters in String in R"
}
] |
How to Do a Left Join in R? - GeeksforGeeks | 21 Dec, 2021
In this article, we will discuss how to do a left join in R programming language.
A left join is used to join the table by selecting all the records from the first dataframe and only matching records in the second dataframe.
This function is used to join the dataframes based on the x parameter that specifies left join.
Syntax:
merge(dataframe1,dataframe2, all.x=TRUE)
where,
dataframe1 is the first dataframe
dataframe2 is the second dataframe
Example: R program to perform two dataframes and perform left join on name column
R
# create first dataframedata1=data.frame('name'=c('siva','ramu','giri','geetha'), 'age'=c(21,23,21,20)) # displayprint(data1) # create second dataframedata2=data.frame('name'=c('siva','ramya','giri','geetha','pallavi'), 'marks'=c(21,23,21,20,30)) # displayprint(data2) print("=========================") # left join on name columnprint(merge(data1, data2, by='name', all.x=TRUE))
Output:
This performs left join on two dataframes which are available in dplyr() package.
Syntax:
left_join(df1, df2, by='column_name')
where
df1 and df2 are the two dataframes
column_name specifies on which column they are joined
Example: R program to find a let join
R
# load the librarylibrary("dplyr") # create first dataframedata1=data.frame('name'=c('siva','ramu','giri','geetha'), 'age'=c(21,23,21,20)) # displayprint(data1) # create second dataframedata2=data.frame('name'=c('siva','ramya','giri','geetha','pallavi'), 'marks'=c(21,23,21,20,30)) # displayprint(data2) print("=========================") # left join on name columnprint(left_join(data1, data2, by='name'))
Output:
sagartomar9927
Picked
R Dplyr
R-DataFrame
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
How to import an Excel File into R ?
Time Series Analysis in R
R - if statement
How to filter R dataframe by multiple conditions? | [
{
"code": null,
"e": 26487,
"s": 26459,
"text": "\n21 Dec, 2021"
},
{
"code": null,
"e": 26569,
"s": 26487,
"text": "In this article, we will discuss how to do a left join in R programming language."
},
{
"code": null,
"e": 26712,
"s": 26569,
"text": "A left join is used to join the table by selecting all the records from the first dataframe and only matching records in the second dataframe."
},
{
"code": null,
"e": 26808,
"s": 26712,
"text": "This function is used to join the dataframes based on the x parameter that specifies left join."
},
{
"code": null,
"e": 26816,
"s": 26808,
"text": "Syntax:"
},
{
"code": null,
"e": 26857,
"s": 26816,
"text": "merge(dataframe1,dataframe2, all.x=TRUE)"
},
{
"code": null,
"e": 26864,
"s": 26857,
"text": "where,"
},
{
"code": null,
"e": 26898,
"s": 26864,
"text": "dataframe1 is the first dataframe"
},
{
"code": null,
"e": 26933,
"s": 26898,
"text": "dataframe2 is the second dataframe"
},
{
"code": null,
"e": 27015,
"s": 26933,
"text": "Example: R program to perform two dataframes and perform left join on name column"
},
{
"code": null,
"e": 27017,
"s": 27015,
"text": "R"
},
{
"code": "# create first dataframedata1=data.frame('name'=c('siva','ramu','giri','geetha'), 'age'=c(21,23,21,20)) # displayprint(data1) # create second dataframedata2=data.frame('name'=c('siva','ramya','giri','geetha','pallavi'), 'marks'=c(21,23,21,20,30)) # displayprint(data2) print(\"=========================\") # left join on name columnprint(merge(data1, data2, by='name', all.x=TRUE))",
"e": 27429,
"s": 27017,
"text": null
},
{
"code": null,
"e": 27437,
"s": 27429,
"text": "Output:"
},
{
"code": null,
"e": 27519,
"s": 27437,
"text": "This performs left join on two dataframes which are available in dplyr() package."
},
{
"code": null,
"e": 27528,
"s": 27519,
"text": "Syntax: "
},
{
"code": null,
"e": 27566,
"s": 27528,
"text": "left_join(df1, df2, by='column_name')"
},
{
"code": null,
"e": 27573,
"s": 27566,
"text": "where "
},
{
"code": null,
"e": 27608,
"s": 27573,
"text": "df1 and df2 are the two dataframes"
},
{
"code": null,
"e": 27662,
"s": 27608,
"text": "column_name specifies on which column they are joined"
},
{
"code": null,
"e": 27700,
"s": 27662,
"text": "Example: R program to find a let join"
},
{
"code": null,
"e": 27702,
"s": 27700,
"text": "R"
},
{
"code": "# load the librarylibrary(\"dplyr\") # create first dataframedata1=data.frame('name'=c('siva','ramu','giri','geetha'), 'age'=c(21,23,21,20)) # displayprint(data1) # create second dataframedata2=data.frame('name'=c('siva','ramya','giri','geetha','pallavi'), 'marks'=c(21,23,21,20,30)) # displayprint(data2) print(\"=========================\") # left join on name columnprint(left_join(data1, data2, by='name'))",
"e": 28141,
"s": 27702,
"text": null
},
{
"code": null,
"e": 28149,
"s": 28141,
"text": "Output:"
},
{
"code": null,
"e": 28164,
"s": 28149,
"text": "sagartomar9927"
},
{
"code": null,
"e": 28171,
"s": 28164,
"text": "Picked"
},
{
"code": null,
"e": 28179,
"s": 28171,
"text": "R Dplyr"
},
{
"code": null,
"e": 28191,
"s": 28179,
"text": "R-DataFrame"
},
{
"code": null,
"e": 28202,
"s": 28191,
"text": "R Language"
},
{
"code": null,
"e": 28300,
"s": 28202,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28352,
"s": 28300,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 28387,
"s": 28352,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 28425,
"s": 28387,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 28483,
"s": 28425,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 28526,
"s": 28483,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 28575,
"s": 28526,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 28612,
"s": 28575,
"text": "How to import an Excel File into R ?"
},
{
"code": null,
"e": 28638,
"s": 28612,
"text": "Time Series Analysis in R"
},
{
"code": null,
"e": 28655,
"s": 28638,
"text": "R - if statement"
}
] |
Learn-One-Rule Algorithm - GeeksforGeeks | 01 Jul, 2021
Prerequisite: Rule-Based Classifier
Learn-One-Rule:
This method is used in the sequential learning algorithm for learning the rules. It returns a single rule that covers at least some examples (as shown in Fig 1). However, what makes it really powerful is its ability to create relations among the attributes given, hence covering a larger hypothesis space.
For example:
IF Mother(y, x) and Female(y), THEN Daughter(x, y).
Here, any person can be associated with the variables x and y
Fig 1: Learn-One-Rule Example
Learn-One-Rule Algorithm
The Learn-One-Rule algorithm follows a greedy searching paradigm where it searches for the rules with high accuracy but its coverage is very low. It classifies all the positive examples for a particular instance. It returns a single rule that covers some examples.
Learn-One-Rule(target_attribute, attributes, examples, k):
Pos = positive examples
Neg = negative examples
best-hypothesis = the most general hypothesis
candidate-hypothesis = {best-hypothesis}
while candidate-hypothesis:
//Generate the next more specific candidate-hypothesis
constraints_list = all constraints in the form "attribute=value"
new-candidate-hypothesis = all specializations of candidate-
hypothesis by adding all-constraints
remove all duplicates/inconsistent hypothesis from new-candidate-hypothesis.
//Update best-hypothesis
best_hypothesis = argmax(h∈CHs) Performance(h,examples,target_attribute)
//Update candidate-hypothesis
candidate-hypothesis = the k best from new-candidate-hypothesis
according to Performance.
prediction = most frequent value of target_attribute from examples that match best-hypothesis
IF best_hypothesis:
return prediction
It involves a PERFORMANCE method that calculates the performance of each candidate hypothesis. (i.e. how well the hypothesis matches the given set of examples in the training data.
Performance(NewRule,h):
h-examples = the set of rules that match h
return (h-examples)
It starts with the most general rule precondition, then greedily adds the variable that most improves performance measured over the training examples.
Learn-One-Rule Example
Let us understand the working of the algorithm using an example:
Step 1 - best_hypothesis = IF h THEN PlayBadminton(x) = Yes
Step 2 - candidate-hypothesis = {best-hypothesis}
Step 3 - constraints_list = {Weather(x)=Sunny, Temp(x)=Hot, Wind(x)=Weak, ......}
Step 4 - new-candidate-hypothesis = {IF Weather=Sunny THEN PlayBadminton=YES,
IF Weather=Overcast THEN PlayBadminton=YES, ...}
Step 5 - best-hypothesis = IF Weather=Sunny THEN PlayBadminton=YES
Step 6 - candidate-hypothesis = {IF Weather=Sunny THEN PlayBadminton=YES,
IF Weather=Sunny THEN PlayBadminton=YES...}
Step 7 - Go to Step 2 and keep doing it till the best-hypothesis is obtained.
You can refer to Fig 1. for a better understanding of how the best-hypothesis is obtained. [Step 5 & 6]
Sequential Learning Algorithm uses this algorithm, improving on it and increasing the coverage of the hypothesis space. It can be modified to accept an argument that specifies the target value of interest.
sagar0719kumar
Machine Learning
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Recurrent Neural Network
Support Vector Machine Algorithm
Intuition of Adam Optimizer
CNN | Introduction to Pooling Layer
Convolutional Neural Network (CNN) in Machine Learning
Markov Decision Process
k-nearest neighbor algorithm in Python
Singular Value Decomposition (SVD)
Q-Learning in Python
SARSA Reinforcement Learning | [
{
"code": null,
"e": 25589,
"s": 25561,
"text": "\n01 Jul, 2021"
},
{
"code": null,
"e": 25626,
"s": 25589,
"text": "Prerequisite: Rule-Based Classifier "
},
{
"code": null,
"e": 25643,
"s": 25626,
"text": "Learn-One-Rule: "
},
{
"code": null,
"e": 25951,
"s": 25643,
"text": "This method is used in the sequential learning algorithm for learning the rules. It returns a single rule that covers at least some examples (as shown in Fig 1). However, what makes it really powerful is its ability to create relations among the attributes given, hence covering a larger hypothesis space. "
},
{
"code": null,
"e": 26079,
"s": 25951,
"text": "For example:\nIF Mother(y, x) and Female(y), THEN Daughter(x, y). \nHere, any person can be associated with the variables x and y"
},
{
"code": null,
"e": 26109,
"s": 26079,
"text": "Fig 1: Learn-One-Rule Example"
},
{
"code": null,
"e": 26134,
"s": 26109,
"text": "Learn-One-Rule Algorithm"
},
{
"code": null,
"e": 26399,
"s": 26134,
"text": "The Learn-One-Rule algorithm follows a greedy searching paradigm where it searches for the rules with high accuracy but its coverage is very low. It classifies all the positive examples for a particular instance. It returns a single rule that covers some examples."
},
{
"code": null,
"e": 27489,
"s": 26399,
"text": "Learn-One-Rule(target_attribute, attributes, examples, k):\n\n Pos = positive examples\n Neg = negative examples\n best-hypothesis = the most general hypothesis\n candidate-hypothesis = {best-hypothesis}\n \n while candidate-hypothesis: \n //Generate the next more specific candidate-hypothesis\n\n constraints_list = all constraints in the form \"attribute=value\"\n new-candidate-hypothesis = all specializations of candidate-\n hypothesis by adding all-constraints\n remove all duplicates/inconsistent hypothesis from new-candidate-hypothesis. \n //Update best-hypothesis\n best_hypothesis = argmax(h∈CHs) Performance(h,examples,target_attribute)\n \n //Update candidate-hypothesis\n\n candidate-hypothesis = the k best from new-candidate-hypothesis \n according to Performance.\n prediction = most frequent value of target_attribute from examples that match best-hypothesis\n IF best_hypothesis:\n return prediction "
},
{
"code": null,
"e": 27670,
"s": 27489,
"text": "It involves a PERFORMANCE method that calculates the performance of each candidate hypothesis. (i.e. how well the hypothesis matches the given set of examples in the training data."
},
{
"code": null,
"e": 27767,
"s": 27670,
"text": "Performance(NewRule,h):\n h-examples = the set of rules that match h\n return (h-examples)"
},
{
"code": null,
"e": 27919,
"s": 27767,
"text": "It starts with the most general rule precondition, then greedily adds the variable that most improves performance measured over the training examples. "
},
{
"code": null,
"e": 27942,
"s": 27919,
"text": "Learn-One-Rule Example"
},
{
"code": null,
"e": 28008,
"s": 27942,
"text": "Let us understand the working of the algorithm using an example: "
},
{
"code": null,
"e": 28633,
"s": 28008,
"text": "Step 1 - best_hypothesis = IF h THEN PlayBadminton(x) = Yes\nStep 2 - candidate-hypothesis = {best-hypothesis}\nStep 3 - constraints_list = {Weather(x)=Sunny, Temp(x)=Hot, Wind(x)=Weak, ......}\nStep 4 - new-candidate-hypothesis = {IF Weather=Sunny THEN PlayBadminton=YES, \n IF Weather=Overcast THEN PlayBadminton=YES, ...}\nStep 5 - best-hypothesis = IF Weather=Sunny THEN PlayBadminton=YES \nStep 6 - candidate-hypothesis = {IF Weather=Sunny THEN PlayBadminton=YES, \n IF Weather=Sunny THEN PlayBadminton=YES...} \nStep 7 - Go to Step 2 and keep doing it till the best-hypothesis is obtained."
},
{
"code": null,
"e": 28737,
"s": 28633,
"text": "You can refer to Fig 1. for a better understanding of how the best-hypothesis is obtained. [Step 5 & 6]"
},
{
"code": null,
"e": 28944,
"s": 28737,
"text": "Sequential Learning Algorithm uses this algorithm, improving on it and increasing the coverage of the hypothesis space. It can be modified to accept an argument that specifies the target value of interest. "
},
{
"code": null,
"e": 28959,
"s": 28944,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 28976,
"s": 28959,
"text": "Machine Learning"
},
{
"code": null,
"e": 28993,
"s": 28976,
"text": "Machine Learning"
},
{
"code": null,
"e": 29091,
"s": 28993,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29132,
"s": 29091,
"text": "Introduction to Recurrent Neural Network"
},
{
"code": null,
"e": 29165,
"s": 29132,
"text": "Support Vector Machine Algorithm"
},
{
"code": null,
"e": 29193,
"s": 29165,
"text": "Intuition of Adam Optimizer"
},
{
"code": null,
"e": 29229,
"s": 29193,
"text": "CNN | Introduction to Pooling Layer"
},
{
"code": null,
"e": 29284,
"s": 29229,
"text": "Convolutional Neural Network (CNN) in Machine Learning"
},
{
"code": null,
"e": 29308,
"s": 29284,
"text": "Markov Decision Process"
},
{
"code": null,
"e": 29347,
"s": 29308,
"text": "k-nearest neighbor algorithm in Python"
},
{
"code": null,
"e": 29382,
"s": 29347,
"text": "Singular Value Decomposition (SVD)"
},
{
"code": null,
"e": 29403,
"s": 29382,
"text": "Q-Learning in Python"
}
] |
HTML | <p> align Attribute - GeeksforGeeks | 22 Feb, 2022
The HTML <p> align Attribute is used to specify the alignment of paragraph text content.
Syntax:
<p align="left | right | center | justify">
Attribute Values:
left: It sets the text left-align. It is a default value.
right: It sets the text right-align.
center: It sets the text center-align.
justify: It stretch the text of paragraph to set the width of all lines equal.
Note: The <p> align attribute is not supported by HTML 5.
Example:
<!DOCTYPE html><html> <head> <title> HTML p align Attribute </title></head> <body> <h1>GeeksforGeeks</h1> <h2>HTML p align Attribute</h2> <p align="left"> Left align content </p> <p align="center"> center align content </p> <p align="right"> Right align content </p></body> </html>
Output:
Supported Browsers: The browser supported by HTML <p> align attribute are listed below:
Google Chrome
Internet Explorer
Firefox
Safari
Opera
HTML is the foundation of webpages, is used for webpage development by structuring websites and web apps.You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples.
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
chhabradhanvi
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
REST API (Introduction)
How to Insert Form Data into Database using PHP ?
CSS to put icon inside an input element in a form
Types of CSS (Cascading Style Sheet)
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 ?
Difference between var, let and const keywords in JavaScript | [
{
"code": null,
"e": 26600,
"s": 26572,
"text": "\n22 Feb, 2022"
},
{
"code": null,
"e": 26689,
"s": 26600,
"text": "The HTML <p> align Attribute is used to specify the alignment of paragraph text content."
},
{
"code": null,
"e": 26697,
"s": 26689,
"text": "Syntax:"
},
{
"code": null,
"e": 26741,
"s": 26697,
"text": "<p align=\"left | right | center | justify\">"
},
{
"code": null,
"e": 26759,
"s": 26741,
"text": "Attribute Values:"
},
{
"code": null,
"e": 26817,
"s": 26759,
"text": "left: It sets the text left-align. It is a default value."
},
{
"code": null,
"e": 26854,
"s": 26817,
"text": "right: It sets the text right-align."
},
{
"code": null,
"e": 26893,
"s": 26854,
"text": "center: It sets the text center-align."
},
{
"code": null,
"e": 26972,
"s": 26893,
"text": "justify: It stretch the text of paragraph to set the width of all lines equal."
},
{
"code": null,
"e": 27030,
"s": 26972,
"text": "Note: The <p> align attribute is not supported by HTML 5."
},
{
"code": null,
"e": 27039,
"s": 27030,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> HTML p align Attribute </title></head> <body> <h1>GeeksforGeeks</h1> <h2>HTML p align Attribute</h2> <p align=\"left\"> Left align content </p> <p align=\"center\"> center align content </p> <p align=\"right\"> Right align content </p></body> </html>",
"e": 27374,
"s": 27039,
"text": null
},
{
"code": null,
"e": 27382,
"s": 27374,
"text": "Output:"
},
{
"code": null,
"e": 27470,
"s": 27382,
"text": "Supported Browsers: The browser supported by HTML <p> align attribute are listed below:"
},
{
"code": null,
"e": 27484,
"s": 27470,
"text": "Google Chrome"
},
{
"code": null,
"e": 27502,
"s": 27484,
"text": "Internet Explorer"
},
{
"code": null,
"e": 27510,
"s": 27502,
"text": "Firefox"
},
{
"code": null,
"e": 27517,
"s": 27510,
"text": "Safari"
},
{
"code": null,
"e": 27523,
"s": 27517,
"text": "Opera"
},
{
"code": null,
"e": 27717,
"s": 27523,
"text": "HTML is the foundation of webpages, is used for webpage development by structuring websites and web apps.You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples."
},
{
"code": null,
"e": 27854,
"s": 27717,
"text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course."
},
{
"code": null,
"e": 27868,
"s": 27854,
"text": "chhabradhanvi"
},
{
"code": null,
"e": 27884,
"s": 27868,
"text": "HTML-Attributes"
},
{
"code": null,
"e": 27889,
"s": 27884,
"text": "HTML"
},
{
"code": null,
"e": 27906,
"s": 27889,
"text": "Web Technologies"
},
{
"code": null,
"e": 27911,
"s": 27906,
"text": "HTML"
},
{
"code": null,
"e": 28009,
"s": 27911,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28057,
"s": 28009,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 28081,
"s": 28057,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 28131,
"s": 28081,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 28181,
"s": 28131,
"text": "CSS to put icon inside an input element in a form"
},
{
"code": null,
"e": 28218,
"s": 28181,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 28258,
"s": 28218,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28291,
"s": 28258,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28336,
"s": 28291,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28379,
"s": 28336,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Python - Test if List contains elements in Range - GeeksforGeeks | 01 Mar, 2020
A lot of times, while working with data, we have a problem in which we need to make sure that a container or a list is having elements in just one range. This has application in Data Domains. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using loopThis is brute force method in which this task can be performed. In this, we just check using if condition if element falls in range, and break if we find even one occurrence out of range.
# Python3 code to demonstrate # Test if List contains elements in Range# using loop # Initializing loop test_list = [4, 5, 6, 7, 3, 9] # printing original list print("The original list is : " + str(test_list)) # Initialization of range i, j = 3, 10 # Test if List contains elements in Range# using loopres = Truefor ele in test_list: if ele < i or ele >= j : res = False break # printing result print ("Does list contain all elements in range : " + str(res))
The original list is : [4, 5, 6, 7, 3, 9]
Does list contain all elements in range : True
Method #2 : Using all()This is alternative and shorter way to perform this task. In this we use check operation as a parameter to all() and returns True when all elements in range.
# Python3 code to demonstrate # Test if List contains elements in Range# using all() # Initializing loop test_list = [4, 5, 6, 7, 3, 9] # printing original list print("The original list is : " + str(test_list)) # Initialization of range i, j = 3, 10 # Test if List contains elements in Range# using all()res = all(ele >= i and ele < j for ele in test_list) # printing result print ("Does list contain all elements in range : " + str(res))
The original list is : [4, 5, 6, 7, 3, 9]
Does list contain all elements in range : True
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python? | [
{
"code": null,
"e": 25562,
"s": 25534,
"text": "\n01 Mar, 2020"
},
{
"code": null,
"e": 25818,
"s": 25562,
"text": "A lot of times, while working with data, we have a problem in which we need to make sure that a container or a list is having elements in just one range. This has application in Data Domains. Let’s discuss certain ways in which this task can be performed."
},
{
"code": null,
"e": 26028,
"s": 25818,
"text": "Method #1 : Using loopThis is brute force method in which this task can be performed. In this, we just check using if condition if element falls in range, and break if we find even one occurrence out of range."
},
{
"code": "# Python3 code to demonstrate # Test if List contains elements in Range# using loop # Initializing loop test_list = [4, 5, 6, 7, 3, 9] # printing original list print(\"The original list is : \" + str(test_list)) # Initialization of range i, j = 3, 10 # Test if List contains elements in Range# using loopres = Truefor ele in test_list: if ele < i or ele >= j : res = False break # printing result print (\"Does list contain all elements in range : \" + str(res))",
"e": 26510,
"s": 26028,
"text": null
},
{
"code": null,
"e": 26600,
"s": 26510,
"text": "The original list is : [4, 5, 6, 7, 3, 9]\nDoes list contain all elements in range : True\n"
},
{
"code": null,
"e": 26783,
"s": 26602,
"text": "Method #2 : Using all()This is alternative and shorter way to perform this task. In this we use check operation as a parameter to all() and returns True when all elements in range."
},
{
"code": "# Python3 code to demonstrate # Test if List contains elements in Range# using all() # Initializing loop test_list = [4, 5, 6, 7, 3, 9] # printing original list print(\"The original list is : \" + str(test_list)) # Initialization of range i, j = 3, 10 # Test if List contains elements in Range# using all()res = all(ele >= i and ele < j for ele in test_list) # printing result print (\"Does list contain all elements in range : \" + str(res))",
"e": 27228,
"s": 26783,
"text": null
},
{
"code": null,
"e": 27318,
"s": 27228,
"text": "The original list is : [4, 5, 6, 7, 3, 9]\nDoes list contain all elements in range : True\n"
},
{
"code": null,
"e": 27339,
"s": 27318,
"text": "Python list-programs"
},
{
"code": null,
"e": 27346,
"s": 27339,
"text": "Python"
},
{
"code": null,
"e": 27362,
"s": 27346,
"text": "Python Programs"
},
{
"code": null,
"e": 27460,
"s": 27362,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27492,
"s": 27460,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27534,
"s": 27492,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27576,
"s": 27534,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27632,
"s": 27576,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27659,
"s": 27632,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27681,
"s": 27659,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27720,
"s": 27681,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 27766,
"s": 27720,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 27804,
"s": 27766,
"text": "Python | Convert a list to dictionary"
}
] |
Scala | yield Keyword - GeeksforGeeks | 07 Jun, 2019
yield keyword will returns a result after completing of loop iterations. The for loop used buffer internally to store iterated result and when finishing all iterations it yields the ultimate result from that buffer. It doesn’t work like imperative loop. The type of the collection that is returned is the same type that we tend to were iterating over, Therefore a Map yields a Map, a List yields a List, and so on.
Syntax:
var result = for{ var x <- List}
yield x
Note: The curly braces have been used to keep the variables and conditions and result is a variable wherever all the values of x are kept within the form of collection.
Example:
// Scala program to illustrate yield keyword // Creating objectobject GFG { // Main method def main(args: Array[String]) { // Using yield with for var print = for( i <- 1 to 10) yield i for(j<-print) { // Printing result println(j) } } }
Output:
1
2
3
4
5
6
7
8
9
10
In above example, the for loop used with a yield statement actually creates a sequence of list.
Example:
// Scala program to illustrate yield keyword // Creating objectobject GFG { // Main method def main(args: Array[String]) { val a = Array( 8, 3, 1, 6, 4, 5) // Using yield with for var print=for (e <- a if e > 4) yield e for(i<-print) { // Printing result println(i) } } }
Output:
8
6
5
In above example, the for loop used with a yield statement actually creates a array. Because we said yield e, it’s a Array[n1, n2, n3, ....]. e <- a is our generator and if (e > 4) could be a guard that filters out number those don't seem to be greater than 4.
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Inheritance in Scala
Scala | Traits
Scala ListBuffer
Scala | Case Class and Case Object
Hello World in Scala
Scala | Functions - Basics
Scala | Decision Making (if, if-else, Nested if-else, if-else if)
Scala List map() method with example
Comments In Scala
Abstract Classes in Scala | [
{
"code": null,
"e": 25301,
"s": 25273,
"text": "\n07 Jun, 2019"
},
{
"code": null,
"e": 25716,
"s": 25301,
"text": "yield keyword will returns a result after completing of loop iterations. The for loop used buffer internally to store iterated result and when finishing all iterations it yields the ultimate result from that buffer. It doesn’t work like imperative loop. The type of the collection that is returned is the same type that we tend to were iterating over, Therefore a Map yields a Map, a List yields a List, and so on."
},
{
"code": null,
"e": 25724,
"s": 25716,
"text": "Syntax:"
},
{
"code": null,
"e": 25765,
"s": 25724,
"text": "var result = for{ var x <- List}\nyield x"
},
{
"code": null,
"e": 25934,
"s": 25765,
"text": "Note: The curly braces have been used to keep the variables and conditions and result is a variable wherever all the values of x are kept within the form of collection."
},
{
"code": null,
"e": 25943,
"s": 25934,
"text": "Example:"
},
{
"code": "// Scala program to illustrate yield keyword // Creating objectobject GFG { // Main method def main(args: Array[String]) { // Using yield with for var print = for( i <- 1 to 10) yield i for(j<-print) { // Printing result println(j) } } } ",
"e": 26259,
"s": 25943,
"text": null
},
{
"code": null,
"e": 26267,
"s": 26259,
"text": "Output:"
},
{
"code": null,
"e": 26288,
"s": 26267,
"text": "1\n2\n3\n4\n5\n6\n7\n8\n9\n10"
},
{
"code": null,
"e": 26384,
"s": 26288,
"text": "In above example, the for loop used with a yield statement actually creates a sequence of list."
},
{
"code": null,
"e": 26393,
"s": 26384,
"text": "Example:"
},
{
"code": "// Scala program to illustrate yield keyword // Creating objectobject GFG { // Main method def main(args: Array[String]) { val a = Array( 8, 3, 1, 6, 4, 5) // Using yield with for var print=for (e <- a if e > 4) yield e for(i<-print) { // Printing result println(i) } } } ",
"e": 26759,
"s": 26393,
"text": null
},
{
"code": null,
"e": 26767,
"s": 26759,
"text": "Output:"
},
{
"code": null,
"e": 26773,
"s": 26767,
"text": "8\n6\n5"
},
{
"code": null,
"e": 27034,
"s": 26773,
"text": "In above example, the for loop used with a yield statement actually creates a array. Because we said yield e, it’s a Array[n1, n2, n3, ....]. e <- a is our generator and if (e > 4) could be a guard that filters out number those don't seem to be greater than 4."
},
{
"code": null,
"e": 27040,
"s": 27034,
"text": "Scala"
},
{
"code": null,
"e": 27138,
"s": 27040,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27159,
"s": 27138,
"text": "Inheritance in Scala"
},
{
"code": null,
"e": 27174,
"s": 27159,
"text": "Scala | Traits"
},
{
"code": null,
"e": 27191,
"s": 27174,
"text": "Scala ListBuffer"
},
{
"code": null,
"e": 27226,
"s": 27191,
"text": "Scala | Case Class and Case Object"
},
{
"code": null,
"e": 27247,
"s": 27226,
"text": "Hello World in Scala"
},
{
"code": null,
"e": 27274,
"s": 27247,
"text": "Scala | Functions - Basics"
},
{
"code": null,
"e": 27340,
"s": 27274,
"text": "Scala | Decision Making (if, if-else, Nested if-else, if-else if)"
},
{
"code": null,
"e": 27377,
"s": 27340,
"text": "Scala List map() method with example"
},
{
"code": null,
"e": 27395,
"s": 27377,
"text": "Comments In Scala"
}
] |
How to Trim White Spaces from input in ReactJS? - GeeksforGeeks | 31 Dec, 2020
Trim white space means removing white spaces from the text input from both start and end. The following example shows how to trim white space from text input in ReactJS.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Step 3: After creating the ReactJS application, Install the validator module using the following command:
npm install validator
Project Structure: It will look like the following.
Project Structure
App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
Javascript
import React, { useState } from "react";import validator from 'validator' const App = () => { const [value, setValue] = useState('') const validate = (inputText) => { setValue("#"+validator.trim(inputText)+"#") } return ( <div style={{ marginLeft: '200px', }}> <pre> <h2>Trimming White Space in ReactJS</h2> <span>Enter Text: </span><input type="text" onChange={(e) => validate(e.target.value)}></input> <br /> <span style={{ fontWeight: 'bold', color: 'red', }}>{value}</span> </pre> </div> );} export default App
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output:
The following will be the output if the user enters input without any space. You can see that the text remains as it is because there is no white space present in the input text.
The following will be the output if the user enters input with white space from both the end. You can see that the final output text is trimmed from both the side by removing white space.
NOTE: In the above example, # is appended from both ends so that the user can see the result that white space is removed.
react-js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript | [
{
"code": null,
"e": 26545,
"s": 26517,
"text": "\n31 Dec, 2020"
},
{
"code": null,
"e": 26715,
"s": 26545,
"text": "Trim white space means removing white spaces from the text input from both start and end. The following example shows how to trim white space from text input in ReactJS."
},
{
"code": null,
"e": 26765,
"s": 26715,
"text": "Creating React Application And Installing Module:"
},
{
"code": null,
"e": 26829,
"s": 26765,
"text": "Step 1: Create a React application using the following command:"
},
{
"code": null,
"e": 26861,
"s": 26829,
"text": "npx create-react-app foldername"
},
{
"code": null,
"e": 26961,
"s": 26861,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:"
},
{
"code": null,
"e": 26975,
"s": 26961,
"text": "cd foldername"
},
{
"code": null,
"e": 27081,
"s": 26975,
"text": "Step 3: After creating the ReactJS application, Install the validator module using the following command:"
},
{
"code": null,
"e": 27103,
"s": 27081,
"text": "npm install validator"
},
{
"code": null,
"e": 27155,
"s": 27103,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 27173,
"s": 27155,
"text": "Project Structure"
},
{
"code": null,
"e": 27302,
"s": 27173,
"text": "App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code."
},
{
"code": null,
"e": 27313,
"s": 27302,
"text": "Javascript"
},
{
"code": "import React, { useState } from \"react\";import validator from 'validator' const App = () => { const [value, setValue] = useState('') const validate = (inputText) => { setValue(\"#\"+validator.trim(inputText)+\"#\") } return ( <div style={{ marginLeft: '200px', }}> <pre> <h2>Trimming White Space in ReactJS</h2> <span>Enter Text: </span><input type=\"text\" onChange={(e) => validate(e.target.value)}></input> <br /> <span style={{ fontWeight: 'bold', color: 'red', }}>{value}</span> </pre> </div> );} export default App",
"e": 27926,
"s": 27313,
"text": null
},
{
"code": null,
"e": 28039,
"s": 27926,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 28049,
"s": 28039,
"text": "npm start"
},
{
"code": null,
"e": 28057,
"s": 28049,
"text": "Output:"
},
{
"code": null,
"e": 28236,
"s": 28057,
"text": "The following will be the output if the user enters input without any space. You can see that the text remains as it is because there is no white space present in the input text."
},
{
"code": null,
"e": 28426,
"s": 28238,
"text": "The following will be the output if the user enters input with white space from both the end. You can see that the final output text is trimmed from both the side by removing white space."
},
{
"code": null,
"e": 28548,
"s": 28426,
"text": "NOTE: In the above example, # is appended from both ends so that the user can see the result that white space is removed."
},
{
"code": null,
"e": 28557,
"s": 28548,
"text": "react-js"
},
{
"code": null,
"e": 28568,
"s": 28557,
"text": "JavaScript"
},
{
"code": null,
"e": 28585,
"s": 28568,
"text": "Web Technologies"
},
{
"code": null,
"e": 28683,
"s": 28585,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28723,
"s": 28683,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28784,
"s": 28723,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 28825,
"s": 28784,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 28847,
"s": 28825,
"text": "JavaScript | Promises"
},
{
"code": null,
"e": 28901,
"s": 28847,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 28941,
"s": 28901,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28974,
"s": 28941,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 29017,
"s": 28974,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 29079,
"s": 29017,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
] |
java.time.Instant Class in Java - GeeksforGeeks | 09 Mar, 2021
In Java language, the Instant Class is used to represent the specific time instant on the current timeline. The Instant Class extends the Object Class and implements the Comparable interface.
Declaration of the Instant Class
public final class Instant extends Object
implements Temporal, TemporalAdjuster, Comparable<Instant>, Serializable
Fields of the class:
Methods of the class:
Description
Example:
The following example shows how the different methods associated with the classwork
Java
import java.time.*;import java.time.temporal.*;public class GFG { public static void main(String[] args) { // Parsing a string sequence to Instant Instant inst1 = Instant.parse("2021-02-09T11:19:42.12Z"); System.out.println("Parsed instant is " + inst1); // Using isSupported() method to check whether the // specified field is supported or not System.out.println(inst1.isSupported(ChronoUnit.DAYS)); System.out.println(inst1.isSupported(ChronoUnit.YEARS)); // Using Instant.now() to get current instant Instant cur = Instant.now(); System.out.println("Current Instant is " + cur); // Using minus() method to find instant value after // subtraction Instant diff = inst1.minus(Duration.ofDays(70)); System.out.println("Instant after subtraction : "+ diff); // Using plus() method to find instant value after // addition Instant sum = inst1.plus(Duration.ofDays(10)); System.out.println("Instant after addition : "+ sum); }}
Parsed instant is 2021-02-09T11:19:42.120Z
true
false
Current Instant is 2021-03-03T16:27:54.378693Z
Instant after subtraction : 2020-12-01T11:19:42.120Z
Instant after addition : 2021-02-19T11:19:42.120Z
Java-Instant
Java-time package
Picked
Technical Scripter 2020
Java
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Generics in Java
Introduction to Java
Comparator Interface in Java with Examples
Internal Working of HashMap in Java
Strings in Java | [
{
"code": null,
"e": 25225,
"s": 25197,
"text": "\n09 Mar, 2021"
},
{
"code": null,
"e": 25417,
"s": 25225,
"text": "In Java language, the Instant Class is used to represent the specific time instant on the current timeline. The Instant Class extends the Object Class and implements the Comparable interface."
},
{
"code": null,
"e": 25450,
"s": 25417,
"text": "Declaration of the Instant Class"
},
{
"code": null,
"e": 25571,
"s": 25450,
"text": "public final class Instant extends Object \nimplements Temporal, TemporalAdjuster, Comparable<Instant>, Serializable "
},
{
"code": null,
"e": 25592,
"s": 25571,
"text": "Fields of the class:"
},
{
"code": null,
"e": 25614,
"s": 25592,
"text": "Methods of the class:"
},
{
"code": null,
"e": 25626,
"s": 25614,
"text": "Description"
},
{
"code": null,
"e": 25635,
"s": 25626,
"text": "Example:"
},
{
"code": null,
"e": 25719,
"s": 25635,
"text": "The following example shows how the different methods associated with the classwork"
},
{
"code": null,
"e": 25724,
"s": 25719,
"text": "Java"
},
{
"code": "import java.time.*;import java.time.temporal.*;public class GFG { public static void main(String[] args) { // Parsing a string sequence to Instant Instant inst1 = Instant.parse(\"2021-02-09T11:19:42.12Z\"); System.out.println(\"Parsed instant is \" + inst1); // Using isSupported() method to check whether the // specified field is supported or not System.out.println(inst1.isSupported(ChronoUnit.DAYS)); System.out.println(inst1.isSupported(ChronoUnit.YEARS)); // Using Instant.now() to get current instant Instant cur = Instant.now(); System.out.println(\"Current Instant is \" + cur); // Using minus() method to find instant value after // subtraction Instant diff = inst1.minus(Duration.ofDays(70)); System.out.println(\"Instant after subtraction : \"+ diff); // Using plus() method to find instant value after // addition Instant sum = inst1.plus(Duration.ofDays(10)); System.out.println(\"Instant after addition : \"+ sum); }}",
"e": 26814,
"s": 25724,
"text": null
},
{
"code": null,
"e": 27018,
"s": 26814,
"text": "Parsed instant is 2021-02-09T11:19:42.120Z\ntrue\nfalse\nCurrent Instant is 2021-03-03T16:27:54.378693Z\nInstant after subtraction : 2020-12-01T11:19:42.120Z\nInstant after addition : 2021-02-19T11:19:42.120Z"
},
{
"code": null,
"e": 27031,
"s": 27018,
"text": "Java-Instant"
},
{
"code": null,
"e": 27049,
"s": 27031,
"text": "Java-time package"
},
{
"code": null,
"e": 27056,
"s": 27049,
"text": "Picked"
},
{
"code": null,
"e": 27080,
"s": 27056,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 27085,
"s": 27080,
"text": "Java"
},
{
"code": null,
"e": 27104,
"s": 27085,
"text": "Technical Scripter"
},
{
"code": null,
"e": 27109,
"s": 27104,
"text": "Java"
},
{
"code": null,
"e": 27207,
"s": 27109,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27222,
"s": 27207,
"text": "Stream In Java"
},
{
"code": null,
"e": 27243,
"s": 27222,
"text": "Constructors in Java"
},
{
"code": null,
"e": 27262,
"s": 27243,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 27292,
"s": 27262,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 27338,
"s": 27292,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 27355,
"s": 27338,
"text": "Generics in Java"
},
{
"code": null,
"e": 27376,
"s": 27355,
"text": "Introduction to Java"
},
{
"code": null,
"e": 27419,
"s": 27376,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 27455,
"s": 27419,
"text": "Internal Working of HashMap in Java"
}
] |
How to Install OpenCV for Python in Linux? - GeeksforGeeks | 06 Oct, 2021
Prerequisite: Python Language Introduction OpenCV is the huge open-source library for computer vision, machine learning, and image processing and now it plays a major role in real-time operation which is very important in today’s systems. By using it, one can process images and videos to identify objects, faces, or even the handwriting of a human. When it integrated with various libraries, such as Numpuy, python is capable of processing the OpenCV array structure for analysis. To Identify image patterns and its various features we use vector space and perform mathematical operations on these features.
To install OpenCV, one must have Python and PIP, preinstalled on their system. To check if your system already contains Python, go through the following instructions:
Open the terminal using Ctrl+Alt+T
Now run the following command:For Python2
python --version
For Python3.x
python3.x --version
If Python is already installed, it will generate a message with the Python version available.
If Python is not present, go through How to install Python on Linux? and follow the instructions provided. PIP is a package management system used to install and manage software packages/libraries written in Python. These files are stored in a large “on-line repository” termed as Python Package Index (PyPI).To check if PIP is already installed on your system, just go to the terminal and execute the following command:
pip3 --version
If PIP is not present, go through How to install PIP on Linux? and follow the instructions provided.
OpenCV can be directly downloaded and installed with the use of pip (package manager). To install OpenCV, just go to the terminal and type the following command:
pip3 install opencv-python
Beginning with the installation:
Type the command in the Terminal and proceed:
Collecting Information and downloading data:
Installing Packages:
Finished Installation:
To check if OpenCV is correctly installed, just run the following commands to perform a version check:
python3
>>>import cv2
>>>print(cv2.__version__)
how-to-install
OpenCV
python-basics
How To
Installation Guide
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install FFmpeg on Windows?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Set Git Username and Password in GitBash?
How to Install Jupyter Notebook on MacOS?
How to Create and Setup Spring Boot Project in Eclipse IDE?
Installation of Node.js on Linux
How to Install FFmpeg on Windows?
How to Install Pygame on Windows ?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Install Jupyter Notebook on MacOS? | [
{
"code": null,
"e": 26197,
"s": 26169,
"text": "\n06 Oct, 2021"
},
{
"code": null,
"e": 26806,
"s": 26197,
"text": "Prerequisite: Python Language Introduction OpenCV is the huge open-source library for computer vision, machine learning, and image processing and now it plays a major role in real-time operation which is very important in today’s systems. By using it, one can process images and videos to identify objects, faces, or even the handwriting of a human. When it integrated with various libraries, such as Numpuy, python is capable of processing the OpenCV array structure for analysis. To Identify image patterns and its various features we use vector space and perform mathematical operations on these features."
},
{
"code": null,
"e": 26973,
"s": 26806,
"text": "To install OpenCV, one must have Python and PIP, preinstalled on their system. To check if your system already contains Python, go through the following instructions:"
},
{
"code": null,
"e": 27008,
"s": 26973,
"text": "Open the terminal using Ctrl+Alt+T"
},
{
"code": null,
"e": 27050,
"s": 27008,
"text": "Now run the following command:For Python2"
},
{
"code": null,
"e": 27068,
"s": 27050,
"text": "python --version\n"
},
{
"code": null,
"e": 27082,
"s": 27068,
"text": "For Python3.x"
},
{
"code": null,
"e": 27103,
"s": 27082,
"text": "python3.x --version\n"
},
{
"code": null,
"e": 27197,
"s": 27103,
"text": "If Python is already installed, it will generate a message with the Python version available."
},
{
"code": null,
"e": 27618,
"s": 27197,
"text": "If Python is not present, go through How to install Python on Linux? and follow the instructions provided. PIP is a package management system used to install and manage software packages/libraries written in Python. These files are stored in a large “on-line repository” termed as Python Package Index (PyPI).To check if PIP is already installed on your system, just go to the terminal and execute the following command:"
},
{
"code": null,
"e": 27633,
"s": 27618,
"text": "pip3 --version"
},
{
"code": null,
"e": 27734,
"s": 27633,
"text": "If PIP is not present, go through How to install PIP on Linux? and follow the instructions provided."
},
{
"code": null,
"e": 27896,
"s": 27734,
"text": "OpenCV can be directly downloaded and installed with the use of pip (package manager). To install OpenCV, just go to the terminal and type the following command:"
},
{
"code": null,
"e": 27923,
"s": 27896,
"text": "pip3 install opencv-python"
},
{
"code": null,
"e": 27956,
"s": 27923,
"text": "Beginning with the installation:"
},
{
"code": null,
"e": 28002,
"s": 27956,
"text": "Type the command in the Terminal and proceed:"
},
{
"code": null,
"e": 28047,
"s": 28002,
"text": "Collecting Information and downloading data:"
},
{
"code": null,
"e": 28068,
"s": 28047,
"text": "Installing Packages:"
},
{
"code": null,
"e": 28091,
"s": 28068,
"text": "Finished Installation:"
},
{
"code": null,
"e": 28194,
"s": 28091,
"text": "To check if OpenCV is correctly installed, just run the following commands to perform a version check:"
},
{
"code": null,
"e": 28243,
"s": 28194,
"text": "python3\n>>>import cv2\n>>>print(cv2.__version__)\n"
},
{
"code": null,
"e": 28258,
"s": 28243,
"text": "how-to-install"
},
{
"code": null,
"e": 28265,
"s": 28258,
"text": "OpenCV"
},
{
"code": null,
"e": 28279,
"s": 28265,
"text": "python-basics"
},
{
"code": null,
"e": 28286,
"s": 28279,
"text": "How To"
},
{
"code": null,
"e": 28305,
"s": 28286,
"text": "Installation Guide"
},
{
"code": null,
"e": 28312,
"s": 28305,
"text": "Python"
},
{
"code": null,
"e": 28410,
"s": 28312,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28444,
"s": 28410,
"text": "How to Install FFmpeg on Windows?"
},
{
"code": null,
"e": 28502,
"s": 28444,
"text": "How to Add External JAR File to an IntelliJ IDEA Project?"
},
{
"code": null,
"e": 28551,
"s": 28502,
"text": "How to Set Git Username and Password in GitBash?"
},
{
"code": null,
"e": 28593,
"s": 28551,
"text": "How to Install Jupyter Notebook on MacOS?"
},
{
"code": null,
"e": 28653,
"s": 28593,
"text": "How to Create and Setup Spring Boot Project in Eclipse IDE?"
},
{
"code": null,
"e": 28686,
"s": 28653,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28720,
"s": 28686,
"text": "How to Install FFmpeg on Windows?"
},
{
"code": null,
"e": 28755,
"s": 28720,
"text": "How to Install Pygame on Windows ?"
},
{
"code": null,
"e": 28813,
"s": 28755,
"text": "How to Add External JAR File to an IntelliJ IDEA Project?"
}
] |
Application Binary Interface(ABI) in Ethereum Virtual Machine - GeeksforGeeks | 11 May, 2022
Smart contracts are pieces of code that are stored on the blockchain and are executed by the Ethereum Virtual Machine (EVM). The EVM also provides a comprehensive instruction set called opcodes which execute certain instructions. Opcodes are low-level codes similar to the processor’s instruction set. The common Ethereum opcodes can be accessed from the Ethereum Yellow Paper. The entire program is compiled and stored in the form of bytes or binary representation in the Ethereum blockchain as a form of address. For Ethereum and the EVM, a contract is just a single program that is run on this sequence of bytes. Only the higher-level language like Solidity, Viper, or Bamboo defines how you get from the entry point of the program to the entry point of a particular function. When an external application or another smart contract wants to interact with the blockchain, it needs to have some knowledge of a smart contract’s interface such as a way to identify a method and its parameters. This is facilitated by the Ethereum Application Binary Interface (ABI).
It is similar to the Application Program Interface (API), which is essentially a representation of the code’s interface in Human readable form or a high-level language. In the EVM the compiled code being stored as binary data and the human-readable interfaces disappear and smart contract interactions have to be translated into a binary format that can be interpreted by the EVM. ABI defines the methods and structures that you can simply use to interact with that binary contract (just like the API does), only on a lower level. The ABI indicates to the caller the needed information (functions signatures and variables declarations) to encode such that it is understood by the Virtual Machine call to the byte code(contract). This process is called ABI encoding.
ABI is the interface between two program modules, one of which is mostly at the machine code level. The interface is the default method for encoding/decoding data into or out of the machine code. In Ethereum it is basically how you encode a language to have contract calls to the EVM or how to read the data out of transactions. ABI encoding is in most cases automated by tools that are part of the compiler like REMIX or wallets which can interact with the blockchain. ABI encoder requires a description of the contract’s interface like function name and parameters which is commonly provided as a JSON.
An Ethereum smart contract is byte code deployed on the Ethereum blockchain. There could be several functions in a contract. An ABI is necessary so that you can point to the specific function call that you want to evoke and also get a guarantee that the function will return data in the format you are expecting. The first four bytes of a transaction payload sent to a contract is usually used to distinguish which function in the contract to call.
1) Contract GeeksForGeeks has certain functions. Let’s call function baz(...).
contract GeeksForGeeks {
function empty() {}
function baz(uint32 x, bool y) returns (bool r)
{ if(x>0)
r = true;
else
r =false;
}
function Ritu(bytes _name, bool _x) {}
}
Function call baz with the parameters 69 and true, we would pass 68 bytes in total.
Method ID.
This is derived as the first 4 bytes of the Keccak-256 hash of the ASCII form of the signature baz(uint32,bool)
0xcdcd77c0
First parameter
uint32 value 69 padded to 32 bytes
0x0000000000000000000000000000000000000000000000000000000000000045:
Second parameter
boolean true, padded to 32 bytes
0x0000000000000000000000000000000000000000000000000000000000000001:
2) balanceOf is a function used to obtain the balance. The function signature is as follows:
balanceOf(address)
Calculating the keccak256 hash of this signature string produces:
0x70a08231b98ef4ca268c9cc3f6b4590e4bfec28280db06bb5d45e689f2a360be
Taking the top four bytes gives us the following function selector or Method ID as also obtained above:
0x70a08231
The ABI encoding is not part of the core protocol of Ethereum because the payload data in transactions are not required to have any structure, it is just a sequence of bytes. Similarly, the Ethereum Virtual Machine also just processes the data as a sequence of bytes. For example, a transaction contains the sequence of bytes. How these bytes are interpreted into structured data is up to the program and is up to the programming language used. In order to make it possible for two programs written in different programming languages to call each other, the compilers of such languages should implement the serialization and deserialization of data in the same way, i.e. although they should implement the ABI they are not compelled to.
Example: In the below example, a contract is created to store a number and returned the stored number. Below the example, there are two outputs: One is the ABI Output and the second one is the output of the execution of the code i.e. the simple Deploy and Run Output of the Solidity code.
Solidity
// Solidity program to// demonstrate abi encodingpragma solidity >=0.4.22 <0.7.0; // Creating a contractcontract Storage { // Declaring a state variable uint256 number; // Defining a function // to store the number function store(uint256 num) public { number = num; } // Defining a function to // send back or return the // stored number function retrieve() public view returns (uint256) { return number; }}
ABI Output:
[
{
"inputs": [],
"name": "retrieve",
"outputs": [
{
"internalType": "uint256",
"name": "",
"type": "uint256"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [
{
"internalType": "uint256",
"name": "num",
"type": "uint256"
}
],
"name": "store",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
}
]
Output:
Blockchain
Solidity
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Solidity - Arrays
Solidity - Mappings
Storage vs Memory in Solidity
Ethereum Blockchain - Getting Free Test Ethers For Rinkeby Test Network
Solidity - Enums and Structs
Solidity - Arrays
Solidity - Mappings
Storage vs Memory in Solidity
Solidity - Enums and Structs
Solidity - Constructors | [
{
"code": null,
"e": 26171,
"s": 26143,
"text": "\n11 May, 2022"
},
{
"code": null,
"e": 27239,
"s": 26171,
"text": "Smart contracts are pieces of code that are stored on the blockchain and are executed by the Ethereum Virtual Machine (EVM). The EVM also provides a comprehensive instruction set called opcodes which execute certain instructions. Opcodes are low-level codes similar to the processor’s instruction set. The common Ethereum opcodes can be accessed from the Ethereum Yellow Paper. The entire program is compiled and stored in the form of bytes or binary representation in the Ethereum blockchain as a form of address. For Ethereum and the EVM, a contract is just a single program that is run on this sequence of bytes. Only the higher-level language like Solidity, Viper, or Bamboo defines how you get from the entry point of the program to the entry point of a particular function. When an external application or another smart contract wants to interact with the blockchain, it needs to have some knowledge of a smart contract’s interface such as a way to identify a method and its parameters. This is facilitated by the Ethereum Application Binary Interface (ABI). "
},
{
"code": null,
"e": 28005,
"s": 27239,
"text": "It is similar to the Application Program Interface (API), which is essentially a representation of the code’s interface in Human readable form or a high-level language. In the EVM the compiled code being stored as binary data and the human-readable interfaces disappear and smart contract interactions have to be translated into a binary format that can be interpreted by the EVM. ABI defines the methods and structures that you can simply use to interact with that binary contract (just like the API does), only on a lower level. The ABI indicates to the caller the needed information (functions signatures and variables declarations) to encode such that it is understood by the Virtual Machine call to the byte code(contract). This process is called ABI encoding."
},
{
"code": null,
"e": 28610,
"s": 28005,
"text": "ABI is the interface between two program modules, one of which is mostly at the machine code level. The interface is the default method for encoding/decoding data into or out of the machine code. In Ethereum it is basically how you encode a language to have contract calls to the EVM or how to read the data out of transactions. ABI encoding is in most cases automated by tools that are part of the compiler like REMIX or wallets which can interact with the blockchain. ABI encoder requires a description of the contract’s interface like function name and parameters which is commonly provided as a JSON."
},
{
"code": null,
"e": 29059,
"s": 28610,
"text": "An Ethereum smart contract is byte code deployed on the Ethereum blockchain. There could be several functions in a contract. An ABI is necessary so that you can point to the specific function call that you want to evoke and also get a guarantee that the function will return data in the format you are expecting. The first four bytes of a transaction payload sent to a contract is usually used to distinguish which function in the contract to call."
},
{
"code": null,
"e": 29138,
"s": 29059,
"text": "1) Contract GeeksForGeeks has certain functions. Let’s call function baz(...)."
},
{
"code": null,
"e": 29336,
"s": 29138,
"text": " contract GeeksForGeeks {\n function empty() {}\n function baz(uint32 x, bool y) returns (bool r) \n { if(x>0) \n r = true;\n else\n r =false;\n }\n function Ritu(bytes _name, bool _x) {}\n}\n"
},
{
"code": null,
"e": 29421,
"s": 29336,
"text": "Function call baz with the parameters 69 and true, we would pass 68 bytes in total. "
},
{
"code": null,
"e": 29800,
"s": 29421,
"text": "Method ID. \nThis is derived as the first 4 bytes of the Keccak-256 hash of the ASCII form of the signature baz(uint32,bool)\n0xcdcd77c0 \n\nFirst parameter\nuint32 value 69 padded to 32 bytes \n0x0000000000000000000000000000000000000000000000000000000000000045:\n\nSecond parameter \nboolean true, padded to 32 bytes\n0x0000000000000000000000000000000000000000000000000000000000000001: \n"
},
{
"code": null,
"e": 29893,
"s": 29800,
"text": "2) balanceOf is a function used to obtain the balance. The function signature is as follows:"
},
{
"code": null,
"e": 29913,
"s": 29893,
"text": "balanceOf(address)\n"
},
{
"code": null,
"e": 29979,
"s": 29913,
"text": "Calculating the keccak256 hash of this signature string produces:"
},
{
"code": null,
"e": 30047,
"s": 29979,
"text": "0x70a08231b98ef4ca268c9cc3f6b4590e4bfec28280db06bb5d45e689f2a360be\n"
},
{
"code": null,
"e": 30151,
"s": 30047,
"text": "Taking the top four bytes gives us the following function selector or Method ID as also obtained above:"
},
{
"code": null,
"e": 30163,
"s": 30151,
"text": "0x70a08231\n"
},
{
"code": null,
"e": 30900,
"s": 30163,
"text": "The ABI encoding is not part of the core protocol of Ethereum because the payload data in transactions are not required to have any structure, it is just a sequence of bytes. Similarly, the Ethereum Virtual Machine also just processes the data as a sequence of bytes. For example, a transaction contains the sequence of bytes. How these bytes are interpreted into structured data is up to the program and is up to the programming language used. In order to make it possible for two programs written in different programming languages to call each other, the compilers of such languages should implement the serialization and deserialization of data in the same way, i.e. although they should implement the ABI they are not compelled to."
},
{
"code": null,
"e": 31189,
"s": 30900,
"text": "Example: In the below example, a contract is created to store a number and returned the stored number. Below the example, there are two outputs: One is the ABI Output and the second one is the output of the execution of the code i.e. the simple Deploy and Run Output of the Solidity code."
},
{
"code": null,
"e": 31198,
"s": 31189,
"text": "Solidity"
},
{
"code": "// Solidity program to// demonstrate abi encodingpragma solidity >=0.4.22 <0.7.0; // Creating a contractcontract Storage { // Declaring a state variable uint256 number; // Defining a function // to store the number function store(uint256 num) public { number = num; } // Defining a function to // send back or return the // stored number function retrieve() public view returns (uint256) { return number; }}",
"e": 31683,
"s": 31198,
"text": null
},
{
"code": null,
"e": 31696,
"s": 31683,
"text": "ABI Output: "
},
{
"code": null,
"e": 32286,
"s": 31696,
"text": "[\n {\n \"inputs\": [],\n \"name\": \"retrieve\",\n \"outputs\": [\n {\n \"internalType\": \"uint256\",\n \"name\": \"\",\n \"type\": \"uint256\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"uint256\",\n \"name\": \"num\",\n \"type\": \"uint256\"\n }\n ],\n \"name\": \"store\",\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n }\n]\n"
},
{
"code": null,
"e": 32294,
"s": 32286,
"text": "Output:"
},
{
"code": null,
"e": 32305,
"s": 32294,
"text": "Blockchain"
},
{
"code": null,
"e": 32314,
"s": 32305,
"text": "Solidity"
},
{
"code": null,
"e": 32412,
"s": 32314,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32430,
"s": 32412,
"text": "Solidity - Arrays"
},
{
"code": null,
"e": 32450,
"s": 32430,
"text": "Solidity - Mappings"
},
{
"code": null,
"e": 32480,
"s": 32450,
"text": "Storage vs Memory in Solidity"
},
{
"code": null,
"e": 32552,
"s": 32480,
"text": "Ethereum Blockchain - Getting Free Test Ethers For Rinkeby Test Network"
},
{
"code": null,
"e": 32581,
"s": 32552,
"text": "Solidity - Enums and Structs"
},
{
"code": null,
"e": 32599,
"s": 32581,
"text": "Solidity - Arrays"
},
{
"code": null,
"e": 32619,
"s": 32599,
"text": "Solidity - Mappings"
},
{
"code": null,
"e": 32649,
"s": 32619,
"text": "Storage vs Memory in Solidity"
},
{
"code": null,
"e": 32678,
"s": 32649,
"text": "Solidity - Enums and Structs"
}
] |
Python program to display half diamond pattern of numbers with star border - GeeksforGeeks | 02 Feb, 2021
Given a number n, the task is to write a Python program to print a half diamond pattern of numbers with a star border.
Examples:
Input: n = 5
Output:
*
*1*
*121*
*12321*
*1234321*
*123454321*
*1234321*
*12321*
*121*
*1*
*
Input: n = 3
Output:
*
*1*
*121*
*12321*
*121*
*1*
*
Approach:
Two for loops will be run in this program in order to print the numbers as well as stars.
First print * and then run for loop from 1 to (n+1) to print up to the rows in ascending order.
In this particular for loop * will be printed up to i and then one more for loop will run from 1 to i+1 in order to print the numbers in ascending order.
Now one more loop will run from i-1 to 0 in order to print the number in the reverse order.
Now one star will be printed and this for loop will end.
Now second for loop will run from n-1 to 0 to print the pattern as in the middle in which the numbers are in a reverse manner.
In this for loop also the same work will be done as in first for loop.
The required pattern will be displayed.
Below is the implementation of the above pattern:
Python3
# function to display the pattern up to ndef display(n): print("*") for i in range(1, n+1): print("*", end="") # for loop to display number up to i for j in range(1, i+1): print(j, end="") # for loop to display number in reverse direction for j in range(i-1, 0, -1): print(j, end="") print("*", end="") print() # for loop to display i in reverse direction for i in range(n-1, 0, -1): print("*", end="") for j in range(1, i+1): print(j, end="") for j in range(i-1, 0, -1): print(j, end="") print("*", end="") print() print("*") # driver coden = 5print('\nFor n =', n)display(n) n = 3print('\nFor n =', n)display(n)
Output:
For n = 5
*
*1*
*121*
*12321*
*1234321*
*123454321*
*1234321*
*12321*
*121*
*1*
*
For n = 3
*
*1*
*121*
*12321*
*121*
*1*
*
Python Pattern-printing
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python? | [
{
"code": null,
"e": 25581,
"s": 25553,
"text": "\n02 Feb, 2021"
},
{
"code": null,
"e": 25700,
"s": 25581,
"text": "Given a number n, the task is to write a Python program to print a half diamond pattern of numbers with a star border."
},
{
"code": null,
"e": 25710,
"s": 25700,
"text": "Examples:"
},
{
"code": null,
"e": 25860,
"s": 25710,
"text": "Input: n = 5\nOutput:\n\n*\n*1*\n*121*\n*12321*\n*1234321*\n*123454321*\n*1234321*\n*12321*\n*121*\n*1*\n*\n\n\nInput: n = 3\nOutput:\n\n*\n*1*\n*121*\n*12321*\n*121*\n*1*\n*"
},
{
"code": null,
"e": 25870,
"s": 25860,
"text": "Approach:"
},
{
"code": null,
"e": 25960,
"s": 25870,
"text": "Two for loops will be run in this program in order to print the numbers as well as stars."
},
{
"code": null,
"e": 26056,
"s": 25960,
"text": "First print * and then run for loop from 1 to (n+1) to print up to the rows in ascending order."
},
{
"code": null,
"e": 26210,
"s": 26056,
"text": "In this particular for loop * will be printed up to i and then one more for loop will run from 1 to i+1 in order to print the numbers in ascending order."
},
{
"code": null,
"e": 26302,
"s": 26210,
"text": "Now one more loop will run from i-1 to 0 in order to print the number in the reverse order."
},
{
"code": null,
"e": 26359,
"s": 26302,
"text": "Now one star will be printed and this for loop will end."
},
{
"code": null,
"e": 26486,
"s": 26359,
"text": "Now second for loop will run from n-1 to 0 to print the pattern as in the middle in which the numbers are in a reverse manner."
},
{
"code": null,
"e": 26557,
"s": 26486,
"text": "In this for loop also the same work will be done as in first for loop."
},
{
"code": null,
"e": 26597,
"s": 26557,
"text": "The required pattern will be displayed."
},
{
"code": null,
"e": 26647,
"s": 26597,
"text": "Below is the implementation of the above pattern:"
},
{
"code": null,
"e": 26655,
"s": 26647,
"text": "Python3"
},
{
"code": "# function to display the pattern up to ndef display(n): print(\"*\") for i in range(1, n+1): print(\"*\", end=\"\") # for loop to display number up to i for j in range(1, i+1): print(j, end=\"\") # for loop to display number in reverse direction for j in range(i-1, 0, -1): print(j, end=\"\") print(\"*\", end=\"\") print() # for loop to display i in reverse direction for i in range(n-1, 0, -1): print(\"*\", end=\"\") for j in range(1, i+1): print(j, end=\"\") for j in range(i-1, 0, -1): print(j, end=\"\") print(\"*\", end=\"\") print() print(\"*\") # driver coden = 5print('\\nFor n =', n)display(n) n = 3print('\\nFor n =', n)display(n)",
"e": 27458,
"s": 26655,
"text": null
},
{
"code": null,
"e": 27467,
"s": 27458,
"text": "Output: "
},
{
"code": null,
"e": 27592,
"s": 27467,
"text": "For n = 5\n*\n*1*\n*121*\n*12321*\n*1234321*\n*123454321*\n*1234321*\n*12321*\n*121*\n*1*\n*\n\nFor n = 3\n*\n*1*\n*121*\n*12321*\n*121*\n*1*\n*"
},
{
"code": null,
"e": 27616,
"s": 27592,
"text": "Python Pattern-printing"
},
{
"code": null,
"e": 27623,
"s": 27616,
"text": "Python"
},
{
"code": null,
"e": 27639,
"s": 27623,
"text": "Python Programs"
},
{
"code": null,
"e": 27737,
"s": 27639,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27769,
"s": 27737,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27811,
"s": 27769,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27853,
"s": 27811,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27909,
"s": 27853,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27936,
"s": 27909,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27958,
"s": 27936,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27997,
"s": 27958,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 28043,
"s": 27997,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 28081,
"s": 28043,
"text": "Python | Convert a list to dictionary"
}
] |
Find the minimum number of steps to reach M from N - GeeksforGeeks | 07 Apr, 2021
Given two integers N and M. The task is to find the minimum number of steps to reach M from N by performing given operations.
Multiply a number x by 2. So, x becomes 2*x.Subtract one from the number x. So, x becomes x-1.
Multiply a number x by 2. So, x becomes 2*x.
Subtract one from the number x. So, x becomes x-1.
Examples:
Input : N = 4, M = 6
Output : 2
Explanation : Perform operation number 2 on N.
So, N becomes 3 and then perform operation number 1.
Then, N becomes 6. So, the minimum number of steps is 2.
Input : N = 10, M = 1
Output : 9
Explanation : Perform operation number two
9 times on N. Then N becomes 1.
Approach : The idea is to reverse the problem as follows: We should get the number N starting from M using the operations:
Divide the number by 2 if it is even.Add 1 to the number.
Divide the number by 2 if it is even.
Add 1 to the number.
Now, the minimum number of operations would be:
If N > M, return the difference between them, that is, number of steps will be adding 1 to M until it becomes equal to N.Else if N < M. Keep dividing M by 2 until it becomes less than N. If M is odd, add 1 to it first and then divide by 2. Once M is less than N, add the difference between them to the count along with the count of above operations.
If N > M, return the difference between them, that is, number of steps will be adding 1 to M until it becomes equal to N.
Else if N < M. Keep dividing M by 2 until it becomes less than N. If M is odd, add 1 to it first and then divide by 2. Once M is less than N, add the difference between them to the count along with the count of above operations.
Keep dividing M by 2 until it becomes less than N. If M is odd, add 1 to it first and then divide by 2. Once M is less than N, add the difference between them to the count along with the count of above operations.
Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// CPP program to find minimum number// of steps to reach M from N#include <bits/stdc++.h>using namespace std; // Function to find a minimum number// of steps to reach M from Nint Minsteps(int n, int m){ int ans = 0; // Continue till m is greater than n while(m > n) { // If m is odd if(m&1) { // add one m++; ans++; } // divide m by 2 m /= 2; ans++; } // Return the required answer return ans + n - m;} // Driver codeint main(){ int n = 4, m = 6; cout << Minsteps(n, m); return 0;}
// Java program to find minimum number// of steps to reach M from Nclass CFG{ // Function to find a minimum number// of steps to reach M from Nstatic int Minsteps(int n, int m){ int ans = 0; // Continue till m is greater than n while(m > n) { // If m is odd if(m % 2 != 0) { // add one m++; ans++; } // divide m by 2 m /= 2; ans++; } // Return the required answer return ans + n - m;} // Driver codepublic static void main(String[] args){ int n = 4, m = 6; System.out.println(Minsteps(n, m));}} // This code is contributed by Code_Mech
# Python3 program to find minimum number# of steps to reach M from N # Function to find a minimum number# of steps to reach M from Ndef Minsteps(n, m): ans = 0 # Continue till m is greater than n while(m > n): # If m is odd if(m & 1): # add one m += 1 ans += 1 # divide m by 2 m //= 2 ans += 1 # Return the required answer return ans + n - m # Driver coden = 4m = 6 print(Minsteps(n, m)) # This code is contributed by mohit kumar
// C# program to find minimum number// of steps to reach M from Nusing System; class GFG{ // Function to find a minimum number// of steps to reach M from Nstatic int Minsteps(int n, int m){ int ans = 0; // Continue till m is greater than n while(m > n) { // If m is odd if(m % 2 != 0) { // add one m++; ans++; } // divide m by 2 m /= 2; ans++; } // Return the required answer return ans + n - m;} // Driver codepublic static void Main(){ int n = 4, m = 6; Console.WriteLine(Minsteps(n, m));}} // This code is contributed// by Akanksha Rai
<?php// PHP program to find minimum number// of steps to reach M from N // Function to find a minimum number// of steps to reach M from Nfunction Minsteps($n, $m){ $ans = 0; // Continue till m is greater than n while($m > $n) { // If m is odd if($m % 2 != 0) { // add one $m++; $ans++; } // divide m by 2 $m /= 2; $ans++; } // Return the required answer return $ans + $n - $m;} // Driver code$n = 4; $m = 6; echo(Minsteps($n, $m)); // This code is contributed by Code_Mech?>
<script>// JavaScript program to find minimum number// of steps to reach M from N // Function to find a minimum number// of steps to reach M from Nfunction Minsteps(n, m){ let ans = 0; // Continue till m is greater than n while(m > n) { // If m is odd if(m&1) { // add one m++; ans++; } // divide m by 2 m = Math.floor(m / 2); ans++; } // Return the required answer return ans + n - m;} // Driver code let n = 4, m = 6; document.write(Minsteps(n, m)); // This code is contributed by Surbhi Tyagi.</script>
2
mohit kumar 29
Code_Mech
Akanksha_Rai
surbhityagi15
Numbers
Greedy
Mathematical
Greedy
Mathematical
Numbers
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Huffman Coding | Greedy Algo-3
Activity Selection Problem | Greedy Algo-1
Fractional Knapsack Problem
Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive)
Job Sequencing Problem
C++ Data Types
Set in C++ Standard Template Library (STL)
Merge two sorted arrays
Modulo Operator (%) in C/C++ with Examples | [
{
"code": null,
"e": 26297,
"s": 26269,
"text": "\n07 Apr, 2021"
},
{
"code": null,
"e": 26425,
"s": 26297,
"text": "Given two integers N and M. The task is to find the minimum number of steps to reach M from N by performing given operations. "
},
{
"code": null,
"e": 26520,
"s": 26425,
"text": "Multiply a number x by 2. So, x becomes 2*x.Subtract one from the number x. So, x becomes x-1."
},
{
"code": null,
"e": 26565,
"s": 26520,
"text": "Multiply a number x by 2. So, x becomes 2*x."
},
{
"code": null,
"e": 26616,
"s": 26565,
"text": "Subtract one from the number x. So, x becomes x-1."
},
{
"code": null,
"e": 26628,
"s": 26616,
"text": "Examples: "
},
{
"code": null,
"e": 26930,
"s": 26628,
"text": "Input : N = 4, M = 6\nOutput : 2\nExplanation : Perform operation number 2 on N. \nSo, N becomes 3 and then perform operation number 1. \nThen, N becomes 6. So, the minimum number of steps is 2. \n\nInput : N = 10, M = 1\nOutput : 9\nExplanation : Perform operation number two \n9 times on N. Then N becomes 1."
},
{
"code": null,
"e": 27057,
"s": 26932,
"text": "Approach : The idea is to reverse the problem as follows: We should get the number N starting from M using the operations: "
},
{
"code": null,
"e": 27115,
"s": 27057,
"text": "Divide the number by 2 if it is even.Add 1 to the number."
},
{
"code": null,
"e": 27153,
"s": 27115,
"text": "Divide the number by 2 if it is even."
},
{
"code": null,
"e": 27174,
"s": 27153,
"text": "Add 1 to the number."
},
{
"code": null,
"e": 27224,
"s": 27174,
"text": "Now, the minimum number of operations would be: "
},
{
"code": null,
"e": 27574,
"s": 27224,
"text": "If N > M, return the difference between them, that is, number of steps will be adding 1 to M until it becomes equal to N.Else if N < M. Keep dividing M by 2 until it becomes less than N. If M is odd, add 1 to it first and then divide by 2. Once M is less than N, add the difference between them to the count along with the count of above operations."
},
{
"code": null,
"e": 27696,
"s": 27574,
"text": "If N > M, return the difference between them, that is, number of steps will be adding 1 to M until it becomes equal to N."
},
{
"code": null,
"e": 27925,
"s": 27696,
"text": "Else if N < M. Keep dividing M by 2 until it becomes less than N. If M is odd, add 1 to it first and then divide by 2. Once M is less than N, add the difference between them to the count along with the count of above operations."
},
{
"code": null,
"e": 28139,
"s": 27925,
"text": "Keep dividing M by 2 until it becomes less than N. If M is odd, add 1 to it first and then divide by 2. Once M is less than N, add the difference between them to the count along with the count of above operations."
},
{
"code": null,
"e": 28192,
"s": 28139,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 28196,
"s": 28192,
"text": "C++"
},
{
"code": null,
"e": 28201,
"s": 28196,
"text": "Java"
},
{
"code": null,
"e": 28209,
"s": 28201,
"text": "Python3"
},
{
"code": null,
"e": 28212,
"s": 28209,
"text": "C#"
},
{
"code": null,
"e": 28216,
"s": 28212,
"text": "PHP"
},
{
"code": null,
"e": 28227,
"s": 28216,
"text": "Javascript"
},
{
"code": "// CPP program to find minimum number// of steps to reach M from N#include <bits/stdc++.h>using namespace std; // Function to find a minimum number// of steps to reach M from Nint Minsteps(int n, int m){ int ans = 0; // Continue till m is greater than n while(m > n) { // If m is odd if(m&1) { // add one m++; ans++; } // divide m by 2 m /= 2; ans++; } // Return the required answer return ans + n - m;} // Driver codeint main(){ int n = 4, m = 6; cout << Minsteps(n, m); return 0;}",
"e": 28857,
"s": 28227,
"text": null
},
{
"code": "// Java program to find minimum number// of steps to reach M from Nclass CFG{ // Function to find a minimum number// of steps to reach M from Nstatic int Minsteps(int n, int m){ int ans = 0; // Continue till m is greater than n while(m > n) { // If m is odd if(m % 2 != 0) { // add one m++; ans++; } // divide m by 2 m /= 2; ans++; } // Return the required answer return ans + n - m;} // Driver codepublic static void main(String[] args){ int n = 4, m = 6; System.out.println(Minsteps(n, m));}} // This code is contributed by Code_Mech",
"e": 29534,
"s": 28857,
"text": null
},
{
"code": "# Python3 program to find minimum number# of steps to reach M from N # Function to find a minimum number# of steps to reach M from Ndef Minsteps(n, m): ans = 0 # Continue till m is greater than n while(m > n): # If m is odd if(m & 1): # add one m += 1 ans += 1 # divide m by 2 m //= 2 ans += 1 # Return the required answer return ans + n - m # Driver coden = 4m = 6 print(Minsteps(n, m)) # This code is contributed by mohit kumar",
"e": 30085,
"s": 29534,
"text": null
},
{
"code": "// C# program to find minimum number// of steps to reach M from Nusing System; class GFG{ // Function to find a minimum number// of steps to reach M from Nstatic int Minsteps(int n, int m){ int ans = 0; // Continue till m is greater than n while(m > n) { // If m is odd if(m % 2 != 0) { // add one m++; ans++; } // divide m by 2 m /= 2; ans++; } // Return the required answer return ans + n - m;} // Driver codepublic static void Main(){ int n = 4, m = 6; Console.WriteLine(Minsteps(n, m));}} // This code is contributed// by Akanksha Rai",
"e": 30765,
"s": 30085,
"text": null
},
{
"code": "<?php// PHP program to find minimum number// of steps to reach M from N // Function to find a minimum number// of steps to reach M from Nfunction Minsteps($n, $m){ $ans = 0; // Continue till m is greater than n while($m > $n) { // If m is odd if($m % 2 != 0) { // add one $m++; $ans++; } // divide m by 2 $m /= 2; $ans++; } // Return the required answer return $ans + $n - $m;} // Driver code$n = 4; $m = 6; echo(Minsteps($n, $m)); // This code is contributed by Code_Mech?>",
"e": 31366,
"s": 30765,
"text": null
},
{
"code": "<script>// JavaScript program to find minimum number// of steps to reach M from N // Function to find a minimum number// of steps to reach M from Nfunction Minsteps(n, m){ let ans = 0; // Continue till m is greater than n while(m > n) { // If m is odd if(m&1) { // add one m++; ans++; } // divide m by 2 m = Math.floor(m / 2); ans++; } // Return the required answer return ans + n - m;} // Driver code let n = 4, m = 6; document.write(Minsteps(n, m)); // This code is contributed by Surbhi Tyagi.</script>",
"e": 32010,
"s": 31366,
"text": null
},
{
"code": null,
"e": 32012,
"s": 32010,
"text": "2"
},
{
"code": null,
"e": 32029,
"s": 32014,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 32039,
"s": 32029,
"text": "Code_Mech"
},
{
"code": null,
"e": 32052,
"s": 32039,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 32066,
"s": 32052,
"text": "surbhityagi15"
},
{
"code": null,
"e": 32074,
"s": 32066,
"text": "Numbers"
},
{
"code": null,
"e": 32081,
"s": 32074,
"text": "Greedy"
},
{
"code": null,
"e": 32094,
"s": 32081,
"text": "Mathematical"
},
{
"code": null,
"e": 32101,
"s": 32094,
"text": "Greedy"
},
{
"code": null,
"e": 32114,
"s": 32101,
"text": "Mathematical"
},
{
"code": null,
"e": 32122,
"s": 32114,
"text": "Numbers"
},
{
"code": null,
"e": 32220,
"s": 32122,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32251,
"s": 32220,
"text": "Huffman Coding | Greedy Algo-3"
},
{
"code": null,
"e": 32294,
"s": 32251,
"text": "Activity Selection Problem | Greedy Algo-1"
},
{
"code": null,
"e": 32322,
"s": 32294,
"text": "Fractional Knapsack Problem"
},
{
"code": null,
"e": 32403,
"s": 32322,
"text": "Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive)"
},
{
"code": null,
"e": 32426,
"s": 32403,
"text": "Job Sequencing Problem"
},
{
"code": null,
"e": 32441,
"s": 32426,
"text": "C++ Data Types"
},
{
"code": null,
"e": 32484,
"s": 32441,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 32508,
"s": 32484,
"text": "Merge two sorted arrays"
}
] |
Tower Of Hanoi | Practice | GeeksforGeeks | The tower of Hanoi is a famous puzzle where we have three rods and N disks. The objective of the puzzle is to move the entire stack to another rod. You are given the number of discs N. Initially, these discs are in the rod 1. You need to print all the steps of discs movement so that all the discs reach the 3rd rod. Also, you need to find the total moves.
Note: The discs are arranged such that the top disc is numbered 1 and the bottom-most disc is numbered N. Also, all the discs have different sizes and a bigger disc cannot be put on the top of a smaller disc. Refer the provided link to get a better clarity about the puzzle.
Example 1:
Input:
N = 2
Output:
move disk 1 from rod 1 to rod 2
move disk 2 from rod 1 to rod 3
move disk 1 from rod 2 to rod 3
3
Explanation: For N=2 , steps will be
as follows in the example and total
3 steps will be taken.
Example 2:
Input:
N = 3
Output:
move disk 1 from rod 1 to rod 3
move disk 2 from rod 1 to rod 2
move disk 1 from rod 3 to rod 2
move disk 3 from rod 1 to rod 3
move disk 1 from rod 2 to rod 1
move disk 2 from rod 2 to rod 3
move disk 1 from rod 1 to rod 3
7
Explanation: For N=3 , steps will be
as follows in the example and total
7 steps will be taken.
Your Task:
You don't need to read input or print anything. You only need to complete the function toh() that takes following parameters: N (number of discs), from (The rod number from which we move the disc), to (The rod number to which we move the disc), aux (The rod that is used as an auxiliary rod) and prints the required moves inside function body (See the example for the format of the output) as well as return the count of total moves made. The total number of moves are printed by the driver code.
Please take care of the case of the letters.
Expected Time Complexity: O(2N).
Expected Auxiliary Space: O(N).
Constraints:
1 <= N <= 16
0
sv10999127 hours ago
JAVA SOLUTION 1.1SEC
class Hanoi { public long towOfhan(int n, int from ,int to, int aux) { if(n == 0){ return 1; } long i = towOfhan(n-1,from,aux,to); System.out.println("move disk "+n + " from rod "+ from +" to rod " + to ); long j = towOfhan(n-1,aux,to,from); return i + j; }
public long toh(int N, int from, int to, int aux){ long steps = towOfhan(N,from,to,aux); return steps-1; }}
0
imabhishek026 days ago
int count=0;
long long toh(int n, int src, int dest, int help) {
if(n>0)
{
toh(n-1,src,help,dest);
cout<<"move disk " <<n<< " from rod "<<src<<" to rod "<<dest<<endl;
count++;
toh(n-1,help,dest,src);
}return count;
}
+2
pickyourpillnow1 week ago
int count=0; long long toh(int N, int from, int to, int aux) { // Your code here if(N>0){ toh(N-1,from,aux,to); cout<<"move disk "<< N <<" from rod "<<from<<" to rod "<<to<<endl; count++; toh(N-1,aux,to,from); } return count; }
0
deepakaryak91 week ago
//Python
class Solution: def countMoves(self,n): if n == 0: return 0; return 2 * self.countMoves(n - 1) + 1 def toh(self, N, fromm, to, aux): # Your code here if N == 1: print("move disk " + str(1) + " from rod " + str(fromm) + " to rod " + str(to)) return 1 else: self.toh(N-1,fromm,aux,to) print("move disk " + str(N) + " from rod " + str(fromm) + " to rod " + str(to)) self.toh(N-1,aux,to,fromm) return self.countMoves(N)
+1
rohankundu8591 week ago
//C++ Solution
long long toh(int N, int from, int to, int aux)
{
// Your code here
int n=N;
if(N==0)
{
return 0;
}
toh(N-1,from,aux,to);
cout<<"move disk "<<N<<" from rod "<<from<<" to rod "<<to<<endl;
toh(N-1,aux,to,from);
return (pow(2,n)-1);
}
0
rahuldebnath292 weeks ago
long long count = 0; long long toh(int N, int from, int to, int aux) { // Your code here if(N==1) { cout<<"move disk 1 from rod "<<from<<" to rod "<<to<<endl; count++; return count; } toh(N-1,from,aux,to); cout<<"move disk "<<N<<" from rod "<<from<<" to rod "<<to<<endl; count ++; toh(N-1,aux,to,from); return count; }
0
rajsandhu19892 weeks ago
long long steps=0;
long long toh(int N, int from, int to, int aux) {
// Your code here
if(N==1){
cout<<"move disk 1 from rod "<<from<<" to rod "<<to<<endl;
steps++;
return steps;
}
toh(N-1,from,aux,to);
cout<<"move disk "<<N<<" from rod "<<from<<" to rod "<<to<<endl;
steps++;
toh(N-1,aux,to,from);
return steps;
}
0
sambhavimukherjee102 weeks ago
public: // You need to complete this function
// avoid space at the starting of the string in "move disk....." long long count = 0; long long toh(int N, int from, int to, int aux) { if(N > 0){ toh(N-1, from, aux, to); cout << "move disk " <<N<< " from rod " <<from<< " to rod " << to <<endl; count++; toh(N-1, aux, to, from); } return count; }};
0
iscream1 month ago
public long f(int n,Stack<Integer> fromRod,Stack<Integer> toRod,Stack<Integer> auxRod,int from,int to,int aux){ if(n ==1){ int disk = fromRod.pop(); System.out.println("move disk " + disk +" from rod " + from+" to rod " + to); toRod.push(disk); return 1; } return f(n-1,fromRod,auxRod,toRod,from,aux,to) + f(1,fromRod,toRod,auxRod,from,to,aux) + f(n-1,auxRod,toRod,fromRod,aux,to,from); } public long toh(int N, int from, int to, int aux) { Stack<Integer> fromRod = new Stack<>(); for(int i=N;i>=1;i--){ fromRod.push(i); } Stack<Integer> toRod = new Stack<>(); Stack<Integer> auxRod = new Stack<>(); return f(N,fromRod,toRod,auxRod,from,to,aux); }
+1
dipanshusharma93131 month ago
// java solution
class Hanoi { public long toh(int N, int from, int to, int aux) { // Your code here long count = 0; if(N == 0){ return 0; } count += toh(N-1, from, aux, to); System.out.println("move disk "+N+" from rod "+from+" to rod "+to); count += toh(N-1, aux, to, from); return ++count; }}
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": 870,
"s": 238,
"text": "The tower of Hanoi is a famous puzzle where we have three rods and N disks. The objective of the puzzle is to move the entire stack to another rod. You are given the number of discs N. Initially, these discs are in the rod 1. You need to print all the steps of discs movement so that all the discs reach the 3rd rod. Also, you need to find the total moves.\nNote: The discs are arranged such that the top disc is numbered 1 and the bottom-most disc is numbered N. Also, all the discs have different sizes and a bigger disc cannot be put on the top of a smaller disc. Refer the provided link to get a better clarity about the puzzle."
},
{
"code": null,
"e": 881,
"s": 870,
"text": "Example 1:"
},
{
"code": null,
"e": 1096,
"s": 881,
"text": "Input:\nN = 2\nOutput:\nmove disk 1 from rod 1 to rod 2\nmove disk 2 from rod 1 to rod 3\nmove disk 1 from rod 2 to rod 3\n3\nExplanation: For N=2 , steps will be\nas follows in the example and total\n3 steps will be taken."
},
{
"code": null,
"e": 1107,
"s": 1096,
"text": "Example 2:"
},
{
"code": null,
"e": 1451,
"s": 1107,
"text": "Input:\nN = 3\nOutput:\nmove disk 1 from rod 1 to rod 3\nmove disk 2 from rod 1 to rod 2\nmove disk 1 from rod 3 to rod 2\nmove disk 3 from rod 1 to rod 3\nmove disk 1 from rod 2 to rod 1\nmove disk 2 from rod 2 to rod 3\nmove disk 1 from rod 1 to rod 3\n7\nExplanation: For N=3 , steps will be\nas follows in the example and total\n7 steps will be taken.\n"
},
{
"code": null,
"e": 2004,
"s": 1451,
"text": "Your Task:\nYou don't need to read input or print anything. You only need to complete the function toh() that takes following parameters: N (number of discs), from (The rod number from which we move the disc), to (The rod number to which we move the disc), aux (The rod that is used as an auxiliary rod) and prints the required moves inside function body (See the example for the format of the output) as well as return the count of total moves made. The total number of moves are printed by the driver code.\nPlease take care of the case of the letters."
},
{
"code": null,
"e": 2069,
"s": 2004,
"text": "Expected Time Complexity: O(2N).\nExpected Auxiliary Space: O(N)."
},
{
"code": null,
"e": 2095,
"s": 2069,
"text": "Constraints:\n1 <= N <= 16"
},
{
"code": null,
"e": 2097,
"s": 2095,
"text": "0"
},
{
"code": null,
"e": 2118,
"s": 2097,
"text": "sv10999127 hours ago"
},
{
"code": null,
"e": 2140,
"s": 2118,
"text": "JAVA SOLUTION 1.1SEC "
},
{
"code": null,
"e": 2464,
"s": 2140,
"text": " class Hanoi { public long towOfhan(int n, int from ,int to, int aux) { if(n == 0){ return 1; } long i = towOfhan(n-1,from,aux,to); System.out.println(\"move disk \"+n + \" from rod \"+ from +\" to rod \" + to ); long j = towOfhan(n-1,aux,to,from); return i + j; }"
},
{
"code": null,
"e": 2592,
"s": 2464,
"text": " public long toh(int N, int from, int to, int aux){ long steps = towOfhan(N,from,to,aux); return steps-1; }}"
},
{
"code": null,
"e": 2594,
"s": 2592,
"text": "0"
},
{
"code": null,
"e": 2617,
"s": 2594,
"text": "imabhishek026 days ago"
},
{
"code": null,
"e": 2940,
"s": 2617,
"text": "\n int count=0;\n long long toh(int n, int src, int dest, int help) {\n \n if(n>0)\n {\n toh(n-1,src,help,dest);\n \n cout<<\"move disk \" <<n<< \" from rod \"<<src<<\" to rod \"<<dest<<endl;\n count++;\n \n toh(n-1,help,dest,src); \n }return count;\n \n }\n\n\n"
},
{
"code": null,
"e": 2943,
"s": 2940,
"text": "+2"
},
{
"code": null,
"e": 2969,
"s": 2943,
"text": "pickyourpillnow1 week ago"
},
{
"code": null,
"e": 3267,
"s": 2969,
"text": "int count=0; long long toh(int N, int from, int to, int aux) { // Your code here if(N>0){ toh(N-1,from,aux,to); cout<<\"move disk \"<< N <<\" from rod \"<<from<<\" to rod \"<<to<<endl; count++; toh(N-1,aux,to,from); } return count; }"
},
{
"code": null,
"e": 3269,
"s": 3267,
"text": "0"
},
{
"code": null,
"e": 3292,
"s": 3269,
"text": "deepakaryak91 week ago"
},
{
"code": null,
"e": 3301,
"s": 3292,
"text": "//Python"
},
{
"code": null,
"e": 3833,
"s": 3303,
"text": "class Solution: def countMoves(self,n): if n == 0: return 0; return 2 * self.countMoves(n - 1) + 1 def toh(self, N, fromm, to, aux): # Your code here if N == 1: print(\"move disk \" + str(1) + \" from rod \" + str(fromm) + \" to rod \" + str(to)) return 1 else: self.toh(N-1,fromm,aux,to) print(\"move disk \" + str(N) + \" from rod \" + str(fromm) + \" to rod \" + str(to)) self.toh(N-1,aux,to,fromm) return self.countMoves(N)"
},
{
"code": null,
"e": 3836,
"s": 3833,
"text": "+1"
},
{
"code": null,
"e": 3860,
"s": 3836,
"text": "rohankundu8591 week ago"
},
{
"code": null,
"e": 4172,
"s": 3860,
"text": "//C++ Solution\nlong long toh(int N, int from, int to, int aux) \n {\n // Your code here\n int n=N;\n if(N==0)\n {\n return 0;\n }\n toh(N-1,from,aux,to);\n cout<<\"move disk \"<<N<<\" from rod \"<<from<<\" to rod \"<<to<<endl;\n toh(N-1,aux,to,from);\n return (pow(2,n)-1);\n }"
},
{
"code": null,
"e": 4174,
"s": 4172,
"text": "0"
},
{
"code": null,
"e": 4200,
"s": 4174,
"text": "rahuldebnath292 weeks ago"
},
{
"code": null,
"e": 4564,
"s": 4200,
"text": " long long count = 0; long long toh(int N, int from, int to, int aux) { // Your code here if(N==1) { cout<<\"move disk 1 from rod \"<<from<<\" to rod \"<<to<<endl; count++; return count; } toh(N-1,from,aux,to); cout<<\"move disk \"<<N<<\" from rod \"<<from<<\" to rod \"<<to<<endl; count ++; toh(N-1,aux,to,from); return count; }"
},
{
"code": null,
"e": 4566,
"s": 4564,
"text": "0"
},
{
"code": null,
"e": 4591,
"s": 4566,
"text": "rajsandhu19892 weeks ago"
},
{
"code": null,
"e": 5014,
"s": 4591,
"text": "long long steps=0;\n long long toh(int N, int from, int to, int aux) {\n // Your code here\n if(N==1){\n cout<<\"move disk 1 from rod \"<<from<<\" to rod \"<<to<<endl;\n steps++;\n return steps;\n }\n toh(N-1,from,aux,to);\n cout<<\"move disk \"<<N<<\" from rod \"<<from<<\" to rod \"<<to<<endl;\n steps++;\n toh(N-1,aux,to,from);\n return steps;\n }"
},
{
"code": null,
"e": 5016,
"s": 5014,
"text": "0"
},
{
"code": null,
"e": 5047,
"s": 5016,
"text": "sambhavimukherjee102 weeks ago"
},
{
"code": null,
"e": 5099,
"s": 5047,
"text": " public: // You need to complete this function"
},
{
"code": null,
"e": 5462,
"s": 5099,
"text": " // avoid space at the starting of the string in \"move disk.....\" long long count = 0; long long toh(int N, int from, int to, int aux) { if(N > 0){ toh(N-1, from, aux, to); cout << \"move disk \" <<N<< \" from rod \" <<from<< \" to rod \" << to <<endl; count++; toh(N-1, aux, to, from); } return count; }};"
},
{
"code": null,
"e": 5464,
"s": 5462,
"text": "0"
},
{
"code": null,
"e": 5483,
"s": 5464,
"text": "iscream1 month ago"
},
{
"code": null,
"e": 6259,
"s": 5483,
"text": " public long f(int n,Stack<Integer> fromRod,Stack<Integer> toRod,Stack<Integer> auxRod,int from,int to,int aux){ if(n ==1){ int disk = fromRod.pop(); System.out.println(\"move disk \" + disk +\" from rod \" + from+\" to rod \" + to); toRod.push(disk); return 1; } return f(n-1,fromRod,auxRod,toRod,from,aux,to) + f(1,fromRod,toRod,auxRod,from,to,aux) + f(n-1,auxRod,toRod,fromRod,aux,to,from); } public long toh(int N, int from, int to, int aux) { Stack<Integer> fromRod = new Stack<>(); for(int i=N;i>=1;i--){ fromRod.push(i); } Stack<Integer> toRod = new Stack<>(); Stack<Integer> auxRod = new Stack<>(); return f(N,fromRod,toRod,auxRod,from,to,aux); }"
},
{
"code": null,
"e": 6262,
"s": 6259,
"text": "+1"
},
{
"code": null,
"e": 6292,
"s": 6262,
"text": "dipanshusharma93131 month ago"
},
{
"code": null,
"e": 6309,
"s": 6292,
"text": "// java solution"
},
{
"code": null,
"e": 6665,
"s": 6309,
"text": "class Hanoi { public long toh(int N, int from, int to, int aux) { // Your code here long count = 0; if(N == 0){ return 0; } count += toh(N-1, from, aux, to); System.out.println(\"move disk \"+N+\" from rod \"+from+\" to rod \"+to); count += toh(N-1, aux, to, from); return ++count; }}"
},
{
"code": null,
"e": 6811,
"s": 6665,
"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": 6847,
"s": 6811,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 6857,
"s": 6847,
"text": "\nProblem\n"
},
{
"code": null,
"e": 6867,
"s": 6857,
"text": "\nContest\n"
},
{
"code": null,
"e": 6930,
"s": 6867,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 7078,
"s": 6930,
"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": 7286,
"s": 7078,
"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": 7392,
"s": 7286,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Java 8 | ObjDoubleConsumer Interface with Example - GeeksforGeeks | 26 Oct, 2018
The ObjDoubleConsumer Interface is a part of the java.util.function package which has been introduced since Java 8, to implement functional programming in Java. It represents a function which takes in two arguments and produces a result. However these kind of functions don’t return any value.
Hence this functional interface takes in one generic namely:-
T: denotes the type of the input argument to the operation
The lambda expression assigned to an object of ObjDoubleConsumer type is used to define its accept() which eventually applies the given operation on its argument. It takes in a double-valued and a T-valued argument and is expected to operate without any side effects. It is more like using an object of type BiConsumer<T, Double> except the fact that one is a reference and one is a primitive data type in this case. Hence we will be obtaining one reference and one value when this function is called.
The ObjDoubleConsumer interface consists of the following two functions:
This method accepts two values and performs the operation on the given arguments.
Syntax:
void accept(T t, double value)
Parameters: This method takes in two parameters:
t– the first input argument
value– the second input argument
Return Value: This method does not return any value.
Below is the code to illustrate accept() method:
Program:
// Java code to demonstrate// accept() method of ObjDoubleConsumer Interface import java.util.Arrays;import java.util.List;import java.util.function.ObjDoubleConsumer;import java.util.stream.Stream; public class GFG { public static void main(String args[]) { // Get the list from which // the Interface is to be instantiated. List<Integer> arr = Arrays.asList(3, 2, 5, 7, 4); // Instantiate the ObjDoubleConsumer interface ObjDoubleConsumer<List<Integer> > func = (list, num) -> { list.stream() .forEach( a -> System.out.println(a * num)); }; func.accept(arr, 2.0); }}
6.0
4.0
10.0
14.0
8.0
Java - util package
Java 8
java-basics
Java-Functional Programming
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
HashMap in Java with Examples
Interfaces in Java
How to iterate any Map in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Singleton Class in Java
Multidimensional Arrays in Java
Set in Java | [
{
"code": null,
"e": 25485,
"s": 25457,
"text": "\n26 Oct, 2018"
},
{
"code": null,
"e": 25779,
"s": 25485,
"text": "The ObjDoubleConsumer Interface is a part of the java.util.function package which has been introduced since Java 8, to implement functional programming in Java. It represents a function which takes in two arguments and produces a result. However these kind of functions don’t return any value."
},
{
"code": null,
"e": 25841,
"s": 25779,
"text": "Hence this functional interface takes in one generic namely:-"
},
{
"code": null,
"e": 25900,
"s": 25841,
"text": "T: denotes the type of the input argument to the operation"
},
{
"code": null,
"e": 26402,
"s": 25900,
"text": "The lambda expression assigned to an object of ObjDoubleConsumer type is used to define its accept() which eventually applies the given operation on its argument. It takes in a double-valued and a T-valued argument and is expected to operate without any side effects. It is more like using an object of type BiConsumer<T, Double> except the fact that one is a reference and one is a primitive data type in this case. Hence we will be obtaining one reference and one value when this function is called."
},
{
"code": null,
"e": 26475,
"s": 26402,
"text": "The ObjDoubleConsumer interface consists of the following two functions:"
},
{
"code": null,
"e": 26557,
"s": 26475,
"text": "This method accepts two values and performs the operation on the given arguments."
},
{
"code": null,
"e": 26565,
"s": 26557,
"text": "Syntax:"
},
{
"code": null,
"e": 26596,
"s": 26565,
"text": "void accept(T t, double value)"
},
{
"code": null,
"e": 26645,
"s": 26596,
"text": "Parameters: This method takes in two parameters:"
},
{
"code": null,
"e": 26673,
"s": 26645,
"text": "t– the first input argument"
},
{
"code": null,
"e": 26706,
"s": 26673,
"text": "value– the second input argument"
},
{
"code": null,
"e": 26759,
"s": 26706,
"text": "Return Value: This method does not return any value."
},
{
"code": null,
"e": 26808,
"s": 26759,
"text": "Below is the code to illustrate accept() method:"
},
{
"code": null,
"e": 26817,
"s": 26808,
"text": "Program:"
},
{
"code": "// Java code to demonstrate// accept() method of ObjDoubleConsumer Interface import java.util.Arrays;import java.util.List;import java.util.function.ObjDoubleConsumer;import java.util.stream.Stream; public class GFG { public static void main(String args[]) { // Get the list from which // the Interface is to be instantiated. List<Integer> arr = Arrays.asList(3, 2, 5, 7, 4); // Instantiate the ObjDoubleConsumer interface ObjDoubleConsumer<List<Integer> > func = (list, num) -> { list.stream() .forEach( a -> System.out.println(a * num)); }; func.accept(arr, 2.0); }}",
"e": 27524,
"s": 26817,
"text": null
},
{
"code": null,
"e": 27547,
"s": 27524,
"text": "6.0\n4.0\n10.0\n14.0\n8.0\n"
},
{
"code": null,
"e": 27567,
"s": 27547,
"text": "Java - util package"
},
{
"code": null,
"e": 27574,
"s": 27567,
"text": "Java 8"
},
{
"code": null,
"e": 27586,
"s": 27574,
"text": "java-basics"
},
{
"code": null,
"e": 27614,
"s": 27586,
"text": "Java-Functional Programming"
},
{
"code": null,
"e": 27619,
"s": 27614,
"text": "Java"
},
{
"code": null,
"e": 27624,
"s": 27619,
"text": "Java"
},
{
"code": null,
"e": 27722,
"s": 27624,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27773,
"s": 27722,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 27803,
"s": 27773,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 27822,
"s": 27803,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 27853,
"s": 27822,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 27871,
"s": 27853,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 27903,
"s": 27871,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 27923,
"s": 27903,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 27947,
"s": 27923,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 27979,
"s": 27947,
"text": "Multidimensional Arrays in Java"
}
] |
How to Find Duplicate Values in a SQL Table using Python? - GeeksforGeeks | 25 Nov, 2020
MySQL server is an open-source relational database management system that is a major support for web-based applications. Databases and related tables are the main component of many websites and applications as the data is stored and exchanged over the web. In order to access MySQL databases from a web server, we use various modules in Python such as PyMySQL, mysql.connector, etc.
In this article, we are going to find duplicate values in a specific MySQL table in a Database. First, we are going to connect to a database having a MySQL table. The SQL query that is going to be used is:
SELECT * FROM table-name
GROUP BY col_1, col_2,..., col_n
HAVING COUNT(*) > 1;
If the table has a primary key then the below query can also be used:
SELECT * FROM table-name
GROUP BY primar-key
HAVING COUNT(*) > 1;
The above queries will generate only duplicate rows in a table, and then these rows will be displayed as output.
Below are some programs which depict how to find duplicate values in a specific MySQL table in a Database:
Example 1
Below is the table Documentary in database geek which is going to be accessed by a Python script:
Below is the program to get the duplicate rows in the MySQL table:
Python3
# import required moduleimport mysql.connector # connect python with mysql with your hostname, # database, user and passworddb = mysql.connector.connect(host='localhost', database='gfg', user='root', password='') # create cursor objectcursor = db.cursor() # get the sum of rows of a columncursor.execute("SELECT * FROM Documentary \ GROUP BY Name, Production \ HAVING COUNT(*) > 1;") # fetch duplicate rows and display themprint('Duplicate Rows:') for row in cursor.fetchall(): print(row) # terminate connectiondb.close()
Output:
Example 2:
Here is another example to find the duplicate rows from a table in a given database, below is the table scheme and rows:
As we can see the Roll attribute is the primary key of the Student table, hence it only can be used with the GROUP BY statement in the query to generate the duplicate rows, below is the python script to get row count from the table Student:
Python3
# import required moduleimport mysql.connector # connect python with mysql with your hostname, # database, user and passworddb = mysql.connector.connect(host='localhost', database='gfg', user='root', password='') # create cursor objectcursor = db.cursor() # get the sum of rows of a columncursor.execute("SELECT * FROM Student \ GROUP BY Roll \ HAVING COUNT(*) > 1;") # fetch duplicate rows and display themprint('Duplicate Rows:') for row in cursor.fetchall(): print(row) # terminate connectiondb.close()
Output:
Python-mySQL
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
*args and **kwargs in Python
Create a Pandas DataFrame from Lists
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Convert integer to string in Python | [
{
"code": null,
"e": 26145,
"s": 26117,
"text": "\n25 Nov, 2020"
},
{
"code": null,
"e": 26529,
"s": 26145,
"text": "MySQL server is an open-source relational database management system that is a major support for web-based applications. Databases and related tables are the main component of many websites and applications as the data is stored and exchanged over the web. In order to access MySQL databases from a web server, we use various modules in Python such as PyMySQL, mysql.connector, etc. "
},
{
"code": null,
"e": 26735,
"s": 26529,
"text": "In this article, we are going to find duplicate values in a specific MySQL table in a Database. First, we are going to connect to a database having a MySQL table. The SQL query that is going to be used is:"
},
{
"code": null,
"e": 26817,
"s": 26735,
"text": "SELECT * FROM table-name \nGROUP BY col_1, col_2,..., col_n \nHAVING COUNT(*) > 1;\n"
},
{
"code": null,
"e": 26887,
"s": 26817,
"text": "If the table has a primary key then the below query can also be used:"
},
{
"code": null,
"e": 26955,
"s": 26887,
"text": "SELECT * FROM table-name \nGROUP BY primar-key\nHAVING COUNT(*) > 1;\n"
},
{
"code": null,
"e": 27068,
"s": 26955,
"text": "The above queries will generate only duplicate rows in a table, and then these rows will be displayed as output."
},
{
"code": null,
"e": 27175,
"s": 27068,
"text": "Below are some programs which depict how to find duplicate values in a specific MySQL table in a Database:"
},
{
"code": null,
"e": 27185,
"s": 27175,
"text": "Example 1"
},
{
"code": null,
"e": 27283,
"s": 27185,
"text": "Below is the table Documentary in database geek which is going to be accessed by a Python script:"
},
{
"code": null,
"e": 27350,
"s": 27283,
"text": "Below is the program to get the duplicate rows in the MySQL table:"
},
{
"code": null,
"e": 27358,
"s": 27350,
"text": "Python3"
},
{
"code": "# import required moduleimport mysql.connector # connect python with mysql with your hostname, # database, user and passworddb = mysql.connector.connect(host='localhost', database='gfg', user='root', password='') # create cursor objectcursor = db.cursor() # get the sum of rows of a columncursor.execute(\"SELECT * FROM Documentary \\ GROUP BY Name, Production \\ HAVING COUNT(*) > 1;\") # fetch duplicate rows and display themprint('Duplicate Rows:') for row in cursor.fetchall(): print(row) # terminate connectiondb.close()",
"e": 28011,
"s": 27358,
"text": null
},
{
"code": null,
"e": 28019,
"s": 28011,
"text": "Output:"
},
{
"code": null,
"e": 28030,
"s": 28019,
"text": "Example 2:"
},
{
"code": null,
"e": 28151,
"s": 28030,
"text": "Here is another example to find the duplicate rows from a table in a given database, below is the table scheme and rows:"
},
{
"code": null,
"e": 28392,
"s": 28151,
"text": "As we can see the Roll attribute is the primary key of the Student table, hence it only can be used with the GROUP BY statement in the query to generate the duplicate rows, below is the python script to get row count from the table Student:"
},
{
"code": null,
"e": 28400,
"s": 28392,
"text": "Python3"
},
{
"code": "# import required moduleimport mysql.connector # connect python with mysql with your hostname, # database, user and passworddb = mysql.connector.connect(host='localhost', database='gfg', user='root', password='') # create cursor objectcursor = db.cursor() # get the sum of rows of a columncursor.execute(\"SELECT * FROM Student \\ GROUP BY Roll \\ HAVING COUNT(*) > 1;\") # fetch duplicate rows and display themprint('Duplicate Rows:') for row in cursor.fetchall(): print(row) # terminate connectiondb.close()",
"e": 29037,
"s": 28400,
"text": null
},
{
"code": null,
"e": 29046,
"s": 29037,
"text": "Output: "
},
{
"code": null,
"e": 29059,
"s": 29046,
"text": "Python-mySQL"
},
{
"code": null,
"e": 29083,
"s": 29059,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 29090,
"s": 29083,
"text": "Python"
},
{
"code": null,
"e": 29109,
"s": 29090,
"text": "Technical Scripter"
},
{
"code": null,
"e": 29207,
"s": 29109,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29225,
"s": 29207,
"text": "Python Dictionary"
},
{
"code": null,
"e": 29257,
"s": 29225,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29279,
"s": 29257,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 29321,
"s": 29279,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 29347,
"s": 29321,
"text": "Python String | replace()"
},
{
"code": null,
"e": 29376,
"s": 29347,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 29413,
"s": 29376,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 29455,
"s": 29413,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 29497,
"s": 29455,
"text": "Check if element exists in list in Python"
}
] |
ML | Adjusted R-Square in Regression Analysis - GeeksforGeeks | 29 Sep, 2021
Prerequisite: Linear Regression, R-square in Regression
Why Adjusted-R Square Test: R-square test is used to determine the goodness of fit in regression analysis. Goodness of fit implies how better regression model is fitted to the data points. More is the value of r-square near to 1, better is the model. But the problem lies in the fact that the value of r-square always increases as new variables(attributes) are added to the model, no matter that the newly added attributes have a positive impact on the model or not. also, it can lead to overfitting of the model if there are large no. of variables.Adjusted r-square is a modified form of r-square whose value increases if new predictors tend to improve model’s performance and decreases if new predictors do not improve performance as expected.
For better understanding consider :
Average Fitted Line
Best Fitted Line :
R-square formula:
Clearly, SStot is always fixed for some data points if new predictors are added to the model, but value of SSres decreases as model tries to find some correlations from the added predictors. Hence, r-square’s value always increases.
Adjusted R-Square :
Adjusted R-Square
Here, k is the no. of regressors and n is the sample size. if the newly added variable is good enough to improve model’s performance, then it will overwhelm the decrease due to k. Otherwise, an increase in k will decrease adjusted r-square value.
Example-
Case #1:
Python3
import pandas as pdimport numpy as np # Download dataset and add complete path of the dataset.# Importing datasets = pd.read_csv('Salary_Data.csv') # Used to standardise statsmodel in pythonf = np.ones((30, 1))s.insert(0, 'extra', f) # Gives summary of data model->gives value of r-square and adjusted r-squareimport statsmodels.formula.api as smX_opt = s.iloc[:, :-1]Y1 = s.iloc[:, -1] regressor_OLS = sm.OLS(endog = Y1, exog = X_opt).fit()regressor_OLS.summary()
Output :
Summary Table
Case #2:
Python3
import pandas as pdimport numpy as np # Download dataset and add complete path of the dataset.# Importing datasets = pd.read_csv('Salary_Data.csv') # Used to standarise statsmodel in pythonf = np.ones((30, 1))s.insert(0, 'extra', f) # Inserting a new column to dataset having employee idsg =[]for i in range(1, 31): g.append(i) s.insert(2, 'Id', g) # Gives summary of data model->gives value of r-square and adjusted r-squareimport statsmodels.formula.api as smX_opt = s.iloc[:, :-1]Y1 = s.iloc[:, -1] regressor_OLS = sm.OLS(endog = Y1, exog = X_opt).fit()regressor_OLS.summary()
Output :
Summary Table
Explanation – R-square value and adjusted r-square value 0.957, 0.955 respectively. But when an attribute Id is added, which is an irrelevant attribute, gives r-square and adjusted r-square equal to 0.958, 0.954 respectively.
Hence on adding an irrelevant attribute in the dataset, the value of r-square increases(from 0.957 to 0.958). But value of adjusted r-square decreases(from 0.955 to 0.954).
shubham_singh
abhishek0719kadiyan
sooda367
Regression
Machine Learning
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Reinforcement learning
Decision Tree
Activation functions in Neural Networks
Decision Tree Introduction with example
Introduction to Recurrent Neural Network
Support Vector Machine Algorithm
Python | Decision tree implementation
ML | Underfitting and Overfitting
Search Algorithms in AI
Clustering in Machine Learning | [
{
"code": null,
"e": 25929,
"s": 25901,
"text": "\n29 Sep, 2021"
},
{
"code": null,
"e": 25985,
"s": 25929,
"text": "Prerequisite: Linear Regression, R-square in Regression"
},
{
"code": null,
"e": 26731,
"s": 25985,
"text": "Why Adjusted-R Square Test: R-square test is used to determine the goodness of fit in regression analysis. Goodness of fit implies how better regression model is fitted to the data points. More is the value of r-square near to 1, better is the model. But the problem lies in the fact that the value of r-square always increases as new variables(attributes) are added to the model, no matter that the newly added attributes have a positive impact on the model or not. also, it can lead to overfitting of the model if there are large no. of variables.Adjusted r-square is a modified form of r-square whose value increases if new predictors tend to improve model’s performance and decreases if new predictors do not improve performance as expected."
},
{
"code": null,
"e": 26768,
"s": 26731,
"text": "For better understanding consider : "
},
{
"code": null,
"e": 26789,
"s": 26768,
"text": "Average Fitted Line "
},
{
"code": null,
"e": 26809,
"s": 26789,
"text": "Best Fitted Line : "
},
{
"code": null,
"e": 26829,
"s": 26809,
"text": "R-square formula: "
},
{
"code": null,
"e": 27062,
"s": 26829,
"text": "Clearly, SStot is always fixed for some data points if new predictors are added to the model, but value of SSres decreases as model tries to find some correlations from the added predictors. Hence, r-square’s value always increases."
},
{
"code": null,
"e": 27084,
"s": 27062,
"text": "Adjusted R-Square : "
},
{
"code": null,
"e": 27102,
"s": 27084,
"text": "Adjusted R-Square"
},
{
"code": null,
"e": 27349,
"s": 27102,
"text": "Here, k is the no. of regressors and n is the sample size. if the newly added variable is good enough to improve model’s performance, then it will overwhelm the decrease due to k. Otherwise, an increase in k will decrease adjusted r-square value."
},
{
"code": null,
"e": 27358,
"s": 27349,
"text": "Example-"
},
{
"code": null,
"e": 27369,
"s": 27358,
"text": "Case #1: "
},
{
"code": null,
"e": 27377,
"s": 27369,
"text": "Python3"
},
{
"code": "import pandas as pdimport numpy as np # Download dataset and add complete path of the dataset.# Importing datasets = pd.read_csv('Salary_Data.csv') # Used to standardise statsmodel in pythonf = np.ones((30, 1))s.insert(0, 'extra', f) # Gives summary of data model->gives value of r-square and adjusted r-squareimport statsmodels.formula.api as smX_opt = s.iloc[:, :-1]Y1 = s.iloc[:, -1] regressor_OLS = sm.OLS(endog = Y1, exog = X_opt).fit()regressor_OLS.summary()",
"e": 27844,
"s": 27377,
"text": null
},
{
"code": null,
"e": 27854,
"s": 27844,
"text": "Output : "
},
{
"code": null,
"e": 27868,
"s": 27854,
"text": "Summary Table"
},
{
"code": null,
"e": 27879,
"s": 27868,
"text": "Case #2: "
},
{
"code": null,
"e": 27887,
"s": 27879,
"text": "Python3"
},
{
"code": "import pandas as pdimport numpy as np # Download dataset and add complete path of the dataset.# Importing datasets = pd.read_csv('Salary_Data.csv') # Used to standarise statsmodel in pythonf = np.ones((30, 1))s.insert(0, 'extra', f) # Inserting a new column to dataset having employee idsg =[]for i in range(1, 31): g.append(i) s.insert(2, 'Id', g) # Gives summary of data model->gives value of r-square and adjusted r-squareimport statsmodels.formula.api as smX_opt = s.iloc[:, :-1]Y1 = s.iloc[:, -1] regressor_OLS = sm.OLS(endog = Y1, exog = X_opt).fit()regressor_OLS.summary()",
"e": 28473,
"s": 27887,
"text": null
},
{
"code": null,
"e": 28483,
"s": 28473,
"text": "Output : "
},
{
"code": null,
"e": 28497,
"s": 28483,
"text": "Summary Table"
},
{
"code": null,
"e": 28724,
"s": 28497,
"text": "Explanation – R-square value and adjusted r-square value 0.957, 0.955 respectively. But when an attribute Id is added, which is an irrelevant attribute, gives r-square and adjusted r-square equal to 0.958, 0.954 respectively. "
},
{
"code": null,
"e": 28898,
"s": 28724,
"text": "Hence on adding an irrelevant attribute in the dataset, the value of r-square increases(from 0.957 to 0.958). But value of adjusted r-square decreases(from 0.955 to 0.954). "
},
{
"code": null,
"e": 28912,
"s": 28898,
"text": "shubham_singh"
},
{
"code": null,
"e": 28932,
"s": 28912,
"text": "abhishek0719kadiyan"
},
{
"code": null,
"e": 28941,
"s": 28932,
"text": "sooda367"
},
{
"code": null,
"e": 28952,
"s": 28941,
"text": "Regression"
},
{
"code": null,
"e": 28969,
"s": 28952,
"text": "Machine Learning"
},
{
"code": null,
"e": 28986,
"s": 28969,
"text": "Machine Learning"
},
{
"code": null,
"e": 29084,
"s": 28986,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29107,
"s": 29084,
"text": "Reinforcement learning"
},
{
"code": null,
"e": 29121,
"s": 29107,
"text": "Decision Tree"
},
{
"code": null,
"e": 29161,
"s": 29121,
"text": "Activation functions in Neural Networks"
},
{
"code": null,
"e": 29201,
"s": 29161,
"text": "Decision Tree Introduction with example"
},
{
"code": null,
"e": 29242,
"s": 29201,
"text": "Introduction to Recurrent Neural Network"
},
{
"code": null,
"e": 29275,
"s": 29242,
"text": "Support Vector Machine Algorithm"
},
{
"code": null,
"e": 29313,
"s": 29275,
"text": "Python | Decision tree implementation"
},
{
"code": null,
"e": 29347,
"s": 29313,
"text": "ML | Underfitting and Overfitting"
},
{
"code": null,
"e": 29371,
"s": 29347,
"text": "Search Algorithms in AI"
}
] |
Java Program to Convert Array To Vector - GeeksforGeeks | 07 Jan, 2021
Array is a group of like-typed variables that are referred to by a common name. Java arrays can be both types namely primitive data types or object (or non-primitive) reference of a class. In the case of primitive data types, the actual values are stored in contiguous memory locations, while in the case of objects of a class, the actual objects are stored in a heap segment.
Vector class implements a growable array of objects. It is compatible with Java collections. Vector implements a dynamic array–means it can grow or shrink as required. It contains components that can be accessed using an integer index like an array.
There are 3 ways to convert an array to a vector in Java.
Using Collections.addAll methodUsing Arrays.asList() methodUsing loop
Using Collections.addAll method
Using Arrays.asList() method
Using loop
Method 1: Using Collections.addAll method
Syntax:
public static boolean addAll(Collection c, T... elements)
Parameters: This method takes the following argument as a parameter
c- the collection into which elements are to be inserted
elements- the elements to insert into c
Return Value: This method returns true if the collection changed as a result of the call.
Example: Make an array and an empty vector, pass the filled array and empty vector in the method and the vector will be filled with the array element.
Java
// Java program to Convert Array To Vector // Using Collections.addAll() method import java.util.*; public class array_to_vector { public static void main(String[] args) { String[] arr = { "I", "love", "geeks", "for", "geeks" }; // create a new vector object of the same type Vector<String> v = new Vector<String>(); // Use the addAll method of the Collections to add // all array elements to the vector object Collections.addAll(v, arr); System.out.println("The vector is"); // printing vector System.out.println(v); }}
The vector is
[I, love, geeks, for, geeks]
Method 2: Using Arrays.asList() method
Syntax:
public static List asList(T... a)
Parameters: This method takes the array a which is required to be converted into a List.
Example: The Vector constructor can take a List object and convert it to a vector. So, convert the array to the List and pass it to the vector constructor.
Java
// Java program to Convert Array To Vector // Using Arrays.asList() method import java.util.*; public class array_to_vector { public static void main(String[] args) { String[] arr = { "I", "love", "geeks", "for", "geeks" }; // create a new vector object of the same type Vector<String> v = new Vector<String>(Arrays.asList(arr)); System.out.println("The vector is"); // printing vector System.out.println(v); }}
The vector is
[I, love, geeks, for, geeks]
Method 3: Using loop
Example: Loop through each element of the array and add that element one by one in the vector.
Java
// Java program to Convert Array To Vector // Using simple iteration method import java.util.*; public class array_to_vector { public static void main(String[] args) { String[] arr = { "I", "love", "geeks", "for", "geeks" }; // create a new vector object of the same type Vector<String> v = new Vector<String>(); for (int i = 0; i < arr.length; i++) v.addElement(arr[i]); System.out.println("The vector is"); // printing vector System.out.println(v); }}
The vector is
[I, love, geeks, for, geeks]
Java-Arrays
Java-Vector
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
Program to print ASCII Value of a character | [
{
"code": null,
"e": 25225,
"s": 25197,
"text": "\n07 Jan, 2021"
},
{
"code": null,
"e": 25602,
"s": 25225,
"text": "Array is a group of like-typed variables that are referred to by a common name. Java arrays can be both types namely primitive data types or object (or non-primitive) reference of a class. In the case of primitive data types, the actual values are stored in contiguous memory locations, while in the case of objects of a class, the actual objects are stored in a heap segment."
},
{
"code": null,
"e": 25852,
"s": 25602,
"text": "Vector class implements a growable array of objects. It is compatible with Java collections. Vector implements a dynamic array–means it can grow or shrink as required. It contains components that can be accessed using an integer index like an array."
},
{
"code": null,
"e": 25910,
"s": 25852,
"text": "There are 3 ways to convert an array to a vector in Java."
},
{
"code": null,
"e": 25980,
"s": 25910,
"text": "Using Collections.addAll methodUsing Arrays.asList() methodUsing loop"
},
{
"code": null,
"e": 26012,
"s": 25980,
"text": "Using Collections.addAll method"
},
{
"code": null,
"e": 26041,
"s": 26012,
"text": "Using Arrays.asList() method"
},
{
"code": null,
"e": 26052,
"s": 26041,
"text": "Using loop"
},
{
"code": null,
"e": 26094,
"s": 26052,
"text": "Method 1: Using Collections.addAll method"
},
{
"code": null,
"e": 26102,
"s": 26094,
"text": "Syntax:"
},
{
"code": null,
"e": 26160,
"s": 26102,
"text": "public static boolean addAll(Collection c, T... elements)"
},
{
"code": null,
"e": 26228,
"s": 26160,
"text": "Parameters: This method takes the following argument as a parameter"
},
{
"code": null,
"e": 26285,
"s": 26228,
"text": "c- the collection into which elements are to be inserted"
},
{
"code": null,
"e": 26325,
"s": 26285,
"text": "elements- the elements to insert into c"
},
{
"code": null,
"e": 26415,
"s": 26325,
"text": "Return Value: This method returns true if the collection changed as a result of the call."
},
{
"code": null,
"e": 26566,
"s": 26415,
"text": "Example: Make an array and an empty vector, pass the filled array and empty vector in the method and the vector will be filled with the array element."
},
{
"code": null,
"e": 26571,
"s": 26566,
"text": "Java"
},
{
"code": "// Java program to Convert Array To Vector // Using Collections.addAll() method import java.util.*; public class array_to_vector { public static void main(String[] args) { String[] arr = { \"I\", \"love\", \"geeks\", \"for\", \"geeks\" }; // create a new vector object of the same type Vector<String> v = new Vector<String>(); // Use the addAll method of the Collections to add // all array elements to the vector object Collections.addAll(v, arr); System.out.println(\"The vector is\"); // printing vector System.out.println(v); }}",
"e": 27207,
"s": 26571,
"text": null
},
{
"code": null,
"e": 27250,
"s": 27207,
"text": "The vector is\n[I, love, geeks, for, geeks]"
},
{
"code": null,
"e": 27289,
"s": 27250,
"text": "Method 2: Using Arrays.asList() method"
},
{
"code": null,
"e": 27298,
"s": 27289,
"text": "Syntax: "
},
{
"code": null,
"e": 27332,
"s": 27298,
"text": "public static List asList(T... a)"
},
{
"code": null,
"e": 27421,
"s": 27332,
"text": "Parameters: This method takes the array a which is required to be converted into a List."
},
{
"code": null,
"e": 27577,
"s": 27421,
"text": "Example: The Vector constructor can take a List object and convert it to a vector. So, convert the array to the List and pass it to the vector constructor."
},
{
"code": null,
"e": 27582,
"s": 27577,
"text": "Java"
},
{
"code": "// Java program to Convert Array To Vector // Using Arrays.asList() method import java.util.*; public class array_to_vector { public static void main(String[] args) { String[] arr = { \"I\", \"love\", \"geeks\", \"for\", \"geeks\" }; // create a new vector object of the same type Vector<String> v = new Vector<String>(Arrays.asList(arr)); System.out.println(\"The vector is\"); // printing vector System.out.println(v); }}",
"e": 28063,
"s": 27582,
"text": null
},
{
"code": null,
"e": 28106,
"s": 28063,
"text": "The vector is\n[I, love, geeks, for, geeks]"
},
{
"code": null,
"e": 28127,
"s": 28106,
"text": "Method 3: Using loop"
},
{
"code": null,
"e": 28222,
"s": 28127,
"text": "Example: Loop through each element of the array and add that element one by one in the vector."
},
{
"code": null,
"e": 28227,
"s": 28222,
"text": "Java"
},
{
"code": "// Java program to Convert Array To Vector // Using simple iteration method import java.util.*; public class array_to_vector { public static void main(String[] args) { String[] arr = { \"I\", \"love\", \"geeks\", \"for\", \"geeks\" }; // create a new vector object of the same type Vector<String> v = new Vector<String>(); for (int i = 0; i < arr.length; i++) v.addElement(arr[i]); System.out.println(\"The vector is\"); // printing vector System.out.println(v); }}",
"e": 28770,
"s": 28227,
"text": null
},
{
"code": null,
"e": 28813,
"s": 28770,
"text": "The vector is\n[I, love, geeks, for, geeks]"
},
{
"code": null,
"e": 28825,
"s": 28813,
"text": "Java-Arrays"
},
{
"code": null,
"e": 28837,
"s": 28825,
"text": "Java-Vector"
},
{
"code": null,
"e": 28844,
"s": 28837,
"text": "Picked"
},
{
"code": null,
"e": 28849,
"s": 28844,
"text": "Java"
},
{
"code": null,
"e": 28863,
"s": 28849,
"text": "Java Programs"
},
{
"code": null,
"e": 28868,
"s": 28863,
"text": "Java"
},
{
"code": null,
"e": 28966,
"s": 28868,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28981,
"s": 28966,
"text": "Stream In Java"
},
{
"code": null,
"e": 29002,
"s": 28981,
"text": "Constructors in Java"
},
{
"code": null,
"e": 29021,
"s": 29002,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 29051,
"s": 29021,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 29097,
"s": 29051,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 29123,
"s": 29097,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 29157,
"s": 29123,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 29204,
"s": 29157,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 29236,
"s": 29204,
"text": "How to Iterate HashMap in Java?"
}
] |
Solidity - Basics of Contracts - GeeksforGeeks | 11 May, 2022
Solidity Contracts are like a class in any other object-oriented programming language. They firmly contain data as state variables and functions which can modify these variables. When a function is called on a different instance (contract), the EVM function call happens and the context is switched in such a way that the state variables are inaccessible. A contract or its function needs to be called for anything to happen. Some basic properties of contracts are as follows :
Constructor: Special method created using the constructor keyword, which is invoked only once when the contract is created.
State Variables: These are the variables that are used to store the state of the contract.
Functions: Functions are used to manipulate the state of the contracts by modifying the state variables.
Creating contracts programmatically is generally done by using JavaScript API web3.js, which has a built-in function web3.eth.Contract to create the contracts. When a contract is created its constructor is executed, a constructor is an optional special method defined by using the constructor keyword which executes one per contract. Once the constructor is called the final code of the contract is added to the blockchain.
Syntax:
contract <contract_name>{
constructor() <visibility>{
.......
}
// rest code
}
Example: In the below example, the contract Test is created to demonstrate how to create a contract in Solidity.
Solidity
// Solidity program to demonstrate // how to create a contractpragma solidity ^0.4.23; // Creating a contractcontract Test { // Declaring variable string str; // Defining a constructor constructor(string str_in){ str = str_in; } // Defining a function to // return value of variable 'str' function str_out( ) public view returns(string memory){ return str; }}
Output :
Solidity provides four types of visibilities for functions and state variables. Functions have to specified by any of the four visibilities but for state variables external is not allowed.
External: External functions are can be called by other contracts via transactions. An external function cannot be called internally. For calling an external function within the contract this.function_name() method is used. Sometimes external functions are more efficient when they have large arrays of data.Public: Public functions or variables can be called both externally or internally via messages. For public static variables, a getter method is created automatically in solidity.Internal: These functions or variables can be accessed only internally i.e. within the contract or the derived contracts.Private: These functions or variables can only be visible for the contracts in which they are defined. They are not accessible to derived contracts also.
External: External functions are can be called by other contracts via transactions. An external function cannot be called internally. For calling an external function within the contract this.function_name() method is used. Sometimes external functions are more efficient when they have large arrays of data.
Public: Public functions or variables can be called both externally or internally via messages. For public static variables, a getter method is created automatically in solidity.
Internal: These functions or variables can be accessed only internally i.e. within the contract or the derived contracts.
Private: These functions or variables can only be visible for the contracts in which they are defined. They are not accessible to derived contracts also.
Example: In the below example, the contract contract_example is created to demonstrate different visibility modifiers discussed above.
Solidity
// Solidity program to demonstrate // visibility modifierspragma solidity ^0.5.0; // Creating a contractcontract contract_example { // Declaring private // state variable uint private num1; // Declaring public // state variable uint public num2; // Declaring Internal // state variable string internal str; // Defining a constructor constructor() public { num2 = 10; } // Defining a private function function increment( uint data1) private pure returns( uint) { return data1 + 1; } // Defining public functions function updateValue( uint data1) public { num1 = data1; } function getValue( ) public view returns( uint) { return num1; } // Declaring public functions function setStr( string memory _str) public; function getStr( ) public returns (string memory); } // Child contract inheriting // from the parent contract // 'contract_example' contract derived_contract is contract_example{ // Defining public function of // parent contract function setStr( string memory _str) public{ str = _str; } // Defining public function // of parent contract function getStr( ) public returns ( string memory){ return str; }} //External Contractcontract D { // Defining a public function to create // an object of child contract access the // functions from child and parent contract function readData( ) public payable returns( string memory, uint) { contract_example c = new derived_contract(); c.setStr("GeeksForGeeks"); c.updateValue(16); return (c.getStr(), c.getValue()); }}
Output :
Blockchain
Solidity
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Storage vs Memory in Solidity
Ethereum Blockchain - Getting Free Test Ethers For Rinkeby Test Network
How to connect ReactJS with MetaMask ?
How to Become a Blockchain Developer?
Proof of Work (PoW) Consensus
Storage vs Memory in Solidity
Solidity - Inheritance
Mathematical Operations in Solidity
Dynamic Arrays and its Operations in Solidity
Solidity - View and Pure Functions | [
{
"code": null,
"e": 25605,
"s": 25577,
"text": "\n11 May, 2022"
},
{
"code": null,
"e": 26083,
"s": 25605,
"text": "Solidity Contracts are like a class in any other object-oriented programming language. They firmly contain data as state variables and functions which can modify these variables. When a function is called on a different instance (contract), the EVM function call happens and the context is switched in such a way that the state variables are inaccessible. A contract or its function needs to be called for anything to happen. Some basic properties of contracts are as follows :"
},
{
"code": null,
"e": 26207,
"s": 26083,
"text": "Constructor: Special method created using the constructor keyword, which is invoked only once when the contract is created."
},
{
"code": null,
"e": 26298,
"s": 26207,
"text": "State Variables: These are the variables that are used to store the state of the contract."
},
{
"code": null,
"e": 26403,
"s": 26298,
"text": "Functions: Functions are used to manipulate the state of the contracts by modifying the state variables."
},
{
"code": null,
"e": 26827,
"s": 26403,
"text": "Creating contracts programmatically is generally done by using JavaScript API web3.js, which has a built-in function web3.eth.Contract to create the contracts. When a contract is created its constructor is executed, a constructor is an optional special method defined by using the constructor keyword which executes one per contract. Once the constructor is called the final code of the contract is added to the blockchain."
},
{
"code": null,
"e": 26835,
"s": 26827,
"text": "Syntax:"
},
{
"code": null,
"e": 26936,
"s": 26835,
"text": "contract <contract_name>{\n\n constructor() <visibility>{\n .......\n }\n // rest code\n}\n"
},
{
"code": null,
"e": 27049,
"s": 26936,
"text": "Example: In the below example, the contract Test is created to demonstrate how to create a contract in Solidity."
},
{
"code": null,
"e": 27058,
"s": 27049,
"text": "Solidity"
},
{
"code": "// Solidity program to demonstrate // how to create a contractpragma solidity ^0.4.23; // Creating a contractcontract Test { // Declaring variable string str; // Defining a constructor constructor(string str_in){ str = str_in; } // Defining a function to // return value of variable 'str' function str_out( ) public view returns(string memory){ return str; }}",
"e": 27449,
"s": 27058,
"text": null
},
{
"code": null,
"e": 27459,
"s": 27449,
"text": "Output : "
},
{
"code": null,
"e": 27649,
"s": 27459,
"text": "Solidity provides four types of visibilities for functions and state variables. Functions have to specified by any of the four visibilities but for state variables external is not allowed. "
},
{
"code": null,
"e": 28410,
"s": 27649,
"text": "External: External functions are can be called by other contracts via transactions. An external function cannot be called internally. For calling an external function within the contract this.function_name() method is used. Sometimes external functions are more efficient when they have large arrays of data.Public: Public functions or variables can be called both externally or internally via messages. For public static variables, a getter method is created automatically in solidity.Internal: These functions or variables can be accessed only internally i.e. within the contract or the derived contracts.Private: These functions or variables can only be visible for the contracts in which they are defined. They are not accessible to derived contracts also."
},
{
"code": null,
"e": 28719,
"s": 28410,
"text": "External: External functions are can be called by other contracts via transactions. An external function cannot be called internally. For calling an external function within the contract this.function_name() method is used. Sometimes external functions are more efficient when they have large arrays of data."
},
{
"code": null,
"e": 28898,
"s": 28719,
"text": "Public: Public functions or variables can be called both externally or internally via messages. For public static variables, a getter method is created automatically in solidity."
},
{
"code": null,
"e": 29020,
"s": 28898,
"text": "Internal: These functions or variables can be accessed only internally i.e. within the contract or the derived contracts."
},
{
"code": null,
"e": 29174,
"s": 29020,
"text": "Private: These functions or variables can only be visible for the contracts in which they are defined. They are not accessible to derived contracts also."
},
{
"code": null,
"e": 29309,
"s": 29174,
"text": "Example: In the below example, the contract contract_example is created to demonstrate different visibility modifiers discussed above."
},
{
"code": null,
"e": 29318,
"s": 29309,
"text": "Solidity"
},
{
"code": "// Solidity program to demonstrate // visibility modifierspragma solidity ^0.5.0; // Creating a contractcontract contract_example { // Declaring private // state variable uint private num1; // Declaring public // state variable uint public num2; // Declaring Internal // state variable string internal str; // Defining a constructor constructor() public { num2 = 10; } // Defining a private function function increment( uint data1) private pure returns( uint) { return data1 + 1; } // Defining public functions function updateValue( uint data1) public { num1 = data1; } function getValue( ) public view returns( uint) { return num1; } // Declaring public functions function setStr( string memory _str) public; function getStr( ) public returns (string memory); } // Child contract inheriting // from the parent contract // 'contract_example' contract derived_contract is contract_example{ // Defining public function of // parent contract function setStr( string memory _str) public{ str = _str; } // Defining public function // of parent contract function getStr( ) public returns ( string memory){ return str; }} //External Contractcontract D { // Defining a public function to create // an object of child contract access the // functions from child and parent contract function readData( ) public payable returns( string memory, uint) { contract_example c = new derived_contract(); c.setStr(\"GeeksForGeeks\"); c.updateValue(16); return (c.getStr(), c.getValue()); }}",
"e": 30976,
"s": 29318,
"text": null
},
{
"code": null,
"e": 30987,
"s": 30976,
"text": "Output : "
},
{
"code": null,
"e": 31000,
"s": 30989,
"text": "Blockchain"
},
{
"code": null,
"e": 31009,
"s": 31000,
"text": "Solidity"
},
{
"code": null,
"e": 31107,
"s": 31009,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31137,
"s": 31107,
"text": "Storage vs Memory in Solidity"
},
{
"code": null,
"e": 31209,
"s": 31137,
"text": "Ethereum Blockchain - Getting Free Test Ethers For Rinkeby Test Network"
},
{
"code": null,
"e": 31248,
"s": 31209,
"text": "How to connect ReactJS with MetaMask ?"
},
{
"code": null,
"e": 31286,
"s": 31248,
"text": "How to Become a Blockchain Developer?"
},
{
"code": null,
"e": 31316,
"s": 31286,
"text": "Proof of Work (PoW) Consensus"
},
{
"code": null,
"e": 31346,
"s": 31316,
"text": "Storage vs Memory in Solidity"
},
{
"code": null,
"e": 31369,
"s": 31346,
"text": "Solidity - Inheritance"
},
{
"code": null,
"e": 31405,
"s": 31369,
"text": "Mathematical Operations in Solidity"
},
{
"code": null,
"e": 31451,
"s": 31405,
"text": "Dynamic Arrays and its Operations in Solidity"
}
] |
How to find the index of all occurrence of elements in an array using JavaScript ? - GeeksforGeeks | 20 Nov, 2019
Given an array containing array elements and the task is to find all occurrence of an element from the array. We are going to do that with the help of JavaScript.
Approach 1: Declare an empty array which stores the indexes of all occurrence of the array element. Visit the array elements one by one using while loop and if the array elements match with the given element then push the index of element into an array. After visiting each element of the array, return the array of indexes.
Example: This example implements the above approach.
<!DOCTYPE HTML> <html> <head> <title> How to find the index of all occurrences of element in an array using JavaScript? </title></head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 15px; font-weight: bold;"> </p> <button onclick = "GFG_Fun()"> Click Here </button> <p id = "GFG_DOWN" style = "color:green; font-size: 20px; font-weight: bold;"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); var arr = [ 'GFG', 'Geeks', 'Portal', 'Computer Science', 'GFG', 'GFG', 'Geek' ]; var elm = 'GFG'; up.innerHTML = "Click on the button to find " + "the position of element in " + "array.<br><br>Array = [" + arr + "]<br>" + "Element - '" + elm + "'"; function getInd(arr, val) { var index = [], i = -1; while ((i = arr.indexOf(val, i+1)) != -1){ index.push(i); } return index; } function GFG_Fun() { down.innerHTML = getInd(arr, elm); } </script> </body> </html>
Output:
Before clicking on the button:
After clicking on the button:
Approach 2: Visit the array elements one by one using reduce() method and if the array elements matches with the given element then push the index into the array. After visiting each element of the array, return the array of indexes.
Example: This example uses reduce() method to find the index of all occurrence of elements in an array.
<!DOCTYPE HTML> <html> <head> <title> How to find the index of all occurrences of element in an array using JavaScript? </title></head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 15px; font-weight: bold;"> </p> <button onclick = "GFG_Fun()"> Click Here </button> <p id = "GFG_DOWN" style = "color:green; font-size: 20px; font-weight: bold;"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); var arr = [ 'GFG', 'Geeks', 'Portal', 'Computer Science', 'GFG', 'GFG', 'Geek' ]; var elm = 'GFG'; up.innerHTML = "Click on the button to " + "find the position of element" + " in array.<br><br>Array = [" + arr + "]<br>" + "Element - '" + elm + "'"; function GFG_Fun() { down.innerHTML = arr.reduce(function(ind, el, i) { if (el === 'GFG') ind.push(i); return ind; }, []); } </script> </body> </html>
Output:
Before clicking on the button:
After clicking on the button:
nidhi_biet
javascript-array
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Difference Between PUT and PATCH Request
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 25913,
"s": 25885,
"text": "\n20 Nov, 2019"
},
{
"code": null,
"e": 26076,
"s": 25913,
"text": "Given an array containing array elements and the task is to find all occurrence of an element from the array. We are going to do that with the help of JavaScript."
},
{
"code": null,
"e": 26401,
"s": 26076,
"text": "Approach 1: Declare an empty array which stores the indexes of all occurrence of the array element. Visit the array elements one by one using while loop and if the array elements match with the given element then push the index of element into an array. After visiting each element of the array, return the array of indexes."
},
{
"code": null,
"e": 26454,
"s": 26401,
"text": "Example: This example implements the above approach."
},
{
"code": "<!DOCTYPE HTML> <html> <head> <title> How to find the index of all occurrences of element in an array using JavaScript? </title></head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 15px; font-weight: bold;\"> </p> <button onclick = \"GFG_Fun()\"> Click Here </button> <p id = \"GFG_DOWN\" style = \"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); var arr = [ 'GFG', 'Geeks', 'Portal', 'Computer Science', 'GFG', 'GFG', 'Geek' ]; var elm = 'GFG'; up.innerHTML = \"Click on the button to find \" + \"the position of element in \" + \"array.<br><br>Array = [\" + arr + \"]<br>\" + \"Element - '\" + elm + \"'\"; function getInd(arr, val) { var index = [], i = -1; while ((i = arr.indexOf(val, i+1)) != -1){ index.push(i); } return index; } function GFG_Fun() { down.innerHTML = getInd(arr, elm); } </script> </body> </html>",
"e": 27863,
"s": 26454,
"text": null
},
{
"code": null,
"e": 27871,
"s": 27863,
"text": "Output:"
},
{
"code": null,
"e": 27902,
"s": 27871,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 27932,
"s": 27902,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 28166,
"s": 27932,
"text": "Approach 2: Visit the array elements one by one using reduce() method and if the array elements matches with the given element then push the index into the array. After visiting each element of the array, return the array of indexes."
},
{
"code": null,
"e": 28270,
"s": 28166,
"text": "Example: This example uses reduce() method to find the index of all occurrence of elements in an array."
},
{
"code": "<!DOCTYPE HTML> <html> <head> <title> How to find the index of all occurrences of element in an array using JavaScript? </title></head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 15px; font-weight: bold;\"> </p> <button onclick = \"GFG_Fun()\"> Click Here </button> <p id = \"GFG_DOWN\" style = \"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); var arr = [ 'GFG', 'Geeks', 'Portal', 'Computer Science', 'GFG', 'GFG', 'Geek' ]; var elm = 'GFG'; up.innerHTML = \"Click on the button to \" + \"find the position of element\" + \" in array.<br><br>Array = [\" + arr + \"]<br>\" + \"Element - '\" + elm + \"'\"; function GFG_Fun() { down.innerHTML = arr.reduce(function(ind, el, i) { if (el === 'GFG') ind.push(i); return ind; }, []); } </script> </body> </html>",
"e": 29616,
"s": 28270,
"text": null
},
{
"code": null,
"e": 29624,
"s": 29616,
"text": "Output:"
},
{
"code": null,
"e": 29655,
"s": 29624,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 29685,
"s": 29655,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 29696,
"s": 29685,
"text": "nidhi_biet"
},
{
"code": null,
"e": 29713,
"s": 29696,
"text": "javascript-array"
},
{
"code": null,
"e": 29724,
"s": 29713,
"text": "JavaScript"
},
{
"code": null,
"e": 29741,
"s": 29724,
"text": "Web Technologies"
},
{
"code": null,
"e": 29768,
"s": 29741,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 29866,
"s": 29768,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29906,
"s": 29866,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29951,
"s": 29906,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 30012,
"s": 29951,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 30084,
"s": 30012,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 30125,
"s": 30084,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 30165,
"s": 30125,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 30198,
"s": 30165,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 30243,
"s": 30198,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 30286,
"s": 30243,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
How to convert a Python datetime.datetime to excel serial date number - GeeksforGeeks | 06 Sep, 2021
This article will discuss the conversion of a python datetime.datetime to an excel serial date number. The Excel “serial date” format is actually the number of days since 1900-01-00. The strftime() function is used to convert date and time objects to their string representation. It takes one or more inputs of formatted code and returns the string representation.
Syntax:
strftime(format)
Parameters: This function accepts a parameter which is illustrated below:
format: This is the specified format code in which the given date and time object is going to be represented.
Return values: It returns the string representation of the date or time object.
Example 1: In the example below, the current date and time are being converted into the excel serial date number. And the returned output will be in the format of ’08/23/21 15:15:53′ which is accepted by Excel as a valid date/time and allows for sorting in Excel.
Python3
# Python3 code to illustrate the conversion of# datetime.datetime to excel serial date number # Importing datetime moduleimport datetime # Calling the now() function to return# current date and timecurrent_datetime = datetime.datetime.now() # Calling the strftime() function to convert# the above current datetime into excel serial date numberprint(current_datetime.strftime('%x %X'))
Output:
08/23/21 15:15:53
If we need the excel serial date number in the form of a date value, then this can be done using the toordinal() function.
Example 2: Serial number in a form of a date value
Python3
# Python3 code to illustrate the conversion of# datetime.datetime to excel serial date number # Importing date module from datetimefrom datetime import date # Taking the parameter from the calling functiondef convert_date_to_excel_ordinal(day, month, year): # Specifying offset value i.e., # the date value for the date of 1900-01-00 offset = 693594 current = date(year, month, day) # Calling the toordinal() function to get # the excel serial date number in the form # of date values n = current.toordinal() return (n - offset) # Calculating the excel serial date number# for the date "02-02-2021" by calling the# user defined function convert_date_to_excel_ordinal()print(convert_date_to_excel_ordinal(2, 2, 2021))
Output:
44229
Example: In the below example, the “2021-05-04” date is being converted into the excel serial date number with reference to the 1899-12-30 date.
Python3
# Python3 code to illustrate the conversion of# datetime.datetime to excel serial date number # Importing datetime modulefrom datetime import datetimeimport datetime as dt def excel_date(date1): # Initializing a reference date # Note that here date is not 31st Dec but 30th! temp = dt.datetime(1899, 12, 30) delta = date1 - temp return float(delta.days) + (float(delta.seconds) / 86400) # Calculating the excel serial date number# for the date "2021-05-04" by calling the# user defined function excel_date()print(excel_date(datetime(2021, 2, 4)))
Output:
44231.0
arorakashish0911
Picked
Python datetime-program
Python-datetime
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists | [
{
"code": null,
"e": 25381,
"s": 25353,
"text": "\n06 Sep, 2021"
},
{
"code": null,
"e": 25746,
"s": 25381,
"text": "This article will discuss the conversion of a python datetime.datetime to an excel serial date number. The Excel “serial date” format is actually the number of days since 1900-01-00. The strftime() function is used to convert date and time objects to their string representation. It takes one or more inputs of formatted code and returns the string representation."
},
{
"code": null,
"e": 25754,
"s": 25746,
"text": "Syntax:"
},
{
"code": null,
"e": 25771,
"s": 25754,
"text": "strftime(format)"
},
{
"code": null,
"e": 25845,
"s": 25771,
"text": "Parameters: This function accepts a parameter which is illustrated below:"
},
{
"code": null,
"e": 25955,
"s": 25845,
"text": "format: This is the specified format code in which the given date and time object is going to be represented."
},
{
"code": null,
"e": 26035,
"s": 25955,
"text": "Return values: It returns the string representation of the date or time object."
},
{
"code": null,
"e": 26299,
"s": 26035,
"text": "Example 1: In the example below, the current date and time are being converted into the excel serial date number. And the returned output will be in the format of ’08/23/21 15:15:53′ which is accepted by Excel as a valid date/time and allows for sorting in Excel."
},
{
"code": null,
"e": 26307,
"s": 26299,
"text": "Python3"
},
{
"code": "# Python3 code to illustrate the conversion of# datetime.datetime to excel serial date number # Importing datetime moduleimport datetime # Calling the now() function to return# current date and timecurrent_datetime = datetime.datetime.now() # Calling the strftime() function to convert# the above current datetime into excel serial date numberprint(current_datetime.strftime('%x %X'))",
"e": 26692,
"s": 26307,
"text": null
},
{
"code": null,
"e": 26700,
"s": 26692,
"text": "Output:"
},
{
"code": null,
"e": 26718,
"s": 26700,
"text": "08/23/21 15:15:53"
},
{
"code": null,
"e": 26841,
"s": 26718,
"text": "If we need the excel serial date number in the form of a date value, then this can be done using the toordinal() function."
},
{
"code": null,
"e": 26892,
"s": 26841,
"text": "Example 2: Serial number in a form of a date value"
},
{
"code": null,
"e": 26900,
"s": 26892,
"text": "Python3"
},
{
"code": "# Python3 code to illustrate the conversion of# datetime.datetime to excel serial date number # Importing date module from datetimefrom datetime import date # Taking the parameter from the calling functiondef convert_date_to_excel_ordinal(day, month, year): # Specifying offset value i.e., # the date value for the date of 1900-01-00 offset = 693594 current = date(year, month, day) # Calling the toordinal() function to get # the excel serial date number in the form # of date values n = current.toordinal() return (n - offset) # Calculating the excel serial date number# for the date \"02-02-2021\" by calling the# user defined function convert_date_to_excel_ordinal()print(convert_date_to_excel_ordinal(2, 2, 2021))",
"e": 27646,
"s": 26900,
"text": null
},
{
"code": null,
"e": 27654,
"s": 27646,
"text": "Output:"
},
{
"code": null,
"e": 27660,
"s": 27654,
"text": "44229"
},
{
"code": null,
"e": 27805,
"s": 27660,
"text": "Example: In the below example, the “2021-05-04” date is being converted into the excel serial date number with reference to the 1899-12-30 date."
},
{
"code": null,
"e": 27813,
"s": 27805,
"text": "Python3"
},
{
"code": "# Python3 code to illustrate the conversion of# datetime.datetime to excel serial date number # Importing datetime modulefrom datetime import datetimeimport datetime as dt def excel_date(date1): # Initializing a reference date # Note that here date is not 31st Dec but 30th! temp = dt.datetime(1899, 12, 30) delta = date1 - temp return float(delta.days) + (float(delta.seconds) / 86400) # Calculating the excel serial date number# for the date \"2021-05-04\" by calling the# user defined function excel_date()print(excel_date(datetime(2021, 2, 4)))",
"e": 28378,
"s": 27813,
"text": null
},
{
"code": null,
"e": 28386,
"s": 28378,
"text": "Output:"
},
{
"code": null,
"e": 28394,
"s": 28386,
"text": "44231.0"
},
{
"code": null,
"e": 28411,
"s": 28394,
"text": "arorakashish0911"
},
{
"code": null,
"e": 28418,
"s": 28411,
"text": "Picked"
},
{
"code": null,
"e": 28442,
"s": 28418,
"text": "Python datetime-program"
},
{
"code": null,
"e": 28458,
"s": 28442,
"text": "Python-datetime"
},
{
"code": null,
"e": 28465,
"s": 28458,
"text": "Python"
},
{
"code": null,
"e": 28563,
"s": 28465,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28581,
"s": 28563,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28616,
"s": 28581,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 28648,
"s": 28616,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28670,
"s": 28648,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28712,
"s": 28670,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28742,
"s": 28712,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 28768,
"s": 28742,
"text": "Python String | replace()"
},
{
"code": null,
"e": 28797,
"s": 28768,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 28841,
"s": 28797,
"text": "Reading and Writing to text files in Python"
}
] |
A Simplex Stop-and-Wait Protocol for a Noisy Channel | Simplex Stop – and – Wait protocol for noisy channel is data link layer protocol for data communications with error control and flow control mechanisms. It is popularly known as Stop – and –Wait Automatic Repeat Request (Stop – and –Wait ARQ) protocol. It adds error control facilities to Stop – and – Wait protocol.
This protocol takes into account the facts that the receiver has a finite processing speed and that frames may get corrupted while transmission. If data frames arrive at the receiver’s end at a rate which is greater than its rate of processing, frames can be dropped out. Also, frames may get corrupted or entirely lost when they are transmitted via network channels. So, the receiver sends an acknowledgment for each valid frame that it receives. The sender sends the next frame only when it has received a positive acknowledgment from the receiver that it is available for further data processing. Otherwise, it waits for a certain amount of time and then resends the frame.
Sender Site − At the sender site, a field is added to the frame to hold a sequence number. If data is available, the data link layer makes a frame with the certain sequence number and sends it. The sender then waits for arrival of acknowledgment for a certain amount of time. If it receives a positive acknowledgment for the frame with that sequence number within the stipulated time, it sends the frame with next sequence number. Otherwise, it resends the same frame.
Sender Site − At the sender site, a field is added to the frame to hold a sequence number. If data is available, the data link layer makes a frame with the certain sequence number and sends it. The sender then waits for arrival of acknowledgment for a certain amount of time. If it receives a positive acknowledgment for the frame with that sequence number within the stipulated time, it sends the frame with next sequence number. Otherwise, it resends the same frame.
Receiver Site − The receiver also keeps a sequence number of the frames expected for arrival. When a frame arrives, the receiver processes it and checks whether it is valid or not. If it is valid and its sequence number matches the sequence number of the expected frame, it extracts the data and delivers it to the network layer. It then sends an acknowledgement for that frame back to the sender along with its sequence number.
Receiver Site − The receiver also keeps a sequence number of the frames expected for arrival. When a frame arrives, the receiver processes it and checks whether it is valid or not. If it is valid and its sequence number matches the sequence number of the expected frame, it extracts the data and delivers it to the network layer. It then sends an acknowledgement for that frame back to the sender along with its sequence number.
begin
SeqNo = 0; // Initialise sequence number of outbound frame
canSend = True; //Allow the first frame to be sent
while (true) //check repeatedly
do
Wait_For_Event(); //wait for availability of packet
if ( Event(Request_For_Transfer) AND canSend) then
Get_Data_From_Network_Layer();
frame = Make_Frame(SeqNo);
Store_Copy_Frame(frame.SeqNo);
Send_Frame_To_Physical_Layer(frame.SeqNo);
Start_Timer(frame.SeqNo);
SeqNo = SeqNo + 1;
canSend = False;
else if ( Event(Acknowledgement_Arrival)) then
Receive_ACK();
if ( ACK_No = SeqNo ) then
Stop_Timer (frame.SeqNo);
canSend = True;
end if
else if ( Event( Timer > Max_time)) then
Resend_Frame_To_Physical_Layer(frame.SeqNo-1);
Start_Timer(frame.SeqNo-1);
end if
end while
end
begin
RSeqNo = 0; // Initialise sequence number of expected frame
while (true) //check repeatedly
do
Wait_For_Event(); //wait for arrival of frame
if ( Event(Frame_Arrival) then
Receive_Frame_From_Physical_Layer();
if ( Corrupted ( frame.SeqNo )
doNothing();
else if ( frame.SeqNo = RSeqNo ) then
Extract_Data();
Deliver_Data_To_Network_Layer();
RSeqNo = RSeqNo + 1;
end if
Send_ACK(ACKframe[RSeqNo]);
end if
end while
end
The following flow diagram depicts communication via simplex stop – and – wait ARQ protocol for noisy channel − | [
{
"code": null,
"e": 1379,
"s": 1062,
"text": "Simplex Stop – and – Wait protocol for noisy channel is data link layer protocol for data communications with error control and flow control mechanisms. It is popularly known as Stop – and –Wait Automatic Repeat Request (Stop – and –Wait ARQ) protocol. It adds error control facilities to Stop – and – Wait protocol."
},
{
"code": null,
"e": 2056,
"s": 1379,
"text": "This protocol takes into account the facts that the receiver has a finite processing speed and that frames may get corrupted while transmission. If data frames arrive at the receiver’s end at a rate which is greater than its rate of processing, frames can be dropped out. Also, frames may get corrupted or entirely lost when they are transmitted via network channels. So, the receiver sends an acknowledgment for each valid frame that it receives. The sender sends the next frame only when it has received a positive acknowledgment from the receiver that it is available for further data processing. Otherwise, it waits for a certain amount of time and then resends the frame."
},
{
"code": null,
"e": 2525,
"s": 2056,
"text": "Sender Site − At the sender site, a field is added to the frame to hold a sequence number. If data is available, the data link layer makes a frame with the certain sequence number and sends it. The sender then waits for arrival of acknowledgment for a certain amount of time. If it receives a positive acknowledgment for the frame with that sequence number within the stipulated time, it sends the frame with next sequence number. Otherwise, it resends the same frame."
},
{
"code": null,
"e": 2994,
"s": 2525,
"text": "Sender Site − At the sender site, a field is added to the frame to hold a sequence number. If data is available, the data link layer makes a frame with the certain sequence number and sends it. The sender then waits for arrival of acknowledgment for a certain amount of time. If it receives a positive acknowledgment for the frame with that sequence number within the stipulated time, it sends the frame with next sequence number. Otherwise, it resends the same frame."
},
{
"code": null,
"e": 3423,
"s": 2994,
"text": "Receiver Site − The receiver also keeps a sequence number of the frames expected for arrival. When a frame arrives, the receiver processes it and checks whether it is valid or not. If it is valid and its sequence number matches the sequence number of the expected frame, it extracts the data and delivers it to the network layer. It then sends an acknowledgement for that frame back to the sender along with its sequence number."
},
{
"code": null,
"e": 3852,
"s": 3423,
"text": "Receiver Site − The receiver also keeps a sequence number of the frames expected for arrival. When a frame arrives, the receiver processes it and checks whether it is valid or not. If it is valid and its sequence number matches the sequence number of the expected frame, it extracts the data and delivers it to the network layer. It then sends an acknowledgement for that frame back to the sender along with its sequence number."
},
{
"code": null,
"e": 4729,
"s": 3852,
"text": "begin\n SeqNo = 0; // Initialise sequence number of outbound frame\n canSend = True; //Allow the first frame to be sent\n while (true) //check repeatedly\n do\n Wait_For_Event(); //wait for availability of packet\n if ( Event(Request_For_Transfer) AND canSend) then\n Get_Data_From_Network_Layer();\n frame = Make_Frame(SeqNo);\n Store_Copy_Frame(frame.SeqNo);\n Send_Frame_To_Physical_Layer(frame.SeqNo);\n Start_Timer(frame.SeqNo);\n SeqNo = SeqNo + 1;\n canSend = False;\n else if ( Event(Acknowledgement_Arrival)) then\n Receive_ACK();\n if ( ACK_No = SeqNo ) then\n Stop_Timer (frame.SeqNo);\n canSend = True;\n end if\n else if ( Event( Timer > Max_time)) then\nResend_Frame_To_Physical_Layer(frame.SeqNo-1);\nStart_Timer(frame.SeqNo-1);\nend if\nend while\nend"
},
{
"code": null,
"e": 5152,
"s": 4729,
"text": "begin\nRSeqNo = 0; // Initialise sequence number of expected frame\nwhile (true) //check repeatedly\ndo\nWait_For_Event(); //wait for arrival of frame\nif ( Event(Frame_Arrival) then\nReceive_Frame_From_Physical_Layer();\nif ( Corrupted ( frame.SeqNo )\ndoNothing();\nelse if ( frame.SeqNo = RSeqNo ) then\nExtract_Data();\nDeliver_Data_To_Network_Layer();\nRSeqNo = RSeqNo + 1;\nend if\nSend_ACK(ACKframe[RSeqNo]);\nend if\nend while\nend"
},
{
"code": null,
"e": 5264,
"s": 5152,
"text": "The following flow diagram depicts communication via simplex stop – and – wait ARQ protocol for noisy channel −"
}
] |
Advanced Options with Hyperopt for Tuning Hyperparameters in Neural Networks | by Nicholas Lewis | Towards Data Science | If you’re anything like me, you spent the first several months looking at applications of machine learning and wondering how to get better performance out of the model. I would spend hours, if not days, making minor tweaks to the model, hoping for better performance. Surely, I thought, there should be a better way to improve the model than manually checking dozens of combinations of hyperparameters.
That’s when I came across this excellent article on the Python package Hyperopt, which uses a Bayesian optimization model to determine the optimal hyperparameters for a machine learning model. Gone are the days of random guesswork and time-consuming trial and error when trying to fit a model to data! Using Bayesian optimization to tune your model also has the advantage that, while it’s important to understand what the hyperparameters are controlling, you don’t have to be the expert in how a model works in order to use it. Rather, you can try out a completely new type of model that you’ve never used before, and with some simple code, you can get some great results.
Before we dive into some examples, I do want to mention a few other packages that accomplish similar objectives but with different methods. Scikit-learn has a RandomizedSearchCV and GridSearchCV method, which are used to search across a space of hyperparameters. If you’re using Keras, Hyperas also provides a nice wrapper for hyperparameter optimization (however, you might run into some limitations if you’re trying to do some of these more advanced applications). The grid search and random search options are much more exhaustive, and thus more time-consuming, but the advantage is you’re not running the risk of getting stuck with a local minimum, which is a possibility when using the Bayesian approach. The disadvantage is that your search will likely spend a lot more time trying out ineffective hyperparameters.
For our data, we’ll generate some First Order Plus Dead Time (FOPDT) model data. FOPDT models are powerful and straightforward models that are often used in industry for preliminary results. They are a way of describing what happens in response to a changing stimulus. For example, we can model how the speed of a car changes based on how much you press the gas pedal.
In the above equation, y(t) is the output variable, u(t) is the input variable, and Kp, τp, and θp are process constants that determine the behavior for the output relative to the input. To put this in concrete terms, think of the gas pedal on your car. You can press the pedal down a given amount (input variable, or u(t), is % the pedal is pushed), and the speed of the car (output variable, or y(t)) will increase accordingly. Kp describes how much the speed changes compared to how much you press the pedal; τp indicates how quickly the speed will increase (commonly reported as the acceleration of the car); θp is the dead time variable, and accounts for any delay between pressing the gas pedal and the speed actually starting to change.
Simulating an FOPDT model in Python is actually quite straightforward. We start with a function rearranges the FOPDT equation to solve for the derivative dy/dt:
def fopdt(y,t,um,Km,taum): # arguments # y = output # t = time # uf = input linear function (for time shift) # Km = model gain # taum = model time constant # calculate derivative dydt = (-(y-yp0) + Km * (um-u0))/taum return dydt
Once we have this, we can create another function that will simulate the first order response to whatever inputs we pass. The crucial part of this is using odeint from scipy.
def sim_model(Km,taum): # array for model values ym = np.zeros(ns) # initial condition ym[0] = yp0 # loop through time steps for i in range(0,ns-1): ts = [t[i],t[i+1]] y1 = odeint(fopdt,ym[i],ts,args=(u[i],Km,taum)) ym[i+1] = y1[-1] return ym
With the functions in place, we can set up our simulation. We start with specifying how many data points we need, as well as the model parameters (feel free to change these around to see a different model response — maybe you want to simulate a race car by simulating a fast acceleration, or a higher maximum speed by increasing the gain, or Kp).
# Parameters and time for FOPDT modelns = 10000t = np.linspace(0,ns-1,ns)u = np.zeros(ns)# Additional FOPDT parametersyp0 = 0.0u0 = u[0]Km = 0.67taum = 160.0
We’ll generate some step data now, which I chose to just generate by randomly changing the input value (u, or gas pedal %) between 0 and 100, and keeping it at that level for a period of time between 5 and 15 minutes. This allows us to see a good variety of steady state and transient data.
# Generate step data for uend = 60 # leave 1st minute of u as 0while end <= ns: start = end end += random.randint(300,900) # keep new Q1s value for anywhere from 5 to 15 minutes u[start:end] = random.randint(0,100)
Now, we can simply call our sim_model function from earlier, and we’ll have the first order response to the input data we just generated.
# Simulate FOPDT modely = sim_model(Km,taum)
Now, this data will look really pretty, which doesn’t reflect reality. There’s always going to be some amount of noise in our sensors, so to get some more real-looking data, we’ll generate some artificial noise and add it to our simulated data. You can also change the amount of noise in your own code and see how it changes the final outcome.
# Add Gaussian noisenoise = np.random.normal(0,0.2,ns)y += noise
Finally, we’ll go ahead and put the data all together, and also do a bit of preprocessing in anticipation for our neural network model. At this point, it’s really straightforward data, but our model will perform better when the data is scaled. This is simple enough thanks to the MinMaxScaler from scikit-learn:
# Scale datadata = np.vstack((u,y)).Ts = MinMaxScaler(feature_range=(0,1))data_s = s.fit_transform(data)
Now we have some FOPDT model data. Let’s take a quick look at it to see what it looks like, and then we’ll discuss what machine learning application we want to do with it.
The gray indicates the data that we’ll set aside for final testing. The orange line (pedal %) is the input, which we called u in the code. The blue line (speed, with the artificially added noise) is the process variable (PV) or output data, which we represented with y. So as you can see, as we press the gas pedal down more, the speed gradually goes up until it reaches a steady state, and as we take the foot off the gas, the speed decreases.
So now, what do we want to do with this data? We want to create a machine learning model that simulates similar behavior, and then use Hyperopt to get the best hyperparameters. If you look at my series on emulating PID controllers with an LSTM neural network, you’ll see that LSTMs worked really well with this type of problem. What we want to do is train an LSTM model that would follow this same type of FOPDT model behavior.
Keras is an excellent platform for constructing neural networks. We could keep this really basic, and do something like the following:
# Keras LSTM modelmodel = Sequential() model.add(LSTM(units = 50, input_shape = (Xtrain.shape[1],Xtrain.shape[2]) ) )model.add(Dropout(rate = 0.1))model.add(Dense(1))model.compile(optimizer='adam', loss='mean_squared_error') es = EarlyStopping(monitor='val_loss',mode='min',verbose=1,patience=15)result = model.fit(Xtrain, ytrain, verbose=0, validation_split=0.1, batch_size=100, epochs=200)
In the above code, we start with the LSTM layer and specify the units hyperparameter, as well as the input shape. We add a Dropout layer, which is helpful to avoid overfitting the data, and then a Dense layer, which is needed for the model to output the results. Then we compile the model with the adam optimizer and mean_squared_error loss metric, add a line of code to stop training the model once the loss plateaus, and then fit the model. Simple enough...until we look at how it actually does:
The plot above shows the real speed and gas pedal from our simulation, then also the predicted and forecasted speeds. Predicted speed makes predictions based on feeding the real measurements into the model, while the forecasted speed takes the previous predicted speeds and feeds them into the model — hence the cause for so much drift and the inability to recover from the drift. As you can see, this model is hardly satisfactory. The good news is that we have some options to improve it. We could generate more data or let it train for more epochs (or fewer, depending on if we overfit or underfit). It’s certainly worth checking those. But the other option is to adjust the hyperparameters, either by trial and error, a deeper understanding of the model structure...or the Hyperopt package.
The purpose of this article isn’t an introduction to Hyperopt, but rather aimed at expanding what you want to do with Hyperopt. Looking at the Keras block of code above, there are several hyperparameters we could pick out to optimize, such as units in the LSTM layer, rate in the Dropout layer, and batch_size when we’re fitting. Finding optimal values of these would be covered in an introductory Hyperopt tutorial. However, we may find it useful to add some extra LSTM and Dropout layers, or even look at a more optimal window of datapoints to feed into the LSTM. We may even find it beneficial to change the objective function that we’re trying to minimize.
Now, using Hyperopt is very beneficial to the beginner, but it does help to have some idea of what each hyperparameter is used for and a good range. We start by defining the range of values we want to search over. Again, the syntax of this step is covered in any introductory Hyperopt tutorial, so my purpose is to show a few nuances. Here’s the code:
from hyperopt.pyll.base import scope #quniform returns float, some parameters require int; use this to force intspace = {'rate' : hp.uniform('rate',0.01,0.5), 'units' : scope.int(hp.quniform('units',10,100,5)), 'batch_size' : scope.int(hp.quniform('batch_size',100,250,25)), 'layers' : scope.int(hp.quniform('layers',1,6,1)), 'window' : scope.int(hp.quniform('window',10,50,5)) }
Most of the time, you can just use the regular options for hp.uniform, hp.choice, hp.logchoice, etc. However, the hp.quniform option returns a float, even though it is a whole number like 1.0 or 5.0. Some Keras hyperparameters require this to be an integer type, so we force Hyperopt to return an integer by including scope.int.
To construct our model, we put everything inside a function, with the possible parameters as the argument:
def f_nn(params): # Generate data with given window Xtrain, ytrain, Xtest, ytest = format_data(window=params['window']) # Keras LSTM model model = Sequential() if params['layers'] == 1: model.add(LSTM(units=params['units'], input_shape=(Xtrain.shape[1],Xtrain.shape[2]))) model.add(Dropout(rate=params['rate'])) else: # First layer specifies input_shape and returns sequences model.add(LSTM(units=params['units'], return_sequences=True, input_shape=(Xtrain.shape[1],Xtrain.shape[2]))) model.add(Dropout(rate=params['rate'])) # Middle layers return sequences for i in range(params['layers']-2): model.add(LSTM(units=params['units'], return_sequences=True)) model.add(Dropout(rate=params['rate'])) # Last layer doesn't return anything model.add(LSTM(units=params['units'])) model.add(Dropout(rate=params['rate'])) model.add(Dense(1)) model.compile(optimizer='adam', loss='mean_squared_error') es = EarlyStopping(monitor='val_loss',mode='min', verbose=1,patience=15) result = model.fit(Xtrain, ytrain, verbose=0, validation_split=0.1, batch_size=params['batch_size'], epochs=200) # Get the lowest validation loss of the training epochs validation_loss = np.amin(result.history['val_loss']) print('Best validation loss of epoch:', validation_loss) return {'loss': validation_loss, 'status': STATUS_OK, 'model': model, 'params': params}
You’ll notice our first line in the function formats the data into Xtrain, ytrain, Xtest, and ytest. This formats our X and y data into the format required by the LSTM, and importantly adjusts the window of input points, based on the range we specified earlier for window. Then we start our Keras model. It has the same elements as before, but you’ll notice that rather than specify a numeric value for a hyperparameter such as rate, we allow it to be in the range we specified by setting it as rate = params['rate']. We also add some logic to allow for multiple LSTM and Dropout layers. Finally, we compile and fit the model just as before, and then we need an objective function to minimize. To start, we just take the validation loss and use that as our objective function, which will suffice the majority of the time (we’ll explore an instance where we might want something else in just a minute). The last step is to return information we might want to use later in the code, such as the loss of our objective function, the Keras model, and the hyperparameter values.
To run the actual optimization, be prepared for some long run times. Training an LSTM always takes a bit of time, and what we’re doing is training it several times with different hyperparameter sets. This next part took about 12 hours to run on my personal computer. You can speed up the process significantly by using Google Colab’s GPU resources.
The actual code you need is straightforward. We set the trials variable so that we can retrieve the data from the optimization, and then use the fmin() function to actually run the optimization. We pass the f_nn function we provided earlier, the space containing the range of hyperparameter values, define the algo as tpe.suggest, and specify the max_evals as the number of sets we want to try. With more trials, we’re more likely to get the optimal solution, but there’s the downside of waiting more time. For something like a classifier that trains data fast, it’s easy to get several hundred evaluations within a few seconds, but with the LSTM, the 50 evaluations specified here takes several hours.
trials = Trials()best = fmin(f_nn, space, algo=tpe.suggest, max_evals=50, trials=trials)
After you’ve let that run, you can take a look at some of the results. I use a bit of list comprehension to access the data stored in trials. We can see everything that we returned in our original f_nn function, including loss, model, and params. Our best model and set of parameters will be associated with the lowest loss, while the worst model and parameter set will have the highest loss. Let’s go ahead and save those as variables so we can plot the results.
best_model = trials.results[np.argmin([r['loss'] for r in trials.results])]['model']best_params = trials.results[np.argmin([r['loss'] for r in trials.results])]['params']worst_model = trials.results[np.argmax([r['loss'] for r in trials.results])]['model']worst_params = trials.results[np.argmax([r['loss'] for r in trials.results])]['params']
Now we’ve run the optimization and saved the model (and for good measure the set of hyperparameters), it’s time to see how the model looks. We’ll look at two different approaches. The first approach involves taking the previous window of actual input data points (pedal %) and using that to predict the next output (speed). We’ll call this the “prediction.” This is quite simply found by taking our test data and applying the model.predict() function. It looks like this:
# Best windowbest_window = best_params['window']# Format dataXtrain, ytrain, Xtest, ytest = format_data(window=best_window)Yp = best_model.predict(Xtest)
We also want to look at one other aspect, though. Lets say we’re trying to forecast where the speed will go without having the moment-to-moment feedback. Rather than taking the actual data values, we use the LSTM prediction to make the next prediction. This is a much harder problem, since if the LSTM prediction is only slightly off, the error can be compounded over time. We’ll call this method the “forecast,” indicating that we’re using the LSTM predictions to update the input values and forecast for a time range. I put this into a function forecast():
def forecast(Xtest,ytest,model,window): Yf = ytest.copy() for i in range(len(Yf)): if i < window: pass else: Xu = Xtest[i,:,0] Xy = Yf[i-window:i] Xf = np.vstack((Xu,Xy)).T Xf = np.reshape(Xf, (1, Xf.shape[0], Xf.shape[1])) Yf[i] = model.predict(Xf)[0] return Yf
Let’s see what this looks like:
OK, it’s actually not that bad. This is actually using the worst model and hyperparameter set. Looking at the best set we came up with after 50 iterations looks like this:
The “prediction” is pretty close, and the “forecast” is much better. We could probably get even better results from the prediction if we let it try more optimizations. But can we do better with the forecast?
This is where the objective function comes in. You can get quite clever with the objective function that you’re minimizing to account for all types of situations where you want to see better results. For example, what if we also want to account for how much time the model takes to train? We could change our loss score to include an element of time — maybe something like multiply by the time it takes, so that a fast training time is rewarded.
In our case, we want to reward the model that has a good forecast. This is actually quite simple, given that we already have the forecast() function. After setting up our f_nn() function as before, we can add a few more lines to change our objective function. Recall that previously, we simply set our loss to the validation_loss value. Now, we actually run the forecast in our f_nn model like so:
# Get validation setval_length = int(0.2*len(ytest))Xval, yval = Xtrain[-val_length:], ytrain[-val_length:]# Evaluate forecastYr, Yp, Yf = forecast(Xval,yval,model,params['window'])mse = np.mean((Yr - Yf)**2)
Note that we have to separate out our validation set — we can’t use our test set, since that would bias the results. Then we simply calculate the mean squared error (mse) between the forecast and actual values. This is then saved as our loss function in the return line like so:
return {'loss': mse, 'status': STATUS_OK, 'model': model, 'params': params}
That’s all there is too it. After running this again, we get the following results:
We could also look at the worst results, just to prove that Hyperopt is actually doing something for us:
Using the best model looks fantastic ! Like we discussed, forecasting is extremely sensitive to small errors, so given the time range that we’re forecasting over, this looks really impressive. We’d expect to see the drift become a bit more pronounced over a longer time frame, but it’s a major improvement using the updated objective function. We could also run the optimization for more than 50 evaluations, and we’d possibly come up with something better.
These are just a few examples of how you can utilize Hyperopt to get increased performance from your machine learning model. While the exact methods used here might not be used in your particular situation, I hope that some ideas were sparked and that you can see some more potential uses for Hyperopt. I’ve included the code from my different simulations on my Github repo.
How else could you take this further? You could easily add a time element to your objective function if you want to find the most time-efficient and accurate model. The principles in here are easily applied to any other machine learning model with hyperparameters, and you might find it much faster to use this on classifiers. Finally, you could speed up the process significantly by using GPU — if your computer doesn’t have one, Google Colab is a great resource. Let me know your thoughts, and feel free to connect with me on LinkedIn. | [
{
"code": null,
"e": 575,
"s": 172,
"text": "If you’re anything like me, you spent the first several months looking at applications of machine learning and wondering how to get better performance out of the model. I would spend hours, if not days, making minor tweaks to the model, hoping for better performance. Surely, I thought, there should be a better way to improve the model than manually checking dozens of combinations of hyperparameters."
},
{
"code": null,
"e": 1248,
"s": 575,
"text": "That’s when I came across this excellent article on the Python package Hyperopt, which uses a Bayesian optimization model to determine the optimal hyperparameters for a machine learning model. Gone are the days of random guesswork and time-consuming trial and error when trying to fit a model to data! Using Bayesian optimization to tune your model also has the advantage that, while it’s important to understand what the hyperparameters are controlling, you don’t have to be the expert in how a model works in order to use it. Rather, you can try out a completely new type of model that you’ve never used before, and with some simple code, you can get some great results."
},
{
"code": null,
"e": 2069,
"s": 1248,
"text": "Before we dive into some examples, I do want to mention a few other packages that accomplish similar objectives but with different methods. Scikit-learn has a RandomizedSearchCV and GridSearchCV method, which are used to search across a space of hyperparameters. If you’re using Keras, Hyperas also provides a nice wrapper for hyperparameter optimization (however, you might run into some limitations if you’re trying to do some of these more advanced applications). The grid search and random search options are much more exhaustive, and thus more time-consuming, but the advantage is you’re not running the risk of getting stuck with a local minimum, which is a possibility when using the Bayesian approach. The disadvantage is that your search will likely spend a lot more time trying out ineffective hyperparameters."
},
{
"code": null,
"e": 2438,
"s": 2069,
"text": "For our data, we’ll generate some First Order Plus Dead Time (FOPDT) model data. FOPDT models are powerful and straightforward models that are often used in industry for preliminary results. They are a way of describing what happens in response to a changing stimulus. For example, we can model how the speed of a car changes based on how much you press the gas pedal."
},
{
"code": null,
"e": 3182,
"s": 2438,
"text": "In the above equation, y(t) is the output variable, u(t) is the input variable, and Kp, τp, and θp are process constants that determine the behavior for the output relative to the input. To put this in concrete terms, think of the gas pedal on your car. You can press the pedal down a given amount (input variable, or u(t), is % the pedal is pushed), and the speed of the car (output variable, or y(t)) will increase accordingly. Kp describes how much the speed changes compared to how much you press the pedal; τp indicates how quickly the speed will increase (commonly reported as the acceleration of the car); θp is the dead time variable, and accounts for any delay between pressing the gas pedal and the speed actually starting to change."
},
{
"code": null,
"e": 3343,
"s": 3182,
"text": "Simulating an FOPDT model in Python is actually quite straightforward. We start with a function rearranges the FOPDT equation to solve for the derivative dy/dt:"
},
{
"code": null,
"e": 3624,
"s": 3343,
"text": "def fopdt(y,t,um,Km,taum): # arguments # y = output # t = time # uf = input linear function (for time shift) # Km = model gain # taum = model time constant # calculate derivative dydt = (-(y-yp0) + Km * (um-u0))/taum return dydt"
},
{
"code": null,
"e": 3799,
"s": 3624,
"text": "Once we have this, we can create another function that will simulate the first order response to whatever inputs we pass. The crucial part of this is using odeint from scipy."
},
{
"code": null,
"e": 4088,
"s": 3799,
"text": "def sim_model(Km,taum): # array for model values ym = np.zeros(ns) # initial condition ym[0] = yp0 # loop through time steps for i in range(0,ns-1): ts = [t[i],t[i+1]] y1 = odeint(fopdt,ym[i],ts,args=(u[i],Km,taum)) ym[i+1] = y1[-1] return ym"
},
{
"code": null,
"e": 4435,
"s": 4088,
"text": "With the functions in place, we can set up our simulation. We start with specifying how many data points we need, as well as the model parameters (feel free to change these around to see a different model response — maybe you want to simulate a race car by simulating a fast acceleration, or a higher maximum speed by increasing the gain, or Kp)."
},
{
"code": null,
"e": 4593,
"s": 4435,
"text": "# Parameters and time for FOPDT modelns = 10000t = np.linspace(0,ns-1,ns)u = np.zeros(ns)# Additional FOPDT parametersyp0 = 0.0u0 = u[0]Km = 0.67taum = 160.0"
},
{
"code": null,
"e": 4884,
"s": 4593,
"text": "We’ll generate some step data now, which I chose to just generate by randomly changing the input value (u, or gas pedal %) between 0 and 100, and keeping it at that level for a period of time between 5 and 15 minutes. This allows us to see a good variety of steady state and transient data."
},
{
"code": null,
"e": 5168,
"s": 4884,
"text": "# Generate step data for uend = 60 # leave 1st minute of u as 0while end <= ns: start = end end += random.randint(300,900) # keep new Q1s value for anywhere from 5 to 15 minutes u[start:end] = random.randint(0,100)"
},
{
"code": null,
"e": 5306,
"s": 5168,
"text": "Now, we can simply call our sim_model function from earlier, and we’ll have the first order response to the input data we just generated."
},
{
"code": null,
"e": 5351,
"s": 5306,
"text": "# Simulate FOPDT modely = sim_model(Km,taum)"
},
{
"code": null,
"e": 5695,
"s": 5351,
"text": "Now, this data will look really pretty, which doesn’t reflect reality. There’s always going to be some amount of noise in our sensors, so to get some more real-looking data, we’ll generate some artificial noise and add it to our simulated data. You can also change the amount of noise in your own code and see how it changes the final outcome."
},
{
"code": null,
"e": 5760,
"s": 5695,
"text": "# Add Gaussian noisenoise = np.random.normal(0,0.2,ns)y += noise"
},
{
"code": null,
"e": 6072,
"s": 5760,
"text": "Finally, we’ll go ahead and put the data all together, and also do a bit of preprocessing in anticipation for our neural network model. At this point, it’s really straightforward data, but our model will perform better when the data is scaled. This is simple enough thanks to the MinMaxScaler from scikit-learn:"
},
{
"code": null,
"e": 6177,
"s": 6072,
"text": "# Scale datadata = np.vstack((u,y)).Ts = MinMaxScaler(feature_range=(0,1))data_s = s.fit_transform(data)"
},
{
"code": null,
"e": 6349,
"s": 6177,
"text": "Now we have some FOPDT model data. Let’s take a quick look at it to see what it looks like, and then we’ll discuss what machine learning application we want to do with it."
},
{
"code": null,
"e": 6794,
"s": 6349,
"text": "The gray indicates the data that we’ll set aside for final testing. The orange line (pedal %) is the input, which we called u in the code. The blue line (speed, with the artificially added noise) is the process variable (PV) or output data, which we represented with y. So as you can see, as we press the gas pedal down more, the speed gradually goes up until it reaches a steady state, and as we take the foot off the gas, the speed decreases."
},
{
"code": null,
"e": 7222,
"s": 6794,
"text": "So now, what do we want to do with this data? We want to create a machine learning model that simulates similar behavior, and then use Hyperopt to get the best hyperparameters. If you look at my series on emulating PID controllers with an LSTM neural network, you’ll see that LSTMs worked really well with this type of problem. What we want to do is train an LSTM model that would follow this same type of FOPDT model behavior."
},
{
"code": null,
"e": 7357,
"s": 7222,
"text": "Keras is an excellent platform for constructing neural networks. We could keep this really basic, and do something like the following:"
},
{
"code": null,
"e": 7838,
"s": 7357,
"text": "# Keras LSTM modelmodel = Sequential() model.add(LSTM(units = 50, input_shape = (Xtrain.shape[1],Xtrain.shape[2]) ) )model.add(Dropout(rate = 0.1))model.add(Dense(1))model.compile(optimizer='adam', loss='mean_squared_error') es = EarlyStopping(monitor='val_loss',mode='min',verbose=1,patience=15)result = model.fit(Xtrain, ytrain, verbose=0, validation_split=0.1, batch_size=100, epochs=200)"
},
{
"code": null,
"e": 8336,
"s": 7838,
"text": "In the above code, we start with the LSTM layer and specify the units hyperparameter, as well as the input shape. We add a Dropout layer, which is helpful to avoid overfitting the data, and then a Dense layer, which is needed for the model to output the results. Then we compile the model with the adam optimizer and mean_squared_error loss metric, add a line of code to stop training the model once the loss plateaus, and then fit the model. Simple enough...until we look at how it actually does:"
},
{
"code": null,
"e": 9130,
"s": 8336,
"text": "The plot above shows the real speed and gas pedal from our simulation, then also the predicted and forecasted speeds. Predicted speed makes predictions based on feeding the real measurements into the model, while the forecasted speed takes the previous predicted speeds and feeds them into the model — hence the cause for so much drift and the inability to recover from the drift. As you can see, this model is hardly satisfactory. The good news is that we have some options to improve it. We could generate more data or let it train for more epochs (or fewer, depending on if we overfit or underfit). It’s certainly worth checking those. But the other option is to adjust the hyperparameters, either by trial and error, a deeper understanding of the model structure...or the Hyperopt package."
},
{
"code": null,
"e": 9791,
"s": 9130,
"text": "The purpose of this article isn’t an introduction to Hyperopt, but rather aimed at expanding what you want to do with Hyperopt. Looking at the Keras block of code above, there are several hyperparameters we could pick out to optimize, such as units in the LSTM layer, rate in the Dropout layer, and batch_size when we’re fitting. Finding optimal values of these would be covered in an introductory Hyperopt tutorial. However, we may find it useful to add some extra LSTM and Dropout layers, or even look at a more optimal window of datapoints to feed into the LSTM. We may even find it beneficial to change the objective function that we’re trying to minimize."
},
{
"code": null,
"e": 10143,
"s": 9791,
"text": "Now, using Hyperopt is very beneficial to the beginner, but it does help to have some idea of what each hyperparameter is used for and a good range. We start by defining the range of values we want to search over. Again, the syntax of this step is covered in any introductory Hyperopt tutorial, so my purpose is to show a few nuances. Here’s the code:"
},
{
"code": null,
"e": 10605,
"s": 10143,
"text": "from hyperopt.pyll.base import scope #quniform returns float, some parameters require int; use this to force intspace = {'rate' : hp.uniform('rate',0.01,0.5), 'units' : scope.int(hp.quniform('units',10,100,5)), 'batch_size' : scope.int(hp.quniform('batch_size',100,250,25)), 'layers' : scope.int(hp.quniform('layers',1,6,1)), 'window' : scope.int(hp.quniform('window',10,50,5)) }"
},
{
"code": null,
"e": 10934,
"s": 10605,
"text": "Most of the time, you can just use the regular options for hp.uniform, hp.choice, hp.logchoice, etc. However, the hp.quniform option returns a float, even though it is a whole number like 1.0 or 5.0. Some Keras hyperparameters require this to be an integer type, so we force Hyperopt to return an integer by including scope.int."
},
{
"code": null,
"e": 11041,
"s": 10934,
"text": "To construct our model, we put everything inside a function, with the possible parameters as the argument:"
},
{
"code": null,
"e": 12801,
"s": 11041,
"text": "def f_nn(params): # Generate data with given window Xtrain, ytrain, Xtest, ytest = format_data(window=params['window']) # Keras LSTM model model = Sequential() if params['layers'] == 1: model.add(LSTM(units=params['units'], input_shape=(Xtrain.shape[1],Xtrain.shape[2]))) model.add(Dropout(rate=params['rate'])) else: # First layer specifies input_shape and returns sequences model.add(LSTM(units=params['units'], return_sequences=True, input_shape=(Xtrain.shape[1],Xtrain.shape[2]))) model.add(Dropout(rate=params['rate'])) # Middle layers return sequences for i in range(params['layers']-2): model.add(LSTM(units=params['units'], return_sequences=True)) model.add(Dropout(rate=params['rate'])) # Last layer doesn't return anything model.add(LSTM(units=params['units'])) model.add(Dropout(rate=params['rate'])) model.add(Dense(1)) model.compile(optimizer='adam', loss='mean_squared_error') es = EarlyStopping(monitor='val_loss',mode='min', verbose=1,patience=15) result = model.fit(Xtrain, ytrain, verbose=0, validation_split=0.1, batch_size=params['batch_size'], epochs=200) # Get the lowest validation loss of the training epochs validation_loss = np.amin(result.history['val_loss']) print('Best validation loss of epoch:', validation_loss) return {'loss': validation_loss, 'status': STATUS_OK, 'model': model, 'params': params}"
},
{
"code": null,
"e": 13874,
"s": 12801,
"text": "You’ll notice our first line in the function formats the data into Xtrain, ytrain, Xtest, and ytest. This formats our X and y data into the format required by the LSTM, and importantly adjusts the window of input points, based on the range we specified earlier for window. Then we start our Keras model. It has the same elements as before, but you’ll notice that rather than specify a numeric value for a hyperparameter such as rate, we allow it to be in the range we specified by setting it as rate = params['rate']. We also add some logic to allow for multiple LSTM and Dropout layers. Finally, we compile and fit the model just as before, and then we need an objective function to minimize. To start, we just take the validation loss and use that as our objective function, which will suffice the majority of the time (we’ll explore an instance where we might want something else in just a minute). The last step is to return information we might want to use later in the code, such as the loss of our objective function, the Keras model, and the hyperparameter values."
},
{
"code": null,
"e": 14223,
"s": 13874,
"text": "To run the actual optimization, be prepared for some long run times. Training an LSTM always takes a bit of time, and what we’re doing is training it several times with different hyperparameter sets. This next part took about 12 hours to run on my personal computer. You can speed up the process significantly by using Google Colab’s GPU resources."
},
{
"code": null,
"e": 14926,
"s": 14223,
"text": "The actual code you need is straightforward. We set the trials variable so that we can retrieve the data from the optimization, and then use the fmin() function to actually run the optimization. We pass the f_nn function we provided earlier, the space containing the range of hyperparameter values, define the algo as tpe.suggest, and specify the max_evals as the number of sets we want to try. With more trials, we’re more likely to get the optimal solution, but there’s the downside of waiting more time. For something like a classifier that trains data fast, it’s easy to get several hundred evaluations within a few seconds, but with the LSTM, the 50 evaluations specified here takes several hours."
},
{
"code": null,
"e": 15061,
"s": 14926,
"text": "trials = Trials()best = fmin(f_nn, space, algo=tpe.suggest, max_evals=50, trials=trials)"
},
{
"code": null,
"e": 15525,
"s": 15061,
"text": "After you’ve let that run, you can take a look at some of the results. I use a bit of list comprehension to access the data stored in trials. We can see everything that we returned in our original f_nn function, including loss, model, and params. Our best model and set of parameters will be associated with the lowest loss, while the worst model and parameter set will have the highest loss. Let’s go ahead and save those as variables so we can plot the results."
},
{
"code": null,
"e": 15884,
"s": 15525,
"text": "best_model = trials.results[np.argmin([r['loss'] for r in trials.results])]['model']best_params = trials.results[np.argmin([r['loss'] for r in trials.results])]['params']worst_model = trials.results[np.argmax([r['loss'] for r in trials.results])]['model']worst_params = trials.results[np.argmax([r['loss'] for r in trials.results])]['params']"
},
{
"code": null,
"e": 16356,
"s": 15884,
"text": "Now we’ve run the optimization and saved the model (and for good measure the set of hyperparameters), it’s time to see how the model looks. We’ll look at two different approaches. The first approach involves taking the previous window of actual input data points (pedal %) and using that to predict the next output (speed). We’ll call this the “prediction.” This is quite simply found by taking our test data and applying the model.predict() function. It looks like this:"
},
{
"code": null,
"e": 16510,
"s": 16356,
"text": "# Best windowbest_window = best_params['window']# Format dataXtrain, ytrain, Xtest, ytest = format_data(window=best_window)Yp = best_model.predict(Xtest)"
},
{
"code": null,
"e": 17069,
"s": 16510,
"text": "We also want to look at one other aspect, though. Lets say we’re trying to forecast where the speed will go without having the moment-to-moment feedback. Rather than taking the actual data values, we use the LSTM prediction to make the next prediction. This is a much harder problem, since if the LSTM prediction is only slightly off, the error can be compounded over time. We’ll call this method the “forecast,” indicating that we’re using the LSTM predictions to update the input values and forecast for a time range. I put this into a function forecast():"
},
{
"code": null,
"e": 17435,
"s": 17069,
"text": "def forecast(Xtest,ytest,model,window): Yf = ytest.copy() for i in range(len(Yf)): if i < window: pass else: Xu = Xtest[i,:,0] Xy = Yf[i-window:i] Xf = np.vstack((Xu,Xy)).T Xf = np.reshape(Xf, (1, Xf.shape[0], Xf.shape[1])) Yf[i] = model.predict(Xf)[0] return Yf"
},
{
"code": null,
"e": 17467,
"s": 17435,
"text": "Let’s see what this looks like:"
},
{
"code": null,
"e": 17639,
"s": 17467,
"text": "OK, it’s actually not that bad. This is actually using the worst model and hyperparameter set. Looking at the best set we came up with after 50 iterations looks like this:"
},
{
"code": null,
"e": 17847,
"s": 17639,
"text": "The “prediction” is pretty close, and the “forecast” is much better. We could probably get even better results from the prediction if we let it try more optimizations. But can we do better with the forecast?"
},
{
"code": null,
"e": 18293,
"s": 17847,
"text": "This is where the objective function comes in. You can get quite clever with the objective function that you’re minimizing to account for all types of situations where you want to see better results. For example, what if we also want to account for how much time the model takes to train? We could change our loss score to include an element of time — maybe something like multiply by the time it takes, so that a fast training time is rewarded."
},
{
"code": null,
"e": 18691,
"s": 18293,
"text": "In our case, we want to reward the model that has a good forecast. This is actually quite simple, given that we already have the forecast() function. After setting up our f_nn() function as before, we can add a few more lines to change our objective function. Recall that previously, we simply set our loss to the validation_loss value. Now, we actually run the forecast in our f_nn model like so:"
},
{
"code": null,
"e": 18900,
"s": 18691,
"text": "# Get validation setval_length = int(0.2*len(ytest))Xval, yval = Xtrain[-val_length:], ytrain[-val_length:]# Evaluate forecastYr, Yp, Yf = forecast(Xval,yval,model,params['window'])mse = np.mean((Yr - Yf)**2)"
},
{
"code": null,
"e": 19179,
"s": 18900,
"text": "Note that we have to separate out our validation set — we can’t use our test set, since that would bias the results. Then we simply calculate the mean squared error (mse) between the forecast and actual values. This is then saved as our loss function in the return line like so:"
},
{
"code": null,
"e": 19279,
"s": 19179,
"text": "return {'loss': mse, 'status': STATUS_OK, 'model': model, 'params': params}"
},
{
"code": null,
"e": 19363,
"s": 19279,
"text": "That’s all there is too it. After running this again, we get the following results:"
},
{
"code": null,
"e": 19468,
"s": 19363,
"text": "We could also look at the worst results, just to prove that Hyperopt is actually doing something for us:"
},
{
"code": null,
"e": 19926,
"s": 19468,
"text": "Using the best model looks fantastic ! Like we discussed, forecasting is extremely sensitive to small errors, so given the time range that we’re forecasting over, this looks really impressive. We’d expect to see the drift become a bit more pronounced over a longer time frame, but it’s a major improvement using the updated objective function. We could also run the optimization for more than 50 evaluations, and we’d possibly come up with something better."
},
{
"code": null,
"e": 20301,
"s": 19926,
"text": "These are just a few examples of how you can utilize Hyperopt to get increased performance from your machine learning model. While the exact methods used here might not be used in your particular situation, I hope that some ideas were sparked and that you can see some more potential uses for Hyperopt. I’ve included the code from my different simulations on my Github repo."
}
] |
CSS - Tables | This tutorial will teach you how to set different properties of an HTML table using CSS. You can set following properties of a table −
The border-collapse specifies whether the browser should control the appearance of the adjacent borders that touch each other or whether each cell should maintain its style.
The border-collapse specifies whether the browser should control the appearance of the adjacent borders that touch each other or whether each cell should maintain its style.
The border-spacing specifies the width that should appear between table cells.
The border-spacing specifies the width that should appear between table cells.
The caption-side captions are presented in the <caption> element. By default, these are rendered above the table in the document. You use the caption-side property to control the placement of the table caption.
The caption-side captions are presented in the <caption> element. By default, these are rendered above the table in the document. You use the caption-side property to control the placement of the table caption.
The empty-cells specifies whether the border should be shown if a cell is empty.
The empty-cells specifies whether the border should be shown if a cell is empty.
The table-layout allows browsers to speed up layout of a table by using the first width properties it comes across for the rest of a column rather than having to load the whole table before rendering it.
The table-layout allows browsers to speed up layout of a table by using the first width properties it comes across for the rest of a column rather than having to load the whole table before rendering it.
Now, we will see how to use these properties with examples.
This property can have two values collapse and separate. The following example uses both the values −
<html>
<head>
<style type = "text/css">
table.one {border-collapse:collapse;}
table.two {border-collapse:separate;}
td.a {
border-style:dotted;
border-width:3px;
border-color:#000000;
padding: 10px;
}
td.b {
border-style:solid;
border-width:3px;
border-color:#333333;
padding:10px;
}
</style>
</head>
<body>
<table class = "one">
<caption>Collapse Border Example</caption>
<tr><td class = "a"> Cell A Collapse Example</td></tr>
<tr><td class = "b"> Cell B Collapse Example</td></tr>
</table>
<br />
<table class = "two">
<caption>Separate Border Example</caption>
<tr><td class = "a"> Cell A Separate Example</td></tr>
<tr><td class = "b"> Cell B Separate Example</td></tr>
</table>
</body>
</html>
It will produce the following result −
The border-spacing property specifies the distance that separates adjacent cells'. borders. It can take either one or two values; these should be units of length.
If you provide one value, it will applies to both vertical and horizontal borders. Or you can specify two values, in which case, the first refers to the horizontal spacing and the second to the vertical spacing −
NOTE − Unfortunately, this property does not work in Netscape 7 or IE 6.
<style type="text/css">
/* If you provide one value */
table.example {border-spacing:10px;}
/* This is how you can provide two values */
table.example {border-spacing:10px; 15px;}
</style>
Now let's modify the previous example and see the effect −
<html>
<head>
<style type = "text/css">
table.one {
border-collapse:separate;
width:400px;
border-spacing:10px;
}
table.two {
border-collapse:separate;
width:400px;
border-spacing:10px 50px;
}
</style>
</head>
<body>
<table class = "one" border = "1">
<caption>Separate Border Example with border-spacing</caption>
<tr><td> Cell A Collapse Example</td></tr>
<tr><td> Cell B Collapse Example</td></tr>
</table>
<br />
<table class = "two" border = "1">
<caption>Separate Border Example with border-spacing</caption>
<tr><td> Cell A Separate Example</td></tr>
<tr><td> Cell B Separate Example</td></tr>
</table>
</body>
</html>
It will produce the following result −
The caption-side property allows you to specify where the content of a <caption> element should be placed in relationship to the table. The table that follows lists the possible values.
This property can have one of the four values top, bottom, left or right. The following example uses each value.
NOTE − These properties may not work with your IE Browser.
<html>
<head>
<style type = "text/css">
caption.top {caption-side:top}
caption.bottom {caption-side:bottom}
caption.left {caption-side:left}
caption.right {caption-side:right}
</style>
</head>
<body>
<table style = "width:400px; border:1px solid black;">
<caption class = "top">
This caption will appear at the top
</caption>
<tr><td > Cell A</td></tr>
<tr><td > Cell B</td></tr>
</table>
<br />
<table style = "width:400px; border:1px solid black;">
<caption class = "bottom">
This caption will appear at the bottom
</caption>
<tr><td > Cell A</td></tr>
<tr><td > Cell B</td></tr>
</table>
<br />
<table style = "width:400px; border:1px solid black;">
<caption class = "left">
This caption will appear at the left
</caption>
<tr><td > Cell A</td></tr>
<tr><td > Cell B</td></tr>
</table>
<br />
<table style = "width:400px; border:1px solid black;">
<caption class = "right">
This caption will appear at the right
</caption>
<tr><td > Cell A</td></tr>
<tr><td > Cell B</td></tr>
</table>
</body>
</html>
It will produce the following result −
The empty-cells property indicates whether a cell without any content should have a border displayed.
This property can have one of the three values - show, hide or inherit.
Here is the empty-cells property used to hide borders of empty cells in the <table> element.
<html>
<head>
<style type = "text/css">
table.empty {
width:350px;
border-collapse:separate;
empty-cells:hide;
}
td.empty {
padding:5px;
border-style:solid;
border-width:1px;
border-color:#999999;
}
</style>
</head>
<body>
<table class = "empty">
<tr>
<th></th>
<th>Title one</th>
<th>Title two</th>
</tr>
<tr>
<th>Row Title</th>
<td class = "empty">value</td>
<td class = "empty">value</td>
</tr>
<tr>
<th>Row Title</th>
<td class = "empty">value</td>
<td class = "empty"></td>
</tr>
</table>
</body>
</html>
It will produce the following result −
The table-layout property is supposed to help you control how a browser should render or lay out a table.
This property can have one of the three values: fixed, auto or inherit.
The following example shows the difference between these properties.
NOTE − This property is not supported by many browsers so do not rely on this property.
<html>
<head>
<style type = "text/css">
table.auto {
table-layout: auto
}
table.fixed {
table-layout: fixed
}
</style>
</head>
<body>
<table class = "auto" border = "1" width = "100%">
<tr>
<td width = "20%">1000000000000000000000000000</td>
<td width = "40%">10000000</td>
<td width = "40%">100</td>
</tr>
</table>
<br />
<table class = "fixed" border = "1" width = "100%">
<tr>
<td width = "20%">1000000000000000000000000000</td>
<td width = "40%">10000000</td>
<td width = "40%">100</td>
</tr>
</table>
</body>
</html>
It will produce the following result −
33 Lectures
2.5 hours
Anadi Sharma
26 Lectures
2.5 hours
Frahaan Hussain
44 Lectures
4.5 hours
DigiFisk (Programming Is Fun)
21 Lectures
2.5 hours
DigiFisk (Programming Is Fun)
51 Lectures
7.5 hours
DigiFisk (Programming Is Fun)
52 Lectures
4 hours
DigiFisk (Programming Is Fun)
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2761,
"s": 2626,
"text": "This tutorial will teach you how to set different properties of an HTML table using CSS. You can set following properties of a table −"
},
{
"code": null,
"e": 2935,
"s": 2761,
"text": "The border-collapse specifies whether the browser should control the appearance of the adjacent borders that touch each other or whether each cell should maintain its style."
},
{
"code": null,
"e": 3109,
"s": 2935,
"text": "The border-collapse specifies whether the browser should control the appearance of the adjacent borders that touch each other or whether each cell should maintain its style."
},
{
"code": null,
"e": 3188,
"s": 3109,
"text": "The border-spacing specifies the width that should appear between table cells."
},
{
"code": null,
"e": 3267,
"s": 3188,
"text": "The border-spacing specifies the width that should appear between table cells."
},
{
"code": null,
"e": 3478,
"s": 3267,
"text": "The caption-side captions are presented in the <caption> element. By default, these are rendered above the table in the document. You use the caption-side property to control the placement of the table caption."
},
{
"code": null,
"e": 3689,
"s": 3478,
"text": "The caption-side captions are presented in the <caption> element. By default, these are rendered above the table in the document. You use the caption-side property to control the placement of the table caption."
},
{
"code": null,
"e": 3770,
"s": 3689,
"text": "The empty-cells specifies whether the border should be shown if a cell is empty."
},
{
"code": null,
"e": 3851,
"s": 3770,
"text": "The empty-cells specifies whether the border should be shown if a cell is empty."
},
{
"code": null,
"e": 4055,
"s": 3851,
"text": "The table-layout allows browsers to speed up layout of a table by using the first width properties it comes across for the rest of a column rather than having to load the whole table before rendering it."
},
{
"code": null,
"e": 4259,
"s": 4055,
"text": "The table-layout allows browsers to speed up layout of a table by using the first width properties it comes across for the rest of a column rather than having to load the whole table before rendering it."
},
{
"code": null,
"e": 4319,
"s": 4259,
"text": "Now, we will see how to use these properties with examples."
},
{
"code": null,
"e": 4421,
"s": 4319,
"text": "This property can have two values collapse and separate. The following example uses both the values −"
},
{
"code": null,
"e": 5402,
"s": 4421,
"text": "<html>\n <head>\n <style type = \"text/css\">\n table.one {border-collapse:collapse;}\n table.two {border-collapse:separate;}\n \n td.a {\n border-style:dotted; \n border-width:3px; \n border-color:#000000; \n padding: 10px;\n }\n td.b {\n border-style:solid; \n border-width:3px; \n border-color:#333333; \n padding:10px;\n }\n </style>\n </head>\n\n <body>\n <table class = \"one\">\n <caption>Collapse Border Example</caption>\n <tr><td class = \"a\"> Cell A Collapse Example</td></tr>\n <tr><td class = \"b\"> Cell B Collapse Example</td></tr>\n </table>\n <br />\n \n <table class = \"two\">\n <caption>Separate Border Example</caption>\n <tr><td class = \"a\"> Cell A Separate Example</td></tr>\n <tr><td class = \"b\"> Cell B Separate Example</td></tr>\n </table>\n </body>\n</html>"
},
{
"code": null,
"e": 5441,
"s": 5402,
"text": "It will produce the following result −"
},
{
"code": null,
"e": 5604,
"s": 5441,
"text": "The border-spacing property specifies the distance that separates adjacent cells'. borders. It can take either one or two values; these should be units of length."
},
{
"code": null,
"e": 5817,
"s": 5604,
"text": "If you provide one value, it will applies to both vertical and horizontal borders. Or you can specify two values, in which case, the first refers to the horizontal spacing and the second to the vertical spacing −"
},
{
"code": null,
"e": 5890,
"s": 5817,
"text": "NOTE − Unfortunately, this property does not work in Netscape 7 or IE 6."
},
{
"code": null,
"e": 6092,
"s": 5890,
"text": "<style type=\"text/css\">\n /* If you provide one value */\n table.example {border-spacing:10px;}\n /* This is how you can provide two values */\n table.example {border-spacing:10px; 15px;}\n</style>\n"
},
{
"code": null,
"e": 6151,
"s": 6092,
"text": "Now let's modify the previous example and see the effect −"
},
{
"code": null,
"e": 7013,
"s": 6151,
"text": "<html>\n <head>\n <style type = \"text/css\">\n table.one {\n border-collapse:separate;\n width:400px;\n border-spacing:10px;\n }\n table.two {\n border-collapse:separate;\n width:400px;\n border-spacing:10px 50px;\n }\n </style>\n </head>\n\n <body>\n \n <table class = \"one\" border = \"1\">\n <caption>Separate Border Example with border-spacing</caption>\n <tr><td> Cell A Collapse Example</td></tr>\n <tr><td> Cell B Collapse Example</td></tr>\n </table>\n <br />\n \n <table class = \"two\" border = \"1\">\n <caption>Separate Border Example with border-spacing</caption>\n <tr><td> Cell A Separate Example</td></tr>\n <tr><td> Cell B Separate Example</td></tr>\n </table>\n \n </body>\n</html> "
},
{
"code": null,
"e": 7052,
"s": 7013,
"text": "It will produce the following result −"
},
{
"code": null,
"e": 7238,
"s": 7052,
"text": "The caption-side property allows you to specify where the content of a <caption> element should be placed in relationship to the table. The table that follows lists the possible values."
},
{
"code": null,
"e": 7353,
"s": 7238,
"text": "This property can have one of the four values top, bottom, left or right. The following example uses each value."
},
{
"code": null,
"e": 7412,
"s": 7353,
"text": "NOTE − These properties may not work with your IE Browser."
},
{
"code": null,
"e": 8768,
"s": 7412,
"text": "<html>\n <head>\n <style type = \"text/css\">\n caption.top {caption-side:top}\n caption.bottom {caption-side:bottom}\n caption.left {caption-side:left}\n caption.right {caption-side:right}\n </style>\n </head>\n\n <body>\n \n <table style = \"width:400px; border:1px solid black;\">\n <caption class = \"top\">\n This caption will appear at the top\n </caption>\n <tr><td > Cell A</td></tr>\n <tr><td > Cell B</td></tr>\n </table>\n <br />\n \n <table style = \"width:400px; border:1px solid black;\">\n <caption class = \"bottom\">\n This caption will appear at the bottom\n </caption>\n <tr><td > Cell A</td></tr>\n <tr><td > Cell B</td></tr>\n </table>\n <br />\n \n <table style = \"width:400px; border:1px solid black;\">\n <caption class = \"left\">\n This caption will appear at the left\n </caption>\n <tr><td > Cell A</td></tr>\n <tr><td > Cell B</td></tr>\n </table>\n <br />\n \n <table style = \"width:400px; border:1px solid black;\">\n <caption class = \"right\">\n This caption will appear at the right\n </caption>\n <tr><td > Cell A</td></tr>\n <tr><td > Cell B</td></tr>\n </table>\n \n </body>\n</html>"
},
{
"code": null,
"e": 8807,
"s": 8768,
"text": "It will produce the following result −"
},
{
"code": null,
"e": 8909,
"s": 8807,
"text": "The empty-cells property indicates whether a cell without any content should have a border displayed."
},
{
"code": null,
"e": 8981,
"s": 8909,
"text": "This property can have one of the three values - show, hide or inherit."
},
{
"code": null,
"e": 9074,
"s": 8981,
"text": "Here is the empty-cells property used to hide borders of empty cells in the <table> element."
},
{
"code": null,
"e": 9929,
"s": 9074,
"text": "<html>\n <head>\n <style type = \"text/css\">\n table.empty {\n width:350px;\n border-collapse:separate;\n empty-cells:hide;\n }\n td.empty {\n padding:5px;\n border-style:solid;\n border-width:1px;\n border-color:#999999;\n }\n </style>\n </head>\n\n <body>\n \n <table class = \"empty\">\n <tr>\n <th></th>\n <th>Title one</th>\n <th>Title two</th>\n </tr>\n \n <tr>\n <th>Row Title</th>\n <td class = \"empty\">value</td>\n <td class = \"empty\">value</td>\n </tr>\n \n <tr>\n <th>Row Title</th>\n <td class = \"empty\">value</td>\n <td class = \"empty\"></td>\n </tr>\n </table>\n \n </body>\n</html> "
},
{
"code": null,
"e": 9968,
"s": 9929,
"text": "It will produce the following result −"
},
{
"code": null,
"e": 10074,
"s": 9968,
"text": "The table-layout property is supposed to help you control how a browser should render or lay out a table."
},
{
"code": null,
"e": 10147,
"s": 10074,
"text": "This property can have one of the three values: fixed, auto or inherit. "
},
{
"code": null,
"e": 10216,
"s": 10147,
"text": "The following example shows the difference between these properties."
},
{
"code": null,
"e": 10304,
"s": 10216,
"text": "NOTE − This property is not supported by many browsers so do not rely on this property."
},
{
"code": null,
"e": 11068,
"s": 10304,
"text": "<html>\n <head>\n <style type = \"text/css\">\n table.auto {\n table-layout: auto\n }\n table.fixed {\n table-layout: fixed\n }\n </style>\n </head>\n \n <body>\n \n <table class = \"auto\" border = \"1\" width = \"100%\">\n <tr>\n <td width = \"20%\">1000000000000000000000000000</td>\n <td width = \"40%\">10000000</td>\n <td width = \"40%\">100</td>\n </tr>\n </table>\n <br />\n \n <table class = \"fixed\" border = \"1\" width = \"100%\">\n <tr>\n <td width = \"20%\">1000000000000000000000000000</td>\n <td width = \"40%\">10000000</td>\n <td width = \"40%\">100</td>\n </tr>\n </table>\n \n </body>\n</html> "
},
{
"code": null,
"e": 11107,
"s": 11068,
"text": "It will produce the following result −"
},
{
"code": null,
"e": 11142,
"s": 11107,
"text": "\n 33 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 11156,
"s": 11142,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 11191,
"s": 11156,
"text": "\n 26 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 11208,
"s": 11191,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 11243,
"s": 11208,
"text": "\n 44 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 11274,
"s": 11243,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 11309,
"s": 11274,
"text": "\n 21 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 11340,
"s": 11309,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 11375,
"s": 11340,
"text": "\n 51 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 11406,
"s": 11375,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 11439,
"s": 11406,
"text": "\n 52 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 11470,
"s": 11439,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 11477,
"s": 11470,
"text": " Print"
},
{
"code": null,
"e": 11488,
"s": 11477,
"text": " Add Notes"
}
] |
How to detect touch screen device using CSS ? - GeeksforGeeks | 18 May, 2021
In a website, it becomes important to detect the pointing device used by the user. For example, if the user uses a finger as the pointing device (which has less accuracy on the screen due to more screen-finger contact area) then we should increase the size of various elements like buttons, links, input fields, etc. so that the user feels comfortable using the website.
A touchscreen device can easily be detected using CSS media queries or by using JavaScript.
HTML alone cannot detect touchscreen devices. Along with HTML, we will need CSS media queries. In CSS media queries we have a feature called pointer used to detect the pointing accuracy of the pointing device used by the user. It has the following 3 values.
pointer: none: It gets triggered when the input mechanism of the device has no pointing device.
pointer: coarse: It gets triggered when the input mechanism of the pointing device has less accuracy. For example, touchscreens.
pointer: fine: It gets triggered when the input mechanism of the pointing device has high accuracy. For example, mouse, trackpad, stylus, etc.
HTML Code: The following code detects if the user is using a touchscreen device or not.
HTML
<!-- HTML code to detect a touch screen device --><!DOCTYPE html><html lang="en"> <head> <style> /* By default, setting the image display to none */ #image-GFG { display: none; } /* In case of touch-screen device, setting image display to block. Using @media to detect pointer accuracy */ @media (pointer:coarse) { #image-GFG { display: block; } } </style></head> <body> <h2> This image will only be visible on a touch screen device </h2> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20210513020603/GFG.png" id="image-GFG"></body> </html>
Output:
Output on the touch screen:
Output from a smartphone
Output on the non-touch screen:
Output from a non touch-screen desktop
Note: To test output on a smartphone, copy the above code into a .html file and transfer it to the smartphone and open it using any browser like Chrome or Safari.
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
CSS-Properties
CSS-Questions
HTML-Questions
Picked
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Design a web page using HTML and CSS
Form validation using jQuery
How to set space between the flexbox ?
Search Bar using HTML, CSS and JavaScript
How to style a checkbox using CSS?
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
Hide or show elements in HTML using display property
How to Insert Form Data into Database using PHP ?
REST API (Introduction) | [
{
"code": null,
"e": 24985,
"s": 24957,
"text": "\n18 May, 2021"
},
{
"code": null,
"e": 25356,
"s": 24985,
"text": "In a website, it becomes important to detect the pointing device used by the user. For example, if the user uses a finger as the pointing device (which has less accuracy on the screen due to more screen-finger contact area) then we should increase the size of various elements like buttons, links, input fields, etc. so that the user feels comfortable using the website."
},
{
"code": null,
"e": 25449,
"s": 25356,
"text": "A touchscreen device can easily be detected using CSS media queries or by using JavaScript. "
},
{
"code": null,
"e": 25707,
"s": 25449,
"text": "HTML alone cannot detect touchscreen devices. Along with HTML, we will need CSS media queries. In CSS media queries we have a feature called pointer used to detect the pointing accuracy of the pointing device used by the user. It has the following 3 values."
},
{
"code": null,
"e": 25803,
"s": 25707,
"text": "pointer: none: It gets triggered when the input mechanism of the device has no pointing device."
},
{
"code": null,
"e": 25932,
"s": 25803,
"text": "pointer: coarse: It gets triggered when the input mechanism of the pointing device has less accuracy. For example, touchscreens."
},
{
"code": null,
"e": 26075,
"s": 25932,
"text": "pointer: fine: It gets triggered when the input mechanism of the pointing device has high accuracy. For example, mouse, trackpad, stylus, etc."
},
{
"code": null,
"e": 26163,
"s": 26075,
"text": "HTML Code: The following code detects if the user is using a touchscreen device or not."
},
{
"code": null,
"e": 26168,
"s": 26163,
"text": "HTML"
},
{
"code": "<!-- HTML code to detect a touch screen device --><!DOCTYPE html><html lang=\"en\"> <head> <style> /* By default, setting the image display to none */ #image-GFG { display: none; } /* In case of touch-screen device, setting image display to block. Using @media to detect pointer accuracy */ @media (pointer:coarse) { #image-GFG { display: block; } } </style></head> <body> <h2> This image will only be visible on a touch screen device </h2> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20210513020603/GFG.png\" id=\"image-GFG\"></body> </html>",
"e": 26898,
"s": 26168,
"text": null
},
{
"code": null,
"e": 26906,
"s": 26898,
"text": "Output:"
},
{
"code": null,
"e": 26948,
"s": 26906,
"text": "Output on the touch screen: "
},
{
"code": null,
"e": 26974,
"s": 26948,
"text": "Output from a smartphone "
},
{
"code": null,
"e": 27006,
"s": 26974,
"text": "Output on the non-touch screen:"
},
{
"code": null,
"e": 27045,
"s": 27006,
"text": "Output from a non touch-screen desktop"
},
{
"code": null,
"e": 27208,
"s": 27045,
"text": "Note: To test output on a smartphone, copy the above code into a .html file and transfer it to the smartphone and open it using any browser like Chrome or Safari."
},
{
"code": null,
"e": 27345,
"s": 27208,
"text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course."
},
{
"code": null,
"e": 27360,
"s": 27345,
"text": "CSS-Properties"
},
{
"code": null,
"e": 27374,
"s": 27360,
"text": "CSS-Questions"
},
{
"code": null,
"e": 27389,
"s": 27374,
"text": "HTML-Questions"
},
{
"code": null,
"e": 27396,
"s": 27389,
"text": "Picked"
},
{
"code": null,
"e": 27400,
"s": 27396,
"text": "CSS"
},
{
"code": null,
"e": 27405,
"s": 27400,
"text": "HTML"
},
{
"code": null,
"e": 27422,
"s": 27405,
"text": "Web Technologies"
},
{
"code": null,
"e": 27427,
"s": 27422,
"text": "HTML"
},
{
"code": null,
"e": 27525,
"s": 27427,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27534,
"s": 27525,
"text": "Comments"
},
{
"code": null,
"e": 27547,
"s": 27534,
"text": "Old Comments"
},
{
"code": null,
"e": 27584,
"s": 27547,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 27613,
"s": 27584,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 27652,
"s": 27613,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 27694,
"s": 27652,
"text": "Search Bar using HTML, CSS and JavaScript"
},
{
"code": null,
"e": 27729,
"s": 27694,
"text": "How to style a checkbox using CSS?"
},
{
"code": null,
"e": 27789,
"s": 27729,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 27850,
"s": 27789,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 27903,
"s": 27850,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 27953,
"s": 27903,
"text": "How to Insert Form Data into Database using PHP ?"
}
] |
Flutter - DatePicker - GeeksforGeeks | 15 Feb, 2021
The flutter, syncfusion date range picker is a widget that is used to select single or multiple dates along with the range between two dates. The use of this library makes the navigation between dates, weeks, months, years, and even centuries simple and easy.
The following are the key features of DatePicker:
1. Multiple Picker View:
This feature allows the user to navigate between dates, months, year, and centuries with ease as shown below:
2. Multi Date Picker View:
It supports selecting single and multiple dates and also supports selecting a range between two dates as shown below:
3. RLT support:
This feature is helpful for users who interact in a language that is written in Right to left manners like Arabic and Hebrew as shown below:
4. Globalization:
It also displays the current date-time according to global standards.
Now let’s look into its implementation in a flutter application by building a simple application. To build the app, follow the below steps:
Add the dependency to the pubspec.yaml file
Import the dependency to the main.dart file
Structure an app with a StatefulWidget
Set the state for the dates
Call the SfDateRangePicker method in the body of the app
Now, let’s look into the steps in detail:
Add syncfusion_flutter_datepicker, in the dependencies section of the pubspec.yaml file as shown below:
To import the dependency in the main.dart file, use the below line of code:
import 'package:syncfusion_flutter_datepicker/datepicker.dart';
Use a StatefulWidget, and extend it to an appbar and a body for getting a simple app structure as shown below:
Dart
class MyApp extends StatefulWidget { @override MyAppState createState() => MyAppState();} @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: const Text('GeeksForGeeks'), backgroundColor: Colors.green, ), body: )); }}
The set that we will set up in the app will be responsible for storing the selected date/dates and information regarding the range if two dates are selected. It can be done as shown below:
Dart
class MyAppState extends State<MyApp> { String _dateCount; String _range; @override void initState() { _dateCount = ''; _range = ''; super.initState(); } void _onSelectionChanged(DateRangePickerSelectionChangedArgs args) { setState(() { if (args.value is PickerDateRange) { _range = DateFormat('dd/MM/yyyy').format(args.value.startDate).toString() + ' - ' + DateFormat('dd/MM/yyyy') .format(args.value.endDate ?? args.value.startDate) .toString(); } else if (args.value is DateTime) { } else if (args.value is List<DateTime>) { _dateCount = args.value.length.toString(); } }); }
The SFDateRangePicker method is an inbuilt method provided by the syncfusion_flutter_datepicker library to get the range between two dates. This method will be called inside the body of the application as shown below:
Dart
child: SfDateRangePicker( onSelectionChanged: _onSelectionChanged, selectionMode: DateRangePickerSelectionMode.range, initialSelectedRange: PickerDateRange( DateTime.now().subtract(const Duration(days: 4)), DateTime.now().add(const Duration(days: 3))), ),
Complete Source Code:
Dart
import 'package:flutter/material.dart';import 'package:intl/intl.dart';import 'package:syncfusion_flutter_datepicker/datepicker.dart'; void main() { return runApp(MyApp());} /// app rootclass MyApp extends StatefulWidget { @override MyAppState createState() => MyAppState();} /// app stateclass MyAppState extends State<MyApp> { String _dateCount; String _range; @override void initState() { _dateCount = ''; _range = ''; super.initState(); } void _onSelectionChanged(DateRangePickerSelectionChangedArgs args) { setState(() { if (args.value is PickerDateRange) { _range = DateFormat('dd/MM/yyyy').format(args.value.startDate).toString() + ' - ' + DateFormat('dd/MM/yyyy') .format(args.value.endDate ?? args.value.startDate) .toString(); } else if (args.value is DateTime) { } else if (args.value is List<DateTime>) { _dateCount = args.value.length.toString(); } }); } @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: const Text('GeeksForGeeks'), backgroundColor: Colors.green, ), body: Stack( children: <Widget>[ Positioned( left: 0, top: 80, right: 0, bottom: 0, child: SfDateRangePicker( onSelectionChanged: _onSelectionChanged, selectionMode: DateRangePickerSelectionMode.range, initialSelectedRange: PickerDateRange( DateTime.now().subtract(const Duration(days: 4)), DateTime.now().add(const Duration(days: 3))), ), ) ], ))); }}
Output:
android
Flutter
Flutter UI-components
Dart
Flutter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Flutter - Custom Bottom Navigation Bar
ListView Class in Flutter
Flutter - Flexible Widget
Flutter - Stack Widget
What is widgets in Flutter?
Flutter - Custom Bottom Navigation Bar
Flutter Tutorial
Flutter - Flexible Widget
Flutter - Stack Widget
Flutter - BorderRadius Widget | [
{
"code": null,
"e": 24010,
"s": 23982,
"text": "\n15 Feb, 2021"
},
{
"code": null,
"e": 24270,
"s": 24010,
"text": "The flutter, syncfusion date range picker is a widget that is used to select single or multiple dates along with the range between two dates. The use of this library makes the navigation between dates, weeks, months, years, and even centuries simple and easy."
},
{
"code": null,
"e": 24320,
"s": 24270,
"text": "The following are the key features of DatePicker:"
},
{
"code": null,
"e": 24345,
"s": 24320,
"text": "1. Multiple Picker View:"
},
{
"code": null,
"e": 24455,
"s": 24345,
"text": "This feature allows the user to navigate between dates, months, year, and centuries with ease as shown below:"
},
{
"code": null,
"e": 24482,
"s": 24455,
"text": "2. Multi Date Picker View:"
},
{
"code": null,
"e": 24600,
"s": 24482,
"text": "It supports selecting single and multiple dates and also supports selecting a range between two dates as shown below:"
},
{
"code": null,
"e": 24617,
"s": 24600,
"text": "3. RLT support: "
},
{
"code": null,
"e": 24758,
"s": 24617,
"text": "This feature is helpful for users who interact in a language that is written in Right to left manners like Arabic and Hebrew as shown below:"
},
{
"code": null,
"e": 24776,
"s": 24758,
"text": "4. Globalization:"
},
{
"code": null,
"e": 24846,
"s": 24776,
"text": "It also displays the current date-time according to global standards."
},
{
"code": null,
"e": 24986,
"s": 24846,
"text": "Now let’s look into its implementation in a flutter application by building a simple application. To build the app, follow the below steps:"
},
{
"code": null,
"e": 25030,
"s": 24986,
"text": "Add the dependency to the pubspec.yaml file"
},
{
"code": null,
"e": 25074,
"s": 25030,
"text": "Import the dependency to the main.dart file"
},
{
"code": null,
"e": 25113,
"s": 25074,
"text": "Structure an app with a StatefulWidget"
},
{
"code": null,
"e": 25141,
"s": 25113,
"text": "Set the state for the dates"
},
{
"code": null,
"e": 25198,
"s": 25141,
"text": "Call the SfDateRangePicker method in the body of the app"
},
{
"code": null,
"e": 25240,
"s": 25198,
"text": "Now, let’s look into the steps in detail:"
},
{
"code": null,
"e": 25344,
"s": 25240,
"text": "Add syncfusion_flutter_datepicker, in the dependencies section of the pubspec.yaml file as shown below:"
},
{
"code": null,
"e": 25420,
"s": 25344,
"text": "To import the dependency in the main.dart file, use the below line of code:"
},
{
"code": null,
"e": 25485,
"s": 25420,
"text": "import 'package:syncfusion_flutter_datepicker/datepicker.dart';\n"
},
{
"code": null,
"e": 25596,
"s": 25485,
"text": "Use a StatefulWidget, and extend it to an appbar and a body for getting a simple app structure as shown below:"
},
{
"code": null,
"e": 25601,
"s": 25596,
"text": "Dart"
},
{
"code": "class MyApp extends StatefulWidget { @override MyAppState createState() => MyAppState();} @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: const Text('GeeksForGeeks'), backgroundColor: Colors.green, ), body: )); }}",
"e": 25961,
"s": 25601,
"text": null
},
{
"code": null,
"e": 26150,
"s": 25961,
"text": "The set that we will set up in the app will be responsible for storing the selected date/dates and information regarding the range if two dates are selected. It can be done as shown below:"
},
{
"code": null,
"e": 26155,
"s": 26150,
"text": "Dart"
},
{
"code": "class MyAppState extends State<MyApp> { String _dateCount; String _range; @override void initState() { _dateCount = ''; _range = ''; super.initState(); } void _onSelectionChanged(DateRangePickerSelectionChangedArgs args) { setState(() { if (args.value is PickerDateRange) { _range = DateFormat('dd/MM/yyyy').format(args.value.startDate).toString() + ' - ' + DateFormat('dd/MM/yyyy') .format(args.value.endDate ?? args.value.startDate) .toString(); } else if (args.value is DateTime) { } else if (args.value is List<DateTime>) { _dateCount = args.value.length.toString(); } }); }",
"e": 26875,
"s": 26155,
"text": null
},
{
"code": null,
"e": 27093,
"s": 26875,
"text": "The SFDateRangePicker method is an inbuilt method provided by the syncfusion_flutter_datepicker library to get the range between two dates. This method will be called inside the body of the application as shown below:"
},
{
"code": null,
"e": 27098,
"s": 27093,
"text": "Dart"
},
{
"code": "child: SfDateRangePicker( onSelectionChanged: _onSelectionChanged, selectionMode: DateRangePickerSelectionMode.range, initialSelectedRange: PickerDateRange( DateTime.now().subtract(const Duration(days: 4)), DateTime.now().add(const Duration(days: 3))), ),",
"e": 27474,
"s": 27098,
"text": null
},
{
"code": null,
"e": 27496,
"s": 27474,
"text": "Complete Source Code:"
},
{
"code": null,
"e": 27501,
"s": 27496,
"text": "Dart"
},
{
"code": "import 'package:flutter/material.dart';import 'package:intl/intl.dart';import 'package:syncfusion_flutter_datepicker/datepicker.dart'; void main() { return runApp(MyApp());} /// app rootclass MyApp extends StatefulWidget { @override MyAppState createState() => MyAppState();} /// app stateclass MyAppState extends State<MyApp> { String _dateCount; String _range; @override void initState() { _dateCount = ''; _range = ''; super.initState(); } void _onSelectionChanged(DateRangePickerSelectionChangedArgs args) { setState(() { if (args.value is PickerDateRange) { _range = DateFormat('dd/MM/yyyy').format(args.value.startDate).toString() + ' - ' + DateFormat('dd/MM/yyyy') .format(args.value.endDate ?? args.value.startDate) .toString(); } else if (args.value is DateTime) { } else if (args.value is List<DateTime>) { _dateCount = args.value.length.toString(); } }); } @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: const Text('GeeksForGeeks'), backgroundColor: Colors.green, ), body: Stack( children: <Widget>[ Positioned( left: 0, top: 80, right: 0, bottom: 0, child: SfDateRangePicker( onSelectionChanged: _onSelectionChanged, selectionMode: DateRangePickerSelectionMode.range, initialSelectedRange: PickerDateRange( DateTime.now().subtract(const Duration(days: 4)), DateTime.now().add(const Duration(days: 3))), ), ) ], ))); }}",
"e": 29382,
"s": 27501,
"text": null
},
{
"code": null,
"e": 29390,
"s": 29382,
"text": "Output:"
},
{
"code": null,
"e": 29398,
"s": 29390,
"text": "android"
},
{
"code": null,
"e": 29406,
"s": 29398,
"text": "Flutter"
},
{
"code": null,
"e": 29428,
"s": 29406,
"text": "Flutter UI-components"
},
{
"code": null,
"e": 29433,
"s": 29428,
"text": "Dart"
},
{
"code": null,
"e": 29441,
"s": 29433,
"text": "Flutter"
},
{
"code": null,
"e": 29539,
"s": 29441,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29578,
"s": 29539,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 29604,
"s": 29578,
"text": "ListView Class in Flutter"
},
{
"code": null,
"e": 29630,
"s": 29604,
"text": "Flutter - Flexible Widget"
},
{
"code": null,
"e": 29653,
"s": 29630,
"text": "Flutter - Stack Widget"
},
{
"code": null,
"e": 29681,
"s": 29653,
"text": "What is widgets in Flutter?"
},
{
"code": null,
"e": 29720,
"s": 29681,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 29737,
"s": 29720,
"text": "Flutter Tutorial"
},
{
"code": null,
"e": 29763,
"s": 29737,
"text": "Flutter - Flexible Widget"
},
{
"code": null,
"e": 29786,
"s": 29763,
"text": "Flutter - Stack Widget"
}
] |
Spatial Data Solution for City Planning in Indonesia: Understanding The GeoDataFrame | by Sutan Ashari Mufti | Towards Data Science | Geographic Information System (GIS) is an essential skill an urban planner must-have. With GIS, urban planners may manage, publish, and analyze spatial data. The spatial data is distinct to ordinary data as spatial data has a spatial element that sometimes people overlook. The awareness and intuition about the “spatial” are what makes an urban planner, or geographer powerful.
As an Indonesian Urban Planner, I deal with spatial data every day, and this essay is inspired by a dataset that is published by Jakarta City, Indonesia. I must say, Jakarta City’s spatial data repository impresses me! It is structured, readable, processable, and well maintained. You do not need digitation. It is a great example of the spatial data repository that many boroughs must look up to. But there’s this one “spatial” data from the Jakarta’s Open Data Portal that raises questions (at least, to me): The Routes of Public Transportation.
The routes are described in a manner that is understandable for people, but not parsable for computers in a geographical sense. For example, where is “Jl. Raya Bekasi” street? How long it is? How does it curve? What are the geometrical properties? To a data analyst like me, this is infuriating. We must look for the street, plot it in GIS software so that we can do further analysis with the computer. This (digitation) process spends time, and time is money. The unprepared data costs analysts and produces tedious works.
Let’s look at another example: a map like illustrated by the figure below. This is supposed to be a map of an Angkot (“public transportation — Minibus”) route.
It is not a map per se, it is a diagram. Geometrical properties in the “map” are just a diagrammatical representation. The length and distance are not the true scaled distance, this is why the “map” does not have a coordinate system/reference.
An attempt to include spatial data such as illustrated above should be appreciated. It holds information, but we can do more.
Now, how should we analyze this spatial data computationally? If you’ve worked with much data especially spatial data, I’m sure you quite understand what I’m talking about. Imagine the digitizing, and cleaning the data. This is not efficient, and only one person/entity should do the cleansing so that not everyone has to. The solution is simple, the provision of standardized, formated, and parsable spatial data.
The spatial data has so many formats. Most popular, I guess, is the Shapefile (.shp) format developed by Esri in the '90s which is pretty old! This is 2020, it’s been a decade since the era of shapefile, surely many data and techniques have been developed. As I play around with Python, I noticed a connection between GeoDataFrame and the spatial data problems that I encountered. So, this essay introduces another type of geospatial data, GeoDataFame, and how it can solve the spatial data attribute problem for Indonesia.
This essay consists of 5 parts:
What is GeoDataFrame? (explains what is GeoDataFrame and how it is different with conventional spreadsheets)Why GeoDataFrame? (the reason for choosing GeoDataFrame, because it is intuitive to most people)Storing The Geometrical Attribute (showing the manifestation/form of the geometrical data. We will use Shapely in Python, but don’t worry about Python, you don’t have to understand Python)How we Store and Distribute the GeoDataFrame (so that people that are familiar and not familiar with spatial data can still understand the data)Concluding Remarks (summarizing and recommendation of what we should do to get started)
What is GeoDataFrame? (explains what is GeoDataFrame and how it is different with conventional spreadsheets)
Why GeoDataFrame? (the reason for choosing GeoDataFrame, because it is intuitive to most people)
Storing The Geometrical Attribute (showing the manifestation/form of the geometrical data. We will use Shapely in Python, but don’t worry about Python, you don’t have to understand Python)
How we Store and Distribute the GeoDataFrame (so that people that are familiar and not familiar with spatial data can still understand the data)
Concluding Remarks (summarizing and recommendation of what we should do to get started)
GeoDataFrame is a spatial data frame that is used by GeoPandas as an object to operate. When we use GeoPandas to analyze and manage spatial data, GeoDataFrame is the target object. The official explanation of GeoDataFrame from GeoPandas is
“A GeoDataFrame is a tabular data structure that contains a GeoSeries.” — GeoPandas
what is a GeoSeries? GeoSeries is a vector that contains the geometries of the data. We can imagine a vector as a single column spreadsheet. It is represented as a column named “geometry” in a GeoDataFrame. I always think of the definition to be confusing and visualizing it always helps. Here’s what a GeoDataFrame look like:
As you can see, a GeoDataFrame is basically a spreadsheet that contains one column of geometry. I’d like to say that GeoDataFrame is like rows of data that have a geometry property. Each feature (each row) has values and a geometric property. For instance, as illustrated, “Pulau Tidung” has a population of 11305 with a geometry described in the geometry column.
When we plot or do spatial analysis, this “geometry” column is the one that is being processed. Dissecting the GeoDataFrame there are 3 components:
The DataFrame: this is the rows and columns of the data. We can imagine this like a Ms. excel spreadsheet. Here we can statistically describe and analyze the features. For instance, what village has the highest population? How’s each village’s population density? (but not spatial interaction)
The Geometry: this is a column that comprises corresponding geometry for each row (feature). This is what defines the spatial element of the data
The Coordinate Reference: Geographical reference of the geometry. For instance, a point with coordinate x=8 and y=15; where is the 0 here that each X and Y can refer? Commonly we use WGS 1984 (World Geodetic System, EPSG 4326) or as most people know, the Longitude and Latitude. You can see that in the first figure, in the “geometry” column, it holds Longitude and Latitude values).
We can also plot the geometry line and make a map. In this example, the population of Jakarta City. Instead of graphs, we can use Choropleth map so that we can overview the spatial relationships.
Geodataframe is more readable to more common people. GeoDataFrame is basically a table, and everyone knows what a table is, so it’s intuitive. Unlike Shapefile that, I think, not everyone knows.
If you’re familiar with python, it’s basically a Pandas Dataframe with one additional column that holds the geometric properties. We can do Pandas methods to GeoDataFrame.
Now, what is the value is inside this geometry column? We’re going to use some Python nomenclatures, but it’s not that complicated as it is pretty much straight forward. Please bear with me a little.
There are 3 main spatial data types:
Points: this is pretty straight forward. Points indicate the location and toponyms. Points are one dimensional and contain 1 coordinate. (expect multipoint, which has many coordinates with the same attributes, but they don’t makeup lines or areas)
Polylines: Lines or Polylines are sets of coordinates that are connected by a line. We can use Polylines to describe networks such as pipes, roads, or rail networks.
Polygon: Polygon is enclosed lines so it has an area. Used to describe administrative boundaries, zoning regulations, basis of a choropleth map.
So Spatial data is basically a bunch of coordinates!
By their nature, Polylines and Polygons consist of vertices. These vertices are Points’ coordinates that are held in the Geometry column. As we can see in the figure below when a value of geometry is expanded, it contains many coordinates of Latitude and Longitude, and when we visualize these vertices, it draws a shape.
Each geometry is an object of Shapely, a library of Python. Shapely deals with geometrics for math purposes. We can do much spatial analysis such as intersections, unions, and many more. This is a very brief introduction: for example, if I want to create a geometric object, what I need to do is write some command to Python like this:
>> from shapely.geometry import Polygon>> Polygon([(104.4, -6.2),(106.4, -7.0), (103.2, -8.9)]
This will create a rectangle as there are 3 vertices (3 coordinates).
Of course, to define each feature’s geometry we do not put it manually. Instead, we can integrate sensors such as GPS to automate the task or do some conversions with some scripts.
While shapefile is very popular I think GeoJSON is neater. Shapefile consists of separate files, besides the geometry itself, such as the projections and the attributes; while GeoJSON is only one “text” file.
Web service that fulfills the OGC standard is a must, this allows websites and algorithms to connect remotely, but sometimes users need downloadable data with common and popular formats such as .xlsx or .csv.
There are several options that I recommend:
Save it as CSV: because the spatial data must be accessible to many people from many backgrounds, the simplest way to store is to convert the GeoDataFrame to a CSV (comma-separated values). This way, spreadsheet software can parse the CSV to become a tablature format. The caveat is that the “geometry” column will be stored as text, so to convert it to the geometric (shapely) object we need further parsing. A web application or some simple script should do the job. It’s an option, but I don’t think this option is preferred.
Save the Dataframe as CSV, and Geometry column as a separate GeoJSON: This yields 2 files; a CSV and a GeoJSON. Don’t worry about GeoJSOn, it’s basically a text file. GeoJSON is a format for interoperability between systems or software. With GeoJSON, many software or websites can parse the text and plot the geometries. The GeoJSON objects will be indexed so that it can be joined with CSV.
I think there should be an awareness of spatial attributes in datasets. Spatial attributes are as crucial as the data frame itself, and should not be separated. A spreadsheet (.xlsx, CSV, many more) must be accompanied by geometry in a GeoJSON format, or even embedded in the CSV itself. A tabular data format must have a column that defines the geometry of each feature whenever geometric properties are suitable. Why GeoDataFrame, CSV or GeoJSON? So it is readable to human eyes to those who are not common to spatial data, and common to spatial data. The geometry must consist of coordinate(s).
I think Including GeoDataFrame should increase the intuition to many people that features do have spatial attributes, and spatially interactable. GeoDataFrame also enables us to compute spatial data in an efficient way. To get started, We can do as simple as “only” adding one column to each of our spreadsheets, that is, the geometry column. | [
{
"code": null,
"e": 551,
"s": 172,
"text": "Geographic Information System (GIS) is an essential skill an urban planner must-have. With GIS, urban planners may manage, publish, and analyze spatial data. The spatial data is distinct to ordinary data as spatial data has a spatial element that sometimes people overlook. The awareness and intuition about the “spatial” are what makes an urban planner, or geographer powerful."
},
{
"code": null,
"e": 1099,
"s": 551,
"text": "As an Indonesian Urban Planner, I deal with spatial data every day, and this essay is inspired by a dataset that is published by Jakarta City, Indonesia. I must say, Jakarta City’s spatial data repository impresses me! It is structured, readable, processable, and well maintained. You do not need digitation. It is a great example of the spatial data repository that many boroughs must look up to. But there’s this one “spatial” data from the Jakarta’s Open Data Portal that raises questions (at least, to me): The Routes of Public Transportation."
},
{
"code": null,
"e": 1623,
"s": 1099,
"text": "The routes are described in a manner that is understandable for people, but not parsable for computers in a geographical sense. For example, where is “Jl. Raya Bekasi” street? How long it is? How does it curve? What are the geometrical properties? To a data analyst like me, this is infuriating. We must look for the street, plot it in GIS software so that we can do further analysis with the computer. This (digitation) process spends time, and time is money. The unprepared data costs analysts and produces tedious works."
},
{
"code": null,
"e": 1783,
"s": 1623,
"text": "Let’s look at another example: a map like illustrated by the figure below. This is supposed to be a map of an Angkot (“public transportation — Minibus”) route."
},
{
"code": null,
"e": 2027,
"s": 1783,
"text": "It is not a map per se, it is a diagram. Geometrical properties in the “map” are just a diagrammatical representation. The length and distance are not the true scaled distance, this is why the “map” does not have a coordinate system/reference."
},
{
"code": null,
"e": 2153,
"s": 2027,
"text": "An attempt to include spatial data such as illustrated above should be appreciated. It holds information, but we can do more."
},
{
"code": null,
"e": 2568,
"s": 2153,
"text": "Now, how should we analyze this spatial data computationally? If you’ve worked with much data especially spatial data, I’m sure you quite understand what I’m talking about. Imagine the digitizing, and cleaning the data. This is not efficient, and only one person/entity should do the cleansing so that not everyone has to. The solution is simple, the provision of standardized, formated, and parsable spatial data."
},
{
"code": null,
"e": 3092,
"s": 2568,
"text": "The spatial data has so many formats. Most popular, I guess, is the Shapefile (.shp) format developed by Esri in the '90s which is pretty old! This is 2020, it’s been a decade since the era of shapefile, surely many data and techniques have been developed. As I play around with Python, I noticed a connection between GeoDataFrame and the spatial data problems that I encountered. So, this essay introduces another type of geospatial data, GeoDataFame, and how it can solve the spatial data attribute problem for Indonesia."
},
{
"code": null,
"e": 3124,
"s": 3092,
"text": "This essay consists of 5 parts:"
},
{
"code": null,
"e": 3748,
"s": 3124,
"text": "What is GeoDataFrame? (explains what is GeoDataFrame and how it is different with conventional spreadsheets)Why GeoDataFrame? (the reason for choosing GeoDataFrame, because it is intuitive to most people)Storing The Geometrical Attribute (showing the manifestation/form of the geometrical data. We will use Shapely in Python, but don’t worry about Python, you don’t have to understand Python)How we Store and Distribute the GeoDataFrame (so that people that are familiar and not familiar with spatial data can still understand the data)Concluding Remarks (summarizing and recommendation of what we should do to get started)"
},
{
"code": null,
"e": 3857,
"s": 3748,
"text": "What is GeoDataFrame? (explains what is GeoDataFrame and how it is different with conventional spreadsheets)"
},
{
"code": null,
"e": 3954,
"s": 3857,
"text": "Why GeoDataFrame? (the reason for choosing GeoDataFrame, because it is intuitive to most people)"
},
{
"code": null,
"e": 4143,
"s": 3954,
"text": "Storing The Geometrical Attribute (showing the manifestation/form of the geometrical data. We will use Shapely in Python, but don’t worry about Python, you don’t have to understand Python)"
},
{
"code": null,
"e": 4288,
"s": 4143,
"text": "How we Store and Distribute the GeoDataFrame (so that people that are familiar and not familiar with spatial data can still understand the data)"
},
{
"code": null,
"e": 4376,
"s": 4288,
"text": "Concluding Remarks (summarizing and recommendation of what we should do to get started)"
},
{
"code": null,
"e": 4616,
"s": 4376,
"text": "GeoDataFrame is a spatial data frame that is used by GeoPandas as an object to operate. When we use GeoPandas to analyze and manage spatial data, GeoDataFrame is the target object. The official explanation of GeoDataFrame from GeoPandas is"
},
{
"code": null,
"e": 4700,
"s": 4616,
"text": "“A GeoDataFrame is a tabular data structure that contains a GeoSeries.” — GeoPandas"
},
{
"code": null,
"e": 5027,
"s": 4700,
"text": "what is a GeoSeries? GeoSeries is a vector that contains the geometries of the data. We can imagine a vector as a single column spreadsheet. It is represented as a column named “geometry” in a GeoDataFrame. I always think of the definition to be confusing and visualizing it always helps. Here’s what a GeoDataFrame look like:"
},
{
"code": null,
"e": 5391,
"s": 5027,
"text": "As you can see, a GeoDataFrame is basically a spreadsheet that contains one column of geometry. I’d like to say that GeoDataFrame is like rows of data that have a geometry property. Each feature (each row) has values and a geometric property. For instance, as illustrated, “Pulau Tidung” has a population of 11305 with a geometry described in the geometry column."
},
{
"code": null,
"e": 5539,
"s": 5391,
"text": "When we plot or do spatial analysis, this “geometry” column is the one that is being processed. Dissecting the GeoDataFrame there are 3 components:"
},
{
"code": null,
"e": 5833,
"s": 5539,
"text": "The DataFrame: this is the rows and columns of the data. We can imagine this like a Ms. excel spreadsheet. Here we can statistically describe and analyze the features. For instance, what village has the highest population? How’s each village’s population density? (but not spatial interaction)"
},
{
"code": null,
"e": 5979,
"s": 5833,
"text": "The Geometry: this is a column that comprises corresponding geometry for each row (feature). This is what defines the spatial element of the data"
},
{
"code": null,
"e": 6363,
"s": 5979,
"text": "The Coordinate Reference: Geographical reference of the geometry. For instance, a point with coordinate x=8 and y=15; where is the 0 here that each X and Y can refer? Commonly we use WGS 1984 (World Geodetic System, EPSG 4326) or as most people know, the Longitude and Latitude. You can see that in the first figure, in the “geometry” column, it holds Longitude and Latitude values)."
},
{
"code": null,
"e": 6559,
"s": 6363,
"text": "We can also plot the geometry line and make a map. In this example, the population of Jakarta City. Instead of graphs, we can use Choropleth map so that we can overview the spatial relationships."
},
{
"code": null,
"e": 6754,
"s": 6559,
"text": "Geodataframe is more readable to more common people. GeoDataFrame is basically a table, and everyone knows what a table is, so it’s intuitive. Unlike Shapefile that, I think, not everyone knows."
},
{
"code": null,
"e": 6926,
"s": 6754,
"text": "If you’re familiar with python, it’s basically a Pandas Dataframe with one additional column that holds the geometric properties. We can do Pandas methods to GeoDataFrame."
},
{
"code": null,
"e": 7126,
"s": 6926,
"text": "Now, what is the value is inside this geometry column? We’re going to use some Python nomenclatures, but it’s not that complicated as it is pretty much straight forward. Please bear with me a little."
},
{
"code": null,
"e": 7163,
"s": 7126,
"text": "There are 3 main spatial data types:"
},
{
"code": null,
"e": 7411,
"s": 7163,
"text": "Points: this is pretty straight forward. Points indicate the location and toponyms. Points are one dimensional and contain 1 coordinate. (expect multipoint, which has many coordinates with the same attributes, but they don’t makeup lines or areas)"
},
{
"code": null,
"e": 7577,
"s": 7411,
"text": "Polylines: Lines or Polylines are sets of coordinates that are connected by a line. We can use Polylines to describe networks such as pipes, roads, or rail networks."
},
{
"code": null,
"e": 7722,
"s": 7577,
"text": "Polygon: Polygon is enclosed lines so it has an area. Used to describe administrative boundaries, zoning regulations, basis of a choropleth map."
},
{
"code": null,
"e": 7775,
"s": 7722,
"text": "So Spatial data is basically a bunch of coordinates!"
},
{
"code": null,
"e": 8097,
"s": 7775,
"text": "By their nature, Polylines and Polygons consist of vertices. These vertices are Points’ coordinates that are held in the Geometry column. As we can see in the figure below when a value of geometry is expanded, it contains many coordinates of Latitude and Longitude, and when we visualize these vertices, it draws a shape."
},
{
"code": null,
"e": 8433,
"s": 8097,
"text": "Each geometry is an object of Shapely, a library of Python. Shapely deals with geometrics for math purposes. We can do much spatial analysis such as intersections, unions, and many more. This is a very brief introduction: for example, if I want to create a geometric object, what I need to do is write some command to Python like this:"
},
{
"code": null,
"e": 8528,
"s": 8433,
"text": ">> from shapely.geometry import Polygon>> Polygon([(104.4, -6.2),(106.4, -7.0), (103.2, -8.9)]"
},
{
"code": null,
"e": 8598,
"s": 8528,
"text": "This will create a rectangle as there are 3 vertices (3 coordinates)."
},
{
"code": null,
"e": 8779,
"s": 8598,
"text": "Of course, to define each feature’s geometry we do not put it manually. Instead, we can integrate sensors such as GPS to automate the task or do some conversions with some scripts."
},
{
"code": null,
"e": 8988,
"s": 8779,
"text": "While shapefile is very popular I think GeoJSON is neater. Shapefile consists of separate files, besides the geometry itself, such as the projections and the attributes; while GeoJSON is only one “text” file."
},
{
"code": null,
"e": 9197,
"s": 8988,
"text": "Web service that fulfills the OGC standard is a must, this allows websites and algorithms to connect remotely, but sometimes users need downloadable data with common and popular formats such as .xlsx or .csv."
},
{
"code": null,
"e": 9241,
"s": 9197,
"text": "There are several options that I recommend:"
},
{
"code": null,
"e": 9770,
"s": 9241,
"text": "Save it as CSV: because the spatial data must be accessible to many people from many backgrounds, the simplest way to store is to convert the GeoDataFrame to a CSV (comma-separated values). This way, spreadsheet software can parse the CSV to become a tablature format. The caveat is that the “geometry” column will be stored as text, so to convert it to the geometric (shapely) object we need further parsing. A web application or some simple script should do the job. It’s an option, but I don’t think this option is preferred."
},
{
"code": null,
"e": 10162,
"s": 9770,
"text": "Save the Dataframe as CSV, and Geometry column as a separate GeoJSON: This yields 2 files; a CSV and a GeoJSON. Don’t worry about GeoJSOn, it’s basically a text file. GeoJSON is a format for interoperability between systems or software. With GeoJSON, many software or websites can parse the text and plot the geometries. The GeoJSON objects will be indexed so that it can be joined with CSV."
},
{
"code": null,
"e": 10760,
"s": 10162,
"text": "I think there should be an awareness of spatial attributes in datasets. Spatial attributes are as crucial as the data frame itself, and should not be separated. A spreadsheet (.xlsx, CSV, many more) must be accompanied by geometry in a GeoJSON format, or even embedded in the CSV itself. A tabular data format must have a column that defines the geometry of each feature whenever geometric properties are suitable. Why GeoDataFrame, CSV or GeoJSON? So it is readable to human eyes to those who are not common to spatial data, and common to spatial data. The geometry must consist of coordinate(s)."
}
] |
java.time.LocalTime.now() Method Example | The java.time.LocalTime.now(ZoneId zone) method obtains the current time from the system clock in the specified time-zone.
Following is the declaration for java.time.LocalTime.now(ZoneId zone) method.
public static LocalTime now(ZoneId zone)
zone − the zone ID to use, not null.
the current time using the system clock, not null.
The following example shows the usage of java.time.LocalTime.now(ZoneId zone) method.
package com.tutorialspoint;
import java.time.LocalTime;
import java.time.ZoneId;
public class LocalTimeDemo {
public static void main(String[] args) {
LocalTime time = LocalTime.now(ZoneId.systemDefault());
System.out.println(time);
}
}
Let us compile and run the above program, this will produce the following result −
12:35:15.354
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2038,
"s": 1915,
"text": "The java.time.LocalTime.now(ZoneId zone) method obtains the current time from the system clock in the specified time-zone."
},
{
"code": null,
"e": 2116,
"s": 2038,
"text": "Following is the declaration for java.time.LocalTime.now(ZoneId zone) method."
},
{
"code": null,
"e": 2158,
"s": 2116,
"text": "public static LocalTime now(ZoneId zone)\n"
},
{
"code": null,
"e": 2196,
"s": 2158,
"text": "zone − the zone ID to use, not null."
},
{
"code": null,
"e": 2247,
"s": 2196,
"text": "the current time using the system clock, not null."
},
{
"code": null,
"e": 2333,
"s": 2247,
"text": "The following example shows the usage of java.time.LocalTime.now(ZoneId zone) method."
},
{
"code": null,
"e": 2594,
"s": 2333,
"text": "package com.tutorialspoint;\n\nimport java.time.LocalTime;\nimport java.time.ZoneId;\n\npublic class LocalTimeDemo {\n public static void main(String[] args) {\n \n LocalTime time = LocalTime.now(ZoneId.systemDefault());\n System.out.println(time); \n }\n}"
},
{
"code": null,
"e": 2677,
"s": 2594,
"text": "Let us compile and run the above program, this will produce the following result −"
},
{
"code": null,
"e": 2691,
"s": 2677,
"text": "12:35:15.354\n"
},
{
"code": null,
"e": 2698,
"s": 2691,
"text": " Print"
},
{
"code": null,
"e": 2709,
"s": 2698,
"text": " Add Notes"
}
] |
Implementing a Chess engine from scratch | by Micaël Paquier | Towards Data Science | As a humble Chess amateur, I gave myself this challenge: to develop a simple, good-looking Chess game with AI that can beat me, without Machine-Learning. This article is about my journey to achieve it and is composed of 4 parts: rules, computation, strategy, and playing.
And just to make things clear, I also decided not to read theoretical or algorithmic explanations on Chess engines, I wanted to build my own algorithm, based on my common sense and personal experience.
I named it Bobby, as a tribute to Robert “Bobby” James Fischer, who has been World Chess Champion and one of my heroes as a young player.
Chess is played by two opponents, one color for each, white and black pieces. Then for each side, there are the following pieces:
♔ — A king
♕ — A queen
♖ — Two rooks
♗— Two bishops
♘ — Two knights
♙ — Eight pawns
At the beginning of the game, the initial position is always the same, strictly defined. A range of pawns in front of the other pieces, the royal couple in the center, then symmetrically come the bishops, knights, and finally rooks.
The board is a squared grid of 8x8 cases (i.e. two-dimensional array), alternating dark and light backgrounds. Now is the time for a visual representation of that board.
When I thought about drawing the pieces, I first started considering free graphic resources. But that would force me to manage pictures, which was not desirable for quick development. Fortunately, I discovered that each symbol is part of the Unicode: a basic text label is thus sufficient to draw a piece! Perfect, I was already able to print the board in the console logs to visualize it:
♜ ♞ ♝ ♛ ♚ ♝ ♞ ♜ ♟ ♟ ♟ ♟ ♟ ♟ ♟ ♟ ♙ ♙ ♙ ♙ ♙ ♙ ♙ ♙ ♖ ♘ ♗ ♕ ♔ ♗ ♘ ♖
Funny, but not as good-looking as what I had in mind, so I decided to create a basic GUI: the board is a single frame, with a grid layout, driven by a MVC architecture.
I started with the definition of the dark and light backgrounds, where each square is a label containing either an empty value or the Unicode symbol of a piece.
If you are familiar with Chess you probably know that the board grid has a coordinate system made of letters (horizontal axis, or files) and digits (vertical axis, ranks) which is used for game notation, i.e. to script the moves. I finally added them on the sides of my board, and here is the result, a simple 10x10 grid:
Let’s continue. What are the rules? What actions are allowed? There are basically 4 types of moves, that may be combined according to the piece:
Straight (used for rooks, queen and king)Diagonal (bishops, queen, king)«L» (knights)Pawns moves
Straight (used for rooks, queen and king)
Diagonal (bishops, queen, king)
«L» (knights)
Pawns moves
Note that special moves en passant, pawn promotion, and castling are deliberately ignored for the sake of simplicity but have been implemented later. The exhaustive description of moves can be found on Wikipedia.
Some additional constraints to implement a move: a piece cannot jump over another piece, except for knights, and when a piece reaches an enemy piece, it may capture it and take its place on the board.
I also designed an optional colored border around squares to highlight moves:
Red — currently selected piece
Blue — possible destination of the selected piece
Green — last move played by the opponent
Now that we can move pieces, we must take into account the rules of the game: there are things that can be done, as well as things that must be done (typically, escaping check).
It is out of scope to explain every single rule here but I tried to implement most of the constraints, among others:
Players’ turns;
Detection of whether a king is in check, and when there is no way to escape from this, determining that the king is checkmate (game lost);
Both kings always being spaced a square apart;
Now how does the game finish? There are two scenarios: either a player wins, or neither win (draw).
As already mentioned, you lose when your king is in check and that there is no possible move to escape being in check.
But you draw if:
There is no possible move but your king is not in check (stalemate); or
Both players repeat the 3 same moves in a row; or
Both kings are alone on the board (or with insufficient material to win)
I also implemented another rule to avoid never-ending games: if there has been neither pawn move, nor a capture within the last 50 moves, the game is a draw. Note that this rule is largely accepted by the Chess community.
With the above rules, two humans can play a game, but we want to play against the computer, so let’s get to the heart of the matter.
What is the lowest intelligence possible? Choosing an allowed move without any strategy. This was the first level of “intelligence” I implemented as a bot: compute all possible moves and randomly select one of them. OK, that was fun, but let’s be serious now.
How do does a human determine which move should be played? He/she selects the move that will give an advantage, which can be translated by an improvement of the situation. We thus need a function to evaluate the current position, try a move and reevaluate it afterwards.
Basically, and according to the game rules, when a move leads to checkmating, then stop searching because that is the best move. On the other hand, I implemented a penalty score if the move leads to a draw because I wanted to make the AI as aggressive as possible.
Then, how to compute the score? Generally, the easiest strategy for beginners is to capture pieces. The implementation is to give points to every type of piece, so you can compute your current score by summing the points of all your pieces, and do the same with opponent’s pieces. It is then easy to estimate how much you dominate (or not) your opponent by comparing both scores.
But no need to be a Chess grandmaster to understand that it is not as simple as this. After your move, it will be your opponent’s turn. Say you captured a pawn with your queen and then your opponent captures your queen, you have lost the most important piece, so in the end, this was a terrible move.
To avoid this, the move selection function has to be recursive so that after having tried a move, the function is called again but for the opponent: the idea is to guess what the answer should be. And evaluate the resulting situation.
As this is a recursive function, this can be applied a few times, allowing us to try to imagine the probable situation in 2, 3, or more turns. But the cost here is exponential since we compute all possible moves, and in practice, I had to bound it to a depth of 3 moves, otherwise it was taking too much time to play.
Note: I will later learn that this kind of computation is part of the Minimax algorithms family — try to maximize your minimal gain, given your opponent’s responses.
Among other things, predicting 1, 2, or 3 moves allows the AI to:
Play a game-winning move leading to an immediate checkmate (depth of 1)
Play a move preventing a loss right after (depth of 2)
And this is exactly what I used as testing: setup a game that can lead to checkmate in 1 or 2 moves and let it find the best move to win and, respectively, avoid the defeat.
The logic above works finely in many situations but is inefficient to eventually win by checkmating the opponent’s king. Some additional intelligence is required in the evaluation function.
I often asked myself what were the tips I was given when I started playing, i.e. what made a move good or bad.
As simple as it seems, one of the keys to winning is to control the center of the board. Placing your pieces in the center, or at least making them cover the center, helps to develop the army, to attack as well as to defend.
I implemented this with the concept of a heat map:
The 4 most centered squares are worth 2 pts each;
The 12 squares around them are worth 1 pt;
All remaining squares are worth 0 pt.
Then, one has to compute the move of every piece, and according to the location they can reach, sum up all points above to get a final score.
I noticed that my AI was able to play quite well at the beginning and in the middle of the game but faced difficulties closing games because it had no heuristic to play moves that lead to attacking the opponent’s king.
I decided to reuse the idea above to tackle this problem, that is to say, define a heat map focused on the opposing king:
3 pts when hitting the king, because it is very good to have the king in check;
2 pts around the king, because you prevent him from escaping;
1 pt around the king area, because it eventually leads to restricting his moves;
0 for all remaining squares.
Like in many games or sports, there is a theoretical part that must not be neglected. The strategy based on the heuristics above is good but may not be sufficient for a good start, and an imperfect start in Chess may quickly lead to losing the battle. In order to avoid an early poor move, players learn openings by heart, and this is what I implemented. Of course, there are libraries with tons of openings, but as my objective was to make an AI comparable to me, I chose to let it know only 15 major openings, with 2–3 moves each.
I used a tree structure to classify the openings: a move leads to a node and a leaf is the last known move for a given opening.
When the AI has to choose a path from a given node, it randomly selects one. I later noticed how appreciable this random selection was, because it introduced variants in each game, avoiding boring predictable paths. When the tree does not know the move that was just played, the AI falls back to its default computation.
Some hints are given to beginners to avoid big mistakes in the early game. For example, castling (a special move consisting in moving both the king and a rook at once) is highly recommended, since it shelters the king whilst activates the rook close to the center. I thus implemented bonus and penalties according to game history.
A bonus is given when:
Castling is done
A penalty is given when:
The king has moved before castling, since the right to castling is lost
Either the king, the queen or a rook (castling excepted) is moved during the opening (5 first moves)
The same piece (pawns excepted) is moved more than once during the opening
Although I played many times during the development phase, I finally decided to create a short tournament, opposing bots and their creator:
A stupid bot, randomly playing
Bots respectively computing moves with a depth of 1, 2 and 3
Another bot computing moves with a depth of 3, but also experienced of some openings
Me, an amateur Chess player
All participants have been facing each other, playing twice with White, and twice with Black in every match. Here is the final scoreboard:
Not sure if it is good or bad news to remain stronger than the AI that was developed but for sure I won most of the games against the AI. I however did drop a point against each of the three best bots, probably due to a loss of concentration and/or playing too fast, which remains a kind of satisfaction since it proves that the AI can beat me.
Unsurprisingly, bots with the highest computation level are runners-up, and the random one finished last. A fun fact is that the latter was able to earn 0.5 pts by making a draw against a stronger bot. As for both bots with level 3, they almost defeated all other bots, and their head-to-head was concluded on a 2–2 score, which is quite logical too. Finally, one cannot say that mastering theoretical openings gives a significant advantage, at least not against other bots playing the same strategy, but I am confident it does make a difference when facing humans.
Now that you know how I built my own Chess intelligence, you might wish to try it. Of course, the code is public and can be found on my GitHub repository.
Running it locally on your computer gives the best experience but a web version is also provided, with some limitations though: only one session (i.e. one player) at a time, because of limited resources, and some graphical latency when moving pieces. But it is free and online:
www.bobby-chess.com
Note: if you are interested in reading how I exposed a Java Swing desktop app through a website, I have written another article dedicated to this technical aspect:
codeburst.io
I am aware that my Chess engine has room for improvement, and is extremely far from the best computer engines. But as I said in the introduction, I wanted to program it with my own insights. This is why I refused to use theoretical material to make it stronger, but I do recommend having a look at Chess programming if you are interested in reading this topic.
Moreover, I am fully convinced that nothing is better than Machine Learning for such games, or maybe a subtle combination of Machine Learning and traditional computation engines. AlphaGo was the first ML-based engine to beat the World Champion at Go. Then in 2017 AlphaZero was introduced and largely defeated the best traditional Chess engine, namely StockFish.
But as my father was kindly testing my Chess engine, he made an interesting statement:
State-of-the-art Chess engines are boring.
And this is particularly true for two reasons: first, they systematically beat us, amateur players. Second, some of them may always play the same moves in a given situation, so they actually can be predictable.
Bobby engine tries to escape from this, thanks to the randomness in the openings, as well as when computing equivalent moves.
And according to the reasonable limitation to 3-moves depth, an amateur Chess player has a chance to win with a bit of creativity when imagining traps.
One of the weaknesses of my engine is its poor development at the beginning of the game, right after the opening: it tries to attack as soon as possible, like a newbie, and if the opponent resists with a correct defense, this may quickly turn into a strong disadvantage for the AI, since an important piece can be captured early as a result of this greedy behavior.
My initial challenge was to build my own Chess game, with a nice UI and the capability to defeat me, and I think it is fair to say that this goal was achieved.
I am pretty pleased with the final result although I believe many things could be improved in the future. I would particularly be interested in developing a Deep Learning AI and having them battle it out.
Bobby on GitHub — code repository
https://www.bobby-chess.com/bobby/ — play online to my Chess engine
Enhancing a Java Swing App to a clean, elegant Web App without changing the code — another post on the technical side of my Chess engine
Chess Programming Wiki — theory and algorithms explained for Chess engines
AlphaZero — a machine-learning Chess engine
Chess symbols in Unicode — chars for Chess pieces
Chess / Movement — Wikipedia page about Chess | [
{
"code": null,
"e": 444,
"s": 172,
"text": "As a humble Chess amateur, I gave myself this challenge: to develop a simple, good-looking Chess game with AI that can beat me, without Machine-Learning. This article is about my journey to achieve it and is composed of 4 parts: rules, computation, strategy, and playing."
},
{
"code": null,
"e": 646,
"s": 444,
"text": "And just to make things clear, I also decided not to read theoretical or algorithmic explanations on Chess engines, I wanted to build my own algorithm, based on my common sense and personal experience."
},
{
"code": null,
"e": 784,
"s": 646,
"text": "I named it Bobby, as a tribute to Robert “Bobby” James Fischer, who has been World Chess Champion and one of my heroes as a young player."
},
{
"code": null,
"e": 914,
"s": 784,
"text": "Chess is played by two opponents, one color for each, white and black pieces. Then for each side, there are the following pieces:"
},
{
"code": null,
"e": 925,
"s": 914,
"text": "♔ — A king"
},
{
"code": null,
"e": 937,
"s": 925,
"text": "♕ — A queen"
},
{
"code": null,
"e": 951,
"s": 937,
"text": "♖ — Two rooks"
},
{
"code": null,
"e": 966,
"s": 951,
"text": "♗— Two bishops"
},
{
"code": null,
"e": 982,
"s": 966,
"text": "♘ — Two knights"
},
{
"code": null,
"e": 998,
"s": 982,
"text": "♙ — Eight pawns"
},
{
"code": null,
"e": 1231,
"s": 998,
"text": "At the beginning of the game, the initial position is always the same, strictly defined. A range of pawns in front of the other pieces, the royal couple in the center, then symmetrically come the bishops, knights, and finally rooks."
},
{
"code": null,
"e": 1401,
"s": 1231,
"text": "The board is a squared grid of 8x8 cases (i.e. two-dimensional array), alternating dark and light backgrounds. Now is the time for a visual representation of that board."
},
{
"code": null,
"e": 1791,
"s": 1401,
"text": "When I thought about drawing the pieces, I first started considering free graphic resources. But that would force me to manage pictures, which was not desirable for quick development. Fortunately, I discovered that each symbol is part of the Unicode: a basic text label is thus sufficient to draw a piece! Perfect, I was already able to print the board in the console logs to visualize it:"
},
{
"code": null,
"e": 1859,
"s": 1791,
"text": "♜ ♞ ♝ ♛ ♚ ♝ ♞ ♜ ♟ ♟ ♟ ♟ ♟ ♟ ♟ ♟ ♙ ♙ ♙ ♙ ♙ ♙ ♙ ♙ ♖ ♘ ♗ ♕ ♔ ♗ ♘ ♖"
},
{
"code": null,
"e": 2028,
"s": 1859,
"text": "Funny, but not as good-looking as what I had in mind, so I decided to create a basic GUI: the board is a single frame, with a grid layout, driven by a MVC architecture."
},
{
"code": null,
"e": 2189,
"s": 2028,
"text": "I started with the definition of the dark and light backgrounds, where each square is a label containing either an empty value or the Unicode symbol of a piece."
},
{
"code": null,
"e": 2511,
"s": 2189,
"text": "If you are familiar with Chess you probably know that the board grid has a coordinate system made of letters (horizontal axis, or files) and digits (vertical axis, ranks) which is used for game notation, i.e. to script the moves. I finally added them on the sides of my board, and here is the result, a simple 10x10 grid:"
},
{
"code": null,
"e": 2656,
"s": 2511,
"text": "Let’s continue. What are the rules? What actions are allowed? There are basically 4 types of moves, that may be combined according to the piece:"
},
{
"code": null,
"e": 2753,
"s": 2656,
"text": "Straight (used for rooks, queen and king)Diagonal (bishops, queen, king)«L» (knights)Pawns moves"
},
{
"code": null,
"e": 2795,
"s": 2753,
"text": "Straight (used for rooks, queen and king)"
},
{
"code": null,
"e": 2827,
"s": 2795,
"text": "Diagonal (bishops, queen, king)"
},
{
"code": null,
"e": 2841,
"s": 2827,
"text": "«L» (knights)"
},
{
"code": null,
"e": 2853,
"s": 2841,
"text": "Pawns moves"
},
{
"code": null,
"e": 3066,
"s": 2853,
"text": "Note that special moves en passant, pawn promotion, and castling are deliberately ignored for the sake of simplicity but have been implemented later. The exhaustive description of moves can be found on Wikipedia."
},
{
"code": null,
"e": 3267,
"s": 3066,
"text": "Some additional constraints to implement a move: a piece cannot jump over another piece, except for knights, and when a piece reaches an enemy piece, it may capture it and take its place on the board."
},
{
"code": null,
"e": 3345,
"s": 3267,
"text": "I also designed an optional colored border around squares to highlight moves:"
},
{
"code": null,
"e": 3376,
"s": 3345,
"text": "Red — currently selected piece"
},
{
"code": null,
"e": 3426,
"s": 3376,
"text": "Blue — possible destination of the selected piece"
},
{
"code": null,
"e": 3467,
"s": 3426,
"text": "Green — last move played by the opponent"
},
{
"code": null,
"e": 3645,
"s": 3467,
"text": "Now that we can move pieces, we must take into account the rules of the game: there are things that can be done, as well as things that must be done (typically, escaping check)."
},
{
"code": null,
"e": 3762,
"s": 3645,
"text": "It is out of scope to explain every single rule here but I tried to implement most of the constraints, among others:"
},
{
"code": null,
"e": 3778,
"s": 3762,
"text": "Players’ turns;"
},
{
"code": null,
"e": 3917,
"s": 3778,
"text": "Detection of whether a king is in check, and when there is no way to escape from this, determining that the king is checkmate (game lost);"
},
{
"code": null,
"e": 3964,
"s": 3917,
"text": "Both kings always being spaced a square apart;"
},
{
"code": null,
"e": 4064,
"s": 3964,
"text": "Now how does the game finish? There are two scenarios: either a player wins, or neither win (draw)."
},
{
"code": null,
"e": 4183,
"s": 4064,
"text": "As already mentioned, you lose when your king is in check and that there is no possible move to escape being in check."
},
{
"code": null,
"e": 4200,
"s": 4183,
"text": "But you draw if:"
},
{
"code": null,
"e": 4272,
"s": 4200,
"text": "There is no possible move but your king is not in check (stalemate); or"
},
{
"code": null,
"e": 4322,
"s": 4272,
"text": "Both players repeat the 3 same moves in a row; or"
},
{
"code": null,
"e": 4395,
"s": 4322,
"text": "Both kings are alone on the board (or with insufficient material to win)"
},
{
"code": null,
"e": 4617,
"s": 4395,
"text": "I also implemented another rule to avoid never-ending games: if there has been neither pawn move, nor a capture within the last 50 moves, the game is a draw. Note that this rule is largely accepted by the Chess community."
},
{
"code": null,
"e": 4750,
"s": 4617,
"text": "With the above rules, two humans can play a game, but we want to play against the computer, so let’s get to the heart of the matter."
},
{
"code": null,
"e": 5010,
"s": 4750,
"text": "What is the lowest intelligence possible? Choosing an allowed move without any strategy. This was the first level of “intelligence” I implemented as a bot: compute all possible moves and randomly select one of them. OK, that was fun, but let’s be serious now."
},
{
"code": null,
"e": 5281,
"s": 5010,
"text": "How do does a human determine which move should be played? He/she selects the move that will give an advantage, which can be translated by an improvement of the situation. We thus need a function to evaluate the current position, try a move and reevaluate it afterwards."
},
{
"code": null,
"e": 5546,
"s": 5281,
"text": "Basically, and according to the game rules, when a move leads to checkmating, then stop searching because that is the best move. On the other hand, I implemented a penalty score if the move leads to a draw because I wanted to make the AI as aggressive as possible."
},
{
"code": null,
"e": 5926,
"s": 5546,
"text": "Then, how to compute the score? Generally, the easiest strategy for beginners is to capture pieces. The implementation is to give points to every type of piece, so you can compute your current score by summing the points of all your pieces, and do the same with opponent’s pieces. It is then easy to estimate how much you dominate (or not) your opponent by comparing both scores."
},
{
"code": null,
"e": 6227,
"s": 5926,
"text": "But no need to be a Chess grandmaster to understand that it is not as simple as this. After your move, it will be your opponent’s turn. Say you captured a pawn with your queen and then your opponent captures your queen, you have lost the most important piece, so in the end, this was a terrible move."
},
{
"code": null,
"e": 6462,
"s": 6227,
"text": "To avoid this, the move selection function has to be recursive so that after having tried a move, the function is called again but for the opponent: the idea is to guess what the answer should be. And evaluate the resulting situation."
},
{
"code": null,
"e": 6780,
"s": 6462,
"text": "As this is a recursive function, this can be applied a few times, allowing us to try to imagine the probable situation in 2, 3, or more turns. But the cost here is exponential since we compute all possible moves, and in practice, I had to bound it to a depth of 3 moves, otherwise it was taking too much time to play."
},
{
"code": null,
"e": 6946,
"s": 6780,
"text": "Note: I will later learn that this kind of computation is part of the Minimax algorithms family — try to maximize your minimal gain, given your opponent’s responses."
},
{
"code": null,
"e": 7012,
"s": 6946,
"text": "Among other things, predicting 1, 2, or 3 moves allows the AI to:"
},
{
"code": null,
"e": 7084,
"s": 7012,
"text": "Play a game-winning move leading to an immediate checkmate (depth of 1)"
},
{
"code": null,
"e": 7139,
"s": 7084,
"text": "Play a move preventing a loss right after (depth of 2)"
},
{
"code": null,
"e": 7313,
"s": 7139,
"text": "And this is exactly what I used as testing: setup a game that can lead to checkmate in 1 or 2 moves and let it find the best move to win and, respectively, avoid the defeat."
},
{
"code": null,
"e": 7503,
"s": 7313,
"text": "The logic above works finely in many situations but is inefficient to eventually win by checkmating the opponent’s king. Some additional intelligence is required in the evaluation function."
},
{
"code": null,
"e": 7614,
"s": 7503,
"text": "I often asked myself what were the tips I was given when I started playing, i.e. what made a move good or bad."
},
{
"code": null,
"e": 7839,
"s": 7614,
"text": "As simple as it seems, one of the keys to winning is to control the center of the board. Placing your pieces in the center, or at least making them cover the center, helps to develop the army, to attack as well as to defend."
},
{
"code": null,
"e": 7890,
"s": 7839,
"text": "I implemented this with the concept of a heat map:"
},
{
"code": null,
"e": 7940,
"s": 7890,
"text": "The 4 most centered squares are worth 2 pts each;"
},
{
"code": null,
"e": 7983,
"s": 7940,
"text": "The 12 squares around them are worth 1 pt;"
},
{
"code": null,
"e": 8021,
"s": 7983,
"text": "All remaining squares are worth 0 pt."
},
{
"code": null,
"e": 8163,
"s": 8021,
"text": "Then, one has to compute the move of every piece, and according to the location they can reach, sum up all points above to get a final score."
},
{
"code": null,
"e": 8382,
"s": 8163,
"text": "I noticed that my AI was able to play quite well at the beginning and in the middle of the game but faced difficulties closing games because it had no heuristic to play moves that lead to attacking the opponent’s king."
},
{
"code": null,
"e": 8504,
"s": 8382,
"text": "I decided to reuse the idea above to tackle this problem, that is to say, define a heat map focused on the opposing king:"
},
{
"code": null,
"e": 8584,
"s": 8504,
"text": "3 pts when hitting the king, because it is very good to have the king in check;"
},
{
"code": null,
"e": 8646,
"s": 8584,
"text": "2 pts around the king, because you prevent him from escaping;"
},
{
"code": null,
"e": 8727,
"s": 8646,
"text": "1 pt around the king area, because it eventually leads to restricting his moves;"
},
{
"code": null,
"e": 8756,
"s": 8727,
"text": "0 for all remaining squares."
},
{
"code": null,
"e": 9289,
"s": 8756,
"text": "Like in many games or sports, there is a theoretical part that must not be neglected. The strategy based on the heuristics above is good but may not be sufficient for a good start, and an imperfect start in Chess may quickly lead to losing the battle. In order to avoid an early poor move, players learn openings by heart, and this is what I implemented. Of course, there are libraries with tons of openings, but as my objective was to make an AI comparable to me, I chose to let it know only 15 major openings, with 2–3 moves each."
},
{
"code": null,
"e": 9417,
"s": 9289,
"text": "I used a tree structure to classify the openings: a move leads to a node and a leaf is the last known move for a given opening."
},
{
"code": null,
"e": 9738,
"s": 9417,
"text": "When the AI has to choose a path from a given node, it randomly selects one. I later noticed how appreciable this random selection was, because it introduced variants in each game, avoiding boring predictable paths. When the tree does not know the move that was just played, the AI falls back to its default computation."
},
{
"code": null,
"e": 10069,
"s": 9738,
"text": "Some hints are given to beginners to avoid big mistakes in the early game. For example, castling (a special move consisting in moving both the king and a rook at once) is highly recommended, since it shelters the king whilst activates the rook close to the center. I thus implemented bonus and penalties according to game history."
},
{
"code": null,
"e": 10092,
"s": 10069,
"text": "A bonus is given when:"
},
{
"code": null,
"e": 10109,
"s": 10092,
"text": "Castling is done"
},
{
"code": null,
"e": 10134,
"s": 10109,
"text": "A penalty is given when:"
},
{
"code": null,
"e": 10206,
"s": 10134,
"text": "The king has moved before castling, since the right to castling is lost"
},
{
"code": null,
"e": 10307,
"s": 10206,
"text": "Either the king, the queen or a rook (castling excepted) is moved during the opening (5 first moves)"
},
{
"code": null,
"e": 10382,
"s": 10307,
"text": "The same piece (pawns excepted) is moved more than once during the opening"
},
{
"code": null,
"e": 10522,
"s": 10382,
"text": "Although I played many times during the development phase, I finally decided to create a short tournament, opposing bots and their creator:"
},
{
"code": null,
"e": 10553,
"s": 10522,
"text": "A stupid bot, randomly playing"
},
{
"code": null,
"e": 10614,
"s": 10553,
"text": "Bots respectively computing moves with a depth of 1, 2 and 3"
},
{
"code": null,
"e": 10699,
"s": 10614,
"text": "Another bot computing moves with a depth of 3, but also experienced of some openings"
},
{
"code": null,
"e": 10727,
"s": 10699,
"text": "Me, an amateur Chess player"
},
{
"code": null,
"e": 10866,
"s": 10727,
"text": "All participants have been facing each other, playing twice with White, and twice with Black in every match. Here is the final scoreboard:"
},
{
"code": null,
"e": 11211,
"s": 10866,
"text": "Not sure if it is good or bad news to remain stronger than the AI that was developed but for sure I won most of the games against the AI. I however did drop a point against each of the three best bots, probably due to a loss of concentration and/or playing too fast, which remains a kind of satisfaction since it proves that the AI can beat me."
},
{
"code": null,
"e": 11777,
"s": 11211,
"text": "Unsurprisingly, bots with the highest computation level are runners-up, and the random one finished last. A fun fact is that the latter was able to earn 0.5 pts by making a draw against a stronger bot. As for both bots with level 3, they almost defeated all other bots, and their head-to-head was concluded on a 2–2 score, which is quite logical too. Finally, one cannot say that mastering theoretical openings gives a significant advantage, at least not against other bots playing the same strategy, but I am confident it does make a difference when facing humans."
},
{
"code": null,
"e": 11932,
"s": 11777,
"text": "Now that you know how I built my own Chess intelligence, you might wish to try it. Of course, the code is public and can be found on my GitHub repository."
},
{
"code": null,
"e": 12210,
"s": 11932,
"text": "Running it locally on your computer gives the best experience but a web version is also provided, with some limitations though: only one session (i.e. one player) at a time, because of limited resources, and some graphical latency when moving pieces. But it is free and online:"
},
{
"code": null,
"e": 12230,
"s": 12210,
"text": "www.bobby-chess.com"
},
{
"code": null,
"e": 12394,
"s": 12230,
"text": "Note: if you are interested in reading how I exposed a Java Swing desktop app through a website, I have written another article dedicated to this technical aspect:"
},
{
"code": null,
"e": 12407,
"s": 12394,
"text": "codeburst.io"
},
{
"code": null,
"e": 12768,
"s": 12407,
"text": "I am aware that my Chess engine has room for improvement, and is extremely far from the best computer engines. But as I said in the introduction, I wanted to program it with my own insights. This is why I refused to use theoretical material to make it stronger, but I do recommend having a look at Chess programming if you are interested in reading this topic."
},
{
"code": null,
"e": 13131,
"s": 12768,
"text": "Moreover, I am fully convinced that nothing is better than Machine Learning for such games, or maybe a subtle combination of Machine Learning and traditional computation engines. AlphaGo was the first ML-based engine to beat the World Champion at Go. Then in 2017 AlphaZero was introduced and largely defeated the best traditional Chess engine, namely StockFish."
},
{
"code": null,
"e": 13218,
"s": 13131,
"text": "But as my father was kindly testing my Chess engine, he made an interesting statement:"
},
{
"code": null,
"e": 13261,
"s": 13218,
"text": "State-of-the-art Chess engines are boring."
},
{
"code": null,
"e": 13472,
"s": 13261,
"text": "And this is particularly true for two reasons: first, they systematically beat us, amateur players. Second, some of them may always play the same moves in a given situation, so they actually can be predictable."
},
{
"code": null,
"e": 13598,
"s": 13472,
"text": "Bobby engine tries to escape from this, thanks to the randomness in the openings, as well as when computing equivalent moves."
},
{
"code": null,
"e": 13750,
"s": 13598,
"text": "And according to the reasonable limitation to 3-moves depth, an amateur Chess player has a chance to win with a bit of creativity when imagining traps."
},
{
"code": null,
"e": 14116,
"s": 13750,
"text": "One of the weaknesses of my engine is its poor development at the beginning of the game, right after the opening: it tries to attack as soon as possible, like a newbie, and if the opponent resists with a correct defense, this may quickly turn into a strong disadvantage for the AI, since an important piece can be captured early as a result of this greedy behavior."
},
{
"code": null,
"e": 14276,
"s": 14116,
"text": "My initial challenge was to build my own Chess game, with a nice UI and the capability to defeat me, and I think it is fair to say that this goal was achieved."
},
{
"code": null,
"e": 14481,
"s": 14276,
"text": "I am pretty pleased with the final result although I believe many things could be improved in the future. I would particularly be interested in developing a Deep Learning AI and having them battle it out."
},
{
"code": null,
"e": 14515,
"s": 14481,
"text": "Bobby on GitHub — code repository"
},
{
"code": null,
"e": 14583,
"s": 14515,
"text": "https://www.bobby-chess.com/bobby/ — play online to my Chess engine"
},
{
"code": null,
"e": 14720,
"s": 14583,
"text": "Enhancing a Java Swing App to a clean, elegant Web App without changing the code — another post on the technical side of my Chess engine"
},
{
"code": null,
"e": 14795,
"s": 14720,
"text": "Chess Programming Wiki — theory and algorithms explained for Chess engines"
},
{
"code": null,
"e": 14839,
"s": 14795,
"text": "AlphaZero — a machine-learning Chess engine"
},
{
"code": null,
"e": 14889,
"s": 14839,
"text": "Chess symbols in Unicode — chars for Chess pieces"
}
] |
Pandas vs SQL. Which Should Data Scientists Use? | Towards Data Science | IntroductionPandasSQLSummaryReferences
Introduction
Pandas
SQL
Summary
References
Both of these tools are important to not only data scientists, but also to those in similar positions like data analytics and business intelligence. With that being said, when should data scientists specifically use pandas over SQL and vice versa? In some situations, you can get away with just using SQL, and some other times, pandas is much easier to use, especially for data scientists who focus on research in a Jupyter Notebook setting. Below, I will discuss when you should use SQL and when you should use pandas. Keep in mind that both of these tools have specific use cases, but there are many times where their functionality overlap, and that is what I will be comparing below as well.
Pandas [3] is an open-source data analysis tool in the Python programing language. The benefit of pandas starts when you already have your main dataset, usually from a SQL query. This main difference can mean that the two tools are separate, however, you can also perform several of the same functions in each respective tool, for example, you can create new features from existing columns in pandas, perhaps easier and faster than in SQL.
It is important to note that I am not comparing what Pandas does that SQL cannot do and vice versa. I will be picking the tool that can do the function more efficiently or preferable for data science work — in my opinion, from personal experience.
Here are times where using pandas is more beneficial than SQL — while also having the same functionality as SQL:
creating calculated fields from existing features
When incorporating a more complex SQL query, you often are incorporating subqueries as well in order to divide values from different columns. In pandas you can simply divide features much easier like the following:
df["new_column"] = df["first_column"]/df["second_column"]
The code above is showing how you can divide two separate columns, and assign those values to a new column — in this case, you are performing the feature creation on the whole entire dataset or dataframe. You can use this function in both feature exploration and feature engineering in the process of data science.
grouping by
Also referring to subqueries, grouping by in SQL can become quite complex and require lines and lines of code that can be visually overwhelming. In pandas, you can simply group by one line of code. I am not referring to the group by at the end of a simple select from table query, but one where there are multiple subqueries involved.
df.groupby(by="first_column").mean()
This result would be returning the mean of the first_column for every column in the dataframe. There are many other ways to use this grouping function, of which are outlined nicely in the pandas documentation linked below.
checking data types
In SQL, you will often have to cast types, but sometimes it can be a little clearer to see the way pandas lays out data types in a vertical format, rather than scrolling through a horizontal output in SQL. You can expect some examples of data types returned to be int64, float64, datetime64[ns], and object.
df.dtypes
While these are all fairly simple functions of pandas and SQL, in SQL, they are particularly tricky, and sometimes just much easier to implement in a pandas dataframe. Now, let’s look at what SQL is better at performing.
SQL is probably the language that is used most by the most amount of different positions. For example, a data engineer could use SQL, a Tableau developer, or a product manager. With that being said, data scientists tend to use SQL frequently. It is important to note that there are several different versions of SQL, usually all having a similar function, just slightly formatted differently.
Here are times where using SQL is more beneficial than pandas — while also having the same functionality as pandas:
WHERE clause
This clause in SQL is used frequently and can also be performed in pandas. In pandas, however, it is slightly more difficult, or less intuitive. For example, you have to write out redundant code, whereas in SQL, you simply need the WHERE.
SELECT IDFROM TABLEWHERE ID > 100
In pandas, it would be something like:
df[df["ID"] > 100]["ID"]
Yes, both are simple, one is just a little more intuitive.
JOINS
Pandas has a few ways to join, which can be a little overwhelming, whereas in SQL you can perform simple joins like the following: INNER, LEFT, RIGHT
SELECTone.column_A,two.column_BFROM FIRST_TABLE oneINNER JOIN SECOND_TABLE two on two.ID = one.ID
In this code, joining is slightly easier to read, than in pandas, where you have to merge dataframes, and especially as you merge more than two dataframes, it can be quite complex in pandas. SQL can perform multiple joins whether it be INNER, etc., all in the same query.
All of these examples, whether it be SQL or pandas, can be used in at least the exploratory data analysis portion of the data science process, as well as in feature engineer, and querying model results once they are stored in a database.
This comparison of pandas versus SQL is more of a personal preference. With that being said, you may feel the opposite of my opinion. However, I hope it still sheds light on the differences between pandas and SQL, as well as what you can perform the same in both tools, using slightly different coding techniques and a different language altogether.
To summarize, we have compared the benefits of using pandas over SQL and vice versa for a few of their shared functions:
* creating calculated fields from existing features* grouping by* checking data types* WHERE clause* JOINS
I hope you found my article both interesting and useful. Please feel free to comment down below if you agree with these comparisons — why or why not? Do you think one tool, in particular, is better than the other? What other data science tools can you think of that would have a similar comparison? What other functions of pandas and SQL could we compare?
Please feel free to check out my profile and other articles, as well as reach out to me on LinkedIn.
[1] Photo by rigel on Unsplash, (2019)
[2] Photo by Kalen Kemp on Unsplash, (2020)
[3] the pandas development team, pandas documentation, (2008-2021)
[4] Photo by Caspar Camille Rubin on Unsplash, (2017) | [
{
"code": null,
"e": 211,
"s": 172,
"text": "IntroductionPandasSQLSummaryReferences"
},
{
"code": null,
"e": 224,
"s": 211,
"text": "Introduction"
},
{
"code": null,
"e": 231,
"s": 224,
"text": "Pandas"
},
{
"code": null,
"e": 235,
"s": 231,
"text": "SQL"
},
{
"code": null,
"e": 243,
"s": 235,
"text": "Summary"
},
{
"code": null,
"e": 254,
"s": 243,
"text": "References"
},
{
"code": null,
"e": 949,
"s": 254,
"text": "Both of these tools are important to not only data scientists, but also to those in similar positions like data analytics and business intelligence. With that being said, when should data scientists specifically use pandas over SQL and vice versa? In some situations, you can get away with just using SQL, and some other times, pandas is much easier to use, especially for data scientists who focus on research in a Jupyter Notebook setting. Below, I will discuss when you should use SQL and when you should use pandas. Keep in mind that both of these tools have specific use cases, but there are many times where their functionality overlap, and that is what I will be comparing below as well."
},
{
"code": null,
"e": 1389,
"s": 949,
"text": "Pandas [3] is an open-source data analysis tool in the Python programing language. The benefit of pandas starts when you already have your main dataset, usually from a SQL query. This main difference can mean that the two tools are separate, however, you can also perform several of the same functions in each respective tool, for example, you can create new features from existing columns in pandas, perhaps easier and faster than in SQL."
},
{
"code": null,
"e": 1637,
"s": 1389,
"text": "It is important to note that I am not comparing what Pandas does that SQL cannot do and vice versa. I will be picking the tool that can do the function more efficiently or preferable for data science work — in my opinion, from personal experience."
},
{
"code": null,
"e": 1750,
"s": 1637,
"text": "Here are times where using pandas is more beneficial than SQL — while also having the same functionality as SQL:"
},
{
"code": null,
"e": 1800,
"s": 1750,
"text": "creating calculated fields from existing features"
},
{
"code": null,
"e": 2015,
"s": 1800,
"text": "When incorporating a more complex SQL query, you often are incorporating subqueries as well in order to divide values from different columns. In pandas you can simply divide features much easier like the following:"
},
{
"code": null,
"e": 2073,
"s": 2015,
"text": "df[\"new_column\"] = df[\"first_column\"]/df[\"second_column\"]"
},
{
"code": null,
"e": 2388,
"s": 2073,
"text": "The code above is showing how you can divide two separate columns, and assign those values to a new column — in this case, you are performing the feature creation on the whole entire dataset or dataframe. You can use this function in both feature exploration and feature engineering in the process of data science."
},
{
"code": null,
"e": 2400,
"s": 2388,
"text": "grouping by"
},
{
"code": null,
"e": 2735,
"s": 2400,
"text": "Also referring to subqueries, grouping by in SQL can become quite complex and require lines and lines of code that can be visually overwhelming. In pandas, you can simply group by one line of code. I am not referring to the group by at the end of a simple select from table query, but one where there are multiple subqueries involved."
},
{
"code": null,
"e": 2772,
"s": 2735,
"text": "df.groupby(by=\"first_column\").mean()"
},
{
"code": null,
"e": 2995,
"s": 2772,
"text": "This result would be returning the mean of the first_column for every column in the dataframe. There are many other ways to use this grouping function, of which are outlined nicely in the pandas documentation linked below."
},
{
"code": null,
"e": 3015,
"s": 2995,
"text": "checking data types"
},
{
"code": null,
"e": 3323,
"s": 3015,
"text": "In SQL, you will often have to cast types, but sometimes it can be a little clearer to see the way pandas lays out data types in a vertical format, rather than scrolling through a horizontal output in SQL. You can expect some examples of data types returned to be int64, float64, datetime64[ns], and object."
},
{
"code": null,
"e": 3333,
"s": 3323,
"text": "df.dtypes"
},
{
"code": null,
"e": 3554,
"s": 3333,
"text": "While these are all fairly simple functions of pandas and SQL, in SQL, they are particularly tricky, and sometimes just much easier to implement in a pandas dataframe. Now, let’s look at what SQL is better at performing."
},
{
"code": null,
"e": 3947,
"s": 3554,
"text": "SQL is probably the language that is used most by the most amount of different positions. For example, a data engineer could use SQL, a Tableau developer, or a product manager. With that being said, data scientists tend to use SQL frequently. It is important to note that there are several different versions of SQL, usually all having a similar function, just slightly formatted differently."
},
{
"code": null,
"e": 4063,
"s": 3947,
"text": "Here are times where using SQL is more beneficial than pandas — while also having the same functionality as pandas:"
},
{
"code": null,
"e": 4076,
"s": 4063,
"text": "WHERE clause"
},
{
"code": null,
"e": 4315,
"s": 4076,
"text": "This clause in SQL is used frequently and can also be performed in pandas. In pandas, however, it is slightly more difficult, or less intuitive. For example, you have to write out redundant code, whereas in SQL, you simply need the WHERE."
},
{
"code": null,
"e": 4349,
"s": 4315,
"text": "SELECT IDFROM TABLEWHERE ID > 100"
},
{
"code": null,
"e": 4388,
"s": 4349,
"text": "In pandas, it would be something like:"
},
{
"code": null,
"e": 4413,
"s": 4388,
"text": "df[df[\"ID\"] > 100][\"ID\"]"
},
{
"code": null,
"e": 4472,
"s": 4413,
"text": "Yes, both are simple, one is just a little more intuitive."
},
{
"code": null,
"e": 4478,
"s": 4472,
"text": "JOINS"
},
{
"code": null,
"e": 4628,
"s": 4478,
"text": "Pandas has a few ways to join, which can be a little overwhelming, whereas in SQL you can perform simple joins like the following: INNER, LEFT, RIGHT"
},
{
"code": null,
"e": 4726,
"s": 4628,
"text": "SELECTone.column_A,two.column_BFROM FIRST_TABLE oneINNER JOIN SECOND_TABLE two on two.ID = one.ID"
},
{
"code": null,
"e": 4998,
"s": 4726,
"text": "In this code, joining is slightly easier to read, than in pandas, where you have to merge dataframes, and especially as you merge more than two dataframes, it can be quite complex in pandas. SQL can perform multiple joins whether it be INNER, etc., all in the same query."
},
{
"code": null,
"e": 5236,
"s": 4998,
"text": "All of these examples, whether it be SQL or pandas, can be used in at least the exploratory data analysis portion of the data science process, as well as in feature engineer, and querying model results once they are stored in a database."
},
{
"code": null,
"e": 5586,
"s": 5236,
"text": "This comparison of pandas versus SQL is more of a personal preference. With that being said, you may feel the opposite of my opinion. However, I hope it still sheds light on the differences between pandas and SQL, as well as what you can perform the same in both tools, using slightly different coding techniques and a different language altogether."
},
{
"code": null,
"e": 5707,
"s": 5586,
"text": "To summarize, we have compared the benefits of using pandas over SQL and vice versa for a few of their shared functions:"
},
{
"code": null,
"e": 5814,
"s": 5707,
"text": "* creating calculated fields from existing features* grouping by* checking data types* WHERE clause* JOINS"
},
{
"code": null,
"e": 6170,
"s": 5814,
"text": "I hope you found my article both interesting and useful. Please feel free to comment down below if you agree with these comparisons — why or why not? Do you think one tool, in particular, is better than the other? What other data science tools can you think of that would have a similar comparison? What other functions of pandas and SQL could we compare?"
},
{
"code": null,
"e": 6271,
"s": 6170,
"text": "Please feel free to check out my profile and other articles, as well as reach out to me on LinkedIn."
},
{
"code": null,
"e": 6310,
"s": 6271,
"text": "[1] Photo by rigel on Unsplash, (2019)"
},
{
"code": null,
"e": 6354,
"s": 6310,
"text": "[2] Photo by Kalen Kemp on Unsplash, (2020)"
},
{
"code": null,
"e": 6421,
"s": 6354,
"text": "[3] the pandas development team, pandas documentation, (2008-2021)"
}
] |
Swap two numbers in PL/SQL without using temp - GeeksforGeeks | 05 Jul, 2018
In PL/SQL code groups of commands are arranged within a block. A block group related declarations or statements. In declare part, we declare variables and between begin and end part, we perform the operations.
Given two numbers num1 and num2 and the task is to swap the value of given numbers.
Examples:
Input : num1 = 1000, num2 = 2000
Output : num1 = 2000, num2 = 1000
Input : num1 = 40, num2 = 20
Output : num1 = 20, num2 = 40
Method 1 (Using Arithmetic Operators)The idea is to get sum in one of the two given numbers. The numbers can then be swapped using the sum and subtraction from sum.
DECLARE -- declare variable num1, num2 -- of datatype number num1 NUMBER; num2 NUMBER; BEGIN num1 := 1000; num2 := 2000; -- print result before swapping dbms_output.Put_line('Before'); dbms_output.Put_line('num1 = ' || num1 ||' num2 = ' || num2); -- swapping of numbers num1 and num2 num1 := num1 + num2; num2 := num1 - num2; num1 := num1 - num2; -- print result after swapping dbms_output.Put_line('After'); dbms_output.Put_line('num1 = ' || num1 ||' num2 = ' || num2); END; -- Program End
Output:
Before
num1 = 1000 num2 = 2000
After
num1 = 2000 num2 = 1000
Method 2 Multiplication and division can also be used for swapping.
DECLARE -- declare variable num1, num2 -- of datatype number num1 NUMBER; num2 NUMBER; BEGIN num1 := 1000; num2 := 2000; -- print result before swapping dbms_output.Put_line('Before'); dbms_output.Put_line('num1 = ' || num1 ||' num2 = ' || num2); -- swapping of numbers num1 and num2 num1 := num1 * num2; -- num1 now becomes 15 (1111) num2 := num1 / num2; -- num2 becomes 10 (1010) num1 := num1 / num2; -- num1 becomes 5 (0101) -- print result after swapping dbms_output.Put_line('After'); dbms_output.Put_line('num1 = ' || num1 ||' num2 = ' || num2); END; -- Program End
Output:
Before
num1 = 1000 num2 = 2000
After
num1 = 2000 num2 = 1000
SQL-PL/SQL
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between SQL and NoSQL
SQL | Views
Difference between DDL and DML in DBMS
SQL Correlated Subqueries
Difference between DELETE, DROP and TRUNCATE
SQL | GROUP BY
What is Cursor in SQL ?
SQL Interview Questions
How to Update Multiple Columns in Single Update Statement in SQL?
SQL | TRANSACTIONS | [
{
"code": null,
"e": 24041,
"s": 24013,
"text": "\n05 Jul, 2018"
},
{
"code": null,
"e": 24251,
"s": 24041,
"text": "In PL/SQL code groups of commands are arranged within a block. A block group related declarations or statements. In declare part, we declare variables and between begin and end part, we perform the operations."
},
{
"code": null,
"e": 24335,
"s": 24251,
"text": "Given two numbers num1 and num2 and the task is to swap the value of given numbers."
},
{
"code": null,
"e": 24345,
"s": 24335,
"text": "Examples:"
},
{
"code": null,
"e": 24477,
"s": 24345,
"text": "Input : num1 = 1000, num2 = 2000\nOutput : num1 = 2000, num2 = 1000\n\nInput : num1 = 40, num2 = 20\nOutput : num1 = 20, num2 = 40\n"
},
{
"code": null,
"e": 24642,
"s": 24477,
"text": "Method 1 (Using Arithmetic Operators)The idea is to get sum in one of the two given numbers. The numbers can then be swapped using the sum and subtraction from sum."
},
{
"code": "DECLARE -- declare variable num1, num2 -- of datatype number num1 NUMBER; num2 NUMBER; BEGIN num1 := 1000; num2 := 2000; -- print result before swapping dbms_output.Put_line('Before'); dbms_output.Put_line('num1 = ' || num1 ||' num2 = ' || num2); -- swapping of numbers num1 and num2 num1 := num1 + num2; num2 := num1 - num2; num1 := num1 - num2; -- print result after swapping dbms_output.Put_line('After'); dbms_output.Put_line('num1 = ' || num1 ||' num2 = ' || num2); END; -- Program End ",
"e": 25365,
"s": 24642,
"text": null
},
{
"code": null,
"e": 25373,
"s": 25365,
"text": "Output:"
},
{
"code": null,
"e": 25435,
"s": 25373,
"text": "Before\nnum1 = 1000 num2 = 2000\nAfter\nnum1 = 2000 num2 = 1000\n"
},
{
"code": null,
"e": 25503,
"s": 25435,
"text": "Method 2 Multiplication and division can also be used for swapping."
},
{
"code": "DECLARE -- declare variable num1, num2 -- of datatype number num1 NUMBER; num2 NUMBER; BEGIN num1 := 1000; num2 := 2000; -- print result before swapping dbms_output.Put_line('Before'); dbms_output.Put_line('num1 = ' || num1 ||' num2 = ' || num2); -- swapping of numbers num1 and num2 num1 := num1 * num2; -- num1 now becomes 15 (1111) num2 := num1 / num2; -- num2 becomes 10 (1010) num1 := num1 / num2; -- num1 becomes 5 (0101) -- print result after swapping dbms_output.Put_line('After'); dbms_output.Put_line('num1 = ' || num1 ||' num2 = ' || num2); END; -- Program End ",
"e": 26307,
"s": 25503,
"text": null
},
{
"code": null,
"e": 26315,
"s": 26307,
"text": "Output:"
},
{
"code": null,
"e": 26377,
"s": 26315,
"text": "Before\nnum1 = 1000 num2 = 2000\nAfter\nnum1 = 2000 num2 = 1000\n"
},
{
"code": null,
"e": 26388,
"s": 26377,
"text": "SQL-PL/SQL"
},
{
"code": null,
"e": 26392,
"s": 26388,
"text": "SQL"
},
{
"code": null,
"e": 26396,
"s": 26392,
"text": "SQL"
},
{
"code": null,
"e": 26494,
"s": 26396,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26503,
"s": 26494,
"text": "Comments"
},
{
"code": null,
"e": 26516,
"s": 26503,
"text": "Old Comments"
},
{
"code": null,
"e": 26549,
"s": 26516,
"text": "Difference between SQL and NoSQL"
},
{
"code": null,
"e": 26561,
"s": 26549,
"text": "SQL | Views"
},
{
"code": null,
"e": 26600,
"s": 26561,
"text": "Difference between DDL and DML in DBMS"
},
{
"code": null,
"e": 26626,
"s": 26600,
"text": "SQL Correlated Subqueries"
},
{
"code": null,
"e": 26671,
"s": 26626,
"text": "Difference between DELETE, DROP and TRUNCATE"
},
{
"code": null,
"e": 26686,
"s": 26671,
"text": "SQL | GROUP BY"
},
{
"code": null,
"e": 26710,
"s": 26686,
"text": "What is Cursor in SQL ?"
},
{
"code": null,
"e": 26734,
"s": 26710,
"text": "SQL Interview Questions"
},
{
"code": null,
"e": 26800,
"s": 26734,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
}
] |
Twitter data collection tutorial using Python | by Yehia “Yaya” Khoja | Towards Data Science | Over the past year, I’ve become more active on Twitter, and with the growing number of interactions, I needed to answer basic questions like:
Where are my followers from?
How many likes do my tweets get on average?
What’s the distribution of the accounts I am following?
So I thought this could be a fun programming exercise. But before I can perform any analysis, we need to collect the needed data.
In this tutorial, we’ll learn how to use Twitter’s API and some Python libraries to collect Twitter data. We will cover setting up the development environment, connecting to Twitter’s API, and collecting data.
For the “Just show me the code" folks, here’s the notebook:
colab.research.google.com
Here’s the list of tools we’ll use
Google Colab for the development environment
Google Drive to store the data
They’re free with a basic Google account and will help keep things simple.
As for Python libraries, here’s what we’ll need
tweepy for accessing the Twitter API using Python.
google.colab to link Google Drive to the Colab notebook
json for loading and saving json files
csv for loading and saving csv files
datetime for handling date data
time for timing code execution
We’ll import all the libraries we need as follows
# Import all needed librariesimport tweepy # Python wrapper around Twitter APIfrom google.colab import drive # to mount Drive to Colab notebookimport jsonimport csvfrom datetime import datefrom datetime import datetimeimport time
To connect Google Drive (where the data lives) to a Colab notebook (where the data is processed) run the following commands.
# Connect Google Drive to Colabdrive.mount('/content/gdrive')# Create a variable to store the data path on your drivepath = './gdrive/My Drive/path/to/data'
Executing the code block above will prompt you to follow a URL to authenticate your account, and allow data streaming between Google Drive and Colab. Simply, click through the prompts, and you’ll receive a message in your notebook when the drive is mounted successfully.
First, apply for a developer account to access the API. The Standard APIs are sufficient for this tutorial. They’re free, but have some limitations that we’ll learn to work around in this tutorial.
Once your developer account is setup, create an app that will make use of the API by clicking on your username in the top right corner to open the drop down menu, and clicking “Apps” as shown below. Then select “Create an app” and fill out the form. For the purposes of this tutorial, use the URL of the Google Colab notebook as the URL of the app.
Now that you have created a developer account and an app, you should have a set of keys to connect to the Twitter API. Specifically, you’ll have an
API key
API secret key
Access token
Access token secret
These could be inserted directly into your code, or loaded from an external file to connect to the Twitter API, as shown below.
# Load Twitter API secrets from an external JSON filesecrets = json.loads(open(path + 'secrets.json').read())api_key = secrets['api_key']api_secret_key = secrets['api_secret_key']access_token = secrets['access_token']access_token_secret = secrets['access_token_secret']# Connect to Twitter API using the secretsauth = tweepy.OAuthHandler(api_key, api_secret_key)auth.set_access_token(access_token, access_token_secret)api = tweepy.API(auth)
We’ll create functions to collect
Tweets: this also includes retweets, and replies collected as Tweet objects.
Followers: all follower information collected as User objects.
Following: information of all accounts I’m following (a.k.a. friends) collected as User objects.
Today’s Stats: the followers and following count that day.
Also, we’ll create two helper functions to make our job easier
Save JSON: to save the collected data in a json file on Google Drive
Rate Limit Handling: to manage the Twitter API limits that come with the free version, mainly the number of API calls permitted in a 15-minute period.
Save JSON
# Helper function to save data into a JSON file# file_name: the file name of the data on Google Drive# file_content: the data you want to savedef save_json(file_name, file_content): with open(path + file_name, 'w', encoding='utf-8') as f: json.dump(file_content, f, ensure_ascii=False, indent=4)
Rate Limit Handling
# Helper function to handle twitter API rate limitdef limit_handled(cursor, list_name): while True: try: yield cursor.next() # Catch Twitter API rate limit exception and wait for 15 minutes except tweepy.RateLimitError: print("\nData points in list = {}".format(len(list_name)))) print('Hit Twitter API rate limit.') for i in range(3, 0, -1): print("Wait for {} mins.".format(i * 5)) time.sleep(5 * 60) # Catch any other Twitter API exceptions except tweepy.error.TweepError: print('\nCaught TweepError exception' )
To unpack this code, let’s start by defining what a cursor is. Here’s the introduction from Tweepy’s documentation:
We use pagination a lot in Twitter API development. Iterating through timelines, user lists, direct messages, etc. In order to perform pagination, we must supply a page/cursor parameter with each of our requests. The problem here is this requires a lot of boiler plate code just to manage the pagination loop. To help make pagination easier and require less code, Tweepy has the Cursor object.
My explanation is that a Cursor object is Tweepy’s way of managing and passing data that spans multiple pages, the same way the contents of your favorite book are distributed over multiple pages.
With that in mind, the function above first requests the next cursor (or page) of data. If the amount of data collected within the last 15 minutes exceeds the API limits, a tweepy.RateLimitError exception is raised, in which case the code will wait for 15 minutes. The last exception is meant to catch any other tweepy.error.TweepError that could come up during execution, like connection errors to the Twitter API.
Tweets
We’ll reuse an implementation on Github with slight modification
# Helper function to get all tweets of a specified user# NOTE:This method only allows access to the most recent 3200 tweets# Source: https://gist.github.com/yanofsky/5436496def get_all_tweets(screen_name): # initialize a list to hold all the Tweets alltweets = [] # make initial request for most recent tweets # (200 is the maximum allowed count) new_tweets = api.user_timeline(screen_name = screen_name,count=200) # save most recent tweets alltweets.extend(new_tweets) # save the id of the oldest tweet less one to avoid duplication oldest = alltweets[-1].id - 1 # keep grabbing tweets until there are no tweets left while len(new_tweets) > 0: print("getting tweets before %s" % (oldest)) # all subsequent requests use the max_id param to prevent # duplicates new_tweets = api.user_timeline(screen_name = screen_name,count=200,max_id=oldest) # save most recent tweets alltweets.extend(new_tweets) # update the id of the oldest tweet less one oldest = alltweets[-1].id - 1 print("...%s tweets downloaded so far" % (len(alltweets))) ### END OF WHILE LOOP ### # transform the tweepy tweets into a 2D array that will # populate the csv outtweets = [[tweet.id_str, tweet.created_at, tweet.text, tweet.favorite_count,tweet.in_reply_to_screen_name, tweet.retweeted] for tweet in alltweets] # write the csv with open(path + '%s_tweets.csv' % screen_name, 'w') as f: writer = csv.writer(f) writer.writerow(["id","created_at","text","likes","in reply to","retweeted"]) writer.writerows(outtweets) pass
The code block above is essentially made up of two parts: a while-loop to collect all tweets in a list, and commands to save the tweets in a csv file.
Before we explain what’s going on in the while-loop, let’s first understand two key methods that are used
api.user_timeline([,count][,max_id]) returns the most recent tweets of the specified user. The count parameter specifies the number of tweets we care to retrieve at a time, 200 being the maximum. The max_id parameter tells the method to only return tweets with an ID less than (that is, older than) or equal to the specified ID.
list.extend(iterable) adds all items in iterable to the list, unlike append which adds only a single element to the end of the list.
Now, let’s breakdown what’s going on in the while-loop
There are three variables in play: alltweets is a list to store all the collected tweets, new_tweets is a list to store the latest batch of collected tweets since we can only retrieve 200 tweets at a time, and oldest stores the ID of the oldest tweet we retrieved so far, so the next batch of retrieved tweets come before it.The variables are initialized before the loop starts. Note that if the specified user doesn’t have any tweets, new_tweets will be empty, and the loop won’t execute.In each iteration, a new list of 200 tweets that were posted before oldest is retrieved and added to alltweets.The while-loop will keep iterating until no tweets are found before oldest or the limit of 3,200 tweets is reached.
There are three variables in play: alltweets is a list to store all the collected tweets, new_tweets is a list to store the latest batch of collected tweets since we can only retrieve 200 tweets at a time, and oldest stores the ID of the oldest tweet we retrieved so far, so the next batch of retrieved tweets come before it.
The variables are initialized before the loop starts. Note that if the specified user doesn’t have any tweets, new_tweets will be empty, and the loop won’t execute.
In each iteration, a new list of 200 tweets that were posted before oldest is retrieved and added to alltweets.
The while-loop will keep iterating until no tweets are found before oldest or the limit of 3,200 tweets is reached.
Now, to write the tweet data into a csv file, we first extract the information we care about from each tweet. This is done using a List comprehension where we capture information like tweet ID, text, and number of likes into a new list called outtweets. Finally, we open a CSV file, and first write a row with the header names of our table, and then write all data in outtweets in the following rows.
Followers
# Function to save follower objects in a JSON file.def get_followers(): # Create a list to store follower data followers_list = [] # For-loop to iterate over tweepy cursors cursor = tweepy.Cursor(api.followers, count=200).pages() for i, page in enumerate(limit_handled(cursor, followers_list)): print("\r"+"Loading"+ i % 5 *".", end='') # Add latest batch of follower data to the list followers_list += page # Extract the follower information followers_list = [x._json for x in followers_list] # Save the data in a JSON file save_json('followers_data.json', followers_list)
As you can see, we use the helper functions we created above. In addition, tweepy.Cursor(api.followers, count=200).pages() creates a Cursor object that will return the data of 200 followers one page at a time. We can now pass this cursor to our limited_handled function along with followers_list. Note, that the retrieved User objects contain two keys _api and _json, so we simply extract the data we care about using the List comprehension [x._json for x in followers_list].
Following
# Function to save friend objects in a JSON file.def get_friends(): # Create a list to store friends data friends_list = [] # For-loop to iterate over tweepy cursors cursor = tweepy.Cursor(api.friends, count=200).pages() for i, page in enumerate(limit_handled(cursor, friends_list)): print("\r"+"Loading"+ i % 5 *".", end='') # Add latest batch of friend data to the list friends_list += page # Extract the friends information friends_list = [x._json for x in friends_list] # Save the data in a JSON file save_json('friends_data.json', friends_list)
You can see that this is exactly like our get_followers() function, except that we use api.friends to define our Cursor object, so we can retrieve the data of the users we’re following.
Today’s Stats
# Function to save daily follower and following counts in a JSON filedef todays_stats(dict_name): # Get my account information info = api.me() # Get follower and following counts followers_cnt = info.followers_count following_cnt = info.friends_count # Get today's date today = date.today() d = today.strftime("%b %d, %Y") # Save today's stats only if they haven't been collected before if d not in dict_name: dict_name[d] = {"followers":followers_cnt, "following":following_cnt} save_json("follower_history.json", dict_name) else: print('Today\'s stats already exist')
api.me() returns the authenticating user’s information, in this case, me. From there, collecting the follower and following counts is straightforward. The date format I specified %b %d, %Y will return dates in a format that looks like Nov 11, 2019, for example. There are many formats to choose from.
I hope that you’ve enjoyed this tutorial which covered Twitter data collection. Writing this post was very helpful in clarifying my understanding of my own code. For example, I better understood tweepy Cursor objects. It reminded me of the quote
“If you want to learn something, teach it”
I’m always looking for ways to improve my writing, so if you have any feedback or thoughts, please feel free to share. Thanks for reading! | [
{
"code": null,
"e": 314,
"s": 172,
"text": "Over the past year, I’ve become more active on Twitter, and with the growing number of interactions, I needed to answer basic questions like:"
},
{
"code": null,
"e": 343,
"s": 314,
"text": "Where are my followers from?"
},
{
"code": null,
"e": 387,
"s": 343,
"text": "How many likes do my tweets get on average?"
},
{
"code": null,
"e": 443,
"s": 387,
"text": "What’s the distribution of the accounts I am following?"
},
{
"code": null,
"e": 573,
"s": 443,
"text": "So I thought this could be a fun programming exercise. But before I can perform any analysis, we need to collect the needed data."
},
{
"code": null,
"e": 783,
"s": 573,
"text": "In this tutorial, we’ll learn how to use Twitter’s API and some Python libraries to collect Twitter data. We will cover setting up the development environment, connecting to Twitter’s API, and collecting data."
},
{
"code": null,
"e": 843,
"s": 783,
"text": "For the “Just show me the code\" folks, here’s the notebook:"
},
{
"code": null,
"e": 869,
"s": 843,
"text": "colab.research.google.com"
},
{
"code": null,
"e": 904,
"s": 869,
"text": "Here’s the list of tools we’ll use"
},
{
"code": null,
"e": 949,
"s": 904,
"text": "Google Colab for the development environment"
},
{
"code": null,
"e": 980,
"s": 949,
"text": "Google Drive to store the data"
},
{
"code": null,
"e": 1055,
"s": 980,
"text": "They’re free with a basic Google account and will help keep things simple."
},
{
"code": null,
"e": 1103,
"s": 1055,
"text": "As for Python libraries, here’s what we’ll need"
},
{
"code": null,
"e": 1154,
"s": 1103,
"text": "tweepy for accessing the Twitter API using Python."
},
{
"code": null,
"e": 1210,
"s": 1154,
"text": "google.colab to link Google Drive to the Colab notebook"
},
{
"code": null,
"e": 1249,
"s": 1210,
"text": "json for loading and saving json files"
},
{
"code": null,
"e": 1286,
"s": 1249,
"text": "csv for loading and saving csv files"
},
{
"code": null,
"e": 1318,
"s": 1286,
"text": "datetime for handling date data"
},
{
"code": null,
"e": 1349,
"s": 1318,
"text": "time for timing code execution"
},
{
"code": null,
"e": 1399,
"s": 1349,
"text": "We’ll import all the libraries we need as follows"
},
{
"code": null,
"e": 1648,
"s": 1399,
"text": "# Import all needed librariesimport tweepy # Python wrapper around Twitter APIfrom google.colab import drive # to mount Drive to Colab notebookimport jsonimport csvfrom datetime import datefrom datetime import datetimeimport time"
},
{
"code": null,
"e": 1773,
"s": 1648,
"text": "To connect Google Drive (where the data lives) to a Colab notebook (where the data is processed) run the following commands."
},
{
"code": null,
"e": 1930,
"s": 1773,
"text": "# Connect Google Drive to Colabdrive.mount('/content/gdrive')# Create a variable to store the data path on your drivepath = './gdrive/My Drive/path/to/data'"
},
{
"code": null,
"e": 2201,
"s": 1930,
"text": "Executing the code block above will prompt you to follow a URL to authenticate your account, and allow data streaming between Google Drive and Colab. Simply, click through the prompts, and you’ll receive a message in your notebook when the drive is mounted successfully."
},
{
"code": null,
"e": 2399,
"s": 2201,
"text": "First, apply for a developer account to access the API. The Standard APIs are sufficient for this tutorial. They’re free, but have some limitations that we’ll learn to work around in this tutorial."
},
{
"code": null,
"e": 2748,
"s": 2399,
"text": "Once your developer account is setup, create an app that will make use of the API by clicking on your username in the top right corner to open the drop down menu, and clicking “Apps” as shown below. Then select “Create an app” and fill out the form. For the purposes of this tutorial, use the URL of the Google Colab notebook as the URL of the app."
},
{
"code": null,
"e": 2896,
"s": 2748,
"text": "Now that you have created a developer account and an app, you should have a set of keys to connect to the Twitter API. Specifically, you’ll have an"
},
{
"code": null,
"e": 2904,
"s": 2896,
"text": "API key"
},
{
"code": null,
"e": 2919,
"s": 2904,
"text": "API secret key"
},
{
"code": null,
"e": 2932,
"s": 2919,
"text": "Access token"
},
{
"code": null,
"e": 2952,
"s": 2932,
"text": "Access token secret"
},
{
"code": null,
"e": 3080,
"s": 2952,
"text": "These could be inserted directly into your code, or loaded from an external file to connect to the Twitter API, as shown below."
},
{
"code": null,
"e": 3521,
"s": 3080,
"text": "# Load Twitter API secrets from an external JSON filesecrets = json.loads(open(path + 'secrets.json').read())api_key = secrets['api_key']api_secret_key = secrets['api_secret_key']access_token = secrets['access_token']access_token_secret = secrets['access_token_secret']# Connect to Twitter API using the secretsauth = tweepy.OAuthHandler(api_key, api_secret_key)auth.set_access_token(access_token, access_token_secret)api = tweepy.API(auth)"
},
{
"code": null,
"e": 3555,
"s": 3521,
"text": "We’ll create functions to collect"
},
{
"code": null,
"e": 3632,
"s": 3555,
"text": "Tweets: this also includes retweets, and replies collected as Tweet objects."
},
{
"code": null,
"e": 3695,
"s": 3632,
"text": "Followers: all follower information collected as User objects."
},
{
"code": null,
"e": 3792,
"s": 3695,
"text": "Following: information of all accounts I’m following (a.k.a. friends) collected as User objects."
},
{
"code": null,
"e": 3851,
"s": 3792,
"text": "Today’s Stats: the followers and following count that day."
},
{
"code": null,
"e": 3914,
"s": 3851,
"text": "Also, we’ll create two helper functions to make our job easier"
},
{
"code": null,
"e": 3983,
"s": 3914,
"text": "Save JSON: to save the collected data in a json file on Google Drive"
},
{
"code": null,
"e": 4134,
"s": 3983,
"text": "Rate Limit Handling: to manage the Twitter API limits that come with the free version, mainly the number of API calls permitted in a 15-minute period."
},
{
"code": null,
"e": 4144,
"s": 4134,
"text": "Save JSON"
},
{
"code": null,
"e": 4444,
"s": 4144,
"text": "# Helper function to save data into a JSON file# file_name: the file name of the data on Google Drive# file_content: the data you want to savedef save_json(file_name, file_content): with open(path + file_name, 'w', encoding='utf-8') as f: json.dump(file_content, f, ensure_ascii=False, indent=4)"
},
{
"code": null,
"e": 4464,
"s": 4444,
"text": "Rate Limit Handling"
},
{
"code": null,
"e": 5035,
"s": 4464,
"text": "# Helper function to handle twitter API rate limitdef limit_handled(cursor, list_name): while True: try: yield cursor.next() # Catch Twitter API rate limit exception and wait for 15 minutes except tweepy.RateLimitError: print(\"\\nData points in list = {}\".format(len(list_name)))) print('Hit Twitter API rate limit.') for i in range(3, 0, -1): print(\"Wait for {} mins.\".format(i * 5)) time.sleep(5 * 60) # Catch any other Twitter API exceptions except tweepy.error.TweepError: print('\\nCaught TweepError exception' )"
},
{
"code": null,
"e": 5151,
"s": 5035,
"text": "To unpack this code, let’s start by defining what a cursor is. Here’s the introduction from Tweepy’s documentation:"
},
{
"code": null,
"e": 5545,
"s": 5151,
"text": "We use pagination a lot in Twitter API development. Iterating through timelines, user lists, direct messages, etc. In order to perform pagination, we must supply a page/cursor parameter with each of our requests. The problem here is this requires a lot of boiler plate code just to manage the pagination loop. To help make pagination easier and require less code, Tweepy has the Cursor object."
},
{
"code": null,
"e": 5741,
"s": 5545,
"text": "My explanation is that a Cursor object is Tweepy’s way of managing and passing data that spans multiple pages, the same way the contents of your favorite book are distributed over multiple pages."
},
{
"code": null,
"e": 6157,
"s": 5741,
"text": "With that in mind, the function above first requests the next cursor (or page) of data. If the amount of data collected within the last 15 minutes exceeds the API limits, a tweepy.RateLimitError exception is raised, in which case the code will wait for 15 minutes. The last exception is meant to catch any other tweepy.error.TweepError that could come up during execution, like connection errors to the Twitter API."
},
{
"code": null,
"e": 6164,
"s": 6157,
"text": "Tweets"
},
{
"code": null,
"e": 6229,
"s": 6164,
"text": "We’ll reuse an implementation on Github with slight modification"
},
{
"code": null,
"e": 7780,
"s": 6229,
"text": "# Helper function to get all tweets of a specified user# NOTE:This method only allows access to the most recent 3200 tweets# Source: https://gist.github.com/yanofsky/5436496def get_all_tweets(screen_name): # initialize a list to hold all the Tweets alltweets = [] # make initial request for most recent tweets # (200 is the maximum allowed count) new_tweets = api.user_timeline(screen_name = screen_name,count=200) # save most recent tweets alltweets.extend(new_tweets) # save the id of the oldest tweet less one to avoid duplication oldest = alltweets[-1].id - 1 # keep grabbing tweets until there are no tweets left while len(new_tweets) > 0: print(\"getting tweets before %s\" % (oldest)) # all subsequent requests use the max_id param to prevent # duplicates new_tweets = api.user_timeline(screen_name = screen_name,count=200,max_id=oldest) # save most recent tweets alltweets.extend(new_tweets) # update the id of the oldest tweet less one oldest = alltweets[-1].id - 1 print(\"...%s tweets downloaded so far\" % (len(alltweets))) ### END OF WHILE LOOP ### # transform the tweepy tweets into a 2D array that will # populate the csv outtweets = [[tweet.id_str, tweet.created_at, tweet.text, tweet.favorite_count,tweet.in_reply_to_screen_name, tweet.retweeted] for tweet in alltweets] # write the csv with open(path + '%s_tweets.csv' % screen_name, 'w') as f: writer = csv.writer(f) writer.writerow([\"id\",\"created_at\",\"text\",\"likes\",\"in reply to\",\"retweeted\"]) writer.writerows(outtweets) pass"
},
{
"code": null,
"e": 7931,
"s": 7780,
"text": "The code block above is essentially made up of two parts: a while-loop to collect all tweets in a list, and commands to save the tweets in a csv file."
},
{
"code": null,
"e": 8037,
"s": 7931,
"text": "Before we explain what’s going on in the while-loop, let’s first understand two key methods that are used"
},
{
"code": null,
"e": 8366,
"s": 8037,
"text": "api.user_timeline([,count][,max_id]) returns the most recent tweets of the specified user. The count parameter specifies the number of tweets we care to retrieve at a time, 200 being the maximum. The max_id parameter tells the method to only return tweets with an ID less than (that is, older than) or equal to the specified ID."
},
{
"code": null,
"e": 8499,
"s": 8366,
"text": "list.extend(iterable) adds all items in iterable to the list, unlike append which adds only a single element to the end of the list."
},
{
"code": null,
"e": 8554,
"s": 8499,
"text": "Now, let’s breakdown what’s going on in the while-loop"
},
{
"code": null,
"e": 9270,
"s": 8554,
"text": "There are three variables in play: alltweets is a list to store all the collected tweets, new_tweets is a list to store the latest batch of collected tweets since we can only retrieve 200 tweets at a time, and oldest stores the ID of the oldest tweet we retrieved so far, so the next batch of retrieved tweets come before it.The variables are initialized before the loop starts. Note that if the specified user doesn’t have any tweets, new_tweets will be empty, and the loop won’t execute.In each iteration, a new list of 200 tweets that were posted before oldest is retrieved and added to alltweets.The while-loop will keep iterating until no tweets are found before oldest or the limit of 3,200 tweets is reached."
},
{
"code": null,
"e": 9596,
"s": 9270,
"text": "There are three variables in play: alltweets is a list to store all the collected tweets, new_tweets is a list to store the latest batch of collected tweets since we can only retrieve 200 tweets at a time, and oldest stores the ID of the oldest tweet we retrieved so far, so the next batch of retrieved tweets come before it."
},
{
"code": null,
"e": 9761,
"s": 9596,
"text": "The variables are initialized before the loop starts. Note that if the specified user doesn’t have any tweets, new_tweets will be empty, and the loop won’t execute."
},
{
"code": null,
"e": 9873,
"s": 9761,
"text": "In each iteration, a new list of 200 tweets that were posted before oldest is retrieved and added to alltweets."
},
{
"code": null,
"e": 9989,
"s": 9873,
"text": "The while-loop will keep iterating until no tweets are found before oldest or the limit of 3,200 tweets is reached."
},
{
"code": null,
"e": 10390,
"s": 9989,
"text": "Now, to write the tweet data into a csv file, we first extract the information we care about from each tweet. This is done using a List comprehension where we capture information like tweet ID, text, and number of likes into a new list called outtweets. Finally, we open a CSV file, and first write a row with the header names of our table, and then write all data in outtweets in the following rows."
},
{
"code": null,
"e": 10400,
"s": 10390,
"text": "Followers"
},
{
"code": null,
"e": 11002,
"s": 10400,
"text": "# Function to save follower objects in a JSON file.def get_followers(): # Create a list to store follower data followers_list = [] # For-loop to iterate over tweepy cursors cursor = tweepy.Cursor(api.followers, count=200).pages() for i, page in enumerate(limit_handled(cursor, followers_list)): print(\"\\r\"+\"Loading\"+ i % 5 *\".\", end='') # Add latest batch of follower data to the list followers_list += page # Extract the follower information followers_list = [x._json for x in followers_list] # Save the data in a JSON file save_json('followers_data.json', followers_list)"
},
{
"code": null,
"e": 11478,
"s": 11002,
"text": "As you can see, we use the helper functions we created above. In addition, tweepy.Cursor(api.followers, count=200).pages() creates a Cursor object that will return the data of 200 followers one page at a time. We can now pass this cursor to our limited_handled function along with followers_list. Note, that the retrieved User objects contain two keys _api and _json, so we simply extract the data we care about using the List comprehension [x._json for x in followers_list]."
},
{
"code": null,
"e": 11488,
"s": 11478,
"text": "Following"
},
{
"code": null,
"e": 12066,
"s": 11488,
"text": "# Function to save friend objects in a JSON file.def get_friends(): # Create a list to store friends data friends_list = [] # For-loop to iterate over tweepy cursors cursor = tweepy.Cursor(api.friends, count=200).pages() for i, page in enumerate(limit_handled(cursor, friends_list)): print(\"\\r\"+\"Loading\"+ i % 5 *\".\", end='') # Add latest batch of friend data to the list friends_list += page # Extract the friends information friends_list = [x._json for x in friends_list] # Save the data in a JSON file save_json('friends_data.json', friends_list)"
},
{
"code": null,
"e": 12252,
"s": 12066,
"text": "You can see that this is exactly like our get_followers() function, except that we use api.friends to define our Cursor object, so we can retrieve the data of the users we’re following."
},
{
"code": null,
"e": 12266,
"s": 12252,
"text": "Today’s Stats"
},
{
"code": null,
"e": 12858,
"s": 12266,
"text": "# Function to save daily follower and following counts in a JSON filedef todays_stats(dict_name): # Get my account information info = api.me() # Get follower and following counts followers_cnt = info.followers_count following_cnt = info.friends_count # Get today's date today = date.today() d = today.strftime(\"%b %d, %Y\") # Save today's stats only if they haven't been collected before if d not in dict_name: dict_name[d] = {\"followers\":followers_cnt, \"following\":following_cnt} save_json(\"follower_history.json\", dict_name) else: print('Today\\'s stats already exist')"
},
{
"code": null,
"e": 13159,
"s": 12858,
"text": "api.me() returns the authenticating user’s information, in this case, me. From there, collecting the follower and following counts is straightforward. The date format I specified %b %d, %Y will return dates in a format that looks like Nov 11, 2019, for example. There are many formats to choose from."
},
{
"code": null,
"e": 13405,
"s": 13159,
"text": "I hope that you’ve enjoyed this tutorial which covered Twitter data collection. Writing this post was very helpful in clarifying my understanding of my own code. For example, I better understood tweepy Cursor objects. It reminded me of the quote"
},
{
"code": null,
"e": 13448,
"s": 13405,
"text": "“If you want to learn something, teach it”"
}
] |
How to Design Image Slider using jQuery ? - GeeksforGeeks | 28 Jan, 2022
A slideshow container that cycles through a list of images on a web page. The following article will guide you to implement an image slider using HTML, CSS, and jQuery. The jQuery image slider contains images that run them using the previous and next icons. Previous and Next arrows are used to traverse back and forth on mouse hover event on the images. The following example code is implemented in a simple and flexible way of showing the images one by one in the carousel by using HTML, CSS, and jQuery. We will accomplish the task into two sections first we will create the structure by HTML the Design the structure bys CSS and make interactive by jQuery.Creating Structure: In this section, we will create the structure of the image slider.
HTML Code: HTML is used to create the structure of an image slider.
html
<!DOCTYPE html><html> <head> <title> How to Design Image Slider using jQuery ? </title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"></head> <body> <center> <h1 style="color:green"> GeeksforGeeks </h1> <b> How to code Image Slider using jQuery </b> <br><br> </center> <!-- Image container of the image slider --> <div class="image-container"> <div class="slide"> <div class="slideNumber">1</div> <img src="https://www.geeksforgeeks.org/wp-content/uploads/html-768x256.png"> </div> <div class="slide"> <div class="slideNumber">2</div> <img src="https://www.geeksforgeeks.org/wp-content/uploads/CSS-768x256.png"> </div> <div class="slide"> <div class="slideNumber">3</div> <img src="https://www.geeksforgeeks.org/wp-content/uploads/jquery-banner.png"> </div> <!-- Next and Previous icon to change images --> <a class="previous" onclick="moveSlides(-1)"> <i class="fa fa-chevron-circle-left"></i> </a> <a class="next" onclick="moveSlides(1)"> <i class="fa fa-chevron-circle-right"></i> </a> </div> <br> <div style="text-align:center"> <span class="footerdot" onclick="activeSlide(1)"> </span> <span class="footerdot" onclick="activeSlide(2)"> </span> <span class="footerdot" onclick="activeSlide(3)"> </span> </div></body> </html>
Designing Structure: Here we will be done the designing part of the image slider by using CSS and make the slider interactive by using jQuery.
CSS Code: Designing the structure on the basis of tags and classes of all the elements.
CSS
<style> img { width: 100%; } .height { height: 10px; } /* Image-container design */ .image-container { max-width: 800px; position: relative; margin: auto; } .next { right: 0; } /* Next and previous icon design */ .previous, .next { cursor: pointer; position: absolute; top: 50%; padding: 10px; margin-top: -25px; } /* caption decorate */ .captionText { color: #000000; font-size: 14px; position: absolute; padding: 12px 12px; bottom: 8px; width: 100%; text-align: center; } /* Slider image number */ .slideNumber { background-color: #5574C5; color: white; border-radius: 25px; right: 0; opacity: .5; margin: 5px; width: 30px; height: 30px; text-align: center; font-weight: bold; font-size: 24px; position: absolute; } .fa { font-size: 32px; } .fa:hover { transform: rotate(360deg); transition: 1s; color: white; } .footerdot { cursor: pointer; height: 15px; width: 15px; margin: 0 2px; background-color: #bbbbbb; border-radius: 50%; display: inline-block; transition: background-color 0.5s ease; } .active, .footerdot:hover { background-color: black; } </style>
jQuery Code: jQuery is used to design the slider interactive.
javascript
<script> var slideIndex = 1; displaySlide(slideIndex); function moveSlides(n) { displaySlide(slideIndex += n); } function activeSlide(n) { displaySlide(slideIndex = n); } /* Main function */ function displaySlide(n) { var i; var totalslides = document.getElementsByClassName("slide"); var totaldots = document.getElementsByClassName("footerdot"); if (n > totalslides.length) { slideIndex = 1; } if (n < 1) { slideIndex = totalslides.length; } for (i = 0; i < totalslides.length; i++) { totalslides[i].style.display = "none"; } for (i = 0; i < totaldots.length; i++) { totaldots[i].className = totaldots[i].className.replace(" active", ""); } totalslides[slideIndex - 1].style.display = "block"; totaldots[slideIndex - 1].className += " active"; }</script>
Complete Solution: In this section, we will combine the above sections together that will be an Image Slider.
html
<!DOCTYPE html><html> <head> <title> How to Design Image Slider using jQuery ? </title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <style> img { width: 100%; } .height { height: 10px; } /* Image-container design */ .image-container { max-width: 800px; position: relative; margin: auto; } .next { right: 0; } /* Next and previous icon design */ .previous, .next { cursor: pointer; position: absolute; top: 50%; padding: 10px; margin-top: -25px; } /* caption decorate */ .captionText { color: #000000; font-size: 14px; position: absolute; padding: 12px 12px; bottom: 8px; width: 100%; text-align: center; } /* Slider image number */ .slideNumber { background-color: #5574C5; color: white; border-radius: 25px; right: 0; opacity: .5; margin: 5px; width: 30px; height: 30px; text-align: center; font-weight: bold; font-size: 24px; position: absolute; } .fa { font-size: 32px; } .fa:hover { transform: rotate(360deg); transition: 1s; color: white; } .footerdot { cursor: pointer; height: 15px; width: 15px; margin: 0 2px; background-color: #bbbbbb; border-radius: 50%; display: inline-block; transition: background-color 0.5s ease; } .active, .footerdot:hover { background-color: black; } </style></head> <body> <center> <h1 style="color:green"> GeeksforGeeks </h1> <b> How to code Image Slider using jQuery </b> <br><br> </center> <!-- Image container of the image slider --> <div class="image-container"> <div class="slide"> <div class="slideNumber">1</div> <img src="https://www.geeksforgeeks.org/wp-content/uploads/html-768x256.png"> </div> <div class="slide"> <div class="slideNumber">2</div> <img src="https://www.geeksforgeeks.org/wp-content/uploads/CSS-768x256.png"> </div> <div class="slide"> <div class="slideNumber">3</div> <img src="https://www.geeksforgeeks.org/wp-content/uploads/jquery-banner.png"> </div> <!-- Next and Previous icon to change images --> <a class="previous" onclick="moveSlides(-1)"> <i class="fa fa-chevron-circle-left"></i> </a> <a class="next" onclick="moveSlides(1)"> <i class="fa fa-chevron-circle-right"></i> </a> </div> <br> <div style="text-align:center"> <span class="footerdot" onclick="activeSlide(1)"> </span> <span class="footerdot" onclick="activeSlide(2)"> </span> <span class="footerdot" onclick="activeSlide(3)"> </span> </div> <script> var slideIndex = 1; displaySlide(slideIndex); function moveSlides(n) { displaySlide(slideIndex += n); } function activeSlide(n) { displaySlide(slideIndex = n); } /* Main function */ function displaySlide(n) { var i; var totalslides = document.getElementsByClassName("slide"); var totaldots = document.getElementsByClassName("footerdot"); if (n > totalslides.length) { slideIndex = 1; } if (n < 1) { slideIndex = totalslides.length; } for (i = 0; i < totalslides.length; i++) { totalslides[i].style.display = "none"; } for (i = 0; i < totaldots.length; i++) { totaldots[i].className = totaldots[i].className.replace(" active", ""); } totalslides[slideIndex - 1].style.display = "block"; totaldots[slideIndex - 1].className += " active"; } </script></body> </html>
Output:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
ruhelaa48
CSS-Misc
HTML-Misc
jQuery-Misc
CSS
HTML
JQuery
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to create footer to stay at the bottom of a Web page?
Types of CSS (Cascading Style Sheet)
Create a Responsive Navbar using ReactJS
Design a web page using HTML and CSS
How to Upload Image into Database and Display it using PHP ?
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
Hide or show elements in HTML using display property
How to Insert Form Data into Database using PHP ?
REST API (Introduction) | [
{
"code": null,
"e": 25375,
"s": 25347,
"text": "\n28 Jan, 2022"
},
{
"code": null,
"e": 26124,
"s": 25375,
"text": "A slideshow container that cycles through a list of images on a web page. The following article will guide you to implement an image slider using HTML, CSS, and jQuery. The jQuery image slider contains images that run them using the previous and next icons. Previous and Next arrows are used to traverse back and forth on mouse hover event on the images. The following example code is implemented in a simple and flexible way of showing the images one by one in the carousel by using HTML, CSS, and jQuery. We will accomplish the task into two sections first we will create the structure by HTML the Design the structure bys CSS and make interactive by jQuery.Creating Structure: In this section, we will create the structure of the image slider. "
},
{
"code": null,
"e": 26194,
"s": 26124,
"text": "HTML Code: HTML is used to create the structure of an image slider. "
},
{
"code": null,
"e": 26199,
"s": 26194,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title> How to Design Image Slider using jQuery ? </title> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css\"></head> <body> <center> <h1 style=\"color:green\"> GeeksforGeeks </h1> <b> How to code Image Slider using jQuery </b> <br><br> </center> <!-- Image container of the image slider --> <div class=\"image-container\"> <div class=\"slide\"> <div class=\"slideNumber\">1</div> <img src=\"https://www.geeksforgeeks.org/wp-content/uploads/html-768x256.png\"> </div> <div class=\"slide\"> <div class=\"slideNumber\">2</div> <img src=\"https://www.geeksforgeeks.org/wp-content/uploads/CSS-768x256.png\"> </div> <div class=\"slide\"> <div class=\"slideNumber\">3</div> <img src=\"https://www.geeksforgeeks.org/wp-content/uploads/jquery-banner.png\"> </div> <!-- Next and Previous icon to change images --> <a class=\"previous\" onclick=\"moveSlides(-1)\"> <i class=\"fa fa-chevron-circle-left\"></i> </a> <a class=\"next\" onclick=\"moveSlides(1)\"> <i class=\"fa fa-chevron-circle-right\"></i> </a> </div> <br> <div style=\"text-align:center\"> <span class=\"footerdot\" onclick=\"activeSlide(1)\"> </span> <span class=\"footerdot\" onclick=\"activeSlide(2)\"> </span> <span class=\"footerdot\" onclick=\"activeSlide(3)\"> </span> </div></body> </html>",
"e": 27972,
"s": 26199,
"text": null
},
{
"code": null,
"e": 28117,
"s": 27972,
"text": "Designing Structure: Here we will be done the designing part of the image slider by using CSS and make the slider interactive by using jQuery. "
},
{
"code": null,
"e": 28207,
"s": 28117,
"text": "CSS Code: Designing the structure on the basis of tags and classes of all the elements. "
},
{
"code": null,
"e": 28211,
"s": 28207,
"text": "CSS"
},
{
"code": "<style> img { width: 100%; } .height { height: 10px; } /* Image-container design */ .image-container { max-width: 800px; position: relative; margin: auto; } .next { right: 0; } /* Next and previous icon design */ .previous, .next { cursor: pointer; position: absolute; top: 50%; padding: 10px; margin-top: -25px; } /* caption decorate */ .captionText { color: #000000; font-size: 14px; position: absolute; padding: 12px 12px; bottom: 8px; width: 100%; text-align: center; } /* Slider image number */ .slideNumber { background-color: #5574C5; color: white; border-radius: 25px; right: 0; opacity: .5; margin: 5px; width: 30px; height: 30px; text-align: center; font-weight: bold; font-size: 24px; position: absolute; } .fa { font-size: 32px; } .fa:hover { transform: rotate(360deg); transition: 1s; color: white; } .footerdot { cursor: pointer; height: 15px; width: 15px; margin: 0 2px; background-color: #bbbbbb; border-radius: 50%; display: inline-block; transition: background-color 0.5s ease; } .active, .footerdot:hover { background-color: black; } </style>",
"e": 29748,
"s": 28211,
"text": null
},
{
"code": null,
"e": 29812,
"s": 29748,
"text": "jQuery Code: jQuery is used to design the slider interactive. "
},
{
"code": null,
"e": 29823,
"s": 29812,
"text": "javascript"
},
{
"code": "<script> var slideIndex = 1; displaySlide(slideIndex); function moveSlides(n) { displaySlide(slideIndex += n); } function activeSlide(n) { displaySlide(slideIndex = n); } /* Main function */ function displaySlide(n) { var i; var totalslides = document.getElementsByClassName(\"slide\"); var totaldots = document.getElementsByClassName(\"footerdot\"); if (n > totalslides.length) { slideIndex = 1; } if (n < 1) { slideIndex = totalslides.length; } for (i = 0; i < totalslides.length; i++) { totalslides[i].style.display = \"none\"; } for (i = 0; i < totaldots.length; i++) { totaldots[i].className = totaldots[i].className.replace(\" active\", \"\"); } totalslides[slideIndex - 1].style.display = \"block\"; totaldots[slideIndex - 1].className += \" active\"; }</script>",
"e": 30812,
"s": 29823,
"text": null
},
{
"code": null,
"e": 30924,
"s": 30812,
"text": "Complete Solution: In this section, we will combine the above sections together that will be an Image Slider. "
},
{
"code": null,
"e": 30929,
"s": 30924,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title> How to Design Image Slider using jQuery ? </title> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css\"> <style> img { width: 100%; } .height { height: 10px; } /* Image-container design */ .image-container { max-width: 800px; position: relative; margin: auto; } .next { right: 0; } /* Next and previous icon design */ .previous, .next { cursor: pointer; position: absolute; top: 50%; padding: 10px; margin-top: -25px; } /* caption decorate */ .captionText { color: #000000; font-size: 14px; position: absolute; padding: 12px 12px; bottom: 8px; width: 100%; text-align: center; } /* Slider image number */ .slideNumber { background-color: #5574C5; color: white; border-radius: 25px; right: 0; opacity: .5; margin: 5px; width: 30px; height: 30px; text-align: center; font-weight: bold; font-size: 24px; position: absolute; } .fa { font-size: 32px; } .fa:hover { transform: rotate(360deg); transition: 1s; color: white; } .footerdot { cursor: pointer; height: 15px; width: 15px; margin: 0 2px; background-color: #bbbbbb; border-radius: 50%; display: inline-block; transition: background-color 0.5s ease; } .active, .footerdot:hover { background-color: black; } </style></head> <body> <center> <h1 style=\"color:green\"> GeeksforGeeks </h1> <b> How to code Image Slider using jQuery </b> <br><br> </center> <!-- Image container of the image slider --> <div class=\"image-container\"> <div class=\"slide\"> <div class=\"slideNumber\">1</div> <img src=\"https://www.geeksforgeeks.org/wp-content/uploads/html-768x256.png\"> </div> <div class=\"slide\"> <div class=\"slideNumber\">2</div> <img src=\"https://www.geeksforgeeks.org/wp-content/uploads/CSS-768x256.png\"> </div> <div class=\"slide\"> <div class=\"slideNumber\">3</div> <img src=\"https://www.geeksforgeeks.org/wp-content/uploads/jquery-banner.png\"> </div> <!-- Next and Previous icon to change images --> <a class=\"previous\" onclick=\"moveSlides(-1)\"> <i class=\"fa fa-chevron-circle-left\"></i> </a> <a class=\"next\" onclick=\"moveSlides(1)\"> <i class=\"fa fa-chevron-circle-right\"></i> </a> </div> <br> <div style=\"text-align:center\"> <span class=\"footerdot\" onclick=\"activeSlide(1)\"> </span> <span class=\"footerdot\" onclick=\"activeSlide(2)\"> </span> <span class=\"footerdot\" onclick=\"activeSlide(3)\"> </span> </div> <script> var slideIndex = 1; displaySlide(slideIndex); function moveSlides(n) { displaySlide(slideIndex += n); } function activeSlide(n) { displaySlide(slideIndex = n); } /* Main function */ function displaySlide(n) { var i; var totalslides = document.getElementsByClassName(\"slide\"); var totaldots = document.getElementsByClassName(\"footerdot\"); if (n > totalslides.length) { slideIndex = 1; } if (n < 1) { slideIndex = totalslides.length; } for (i = 0; i < totalslides.length; i++) { totalslides[i].style.display = \"none\"; } for (i = 0; i < totaldots.length; i++) { totaldots[i].className = totaldots[i].className.replace(\" active\", \"\"); } totalslides[slideIndex - 1].style.display = \"block\"; totaldots[slideIndex - 1].className += \" active\"; } </script></body> </html>",
"e": 35658,
"s": 30929,
"text": null
},
{
"code": null,
"e": 35668,
"s": 35658,
"text": "Output: "
},
{
"code": null,
"e": 35807,
"s": 35670,
"text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course."
},
{
"code": null,
"e": 35817,
"s": 35807,
"text": "ruhelaa48"
},
{
"code": null,
"e": 35826,
"s": 35817,
"text": "CSS-Misc"
},
{
"code": null,
"e": 35836,
"s": 35826,
"text": "HTML-Misc"
},
{
"code": null,
"e": 35848,
"s": 35836,
"text": "jQuery-Misc"
},
{
"code": null,
"e": 35852,
"s": 35848,
"text": "CSS"
},
{
"code": null,
"e": 35857,
"s": 35852,
"text": "HTML"
},
{
"code": null,
"e": 35864,
"s": 35857,
"text": "JQuery"
},
{
"code": null,
"e": 35881,
"s": 35864,
"text": "Web Technologies"
},
{
"code": null,
"e": 35908,
"s": 35881,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 35913,
"s": 35908,
"text": "HTML"
},
{
"code": null,
"e": 36011,
"s": 35913,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36069,
"s": 36011,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 36106,
"s": 36069,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 36147,
"s": 36106,
"text": "Create a Responsive Navbar using ReactJS"
},
{
"code": null,
"e": 36184,
"s": 36147,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 36245,
"s": 36184,
"text": "How to Upload Image into Database and Display it using PHP ?"
},
{
"code": null,
"e": 36305,
"s": 36245,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 36366,
"s": 36305,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 36419,
"s": 36366,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 36469,
"s": 36419,
"text": "How to Insert Form Data into Database using PHP ?"
}
] |
How to specify an image as a client-side image-map in HTML? | Use the usemap attribute to specify an image as a client-side image-map in HTML. You can try to run the following code to implement usemap attribute −
<!DOCTYPE html>
<html>
<head>
<title>HTML map Tag</title>
</head>
<body>
<img src = "/images/html.gif" alt = "HTML Map" border = "0" usemap = "#html"/>
<!-- Create Mappings -->
<map name = "html">
<area shape = "circle" coords = "154,150,59" href = "about/about_team.htm"
alt = "Team" target = "_self" />
</map>
</body>
</html> | [
{
"code": null,
"e": 1213,
"s": 1062,
"text": "Use the usemap attribute to specify an image as a client-side image-map in HTML. You can try to run the following code to implement usemap attribute −"
},
{
"code": null,
"e": 1601,
"s": 1213,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>HTML map Tag</title>\n </head>\n <body>\n <img src = \"/images/html.gif\" alt = \"HTML Map\" border = \"0\" usemap = \"#html\"/>\n <!-- Create Mappings -->\n <map name = \"html\">\n <area shape = \"circle\" coords = \"154,150,59\" href = \"about/about_team.htm\"\n alt = \"Team\" target = \"_self\" />\n </map>\n </body>\n</html>"
}
] |
How to Setup SSL for MySQL Server and Client on Linux | In this tutorial, I will be explaining about – how to set up a secure connection to MySQL server using an SSH connection for encryption so that data in the database will be in safe and which is impossible for hackers to steal the data. SSL is used to verify the means of SSL certificates which can protect against phishing attacks. This will also show you – how to enable SSL on MySQL server also.
Connect to the MySQL server and check that SSL status of the MySQL server
# mysql -u root -p
mysql> show variables like '%ssl%';
Output:
+---------------+----------+
| Variable_name | Value |
+---------------+----------+
| have_openssl | DISABLED |
| have_ssl | DISABLED |
| ssl_ca | |
| ssl_capath | |
| ssl_cert | |
| ssl_cipher | |
| ssl_key | |
+---------------+----------+
7 rows in set (0.00 sec)
mysql> \q
Bye
Create a directory for storing the certificate files
# mkdir /etc/certificates
# cd /etc/certificates
# openssl genrsa 2048 > ca-key.pem
Generating RSA private key, 2048 bit long modulus
...................................................................................+++
..........+++
e is 65537 (0x10001)
# openssl req -newkey rsa:2048 -days 1000 -nodes -keyout server-key.pem > server-req.pem
Generating a 2048 bit RSA private key
..................+++
..............................................................................................+++
writing new private key to 'server-key.pem'
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [XX]:
State or Province Name (full name) []:
Locality Name (eg, city) [Default City]:
Organization Name (eg, company) [Default Company Ltd]:
Organizational Unit Name (eg, section) []:
Common Name (eg, your name or your server's hostname) []:
Email Address []:
Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:
# openssl x509 -req -in server-req.pem -days 1000 -CA ca-cert.pem -CAkey ca-key.pem -set_serial 01 > server-cert.pem
Signature ok
subject=/C=XX/L=Default City/O=Default Company Ltd
Error opening CA Certificate ca-cert.pem
139991633303368:error:02001002:system library:fopen:No such file or directory:bss_file.c:398:fopen('ca-cert.pem','r')
139991633303368:error:20074002:BIO routines:FILE_CTRL:system lib:bss_file.c:400:
unable to load certificate
Generating client certificates
# openssl req -newkey rsa:2048 -days 1000 -nodes -keyout client-key.pem > client-req.pem
Generating a 2048 bit RSA private key
...............................................+++
.................+++
writing new private key to 'client-key.pem'
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [XX]:
State or Province Name (full name) []:
Locality Name (eg, city) [Default City]:
Organization Name (eg, company) [Default Company Ltd]:
Organizational Unit Name (eg, section) []:
Common Name (eg, your name or your server's hostname) []:
Email Address []:
Please enter the following 'extra' attributes openssl x509 -req -in client-req.pem -days 1000 -CA ca-# cert.pem -CAkey ca-key.pem -set_serial 01 > client-cert.pem
Signature ok
subject=/C=XX/L=Default City/O=Default Company Ltd
Error opening CA Certificate ca-cert.pem
140327140685640:error:02001002:system library:fopen:No such file or directory:bss_file.c:398:fopen('ca-cert.pem','r')
140327140685640:error:20074002:BIO routines:FILE_CTRL:system lib:bss_file.c:400:
unable to load certificate to be sent with your certificate request
A challenge password []:
An optional company name []:
Now open the my.cnf file and add the certificates
# vi /etc/my.cnf
[mysqld]
ssl-ca=/etc/certificates/cacert.pem
ssl-cert=/etc/certificates/server-cert.pem
ssl-key=/etc/certificates/server-key.pem
#service mysqld restart
#mysql -uroot -p
mysql>show variables like '%ssl%';
+---------------+-----------------------------------+
| Variable_name | Value |
+---------------+-----------------------------------+
| have_openssl | YES |
| have_ssl | YES |
| ssl_ca |/etc/certificates/cacert.pem |
| ssl_capath | |
| ssl_cert | /etc/certificates/server-cert.pem |
| ssl_cipher | |
| ssl_key | /etc/certificates/server-key.pem |
+---------------+-----------------------------------+
7 rows in set (0.00 sec)
mysql> GRANT ALL PRIVILEGES ON *.* TO ‘ssl_user’@’%’ IDENTIFIED BY ‘password’ REQUIRE SSL;
mysql> FLUSH PRIVILEGES;
From server side we needed to copy client-cert.pem client-key.pem client-req.pem from server to client.
# scp /etc/ certificates/client-cert.pem [email protected]:/etc/certificates
# scp /etc/ certificates/client-key.pem [email protected]:/etc/certificates
# scp /etc/ certificates/client-req.pem [email protected]:/etc/certificates
Once the files transferred to client connect to the client and try to connect to the MySQL using SSL certificates.
# mysql --ssl-ca=ca-cert.pem --ssl-cert=client-cert.pem --ssl-key=client-key.pem -h 192.168.87.156 -u ssluser -p
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 3
Server version: 5.1.73 Source distribution
Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql> status
--------------
mysql Ver 14.14 Distrib 5.1.73, for redhat-linux-gnu (x86_64) using readline 5.1
Connection id: 3
Current database:
Current user: root@localhost
SSL: Clipher in use is DHE-RSA-AES256-SHA
Current pager: stdout
Using outfile: ''
Using delimiter: ;
Server version: 5.1.73 Source distribution
Protocol version: 10
Connection: 192.168.87.158 via TCP/IP
Server characterset: latin1
Db characterset: latin1
Client characterset: latin1
Conn. characterset: latin1
UNIX socket: /var/lib/mysql/mysql.sock
Uptime: 11 min 13 sec
Threads: 1 Questions: 8 Slow queries: 0 Opens: 15 Flush tables: 1 Open tables: 8 Queries per second avg: 0.11
-------------
Later, add the settings in the /etc/my.cnf file, to permanently so that when we connect to the MySQL server we should connect using SSL.
# vi /etc/my.cnf
[client]
ssl-ca=/etc/certificates/ client-cert.pem
ssl-cert=/etc/certificates/client-cert.pem
ssl-key=/etc/certificates/client-key.pem
After this configuration and set up now you can be able to connect to MySQL server from the client side using the SSL key to protect the data from stealing data and which also secures the data from hackers. | [
{
"code": null,
"e": 1460,
"s": 1062,
"text": "In this tutorial, I will be explaining about – how to set up a secure connection to MySQL server using an SSH connection for encryption so that data in the database will be in safe and which is impossible for hackers to steal the data. SSL is used to verify the means of SSL certificates which can protect against phishing attacks. This will also show you – how to enable SSL on MySQL server also."
},
{
"code": null,
"e": 1534,
"s": 1460,
"text": "Connect to the MySQL server and check that SSL status of the MySQL server"
},
{
"code": null,
"e": 1955,
"s": 1534,
"text": "# mysql -u root -p\nmysql> show variables like '%ssl%';\nOutput:\n+---------------+----------+\n| Variable_name | Value |\n+---------------+----------+\n| have_openssl | DISABLED |\n| have_ssl | DISABLED |\n| ssl_ca | |\n| ssl_capath | |\n| ssl_cert | |\n| ssl_cipher | |\n| ssl_key | |\n+---------------+----------+\n7 rows in set (0.00 sec)\nmysql> \\q\nBye"
},
{
"code": null,
"e": 2008,
"s": 1955,
"text": "Create a directory for storing the certificate files"
},
{
"code": null,
"e": 2057,
"s": 2008,
"text": "# mkdir /etc/certificates\n# cd /etc/certificates"
},
{
"code": null,
"e": 3805,
"s": 2057,
"text": "# openssl genrsa 2048 > ca-key.pem\nGenerating RSA private key, 2048 bit long modulus\n...................................................................................+++\n..........+++\ne is 65537 (0x10001)\n# openssl req -newkey rsa:2048 -days 1000 -nodes -keyout server-key.pem > server-req.pem\nGenerating a 2048 bit RSA private key\n..................+++\n..............................................................................................+++\nwriting new private key to 'server-key.pem'\nYou are about to be asked to enter information that will be incorporated\ninto your certificate request.\nWhat you are about to enter is what is called a Distinguished Name or a DN.\nThere are quite a few fields but you can leave some blank\nFor some fields there will be a default value,\nIf you enter '.', the field will be left blank.\n-----\nCountry Name (2 letter code) [XX]:\nState or Province Name (full name) []:\nLocality Name (eg, city) [Default City]:\nOrganization Name (eg, company) [Default Company Ltd]:\nOrganizational Unit Name (eg, section) []:\nCommon Name (eg, your name or your server's hostname) []:\nEmail Address []:\nPlease enter the following 'extra' attributes\nto be sent with your certificate request\nA challenge password []:\nAn optional company name []:\n# openssl x509 -req -in server-req.pem -days 1000 -CA ca-cert.pem -CAkey ca-key.pem -set_serial 01 > server-cert.pem\nSignature ok\nsubject=/C=XX/L=Default City/O=Default Company Ltd\nError opening CA Certificate ca-cert.pem\n139991633303368:error:02001002:system library:fopen:No such file or directory:bss_file.c:398:fopen('ca-cert.pem','r')\n139991633303368:error:20074002:BIO routines:FILE_CTRL:system lib:bss_file.c:400:\nunable to load certificate\nGenerating client certificates\n\n"
},
{
"code": null,
"e": 5271,
"s": 3805,
"text": "# openssl req -newkey rsa:2048 -days 1000 -nodes -keyout client-key.pem > client-req.pem\nGenerating a 2048 bit RSA private key\n...............................................+++\n.................+++\nwriting new private key to 'client-key.pem'\n-----\nYou are about to be asked to enter information that will be incorporated\ninto your certificate request.\nWhat you are about to enter is what is called a Distinguished Name or a DN.\nThere are quite a few fields but you can leave some blank\nFor some fields there will be a default value,\nIf you enter '.', the field will be left blank.\n-----\nCountry Name (2 letter code) [XX]:\nState or Province Name (full name) []:\nLocality Name (eg, city) [Default City]:\nOrganization Name (eg, company) [Default Company Ltd]:\nOrganizational Unit Name (eg, section) []:\nCommon Name (eg, your name or your server's hostname) []:\nEmail Address []:\nPlease enter the following 'extra' attributes openssl x509 -req -in client-req.pem -days 1000 -CA ca-# cert.pem -CAkey ca-key.pem -set_serial 01 > client-cert.pem\nSignature ok\nsubject=/C=XX/L=Default City/O=Default Company Ltd\nError opening CA Certificate ca-cert.pem\n140327140685640:error:02001002:system library:fopen:No such file or directory:bss_file.c:398:fopen('ca-cert.pem','r')\n140327140685640:error:20074002:BIO routines:FILE_CTRL:system lib:bss_file.c:400:\nunable to load certificate to be sent with your certificate request\nA challenge password []:\nAn optional company name []:"
},
{
"code": null,
"e": 5321,
"s": 5271,
"text": "Now open the my.cnf file and add the certificates"
},
{
"code": null,
"e": 5467,
"s": 5321,
"text": "# vi /etc/my.cnf\n[mysqld]\nssl-ca=/etc/certificates/cacert.pem\nssl-cert=/etc/certificates/server-cert.pem\nssl-key=/etc/certificates/server-key.pem"
},
{
"code": null,
"e": 6162,
"s": 5467,
"text": "#service mysqld restart\n#mysql -uroot -p\nmysql>show variables like '%ssl%';\n+---------------+-----------------------------------+\n| Variable_name | Value |\n+---------------+-----------------------------------+\n| have_openssl | YES |\n| have_ssl | YES |\n| ssl_ca |/etc/certificates/cacert.pem |\n| ssl_capath | |\n| ssl_cert | /etc/certificates/server-cert.pem |\n| ssl_cipher | |\n| ssl_key | /etc/certificates/server-key.pem |\n+---------------+-----------------------------------+\n7 rows in set (0.00 sec)"
},
{
"code": null,
"e": 6278,
"s": 6162,
"text": "mysql> GRANT ALL PRIVILEGES ON *.* TO ‘ssl_user’@’%’ IDENTIFIED BY ‘password’ REQUIRE SSL;\nmysql> FLUSH PRIVILEGES;"
},
{
"code": null,
"e": 6382,
"s": 6278,
"text": "From server side we needed to copy client-cert.pem client-key.pem client-req.pem from server to client."
},
{
"code": null,
"e": 6617,
"s": 6382,
"text": "# scp /etc/ certificates/client-cert.pem [email protected]:/etc/certificates\n# scp /etc/ certificates/client-key.pem [email protected]:/etc/certificates\n# scp /etc/ certificates/client-req.pem [email protected]:/etc/certificates"
},
{
"code": null,
"e": 6732,
"s": 6617,
"text": "Once the files transferred to client connect to the client and try to connect to the MySQL using SSL certificates."
},
{
"code": null,
"e": 7936,
"s": 6732,
"text": "# mysql --ssl-ca=ca-cert.pem --ssl-cert=client-cert.pem --ssl-key=client-key.pem -h 192.168.87.156 -u ssluser -p\nWelcome to the MySQL monitor. Commands end with ; or \\g.\nYour MySQL connection id is 3\nServer version: 5.1.73 Source distribution\nCopyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.\nOracle is a registered trademark of Oracle Corporation and/or its\naffiliates. Other names may be trademarks of their respective\nowners.\nType 'help;' or '\\h' for help. Type '\\c' to clear the current input statement.\nmysql> status\n--------------\nmysql Ver 14.14 Distrib 5.1.73, for redhat-linux-gnu (x86_64) using readline 5.1\nConnection id: 3\nCurrent database:\nCurrent user: root@localhost\nSSL: Clipher in use is DHE-RSA-AES256-SHA\nCurrent pager: stdout\nUsing outfile: ''\nUsing delimiter: ;\nServer version: 5.1.73 Source distribution\nProtocol version: 10\nConnection: 192.168.87.158 via TCP/IP\nServer characterset: latin1\nDb characterset: latin1\nClient characterset: latin1\nConn. characterset: latin1\nUNIX socket: /var/lib/mysql/mysql.sock\nUptime: 11 min 13 sec\nThreads: 1 Questions: 8 Slow queries: 0 Opens: 15 Flush tables: 1 Open tables: 8 Queries per second avg: 0.11\n-------------"
},
{
"code": null,
"e": 8073,
"s": 7936,
"text": "Later, add the settings in the /etc/my.cnf file, to permanently so that when we connect to the MySQL server we should connect using SSL."
},
{
"code": null,
"e": 8225,
"s": 8073,
"text": "# vi /etc/my.cnf\n[client]\nssl-ca=/etc/certificates/ client-cert.pem\nssl-cert=/etc/certificates/client-cert.pem\nssl-key=/etc/certificates/client-key.pem"
},
{
"code": null,
"e": 8432,
"s": 8225,
"text": "After this configuration and set up now you can be able to connect to MySQL server from the client side using the SSL key to protect the data from stealing data and which also secures the data from hackers."
}
] |
How to delete data in a MySQL database with Java? | Delete data from a MySQL database with the help of DELETE command. The syntax is as follows.
delete from yourTableName where condition;
I will delete data from a MySQL database with the help of JAVA programming language. First, create a table and insert some records. The following is the query to create a table.
mysql> create table DeleteTableDemo
-> (
-> id int,
-> Name varchar(200)
-> );
Query OK, 0 rows affected (0.94 sec)
Insert records in the above table. The query to insert records is as follows.
mysql> insert into DeleteTableDemo values(101,'Smith');
Query OK, 1 row affected (0.21 sec)
mysql> insert into DeleteTableDemo values(102,'Johnson');
Query OK, 1 row affected (0.27 sec)
Now we can check how many records are in my table. The query is as follows.
mysql> select *from DeleteTableDemo;
The following is the output.
+------+---------+
| id | Name |
+------+---------+
| 101 | Smith |
| 102 | Johnson |
+------+---------+
2 rows in set (0.00 sec)
We have two records in the table. Now, let us deleted data from a MySQL database table with the help of delete command. Here is the JAVA code that deletes the data with id=101. Before that, we will establish a Java Connection to our MySQL database.
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
import com.mysql.jdbc.Statement;
public class JavaDeleteDemo {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (Exception e) {
System.out.println(e);
}
conn = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/business", "Manish", "123456");
System.out.println("Connection is created successfully:");
stmt = (Statement) conn.createStatement();
String query1 = "delete from DeleteTableDemo " +
"where id=101";
stmt.executeUpdate(query1);
System.out.println("Record is deleted from the table successfully..................");
} catch (SQLException excep) {
excep.printStackTrace();
} catch (Exception excep) {
excep.printStackTrace();
} finally {
try {
if (stmt != null)
conn.close();
} catch (SQLException se) {}
try {
if (conn != null)
conn.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
System.out.println("Please check it in the MySQL Table. Record is now deleted.......");
}
}
The following is the output.
mysql> select *from DeleteTableDemo;
The following is the output.
+------+---------+
| id | Name |
+------+---------+
| 102 |Johnson |
+------+---------+
1 row in set (0.00 sec) We have deleted the data with id 101. | [
{
"code": null,
"e": 1155,
"s": 1062,
"text": "Delete data from a MySQL database with the help of DELETE command. The syntax is as follows."
},
{
"code": null,
"e": 1198,
"s": 1155,
"text": "delete from yourTableName where condition;"
},
{
"code": null,
"e": 1376,
"s": 1198,
"text": "I will delete data from a MySQL database with the help of JAVA programming language. First, create a table and insert some records. The following is the query to create a table."
},
{
"code": null,
"e": 1504,
"s": 1376,
"text": "mysql> create table DeleteTableDemo\n -> (\n -> id int,\n -> Name varchar(200)\n -> );\nQuery OK, 0 rows affected (0.94 sec)"
},
{
"code": null,
"e": 1582,
"s": 1504,
"text": "Insert records in the above table. The query to insert records is as follows."
},
{
"code": null,
"e": 1769,
"s": 1582,
"text": "mysql> insert into DeleteTableDemo values(101,'Smith');\nQuery OK, 1 row affected (0.21 sec)\n\nmysql> insert into DeleteTableDemo values(102,'Johnson');\nQuery OK, 1 row affected (0.27 sec)"
},
{
"code": null,
"e": 1845,
"s": 1769,
"text": "Now we can check how many records are in my table. The query is as follows."
},
{
"code": null,
"e": 1882,
"s": 1845,
"text": "mysql> select *from DeleteTableDemo;"
},
{
"code": null,
"e": 1911,
"s": 1882,
"text": "The following is the output."
},
{
"code": null,
"e": 2050,
"s": 1911,
"text": "+------+---------+\n| id | Name |\n+------+---------+\n| 101 | Smith |\n| 102 | Johnson |\n+------+---------+\n2 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2299,
"s": 2050,
"text": "We have two records in the table. Now, let us deleted data from a MySQL database table with the help of delete command. Here is the JAVA code that deletes the data with id=101. Before that, we will establish a Java Connection to our MySQL database."
},
{
"code": null,
"e": 3796,
"s": 2299,
"text": "import java.sql.DriverManager;\nimport java.sql.ResultSet;\nimport java.sql.SQLException;\nimport com.mysql.jdbc.Connection;\nimport com.mysql.jdbc.PreparedStatement;\nimport com.mysql.jdbc.Statement;\npublic class JavaDeleteDemo {\n public static void main(String[] args) {\n Connection conn = null;\n Statement stmt = null;\n try {\n try {\n Class.forName(\"com.mysql.jdbc.Driver\");\n } catch (Exception e) {\n System.out.println(e);\n }\n conn = (Connection) DriverManager.getConnection(\"jdbc:mysql://localhost/business\", \"Manish\", \"123456\");\n System.out.println(\"Connection is created successfully:\");\n stmt = (Statement) conn.createStatement();\n String query1 = \"delete from DeleteTableDemo \" +\n \"where id=101\";\n stmt.executeUpdate(query1);\n System.out.println(\"Record is deleted from the table successfully..................\");\n } catch (SQLException excep) {\n excep.printStackTrace();\n } catch (Exception excep) {\n excep.printStackTrace();\n } finally {\n try {\n if (stmt != null)\n conn.close();\n } catch (SQLException se) {}\n try {\n if (conn != null)\n conn.close();\n } catch (SQLException se) {\n se.printStackTrace();\n }\n }\n System.out.println(\"Please check it in the MySQL Table. Record is now deleted.......\");\n }\n}"
},
{
"code": null,
"e": 3825,
"s": 3796,
"text": "The following is the output."
},
{
"code": null,
"e": 3862,
"s": 3825,
"text": "mysql> select *from DeleteTableDemo;"
},
{
"code": null,
"e": 3891,
"s": 3862,
"text": "The following is the output."
},
{
"code": null,
"e": 4044,
"s": 3891,
"text": "+------+---------+\n| id | Name |\n+------+---------+\n| 102 |Johnson |\n+------+---------+\n1 row in set (0.00 sec) We have deleted the data with id 101."
}
] |
An Overview of Building a Merchant Name Cleaning Engine with SequenceMatcher and spaCy | by Cheng | Towards Data Science | Merchant names cleaning can be a quite challenging problem. As different bank provides different quality of transaction data, there is not a very mature way to clean the data. Commonly, merchant names cleaning can be classified as a Named Entity Recognition (NER) task and be solved in a similar way as an entity extraction problem.
For a FinTech company, a merchant names cleaning step is important because developers need to utilize these cleaned merchant names out of originally messy transaction data to generate proper transaction categorization to deliver a better customer experience in terms of managing personal finance.
I found this topic very interesting and I have been searching resources for weeks to write up this overview with my own basic solution to this. Therefore, I hope some of my thoughts on this topic can be helpful for the readers to better solve this merchant names cleaning problem.
If you are searching for more readings on this topic, you’re welcome to check the Reference List at the end of this article.
For a basic merchant names cleaning engine, I plan to divide it into three layers:
1st Layer: Remove special characters & numbers and convert cases.
2nd Layer: Return name matches based on similarity scores.
3rd Layer: Train a spaCy model to detect patterns and clean the inputs.
Toolkit for this project includes regular expression operations in python, FuzzyWuzzy/SequenceMatcher (library) and some knowledge in the spaCy model algorithm.
As the reading progresses, I will also share some related readings I found helpful.
Removing all special characters & numbers will be the first step for the project. It’s useful because special characters and numbers often adds more complexity when we try to find merchant name matches and compute similarity scores. Completely removing all special characters and numbers might be a little aggressive. However, considering a dataset of thousands of raw merchant names, you may find that the majority of special characters and numbers can be removed without affecting any keyword in a merchant name.
Special characters and numbers removal can be efficiently done with the help of Python Re library. Some pre-requisite knowledge is regular expression in Python.
medium.com
medium.com
By successfully completing the above step, you now have a dataset of merchant names containing only the alphabet letters. However, you might still find that some merchant names are in different cases such as “AMAZON”, “amazon” or “Amazon”. To convert the cases, some useful string functions can be found in the following article:
towardsdatascience.com
For this layer, our main goal is to calculate a similarity score table and return the matched names with the top 3 largest similarity scores. This is a useful method to clean merchant names assuming that you already have a catalogue of names to match and also the raw inputs are non-messy.
FuzzyWuzzy is a Python library that uses Levenshtein Distance to calculate the differences between sequences in a simple-to-use package.
github.com
Some practical examples in use of FuzzyWuzzy are as followings:
Simple Ratio
>>> fuzz.ratio("this is a test", "this is a test!") 97
Partial Ratio
>>> fuzz.partial_ratio("this is a test", "this is a test!") 100
Token Sort Ratio
>>> fuzz.ratio("fuzzy wuzzy was a bear", "wuzzy fuzzy was a bear") 91>>> fuzz.token_sort_ratio("fuzzy wuzzy was a bear", "wuzzy fuzzy was a bear") 100
Token Set Ratio
>>> fuzz.token_sort_ratio("fuzzy was a bear", "fuzzy fuzzy was a bear") 84>>> fuzz.token_set_ratio("fuzzy was a bear", "fuzzy fuzzy was a bear") 100
towardsdatascience.com
towardsdatascience.com
Alternatively, SequenceMatcher is also a great tool often used to compute the similarity between inputs.
The basic idea is to find the longest contiguous matching subsequence that contains no “junk” elements. The same idea is then applied recursively to the pieces of the sequences to the left and to the right of the matching subsequence. This does not yield minimal edit sequences, but does tend to yield matches that “look right” to people.
>>> s = SequenceMatcher(lambda x: x == " ", "private Thread currentThread;", "private volatile Thread currentThread;") >>> .ratio() returns a float in [0, 1], measuring the "similarity" of the sequences. As a rule of thumb, a .ratio() value over 0.6 means the sequences are close matches>>> print(round(s.ratio(), 3)) 0.866
towardsdatascience.com
For me, I choose the SequenceMatcher as the metrics of evaluating similarity. The process will be similar if you choose the FuzzyWuzzy library.
# define a function to calculate similarity between input sequencesdef similarity_map(word1, word2): seq = difflib.SequenceMatcher(None,word1,word2) d = seq.ratio() return d
The above customized function takes two sequences as input and returns a ratio value of similarity score.
To further compute a table of similarity scores, I made a dataset that has raw merchant names as row indexes and a catalogue of cleaned merchant names as column names. By running the code cell below, it will generate a table of similarity scores for each pair of row index and column name.
# prepare a sample datasetdf = pd.DataFrame(data, index =['amazon co com', 'www netflix com', 'paypal payment', 'apple com bill', 'google play', 'facebook ads'],columns = ['amazon', 'netflix', 'paypal', 'apple', 'google', 'facebook']) # print the data dffrom tqdm import tqdmfor i in tqdm(range(6)): for j in range(6): df.loc[df.index[i], df.columns[j]] = similarity_map(str(df.index[i]), str(df.columns[j])) df.head()
Once you completed running the above cell, you should have a table of similarity scores looks like the following:
Based on the above table, we can further analyze insights by return merchant names that have top 3 highest similarity scores for each row.
Write a function top that takes above dataset as input and returns a dataset of top 3 names along with their similarity scores.
similarity = df.reset_index()similarity.head()def top(x): x.set_index('index', inplace=True) df = pd.DataFrame({'Max1Name':[],'Max2Name':[],'Max3Name':[],'Max1Value':[],'Max2Value':[],'Max3Value':[]}) df.index.name='index' df.loc[x.index.values[0],['Max1Name', 'Max2Name', 'Max3Name']] = x.sum().nlargest(3).index.tolist() df.loc[x.index.values[0],['Max1Value', 'Max2Value', 'Max3Value']] = x.sum().nlargest(3).values return dftest = similarity.groupby('index').apply(top).reset_index(level=1, drop=True).reset_index()test.head()
stackoverflow.com
stackoverflow.com
By successfully implementing the above code cell, you should have a return dataset like the following:
Although this is just a test on a sample dataset, we may still find this method useful if we have non-messy inputs along with a catalogue of cleaned merchant names.
However, this method may not perform well for more complex merchant inputs. For instance, a merchant name paypal * card payment on booking.com toronto will likely return a low similarity score (less than 0.5) with respect to either PayPal or Booking.
In this case, it requires a more advanced method to detect the location of the “real” merchant name we want.
By completing first two layers, we are able to solve some of the merchant names cleaning problems such as names of mis-spelling, different cases, missing characters/spaces and even some of the non-messy merchant inputs by simply returning a similarity score table.
However, we are actually still in the phase of working with a rule-based cleaning engine, which means so far we still haven’t learned from the data. Furthermore, even by use of a typical machine learning model, the training phase still requires a large amount of time to perform feature engineering in creating more informative features.
... potentially informative transaction-level features such as dollar amount and category, while also generating word-level natural language features such as word position within the label (e.g., 1st, 2nd), word length, proportion of vowels, consonants, and alphanumeric characters, among others.
CleanMachine: Financial transaction label translation for wallet.AI
Therefore, I researched on how to use a deep learning model to create the cleaning engine. The advantage of using a deep learning model is that we are able to “skip” the feature engineering step and let the model itself detect any insightful patterns from the inputs.
A free short course on spaCy can be found as following:
course.spacy.io
According to the spaCy Guide:
spaCy is a library for advanced Natural Language Processing in Python and Cython. It’s built on the very latest research, and was designed from day one to be used in real products. spaCy comes with pre-trained statistical models and word vectors, and currently supports tokenization for 60+ languages.
It features state-of-the-art speed, convolutional neural network models for tagging, parsing and named entity recognition and easy deep learning integration. It’s commercial open-source software, released under the MIT license.
github.com
Since the merchant names cleaning problem can be classified under the topic of named entity recognition(NER), I feel confident that a spaCy model will have a good performance by feeding in a set of representative input data.
To train a spaCy model, we don’t just want it to memorize our examples — we want it to come up with a theory that can be generalized across other examples.
Therefore, the training data should always be representative of the data we want to process. For our project, we may want to select training data from different types of merchant names. Eventually, our training data will be in form of an entity list like the following:
TRAIN_DATA = [('Amazon co ca', {'entities': [(0, 6, 'BRD')]}),('AMZNMKTPLACE AMAZON CO', {'entities': [(13, 19, 'BRD')]}),('APPLE COM BILL', {'entities': [(0, 5, 'BRD')]}),('BOOKING COM New York City', {'entities': [(0, 7, 'BRD')]}),('STARBUCKS Vancouver', {'entities': [(0, 9, 'BRD')]}),('Uber BV', {'entities': [(0, 4, 'BRD')]}),('Hotel on Booking com Toronto', {'entities': [(9, 16, 'BRD')]}),('UBER com', {'entities': [(0, 4, 'BRD')]}),('Netflix com', {'entities': [(0, 7, 'BRD')]})]]
The training data I choose is just a sample. The model can take more complex inputs. However, it can be a little boring to annotate a long list of merchant names. I would like to recommend another data labeling tool UBIAI to complete this task, as it supports output in a spaCy format or even in an Amazon Comprehend format.
ubiai.tools
medium.com
medium.com
It may require some experience on how to select a representative data input. As you practice more and observe the way how a spaCy model learns, it will become clearer that “representative” probably means “different locations”. It’s the reason why we need to provide an entity start & end index in the input data, because it can help the model to learn the patterns from different contexts.
If a model is often trained with the location of the first word being a merchant name (Amazon ca), then it tends to believe that a merchant name only locates at the beginning of an input. This will likely cause a bias and result in a wrong prediction for input such as “Music Spotify” because “Spotify” happens to be the second word.
However, it’s also important to include various merchant names in the input. Just be aware that we don’t want our model to merely memorize them.
Once you have finalized tuning your training data, the remaining process will almost be automated.
import spacyimport randomdef train_spacy(data,iterations): TRAIN_DATA = data nlp = spacy.blank('en') # create blank Language class # create the built-in pipeline components and add them to the pipeline # nlp.create_pipe works for built-ins that are registered with spaCy if 'ner' not in nlp.pipe_names: ner = nlp.create_pipe('ner') nlp.add_pipe(ner, last=True)# add labels for _, annotations in TRAIN_DATA: for ent in annotations.get('entities'): ner.add_label(ent[2])# get names of other pipes to disable them during training other_pipes = [pipe for pipe in nlp.pipe_names if pipe != 'ner'] with nlp.disable_pipes(*other_pipes): # only train NER optimizer = nlp.begin_training() for itn in range(iterations): print("Statring iteration " + str(itn)) random.shuffle(TRAIN_DATA) losses = {} for text, annotations in TRAIN_DATA: nlp.update( [text], # batch of texts [annotations], # batch of annotations drop=0.2, # dropout - make it harder to memorise data sgd=optimizer, # callable to update weights losses=losses) print(losses) return nlpprdnlp = train_spacy(TRAIN_DATA, 20)# Save our trained Modelmodelfile = input("Enter your Model Name: ")prdnlp.to_disk(modelfile)#Test your texttest_text = input("Enter your testing text: ")doc = prdnlp(test_text)for ent in doc.ents: print(ent.text, ent.start_char, ent.end_char, ent.label_)
Above code is from the following Medium article, as I found it very helpful and it inspired me to test spaCy on a merchant names cleaning problem.
manivannan-ai.medium.com
www.machinelearningplus.com
By successfully completing the training step, we can monitor the model progress by checking its loss values.
Statring iteration 0{'ner': 18.696674078702927}Statring iteration 1{'ner': 10.93641816265881}Statring iteration 2{'ner': 7.63046314753592}Statring iteration 3{'ner': 1.8599222962139454}Statring iteration 4{'ner': 0.29048295595632395}Statring iteration 5{'ner': 0.0009769084971516626}
The model is then shown the unlabelled text and will make a prediction. Because we know the correct answer, we can give the model feedback on its prediction in the form of an error gradient of the loss function that calculates the difference between the training example and the expected output. The greater the difference, the more significant the gradient and the updates to our model.
To test your model, you can run the code cell below:
#Test your texttest_text = input("Enter your testing text: ")doc = prdnlp(test_text)for ent in doc.ents: print(ent.text, ent.start_char, ent.end_char, ent.label_)
For instance, we can use “paypal payment” as input and test the model if it can detect “paypal” as the correct brand name.
The model did a great job considering PayPal did not appear in the training input.
This also concludes my project of building a merchant names cleaning engine with a spaCy model.
First of all, thank you for your time reading this long article and I sincerely hope you found it helpful~
I started from an introduction on why merchant names cleaning is important.
Then, I divided the cleaning engine into three layers.
Finally, for each layer, I explained the inputs & outputs as well as why each layer is necessary to have.
As an overview on this challenging problem, I didn’t fully expect to give a perfect solution to this. But I believe that it can be helpful to share my thoughts and any useful readings I found during my research.
Hence, I hope you enjoyed reading this article. Meanwhile, I added a Reference List section at the end of this article in case you are interested in learning more about this topic.
Thank you~
A little update on the spaCy model training results with around 1000 lines of input data. (1000 annotations)
I have set the model to 50 iterations each round of training and trained it for 10 rounds to see how the training loss varies. And it seems if we preprocess the data in a correct way, we should be able to reach a low & consistent training loss every time through 50 iterations, plotted as the following:
🤔 However, is there still any way to make our spaCy model more interactive? Would it be more user-friendly if we can integrate spaCy model with Streamlit into a web interface?
I was inspired by the spaCy documentation like the following:
It seems that spaCy supports many fancy tools including Streamlit. Therefore, I decided to try to integrate spaCy and Streamlit together for a web app.
If you would like more knowledge on Streamlit, the following article is a good start.
towardsdatascience.com
Since previously we have defined our spaCy training function as train_spacy, the remaining work will be within 10 lines of code. It’s also the reason why I think I should give an update under the same article 🤗
Assuming we have also prepared our input annotation list in the format of previous TRAIN_DATA.
A web app interface’s code in Streamlit will look like the following:
import pandas as pdimport numpy as np import randomimport spacyimport reimport warningsimport streamlit as st warnings.filterwarnings('ignore') # ignore warnings nlp = train_spacy(TRAIN_DATA, 50) # number of iterations set as 50# Save our trained Model # Once you obtained a trained model, you can switch to load a model for merchant name cleaningmodelfile = input("Enter your Model Name: ")nlp.to_disk(modelfile)# Load our saved Model # Load your model to clean a user input instead of training a new model once again when there is a new input# nlp = spacy.load(modelfile/) # path to the saved file foldertext = 'Amazon/ca' # default text input on web interfacest.title('Merchant Names Cleaning App') # web app title nameuser_input = st.text_input("Text", text) # input text placedoc = nlp(user_input) for ent in doc.ents: st.write('Text:', ent.text) # display model output st.write('Label:', ent.label_) # display model output
A successful web interface will look like the following:
Hope you enjoyed the reading!
[1] Cleaning up business names from Reddit
[2] Improving the classification of your transaction data with Machine Learning
[3] Making sense of messy bank data
[4] Standardizing +113 million Merchant Names in Financial Services with Greenplum Hadoop
[5] String Matching With FuzzyWuzzy
[6] Natural Language Processing for Fuzzy String Matching with Python
[7] An Ensemble Approach to Large-Scale Fuzzy Name Matching
[8] Hybrid Fuzzy Name Matching
[9] CleanMachine: Financial transaction label translation for wallet.AI
[10] Deep Learning Magic: Small Business Type
[11] Merchant Name Detection using Pytorch
[12] Categorize Banking Transaction Data
[13] Training spaCy’s Statistical Models
[14] How to Train spaCy to Autodetect New Entities (NER) [Complete Guide]
[15] Build a custom entity recognizer using Amazon Comprehend
[16] Developing NER models with Amazon SageMaker Ground Truth and Amazon Comprehend
[17] UBIAI Documentation
[18] How to Automate Job Searches Using Named Entity Recognition — Part 1
[19] Building a Job Entity Recognizer Using Amazon Comprehend
[20] Streamlit and spaCy: Create an App to Predict Sentiment and Word Similarities with Minimal Domain Knowledge | [
{
"code": null,
"e": 505,
"s": 172,
"text": "Merchant names cleaning can be a quite challenging problem. As different bank provides different quality of transaction data, there is not a very mature way to clean the data. Commonly, merchant names cleaning can be classified as a Named Entity Recognition (NER) task and be solved in a similar way as an entity extraction problem."
},
{
"code": null,
"e": 802,
"s": 505,
"text": "For a FinTech company, a merchant names cleaning step is important because developers need to utilize these cleaned merchant names out of originally messy transaction data to generate proper transaction categorization to deliver a better customer experience in terms of managing personal finance."
},
{
"code": null,
"e": 1083,
"s": 802,
"text": "I found this topic very interesting and I have been searching resources for weeks to write up this overview with my own basic solution to this. Therefore, I hope some of my thoughts on this topic can be helpful for the readers to better solve this merchant names cleaning problem."
},
{
"code": null,
"e": 1208,
"s": 1083,
"text": "If you are searching for more readings on this topic, you’re welcome to check the Reference List at the end of this article."
},
{
"code": null,
"e": 1291,
"s": 1208,
"text": "For a basic merchant names cleaning engine, I plan to divide it into three layers:"
},
{
"code": null,
"e": 1357,
"s": 1291,
"text": "1st Layer: Remove special characters & numbers and convert cases."
},
{
"code": null,
"e": 1416,
"s": 1357,
"text": "2nd Layer: Return name matches based on similarity scores."
},
{
"code": null,
"e": 1488,
"s": 1416,
"text": "3rd Layer: Train a spaCy model to detect patterns and clean the inputs."
},
{
"code": null,
"e": 1649,
"s": 1488,
"text": "Toolkit for this project includes regular expression operations in python, FuzzyWuzzy/SequenceMatcher (library) and some knowledge in the spaCy model algorithm."
},
{
"code": null,
"e": 1733,
"s": 1649,
"text": "As the reading progresses, I will also share some related readings I found helpful."
},
{
"code": null,
"e": 2248,
"s": 1733,
"text": "Removing all special characters & numbers will be the first step for the project. It’s useful because special characters and numbers often adds more complexity when we try to find merchant name matches and compute similarity scores. Completely removing all special characters and numbers might be a little aggressive. However, considering a dataset of thousands of raw merchant names, you may find that the majority of special characters and numbers can be removed without affecting any keyword in a merchant name."
},
{
"code": null,
"e": 2409,
"s": 2248,
"text": "Special characters and numbers removal can be efficiently done with the help of Python Re library. Some pre-requisite knowledge is regular expression in Python."
},
{
"code": null,
"e": 2420,
"s": 2409,
"text": "medium.com"
},
{
"code": null,
"e": 2431,
"s": 2420,
"text": "medium.com"
},
{
"code": null,
"e": 2761,
"s": 2431,
"text": "By successfully completing the above step, you now have a dataset of merchant names containing only the alphabet letters. However, you might still find that some merchant names are in different cases such as “AMAZON”, “amazon” or “Amazon”. To convert the cases, some useful string functions can be found in the following article:"
},
{
"code": null,
"e": 2784,
"s": 2761,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 3074,
"s": 2784,
"text": "For this layer, our main goal is to calculate a similarity score table and return the matched names with the top 3 largest similarity scores. This is a useful method to clean merchant names assuming that you already have a catalogue of names to match and also the raw inputs are non-messy."
},
{
"code": null,
"e": 3211,
"s": 3074,
"text": "FuzzyWuzzy is a Python library that uses Levenshtein Distance to calculate the differences between sequences in a simple-to-use package."
},
{
"code": null,
"e": 3222,
"s": 3211,
"text": "github.com"
},
{
"code": null,
"e": 3286,
"s": 3222,
"text": "Some practical examples in use of FuzzyWuzzy are as followings:"
},
{
"code": null,
"e": 3299,
"s": 3286,
"text": "Simple Ratio"
},
{
"code": null,
"e": 3357,
"s": 3299,
"text": ">>> fuzz.ratio(\"this is a test\", \"this is a test!\") 97"
},
{
"code": null,
"e": 3371,
"s": 3357,
"text": "Partial Ratio"
},
{
"code": null,
"e": 3438,
"s": 3371,
"text": ">>> fuzz.partial_ratio(\"this is a test\", \"this is a test!\") 100"
},
{
"code": null,
"e": 3455,
"s": 3438,
"text": "Token Sort Ratio"
},
{
"code": null,
"e": 3612,
"s": 3455,
"text": ">>> fuzz.ratio(\"fuzzy wuzzy was a bear\", \"wuzzy fuzzy was a bear\") 91>>> fuzz.token_sort_ratio(\"fuzzy wuzzy was a bear\", \"wuzzy fuzzy was a bear\") 100"
},
{
"code": null,
"e": 3628,
"s": 3612,
"text": "Token Set Ratio"
},
{
"code": null,
"e": 3783,
"s": 3628,
"text": ">>> fuzz.token_sort_ratio(\"fuzzy was a bear\", \"fuzzy fuzzy was a bear\") 84>>> fuzz.token_set_ratio(\"fuzzy was a bear\", \"fuzzy fuzzy was a bear\") 100"
},
{
"code": null,
"e": 3806,
"s": 3783,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 3829,
"s": 3806,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 3934,
"s": 3829,
"text": "Alternatively, SequenceMatcher is also a great tool often used to compute the similarity between inputs."
},
{
"code": null,
"e": 4273,
"s": 3934,
"text": "The basic idea is to find the longest contiguous matching subsequence that contains no “junk” elements. The same idea is then applied recursively to the pieces of the sequences to the left and to the right of the matching subsequence. This does not yield minimal edit sequences, but does tend to yield matches that “look right” to people."
},
{
"code": null,
"e": 4604,
"s": 4273,
"text": ">>> s = SequenceMatcher(lambda x: x == \" \", \"private Thread currentThread;\", \"private volatile Thread currentThread;\") >>> .ratio() returns a float in [0, 1], measuring the \"similarity\" of the sequences. As a rule of thumb, a .ratio() value over 0.6 means the sequences are close matches>>> print(round(s.ratio(), 3)) 0.866"
},
{
"code": null,
"e": 4627,
"s": 4604,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 4771,
"s": 4627,
"text": "For me, I choose the SequenceMatcher as the metrics of evaluating similarity. The process will be similar if you choose the FuzzyWuzzy library."
},
{
"code": null,
"e": 4962,
"s": 4771,
"text": "# define a function to calculate similarity between input sequencesdef similarity_map(word1, word2): seq = difflib.SequenceMatcher(None,word1,word2) d = seq.ratio() return d"
},
{
"code": null,
"e": 5068,
"s": 4962,
"text": "The above customized function takes two sequences as input and returns a ratio value of similarity score."
},
{
"code": null,
"e": 5358,
"s": 5068,
"text": "To further compute a table of similarity scores, I made a dataset that has raw merchant names as row indexes and a catalogue of cleaned merchant names as column names. By running the code cell below, it will generate a table of similarity scores for each pair of row index and column name."
},
{
"code": null,
"e": 5796,
"s": 5358,
"text": "# prepare a sample datasetdf = pd.DataFrame(data, index =['amazon co com', 'www netflix com', 'paypal payment', 'apple com bill', 'google play', 'facebook ads'],columns = ['amazon', 'netflix', 'paypal', 'apple', 'google', 'facebook']) # print the data dffrom tqdm import tqdmfor i in tqdm(range(6)): for j in range(6): df.loc[df.index[i], df.columns[j]] = similarity_map(str(df.index[i]), str(df.columns[j])) df.head()"
},
{
"code": null,
"e": 5910,
"s": 5796,
"text": "Once you completed running the above cell, you should have a table of similarity scores looks like the following:"
},
{
"code": null,
"e": 6049,
"s": 5910,
"text": "Based on the above table, we can further analyze insights by return merchant names that have top 3 highest similarity scores for each row."
},
{
"code": null,
"e": 6177,
"s": 6049,
"text": "Write a function top that takes above dataset as input and returns a dataset of top 3 names along with their similarity scores."
},
{
"code": null,
"e": 6725,
"s": 6177,
"text": "similarity = df.reset_index()similarity.head()def top(x): x.set_index('index', inplace=True) df = pd.DataFrame({'Max1Name':[],'Max2Name':[],'Max3Name':[],'Max1Value':[],'Max2Value':[],'Max3Value':[]}) df.index.name='index' df.loc[x.index.values[0],['Max1Name', 'Max2Name', 'Max3Name']] = x.sum().nlargest(3).index.tolist() df.loc[x.index.values[0],['Max1Value', 'Max2Value', 'Max3Value']] = x.sum().nlargest(3).values return dftest = similarity.groupby('index').apply(top).reset_index(level=1, drop=True).reset_index()test.head()"
},
{
"code": null,
"e": 6743,
"s": 6725,
"text": "stackoverflow.com"
},
{
"code": null,
"e": 6761,
"s": 6743,
"text": "stackoverflow.com"
},
{
"code": null,
"e": 6864,
"s": 6761,
"text": "By successfully implementing the above code cell, you should have a return dataset like the following:"
},
{
"code": null,
"e": 7029,
"s": 6864,
"text": "Although this is just a test on a sample dataset, we may still find this method useful if we have non-messy inputs along with a catalogue of cleaned merchant names."
},
{
"code": null,
"e": 7280,
"s": 7029,
"text": "However, this method may not perform well for more complex merchant inputs. For instance, a merchant name paypal * card payment on booking.com toronto will likely return a low similarity score (less than 0.5) with respect to either PayPal or Booking."
},
{
"code": null,
"e": 7389,
"s": 7280,
"text": "In this case, it requires a more advanced method to detect the location of the “real” merchant name we want."
},
{
"code": null,
"e": 7654,
"s": 7389,
"text": "By completing first two layers, we are able to solve some of the merchant names cleaning problems such as names of mis-spelling, different cases, missing characters/spaces and even some of the non-messy merchant inputs by simply returning a similarity score table."
},
{
"code": null,
"e": 7992,
"s": 7654,
"text": "However, we are actually still in the phase of working with a rule-based cleaning engine, which means so far we still haven’t learned from the data. Furthermore, even by use of a typical machine learning model, the training phase still requires a large amount of time to perform feature engineering in creating more informative features."
},
{
"code": null,
"e": 8289,
"s": 7992,
"text": "... potentially informative transaction-level features such as dollar amount and category, while also generating word-level natural language features such as word position within the label (e.g., 1st, 2nd), word length, proportion of vowels, consonants, and alphanumeric characters, among others."
},
{
"code": null,
"e": 8357,
"s": 8289,
"text": "CleanMachine: Financial transaction label translation for wallet.AI"
},
{
"code": null,
"e": 8625,
"s": 8357,
"text": "Therefore, I researched on how to use a deep learning model to create the cleaning engine. The advantage of using a deep learning model is that we are able to “skip” the feature engineering step and let the model itself detect any insightful patterns from the inputs."
},
{
"code": null,
"e": 8681,
"s": 8625,
"text": "A free short course on spaCy can be found as following:"
},
{
"code": null,
"e": 8697,
"s": 8681,
"text": "course.spacy.io"
},
{
"code": null,
"e": 8727,
"s": 8697,
"text": "According to the spaCy Guide:"
},
{
"code": null,
"e": 9029,
"s": 8727,
"text": "spaCy is a library for advanced Natural Language Processing in Python and Cython. It’s built on the very latest research, and was designed from day one to be used in real products. spaCy comes with pre-trained statistical models and word vectors, and currently supports tokenization for 60+ languages."
},
{
"code": null,
"e": 9257,
"s": 9029,
"text": "It features state-of-the-art speed, convolutional neural network models for tagging, parsing and named entity recognition and easy deep learning integration. It’s commercial open-source software, released under the MIT license."
},
{
"code": null,
"e": 9268,
"s": 9257,
"text": "github.com"
},
{
"code": null,
"e": 9493,
"s": 9268,
"text": "Since the merchant names cleaning problem can be classified under the topic of named entity recognition(NER), I feel confident that a spaCy model will have a good performance by feeding in a set of representative input data."
},
{
"code": null,
"e": 9649,
"s": 9493,
"text": "To train a spaCy model, we don’t just want it to memorize our examples — we want it to come up with a theory that can be generalized across other examples."
},
{
"code": null,
"e": 9919,
"s": 9649,
"text": "Therefore, the training data should always be representative of the data we want to process. For our project, we may want to select training data from different types of merchant names. Eventually, our training data will be in form of an entity list like the following:"
},
{
"code": null,
"e": 10408,
"s": 9919,
"text": "TRAIN_DATA = [('Amazon co ca', {'entities': [(0, 6, 'BRD')]}),('AMZNMKTPLACE AMAZON CO', {'entities': [(13, 19, 'BRD')]}),('APPLE COM BILL', {'entities': [(0, 5, 'BRD')]}),('BOOKING COM New York City', {'entities': [(0, 7, 'BRD')]}),('STARBUCKS Vancouver', {'entities': [(0, 9, 'BRD')]}),('Uber BV', {'entities': [(0, 4, 'BRD')]}),('Hotel on Booking com Toronto', {'entities': [(9, 16, 'BRD')]}),('UBER com', {'entities': [(0, 4, 'BRD')]}),('Netflix com', {'entities': [(0, 7, 'BRD')]})]]"
},
{
"code": null,
"e": 10733,
"s": 10408,
"text": "The training data I choose is just a sample. The model can take more complex inputs. However, it can be a little boring to annotate a long list of merchant names. I would like to recommend another data labeling tool UBIAI to complete this task, as it supports output in a spaCy format or even in an Amazon Comprehend format."
},
{
"code": null,
"e": 10745,
"s": 10733,
"text": "ubiai.tools"
},
{
"code": null,
"e": 10756,
"s": 10745,
"text": "medium.com"
},
{
"code": null,
"e": 10767,
"s": 10756,
"text": "medium.com"
},
{
"code": null,
"e": 11157,
"s": 10767,
"text": "It may require some experience on how to select a representative data input. As you practice more and observe the way how a spaCy model learns, it will become clearer that “representative” probably means “different locations”. It’s the reason why we need to provide an entity start & end index in the input data, because it can help the model to learn the patterns from different contexts."
},
{
"code": null,
"e": 11491,
"s": 11157,
"text": "If a model is often trained with the location of the first word being a merchant name (Amazon ca), then it tends to believe that a merchant name only locates at the beginning of an input. This will likely cause a bias and result in a wrong prediction for input such as “Music Spotify” because “Spotify” happens to be the second word."
},
{
"code": null,
"e": 11636,
"s": 11491,
"text": "However, it’s also important to include various merchant names in the input. Just be aware that we don’t want our model to merely memorize them."
},
{
"code": null,
"e": 11735,
"s": 11636,
"text": "Once you have finalized tuning your training data, the remaining process will almost be automated."
},
{
"code": null,
"e": 13313,
"s": 11735,
"text": "import spacyimport randomdef train_spacy(data,iterations): TRAIN_DATA = data nlp = spacy.blank('en') # create blank Language class # create the built-in pipeline components and add them to the pipeline # nlp.create_pipe works for built-ins that are registered with spaCy if 'ner' not in nlp.pipe_names: ner = nlp.create_pipe('ner') nlp.add_pipe(ner, last=True)# add labels for _, annotations in TRAIN_DATA: for ent in annotations.get('entities'): ner.add_label(ent[2])# get names of other pipes to disable them during training other_pipes = [pipe for pipe in nlp.pipe_names if pipe != 'ner'] with nlp.disable_pipes(*other_pipes): # only train NER optimizer = nlp.begin_training() for itn in range(iterations): print(\"Statring iteration \" + str(itn)) random.shuffle(TRAIN_DATA) losses = {} for text, annotations in TRAIN_DATA: nlp.update( [text], # batch of texts [annotations], # batch of annotations drop=0.2, # dropout - make it harder to memorise data sgd=optimizer, # callable to update weights losses=losses) print(losses) return nlpprdnlp = train_spacy(TRAIN_DATA, 20)# Save our trained Modelmodelfile = input(\"Enter your Model Name: \")prdnlp.to_disk(modelfile)#Test your texttest_text = input(\"Enter your testing text: \")doc = prdnlp(test_text)for ent in doc.ents: print(ent.text, ent.start_char, ent.end_char, ent.label_)"
},
{
"code": null,
"e": 13460,
"s": 13313,
"text": "Above code is from the following Medium article, as I found it very helpful and it inspired me to test spaCy on a merchant names cleaning problem."
},
{
"code": null,
"e": 13485,
"s": 13460,
"text": "manivannan-ai.medium.com"
},
{
"code": null,
"e": 13513,
"s": 13485,
"text": "www.machinelearningplus.com"
},
{
"code": null,
"e": 13622,
"s": 13513,
"text": "By successfully completing the training step, we can monitor the model progress by checking its loss values."
},
{
"code": null,
"e": 13906,
"s": 13622,
"text": "Statring iteration 0{'ner': 18.696674078702927}Statring iteration 1{'ner': 10.93641816265881}Statring iteration 2{'ner': 7.63046314753592}Statring iteration 3{'ner': 1.8599222962139454}Statring iteration 4{'ner': 0.29048295595632395}Statring iteration 5{'ner': 0.0009769084971516626}"
},
{
"code": null,
"e": 14294,
"s": 13906,
"text": "The model is then shown the unlabelled text and will make a prediction. Because we know the correct answer, we can give the model feedback on its prediction in the form of an error gradient of the loss function that calculates the difference between the training example and the expected output. The greater the difference, the more significant the gradient and the updates to our model."
},
{
"code": null,
"e": 14347,
"s": 14294,
"text": "To test your model, you can run the code cell below:"
},
{
"code": null,
"e": 14513,
"s": 14347,
"text": "#Test your texttest_text = input(\"Enter your testing text: \")doc = prdnlp(test_text)for ent in doc.ents: print(ent.text, ent.start_char, ent.end_char, ent.label_)"
},
{
"code": null,
"e": 14636,
"s": 14513,
"text": "For instance, we can use “paypal payment” as input and test the model if it can detect “paypal” as the correct brand name."
},
{
"code": null,
"e": 14719,
"s": 14636,
"text": "The model did a great job considering PayPal did not appear in the training input."
},
{
"code": null,
"e": 14815,
"s": 14719,
"text": "This also concludes my project of building a merchant names cleaning engine with a spaCy model."
},
{
"code": null,
"e": 14922,
"s": 14815,
"text": "First of all, thank you for your time reading this long article and I sincerely hope you found it helpful~"
},
{
"code": null,
"e": 14998,
"s": 14922,
"text": "I started from an introduction on why merchant names cleaning is important."
},
{
"code": null,
"e": 15053,
"s": 14998,
"text": "Then, I divided the cleaning engine into three layers."
},
{
"code": null,
"e": 15159,
"s": 15053,
"text": "Finally, for each layer, I explained the inputs & outputs as well as why each layer is necessary to have."
},
{
"code": null,
"e": 15371,
"s": 15159,
"text": "As an overview on this challenging problem, I didn’t fully expect to give a perfect solution to this. But I believe that it can be helpful to share my thoughts and any useful readings I found during my research."
},
{
"code": null,
"e": 15552,
"s": 15371,
"text": "Hence, I hope you enjoyed reading this article. Meanwhile, I added a Reference List section at the end of this article in case you are interested in learning more about this topic."
},
{
"code": null,
"e": 15563,
"s": 15552,
"text": "Thank you~"
},
{
"code": null,
"e": 15672,
"s": 15563,
"text": "A little update on the spaCy model training results with around 1000 lines of input data. (1000 annotations)"
},
{
"code": null,
"e": 15976,
"s": 15672,
"text": "I have set the model to 50 iterations each round of training and trained it for 10 rounds to see how the training loss varies. And it seems if we preprocess the data in a correct way, we should be able to reach a low & consistent training loss every time through 50 iterations, plotted as the following:"
},
{
"code": null,
"e": 16152,
"s": 15976,
"text": "🤔 However, is there still any way to make our spaCy model more interactive? Would it be more user-friendly if we can integrate spaCy model with Streamlit into a web interface?"
},
{
"code": null,
"e": 16214,
"s": 16152,
"text": "I was inspired by the spaCy documentation like the following:"
},
{
"code": null,
"e": 16366,
"s": 16214,
"text": "It seems that spaCy supports many fancy tools including Streamlit. Therefore, I decided to try to integrate spaCy and Streamlit together for a web app."
},
{
"code": null,
"e": 16452,
"s": 16366,
"text": "If you would like more knowledge on Streamlit, the following article is a good start."
},
{
"code": null,
"e": 16475,
"s": 16452,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 16686,
"s": 16475,
"text": "Since previously we have defined our spaCy training function as train_spacy, the remaining work will be within 10 lines of code. It’s also the reason why I think I should give an update under the same article 🤗"
},
{
"code": null,
"e": 16781,
"s": 16686,
"text": "Assuming we have also prepared our input annotation list in the format of previous TRAIN_DATA."
},
{
"code": null,
"e": 16851,
"s": 16781,
"text": "A web app interface’s code in Streamlit will look like the following:"
},
{
"code": null,
"e": 17791,
"s": 16851,
"text": "import pandas as pdimport numpy as np import randomimport spacyimport reimport warningsimport streamlit as st warnings.filterwarnings('ignore') # ignore warnings nlp = train_spacy(TRAIN_DATA, 50) # number of iterations set as 50# Save our trained Model # Once you obtained a trained model, you can switch to load a model for merchant name cleaningmodelfile = input(\"Enter your Model Name: \")nlp.to_disk(modelfile)# Load our saved Model # Load your model to clean a user input instead of training a new model once again when there is a new input# nlp = spacy.load(modelfile/) # path to the saved file foldertext = 'Amazon/ca' # default text input on web interfacest.title('Merchant Names Cleaning App') # web app title nameuser_input = st.text_input(\"Text\", text) # input text placedoc = nlp(user_input) for ent in doc.ents: st.write('Text:', ent.text) # display model output st.write('Label:', ent.label_) # display model output"
},
{
"code": null,
"e": 17848,
"s": 17791,
"text": "A successful web interface will look like the following:"
},
{
"code": null,
"e": 17878,
"s": 17848,
"text": "Hope you enjoyed the reading!"
},
{
"code": null,
"e": 17921,
"s": 17878,
"text": "[1] Cleaning up business names from Reddit"
},
{
"code": null,
"e": 18001,
"s": 17921,
"text": "[2] Improving the classification of your transaction data with Machine Learning"
},
{
"code": null,
"e": 18037,
"s": 18001,
"text": "[3] Making sense of messy bank data"
},
{
"code": null,
"e": 18127,
"s": 18037,
"text": "[4] Standardizing +113 million Merchant Names in Financial Services with Greenplum Hadoop"
},
{
"code": null,
"e": 18163,
"s": 18127,
"text": "[5] String Matching With FuzzyWuzzy"
},
{
"code": null,
"e": 18233,
"s": 18163,
"text": "[6] Natural Language Processing for Fuzzy String Matching with Python"
},
{
"code": null,
"e": 18293,
"s": 18233,
"text": "[7] An Ensemble Approach to Large-Scale Fuzzy Name Matching"
},
{
"code": null,
"e": 18324,
"s": 18293,
"text": "[8] Hybrid Fuzzy Name Matching"
},
{
"code": null,
"e": 18396,
"s": 18324,
"text": "[9] CleanMachine: Financial transaction label translation for wallet.AI"
},
{
"code": null,
"e": 18442,
"s": 18396,
"text": "[10] Deep Learning Magic: Small Business Type"
},
{
"code": null,
"e": 18485,
"s": 18442,
"text": "[11] Merchant Name Detection using Pytorch"
},
{
"code": null,
"e": 18526,
"s": 18485,
"text": "[12] Categorize Banking Transaction Data"
},
{
"code": null,
"e": 18567,
"s": 18526,
"text": "[13] Training spaCy’s Statistical Models"
},
{
"code": null,
"e": 18641,
"s": 18567,
"text": "[14] How to Train spaCy to Autodetect New Entities (NER) [Complete Guide]"
},
{
"code": null,
"e": 18703,
"s": 18641,
"text": "[15] Build a custom entity recognizer using Amazon Comprehend"
},
{
"code": null,
"e": 18787,
"s": 18703,
"text": "[16] Developing NER models with Amazon SageMaker Ground Truth and Amazon Comprehend"
},
{
"code": null,
"e": 18812,
"s": 18787,
"text": "[17] UBIAI Documentation"
},
{
"code": null,
"e": 18886,
"s": 18812,
"text": "[18] How to Automate Job Searches Using Named Entity Recognition — Part 1"
},
{
"code": null,
"e": 18948,
"s": 18886,
"text": "[19] Building a Job Entity Recognizer Using Amazon Comprehend"
}
] |
Batch Script - ATTRIB | Displays or sets the attributes of the files in the current directory
attrib
The following example shows the different variants of the attrib command.
@echo off
Rem Displays the attribites of the file in the current directory
Attrib
Rem Displays the attributes of the file lists.txt
attrib C:\tp\lists.txt
Rem Adds the "Read-only" attribute to the file.
attrib +r C:\tp\lists.txt
Attrib C:\tp\lists.txt
Rem Removes the "Archived" attribute from the file
attrib -a C:\tp\lists.txt
Attrib C:\tp\lists.txt
For example,
A C:\tp\assoclst.txt
A C:\tp\List.cmd
A C:\tp\lists.txt
A C:\tp\listsA.txt
A C:\tp\lists.txt
A R C:\tp\lists.txt
R C:\tp\lists.txt
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2239,
"s": 2169,
"text": "Displays or sets the attributes of the files in the current directory"
},
{
"code": null,
"e": 2247,
"s": 2239,
"text": "attrib\n"
},
{
"code": null,
"e": 2321,
"s": 2247,
"text": "The following example shows the different variants of the attrib command."
},
{
"code": null,
"e": 2676,
"s": 2321,
"text": "@echo off\nRem Displays the attribites of the file in the current directory\nAttrib\n\nRem Displays the attributes of the file lists.txt\nattrib C:\\tp\\lists.txt\n\nRem Adds the \"Read-only\" attribute to the file.\nattrib +r C:\\tp\\lists.txt\nAttrib C:\\tp\\lists.txt\n\nRem Removes the \"Archived\" attribute from the file\nattrib -a C:\\tp\\lists.txt\nAttrib C:\\tp\\lists.txt"
},
{
"code": null,
"e": 2689,
"s": 2676,
"text": "For example,"
},
{
"code": null,
"e": 2889,
"s": 2689,
"text": "A C:\\tp\\assoclst.txt\nA C:\\tp\\List.cmd\nA C:\\tp\\lists.txt\nA C:\\tp\\listsA.txt\nA C:\\tp\\lists.txt\nA R C:\\tp\\lists.txt\n R C:\\tp\\lists.txt\n"
},
{
"code": null,
"e": 2896,
"s": 2889,
"text": " Print"
},
{
"code": null,
"e": 2907,
"s": 2896,
"text": " Add Notes"
}
] |
How to add picasso library in android studio? | Before getting into picasso library example, we should know about picasso. Picasso is image processing library and developed by Square Inc. In older days we used to write lengthy of codes to grab image from server or do process., to optimize the process picasso introduced.
This example demonstrate about how to integrate picasso library in android studio.
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 in build.gradle.
apply plugin: 'com.android.application'
android {
compileSdkVersion 28
defaultConfig {
applicationId "com.example.andy.myapplication"
minSdkVersion 15
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
testImplementation 'junit:junit:4.12'
implementation 'com.squareup.picasso3:picasso:2.71828'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
Step 3 − Add the following code to res/layout/activity_main.xml.
<?xml version = "1.0" encoding = "utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android = "http://schemas.android.com/apk/res/android" xmlns:tools = "http://schemas.android.com/tools" android:layout_width = "match_parent"
android:layout_height = "match_parent">
<LinearLayout
android:layout_width = "match_parent"
android:layout_height = "match_parent"
android:gravity = "center"
android:orientation = "vertical">
<ImageView
android:id = "@+id/imageView"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content" />
</LinearLayout>
</android.support.constraint.ConstraintLayout>
Step 4 − Add the following code to src/MainActivity.java
package com.example.andy.myapplication;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView;
import android.widget.Toast;
import com.squareup.picasso.Callback;
import com.squareup.picasso.Picasso;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView imageView=findViewById(R.id.imageView);
Picasso.with(this)
.load("https://www.tutorialspoint.com/images/tp-logo-diamond.png")
.placeholder(R.mipmap.ic_launcher)
.resize(400, 400)
.centerCrop()
.rotate(0)
.into(imageView, new Callback() {
@Override
public void onSuccess() {
Toast.makeText(getApplicationContext(), "Fetched image from internet", Toast.LENGTH_SHORT).show();
}
@Override
public void onError() {
Toast.makeText(getApplicationContext(), "An error occurred", Toast.LENGTH_SHORT).show();
}
});
}
}
In the above code we have so many methods are associate with picasso as shown below.
with() − we have to pass context for the piasso library
with() − we have to pass context for the piasso library
load() − what we want to load in picass we have to give that path either it is local directory or internet source
load() − what we want to load in picass we have to give that path either it is local directory or internet source
resize() − if you want to resize your image, you can do that with certain width and height.
resize() − if you want to resize your image, you can do that with certain width and height.
centercrop() − you can do center crop to your image view.
centercrop() − you can do center crop to your image view.
rotate() − you can rotate your image as 0 to 360 degreees
rotate() − you can rotate your image as 0 to 360 degreees
into() − In which view you want to show, we have to give imageview paths and there are two call backs are available as shown below
into() − In which view you want to show, we have to give imageview paths and there are two call backs are available as shown below
onSuccess() − if image is successfully downloaded, you can do any action.
onSuccess() − if image is successfully downloaded, you can do any action.
onError() − if image is not successfully downloaded, you can do any action.
onError() − if image is not successfully downloaded, you can do any action.
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen.
Now you can observe the above image, The above image is cropped according to size which we have given in resize(). now we have removed the centerCrop() and resize method, it will show image with default size as shown below.
Click here to download the project code | [
{
"code": null,
"e": 1336,
"s": 1062,
"text": "Before getting into picasso library example, we should know about picasso. Picasso is image processing library and developed by Square Inc. In older days we used to write lengthy of codes to grab image from server or do process., to optimize the process picasso introduced."
},
{
"code": null,
"e": 1419,
"s": 1336,
"text": "This example demonstrate about how to integrate picasso library in android studio."
},
{
"code": null,
"e": 1548,
"s": 1419,
"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": 1597,
"s": 1548,
"text": "Step 2 − Add the following code in build.gradle."
},
{
"code": null,
"e": 2557,
"s": 1597,
"text": "apply plugin: 'com.android.application'\nandroid {\n compileSdkVersion 28\n defaultConfig {\n applicationId \"com.example.andy.myapplication\"\n minSdkVersion 15\n targetSdkVersion 28\n versionCode 1\n versionName \"1.0\"\n testInstrumentationRunner \"android.support.test.runner.AndroidJUnitRunner\"\n }\n buildTypes {\n release {\n minifyEnabled false\n proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' \n }\n }\n}\ndependencies {\n implementation fileTree(dir: 'libs', include: ['*.jar'])\n implementation 'com.android.support:appcompat-v7:28.0.0'\n implementation 'com.android.support.constraint:constraint-layout:1.1.3'\n testImplementation 'junit:junit:4.12'\n implementation 'com.squareup.picasso3:picasso:2.71828'\n androidTestImplementation 'com.android.support.test:runner:1.0.2'\n androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'\n}"
},
{
"code": null,
"e": 2622,
"s": 2557,
"text": "Step 3 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 3273,
"s": 2622,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<android.support.constraint.ConstraintLayout\n xmlns:android = \"http://schemas.android.com/apk/res/android\" xmlns:tools = \"http://schemas.android.com/tools\" android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\">\n<LinearLayout\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n android:gravity = \"center\"\n android:orientation = \"vertical\">\n <ImageView\n android:id = \"@+id/imageView\"\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\" />\n</LinearLayout>\n</android.support.constraint.ConstraintLayout>"
},
{
"code": null,
"e": 3330,
"s": 3273,
"text": "Step 4 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 4446,
"s": 3330,
"text": "package com.example.andy.myapplication;\nimport android.os.Bundle;\nimport android.support.v7.app.AppCompatActivity;\nimport android.widget.ImageView;\nimport android.widget.Toast;\nimport com.squareup.picasso.Callback;\nimport com.squareup.picasso.Picasso;\npublic class MainActivity extends AppCompatActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n ImageView imageView=findViewById(R.id.imageView);\n Picasso.with(this)\n .load(\"https://www.tutorialspoint.com/images/tp-logo-diamond.png\")\n .placeholder(R.mipmap.ic_launcher)\n .resize(400, 400)\n .centerCrop()\n .rotate(0)\n .into(imageView, new Callback() {\n @Override\n public void onSuccess() {\n Toast.makeText(getApplicationContext(), \"Fetched image from internet\", Toast.LENGTH_SHORT).show();\n }\n @Override\n public void onError() {\n Toast.makeText(getApplicationContext(), \"An error occurred\", Toast.LENGTH_SHORT).show();\n }\n });\n }\n}"
},
{
"code": null,
"e": 4531,
"s": 4446,
"text": "In the above code we have so many methods are associate with picasso as shown below."
},
{
"code": null,
"e": 4587,
"s": 4531,
"text": "with() − we have to pass context for the piasso library"
},
{
"code": null,
"e": 4643,
"s": 4587,
"text": "with() − we have to pass context for the piasso library"
},
{
"code": null,
"e": 4757,
"s": 4643,
"text": "load() − what we want to load in picass we have to give that path either it is local directory or internet source"
},
{
"code": null,
"e": 4871,
"s": 4757,
"text": "load() − what we want to load in picass we have to give that path either it is local directory or internet source"
},
{
"code": null,
"e": 4963,
"s": 4871,
"text": "resize() − if you want to resize your image, you can do that with certain width and height."
},
{
"code": null,
"e": 5055,
"s": 4963,
"text": "resize() − if you want to resize your image, you can do that with certain width and height."
},
{
"code": null,
"e": 5113,
"s": 5055,
"text": "centercrop() − you can do center crop to your image view."
},
{
"code": null,
"e": 5171,
"s": 5113,
"text": "centercrop() − you can do center crop to your image view."
},
{
"code": null,
"e": 5229,
"s": 5171,
"text": "rotate() − you can rotate your image as 0 to 360 degreees"
},
{
"code": null,
"e": 5287,
"s": 5229,
"text": "rotate() − you can rotate your image as 0 to 360 degreees"
},
{
"code": null,
"e": 5418,
"s": 5287,
"text": "into() − In which view you want to show, we have to give imageview paths and there are two call backs are available as shown below"
},
{
"code": null,
"e": 5549,
"s": 5418,
"text": "into() − In which view you want to show, we have to give imageview paths and there are two call backs are available as shown below"
},
{
"code": null,
"e": 5623,
"s": 5549,
"text": "onSuccess() − if image is successfully downloaded, you can do any action."
},
{
"code": null,
"e": 5697,
"s": 5623,
"text": "onSuccess() − if image is successfully downloaded, you can do any action."
},
{
"code": null,
"e": 5773,
"s": 5697,
"text": "onError() − if image is not successfully downloaded, you can do any action."
},
{
"code": null,
"e": 5849,
"s": 5773,
"text": "onError() − if image is not successfully downloaded, you can do any action."
},
{
"code": null,
"e": 6196,
"s": 5849,
"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": 6420,
"s": 6196,
"text": "Now you can observe the above image, The above image is cropped according to size which we have given in resize(). now we have removed the centerCrop() and resize method, it will show image with default size as shown below."
},
{
"code": null,
"e": 6460,
"s": 6420,
"text": "Click here to download the project code"
}
] |
Encoding Data with Transformers. How to use transformer-based technology... | by Michelangiolo Mazzeschi | Towards Data Science | Data encoding has been one of the most recent technological advancements in the domain of Artificial Intelligence. By using encoder models, we can convert categorical data into numerical data, and this allows us to make comparisons, see how the data is related to each other, make recommendations, improve searches...
In this article, I am going to explain how to convert a set of articles (textual data) into vectors (numerical data), by using one of the models which are installed on the RelevanceAI library.
If you wish to use the API, there is a quick start guide that you can follow to perform your first semantic search on a dataset using vector-based technology.
Encoding means that we are converting categorical data into numerical data. There are very rudimental kinds of encoding, for example, one_hot encoding, or index-based encoding. However, when we are working with textual data, the most advanced form of encoding can be done using embeddings.
Embeddings are able to scan a corpus of words, and place each one of them into a multidimensional space, essentially converting each word into a vector. Once the model has been trained, each word in the corpus has been properly placed into a mathematical space in proximity of words with similar meanings.
You can have fun exploring an embedding using Google’s embedding projector:
This technology is having a huge impact on the way searches are working right now, finding most of the applications in search engines, recommendation systems, and computer vision.
The most popular textual encoder, up to a few years ago, was word2vec. Being available in several models, you could convert each word into the corresponding vectors in space. However, this is known as static embedding, meaning that the vectors will never change: the model is encoding word by word ignoring the context of a sentence: we can do better than that!
The answer to this problem has now taken the form of transformers models. These encoders use dynamic embeddings: each word can have a different vector according to the word around it.
As you can imagine, this is much more accurate than using static embeddings: RelevanceAI is committed to using this same technology.
The only thing you need to do to encode textual data is to download the vectorhub library, which hosts the RelevanceAI encoders:
#encode on localfrom vectorhub.encoders.text.sentence_transformers import SentenceTransformer2Vecmodel = SentenceTransformer2Vec("bert-base-uncased")df_json = model.encode_documents(documents=df_json, fields=['raw'])df_json
Because it is always useful to try things with a bigger dataset, you can make use of our datasets through the relevanceai API. Let us try to encode a dataset, we will be using it in later articles to upload it onto your relevanceai workspace and experiment with several methods:
The first step is to install relevanceai on your notebook. The installation is quite straightforward, as it uses pip.
!pip install vectorhub[encoders-text-sentence-transformers]!pip install -U relevanceaiimport relevanceaiprint(relevanceai.__version__)#restart notebook if you are updating the API rather than just installing it for the first timeOutput:0.12.17
RelevanceAI allows you to download several possible sample datasets. In this case, I will use the flipkart dataset with around 20.000 samples. To download it, just use the following code:
from relevanceai import datasetsjson_files = datasets.get_flipkart_dataset()json_files
Once the uploading procedure has ended, let us now check the schema of the dataset: we can see all its fields. So far, none of the fields has been encoded, yet.
{'_id': 0, 'product_name': "Alisha Solid Women's Cycling Shorts", 'description': "Key Features of Alisha Solid...", 'retail_price': 999.0}, {'_id': 1, 'product_name': 'FabHomeDecor Fabric Double Sofa Bed', 'description': "FabHomeDecor Fabric Double ...", 'retail_price': 32157.0}, {'_id': 2, 'product_name': 'AW Bellies', 'description': 'Key Features of AW Bellies Sandals...', 'retail_price': 999.0}, {'_id': 3, 'product_name': "Alisha Solid Women's Cycling Shorts", 'description': "Key Features of Alisha Solid Women's Cycling...", 'retail_price': 699.0},
To start performing encoding of the textual data locally, you can easily have access to some of our transformers models through the vectorhub library. Performing the encoding is very simple, you just need to pass in the json_files data specifying the fields you wish to encode:
#encode on localfrom vectorhub.encoders.text.sentence_transformers import SentenceTransformer2Vecmodel = SentenceTransformer2Vec("bert-base-uncased")df_json = model.encode_documents(documents=json_files[0:1000], fields=['product_name'])df_json
I will only encode the first 1000 samples, otherwise, the encoder may run for a while. After about one minute, this will be the output: as you can see, a new field containing vectors has been added to the dictionary.
Output:[{'_id': 0, 'product_name': "Alisha Solid Women's Cycling Shorts", 'description': "Key Features of Alisha Solid Women's...", 'retail_price': 999.0, 'product_name_sentence_transformers_vector_': [0.29085323214530945, -0.12144982814788818, -0.33044129610061646, 0.07810567319393158, 0.3813101351261139, -0.13027772307395935,
Because you have not yet uploaded your dataset into relevanceAI (we will be showing you how to do this in the next article), you will have to visualize your data manually. Here is a sample code you can use to transform the output dictionary into a pandas DataFrame.
import numpy as npimport pandas as pddf = pd.DataFrame(df_json)df_vectors = pd.DataFrame(np.column_stack(list(zip(*df[['product_name_sentence_transformers_vector_']].values))))df_vectors.index = df['product_name']df_vectors
Because the data consists of 768 columns, to visualize it you need to compress it. You can use a PCA to easily visualize your data. Know that there are plenty more advanced techniques to obtain the same result, but this will be sufficient to have a quick look at the data.
from sklearn.decomposition import PCAimport matplotlib.pyplot as pltpca = PCA(n_components=2, svd_solver='auto')pca_result = pca.fit_transform(df_vectors.values)#display(df)fig = plt.figure(figsize=(14, 8))x = list(pca_result[:,0])y = list(pca_result[:,1])# x and y given as array_like objectsimport plotly.express as pxfig = px.scatter(df, x=x, y=y, hover_name=df_vectors.index)fig.update_traces(textfont_size=10)fig.show()
Wonderful! All these 1000 samples have been placed in space, and now we can see them.
By zooming on the data, we can look at how each individual product relates to another: | [
{
"code": null,
"e": 489,
"s": 171,
"text": "Data encoding has been one of the most recent technological advancements in the domain of Artificial Intelligence. By using encoder models, we can convert categorical data into numerical data, and this allows us to make comparisons, see how the data is related to each other, make recommendations, improve searches..."
},
{
"code": null,
"e": 682,
"s": 489,
"text": "In this article, I am going to explain how to convert a set of articles (textual data) into vectors (numerical data), by using one of the models which are installed on the RelevanceAI library."
},
{
"code": null,
"e": 841,
"s": 682,
"text": "If you wish to use the API, there is a quick start guide that you can follow to perform your first semantic search on a dataset using vector-based technology."
},
{
"code": null,
"e": 1131,
"s": 841,
"text": "Encoding means that we are converting categorical data into numerical data. There are very rudimental kinds of encoding, for example, one_hot encoding, or index-based encoding. However, when we are working with textual data, the most advanced form of encoding can be done using embeddings."
},
{
"code": null,
"e": 1437,
"s": 1131,
"text": "Embeddings are able to scan a corpus of words, and place each one of them into a multidimensional space, essentially converting each word into a vector. Once the model has been trained, each word in the corpus has been properly placed into a mathematical space in proximity of words with similar meanings."
},
{
"code": null,
"e": 1513,
"s": 1437,
"text": "You can have fun exploring an embedding using Google’s embedding projector:"
},
{
"code": null,
"e": 1693,
"s": 1513,
"text": "This technology is having a huge impact on the way searches are working right now, finding most of the applications in search engines, recommendation systems, and computer vision."
},
{
"code": null,
"e": 2055,
"s": 1693,
"text": "The most popular textual encoder, up to a few years ago, was word2vec. Being available in several models, you could convert each word into the corresponding vectors in space. However, this is known as static embedding, meaning that the vectors will never change: the model is encoding word by word ignoring the context of a sentence: we can do better than that!"
},
{
"code": null,
"e": 2239,
"s": 2055,
"text": "The answer to this problem has now taken the form of transformers models. These encoders use dynamic embeddings: each word can have a different vector according to the word around it."
},
{
"code": null,
"e": 2372,
"s": 2239,
"text": "As you can imagine, this is much more accurate than using static embeddings: RelevanceAI is committed to using this same technology."
},
{
"code": null,
"e": 2501,
"s": 2372,
"text": "The only thing you need to do to encode textual data is to download the vectorhub library, which hosts the RelevanceAI encoders:"
},
{
"code": null,
"e": 2725,
"s": 2501,
"text": "#encode on localfrom vectorhub.encoders.text.sentence_transformers import SentenceTransformer2Vecmodel = SentenceTransformer2Vec(\"bert-base-uncased\")df_json = model.encode_documents(documents=df_json, fields=['raw'])df_json"
},
{
"code": null,
"e": 3004,
"s": 2725,
"text": "Because it is always useful to try things with a bigger dataset, you can make use of our datasets through the relevanceai API. Let us try to encode a dataset, we will be using it in later articles to upload it onto your relevanceai workspace and experiment with several methods:"
},
{
"code": null,
"e": 3122,
"s": 3004,
"text": "The first step is to install relevanceai on your notebook. The installation is quite straightforward, as it uses pip."
},
{
"code": null,
"e": 3366,
"s": 3122,
"text": "!pip install vectorhub[encoders-text-sentence-transformers]!pip install -U relevanceaiimport relevanceaiprint(relevanceai.__version__)#restart notebook if you are updating the API rather than just installing it for the first timeOutput:0.12.17"
},
{
"code": null,
"e": 3554,
"s": 3366,
"text": "RelevanceAI allows you to download several possible sample datasets. In this case, I will use the flipkart dataset with around 20.000 samples. To download it, just use the following code:"
},
{
"code": null,
"e": 3641,
"s": 3554,
"text": "from relevanceai import datasetsjson_files = datasets.get_flipkart_dataset()json_files"
},
{
"code": null,
"e": 3802,
"s": 3641,
"text": "Once the uploading procedure has ended, let us now check the schema of the dataset: we can see all its fields. So far, none of the fields has been encoded, yet."
},
{
"code": null,
"e": 4372,
"s": 3802,
"text": "{'_id': 0, 'product_name': \"Alisha Solid Women's Cycling Shorts\", 'description': \"Key Features of Alisha Solid...\", 'retail_price': 999.0}, {'_id': 1, 'product_name': 'FabHomeDecor Fabric Double Sofa Bed', 'description': \"FabHomeDecor Fabric Double ...\", 'retail_price': 32157.0}, {'_id': 2, 'product_name': 'AW Bellies', 'description': 'Key Features of AW Bellies Sandals...', 'retail_price': 999.0}, {'_id': 3, 'product_name': \"Alisha Solid Women's Cycling Shorts\", 'description': \"Key Features of Alisha Solid Women's Cycling...\", 'retail_price': 699.0},"
},
{
"code": null,
"e": 4650,
"s": 4372,
"text": "To start performing encoding of the textual data locally, you can easily have access to some of our transformers models through the vectorhub library. Performing the encoding is very simple, you just need to pass in the json_files data specifying the fields you wish to encode:"
},
{
"code": null,
"e": 4894,
"s": 4650,
"text": "#encode on localfrom vectorhub.encoders.text.sentence_transformers import SentenceTransformer2Vecmodel = SentenceTransformer2Vec(\"bert-base-uncased\")df_json = model.encode_documents(documents=json_files[0:1000], fields=['product_name'])df_json"
},
{
"code": null,
"e": 5111,
"s": 4894,
"text": "I will only encode the first 1000 samples, otherwise, the encoder may run for a while. After about one minute, this will be the output: as you can see, a new field containing vectors has been added to the dictionary."
},
{
"code": null,
"e": 5455,
"s": 5111,
"text": "Output:[{'_id': 0, 'product_name': \"Alisha Solid Women's Cycling Shorts\", 'description': \"Key Features of Alisha Solid Women's...\", 'retail_price': 999.0, 'product_name_sentence_transformers_vector_': [0.29085323214530945, -0.12144982814788818, -0.33044129610061646, 0.07810567319393158, 0.3813101351261139, -0.13027772307395935,"
},
{
"code": null,
"e": 5721,
"s": 5455,
"text": "Because you have not yet uploaded your dataset into relevanceAI (we will be showing you how to do this in the next article), you will have to visualize your data manually. Here is a sample code you can use to transform the output dictionary into a pandas DataFrame."
},
{
"code": null,
"e": 5945,
"s": 5721,
"text": "import numpy as npimport pandas as pddf = pd.DataFrame(df_json)df_vectors = pd.DataFrame(np.column_stack(list(zip(*df[['product_name_sentence_transformers_vector_']].values))))df_vectors.index = df['product_name']df_vectors"
},
{
"code": null,
"e": 6218,
"s": 5945,
"text": "Because the data consists of 768 columns, to visualize it you need to compress it. You can use a PCA to easily visualize your data. Know that there are plenty more advanced techniques to obtain the same result, but this will be sufficient to have a quick look at the data."
},
{
"code": null,
"e": 6643,
"s": 6218,
"text": "from sklearn.decomposition import PCAimport matplotlib.pyplot as pltpca = PCA(n_components=2, svd_solver='auto')pca_result = pca.fit_transform(df_vectors.values)#display(df)fig = plt.figure(figsize=(14, 8))x = list(pca_result[:,0])y = list(pca_result[:,1])# x and y given as array_like objectsimport plotly.express as pxfig = px.scatter(df, x=x, y=y, hover_name=df_vectors.index)fig.update_traces(textfont_size=10)fig.show()"
},
{
"code": null,
"e": 6729,
"s": 6643,
"text": "Wonderful! All these 1000 samples have been placed in space, and now we can see them."
}
] |
POS Tagging Using RNN. Learn how to use RNNs to tag words in... | by Tanya Dayanand | Towards Data Science | The classical way of doing POS tagging is using some variant of Hidden Markov Model. Here we'll see how we could do that using Recurrent neural networks. The original RNN architecture has some variants too. It has a novel RNN architecture — the Bidirectional RNN which is capable of reading sequences in the ‘reverse order’ as well and has proven to boost performance significantly.
Then two important cutting-edge variants of the RNN which have made it possible to train large networks on real datasets. Although RNNs are capable of solving a variety of sequence problems, their architecture itself is their biggest enemy due to the problems of exploding and vanishing gradients that occur during the training of RNNs. This problem is solved by two popular gated RNN architectures — the Long, Short Term Memory (LSTM) and the Gated Recurrent Unit (GRU). We’ll look into all these models here with respect to POS tagging.
The process of classifying words into their parts of speech and labeling them accordingly is known as part-of-speech tagging, or simply POS-tagging. The NLTK library has a number of corpora that contain words and their POS tag. I will be using the POS tagged corpora i.e treebank, conll2000, and brown from NLTK to demonstrate the key concepts. To get into the codes directly, an accompanying notebook is published on Kaggle.
www.kaggle.com
The following table provides information about some of the major tags:
Preprocess dataWord EmbeddingsVanilla RNNLSTMGRUBidirectional LSTMModel Evaluation
Preprocess data
Word Embeddings
Vanilla RNN
LSTM
GRU
Bidirectional LSTM
Model Evaluation
Let’s begin with importing the necessary libraries and loading the dataset. This is a requisite step in every data analysis process(The complete code can be viewed here). We’ll be loading the data first using three well-known text corpora and taking the union of those.
# Importing and Loading the data into data frame# load POS tagged corpora from NLTKtreebank_corpus = treebank.tagged_sents(tagset='universal')brown_corpus = brown.tagged_sents(tagset='universal')conll_corpus = conll2000.tagged_sents(tagset='universal')# Merging the dataframes to create a master dftagged_sentences = treebank_corpus + brown_corpus + conll_corpus
As a part of preprocessing, we’ll be performing various steps such as dividing data into words and tags, Vectorise X and Y, and Pad sequences.
Let's look at the data first. For each of the words below, there is a tag associated with it.
# let's look at the datatagged_sentences[7]
Since this is a many-to-many problem, each data point will be a different sentence of the corpora. Each data point will have multiple words in the input sequence. This is what we will refer to as X. Each word will have its corresponding tag in the output sequence. This what we will refer to as Y. Sample dataset:
X = [] # store input sequenceY = [] # store output sequencefor sentence in tagged_sentences: X_sentence = [] Y_sentence = [] for entity in sentence: X_sentence.append(entity[0]) # entity[0] contains the word Y_sentence.append(entity[1]) # entity[1] contains corresponding tag X.append(X_sentence) Y.append(Y_sentence)num_words = len(set([word.lower() for sentence in X for word in sentence]))num_tags = len(set([word.lower() for sentence in Y for word in sentence]))print("Total number of tagged sentences: {}".format(len(X)))print("Vocabulary size: {}".format(num_words))print("Total number of tags: {}".format(num_tags))
# let’s look at first data point# this is one data point that will be fed to the RNNprint(‘sample X: ‘, X[0], ‘\n’)print(‘sample Y: ‘, Y[0], ‘\n’)
# In this many-to-many problem, the length of each input and output sequence must be the same.# Since each word is tagged, it’s important to make sure that the length of input sequence equals the output sequenceprint(“Length of first input sequence : {}”.format(len(X[0])))print(“Length of first output sequence : {}”.format(len(Y[0])))
The next thing we need to figure out is how are we going to feed these inputs to an RNN. If we have to give the words as input to any neural networks then we essentially have to convert them into numbers. We need to create a word embedding or one-hot vectors i.e. a vector of numbers form of each word. To start with this we'll first encode the input and output which will give a blind unique id to each word in the entire corpus for input data. On the other hand, we have the Y matrix(tags/output data). We have twelve POS tags here, treating each of them as a class and each pos tag is converted into one-hot encoding of length twelve. We’ll use the Tokenizer() function from Keras library to encode text sequence to integer sequence.
# encode Xword_tokenizer = Tokenizer() # instantiate tokeniserword_tokenizer.fit_on_texts(X) # fit tokeniser on data# use the tokeniser to encode input sequenceX_encoded = word_tokenizer.texts_to_sequences(X) # encode Ytag_tokenizer = Tokenizer()tag_tokenizer.fit_on_texts(Y)Y_encoded = tag_tokenizer.texts_to_sequences(Y)# look at first encoded data pointprint("** Raw data point **", "\n", "-"*100, "\n")print('X: ', X[0], '\n')print('Y: ', Y[0], '\n')print()print("** Encoded data point **", "\n", "-"*100, "\n")print('X: ', X_encoded[0], '\n')print('Y: ', Y_encoded[0], '\n')
Make sure that each sequence of input and output is of the same length.
The sentences in the corpus are not of the same length. Before we feed the input in the RNN model we need to fix the length of the sentences. We cannot dynamically allocate memory required to process each sentence in the corpus as they are of different lengths. Therefore the next step after encoding the data is to define the sequence lengths. We need to either pad short sentences or truncate long sentences to a fixed length. This fixed length, however, is a hyperparameter.
# Pad each sequence to MAX_SEQ_LENGTH using KERAS’ pad_sequences() function. # Sentences longer than MAX_SEQ_LENGTH are truncated.# Sentences shorter than MAX_SEQ_LENGTH are padded with zeroes.# Truncation and padding can either be ‘pre’ or ‘post’. # For padding we are using ‘pre’ padding type, that is, add zeroes on the left side.# For truncation, we are using ‘post’, that is, truncate a sentence from right side.# sequences greater than 100 in length will be truncatedMAX_SEQ_LENGTH = 100X_padded = pad_sequences(X_encoded, maxlen=MAX_SEQ_LENGTH, padding=”pre”, truncating=”post”)Y_padded = pad_sequences(Y_encoded, maxlen=MAX_SEQ_LENGTH, padding=”pre”, truncating=”post”)# print the first sequenceprint(X_padded[0], "\n"*3)print(Y_padded[0])
You know that a better way (than one-hot vectors) to represent text is word embeddings. Currently, each word and each tag is encoded as an integer. We’ll use a more sophisticated technique to represent the input words (X) using what’s known as word embeddings.
However, to represent each tag in Y, we’ll simply use one-hot encoding scheme since there are only 12 tags in the dataset and the LSTM will have no problems in learning its own representation of these tags.
To use word embeddings, you can go for either of the following models:
word2vec modelGloVe model
word2vec model
GloVe model
We’re using the word2vec model for no particular reason. Both of these are very efficient in representing words. You can try both and see which one works better.
The dimension of a word embedding is: (VOCABULARY_SIZE, EMBEDDING_DIMENSION)
# word2vecpath = ‘../input/wordembeddings/GoogleNews-vectors-negative300.bin’# load word2vec using the following function present in the gensim libraryword2vec = KeyedVectors.load_word2vec_format(path, binary=True)# assign word vectors from word2vec model# each word in word2vec model is represented using a 300 dimensional vectorEMBEDDING_SIZE = 300 VOCABULARY_SIZE = len(word_tokenizer.word_index) + 1# create an empty embedding matixembedding_weights = np.zeros((VOCABULARY_SIZE, EMBEDDING_SIZE))# create a word to index dictionary mappingword2id = word_tokenizer.word_index# copy vectors from word2vec model to the words present in corpusfor word, index in word2id.items(): try: embedding_weights[index, :] = word2vec[word] except KeyError: pass
# use Keras’ to_categorical function to one-hot encode YY = to_categorical(Y)
All the data preprocessing is now complete. Let’s now jump to the modeling part by splitting the data to train, validation, and test sets.
Before using RNN, we must make sure the dimensions of the data are what an RNN expects. In general, an RNN expects the following shape
Shape of X: (#samples, #timesteps, #features)
Shape of Y: (#samples, #timesteps, #features)
Now, there can be various variations in the shape that you use to feed an RNN depending on the type of architecture. Since the problem we’re working on has a many-to-many architecture, the input and the output both include number of timesteps which is nothing but the sequence length. But notice that the tensor X doesn’t have the third dimension, that is, number of features. That’s because we’re going to use word embeddings before feeding in the data to an RNN, and hence there is no need to explicitly mention the third dimension. That’s because when you use the Embedding() layer in Keras, the training data will automatically be converted to (#samples, #timesteps, #features) where #features will be the embedding dimension (and note that the Embedding layer is always the very first layer of an RNN). While using the embedding layer we only need to reshape the data to (#samples, #timesteps) which is what we have done. However, note that you’ll need to shape it to (#samples, #timesteps, #features) in case you don’t use the Embedding() layer in Keras.
Next, let’s build the RNN model. We’re going to use word embeddings to represent the words. Now, while training the model, you can also train the word embeddings along with the network weights. These are often called the embedding weights. While training, the embedding weights will be treated as normal weights of the network which are updated in each iteration.
In the next few sections, we will try the following three RNN models:
RNN with arbitrarily initialized, untrainable embeddings: In this model, we will initialize the embedding weights arbitrarily. Further, we’ll freeze the embeddings, that is, we won’t allow the network to train them.
RNN with arbitrarily initialized, trainable embeddings: In this model, we’ll allow the network to train the embeddings.
RNN with trainable word2vec embeddings: In this experiment, we’ll use word2vec word embeddings and also allow the network to train them further.
Let’s start with the first experiment: a vanilla RNN with arbitrarily initialized, untrainable embedding. For this RNN we won’t use the pre-trained word embeddings. We’ll use randomly initialized embeddings. Moreover, we won’t update the embeddings weights.
# create architecturernn_model = Sequential()# create embedding layer — usually the first layer in text problems# vocabulary size — number of unique words in datarnn_model.add(Embedding(input_dim = VOCABULARY_SIZE, # length of vector with which each word is represented output_dim = EMBEDDING_SIZE, # length of input sequence input_length = MAX_SEQ_LENGTH, # False — don’t update the embeddings trainable = False ))# add an RNN layer which contains 64 RNN cells# True — return whole sequence; False — return single output of the end of the sequencernn_model.add(SimpleRNN(64, return_sequences=True))# add time distributed (output at each sequence) layerrnn_model.add(TimeDistributed(Dense(NUM_CLASSES, activation=’softmax’)))#compile modelrnn_model.compile(loss = 'categorical_crossentropy', optimizer = 'adam', metrics = ['acc'])# check summary of the modelrnn_model.summary()
#fit modelrnn_training = rnn_model.fit(X_train, Y_train, batch_size=128, epochs=10, validation_data=(X_validation, Y_validation))
We can see here, after ten epoch, it is giving fairly decent accuracy of approx 95%. Also, we are getting a healthy growth curve below.
Next, try the second model — RNN with arbitrarily initialized, trainable embeddings. Here, we’ll allow the embeddings to get trained with the network. All I am doing is changing the parameter trainable to true i.e trainable = True. Rest all remains the same as above. On checking the model summary we can see that all the parameters have become trainable. i.e trainable params are equal to total params.
# check summary of the modelrnn_model.summary()
On fitting the model the accuracy has grown significantly. It has gone up to approx 98.95% by allowing the embedding weights to train. Therefore embedding has a significant effect on how the network is going to perform.
we’ll now try the word2vec embeddings and see if that improves our model or not.
Let’s now try the third experiment — RNN with trainable word2vec embeddings. Recall that we had loaded the word2vec embeddings in a matrix called ‘embedding_weights’. Using word2vec embeddings is just as easy as including this matrix in the model architecture.
The network architecture is the same as above but instead of starting with an arbitrary embedding matrix, we’ll use pre-trained embedding weights (weights = [embedding_weights]) coming from word2vec. The accuracy, in this case, has gone even further to approx 99.04%.
The results improved marginally in this case. That’s because the model was already performing very well. You’ll see much more improvements by using pre-trained embeddings in cases where you don’t have such a good model performance. Pre-trained embeddings provide a real boost in many applications.
To solve the vanishing gradients problem, many attempts have been made to tweak the vanilla RNNs such that the gradients don’t die when sequences get long. The most popular and successful of these attempts has been the long, short-term memory network, or the LSTM. LSTMs have proven to be so effective that they have almost replaced vanilla RNNs.
Thus, one of the fundamental differences between an RNN and an LSTM is that an LSTM has an explicit memory unit which stores information relevant for learning some task. In the standard RNN, the only way the network remembers past information is through updating the hidden states over time, but it does not have an explicit memory to store information.
On the other hand, in LSTMs, the memory units retain pieces of information even when the sequences get really long.
Next, we’ll build an LSTM model instead of an RNN. We just need to replace the RNN layer with LSTM layer.
# create architecturelstm_model = Sequential()# vocabulary size — number of unique words in data# length of vector with which each word is representedlstm_model.add(Embedding(input_dim = VOCABULARY_SIZE, output_dim = EMBEDDING_SIZE, # length of input sequenceinput_length = MAX_SEQ_LENGTH, # word embedding matrixweights = [embedding_weights],# True — update embeddings_weight matrixtrainable = True ))# add an LSTM layer which contains 64 LSTM cells# True — return whole sequence; False — return single output of the end of the sequencelstm_model.add(LSTM(64, return_sequences=True))lstm_model.add(TimeDistributed(Dense(NUM_CLASSES, activation=’softmax’)))#compile modelrnn_model.compile(loss = 'categorical_crossentropy', optimizer = 'adam', metrics = ['acc'])# check summary of the modelrnn_model.summary()
lstm_training = lstm_model.fit(X_train, Y_train, batch_size=128, epochs=10, validation_data=(X_validation, Y_validation))
The LSTM model also provided some marginal improvement. However, if we use an LSTM model in other tasks such as language translation, image captioning, time series forecasting, etc. then you may see a significant boost in the performance.
Keeping in mind the computational expenses and the problem of overfitting, researchers have tried to come up with alternate structures of the LSTM cell. The most popular one of these alternatives is the gated recurrent unit (GRU). GRU being a simpler model than LSTM, it's always easier to train. LSTMs and GRUs have almost completely replaced the standard RNNs in practice because they’re more effective and faster to train than vanilla RNNs (despite the larger number of parameters).
Let’s now build a GRU model. We’ll then also compare the performance of the RNN, LSTM, and the GRU model.
# create architecturelstm_model = Sequential()# vocabulary size — number of unique words in data# length of vector with which each word is representedlstm_model.add(Embedding(input_dim = VOCABULARY_SIZE, output_dim = EMBEDDING_SIZE, # length of input sequenceinput_length = MAX_SEQ_LENGTH, # word embedding matrixweights = [embedding_weights],# True — update embeddings_weight matrixtrainable = True ))# add an LSTM layer which contains 64 LSTM cells# True — return whole sequence; False — return single output of the end of the sequencelstm_model.add(GRU(64, return_sequences=True))lstm_model.add(TimeDistributed(Dense(NUM_CLASSES, activation=’softmax’)))#compile modelrnn_model.compile(loss = 'categorical_crossentropy', optimizer = 'adam', metrics = ['acc'])# check summary of the modelrnn_model.summary()
There is a reduction in params in GRU as compared to LSTM. Therefore we do get a significant boost in terms of computational efficiency with hardly any decremental effect in the performance of the model.
gru_training = gru_model.fit(X_train, Y_train, batch_size=128, epochs=10, validation_data=(X_validation, Y_validation))
The accuracy of the model remains the same as the LSTM. But we saw that the time taken by an LSTM is greater than a GRU and an RNN. This was expected since the parameters in an LSTM and GRU are 4x and 3x of a normal RNN, respectively.
For example, when you want to assign a sentiment score to a piece of text (say a customer review), the network can see the entire review text before assigning them a score. On the other hand, in a task such as predicting the next word given previous few typed words, the network does not have access to the words in the future time steps while predicting the next word.
These two types of tasks are called offline and online sequence processing respectively.
Now, there is a neat trick you can use with offline tasks — since the network has access to the entire sequence before making predictions, why not use this task to make the network ‘look at the future elements in the sequence’ while training, hoping that this will make the network learn better?
This is the idea exploited by what is called bidirectional RNNs.
By using bidirectional RNNs, it is almost certain that you’ll get better results. However, bidirectional RNNs take almost double the time to train since the number of parameters of the network increase. Therefore, you have a tradeoff between training time and performance. The decision to use a bidirectional RNN depends on the computing resources that you have and the performance you are aiming for.
Finally, let’s build one more model — a bidirectional LSTM and compare its performance in terms of accuracy and training time as compared to the previous models.
# create architecturebidirect_model = Sequential()bidirect_model.add(Embedding(input_dim = VOCABULARY_SIZE, output_dim = EMBEDDING_SIZE, input_length = MAX_SEQ_LENGTH, weights = [embedding_weights], trainable = True))bidirect_model.add(Bidirectional(LSTM(64, return_sequences=True)))bidirect_model.add(TimeDistributed(Dense(NUM_CLASSES, activation=’softmax’)))#compile modelbidirect_model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['acc'])# check summary of modelbidirect_model.summary()
You can see the no of parameters has gone up. It does significantly shoot up the no of params.
bidirect_training = bidirect_model.fit(X_train, Y_train, batch_size=128, epochs=10, validation_data=(X_validation, Y_validation))
The bidirectional LSTM did increase the accuracy substantially (considering that the accuracy was already hitting the roof). This shows the power of bidirectional LSTMs. However, this increased accuracy comes at a cost. The time taken was almost double than of a normal LSTM network.
Below is the quick summary of each of the four models we tried. We can see a trend here as we move from one model to another.
loss, accuracy = rnn_model.evaluate(X_test, Y_test, verbose = 1)print(“Loss: {0},\nAccuracy: {1}”.format(loss, accuracy))
loss, accuracy = lstm_model.evaluate(X_test, Y_test, verbose = 1)print(“Loss: {0},\nAccuracy: {1}”.format(loss, accuracy))
loss, accuracy = gru_model.evaluate(X_test, Y_test, verbose = 1)print(“Loss: {0},\nAccuracy: {1}”.format(loss, accuracy))
loss, accuracy = bidirect_model.evaluate(X_test, Y_test, verbose = 1)print("Loss: {0},\nAccuracy: {1}".format(loss, accuracy))
If you have any questions, recommendations, or critiques, I can be reached via LinkedIn or the comment section. | [
{
"code": null,
"e": 554,
"s": 171,
"text": "The classical way of doing POS tagging is using some variant of Hidden Markov Model. Here we'll see how we could do that using Recurrent neural networks. The original RNN architecture has some variants too. It has a novel RNN architecture — the Bidirectional RNN which is capable of reading sequences in the ‘reverse order’ as well and has proven to boost performance significantly."
},
{
"code": null,
"e": 1093,
"s": 554,
"text": "Then two important cutting-edge variants of the RNN which have made it possible to train large networks on real datasets. Although RNNs are capable of solving a variety of sequence problems, their architecture itself is their biggest enemy due to the problems of exploding and vanishing gradients that occur during the training of RNNs. This problem is solved by two popular gated RNN architectures — the Long, Short Term Memory (LSTM) and the Gated Recurrent Unit (GRU). We’ll look into all these models here with respect to POS tagging."
},
{
"code": null,
"e": 1519,
"s": 1093,
"text": "The process of classifying words into their parts of speech and labeling them accordingly is known as part-of-speech tagging, or simply POS-tagging. The NLTK library has a number of corpora that contain words and their POS tag. I will be using the POS tagged corpora i.e treebank, conll2000, and brown from NLTK to demonstrate the key concepts. To get into the codes directly, an accompanying notebook is published on Kaggle."
},
{
"code": null,
"e": 1534,
"s": 1519,
"text": "www.kaggle.com"
},
{
"code": null,
"e": 1605,
"s": 1534,
"text": "The following table provides information about some of the major tags:"
},
{
"code": null,
"e": 1688,
"s": 1605,
"text": "Preprocess dataWord EmbeddingsVanilla RNNLSTMGRUBidirectional LSTMModel Evaluation"
},
{
"code": null,
"e": 1704,
"s": 1688,
"text": "Preprocess data"
},
{
"code": null,
"e": 1720,
"s": 1704,
"text": "Word Embeddings"
},
{
"code": null,
"e": 1732,
"s": 1720,
"text": "Vanilla RNN"
},
{
"code": null,
"e": 1737,
"s": 1732,
"text": "LSTM"
},
{
"code": null,
"e": 1741,
"s": 1737,
"text": "GRU"
},
{
"code": null,
"e": 1760,
"s": 1741,
"text": "Bidirectional LSTM"
},
{
"code": null,
"e": 1777,
"s": 1760,
"text": "Model Evaluation"
},
{
"code": null,
"e": 2047,
"s": 1777,
"text": "Let’s begin with importing the necessary libraries and loading the dataset. This is a requisite step in every data analysis process(The complete code can be viewed here). We’ll be loading the data first using three well-known text corpora and taking the union of those."
},
{
"code": null,
"e": 2410,
"s": 2047,
"text": "# Importing and Loading the data into data frame# load POS tagged corpora from NLTKtreebank_corpus = treebank.tagged_sents(tagset='universal')brown_corpus = brown.tagged_sents(tagset='universal')conll_corpus = conll2000.tagged_sents(tagset='universal')# Merging the dataframes to create a master dftagged_sentences = treebank_corpus + brown_corpus + conll_corpus"
},
{
"code": null,
"e": 2553,
"s": 2410,
"text": "As a part of preprocessing, we’ll be performing various steps such as dividing data into words and tags, Vectorise X and Y, and Pad sequences."
},
{
"code": null,
"e": 2647,
"s": 2553,
"text": "Let's look at the data first. For each of the words below, there is a tag associated with it."
},
{
"code": null,
"e": 2691,
"s": 2647,
"text": "# let's look at the datatagged_sentences[7]"
},
{
"code": null,
"e": 3005,
"s": 2691,
"text": "Since this is a many-to-many problem, each data point will be a different sentence of the corpora. Each data point will have multiple words in the input sequence. This is what we will refer to as X. Each word will have its corresponding tag in the output sequence. This what we will refer to as Y. Sample dataset:"
},
{
"code": null,
"e": 3632,
"s": 3005,
"text": "X = [] # store input sequenceY = [] # store output sequencefor sentence in tagged_sentences: X_sentence = [] Y_sentence = [] for entity in sentence: X_sentence.append(entity[0]) # entity[0] contains the word Y_sentence.append(entity[1]) # entity[1] contains corresponding tag X.append(X_sentence) Y.append(Y_sentence)num_words = len(set([word.lower() for sentence in X for word in sentence]))num_tags = len(set([word.lower() for sentence in Y for word in sentence]))print(\"Total number of tagged sentences: {}\".format(len(X)))print(\"Vocabulary size: {}\".format(num_words))print(\"Total number of tags: {}\".format(num_tags))"
},
{
"code": null,
"e": 3779,
"s": 3632,
"text": "# let’s look at first data point# this is one data point that will be fed to the RNNprint(‘sample X: ‘, X[0], ‘\\n’)print(‘sample Y: ‘, Y[0], ‘\\n’)"
},
{
"code": null,
"e": 4116,
"s": 3779,
"text": "# In this many-to-many problem, the length of each input and output sequence must be the same.# Since each word is tagged, it’s important to make sure that the length of input sequence equals the output sequenceprint(“Length of first input sequence : {}”.format(len(X[0])))print(“Length of first output sequence : {}”.format(len(Y[0])))"
},
{
"code": null,
"e": 4853,
"s": 4116,
"text": "The next thing we need to figure out is how are we going to feed these inputs to an RNN. If we have to give the words as input to any neural networks then we essentially have to convert them into numbers. We need to create a word embedding or one-hot vectors i.e. a vector of numbers form of each word. To start with this we'll first encode the input and output which will give a blind unique id to each word in the entire corpus for input data. On the other hand, we have the Y matrix(tags/output data). We have twelve POS tags here, treating each of them as a class and each pos tag is converted into one-hot encoding of length twelve. We’ll use the Tokenizer() function from Keras library to encode text sequence to integer sequence."
},
{
"code": null,
"e": 5458,
"s": 4853,
"text": "# encode Xword_tokenizer = Tokenizer() # instantiate tokeniserword_tokenizer.fit_on_texts(X) # fit tokeniser on data# use the tokeniser to encode input sequenceX_encoded = word_tokenizer.texts_to_sequences(X) # encode Ytag_tokenizer = Tokenizer()tag_tokenizer.fit_on_texts(Y)Y_encoded = tag_tokenizer.texts_to_sequences(Y)# look at first encoded data pointprint(\"** Raw data point **\", \"\\n\", \"-\"*100, \"\\n\")print('X: ', X[0], '\\n')print('Y: ', Y[0], '\\n')print()print(\"** Encoded data point **\", \"\\n\", \"-\"*100, \"\\n\")print('X: ', X_encoded[0], '\\n')print('Y: ', Y_encoded[0], '\\n')"
},
{
"code": null,
"e": 5530,
"s": 5458,
"text": "Make sure that each sequence of input and output is of the same length."
},
{
"code": null,
"e": 6008,
"s": 5530,
"text": "The sentences in the corpus are not of the same length. Before we feed the input in the RNN model we need to fix the length of the sentences. We cannot dynamically allocate memory required to process each sentence in the corpus as they are of different lengths. Therefore the next step after encoding the data is to define the sequence lengths. We need to either pad short sentences or truncate long sentences to a fixed length. This fixed length, however, is a hyperparameter."
},
{
"code": null,
"e": 6756,
"s": 6008,
"text": "# Pad each sequence to MAX_SEQ_LENGTH using KERAS’ pad_sequences() function. # Sentences longer than MAX_SEQ_LENGTH are truncated.# Sentences shorter than MAX_SEQ_LENGTH are padded with zeroes.# Truncation and padding can either be ‘pre’ or ‘post’. # For padding we are using ‘pre’ padding type, that is, add zeroes on the left side.# For truncation, we are using ‘post’, that is, truncate a sentence from right side.# sequences greater than 100 in length will be truncatedMAX_SEQ_LENGTH = 100X_padded = pad_sequences(X_encoded, maxlen=MAX_SEQ_LENGTH, padding=”pre”, truncating=”post”)Y_padded = pad_sequences(Y_encoded, maxlen=MAX_SEQ_LENGTH, padding=”pre”, truncating=”post”)# print the first sequenceprint(X_padded[0], \"\\n\"*3)print(Y_padded[0])"
},
{
"code": null,
"e": 7017,
"s": 6756,
"text": "You know that a better way (than one-hot vectors) to represent text is word embeddings. Currently, each word and each tag is encoded as an integer. We’ll use a more sophisticated technique to represent the input words (X) using what’s known as word embeddings."
},
{
"code": null,
"e": 7224,
"s": 7017,
"text": "However, to represent each tag in Y, we’ll simply use one-hot encoding scheme since there are only 12 tags in the dataset and the LSTM will have no problems in learning its own representation of these tags."
},
{
"code": null,
"e": 7295,
"s": 7224,
"text": "To use word embeddings, you can go for either of the following models:"
},
{
"code": null,
"e": 7321,
"s": 7295,
"text": "word2vec modelGloVe model"
},
{
"code": null,
"e": 7336,
"s": 7321,
"text": "word2vec model"
},
{
"code": null,
"e": 7348,
"s": 7336,
"text": "GloVe model"
},
{
"code": null,
"e": 7510,
"s": 7348,
"text": "We’re using the word2vec model for no particular reason. Both of these are very efficient in representing words. You can try both and see which one works better."
},
{
"code": null,
"e": 7587,
"s": 7510,
"text": "The dimension of a word embedding is: (VOCABULARY_SIZE, EMBEDDING_DIMENSION)"
},
{
"code": null,
"e": 8359,
"s": 7587,
"text": "# word2vecpath = ‘../input/wordembeddings/GoogleNews-vectors-negative300.bin’# load word2vec using the following function present in the gensim libraryword2vec = KeyedVectors.load_word2vec_format(path, binary=True)# assign word vectors from word2vec model# each word in word2vec model is represented using a 300 dimensional vectorEMBEDDING_SIZE = 300 VOCABULARY_SIZE = len(word_tokenizer.word_index) + 1# create an empty embedding matixembedding_weights = np.zeros((VOCABULARY_SIZE, EMBEDDING_SIZE))# create a word to index dictionary mappingword2id = word_tokenizer.word_index# copy vectors from word2vec model to the words present in corpusfor word, index in word2id.items(): try: embedding_weights[index, :] = word2vec[word] except KeyError: pass"
},
{
"code": null,
"e": 8437,
"s": 8359,
"text": "# use Keras’ to_categorical function to one-hot encode YY = to_categorical(Y)"
},
{
"code": null,
"e": 8576,
"s": 8437,
"text": "All the data preprocessing is now complete. Let’s now jump to the modeling part by splitting the data to train, validation, and test sets."
},
{
"code": null,
"e": 8711,
"s": 8576,
"text": "Before using RNN, we must make sure the dimensions of the data are what an RNN expects. In general, an RNN expects the following shape"
},
{
"code": null,
"e": 8757,
"s": 8711,
"text": "Shape of X: (#samples, #timesteps, #features)"
},
{
"code": null,
"e": 8803,
"s": 8757,
"text": "Shape of Y: (#samples, #timesteps, #features)"
},
{
"code": null,
"e": 9864,
"s": 8803,
"text": "Now, there can be various variations in the shape that you use to feed an RNN depending on the type of architecture. Since the problem we’re working on has a many-to-many architecture, the input and the output both include number of timesteps which is nothing but the sequence length. But notice that the tensor X doesn’t have the third dimension, that is, number of features. That’s because we’re going to use word embeddings before feeding in the data to an RNN, and hence there is no need to explicitly mention the third dimension. That’s because when you use the Embedding() layer in Keras, the training data will automatically be converted to (#samples, #timesteps, #features) where #features will be the embedding dimension (and note that the Embedding layer is always the very first layer of an RNN). While using the embedding layer we only need to reshape the data to (#samples, #timesteps) which is what we have done. However, note that you’ll need to shape it to (#samples, #timesteps, #features) in case you don’t use the Embedding() layer in Keras."
},
{
"code": null,
"e": 10228,
"s": 9864,
"text": "Next, let’s build the RNN model. We’re going to use word embeddings to represent the words. Now, while training the model, you can also train the word embeddings along with the network weights. These are often called the embedding weights. While training, the embedding weights will be treated as normal weights of the network which are updated in each iteration."
},
{
"code": null,
"e": 10298,
"s": 10228,
"text": "In the next few sections, we will try the following three RNN models:"
},
{
"code": null,
"e": 10514,
"s": 10298,
"text": "RNN with arbitrarily initialized, untrainable embeddings: In this model, we will initialize the embedding weights arbitrarily. Further, we’ll freeze the embeddings, that is, we won’t allow the network to train them."
},
{
"code": null,
"e": 10634,
"s": 10514,
"text": "RNN with arbitrarily initialized, trainable embeddings: In this model, we’ll allow the network to train the embeddings."
},
{
"code": null,
"e": 10779,
"s": 10634,
"text": "RNN with trainable word2vec embeddings: In this experiment, we’ll use word2vec word embeddings and also allow the network to train them further."
},
{
"code": null,
"e": 11037,
"s": 10779,
"text": "Let’s start with the first experiment: a vanilla RNN with arbitrarily initialized, untrainable embedding. For this RNN we won’t use the pre-trained word embeddings. We’ll use randomly initialized embeddings. Moreover, we won’t update the embeddings weights."
},
{
"code": null,
"e": 11960,
"s": 11037,
"text": "# create architecturernn_model = Sequential()# create embedding layer — usually the first layer in text problems# vocabulary size — number of unique words in datarnn_model.add(Embedding(input_dim = VOCABULARY_SIZE, # length of vector with which each word is represented output_dim = EMBEDDING_SIZE, # length of input sequence input_length = MAX_SEQ_LENGTH, # False — don’t update the embeddings trainable = False ))# add an RNN layer which contains 64 RNN cells# True — return whole sequence; False — return single output of the end of the sequencernn_model.add(SimpleRNN(64, return_sequences=True))# add time distributed (output at each sequence) layerrnn_model.add(TimeDistributed(Dense(NUM_CLASSES, activation=’softmax’)))#compile modelrnn_model.compile(loss = 'categorical_crossentropy', optimizer = 'adam', metrics = ['acc'])# check summary of the modelrnn_model.summary()"
},
{
"code": null,
"e": 12090,
"s": 11960,
"text": "#fit modelrnn_training = rnn_model.fit(X_train, Y_train, batch_size=128, epochs=10, validation_data=(X_validation, Y_validation))"
},
{
"code": null,
"e": 12226,
"s": 12090,
"text": "We can see here, after ten epoch, it is giving fairly decent accuracy of approx 95%. Also, we are getting a healthy growth curve below."
},
{
"code": null,
"e": 12630,
"s": 12226,
"text": "Next, try the second model — RNN with arbitrarily initialized, trainable embeddings. Here, we’ll allow the embeddings to get trained with the network. All I am doing is changing the parameter trainable to true i.e trainable = True. Rest all remains the same as above. On checking the model summary we can see that all the parameters have become trainable. i.e trainable params are equal to total params."
},
{
"code": null,
"e": 12678,
"s": 12630,
"text": "# check summary of the modelrnn_model.summary()"
},
{
"code": null,
"e": 12898,
"s": 12678,
"text": "On fitting the model the accuracy has grown significantly. It has gone up to approx 98.95% by allowing the embedding weights to train. Therefore embedding has a significant effect on how the network is going to perform."
},
{
"code": null,
"e": 12979,
"s": 12898,
"text": "we’ll now try the word2vec embeddings and see if that improves our model or not."
},
{
"code": null,
"e": 13240,
"s": 12979,
"text": "Let’s now try the third experiment — RNN with trainable word2vec embeddings. Recall that we had loaded the word2vec embeddings in a matrix called ‘embedding_weights’. Using word2vec embeddings is just as easy as including this matrix in the model architecture."
},
{
"code": null,
"e": 13508,
"s": 13240,
"text": "The network architecture is the same as above but instead of starting with an arbitrary embedding matrix, we’ll use pre-trained embedding weights (weights = [embedding_weights]) coming from word2vec. The accuracy, in this case, has gone even further to approx 99.04%."
},
{
"code": null,
"e": 13806,
"s": 13508,
"text": "The results improved marginally in this case. That’s because the model was already performing very well. You’ll see much more improvements by using pre-trained embeddings in cases where you don’t have such a good model performance. Pre-trained embeddings provide a real boost in many applications."
},
{
"code": null,
"e": 14153,
"s": 13806,
"text": "To solve the vanishing gradients problem, many attempts have been made to tweak the vanilla RNNs such that the gradients don’t die when sequences get long. The most popular and successful of these attempts has been the long, short-term memory network, or the LSTM. LSTMs have proven to be so effective that they have almost replaced vanilla RNNs."
},
{
"code": null,
"e": 14507,
"s": 14153,
"text": "Thus, one of the fundamental differences between an RNN and an LSTM is that an LSTM has an explicit memory unit which stores information relevant for learning some task. In the standard RNN, the only way the network remembers past information is through updating the hidden states over time, but it does not have an explicit memory to store information."
},
{
"code": null,
"e": 14623,
"s": 14507,
"text": "On the other hand, in LSTMs, the memory units retain pieces of information even when the sequences get really long."
},
{
"code": null,
"e": 14729,
"s": 14623,
"text": "Next, we’ll build an LSTM model instead of an RNN. We just need to replace the RNN layer with LSTM layer."
},
{
"code": null,
"e": 15584,
"s": 14729,
"text": "# create architecturelstm_model = Sequential()# vocabulary size — number of unique words in data# length of vector with which each word is representedlstm_model.add(Embedding(input_dim = VOCABULARY_SIZE, output_dim = EMBEDDING_SIZE, # length of input sequenceinput_length = MAX_SEQ_LENGTH, # word embedding matrixweights = [embedding_weights],# True — update embeddings_weight matrixtrainable = True ))# add an LSTM layer which contains 64 LSTM cells# True — return whole sequence; False — return single output of the end of the sequencelstm_model.add(LSTM(64, return_sequences=True))lstm_model.add(TimeDistributed(Dense(NUM_CLASSES, activation=’softmax’)))#compile modelrnn_model.compile(loss = 'categorical_crossentropy', optimizer = 'adam', metrics = ['acc'])# check summary of the modelrnn_model.summary()"
},
{
"code": null,
"e": 15706,
"s": 15584,
"text": "lstm_training = lstm_model.fit(X_train, Y_train, batch_size=128, epochs=10, validation_data=(X_validation, Y_validation))"
},
{
"code": null,
"e": 15945,
"s": 15706,
"text": "The LSTM model also provided some marginal improvement. However, if we use an LSTM model in other tasks such as language translation, image captioning, time series forecasting, etc. then you may see a significant boost in the performance."
},
{
"code": null,
"e": 16431,
"s": 15945,
"text": "Keeping in mind the computational expenses and the problem of overfitting, researchers have tried to come up with alternate structures of the LSTM cell. The most popular one of these alternatives is the gated recurrent unit (GRU). GRU being a simpler model than LSTM, it's always easier to train. LSTMs and GRUs have almost completely replaced the standard RNNs in practice because they’re more effective and faster to train than vanilla RNNs (despite the larger number of parameters)."
},
{
"code": null,
"e": 16537,
"s": 16431,
"text": "Let’s now build a GRU model. We’ll then also compare the performance of the RNN, LSTM, and the GRU model."
},
{
"code": null,
"e": 17391,
"s": 16537,
"text": "# create architecturelstm_model = Sequential()# vocabulary size — number of unique words in data# length of vector with which each word is representedlstm_model.add(Embedding(input_dim = VOCABULARY_SIZE, output_dim = EMBEDDING_SIZE, # length of input sequenceinput_length = MAX_SEQ_LENGTH, # word embedding matrixweights = [embedding_weights],# True — update embeddings_weight matrixtrainable = True ))# add an LSTM layer which contains 64 LSTM cells# True — return whole sequence; False — return single output of the end of the sequencelstm_model.add(GRU(64, return_sequences=True))lstm_model.add(TimeDistributed(Dense(NUM_CLASSES, activation=’softmax’)))#compile modelrnn_model.compile(loss = 'categorical_crossentropy', optimizer = 'adam', metrics = ['acc'])# check summary of the modelrnn_model.summary()"
},
{
"code": null,
"e": 17595,
"s": 17391,
"text": "There is a reduction in params in GRU as compared to LSTM. Therefore we do get a significant boost in terms of computational efficiency with hardly any decremental effect in the performance of the model."
},
{
"code": null,
"e": 17715,
"s": 17595,
"text": "gru_training = gru_model.fit(X_train, Y_train, batch_size=128, epochs=10, validation_data=(X_validation, Y_validation))"
},
{
"code": null,
"e": 17950,
"s": 17715,
"text": "The accuracy of the model remains the same as the LSTM. But we saw that the time taken by an LSTM is greater than a GRU and an RNN. This was expected since the parameters in an LSTM and GRU are 4x and 3x of a normal RNN, respectively."
},
{
"code": null,
"e": 18320,
"s": 17950,
"text": "For example, when you want to assign a sentiment score to a piece of text (say a customer review), the network can see the entire review text before assigning them a score. On the other hand, in a task such as predicting the next word given previous few typed words, the network does not have access to the words in the future time steps while predicting the next word."
},
{
"code": null,
"e": 18409,
"s": 18320,
"text": "These two types of tasks are called offline and online sequence processing respectively."
},
{
"code": null,
"e": 18705,
"s": 18409,
"text": "Now, there is a neat trick you can use with offline tasks — since the network has access to the entire sequence before making predictions, why not use this task to make the network ‘look at the future elements in the sequence’ while training, hoping that this will make the network learn better?"
},
{
"code": null,
"e": 18770,
"s": 18705,
"text": "This is the idea exploited by what is called bidirectional RNNs."
},
{
"code": null,
"e": 19172,
"s": 18770,
"text": "By using bidirectional RNNs, it is almost certain that you’ll get better results. However, bidirectional RNNs take almost double the time to train since the number of parameters of the network increase. Therefore, you have a tradeoff between training time and performance. The decision to use a bidirectional RNN depends on the computing resources that you have and the performance you are aiming for."
},
{
"code": null,
"e": 19334,
"s": 19172,
"text": "Finally, let’s build one more model — a bidirectional LSTM and compare its performance in terms of accuracy and training time as compared to the previous models."
},
{
"code": null,
"e": 19873,
"s": 19334,
"text": "# create architecturebidirect_model = Sequential()bidirect_model.add(Embedding(input_dim = VOCABULARY_SIZE, output_dim = EMBEDDING_SIZE, input_length = MAX_SEQ_LENGTH, weights = [embedding_weights], trainable = True))bidirect_model.add(Bidirectional(LSTM(64, return_sequences=True)))bidirect_model.add(TimeDistributed(Dense(NUM_CLASSES, activation=’softmax’)))#compile modelbidirect_model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['acc'])# check summary of modelbidirect_model.summary()"
},
{
"code": null,
"e": 19968,
"s": 19873,
"text": "You can see the no of parameters has gone up. It does significantly shoot up the no of params."
},
{
"code": null,
"e": 20098,
"s": 19968,
"text": "bidirect_training = bidirect_model.fit(X_train, Y_train, batch_size=128, epochs=10, validation_data=(X_validation, Y_validation))"
},
{
"code": null,
"e": 20382,
"s": 20098,
"text": "The bidirectional LSTM did increase the accuracy substantially (considering that the accuracy was already hitting the roof). This shows the power of bidirectional LSTMs. However, this increased accuracy comes at a cost. The time taken was almost double than of a normal LSTM network."
},
{
"code": null,
"e": 20508,
"s": 20382,
"text": "Below is the quick summary of each of the four models we tried. We can see a trend here as we move from one model to another."
},
{
"code": null,
"e": 20630,
"s": 20508,
"text": "loss, accuracy = rnn_model.evaluate(X_test, Y_test, verbose = 1)print(“Loss: {0},\\nAccuracy: {1}”.format(loss, accuracy))"
},
{
"code": null,
"e": 20753,
"s": 20630,
"text": "loss, accuracy = lstm_model.evaluate(X_test, Y_test, verbose = 1)print(“Loss: {0},\\nAccuracy: {1}”.format(loss, accuracy))"
},
{
"code": null,
"e": 20875,
"s": 20753,
"text": "loss, accuracy = gru_model.evaluate(X_test, Y_test, verbose = 1)print(“Loss: {0},\\nAccuracy: {1}”.format(loss, accuracy))"
},
{
"code": null,
"e": 21002,
"s": 20875,
"text": "loss, accuracy = bidirect_model.evaluate(X_test, Y_test, verbose = 1)print(\"Loss: {0},\\nAccuracy: {1}\".format(loss, accuracy))"
}
] |
SQLite - GLOB Clause | SQLite GLOB operator is used to match only text values against a pattern using wildcards. If the search expression can be matched to the pattern expression, the GLOB operator will return true, which is 1. Unlike LIKE operator, GLOB is case sensitive and it follows syntax of UNIX for specifying THE following wildcards.
The asterisk sign (*)
The question mark (?)
The asterisk sign (*) represents zero or multiple numbers or characters. The question mark (?) represents a single number or character.
Following is the basic syntax of * and ?.
SELECT FROM table_name
WHERE column GLOB 'XXXX*'
or
SELECT FROM table_name
WHERE column GLOB '*XXXX*'
or
SELECT FROM table_name
WHERE column GLOB 'XXXX?'
or
SELECT FROM table_name
WHERE column GLOB '?XXXX'
or
SELECT FROM table_name
WHERE column GLOB '?XXXX?'
or
SELECT FROM table_name
WHERE column GLOB '????'
You can combine N number of conditions using AND or OR operators. Here, XXXX could be any numeric or string value.
Following table lists a number of examples showing WHERE part having different LIKE clause with '*' and '?' operators.
WHERE SALARY GLOB '200*'
Finds any values that start with 200
WHERE SALARY GLOB '*200*'
Finds any values that have 200 in any position
WHERE SALARY GLOB '?00*'
Finds any values that have 00 in the second and third positions
WHERE SALARY GLOB '2??'
Finds any values that start with 2 and are at least 3 characters in length
WHERE SALARY GLOB '*2'
Finds any values that end with 2
WHERE SALARY GLOB '?2*3'
Finds any values that have a 2 in the second position and end with a 3
WHERE SALARY GLOB '2???3'
Finds any values in a five-digit number that start with 2 and end with 3
Let us take a real example, consider COMPANY table with the following records −
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
1 Paul 32 California 20000.0
2 Allen 25 Texas 15000.0
3 Teddy 23 Norway 20000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
6 Kim 22 South-Hall 45000.0
7 James 24 Houston 10000.0
Following is an example, which will display all the records from COMPANY table, where AGE starts with 2.
sqlite> SELECT * FROM COMPANY WHERE AGE GLOB '2*';
This will produce the following result.
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
2 Allen 25 Texas 15000.0
3 Teddy 23 Norway 20000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
6 Kim 22 South-Hall 45000.0
7 James 24 Houston 10000.0
Following is an example, which will display all the records from COMPANY table where ADDRESS will have a hyphen (-) inside the text −
sqlite> SELECT * FROM COMPANY WHERE ADDRESS GLOB '*-*';
This will produce the following result.
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
4 Mark 25 Rich-Mond 65000.0
6 Kim 22 South-Hall 45000.0
25 Lectures
4.5 hours
Sandip Bhattacharya
17 Lectures
1 hours
Laurence Svekis
5 Lectures
51 mins
Vinay Kumar
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2958,
"s": 2638,
"text": "SQLite GLOB operator is used to match only text values against a pattern using wildcards. If the search expression can be matched to the pattern expression, the GLOB operator will return true, which is 1. Unlike LIKE operator, GLOB is case sensitive and it follows syntax of UNIX for specifying THE following wildcards."
},
{
"code": null,
"e": 2980,
"s": 2958,
"text": "The asterisk sign (*)"
},
{
"code": null,
"e": 3002,
"s": 2980,
"text": "The question mark (?)"
},
{
"code": null,
"e": 3138,
"s": 3002,
"text": "The asterisk sign (*) represents zero or multiple numbers or characters. The question mark (?) represents a single number or character."
},
{
"code": null,
"e": 3180,
"s": 3138,
"text": "Following is the basic syntax of * and ?."
},
{
"code": null,
"e": 3492,
"s": 3180,
"text": "SELECT FROM table_name\nWHERE column GLOB 'XXXX*'\nor \nSELECT FROM table_name\nWHERE column GLOB '*XXXX*'\nor\nSELECT FROM table_name\nWHERE column GLOB 'XXXX?'\nor\nSELECT FROM table_name\nWHERE column GLOB '?XXXX'\nor\nSELECT FROM table_name\nWHERE column GLOB '?XXXX?'\nor\nSELECT FROM table_name\nWHERE column GLOB '????'\n"
},
{
"code": null,
"e": 3607,
"s": 3492,
"text": "You can combine N number of conditions using AND or OR operators. Here, XXXX could be any numeric or string value."
},
{
"code": null,
"e": 3726,
"s": 3607,
"text": "Following table lists a number of examples showing WHERE part having different LIKE clause with '*' and '?' operators."
},
{
"code": null,
"e": 3751,
"s": 3726,
"text": "WHERE SALARY GLOB '200*'"
},
{
"code": null,
"e": 3788,
"s": 3751,
"text": "Finds any values that start with 200"
},
{
"code": null,
"e": 3814,
"s": 3788,
"text": "WHERE SALARY GLOB '*200*'"
},
{
"code": null,
"e": 3861,
"s": 3814,
"text": "Finds any values that have 200 in any position"
},
{
"code": null,
"e": 3886,
"s": 3861,
"text": "WHERE SALARY GLOB '?00*'"
},
{
"code": null,
"e": 3950,
"s": 3886,
"text": "Finds any values that have 00 in the second and third positions"
},
{
"code": null,
"e": 3974,
"s": 3950,
"text": "WHERE SALARY GLOB '2??'"
},
{
"code": null,
"e": 4049,
"s": 3974,
"text": "Finds any values that start with 2 and are at least 3 characters in length"
},
{
"code": null,
"e": 4072,
"s": 4049,
"text": "WHERE SALARY GLOB '*2'"
},
{
"code": null,
"e": 4105,
"s": 4072,
"text": "Finds any values that end with 2"
},
{
"code": null,
"e": 4130,
"s": 4105,
"text": "WHERE SALARY GLOB '?2*3'"
},
{
"code": null,
"e": 4201,
"s": 4130,
"text": "Finds any values that have a 2 in the second position and end with a 3"
},
{
"code": null,
"e": 4227,
"s": 4201,
"text": "WHERE SALARY GLOB '2???3'"
},
{
"code": null,
"e": 4300,
"s": 4227,
"text": "Finds any values in a five-digit number that start with 2 and end with 3"
},
{
"code": null,
"e": 4380,
"s": 4300,
"text": "Let us take a real example, consider COMPANY table with the following records −"
},
{
"code": null,
"e": 4886,
"s": 4380,
"text": "ID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n1 Paul 32 California 20000.0\n2 Allen 25 Texas 15000.0\n3 Teddy 23 Norway 20000.0\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0\n6 Kim 22 South-Hall 45000.0\n7 James 24 Houston 10000.0"
},
{
"code": null,
"e": 4991,
"s": 4886,
"text": "Following is an example, which will display all the records from COMPANY table, where AGE starts with 2."
},
{
"code": null,
"e": 5043,
"s": 4991,
"text": "sqlite> SELECT * FROM COMPANY WHERE AGE GLOB '2*';"
},
{
"code": null,
"e": 5083,
"s": 5043,
"text": "This will produce the following result."
},
{
"code": null,
"e": 5534,
"s": 5083,
"text": "ID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n2 Allen 25 Texas 15000.0\n3 Teddy 23 Norway 20000.0\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0\n6 Kim 22 South-Hall 45000.0\n7 James 24 Houston 10000.0\n"
},
{
"code": null,
"e": 5668,
"s": 5534,
"text": "Following is an example, which will display all the records from COMPANY table where ADDRESS will have a hyphen (-) inside the text −"
},
{
"code": null,
"e": 5725,
"s": 5668,
"text": "sqlite> SELECT * FROM COMPANY WHERE ADDRESS GLOB '*-*';"
},
{
"code": null,
"e": 5765,
"s": 5725,
"text": "This will produce the following result."
},
{
"code": null,
"e": 5992,
"s": 5765,
"text": "ID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n4 Mark 25 Rich-Mond 65000.0\n6 Kim 22 South-Hall 45000.0\n"
},
{
"code": null,
"e": 6027,
"s": 5992,
"text": "\n 25 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 6048,
"s": 6027,
"text": " Sandip Bhattacharya"
},
{
"code": null,
"e": 6081,
"s": 6048,
"text": "\n 17 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 6098,
"s": 6081,
"text": " Laurence Svekis"
},
{
"code": null,
"e": 6129,
"s": 6098,
"text": "\n 5 Lectures \n 51 mins\n"
},
{
"code": null,
"e": 6142,
"s": 6129,
"text": " Vinay Kumar"
},
{
"code": null,
"e": 6149,
"s": 6142,
"text": " Print"
},
{
"code": null,
"e": 6160,
"s": 6149,
"text": " Add Notes"
}
] |
Find the sum of maximum difference possible from all subset of a given array. - GeeksforGeeks | 18 Nov, 2021
We are given an array arr[] of n non-negative integers (repeated elements allowed), find out the sum of maximum difference possible from all subsets of the given array. Suppose max(s) represents the maximum value in any subset ‘s’ whereas min(s) represents the minimum value in the set ‘s’. We need to find the sum of max(s)-min(s) for all possible subsets.
Examples:
Input : arr[] = {1, 2, 3}
Output : result = 6
Explanation :
All possible subset and for each subset s,
max(s)-min(s) are as :
SUBSET | max(s) | min(s) | max(s)-min(s)
{1, 2} | 2 | 1 | 1
{1, 3} | 3 | 1 | 2
{2, 3} | 3 | 2 | 1
{1, 2, 3} | 3 | 1 | 2
Total Difference sum = 6
Note : max(s) - min(s) for all subset with
single element must be zero.
Input : arr[] = {1, 2, 2}
Output : result = 3
Explanation :
All possible subset and for each subset s,
max(s)-min(s) are as :
SUBSET | max(s) | min(s)| max(s)-min(s)
{1, 2} | 2 | 1 | 1
{1, 2} | 2 | 1 | 1
{2, 2} | 2 | 2 | 0
{1, 2, 2} | 2 | 1 | 1
Total Difference sum = 3
Basic Approach: Compute the sum of the maximum element of each subset, and the sum of the minimum element of each subset separately, and then subtract the minimum sum from the maximum to get the answer. The sum of the maximum/ minimum element of each subset can be computed easily by iterating through the elements of each subset. But as we have to iterate through all subsets the time complexity for this approach is exponential O(n2^n).Efficient Approach: As we have to compute the sum of the maximum element of each subset, and the sum of the minimum element of each subset separately here is an efficient way to perform this calculation. Sum of Minimum Elements of All Subsets: Let us say that the elements of arr[] in non-decreasing order are {a1,a2,..., an}. Now, we can partition the subsets of arr[] into the following categories:
Subsets containing element a1: These subsets can be obtained by taking any subset of {a2,a3,..., an} and then adding a1 into it. The number of such subsets will be 2n-1, and they all have a1 as their minimum element.
Subsets not containing element a1, but containing a2: These subsets can be obtained by taking any subset of {a3, a4,...,an}, and then adding a2 into it. The number of such subsets will be 2n-2, and they all have a2 as their minimum element.
.....
Subsets not containing elements a1, a2,..., ai-1 but containing ai: These subsets can be obtained by taking any subset of {ai+1,ai+2,..., an}, and then adding ai into it. The number of such subsets will be 2n-i, and they all have ai as their minimum element.
it can be seen that the above iteration is complete, i.e., it considers each subset exactly once. Hence, the sum of the minimum element of all subsets will be:min_sum = a1*2n-1 + a2*2n-2 + ... + an*20 This sum can be computed easily in linear time with help of the Horner method...Similarly, we can compute the sum of the maximum element of all subsets of arr[]. The only difference is that we need to iterate the elements of arr[] in non-increasing order. Note: We may have a large answer, so we have to calculate the answer with mod 10^9 +7.
C++
Java
Python3
C#
PHP
Javascript
// CPP for finding max min difference// from all subset of given set#include <bits/stdc++.h>using namespace std; const long long int MOD = 1000000007; // function for sum of max min difference int maxMin (int arr[], int n) { // sort all numbers sort(arr, arr + n); // iterate over array and with help of // horner's rule calc max_sum and min_sum long long int min_sum = 0, max_sum = 0; for (int i = 0; i < n; i++) { max_sum = 2 * max_sum + arr[n-1-i]; max_sum %= MOD; min_sum = 2 * min_sum + arr[i]; min_sum %= MOD; } return (max_sum - min_sum + MOD) % MOD;} // Driver Codeint main(){ int arr[] = {1, 2, 3, 4}; int n = sizeof(arr) / sizeof(arr[0]); cout << maxMin(arr,n); return 0;}
// JAVA Code for Find the sum of maximum // difference possible from all subset // of a given array.import java.util.*; class GFG { public static int MOD = 1000000007; // function for sum of max min difference public static long maxMin (int arr[], int n) { // sort all numbers Arrays.sort(arr); // iterate over array and with help of // horner's rule calc max_sum and min_sum long min_sum = 0, max_sum = 0; for (int i = 0; i < n; i++) { max_sum = 2 * max_sum + arr[n - 1 - i]; max_sum %= MOD; min_sum = 2 * min_sum + arr[i]; min_sum %= MOD; } return (max_sum - min_sum + MOD)%MOD; } // Driver Code public static void main(String[] args) { int arr[] = {1, 2, 3, 4}; int n = arr.length; System.out.println(maxMin(arr, n)); }} // This code is contributed by Arnav Kr. Mandal.
# python for finding max min difference#from all subset of given set MOD = 1000000007; # function for sum of max min difference def maxMin (arr,n): # sort all numbers arr.sort() # iterate over array and with help of # horner's rule calc max_sum and min_sum min_sum = 0 max_sum = 0 for i in range(0,n): max_sum = 2 * max_sum + arr[n-1-i]; max_sum %= MOD; min_sum = 2 * min_sum + arr[i]; min_sum %= MOD; return (max_sum - min_sum + MOD) % MOD; # Driver Codearr = [1, 2, 3, 4]n = len(arr)print( maxMin(arr, n)) # This code is contributed by Sam007.
// C# Code to Find the sum of maximum // difference possible from all subset // of a given array.using System; class GFG { public static int MOD = 1000000007; // function for sum of max min difference public static long maxMin (int []arr, int n) { // sort all numbers Array.Sort(arr); // iterate over array and with help of // horner's rule calc max_sum and min_sum long min_sum = 0, max_sum = 0; for (int i = 0; i < n; i++) { max_sum = 2 * max_sum + arr[n - 1 - i]; max_sum %= MOD; min_sum = 2 * min_sum + arr[i]; min_sum %= MOD; } return (max_sum - min_sum + MOD) % MOD; } // Driver Code public static void Main() { int []arr = {1, 2, 3, 4}; int n = arr.Length; Console.Write(maxMin(arr, n)); }} // This code is contributed by nitin mittal
<?php// PHP for finding max min difference// from all subset of given set$MOD = 1000000007; // function for sum of // max min difference function maxMin ($arr, $n) { global $MOD; // sort all numbers sort($arr); // iterate over array // and with help of // horner's rule calc // max_sum and min_sum $min_sum = 0; $max_sum = 0; for ($i = 0; $i < $n;$i++) { $max_sum = 2 * $max_sum + $arr[$n - 1 - $i]; $max_sum %= $MOD; $min_sum = 2 * $min_sum + $arr[$i]; $min_sum %= $MOD; } return ($max_sum - $min_sum + $MOD) % $MOD;} // Driver Code$arr = array(1, 2, 3, 4);$n = count($arr);echo maxMin($arr, $n); // This code is contributed by vt_m. ?>
<script> // Javascript for finding max min difference// from all subset of given set var MOD = 1000000007; // function for sum of max min difference function maxMin (arr, n) { // sort all numbers arr.sort((a,b)=> a-b); // iterate over array and with help of // horner's rule calc max_sum and min_sum var min_sum = 0, max_sum = 0; for (var i = 0; i < n; i++) { max_sum = 2 * max_sum + arr[n-1-i]; max_sum %= MOD; min_sum = 2 * min_sum + arr[i]; min_sum %= MOD; } return (max_sum - min_sum + MOD) % MOD;} // Driver Codevar arr = [1, 2, 3, 4];var n = arr.length;document.write( maxMin(arr,n)); </script>
Output:
23
This article is contributed by Shivam Pradhan (anuj_charm). 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.
nitin mittal
vt_m
Sam007
987saurabhpatel
itsok
Arrays
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Introduction to Arrays
Linear Search
Maximum and minimum of an array using minimum number of comparisons
Python | Using 2D arrays/lists the right way
Linked List vs Array
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Queue | Set 1 (Introduction and Array Implementation) | [
{
"code": null,
"e": 24886,
"s": 24858,
"text": "\n18 Nov, 2021"
},
{
"code": null,
"e": 25245,
"s": 24886,
"text": "We are given an array arr[] of n non-negative integers (repeated elements allowed), find out the sum of maximum difference possible from all subsets of the given array. Suppose max(s) represents the maximum value in any subset ‘s’ whereas min(s) represents the minimum value in the set ‘s’. We need to find the sum of max(s)-min(s) for all possible subsets. "
},
{
"code": null,
"e": 25256,
"s": 25245,
"text": "Examples: "
},
{
"code": null,
"e": 26001,
"s": 25256,
"text": "Input : arr[] = {1, 2, 3}\nOutput : result = 6\n\nExplanation : \nAll possible subset and for each subset s,\nmax(s)-min(s) are as :\nSUBSET | max(s) | min(s) | max(s)-min(s)\n{1, 2} | 2 | 1 | 1\n{1, 3} | 3 | 1 | 2\n{2, 3} | 3 | 2 | 1\n{1, 2, 3} | 3 | 1 | 2\nTotal Difference sum = 6\nNote : max(s) - min(s) for all subset with \nsingle element must be zero.\n\nInput : arr[] = {1, 2, 2}\nOutput : result = 3\n\nExplanation : \nAll possible subset and for each subset s,\nmax(s)-min(s) are as :\n SUBSET | max(s) | min(s)| max(s)-min(s)\n {1, 2} | 2 | 1 | 1\n {1, 2} | 2 | 1 | 1\n {2, 2} | 2 | 2 | 0\n{1, 2, 2} | 2 | 1 | 1\nTotal Difference sum = 3"
},
{
"code": null,
"e": 26842,
"s": 26001,
"text": "Basic Approach: Compute the sum of the maximum element of each subset, and the sum of the minimum element of each subset separately, and then subtract the minimum sum from the maximum to get the answer. The sum of the maximum/ minimum element of each subset can be computed easily by iterating through the elements of each subset. But as we have to iterate through all subsets the time complexity for this approach is exponential O(n2^n).Efficient Approach: As we have to compute the sum of the maximum element of each subset, and the sum of the minimum element of each subset separately here is an efficient way to perform this calculation. Sum of Minimum Elements of All Subsets: Let us say that the elements of arr[] in non-decreasing order are {a1,a2,..., an}. Now, we can partition the subsets of arr[] into the following categories: "
},
{
"code": null,
"e": 27059,
"s": 26842,
"text": "Subsets containing element a1: These subsets can be obtained by taking any subset of {a2,a3,..., an} and then adding a1 into it. The number of such subsets will be 2n-1, and they all have a1 as their minimum element."
},
{
"code": null,
"e": 27300,
"s": 27059,
"text": "Subsets not containing element a1, but containing a2: These subsets can be obtained by taking any subset of {a3, a4,...,an}, and then adding a2 into it. The number of such subsets will be 2n-2, and they all have a2 as their minimum element."
},
{
"code": null,
"e": 27306,
"s": 27300,
"text": "....."
},
{
"code": null,
"e": 27565,
"s": 27306,
"text": "Subsets not containing elements a1, a2,..., ai-1 but containing ai: These subsets can be obtained by taking any subset of {ai+1,ai+2,..., an}, and then adding ai into it. The number of such subsets will be 2n-i, and they all have ai as their minimum element."
},
{
"code": null,
"e": 28110,
"s": 27565,
"text": "it can be seen that the above iteration is complete, i.e., it considers each subset exactly once. Hence, the sum of the minimum element of all subsets will be:min_sum = a1*2n-1 + a2*2n-2 + ... + an*20 This sum can be computed easily in linear time with help of the Horner method...Similarly, we can compute the sum of the maximum element of all subsets of arr[]. The only difference is that we need to iterate the elements of arr[] in non-increasing order. Note: We may have a large answer, so we have to calculate the answer with mod 10^9 +7. "
},
{
"code": null,
"e": 28114,
"s": 28110,
"text": "C++"
},
{
"code": null,
"e": 28119,
"s": 28114,
"text": "Java"
},
{
"code": null,
"e": 28127,
"s": 28119,
"text": "Python3"
},
{
"code": null,
"e": 28130,
"s": 28127,
"text": "C#"
},
{
"code": null,
"e": 28134,
"s": 28130,
"text": "PHP"
},
{
"code": null,
"e": 28145,
"s": 28134,
"text": "Javascript"
},
{
"code": "// CPP for finding max min difference// from all subset of given set#include <bits/stdc++.h>using namespace std; const long long int MOD = 1000000007; // function for sum of max min difference int maxMin (int arr[], int n) { // sort all numbers sort(arr, arr + n); // iterate over array and with help of // horner's rule calc max_sum and min_sum long long int min_sum = 0, max_sum = 0; for (int i = 0; i < n; i++) { max_sum = 2 * max_sum + arr[n-1-i]; max_sum %= MOD; min_sum = 2 * min_sum + arr[i]; min_sum %= MOD; } return (max_sum - min_sum + MOD) % MOD;} // Driver Codeint main(){ int arr[] = {1, 2, 3, 4}; int n = sizeof(arr) / sizeof(arr[0]); cout << maxMin(arr,n); return 0;} ",
"e": 28908,
"s": 28145,
"text": null
},
{
"code": "// JAVA Code for Find the sum of maximum // difference possible from all subset // of a given array.import java.util.*; class GFG { public static int MOD = 1000000007; // function for sum of max min difference public static long maxMin (int arr[], int n) { // sort all numbers Arrays.sort(arr); // iterate over array and with help of // horner's rule calc max_sum and min_sum long min_sum = 0, max_sum = 0; for (int i = 0; i < n; i++) { max_sum = 2 * max_sum + arr[n - 1 - i]; max_sum %= MOD; min_sum = 2 * min_sum + arr[i]; min_sum %= MOD; } return (max_sum - min_sum + MOD)%MOD; } // Driver Code public static void main(String[] args) { int arr[] = {1, 2, 3, 4}; int n = arr.length; System.out.println(maxMin(arr, n)); }} // This code is contributed by Arnav Kr. Mandal.",
"e": 29888,
"s": 28908,
"text": null
},
{
"code": "# python for finding max min difference#from all subset of given set MOD = 1000000007; # function for sum of max min difference def maxMin (arr,n): # sort all numbers arr.sort() # iterate over array and with help of # horner's rule calc max_sum and min_sum min_sum = 0 max_sum = 0 for i in range(0,n): max_sum = 2 * max_sum + arr[n-1-i]; max_sum %= MOD; min_sum = 2 * min_sum + arr[i]; min_sum %= MOD; return (max_sum - min_sum + MOD) % MOD; # Driver Codearr = [1, 2, 3, 4]n = len(arr)print( maxMin(arr, n)) # This code is contributed by Sam007.",
"e": 30519,
"s": 29888,
"text": null
},
{
"code": " // C# Code to Find the sum of maximum // difference possible from all subset // of a given array.using System; class GFG { public static int MOD = 1000000007; // function for sum of max min difference public static long maxMin (int []arr, int n) { // sort all numbers Array.Sort(arr); // iterate over array and with help of // horner's rule calc max_sum and min_sum long min_sum = 0, max_sum = 0; for (int i = 0; i < n; i++) { max_sum = 2 * max_sum + arr[n - 1 - i]; max_sum %= MOD; min_sum = 2 * min_sum + arr[i]; min_sum %= MOD; } return (max_sum - min_sum + MOD) % MOD; } // Driver Code public static void Main() { int []arr = {1, 2, 3, 4}; int n = arr.Length; Console.Write(maxMin(arr, n)); }} // This code is contributed by nitin mittal",
"e": 31475,
"s": 30519,
"text": null
},
{
"code": "<?php// PHP for finding max min difference// from all subset of given set$MOD = 1000000007; // function for sum of // max min difference function maxMin ($arr, $n) { global $MOD; // sort all numbers sort($arr); // iterate over array // and with help of // horner's rule calc // max_sum and min_sum $min_sum = 0; $max_sum = 0; for ($i = 0; $i < $n;$i++) { $max_sum = 2 * $max_sum + $arr[$n - 1 - $i]; $max_sum %= $MOD; $min_sum = 2 * $min_sum + $arr[$i]; $min_sum %= $MOD; } return ($max_sum - $min_sum + $MOD) % $MOD;} // Driver Code$arr = array(1, 2, 3, 4);$n = count($arr);echo maxMin($arr, $n); // This code is contributed by vt_m. ?>",
"e": 32226,
"s": 31475,
"text": null
},
{
"code": "<script> // Javascript for finding max min difference// from all subset of given set var MOD = 1000000007; // function for sum of max min difference function maxMin (arr, n) { // sort all numbers arr.sort((a,b)=> a-b); // iterate over array and with help of // horner's rule calc max_sum and min_sum var min_sum = 0, max_sum = 0; for (var i = 0; i < n; i++) { max_sum = 2 * max_sum + arr[n-1-i]; max_sum %= MOD; min_sum = 2 * min_sum + arr[i]; min_sum %= MOD; } return (max_sum - min_sum + MOD) % MOD;} // Driver Codevar arr = [1, 2, 3, 4];var n = arr.length;document.write( maxMin(arr,n)); </script>",
"e": 32896,
"s": 32226,
"text": null
},
{
"code": null,
"e": 32904,
"s": 32896,
"text": "Output:"
},
{
"code": null,
"e": 32907,
"s": 32904,
"text": "23"
},
{
"code": null,
"e": 33348,
"s": 32907,
"text": "This article is contributed by Shivam Pradhan (anuj_charm). 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. "
},
{
"code": null,
"e": 33361,
"s": 33348,
"text": "nitin mittal"
},
{
"code": null,
"e": 33366,
"s": 33361,
"text": "vt_m"
},
{
"code": null,
"e": 33373,
"s": 33366,
"text": "Sam007"
},
{
"code": null,
"e": 33389,
"s": 33373,
"text": "987saurabhpatel"
},
{
"code": null,
"e": 33395,
"s": 33389,
"text": "itsok"
},
{
"code": null,
"e": 33402,
"s": 33395,
"text": "Arrays"
},
{
"code": null,
"e": 33409,
"s": 33402,
"text": "Arrays"
},
{
"code": null,
"e": 33507,
"s": 33409,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33516,
"s": 33507,
"text": "Comments"
},
{
"code": null,
"e": 33529,
"s": 33516,
"text": "Old Comments"
},
{
"code": null,
"e": 33577,
"s": 33529,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 33621,
"s": 33577,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 33653,
"s": 33621,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 33676,
"s": 33653,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 33690,
"s": 33676,
"text": "Linear Search"
},
{
"code": null,
"e": 33758,
"s": 33690,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 33803,
"s": 33758,
"text": "Python | Using 2D arrays/lists the right way"
},
{
"code": null,
"e": 33824,
"s": 33803,
"text": "Linked List vs Array"
},
{
"code": null,
"e": 33909,
"s": 33824,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
}
] |
How to avoid the warning “Cannot compute exact p-value with ties” while perform correlation test for Spearman’s correlation in R? | When the variables are not continuous but could be ranked then we do not use pearson correlation coefficient to find the linear relationship, in this case spearman correlation coefficient comes into the scene. Since the spearman correlation coefficient considers the rank of values, the correlation test ignores the same ranks to find the p-values as a result we get the warning “Cannot compute exact p-value with ties”. This can be avoided by using exact = FALSE inside the cor.test function.
Consider the below vectors and perform spearman correlation test to check the relationship between them −
Live Demo
x1<-rpois(20,2)
y1<-rpois(20,5)
cor.test(x1,y1,method="spearman")
Spearman's rank correlation rho
data: x1 and y1
S = 1401.7, p-value = 0.8214
alternative hypothesis: true rho is not equal to 0
sample estimates:
rho
-0.05390585
Warning message:
In cor.test.default(x1, y1, method = "spearman") :
Cannot compute exact p-value with ties
Here, we have the warning for ties, this can be avoided by using exact=FALSE as shown below −
cor.test(x1,y1,method="spearman",exact=FALSE)
Spearman's rank correlation rho
data: x1 and y1
S = 1401.7, p-value = 0.8214
alternative hypothesis: true rho is not equal to 0
sample estimates:
rho
-0.05390585
Let’s have a look at some more examples −
Live Demo
x2<-sample(1:100,500,replace=TRUE)
y2<-sample(1:50,500,replace=TRUE)
cor.test(x2,y2,method="spearman")
Spearman's rank correlation rho
data: x2 and y2
S = 20110148, p-value = 0.4387
alternative hypothesis: true rho is not equal to 0
sample estimates:
rho
0.03470902
Warning message:
In cor.test.default(x2, y2, method = "spearman") :
Cannot compute exact p-value with ties
cor.test(x2,y2,method="spearman",exact=FALSE)
Spearman's rank correlation rho
data: x2 and y2
S = 20110148, p-value = 0.4387
alternative hypothesis: true rho is not equal to 0
sample estimates:
rho
0.03470902
Live Demo
x3<-sample(101:110,5000,replace=TRUE)
y3<-sample(501:510,5000,replace=TRUE)
cor.test(x3,y3,method="spearman")
Spearman's rank correlation rho
data: x3 and y3
S = 2.0642e+10, p-value = 0.5155
alternative hypothesis: true rho is not equal to 0
sample estimates:
rho
0.009199129
Warning message:
In cor.test.default(x3, y3, method = "spearman") :
Cannot compute exact p-value with ties
cor.test(x3,y3,method="spearman",exact=FALSE)
Spearman's rank correlation rho
data: x3 and y3
S = 2.0642e+10, p-value = 0.5155
alternative hypothesis: true rho is not equal to 0
sample estimates:
rho
0.009199129 | [
{
"code": null,
"e": 1556,
"s": 1062,
"text": "When the variables are not continuous but could be ranked then we do not use pearson correlation coefficient to find the linear relationship, in this case spearman correlation coefficient comes into the scene. Since the spearman correlation coefficient considers the rank of values, the correlation test ignores the same ranks to find the p-values as a result we get the warning “Cannot compute exact p-value with ties”. This can be avoided by using exact = FALSE inside the cor.test function."
},
{
"code": null,
"e": 1662,
"s": 1556,
"text": "Consider the below vectors and perform spearman correlation test to check the relationship between them −"
},
{
"code": null,
"e": 1673,
"s": 1662,
"text": " Live Demo"
},
{
"code": null,
"e": 1739,
"s": 1673,
"text": "x1<-rpois(20,2)\ny1<-rpois(20,5)\ncor.test(x1,y1,method=\"spearman\")"
},
{
"code": null,
"e": 2014,
"s": 1739,
"text": " Spearman's rank correlation rho\ndata: x1 and y1\nS = 1401.7, p-value = 0.8214\nalternative hypothesis: true rho is not equal to 0\nsample estimates:\n rho\n-0.05390585\nWarning message:\nIn cor.test.default(x1, y1, method = \"spearman\") :\nCannot compute exact p-value with ties"
},
{
"code": null,
"e": 2108,
"s": 2014,
"text": "Here, we have the warning for ties, this can be avoided by using exact=FALSE as shown below −"
},
{
"code": null,
"e": 2154,
"s": 2108,
"text": "cor.test(x1,y1,method=\"spearman\",exact=FALSE)"
},
{
"code": null,
"e": 2322,
"s": 2154,
"text": " Spearman's rank correlation rho\ndata: x1 and y1\nS = 1401.7, p-value = 0.8214\nalternative hypothesis: true rho is not equal to 0\nsample estimates:\n rho\n-0.05390585"
},
{
"code": null,
"e": 2364,
"s": 2322,
"text": "Let’s have a look at some more examples −"
},
{
"code": null,
"e": 2375,
"s": 2364,
"text": " Live Demo"
},
{
"code": null,
"e": 2478,
"s": 2375,
"text": "x2<-sample(1:100,500,replace=TRUE)\ny2<-sample(1:50,500,replace=TRUE)\ncor.test(x2,y2,method=\"spearman\")"
},
{
"code": null,
"e": 2754,
"s": 2478,
"text": " Spearman's rank correlation rho\ndata: x2 and y2\nS = 20110148, p-value = 0.4387\nalternative hypothesis: true rho is not equal to 0\nsample estimates:\n rho\n0.03470902\nWarning message:\nIn cor.test.default(x2, y2, method = \"spearman\") :\nCannot compute exact p-value with ties"
},
{
"code": null,
"e": 2800,
"s": 2754,
"text": "cor.test(x2,y2,method=\"spearman\",exact=FALSE)"
},
{
"code": null,
"e": 2969,
"s": 2800,
"text": " Spearman's rank correlation rho\ndata: x2 and y2\nS = 20110148, p-value = 0.4387\nalternative hypothesis: true rho is not equal to 0\nsample estimates:\n rho\n0.03470902"
},
{
"code": null,
"e": 2980,
"s": 2969,
"text": " Live Demo"
},
{
"code": null,
"e": 3090,
"s": 2980,
"text": "x3<-sample(101:110,5000,replace=TRUE)\ny3<-sample(501:510,5000,replace=TRUE)\ncor.test(x3,y3,method=\"spearman\")"
},
{
"code": null,
"e": 3369,
"s": 3090,
"text": " Spearman's rank correlation rho\ndata: x3 and y3\nS = 2.0642e+10, p-value = 0.5155\nalternative hypothesis: true rho is not equal to 0\nsample estimates:\n rho\n0.009199129\nWarning message:\nIn cor.test.default(x3, y3, method = \"spearman\") :\nCannot compute exact p-value with ties"
},
{
"code": null,
"e": 3415,
"s": 3369,
"text": "cor.test(x3,y3,method=\"spearman\",exact=FALSE)"
},
{
"code": null,
"e": 3587,
"s": 3415,
"text": " Spearman's rank correlation rho\ndata: x3 and y3\nS = 2.0642e+10, p-value = 0.5155\nalternative hypothesis: true rho is not equal to 0\nsample estimates:\n rho\n0.009199129"
}
] |
Python os.chown() Method | Python method chown() changes the owner and group id of path to the numeric uid and gid. To leave one of the ids unchanged, set it to -1.To set ownership, you would need super user privilege..
Following is the syntax for chown() method −
os.chown(path, uid, gid);
path − This is the path for which owner id and group id need to be setup.
path − This is the path for which owner id and group id need to be setup.
uid − This is Owner ID to be set for the file.
uid − This is Owner ID to be set for the file.
gid − This is Group ID to be set for the file.
gid − This is Group ID to be set for the file.
This method does not return any value.
The following example shows the usage of chown() method.
#!/usr/bin/python
import os, sys
# Assuming /tmp/foo.txt exists.
# To set owner ID 100 following has to be done.
os.chown("/tmp/foo.txt", 100, -1)
print "Changed ownership successfully!!"
When we run above program, it produces following result −
Changed ownership successfully!!
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2437,
"s": 2244,
"text": "Python method chown() changes the owner and group id of path to the numeric uid and gid. To leave one of the ids unchanged, set it to -1.To set ownership, you would need super user privilege.."
},
{
"code": null,
"e": 2482,
"s": 2437,
"text": "Following is the syntax for chown() method −"
},
{
"code": null,
"e": 2509,
"s": 2482,
"text": "os.chown(path, uid, gid);\n"
},
{
"code": null,
"e": 2583,
"s": 2509,
"text": "path − This is the path for which owner id and group id need to be setup."
},
{
"code": null,
"e": 2657,
"s": 2583,
"text": "path − This is the path for which owner id and group id need to be setup."
},
{
"code": null,
"e": 2704,
"s": 2657,
"text": "uid − This is Owner ID to be set for the file."
},
{
"code": null,
"e": 2751,
"s": 2704,
"text": "uid − This is Owner ID to be set for the file."
},
{
"code": null,
"e": 2798,
"s": 2751,
"text": "gid − This is Group ID to be set for the file."
},
{
"code": null,
"e": 2845,
"s": 2798,
"text": "gid − This is Group ID to be set for the file."
},
{
"code": null,
"e": 2884,
"s": 2845,
"text": "This method does not return any value."
},
{
"code": null,
"e": 2941,
"s": 2884,
"text": "The following example shows the usage of chown() method."
},
{
"code": null,
"e": 3132,
"s": 2941,
"text": "#!/usr/bin/python\n\nimport os, sys\n\n# Assuming /tmp/foo.txt exists.\n# To set owner ID 100 following has to be done.\nos.chown(\"/tmp/foo.txt\", 100, -1)\n\nprint \"Changed ownership successfully!!\""
},
{
"code": null,
"e": 3190,
"s": 3132,
"text": "When we run above program, it produces following result −"
},
{
"code": null,
"e": 3224,
"s": 3190,
"text": "Changed ownership successfully!!\n"
},
{
"code": null,
"e": 3261,
"s": 3224,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 3277,
"s": 3261,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3310,
"s": 3277,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 3329,
"s": 3310,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3364,
"s": 3329,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 3386,
"s": 3364,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 3420,
"s": 3386,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 3448,
"s": 3420,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3483,
"s": 3448,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 3497,
"s": 3483,
"text": " Lets Kode It"
},
{
"code": null,
"e": 3530,
"s": 3497,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3547,
"s": 3530,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 3554,
"s": 3547,
"text": " Print"
},
{
"code": null,
"e": 3565,
"s": 3554,
"text": " Add Notes"
}
] |
Difference Between Inline and Macro in C++ | In this post, we will understand the difference between inline and macro in C++.
It is a function in C++.
It is a function in C++.
It is parsed by the compiler.
It is parsed by the compiler.
It can be defined inside or outside the class.
It can be defined inside or outside the class.
It evaluates the argument only once.
It evaluates the argument only once.
The compiler may not convert all functions to ‘inline’ function and expand them all.
The compiler may not convert all functions to ‘inline’ function and expand them all.
The short functions that are defined inside the class are automatically made as inline functions.
The short functions that are defined inside the class are automatically made as inline functions.
An inline function inside a class can access the data members of the class.
An inline function inside a class can access the data members of the class.
Inline function can be terminated using curly brackets.
Inline function can be terminated using curly brackets.
It is easy to debug.
It is easy to debug.
This is because error checking is done during compilation.
This is because error checking is done during compilation.
It binds all statements in the body of the function.
It binds all statements in the body of the function.
inline return_type funct_name ( parameters ) {
. . .
}
It is expanded by the preprocessor.
It is expanded by the preprocessor.
It is defined at the beginning of the program.
It is defined at the beginning of the program.
It evaluates the argument every time it is used inside the code.
It evaluates the argument every time it is used inside the code.
They always need to be/are expanded.
They always need to be/are expanded.
They need to be defined specifically.
They need to be defined specifically.
They will never become members of class.
They will never become members of class.
They can’t access data members of the class.
They can’t access data members of the class.
Definition of macro ends with the new line.
Definition of macro ends with the new line.
It is difficult to debug macros since error checking doesn’t happen during compile time.
It is difficult to debug macros since error checking doesn’t happen during compile time.
It encounters binding problem if it contains more than one statement since it doesn’t have a termination symbol.
It encounters binding problem if it contains more than one statement since it doesn’t have a termination symbol.
#define macro_name char_sequence | [
{
"code": null,
"e": 1143,
"s": 1062,
"text": "In this post, we will understand the difference between inline and macro in C++."
},
{
"code": null,
"e": 1168,
"s": 1143,
"text": "It is a function in C++."
},
{
"code": null,
"e": 1193,
"s": 1168,
"text": "It is a function in C++."
},
{
"code": null,
"e": 1223,
"s": 1193,
"text": "It is parsed by the compiler."
},
{
"code": null,
"e": 1253,
"s": 1223,
"text": "It is parsed by the compiler."
},
{
"code": null,
"e": 1300,
"s": 1253,
"text": "It can be defined inside or outside the class."
},
{
"code": null,
"e": 1347,
"s": 1300,
"text": "It can be defined inside or outside the class."
},
{
"code": null,
"e": 1384,
"s": 1347,
"text": "It evaluates the argument only once."
},
{
"code": null,
"e": 1421,
"s": 1384,
"text": "It evaluates the argument only once."
},
{
"code": null,
"e": 1506,
"s": 1421,
"text": "The compiler may not convert all functions to ‘inline’ function and expand them all."
},
{
"code": null,
"e": 1591,
"s": 1506,
"text": "The compiler may not convert all functions to ‘inline’ function and expand them all."
},
{
"code": null,
"e": 1689,
"s": 1591,
"text": "The short functions that are defined inside the class are automatically made as inline functions."
},
{
"code": null,
"e": 1787,
"s": 1689,
"text": "The short functions that are defined inside the class are automatically made as inline functions."
},
{
"code": null,
"e": 1863,
"s": 1787,
"text": "An inline function inside a class can access the data members of the class."
},
{
"code": null,
"e": 1939,
"s": 1863,
"text": "An inline function inside a class can access the data members of the class."
},
{
"code": null,
"e": 1995,
"s": 1939,
"text": "Inline function can be terminated using curly brackets."
},
{
"code": null,
"e": 2051,
"s": 1995,
"text": "Inline function can be terminated using curly brackets."
},
{
"code": null,
"e": 2072,
"s": 2051,
"text": "It is easy to debug."
},
{
"code": null,
"e": 2093,
"s": 2072,
"text": "It is easy to debug."
},
{
"code": null,
"e": 2152,
"s": 2093,
"text": "This is because error checking is done during compilation."
},
{
"code": null,
"e": 2211,
"s": 2152,
"text": "This is because error checking is done during compilation."
},
{
"code": null,
"e": 2264,
"s": 2211,
"text": "It binds all statements in the body of the function."
},
{
"code": null,
"e": 2317,
"s": 2264,
"text": "It binds all statements in the body of the function."
},
{
"code": null,
"e": 2375,
"s": 2317,
"text": "inline return_type funct_name ( parameters ) {\n . . .\n}"
},
{
"code": null,
"e": 2411,
"s": 2375,
"text": "It is expanded by the preprocessor."
},
{
"code": null,
"e": 2447,
"s": 2411,
"text": "It is expanded by the preprocessor."
},
{
"code": null,
"e": 2494,
"s": 2447,
"text": "It is defined at the beginning of the program."
},
{
"code": null,
"e": 2541,
"s": 2494,
"text": "It is defined at the beginning of the program."
},
{
"code": null,
"e": 2606,
"s": 2541,
"text": "It evaluates the argument every time it is used inside the code."
},
{
"code": null,
"e": 2671,
"s": 2606,
"text": "It evaluates the argument every time it is used inside the code."
},
{
"code": null,
"e": 2708,
"s": 2671,
"text": "They always need to be/are expanded."
},
{
"code": null,
"e": 2745,
"s": 2708,
"text": "They always need to be/are expanded."
},
{
"code": null,
"e": 2783,
"s": 2745,
"text": "They need to be defined specifically."
},
{
"code": null,
"e": 2821,
"s": 2783,
"text": "They need to be defined specifically."
},
{
"code": null,
"e": 2862,
"s": 2821,
"text": "They will never become members of class."
},
{
"code": null,
"e": 2903,
"s": 2862,
"text": "They will never become members of class."
},
{
"code": null,
"e": 2948,
"s": 2903,
"text": "They can’t access data members of the class."
},
{
"code": null,
"e": 2993,
"s": 2948,
"text": "They can’t access data members of the class."
},
{
"code": null,
"e": 3037,
"s": 2993,
"text": "Definition of macro ends with the new line."
},
{
"code": null,
"e": 3081,
"s": 3037,
"text": "Definition of macro ends with the new line."
},
{
"code": null,
"e": 3170,
"s": 3081,
"text": "It is difficult to debug macros since error checking doesn’t happen during compile time."
},
{
"code": null,
"e": 3259,
"s": 3170,
"text": "It is difficult to debug macros since error checking doesn’t happen during compile time."
},
{
"code": null,
"e": 3372,
"s": 3259,
"text": "It encounters binding problem if it contains more than one statement since it doesn’t have a termination symbol."
},
{
"code": null,
"e": 3485,
"s": 3372,
"text": "It encounters binding problem if it contains more than one statement since it doesn’t have a termination symbol."
},
{
"code": null,
"e": 3518,
"s": 3485,
"text": "#define macro_name char_sequence"
}
] |
MFC - Button | A button is an object that the user clicks to initiate an action. Button control is represented by CButton class.
Create
Creates the Windows button control and attaches it to the CButton object.
DrawItem
Override to draw an owner-drawn CButton object.
GetBitmap
Retrieves the handle of the bitmap previously set with SetBitmap.
GetButtonStyle
Retrieves information about the button control style.
GetCheck
Retrieves the check state of a button control.
GetCursor
Retrieves the handle of the cursor image previously set with SetCursor.
GetIcon
Retrieves the handle of the icon previously set with SetIcon.
GetIdealSize
Retrieves the ideal size of the button control.
GetImageList
Retrieves the image list of the button control.
GetNote
Retrieves the note component of the current command link control.
GetNoteLength
Retrieves the length of the note text for the current command link control.
GetSplitGlyph
Retrieves the glyph associated with the current split button control.
GetSplitImageList
Retrieves the image list for the current split button control.
GetSplitInfo
Retrieves information that defines the current split button control.
GetSplitSize
Retrieves the bounding rectangle of the drop-down component of the current split button control.
GetSplitStyle
Retrieves the split button styles that define the current split button control.
GetState
Retrieves the check state, highlight state, and focus state of a button control.
GetTextMargin
Retrieves the text margin of the button control.
SetBitmap
Specifies a bitmap to be displayed on the button.
SetButtonStyle
Changes the style of a button.
SetCheck
Sets the check state of a button control.
SetCursor
Specifies a cursor image to be displayed on the button.
SetDropDownState
Sets the drop-down state of the current split button control.
SetIcon
Specifies an icon to be displayed on the button.
SetImageList
Sets the image list of the button control.
SetNote
Sets the note on the current command link control.
SetSplitGlyph
Associates a specified glyph with the current split button control.
SetSplitImageList
Associates an image list with the current split button control.
SetSplitInfo
Specifies information that defines the current split button control.
SetSplitSize
Sets the bounding rectangle of the drop-down component of the current split button control.
SetSplitStyle
Sets the style of the current split button control.
SetState
Sets the highlighting state of a button control.
SetTextMargin
Sets the text margin of the button control.
Here is the list of messages mapping for Button control −
Let us look into a simple example by dragging two buttons from the Toolbox.
Step 1 − Change the Caption from Start, Stop and ID to IDC_BUTTON_START, IDC_BUTTON_STOP for both buttons.
Step 2 − Let us add event handler for both buttons.
Step 3 − Here is an implementation of both events in which we will start and stop animation.
void CMFCAnimationDemoDlg::OnBnClickedButtonStart() {
// TODO: Add your control notification handler code here
m_animationCtrl.Open(L"res\\copyfile.avi");
}
void CMFCAnimationDemoDlg::OnBnClickedButtonStop() {
// TODO: Add your control notification handler code here
m_animationCtrl.Stop();
}
Step 4 − When the above code is compiled and executed, you will see the following output.
Step 5 − When you click the Stop button, the animation stops and when you press the Start button, it starts again.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2181,
"s": 2067,
"text": "A button is an object that the user clicks to initiate an action. Button control is represented by CButton class."
},
{
"code": null,
"e": 2188,
"s": 2181,
"text": "Create"
},
{
"code": null,
"e": 2262,
"s": 2188,
"text": "Creates the Windows button control and attaches it to the CButton object."
},
{
"code": null,
"e": 2271,
"s": 2262,
"text": "DrawItem"
},
{
"code": null,
"e": 2319,
"s": 2271,
"text": "Override to draw an owner-drawn CButton object."
},
{
"code": null,
"e": 2329,
"s": 2319,
"text": "GetBitmap"
},
{
"code": null,
"e": 2395,
"s": 2329,
"text": "Retrieves the handle of the bitmap previously set with SetBitmap."
},
{
"code": null,
"e": 2410,
"s": 2395,
"text": "GetButtonStyle"
},
{
"code": null,
"e": 2464,
"s": 2410,
"text": "Retrieves information about the button control style."
},
{
"code": null,
"e": 2473,
"s": 2464,
"text": "GetCheck"
},
{
"code": null,
"e": 2520,
"s": 2473,
"text": "Retrieves the check state of a button control."
},
{
"code": null,
"e": 2530,
"s": 2520,
"text": "GetCursor"
},
{
"code": null,
"e": 2602,
"s": 2530,
"text": "Retrieves the handle of the cursor image previously set with SetCursor."
},
{
"code": null,
"e": 2610,
"s": 2602,
"text": "GetIcon"
},
{
"code": null,
"e": 2672,
"s": 2610,
"text": "Retrieves the handle of the icon previously set with SetIcon."
},
{
"code": null,
"e": 2685,
"s": 2672,
"text": "GetIdealSize"
},
{
"code": null,
"e": 2733,
"s": 2685,
"text": "Retrieves the ideal size of the button control."
},
{
"code": null,
"e": 2746,
"s": 2733,
"text": "GetImageList"
},
{
"code": null,
"e": 2794,
"s": 2746,
"text": "Retrieves the image list of the button control."
},
{
"code": null,
"e": 2802,
"s": 2794,
"text": "GetNote"
},
{
"code": null,
"e": 2868,
"s": 2802,
"text": "Retrieves the note component of the current command link control."
},
{
"code": null,
"e": 2882,
"s": 2868,
"text": "GetNoteLength"
},
{
"code": null,
"e": 2958,
"s": 2882,
"text": "Retrieves the length of the note text for the current command link control."
},
{
"code": null,
"e": 2972,
"s": 2958,
"text": "GetSplitGlyph"
},
{
"code": null,
"e": 3042,
"s": 2972,
"text": "Retrieves the glyph associated with the current split button control."
},
{
"code": null,
"e": 3060,
"s": 3042,
"text": "GetSplitImageList"
},
{
"code": null,
"e": 3123,
"s": 3060,
"text": "Retrieves the image list for the current split button control."
},
{
"code": null,
"e": 3136,
"s": 3123,
"text": "GetSplitInfo"
},
{
"code": null,
"e": 3205,
"s": 3136,
"text": "Retrieves information that defines the current split button control."
},
{
"code": null,
"e": 3218,
"s": 3205,
"text": "GetSplitSize"
},
{
"code": null,
"e": 3315,
"s": 3218,
"text": "Retrieves the bounding rectangle of the drop-down component of the current split button control."
},
{
"code": null,
"e": 3329,
"s": 3315,
"text": "GetSplitStyle"
},
{
"code": null,
"e": 3409,
"s": 3329,
"text": "Retrieves the split button styles that define the current split button control."
},
{
"code": null,
"e": 3418,
"s": 3409,
"text": "GetState"
},
{
"code": null,
"e": 3499,
"s": 3418,
"text": "Retrieves the check state, highlight state, and focus state of a button control."
},
{
"code": null,
"e": 3513,
"s": 3499,
"text": "GetTextMargin"
},
{
"code": null,
"e": 3562,
"s": 3513,
"text": "Retrieves the text margin of the button control."
},
{
"code": null,
"e": 3572,
"s": 3562,
"text": "SetBitmap"
},
{
"code": null,
"e": 3622,
"s": 3572,
"text": "Specifies a bitmap to be displayed on the button."
},
{
"code": null,
"e": 3637,
"s": 3622,
"text": "SetButtonStyle"
},
{
"code": null,
"e": 3668,
"s": 3637,
"text": "Changes the style of a button."
},
{
"code": null,
"e": 3677,
"s": 3668,
"text": "SetCheck"
},
{
"code": null,
"e": 3719,
"s": 3677,
"text": "Sets the check state of a button control."
},
{
"code": null,
"e": 3729,
"s": 3719,
"text": "SetCursor"
},
{
"code": null,
"e": 3785,
"s": 3729,
"text": "Specifies a cursor image to be displayed on the button."
},
{
"code": null,
"e": 3802,
"s": 3785,
"text": "SetDropDownState"
},
{
"code": null,
"e": 3864,
"s": 3802,
"text": "Sets the drop-down state of the current split button control."
},
{
"code": null,
"e": 3872,
"s": 3864,
"text": "SetIcon"
},
{
"code": null,
"e": 3921,
"s": 3872,
"text": "Specifies an icon to be displayed on the button."
},
{
"code": null,
"e": 3934,
"s": 3921,
"text": "SetImageList"
},
{
"code": null,
"e": 3977,
"s": 3934,
"text": "Sets the image list of the button control."
},
{
"code": null,
"e": 3985,
"s": 3977,
"text": "SetNote"
},
{
"code": null,
"e": 4036,
"s": 3985,
"text": "Sets the note on the current command link control."
},
{
"code": null,
"e": 4050,
"s": 4036,
"text": "SetSplitGlyph"
},
{
"code": null,
"e": 4118,
"s": 4050,
"text": "Associates a specified glyph with the current split button control."
},
{
"code": null,
"e": 4136,
"s": 4118,
"text": "SetSplitImageList"
},
{
"code": null,
"e": 4200,
"s": 4136,
"text": "Associates an image list with the current split button control."
},
{
"code": null,
"e": 4213,
"s": 4200,
"text": "SetSplitInfo"
},
{
"code": null,
"e": 4282,
"s": 4213,
"text": "Specifies information that defines the current split button control."
},
{
"code": null,
"e": 4295,
"s": 4282,
"text": "SetSplitSize"
},
{
"code": null,
"e": 4387,
"s": 4295,
"text": "Sets the bounding rectangle of the drop-down component of the current split button control."
},
{
"code": null,
"e": 4401,
"s": 4387,
"text": "SetSplitStyle"
},
{
"code": null,
"e": 4453,
"s": 4401,
"text": "Sets the style of the current split button control."
},
{
"code": null,
"e": 4462,
"s": 4453,
"text": "SetState"
},
{
"code": null,
"e": 4511,
"s": 4462,
"text": "Sets the highlighting state of a button control."
},
{
"code": null,
"e": 4525,
"s": 4511,
"text": "SetTextMargin"
},
{
"code": null,
"e": 4569,
"s": 4525,
"text": "Sets the text margin of the button control."
},
{
"code": null,
"e": 4627,
"s": 4569,
"text": "Here is the list of messages mapping for Button control −"
},
{
"code": null,
"e": 4703,
"s": 4627,
"text": "Let us look into a simple example by dragging two buttons from the Toolbox."
},
{
"code": null,
"e": 4810,
"s": 4703,
"text": "Step 1 − Change the Caption from Start, Stop and ID to IDC_BUTTON_START, IDC_BUTTON_STOP for both buttons."
},
{
"code": null,
"e": 4862,
"s": 4810,
"text": "Step 2 − Let us add event handler for both buttons."
},
{
"code": null,
"e": 4955,
"s": 4862,
"text": "Step 3 − Here is an implementation of both events in which we will start and stop animation."
},
{
"code": null,
"e": 5269,
"s": 4955,
"text": "void CMFCAnimationDemoDlg::OnBnClickedButtonStart() {\n \n // TODO: Add your control notification handler code here\n m_animationCtrl.Open(L\"res\\\\copyfile.avi\");\n}\n\nvoid CMFCAnimationDemoDlg::OnBnClickedButtonStop() {\n \n // TODO: Add your control notification handler code here\n m_animationCtrl.Stop();\n}"
},
{
"code": null,
"e": 5359,
"s": 5269,
"text": "Step 4 − When the above code is compiled and executed, you will see the following output."
},
{
"code": null,
"e": 5474,
"s": 5359,
"text": "Step 5 − When you click the Stop button, the animation stops and when you press the Start button, it starts again."
},
{
"code": null,
"e": 5481,
"s": 5474,
"text": " Print"
},
{
"code": null,
"e": 5492,
"s": 5481,
"text": " Add Notes"
}
] |
Spring Boot - Unit Test Cases | Unit Testing is a one of the testing done by the developers to make sure individual unit or component functionalities are working fine.
In this tutorial, we are going to see how to write a unit test case by using Mockito and Web Controller.
For injecting Mockito Mocks into Spring Beans, we need to add the Mockito-core dependency in our build configuration file.
Maven users can add the following dependency in your pom.xml file.
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>2.13.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
Gradle users can add the following dependency in the build.gradle file.
compile group: 'org.mockito', name: 'mockito-core', version: '2.13.0'
testCompile('org.springframework.boot:spring-boot-starter-test')
The code to write a Service class which contains a method that returns the String value is given here.
package com.tutorialspoint.mockitodemo;
import org.springframework.stereotype.Service;
@Service
public class ProductService {
public String getProductName() {
return "Honey";
}
}
Now, inject the ProductService class into another Service class file as shown.
package com.tutorialspoint.mockitodemo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class OrderService {
@Autowired
ProductService productService;
public OrderService(ProductService productService) {
this.productService = productService;
}
public String getProductName() {
return productService.getProductName();
}
}
The main Spring Boot application class file is given below −
package com.tutorialspoint.mockitodemo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MockitoDemoApplication {
public static void main(String[] args) {
SpringApplication.run(MockitoDemoApplication.class, args);
}
}
Then, configure the Application context for the tests. The @Profile(“test”) annotation is used to configure the class when the Test cases are running.
package com.tutorialspoint.mockitodemo;
import org.mockito.Mockito;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Profile;
@Profile("test")
@Configuration
public class ProductServiceTestConfiguration {
@Bean
@Primary
public ProductService productService() {
return Mockito.mock(ProductService.class);
}
}
Now, you can write a Unit Test case for Order Service under the src/test/resources package.
package com.tutorialspoint.mockitodemo;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@SpringBootTest
@ActiveProfiles("test")
@RunWith(SpringJUnit4ClassRunner.class)
public class MockitoDemoApplicationTests {
@Autowired
private OrderService orderService;
@Autowired
private ProductService productService;
@Test
public void whenUserIdIsProvided_thenRetrievedNameIsCorrect() {
Mockito.when(productService.getProductName()).thenReturn("Mock Product Name");
String testName = orderService.getProductName();
Assert.assertEquals("Mock Product Name", testName);
}
}
The complete code for build configuration file is given below.
Maven – pom.xml
<?xml version = "1.0" encoding = "UTF-8"?>
<project xmlns = "http://maven.apache.org/POM/4.0.0"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.tutorialspoint</groupId>
<artifactId>mockito-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>mockito-demo</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>2.13.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Gradle – build.gradle
buildscript {
ext {
springBootVersion = '1.5.9.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
group = 'com.tutorialspoint'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
compile('org.springframework.boot:spring-boot-starter')
compile group: 'org.mockito', name: 'mockito-core', version: '2.13.0'
testCompile('org.springframework.boot:spring-boot-starter-test')
}
You can create an executable JAR file, and run the Spring Boot application by using the following Maven or Gradle1 commands.
For Maven, you can use the command as shown −
mvn clean install
You can see the test results in console window.
For Gradle, you can use the command as shown −
gradle clean build
You can see the rest results in console window.
102 Lectures
8 hours
Karthikeya T
39 Lectures
5 hours
Chaand Sheikh
73 Lectures
5.5 hours
Senol Atac
62 Lectures
4.5 hours
Senol Atac
67 Lectures
4.5 hours
Senol Atac
69 Lectures
5 hours
Senol Atac
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 3161,
"s": 3025,
"text": "Unit Testing is a one of the testing done by the developers to make sure individual unit or component functionalities are working fine."
},
{
"code": null,
"e": 3266,
"s": 3161,
"text": "In this tutorial, we are going to see how to write a unit test case by using Mockito and Web Controller."
},
{
"code": null,
"e": 3389,
"s": 3266,
"text": "For injecting Mockito Mocks into Spring Beans, we need to add the Mockito-core dependency in our build configuration file."
},
{
"code": null,
"e": 3456,
"s": 3389,
"text": "Maven users can add the following dependency in your pom.xml file."
},
{
"code": null,
"e": 3737,
"s": 3456,
"text": "<dependency>\n <groupId>org.mockito</groupId>\n <artifactId>mockito-core</artifactId>\n <version>2.13.0</version>\n</dependency>\n<dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-test</artifactId>\n <scope>test</scope>\n</dependency>"
},
{
"code": null,
"e": 3809,
"s": 3737,
"text": "Gradle users can add the following dependency in the build.gradle file."
},
{
"code": null,
"e": 3944,
"s": 3809,
"text": "compile group: 'org.mockito', name: 'mockito-core', version: '2.13.0'\ntestCompile('org.springframework.boot:spring-boot-starter-test')"
},
{
"code": null,
"e": 4047,
"s": 3944,
"text": "The code to write a Service class which contains a method that returns the String value is given here."
},
{
"code": null,
"e": 4241,
"s": 4047,
"text": "package com.tutorialspoint.mockitodemo;\n\nimport org.springframework.stereotype.Service;\n\n@Service\npublic class ProductService {\n public String getProductName() {\n return \"Honey\";\n } \n}"
},
{
"code": null,
"e": 4320,
"s": 4241,
"text": "Now, inject the ProductService class into another Service class file as shown."
},
{
"code": null,
"e": 4752,
"s": 4320,
"text": "package com.tutorialspoint.mockitodemo;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Service;\n\n@Service\npublic class OrderService {\n @Autowired\n ProductService productService;\n\n public OrderService(ProductService productService) {\n this.productService = productService;\n }\n public String getProductName() {\n return productService.getProductName();\n }\n}"
},
{
"code": null,
"e": 4813,
"s": 4752,
"text": "The main Spring Boot application class file is given below −"
},
{
"code": null,
"e": 5152,
"s": 4813,
"text": "package com.tutorialspoint.mockitodemo;\n\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\n\n@SpringBootApplication\npublic class MockitoDemoApplication {\n public static void main(String[] args) {\n SpringApplication.run(MockitoDemoApplication.class, args);\n }\n}"
},
{
"code": null,
"e": 5303,
"s": 5152,
"text": "Then, configure the Application context for the tests. The @Profile(“test”) annotation is used to configure the class when the Test cases are running."
},
{
"code": null,
"e": 5796,
"s": 5303,
"text": "package com.tutorialspoint.mockitodemo;\n\nimport org.mockito.Mockito;\nimport org.springframework.context.annotation.Bean;\nimport org.springframework.context.annotation.Configuration;\nimport org.springframework.context.annotation.Primary;\nimport org.springframework.context.annotation.Profile;\n\n@Profile(\"test\")\n@Configuration\npublic class ProductServiceTestConfiguration {\n @Bean\n @Primary\n public ProductService productService() {\n return Mockito.mock(ProductService.class);\n }\n}"
},
{
"code": null,
"e": 5888,
"s": 5796,
"text": "Now, you can write a Unit Test case for Order Service under the src/test/resources package."
},
{
"code": null,
"e": 6808,
"s": 5888,
"text": "package com.tutorialspoint.mockitodemo;\n\nimport org.junit.Assert;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.mockito.Mockito;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.boot.test.context.SpringBootTest;\nimport org.springframework.test.context.ActiveProfiles;\nimport org.springframework.test.context.junit4.SpringJUnit4ClassRunner;\n\n@SpringBootTest\n@ActiveProfiles(\"test\")\n@RunWith(SpringJUnit4ClassRunner.class)\npublic class MockitoDemoApplicationTests {\n @Autowired\n private OrderService orderService;\n \n @Autowired\n private ProductService productService;\n\n @Test\n public void whenUserIdIsProvided_thenRetrievedNameIsCorrect() {\n Mockito.when(productService.getProductName()).thenReturn(\"Mock Product Name\");\n String testName = orderService.getProductName();\n Assert.assertEquals(\"Mock Product Name\", testName);\n }\n}"
},
{
"code": null,
"e": 6871,
"s": 6808,
"text": "The complete code for build configuration file is given below."
},
{
"code": null,
"e": 6887,
"s": 6871,
"text": "Maven – pom.xml"
},
{
"code": null,
"e": 8646,
"s": 6887,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<project xmlns = \"http://maven.apache.org/POM/4.0.0\" \n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://maven.apache.org/POM/4.0.0 \n http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n \n <modelVersion>4.0.0</modelVersion>\n <groupId>com.tutorialspoint</groupId>\n <artifactId>mockito-demo</artifactId>\n <version>0.0.1-SNAPSHOT</version>\n <packaging>jar</packaging>\n\n <name>mockito-demo</name>\n <description>Demo project for Spring Boot</description>\n\n <parent>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-parent</artifactId>\n <version>1.5.9.RELEASE</version>\n <relativePath /> <!-- lookup parent from repository -->\n </parent>\n\n <properties>\n <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>\n <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>\n <java.version>1.8</java.version>\n </properties>\n\n <dependencies>\n <dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter</artifactId>\n </dependency>\n <dependency>\n <groupId>org.mockito</groupId>\n <artifactId>mockito-core</artifactId>\n <version>2.13.0</version>\n </dependency>\n <dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-test</artifactId>\n <scope>test</scope>\n </dependency>\n </dependencies>\n\n <build>\n <plugins>\n <plugin>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-maven-plugin</artifactId>\n </plugin>\n </plugins>\n </build>\n \n</project>"
},
{
"code": null,
"e": 8668,
"s": 8646,
"text": "Gradle – build.gradle"
},
{
"code": null,
"e": 9324,
"s": 8668,
"text": "buildscript {\n ext {\n springBootVersion = '1.5.9.RELEASE'\n }\n repositories {\n mavenCentral()\n }\n dependencies {\n classpath(\"org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}\")\n }\n}\n\napply plugin: 'java'\napply plugin: 'eclipse'\napply plugin: 'org.springframework.boot'\n\ngroup = 'com.tutorialspoint'\nversion = '0.0.1-SNAPSHOT'\nsourceCompatibility = 1.8\n\nrepositories {\n mavenCentral()\n}\ndependencies {\n compile('org.springframework.boot:spring-boot-starter')\n compile group: 'org.mockito', name: 'mockito-core', version: '2.13.0'\n testCompile('org.springframework.boot:spring-boot-starter-test')\n} "
},
{
"code": null,
"e": 9449,
"s": 9324,
"text": "You can create an executable JAR file, and run the Spring Boot application by using the following Maven or Gradle1 commands."
},
{
"code": null,
"e": 9495,
"s": 9449,
"text": "For Maven, you can use the command as shown −"
},
{
"code": null,
"e": 9515,
"s": 9495,
"text": "mvn clean install \n"
},
{
"code": null,
"e": 9563,
"s": 9515,
"text": "You can see the test results in console window."
},
{
"code": null,
"e": 9610,
"s": 9563,
"text": "For Gradle, you can use the command as shown −"
},
{
"code": null,
"e": 9631,
"s": 9610,
"text": "gradle clean build \n"
},
{
"code": null,
"e": 9679,
"s": 9631,
"text": "You can see the rest results in console window."
},
{
"code": null,
"e": 9713,
"s": 9679,
"text": "\n 102 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 9727,
"s": 9713,
"text": " Karthikeya T"
},
{
"code": null,
"e": 9760,
"s": 9727,
"text": "\n 39 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 9775,
"s": 9760,
"text": " Chaand Sheikh"
},
{
"code": null,
"e": 9810,
"s": 9775,
"text": "\n 73 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 9822,
"s": 9810,
"text": " Senol Atac"
},
{
"code": null,
"e": 9857,
"s": 9822,
"text": "\n 62 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 9869,
"s": 9857,
"text": " Senol Atac"
},
{
"code": null,
"e": 9904,
"s": 9869,
"text": "\n 67 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 9916,
"s": 9904,
"text": " Senol Atac"
},
{
"code": null,
"e": 9949,
"s": 9916,
"text": "\n 69 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 9961,
"s": 9949,
"text": " Senol Atac"
},
{
"code": null,
"e": 9968,
"s": 9961,
"text": " Print"
},
{
"code": null,
"e": 9979,
"s": 9968,
"text": " Add Notes"
}
] |
Flatten a binary tree into linked list - GeeksforGeeks | 21 Apr, 2022
Given a binary tree, flatten it into linked list in-place. Usage of auxiliary data structure is not allowed. After flattening, left of each node should point to NULL and right should contain next node in preorder.
Examples:
Input :
1
/ \
2 5
/ \ \
3 4 6
Output :
1
\
2
\
3
\
4
\
5
\
6
Input :
1
/ \
3 4
/
2
\
5
Output :
1
\
3
\
4
\
2
\
5
Simple Approach: A simple solution is to use Level Order Traversal using Queue. In level order traversal, keep track of previous node. Make current node as right child of previous and left of previous node as NULL. This solution requires queue, but question asks to solve without additional data structure.
Efficient Without Additional Data Structure Recursively look for the node with no grandchildren and both left and right child in the left sub-tree. Then store node->right in temp and make node->right=node->left. Insert temp in first node NULL on right of node by node=node->right. Repeat until it is converted to linked list.
For Example,
C++
C
Java
Python3
C#
Javascript
// C++ Program to flatten a given Binary Tree into linked// list#include <bits/stdc++.h>using namespace std; struct Node { int key; Node *left, *right;}; // utility that allocates a new Node with the given keyNode* newNode(int key){ Node* node = new Node; node->key = key; node->left = node->right = NULL; return (node);} // Function to convert binary tree into linked list by// altering the right node and making left node point to// NULLvoid flatten(struct Node* root){ // base condition- return if root is NULL or if it is a // leaf node if (root == NULL || root->left == NULL && root->right == NULL) return; // if root->left exists then we have to make it // root->right if (root->left != NULL) { // move left recursively flatten(root->left); // store the node root->right struct Node* tmpRight = root->right; root->right = root->left; root->left = NULL; // find the position to insert the stored value struct Node* t = root->right; while (t->right != NULL) t = t->right; // insert the stored value t->right = tmpRight; } // now call the same function for root->right flatten(root->right);} // To find the inorder traversalvoid inorder(struct Node* root){ // base condition if (root == NULL) return; inorder(root->left); cout << root->key << " "; inorder(root->right);} /* Driver program to test above functions*/int main(){ /* 1 / \ 2 5 / \ \ 3 4 6 */ Node* root = newNode(1); root->left = newNode(2); root->right = newNode(5); root->left->left = newNode(3); root->left->right = newNode(4); root->right->right = newNode(6); flatten(root); cout << "The Inorder traversal after flattening binary tree "; inorder(root); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)
// C Program to flatten a given Binary Tree into linked// list#include <stdio.h>#include <stdlib.h> typedef struct Node { int key; struct Node *left, *right;}Node; // utility that allocates a new Node with the given keyNode* newNode(int key){ Node* node = (Node*)malloc(sizeof(Node)); node->key = key; node->left = node->right = NULL; return (node);} // Function to convert binary tree into linked list by// altering the right node and making left node point to// NULLvoid flatten(Node* root){ // base condition- return if root is NULL or if it is a // leaf node if (root == NULL || root->left == NULL && root->right == NULL) return; // if root->left exists then we have to make it // root->right if (root->left != NULL) { // move left recursively flatten(root->left); // store the node root->right struct Node* tmpRight = root->right; root->right = root->left; root->left = NULL; // find the position to insert the stored value struct Node* t = root->right; while (t->right != NULL) t = t->right; // insert the stored value t->right = tmpRight; } // now call the same function for root->right flatten(root->right);} // To find the inorder traversalvoid inorder(struct Node* root){ // base condition if (root == NULL) return; inorder(root->left); printf("%d ", root->key); inorder(root->right);} /* Driver program to test above functions*/int main(){ /* 1 / \ 2 5 / \ \ 3 4 6 */ Node* root = newNode(1); root->left = newNode(2); root->right = newNode(5); root->left->left = newNode(3); root->left->right = newNode(4); root->right->right = newNode(6); flatten(root); printf("The Inorder traversal after flattening binary tree "); inorder(root); return 0;} // This code is contributed by aditykumar129.
// Java program to flatten a given Binary Tree into linked// list // A binary tree nodeclass Node { int data; Node left, right; Node(int key) { data = key; left = right = null; }} class BinaryTree { Node root; // Function to convert binary tree into linked list by // altering the right node and making left node NULL public void flatten(Node node) { // Base case - return if root is NULL if (node == null) return; // Or if it is a leaf node if (node.left == null && node.right == null) return; // If root.left children exists then we have to make // it node.right (where node is root) if (node.left != null) { // Move left recursively flatten(node.left); // Store the node.right in Node named tempNode Node tempNode = node.right; node.right = node.left; node.left = null; // Find the position to insert the stored value Node curr = node.right; while (curr.right != null) curr = curr.right; // Insert the stored value curr.right = tempNode; } // Now call the same function for node.right flatten(node.right); } // Function for Inorder traversal public void inOrder(Node node) { // Base Condition if (node == null) return; inOrder(node.left); System.out.print(node.data + " "); inOrder(node.right); } // Driver code public static void main(String[] args) { BinaryTree tree = new BinaryTree(); /* 1 / \ 2 5 / \ \ 3 4 6 */ tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(5); tree.root.left.left = new Node(3); tree.root.left.right = new Node(4); tree.root.right.right = new Node(6); System.out.println( "The Inorder traversal after flattening binary tree "); tree.flatten(tree.root); tree.inOrder(tree.root); }} // This code is contributed by Aditya Kumar (adityakumar129)
# Python3 program to flatten a given Binary# Tree into linked listclass Node: def __init__(self): self.key = 0 self.left = None self.right = None # Utility that allocates a new Node# with the given keydef newNode(key): node = Node() node.key = key node.left = node.right = None return (node) # Function to convert binary tree into# linked list by altering the right node# and making left node point to Nonedef flatten(root): # Base condition- return if root is None # or if it is a leaf node if (root == None or root.left == None and root.right == None): return # If root.left exists then we have # to make it root.right if (root.left != None): # Move left recursively flatten(root.left) # Store the node root.right tmpRight = root.right root.right = root.left root.left = None # Find the position to insert # the stored value t = root.right while (t.right != None): t = t.right # Insert the stored value t.right = tmpRight # Now call the same function # for root.right flatten(root.right) # To find the inorder traversaldef inorder(root): # Base condition if (root == None): return inorder(root.left) print(root.key, end = ' ') inorder(root.right) # Driver Codeif __name__=='__main__': ''' 1 / \ 2 5 / \ \ 3 4 6 ''' root = newNode(1) root.left = newNode(2) root.right = newNode(5) root.left.left = newNode(3) root.left.right = newNode(4) root.right.right = newNode(6) flatten(root) print("The Inorder traversal after " "flattening binary tree ", end = '') inorder(root) # This code is contributed by pratham76
// C# program to flatten a given// Binary Tree into linked listusing System; // A binary tree nodeclass Node{ public int data; public Node left, right; public Node(int key) { data = key; left = right = null; }} class BinaryTree{ Node root; // Function to convert binary tree into // linked list by altering the right node // and making left node NULL public void flatten(Node node) { // Base case - return if root is NULL if (node == null) return; // Or if it is a leaf node if (node.left == null && node.right == null) return; // If root.left children exists then we have // to make it node.right (where node is root) if (node.left != null) { // Move left recursively flatten(node.left); // Store the node.right in // Node named tempNode Node tempNode = node.right; node.right = node.left; node.left = null; // Find the position to insert // the stored value Node curr = node.right; while (curr.right != null) { curr = curr.right; } // Insert the stored value curr.right = tempNode; } // Now call the same function // for node.right flatten(node.right); } // Function for Inorder traversal public void inOrder(Node node) { // Base Condition if (node == null) return; inOrder(node.left); Console.Write(node.data + " "); inOrder(node.right); } // Driver code public static void Main(string[] args) { BinaryTree tree = new BinaryTree(); /* 1 / \ 2 5 / \ \ 3 4 6 */ tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(5); tree.root.left.left = new Node(3); tree.root.left.right = new Node(4); tree.root.right.right = new Node(6); Console.Write("The Inorder traversal after " + "flattening binary tree "); tree.flatten(tree.root); tree.inOrder(tree.root); }} // This code is contributed by rutvik_56
<script> // Javascript program to flatten a given// Binary Tree into linked list // A binary tree nodeclass Node{ constructor(key) { this.data = key; this.left = null; this.right = null; }} var root; // Function to convert binary tree into// linked list by altering the right node// and making left node NULLfunction flatten(node){ // Base case - return if root is NULL if (node == null) return; // Or if it is a leaf node if (node.left == null && node.right == null) return; // If root.left children exists then we have // to make it node.right (where node is root) if (node.left != null) { // Move left recursively flatten(node.left); // Store the node.right in // Node named tempNode var tempNode = node.right; node.right = node.left; node.left = null; // Find the position to insert // the stored value var curr = node.right; while (curr.right != null) { curr = curr.right; } // Insert the stored value curr.right = tempNode; } // Now call the same function // for node.right flatten(node.right);} // Function for Inorder traversalfunction inOrder(node){ // Base Condition if (node == null) return; inOrder(node.left); document.write(node.data + " "); inOrder(node.right);} // Driver code/* 1 / \ 2 5 / \ \3 4 6 */root = new Node(1);root.left = new Node(2);root.right = new Node(5);root.left.left = new Node(3);root.left.right = new Node(4);root.right.right = new Node(6); document.write("The Inorder traversal after " + "flattening binary tree "); flatten(root);inOrder(root); // This code is contributed by famously </script>
The Inorder traversal after flattening
binary tree 1 2 3 4 5 6
Spider_man
ysinghal555
rutvik_56
pratham76
famously
adityakumar129
Binary Tree
tree-level-order
Linked List
Recursion
Tree
Linked List
Recursion
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Linked List vs Array
Detect loop in a linked list
Delete a Linked List node at a given position
Merge two sorted linked lists
Find the middle of a given linked list
Write a program to print all permutations of a given string
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Recursion
Program for Tower of Hanoi
Program for Sum of the digits of a given number | [
{
"code": null,
"e": 25178,
"s": 25150,
"text": "\n21 Apr, 2022"
},
{
"code": null,
"e": 25392,
"s": 25178,
"text": "Given a binary tree, flatten it into linked list in-place. Usage of auxiliary data structure is not allowed. After flattening, left of each node should point to NULL and right should contain next node in preorder."
},
{
"code": null,
"e": 25404,
"s": 25392,
"text": "Examples: "
},
{
"code": null,
"e": 25813,
"s": 25404,
"text": "Input : \n 1\n / \\\n 2 5\n / \\ \\\n 3 4 6\n\nOutput :\n 1\n \\\n 2\n \\\n 3\n \\\n 4\n \\\n 5\n \\\n 6\n\nInput :\n 1\n / \\\n 3 4\n /\n 2\n \\\n 5\nOutput :\n 1\n \\\n 3\n \\\n 4\n \\\n 2\n \\ \n 5"
},
{
"code": null,
"e": 26120,
"s": 25813,
"text": "Simple Approach: A simple solution is to use Level Order Traversal using Queue. In level order traversal, keep track of previous node. Make current node as right child of previous and left of previous node as NULL. This solution requires queue, but question asks to solve without additional data structure."
},
{
"code": null,
"e": 26447,
"s": 26120,
"text": "Efficient Without Additional Data Structure Recursively look for the node with no grandchildren and both left and right child in the left sub-tree. Then store node->right in temp and make node->right=node->left. Insert temp in first node NULL on right of node by node=node->right. Repeat until it is converted to linked list. "
},
{
"code": null,
"e": 26462,
"s": 26447,
"text": "For Example, "
},
{
"code": null,
"e": 26468,
"s": 26464,
"text": "C++"
},
{
"code": null,
"e": 26470,
"s": 26468,
"text": "C"
},
{
"code": null,
"e": 26475,
"s": 26470,
"text": "Java"
},
{
"code": null,
"e": 26483,
"s": 26475,
"text": "Python3"
},
{
"code": null,
"e": 26486,
"s": 26483,
"text": "C#"
},
{
"code": null,
"e": 26497,
"s": 26486,
"text": "Javascript"
},
{
"code": "// C++ Program to flatten a given Binary Tree into linked// list#include <bits/stdc++.h>using namespace std; struct Node { int key; Node *left, *right;}; // utility that allocates a new Node with the given keyNode* newNode(int key){ Node* node = new Node; node->key = key; node->left = node->right = NULL; return (node);} // Function to convert binary tree into linked list by// altering the right node and making left node point to// NULLvoid flatten(struct Node* root){ // base condition- return if root is NULL or if it is a // leaf node if (root == NULL || root->left == NULL && root->right == NULL) return; // if root->left exists then we have to make it // root->right if (root->left != NULL) { // move left recursively flatten(root->left); // store the node root->right struct Node* tmpRight = root->right; root->right = root->left; root->left = NULL; // find the position to insert the stored value struct Node* t = root->right; while (t->right != NULL) t = t->right; // insert the stored value t->right = tmpRight; } // now call the same function for root->right flatten(root->right);} // To find the inorder traversalvoid inorder(struct Node* root){ // base condition if (root == NULL) return; inorder(root->left); cout << root->key << \" \"; inorder(root->right);} /* Driver program to test above functions*/int main(){ /* 1 / \\ 2 5 / \\ \\ 3 4 6 */ Node* root = newNode(1); root->left = newNode(2); root->right = newNode(5); root->left->left = newNode(3); root->left->right = newNode(4); root->right->right = newNode(6); flatten(root); cout << \"The Inorder traversal after flattening binary tree \"; inorder(root); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 28427,
"s": 26497,
"text": null
},
{
"code": "// C Program to flatten a given Binary Tree into linked// list#include <stdio.h>#include <stdlib.h> typedef struct Node { int key; struct Node *left, *right;}Node; // utility that allocates a new Node with the given keyNode* newNode(int key){ Node* node = (Node*)malloc(sizeof(Node)); node->key = key; node->left = node->right = NULL; return (node);} // Function to convert binary tree into linked list by// altering the right node and making left node point to// NULLvoid flatten(Node* root){ // base condition- return if root is NULL or if it is a // leaf node if (root == NULL || root->left == NULL && root->right == NULL) return; // if root->left exists then we have to make it // root->right if (root->left != NULL) { // move left recursively flatten(root->left); // store the node root->right struct Node* tmpRight = root->right; root->right = root->left; root->left = NULL; // find the position to insert the stored value struct Node* t = root->right; while (t->right != NULL) t = t->right; // insert the stored value t->right = tmpRight; } // now call the same function for root->right flatten(root->right);} // To find the inorder traversalvoid inorder(struct Node* root){ // base condition if (root == NULL) return; inorder(root->left); printf(\"%d \", root->key); inorder(root->right);} /* Driver program to test above functions*/int main(){ /* 1 / \\ 2 5 / \\ \\ 3 4 6 */ Node* root = newNode(1); root->left = newNode(2); root->right = newNode(5); root->left->left = newNode(3); root->left->right = newNode(4); root->right->right = newNode(6); flatten(root); printf(\"The Inorder traversal after flattening binary tree \"); inorder(root); return 0;} // This code is contributed by aditykumar129.",
"e": 30368,
"s": 28427,
"text": null
},
{
"code": "// Java program to flatten a given Binary Tree into linked// list // A binary tree nodeclass Node { int data; Node left, right; Node(int key) { data = key; left = right = null; }} class BinaryTree { Node root; // Function to convert binary tree into linked list by // altering the right node and making left node NULL public void flatten(Node node) { // Base case - return if root is NULL if (node == null) return; // Or if it is a leaf node if (node.left == null && node.right == null) return; // If root.left children exists then we have to make // it node.right (where node is root) if (node.left != null) { // Move left recursively flatten(node.left); // Store the node.right in Node named tempNode Node tempNode = node.right; node.right = node.left; node.left = null; // Find the position to insert the stored value Node curr = node.right; while (curr.right != null) curr = curr.right; // Insert the stored value curr.right = tempNode; } // Now call the same function for node.right flatten(node.right); } // Function for Inorder traversal public void inOrder(Node node) { // Base Condition if (node == null) return; inOrder(node.left); System.out.print(node.data + \" \"); inOrder(node.right); } // Driver code public static void main(String[] args) { BinaryTree tree = new BinaryTree(); /* 1 / \\ 2 5 / \\ \\ 3 4 6 */ tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(5); tree.root.left.left = new Node(3); tree.root.left.right = new Node(4); tree.root.right.right = new Node(6); System.out.println( \"The Inorder traversal after flattening binary tree \"); tree.flatten(tree.root); tree.inOrder(tree.root); }} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 32568,
"s": 30368,
"text": null
},
{
"code": "# Python3 program to flatten a given Binary# Tree into linked listclass Node: def __init__(self): self.key = 0 self.left = None self.right = None # Utility that allocates a new Node# with the given keydef newNode(key): node = Node() node.key = key node.left = node.right = None return (node) # Function to convert binary tree into# linked list by altering the right node# and making left node point to Nonedef flatten(root): # Base condition- return if root is None # or if it is a leaf node if (root == None or root.left == None and root.right == None): return # If root.left exists then we have # to make it root.right if (root.left != None): # Move left recursively flatten(root.left) # Store the node root.right tmpRight = root.right root.right = root.left root.left = None # Find the position to insert # the stored value t = root.right while (t.right != None): t = t.right # Insert the stored value t.right = tmpRight # Now call the same function # for root.right flatten(root.right) # To find the inorder traversaldef inorder(root): # Base condition if (root == None): return inorder(root.left) print(root.key, end = ' ') inorder(root.right) # Driver Codeif __name__=='__main__': ''' 1 / \\ 2 5 / \\ \\ 3 4 6 ''' root = newNode(1) root.left = newNode(2) root.right = newNode(5) root.left.left = newNode(3) root.left.right = newNode(4) root.right.right = newNode(6) flatten(root) print(\"The Inorder traversal after \" \"flattening binary tree \", end = '') inorder(root) # This code is contributed by pratham76",
"e": 34425,
"s": 32568,
"text": null
},
{
"code": "// C# program to flatten a given// Binary Tree into linked listusing System; // A binary tree nodeclass Node{ public int data; public Node left, right; public Node(int key) { data = key; left = right = null; }} class BinaryTree{ Node root; // Function to convert binary tree into // linked list by altering the right node // and making left node NULL public void flatten(Node node) { // Base case - return if root is NULL if (node == null) return; // Or if it is a leaf node if (node.left == null && node.right == null) return; // If root.left children exists then we have // to make it node.right (where node is root) if (node.left != null) { // Move left recursively flatten(node.left); // Store the node.right in // Node named tempNode Node tempNode = node.right; node.right = node.left; node.left = null; // Find the position to insert // the stored value Node curr = node.right; while (curr.right != null) { curr = curr.right; } // Insert the stored value curr.right = tempNode; } // Now call the same function // for node.right flatten(node.right); } // Function for Inorder traversal public void inOrder(Node node) { // Base Condition if (node == null) return; inOrder(node.left); Console.Write(node.data + \" \"); inOrder(node.right); } // Driver code public static void Main(string[] args) { BinaryTree tree = new BinaryTree(); /* 1 / \\ 2 5 / \\ \\ 3 4 6 */ tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(5); tree.root.left.left = new Node(3); tree.root.left.right = new Node(4); tree.root.right.right = new Node(6); Console.Write(\"The Inorder traversal after \" + \"flattening binary tree \"); tree.flatten(tree.root); tree.inOrder(tree.root); }} // This code is contributed by rutvik_56",
"e": 36452,
"s": 34425,
"text": null
},
{
"code": "<script> // Javascript program to flatten a given// Binary Tree into linked list // A binary tree nodeclass Node{ constructor(key) { this.data = key; this.left = null; this.right = null; }} var root; // Function to convert binary tree into// linked list by altering the right node// and making left node NULLfunction flatten(node){ // Base case - return if root is NULL if (node == null) return; // Or if it is a leaf node if (node.left == null && node.right == null) return; // If root.left children exists then we have // to make it node.right (where node is root) if (node.left != null) { // Move left recursively flatten(node.left); // Store the node.right in // Node named tempNode var tempNode = node.right; node.right = node.left; node.left = null; // Find the position to insert // the stored value var curr = node.right; while (curr.right != null) { curr = curr.right; } // Insert the stored value curr.right = tempNode; } // Now call the same function // for node.right flatten(node.right);} // Function for Inorder traversalfunction inOrder(node){ // Base Condition if (node == null) return; inOrder(node.left); document.write(node.data + \" \"); inOrder(node.right);} // Driver code/* 1 / \\ 2 5 / \\ \\3 4 6 */root = new Node(1);root.left = new Node(2);root.right = new Node(5);root.left.left = new Node(3);root.left.right = new Node(4);root.right.right = new Node(6); document.write(\"The Inorder traversal after \" + \"flattening binary tree \"); flatten(root);inOrder(root); // This code is contributed by famously </script>",
"e": 38343,
"s": 36452,
"text": null
},
{
"code": null,
"e": 38407,
"s": 38343,
"text": "The Inorder traversal after flattening \nbinary tree 1 2 3 4 5 6"
},
{
"code": null,
"e": 38420,
"s": 38409,
"text": "Spider_man"
},
{
"code": null,
"e": 38432,
"s": 38420,
"text": "ysinghal555"
},
{
"code": null,
"e": 38442,
"s": 38432,
"text": "rutvik_56"
},
{
"code": null,
"e": 38452,
"s": 38442,
"text": "pratham76"
},
{
"code": null,
"e": 38461,
"s": 38452,
"text": "famously"
},
{
"code": null,
"e": 38476,
"s": 38461,
"text": "adityakumar129"
},
{
"code": null,
"e": 38488,
"s": 38476,
"text": "Binary Tree"
},
{
"code": null,
"e": 38505,
"s": 38488,
"text": "tree-level-order"
},
{
"code": null,
"e": 38517,
"s": 38505,
"text": "Linked List"
},
{
"code": null,
"e": 38527,
"s": 38517,
"text": "Recursion"
},
{
"code": null,
"e": 38532,
"s": 38527,
"text": "Tree"
},
{
"code": null,
"e": 38544,
"s": 38532,
"text": "Linked List"
},
{
"code": null,
"e": 38554,
"s": 38544,
"text": "Recursion"
},
{
"code": null,
"e": 38559,
"s": 38554,
"text": "Tree"
},
{
"code": null,
"e": 38657,
"s": 38559,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 38678,
"s": 38657,
"text": "Linked List vs Array"
},
{
"code": null,
"e": 38707,
"s": 38678,
"text": "Detect loop in a linked list"
},
{
"code": null,
"e": 38753,
"s": 38707,
"text": "Delete a Linked List node at a given position"
},
{
"code": null,
"e": 38783,
"s": 38753,
"text": "Merge two sorted linked lists"
},
{
"code": null,
"e": 38822,
"s": 38783,
"text": "Find the middle of a given linked list"
},
{
"code": null,
"e": 38882,
"s": 38822,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 38967,
"s": 38882,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 38977,
"s": 38967,
"text": "Recursion"
},
{
"code": null,
"e": 39004,
"s": 38977,
"text": "Program for Tower of Hanoi"
}
] |
How can we set a border to JCheckBox in Java?
| A JCheckBox is a component that can extend JToggleButton and an object of JCheckBox represents an option that can be checked or unchecked. If there are two or more options then any combination of these options can be selected at the same time. We can set a border to the JCheckBox component by using the setBorder() method and make sure that setBorderPainted() method set to true.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class BorderedJCheckBoxTest extends JFrame {
private JCheckBox jcb;
public BorderedJCheckBoxTest() throws Exception {
setTitle("JCheckBox Test");
setLayout(new FlowLayout());
jcb = new JCheckBox("BorderedJCheckBox Test");
jcb.setBorderPainted(true);
jcb.setBorder(BorderFactory.createLineBorder(Color.red)); // set the border
add(jcb);
setSize(375, 250);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String args[]) throws Exception {
new BorderedJCheckBoxTest();
}
} | [
{
"code": null,
"e": 1443,
"s": 1062,
"text": "A JCheckBox is a component that can extend JToggleButton and an object of JCheckBox represents an option that can be checked or unchecked. If there are two or more options then any combination of these options can be selected at the same time. We can set a border to the JCheckBox component by using the setBorder() method and make sure that setBorderPainted() method set to true."
},
{
"code": null,
"e": 2140,
"s": 1443,
"text": "import java.awt.*;\nimport java.awt.event.*;\nimport javax.swing.*;\npublic class BorderedJCheckBoxTest extends JFrame {\n private JCheckBox jcb;\n public BorderedJCheckBoxTest() throws Exception {\n setTitle(\"JCheckBox Test\");\n setLayout(new FlowLayout());\n jcb = new JCheckBox(\"BorderedJCheckBox Test\");\n jcb.setBorderPainted(true);\n jcb.setBorder(BorderFactory.createLineBorder(Color.red)); // set the border\n add(jcb);\n setSize(375, 250);\n setLocationRelativeTo(null);\n setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n setVisible(true);\n }\n public static void main(String args[]) throws Exception {\n new BorderedJCheckBoxTest();\n }\n}"
}
] |
Creating a Finance Web App in 3 Minutes! | Towards Data Science | A vital part of any data-driven project is its ability to be easily explained and viewable even for others who may not know anything about the data beforehand. Introducing Streamlit in Python!
Streamlit is an extremely easy to use and intuitive tool for building highly interactive, data-driven web applications in Python. With this tool, you can simply focus on the data aspect without worrying about a tedious deployment with Flask or Django.
The process is entirely intuitive and by the end of this article, you too should be able to deploy your web app within minutes and only a few lines of code!
To get started with our Streamlit web app, we must first download it using PyPi (Python’s Package Manager). Simply type the following in your terminal for any packages you may not have (including streamlit) and we should be good to go.
pip install streamlit
If you don’t have pip installed on your computer, you can take a quick look at this article and return back here once it's installed.
First, we must import all the dependencies we will need throughout the program. The primary libraries we will use will be Yfinance, Streamlit, and TaLib. Yfinance will allow us to receive historical stock prices for any ticker, Streamlit will allow us to deploy the web app onto the localhost, and TaLib will allow us to calculate the technical indicators we will show on the app later on.
Now that we have the dependencies set up, we can finally get into the building of our app!
First, in order to run the program, head over to your terminal and type in the command streamlit run file_name.py. Replace file_name.py with the file name you choose to create from this program. A web app should then open up on your local host!
In order to write text on the website, we can use the .write() method in Streamlit. To show bigger and bolder text, we can use a hashtag (#) before and Streamlit will automatically change the text to make it look like a title (Markdown formatting). To bold text, we can simply surround the text we want to bold with two asterisks.
Next, we can create a header using the header method and set up a function to get the inputs from the user. Since we are creating a technical analysis web app, we need a stock ticker, start date, and end date. We can set values to be there automatically just incase the user doesn’t input there own. In this case, I went with Apple’s ticker (AAPL), 2019–01–01 as the start date, and today’s date for the end.
In order to make the web app look a little nicer, we can create a function that sends a request to Yahoo Finance and retrieve the companies name for any ticker we input!
We can convert the start and end dates from strings to DateTime format using the pandas.to_datetime() method just so we don’t get any errors later on. Lastly, we can retrieve the historical stock data with the Yfinance module that was mentioned earlier. Just to keep track of where we are currently, this is how the web app should look now.
Now, all that is left is creating the graphs we will display.
As I mentioned before, the wonderful TaLib library makes it ridiculously easy to calculate the technical indicators we will be plotting. For this project, I’ve chose the popular indicators such as Moving Average Crossovers, Bollinger Bands, Moving Average Convergence Divergence, Commodity Channel Index, Relative Strength Index, and On Balance Volume. To get more in-depth explanations on what these indicators can show, I would recommend looking them up on Investopedia.com.
For this section of code, there are three primary sections for each indicator we will show. First, we must calculate the indicator using TaLib, then we must set a header title that includes what the indicator actually is, and finally, we can display the chart using streamlit.line_chart(). That’s all it takes!
Now we have a fully interactive, live, responsive, and easy-to-use web application within a matter of minutes and with less than 100 lines of code. If you’ve been following along this entire time with the code we should have a similar-looking website as down below.
I’ve included the entire code for this program in the GitHub Gist below!
In terms of the next steps, you could expand on the data we showed as Streamlit allows users to show virtually any type of data, including Pandas DataFrames. Or you can decide to deploy this to the cloud using Heroku (if this is something you would like to do, check out this amazing article by Hamilton Chang). Now that you know how to create your own data web application, the possibilities are truly endless!
Thank you so much for reading and I hope you enjoyed it!
Note: If you are deploying this specific app to Heroku, remember to remove TaLib from the requirements.txt and instead, add a buildpack for it!
If you enjoyed this article, join my free investing community on Finary and check out some of my other articles below! | [
{
"code": null,
"e": 365,
"s": 172,
"text": "A vital part of any data-driven project is its ability to be easily explained and viewable even for others who may not know anything about the data beforehand. Introducing Streamlit in Python!"
},
{
"code": null,
"e": 617,
"s": 365,
"text": "Streamlit is an extremely easy to use and intuitive tool for building highly interactive, data-driven web applications in Python. With this tool, you can simply focus on the data aspect without worrying about a tedious deployment with Flask or Django."
},
{
"code": null,
"e": 774,
"s": 617,
"text": "The process is entirely intuitive and by the end of this article, you too should be able to deploy your web app within minutes and only a few lines of code!"
},
{
"code": null,
"e": 1010,
"s": 774,
"text": "To get started with our Streamlit web app, we must first download it using PyPi (Python’s Package Manager). Simply type the following in your terminal for any packages you may not have (including streamlit) and we should be good to go."
},
{
"code": null,
"e": 1032,
"s": 1010,
"text": "pip install streamlit"
},
{
"code": null,
"e": 1166,
"s": 1032,
"text": "If you don’t have pip installed on your computer, you can take a quick look at this article and return back here once it's installed."
},
{
"code": null,
"e": 1556,
"s": 1166,
"text": "First, we must import all the dependencies we will need throughout the program. The primary libraries we will use will be Yfinance, Streamlit, and TaLib. Yfinance will allow us to receive historical stock prices for any ticker, Streamlit will allow us to deploy the web app onto the localhost, and TaLib will allow us to calculate the technical indicators we will show on the app later on."
},
{
"code": null,
"e": 1647,
"s": 1556,
"text": "Now that we have the dependencies set up, we can finally get into the building of our app!"
},
{
"code": null,
"e": 1892,
"s": 1647,
"text": "First, in order to run the program, head over to your terminal and type in the command streamlit run file_name.py. Replace file_name.py with the file name you choose to create from this program. A web app should then open up on your local host!"
},
{
"code": null,
"e": 2223,
"s": 1892,
"text": "In order to write text on the website, we can use the .write() method in Streamlit. To show bigger and bolder text, we can use a hashtag (#) before and Streamlit will automatically change the text to make it look like a title (Markdown formatting). To bold text, we can simply surround the text we want to bold with two asterisks."
},
{
"code": null,
"e": 2632,
"s": 2223,
"text": "Next, we can create a header using the header method and set up a function to get the inputs from the user. Since we are creating a technical analysis web app, we need a stock ticker, start date, and end date. We can set values to be there automatically just incase the user doesn’t input there own. In this case, I went with Apple’s ticker (AAPL), 2019–01–01 as the start date, and today’s date for the end."
},
{
"code": null,
"e": 2802,
"s": 2632,
"text": "In order to make the web app look a little nicer, we can create a function that sends a request to Yahoo Finance and retrieve the companies name for any ticker we input!"
},
{
"code": null,
"e": 3143,
"s": 2802,
"text": "We can convert the start and end dates from strings to DateTime format using the pandas.to_datetime() method just so we don’t get any errors later on. Lastly, we can retrieve the historical stock data with the Yfinance module that was mentioned earlier. Just to keep track of where we are currently, this is how the web app should look now."
},
{
"code": null,
"e": 3205,
"s": 3143,
"text": "Now, all that is left is creating the graphs we will display."
},
{
"code": null,
"e": 3682,
"s": 3205,
"text": "As I mentioned before, the wonderful TaLib library makes it ridiculously easy to calculate the technical indicators we will be plotting. For this project, I’ve chose the popular indicators such as Moving Average Crossovers, Bollinger Bands, Moving Average Convergence Divergence, Commodity Channel Index, Relative Strength Index, and On Balance Volume. To get more in-depth explanations on what these indicators can show, I would recommend looking them up on Investopedia.com."
},
{
"code": null,
"e": 3993,
"s": 3682,
"text": "For this section of code, there are three primary sections for each indicator we will show. First, we must calculate the indicator using TaLib, then we must set a header title that includes what the indicator actually is, and finally, we can display the chart using streamlit.line_chart(). That’s all it takes!"
},
{
"code": null,
"e": 4259,
"s": 3993,
"text": "Now we have a fully interactive, live, responsive, and easy-to-use web application within a matter of minutes and with less than 100 lines of code. If you’ve been following along this entire time with the code we should have a similar-looking website as down below."
},
{
"code": null,
"e": 4332,
"s": 4259,
"text": "I’ve included the entire code for this program in the GitHub Gist below!"
},
{
"code": null,
"e": 4744,
"s": 4332,
"text": "In terms of the next steps, you could expand on the data we showed as Streamlit allows users to show virtually any type of data, including Pandas DataFrames. Or you can decide to deploy this to the cloud using Heroku (if this is something you would like to do, check out this amazing article by Hamilton Chang). Now that you know how to create your own data web application, the possibilities are truly endless!"
},
{
"code": null,
"e": 4801,
"s": 4744,
"text": "Thank you so much for reading and I hope you enjoyed it!"
},
{
"code": null,
"e": 4945,
"s": 4801,
"text": "Note: If you are deploying this specific app to Heroku, remember to remove TaLib from the requirements.txt and instead, add a buildpack for it!"
}
] |
Getting Started with Python | In the first chapter, we have learnt what web scraping is all about. In this chapter, let us see how to implement web scraping using Python.
Python is a popular tool for implementing web scraping. Python programming language is also used for other useful projects related to cyber security, penetration testing as well as digital forensic applications. Using the base programming of Python, web scraping can be performed without using any other third party tool.
Python programming language is gaining huge popularity and the reasons that make Python a good fit for web scraping projects are as below −
Python has the simplest structure when compared to other programming languages. This feature of Python makes the testing easier and a developer can focus more on programming.
Another reason for using Python for web scraping is the inbuilt as well as external useful libraries it possesses. We can perform many implementations related to web scraping by using Python as the base for programming.
Python has huge support from the community because it is an open source programming language.
Python can be used for various programming tasks ranging from small shell scripts to enterprise web applications.
Python distribution is available for platforms like Windows, MAC and Unix/Linux. We need to download only the binary code applicable for our platform to install Python. But in case if the binary code for our platform is not available, we must have a C compiler so that source code can be compiled manually.
We can install Python on various platforms as follows −
You need to followings steps given below to install Python on Unix/Linux machines −
Step 1 − Go to the link https://www.python.org/downloads/
Step 2 − Download the zipped source code available for Unix/Linux on above link.
Step 3 − Extract the files onto your computer.
Step 4 − Use the following commands to complete the installation −
run ./configure script
make
make install
You can find installed Python at the standard location /usr/local/bin and its libraries at /usr/local/lib/pythonXX, where XX is the version of Python.
You need to followings steps given below to install Python on Windows machines −
Step 1 − Go to the link https://www.python.org/downloads/
Step 2 − Download the Windows installer python-XYZ.msi file, where XYZ is the version we need to install.
Step 3 − Now, save the installer file to your local machine and run the MSI file.
Step 4 − At last, run the downloaded file to bring up the Python install wizard.
We must use Homebrew for installing Python 3 on Mac OS X. Homebrew is easy to install and a great package installer.
Homebrew can also be installed by using the following command −
$ ruby -e "$(curl -fsSL
https://raw.githubusercontent.com/Homebrew/install/master/install)"
For updating the package manager, we can use the following command −
$ brew update
With the help of the following command, we can install Python3 on our MAC machine −
$ brew install python3
You can use the following instructions to set up the path on various environments −
Use the following commands for setting up paths using various command shells −
setenv PATH "$PATH:/usr/local/bin/python".
ATH="$PATH:/usr/local/bin/python".
PATH="$PATH:/usr/local/bin/python".
For setting the path on Windows, we can use the path %path%;C:\Python at the command prompt and then press Enter.
We can start Python using any of the following three ways −
An operating system such as UNIX and DOS that is providing a command-line interpreter or shell can be used for starting Python.
We can start coding in interactive interpreter as follows −
Step 1 − Enter python at the command line.
Step 2 − Then, we can start coding right away in the interactive interpreter.
$python # Unix/Linux
or
python% # Unix/Linux
or
C:> python # Windows/DOS
We can execute a Python script at command line by invoking the interpreter. It can be understood as follows −
$python script.py # Unix/Linux
or
python% script.py # Unix/Linux
or
C: >python script.py # Windows/DOS
We can also run Python from GUI environment if the system is having GUI application that is supporting Python. Some IDEs that support Python on various platforms are given below −
IDE for UNIX − UNIX, for Python, has IDLE IDE.
IDE for Windows − Windows has PythonWin IDE which has GUI too.
IDE for Macintosh − Macintosh has IDLE IDE which is downloadable as either MacBinary or BinHex'd files from the main website.
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2053,
"s": 1912,
"text": "In the first chapter, we have learnt what web scraping is all about. In this chapter, let us see how to implement web scraping using Python."
},
{
"code": null,
"e": 2375,
"s": 2053,
"text": "Python is a popular tool for implementing web scraping. Python programming language is also used for other useful projects related to cyber security, penetration testing as well as digital forensic applications. Using the base programming of Python, web scraping can be performed without using any other third party tool."
},
{
"code": null,
"e": 2515,
"s": 2375,
"text": "Python programming language is gaining huge popularity and the reasons that make Python a good fit for web scraping projects are as below −"
},
{
"code": null,
"e": 2690,
"s": 2515,
"text": "Python has the simplest structure when compared to other programming languages. This feature of Python makes the testing easier and a developer can focus more on programming."
},
{
"code": null,
"e": 2910,
"s": 2690,
"text": "Another reason for using Python for web scraping is the inbuilt as well as external useful libraries it possesses. We can perform many implementations related to web scraping by using Python as the base for programming."
},
{
"code": null,
"e": 3004,
"s": 2910,
"text": "Python has huge support from the community because it is an open source programming language."
},
{
"code": null,
"e": 3118,
"s": 3004,
"text": "Python can be used for various programming tasks ranging from small shell scripts to enterprise web applications."
},
{
"code": null,
"e": 3425,
"s": 3118,
"text": "Python distribution is available for platforms like Windows, MAC and Unix/Linux. We need to download only the binary code applicable for our platform to install Python. But in case if the binary code for our platform is not available, we must have a C compiler so that source code can be compiled manually."
},
{
"code": null,
"e": 3481,
"s": 3425,
"text": "We can install Python on various platforms as follows −"
},
{
"code": null,
"e": 3565,
"s": 3481,
"text": "You need to followings steps given below to install Python on Unix/Linux machines −"
},
{
"code": null,
"e": 3623,
"s": 3565,
"text": "Step 1 − Go to the link https://www.python.org/downloads/"
},
{
"code": null,
"e": 3704,
"s": 3623,
"text": "Step 2 − Download the zipped source code available for Unix/Linux on above link."
},
{
"code": null,
"e": 3751,
"s": 3704,
"text": "Step 3 − Extract the files onto your computer."
},
{
"code": null,
"e": 3818,
"s": 3751,
"text": "Step 4 − Use the following commands to complete the installation −"
},
{
"code": null,
"e": 3860,
"s": 3818,
"text": "run ./configure script\nmake\nmake install\n"
},
{
"code": null,
"e": 4011,
"s": 3860,
"text": "You can find installed Python at the standard location /usr/local/bin and its libraries at /usr/local/lib/pythonXX, where XX is the version of Python."
},
{
"code": null,
"e": 4092,
"s": 4011,
"text": "You need to followings steps given below to install Python on Windows machines −"
},
{
"code": null,
"e": 4150,
"s": 4092,
"text": "Step 1 − Go to the link https://www.python.org/downloads/"
},
{
"code": null,
"e": 4256,
"s": 4150,
"text": "Step 2 − Download the Windows installer python-XYZ.msi file, where XYZ is the version we need to install."
},
{
"code": null,
"e": 4338,
"s": 4256,
"text": "Step 3 − Now, save the installer file to your local machine and run the MSI file."
},
{
"code": null,
"e": 4419,
"s": 4338,
"text": "Step 4 − At last, run the downloaded file to bring up the Python install wizard."
},
{
"code": null,
"e": 4536,
"s": 4419,
"text": "We must use Homebrew for installing Python 3 on Mac OS X. Homebrew is easy to install and a great package installer."
},
{
"code": null,
"e": 4600,
"s": 4536,
"text": "Homebrew can also be installed by using the following command −"
},
{
"code": null,
"e": 4693,
"s": 4600,
"text": "$ ruby -e \"$(curl -fsSL\nhttps://raw.githubusercontent.com/Homebrew/install/master/install)\"\n"
},
{
"code": null,
"e": 4762,
"s": 4693,
"text": "For updating the package manager, we can use the following command −"
},
{
"code": null,
"e": 4777,
"s": 4762,
"text": "$ brew update\n"
},
{
"code": null,
"e": 4861,
"s": 4777,
"text": "With the help of the following command, we can install Python3 on our MAC machine −"
},
{
"code": null,
"e": 4885,
"s": 4861,
"text": "$ brew install python3\n"
},
{
"code": null,
"e": 4969,
"s": 4885,
"text": "You can use the following instructions to set up the path on various environments −"
},
{
"code": null,
"e": 5048,
"s": 4969,
"text": "Use the following commands for setting up paths using various command shells −"
},
{
"code": null,
"e": 5092,
"s": 5048,
"text": "setenv PATH \"$PATH:/usr/local/bin/python\".\n"
},
{
"code": null,
"e": 5128,
"s": 5092,
"text": "ATH=\"$PATH:/usr/local/bin/python\".\n"
},
{
"code": null,
"e": 5165,
"s": 5128,
"text": "PATH=\"$PATH:/usr/local/bin/python\".\n"
},
{
"code": null,
"e": 5279,
"s": 5165,
"text": "For setting the path on Windows, we can use the path %path%;C:\\Python at the command prompt and then press Enter."
},
{
"code": null,
"e": 5339,
"s": 5279,
"text": "We can start Python using any of the following three ways −"
},
{
"code": null,
"e": 5467,
"s": 5339,
"text": "An operating system such as UNIX and DOS that is providing a command-line interpreter or shell can be used for starting Python."
},
{
"code": null,
"e": 5527,
"s": 5467,
"text": "We can start coding in interactive interpreter as follows −"
},
{
"code": null,
"e": 5570,
"s": 5527,
"text": "Step 1 − Enter python at the command line."
},
{
"code": null,
"e": 5648,
"s": 5570,
"text": "Step 2 − Then, we can start coding right away in the interactive interpreter."
},
{
"code": null,
"e": 5722,
"s": 5648,
"text": "$python # Unix/Linux\nor\npython% # Unix/Linux\nor\nC:> python # Windows/DOS\n"
},
{
"code": null,
"e": 5832,
"s": 5722,
"text": "We can execute a Python script at command line by invoking the interpreter. It can be understood as follows −"
},
{
"code": null,
"e": 5936,
"s": 5832,
"text": "$python script.py # Unix/Linux\nor\npython% script.py # Unix/Linux\nor\nC: >python script.py # Windows/DOS\n"
},
{
"code": null,
"e": 6116,
"s": 5936,
"text": "We can also run Python from GUI environment if the system is having GUI application that is supporting Python. Some IDEs that support Python on various platforms are given below −"
},
{
"code": null,
"e": 6163,
"s": 6116,
"text": "IDE for UNIX − UNIX, for Python, has IDLE IDE."
},
{
"code": null,
"e": 6226,
"s": 6163,
"text": "IDE for Windows − Windows has PythonWin IDE which has GUI too."
},
{
"code": null,
"e": 6352,
"s": 6226,
"text": "IDE for Macintosh − Macintosh has IDLE IDE which is downloadable as either MacBinary or BinHex'd files from the main website."
},
{
"code": null,
"e": 6389,
"s": 6352,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 6405,
"s": 6389,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 6438,
"s": 6405,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 6457,
"s": 6438,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 6492,
"s": 6457,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 6514,
"s": 6492,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 6548,
"s": 6514,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 6576,
"s": 6548,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 6611,
"s": 6576,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 6625,
"s": 6611,
"text": " Lets Kode It"
},
{
"code": null,
"e": 6658,
"s": 6625,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 6675,
"s": 6658,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 6682,
"s": 6675,
"text": " Print"
},
{
"code": null,
"e": 6693,
"s": 6682,
"text": " Add Notes"
}
] |
C# Program to Implement the Same Method in Multiple Classes - GeeksforGeeks | 30 Sep, 2021
C# is a general-purpose programming language it is used to create mobile apps, desktop apps, websites, and games. In C#, an object is a real-world entity. Or in other words, an object is a runtime entity that is created at runtime. It is an instance of a class. In this article, Implement the same method in Multiple Classes The implementation of the same method in multiple classes can be achieved by using Interfaces. Interface in C# is just like the class it also has methods, properties, indexers, and events. But it only contains the declaration of the members and the implementation of its members will be given by the class that implements the interface implicitly or explicitly. Or we can say that all the methods which are declared inside the interface are abstract methods. It is used to achieve multiple inheritances which can’t be achieved by class.
Approach:
Create an Interface and declare Method (i.e. greet)
Now create three classes with names Class1, Class2, and Class3 and define the method greet() in all the classes.
Create the class DemoClass and define the main method.
In the Main method create a reference variable for Interface and initialize the reference variable by objects of class1, class2, and class3 and call the method greet().
Example 1:
C#
// C# program to illustrate the above conceptusing System; interface Interface{ // Declaring Method void greet();} // Creating classes and define the method // greet() in all classes.class Class1 : Interface{ public void greet() { Console.WriteLine("Welcome Geeks"); } } class Class2 : Interface{ public void greet() { Console.WriteLine("Hello Geeks"); } } class Class3 : Interface{ public void greet() { Console.WriteLine("Bella Ciao Geeks"); } } class GFG{ public static void Main(String[] args){ // I is the reference variable of Interface Interface I; // Initializing the I with objects of all the // classes one by one and calling the method greet() I = new Class1(); I.greet(); I = new Class2(); I.greet(); I = new Class3(); I.greet();}}
Welcome Geeks
Hello Geeks
Bella Ciao Geeks
Example 2:
C#
// C# program to illustrate the above conceptusing System; // Interfaceinterface Interface{ // Declaring Method void greet();} // Creating classes and define the method// greet() in all classes.class Class1 : Interface{ public void greet() { Console.WriteLine("Welcome Geeks"); } } class Class2 : Interface{ public void greet() { Console.WriteLine("Hello Geeks"); } } class Class3 : Interface{ public void greet() { Console.WriteLine("Bella Ciao Geeks"); } } class Class4 : Interface{ public void greet() { Console.WriteLine("hola geeks"); } } class Class5 : Interface{ public void greet() { Console.WriteLine("welcome to geeksforgeeks"); }} class GFG{ public static void Main(String[] args){ // I is the reference variable of Interface Interface I; // Initializing the I with objects of all the // classes one by one and calling the method greet() I = new Class1(); I.greet(); I = new Class2(); I.greet(); I = new Class3(); I.greet(); I = new Class4(); I.greet(); I = new Class5(); I.greet();}}
Welcome Geeks
Hello Geeks
Bella Ciao Geeks
hola geeks
welcome to geeksforgeeks
CSharp-programs
Picked
Backtracking
C#
Backtracking
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Tug of War
Find if there is a path of more than k length from a source
Difference between Backtracking and Branch-N-Bound technique
N-Queen Problem | Local Search using Hill climbing with random neighbour
Find shortest safe route in a path with landmines
Difference between Abstract Class and Interface in C#
C# | How to check whether a List contains a specified element
C# | IsNullOrEmpty() Method
String.Split() Method in C# with Examples
C# Dictionary with examples | [
{
"code": null,
"e": 24958,
"s": 24930,
"text": "\n30 Sep, 2021"
},
{
"code": null,
"e": 25820,
"s": 24958,
"text": "C# is a general-purpose programming language it is used to create mobile apps, desktop apps, websites, and games. In C#, an object is a real-world entity. Or in other words, an object is a runtime entity that is created at runtime. It is an instance of a class. In this article, Implement the same method in Multiple Classes The implementation of the same method in multiple classes can be achieved by using Interfaces. Interface in C# is just like the class it also has methods, properties, indexers, and events. But it only contains the declaration of the members and the implementation of its members will be given by the class that implements the interface implicitly or explicitly. Or we can say that all the methods which are declared inside the interface are abstract methods. It is used to achieve multiple inheritances which can’t be achieved by class."
},
{
"code": null,
"e": 25830,
"s": 25820,
"text": "Approach:"
},
{
"code": null,
"e": 25882,
"s": 25830,
"text": "Create an Interface and declare Method (i.e. greet)"
},
{
"code": null,
"e": 25995,
"s": 25882,
"text": "Now create three classes with names Class1, Class2, and Class3 and define the method greet() in all the classes."
},
{
"code": null,
"e": 26050,
"s": 25995,
"text": "Create the class DemoClass and define the main method."
},
{
"code": null,
"e": 26219,
"s": 26050,
"text": "In the Main method create a reference variable for Interface and initialize the reference variable by objects of class1, class2, and class3 and call the method greet()."
},
{
"code": null,
"e": 26230,
"s": 26219,
"text": "Example 1:"
},
{
"code": null,
"e": 26233,
"s": 26230,
"text": "C#"
},
{
"code": "// C# program to illustrate the above conceptusing System; interface Interface{ // Declaring Method void greet();} // Creating classes and define the method // greet() in all classes.class Class1 : Interface{ public void greet() { Console.WriteLine(\"Welcome Geeks\"); } } class Class2 : Interface{ public void greet() { Console.WriteLine(\"Hello Geeks\"); } } class Class3 : Interface{ public void greet() { Console.WriteLine(\"Bella Ciao Geeks\"); } } class GFG{ public static void Main(String[] args){ // I is the reference variable of Interface Interface I; // Initializing the I with objects of all the // classes one by one and calling the method greet() I = new Class1(); I.greet(); I = new Class2(); I.greet(); I = new Class3(); I.greet();}}",
"e": 27106,
"s": 26233,
"text": null
},
{
"code": null,
"e": 27149,
"s": 27106,
"text": "Welcome Geeks\nHello Geeks\nBella Ciao Geeks"
},
{
"code": null,
"e": 27160,
"s": 27149,
"text": "Example 2:"
},
{
"code": null,
"e": 27163,
"s": 27160,
"text": "C#"
},
{
"code": "// C# program to illustrate the above conceptusing System; // Interfaceinterface Interface{ // Declaring Method void greet();} // Creating classes and define the method// greet() in all classes.class Class1 : Interface{ public void greet() { Console.WriteLine(\"Welcome Geeks\"); } } class Class2 : Interface{ public void greet() { Console.WriteLine(\"Hello Geeks\"); } } class Class3 : Interface{ public void greet() { Console.WriteLine(\"Bella Ciao Geeks\"); } } class Class4 : Interface{ public void greet() { Console.WriteLine(\"hola geeks\"); } } class Class5 : Interface{ public void greet() { Console.WriteLine(\"welcome to geeksforgeeks\"); }} class GFG{ public static void Main(String[] args){ // I is the reference variable of Interface Interface I; // Initializing the I with objects of all the // classes one by one and calling the method greet() I = new Class1(); I.greet(); I = new Class2(); I.greet(); I = new Class3(); I.greet(); I = new Class4(); I.greet(); I = new Class5(); I.greet();}}",
"e": 28348,
"s": 27163,
"text": null
},
{
"code": null,
"e": 28427,
"s": 28348,
"text": "Welcome Geeks\nHello Geeks\nBella Ciao Geeks\nhola geeks\nwelcome to geeksforgeeks"
},
{
"code": null,
"e": 28443,
"s": 28427,
"text": "CSharp-programs"
},
{
"code": null,
"e": 28450,
"s": 28443,
"text": "Picked"
},
{
"code": null,
"e": 28463,
"s": 28450,
"text": "Backtracking"
},
{
"code": null,
"e": 28466,
"s": 28463,
"text": "C#"
},
{
"code": null,
"e": 28479,
"s": 28466,
"text": "Backtracking"
},
{
"code": null,
"e": 28577,
"s": 28479,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28588,
"s": 28577,
"text": "Tug of War"
},
{
"code": null,
"e": 28648,
"s": 28588,
"text": "Find if there is a path of more than k length from a source"
},
{
"code": null,
"e": 28709,
"s": 28648,
"text": "Difference between Backtracking and Branch-N-Bound technique"
},
{
"code": null,
"e": 28782,
"s": 28709,
"text": "N-Queen Problem | Local Search using Hill climbing with random neighbour"
},
{
"code": null,
"e": 28832,
"s": 28782,
"text": "Find shortest safe route in a path with landmines"
},
{
"code": null,
"e": 28886,
"s": 28832,
"text": "Difference between Abstract Class and Interface in C#"
},
{
"code": null,
"e": 28948,
"s": 28886,
"text": "C# | How to check whether a List contains a specified element"
},
{
"code": null,
"e": 28976,
"s": 28948,
"text": "C# | IsNullOrEmpty() Method"
},
{
"code": null,
"e": 29018,
"s": 28976,
"text": "String.Split() Method in C# with Examples"
}
] |
Accessing inner element of JSON array in MongoDB? | To access inner element of JSON array in MongoDB, use dot notation. Let us create a collection with documents −
> db.demo687.insert({CountryName:'US',
... info:
... {
... id:101,
... details:
... [
... {
... Name:'Chris',
... SubjectName:'MongoDB',
... otherDetails:{
... "Marks":58,
... Age:23
... }
... }
... ]
... }
... }
... )
WriteResult({ "nInserted" : 1 })
> db.demo687.insert({CountryName:'UK',
... info:
... {
... id:102,
... details:
... [
... {
... Name:'David',
... SubjectName:'MySQL',
... otherDetails:{
... "Marks":78,
... Age:21
... }
... }
... ]
... }
... }
... )
WriteResult({ "nInserted" : 1 })
Display all documents from a collection with the help of find() method −
> db.demo687.find();
This will produce the following output −
{ "_id" : ObjectId("5ea55658a7e81adc6a0b3962"), "CountryName" : "US", "info" : { "id" : 101, "details" : [ { "Name" : "Chris", "SubjectName" : "MongoDB", "otherDetails" : { "Marks" : 58, "Age" : 23 } } ] } }
{ "_id" : ObjectId("5ea55673a7e81adc6a0b3963"), "CountryName" : "UK", "info" : { "id" : 102, "details" : [ { "Name" : "David", "SubjectName" : "MySQL", "otherDetails" : { "Marks" : 78, "Age" : 21 } } ] } }
Following is the query to access inner element of JSON array −
> db.demo687.find({"info.details.otherDetails.Marks":58});
This will produce the following output −
{ "_id" : ObjectId("5ea55658a7e81adc6a0b3962"), "CountryName" : "US", "info" : { "id" : 101, "details" : [ { "Name" : "Chris", "SubjectName" : "MongoDB", "otherDetails" : { "Marks" : 58, "Age" : 23 } } ] } } | [
{
"code": null,
"e": 1174,
"s": 1062,
"text": "To access inner element of JSON array in MongoDB, use dot notation. Let us create a collection with documents −"
},
{
"code": null,
"e": 1724,
"s": 1174,
"text": "> db.demo687.insert({CountryName:'US',\n... info:\n... {\n... id:101,\n... details:\n... [\n... {\n... Name:'Chris',\n... SubjectName:'MongoDB',\n... otherDetails:{\n... \"Marks\":58,\n... Age:23\n... }\n... }\n... ]\n... }\n... }\n... )\nWriteResult({ \"nInserted\" : 1 })\n> db.demo687.insert({CountryName:'UK',\n... info:\n... {\n... id:102,\n... details:\n... [\n... {\n... Name:'David',\n... SubjectName:'MySQL',\n... otherDetails:{\n... \"Marks\":78,\n... Age:21\n... }\n... }\n... ]\n... }\n... }\n... )\nWriteResult({ \"nInserted\" : 1 })"
},
{
"code": null,
"e": 1797,
"s": 1724,
"text": "Display all documents from a collection with the help of find() method −"
},
{
"code": null,
"e": 1818,
"s": 1797,
"text": "> db.demo687.find();"
},
{
"code": null,
"e": 1859,
"s": 1818,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2273,
"s": 1859,
"text": "{ \"_id\" : ObjectId(\"5ea55658a7e81adc6a0b3962\"), \"CountryName\" : \"US\", \"info\" : { \"id\" : 101, \"details\" : [ { \"Name\" : \"Chris\", \"SubjectName\" : \"MongoDB\", \"otherDetails\" : { \"Marks\" : 58, \"Age\" : 23 } } ] } }\n{ \"_id\" : ObjectId(\"5ea55673a7e81adc6a0b3963\"), \"CountryName\" : \"UK\", \"info\" : { \"id\" : 102, \"details\" : [ { \"Name\" : \"David\", \"SubjectName\" : \"MySQL\", \"otherDetails\" : { \"Marks\" : 78, \"Age\" : 21 } } ] } }"
},
{
"code": null,
"e": 2336,
"s": 2273,
"text": "Following is the query to access inner element of JSON array −"
},
{
"code": null,
"e": 2395,
"s": 2336,
"text": "> db.demo687.find({\"info.details.otherDetails.Marks\":58});"
},
{
"code": null,
"e": 2436,
"s": 2395,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2644,
"s": 2436,
"text": "{ \"_id\" : ObjectId(\"5ea55658a7e81adc6a0b3962\"), \"CountryName\" : \"US\", \"info\" : { \"id\" : 101, \"details\" : [ { \"Name\" : \"Chris\", \"SubjectName\" : \"MongoDB\", \"otherDetails\" : { \"Marks\" : 58, \"Age\" : 23 } } ] } }"
}
] |
Convert Infix to Prefix Expression | To solve expressions by the computer, we can either convert it in postfix form or to the prefix form. Here we will see how infix expressions are converted to prefix form.
At first infix expression is reversed. Note that for reversing the opening and closing parenthesis will also be reversed.
for an example: The expression: A + B * (C - D)
after reversing the expression will be: ) D – C ( * B + A
so we need to convert opening parenthesis to closing parenthesis and vice versa.
After reversing, the expression is converted to postfix form by using infix to postfix algorithm. After that again the postfix expression is reversed to get the prefix expression.
Input:
Infix Expression: x^y/(5*z)+2
Output:
Prefix Form Is: +/^xy*5z2
infixToPrefix(infix)
Input − Infix expression to convert into prefix form.
Output − The prefix expression.
Begin
reverse the infix expression
for each character ch of reversed infix expression, do
if ch = opening parenthesis, then
convert ch to closing parenthesis
else if ch = closing parenthesis, then
convert ch to opening parenthesis
done
postfix := find transformed infix expression to postfix expression
prefix := reverse recently calculated postfix form
return prefix
End
#include<iostream>
#include<stack>
#include<locale> //for function isalnum()
#include<algorithm>
using namespace std;
int preced(char ch) {
if(ch == '+' || ch == '-') {
return 1; //Precedence of + or - is 1
}else if(ch == '*' || ch == '/') {
return 2; //Precedence of * or / is 2
}else if(ch == '^') {
return 3; //Precedence of ^ is 3
}else {
return 0;
}
}
string inToPost(string infix) {
stack<char> stk;
stk.push('#'); //add some extra character to avoid underflow
string postfix = ""; //initially the postfix string is empty
string::iterator it;
for(it = infix.begin(); it!=infix.end(); it++) {
if(isalnum(char(*it)))
postfix += *it; //add to postfix when character is letter or number
else if(*it == '(')
stk.push('(');
else if(*it == '^')
stk.push('^');
else if(*it == ')') {
while(stk.top() != '#' && stk.top() != '(') {
postfix += stk.top(); //store and pop until ( has found
stk.pop();
}
stk.pop(); //remove the '(' from stack
}else {
if(preced(*it) > preced(stk.top()))
stk.push(*it); //push if precedence is high
else {
while(stk.top() != '#' && preced(*it) <= preced(stk.top())) {
postfix += stk.top(); //store and pop until higher precedence is found
stk.pop();
}
stk.push(*it);
}
}
}
while(stk.top() != '#') {
postfix += stk.top(); //store and pop until stack is not empty
stk.pop();
}
return postfix;
}
string inToPre(string infix) {
string prefix;
reverse(infix.begin(), infix.end()); //reverse the infix expression
string::iterator it;
for(it = infix.begin(); it != infix.end(); it++) { //reverse the parenthesis after reverse
if(*it == '(')
*it = ')';
else if(*it == ')')
*it = '(';
}
prefix = inToPost(infix); //convert new reversed infix to postfix form.
reverse(prefix.begin(), prefix.end()); //again reverse the result to get final prefix form
return prefix;
}
int main() {
string infix = "x^y/(5*z)+2";
cout << "Prefix Form Is: " << inToPre(infix) << endl;
}
Prefix Form Is: +/^xy*5z2 | [
{
"code": null,
"e": 1233,
"s": 1062,
"text": "To solve expressions by the computer, we can either convert it in postfix form or to the prefix form. Here we will see how infix expressions are converted to prefix form."
},
{
"code": null,
"e": 1355,
"s": 1233,
"text": "At first infix expression is reversed. Note that for reversing the opening and closing parenthesis will also be reversed."
},
{
"code": null,
"e": 1403,
"s": 1355,
"text": "for an example: The expression: A + B * (C - D)"
},
{
"code": null,
"e": 1461,
"s": 1403,
"text": "after reversing the expression will be: ) D – C ( * B + A"
},
{
"code": null,
"e": 1542,
"s": 1461,
"text": "so we need to convert opening parenthesis to closing parenthesis and vice versa."
},
{
"code": null,
"e": 1722,
"s": 1542,
"text": "After reversing, the expression is converted to postfix form by using infix to postfix algorithm. After that again the postfix expression is reversed to get the prefix expression."
},
{
"code": null,
"e": 1793,
"s": 1722,
"text": "Input:\nInfix Expression: x^y/(5*z)+2\nOutput:\nPrefix Form Is: +/^xy*5z2"
},
{
"code": null,
"e": 1814,
"s": 1793,
"text": "infixToPrefix(infix)"
},
{
"code": null,
"e": 1868,
"s": 1814,
"text": "Input − Infix expression to convert into prefix form."
},
{
"code": null,
"e": 1900,
"s": 1868,
"text": "Output − The prefix expression."
},
{
"code": null,
"e": 2321,
"s": 1900,
"text": "Begin\n reverse the infix expression\n for each character ch of reversed infix expression, do\n if ch = opening parenthesis, then\n convert ch to closing parenthesis\n else if ch = closing parenthesis, then\n convert ch to opening parenthesis\n done\n\n postfix := find transformed infix expression to postfix expression\n prefix := reverse recently calculated postfix form\n return prefix\nEnd"
},
{
"code": null,
"e": 4627,
"s": 2321,
"text": "#include<iostream>\n#include<stack>\n#include<locale> //for function isalnum()\n#include<algorithm>\nusing namespace std;\n\nint preced(char ch) {\n if(ch == '+' || ch == '-') {\n return 1; //Precedence of + or - is 1\n }else if(ch == '*' || ch == '/') {\n return 2; //Precedence of * or / is 2\n }else if(ch == '^') {\n return 3; //Precedence of ^ is 3\n }else {\n return 0;\n }\n}\n\nstring inToPost(string infix) {\n stack<char> stk;\n stk.push('#'); //add some extra character to avoid underflow\n string postfix = \"\"; //initially the postfix string is empty\n string::iterator it;\n\n for(it = infix.begin(); it!=infix.end(); it++) {\n if(isalnum(char(*it)))\n postfix += *it; //add to postfix when character is letter or number\n else if(*it == '(')\n stk.push('(');\n else if(*it == '^')\n stk.push('^');\n else if(*it == ')') {\n while(stk.top() != '#' && stk.top() != '(') {\n postfix += stk.top(); //store and pop until ( has found\n stk.pop();\n }\n\n stk.pop(); //remove the '(' from stack\n }else {\n if(preced(*it) > preced(stk.top()))\n stk.push(*it); //push if precedence is high\n else {\n while(stk.top() != '#' && preced(*it) <= preced(stk.top())) {\n postfix += stk.top(); //store and pop until higher precedence is found\n stk.pop();\n }\n stk.push(*it);\n }\n }\n }\n\n while(stk.top() != '#') {\n postfix += stk.top(); //store and pop until stack is not empty\n\n stk.pop();\n\n }\n return postfix;\n}\n\nstring inToPre(string infix) {\n string prefix;\n reverse(infix.begin(), infix.end()); //reverse the infix expression\n string::iterator it;\n\n for(it = infix.begin(); it != infix.end(); it++) { //reverse the parenthesis after reverse\n if(*it == '(')\n *it = ')';\n else if(*it == ')')\n *it = '(';\n }\n\n prefix = inToPost(infix); //convert new reversed infix to postfix form.\n reverse(prefix.begin(), prefix.end()); //again reverse the result to get final prefix form\n return prefix;\n}\n\nint main() {\n string infix = \"x^y/(5*z)+2\";\n cout << \"Prefix Form Is: \" << inToPre(infix) << endl;\n}"
},
{
"code": null,
"e": 4653,
"s": 4627,
"text": "Prefix Form Is: +/^xy*5z2"
}
] |
Extracting rows using Pandas .iloc[] in Python | Pandas is a famous python library that Is extensively used for data processing and analysis in python. In this article we will see how to use the .iloc method which is used for reading selective data from python by filtering both rows and columns from the dataframe.
iloc method processes data by using integer based indexes which may or may not be part of the original data set. The first row is assigned index 0 and second and index 1 and so on. Similarly, the first column is index 0 and second is index 1 and so on.
Below is the data set which we are going to use.
Id SepalLengthCm ... PetalLengthCm PetalWidthCm
Iris-setosa-1 5.1 ... 1.4 0.2
Iris-setosa-2 4.9 ... 1.4 0.2
Iris-setosa-3 4.7 ... 1.3 0.2
We can select both a single row and multiple rows by specifying the integer for the index. In the below example we are selecting individual rows at row 0 and row 1.
import pandas as pd
# Create data frame from csv file
data = pd.read_csv("D:\\Iris_readings.csv")
row0 = data.iloc[0]
row1 = data.iloc[1]
print(row0)
print(row1)
Running the above code gives us the following result −
Id Iris-setosa-1
SepalLengthCm 5.1
SepalWidthCm 3.5
PetalLengthCm 1.4
PetalWidthCm 0.2
Name: 0, dtype: object
Id Iris-setosa-2
SepalLengthCm 4.9
SepalWidthCm 3
PetalLengthCm 1.4
PetalWidthCm 0.2
Name: 1, dtype: object
In the below example we select many rows together at one shot by mentioning the slice of the rows we need.
import pandas as pd
# making data frame from csv file
data = pd.read_csv("D:\\Iris_readings.csv")
rows = data.iloc[4:8]
print(rows)
Running the above code gives us the following result −
Id SepalLengthCm SepalWidthCm PetalLengthCm PetalWidthCm
4 Iris-setosa-5 5.0 3.6 1.4 0.2
5 Iris-versicolor-51 7.0 3.2 4.7 1.4
6 Iris-versicolor-52 6.4 3.2 4.5 1.5
7 Iris-versicolor-53 6.9 3.1 4.9 1.5
In the below example we can select both rows and columns as necessary.
import pandas as pd
# making data frame from csv file
data = pd.read_csv("D:\\Iris_readings.csv")
rows_columns = data.iloc[4:8,0:2]
print(rows_columns)
Running the above code gives us the following result −
Id SepalLengthCm
4 Iris-setosa-5 5.0
5 Iris-versicolor-51 7.0
6 Iris-versicolor-52 6.4
7 Iris-versicolor-53 6.9 | [
{
"code": null,
"e": 1329,
"s": 1062,
"text": "Pandas is a famous python library that Is extensively used for data processing and analysis in python. In this article we will see how to use the .iloc method which is used for reading selective data from python by filtering both rows and columns from the dataframe."
},
{
"code": null,
"e": 1582,
"s": 1329,
"text": "iloc method processes data by using integer based indexes which may or may not be part of the original data set. The first row is assigned index 0 and second and index 1 and so on. Similarly, the first column is index 0 and second is index 1 and so on."
},
{
"code": null,
"e": 1631,
"s": 1582,
"text": "Below is the data set which we are going to use."
},
{
"code": null,
"e": 1880,
"s": 1631,
"text": "Id SepalLengthCm ... PetalLengthCm PetalWidthCm\nIris-setosa-1 5.1 ... 1.4 0.2\nIris-setosa-2 4.9 ... 1.4 0.2\nIris-setosa-3 4.7 ... 1.3 0.2"
},
{
"code": null,
"e": 2045,
"s": 1880,
"text": "We can select both a single row and multiple rows by specifying the integer for the index. In the below example we are selecting individual rows at row 0 and row 1."
},
{
"code": null,
"e": 2209,
"s": 2045,
"text": "import pandas as pd\n\n# Create data frame from csv file\ndata = pd.read_csv(\"D:\\\\Iris_readings.csv\")\n\nrow0 = data.iloc[0]\nrow1 = data.iloc[1]\nprint(row0)\nprint(row1)"
},
{
"code": null,
"e": 2264,
"s": 2209,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 2525,
"s": 2264,
"text": "Id Iris-setosa-1\nSepalLengthCm 5.1\nSepalWidthCm 3.5\nPetalLengthCm 1.4\nPetalWidthCm 0.2\nName: 0, dtype: object\n\nId Iris-setosa-2\nSepalLengthCm 4.9\nSepalWidthCm 3\nPetalLengthCm 1.4\nPetalWidthCm 0.2\nName: 1, dtype: object"
},
{
"code": null,
"e": 2632,
"s": 2525,
"text": "In the below example we select many rows together at one shot by mentioning the slice of the rows we need."
},
{
"code": null,
"e": 2766,
"s": 2632,
"text": "import pandas as pd\n\n# making data frame from csv file\ndata = pd.read_csv(\"D:\\\\Iris_readings.csv\")\n\nrows = data.iloc[4:8]\nprint(rows)"
},
{
"code": null,
"e": 2821,
"s": 2766,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 3209,
"s": 2821,
"text": " Id SepalLengthCm SepalWidthCm PetalLengthCm PetalWidthCm\n4 Iris-setosa-5 5.0 3.6 1.4 0.2\n5 Iris-versicolor-51 7.0 3.2 4.7 1.4\n6 Iris-versicolor-52 6.4 3.2 4.5 1.5\n7 Iris-versicolor-53 6.9 3.1 4.9 1.5"
},
{
"code": null,
"e": 3280,
"s": 3209,
"text": "In the below example we can select both rows and columns as necessary."
},
{
"code": null,
"e": 3434,
"s": 3280,
"text": "import pandas as pd\n\n# making data frame from csv file\ndata = pd.read_csv(\"D:\\\\Iris_readings.csv\")\n\nrows_columns = data.iloc[4:8,0:2]\nprint(rows_columns)"
},
{
"code": null,
"e": 3489,
"s": 3434,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 3646,
"s": 3489,
"text": " Id SepalLengthCm\n4 Iris-setosa-5 5.0\n5 Iris-versicolor-51 7.0\n6 Iris-versicolor-52 6.4\n7 Iris-versicolor-53 6.9"
}
] |
C# Linq SelectMany Method | Use SelectMany method to collapse elements into a single collection like an error.
An example would be to convert string to character array. The following is our string array.
string[] str = { "Mobile", "Laptop", "Tablet" };
Now, convert to character array.
str.SelectMany(item => item.ToCharArray());
Live Demo
using System;
using System.Linq;
using System.Collections.Generic;
public class Demo {
public static void Main() {
string[] str = { "Mobile", "Laptop", "Tablet" };
var res = str.SelectMany(item => item.ToCharArray());
Console.WriteLine("String converted to character array: ");
foreach (char letter in res) {
Console.Write(letter);
}
}
}
String converted to character array:
MobileLaptopTablet | [
{
"code": null,
"e": 1145,
"s": 1062,
"text": "Use SelectMany method to collapse elements into a single collection like an error."
},
{
"code": null,
"e": 1238,
"s": 1145,
"text": "An example would be to convert string to character array. The following is our string array."
},
{
"code": null,
"e": 1287,
"s": 1238,
"text": "string[] str = { \"Mobile\", \"Laptop\", \"Tablet\" };"
},
{
"code": null,
"e": 1320,
"s": 1287,
"text": "Now, convert to character array."
},
{
"code": null,
"e": 1364,
"s": 1320,
"text": "str.SelectMany(item => item.ToCharArray());"
},
{
"code": null,
"e": 1375,
"s": 1364,
"text": " Live Demo"
},
{
"code": null,
"e": 1758,
"s": 1375,
"text": "using System;\nusing System.Linq;\nusing System.Collections.Generic;\npublic class Demo {\n public static void Main() {\n string[] str = { \"Mobile\", \"Laptop\", \"Tablet\" };\n var res = str.SelectMany(item => item.ToCharArray());\n Console.WriteLine(\"String converted to character array: \");\n foreach (char letter in res) {\n Console.Write(letter);\n }\n }\n}"
},
{
"code": null,
"e": 1814,
"s": 1758,
"text": "String converted to character array:\nMobileLaptopTablet"
}
] |
Performance of paging - GeeksforGeeks | 23 Oct, 2020
In this article, we are going to cover the performance of paging and will also cover the expression for evaluating paging performance. Let’s discuss one by one.
Pre-requisite –Paging in Operating System
Performance of Paging :Evaluating of paging performance is one of the important tasks. Consider the main memory access time is M and the page table is stored in the main memory then the evaluating expression for effective memory access time is as follows.
Effective Memory Access Time (E.M.A.T) = 2M
Features of Performance of Paging :
Translation lookaside buffer(TLB) is added to improve the performance of paging.
The TLB is a hardware device implemented using associative registers.
TLB access time will be very less compared to the main memory access time.
TLB contains frequently referred page numbers and corresponding frame numbers.
Now, let’s see the diagram given below of the performance of paging for a better understanding.
Evaluating Expression for the performance of paging :
Consider the TLB access time is ‘c’. And the TLB hit ratio is ‘x’ then the Evaluating Expression for the performance of paging is as follows.
Effective Memory Access Time (E.M.A.T) with TLB
= x(c+m) + (1-x) (c + 2 m)
Operating Systems-Memory Management
GATE CS
Operating Systems
Operating Systems
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Differences between IPv4 and IPv6
Preemptive and Non-Preemptive Scheduling
Difference between Clustered and Non-clustered index
Phases of a Compiler
Three address code in Compiler
Banker's Algorithm in Operating System
Program for FCFS CPU Scheduling | Set 1
Paging in Operating System
Introduction of Deadlock in Operating System
Program for Round Robin scheduling | Set 1 | [
{
"code": null,
"e": 25627,
"s": 25599,
"text": "\n23 Oct, 2020"
},
{
"code": null,
"e": 25788,
"s": 25627,
"text": "In this article, we are going to cover the performance of paging and will also cover the expression for evaluating paging performance. Let’s discuss one by one."
},
{
"code": null,
"e": 25830,
"s": 25788,
"text": "Pre-requisite –Paging in Operating System"
},
{
"code": null,
"e": 26086,
"s": 25830,
"text": "Performance of Paging :Evaluating of paging performance is one of the important tasks. Consider the main memory access time is M and the page table is stored in the main memory then the evaluating expression for effective memory access time is as follows."
},
{
"code": null,
"e": 26131,
"s": 26086,
"text": "Effective Memory Access Time (E.M.A.T) = 2M\n"
},
{
"code": null,
"e": 26167,
"s": 26131,
"text": "Features of Performance of Paging :"
},
{
"code": null,
"e": 26248,
"s": 26167,
"text": "Translation lookaside buffer(TLB) is added to improve the performance of paging."
},
{
"code": null,
"e": 26318,
"s": 26248,
"text": "The TLB is a hardware device implemented using associative registers."
},
{
"code": null,
"e": 26393,
"s": 26318,
"text": "TLB access time will be very less compared to the main memory access time."
},
{
"code": null,
"e": 26472,
"s": 26393,
"text": "TLB contains frequently referred page numbers and corresponding frame numbers."
},
{
"code": null,
"e": 26568,
"s": 26472,
"text": "Now, let’s see the diagram given below of the performance of paging for a better understanding."
},
{
"code": null,
"e": 26622,
"s": 26568,
"text": "Evaluating Expression for the performance of paging :"
},
{
"code": null,
"e": 26764,
"s": 26622,
"text": "Consider the TLB access time is ‘c’. And the TLB hit ratio is ‘x’ then the Evaluating Expression for the performance of paging is as follows."
},
{
"code": null,
"e": 26840,
"s": 26764,
"text": "Effective Memory Access Time (E.M.A.T) with TLB\n= x(c+m) + (1-x) (c + 2 m)\n"
},
{
"code": null,
"e": 26876,
"s": 26840,
"text": "Operating Systems-Memory Management"
},
{
"code": null,
"e": 26884,
"s": 26876,
"text": "GATE CS"
},
{
"code": null,
"e": 26902,
"s": 26884,
"text": "Operating Systems"
},
{
"code": null,
"e": 26920,
"s": 26902,
"text": "Operating Systems"
},
{
"code": null,
"e": 27018,
"s": 26920,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27052,
"s": 27018,
"text": "Differences between IPv4 and IPv6"
},
{
"code": null,
"e": 27093,
"s": 27052,
"text": "Preemptive and Non-Preemptive Scheduling"
},
{
"code": null,
"e": 27146,
"s": 27093,
"text": "Difference between Clustered and Non-clustered index"
},
{
"code": null,
"e": 27167,
"s": 27146,
"text": "Phases of a Compiler"
},
{
"code": null,
"e": 27198,
"s": 27167,
"text": "Three address code in Compiler"
},
{
"code": null,
"e": 27237,
"s": 27198,
"text": "Banker's Algorithm in Operating System"
},
{
"code": null,
"e": 27277,
"s": 27237,
"text": "Program for FCFS CPU Scheduling | Set 1"
},
{
"code": null,
"e": 27304,
"s": 27277,
"text": "Paging in Operating System"
},
{
"code": null,
"e": 27349,
"s": 27304,
"text": "Introduction of Deadlock in Operating System"
}
] |
Python | Numpy matrix.argmax() - GeeksforGeeks | 10 Apr, 2019
With the help of Numpy matrix.argmax() method, we are able to find the index value of the maximum element in the given matrix having one or more dimension.
Syntax : matrix.argmax()
Return : Return index number of maximum element in matrix
Example #1 :In this example we can see that with the help of matrix.argmax() method we are able to find the index of maximum element in a given matrix.
# import the important module in pythonimport numpy as np # make a matrix with numpygfg = np.matrix('[1, 2, 3, 4]') # applying matrix.argmax() methodgeeks = gfg.argmax() print(geeks)
3
Example #2 :
# import the important module in pythonimport numpy as np # make a matrix with numpygfg = np.matrix('[1, 2, 3; 4, 5, 6; 7, 8, 9]') # applying matrix.argmax() methodgeeks = gfg.argmax() print(geeks)
8
Python numpy-Matrix Function
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Reading and Writing to text files in Python
*args and **kwargs in Python
Convert integer to string in Python
Create a Pandas DataFrame from Lists
Check if element exists in list in Python | [
{
"code": null,
"e": 25709,
"s": 25681,
"text": "\n10 Apr, 2019"
},
{
"code": null,
"e": 25865,
"s": 25709,
"text": "With the help of Numpy matrix.argmax() method, we are able to find the index value of the maximum element in the given matrix having one or more dimension."
},
{
"code": null,
"e": 25890,
"s": 25865,
"text": "Syntax : matrix.argmax()"
},
{
"code": null,
"e": 25948,
"s": 25890,
"text": "Return : Return index number of maximum element in matrix"
},
{
"code": null,
"e": 26100,
"s": 25948,
"text": "Example #1 :In this example we can see that with the help of matrix.argmax() method we are able to find the index of maximum element in a given matrix."
},
{
"code": "# import the important module in pythonimport numpy as np # make a matrix with numpygfg = np.matrix('[1, 2, 3, 4]') # applying matrix.argmax() methodgeeks = gfg.argmax() print(geeks)",
"e": 26307,
"s": 26100,
"text": null
},
{
"code": null,
"e": 26310,
"s": 26307,
"text": "3\n"
},
{
"code": null,
"e": 26323,
"s": 26310,
"text": "Example #2 :"
},
{
"code": "# import the important module in pythonimport numpy as np # make a matrix with numpygfg = np.matrix('[1, 2, 3; 4, 5, 6; 7, 8, 9]') # applying matrix.argmax() methodgeeks = gfg.argmax() print(geeks)",
"e": 26545,
"s": 26323,
"text": null
},
{
"code": null,
"e": 26548,
"s": 26545,
"text": "8\n"
},
{
"code": null,
"e": 26577,
"s": 26548,
"text": "Python numpy-Matrix Function"
},
{
"code": null,
"e": 26590,
"s": 26577,
"text": "Python-numpy"
},
{
"code": null,
"e": 26597,
"s": 26590,
"text": "Python"
},
{
"code": null,
"e": 26695,
"s": 26597,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26713,
"s": 26695,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26748,
"s": 26713,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 26780,
"s": 26748,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26822,
"s": 26780,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 26848,
"s": 26822,
"text": "Python String | replace()"
},
{
"code": null,
"e": 26892,
"s": 26848,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 26921,
"s": 26892,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 26957,
"s": 26921,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 26994,
"s": 26957,
"text": "Create a Pandas DataFrame from Lists"
}
] |
Java.lang.ProcessBuilder class in Java - GeeksforGeeks | 14 Jan, 2022
This class is used to create operating system processes. Each ProcessBuilder instance manages a collection of process attributes. The start() method creates a new Process instance with those attributes. The start() method can be invoked repeatedly from the same instance to create new subprocesses with identical or related attributes.
ProcessBuilder can be used to help create an operating system process.
Before JDK 5.0, the only way to create a process and execute it was to use Runtime.exec() method.
It extends the class Object.
This class is not synchronized.
Constructor:
ProcessBuilder(List command): This constructs a process builder with the specified operating system program and arguments.
ProcessBuilder(String... command): This constructs a process builder with the specified operating system program and arguments.
Methods:
1. List command(): This method returns the process builder’s operating system program and arguments.
Syntax: public List command().
Returns: this process builder's program and its arguments.
Exceptions: NullPointerException - if the argument is null.
Java
// Java code illustrating command() methodimport java.io.*;import java.lang.*;import java.util.*;class ProcessBuilderDemo { public static void main(String[] arg) throws IOException { // creating list of process List<String> list = new ArrayList<String>(); list.add("notepad.exe"); // create the process ProcessBuilder build = new ProcessBuilder(list); // checking the command i list System.out.println("command: " + build.command()); }}
command: [notepad.exe]
2. ProcessBuilder command(List command): This method sets the process builder’s operating system program and arguments.
Syntax: public ProcessBuilder command(List command).
Returns: NA.
Exception: NullPointerException - if the argument is null.
Java
// Java code illustrating ProcessBuilder// command(List<String> command)import java.io.*;import java.lang.*;import java.util.*;class ProcessBuilderDemo { public static void main(String[] arg) throws IOException { // creating list of process List<String> list = new ArrayList<String>(); list.add("notepad.exe"); list.add("xyz.txt"); // create the process ProcessBuilder build = new ProcessBuilder(list); // checking the command in list System.out.println("command: " + build.command()); }}
command: [notepad.exe, xyz.txt]
3. ProcessBuilder directory(File directory): This method sets the process builder’s working directory. Subprocesses subsequently started by object’s start() method will use it as their working directory. The argument may be null – which means to use the working directory of the current Java process, usually, the directory named by the system property user.dir, as the working directory of the child process.
Syntax: public ProcessBuilder directory(File directory).
Returns: this process builder.
Exception: NA.
Java
// Java code illustrating directory() methodimport java.io.*;import java.lang.*;import java.util.*;class ProcessBuilderDemo { public static void main(String[] arg) throws IOException { // creating list of process List<String> list = new ArrayList<String>(); list.add("notepad.exe"); list.add("abc.txt"); // creating the process ProcessBuilder build = new ProcessBuilder(list); // setting the directory build.directory(new File("src")); // checking the directory, on which currently // working on System.out.println("directory: " + build.directory()); }}
directory: src
4. Map environment(): This method returns a string map view of the process builder’s environment. Whenever a process builder is created, the environment is initialized to a copy of the current process environment. Subprocesses subsequently started by the object’s start() method will use this map as their environment.
Syntax: public Map environment()
Returns: this process builder's environment
Exception: SecurityException - if a security manager exists
and its checkPermission method doesn't allow access to the process environment.
Java
// Java code illustrating environment() methodimport java.io.*;import java.util.*;class ProcessBuilderDemo { public static void main(String[] arg) throws IOException { // creating the process ProcessBuilder pb = new ProcessBuilder(); // map view of this process builder's environment Map<String, String> envMap = pb.environment(); // checking map view of environment for (Map.Entry<String, String> entry : envMap.entrySet()) { // checking key and value separately System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); } }}
Output:
Key = PATH, Value = /usr/bin:/bin:/usr/sbin:/sbin
Key = JAVA_MAIN_CLASS_14267, Value = ProcessBuilderDemo
Key = J2D_PIXMAPS, Value = shared
Key = SHELL, Value = /bin/bash
Key = JAVA_MAIN_CLASS_11858, Value = org.netbeans.Main
Key = USER, Value = abhishekverma
Key = TMPDIR, Value = /var/folders/9z/p63ysmfd797clc0468vvy4980000gn/T/
Key = SSH_AUTH_SOCK, Value = /private/tmp/com.apple.launchd.uWvCfYQWBP/Listeners
Key = XPC_FLAGS, Value = 0x0
Key = LD_LIBRARY_PATH, Value = /Library/Java/JavaVirtualMachines
/jdk1.8.0_121.jdk/Contents/Home/jre/lib/
amd64:/Library/Java/JavaVirtualMachines/jdk1.8.0_121.jdk
/Contents/Home/jre/lib/i386:
Key = __CF_USER_TEXT_ENCODING, Value = 0x1F5:0x0:0x0
Key = Apple_PubSub_Socket_Render, Value = /private/tmp/com.apple.launchd.weuNq4pAfF/Render
Key = LOGNAME, Value = abhishekverma
Key = LC_CTYPE, Value = UTF-8
Key = XPC_SERVICE_NAME, Value = 0
Key = PWD, Value = /
Key = SHLVL, Value = 1
Key = HOME, Value = /Users/abhishekverma
Key = _, Value = /Library/Java/JavaVirtualMachines/
jdk1.8.0_121.jdk/Contents/Home/bin/java
Understanding the above output: The output is the map view of the subprocess build upon. The above output varies from user to user totally depends upon the operating system and user.
5. boolean redirectErrorStream(): This method tells whether the process builder merges standard error and standard output. If this property is true, then any error output generated by subprocesses subsequently started by the object’s start() method will be merged with the standard output, so that both can be read using the Process.getInputStream() method. It makes it easier to correlate error messages with the corresponding output. The initial value is false.
Syntax: public boolean redirectErrorStream().
Returns: this process builder's redirectErrorStream property.
Exception: NA.
Java
// Java code illustrating redirectErrorStream() methodimport java.io.*;import java.lang.*;import java.util.*;class ProcessBuilderDemo { public static void main(String[] arg) throws IOException { // creating list of commands List list = new ArrayList(); list.add("notepad.exe"); list.add("xyz.txt"); // creating the process ProcessBuilder build = new ProcessBuilder(list); // checking if error stream is redirected System.out.println(build.redirectErrorStream()); }}
Output:
false
6. ProcessBuilder redirectErrorStream(boolean redirectErrorStream): This method sets this process builder’s redirectErrorStream property. If this property is true, then any error output generated by subprocesses subsequently started by this object’s start() method will be merged with the standard output so that both can be read using the Process.getInputStream() method. This makes it easier to correlate error messages with the corresponding output. The initial value is false.
Syntax: public ProcessBuilder redirectErrorStream(boolean redirectErrorStream).
Returns: this process builder.
Exception: NA.
Java
// Java code illustrating redirectErrorStream(boolean// redirectErrorStream) methodimport java.io.*;import java.lang.*;import java.util.*;class ProcessBuilderDemo { public static void main(String[] arg) throws IOException { // creating list of commands List list = new ArrayList(); list.add("notepad.exe"); list.add("xyz.txt"); // creating the process ProcessBuilder build = new ProcessBuilder(list); // redirecting error stream build.redirectErrorStream(true); // checking if error stream is redirected System.out.println(build.redirectErrorStream()); }}
Output:
true
Process start(): This method starts a new process using the attributes of the process builder. The new process will invoke the command and arguments given by command(), in a working directory as given by directory(), with a process environment as given by environment(). This method checks that the command is a valid operating system command. Which commands are valid is system-dependent, but at the very least the command must be a non-empty list of non-null strings. If there is a security manager, its checkExec method is called with the first component of this object’s command array as its argument. It may result in a SecurityException being thrown.
Syntax: public Process start().
Returns: a new Process object for managing the subprocess.
Exception: NullPointerException - If an element of the command list is null
IndexOutOfBoundsException - If the command is an empty list (has size 0).
SecurityException - If a security manager exists
and its checkExec method doesn't allow creation of the subprocess.
IOException - If an I/O error occurs.
Java
// Java code illustrating start() methodimport java.io.*;import java.lang.*;import java.util.*;class ProcessBuilderDemo { public static void main(String[] arg) throws IOException { // creating list of commands List<String> commands = new ArrayList<String>(); commands.add("ls"); // command commands.add("-l"); // command commands.add( "/Users/abhishekverma"); // command in Mac OS // creating the process ProcessBuilder pb = new ProcessBuilder(commands); // starting the process Process process = pb.start(); // for reading the output from stream BufferedReader stdInput = new BufferedReader(new InputStreamReader( process.getInputStream())); String s = null; while ((s = stdInput.readLine()) != null) { System.out.println(s); } }}
Output:
total 0
drwxr-xr-x 10 abhishekverma staff 340 Jun 20 02:24 AndroidStudioProjects
drwx------@ 22 abhishekverma staff 748 Jun 20 03:00 Desktop
drwx------@ 7 abhishekverma staff 238 Apr 29 22:03 Documents
drwx------+ 27 abhishekverma staff 918 Jun 20 03:01 Downloads
drwx------@ 65 abhishekverma staff 2210 Jun 18 20:48 Library
drwx------+ 3 abhishekverma staff 102 Mar 28 13:08 Movies
drwx------+ 4 abhishekverma staff 136 Apr 8 04:51 Music
drwxr-xr-x 4 abhishekverma staff 136 Jun 19 15:01 NetBeansProjects
drwx------+ 5 abhishekverma staff 170 Apr 10 09:46 Pictures
drwxr-xr-x+ 6 abhishekverma staff 204 Jun 18 20:45 Public
-rw-r--r-- 1 abhishekverma staff 0 Apr 15 19:23 newreactjs.jsx
ProcessBuilder inheritIO(): Sets the source and destination for subprocess standard I/O to be the same as those of the current Java process.
Syntax: public ProcessBuilder inheritIO().
Returns: this process builder.
Exception: NA.
Java
// Java code illustrating inheritIO() methodimport java.io.*;import java.lang.*;import java.util.*;class ProcessBuilderDemo { public static void main(String[] arg) throws IOException, InterruptedException { ProcessBuilder pb = new ProcessBuilder( "echo", "Hello GeeksforGeeks\n" + "This is ProcessBuilder Example"); pb.inheritIO(); Process process = pb.start(); process.waitFor(); }}
Output:
Hello GeeksforGeeks
This is ProcessBuilder Example
This article is contributed by Abhishek Verma. 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.
munendersingh24
Code_Mech
simranarora5sos
Java-lang package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Stream In Java
How to iterate any Map in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Singleton Class in Java
Multidimensional Arrays in Java
Set in Java | [
{
"code": null,
"e": 25455,
"s": 25427,
"text": "\n14 Jan, 2022"
},
{
"code": null,
"e": 25792,
"s": 25455,
"text": "This class is used to create operating system processes. Each ProcessBuilder instance manages a collection of process attributes. The start() method creates a new Process instance with those attributes. The start() method can be invoked repeatedly from the same instance to create new subprocesses with identical or related attributes. "
},
{
"code": null,
"e": 25863,
"s": 25792,
"text": "ProcessBuilder can be used to help create an operating system process."
},
{
"code": null,
"e": 25961,
"s": 25863,
"text": "Before JDK 5.0, the only way to create a process and execute it was to use Runtime.exec() method."
},
{
"code": null,
"e": 25990,
"s": 25961,
"text": "It extends the class Object."
},
{
"code": null,
"e": 26022,
"s": 25990,
"text": "This class is not synchronized."
},
{
"code": null,
"e": 26036,
"s": 26022,
"text": "Constructor: "
},
{
"code": null,
"e": 26161,
"s": 26036,
"text": "ProcessBuilder(List command): This constructs a process builder with the specified operating system program and arguments. "
},
{
"code": null,
"e": 26289,
"s": 26161,
"text": "ProcessBuilder(String... command): This constructs a process builder with the specified operating system program and arguments."
},
{
"code": null,
"e": 26300,
"s": 26289,
"text": "Methods: "
},
{
"code": null,
"e": 26402,
"s": 26300,
"text": "1. List command(): This method returns the process builder’s operating system program and arguments. "
},
{
"code": null,
"e": 26552,
"s": 26402,
"text": "Syntax: public List command().\nReturns: this process builder's program and its arguments.\nExceptions: NullPointerException - if the argument is null."
},
{
"code": null,
"e": 26557,
"s": 26552,
"text": "Java"
},
{
"code": "// Java code illustrating command() methodimport java.io.*;import java.lang.*;import java.util.*;class ProcessBuilderDemo { public static void main(String[] arg) throws IOException { // creating list of process List<String> list = new ArrayList<String>(); list.add(\"notepad.exe\"); // create the process ProcessBuilder build = new ProcessBuilder(list); // checking the command i list System.out.println(\"command: \" + build.command()); }}",
"e": 27054,
"s": 26557,
"text": null
},
{
"code": null,
"e": 27077,
"s": 27054,
"text": "command: [notepad.exe]"
},
{
"code": null,
"e": 27198,
"s": 27077,
"text": "2. ProcessBuilder command(List command): This method sets the process builder’s operating system program and arguments. "
},
{
"code": null,
"e": 27323,
"s": 27198,
"text": "Syntax: public ProcessBuilder command(List command).\nReturns: NA.\nException: NullPointerException - if the argument is null."
},
{
"code": null,
"e": 27328,
"s": 27323,
"text": "Java"
},
{
"code": "// Java code illustrating ProcessBuilder// command(List<String> command)import java.io.*;import java.lang.*;import java.util.*;class ProcessBuilderDemo { public static void main(String[] arg) throws IOException { // creating list of process List<String> list = new ArrayList<String>(); list.add(\"notepad.exe\"); list.add(\"xyz.txt\"); // create the process ProcessBuilder build = new ProcessBuilder(list); // checking the command in list System.out.println(\"command: \" + build.command()); }}",
"e": 27884,
"s": 27328,
"text": null
},
{
"code": null,
"e": 27916,
"s": 27884,
"text": "command: [notepad.exe, xyz.txt]"
},
{
"code": null,
"e": 28327,
"s": 27916,
"text": "3. ProcessBuilder directory(File directory): This method sets the process builder’s working directory. Subprocesses subsequently started by object’s start() method will use it as their working directory. The argument may be null – which means to use the working directory of the current Java process, usually, the directory named by the system property user.dir, as the working directory of the child process. "
},
{
"code": null,
"e": 28430,
"s": 28327,
"text": "Syntax: public ProcessBuilder directory(File directory).\nReturns: this process builder.\nException: NA."
},
{
"code": null,
"e": 28435,
"s": 28430,
"text": "Java"
},
{
"code": "// Java code illustrating directory() methodimport java.io.*;import java.lang.*;import java.util.*;class ProcessBuilderDemo { public static void main(String[] arg) throws IOException { // creating list of process List<String> list = new ArrayList<String>(); list.add(\"notepad.exe\"); list.add(\"abc.txt\"); // creating the process ProcessBuilder build = new ProcessBuilder(list); // setting the directory build.directory(new File(\"src\")); // checking the directory, on which currently // working on System.out.println(\"directory: \" + build.directory()); }}",
"e": 29104,
"s": 28435,
"text": null
},
{
"code": null,
"e": 29119,
"s": 29104,
"text": "directory: src"
},
{
"code": null,
"e": 29439,
"s": 29119,
"text": "4. Map environment(): This method returns a string map view of the process builder’s environment. Whenever a process builder is created, the environment is initialized to a copy of the current process environment. Subprocesses subsequently started by the object’s start() method will use this map as their environment. "
},
{
"code": null,
"e": 29657,
"s": 29439,
"text": "Syntax: public Map environment()\nReturns: this process builder's environment\nException: SecurityException - if a security manager exists \nand its checkPermission method doesn't allow access to the process environment."
},
{
"code": null,
"e": 29662,
"s": 29657,
"text": "Java"
},
{
"code": "// Java code illustrating environment() methodimport java.io.*;import java.util.*;class ProcessBuilderDemo { public static void main(String[] arg) throws IOException { // creating the process ProcessBuilder pb = new ProcessBuilder(); // map view of this process builder's environment Map<String, String> envMap = pb.environment(); // checking map view of environment for (Map.Entry<String, String> entry : envMap.entrySet()) { // checking key and value separately System.out.println(\"Key = \" + entry.getKey() + \", Value = \" + entry.getValue()); } }}",
"e": 30366,
"s": 29662,
"text": null
},
{
"code": null,
"e": 30375,
"s": 30366,
"text": "Output: "
},
{
"code": null,
"e": 31431,
"s": 30375,
"text": "Key = PATH, Value = /usr/bin:/bin:/usr/sbin:/sbin\nKey = JAVA_MAIN_CLASS_14267, Value = ProcessBuilderDemo\nKey = J2D_PIXMAPS, Value = shared\nKey = SHELL, Value = /bin/bash\nKey = JAVA_MAIN_CLASS_11858, Value = org.netbeans.Main\nKey = USER, Value = abhishekverma\nKey = TMPDIR, Value = /var/folders/9z/p63ysmfd797clc0468vvy4980000gn/T/\nKey = SSH_AUTH_SOCK, Value = /private/tmp/com.apple.launchd.uWvCfYQWBP/Listeners\nKey = XPC_FLAGS, Value = 0x0\nKey = LD_LIBRARY_PATH, Value = /Library/Java/JavaVirtualMachines\n/jdk1.8.0_121.jdk/Contents/Home/jre/lib/\namd64:/Library/Java/JavaVirtualMachines/jdk1.8.0_121.jdk\n/Contents/Home/jre/lib/i386:\nKey = __CF_USER_TEXT_ENCODING, Value = 0x1F5:0x0:0x0\nKey = Apple_PubSub_Socket_Render, Value = /private/tmp/com.apple.launchd.weuNq4pAfF/Render\nKey = LOGNAME, Value = abhishekverma\nKey = LC_CTYPE, Value = UTF-8\nKey = XPC_SERVICE_NAME, Value = 0\nKey = PWD, Value = /\nKey = SHLVL, Value = 1\nKey = HOME, Value = /Users/abhishekverma\nKey = _, Value = /Library/Java/JavaVirtualMachines/\njdk1.8.0_121.jdk/Contents/Home/bin/java"
},
{
"code": null,
"e": 31614,
"s": 31431,
"text": "Understanding the above output: The output is the map view of the subprocess build upon. The above output varies from user to user totally depends upon the operating system and user."
},
{
"code": null,
"e": 32079,
"s": 31614,
"text": "5. boolean redirectErrorStream(): This method tells whether the process builder merges standard error and standard output. If this property is true, then any error output generated by subprocesses subsequently started by the object’s start() method will be merged with the standard output, so that both can be read using the Process.getInputStream() method. It makes it easier to correlate error messages with the corresponding output. The initial value is false. "
},
{
"code": null,
"e": 32202,
"s": 32079,
"text": "Syntax: public boolean redirectErrorStream().\nReturns: this process builder's redirectErrorStream property.\nException: NA."
},
{
"code": null,
"e": 32207,
"s": 32202,
"text": "Java"
},
{
"code": "// Java code illustrating redirectErrorStream() methodimport java.io.*;import java.lang.*;import java.util.*;class ProcessBuilderDemo { public static void main(String[] arg) throws IOException { // creating list of commands List list = new ArrayList(); list.add(\"notepad.exe\"); list.add(\"xyz.txt\"); // creating the process ProcessBuilder build = new ProcessBuilder(list); // checking if error stream is redirected System.out.println(build.redirectErrorStream()); }}",
"e": 32742,
"s": 32207,
"text": null
},
{
"code": null,
"e": 32751,
"s": 32742,
"text": "Output: "
},
{
"code": null,
"e": 32757,
"s": 32751,
"text": "false"
},
{
"code": null,
"e": 33239,
"s": 32757,
"text": "6. ProcessBuilder redirectErrorStream(boolean redirectErrorStream): This method sets this process builder’s redirectErrorStream property. If this property is true, then any error output generated by subprocesses subsequently started by this object’s start() method will be merged with the standard output so that both can be read using the Process.getInputStream() method. This makes it easier to correlate error messages with the corresponding output. The initial value is false. "
},
{
"code": null,
"e": 33365,
"s": 33239,
"text": "Syntax: public ProcessBuilder redirectErrorStream(boolean redirectErrorStream).\nReturns: this process builder.\nException: NA."
},
{
"code": null,
"e": 33370,
"s": 33365,
"text": "Java"
},
{
"code": "// Java code illustrating redirectErrorStream(boolean// redirectErrorStream) methodimport java.io.*;import java.lang.*;import java.util.*;class ProcessBuilderDemo { public static void main(String[] arg) throws IOException { // creating list of commands List list = new ArrayList(); list.add(\"notepad.exe\"); list.add(\"xyz.txt\"); // creating the process ProcessBuilder build = new ProcessBuilder(list); // redirecting error stream build.redirectErrorStream(true); // checking if error stream is redirected System.out.println(build.redirectErrorStream()); }}",
"e": 34010,
"s": 33370,
"text": null
},
{
"code": null,
"e": 34019,
"s": 34010,
"text": "Output: "
},
{
"code": null,
"e": 34024,
"s": 34019,
"text": "true"
},
{
"code": null,
"e": 34682,
"s": 34024,
"text": "Process start(): This method starts a new process using the attributes of the process builder. The new process will invoke the command and arguments given by command(), in a working directory as given by directory(), with a process environment as given by environment(). This method checks that the command is a valid operating system command. Which commands are valid is system-dependent, but at the very least the command must be a non-empty list of non-null strings. If there is a security manager, its checkExec method is called with the first component of this object’s command array as its argument. It may result in a SecurityException being thrown. "
},
{
"code": null,
"e": 35078,
"s": 34682,
"text": "Syntax: public Process start().\nReturns: a new Process object for managing the subprocess.\nException: NullPointerException - If an element of the command list is null\nIndexOutOfBoundsException - If the command is an empty list (has size 0).\nSecurityException - If a security manager exists \nand its checkExec method doesn't allow creation of the subprocess.\nIOException - If an I/O error occurs."
},
{
"code": null,
"e": 35083,
"s": 35078,
"text": "Java"
},
{
"code": "// Java code illustrating start() methodimport java.io.*;import java.lang.*;import java.util.*;class ProcessBuilderDemo { public static void main(String[] arg) throws IOException { // creating list of commands List<String> commands = new ArrayList<String>(); commands.add(\"ls\"); // command commands.add(\"-l\"); // command commands.add( \"/Users/abhishekverma\"); // command in Mac OS // creating the process ProcessBuilder pb = new ProcessBuilder(commands); // starting the process Process process = pb.start(); // for reading the output from stream BufferedReader stdInput = new BufferedReader(new InputStreamReader( process.getInputStream())); String s = null; while ((s = stdInput.readLine()) != null) { System.out.println(s); } }}",
"e": 35973,
"s": 35083,
"text": null
},
{
"code": null,
"e": 35982,
"s": 35973,
"text": "Output: "
},
{
"code": null,
"e": 36714,
"s": 35982,
"text": "total 0\ndrwxr-xr-x 10 abhishekverma staff 340 Jun 20 02:24 AndroidStudioProjects\ndrwx------@ 22 abhishekverma staff 748 Jun 20 03:00 Desktop\ndrwx------@ 7 abhishekverma staff 238 Apr 29 22:03 Documents\ndrwx------+ 27 abhishekverma staff 918 Jun 20 03:01 Downloads\ndrwx------@ 65 abhishekverma staff 2210 Jun 18 20:48 Library\ndrwx------+ 3 abhishekverma staff 102 Mar 28 13:08 Movies\ndrwx------+ 4 abhishekverma staff 136 Apr 8 04:51 Music\ndrwxr-xr-x 4 abhishekverma staff 136 Jun 19 15:01 NetBeansProjects\ndrwx------+ 5 abhishekverma staff 170 Apr 10 09:46 Pictures\ndrwxr-xr-x+ 6 abhishekverma staff 204 Jun 18 20:45 Public\n-rw-r--r-- 1 abhishekverma staff 0 Apr 15 19:23 newreactjs.jsx"
},
{
"code": null,
"e": 36856,
"s": 36714,
"text": "ProcessBuilder inheritIO(): Sets the source and destination for subprocess standard I/O to be the same as those of the current Java process. "
},
{
"code": null,
"e": 36945,
"s": 36856,
"text": "Syntax: public ProcessBuilder inheritIO().\nReturns: this process builder.\nException: NA."
},
{
"code": null,
"e": 36950,
"s": 36945,
"text": "Java"
},
{
"code": "// Java code illustrating inheritIO() methodimport java.io.*;import java.lang.*;import java.util.*;class ProcessBuilderDemo { public static void main(String[] arg) throws IOException, InterruptedException { ProcessBuilder pb = new ProcessBuilder( \"echo\", \"Hello GeeksforGeeks\\n\" + \"This is ProcessBuilder Example\"); pb.inheritIO(); Process process = pb.start(); process.waitFor(); }}",
"e": 37412,
"s": 36950,
"text": null
},
{
"code": null,
"e": 37421,
"s": 37412,
"text": "Output: "
},
{
"code": null,
"e": 37472,
"s": 37421,
"text": "Hello GeeksforGeeks\nThis is ProcessBuilder Example"
},
{
"code": null,
"e": 37894,
"s": 37472,
"text": "This article is contributed by Abhishek Verma. 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": 37910,
"s": 37894,
"text": "munendersingh24"
},
{
"code": null,
"e": 37920,
"s": 37910,
"text": "Code_Mech"
},
{
"code": null,
"e": 37936,
"s": 37920,
"text": "simranarora5sos"
},
{
"code": null,
"e": 37954,
"s": 37936,
"text": "Java-lang package"
},
{
"code": null,
"e": 37959,
"s": 37954,
"text": "Java"
},
{
"code": null,
"e": 37964,
"s": 37959,
"text": "Java"
},
{
"code": null,
"e": 38062,
"s": 37964,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 38113,
"s": 38062,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 38143,
"s": 38113,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 38158,
"s": 38143,
"text": "Stream In Java"
},
{
"code": null,
"e": 38189,
"s": 38158,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 38207,
"s": 38189,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 38239,
"s": 38207,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 38259,
"s": 38239,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 38283,
"s": 38259,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 38315,
"s": 38283,
"text": "Multidimensional Arrays in Java"
}
] |
Dart - Variables - GeeksforGeeks | 12 Feb, 2021
A variable name is the name assign to the memory location where the user stores the data and that data can be fetched when required with the help of the variable by calling its variable name. There are various types of variable which are used to store the data. The type which will be used to store data depends upon the type of data to be stored.
To declare a variable:
Syntax: type variable_name;
To declare multiple variables of same type:
Syntax: type variable1_name, variable2_name, variable3_name, ....variableN_name;
Type of the variable can be among:
1. Integer
2. Double
3. String
4. Booleans
5. Lists
6. Maps
Conditions to write variable name or identifiers :
Variable name or identifiers can’t be the keyword.Variable name or identifiers can contain alphabets and numbers.Variable name or identifiers can’t contain spaces and special characters, except the underscore(_) and the dollar($) sign.Variable name or identifiers can’t begin with number.
Variable name or identifiers can’t be the keyword.
Variable name or identifiers can contain alphabets and numbers.
Variable name or identifiers can’t contain spaces and special characters, except the underscore(_) and the dollar($) sign.
Variable name or identifiers can’t begin with number.
Note:Dart supports type-checking, it means that it checks whether the data type and the data thatvariable holds are specific to that data or not.
Example 1:
Printing default and assigned values in Dart of variables of different data types.
Dart
void main() { // Declaring and initialising a variable int gfg1 = 10; // Declaring another variable double gfg2; bool gfg3; // Declaring multiple variable String gfg4, gfg5 = "Geeks for Geeks"; // Printing values of all the variables print(gfg1); // Print 10 print(gfg2); // Print default double value print(gfg3); // Print default string value print(gfg4); // Print default bool value print(gfg5); // Print Geeks for Geeks}
Output:
10
null
null
null
Geeks for Geeks
Keywords are the set of reserved words which can’t be used as a variable name or identifier because they are standard identifiers whose function are predefined in Dart.
Dynamic type variable in Dart:
This is a special variable initialised with keyword dynamic. The variable declared with this data type can store implicitly any value during running the program. It is quite similar to var datatype in Dart, but the difference between them is the moment you assign the data to variable with var keyword it is replaced with the appropriate data type.
Syntax: dynamic variable_name;
Example 2:
Showing how datatype are dynamically change using dynamic keyword.
Dart
void main() { // Assigning value to geek variable dynamic geek = "Geeks For Geeks"; // Printing variable geek print(geek); // Reassigning the data to variable and printing it geek = 3.14157; print(geek);}
Output:
Geeks For Geeks
3.14157
Note: If we use var instead of dynamic in the above code then it will show error.
Output:
Error compiling to JavaScript:
main.dart:9:10:
Error: A value of type 'double' can't be assigned to a variable of type 'String'.
geek = 3.14157;
^
Error: Compilation failed.
Final And Const Keyword in Dart:
These keywords are used to define constant variable in Dart i.e. once a variable is defined using these keyword then its value can’t be changed in the entire code. These keyword can be used with or without data type name.
Syntax for Final:
// Without datatype
final variable_name
// With datatype
final data_type variable_name
Syntax for Const:
// Without datatype
const variable_name
// With datatype
const data_type variable_name
Example 3:
Using final keywords in a Dart program.
Dart
void main() { // Assigning value to geek1 variable without datatype final geek1 = "Geeks For Geeks"; // Printing variable geek1 print(geek1); // Assigning value to geek2 variable with datatype final String geek2 = "Geeks For Geeks Again!!"; // Printing variable geek2 print(geek2);}
Output:
Geeks For Geeks
Geeks For Geeks Again!!
Now, if we try to reassign the geek1 variable in the above program, then:
Output:
Error compiling to JavaScript:
main.dart:8:3:
Error: Can't assign to the final variable 'geek1'.
geek1 = "Geeks For Geeks Again!!";
^^^^^
Error: Compilation failed.
Example 4:
Using const keywords in a Dart program.
Dart
void main() { // Assigning value to geek1 variable without datatype const geek1 = "Geeks For Geeks"; // Printing variable geek1 print(geek1); // Assigning value to geek2 variable with datatype const geek2 = "Geeks For Geeks Again!!"; // Printing variable geek2 print(geek2);}
Output:
Geeks For Geeks
Geeks For Geeks Again!!
Now, if we try to reassign the geek1 variable in the above program, then:
Output:
Error compiling to JavaScript:
main.dart:8:2:
Error: Can't assign to the const variable 'geek1'.
geek1 = "Geeks For Geeks Again!!";
^^^^^
Error: Compilation failed.
Dart
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Flutter - DropDownButton Widget
Flutter - Custom Bottom Navigation Bar
ListView Class in Flutter
Flutter - Checkbox Widget
Flutter - Flexible Widget
Flutter - BoxShadow Widget
Dart Tutorial
Flutter - Stack Widget
Operators in Dart
Android Studio Setup for Flutter Development | [
{
"code": null,
"e": 25402,
"s": 25374,
"text": "\n12 Feb, 2021"
},
{
"code": null,
"e": 25750,
"s": 25402,
"text": "A variable name is the name assign to the memory location where the user stores the data and that data can be fetched when required with the help of the variable by calling its variable name. There are various types of variable which are used to store the data. The type which will be used to store data depends upon the type of data to be stored."
},
{
"code": null,
"e": 25774,
"s": 25750,
"text": "To declare a variable: "
},
{
"code": null,
"e": 25803,
"s": 25774,
"text": "Syntax: type variable_name;\n"
},
{
"code": null,
"e": 25848,
"s": 25803,
"text": "To declare multiple variables of same type: "
},
{
"code": null,
"e": 25930,
"s": 25848,
"text": "Syntax: type variable1_name, variable2_name, variable3_name, ....variableN_name;\n"
},
{
"code": null,
"e": 25966,
"s": 25930,
"text": "Type of the variable can be among: "
},
{
"code": null,
"e": 26027,
"s": 25966,
"text": "1. Integer\n2. Double\n3. String\n4. Booleans\n5. Lists\n6. Maps\n"
},
{
"code": null,
"e": 26079,
"s": 26027,
"text": "Conditions to write variable name or identifiers : "
},
{
"code": null,
"e": 26369,
"s": 26079,
"text": "Variable name or identifiers can’t be the keyword.Variable name or identifiers can contain alphabets and numbers.Variable name or identifiers can’t contain spaces and special characters, except the underscore(_) and the dollar($) sign.Variable name or identifiers can’t begin with number. "
},
{
"code": null,
"e": 26420,
"s": 26369,
"text": "Variable name or identifiers can’t be the keyword."
},
{
"code": null,
"e": 26484,
"s": 26420,
"text": "Variable name or identifiers can contain alphabets and numbers."
},
{
"code": null,
"e": 26607,
"s": 26484,
"text": "Variable name or identifiers can’t contain spaces and special characters, except the underscore(_) and the dollar($) sign."
},
{
"code": null,
"e": 26662,
"s": 26607,
"text": "Variable name or identifiers can’t begin with number. "
},
{
"code": null,
"e": 26808,
"s": 26662,
"text": "Note:Dart supports type-checking, it means that it checks whether the data type and the data thatvariable holds are specific to that data or not."
},
{
"code": null,
"e": 26819,
"s": 26808,
"text": "Example 1:"
},
{
"code": null,
"e": 26903,
"s": 26819,
"text": "Printing default and assigned values in Dart of variables of different data types. "
},
{
"code": null,
"e": 26908,
"s": 26903,
"text": "Dart"
},
{
"code": "void main() { // Declaring and initialising a variable int gfg1 = 10; // Declaring another variable double gfg2; bool gfg3; // Declaring multiple variable String gfg4, gfg5 = \"Geeks for Geeks\"; // Printing values of all the variables print(gfg1); // Print 10 print(gfg2); // Print default double value print(gfg3); // Print default string value print(gfg4); // Print default bool value print(gfg5); // Print Geeks for Geeks}",
"e": 27362,
"s": 26908,
"text": null
},
{
"code": null,
"e": 27373,
"s": 27364,
"text": "Output: "
},
{
"code": null,
"e": 27408,
"s": 27373,
"text": "10\nnull\nnull\nnull\nGeeks for Geeks\n"
},
{
"code": null,
"e": 27578,
"s": 27408,
"text": "Keywords are the set of reserved words which can’t be used as a variable name or identifier because they are standard identifiers whose function are predefined in Dart. "
},
{
"code": null,
"e": 27611,
"s": 27580,
"text": "Dynamic type variable in Dart:"
},
{
"code": null,
"e": 27961,
"s": 27611,
"text": "This is a special variable initialised with keyword dynamic. The variable declared with this data type can store implicitly any value during running the program. It is quite similar to var datatype in Dart, but the difference between them is the moment you assign the data to variable with var keyword it is replaced with the appropriate data type. "
},
{
"code": null,
"e": 27993,
"s": 27961,
"text": "Syntax: dynamic variable_name;\n"
},
{
"code": null,
"e": 28004,
"s": 27993,
"text": "Example 2:"
},
{
"code": null,
"e": 28071,
"s": 28004,
"text": "Showing how datatype are dynamically change using dynamic keyword."
},
{
"code": null,
"e": 28076,
"s": 28071,
"text": "Dart"
},
{
"code": "void main() { // Assigning value to geek variable dynamic geek = \"Geeks For Geeks\"; // Printing variable geek print(geek); // Reassigning the data to variable and printing it geek = 3.14157; print(geek);}",
"e": 28296,
"s": 28076,
"text": null
},
{
"code": null,
"e": 28304,
"s": 28296,
"text": "Output:"
},
{
"code": null,
"e": 28329,
"s": 28304,
"text": "Geeks For Geeks\n3.14157\n"
},
{
"code": null,
"e": 28411,
"s": 28329,
"text": "Note: If we use var instead of dynamic in the above code then it will show error."
},
{
"code": null,
"e": 28419,
"s": 28411,
"text": "Output:"
},
{
"code": null,
"e": 28605,
"s": 28419,
"text": "Error compiling to JavaScript:\nmain.dart:9:10:\nError: A value of type 'double' can't be assigned to a variable of type 'String'.\n geek = 3.14157;\n ^\nError: Compilation failed.\n"
},
{
"code": null,
"e": 28640,
"s": 28607,
"text": "Final And Const Keyword in Dart:"
},
{
"code": null,
"e": 28862,
"s": 28640,
"text": "These keywords are used to define constant variable in Dart i.e. once a variable is defined using these keyword then its value can’t be changed in the entire code. These keyword can be used with or without data type name."
},
{
"code": null,
"e": 28971,
"s": 28862,
"text": "Syntax for Final:\n// Without datatype\nfinal variable_name\n\n// With datatype\nfinal data_type variable_name\n\n"
},
{
"code": null,
"e": 29081,
"s": 28973,
"text": "Syntax for Const:\n// Without datatype\nconst variable_name\n\n// With datatype\nconst data_type variable_name\n\n"
},
{
"code": null,
"e": 29094,
"s": 29083,
"text": "Example 3:"
},
{
"code": null,
"e": 29135,
"s": 29094,
"text": " Using final keywords in a Dart program."
},
{
"code": null,
"e": 29140,
"s": 29135,
"text": "Dart"
},
{
"code": "void main() { // Assigning value to geek1 variable without datatype final geek1 = \"Geeks For Geeks\"; // Printing variable geek1 print(geek1); // Assigning value to geek2 variable with datatype final String geek2 = \"Geeks For Geeks Again!!\"; // Printing variable geek2 print(geek2);}",
"e": 29435,
"s": 29140,
"text": null
},
{
"code": null,
"e": 29443,
"s": 29435,
"text": "Output:"
},
{
"code": null,
"e": 29484,
"s": 29443,
"text": "Geeks For Geeks\nGeeks For Geeks Again!!\n"
},
{
"code": null,
"e": 29558,
"s": 29484,
"text": "Now, if we try to reassign the geek1 variable in the above program, then:"
},
{
"code": null,
"e": 29566,
"s": 29558,
"text": "Output:"
},
{
"code": null,
"e": 29737,
"s": 29566,
"text": "Error compiling to JavaScript:\nmain.dart:8:3:\nError: Can't assign to the final variable 'geek1'.\n geek1 = \"Geeks For Geeks Again!!\";\n ^^^^^\nError: Compilation failed.\n\n"
},
{
"code": null,
"e": 29749,
"s": 29737,
"text": "Example 4: "
},
{
"code": null,
"e": 29789,
"s": 29749,
"text": "Using const keywords in a Dart program."
},
{
"code": null,
"e": 29794,
"s": 29789,
"text": "Dart"
},
{
"code": "void main() { // Assigning value to geek1 variable without datatype const geek1 = \"Geeks For Geeks\"; // Printing variable geek1 print(geek1); // Assigning value to geek2 variable with datatype const geek2 = \"Geeks For Geeks Again!!\"; // Printing variable geek2 print(geek2);}",
"e": 30082,
"s": 29794,
"text": null
},
{
"code": null,
"e": 30090,
"s": 30082,
"text": "Output:"
},
{
"code": null,
"e": 30131,
"s": 30090,
"text": "Geeks For Geeks\nGeeks For Geeks Again!!\n"
},
{
"code": null,
"e": 30205,
"s": 30131,
"text": "Now, if we try to reassign the geek1 variable in the above program, then:"
},
{
"code": null,
"e": 30213,
"s": 30205,
"text": "Output:"
},
{
"code": null,
"e": 30381,
"s": 30213,
"text": "Error compiling to JavaScript:\nmain.dart:8:2:\nError: Can't assign to the const variable 'geek1'.\n geek1 = \"Geeks For Geeks Again!!\";\n ^^^^^\nError: Compilation failed.\n"
},
{
"code": null,
"e": 30386,
"s": 30381,
"text": "Dart"
},
{
"code": null,
"e": 30484,
"s": 30386,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30516,
"s": 30484,
"text": "Flutter - DropDownButton Widget"
},
{
"code": null,
"e": 30555,
"s": 30516,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 30581,
"s": 30555,
"text": "ListView Class in Flutter"
},
{
"code": null,
"e": 30607,
"s": 30581,
"text": "Flutter - Checkbox Widget"
},
{
"code": null,
"e": 30633,
"s": 30607,
"text": "Flutter - Flexible Widget"
},
{
"code": null,
"e": 30660,
"s": 30633,
"text": "Flutter - BoxShadow Widget"
},
{
"code": null,
"e": 30674,
"s": 30660,
"text": "Dart Tutorial"
},
{
"code": null,
"e": 30697,
"s": 30674,
"text": "Flutter - Stack Widget"
},
{
"code": null,
"e": 30715,
"s": 30697,
"text": "Operators in Dart"
}
] |
Installing MATLAB on Windows - GeeksforGeeks | 30 May, 2021
MATLAB stands for “Matrix Laboratory” and it is a numerical computing environment and fourth-generation programming language. designed by Math Works, MATLAB allows matrix manipulations, plotting of functions and data, implementation of algorithms, creation of user interfaces, and interfacing with programs written in other languages, including C, C++, and FORTRAN.
In this article, we will see how to download and install MATLAB on windows
For Installation of MATLAB your system must satisfy the following minimum requirements :
Operating system: Windows 7(service pack 1), Windows 10 or higher.
Processor: Any Intel or AMD x86-64 processor
RAM required: At least 4 GB of RAM is required
Disk Space: MATLAB installation may take up to 31 GB of disk space
If your system completes the above minimum requirement then you can install MATLAB on your system else you have to upgrade your system before the installation of MATLAB.
Step 1: Go to your Mathworks account homepage.
Step 2: Locate the License you would like to download products for in the list.
Step 3: Click the downwards-pointing blue arrow on the same row as the license in question.
Step 4: Click the blue button on the left to download the latest release of MATLAB you have access to, or select an older license in the menu on the right.
Step 5: Choose the platform you need the installer for.
Step 6: If prompted by your browser to Run or Save the installer choose to save.
Step 7: Locate the installer in a file browser. It should be located in the default download location unless you specified another location. The installer will be named:
Windows 64 bit: matlab_R20XXx_win64.exe
Windows 32 bit: matlab_R20XXx_win32.exe
Mac: matlab_R20XXx_maci64.zip
Linux: matlab_R20XXx_glnxa64.zip
To begin with the installation process you must have downloaded the MATLAB setup.
Step 1: After the extraction of the setup, an application named ‘setup’ with MATLAB icon will appear. Click on that application the following window will appear:
MathWorks License Agreement Window
Step 2: After reading the terms and conditions click on “Yes” and then press Next.
Step 3: Then a window asking for the installation key and License file will appear key them ready beforehand so that you can complete the setup in one go without arranging the elements.
Note: Format of Instlllation key is a combination of 30 digits as xxxxx-xxxxx-xxxxx-xxxxx-xxxxx-xxxxx
Step 4: After you have entered the Installation key, it will require a license file that will be extracted with the setup if you have purchased the software so give the location of that file to continue the installation.
Step 5: When the Installation key and the License file are verified it will ask you for the location you want to install it on.
Note: Install it in the C:/ directory to avoid any problem in future
Step 6: For the final step before installation selects the products you want to use in your MATLAB. You should probably select all services in case you want to use some service in the future.
Step 7: After that wait for the installation process to be finished and then open the MATLAB application installed to confirm the proper functioning for the first time.
Now the MATLAB is successfully installed on your windows, and you can use it to its fullest.
MATLAB-Basic
Picked
MATLAB
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Forward and Inverse Fourier Transform of an Image in MATLAB
Boundary Extraction of image using MATLAB
How to Remove Noise from Digital Image in Frequency Domain Using MATLAB?
How to Solve Histogram Equalization Numerical Problem in MATLAB?
How to Normalize a Histogram in MATLAB?
How to Remove Salt and Pepper Noise from Image Using MATLAB?
Classes and Object in MATLAB
Double Integral in MATLAB
Adaptive Histogram Equalization in Image Processing Using MATLAB
What are different types of denoising filters in MATLAB? | [
{
"code": null,
"e": 25887,
"s": 25859,
"text": "\n30 May, 2021"
},
{
"code": null,
"e": 26254,
"s": 25887,
"text": "MATLAB stands for “Matrix Laboratory” and it is a numerical computing environment and fourth-generation programming language. designed by Math Works, MATLAB allows matrix manipulations, plotting of functions and data, implementation of algorithms, creation of user interfaces, and interfacing with programs written in other languages, including C, C++, and FORTRAN."
},
{
"code": null,
"e": 26329,
"s": 26254,
"text": "In this article, we will see how to download and install MATLAB on windows"
},
{
"code": null,
"e": 26418,
"s": 26329,
"text": "For Installation of MATLAB your system must satisfy the following minimum requirements :"
},
{
"code": null,
"e": 26485,
"s": 26418,
"text": "Operating system: Windows 7(service pack 1), Windows 10 or higher."
},
{
"code": null,
"e": 26530,
"s": 26485,
"text": "Processor: Any Intel or AMD x86-64 processor"
},
{
"code": null,
"e": 26577,
"s": 26530,
"text": "RAM required: At least 4 GB of RAM is required"
},
{
"code": null,
"e": 26644,
"s": 26577,
"text": "Disk Space: MATLAB installation may take up to 31 GB of disk space"
},
{
"code": null,
"e": 26814,
"s": 26644,
"text": "If your system completes the above minimum requirement then you can install MATLAB on your system else you have to upgrade your system before the installation of MATLAB."
},
{
"code": null,
"e": 26861,
"s": 26814,
"text": "Step 1: Go to your Mathworks account homepage."
},
{
"code": null,
"e": 26941,
"s": 26861,
"text": "Step 2: Locate the License you would like to download products for in the list."
},
{
"code": null,
"e": 27033,
"s": 26941,
"text": "Step 3: Click the downwards-pointing blue arrow on the same row as the license in question."
},
{
"code": null,
"e": 27189,
"s": 27033,
"text": "Step 4: Click the blue button on the left to download the latest release of MATLAB you have access to, or select an older license in the menu on the right."
},
{
"code": null,
"e": 27245,
"s": 27189,
"text": "Step 5: Choose the platform you need the installer for."
},
{
"code": null,
"e": 27326,
"s": 27245,
"text": "Step 6: If prompted by your browser to Run or Save the installer choose to save."
},
{
"code": null,
"e": 27496,
"s": 27326,
"text": "Step 7: Locate the installer in a file browser. It should be located in the default download location unless you specified another location. The installer will be named:"
},
{
"code": null,
"e": 27639,
"s": 27496,
"text": "Windows 64 bit: matlab_R20XXx_win64.exe\nWindows 32 bit: matlab_R20XXx_win32.exe\nMac: matlab_R20XXx_maci64.zip\nLinux: matlab_R20XXx_glnxa64.zip"
},
{
"code": null,
"e": 27721,
"s": 27639,
"text": "To begin with the installation process you must have downloaded the MATLAB setup."
},
{
"code": null,
"e": 27883,
"s": 27721,
"text": "Step 1: After the extraction of the setup, an application named ‘setup’ with MATLAB icon will appear. Click on that application the following window will appear:"
},
{
"code": null,
"e": 27918,
"s": 27883,
"text": "MathWorks License Agreement Window"
},
{
"code": null,
"e": 28001,
"s": 27918,
"text": "Step 2: After reading the terms and conditions click on “Yes” and then press Next."
},
{
"code": null,
"e": 28188,
"s": 28001,
"text": "Step 3: Then a window asking for the installation key and License file will appear key them ready beforehand so that you can complete the setup in one go without arranging the elements. "
},
{
"code": null,
"e": 28290,
"s": 28188,
"text": "Note: Format of Instlllation key is a combination of 30 digits as xxxxx-xxxxx-xxxxx-xxxxx-xxxxx-xxxxx"
},
{
"code": null,
"e": 28511,
"s": 28290,
"text": "Step 4: After you have entered the Installation key, it will require a license file that will be extracted with the setup if you have purchased the software so give the location of that file to continue the installation."
},
{
"code": null,
"e": 28639,
"s": 28511,
"text": "Step 5: When the Installation key and the License file are verified it will ask you for the location you want to install it on."
},
{
"code": null,
"e": 28708,
"s": 28639,
"text": "Note: Install it in the C:/ directory to avoid any problem in future"
},
{
"code": null,
"e": 28900,
"s": 28708,
"text": "Step 6: For the final step before installation selects the products you want to use in your MATLAB. You should probably select all services in case you want to use some service in the future."
},
{
"code": null,
"e": 29069,
"s": 28900,
"text": "Step 7: After that wait for the installation process to be finished and then open the MATLAB application installed to confirm the proper functioning for the first time."
},
{
"code": null,
"e": 29162,
"s": 29069,
"text": "Now the MATLAB is successfully installed on your windows, and you can use it to its fullest."
},
{
"code": null,
"e": 29175,
"s": 29162,
"text": "MATLAB-Basic"
},
{
"code": null,
"e": 29182,
"s": 29175,
"text": "Picked"
},
{
"code": null,
"e": 29189,
"s": 29182,
"text": "MATLAB"
},
{
"code": null,
"e": 29287,
"s": 29189,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29347,
"s": 29287,
"text": "Forward and Inverse Fourier Transform of an Image in MATLAB"
},
{
"code": null,
"e": 29389,
"s": 29347,
"text": "Boundary Extraction of image using MATLAB"
},
{
"code": null,
"e": 29462,
"s": 29389,
"text": "How to Remove Noise from Digital Image in Frequency Domain Using MATLAB?"
},
{
"code": null,
"e": 29527,
"s": 29462,
"text": "How to Solve Histogram Equalization Numerical Problem in MATLAB?"
},
{
"code": null,
"e": 29567,
"s": 29527,
"text": "How to Normalize a Histogram in MATLAB?"
},
{
"code": null,
"e": 29628,
"s": 29567,
"text": "How to Remove Salt and Pepper Noise from Image Using MATLAB?"
},
{
"code": null,
"e": 29657,
"s": 29628,
"text": "Classes and Object in MATLAB"
},
{
"code": null,
"e": 29683,
"s": 29657,
"text": "Double Integral in MATLAB"
},
{
"code": null,
"e": 29748,
"s": 29683,
"text": "Adaptive Histogram Equalization in Image Processing Using MATLAB"
}
] |
Type Casting or Type Conversion in Golang - GeeksforGeeks | 13 Jul, 2021
Type conversion happens when we assign the value of one data type to another. Statically typed languages like C/C++, Java, provide the support for Implicit Type Conversion but Golang is different, as it doesn’t support the Automatic Type Conversion or Implicit Type Conversion even if the data types are compatible. The reason for this is the Strong Type System of the Golang which doesn’t allow to do this. For type conversion, you must perform explicit conversion. As per Golang Specification, there is no typecasting word or terminology in Golang. If you will try to search Type Casting in Golang Specifications or Documentation, you will find nothing like this. There is only Type Conversion. In Other programming languages, typecasting is also termed as the type conversion.What is the need for Type Conversion? Well, if you need to take advantage of certain characteristics of data type hierarchies, then we have to change entities from one data type into another. The general syntax for converting a value val to a type T is T(val). Example:
var geek1 int = 845
// explicit type conversion
var geek2 float64 = float64(geek1)
var geek3 int64 = int64(geek1)
var geek4 uint = uint(geek1)
C
// Go program to find the// average of numberspackage main import "fmt" func main() { // taking the required // data into variables var totalsum int = 846 var number int = 19 var avg float32 // explicit type conversion avg = float32(totalsum) / float32(number) // Displaying the result fmt.Printf("Average = %f\n", avg)}
Output:
Average = 44.526318
Note: As Golang has a strong type system, it doesn’t allow to mix(like addition, subtraction, multiplication, division, etc.) the numeric types in the expressions and also you are not allowed to perform an assignment between the two mixed types.Example:
var geek1 int64 = 875
// it will give compile time error as we
// are performing an assignment between
// mixed types i.e. int64 as int type
var geek2 int = geek1
var geek3 int = 100
// it gives compile time error
// as this is invalid operation
// because types are mix i.e.
// int64 and int
var addition = geek1 + geek3
surindertarika1234
Go-Basics
Golang
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
6 Best Books to Learn Go Programming Language
Arrays in Go
How to Split a String in Golang?
Golang Maps
Slices in Golang
Different Ways to Find the Type of Variable in Golang
Inheritance in GoLang
Interfaces in Golang
How to Trim a String in Golang?
How to compare times in Golang? | [
{
"code": null,
"e": 25696,
"s": 25668,
"text": "\n13 Jul, 2021"
},
{
"code": null,
"e": 26746,
"s": 25696,
"text": "Type conversion happens when we assign the value of one data type to another. Statically typed languages like C/C++, Java, provide the support for Implicit Type Conversion but Golang is different, as it doesn’t support the Automatic Type Conversion or Implicit Type Conversion even if the data types are compatible. The reason for this is the Strong Type System of the Golang which doesn’t allow to do this. For type conversion, you must perform explicit conversion. As per Golang Specification, there is no typecasting word or terminology in Golang. If you will try to search Type Casting in Golang Specifications or Documentation, you will find nothing like this. There is only Type Conversion. In Other programming languages, typecasting is also termed as the type conversion.What is the need for Type Conversion? Well, if you need to take advantage of certain characteristics of data type hierarchies, then we have to change entities from one data type into another. The general syntax for converting a value val to a type T is T(val). Example: "
},
{
"code": null,
"e": 26892,
"s": 26746,
"text": "var geek1 int = 845\n\n// explicit type conversion\nvar geek2 float64 = float64(geek1)\n\nvar geek3 int64 = int64(geek1)\n\nvar geek4 uint = uint(geek1)"
},
{
"code": null,
"e": 26896,
"s": 26894,
"text": "C"
},
{
"code": "// Go program to find the// average of numberspackage main import \"fmt\" func main() { // taking the required // data into variables var totalsum int = 846 var number int = 19 var avg float32 // explicit type conversion avg = float32(totalsum) / float32(number) // Displaying the result fmt.Printf(\"Average = %f\\n\", avg)}",
"e": 27247,
"s": 26896,
"text": null
},
{
"code": null,
"e": 27256,
"s": 27247,
"text": "Output: "
},
{
"code": null,
"e": 27276,
"s": 27256,
"text": "Average = 44.526318"
},
{
"code": null,
"e": 27531,
"s": 27276,
"text": "Note: As Golang has a strong type system, it doesn’t allow to mix(like addition, subtraction, multiplication, division, etc.) the numeric types in the expressions and also you are not allowed to perform an assignment between the two mixed types.Example: "
},
{
"code": null,
"e": 27856,
"s": 27531,
"text": "var geek1 int64 = 875\n\n// it will give compile time error as we\n// are performing an assignment between\n// mixed types i.e. int64 as int type\nvar geek2 int = geek1\n\nvar geek3 int = 100\n\n// it gives compile time error\n// as this is invalid operation\n// because types are mix i.e.\n// int64 and int\nvar addition = geek1 + geek3"
},
{
"code": null,
"e": 27877,
"s": 27858,
"text": "surindertarika1234"
},
{
"code": null,
"e": 27887,
"s": 27877,
"text": "Go-Basics"
},
{
"code": null,
"e": 27894,
"s": 27887,
"text": "Golang"
},
{
"code": null,
"e": 27906,
"s": 27894,
"text": "Go Language"
},
{
"code": null,
"e": 28004,
"s": 27906,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28050,
"s": 28004,
"text": "6 Best Books to Learn Go Programming Language"
},
{
"code": null,
"e": 28063,
"s": 28050,
"text": "Arrays in Go"
},
{
"code": null,
"e": 28096,
"s": 28063,
"text": "How to Split a String in Golang?"
},
{
"code": null,
"e": 28108,
"s": 28096,
"text": "Golang Maps"
},
{
"code": null,
"e": 28125,
"s": 28108,
"text": "Slices in Golang"
},
{
"code": null,
"e": 28179,
"s": 28125,
"text": "Different Ways to Find the Type of Variable in Golang"
},
{
"code": null,
"e": 28201,
"s": 28179,
"text": "Inheritance in GoLang"
},
{
"code": null,
"e": 28222,
"s": 28201,
"text": "Interfaces in Golang"
},
{
"code": null,
"e": 28254,
"s": 28222,
"text": "How to Trim a String in Golang?"
}
] |
Evaluation of Postfix Expression | Practice | GeeksforGeeks | Given string S representing a postfix expression, the task is to evaluate the expression and find the final value. Operators will only include the basic arithmetic operators like *, /, + and -.
Example 1:
Input: S = "231*+9-"
Output: -4
Explanation:
After solving the given expression,
we have -4 as result.
Example 2:
Input: S = "123+*8-"
Output: -3
Explanation:
After solving the given postfix
expression, we have -3 as result.
Your Task:
You do not need to read input or print anything. Complete the function evaluatePostfixExpression() that takes the string S denoting the expression as input parameter and returns the evaluated value.
Expected Time Complexity: O(|S|)
Expected Auixilliary Space: O(|S|)
Constraints:
1 ≤ |S| ≤ 105
0 ≤ |Si|≤ 9 (And given operators)
0
adarsh471112 weeks ago
Java solution
class Solution
{
//Function to evaluate a postfix expression.
public static int evaluatePostFix(String s)
{
Stack<Integer> st=new Stack<>();
for(int i=0; i<s.length(); i++)
{
int var1, var2;
char ch=s.charAt(i);
if(ch=='+' || ch=='-' || ch=='*' || ch=='/')
{
var2=st.pop();
var1=st.pop();
switch(ch)
{
case '+':
st.push(var1+var2);
break;
case '-':
st.push(var1-var2);
break;
case '*':
st.push(var1*var2);
break;
case '/':
st.push(var1/var2);
break;
}
}
else
st.push(ch-'0');
}
return st.pop();
}
}
0
maneshram20Premium2 weeks ago
Best Ever Easy Understanding Solution in C++
class Solution
{
bool isOperand(char ch){
if(ch=='+' or ch=='-' or ch=='*' or ch=='/'){
return false;
}
return true;
}
public:
//Function to evaluate a postfix expression.
int evaluatePostfix(string str)
{
stack<int> st;
int i=0,j=0,n=str.size();
for(int i=0;i<n;i++){
if(isOperand(str[i])){
st.push(str[i]-'0');
}
else{
int x2 = st.top();
st.pop();
int x1 = st.top();
st.pop();
switch(str[i]){
case '+' : st.push(x1+x2); break;
case '-' : st.push(x1-x2); break;
case '*' : st.push(x1*x2); break;
case '/' : st.push(x1/x2); break;
}
}
}
return st.top();
}
};
0
mahesh_phutane3 weeks ago
Suimple java solution using Stack
class Solution
{
//Function to evaluate a postfix expression.
public static int evaluatePostFix(String S)
{
Stack<Integer> st = new Stack<>();
for(int i = 0;i<S.length();i++){
char ch = S.charAt(i);
if(ch =='*' || ch == '/' || ch =='+' || ch == '-' ){
int a = st.pop();
int b = st.pop();
// System.out.println(a+" "+b+" "+ch);
evaluate(b,a,ch,st);
}
else{
st.push(ch-'0');
}
}
return st.pop();
}
public static void evaluate(int a,int b,char ch,Stack<Integer> st){
switch(ch){
case '*': st.push(a*b);
break;
case '/': st.push(a/b);
break;
case '+': st.push(a+b);
break;
case '-': st.push(a-b);
break;
}
}
}
0
akashdsingh0061 month ago
JAVA Code 0.13/1.86
// Your code here Stack<Integer> inf=new Stack<>(); for(int i=0;i<S.length();i++) { char ch=S.charAt(i); if(Character.isDigit(ch)) { inf.push(ch-'0'); } else if(ch=='+'||ch=='-'||ch=='*'||ch=='/') { int v2=inf.pop(); int v1=inf.pop(); int ans=operation(ch,v1,v2); inf.push(ans); } } int k=inf.pop(); return k; } public static int precedence(char ch) { if(ch=='+'||ch=='-') return 1; else return 2; } public static int operation(char ch,int a,int b) { switch(ch){ case '+': return a+b; case '-': return a-b; case '*': return a*b; case '/': return a/b; } return 0; }
0
agrawalharshita07111 month ago
class Solution:
#Function to evaluate a postfix expression.
def evaluatePostfix(self, S):
#code here
stk=[]
for i in S:
if i.isdigit():
stk.append(i)
else:
a=stk.pop()
b=stk.pop()
if i=='+':
stk.append(str(int(b)+int(a)))
if i=='-':
stk.append(str(int(b)-int(a)))
if i=='*':
stk.append(str(int(b)*int(a)))
if i=='/':
stk.append(str(int(int(b)/int(a))))
return stk.pop(0)
0
gaurabhkumarjha271020011 month ago
stack <int> ss;
int a=0, b=0;
for (int i=0; i< s.length(); i++){
if (isdigit (s[i]))
ss.push(s[i]- '0');
switch (s[i]){
case '/':
a= ss.top(); ss.pop();
b= ss.top(); ss.pop();
ss.push(b/a);
break;
case '*':
a= ss.top(); ss.pop();
b= ss.top(); ss.pop();
ss.push(b*a);
break;
case '+':
a= ss.top(); ss.pop();
b= ss.top(); ss.pop();
ss.push(b+a);
break;
case '-':
a= ss.top(); ss.pop();
b= ss.top(); ss.pop();
ss.push(b-a);
break;
}
}
return ss.top();
0
gaurabhkumarjha271020011 month ago
// easy c++ code
stack <int> ss;
int a=0, b=0;
for (int i=0; i< s.length(); i++){
if (isdigit (s[i]))
ss.push(s[i]- '0');
switch (s[i]){
case '/':
a= ss.top(); ss.pop();
b= ss.top(); ss.pop();
ss.push(b/a);
break;
case '*':
a= ss.top(); ss.pop();
b= ss.top(); ss.pop();
ss.push(b*a);
break;
case '+':
a= ss.top(); ss.pop();
b= ss.top(); ss.pop();
ss.push(b+a);
break;
case '-':
a= ss.top(); ss.pop();
b= ss.top(); ss.pop();
ss.push(b-a);
break;
}
}
return ss.top();
0
tarunkanade1 month ago
0.1/1.9
public static int evaluatePostFix(String S)
{
// Your code here
ArrayDeque<Integer> stack = new ArrayDeque<>();
int res = 0;
for(int i=0; i<S.length(); i++){
char c = S.charAt(i);
if(Character.isDigit(c)){
stack.push(Character.getNumericValue(c));
}
else{
int b = stack.pop();
int a = stack.pop();
res = evaluate(a, c, b);
stack.push(res);
}
}
return stack.pop();
}
private static int evaluate(int a, char op, int b){
switch(op){
case '+':
return a+b;
case '-':
return a-b;
case '*':
return a*b;
case '/':
return a/b;
}
return 0;
}
+1
amar_raj2 months ago
//Time Taken =0.0 Sec//
//C++ easy Solution//
stack<int> st;
for(auto x:S)
{
if(x>='0'&&x<='9')
{
st.push(x-'0');
}
else
{
int a=st.top();
st.pop();
int b=st.top();
st.pop();
if(x=='*'){
st.push((b*a));
}
else if(x=='/'){
st.push((b/a));
}
else if(x=='+'){
st.push((b+a));
}
else
{
st.push((b-a));
}
}
}
return st.top();
-1
nishitchaudhary00552 months ago
class Solution: def __init__(self): self.stack = [] def isEmpty(self): return self.stack == [] def push(self,op): self.stack.append(op) def pop(self): if not self.isEmpty(): return self.stack.pop() else: return '$' #Function to evaluate a postfix expression. def evaluatePostfix(self, S): for i in S: if(i.isdigit()): self.push(i) else: a = self.pop() b = self.pop() self.push(str(eval(b+i+a))) return int(self.pop())
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": 432,
"s": 238,
"text": "Given string S representing a postfix expression, the task is to evaluate the expression and find the final value. Operators will only include the basic arithmetic operators like *, /, + and -."
},
{
"code": null,
"e": 445,
"s": 434,
"text": "Example 1:"
},
{
"code": null,
"e": 550,
"s": 445,
"text": "Input: S = \"231*+9-\"\nOutput: -4\nExplanation:\nAfter solving the given expression, \nwe have -4 as result.\n"
},
{
"code": null,
"e": 561,
"s": 550,
"text": "Example 2:"
},
{
"code": null,
"e": 674,
"s": 561,
"text": "Input: S = \"123+*8-\"\nOutput: -3\nExplanation:\nAfter solving the given postfix \nexpression, we have -3 as result.\n"
},
{
"code": null,
"e": 885,
"s": 674,
"text": "\nYour Task:\nYou do not need to read input or print anything. Complete the function evaluatePostfixExpression() that takes the string S denoting the expression as input parameter and returns the evaluated value."
},
{
"code": null,
"e": 954,
"s": 885,
"text": "\nExpected Time Complexity: O(|S|)\nExpected Auixilliary Space: O(|S|)"
},
{
"code": null,
"e": 982,
"s": 954,
"text": "\nConstraints:\n1 ≤ |S| ≤ 105"
},
{
"code": null,
"e": 1016,
"s": 982,
"text": "0 ≤ |Si|≤ 9 (And given operators)"
},
{
"code": null,
"e": 1018,
"s": 1016,
"text": "0"
},
{
"code": null,
"e": 1041,
"s": 1018,
"text": "adarsh471112 weeks ago"
},
{
"code": null,
"e": 1055,
"s": 1041,
"text": "Java solution"
},
{
"code": null,
"e": 2065,
"s": 1055,
"text": "class Solution\n{\n //Function to evaluate a postfix expression.\n public static int evaluatePostFix(String s)\n {\n Stack<Integer> st=new Stack<>();\n \n for(int i=0; i<s.length(); i++)\n {\n int var1, var2;\n char ch=s.charAt(i);\n \n if(ch=='+' || ch=='-' || ch=='*' || ch=='/')\n {\n var2=st.pop();\n var1=st.pop();\n switch(ch)\n {\n case '+':\n st.push(var1+var2);\n break;\n case '-':\n st.push(var1-var2);\n break;\n case '*':\n st.push(var1*var2);\n break;\n case '/':\n st.push(var1/var2);\n break;\n }\n }\n else\n st.push(ch-'0');\n }\n return st.pop();\n }\n}"
},
{
"code": null,
"e": 2067,
"s": 2065,
"text": "0"
},
{
"code": null,
"e": 2097,
"s": 2067,
"text": "maneshram20Premium2 weeks ago"
},
{
"code": null,
"e": 2142,
"s": 2097,
"text": "Best Ever Easy Understanding Solution in C++"
},
{
"code": null,
"e": 3045,
"s": 2142,
"text": "class Solution\n{\n bool isOperand(char ch){\n if(ch=='+' or ch=='-' or ch=='*' or ch=='/'){\n return false;\n }\n return true;\n }\n public:\n //Function to evaluate a postfix expression.\n int evaluatePostfix(string str)\n {\n stack<int> st;\n int i=0,j=0,n=str.size();\n for(int i=0;i<n;i++){\n if(isOperand(str[i])){\n st.push(str[i]-'0');\n }\n else{\n int x2 = st.top();\n st.pop();\n int x1 = st.top();\n st.pop();\n switch(str[i]){\n case '+' : st.push(x1+x2); break;\n case '-' : st.push(x1-x2); break;\n case '*' : st.push(x1*x2); break;\n case '/' : st.push(x1/x2); break;\n }\n }\n }\n return st.top();\n }\n};"
},
{
"code": null,
"e": 3047,
"s": 3045,
"text": "0"
},
{
"code": null,
"e": 3073,
"s": 3047,
"text": "mahesh_phutane3 weeks ago"
},
{
"code": null,
"e": 3107,
"s": 3073,
"text": "Suimple java solution using Stack"
},
{
"code": null,
"e": 4074,
"s": 3107,
"text": "class Solution\n{\n //Function to evaluate a postfix expression.\n public static int evaluatePostFix(String S)\n {\n Stack<Integer> st = new Stack<>();\n for(int i = 0;i<S.length();i++){\n char ch = S.charAt(i);\n if(ch =='*' || ch == '/' || ch =='+' || ch == '-' ){\n int a = st.pop();\n int b = st.pop();\n // System.out.println(a+\" \"+b+\" \"+ch);\n evaluate(b,a,ch,st);\n }\n else{\n st.push(ch-'0');\n }\n }\n return st.pop();\n }\n \n public static void evaluate(int a,int b,char ch,Stack<Integer> st){\n switch(ch){\n \n case '*': st.push(a*b);\n break;\n case '/': st.push(a/b);\n break; \n case '+': st.push(a+b);\n break;\n case '-': st.push(a-b);\n break;\n }\n }\n}"
},
{
"code": null,
"e": 4076,
"s": 4074,
"text": "0"
},
{
"code": null,
"e": 4102,
"s": 4076,
"text": "akashdsingh0061 month ago"
},
{
"code": null,
"e": 4122,
"s": 4102,
"text": "JAVA Code 0.13/1.86"
},
{
"code": null,
"e": 5119,
"s": 4124,
"text": " // Your code here Stack<Integer> inf=new Stack<>(); for(int i=0;i<S.length();i++) { char ch=S.charAt(i); if(Character.isDigit(ch)) { inf.push(ch-'0'); } else if(ch=='+'||ch=='-'||ch=='*'||ch=='/') { int v2=inf.pop(); int v1=inf.pop(); int ans=operation(ch,v1,v2); inf.push(ans); } } int k=inf.pop(); return k; } public static int precedence(char ch) { if(ch=='+'||ch=='-') return 1; else return 2; } public static int operation(char ch,int a,int b) { switch(ch){ case '+': return a+b; case '-': return a-b; case '*': return a*b; case '/': return a/b; } return 0; }"
},
{
"code": null,
"e": 5121,
"s": 5119,
"text": "0"
},
{
"code": null,
"e": 5152,
"s": 5121,
"text": "agrawalharshita07111 month ago"
},
{
"code": null,
"e": 5793,
"s": 5152,
"text": "class Solution:\n \n #Function to evaluate a postfix expression.\n def evaluatePostfix(self, S):\n #code here\n stk=[]\n for i in S:\n if i.isdigit():\n stk.append(i)\n else:\n a=stk.pop()\n b=stk.pop()\n if i=='+':\n stk.append(str(int(b)+int(a)))\n if i=='-':\n stk.append(str(int(b)-int(a)))\n if i=='*':\n stk.append(str(int(b)*int(a)))\n if i=='/':\n stk.append(str(int(int(b)/int(a))))\n return stk.pop(0) "
},
{
"code": null,
"e": 5795,
"s": 5793,
"text": "0"
},
{
"code": null,
"e": 5830,
"s": 5795,
"text": "gaurabhkumarjha271020011 month ago"
},
{
"code": null,
"e": 6996,
"s": 5830,
"text": "stack <int> ss;\n int a=0, b=0;\n \n for (int i=0; i< s.length(); i++){\n \n if (isdigit (s[i]))\n ss.push(s[i]- '0');\n \n \n switch (s[i]){\n \n case '/':\n a= ss.top(); ss.pop();\n b= ss.top(); ss.pop();\n ss.push(b/a);\n break;\n \n case '*':\n a= ss.top(); ss.pop();\n b= ss.top(); ss.pop();\n ss.push(b*a);\n break;\n \n case '+':\n a= ss.top(); ss.pop();\n b= ss.top(); ss.pop();\n ss.push(b+a);\n break;\n \n case '-':\n a= ss.top(); ss.pop();\n b= ss.top(); ss.pop();\n ss.push(b-a);\n break; \n \n } \n }\n \n return ss.top();"
},
{
"code": null,
"e": 6998,
"s": 6996,
"text": "0"
},
{
"code": null,
"e": 7033,
"s": 6998,
"text": "gaurabhkumarjha271020011 month ago"
},
{
"code": null,
"e": 8195,
"s": 7033,
"text": "// easy c++ code \n stack <int> ss;\n int a=0, b=0;\n \n for (int i=0; i< s.length(); i++){\n \n if (isdigit (s[i]))\n ss.push(s[i]- '0');\n \n \n switch (s[i]){\n \n case '/':\n a= ss.top(); ss.pop();\n b= ss.top(); ss.pop();\n ss.push(b/a);\n break;\n \n case '*':\n a= ss.top(); ss.pop();\n b= ss.top(); ss.pop();\n ss.push(b*a);\n break;\n \n case '+':\n a= ss.top(); ss.pop();\n b= ss.top(); ss.pop();\n ss.push(b+a);\n break;\n \n case '-':\n a= ss.top(); ss.pop();\n b= ss.top(); ss.pop();\n ss.push(b-a);\n break; \n \n } \n }\n \n return ss.top();"
},
{
"code": null,
"e": 8197,
"s": 8195,
"text": "0"
},
{
"code": null,
"e": 8220,
"s": 8197,
"text": "tarunkanade1 month ago"
},
{
"code": null,
"e": 8228,
"s": 8220,
"text": "0.1/1.9"
},
{
"code": null,
"e": 9172,
"s": 8228,
"text": "public static int evaluatePostFix(String S)\n {\n // Your code here\n ArrayDeque<Integer> stack = new ArrayDeque<>();\n int res = 0;\n \n for(int i=0; i<S.length(); i++){\n char c = S.charAt(i);\n \n if(Character.isDigit(c)){\n stack.push(Character.getNumericValue(c));\n }\n else{\n int b = stack.pop();\n int a = stack.pop();\n \n res = evaluate(a, c, b);\n stack.push(res);\n }\n }\n \n return stack.pop();\n }\n \n private static int evaluate(int a, char op, int b){\n \n switch(op){\n case '+':\n return a+b;\n case '-':\n return a-b;\n case '*':\n return a*b;\n case '/':\n return a/b;\n }\n \n return 0;\n } "
},
{
"code": null,
"e": 9175,
"s": 9172,
"text": "+1"
},
{
"code": null,
"e": 9196,
"s": 9175,
"text": "amar_raj2 months ago"
},
{
"code": null,
"e": 9999,
"s": 9196,
"text": " //Time Taken =0.0 Sec//\n //C++ easy Solution// \n stack<int> st;\n for(auto x:S)\n {\n if(x>='0'&&x<='9')\n {\n st.push(x-'0');\n }\n else\n {\n int a=st.top();\n st.pop();\n int b=st.top();\n st.pop();\n if(x=='*'){\n \n st.push((b*a));\n }\n else if(x=='/'){\n \n st.push((b/a));\n }\n else if(x=='+'){\n \n st.push((b+a));\n }\n \n else\n {\n st.push((b-a));\n }\n }\n }\n return st.top();"
},
{
"code": null,
"e": 10002,
"s": 9999,
"text": "-1"
},
{
"code": null,
"e": 10034,
"s": 10002,
"text": "nishitchaudhary00552 months ago"
},
{
"code": null,
"e": 10656,
"s": 10034,
"text": "class Solution: def __init__(self): self.stack = [] def isEmpty(self): return self.stack == [] def push(self,op): self.stack.append(op) def pop(self): if not self.isEmpty(): return self.stack.pop() else: return '$' #Function to evaluate a postfix expression. def evaluatePostfix(self, S): for i in S: if(i.isdigit()): self.push(i) else: a = self.pop() b = self.pop() self.push(str(eval(b+i+a))) return int(self.pop()) "
},
{
"code": null,
"e": 10802,
"s": 10656,
"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": 10838,
"s": 10802,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 10848,
"s": 10838,
"text": "\nProblem\n"
},
{
"code": null,
"e": 10858,
"s": 10848,
"text": "\nContest\n"
},
{
"code": null,
"e": 10921,
"s": 10858,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 11069,
"s": 10921,
"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": 11277,
"s": 11069,
"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": 11383,
"s": 11277,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Java Program to Detect Cycle in a Directed Graph - GeeksforGeeks | 02 Jan, 2019
Given a directed graph, check whether the graph contains a cycle or not. Your function should return true if the given graph contains at least one cycle, else return false. For example, the following graph contains three cycles 0->2->0, 0->1->2->0 and 3->3, so your function must return true.
Java
// A Java Program to detect cycle in a graphimport java.util.ArrayList;import java.util.LinkedList;import java.util.List; class Graph { private final int V; private final List<List<Integer> > adj; public Graph(int V) { this.V = V; adj = new ArrayList<>(V); for (int i = 0; i < V; i++) adj.add(new LinkedList<>()); } // This function is a variation of DFSUytil() in // https:// www.geeksforgeeks.org/archives/18212 private boolean isCyclicUtil(int i, boolean[] visited, boolean[] recStack) { // Mark the current node as visited and // part of recursion stack if (recStack[i]) return true; if (visited[i]) return false; visited[i] = true; recStack[i] = true; List<Integer> children = adj.get(i); for (Integer c : children) if (isCyclicUtil(c, visited, recStack)) return true; recStack[i] = false; return false; } private void addEdge(int source, int dest) { adj.get(source).add(dest); } // Returns true if the graph contains a // cycle, else false. // This function is a variation of DFS() in // https:// www.geeksforgeeks.org/archives/18212 private boolean isCyclic() { // Mark all the vertices as not visited and // not part of recursion stack boolean[] visited = new boolean[V]; boolean[] recStack = new boolean[V]; // Call the recursive helper function to // detect cycle in different DFS trees for (int i = 0; i < V; i++) if (isCyclicUtil(i, visited, recStack)) return true; return false; } // Driver code public static void main(String[] args) { Graph graph = new Graph(4); graph.addEdge(0, 1); graph.addEdge(0, 2); graph.addEdge(1, 2); graph.addEdge(2, 0); graph.addEdge(2, 3); graph.addEdge(3, 3); if (graph.isCyclic()) System.out.println("Graph contains cycle"); else System.out.println("Graph doesn't " + "contain cycle"); }} // This code is contributed by Sagar Shah.
Graph contains cycle
Please refer complete article on Detect Cycle in a Directed Graph for more details!
Java Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Iterate Over the Characters of a String in Java
How to Get Elements By Index from HashSet in Java?
Java Program to Write into a File
How to Replace a Element in Java ArrayList?
Java Program to Find Sum of Array Elements
Java Program to Read a File to String
Tic-Tac-Toe Game in Java
How to Write Data into Excel Sheet using Java?
Removing last element from ArrayList in Java
Java Program to Write an Array of Strings to the Output Console | [
{
"code": null,
"e": 26107,
"s": 26079,
"text": "\n02 Jan, 2019"
},
{
"code": null,
"e": 26400,
"s": 26107,
"text": "Given a directed graph, check whether the graph contains a cycle or not. Your function should return true if the given graph contains at least one cycle, else return false. For example, the following graph contains three cycles 0->2->0, 0->1->2->0 and 3->3, so your function must return true."
},
{
"code": null,
"e": 26405,
"s": 26400,
"text": "Java"
},
{
"code": "// A Java Program to detect cycle in a graphimport java.util.ArrayList;import java.util.LinkedList;import java.util.List; class Graph { private final int V; private final List<List<Integer> > adj; public Graph(int V) { this.V = V; adj = new ArrayList<>(V); for (int i = 0; i < V; i++) adj.add(new LinkedList<>()); } // This function is a variation of DFSUytil() in // https:// www.geeksforgeeks.org/archives/18212 private boolean isCyclicUtil(int i, boolean[] visited, boolean[] recStack) { // Mark the current node as visited and // part of recursion stack if (recStack[i]) return true; if (visited[i]) return false; visited[i] = true; recStack[i] = true; List<Integer> children = adj.get(i); for (Integer c : children) if (isCyclicUtil(c, visited, recStack)) return true; recStack[i] = false; return false; } private void addEdge(int source, int dest) { adj.get(source).add(dest); } // Returns true if the graph contains a // cycle, else false. // This function is a variation of DFS() in // https:// www.geeksforgeeks.org/archives/18212 private boolean isCyclic() { // Mark all the vertices as not visited and // not part of recursion stack boolean[] visited = new boolean[V]; boolean[] recStack = new boolean[V]; // Call the recursive helper function to // detect cycle in different DFS trees for (int i = 0; i < V; i++) if (isCyclicUtil(i, visited, recStack)) return true; return false; } // Driver code public static void main(String[] args) { Graph graph = new Graph(4); graph.addEdge(0, 1); graph.addEdge(0, 2); graph.addEdge(1, 2); graph.addEdge(2, 0); graph.addEdge(2, 3); graph.addEdge(3, 3); if (graph.isCyclic()) System.out.println(\"Graph contains cycle\"); else System.out.println(\"Graph doesn't \" + \"contain cycle\"); }} // This code is contributed by Sagar Shah.",
"e": 28678,
"s": 26405,
"text": null
},
{
"code": null,
"e": 28700,
"s": 28678,
"text": "Graph contains cycle\n"
},
{
"code": null,
"e": 28784,
"s": 28700,
"text": "Please refer complete article on Detect Cycle in a Directed Graph for more details!"
},
{
"code": null,
"e": 28798,
"s": 28784,
"text": "Java Programs"
},
{
"code": null,
"e": 28896,
"s": 28798,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28944,
"s": 28896,
"text": "Iterate Over the Characters of a String in Java"
},
{
"code": null,
"e": 28995,
"s": 28944,
"text": "How to Get Elements By Index from HashSet in Java?"
},
{
"code": null,
"e": 29029,
"s": 28995,
"text": "Java Program to Write into a File"
},
{
"code": null,
"e": 29073,
"s": 29029,
"text": "How to Replace a Element in Java ArrayList?"
},
{
"code": null,
"e": 29116,
"s": 29073,
"text": "Java Program to Find Sum of Array Elements"
},
{
"code": null,
"e": 29154,
"s": 29116,
"text": "Java Program to Read a File to String"
},
{
"code": null,
"e": 29179,
"s": 29154,
"text": "Tic-Tac-Toe Game in Java"
},
{
"code": null,
"e": 29226,
"s": 29179,
"text": "How to Write Data into Excel Sheet using Java?"
},
{
"code": null,
"e": 29271,
"s": 29226,
"text": "Removing last element from ArrayList in Java"
}
] |
Teradata - Compression | Compression is used to reduce the storage used by the tables. In Teradata, compression can compress up to 255 distinct values including NULL. Since the storage is reduced, Teradata can store more records in a block. This results in improved query response time since any I/O operation can process more rows per block. Compression can be added at table creation using CREATE TABLE or after table creation using ALTER TABLE command.
Only 255 values can be compressed per column.
Primary Index column cannot be compressed.
Volatile tables cannot be compressed.
The following table compresses the field DepatmentNo for values 1, 2 and 3. When compression is applied on a column, the values for this column is not stored with the row. Instead the values are stored in the Table header in each AMP and only presence bits are added to the row to indicate the value.
CREATE SET TABLE employee (
EmployeeNo integer,
FirstName CHAR(30),
LastName CHAR(30),
BirthDate DATE FORMAT 'YYYY-MM-DD-',
JoinedDate DATE FORMAT 'YYYY-MM-DD-',
employee_gender CHAR(1),
DepartmentNo CHAR(02) COMPRESS(1,2,3)
)
UNIQUE PRIMARY INDEX(EmployeeNo);
Multi-Value compression can be used when you have a column in a large table with finite values. | [
{
"code": null,
"e": 3195,
"s": 2764,
"text": "Compression is used to reduce the storage used by the tables. In Teradata, compression can compress up to 255 distinct values including NULL. Since the storage is reduced, Teradata can store more records in a block. This results in improved query response time since any I/O operation can process more rows per block. Compression can be added at table creation using CREATE TABLE or after table creation using ALTER TABLE command."
},
{
"code": null,
"e": 3241,
"s": 3195,
"text": "Only 255 values can be compressed per column."
},
{
"code": null,
"e": 3284,
"s": 3241,
"text": "Primary Index column cannot be compressed."
},
{
"code": null,
"e": 3322,
"s": 3284,
"text": "Volatile tables cannot be compressed."
},
{
"code": null,
"e": 3623,
"s": 3322,
"text": "The following table compresses the field DepatmentNo for values 1, 2 and 3. When compression is applied on a column, the values for this column is not stored with the row. Instead the values are stored in the Table header in each AMP and only presence bits are added to the row to indicate the value."
},
{
"code": null,
"e": 3914,
"s": 3623,
"text": "CREATE SET TABLE employee ( \n EmployeeNo integer, \n FirstName CHAR(30), \n LastName CHAR(30), \n BirthDate DATE FORMAT 'YYYY-MM-DD-', \n JoinedDate DATE FORMAT 'YYYY-MM-DD-', \n employee_gender CHAR(1), \n DepartmentNo CHAR(02) COMPRESS(1,2,3) \n) \nUNIQUE PRIMARY INDEX(EmployeeNo);"
}
] |
Text Preprocessing in Python | Set – 1 | 27 Jan, 2022
Prerequisites: Introduction to NLPWhenever we have textual data, we need to apply several pre-processing steps to the data to transform words into numerical features that work with machine learning algorithms. The pre-processing steps for a problem depend mainly on the domain and the problem itself, hence, we don’t need to apply all steps to every problem. In this article, we are going to see text preprocessing in Python. We will be using the NLTK (Natural Language Toolkit) library here.
Python3
# import the necessary librariesimport nltkimport stringimport re
We lowercase the text to reduce the size of the vocabulary of our text data.
Python3
def text_lowercase(text): return text.lower() input_str = "Hey, did you know that the summer break is coming? Amazing right !! It's only 5 more days !!"text_lowercase(input_str)
Example:
Input: “Hey, did you know that the summer break is coming? Amazing right!! It’s only 5 more days!!” Output: “hey, did you know that the summer break is coming? amazing right!! it’s only 5 more days!!”
We can either remove numbers or convert the numbers into their textual representations. We can use regular expressions to remove the numbers.
Python3
# Remove numbersdef remove_numbers(text): result = re.sub(r'\d+', '', text) return result input_str = "There are 3 balls in this bag, and 12 in the other one."remove_numbers(input_str)
Example:
Input: “There are 3 balls in this bag, and 12 in the other one.” Output: ‘There are balls in this bag, and in the other one.’
We can also convert the numbers into words. This can be done by using the inflect library.
Python3
# import the inflect libraryimport inflectp = inflect.engine() # convert number into wordsdef convert_number(text): # split string into list of words temp_str = text.split() # initialise empty list new_string = [] for word in temp_str: # if word is a digit, convert the digit # to numbers and append into the new_string list if word.isdigit(): temp = p.number_to_words(word) new_string.append(temp) # append the word as it is else: new_string.append(word) # join the words of new_string to form a string temp_str = ' '.join(new_string) return temp_str input_str = 'There are 3 balls in this bag, and 12 in the other one.'convert_number(input_str)
Example:
Input: “There are 3 balls in this bag, and 12 in the other one.” Output: “There are three balls in this bag, and twelve in the other one.”
We remove punctuations so that we don’t have different forms of the same word. If we don’t remove the punctuation, then been. been, been! will be treated separately.
Python3
# remove punctuationdef remove_punctuation(text): translator = str.maketrans('', '', string.punctuation) return text.translate(translator) input_str = "Hey, did you know that the summer break is coming? Amazing right !! It's only 5 more days !!"remove_punctuation(input_str)
Example:
Input: “Hey, did you know that the summer break is coming? Amazing right!! It’s only 5 more days!!” Output: “Hey did you know that the summer break is coming Amazing right Its only 5 more days”
We can use the join and split function to remove all the white spaces in a string.
Python3
# remove whitespace from textdef remove_whitespace(text): return " ".join(text.split()) input_str = " we don't need the given questions"remove_whitespace(input_str)
Example:
Input: " we don't need the given questions"
Output: "we don't need the given questions"
Stopwords are words that do not contribute to the meaning of a sentence. Hence, they can safely be removed without causing any change in the meaning of the sentence. The NLTK library has a set of stopwords and we can use these to remove stopwords from our text and return a list of word tokens.
Python3
from nltk.corpus import stopwordsfrom nltk.tokenize import word_tokenize # remove stopwords functiondef remove_stopwords(text): stop_words = set(stopwords.words("english")) word_tokens = word_tokenize(text) filtered_text = [word for word in word_tokens if word not in stop_words] return filtered_text example_text = "This is a sample sentence and we are going to remove the stopwords from this."remove_stopwords(example_text)
Example:
Input: “This is a sample sentence and we are going to remove the stopwords from this” Output: [‘This’, ‘sample’, ‘sentence’, ‘going’, ‘remove’, ‘stopwords’]
Stemming is the process of getting the root form of a word. Stem or root is the part to which inflectional affixes (-ed, -ize, -de, -s, etc.) are added. The stem of a word is created by removing the prefix or suffix of a word. So, stemming a word may not result in actual words.Example:
books ---> book
looked ---> look
denied ---> deni
flies ---> fli
If the text is not in tokens, then we need to convert it into tokens. After we have converted strings of text into tokens, we can convert the word tokens into their root form. There are mainly three algorithms for stemming. These are the Porter Stemmer, the Snowball Stemmer and the Lancaster Stemmer. Porter Stemmer is the most common among them.
Python3
from nltk.stem.porter import PorterStemmerfrom nltk.tokenize import word_tokenizestemmer = PorterStemmer() # stem words in the list of tokenized wordsdef stem_words(text): word_tokens = word_tokenize(text) stems = [stemmer.stem(word) for word in word_tokens] return stems text = 'data science uses scientific methods algorithms and many types of processes'stem_words(text)
Example:
Input: ‘data science uses scientific methods algorithms and many types of processes’ Output: [‘data’, ‘scienc’, ‘use’, ‘scientif’, ‘method’, ‘algorithm’, ‘and’, ‘mani’, ‘type’, ‘of’, ‘process’]
Like stemming, lemmatization also converts a word to its root form. The only difference is that lemmatization ensures that the root word belongs to the language. We will get valid words if we use lemmatization. In NLTK, we use the WordNetLemmatizer to get the lemmas of words. We also need to provide a context for the lemmatization. So, we add the part-of-speech as a parameter.
Python3
from nltk.stem import WordNetLemmatizerfrom nltk.tokenize import word_tokenizelemmatizer = WordNetLemmatizer()# lemmatize stringdef lemmatize_word(text): word_tokens = word_tokenize(text) # provide context i.e. part-of-speech lemmas = [lemmatizer.lemmatize(word, pos ='v') for word in word_tokens] return lemmas text = 'data science uses scientific methods algorithms and many types of processes'lemmatize_word(text)
Example:
Input: ‘data science uses scientific methods algorithms and many types of processes’ Output: [‘data’, ‘science’, ‘use’, ‘scientific’, ‘methods’, ‘algorithms’, ‘and’, ‘many’, ‘type’, ‘of’, ‘process’]
frikishaan
rkbhola5
Natural-language-processing
Python-nltk
Machine Learning
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Linear Regression
Search Algorithms in AI
Getting started with Machine Learning
Introduction to Recurrent Neural Network
Support Vector Machine Algorithm
Random Forest Regression in Python
Running Python script on GPU.
ML | Underfitting and Overfitting
Association Rule
ML | Monte Carlo Tree Search (MCTS) | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n27 Jan, 2022"
},
{
"code": null,
"e": 548,
"s": 53,
"text": "Prerequisites: Introduction to NLPWhenever we have textual data, we need to apply several pre-processing steps to the data to transform words into numerical features that work with machine learning algorithms. The pre-processing steps for a problem depend mainly on the domain and the problem itself, hence, we don’t need to apply all steps to every problem. In this article, we are going to see text preprocessing in Python. We will be using the NLTK (Natural Language Toolkit) library here. "
},
{
"code": null,
"e": 556,
"s": 548,
"text": "Python3"
},
{
"code": "# import the necessary librariesimport nltkimport stringimport re",
"e": 622,
"s": 556,
"text": null
},
{
"code": null,
"e": 700,
"s": 622,
"text": "We lowercase the text to reduce the size of the vocabulary of our text data. "
},
{
"code": null,
"e": 708,
"s": 700,
"text": "Python3"
},
{
"code": "def text_lowercase(text): return text.lower() input_str = \"Hey, did you know that the summer break is coming? Amazing right !! It's only 5 more days !!\"text_lowercase(input_str)",
"e": 889,
"s": 708,
"text": null
},
{
"code": null,
"e": 900,
"s": 889,
"text": "Example: "
},
{
"code": null,
"e": 1103,
"s": 900,
"text": "Input: “Hey, did you know that the summer break is coming? Amazing right!! It’s only 5 more days!!” Output: “hey, did you know that the summer break is coming? amazing right!! it’s only 5 more days!!” "
},
{
"code": null,
"e": 1249,
"s": 1105,
"text": "We can either remove numbers or convert the numbers into their textual representations. We can use regular expressions to remove the numbers. "
},
{
"code": null,
"e": 1257,
"s": 1249,
"text": "Python3"
},
{
"code": "# Remove numbersdef remove_numbers(text): result = re.sub(r'\\d+', '', text) return result input_str = \"There are 3 balls in this bag, and 12 in the other one.\"remove_numbers(input_str)",
"e": 1448,
"s": 1257,
"text": null
},
{
"code": null,
"e": 1459,
"s": 1448,
"text": "Example: "
},
{
"code": null,
"e": 1587,
"s": 1459,
"text": "Input: “There are 3 balls in this bag, and 12 in the other one.” Output: ‘There are balls in this bag, and in the other one.’ "
},
{
"code": null,
"e": 1679,
"s": 1587,
"text": "We can also convert the numbers into words. This can be done by using the inflect library. "
},
{
"code": null,
"e": 1687,
"s": 1679,
"text": "Python3"
},
{
"code": "# import the inflect libraryimport inflectp = inflect.engine() # convert number into wordsdef convert_number(text): # split string into list of words temp_str = text.split() # initialise empty list new_string = [] for word in temp_str: # if word is a digit, convert the digit # to numbers and append into the new_string list if word.isdigit(): temp = p.number_to_words(word) new_string.append(temp) # append the word as it is else: new_string.append(word) # join the words of new_string to form a string temp_str = ' '.join(new_string) return temp_str input_str = 'There are 3 balls in this bag, and 12 in the other one.'convert_number(input_str)",
"e": 2429,
"s": 1687,
"text": null
},
{
"code": null,
"e": 2440,
"s": 2429,
"text": "Example: "
},
{
"code": null,
"e": 2581,
"s": 2440,
"text": "Input: “There are 3 balls in this bag, and 12 in the other one.” Output: “There are three balls in this bag, and twelve in the other one.” "
},
{
"code": null,
"e": 2750,
"s": 2583,
"text": "We remove punctuations so that we don’t have different forms of the same word. If we don’t remove the punctuation, then been. been, been! will be treated separately. "
},
{
"code": null,
"e": 2758,
"s": 2750,
"text": "Python3"
},
{
"code": "# remove punctuationdef remove_punctuation(text): translator = str.maketrans('', '', string.punctuation) return text.translate(translator) input_str = \"Hey, did you know that the summer break is coming? Amazing right !! It's only 5 more days !!\"remove_punctuation(input_str)",
"e": 3039,
"s": 2758,
"text": null
},
{
"code": null,
"e": 3050,
"s": 3039,
"text": "Example: "
},
{
"code": null,
"e": 3246,
"s": 3050,
"text": "Input: “Hey, did you know that the summer break is coming? Amazing right!! It’s only 5 more days!!” Output: “Hey did you know that the summer break is coming Amazing right Its only 5 more days” "
},
{
"code": null,
"e": 3332,
"s": 3248,
"text": "We can use the join and split function to remove all the white spaces in a string. "
},
{
"code": null,
"e": 3340,
"s": 3332,
"text": "Python3"
},
{
"code": "# remove whitespace from textdef remove_whitespace(text): return \" \".join(text.split()) input_str = \" we don't need the given questions\"remove_whitespace(input_str)",
"e": 3513,
"s": 3340,
"text": null
},
{
"code": null,
"e": 3524,
"s": 3513,
"text": "Example: "
},
{
"code": null,
"e": 3616,
"s": 3524,
"text": "Input: \" we don't need the given questions\"\nOutput: \"we don't need the given questions\""
},
{
"code": null,
"e": 3914,
"s": 3618,
"text": "Stopwords are words that do not contribute to the meaning of a sentence. Hence, they can safely be removed without causing any change in the meaning of the sentence. The NLTK library has a set of stopwords and we can use these to remove stopwords from our text and return a list of word tokens. "
},
{
"code": null,
"e": 3924,
"s": 3916,
"text": "Python3"
},
{
"code": "from nltk.corpus import stopwordsfrom nltk.tokenize import word_tokenize # remove stopwords functiondef remove_stopwords(text): stop_words = set(stopwords.words(\"english\")) word_tokens = word_tokenize(text) filtered_text = [word for word in word_tokens if word not in stop_words] return filtered_text example_text = \"This is a sample sentence and we are going to remove the stopwords from this.\"remove_stopwords(example_text)",
"e": 4362,
"s": 3924,
"text": null
},
{
"code": null,
"e": 4373,
"s": 4362,
"text": "Example: "
},
{
"code": null,
"e": 4532,
"s": 4373,
"text": "Input: “This is a sample sentence and we are going to remove the stopwords from this” Output: [‘This’, ‘sample’, ‘sentence’, ‘going’, ‘remove’, ‘stopwords’] "
},
{
"code": null,
"e": 4823,
"s": 4534,
"text": "Stemming is the process of getting the root form of a word. Stem or root is the part to which inflectional affixes (-ed, -ize, -de, -s, etc.) are added. The stem of a word is created by removing the prefix or suffix of a word. So, stemming a word may not result in actual words.Example: "
},
{
"code": null,
"e": 4918,
"s": 4823,
"text": "books ---> book\nlooked ---> look\ndenied ---> deni\nflies ---> fli"
},
{
"code": null,
"e": 5271,
"s": 4922,
"text": "If the text is not in tokens, then we need to convert it into tokens. After we have converted strings of text into tokens, we can convert the word tokens into their root form. There are mainly three algorithms for stemming. These are the Porter Stemmer, the Snowball Stemmer and the Lancaster Stemmer. Porter Stemmer is the most common among them. "
},
{
"code": null,
"e": 5279,
"s": 5271,
"text": "Python3"
},
{
"code": "from nltk.stem.porter import PorterStemmerfrom nltk.tokenize import word_tokenizestemmer = PorterStemmer() # stem words in the list of tokenized wordsdef stem_words(text): word_tokens = word_tokenize(text) stems = [stemmer.stem(word) for word in word_tokens] return stems text = 'data science uses scientific methods algorithms and many types of processes'stem_words(text)",
"e": 5661,
"s": 5279,
"text": null
},
{
"code": null,
"e": 5672,
"s": 5661,
"text": "Example: "
},
{
"code": null,
"e": 5868,
"s": 5672,
"text": "Input: ‘data science uses scientific methods algorithms and many types of processes’ Output: [‘data’, ‘scienc’, ‘use’, ‘scientif’, ‘method’, ‘algorithm’, ‘and’, ‘mani’, ‘type’, ‘of’, ‘process’] "
},
{
"code": null,
"e": 6252,
"s": 5870,
"text": "Like stemming, lemmatization also converts a word to its root form. The only difference is that lemmatization ensures that the root word belongs to the language. We will get valid words if we use lemmatization. In NLTK, we use the WordNetLemmatizer to get the lemmas of words. We also need to provide a context for the lemmatization. So, we add the part-of-speech as a parameter. "
},
{
"code": null,
"e": 6260,
"s": 6252,
"text": "Python3"
},
{
"code": "from nltk.stem import WordNetLemmatizerfrom nltk.tokenize import word_tokenizelemmatizer = WordNetLemmatizer()# lemmatize stringdef lemmatize_word(text): word_tokens = word_tokenize(text) # provide context i.e. part-of-speech lemmas = [lemmatizer.lemmatize(word, pos ='v') for word in word_tokens] return lemmas text = 'data science uses scientific methods algorithms and many types of processes'lemmatize_word(text)",
"e": 6689,
"s": 6260,
"text": null
},
{
"code": null,
"e": 6700,
"s": 6689,
"text": "Example: "
},
{
"code": null,
"e": 6901,
"s": 6700,
"text": "Input: ‘data science uses scientific methods algorithms and many types of processes’ Output: [‘data’, ‘science’, ‘use’, ‘scientific’, ‘methods’, ‘algorithms’, ‘and’, ‘many’, ‘type’, ‘of’, ‘process’] "
},
{
"code": null,
"e": 6914,
"s": 6903,
"text": "frikishaan"
},
{
"code": null,
"e": 6923,
"s": 6914,
"text": "rkbhola5"
},
{
"code": null,
"e": 6951,
"s": 6923,
"text": "Natural-language-processing"
},
{
"code": null,
"e": 6963,
"s": 6951,
"text": "Python-nltk"
},
{
"code": null,
"e": 6980,
"s": 6963,
"text": "Machine Learning"
},
{
"code": null,
"e": 6997,
"s": 6980,
"text": "Machine Learning"
},
{
"code": null,
"e": 7095,
"s": 6997,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7118,
"s": 7095,
"text": "ML | Linear Regression"
},
{
"code": null,
"e": 7142,
"s": 7118,
"text": "Search Algorithms in AI"
},
{
"code": null,
"e": 7180,
"s": 7142,
"text": "Getting started with Machine Learning"
},
{
"code": null,
"e": 7221,
"s": 7180,
"text": "Introduction to Recurrent Neural Network"
},
{
"code": null,
"e": 7254,
"s": 7221,
"text": "Support Vector Machine Algorithm"
},
{
"code": null,
"e": 7289,
"s": 7254,
"text": "Random Forest Regression in Python"
},
{
"code": null,
"e": 7319,
"s": 7289,
"text": "Running Python script on GPU."
},
{
"code": null,
"e": 7353,
"s": 7319,
"text": "ML | Underfitting and Overfitting"
},
{
"code": null,
"e": 7370,
"s": 7353,
"text": "Association Rule"
}
] |
Node.js forEach() function | 13 Oct, 2021
forEach() is an array function from Node.js that is used to iterate over items in a given array.
Syntax:
array_name.forEach(function)
Parameter: This function takes a function (which is to be executed) as a parameter.
Return type: The function returns array element after iteration.
The program below demonstrates the working of the function:
Program 1:
const arr = ['cat', 'dog', 'fish'];arr.forEach(element => { console.log(element);});
Output:
cat
dog
fish
Program 2:
const arr = [1, 2, 3, 8, 7];arr.forEach(element => { console.log(element);});
Output:
1
2
3
8
7
NodeJS-function
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between promise and async await in Node.js
Mongoose | findByIdAndUpdate() Function
JWT Authentication with Node.js
Installation of Node.js on Windows
Difference between dependencies, devDependencies and peerDependencies
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n13 Oct, 2021"
},
{
"code": null,
"e": 150,
"s": 53,
"text": "forEach() is an array function from Node.js that is used to iterate over items in a given array."
},
{
"code": null,
"e": 158,
"s": 150,
"text": "Syntax:"
},
{
"code": null,
"e": 187,
"s": 158,
"text": "array_name.forEach(function)"
},
{
"code": null,
"e": 271,
"s": 187,
"text": "Parameter: This function takes a function (which is to be executed) as a parameter."
},
{
"code": null,
"e": 336,
"s": 271,
"text": "Return type: The function returns array element after iteration."
},
{
"code": null,
"e": 396,
"s": 336,
"text": "The program below demonstrates the working of the function:"
},
{
"code": null,
"e": 407,
"s": 396,
"text": "Program 1:"
},
{
"code": "const arr = ['cat', 'dog', 'fish'];arr.forEach(element => { console.log(element);});",
"e": 493,
"s": 407,
"text": null
},
{
"code": null,
"e": 501,
"s": 493,
"text": "Output:"
},
{
"code": null,
"e": 514,
"s": 501,
"text": "cat\ndog\nfish"
},
{
"code": null,
"e": 525,
"s": 514,
"text": "Program 2:"
},
{
"code": "const arr = [1, 2, 3, 8, 7];arr.forEach(element => { console.log(element);});",
"e": 604,
"s": 525,
"text": null
},
{
"code": null,
"e": 612,
"s": 604,
"text": "Output:"
},
{
"code": null,
"e": 622,
"s": 612,
"text": "1\n2\n3\n8\n7"
},
{
"code": null,
"e": 638,
"s": 622,
"text": "NodeJS-function"
},
{
"code": null,
"e": 646,
"s": 638,
"text": "Node.js"
},
{
"code": null,
"e": 663,
"s": 646,
"text": "Web Technologies"
},
{
"code": null,
"e": 761,
"s": 663,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 815,
"s": 761,
"text": "Difference between promise and async await in Node.js"
},
{
"code": null,
"e": 855,
"s": 815,
"text": "Mongoose | findByIdAndUpdate() Function"
},
{
"code": null,
"e": 887,
"s": 855,
"text": "JWT Authentication with Node.js"
},
{
"code": null,
"e": 922,
"s": 887,
"text": "Installation of Node.js on Windows"
},
{
"code": null,
"e": 992,
"s": 922,
"text": "Difference between dependencies, devDependencies and peerDependencies"
},
{
"code": null,
"e": 1054,
"s": 992,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 1115,
"s": 1054,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1165,
"s": 1115,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 1208,
"s": 1165,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
set vs map in C++ STL | 13 Jun, 2022
set and map in STL are similar in the sense that they both use Red Black Tree (A self balancing BST). Note that the time complexities of search, insert and delete are O(Log n). Differences: The difference is set is used to store only keys while map is used to store key value pairs. For example consider in the problem of printing sorted distinct elements, we use set as there is value needed for a key. While if we change the problem to print frequencies of distinct sorted elements, we use map. We need map to store array values as key and frequencies as value.
CPP
// CPP program to demonstrate working of set#include <bits/stdc++.h>using namespace std; int main(){ set<int> s1; s1.insert(2); s1.insert(5); s1.insert(3); s1.insert(6); cout << "Elements in set:\n"; for (auto it : s1) cout << it << " "; // Sorted return 0;}
Elements in set:
2 3 5 6
CPP
// CPP program to demonstrate working of map#include <bits/stdc++.h>using namespace std; int main(){ map<int, int> m; m[1] = 2; // Insertion by indexing // Direct pair insertion m.insert({ 4, 5 }); // Insertion of pair by make_pair m.insert(make_pair(8, 5)); cout << "Elements in map:\n"; for (auto it : m) cout << "[ " << it.first << ", " << it.second << "]\n"; // Sorted return 0;}
Elements in map:
[ 1, 2]
[ 4, 5]
[ 8, 5]
Variations of set and map: Set and Map, both stores unique values and sorted values as well. But If we don’t have such a requirement, we use multiset/multimap and unordered_set/unordered_map. Multimap: Multimap doesn’t allow elements to stored by indexing.
CPP
// CPP program to demonstrate working of Multimap#include <bits/stdc++.h>using namespace std; int main(){ multimap<int, int> m; m.insert({ 1, 2 }); m.insert({ 2, 3 }); m.insert({ 4, 5 }); m.insert({ 2, 3 }); m.insert({ 1, 2 }); cout << "Elements in Multimap:\n"; for (auto it : m) cout << "[ " << it.first << ", " << it.second << "]\n"; // Sorted return 0;}
Elements in Multimap:
[ 1, 2]
[ 1, 2]
[ 2, 3]
[ 2, 3]
[ 4, 5]
Multiset:
CPP
// CPP program to demonstrate working of Multiset#include <bits/stdc++.h>using namespace std; int main(){ multiset<int> ms; ms.insert(1); ms.insert(3); ms.insert(4); ms.insert(2); ms.insert(2); cout << "Elements in Multiset:\n"; for (auto it : ms) cout << it << " "; return 0;}
Elements in Multiset:
1 2 2 3 4
Unordered_set:
CPP
// CPP program to demonstrate working of Unordered_set#include <bits/stdc++.h>using namespace std; int main(){ unordered_set<int> us; us.insert(1); us.insert(3); us.insert(4); us.insert(2); us.insert(2); cout << "Elements in unordered_set:\n"; for (auto it : us) cout << it << " "; // Sorted return 0;}
Elements in unordered_set:
2 4 1 3
Unordered_map:
CPP
// CPP program to demonstrate working of Unordered_map#include <bits/stdc++.h>using namespace std; int main(){ unordered_map<int, int> um; um[1] = 2; um[4] = 5; um[2] = 3; um[8] = 5; um[3] = 6; cout << "Elements in unordered_map:\n"; for (auto it : um) cout << "[ " << it.first << ", " << it.second << "]\n"; return 0;}
Elements in unordered_map:
[ 3, 6]
[ 2, 3]
[ 8, 5]
[ 1, 2]
[ 4, 5]
Let us see the differences in a tabular form -:
Its syntax is -:
set<data_type>name_of_set;
Its syntax is -:
map<data_type , data_type>name_of_map;
hansschukkink
surajv
mayank007rawa
cpp-map
cpp-set
STL
C++
Difference Between
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Bitwise Operators in C/C++
vector erase() and clear() in C++
Substring in C++
Priority Queue in C++ Standard Template Library (STL)
Inheritance in C++
Class method vs Static method in Python
Difference between BFS and DFS
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Differences between JDK, JRE and JVM | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n13 Jun, 2022"
},
{
"code": null,
"e": 618,
"s": 53,
"text": "set and map in STL are similar in the sense that they both use Red Black Tree (A self balancing BST). Note that the time complexities of search, insert and delete are O(Log n). Differences: The difference is set is used to store only keys while map is used to store key value pairs. For example consider in the problem of printing sorted distinct elements, we use set as there is value needed for a key. While if we change the problem to print frequencies of distinct sorted elements, we use map. We need map to store array values as key and frequencies as value. "
},
{
"code": null,
"e": 622,
"s": 618,
"text": "CPP"
},
{
"code": "// CPP program to demonstrate working of set#include <bits/stdc++.h>using namespace std; int main(){ set<int> s1; s1.insert(2); s1.insert(5); s1.insert(3); s1.insert(6); cout << \"Elements in set:\\n\"; for (auto it : s1) cout << it << \" \"; // Sorted return 0;}",
"e": 914,
"s": 622,
"text": null
},
{
"code": null,
"e": 939,
"s": 914,
"text": "Elements in set:\n2 3 5 6"
},
{
"code": null,
"e": 945,
"s": 941,
"text": "CPP"
},
{
"code": "// CPP program to demonstrate working of map#include <bits/stdc++.h>using namespace std; int main(){ map<int, int> m; m[1] = 2; // Insertion by indexing // Direct pair insertion m.insert({ 4, 5 }); // Insertion of pair by make_pair m.insert(make_pair(8, 5)); cout << \"Elements in map:\\n\"; for (auto it : m) cout << \"[ \" << it.first << \", \" << it.second << \"]\\n\"; // Sorted return 0;}",
"e": 1380,
"s": 945,
"text": null
},
{
"code": null,
"e": 1421,
"s": 1380,
"text": "Elements in map:\n[ 1, 2]\n[ 4, 5]\n[ 8, 5]"
},
{
"code": null,
"e": 1682,
"s": 1423,
"text": "Variations of set and map: Set and Map, both stores unique values and sorted values as well. But If we don’t have such a requirement, we use multiset/multimap and unordered_set/unordered_map. Multimap: Multimap doesn’t allow elements to stored by indexing. "
},
{
"code": null,
"e": 1686,
"s": 1682,
"text": "CPP"
},
{
"code": "// CPP program to demonstrate working of Multimap#include <bits/stdc++.h>using namespace std; int main(){ multimap<int, int> m; m.insert({ 1, 2 }); m.insert({ 2, 3 }); m.insert({ 4, 5 }); m.insert({ 2, 3 }); m.insert({ 1, 2 }); cout << \"Elements in Multimap:\\n\"; for (auto it : m) cout << \"[ \" << it.first << \", \" << it.second << \"]\\n\"; // Sorted return 0;}",
"e": 2093,
"s": 1686,
"text": null
},
{
"code": null,
"e": 2155,
"s": 2093,
"text": "Elements in Multimap:\n[ 1, 2]\n[ 1, 2]\n[ 2, 3]\n[ 2, 3]\n[ 4, 5]"
},
{
"code": null,
"e": 2169,
"s": 2157,
"text": "Multiset: "
},
{
"code": null,
"e": 2173,
"s": 2169,
"text": "CPP"
},
{
"code": "// CPP program to demonstrate working of Multiset#include <bits/stdc++.h>using namespace std; int main(){ multiset<int> ms; ms.insert(1); ms.insert(3); ms.insert(4); ms.insert(2); ms.insert(2); cout << \"Elements in Multiset:\\n\"; for (auto it : ms) cout << it << \" \"; return 0;}",
"e": 2488,
"s": 2173,
"text": null
},
{
"code": null,
"e": 2520,
"s": 2488,
"text": "Elements in Multiset:\n1 2 2 3 4"
},
{
"code": null,
"e": 2539,
"s": 2522,
"text": "Unordered_set: "
},
{
"code": null,
"e": 2543,
"s": 2539,
"text": "CPP"
},
{
"code": "// CPP program to demonstrate working of Unordered_set#include <bits/stdc++.h>using namespace std; int main(){ unordered_set<int> us; us.insert(1); us.insert(3); us.insert(4); us.insert(2); us.insert(2); cout << \"Elements in unordered_set:\\n\"; for (auto it : us) cout << it << \" \"; // Sorted return 0;}",
"e": 2883,
"s": 2543,
"text": null
},
{
"code": null,
"e": 2918,
"s": 2883,
"text": "Elements in unordered_set:\n2 4 1 3"
},
{
"code": null,
"e": 2937,
"s": 2920,
"text": "Unordered_map: "
},
{
"code": null,
"e": 2941,
"s": 2937,
"text": "CPP"
},
{
"code": "// CPP program to demonstrate working of Unordered_map#include <bits/stdc++.h>using namespace std; int main(){ unordered_map<int, int> um; um[1] = 2; um[4] = 5; um[2] = 3; um[8] = 5; um[3] = 6; cout << \"Elements in unordered_map:\\n\"; for (auto it : um) cout << \"[ \" << it.first << \", \" << it.second << \"]\\n\"; return 0;}",
"e": 3298,
"s": 2941,
"text": null
},
{
"code": null,
"e": 3365,
"s": 3298,
"text": "Elements in unordered_map:\n[ 3, 6]\n[ 2, 3]\n[ 8, 5]\n[ 1, 2]\n[ 4, 5]"
},
{
"code": null,
"e": 3416,
"s": 3367,
"text": "Let us see the differences in a tabular form -: "
},
{
"code": null,
"e": 3433,
"s": 3416,
"text": "Its syntax is -:"
},
{
"code": null,
"e": 3460,
"s": 3433,
"text": "set<data_type>name_of_set;"
},
{
"code": null,
"e": 3477,
"s": 3460,
"text": "Its syntax is -:"
},
{
"code": null,
"e": 3516,
"s": 3477,
"text": "map<data_type , data_type>name_of_map;"
},
{
"code": null,
"e": 3530,
"s": 3516,
"text": "hansschukkink"
},
{
"code": null,
"e": 3537,
"s": 3530,
"text": "surajv"
},
{
"code": null,
"e": 3551,
"s": 3537,
"text": "mayank007rawa"
},
{
"code": null,
"e": 3559,
"s": 3551,
"text": "cpp-map"
},
{
"code": null,
"e": 3567,
"s": 3559,
"text": "cpp-set"
},
{
"code": null,
"e": 3571,
"s": 3567,
"text": "STL"
},
{
"code": null,
"e": 3575,
"s": 3571,
"text": "C++"
},
{
"code": null,
"e": 3594,
"s": 3575,
"text": "Difference Between"
},
{
"code": null,
"e": 3598,
"s": 3594,
"text": "STL"
},
{
"code": null,
"e": 3602,
"s": 3598,
"text": "CPP"
},
{
"code": null,
"e": 3700,
"s": 3602,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3727,
"s": 3700,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 3761,
"s": 3727,
"text": "vector erase() and clear() in C++"
},
{
"code": null,
"e": 3778,
"s": 3761,
"text": "Substring in C++"
},
{
"code": null,
"e": 3832,
"s": 3778,
"text": "Priority Queue in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 3851,
"s": 3832,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 3891,
"s": 3851,
"text": "Class method vs Static method in Python"
},
{
"code": null,
"e": 3922,
"s": 3891,
"text": "Difference between BFS and DFS"
},
{
"code": null,
"e": 3983,
"s": 3922,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 4051,
"s": 3983,
"text": "Difference Between Method Overloading and Method Overriding in Java"
}
] |
Python Program to get all unique keys from a List of Dictionaries | 22 Mar, 2021
Given a list arr[] consisting of N dictionaries, the task is to find the sum of unique keys from the given list of the dictionary.
Examples:
Input: arr = [{‘my’: 1, ‘name’: 2}, {‘is’: 1, ‘my’: 3}, {‘ria’: 2}]Output: [‘ria’, ‘my’, ‘is’, ‘name’]Explanation: The set of unique keys are {“ria”, “my”, “Is”, “name”}.
Input: arr = [{‘X’: 100, ‘Y’: 2}, {‘Z’: 1, ‘Z’: 30}, {‘X’: 21}]Output: [‘Z’, ‘X’, ‘Y’]Explanation: The set of unique keys are {“X”, “Y”, “Z”}.
Approach using Chain iterable tools: The problem can be solved using set() and keys() methods and chain iterable tools to solve the above problem.
Follow the steps below to solve the problem:
Traverse all keys of every dictionary using chain iterable tools
Store the set of keys in a list, say res.
Print the list res as the required answer.
Below is the implementation of the above approach:
Python3
# Python3 program for the above approachfrom itertools import chain # Function to print all unique keys# present in a list of dictionariesdef UniqueKeys(arr): # Stores the list of unique keys res = list(set(chain.from_iterable(sub.keys() for sub in arr))) # Print the list print(str(res)) # Driver Codearr = [{'my': 1, 'name': 2}, {'is': 1, 'my': 3}, {'ria': 2}]UniqueKeys(arr)
['is', 'ria', 'my', 'name']
Time Complexity: O(N * maxm), where maxm denotes the size of the longest dictionary.Auxiliary Space: O(N * maxm)
Approach using List Comprehension and Dictionary Comprehension: The problem can be solved alternately using set() and keys() method and list comprehension and dictionary comprehension to solve the problem.
Follow the steps below to solve the problem:
Traverse all the keys of every dictionary using List Comprehension and Dictionary Comprehension and then store the set of keys in a list, say res.
Print the list res as the required answer.
Below is the implementation of the above approach:
Python3
# Python3 program for the above approach from itertools import chain # Function to print all unique keys# from a list of dictionariesdef UniqueKeys(arr): # Stores the list of unique keys res = list(set(val for dic in arr for val in dic.keys())) # Print the list print(str(res)) # Driver Code # Inputarr = [{'my': 1, 'name': 2}, {'is': 1, 'my': 3}, {'ria': 2}] UniqueKeys(arr)
['ria', 'my', 'name', 'is']
Time Complexity: O(N * maxm), where maxm denotes the size of the longest dictionary.Auxiliary Space: O(N * maxm)
Python dictionary-programs
Python list-programs
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Mar, 2021"
},
{
"code": null,
"e": 159,
"s": 28,
"text": "Given a list arr[] consisting of N dictionaries, the task is to find the sum of unique keys from the given list of the dictionary."
},
{
"code": null,
"e": 169,
"s": 159,
"text": "Examples:"
},
{
"code": null,
"e": 340,
"s": 169,
"text": "Input: arr = [{‘my’: 1, ‘name’: 2}, {‘is’: 1, ‘my’: 3}, {‘ria’: 2}]Output: [‘ria’, ‘my’, ‘is’, ‘name’]Explanation: The set of unique keys are {“ria”, “my”, “Is”, “name”}."
},
{
"code": null,
"e": 483,
"s": 340,
"text": "Input: arr = [{‘X’: 100, ‘Y’: 2}, {‘Z’: 1, ‘Z’: 30}, {‘X’: 21}]Output: [‘Z’, ‘X’, ‘Y’]Explanation: The set of unique keys are {“X”, “Y”, “Z”}."
},
{
"code": null,
"e": 630,
"s": 483,
"text": "Approach using Chain iterable tools: The problem can be solved using set() and keys() methods and chain iterable tools to solve the above problem."
},
{
"code": null,
"e": 675,
"s": 630,
"text": "Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 740,
"s": 675,
"text": "Traverse all keys of every dictionary using chain iterable tools"
},
{
"code": null,
"e": 782,
"s": 740,
"text": "Store the set of keys in a list, say res."
},
{
"code": null,
"e": 825,
"s": 782,
"text": "Print the list res as the required answer."
},
{
"code": null,
"e": 876,
"s": 825,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 884,
"s": 876,
"text": "Python3"
},
{
"code": "# Python3 program for the above approachfrom itertools import chain # Function to print all unique keys# present in a list of dictionariesdef UniqueKeys(arr): # Stores the list of unique keys res = list(set(chain.from_iterable(sub.keys() for sub in arr))) # Print the list print(str(res)) # Driver Codearr = [{'my': 1, 'name': 2}, {'is': 1, 'my': 3}, {'ria': 2}]UniqueKeys(arr)",
"e": 1295,
"s": 884,
"text": null
},
{
"code": null,
"e": 1324,
"s": 1295,
"text": "['is', 'ria', 'my', 'name']\n"
},
{
"code": null,
"e": 1437,
"s": 1324,
"text": "Time Complexity: O(N * maxm), where maxm denotes the size of the longest dictionary.Auxiliary Space: O(N * maxm)"
},
{
"code": null,
"e": 1643,
"s": 1437,
"text": "Approach using List Comprehension and Dictionary Comprehension: The problem can be solved alternately using set() and keys() method and list comprehension and dictionary comprehension to solve the problem."
},
{
"code": null,
"e": 1688,
"s": 1643,
"text": "Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 1835,
"s": 1688,
"text": "Traverse all the keys of every dictionary using List Comprehension and Dictionary Comprehension and then store the set of keys in a list, say res."
},
{
"code": null,
"e": 1878,
"s": 1835,
"text": "Print the list res as the required answer."
},
{
"code": null,
"e": 1929,
"s": 1878,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 1937,
"s": 1929,
"text": "Python3"
},
{
"code": "# Python3 program for the above approach from itertools import chain # Function to print all unique keys# from a list of dictionariesdef UniqueKeys(arr): # Stores the list of unique keys res = list(set(val for dic in arr for val in dic.keys())) # Print the list print(str(res)) # Driver Code # Inputarr = [{'my': 1, 'name': 2}, {'is': 1, 'my': 3}, {'ria': 2}] UniqueKeys(arr)",
"e": 2347,
"s": 1937,
"text": null
},
{
"code": null,
"e": 2376,
"s": 2347,
"text": "['ria', 'my', 'name', 'is']\n"
},
{
"code": null,
"e": 2489,
"s": 2376,
"text": "Time Complexity: O(N * maxm), where maxm denotes the size of the longest dictionary.Auxiliary Space: O(N * maxm)"
},
{
"code": null,
"e": 2516,
"s": 2489,
"text": "Python dictionary-programs"
},
{
"code": null,
"e": 2537,
"s": 2516,
"text": "Python list-programs"
},
{
"code": null,
"e": 2553,
"s": 2537,
"text": "Python Programs"
}
] |
How to Find All Failed SSH login Attempts in Linux? | 16 Feb, 2021
SSH Server provides us with a secure encrypted communications channel between two untrusted hosts over an insecure network. Still, we can not say for sure that it is secured. It is generally very susceptible to many kinds of password guessing and brute-forcing attacks.
To enable and start the SSH server, the commands could be executed in the following ways:
sudo systemctl enable ssh
sudo systemctl start ssh
To check the running status of the server execute the following command.
sudo systemctl status ssh
Each plan to log in into an SSH server is tracked and recorded into a log file by the rsyslog daemon in Linux. We can easily view this file using cat and grep commands.
There could be various reasons due to which the failed login attempt could be generated. Below are the listed, three most common reasons:
Typo: Tying error with wrong passwords
Wrong Password: Trying to enter with the wrong password
Brute-force Attack: Using Dictionary to attack with a combination of common userid and passwords
With either of the two commands given below we can view all failed login attempts:
grep "Failed password" /var/log/auth.log
cat /var/log/auth.log | grep "Failed password"
To view additional information use the below command:
egrep "Failed|Failure" /var/log/auth.log
# It works the same way as grep -E does
To filter out only the IP address from these logs using the below command. This will display a list of IP addresses along with the number of times the log was generated from the IP address.
grep "Failed password" /var/log/auth.log | awk '{print $11}' | uniq -c | sort -nr
The command functions in the following way:
List out the “Failed password” using grep command with /var/log/secure or /var/log/auth.log filesPrint IP/ hostname with awk and cut commandFormat the data with the sort command (Optional)Print total failed attempts to SSH login with uniq commands
List out the “Failed password” using grep command with /var/log/secure or /var/log/auth.log files
Print IP/ hostname with awk and cut command
Format the data with the sort command (Optional)
Print total failed attempts to SSH login with uniq commands
Similarly, you can also print authentication failure logs to the terminal:
grep "authentication failure" /var/log/auth.log | awk '{ print $13 }' | cut -b7- | sort | uniq -c
Alternatively, we can also view the logs using the Systemd daemon using the journalctl command.
journalctl _SYSTEMD_UNIT=ssh.service | egrep "Failed|Failure"
It’s best practice to check the settings for the failed login attempts to the server. You could check out /etc/pam.d/common-auth file, which is used with the Linux Pluggable Authentication Modules (PAM) within the system.
cat /etc/pam.d/password-auth
Settings within this file control the threshold for the failed login attempts before the account is temporarily locked. You could even adjust the timing for this temporary lock.
The following code segment will have PAM locking an account temporarily after three failed login attempts. The lockout will last for 300 seconds which is 5 minutes.
auth required pam_tally2.so deny=3 unlock_time=300
Occasionally failed logins are to be expected but still, it is crucial to identify the failed login attempts to your server. The IP that frequently hits your server should be identified immediately and should be blocked within the firewall so any potential attacks to your server could be prevented.
Picked
Technical Scripter 2020
How To
Linux-Unix
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Set Git Username and Password in GitBash?
How to Install Jupyter Notebook on MacOS?
How to Install and Use NVM on Windows?
How to Install Python Packages for AWS Lambda Layers?
How to Install Git in VS Code?
Sed Command in Linux/Unix with examples
AWK command in Unix/Linux with examples
grep command in Unix/Linux
cut command in Linux with examples
cp command in Linux with examples | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n16 Feb, 2021"
},
{
"code": null,
"e": 298,
"s": 28,
"text": "SSH Server provides us with a secure encrypted communications channel between two untrusted hosts over an insecure network. Still, we can not say for sure that it is secured. It is generally very susceptible to many kinds of password guessing and brute-forcing attacks."
},
{
"code": null,
"e": 388,
"s": 298,
"text": "To enable and start the SSH server, the commands could be executed in the following ways:"
},
{
"code": null,
"e": 439,
"s": 388,
"text": "sudo systemctl enable ssh\nsudo systemctl start ssh"
},
{
"code": null,
"e": 512,
"s": 439,
"text": "To check the running status of the server execute the following command."
},
{
"code": null,
"e": 538,
"s": 512,
"text": "sudo systemctl status ssh"
},
{
"code": null,
"e": 707,
"s": 538,
"text": "Each plan to log in into an SSH server is tracked and recorded into a log file by the rsyslog daemon in Linux. We can easily view this file using cat and grep commands."
},
{
"code": null,
"e": 845,
"s": 707,
"text": "There could be various reasons due to which the failed login attempt could be generated. Below are the listed, three most common reasons:"
},
{
"code": null,
"e": 884,
"s": 845,
"text": "Typo: Tying error with wrong passwords"
},
{
"code": null,
"e": 940,
"s": 884,
"text": "Wrong Password: Trying to enter with the wrong password"
},
{
"code": null,
"e": 1037,
"s": 940,
"text": "Brute-force Attack: Using Dictionary to attack with a combination of common userid and passwords"
},
{
"code": null,
"e": 1120,
"s": 1037,
"text": "With either of the two commands given below we can view all failed login attempts:"
},
{
"code": null,
"e": 1161,
"s": 1120,
"text": "grep \"Failed password\" /var/log/auth.log"
},
{
"code": null,
"e": 1208,
"s": 1161,
"text": "cat /var/log/auth.log | grep \"Failed password\""
},
{
"code": null,
"e": 1262,
"s": 1208,
"text": "To view additional information use the below command:"
},
{
"code": null,
"e": 1344,
"s": 1262,
"text": "egrep \"Failed|Failure\" /var/log/auth.log\n# It works the same way as grep -E does "
},
{
"code": null,
"e": 1534,
"s": 1344,
"text": "To filter out only the IP address from these logs using the below command. This will display a list of IP addresses along with the number of times the log was generated from the IP address."
},
{
"code": null,
"e": 1616,
"s": 1534,
"text": "grep \"Failed password\" /var/log/auth.log | awk '{print $11}' | uniq -c | sort -nr"
},
{
"code": null,
"e": 1663,
"s": 1616,
"text": "The command functions in the following way: "
},
{
"code": null,
"e": 1911,
"s": 1663,
"text": "List out the “Failed password” using grep command with /var/log/secure or /var/log/auth.log filesPrint IP/ hostname with awk and cut commandFormat the data with the sort command (Optional)Print total failed attempts to SSH login with uniq commands"
},
{
"code": null,
"e": 2009,
"s": 1911,
"text": "List out the “Failed password” using grep command with /var/log/secure or /var/log/auth.log files"
},
{
"code": null,
"e": 2053,
"s": 2009,
"text": "Print IP/ hostname with awk and cut command"
},
{
"code": null,
"e": 2102,
"s": 2053,
"text": "Format the data with the sort command (Optional)"
},
{
"code": null,
"e": 2162,
"s": 2102,
"text": "Print total failed attempts to SSH login with uniq commands"
},
{
"code": null,
"e": 2237,
"s": 2162,
"text": "Similarly, you can also print authentication failure logs to the terminal:"
},
{
"code": null,
"e": 2336,
"s": 2237,
"text": "grep \"authentication failure\" /var/log/auth.log | awk '{ print $13 }' | cut -b7- | sort | uniq -c"
},
{
"code": null,
"e": 2432,
"s": 2336,
"text": "Alternatively, we can also view the logs using the Systemd daemon using the journalctl command."
},
{
"code": null,
"e": 2494,
"s": 2432,
"text": "journalctl _SYSTEMD_UNIT=ssh.service | egrep \"Failed|Failure\""
},
{
"code": null,
"e": 2716,
"s": 2494,
"text": "It’s best practice to check the settings for the failed login attempts to the server. You could check out /etc/pam.d/common-auth file, which is used with the Linux Pluggable Authentication Modules (PAM) within the system."
},
{
"code": null,
"e": 2745,
"s": 2716,
"text": "cat /etc/pam.d/password-auth"
},
{
"code": null,
"e": 2923,
"s": 2745,
"text": "Settings within this file control the threshold for the failed login attempts before the account is temporarily locked. You could even adjust the timing for this temporary lock."
},
{
"code": null,
"e": 3088,
"s": 2923,
"text": "The following code segment will have PAM locking an account temporarily after three failed login attempts. The lockout will last for 300 seconds which is 5 minutes."
},
{
"code": null,
"e": 3139,
"s": 3088,
"text": "auth required pam_tally2.so deny=3 unlock_time=300"
},
{
"code": null,
"e": 3440,
"s": 3139,
"text": "Occasionally failed logins are to be expected but still, it is crucial to identify the failed login attempts to your server. The IP that frequently hits your server should be identified immediately and should be blocked within the firewall so any potential attacks to your server could be prevented. "
},
{
"code": null,
"e": 3447,
"s": 3440,
"text": "Picked"
},
{
"code": null,
"e": 3471,
"s": 3447,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 3478,
"s": 3471,
"text": "How To"
},
{
"code": null,
"e": 3489,
"s": 3478,
"text": "Linux-Unix"
},
{
"code": null,
"e": 3508,
"s": 3489,
"text": "Technical Scripter"
},
{
"code": null,
"e": 3606,
"s": 3508,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3655,
"s": 3606,
"text": "How to Set Git Username and Password in GitBash?"
},
{
"code": null,
"e": 3697,
"s": 3655,
"text": "How to Install Jupyter Notebook on MacOS?"
},
{
"code": null,
"e": 3736,
"s": 3697,
"text": "How to Install and Use NVM on Windows?"
},
{
"code": null,
"e": 3790,
"s": 3736,
"text": "How to Install Python Packages for AWS Lambda Layers?"
},
{
"code": null,
"e": 3821,
"s": 3790,
"text": "How to Install Git in VS Code?"
},
{
"code": null,
"e": 3861,
"s": 3821,
"text": "Sed Command in Linux/Unix with examples"
},
{
"code": null,
"e": 3901,
"s": 3861,
"text": "AWK command in Unix/Linux with examples"
},
{
"code": null,
"e": 3928,
"s": 3901,
"text": "grep command in Unix/Linux"
},
{
"code": null,
"e": 3963,
"s": 3928,
"text": "cut command in Linux with examples"
}
] |
Session Management in Android with Example | 23 Feb, 2021
Session Management is one of the most important features that are to be used in the Android App when you are integrating the login feature in Android. In your android app if you are using a feature of Login then you should have to save the state if the user has signed the first time. Then when the user closes his app and reopens it then he should redirect to our Home screen, rather than opening a login screen. So in this article, we will implement Session Management functionality in our Android app. For implementing this functionality we are creating a simple login form and a home screen. In our login form, the user has to enter his credentials and login into the app. After login, the user’s credentials will be saved inside the app, and whenever he reopens the app the user will be redirected to the home screen. For session management inside our app, we will be using Shared Preferences to store users’ credentials. Now we will move towards the implementation part.
We will be creating a simple Login app as mentioned above for storing user session. A sample GIF is given below in which we will get to see what we will be building in our app. Note that we will be implementing this project using Java language.
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Add the below strings in your strings.xml file
Navigate to the app > res > values > strings.xml and add the below strings to it.
XML
<resources> <!--app name--> <string name="app_name">Session Management</string> <!--string for login button--> <string name="login">Login</string> <!--string for edittext hint in password--> <string name="enter_password">Enter password</string> <!--string for edittext hint in email--> <string name="enter_youe_email">Enter your Email</string> <!--string for logout button--> <string name="logout">Logout</string></resources>
Step 3: Working with the activity_main.xml file
Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file.
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" tools:context=".MainActivity"> <!--EditText for getting user email address--> <!--input type is set to email--> <EditText android:id="@+id/idEdtEmail" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="10dp" android:layout_marginTop="50dp" android:layout_marginEnd="10dp" android:hint="@string/enter_youe_email" android:importantForAutofill="no" android:inputType="textEmailAddress" /> <!--EditText for getting user password--> <!--input type is set to password--> <EditText android:id="@+id/idEdtPassword" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/idEdtEmail" android:layout_marginStart="10dp" android:layout_marginTop="30dp" android:layout_marginEnd="10dp" android:hint="@string/enter_password" android:importantForAutofill="no" android:inputType="textPassword" /> <!--button to continue to login--> <Button android:id="@+id/idBtnLogin" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/idEdtPassword" android:layout_marginStart="10dp" android:layout_marginTop="30dp" android:layout_marginEnd="10dp" android:text="@string/login" /> </RelativeLayout>
Step 4: Create a new Activity for Home Screen
Navigate to the app > java > your app’s package name > Right-Click on your package name and New > Activity > Empty Activity and make sure to keep your language as Java. Name the activity as HomeActivity.
Step 5: Working with the MainActivity.java file
Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
Java
import android.content.Context;import android.content.Intent;import android.content.SharedPreferences;import android.os.Bundle;import android.text.TextUtils;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.Toast;import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { // creating constant keys for shared preferences. public static final String SHARED_PREFS = "shared_prefs"; // key for storing email. public static final String EMAIL_KEY = "email_key"; // key for storing password. public static final String PASSWORD_KEY = "password_key"; // variable for shared preferences. SharedPreferences sharedpreferences; String email, password; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Initializing EditTexts and our Button EditText emailEdt = findViewById(R.id.idEdtEmail); EditText passwordEdt = findViewById(R.id.idEdtPassword); Button loginBtn = findViewById(R.id.idBtnLogin); // getting the data which is stored in shared preferences. sharedpreferences = getSharedPreferences(SHARED_PREFS, Context.MODE_PRIVATE); // in shared prefs inside het string method // we are passing key value as EMAIL_KEY and // default value is // set to null if not present. email = sharedpreferences.getString(EMAIL_KEY, null); password = sharedpreferences.getString(PASSWORD_KEY, null); // calling on click listener for login button. loginBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // to check if the user fields are empty or not. if (TextUtils.isEmpty(emailEdt.getText().toString()) && TextUtils.isEmpty(passwordEdt.getText().toString())) { // this method will call when email and password fields are empty. Toast.makeText(MainActivity.this, "Please Enter Email and Password", Toast.LENGTH_SHORT).show(); } else { SharedPreferences.Editor editor = sharedpreferences.edit(); // below two lines will put values for // email and password in shared preferences. editor.putString(EMAIL_KEY, emailEdt.getText().toString()); editor.putString(PASSWORD_KEY, passwordEdt.getText().toString()); // to save our data with key and value. editor.apply(); // starting new activity. Intent i = new Intent(MainActivity.this, HomeActivity.class); startActivity(i); finish(); } } }); } @Override protected void onStart() { super.onStart(); if (email != null && password != null) { Intent i = new Intent(MainActivity.this, HomeActivity.class); startActivity(i); } }}
Step 6: Now we will work on our Home Screen
Inside our home screen, we will be displaying users’ email address and a logout button so that users can Logout of the app. For Home Screen, we have created an activity named as HomeActivity. Navigate to the app > res > layout > activity_home.xml and open it and add the below code to it.
Java
<?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" tools:context=".HomeActivity"> <!--Textview for displaying user's email address--> <TextView android:id="@+id/idTVWelcome" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerInParent="true" android:padding="5dp" android:textAlignment="center" android:textSize="20sp" /> <!--button for logging out of the app--> <Button android:id="@+id/idBtnLogout" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/idTVWelcome" android:layout_marginStart="20dp" android:layout_marginTop="20dp" android:layout_marginEnd="20dp" android:text="@string/logout" /> </RelativeLayout>
Now we will move towards the java file of our HomeActivity. Navigate to the app > java > your app’s package name and open the HomeActivity.java file. Add below code inside that file.
Java
import android.content.Context;import android.content.Intent;import android.content.SharedPreferences;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.TextView;import androidx.appcompat.app.AppCompatActivity; public class HomeActivity extends AppCompatActivity { // creating constant keys for shared preferences. public static final String SHARED_PREFS = "shared_prefs"; // key for storing email. public static final String EMAIL_KEY = "email_key"; // key for storing password. public static final String PASSWORD_KEY = "password_key"; // variable for shared preferences. SharedPreferences sharedpreferences; String email; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_home); // initializing our shared preferences. sharedpreferences = getSharedPreferences(SHARED_PREFS, Context.MODE_PRIVATE); // getting data from shared prefs and // storing it in our string variable. email = sharedpreferences.getString(EMAIL_KEY, null); // initializing our textview and button. TextView welcomeTV = findViewById(R.id.idTVWelcome); welcomeTV.setText("Welcome \n" + email); Button logoutBtn = findViewById(R.id.idBtnLogout); logoutBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // calling method to edit values in shared prefs. SharedPreferences.Editor editor = sharedpreferences.edit(); // below line will clear // the data in shared prefs. editor.clear(); // below line will apply empty // data to shared prefs. editor.apply(); // starting mainactivity after // clearing values in shared preferences. Intent i = new Intent(HomeActivity.this, MainActivity.class); startActivity(i); finish(); } }); }}
Check out the GitHub link: https://github.com/ChaitanyaMunje/SessionManagementAndroid
Android-Misc
Picked
Technical Scripter 2020
Android
Java
Technical Scripter
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Add Views Dynamically and Store Data in Arraylist in Android?
Android SDK and it's Components
Flutter - Custom Bottom Navigation Bar
How to Communicate Between Fragments in Android?
Retrofit with Kotlin Coroutine in Android
Arrays in Java
Arrays.sort() in Java with examples
Split() String method in Java with examples
Reverse a string in Java
Object Oriented Programming (OOPs) Concept in Java | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 Feb, 2021"
},
{
"code": null,
"e": 1005,
"s": 28,
"text": "Session Management is one of the most important features that are to be used in the Android App when you are integrating the login feature in Android. In your android app if you are using a feature of Login then you should have to save the state if the user has signed the first time. Then when the user closes his app and reopens it then he should redirect to our Home screen, rather than opening a login screen. So in this article, we will implement Session Management functionality in our Android app. For implementing this functionality we are creating a simple login form and a home screen. In our login form, the user has to enter his credentials and login into the app. After login, the user’s credentials will be saved inside the app, and whenever he reopens the app the user will be redirected to the home screen. For session management inside our app, we will be using Shared Preferences to store users’ credentials. Now we will move towards the implementation part."
},
{
"code": null,
"e": 1251,
"s": 1005,
"text": "We will be creating a simple Login app as mentioned above for storing user session. A sample GIF is given below in which we will get to see what we will be building in our app. Note that we will be implementing this project using Java language. "
},
{
"code": null,
"e": 1280,
"s": 1251,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 1443,
"s": 1280,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. "
},
{
"code": null,
"e": 1498,
"s": 1443,
"text": "Step 2: Add the below strings in your strings.xml file"
},
{
"code": null,
"e": 1581,
"s": 1498,
"text": "Navigate to the app > res > values > strings.xml and add the below strings to it. "
},
{
"code": null,
"e": 1585,
"s": 1581,
"text": "XML"
},
{
"code": "<resources> <!--app name--> <string name=\"app_name\">Session Management</string> <!--string for login button--> <string name=\"login\">Login</string> <!--string for edittext hint in password--> <string name=\"enter_password\">Enter password</string> <!--string for edittext hint in email--> <string name=\"enter_youe_email\">Enter your Email</string> <!--string for logout button--> <string name=\"logout\">Logout</string></resources>",
"e": 2041,
"s": 1585,
"text": null
},
{
"code": null,
"e": 2089,
"s": 2041,
"text": "Step 3: Working with the activity_main.xml file"
},
{
"code": null,
"e": 2205,
"s": 2089,
"text": "Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file."
},
{
"code": null,
"e": 2209,
"s": 2205,
"text": "XML"
},
{
"code": "<?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\" tools:context=\".MainActivity\"> <!--EditText for getting user email address--> <!--input type is set to email--> <EditText android:id=\"@+id/idEdtEmail\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"10dp\" android:layout_marginTop=\"50dp\" android:layout_marginEnd=\"10dp\" android:hint=\"@string/enter_youe_email\" android:importantForAutofill=\"no\" android:inputType=\"textEmailAddress\" /> <!--EditText for getting user password--> <!--input type is set to password--> <EditText android:id=\"@+id/idEdtPassword\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/idEdtEmail\" android:layout_marginStart=\"10dp\" android:layout_marginTop=\"30dp\" android:layout_marginEnd=\"10dp\" android:hint=\"@string/enter_password\" android:importantForAutofill=\"no\" android:inputType=\"textPassword\" /> <!--button to continue to login--> <Button android:id=\"@+id/idBtnLogin\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/idEdtPassword\" android:layout_marginStart=\"10dp\" android:layout_marginTop=\"30dp\" android:layout_marginEnd=\"10dp\" android:text=\"@string/login\" /> </RelativeLayout>",
"e": 3888,
"s": 2209,
"text": null
},
{
"code": null,
"e": 3935,
"s": 3888,
"text": "Step 4: Create a new Activity for Home Screen "
},
{
"code": null,
"e": 4140,
"s": 3935,
"text": "Navigate to the app > java > your app’s package name > Right-Click on your package name and New > Activity > Empty Activity and make sure to keep your language as Java. Name the activity as HomeActivity. "
},
{
"code": null,
"e": 4188,
"s": 4140,
"text": "Step 5: Working with the MainActivity.java file"
},
{
"code": null,
"e": 4378,
"s": 4188,
"text": "Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 4383,
"s": 4378,
"text": "Java"
},
{
"code": "import android.content.Context;import android.content.Intent;import android.content.SharedPreferences;import android.os.Bundle;import android.text.TextUtils;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.Toast;import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { // creating constant keys for shared preferences. public static final String SHARED_PREFS = \"shared_prefs\"; // key for storing email. public static final String EMAIL_KEY = \"email_key\"; // key for storing password. public static final String PASSWORD_KEY = \"password_key\"; // variable for shared preferences. SharedPreferences sharedpreferences; String email, password; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Initializing EditTexts and our Button EditText emailEdt = findViewById(R.id.idEdtEmail); EditText passwordEdt = findViewById(R.id.idEdtPassword); Button loginBtn = findViewById(R.id.idBtnLogin); // getting the data which is stored in shared preferences. sharedpreferences = getSharedPreferences(SHARED_PREFS, Context.MODE_PRIVATE); // in shared prefs inside het string method // we are passing key value as EMAIL_KEY and // default value is // set to null if not present. email = sharedpreferences.getString(EMAIL_KEY, null); password = sharedpreferences.getString(PASSWORD_KEY, null); // calling on click listener for login button. loginBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // to check if the user fields are empty or not. if (TextUtils.isEmpty(emailEdt.getText().toString()) && TextUtils.isEmpty(passwordEdt.getText().toString())) { // this method will call when email and password fields are empty. Toast.makeText(MainActivity.this, \"Please Enter Email and Password\", Toast.LENGTH_SHORT).show(); } else { SharedPreferences.Editor editor = sharedpreferences.edit(); // below two lines will put values for // email and password in shared preferences. editor.putString(EMAIL_KEY, emailEdt.getText().toString()); editor.putString(PASSWORD_KEY, passwordEdt.getText().toString()); // to save our data with key and value. editor.apply(); // starting new activity. Intent i = new Intent(MainActivity.this, HomeActivity.class); startActivity(i); finish(); } } }); } @Override protected void onStart() { super.onStart(); if (email != null && password != null) { Intent i = new Intent(MainActivity.this, HomeActivity.class); startActivity(i); } }}",
"e": 7627,
"s": 4383,
"text": null
},
{
"code": null,
"e": 7671,
"s": 7627,
"text": "Step 6: Now we will work on our Home Screen"
},
{
"code": null,
"e": 7961,
"s": 7671,
"text": "Inside our home screen, we will be displaying users’ email address and a logout button so that users can Logout of the app. For Home Screen, we have created an activity named as HomeActivity. Navigate to the app > res > layout > activity_home.xml and open it and add the below code to it. "
},
{
"code": null,
"e": 7966,
"s": 7961,
"text": "Java"
},
{
"code": "<?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\" tools:context=\".HomeActivity\"> <!--Textview for displaying user's email address--> <TextView android:id=\"@+id/idTVWelcome\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_centerInParent=\"true\" android:padding=\"5dp\" android:textAlignment=\"center\" android:textSize=\"20sp\" /> <!--button for logging out of the app--> <Button android:id=\"@+id/idBtnLogout\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/idTVWelcome\" android:layout_marginStart=\"20dp\" android:layout_marginTop=\"20dp\" android:layout_marginEnd=\"20dp\" android:text=\"@string/logout\" /> </RelativeLayout>",
"e": 8997,
"s": 7966,
"text": null
},
{
"code": null,
"e": 9181,
"s": 8997,
"text": "Now we will move towards the java file of our HomeActivity. Navigate to the app > java > your app’s package name and open the HomeActivity.java file. Add below code inside that file. "
},
{
"code": null,
"e": 9186,
"s": 9181,
"text": "Java"
},
{
"code": "import android.content.Context;import android.content.Intent;import android.content.SharedPreferences;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.TextView;import androidx.appcompat.app.AppCompatActivity; public class HomeActivity extends AppCompatActivity { // creating constant keys for shared preferences. public static final String SHARED_PREFS = \"shared_prefs\"; // key for storing email. public static final String EMAIL_KEY = \"email_key\"; // key for storing password. public static final String PASSWORD_KEY = \"password_key\"; // variable for shared preferences. SharedPreferences sharedpreferences; String email; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_home); // initializing our shared preferences. sharedpreferences = getSharedPreferences(SHARED_PREFS, Context.MODE_PRIVATE); // getting data from shared prefs and // storing it in our string variable. email = sharedpreferences.getString(EMAIL_KEY, null); // initializing our textview and button. TextView welcomeTV = findViewById(R.id.idTVWelcome); welcomeTV.setText(\"Welcome \\n\" + email); Button logoutBtn = findViewById(R.id.idBtnLogout); logoutBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // calling method to edit values in shared prefs. SharedPreferences.Editor editor = sharedpreferences.edit(); // below line will clear // the data in shared prefs. editor.clear(); // below line will apply empty // data to shared prefs. editor.apply(); // starting mainactivity after // clearing values in shared preferences. Intent i = new Intent(HomeActivity.this, MainActivity.class); startActivity(i); finish(); } }); }}",
"e": 11438,
"s": 9186,
"text": null
},
{
"code": null,
"e": 11524,
"s": 11438,
"text": "Check out the GitHub link: https://github.com/ChaitanyaMunje/SessionManagementAndroid"
},
{
"code": null,
"e": 11537,
"s": 11524,
"text": "Android-Misc"
},
{
"code": null,
"e": 11544,
"s": 11537,
"text": "Picked"
},
{
"code": null,
"e": 11568,
"s": 11544,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 11576,
"s": 11568,
"text": "Android"
},
{
"code": null,
"e": 11581,
"s": 11576,
"text": "Java"
},
{
"code": null,
"e": 11600,
"s": 11581,
"text": "Technical Scripter"
},
{
"code": null,
"e": 11605,
"s": 11600,
"text": "Java"
},
{
"code": null,
"e": 11613,
"s": 11605,
"text": "Android"
},
{
"code": null,
"e": 11711,
"s": 11613,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 11780,
"s": 11711,
"text": "How to Add Views Dynamically and Store Data in Arraylist in Android?"
},
{
"code": null,
"e": 11812,
"s": 11780,
"text": "Android SDK and it's Components"
},
{
"code": null,
"e": 11851,
"s": 11812,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 11900,
"s": 11851,
"text": "How to Communicate Between Fragments in Android?"
},
{
"code": null,
"e": 11942,
"s": 11900,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 11957,
"s": 11942,
"text": "Arrays in Java"
},
{
"code": null,
"e": 11993,
"s": 11957,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 12037,
"s": 11993,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 12062,
"s": 12037,
"text": "Reverse a string in Java"
}
] |
Subsets and Splits