title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
|---|---|---|
Python MongoDB - Delete Document
|
You can delete documents in a collection using the remove() method of MongoDB. This method accepts two optional parameters −
deletion criteria specifying the condition to delete documents.
deletion criteria specifying the condition to delete documents.
just one, if you pass true or 1 as second parameter, then only one document will be deleted.
just one, if you pass true or 1 as second parameter, then only one document will be deleted.
Following is the syntax of the remove() method −
>db.COLLECTION_NAME.remove(DELLETION_CRITTERIA)
Assume we have created a collection and inserted 5 documents into it as shown below −
> use testDB
switched to db testDB
> db.createCollection("myColl")
{ "ok" : 1 }
> data = [
... {"_id": "1001", "name": "Ram", "age": "26", "city": "Hyderabad"},
... {"_id": "1002", "name": "Rahim", "age": 27, "city": "Bangalore"},
... {"_id": "1003", "name": "Robert", "age": 28, "city": "Mumbai"},
... {"_id": "1004", "name": "Romeo", "age": 25, "city": "Pune"},
... {"_id": "1005", "name": "Sarmista", "age": 23, "city": "Delhi"},
... {"_id": "1006", "name": "Rasajna", "age": 26, "city": "Chennai"}
]
> db.sample.insert(data)
BulkWriteResult({
"writeErrors" : [ ],
"writeConcernErrors" : [ ],
"nInserted" : 6,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
})
Following query deletes the document(s) of the collection which have name value as Sarmista.
> db.sample.remove({"name": "Sarmista"})
WriteResult({ "nRemoved" : 1 })
> db.sample.find()
{ "_id" : "1001", "name" : "Ram", "age" : "26", "city" : "Hyderabad" }
{ "_id" : "1002", "name" : "Rahim", "age" : 27, "city" : "Bangalore" }
{ "_id" : "1003", "name" : "Robert", "age" : 28, "city" : "Mumbai" }
{ "_id" : "1004", "name" : "Romeo", "age" : 25, "city" : "Pune" }
{ "_id" : "1006", "name" : "Rasajna", "age" : 26, "city" : "Chennai" }
If you invoke remove() method without passing deletion criteria, all the documents in the collection will be deleted.
> db.sample.remove({})
WriteResult({ "nRemoved" : 5 })
> db.sample.find()
To delete documents from a collection of MangoDB, you can delete documents from a collections using the methods delete_one() and delete_many() methods.
These methods accept a query object specifying the condition for deleting documents.
The detele_one() method deletes a single document, in case of a match. If no query is specified this method deletes the first document in the collection.
Following python example deletes the document in the collection which has id value as 1006.
from pymongo import MongoClient
#Creating a pymongo client
client = MongoClient('localhost', 27017)
#Getting the database instance
db = client['lpaksgf']
#Creating a collection
coll = db['example']
#Inserting document into a collection
data = [
{"_id": "1001", "name": "Ram", "age": "26", "city": "Hyderabad"},
{"_id": "1002", "name": "Rahim", "age": "27", "city": "Bangalore"},
{"_id": "1003", "name": "Robert", "age": "28", "city": "Mumbai"},
{"_id": "1004", "name": "Romeo", "age": 25, "city": "Pune"},
{"_id": "1005", "name": "Sarmista", "age": 23, "city": "Delhi"},
{"_id": "1006", "name": "Rasajna", "age": 26, "city": "Chennai"}
]
res = coll.insert_many(data)
print("Data inserted ......")
#Deleting one document
coll.delete_one({"_id" : "1006"})
#Retrieving all the records using the find() method
print("Documents in the collection after update operation: ")
for doc2 in coll.find():
print(doc2)
Data inserted ......
Documents in the collection after update operation:
{'_id': '1001', 'name': 'Ram', 'age': '26', 'city': 'Hyderabad'}
{'_id': '1002', 'name': 'Rahim', 'age': '27', 'city': 'Bangalore'}
{'_id': '1003', 'name': 'Robert', 'age': '28', 'city': 'Mumbai'}
{'_id': '1004', 'name': 'Romeo', 'age': 25, 'city': 'Pune'}
{'_id': '1005', 'name': 'Sarmista', 'age': 23, 'city': 'Delhi'}
Similarly, the delete_many() method of pymongo deletes all the documents that satisfies the specified condition.
Following example deletes all the documents in the collection whose age value is greater than 26 −
from pymongo import MongoClient
#Creating a pymongo client
client = MongoClient('localhost', 27017)
#Getting the database instance
db = client['sampleDB']
#Creating a collection
coll = db['example']
#Inserting document into a collection
data = [
{"_id": "1001", "name": "Ram", "age": "26", "city": "Hyderabad"},
{"_id": "1002", "name": "Rahim", "age": "27", "city": "Bangalore"},
{"_id": "1003", "name": "Robert", "age": "28", "city": "Mumbai"},
{"_id": "1004", "name": "Romeo", "age": "25", "city": "Pune"},
{"_id": "1005", "name": "Sarmista", "age": "23", "city": "Delhi"},
{"_id": "1006", "name": "Rasajna", "age": "26", "city": "Chennai"}
]
res = coll.insert_many(data)
print("Data inserted ......")
#Deleting multiple documents
coll.delete_many({"age":{"$gt":"26"}})
#Retrieving all the records using the find() method
print("Documents in the collection after update operation: ")
for doc2 in coll.find():
print(doc2)
Data inserted ......
Documents in the collection after update operation:
{'_id': '1001', 'name': 'Ram', 'age': '26', 'city': 'Hyderabad'}
{'_id': '1004', 'name': 'Romeo', 'age': '25', 'city': 'Pune'}
{'_id': '1005', 'name': 'Sarmista', 'age': '23', 'city': 'Delhi'}
{'_id': '1006', 'name': 'Rasajna', 'age': '26', 'city': 'Chennai'}
If you invoke the delete_many() method without passing any query, this method deletes all the documents in the collection.
coll.delete_many({})
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": 3330,
"s": 3205,
"text": "You can delete documents in a collection using the remove() method of MongoDB. This method accepts two optional parameters −"
},
{
"code": null,
"e": 3394,
"s": 3330,
"text": "deletion criteria specifying the condition to delete documents."
},
{
"code": null,
"e": 3458,
"s": 3394,
"text": "deletion criteria specifying the condition to delete documents."
},
{
"code": null,
"e": 3551,
"s": 3458,
"text": "just one, if you pass true or 1 as second parameter, then only one document will be deleted."
},
{
"code": null,
"e": 3644,
"s": 3551,
"text": "just one, if you pass true or 1 as second parameter, then only one document will be deleted."
},
{
"code": null,
"e": 3693,
"s": 3644,
"text": "Following is the syntax of the remove() method −"
},
{
"code": null,
"e": 3742,
"s": 3693,
"text": ">db.COLLECTION_NAME.remove(DELLETION_CRITTERIA)\n"
},
{
"code": null,
"e": 3828,
"s": 3742,
"text": "Assume we have created a collection and inserted 5 documents into it as shown below −"
},
{
"code": null,
"e": 4569,
"s": 3828,
"text": "> use testDB\nswitched to db testDB\n> db.createCollection(\"myColl\")\n{ \"ok\" : 1 }\n> data = [\n ... {\"_id\": \"1001\", \"name\": \"Ram\", \"age\": \"26\", \"city\": \"Hyderabad\"},\n ... {\"_id\": \"1002\", \"name\": \"Rahim\", \"age\": 27, \"city\": \"Bangalore\"},\n ... {\"_id\": \"1003\", \"name\": \"Robert\", \"age\": 28, \"city\": \"Mumbai\"},\n ... {\"_id\": \"1004\", \"name\": \"Romeo\", \"age\": 25, \"city\": \"Pune\"},\n ... {\"_id\": \"1005\", \"name\": \"Sarmista\", \"age\": 23, \"city\": \"Delhi\"},\n ... {\"_id\": \"1006\", \"name\": \"Rasajna\", \"age\": 26, \"city\": \"Chennai\"}\n]\n> db.sample.insert(data)\nBulkWriteResult({\n \"writeErrors\" : [ ],\n \"writeConcernErrors\" : [ ],\n \"nInserted\" : 6,\n \"nUpserted\" : 0,\n \"nMatched\" : 0,\n \"nModified\" : 0,\n \"nRemoved\" : 0,\n \"upserted\" : [ ]\n})"
},
{
"code": null,
"e": 4662,
"s": 4569,
"text": "Following query deletes the document(s) of the collection which have name value as Sarmista."
},
{
"code": null,
"e": 5103,
"s": 4662,
"text": "> db.sample.remove({\"name\": \"Sarmista\"})\nWriteResult({ \"nRemoved\" : 1 })\n> db.sample.find()\n{ \"_id\" : \"1001\", \"name\" : \"Ram\", \"age\" : \"26\", \"city\" : \"Hyderabad\" }\n{ \"_id\" : \"1002\", \"name\" : \"Rahim\", \"age\" : 27, \"city\" : \"Bangalore\" }\n{ \"_id\" : \"1003\", \"name\" : \"Robert\", \"age\" : 28, \"city\" : \"Mumbai\" }\n{ \"_id\" : \"1004\", \"name\" : \"Romeo\", \"age\" : 25, \"city\" : \"Pune\" }\n{ \"_id\" : \"1006\", \"name\" : \"Rasajna\", \"age\" : 26, \"city\" : \"Chennai\" }\n"
},
{
"code": null,
"e": 5221,
"s": 5103,
"text": "If you invoke remove() method without passing deletion criteria, all the documents in the collection will be deleted."
},
{
"code": null,
"e": 5296,
"s": 5221,
"text": "> db.sample.remove({})\nWriteResult({ \"nRemoved\" : 5 })\n> db.sample.find()\n"
},
{
"code": null,
"e": 5448,
"s": 5296,
"text": "To delete documents from a collection of MangoDB, you can delete documents from a collections using the methods delete_one() and delete_many() methods."
},
{
"code": null,
"e": 5533,
"s": 5448,
"text": "These methods accept a query object specifying the condition for deleting documents."
},
{
"code": null,
"e": 5687,
"s": 5533,
"text": "The detele_one() method deletes a single document, in case of a match. If no query is specified this method deletes the first document in the collection."
},
{
"code": null,
"e": 5779,
"s": 5687,
"text": "Following python example deletes the document in the collection which has id value as 1006."
},
{
"code": null,
"e": 6712,
"s": 5779,
"text": "from pymongo import MongoClient\n\n#Creating a pymongo client\nclient = MongoClient('localhost', 27017)\n\n#Getting the database instance\ndb = client['lpaksgf']\n\n#Creating a collection\ncoll = db['example']\n\n#Inserting document into a collection\ndata = [\n {\"_id\": \"1001\", \"name\": \"Ram\", \"age\": \"26\", \"city\": \"Hyderabad\"},\n {\"_id\": \"1002\", \"name\": \"Rahim\", \"age\": \"27\", \"city\": \"Bangalore\"},\n {\"_id\": \"1003\", \"name\": \"Robert\", \"age\": \"28\", \"city\": \"Mumbai\"},\n {\"_id\": \"1004\", \"name\": \"Romeo\", \"age\": 25, \"city\": \"Pune\"},\n {\"_id\": \"1005\", \"name\": \"Sarmista\", \"age\": 23, \"city\": \"Delhi\"},\n {\"_id\": \"1006\", \"name\": \"Rasajna\", \"age\": 26, \"city\": \"Chennai\"}\n]\nres = coll.insert_many(data)\nprint(\"Data inserted ......\")\n\n#Deleting one document\ncoll.delete_one({\"_id\" : \"1006\"})\n\n#Retrieving all the records using the find() method\nprint(\"Documents in the collection after update operation: \")\n\nfor doc2 in coll.find():\n print(doc2)"
},
{
"code": null,
"e": 7107,
"s": 6712,
"text": "Data inserted ......\nDocuments in the collection after update operation:\n{'_id': '1001', 'name': 'Ram', 'age': '26', 'city': 'Hyderabad'}\n{'_id': '1002', 'name': 'Rahim', 'age': '27', 'city': 'Bangalore'}\n{'_id': '1003', 'name': 'Robert', 'age': '28', 'city': 'Mumbai'}\n{'_id': '1004', 'name': 'Romeo', 'age': 25, 'city': 'Pune'}\n{'_id': '1005', 'name': 'Sarmista', 'age': 23, 'city': 'Delhi'}\n"
},
{
"code": null,
"e": 7220,
"s": 7107,
"text": "Similarly, the delete_many() method of pymongo deletes all the documents that satisfies the specified condition."
},
{
"code": null,
"e": 7319,
"s": 7220,
"text": "Following example deletes all the documents in the collection whose age value is greater than 26 −"
},
{
"code": null,
"e": 8270,
"s": 7319,
"text": "from pymongo import MongoClient\n\n#Creating a pymongo client\nclient = MongoClient('localhost', 27017)\n\n#Getting the database instance\ndb = client['sampleDB']\n\n#Creating a collection\ncoll = db['example']\n\n#Inserting document into a collection\ndata = [\n {\"_id\": \"1001\", \"name\": \"Ram\", \"age\": \"26\", \"city\": \"Hyderabad\"},\n {\"_id\": \"1002\", \"name\": \"Rahim\", \"age\": \"27\", \"city\": \"Bangalore\"},\n {\"_id\": \"1003\", \"name\": \"Robert\", \"age\": \"28\", \"city\": \"Mumbai\"},\n {\"_id\": \"1004\", \"name\": \"Romeo\", \"age\": \"25\", \"city\": \"Pune\"},\n {\"_id\": \"1005\", \"name\": \"Sarmista\", \"age\": \"23\", \"city\": \"Delhi\"},\n {\"_id\": \"1006\", \"name\": \"Rasajna\", \"age\": \"26\", \"city\": \"Chennai\"}\n]\nres = coll.insert_many(data)\nprint(\"Data inserted ......\")\n\n#Deleting multiple documents\ncoll.delete_many({\"age\":{\"$gt\":\"26\"}})\n\n#Retrieving all the records using the find() method\nprint(\"Documents in the collection after update operation: \")\n\nfor doc2 in coll.find():\n print(doc2)"
},
{
"code": null,
"e": 8604,
"s": 8270,
"text": "Data inserted ......\nDocuments in the collection after update operation:\n{'_id': '1001', 'name': 'Ram', 'age': '26', 'city': 'Hyderabad'}\n{'_id': '1004', 'name': 'Romeo', 'age': '25', 'city': 'Pune'}\n{'_id': '1005', 'name': 'Sarmista', 'age': '23', 'city': 'Delhi'}\n{'_id': '1006', 'name': 'Rasajna', 'age': '26', 'city': 'Chennai'}\n"
},
{
"code": null,
"e": 8727,
"s": 8604,
"text": "If you invoke the delete_many() method without passing any query, this method deletes all the documents in the collection."
},
{
"code": null,
"e": 8749,
"s": 8727,
"text": "coll.delete_many({})\n"
},
{
"code": null,
"e": 8786,
"s": 8749,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 8802,
"s": 8786,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 8835,
"s": 8802,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 8854,
"s": 8835,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 8889,
"s": 8854,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 8911,
"s": 8889,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 8945,
"s": 8911,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 8973,
"s": 8945,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 9008,
"s": 8973,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 9022,
"s": 9008,
"text": " Lets Kode It"
},
{
"code": null,
"e": 9055,
"s": 9022,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 9072,
"s": 9055,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 9079,
"s": 9072,
"text": " Print"
},
{
"code": null,
"e": 9090,
"s": 9079,
"text": " Add Notes"
}
] |
Displaying content of a HashMap in Java
|
Let us first create a HashMap and add elements −
HashMap hm = new HashMap();
hm.put("Wallet", new Integer(700));
hm.put("Belt", new Integer(600));
To display the content, just print the HashMap object −
System.out.println("Map = "+hm);
The following is an example to display content of a HashMap −
Live Demo
import java.util.*;
public class Demo {
public static void main(String args[]) {
// Create hash map
HashMap hm = new HashMap();
hm.put("Wallet", new Integer(700));
hm.put("Belt", new Integer(600));
System.out.println("Map = "+hm);
}
}
Map = {Belt=600, Wallet=700}
|
[
{
"code": null,
"e": 1111,
"s": 1062,
"text": "Let us first create a HashMap and add elements −"
},
{
"code": null,
"e": 1209,
"s": 1111,
"text": "HashMap hm = new HashMap();\nhm.put(\"Wallet\", new Integer(700));\nhm.put(\"Belt\", new Integer(600));"
},
{
"code": null,
"e": 1265,
"s": 1209,
"text": "To display the content, just print the HashMap object −"
},
{
"code": null,
"e": 1298,
"s": 1265,
"text": "System.out.println(\"Map = \"+hm);"
},
{
"code": null,
"e": 1360,
"s": 1298,
"text": "The following is an example to display content of a HashMap −"
},
{
"code": null,
"e": 1371,
"s": 1360,
"text": " Live Demo"
},
{
"code": null,
"e": 1642,
"s": 1371,
"text": "import java.util.*;\npublic class Demo {\n public static void main(String args[]) {\n // Create hash map\n HashMap hm = new HashMap();\n hm.put(\"Wallet\", new Integer(700));\n hm.put(\"Belt\", new Integer(600));\n System.out.println(\"Map = \"+hm);\n }\n}"
},
{
"code": null,
"e": 1671,
"s": 1642,
"text": "Map = {Belt=600, Wallet=700}"
}
] |
C# Regex. Matches Method
|
The method matches instances of a pattern and is used to extract value based on a pattern.
Let us see hoe to check for a valid URL.
For that, pass the regex expression in the Matches method.
MatchCollection mc = Regex.Matches(text, expr);
Above, the expr is our expression that we have set to check for valid URL.
"^(http|http(s)?://)?([\w-]+\.)+[\w-]+[.com|.in|.org]+(\[\?%&=]*)?”
The text we have set to check is a URL i.e.
https://demo.com
Let us see the complete code.
Live Demo
using System;
using System.Text.RegularExpressions;
namespace Demo {
class Program {
private static void showMatch(string text, string expr) {
MatchCollection mc = Regex.Matches(text, expr);
foreach (Match m in mc) {
Console.WriteLine(m);
}
}
static void Main(string[] args) {
string str = "https://demo.com";
Console.WriteLine("Matching URL...");
showMatch(str, @"^(http|http(s)?://)?([\w-]+\.)+[\w-]+[.com|.in|.org]+(\[\?%&=]*)?");
Console.ReadKey();
}
}
}
Matching URL...
https://demo.com
|
[
{
"code": null,
"e": 1153,
"s": 1062,
"text": "The method matches instances of a pattern and is used to extract value based on a pattern."
},
{
"code": null,
"e": 1194,
"s": 1153,
"text": "Let us see hoe to check for a valid URL."
},
{
"code": null,
"e": 1253,
"s": 1194,
"text": "For that, pass the regex expression in the Matches method."
},
{
"code": null,
"e": 1301,
"s": 1253,
"text": "MatchCollection mc = Regex.Matches(text, expr);"
},
{
"code": null,
"e": 1376,
"s": 1301,
"text": "Above, the expr is our expression that we have set to check for valid URL."
},
{
"code": null,
"e": 1444,
"s": 1376,
"text": "\"^(http|http(s)?://)?([\\w-]+\\.)+[\\w-]+[.com|.in|.org]+(\\[\\?%&=]*)?”"
},
{
"code": null,
"e": 1488,
"s": 1444,
"text": "The text we have set to check is a URL i.e."
},
{
"code": null,
"e": 1505,
"s": 1488,
"text": "https://demo.com"
},
{
"code": null,
"e": 1535,
"s": 1505,
"text": "Let us see the complete code."
},
{
"code": null,
"e": 1546,
"s": 1535,
"text": " Live Demo"
},
{
"code": null,
"e": 2110,
"s": 1546,
"text": "using System;\nusing System.Text.RegularExpressions;\nnamespace Demo {\n class Program {\n private static void showMatch(string text, string expr) {\n MatchCollection mc = Regex.Matches(text, expr);\n foreach (Match m in mc) {\n Console.WriteLine(m);\n }\n }\n static void Main(string[] args) {\n string str = \"https://demo.com\";\n Console.WriteLine(\"Matching URL...\");\n showMatch(str, @\"^(http|http(s)?://)?([\\w-]+\\.)+[\\w-]+[.com|.in|.org]+(\\[\\?%&=]*)?\");\n Console.ReadKey();\n }\n }\n}"
},
{
"code": null,
"e": 2143,
"s": 2110,
"text": "Matching URL...\nhttps://demo.com"
}
] |
How to insert current date and time in a database using JDBC?
|
The time stamp dataType in MySQL database stores day, month, year, hour, minute, second, fractional seconds. Using this you can represent date and time at once.
There are two ways to insert/get current time stamp values while working with JDBC.
Using the database default value for a date.
Using the database default value for a date.
Using the getTime() method of the calendar class.
Using the getTime() method of the calendar class.
Create a table named sample to store time stamps in MySQL database using the following query:
CREATE TABLE Sample(Id INT, Current_Time_Stamp TimeStamp);
Now describe the table as shown below:
+--------------------+-----------+------+-----+-------------------+
| Field | Type | Null | Key | Default |
+--------------------+-----------+------+-----+-------------------+
| Id | int(11) | YES | | NULL |
| Current_Time_Stamp | timestamp | NO | | CURRENT_TIMESTAMP |
+--------------------+-----------+------+-----+-------------------+
If you observe, the default value of the time stamp is current timestamp of the system. i.e. if you do not pass any value to this column by default it is filled with the current timestamp value.
Therefore, while inserting value into a table which has time stamp using JDBC program, in the Prepared statement leave the column of time stamp or, simply use CURRENT_TIMESTAMP instead of the place holder ? this will be filled with the current timestamp value.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class InsertingCurrentTime {
public static void main(String args[])throws Exception {
//Getting the connection
String mysqlUrl = "jdbc:mysql://localhost/sampleDB";
Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
System.out.println("Connection established......");
//Inserting values to a table
String query = "INSERT INTO sample(ID, Current_Time_Stamp)
VALUES (?, CURRENT_TIMESTAMP)";
PreparedStatement pstmt = con.prepareStatement(query);
pstmt.setInt(1, 1);
pstmt.execute();
System.out.println("Data inserted......");
}
}
Data inserted......
If you observe the contents of the table you can see it with the current time stamp value as:
+------+---------------------+
| Id | Current_Time_Stamp |
+------+---------------------+
| 1 | 2019-02-27 17:18:17 |
+------+---------------------+
The getTime() method of the Calendar class returns an Object of the Date class which holds the current time value of the calendar.
Calendar calendar = Calendar.getInstance();
java.util.Date currentTime = calendar.getTime();
The java.util.Date class also provides a method named getTime() this method returns a variable of type long which represents the number of milliseconds from the standard epoch time (since January 1, 1970, 00:00:00 GMT) to the current time value of this object.
long time = currentTime.getTime();
Now, pass this obtained current time value to the setTimedtamp() method as one parameter where, the other one will be an integer representing the parameter index of the place holder ? to which you need to set the current timestamp value.
pstmt.setTimestamp(2, new Timestamp(time));
|
[
{
"code": null,
"e": 1223,
"s": 1062,
"text": "The time stamp dataType in MySQL database stores day, month, year, hour, minute, second, fractional seconds. Using this you can represent date and time at once."
},
{
"code": null,
"e": 1307,
"s": 1223,
"text": "There are two ways to insert/get current time stamp values while working with JDBC."
},
{
"code": null,
"e": 1352,
"s": 1307,
"text": "Using the database default value for a date."
},
{
"code": null,
"e": 1397,
"s": 1352,
"text": "Using the database default value for a date."
},
{
"code": null,
"e": 1447,
"s": 1397,
"text": "Using the getTime() method of the calendar class."
},
{
"code": null,
"e": 1497,
"s": 1447,
"text": "Using the getTime() method of the calendar class."
},
{
"code": null,
"e": 1591,
"s": 1497,
"text": "Create a table named sample to store time stamps in MySQL database using the following query:"
},
{
"code": null,
"e": 1650,
"s": 1591,
"text": "CREATE TABLE Sample(Id INT, Current_Time_Stamp TimeStamp);"
},
{
"code": null,
"e": 1689,
"s": 1650,
"text": "Now describe the table as shown below:"
},
{
"code": null,
"e": 2097,
"s": 1689,
"text": "+--------------------+-----------+------+-----+-------------------+\n| Field | Type | Null | Key | Default |\n+--------------------+-----------+------+-----+-------------------+\n| Id | int(11) | YES | | NULL |\n| Current_Time_Stamp | timestamp | NO | | CURRENT_TIMESTAMP |\n+--------------------+-----------+------+-----+-------------------+"
},
{
"code": null,
"e": 2292,
"s": 2097,
"text": "If you observe, the default value of the time stamp is current timestamp of the system. i.e. if you do not pass any value to this column by default it is filled with the current timestamp value."
},
{
"code": null,
"e": 2553,
"s": 2292,
"text": "Therefore, while inserting value into a table which has time stamp using JDBC program, in the Prepared statement leave the column of time stamp or, simply use CURRENT_TIMESTAMP instead of the place holder ? this will be filled with the current timestamp value."
},
{
"code": null,
"e": 3280,
"s": 2553,
"text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.PreparedStatement;\npublic class InsertingCurrentTime {\n public static void main(String args[])throws Exception {\n //Getting the connection\n String mysqlUrl = \"jdbc:mysql://localhost/sampleDB\";\n Connection con = DriverManager.getConnection(mysqlUrl, \"root\", \"password\");\n System.out.println(\"Connection established......\");\n //Inserting values to a table\n\n String query = \"INSERT INTO sample(ID, Current_Time_Stamp)\n VALUES (?, CURRENT_TIMESTAMP)\";\n\n PreparedStatement pstmt = con.prepareStatement(query);\n pstmt.setInt(1, 1);\n pstmt.execute();\n System.out.println(\"Data inserted......\");\n }\n}"
},
{
"code": null,
"e": 3300,
"s": 3280,
"text": "Data inserted......"
},
{
"code": null,
"e": 3394,
"s": 3300,
"text": "If you observe the contents of the table you can see it with the current time stamp value as:"
},
{
"code": null,
"e": 3549,
"s": 3394,
"text": "+------+---------------------+\n| Id | Current_Time_Stamp |\n+------+---------------------+\n| 1 | 2019-02-27 17:18:17 |\n+------+---------------------+"
},
{
"code": null,
"e": 3680,
"s": 3549,
"text": "The getTime() method of the Calendar class returns an Object of the Date class which holds the current time value of the calendar."
},
{
"code": null,
"e": 3773,
"s": 3680,
"text": "Calendar calendar = Calendar.getInstance();\njava.util.Date currentTime = calendar.getTime();"
},
{
"code": null,
"e": 4034,
"s": 3773,
"text": "The java.util.Date class also provides a method named getTime() this method returns a variable of type long which represents the number of milliseconds from the standard epoch time (since January 1, 1970, 00:00:00 GMT) to the current time value of this object."
},
{
"code": null,
"e": 4069,
"s": 4034,
"text": "long time = currentTime.getTime();"
},
{
"code": null,
"e": 4307,
"s": 4069,
"text": "Now, pass this obtained current time value to the setTimedtamp() method as one parameter where, the other one will be an integer representing the parameter index of the place holder ? to which you need to set the current timestamp value."
},
{
"code": null,
"e": 4351,
"s": 4307,
"text": "pstmt.setTimestamp(2, new Timestamp(time));"
}
] |
How to create pagination in Bootstrap 4 ?
|
29 Nov, 2021
Bootstrap is a free and open-source tool collection for creating responsive websites and web applications. It is the most popular HTML, CSS, and JavaScript framework for developing responsive, mobile-first websites. It solves many problems which we had once, one of which is the cross-browser compatibility issue.
Pagination is an element used to indicate the actuality of a series of affiliated content across multiple runners and enables navigation across them.
Introduction to Pagination: We utilize an enormous square of associated joins for our pagination, making joins hard to miss and effectively adaptable—all while giving huge hit regions. Pagination is worked with a list of HTML components so screen per user can report the number of accessible connections. Utilize a wrapping <nav> component to distinguish it as a routing area to screen per user and other assistive advances.
Also, as pages probably have more than one such route area, it’s prudent to give a clear aria-name to the <nav>. For instance, if the pagination part is utilized to explore between a bunch of list items, a proper name could be aria-label=”Search results pages”.
Example:
HTML
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <style> .pagination { padding: 12rem 0 0 22rem; } .page-link { background-color: green; color: white; } </style></head> <body> <nav aria-label="navigation example"> <ul class="pagination border-success"> <li><a class="page-link" href="#">Previous</a></li> <li><a class="page-link" href="#">11</a></li> <li><a class="page-link" href="#">12</a></li> <li><a class="page-link" href="#">13</a></li> <li><a class="page-link" href="#">14</a></li> <li><a class="page-link" href="#">15</a></li> <li><a class="page-link" href="#">Next</a></li> </ul> </nav></body> </html>
Output:
Working with icons: Hoping to utilize a symbol or image instead of text for some pagination joins. Make certain to furnish legitimate screen per user support with aria ascribes and the .sr only
Example:
HTML
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <style> .pagination { padding: 12rem 0 0 22rem; } .page-link { background-color: green; color: white; } </style></head> <body> <nav aria-label="Page navigation"> <ul class="pagination"> <li class="page-item"> <a class="page-link" href="#" aria-label="Previous"> <span aria-hidden="true">«</span> <span class="sr-only">Previous</span> </a> </li> <li><a class="page-link" href="#">11</a></li> <li><a class="page-link" href="#">12</a></li> <li><a class="page-link" href="#">13</a></li> <li><a class="page-link" href="#">14</a></li> <li><a class="page-link" href="#">15</a></li> <li> <a class="page-link" href="#" aria-label="Next"> <span aria-hidden="true">»</span> <span class="sr-only">Next</span> </a> </li> </ul> </nav></body> </html>
Output:
Disabled and Active States:
Active: Pagination joins are adjustable for various conditions. Use .active to show the current page.
Example:
HTML
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <style> .pagination { padding: 12rem 0 0 22rem; } .page-link { background-color: green; color: white; } </style></head> <body> <nav aria-label="..."> <ul class="pagination"> <li> <a class="page-link" href="#" tabindex="-1">Previous</a> </li> <li><a class="page-link" href="#">11</a></li> <li class="active"> <a class="page-link" href="#">12</a> </li> <li><a class="page-link" href="#">13</a></li> <li class="active"> <li><a class="page-link" href="#">14</a></li> <li class="active"> <li><a class="page-link" href="#">15</a></li> <li class="active"> <a class="page-link" href="#">Next</a> </li> </ul> </nav></body> </html>
Output:
Disabled: While the .disabled class utilizes pointer-occasions: none to attempt to cripple the connection usefulness of <a>, that CSS property isn’t yet normalized and doesn’t represent console route. Accordingly, you ought to consistently add tab index=”- 1′′ on crippled connections and utilize custom JavaScript to completely incapacitate their usefulness.
Example:
HTML
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <style> .pagination { padding: 12rem 0 0 22rem; } .page-link { background-color: green; color: white; } </style></head> <body> <nav aria-label="..."> <ul class="pagination"> <li class="page-item disabled"> <span class="page-link">Previous</span> </li> <li class="page-item"> <a class="page-link" href="#">11</a> </li> <li class="page-item active"> <span class="page-link"> 12 <span class="sr-only">(current)</span> </span> </li> <li class="page-item"> <a class="page-link" href="#">13</a> </li> <li class="page-item disabled"> <a class="page-link" href="#">Next</a> </li> </ul> </nav></body> </html>
Output:
Sizing: Larger and Smaller: In this case, we will set the size of the pagination list.
Example:
HTML
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <style> .pagination { padding: 2rem 0 0 2rem; } .page-link { background-color: green; color: white; } </style></head> <body> <nav aria-label="larger"> <ul class="pagination pagination-lg"> <li class=" disabled"> <a class="page-link" href="#" tabindex="-1">11</a> </li> <li><a class="page-link" href="#">12</a></li> <li><a class="page-link" href="#">13</a></li> </ul> </nav> <nav aria-label="small"> <ul class="pagination pagination-sm"> <li class="disabled"> <a class="page-link" href="#" tabindex="-1">11</a> </li> <li><a class="page-link" href="#">12</a></li> <li><a class="page-link" href="#">13</a></li> </ul> </nav></body> </html>
Output:
Alignment: In this case, we will change the alignment of pagination components with flexbox.
Example:
HTML
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <style> .pagination { padding: 2rem 0 0 0; } .page-link { background-color: green; color: white; } </style></head> <body> <!-- Pagination in Center --> <nav aria-label="Page navigation"> <ul class="pagination justify-content-center"> <li class="page-item disabled"> <a class="page-link" href="#" tabindex="-1">Previous </a> </li> <li class="page-item"> <a class="page-link" href="#">11</a> </li> <li class="page-item"> <a class="page-link" href="#">12</a> </li> <li class="page-item"> <a class="page-link" href="#">13</a> </li> <li class="page-item"> <a class="page-link" href="#">Next</a> </li> </ul> </nav> <!-- Pagination in End --> <nav aria-label="Page navigation"> <ul class="pagination justify-content-end"> <li class="page-item disabled"> <a class="page-link" href="#" tabindex="-1">Previous </a> </li> <li class="page-item"> <a class="page-link" href="#">11</a> </li> <li class="page-item"> <a class="page-link" href="#">12</a> </li> <li class="page-item"> <a class="page-link" href="#">13</a> </li> <li class="page-item"> <a class="page-link" href="#">Next</a> </li> </ul> </nav></body> </html>
Output:
Bootstrap-4
Bootstrap-Questions
HTML-Questions
Picked
Bootstrap
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Show Images on Click using HTML ?
How to Use Bootstrap with React?
Tailwind CSS vs Bootstrap
How to toggle password visibility in forms using Bootstrap-icons ?
How to set vertical alignment in Bootstrap ?
How to update Node.js and NPM to next version ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
REST API (Introduction)
Hide or show elements in HTML using display property
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 Nov, 2021"
},
{
"code": null,
"e": 342,
"s": 28,
"text": "Bootstrap is a free and open-source tool collection for creating responsive websites and web applications. It is the most popular HTML, CSS, and JavaScript framework for developing responsive, mobile-first websites. It solves many problems which we had once, one of which is the cross-browser compatibility issue."
},
{
"code": null,
"e": 492,
"s": 342,
"text": "Pagination is an element used to indicate the actuality of a series of affiliated content across multiple runners and enables navigation across them."
},
{
"code": null,
"e": 919,
"s": 492,
"text": "Introduction to Pagination: We utilize an enormous square of associated joins for our pagination, making joins hard to miss and effectively adaptable—all while giving huge hit regions. Pagination is worked with a list of HTML components so screen per user can report the number of accessible connections. Utilize a wrapping <nav> component to distinguish it as a routing area to screen per user and other assistive advances. "
},
{
"code": null,
"e": 1181,
"s": 919,
"text": "Also, as pages probably have more than one such route area, it’s prudent to give a clear aria-name to the <nav>. For instance, if the pagination part is utilized to explore between a bunch of list items, a proper name could be aria-label=”Search results pages”."
},
{
"code": null,
"e": 1192,
"s": 1183,
"text": "Example:"
},
{
"code": null,
"e": 1197,
"s": 1192,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css\" integrity=\"sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm\" crossorigin=\"anonymous\"> <style> .pagination { padding: 12rem 0 0 22rem; } .page-link { background-color: green; color: white; } </style></head> <body> <nav aria-label=\"navigation example\"> <ul class=\"pagination border-success\"> <li><a class=\"page-link\" href=\"#\">Previous</a></li> <li><a class=\"page-link\" href=\"#\">11</a></li> <li><a class=\"page-link\" href=\"#\">12</a></li> <li><a class=\"page-link\" href=\"#\">13</a></li> <li><a class=\"page-link\" href=\"#\">14</a></li> <li><a class=\"page-link\" href=\"#\">15</a></li> <li><a class=\"page-link\" href=\"#\">Next</a></li> </ul> </nav></body> </html>",
"e": 2368,
"s": 1197,
"text": null
},
{
"code": null,
"e": 2376,
"s": 2368,
"text": "Output:"
},
{
"code": null,
"e": 2570,
"s": 2376,
"text": "Working with icons: Hoping to utilize a symbol or image instead of text for some pagination joins. Make certain to furnish legitimate screen per user support with aria ascribes and the .sr only"
},
{
"code": null,
"e": 2579,
"s": 2570,
"text": "Example:"
},
{
"code": null,
"e": 2584,
"s": 2579,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css\" integrity=\"sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm\" crossorigin=\"anonymous\"> <style> .pagination { padding: 12rem 0 0 22rem; } .page-link { background-color: green; color: white; } </style></head> <body> <nav aria-label=\"Page navigation\"> <ul class=\"pagination\"> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\" aria-label=\"Previous\"> <span aria-hidden=\"true\">«</span> <span class=\"sr-only\">Previous</span> </a> </li> <li><a class=\"page-link\" href=\"#\">11</a></li> <li><a class=\"page-link\" href=\"#\">12</a></li> <li><a class=\"page-link\" href=\"#\">13</a></li> <li><a class=\"page-link\" href=\"#\">14</a></li> <li><a class=\"page-link\" href=\"#\">15</a></li> <li> <a class=\"page-link\" href=\"#\" aria-label=\"Next\"> <span aria-hidden=\"true\">»</span> <span class=\"sr-only\">Next</span> </a> </li> </ul> </nav></body> </html>",
"e": 4106,
"s": 2584,
"text": null
},
{
"code": null,
"e": 4114,
"s": 4106,
"text": "Output:"
},
{
"code": null,
"e": 4144,
"s": 4116,
"text": "Disabled and Active States:"
},
{
"code": null,
"e": 4246,
"s": 4144,
"text": "Active: Pagination joins are adjustable for various conditions. Use .active to show the current page."
},
{
"code": null,
"e": 4255,
"s": 4246,
"text": "Example:"
},
{
"code": null,
"e": 4260,
"s": 4255,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css\" integrity=\"sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm\" crossorigin=\"anonymous\"> <style> .pagination { padding: 12rem 0 0 22rem; } .page-link { background-color: green; color: white; } </style></head> <body> <nav aria-label=\"...\"> <ul class=\"pagination\"> <li> <a class=\"page-link\" href=\"#\" tabindex=\"-1\">Previous</a> </li> <li><a class=\"page-link\" href=\"#\">11</a></li> <li class=\"active\"> <a class=\"page-link\" href=\"#\">12</a> </li> <li><a class=\"page-link\" href=\"#\">13</a></li> <li class=\"active\"> <li><a class=\"page-link\" href=\"#\">14</a></li> <li class=\"active\"> <li><a class=\"page-link\" href=\"#\">15</a></li> <li class=\"active\"> <a class=\"page-link\" href=\"#\">Next</a> </li> </ul> </nav></body> </html>",
"e": 5611,
"s": 4260,
"text": null
},
{
"code": null,
"e": 5619,
"s": 5611,
"text": "Output:"
},
{
"code": null,
"e": 5979,
"s": 5619,
"text": "Disabled: While the .disabled class utilizes pointer-occasions: none to attempt to cripple the connection usefulness of <a>, that CSS property isn’t yet normalized and doesn’t represent console route. Accordingly, you ought to consistently add tab index=”- 1′′ on crippled connections and utilize custom JavaScript to completely incapacitate their usefulness."
},
{
"code": null,
"e": 5988,
"s": 5979,
"text": "Example:"
},
{
"code": null,
"e": 5993,
"s": 5988,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css\" integrity=\"sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm\" crossorigin=\"anonymous\"> <style> .pagination { padding: 12rem 0 0 22rem; } .page-link { background-color: green; color: white; } </style></head> <body> <nav aria-label=\"...\"> <ul class=\"pagination\"> <li class=\"page-item disabled\"> <span class=\"page-link\">Previous</span> </li> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">11</a> </li> <li class=\"page-item active\"> <span class=\"page-link\"> 12 <span class=\"sr-only\">(current)</span> </span> </li> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">13</a> </li> <li class=\"page-item disabled\"> <a class=\"page-link\" href=\"#\">Next</a> </li> </ul> </nav></body> </html>",
"e": 7363,
"s": 5993,
"text": null
},
{
"code": null,
"e": 7371,
"s": 7363,
"text": "Output:"
},
{
"code": null,
"e": 7458,
"s": 7371,
"text": "Sizing: Larger and Smaller: In this case, we will set the size of the pagination list."
},
{
"code": null,
"e": 7467,
"s": 7458,
"text": "Example:"
},
{
"code": null,
"e": 7472,
"s": 7467,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css\" integrity=\"sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm\" crossorigin=\"anonymous\"> <style> .pagination { padding: 2rem 0 0 2rem; } .page-link { background-color: green; color: white; } </style></head> <body> <nav aria-label=\"larger\"> <ul class=\"pagination pagination-lg\"> <li class=\" disabled\"> <a class=\"page-link\" href=\"#\" tabindex=\"-1\">11</a> </li> <li><a class=\"page-link\" href=\"#\">12</a></li> <li><a class=\"page-link\" href=\"#\">13</a></li> </ul> </nav> <nav aria-label=\"small\"> <ul class=\"pagination pagination-sm\"> <li class=\"disabled\"> <a class=\"page-link\" href=\"#\" tabindex=\"-1\">11</a> </li> <li><a class=\"page-link\" href=\"#\">12</a></li> <li><a class=\"page-link\" href=\"#\">13</a></li> </ul> </nav></body> </html>",
"e": 8818,
"s": 7472,
"text": null
},
{
"code": null,
"e": 8826,
"s": 8818,
"text": "Output:"
},
{
"code": null,
"e": 8919,
"s": 8826,
"text": "Alignment: In this case, we will change the alignment of pagination components with flexbox."
},
{
"code": null,
"e": 8928,
"s": 8919,
"text": "Example:"
},
{
"code": null,
"e": 8933,
"s": 8928,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css\" integrity=\"sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm\" crossorigin=\"anonymous\"> <style> .pagination { padding: 2rem 0 0 0; } .page-link { background-color: green; color: white; } </style></head> <body> <!-- Pagination in Center --> <nav aria-label=\"Page navigation\"> <ul class=\"pagination justify-content-center\"> <li class=\"page-item disabled\"> <a class=\"page-link\" href=\"#\" tabindex=\"-1\">Previous </a> </li> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">11</a> </li> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">12</a> </li> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">13</a> </li> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">Next</a> </li> </ul> </nav> <!-- Pagination in End --> <nav aria-label=\"Page navigation\"> <ul class=\"pagination justify-content-end\"> <li class=\"page-item disabled\"> <a class=\"page-link\" href=\"#\" tabindex=\"-1\">Previous </a> </li> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">11</a> </li> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">12</a> </li> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">13</a> </li> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">Next</a> </li> </ul> </nav></body> </html>",
"e": 11035,
"s": 8933,
"text": null
},
{
"code": null,
"e": 11043,
"s": 11035,
"text": "Output:"
},
{
"code": null,
"e": 11055,
"s": 11043,
"text": "Bootstrap-4"
},
{
"code": null,
"e": 11075,
"s": 11055,
"text": "Bootstrap-Questions"
},
{
"code": null,
"e": 11090,
"s": 11075,
"text": "HTML-Questions"
},
{
"code": null,
"e": 11097,
"s": 11090,
"text": "Picked"
},
{
"code": null,
"e": 11107,
"s": 11097,
"text": "Bootstrap"
},
{
"code": null,
"e": 11112,
"s": 11107,
"text": "HTML"
},
{
"code": null,
"e": 11129,
"s": 11112,
"text": "Web Technologies"
},
{
"code": null,
"e": 11134,
"s": 11129,
"text": "HTML"
},
{
"code": null,
"e": 11232,
"s": 11134,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 11273,
"s": 11232,
"text": "How to Show Images on Click using HTML ?"
},
{
"code": null,
"e": 11306,
"s": 11273,
"text": "How to Use Bootstrap with React?"
},
{
"code": null,
"e": 11332,
"s": 11306,
"text": "Tailwind CSS vs Bootstrap"
},
{
"code": null,
"e": 11399,
"s": 11332,
"text": "How to toggle password visibility in forms using Bootstrap-icons ?"
},
{
"code": null,
"e": 11444,
"s": 11399,
"text": "How to set vertical alignment in Bootstrap ?"
},
{
"code": null,
"e": 11492,
"s": 11444,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 11554,
"s": 11492,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 11604,
"s": 11554,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 11628,
"s": 11604,
"text": "REST API (Introduction)"
}
] |
How to implement Inheritance in Typescript ?
|
14 Jul, 2021
Inheritance is a major pillar of object-oriented programming languages and inheritance is used to create a new class from the existing one. The newly created class is known as the Derived class and the class from which the derived class inherited is known as the Base class. An inherited derived class acquires the properties and behaviors of the base class. TypeScript supports single inheritance and multilevel inheritance. We can not implement hybrid and multiple inheritances using TypeScript. The inheritance uses class-based inheritance and it can be implemented using extends keywords in typescript. In this article, we will see how inheritance is implemented in TypeScript.
Syntax:
class baseClassName {
}
class derivedClassName extends baseClassName {
}
Single Inheritance in TypeScript: In single inheritance, the properties and behaviour of the base class can be inherited into at most one derived class. It used to add new functionality to the already implemented class.
Example: In this example, we are creating a Person as a base class and using single inheritance implementing Teacher as a Derived class.
Javascript
// Base classclass Person { Name: string; constructor(name: string) { this.Name = name; }}// Deriving Teacher classclass Teacher extends Person { Payment: number; constructor(name: string, payment: number) { super(name); this.Payment = payment; } display(): void { console.log("Teacher's Name: " + this.Name); console.log("Teacher's Payment " + this.Payment); }}// Create Objectlet obj = new Teacher("GeeksforGeeks", 8500000);obj.display();
Output:
Teacher's Name: GeeksforGeeks
Teacher's Payment 8500000
2.Multilevel Inheritance:
In multilevel inheritance, the derived class acts as the base class for another derived class. The newly created derived class acquires the properties and behavior of other base classes.
Example: In this example, we are creating a Vehicle as a base class and a Car as a subclass which deriving the new class called carModel and the class carModel acquires all features of the Vehicle as well as Car class.
Javascript
// Base classclass Vehicle { Type(): void { console.log("Car"); }} // Inherites from Vehicleclass Car extends Vehicle { Brand(): void { console.log("ABC"); }} // Inherites all properties of // Vehicle and Car classclass carModel extends Car { Model(): void { console.log("ABC2021"); }} // Object creationlet obj = new carModel();obj.Type();obj.Brand();obj.Model();
Output:
Car
ABC
ABC2021
Picked
TypeScript
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n14 Jul, 2021"
},
{
"code": null,
"e": 710,
"s": 28,
"text": "Inheritance is a major pillar of object-oriented programming languages and inheritance is used to create a new class from the existing one. The newly created class is known as the Derived class and the class from which the derived class inherited is known as the Base class. An inherited derived class acquires the properties and behaviors of the base class. TypeScript supports single inheritance and multilevel inheritance. We can not implement hybrid and multiple inheritances using TypeScript. The inheritance uses class-based inheritance and it can be implemented using extends keywords in typescript. In this article, we will see how inheritance is implemented in TypeScript."
},
{
"code": null,
"e": 718,
"s": 710,
"text": "Syntax:"
},
{
"code": null,
"e": 791,
"s": 718,
"text": "class baseClassName {\n}\nclass derivedClassName extends baseClassName {\n}"
},
{
"code": null,
"e": 1011,
"s": 791,
"text": "Single Inheritance in TypeScript: In single inheritance, the properties and behaviour of the base class can be inherited into at most one derived class. It used to add new functionality to the already implemented class."
},
{
"code": null,
"e": 1149,
"s": 1011,
"text": "Example: In this example, we are creating a Person as a base class and using single inheritance implementing Teacher as a Derived class. "
},
{
"code": null,
"e": 1162,
"s": 1151,
"text": "Javascript"
},
{
"code": "// Base classclass Person { Name: string; constructor(name: string) { this.Name = name; }}// Deriving Teacher classclass Teacher extends Person { Payment: number; constructor(name: string, payment: number) { super(name); this.Payment = payment; } display(): void { console.log(\"Teacher's Name: \" + this.Name); console.log(\"Teacher's Payment \" + this.Payment); }}// Create Objectlet obj = new Teacher(\"GeeksforGeeks\", 8500000);obj.display();",
"e": 1626,
"s": 1162,
"text": null
},
{
"code": null,
"e": 1634,
"s": 1626,
"text": "Output:"
},
{
"code": null,
"e": 1691,
"s": 1634,
"text": "Teacher's Name: GeeksforGeeks \nTeacher's Payment 8500000"
},
{
"code": null,
"e": 1717,
"s": 1691,
"text": "2.Multilevel Inheritance:"
},
{
"code": null,
"e": 1904,
"s": 1717,
"text": "In multilevel inheritance, the derived class acts as the base class for another derived class. The newly created derived class acquires the properties and behavior of other base classes."
},
{
"code": null,
"e": 2123,
"s": 1904,
"text": "Example: In this example, we are creating a Vehicle as a base class and a Car as a subclass which deriving the new class called carModel and the class carModel acquires all features of the Vehicle as well as Car class."
},
{
"code": null,
"e": 2134,
"s": 2123,
"text": "Javascript"
},
{
"code": "// Base classclass Vehicle { Type(): void { console.log(\"Car\"); }} // Inherites from Vehicleclass Car extends Vehicle { Brand(): void { console.log(\"ABC\"); }} // Inherites all properties of // Vehicle and Car classclass carModel extends Car { Model(): void { console.log(\"ABC2021\"); }} // Object creationlet obj = new carModel();obj.Type();obj.Brand();obj.Model();",
"e": 2517,
"s": 2134,
"text": null
},
{
"code": null,
"e": 2525,
"s": 2517,
"text": "Output:"
},
{
"code": null,
"e": 2543,
"s": 2525,
"text": "Car \nABC\nABC2021"
},
{
"code": null,
"e": 2550,
"s": 2543,
"text": "Picked"
},
{
"code": null,
"e": 2561,
"s": 2550,
"text": "TypeScript"
},
{
"code": null,
"e": 2572,
"s": 2561,
"text": "JavaScript"
},
{
"code": null,
"e": 2589,
"s": 2572,
"text": "Web Technologies"
}
] |
Reshape DataFrame from Long to Wide Format in R
|
23 Sep, 2021
In this article, we will discuss how to reshape dataframe from long to wide format in R programming language.
The data in the dataframe is recognized by the format in which the storage and retrieval happens. Duplicate key-value pairs exist in dataframe and can be rearranged using the following methods.
The reshape method in R is used to reshape the grouped data. It is available in base R. The method basically reshapes a specified dataframe between different formats, that is ‘wide’ format with repetitive measurements done in separate columns as well as ‘long’ formats with repetitive measurements in separate rows.
Syntax: reshape (data-frame, idvar = , timevar = , direction = )
Parameter :
data-frame : The dataframe to reshape
timevar : Indicator of the variable given in long format that differentiates multiple records from the same group.
idvar : Indicator of the variable(s) in long format that identify multiple records from the same group.
direction : specifies whether to depict data in “long” or “wide” format.
The output retains the original dataframe row numbers. The missing values are appended with an NA value in the dataframe.
Example: Reshape dataframe from long to wide
R
# create first dataframedata_frame1<-data.frame(col1=c(rep('Grp1',2), rep('Grp2',2), rep('Grp3',2)), col2=rep(1:3,2), col3 = letters[1:6] ) print("Original DataFrame")print(data_frame1) # reshaping the datadata_frame_mod <- reshape(data_frame1, idvar = "col1", timevar = "col2", direction = "wide") print("Modified DataFrame")print(data_frame_mod)
Output:
[1] "Original DataFrame"
col1 col2 col3
1 Grp1 1 a
2 Grp1 2 b
3 Grp2 3 c
4 Grp2 1 d
5 Grp3 2 e
6 Grp3 3 f
[1] "Modified DataFrame"
col1 col3.1 col3.2 col3.3
1 Grp1 a b <NA>
3 Grp2 d <NA> c
5 Grp3 <NA> e f
The package can be downloaded and installed into the working space using the following syntax :
install.packages("tidyr")
The spread method of this package can be used to reshape the data from long to wide format in R. The method is used to append a new column for each unique value of the key column. These unique set of values will form the names for new columns.
Syntax:
spread (data-frame, key, value)
Example: Reshape dataframe from long to wide
Python3
library("tidyr") # create first dataframedata_frame1 < -data.frame(col1=c(rep('Grp1', 2), rep('Grp2', 2), rep('Grp3', 2)), col2=rep(1: 3, 2), col3=letters[1:6] )print("Original DataFrame")print(data_frame1) # reshaping the datadata_frame_mod < - spread(data_frame1, key=col2, value=col3)print("Modified DataFrame")print(data_frame_mod)
Output:
col1 1 2 3
1 Grp1 a b <NA>
2 Grp2 d <NA> c
3 Grp3 <NA> e f
Picked
R DataFrame-Programs
R-DataFrame
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Split Column Into Multiple Columns in R DataFrame?
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to import an Excel File into R ?
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
Extract First or Last n Characters from String in R
Merge DataFrames by Column Names in R
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 Sep, 2021"
},
{
"code": null,
"e": 138,
"s": 28,
"text": "In this article, we will discuss how to reshape dataframe from long to wide format in R programming language."
},
{
"code": null,
"e": 332,
"s": 138,
"text": "The data in the dataframe is recognized by the format in which the storage and retrieval happens. Duplicate key-value pairs exist in dataframe and can be rearranged using the following methods."
},
{
"code": null,
"e": 649,
"s": 332,
"text": "The reshape method in R is used to reshape the grouped data. It is available in base R. The method basically reshapes a specified dataframe between different formats, that is ‘wide’ format with repetitive measurements done in separate columns as well as ‘long’ formats with repetitive measurements in separate rows. "
},
{
"code": null,
"e": 714,
"s": 649,
"text": "Syntax: reshape (data-frame, idvar = , timevar = , direction = )"
},
{
"code": null,
"e": 727,
"s": 714,
"text": "Parameter : "
},
{
"code": null,
"e": 765,
"s": 727,
"text": "data-frame : The dataframe to reshape"
},
{
"code": null,
"e": 881,
"s": 765,
"text": "timevar : Indicator of the variable given in long format that differentiates multiple records from the same group. "
},
{
"code": null,
"e": 986,
"s": 881,
"text": "idvar : Indicator of the variable(s) in long format that identify multiple records from the same group. "
},
{
"code": null,
"e": 1060,
"s": 986,
"text": "direction : specifies whether to depict data in “long” or “wide” format. "
},
{
"code": null,
"e": 1183,
"s": 1060,
"text": "The output retains the original dataframe row numbers. The missing values are appended with an NA value in the dataframe. "
},
{
"code": null,
"e": 1228,
"s": 1183,
"text": "Example: Reshape dataframe from long to wide"
},
{
"code": null,
"e": 1230,
"s": 1228,
"text": "R"
},
{
"code": "# create first dataframedata_frame1<-data.frame(col1=c(rep('Grp1',2), rep('Grp2',2), rep('Grp3',2)), col2=rep(1:3,2), col3 = letters[1:6] ) print(\"Original DataFrame\")print(data_frame1) # reshaping the datadata_frame_mod <- reshape(data_frame1, idvar = \"col1\", timevar = \"col2\", direction = \"wide\") print(\"Modified DataFrame\")print(data_frame_mod)",
"e": 1737,
"s": 1230,
"text": null
},
{
"code": null,
"e": 1745,
"s": 1737,
"text": "Output:"
},
{
"code": null,
"e": 2038,
"s": 1745,
"text": "[1] \"Original DataFrame\" \n col1 col2 col3 \n1 Grp1 1 a \n2 Grp1 2 b \n3 Grp2 3 c \n4 Grp2 1 d \n5 Grp3 2 e \n6 Grp3 3 f \n[1] \"Modified DataFrame\" \n col1 col3.1 col3.2 col3.3 \n1 Grp1 a b <NA> \n3 Grp2 d <NA> c \n5 Grp3 <NA> e f"
},
{
"code": null,
"e": 2135,
"s": 2038,
"text": "The package can be downloaded and installed into the working space using the following syntax : "
},
{
"code": null,
"e": 2161,
"s": 2135,
"text": "install.packages(\"tidyr\")"
},
{
"code": null,
"e": 2405,
"s": 2161,
"text": "The spread method of this package can be used to reshape the data from long to wide format in R. The method is used to append a new column for each unique value of the key column. These unique set of values will form the names for new columns."
},
{
"code": null,
"e": 2413,
"s": 2405,
"text": "Syntax:"
},
{
"code": null,
"e": 2445,
"s": 2413,
"text": "spread (data-frame, key, value)"
},
{
"code": null,
"e": 2490,
"s": 2445,
"text": "Example: Reshape dataframe from long to wide"
},
{
"code": null,
"e": 2498,
"s": 2490,
"text": "Python3"
},
{
"code": "library(\"tidyr\") # create first dataframedata_frame1 < -data.frame(col1=c(rep('Grp1', 2), rep('Grp2', 2), rep('Grp3', 2)), col2=rep(1: 3, 2), col3=letters[1:6] )print(\"Original DataFrame\")print(data_frame1) # reshaping the datadata_frame_mod < - spread(data_frame1, key=col2, value=col3)print(\"Modified DataFrame\")print(data_frame_mod)",
"e": 2964,
"s": 2498,
"text": null
},
{
"code": null,
"e": 2972,
"s": 2964,
"text": "Output:"
},
{
"code": null,
"e": 3062,
"s": 2972,
"text": " col1 1 2 3 \n1 Grp1 a b <NA> \n2 Grp2 d <NA> c \n3 Grp3 <NA> e f"
},
{
"code": null,
"e": 3069,
"s": 3062,
"text": "Picked"
},
{
"code": null,
"e": 3090,
"s": 3069,
"text": "R DataFrame-Programs"
},
{
"code": null,
"e": 3102,
"s": 3090,
"text": "R-DataFrame"
},
{
"code": null,
"e": 3113,
"s": 3102,
"text": "R Language"
},
{
"code": null,
"e": 3124,
"s": 3113,
"text": "R Programs"
},
{
"code": null,
"e": 3222,
"s": 3124,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3280,
"s": 3222,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 3332,
"s": 3280,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 3367,
"s": 3332,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 3405,
"s": 3367,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 3442,
"s": 3405,
"text": "How to import an Excel File into R ?"
},
{
"code": null,
"e": 3500,
"s": 3442,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 3543,
"s": 3500,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 3592,
"s": 3543,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 3644,
"s": 3592,
"text": "Extract First or Last n Characters from String in R"
}
] |
How to Count Variable Numbers of Arguments in C?
|
28 May, 2017
C supports variable numbers of arguments. But there is no language provided way for finding out total number of arguments passed. User has to handle this in one of the following ways:1) By passing first argument as count of arguments.2) By passing last argument as NULL (or 0).3) Using some printf (or scanf) like mechanism where first argument has placeholders for rest of the arguments.
Following is an example that uses first argument arg_count to hold count of other arguments.
#include <stdarg.h>#include <stdio.h> // this function returns minimum of integer numbers passed. First // argument is count of numbers.int min(int arg_count, ...){ int i; int min, a; // va_list is a type to hold information about variable arguments va_list ap; // va_start must be called before accessing variable argument list va_start(ap, arg_count); // Now arguments can be accessed one by one using va_arg macro // Initialize min as first argument in list min = va_arg(ap, int); // traverse rest of the arguments to find out minimum for(i = 2; i <= arg_count; i++) { if((a = va_arg(ap, int)) < min) min = a; } //va_end should be executed before the function returns whenever // va_start has been previously used in that function va_end(ap); return min;} int main(){ int count = 5; // Find minimum of 5 numbers: (12, 67, 6, 7, 100) printf("Minimum value is %d", min(count, 12, 67, 6, 7, 100)); getchar(); return 0;}
Output:Minimum value is 6
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
C-Functions
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n28 May, 2017"
},
{
"code": null,
"e": 441,
"s": 52,
"text": "C supports variable numbers of arguments. But there is no language provided way for finding out total number of arguments passed. User has to handle this in one of the following ways:1) By passing first argument as count of arguments.2) By passing last argument as NULL (or 0).3) Using some printf (or scanf) like mechanism where first argument has placeholders for rest of the arguments."
},
{
"code": null,
"e": 534,
"s": 441,
"text": "Following is an example that uses first argument arg_count to hold count of other arguments."
},
{
"code": "#include <stdarg.h>#include <stdio.h> // this function returns minimum of integer numbers passed. First // argument is count of numbers.int min(int arg_count, ...){ int i; int min, a; // va_list is a type to hold information about variable arguments va_list ap; // va_start must be called before accessing variable argument list va_start(ap, arg_count); // Now arguments can be accessed one by one using va_arg macro // Initialize min as first argument in list min = va_arg(ap, int); // traverse rest of the arguments to find out minimum for(i = 2; i <= arg_count; i++) { if((a = va_arg(ap, int)) < min) min = a; } //va_end should be executed before the function returns whenever // va_start has been previously used in that function va_end(ap); return min;} int main(){ int count = 5; // Find minimum of 5 numbers: (12, 67, 6, 7, 100) printf(\"Minimum value is %d\", min(count, 12, 67, 6, 7, 100)); getchar(); return 0;}",
"e": 1528,
"s": 534,
"text": null
},
{
"code": null,
"e": 1554,
"s": 1528,
"text": "Output:Minimum value is 6"
},
{
"code": null,
"e": 1679,
"s": 1554,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 1691,
"s": 1679,
"text": "C-Functions"
},
{
"code": null,
"e": 1702,
"s": 1691,
"text": "C Language"
}
] |
Difference Between Algorithm and Flowchart - GeeksforGeeks
|
21 May, 2020
Algorithm:
The word Algorithm means “a process or set of rules to be followed in calculations or other problem-solving operations”. Therefore Algorithm refers to a set of rules/instructions that step-by-step define how a work is to be executed upon inorder to get the expected results.
Let’s take a look at an example for a better understanding. As a programmer, we are all aware of the Linear Search program. (Linear Search)
Algorithm of linear search :
1. Start from the leftmost element of arr[] and
one by one compare x with each element of arr[].
2. If x matches with an element, return the index.
3. If x doesn’t match with any of elements, return -1.
Here, we can see how the steps of a linear search program are explained in a simple, English language.
Flowchart:
A flowchart is a graphical representation of an algorithm. Programmers often use it as a program-planning tool to solve a problem. It makes use of symbols which are connected among them to indicate the flow of information and processing.The process of drawing a flowchart for an algorithm is known as “flowcharting”.
Example: Draw a flowchart to input two numbers from the user and display the largest of two numbers
Let’s see the difference between algorithm and flow chart:-
pp_pankaj
Data Structures
Difference Between
Data Structures
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
SDE SHEET - A Complete Guide for SDE Preparation
Top 50 Array Coding Problems for Interviews
DSA Sheet by Love Babbar
Doubly Linked List | Set 1 (Introduction and Insertion)
Implementing a Linked List in Java using Class
Difference between BFS and DFS
Class method vs Static method in Python
Differences between TCP and UDP
Stack vs Heap Memory Allocation
Difference between Process and Thread
|
[
{
"code": null,
"e": 34514,
"s": 34486,
"text": "\n21 May, 2020"
},
{
"code": null,
"e": 34525,
"s": 34514,
"text": "Algorithm:"
},
{
"code": null,
"e": 34800,
"s": 34525,
"text": "The word Algorithm means “a process or set of rules to be followed in calculations or other problem-solving operations”. Therefore Algorithm refers to a set of rules/instructions that step-by-step define how a work is to be executed upon inorder to get the expected results."
},
{
"code": null,
"e": 34940,
"s": 34800,
"text": "Let’s take a look at an example for a better understanding. As a programmer, we are all aware of the Linear Search program. (Linear Search)"
},
{
"code": null,
"e": 34969,
"s": 34940,
"text": "Algorithm of linear search :"
},
{
"code": null,
"e": 35177,
"s": 34969,
"text": "1. Start from the leftmost element of arr[] and \none by one compare x with each element of arr[]. \n2. If x matches with an element, return the index. \n3. If x doesn’t match with any of elements, return -1. \n"
},
{
"code": null,
"e": 35280,
"s": 35177,
"text": "Here, we can see how the steps of a linear search program are explained in a simple, English language."
},
{
"code": null,
"e": 35291,
"s": 35280,
"text": "Flowchart:"
},
{
"code": null,
"e": 35608,
"s": 35291,
"text": "A flowchart is a graphical representation of an algorithm. Programmers often use it as a program-planning tool to solve a problem. It makes use of symbols which are connected among them to indicate the flow of information and processing.The process of drawing a flowchart for an algorithm is known as “flowcharting”."
},
{
"code": null,
"e": 35708,
"s": 35608,
"text": "Example: Draw a flowchart to input two numbers from the user and display the largest of two numbers"
},
{
"code": null,
"e": 35768,
"s": 35708,
"text": "Let’s see the difference between algorithm and flow chart:-"
},
{
"code": null,
"e": 35778,
"s": 35768,
"text": "pp_pankaj"
},
{
"code": null,
"e": 35794,
"s": 35778,
"text": "Data Structures"
},
{
"code": null,
"e": 35813,
"s": 35794,
"text": "Difference Between"
},
{
"code": null,
"e": 35829,
"s": 35813,
"text": "Data Structures"
},
{
"code": null,
"e": 35927,
"s": 35829,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35936,
"s": 35927,
"text": "Comments"
},
{
"code": null,
"e": 35949,
"s": 35936,
"text": "Old Comments"
},
{
"code": null,
"e": 35998,
"s": 35949,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 36042,
"s": 35998,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 36067,
"s": 36042,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 36123,
"s": 36067,
"text": "Doubly Linked List | Set 1 (Introduction and Insertion)"
},
{
"code": null,
"e": 36170,
"s": 36123,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 36201,
"s": 36170,
"text": "Difference between BFS and DFS"
},
{
"code": null,
"e": 36241,
"s": 36201,
"text": "Class method vs Static method in Python"
},
{
"code": null,
"e": 36273,
"s": 36241,
"text": "Differences between TCP and UDP"
},
{
"code": null,
"e": 36305,
"s": 36273,
"text": "Stack vs Heap Memory Allocation"
}
] |
Design Patterns - MVC Pattern
|
MVC Pattern stands for Model-View-Controller Pattern. This pattern is used to separate application's concerns.
Model - Model represents an object or JAVA POJO carrying data. It can also have logic to update controller if its data changes.
Model - Model represents an object or JAVA POJO carrying data. It can also have logic to update controller if its data changes.
View - View represents the visualization of the data that model contains.
View - View represents the visualization of the data that model contains.
Controller - Controller acts on both model and view. It controls the data flow into model object and updates the view whenever data changes. It keeps view and model separate.
Controller - Controller acts on both model and view. It controls the data flow into model object and updates the view whenever data changes. It keeps view and model separate.
We are going to create a Student object acting as a model.StudentView will be a view class which can print student details on console and StudentController is the controller class responsible to store data in Student object and update view StudentView accordingly.
MVCPatternDemo, our demo class, will use StudentController to demonstrate use of MVC pattern.
Create Model.
Student.java
public class Student {
private String rollNo;
private String name;
public String getRollNo() {
return rollNo;
}
public void setRollNo(String rollNo) {
this.rollNo = rollNo;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Create View.
StudentView.java
public class StudentView {
public void printStudentDetails(String studentName, String studentRollNo){
System.out.println("Student: ");
System.out.println("Name: " + studentName);
System.out.println("Roll No: " + studentRollNo);
}
}
Create Controller.
StudentController.java
public class StudentController {
private Student model;
private StudentView view;
public StudentController(Student model, StudentView view){
this.model = model;
this.view = view;
}
public void setStudentName(String name){
model.setName(name);
}
public String getStudentName(){
return model.getName();
}
public void setStudentRollNo(String rollNo){
model.setRollNo(rollNo);
}
public String getStudentRollNo(){
return model.getRollNo();
}
public void updateView(){
view.printStudentDetails(model.getName(), model.getRollNo());
}
}
Use the StudentController methods to demonstrate MVC design pattern usage.
MVCPatternDemo.java
public class MVCPatternDemo {
public static void main(String[] args) {
//fetch student record based on his roll no from the database
Student model = retriveStudentFromDatabase();
//Create a view : to write student details on console
StudentView view = new StudentView();
StudentController controller = new StudentController(model, view);
controller.updateView();
//update model data
controller.setStudentName("John");
controller.updateView();
}
private static Student retriveStudentFromDatabase(){
Student student = new Student();
student.setName("Robert");
student.setRollNo("10");
return student;
}
}
Verify the output.
Student:
Name: Robert
Roll No: 10
Student:
Name: John
Roll No: 10
102 Lectures
10 hours
Arnab Chakraborty
30 Lectures
3 hours
Arnab Chakraborty
31 Lectures
4 hours
Arnab Chakraborty
43 Lectures
1.5 hours
Manoj Kumar
7 Lectures
1 hours
Zach Miller
54 Lectures
4 hours
Sasha Miller
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2862,
"s": 2751,
"text": "MVC Pattern stands for Model-View-Controller Pattern. This pattern is used to separate application's concerns."
},
{
"code": null,
"e": 2990,
"s": 2862,
"text": "Model - Model represents an object or JAVA POJO carrying data. It can also have logic to update controller if its data changes."
},
{
"code": null,
"e": 3118,
"s": 2990,
"text": "Model - Model represents an object or JAVA POJO carrying data. It can also have logic to update controller if its data changes."
},
{
"code": null,
"e": 3192,
"s": 3118,
"text": "View - View represents the visualization of the data that model contains."
},
{
"code": null,
"e": 3266,
"s": 3192,
"text": "View - View represents the visualization of the data that model contains."
},
{
"code": null,
"e": 3441,
"s": 3266,
"text": "Controller - Controller acts on both model and view. It controls the data flow into model object and updates the view whenever data changes. It keeps view and model separate."
},
{
"code": null,
"e": 3616,
"s": 3441,
"text": "Controller - Controller acts on both model and view. It controls the data flow into model object and updates the view whenever data changes. It keeps view and model separate."
},
{
"code": null,
"e": 3881,
"s": 3616,
"text": "We are going to create a Student object acting as a model.StudentView will be a view class which can print student details on console and StudentController is the controller class responsible to store data in Student object and update view StudentView accordingly."
},
{
"code": null,
"e": 3975,
"s": 3881,
"text": "MVCPatternDemo, our demo class, will use StudentController to demonstrate use of MVC pattern."
},
{
"code": null,
"e": 3989,
"s": 3975,
"text": "Create Model."
},
{
"code": null,
"e": 4002,
"s": 3989,
"text": "Student.java"
},
{
"code": null,
"e": 4345,
"s": 4002,
"text": "public class Student {\n private String rollNo;\n private String name;\n \n public String getRollNo() {\n return rollNo;\n }\n \n public void setRollNo(String rollNo) {\n this.rollNo = rollNo;\n }\n \n public String getName() {\n return name;\n }\n \n public void setName(String name) {\n this.name = name;\n }\n}"
},
{
"code": null,
"e": 4358,
"s": 4345,
"text": "Create View."
},
{
"code": null,
"e": 4375,
"s": 4358,
"text": "StudentView.java"
},
{
"code": null,
"e": 4631,
"s": 4375,
"text": "public class StudentView {\n public void printStudentDetails(String studentName, String studentRollNo){\n System.out.println(\"Student: \");\n System.out.println(\"Name: \" + studentName);\n System.out.println(\"Roll No: \" + studentRollNo);\n }\n}"
},
{
"code": null,
"e": 4650,
"s": 4631,
"text": "Create Controller."
},
{
"code": null,
"e": 4673,
"s": 4650,
"text": "StudentController.java"
},
{
"code": null,
"e": 5305,
"s": 4673,
"text": "public class StudentController {\n private Student model;\n private StudentView view;\n\n public StudentController(Student model, StudentView view){\n this.model = model;\n this.view = view;\n }\n\n public void setStudentName(String name){\n model.setName(name);\t\t\n }\n\n public String getStudentName(){\n return model.getName();\t\t\n }\n\n public void setStudentRollNo(String rollNo){\n model.setRollNo(rollNo);\t\t\n }\n\n public String getStudentRollNo(){\n return model.getRollNo();\t\t\n }\n\n public void updateView(){\t\t\t\t\n view.printStudentDetails(model.getName(), model.getRollNo());\n }\t\n}"
},
{
"code": null,
"e": 5380,
"s": 5305,
"text": "Use the StudentController methods to demonstrate MVC design pattern usage."
},
{
"code": null,
"e": 5400,
"s": 5380,
"text": "MVCPatternDemo.java"
},
{
"code": null,
"e": 6101,
"s": 5400,
"text": "public class MVCPatternDemo {\n public static void main(String[] args) {\n\n //fetch student record based on his roll no from the database\n Student model = retriveStudentFromDatabase();\n\n //Create a view : to write student details on console\n StudentView view = new StudentView();\n\n StudentController controller = new StudentController(model, view);\n\n controller.updateView();\n\n //update model data\n controller.setStudentName(\"John\");\n\n controller.updateView();\n }\n\n private static Student retriveStudentFromDatabase(){\n Student student = new Student();\n student.setName(\"Robert\");\n student.setRollNo(\"10\");\n return student;\n }\n}"
},
{
"code": null,
"e": 6120,
"s": 6101,
"text": "Verify the output."
},
{
"code": null,
"e": 6189,
"s": 6120,
"text": "Student: \nName: Robert\nRoll No: 10\nStudent: \nName: John\nRoll No: 10\n"
},
{
"code": null,
"e": 6224,
"s": 6189,
"text": "\n 102 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 6243,
"s": 6224,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 6276,
"s": 6243,
"text": "\n 30 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 6295,
"s": 6276,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 6328,
"s": 6295,
"text": "\n 31 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 6347,
"s": 6328,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 6382,
"s": 6347,
"text": "\n 43 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 6395,
"s": 6382,
"text": " Manoj Kumar"
},
{
"code": null,
"e": 6427,
"s": 6395,
"text": "\n 7 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 6440,
"s": 6427,
"text": " Zach Miller"
},
{
"code": null,
"e": 6473,
"s": 6440,
"text": "\n 54 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 6487,
"s": 6473,
"text": " Sasha Miller"
},
{
"code": null,
"e": 6494,
"s": 6487,
"text": " Print"
},
{
"code": null,
"e": 6505,
"s": 6494,
"text": " Add Notes"
}
] |
Vector Class in Java
|
07 Jul, 2022
The Vector class implements a growable array of objects. Vectors fall in legacy classes, but now it is fully compatible with collections. It is found in java.util package and implement the List interface, so we can use all the methods of the List interface as shown below as follows:
Vector implements a dynamic array which means it can grow or shrink as required. Like an array, it contains components that can be accessed using an integer index.
They are very similar to ArrayList, but Vector is synchronized and has some legacy methods that the collection framework does not contain.
It also maintains an insertion order like an ArrayList. Still, it is rarely used in a non-thread environment as it is synchronized, and due to this, it gives a poor performance in adding, searching, deleting, and updating its elements.
The Iterators returned by the Vector class are fail-fast. In the case of concurrent modification, it fails and throws the ConcurrentModificationException.
Syntax:
public class Vector<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, Serializable
Here, E is the type of element.
It extends AbstractList and implements List interfaces.
It implements Serializable, Cloneable, Iterable<E>, Collection<E>, List<E>, RandomAccess interfaces.
The directly known subclass is Stack.
Important points regarding the Increment of vector capacity are as follows:
If the increment is specified, Vector will expand according to it in each allocation cycle. Still, if the increment is not specified, then the vector’s capacity gets doubled in each allocation cycle. Vector defines three protected data members:
int capacityIncreament: Contains the increment value.
int elementCount: Number of elements currently in vector stored in it.
Object elementData[]: Array that holds the vector is stored in it.
Common Errors in the declaration of Vectors are as follows:
Vector throws an IllegalArgumentException if the InitialSize of the vector defined is negative.
If the specified collection is null, It throws NullPointerException.
1. Vector(): Creates a default vector of the initial capacity is 10.
Vector<E> v = new Vector<E>();
2. Vector(int size): Creates a vector whose initial capacity is specified by size.
Vector<E> v = new Vector<E>(int size);
3. Vector(int size, int incr): Creates a vector whose initial capacity is specified by size and increment is specified by incr. It specifies the number of elements to allocate each time a vector is resized upward.
Vector<E> v = new Vector<E>(int size, int incr);
4. Vector(Collection c): Creates a vector that contains the elements of collection c.
vect
Vector<E> v = new Vector<E>(Collection c);
METHOD
DESCRIPTION
addAll(Collection<?
extends E> c)
addAll(int index,
Collection<? extends E> c)
forEach(Consumer<?
super E> action)
Returns the index of the first occurrence of the specified element in this vector,
or -1 if this vector does not contain the element.
Returns the index of the last occurrence of the specified element in this vector,
or -1 if this vector does not contain the element.
Returns a list iterator over the elements in this list (in proper sequence),
starting at the specified position in the list.
removeRange(int fromIndex,
int toIndex)
Let us first discuss and implement how to create and use a Vector prior to landing upon the methods of this class.
Example:
Java
// Java Program to Demonstrate Working of Vector// Via Creating and Using It // Importing required classesimport java.io.*;import java.util.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Size of the Vector int n = 5; // Declaring the Vector with // initial size n Vector<Integer> v = new Vector<Integer>(n); // Appending new elements at // the end of the vector for (int i = 1; i <= n; i++) v.add(i); // Printing elements System.out.println(v); // Remove element at index 3 v.remove(3); // Displaying the vector // after deletion System.out.println(v); // iterating over vector elements // using for loop for (int i = 0; i < v.size(); i++) // Printing elements one by one System.out.print(v.get(i) + " "); }}
[1, 2, 3, 4, 5]
[1, 2, 3, 5]
1 2 3 5
Note:
If the vector increment is not specified then it’s capacity will be doubled in every increment cycle.
The capacity of a vector cannot be below the size, it may equal to it.
Let us discuss various operations on Vector class that are listed as follows:
Adding elementsUpdating elementsRemoving elementsIterating over elements
Adding elements
Updating elements
Removing elements
Iterating over elements
Operation 1: Adding Elements
In order to add the elements to the Vector, we use the add() method. This method is overloaded to perform multiple operations based on different parameters. They are listed below as follows:
add(Object): This method is used to add an element at the end of the Vector.
add(int index, Object): This method is used to add an element at a specific index in the Vector.
Example:
Java
// Java Program to Add Elements in Vector Class // Importing required classesimport java.io.*;import java.util.*; // Main class// AddElementsToVectorclass GFG { // Main driver method public static void main(String[] arg) { // Case 1 // Creating a default vector Vector v1 = new Vector(); // Adding custom elements // using add() method v1.add(1); v1.add(2); v1.add("geeks"); v1.add("forGeeks"); v1.add(3); // Printing the vector elements to the console System.out.println("Vector v1 is " + v1); // Case 2 // Creating generic vector Vector<Integer> v2 = new Vector<Integer>(); // Adding custom elements // using add() method v2.add(1); v2.add(2); v2.add(3); // Printing the vector elements to the console System.out.println("Vector v2 is " + v2); }}
Output:
Vector v1 is [1, 2, geeks, forGeeks, 3]
Vector v2 is [1, 2, 3]
Operation 2: Updating Elements
After adding the elements, if we wish to change the element, it can be done using the set() method. Since a Vector is indexed, the element which we wish to change is referenced by the index of the element. Therefore, this method takes an index and the updated element to be inserted at that index.
Example
Java
// Java code to change the// elements in vector class import java.util.*; public class UpdatingVector { public static void main(String args[]) { // Creating an empty Vector Vector<Integer> vec_tor = new Vector<Integer>(); // Use add() method to add elements in the vector vec_tor.add(12); vec_tor.add(23); vec_tor.add(22); vec_tor.add(10); vec_tor.add(20); // Displaying the Vector System.out.println("Vector: " + vec_tor); // Using set() method to replace 12 with 21 System.out.println("The Object that is replaced is: " + vec_tor.set(0, 21)); // Using set() method to replace 20 with 50 System.out.println("The Object that is replaced is: " + vec_tor.set(4, 50)); // Displaying the modified vector System.out.println("The new Vector is:" + vec_tor); } }
Vector: [12, 23, 22, 10, 20]
The Object that is replaced is: 12
The Object that is replaced is: 20
The new Vector is:[21, 23, 22, 10, 50]
Operation 3: Removing Elements
In order to remove an element from a Vector, we can use the remove() method. This method is overloaded to perform multiple operations based on different parameters. They are:
remove(Object): This method is used to remove an object from the Vector. If there are multiple such objects, then the first occurrence of the object is removed.
remove(int index): Since a Vector is indexed, this method takes an integer value which simply removes the element present at that specific index in the Vector. After removing the element, all the elements are moved to the left to fill the space and the indices of the objects are updated.
Example
Java
// Java code illustrating the removal// of elements from vector import java.util.*;import java.io.*; class RemovingElementsFromVector { public static void main(String[] arg) { // create default vector of capacity 10 Vector v = new Vector(); // Add elements using add() method v.add(1); v.add(2); v.add("Geeks"); v.add("forGeeks"); v.add(4); // removing first occurrence element at 1 v.remove(1); // checking vector System.out.println("after removal: " + v); }}
Output:
after removal: [1, Geeks, forGeeks, 4]
Operation 4: Iterating the Vector
There are multiple ways to iterate through the Vector. The most famous ways are by using the basic for loop in combination with a get() method to get the element at a specific index and the advanced for a loop.
Example
Java
// Java program to iterate the elements// in a Vector import java.util.*; public class IteratingVector { public static void main(String args[]) { // create an instance of vector Vector<String> v = new Vector<>(); // Add elements using add() method v.add("Geeks"); v.add("Geeks"); v.add(1, "For"); // Using the Get method and the // for loop for (int i = 0; i < v.size(); i++) { System.out.print(v.get(i) + " "); } System.out.println(); // Using the for each loop for (String str : v) System.out.print(str + " "); }}
Geeks For Geeks
Geeks For Geeks
Note: Do give a read to the ArrayList vs Vector class in Java to grasp it better.
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 review-team@geeksforgeeks.org. 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.
anmol bhatnagar
ManasChhabra2
yashas6a
Ganeshchowdharysadanala
solankimayank
nishkarshgandhi
sumitgumber28
kothavvsaakash
Java - util package
Java-Collections
Java-Vector
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Split() String method in Java with examples
Arrays.sort() in Java with examples
Reverse a string in Java
How to iterate any Map in Java
Stream In Java
Singleton Class in Java
Initialize an ArrayList in Java
Initializing a List in Java
Generics in Java
Java Programming Examples
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n07 Jul, 2022"
},
{
"code": null,
"e": 336,
"s": 52,
"text": "The Vector class implements a growable array of objects. Vectors fall in legacy classes, but now it is fully compatible with collections. It is found in java.util package and implement the List interface, so we can use all the methods of the List interface as shown below as follows:"
},
{
"code": null,
"e": 500,
"s": 336,
"text": "Vector implements a dynamic array which means it can grow or shrink as required. Like an array, it contains components that can be accessed using an integer index."
},
{
"code": null,
"e": 639,
"s": 500,
"text": "They are very similar to ArrayList, but Vector is synchronized and has some legacy methods that the collection framework does not contain."
},
{
"code": null,
"e": 875,
"s": 639,
"text": "It also maintains an insertion order like an ArrayList. Still, it is rarely used in a non-thread environment as it is synchronized, and due to this, it gives a poor performance in adding, searching, deleting, and updating its elements."
},
{
"code": null,
"e": 1030,
"s": 875,
"text": "The Iterators returned by the Vector class are fail-fast. In the case of concurrent modification, it fails and throws the ConcurrentModificationException."
},
{
"code": null,
"e": 1039,
"s": 1030,
"text": "Syntax: "
},
{
"code": null,
"e": 1144,
"s": 1039,
"text": "public class Vector<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, Serializable"
},
{
"code": null,
"e": 1176,
"s": 1144,
"text": "Here, E is the type of element."
},
{
"code": null,
"e": 1232,
"s": 1176,
"text": "It extends AbstractList and implements List interfaces."
},
{
"code": null,
"e": 1333,
"s": 1232,
"text": "It implements Serializable, Cloneable, Iterable<E>, Collection<E>, List<E>, RandomAccess interfaces."
},
{
"code": null,
"e": 1371,
"s": 1333,
"text": "The directly known subclass is Stack."
},
{
"code": null,
"e": 1447,
"s": 1371,
"text": "Important points regarding the Increment of vector capacity are as follows:"
},
{
"code": null,
"e": 1692,
"s": 1447,
"text": "If the increment is specified, Vector will expand according to it in each allocation cycle. Still, if the increment is not specified, then the vector’s capacity gets doubled in each allocation cycle. Vector defines three protected data members:"
},
{
"code": null,
"e": 1746,
"s": 1692,
"text": "int capacityIncreament: Contains the increment value."
},
{
"code": null,
"e": 1817,
"s": 1746,
"text": "int elementCount: Number of elements currently in vector stored in it."
},
{
"code": null,
"e": 1884,
"s": 1817,
"text": "Object elementData[]: Array that holds the vector is stored in it."
},
{
"code": null,
"e": 1944,
"s": 1884,
"text": "Common Errors in the declaration of Vectors are as follows:"
},
{
"code": null,
"e": 2040,
"s": 1944,
"text": "Vector throws an IllegalArgumentException if the InitialSize of the vector defined is negative."
},
{
"code": null,
"e": 2110,
"s": 2040,
"text": "If the specified collection is null, It throws NullPointerException. "
},
{
"code": null,
"e": 2179,
"s": 2110,
"text": "1. Vector(): Creates a default vector of the initial capacity is 10."
},
{
"code": null,
"e": 2210,
"s": 2179,
"text": "Vector<E> v = new Vector<E>();"
},
{
"code": null,
"e": 2293,
"s": 2210,
"text": "2. Vector(int size): Creates a vector whose initial capacity is specified by size."
},
{
"code": null,
"e": 2332,
"s": 2293,
"text": "Vector<E> v = new Vector<E>(int size);"
},
{
"code": null,
"e": 2546,
"s": 2332,
"text": "3. Vector(int size, int incr): Creates a vector whose initial capacity is specified by size and increment is specified by incr. It specifies the number of elements to allocate each time a vector is resized upward."
},
{
"code": null,
"e": 2595,
"s": 2546,
"text": "Vector<E> v = new Vector<E>(int size, int incr);"
},
{
"code": null,
"e": 2681,
"s": 2595,
"text": "4. Vector(Collection c): Creates a vector that contains the elements of collection c."
},
{
"code": null,
"e": 2686,
"s": 2681,
"text": "vect"
},
{
"code": null,
"e": 2729,
"s": 2686,
"text": "Vector<E> v = new Vector<E>(Collection c);"
},
{
"code": null,
"e": 2736,
"s": 2729,
"text": "METHOD"
},
{
"code": null,
"e": 2748,
"s": 2736,
"text": "DESCRIPTION"
},
{
"code": null,
"e": 2768,
"s": 2748,
"text": "addAll(Collection<?"
},
{
"code": null,
"e": 2782,
"s": 2768,
"text": "extends E> c)"
},
{
"code": null,
"e": 2800,
"s": 2782,
"text": "addAll(int index,"
},
{
"code": null,
"e": 2827,
"s": 2800,
"text": "Collection<? extends E> c)"
},
{
"code": null,
"e": 2846,
"s": 2827,
"text": "forEach(Consumer<?"
},
{
"code": null,
"e": 2863,
"s": 2846,
"text": "super E> action)"
},
{
"code": null,
"e": 2946,
"s": 2863,
"text": "Returns the index of the first occurrence of the specified element in this vector,"
},
{
"code": null,
"e": 2997,
"s": 2946,
"text": "or -1 if this vector does not contain the element."
},
{
"code": null,
"e": 3079,
"s": 2997,
"text": "Returns the index of the last occurrence of the specified element in this vector,"
},
{
"code": null,
"e": 3130,
"s": 3079,
"text": "or -1 if this vector does not contain the element."
},
{
"code": null,
"e": 3207,
"s": 3130,
"text": "Returns a list iterator over the elements in this list (in proper sequence),"
},
{
"code": null,
"e": 3255,
"s": 3207,
"text": "starting at the specified position in the list."
},
{
"code": null,
"e": 3282,
"s": 3255,
"text": "removeRange(int fromIndex,"
},
{
"code": null,
"e": 3295,
"s": 3282,
"text": "int toIndex)"
},
{
"code": null,
"e": 3410,
"s": 3295,
"text": "Let us first discuss and implement how to create and use a Vector prior to landing upon the methods of this class."
},
{
"code": null,
"e": 3419,
"s": 3410,
"text": "Example:"
},
{
"code": null,
"e": 3424,
"s": 3419,
"text": "Java"
},
{
"code": "// Java Program to Demonstrate Working of Vector// Via Creating and Using It // Importing required classesimport java.io.*;import java.util.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Size of the Vector int n = 5; // Declaring the Vector with // initial size n Vector<Integer> v = new Vector<Integer>(n); // Appending new elements at // the end of the vector for (int i = 1; i <= n; i++) v.add(i); // Printing elements System.out.println(v); // Remove element at index 3 v.remove(3); // Displaying the vector // after deletion System.out.println(v); // iterating over vector elements // using for loop for (int i = 0; i < v.size(); i++) // Printing elements one by one System.out.print(v.get(i) + \" \"); }}",
"e": 4369,
"s": 3424,
"text": null
},
{
"code": null,
"e": 4406,
"s": 4369,
"text": "[1, 2, 3, 4, 5]\n[1, 2, 3, 5]\n1 2 3 5"
},
{
"code": null,
"e": 4412,
"s": 4406,
"text": "Note:"
},
{
"code": null,
"e": 4514,
"s": 4412,
"text": "If the vector increment is not specified then it’s capacity will be doubled in every increment cycle."
},
{
"code": null,
"e": 4585,
"s": 4514,
"text": "The capacity of a vector cannot be below the size, it may equal to it."
},
{
"code": null,
"e": 4663,
"s": 4585,
"text": "Let us discuss various operations on Vector class that are listed as follows:"
},
{
"code": null,
"e": 4736,
"s": 4663,
"text": "Adding elementsUpdating elementsRemoving elementsIterating over elements"
},
{
"code": null,
"e": 4752,
"s": 4736,
"text": "Adding elements"
},
{
"code": null,
"e": 4770,
"s": 4752,
"text": "Updating elements"
},
{
"code": null,
"e": 4788,
"s": 4770,
"text": "Removing elements"
},
{
"code": null,
"e": 4812,
"s": 4788,
"text": "Iterating over elements"
},
{
"code": null,
"e": 4841,
"s": 4812,
"text": "Operation 1: Adding Elements"
},
{
"code": null,
"e": 5032,
"s": 4841,
"text": "In order to add the elements to the Vector, we use the add() method. This method is overloaded to perform multiple operations based on different parameters. They are listed below as follows:"
},
{
"code": null,
"e": 5109,
"s": 5032,
"text": "add(Object): This method is used to add an element at the end of the Vector."
},
{
"code": null,
"e": 5206,
"s": 5109,
"text": "add(int index, Object): This method is used to add an element at a specific index in the Vector."
},
{
"code": null,
"e": 5215,
"s": 5206,
"text": "Example:"
},
{
"code": null,
"e": 5220,
"s": 5215,
"text": "Java"
},
{
"code": "// Java Program to Add Elements in Vector Class // Importing required classesimport java.io.*;import java.util.*; // Main class// AddElementsToVectorclass GFG { // Main driver method public static void main(String[] arg) { // Case 1 // Creating a default vector Vector v1 = new Vector(); // Adding custom elements // using add() method v1.add(1); v1.add(2); v1.add(\"geeks\"); v1.add(\"forGeeks\"); v1.add(3); // Printing the vector elements to the console System.out.println(\"Vector v1 is \" + v1); // Case 2 // Creating generic vector Vector<Integer> v2 = new Vector<Integer>(); // Adding custom elements // using add() method v2.add(1); v2.add(2); v2.add(3); // Printing the vector elements to the console System.out.println(\"Vector v2 is \" + v2); }}",
"e": 6151,
"s": 5220,
"text": null
},
{
"code": null,
"e": 6160,
"s": 6151,
"text": " Output:"
},
{
"code": null,
"e": 6225,
"s": 6162,
"text": "Vector v1 is [1, 2, geeks, forGeeks, 3]\nVector v2 is [1, 2, 3]"
},
{
"code": null,
"e": 6256,
"s": 6225,
"text": "Operation 2: Updating Elements"
},
{
"code": null,
"e": 6554,
"s": 6256,
"text": "After adding the elements, if we wish to change the element, it can be done using the set() method. Since a Vector is indexed, the element which we wish to change is referenced by the index of the element. Therefore, this method takes an index and the updated element to be inserted at that index."
},
{
"code": null,
"e": 6562,
"s": 6554,
"text": "Example"
},
{
"code": null,
"e": 6567,
"s": 6562,
"text": "Java"
},
{
"code": "// Java code to change the// elements in vector class import java.util.*; public class UpdatingVector { public static void main(String args[]) { // Creating an empty Vector Vector<Integer> vec_tor = new Vector<Integer>(); // Use add() method to add elements in the vector vec_tor.add(12); vec_tor.add(23); vec_tor.add(22); vec_tor.add(10); vec_tor.add(20); // Displaying the Vector System.out.println(\"Vector: \" + vec_tor); // Using set() method to replace 12 with 21 System.out.println(\"The Object that is replaced is: \" + vec_tor.set(0, 21)); // Using set() method to replace 20 with 50 System.out.println(\"The Object that is replaced is: \" + vec_tor.set(4, 50)); // Displaying the modified vector System.out.println(\"The new Vector is:\" + vec_tor); } } ",
"e": 7527,
"s": 6567,
"text": null
},
{
"code": null,
"e": 7665,
"s": 7527,
"text": "Vector: [12, 23, 22, 10, 20]\nThe Object that is replaced is: 12\nThe Object that is replaced is: 20\nThe new Vector is:[21, 23, 22, 10, 50]"
},
{
"code": null,
"e": 7696,
"s": 7665,
"text": "Operation 3: Removing Elements"
},
{
"code": null,
"e": 7871,
"s": 7696,
"text": "In order to remove an element from a Vector, we can use the remove() method. This method is overloaded to perform multiple operations based on different parameters. They are:"
},
{
"code": null,
"e": 8032,
"s": 7871,
"text": "remove(Object): This method is used to remove an object from the Vector. If there are multiple such objects, then the first occurrence of the object is removed."
},
{
"code": null,
"e": 8321,
"s": 8032,
"text": "remove(int index): Since a Vector is indexed, this method takes an integer value which simply removes the element present at that specific index in the Vector. After removing the element, all the elements are moved to the left to fill the space and the indices of the objects are updated."
},
{
"code": null,
"e": 8329,
"s": 8321,
"text": "Example"
},
{
"code": null,
"e": 8334,
"s": 8329,
"text": "Java"
},
{
"code": "// Java code illustrating the removal// of elements from vector import java.util.*;import java.io.*; class RemovingElementsFromVector { public static void main(String[] arg) { // create default vector of capacity 10 Vector v = new Vector(); // Add elements using add() method v.add(1); v.add(2); v.add(\"Geeks\"); v.add(\"forGeeks\"); v.add(4); // removing first occurrence element at 1 v.remove(1); // checking vector System.out.println(\"after removal: \" + v); }}",
"e": 8904,
"s": 8334,
"text": null
},
{
"code": null,
"e": 8913,
"s": 8904,
"text": " Output:"
},
{
"code": null,
"e": 8952,
"s": 8913,
"text": "after removal: [1, Geeks, forGeeks, 4]"
},
{
"code": null,
"e": 8986,
"s": 8952,
"text": "Operation 4: Iterating the Vector"
},
{
"code": null,
"e": 9197,
"s": 8986,
"text": "There are multiple ways to iterate through the Vector. The most famous ways are by using the basic for loop in combination with a get() method to get the element at a specific index and the advanced for a loop."
},
{
"code": null,
"e": 9205,
"s": 9197,
"text": "Example"
},
{
"code": null,
"e": 9210,
"s": 9205,
"text": "Java"
},
{
"code": "// Java program to iterate the elements// in a Vector import java.util.*; public class IteratingVector { public static void main(String args[]) { // create an instance of vector Vector<String> v = new Vector<>(); // Add elements using add() method v.add(\"Geeks\"); v.add(\"Geeks\"); v.add(1, \"For\"); // Using the Get method and the // for loop for (int i = 0; i < v.size(); i++) { System.out.print(v.get(i) + \" \"); } System.out.println(); // Using the for each loop for (String str : v) System.out.print(str + \" \"); }}",
"e": 9866,
"s": 9210,
"text": null
},
{
"code": null,
"e": 9899,
"s": 9866,
"text": "Geeks For Geeks \nGeeks For Geeks"
},
{
"code": null,
"e": 9981,
"s": 9899,
"text": "Note: Do give a read to the ArrayList vs Vector class in Java to grasp it better."
},
{
"code": null,
"e": 10280,
"s": 9981,
"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 review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. "
},
{
"code": null,
"e": 10405,
"s": 10280,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 10421,
"s": 10405,
"text": "anmol bhatnagar"
},
{
"code": null,
"e": 10435,
"s": 10421,
"text": "ManasChhabra2"
},
{
"code": null,
"e": 10444,
"s": 10435,
"text": "yashas6a"
},
{
"code": null,
"e": 10468,
"s": 10444,
"text": "Ganeshchowdharysadanala"
},
{
"code": null,
"e": 10482,
"s": 10468,
"text": "solankimayank"
},
{
"code": null,
"e": 10498,
"s": 10482,
"text": "nishkarshgandhi"
},
{
"code": null,
"e": 10512,
"s": 10498,
"text": "sumitgumber28"
},
{
"code": null,
"e": 10527,
"s": 10512,
"text": "kothavvsaakash"
},
{
"code": null,
"e": 10547,
"s": 10527,
"text": "Java - util package"
},
{
"code": null,
"e": 10564,
"s": 10547,
"text": "Java-Collections"
},
{
"code": null,
"e": 10576,
"s": 10564,
"text": "Java-Vector"
},
{
"code": null,
"e": 10581,
"s": 10576,
"text": "Java"
},
{
"code": null,
"e": 10586,
"s": 10581,
"text": "Java"
},
{
"code": null,
"e": 10603,
"s": 10586,
"text": "Java-Collections"
},
{
"code": null,
"e": 10701,
"s": 10603,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 10745,
"s": 10701,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 10781,
"s": 10745,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 10806,
"s": 10781,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 10837,
"s": 10806,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 10852,
"s": 10837,
"text": "Stream In Java"
},
{
"code": null,
"e": 10876,
"s": 10852,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 10908,
"s": 10876,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 10936,
"s": 10908,
"text": "Initializing a List in Java"
},
{
"code": null,
"e": 10953,
"s": 10936,
"text": "Generics in Java"
}
] |
How to remove numbers from string in Python – Pandas?
|
25 Feb, 2021
In this article, let’s see how to remove numbers from string in Pandas. Currently, we will be using only the .csv file for demonstration purposes, but the process is the same for other types of files. The function read_csv() is used to read CSV files.
Syntax:
for the method ‘replace()’:
str.replace(old, new)
Here str. replace() will return a string in which the parameter ‘old’ will be replaced by the parameter ‘new’. Now let us see through coding how to remove numbers from strings in the pandas data frame.
Example 1:
Python3
# codeimport pandas as pd # creating dataframedf = pd.DataFrame.from_dict({'Name': ['May21', 'James', 'Adi22', 'Hello', 'Girl90'], 'Age': [25, 15, 20, 33, 42], 'Income': [21321, 12311, 25000, 32454, 65465]}) # removing numbers from strings of speciafied # column, here 'Name'df['Name'] = df['Name'].str.replace('\d+', '') # display output with numbers removed from # required stringsprint(df)
Output:
Example 2:
Python3
# codeimport pandas as pd # creating dataframedf = pd.DataFrame.from_dict({'Name': ['rohan21', 'Jelly', 'Alok22', 'Hey65', 'boy92'], 'Age': [24, 25, 10, 73, 92], 'Income': [28421, 14611, 28200, 45454, 66565]}) # removing numbers from strings of speciafied # column, here 'Name'df['Name'] = df['Name'].str.replace('\d+', '') # display output with numbers removed from # required stringsprint(df)
Output:
Picked
Python pandas-dataFrame
Python-pandas
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n25 Feb, 2021"
},
{
"code": null,
"e": 306,
"s": 54,
"text": "In this article, let’s see how to remove numbers from string in Pandas. Currently, we will be using only the .csv file for demonstration purposes, but the process is the same for other types of files. The function read_csv() is used to read CSV files."
},
{
"code": null,
"e": 314,
"s": 306,
"text": "Syntax:"
},
{
"code": null,
"e": 343,
"s": 314,
"text": " for the method ‘replace()’:"
},
{
"code": null,
"e": 365,
"s": 343,
"text": "str.replace(old, new)"
},
{
"code": null,
"e": 567,
"s": 365,
"text": "Here str. replace() will return a string in which the parameter ‘old’ will be replaced by the parameter ‘new’. Now let us see through coding how to remove numbers from strings in the pandas data frame."
},
{
"code": null,
"e": 578,
"s": 567,
"text": "Example 1:"
},
{
"code": null,
"e": 586,
"s": 578,
"text": "Python3"
},
{
"code": "# codeimport pandas as pd # creating dataframedf = pd.DataFrame.from_dict({'Name': ['May21', 'James', 'Adi22', 'Hello', 'Girl90'], 'Age': [25, 15, 20, 33, 42], 'Income': [21321, 12311, 25000, 32454, 65465]}) # removing numbers from strings of speciafied # column, here 'Name'df['Name'] = df['Name'].str.replace('\\d+', '') # display output with numbers removed from # required stringsprint(df)",
"e": 1246,
"s": 586,
"text": null
},
{
"code": null,
"e": 1254,
"s": 1246,
"text": "Output:"
},
{
"code": null,
"e": 1265,
"s": 1254,
"text": "Example 2:"
},
{
"code": null,
"e": 1273,
"s": 1265,
"text": "Python3"
},
{
"code": "# codeimport pandas as pd # creating dataframedf = pd.DataFrame.from_dict({'Name': ['rohan21', 'Jelly', 'Alok22', 'Hey65', 'boy92'], 'Age': [24, 25, 10, 73, 92], 'Income': [28421, 14611, 28200, 45454, 66565]}) # removing numbers from strings of speciafied # column, here 'Name'df['Name'] = df['Name'].str.replace('\\d+', '') # display output with numbers removed from # required stringsprint(df)",
"e": 1904,
"s": 1273,
"text": null
},
{
"code": null,
"e": 1912,
"s": 1904,
"text": "Output:"
},
{
"code": null,
"e": 1919,
"s": 1912,
"text": "Picked"
},
{
"code": null,
"e": 1943,
"s": 1919,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 1957,
"s": 1943,
"text": "Python-pandas"
},
{
"code": null,
"e": 1981,
"s": 1957,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 1988,
"s": 1981,
"text": "Python"
},
{
"code": null,
"e": 2007,
"s": 1988,
"text": "Technical Scripter"
},
{
"code": null,
"e": 2105,
"s": 2007,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2137,
"s": 2105,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2164,
"s": 2137,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2185,
"s": 2164,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2208,
"s": 2185,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2264,
"s": 2208,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2295,
"s": 2264,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2337,
"s": 2295,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 2379,
"s": 2337,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 2418,
"s": 2379,
"text": "Python | Get unique values from a list"
}
] |
HTML | Quotations
|
28 Jun, 2022
The Quotation elements in HTML are used to insert quoted texts in a web page, that is portion of texts different from the normal texts in the web page. Below are some of the most used quotation elements of HTML:
<q> element: The <q> element is used to set a set of text inside the quotation marks. It has both opening and closing tags.
<q> element: The <q> element is used to set a set of text inside the quotation marks. It has both opening and closing tags.
Example:
HTML
<!DOCTYPE html><html><head> <title>Quotations</title></head><body> <h3>GeeksforGeeks</h3> <p>The quick brown fox jumps over the lazy dog<br></p> <!--Inside quotes--> <p><q>The quick brown fox jumps over the lazy dog</q></p> </body></html>
Output:
2. <blockquote> element: The <blockquote> element is also used for quotations in a different way. Instead of putting the text in quotes, it adds space before the start of the sentence, with this tag we can also indent the start of the new paragraph. It has both opening and closing tags.
Example:
HTML
<!DOCTYPE html><html><head> <title>Blockquote</title></head><body> <h3>GeeksforGeeks</h3> <p>The quick brown fox jumps over the lazy dog<br></p> <!--Inside blockquotes--> <p><blockquote>The quick brown fox jumpsover the lazy dog</blockquote></p> </body></html>
Output:
3. <address> element: Using the <address> element, we can define an address in a webpage and the text put inside the address tag will be emphasized. Usually line break is added before and after the address tag and content inside this tag is generally renders in italic format. It helps screen reader also It has both opening and closing tags.
Example:
HTML
<!DOCTYPE html><html><head> <title>Address</title></head><body> <h3>GeeksforGeeks</h3> <address> <p>Address:<br> 710-B, Advant Navis Business Park,<br> Sector-142, Noida Uttar Pradesh – 201305</p> </address></body></html>
Output:
4. <abbr> element: The <abbr> element is used to define a text as an acronym or abbreviations. The title attribute can be used to show the full version of the abbreviation/acronym when you hover the mouse over the <abbr> element. It has both opening and closing tags. This is useful for browsers and search engines.
Example:
HTML
<!DOCTYPE html><html><head> <title>Abbreviations</title></head><body> <h3>GeeksforGeeks</h3> <!--Here the marked text is the acronym--> <p>Welcome to <abbr title="GeeksforGeeks">GfG</abbr></p> </body></html>
Output:
5. <bdo> element: The <bdo> element is used to define a bidirectional override which means that, the text written from right to left or left to right. It has both opening and closing tags. It is used to over-ride the current text direction. It takes an attribute “rtl” to display the text from right to left.
Example:
HTML
<!DOCTYPE html><html><head> <title>Bidirectional</title></head><body> <h3>GeeksforGeeks</h3> <!--Normal text--> <p>The quick brown fox jumps over the lazy dog<br></p> <!--Inside <bdo> tag--> <p><bdo dir="rtl">The quick brown fox jumps over the lazy dog</bdo></p> </body></html>
Output:
6. <cite> element: This element is used to define a title of a work and emphasizes a text.
Example:
HTML
<!DOCTYPE html><html><head> <title>Cite</title></head><body> <h3>GeeksforGeeks</h3> <!--The title is kept in cite tag--> <p>The <cite>GeeksforGeeks</cite> is the best site to<br> to search for articles and practice problems.</p> </body></html>
Output:
Supported Browser:
Google Chrome
Microsoft Edge
Firefox
Opera
Safari
davidhandl
JyotiGoyal1
simranarora5sos
ysachin2314
sanayush1357
lucidcoder121
prateek7860chauhan
HTML and XML
HTML-Basics
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n28 Jun, 2022"
},
{
"code": null,
"e": 264,
"s": 52,
"text": "The Quotation elements in HTML are used to insert quoted texts in a web page, that is portion of texts different from the normal texts in the web page. Below are some of the most used quotation elements of HTML:"
},
{
"code": null,
"e": 389,
"s": 264,
"text": "<q> element: The <q> element is used to set a set of text inside the quotation marks. It has both opening and closing tags. "
},
{
"code": null,
"e": 514,
"s": 389,
"text": "<q> element: The <q> element is used to set a set of text inside the quotation marks. It has both opening and closing tags. "
},
{
"code": null,
"e": 524,
"s": 514,
"text": "Example: "
},
{
"code": null,
"e": 529,
"s": 524,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><head> <title>Quotations</title></head><body> <h3>GeeksforGeeks</h3> <p>The quick brown fox jumps over the lazy dog<br></p> <!--Inside quotes--> <p><q>The quick brown fox jumps over the lazy dog</q></p> </body></html>",
"e": 790,
"s": 529,
"text": null
},
{
"code": null,
"e": 798,
"s": 790,
"text": "Output:"
},
{
"code": null,
"e": 1090,
"s": 798,
"text": " 2. <blockquote> element: The <blockquote> element is also used for quotations in a different way. Instead of putting the text in quotes, it adds space before the start of the sentence, with this tag we can also indent the start of the new paragraph. It has both opening and closing tags. "
},
{
"code": null,
"e": 1100,
"s": 1090,
"text": "Example: "
},
{
"code": null,
"e": 1105,
"s": 1100,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><head> <title>Blockquote</title></head><body> <h3>GeeksforGeeks</h3> <p>The quick brown fox jumps over the lazy dog<br></p> <!--Inside blockquotes--> <p><blockquote>The quick brown fox jumpsover the lazy dog</blockquote></p> </body></html>",
"e": 1388,
"s": 1105,
"text": null
},
{
"code": null,
"e": 1396,
"s": 1388,
"text": "Output:"
},
{
"code": null,
"e": 1745,
"s": 1398,
"text": " 3. <address> element: Using the <address> element, we can define an address in a webpage and the text put inside the address tag will be emphasized. Usually line break is added before and after the address tag and content inside this tag is generally renders in italic format. It helps screen reader also It has both opening and closing tags. "
},
{
"code": null,
"e": 1755,
"s": 1745,
"text": "Example: "
},
{
"code": null,
"e": 1760,
"s": 1755,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><head> <title>Address</title></head><body> <h3>GeeksforGeeks</h3> <address> <p>Address:<br> 710-B, Advant Navis Business Park,<br> Sector-142, Noida Uttar Pradesh – 201305</p> </address></body></html>",
"e": 2007,
"s": 1760,
"text": null
},
{
"code": null,
"e": 2015,
"s": 2007,
"text": "Output:"
},
{
"code": null,
"e": 2337,
"s": 2017,
"text": " 4. <abbr> element: The <abbr> element is used to define a text as an acronym or abbreviations. The title attribute can be used to show the full version of the abbreviation/acronym when you hover the mouse over the <abbr> element. It has both opening and closing tags. This is useful for browsers and search engines. "
},
{
"code": null,
"e": 2347,
"s": 2337,
"text": "Example: "
},
{
"code": null,
"e": 2352,
"s": 2347,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><head> <title>Abbreviations</title></head><body> <h3>GeeksforGeeks</h3> <!--Here the marked text is the acronym--> <p>Welcome to <abbr title=\"GeeksforGeeks\">GfG</abbr></p> </body></html>",
"e": 2575,
"s": 2352,
"text": null
},
{
"code": null,
"e": 2583,
"s": 2575,
"text": "Output:"
},
{
"code": null,
"e": 2898,
"s": 2585,
"text": " 5. <bdo> element: The <bdo> element is used to define a bidirectional override which means that, the text written from right to left or left to right. It has both opening and closing tags. It is used to over-ride the current text direction. It takes an attribute “rtl” to display the text from right to left. "
},
{
"code": null,
"e": 2908,
"s": 2898,
"text": "Example: "
},
{
"code": null,
"e": 2913,
"s": 2908,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><head> <title>Bidirectional</title></head><body> <h3>GeeksforGeeks</h3> <!--Normal text--> <p>The quick brown fox jumps over the lazy dog<br></p> <!--Inside <bdo> tag--> <p><bdo dir=\"rtl\">The quick brown fox jumps over the lazy dog</bdo></p> </body></html>",
"e": 3219,
"s": 2913,
"text": null
},
{
"code": null,
"e": 3227,
"s": 3219,
"text": "Output:"
},
{
"code": null,
"e": 3324,
"s": 3229,
"text": " 6. <cite> element: This element is used to define a title of a work and emphasizes a text. "
},
{
"code": null,
"e": 3334,
"s": 3324,
"text": "Example: "
},
{
"code": null,
"e": 3339,
"s": 3334,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><head> <title>Cite</title></head><body> <h3>GeeksforGeeks</h3> <!--The title is kept in cite tag--> <p>The <cite>GeeksforGeeks</cite> is the best site to<br> to search for articles and practice problems.</p> </body></html>",
"e": 3601,
"s": 3339,
"text": null
},
{
"code": null,
"e": 3609,
"s": 3601,
"text": "Output:"
},
{
"code": null,
"e": 3628,
"s": 3609,
"text": "Supported Browser:"
},
{
"code": null,
"e": 3642,
"s": 3628,
"text": "Google Chrome"
},
{
"code": null,
"e": 3657,
"s": 3642,
"text": "Microsoft Edge"
},
{
"code": null,
"e": 3665,
"s": 3657,
"text": "Firefox"
},
{
"code": null,
"e": 3671,
"s": 3665,
"text": "Opera"
},
{
"code": null,
"e": 3678,
"s": 3671,
"text": "Safari"
},
{
"code": null,
"e": 3689,
"s": 3678,
"text": "davidhandl"
},
{
"code": null,
"e": 3701,
"s": 3689,
"text": "JyotiGoyal1"
},
{
"code": null,
"e": 3717,
"s": 3701,
"text": "simranarora5sos"
},
{
"code": null,
"e": 3729,
"s": 3717,
"text": "ysachin2314"
},
{
"code": null,
"e": 3742,
"s": 3729,
"text": "sanayush1357"
},
{
"code": null,
"e": 3756,
"s": 3742,
"text": "lucidcoder121"
},
{
"code": null,
"e": 3775,
"s": 3756,
"text": "prateek7860chauhan"
},
{
"code": null,
"e": 3788,
"s": 3775,
"text": "HTML and XML"
},
{
"code": null,
"e": 3800,
"s": 3788,
"text": "HTML-Basics"
},
{
"code": null,
"e": 3805,
"s": 3800,
"text": "HTML"
},
{
"code": null,
"e": 3822,
"s": 3805,
"text": "Web Technologies"
},
{
"code": null,
"e": 3827,
"s": 3822,
"text": "HTML"
}
] |
ML | Using SVM to perform classification on a non-linear dataset
|
15 Jan, 2019
Prerequisite: Support Vector Machines
Definition of a hyperplane and SVM classifier:For a linearly separable dataset having n features (thereby needing n dimensions for representation), a hyperplane is basically an (n – 1) dimensional subspace used for separating the dataset into two sets, each set containing data points belonging to a different class. For example, for a dataset having two features X and Y (therefore lying in a 2-dimensional space), the separating hyperplane is a line (a 1-dimensional subspace). Similarly, for a dataset having 3-dimensions, we have a 2-dimensional separating hyperplane, and so on.In machine learning, Support Vector Machine (SVM) is a non-probabilistic, linear, binary classifier used for classifying data by learning a hyperplane separating the data.
Classifying a non-linearly separable dataset using a SVM – a linear classifier:As mentioned above SVM is a linear classifier which learns an (n – 1)-dimensional classifier for classification of data into two classes. However, it can be used for classifying a non-linear dataset. This can be done by projecting the dataset into a higher dimension in which it is linearly separable!
To get a better understanding, let’s consider circles dataset.
# importing librariesimport numpy as npimport matplotlib.pyplot as pltfrom sklearn.datasets import make_circlesfrom mpl_toolkits.mplot3d import Axes3D # generating dataX, Y = make_circles(n_samples = 500, noise = 0.02) # visualizing dataplt.scatter(X[:, 0], X[:, 1], c = Y, marker = '.')plt.show()
The dataset is clearly a non-linear dataset and consists of two features (say, X and Y).
In order to use SVM for classifying this data, introduce another feature Z = X2 + Y2 into the dataset. Thus, projecting the 2-dimensional data into 3-dimensional space. The first dimension representing the feature X, second representing Y and third representing Z (which, mathematically, is equal to the radius of the circle of which the point (x, y) is a part of). Now, clearly, for the data shown above, the ‘yellow’ data points belong to a circle of smaller radius and the ‘purple’ data points belong to a circle of larger radius. Thus, the data becomes linearly separable along the Z-axis.
# adding a new dimension to XX1 = X[:, 0].reshape((-1, 1))X2 = X[:, 1].reshape((-1, 1))X3 = (X1**2 + X2**2)X = np.hstack((X, X3)) # visualizing data in higher dimensionfig = plt.figure()axes = fig.add_subplot(111, projection = '3d')axes.scatter(X1, X2, X1**2 + X2**2, c = Y, depthshade = True)plt.show()
Now, we can use SVM (or, for that matter, any other linear classifier) to learn a 2-dimensional separating hyperplane. This is how the hyperplane would look like:
# create support vector classifier using a linear kernelfrom sklearn import svm svc = svm.SVC(kernel = 'linear')svc.fit(X, Y)w = svc.coef_b = svc.intercept_ # plotting the separating hyperplanex1 = X[:, 0].reshape((-1, 1))x2 = X[:, 1].reshape((-1, 1))x1, x2 = np.meshgrid(x1, x2)x3 = -(w[0][0]*x1 + w[0][1]*x2 + b) / w[0][2] fig = plt.figure()axes2 = fig.add_subplot(111, projection = '3d')axes2.scatter(X1, X2, X1**2 + X2**2, c = Y, depthshade = True)axes1 = fig.gca(projection = '3d')axes1.plot_surface(x1, x2, x3, alpha = 0.01)plt.show()
Thus, using a linear classifier we can separate a non-linearly separable dataset.
A brief introduction to kernels in machine learning:In machine learning, a trick known as “kernel trick” is used to learn a linear classifier to classify a non-linear dataset. It transforms the linearly inseparable data into a linearly separable one by projecting it into a higher dimension. A kernel function is applied on each data instance to map the original non-linear data points into some higher dimensional space in which they become linearly separable.
Advanced Computer Subject
Machine Learning
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Reinforcement learning
Fuzzy Logic | Introduction
System Design Tutorial
Getting started with Machine Learning
Game Playing in Artificial Intelligence
Reinforcement learning
What is Information Retrieval?
Support Vector Machine Algorithm
Agents in Artificial Intelligence
Elbow Method for optimal value of k in KMeans
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n15 Jan, 2019"
},
{
"code": null,
"e": 66,
"s": 28,
"text": "Prerequisite: Support Vector Machines"
},
{
"code": null,
"e": 821,
"s": 66,
"text": "Definition of a hyperplane and SVM classifier:For a linearly separable dataset having n features (thereby needing n dimensions for representation), a hyperplane is basically an (n – 1) dimensional subspace used for separating the dataset into two sets, each set containing data points belonging to a different class. For example, for a dataset having two features X and Y (therefore lying in a 2-dimensional space), the separating hyperplane is a line (a 1-dimensional subspace). Similarly, for a dataset having 3-dimensions, we have a 2-dimensional separating hyperplane, and so on.In machine learning, Support Vector Machine (SVM) is a non-probabilistic, linear, binary classifier used for classifying data by learning a hyperplane separating the data."
},
{
"code": null,
"e": 1202,
"s": 821,
"text": "Classifying a non-linearly separable dataset using a SVM – a linear classifier:As mentioned above SVM is a linear classifier which learns an (n – 1)-dimensional classifier for classification of data into two classes. However, it can be used for classifying a non-linear dataset. This can be done by projecting the dataset into a higher dimension in which it is linearly separable!"
},
{
"code": null,
"e": 1265,
"s": 1202,
"text": "To get a better understanding, let’s consider circles dataset."
},
{
"code": "# importing librariesimport numpy as npimport matplotlib.pyplot as pltfrom sklearn.datasets import make_circlesfrom mpl_toolkits.mplot3d import Axes3D # generating dataX, Y = make_circles(n_samples = 500, noise = 0.02) # visualizing dataplt.scatter(X[:, 0], X[:, 1], c = Y, marker = '.')plt.show()",
"e": 1565,
"s": 1265,
"text": null
},
{
"code": null,
"e": 1654,
"s": 1565,
"text": "The dataset is clearly a non-linear dataset and consists of two features (say, X and Y)."
},
{
"code": null,
"e": 2248,
"s": 1654,
"text": "In order to use SVM for classifying this data, introduce another feature Z = X2 + Y2 into the dataset. Thus, projecting the 2-dimensional data into 3-dimensional space. The first dimension representing the feature X, second representing Y and third representing Z (which, mathematically, is equal to the radius of the circle of which the point (x, y) is a part of). Now, clearly, for the data shown above, the ‘yellow’ data points belong to a circle of smaller radius and the ‘purple’ data points belong to a circle of larger radius. Thus, the data becomes linearly separable along the Z-axis."
},
{
"code": "# adding a new dimension to XX1 = X[:, 0].reshape((-1, 1))X2 = X[:, 1].reshape((-1, 1))X3 = (X1**2 + X2**2)X = np.hstack((X, X3)) # visualizing data in higher dimensionfig = plt.figure()axes = fig.add_subplot(111, projection = '3d')axes.scatter(X1, X2, X1**2 + X2**2, c = Y, depthshade = True)plt.show()",
"e": 2553,
"s": 2248,
"text": null
},
{
"code": null,
"e": 2716,
"s": 2553,
"text": "Now, we can use SVM (or, for that matter, any other linear classifier) to learn a 2-dimensional separating hyperplane. This is how the hyperplane would look like:"
},
{
"code": "# create support vector classifier using a linear kernelfrom sklearn import svm svc = svm.SVC(kernel = 'linear')svc.fit(X, Y)w = svc.coef_b = svc.intercept_ # plotting the separating hyperplanex1 = X[:, 0].reshape((-1, 1))x2 = X[:, 1].reshape((-1, 1))x1, x2 = np.meshgrid(x1, x2)x3 = -(w[0][0]*x1 + w[0][1]*x2 + b) / w[0][2] fig = plt.figure()axes2 = fig.add_subplot(111, projection = '3d')axes2.scatter(X1, X2, X1**2 + X2**2, c = Y, depthshade = True)axes1 = fig.gca(projection = '3d')axes1.plot_surface(x1, x2, x3, alpha = 0.01)plt.show()",
"e": 3260,
"s": 2716,
"text": null
},
{
"code": null,
"e": 3342,
"s": 3260,
"text": "Thus, using a linear classifier we can separate a non-linearly separable dataset."
},
{
"code": null,
"e": 3804,
"s": 3342,
"text": "A brief introduction to kernels in machine learning:In machine learning, a trick known as “kernel trick” is used to learn a linear classifier to classify a non-linear dataset. It transforms the linearly inseparable data into a linearly separable one by projecting it into a higher dimension. A kernel function is applied on each data instance to map the original non-linear data points into some higher dimensional space in which they become linearly separable."
},
{
"code": null,
"e": 3830,
"s": 3804,
"text": "Advanced Computer Subject"
},
{
"code": null,
"e": 3847,
"s": 3830,
"text": "Machine Learning"
},
{
"code": null,
"e": 3864,
"s": 3847,
"text": "Machine Learning"
},
{
"code": null,
"e": 3962,
"s": 3864,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3985,
"s": 3962,
"text": "Reinforcement learning"
},
{
"code": null,
"e": 4012,
"s": 3985,
"text": "Fuzzy Logic | Introduction"
},
{
"code": null,
"e": 4035,
"s": 4012,
"text": "System Design Tutorial"
},
{
"code": null,
"e": 4073,
"s": 4035,
"text": "Getting started with Machine Learning"
},
{
"code": null,
"e": 4113,
"s": 4073,
"text": "Game Playing in Artificial Intelligence"
},
{
"code": null,
"e": 4136,
"s": 4113,
"text": "Reinforcement learning"
},
{
"code": null,
"e": 4167,
"s": 4136,
"text": "What is Information Retrieval?"
},
{
"code": null,
"e": 4200,
"s": 4167,
"text": "Support Vector Machine Algorithm"
},
{
"code": null,
"e": 4234,
"s": 4200,
"text": "Agents in Artificial Intelligence"
}
] |
MongoDB - Map Reduce
|
As per the MongoDB documentation, Map-reduce is a data processing paradigm for condensing large volumes of data into useful aggregated results. MongoDB uses mapReduce command for map-reduce operations. MapReduce is generally used for processing large data sets.
Following is the syntax of the basic mapReduce command −
>db.collection.mapReduce(
function() {emit(key,value);}, //map function
function(key,values) {return reduceFunction}, { //reduce function
out: collection,
query: document,
sort: document,
limit: number
}
)
The map-reduce function first queries the collection, then maps the result documents to emit key-value pairs, which is then reduced based on the keys that have multiple values.
In the above syntax −
map is a javascript function that maps a value with a key and emits a key-value pair
map is a javascript function that maps a value with a key and emits a key-value pair
reduce is a javascript function that reduces or groups all the documents having the same key
reduce is a javascript function that reduces or groups all the documents having the same key
out specifies the location of the map-reduce query result
out specifies the location of the map-reduce query result
query specifies the optional selection criteria for selecting documents
query specifies the optional selection criteria for selecting documents
sort specifies the optional sort criteria
sort specifies the optional sort criteria
limit specifies the optional maximum number of documents to be returned
limit specifies the optional maximum number of documents to be returned
Consider the following document structure storing user posts. The document stores user_name of the user and the status of post.
{
"post_text": "tutorialspoint is an awesome website for tutorials",
"user_name": "mark",
"status":"active"
}
Now, we will use a mapReduce function on our posts collection to select all the active posts, group them on the basis of user_name and then count the number of posts by each user using the following code −
>db.posts.mapReduce(
function() { emit(this.user_id,1); },
function(key, values) {return Array.sum(values)}, {
query:{status:"active"},
out:"post_total"
}
)
The above mapReduce query outputs the following result −
{
"result" : "post_total",
"timeMillis" : 9,
"counts" : {
"input" : 4,
"emit" : 4,
"reduce" : 2,
"output" : 2
},
"ok" : 1,
}
The result shows that a total of 4 documents matched the query (status:"active"), the map function emitted 4 documents with key-value pairs and finally the reduce function grouped mapped documents having the same keys into 2.
To see the result of this mapReduce query, use the find operator −
>db.posts.mapReduce(
function() { emit(this.user_id,1); },
function(key, values) {return Array.sum(values)}, {
query:{status:"active"},
out:"post_total"
}
).find()
The above query gives the following result which indicates that both users tom and mark have two posts in active states −
{ "_id" : "tom", "value" : 2 }
{ "_id" : "mark", "value" : 2 }
In a similar manner, MapReduce queries can be used to construct large complex aggregation queries. The use of custom Javascript functions make use of MapReduce which is very flexible and powerful.
|
[
{
"code": null,
"e": 2949,
"s": 2687,
"text": "As per the MongoDB documentation, Map-reduce is a data processing paradigm for condensing large volumes of data into useful aggregated results. MongoDB uses mapReduce command for map-reduce operations. MapReduce is generally used for processing large data sets."
},
{
"code": null,
"e": 3006,
"s": 2949,
"text": "Following is the syntax of the basic mapReduce command −"
},
{
"code": null,
"e": 3248,
"s": 3006,
"text": ">db.collection.mapReduce(\n function() {emit(key,value);}, //map function\n function(key,values) {return reduceFunction}, { //reduce function\n out: collection,\n query: document,\n sort: document,\n limit: number\n }\n)"
},
{
"code": null,
"e": 3425,
"s": 3248,
"text": "The map-reduce function first queries the collection, then maps the result documents to emit key-value pairs, which is then reduced based on the keys that have multiple values."
},
{
"code": null,
"e": 3447,
"s": 3425,
"text": "In the above syntax −"
},
{
"code": null,
"e": 3532,
"s": 3447,
"text": "map is a javascript function that maps a value with a key and emits a key-value pair"
},
{
"code": null,
"e": 3617,
"s": 3532,
"text": "map is a javascript function that maps a value with a key and emits a key-value pair"
},
{
"code": null,
"e": 3710,
"s": 3617,
"text": "reduce is a javascript function that reduces or groups all the documents having the same key"
},
{
"code": null,
"e": 3803,
"s": 3710,
"text": "reduce is a javascript function that reduces or groups all the documents having the same key"
},
{
"code": null,
"e": 3861,
"s": 3803,
"text": "out specifies the location of the map-reduce query result"
},
{
"code": null,
"e": 3919,
"s": 3861,
"text": "out specifies the location of the map-reduce query result"
},
{
"code": null,
"e": 3991,
"s": 3919,
"text": "query specifies the optional selection criteria for selecting documents"
},
{
"code": null,
"e": 4063,
"s": 3991,
"text": "query specifies the optional selection criteria for selecting documents"
},
{
"code": null,
"e": 4105,
"s": 4063,
"text": "sort specifies the optional sort criteria"
},
{
"code": null,
"e": 4147,
"s": 4105,
"text": "sort specifies the optional sort criteria"
},
{
"code": null,
"e": 4219,
"s": 4147,
"text": "limit specifies the optional maximum number of documents to be returned"
},
{
"code": null,
"e": 4291,
"s": 4219,
"text": "limit specifies the optional maximum number of documents to be returned"
},
{
"code": null,
"e": 4419,
"s": 4291,
"text": "Consider the following document structure storing user posts. The document stores user_name of the user and the status of post."
},
{
"code": null,
"e": 4538,
"s": 4419,
"text": "{\n \"post_text\": \"tutorialspoint is an awesome website for tutorials\",\n \"user_name\": \"mark\",\n \"status\":\"active\"\n}"
},
{
"code": null,
"e": 4744,
"s": 4538,
"text": "Now, we will use a mapReduce function on our posts collection to select all the active posts, group them on the basis of user_name and then count the number of posts by each user using the following code −"
},
{
"code": null,
"e": 4931,
"s": 4744,
"text": ">db.posts.mapReduce( \n function() { emit(this.user_id,1); }, \n\t\n function(key, values) {return Array.sum(values)}, { \n query:{status:\"active\"}, \n out:\"post_total\" \n }\n)"
},
{
"code": null,
"e": 4988,
"s": 4931,
"text": "The above mapReduce query outputs the following result −"
},
{
"code": null,
"e": 5153,
"s": 4988,
"text": "{\n \"result\" : \"post_total\",\n \"timeMillis\" : 9,\n \"counts\" : {\n \"input\" : 4,\n \"emit\" : 4,\n \"reduce\" : 2,\n \"output\" : 2\n },\n \"ok\" : 1,\n}\n"
},
{
"code": null,
"e": 5379,
"s": 5153,
"text": "The result shows that a total of 4 documents matched the query (status:\"active\"), the map function emitted 4 documents with key-value pairs and finally the reduce function grouped mapped documents having the same keys into 2."
},
{
"code": null,
"e": 5446,
"s": 5379,
"text": "To see the result of this mapReduce query, use the find operator −"
},
{
"code": null,
"e": 5640,
"s": 5446,
"text": ">db.posts.mapReduce( \n function() { emit(this.user_id,1); }, \n function(key, values) {return Array.sum(values)}, { \n query:{status:\"active\"}, \n out:\"post_total\" \n }\n\t\n).find()"
},
{
"code": null,
"e": 5762,
"s": 5640,
"text": "The above query gives the following result which indicates that both users tom and mark have two posts in active states −"
},
{
"code": null,
"e": 5825,
"s": 5762,
"text": "{ \"_id\" : \"tom\", \"value\" : 2 }\n{ \"_id\" : \"mark\", \"value\" : 2 }"
}
] |
Find the total marks obtained according to given marking scheme
|
14 Apr, 2021
Given the answer key of N MCQ and the answer marked by the student. The task is to calculate the Marks of the student.
Marking Scheme is as follows:
+3 marks for every correct answer.
-1 marks for every wrong answer.
0 marks for not attempting the question.
Examples:
Input: N = 5
Answer key = {1, 2, 1, 3, 1}
Student answer = {1, 3, 1, 0, 2}
Output: 4
(Only 1 and 3 questions are correctly marked and 2 and 5 are
marked wrong and 4 is not attempt so, (2 * 3) + (2 * -1) = 4)
Input: N = 5
Answer key = {1, 2, 3, 4, 1}
Student answer = {1, 2, 3, 4, 0}
Output: 12
(1, 2, 3, 4 questions are correctly marked and 5 is not attempt
so, (4 * 3) = 12)
Approach:
Start traversing the Student_answer[].If the value at current index of Student_answer[] = 0 then that question is not attempted.Else If the value at current index is equal to the value at corresponding index in Answer_key[] then increment the count of positive answers.Else increment the count of negative answers.Print the total marks by calculating positive marks and negative marks.
Start traversing the Student_answer[].
If the value at current index of Student_answer[] = 0 then that question is not attempted.
Else If the value at current index is equal to the value at corresponding index in Answer_key[] then increment the count of positive answers.
Else increment the count of negative answers.
Print the total marks by calculating positive marks and negative marks.
Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation of above approach#include <bits/stdc++.h>using namespace std; // Function that calculates marks.int markingScheme(int N, int answerKey[], int studentAnswer[]){ int positive = 0, negative = 0, notattempt = 0; for (int i = 0; i < N; i++) { // for not attempt score + 0 if (studentAnswer[i] == 0) notattempt++; // for each correct answer score + 3 else if (answerKey[i] == studentAnswer[i]) positive++; // for each wrong answer score - 1 else if (answerKey[i] != studentAnswer[i]) negative++; } // calculate total marks return (positive * 3) + (negative * -1);} // Driver codeint main(){ int answerKey[] = { 1, 2, 3, 4, 1 }; int studentAnswer[] = { 1, 2, 3, 4, 0 }; int N = sizeof(answerKey)/sizeof(answerKey[0]); cout << markingScheme(N, answerKey, studentAnswer); return 0;}
// Java implementation of above approach // Function that calculates marks.class geeksforgeeks{static int markingScheme(int N, int answerKey[], int studentAnswer[]){ int positive = 0, negative = 0, notattempt = 0; for (int i = 0; i < N; i++) { // for not attempt score + 0 if (studentAnswer[i] == 0) notattempt++; // for each correct answer score + 3 else if (answerKey[i] == studentAnswer[i]) positive++; // for each wrong answer score - 1 else if (answerKey[i] != studentAnswer[i]) negative++; } // calculate total marks return (positive * 3) + (negative * -1);} // Driver codepublic static void main(String args[]){ int answerKey[] = { 1, 2, 3, 4, 1 }; int studentAnswer[] = { 1, 2, 3, 4, 0 }; int N = answerKey.length; int marking_Scheme = markingScheme(N, answerKey, studentAnswer); System.out.println(marking_Scheme);}}
# Python 3 implementation of above approach # Function that calculates marks.def markingScheme( N, answerKey, studentAnswer): positive = 0 negative = 0 notattempt = 0 for i in range (0, N): # for not attempt score + 0 if (studentAnswer[i] == 0): notattempt += 1 # for each correct answer score + 3 elif (answerKey[i] == studentAnswer[i]): positive += 1 # for each wrong answer score - 1 elif (answerKey[i] != studentAnswer[i]): negative += 1 # calculate total marks return (positive * 3) + (negative * -1) # Driver codedef main(): answerKey = [1, 2, 3, 4, 1] studentAnswer = [1, 2, 3, 4, 0] N = 5 print (markingScheme(N, answerKey, studentAnswer))
// C# implementation of above approach// Function that calculates marks.using System; class GFG{static int markingScheme(int N, int []answerKey, int []studentAnswer){ int positive = 0, negative = 0, notattempt = 0; for (int i = 0; i < N; i++) { // for not attempt score + 0 if (studentAnswer[i] == 0) notattempt++; // for each correct answer score + 3 else if (answerKey[i] == studentAnswer[i]) positive++; // for each wrong answer score - 1 else if (answerKey[i] != studentAnswer[i]) negative++; } // calculate total marks return (positive * 3) + (negative * -1);} // Driver codestatic public void Main (){ int []answerKey = { 1, 2, 3, 4, 1 }; int []studentAnswer = { 1, 2, 3, 4, 0 }; int N = answerKey.Length; int marking_Scheme = markingScheme(N, answerKey, studentAnswer); Console.WriteLine(marking_Scheme);}} // This code is contributed// by Sach_Code
<?php// PHP implementation of above approach // Function that calculates marks.function markingScheme($N, $answerKey, $studentAnswer){ $positive = 0; $negative = 0; $notattempt = 0; for ($i = 0; $i < $N; $i++) { // for not attempt score + 0 if ($studentAnswer[$i] == 0) $notattempt++; // for each correct answer score + 3 else if ($answerKey[$i] == $studentAnswer[$i]) $positive++; // for each wrong answer score - 1 else if ($answerKey[$i] != $studentAnswer[$i]) $negative++; } // calculate total marks return ($positive * 3) + ($negative * -1);} // Driver code$answerKey = array( 1, 2, 3, 4, 1 );$studentAnswer = array( 1, 2, 3, 4, 0 ); $N = sizeof($answerKey);echo markingScheme($N, $answerKey, $studentAnswer); // This code is contributed by akt_mit?>
<script> // Javascript implementation of above approach // Function that calculates marks.function markingScheme(N, answerKey, studentAnswer){ var positive = 0, negative = 0, notattempt = 0; for (var i = 0; i < N; i++) { // for not attempt score + 0 if (studentAnswer[i] == 0) notattempt++; // for each correct answer score + 3 else if (answerKey[i] == studentAnswer[i]) positive++; // for each wrong answer score - 1 else if (answerKey[i] != studentAnswer[i]) negative++; } // calculate total marks return (positive * 3) + (negative * -1);} // Driver codevar answerKey = [ 1, 2, 3, 4, 1 ];var studentAnswer = [ 1, 2, 3, 4, 0 ]; var N = answerKey.length;document.write( markingScheme(N, answerKey, studentAnswer)); </script>
12
Krishna_Yadav
Sach_Code
jit_t
noob2000
Arrays
Mathematical
School Programming
Arrays
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
Window Sliding Technique
Search, insert and delete in an unsorted array
Chocolate Distribution Problem
Find duplicates in O(n) time and O(1) extra space | Set 1
Program for Fibonacci numbers
Set in C++ Standard Template Library (STL)
Write a program to print all permutations of a given string
C++ Data Types
Coin Change | DP-7
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n14 Apr, 2021"
},
{
"code": null,
"e": 174,
"s": 53,
"text": "Given the answer key of N MCQ and the answer marked by the student. The task is to calculate the Marks of the student. "
},
{
"code": null,
"e": 206,
"s": 174,
"text": "Marking Scheme is as follows: "
},
{
"code": null,
"e": 241,
"s": 206,
"text": "+3 marks for every correct answer."
},
{
"code": null,
"e": 274,
"s": 241,
"text": "-1 marks for every wrong answer."
},
{
"code": null,
"e": 315,
"s": 274,
"text": "0 marks for not attempting the question."
},
{
"code": null,
"e": 327,
"s": 315,
"text": "Examples: "
},
{
"code": null,
"e": 746,
"s": 327,
"text": "Input: N = 5\n Answer key = {1, 2, 1, 3, 1}\n Student answer = {1, 3, 1, 0, 2}\nOutput: 4 \n(Only 1 and 3 questions are correctly marked and 2 and 5 are \nmarked wrong and 4 is not attempt so, (2 * 3) + (2 * -1) = 4)\n\nInput: N = 5\n Answer key = {1, 2, 3, 4, 1}\n Student answer = {1, 2, 3, 4, 0}\nOutput: 12\n(1, 2, 3, 4 questions are correctly marked and 5 is not attempt \nso, (4 * 3) = 12)"
},
{
"code": null,
"e": 760,
"s": 748,
"text": "Approach: "
},
{
"code": null,
"e": 1146,
"s": 760,
"text": "Start traversing the Student_answer[].If the value at current index of Student_answer[] = 0 then that question is not attempted.Else If the value at current index is equal to the value at corresponding index in Answer_key[] then increment the count of positive answers.Else increment the count of negative answers.Print the total marks by calculating positive marks and negative marks."
},
{
"code": null,
"e": 1185,
"s": 1146,
"text": "Start traversing the Student_answer[]."
},
{
"code": null,
"e": 1276,
"s": 1185,
"text": "If the value at current index of Student_answer[] = 0 then that question is not attempted."
},
{
"code": null,
"e": 1418,
"s": 1276,
"text": "Else If the value at current index is equal to the value at corresponding index in Answer_key[] then increment the count of positive answers."
},
{
"code": null,
"e": 1464,
"s": 1418,
"text": "Else increment the count of negative answers."
},
{
"code": null,
"e": 1536,
"s": 1464,
"text": "Print the total marks by calculating positive marks and negative marks."
},
{
"code": null,
"e": 1589,
"s": 1536,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1593,
"s": 1589,
"text": "C++"
},
{
"code": null,
"e": 1598,
"s": 1593,
"text": "Java"
},
{
"code": null,
"e": 1606,
"s": 1598,
"text": "Python3"
},
{
"code": null,
"e": 1609,
"s": 1606,
"text": "C#"
},
{
"code": null,
"e": 1613,
"s": 1609,
"text": "PHP"
},
{
"code": null,
"e": 1624,
"s": 1613,
"text": "Javascript"
},
{
"code": "// C++ implementation of above approach#include <bits/stdc++.h>using namespace std; // Function that calculates marks.int markingScheme(int N, int answerKey[], int studentAnswer[]){ int positive = 0, negative = 0, notattempt = 0; for (int i = 0; i < N; i++) { // for not attempt score + 0 if (studentAnswer[i] == 0) notattempt++; // for each correct answer score + 3 else if (answerKey[i] == studentAnswer[i]) positive++; // for each wrong answer score - 1 else if (answerKey[i] != studentAnswer[i]) negative++; } // calculate total marks return (positive * 3) + (negative * -1);} // Driver codeint main(){ int answerKey[] = { 1, 2, 3, 4, 1 }; int studentAnswer[] = { 1, 2, 3, 4, 0 }; int N = sizeof(answerKey)/sizeof(answerKey[0]); cout << markingScheme(N, answerKey, studentAnswer); return 0;}",
"e": 2534,
"s": 1624,
"text": null
},
{
"code": "// Java implementation of above approach // Function that calculates marks.class geeksforgeeks{static int markingScheme(int N, int answerKey[], int studentAnswer[]){ int positive = 0, negative = 0, notattempt = 0; for (int i = 0; i < N; i++) { // for not attempt score + 0 if (studentAnswer[i] == 0) notattempt++; // for each correct answer score + 3 else if (answerKey[i] == studentAnswer[i]) positive++; // for each wrong answer score - 1 else if (answerKey[i] != studentAnswer[i]) negative++; } // calculate total marks return (positive * 3) + (negative * -1);} // Driver codepublic static void main(String args[]){ int answerKey[] = { 1, 2, 3, 4, 1 }; int studentAnswer[] = { 1, 2, 3, 4, 0 }; int N = answerKey.length; int marking_Scheme = markingScheme(N, answerKey, studentAnswer); System.out.println(marking_Scheme);}}",
"e": 3471,
"s": 2534,
"text": null
},
{
"code": "# Python 3 implementation of above approach # Function that calculates marks.def markingScheme( N, answerKey, studentAnswer): positive = 0 negative = 0 notattempt = 0 for i in range (0, N): # for not attempt score + 0 if (studentAnswer[i] == 0): notattempt += 1 # for each correct answer score + 3 elif (answerKey[i] == studentAnswer[i]): positive += 1 # for each wrong answer score - 1 elif (answerKey[i] != studentAnswer[i]): negative += 1 # calculate total marks return (positive * 3) + (negative * -1) # Driver codedef main(): answerKey = [1, 2, 3, 4, 1] studentAnswer = [1, 2, 3, 4, 0] N = 5 print (markingScheme(N, answerKey, studentAnswer))",
"e": 4239,
"s": 3471,
"text": null
},
{
"code": "// C# implementation of above approach// Function that calculates marks.using System; class GFG{static int markingScheme(int N, int []answerKey, int []studentAnswer){ int positive = 0, negative = 0, notattempt = 0; for (int i = 0; i < N; i++) { // for not attempt score + 0 if (studentAnswer[i] == 0) notattempt++; // for each correct answer score + 3 else if (answerKey[i] == studentAnswer[i]) positive++; // for each wrong answer score - 1 else if (answerKey[i] != studentAnswer[i]) negative++; } // calculate total marks return (positive * 3) + (negative * -1);} // Driver codestatic public void Main (){ int []answerKey = { 1, 2, 3, 4, 1 }; int []studentAnswer = { 1, 2, 3, 4, 0 }; int N = answerKey.Length; int marking_Scheme = markingScheme(N, answerKey, studentAnswer); Console.WriteLine(marking_Scheme);}} // This code is contributed// by Sach_Code",
"e": 5299,
"s": 4239,
"text": null
},
{
"code": "<?php// PHP implementation of above approach // Function that calculates marks.function markingScheme($N, $answerKey, $studentAnswer){ $positive = 0; $negative = 0; $notattempt = 0; for ($i = 0; $i < $N; $i++) { // for not attempt score + 0 if ($studentAnswer[$i] == 0) $notattempt++; // for each correct answer score + 3 else if ($answerKey[$i] == $studentAnswer[$i]) $positive++; // for each wrong answer score - 1 else if ($answerKey[$i] != $studentAnswer[$i]) $negative++; } // calculate total marks return ($positive * 3) + ($negative * -1);} // Driver code$answerKey = array( 1, 2, 3, 4, 1 );$studentAnswer = array( 1, 2, 3, 4, 0 ); $N = sizeof($answerKey);echo markingScheme($N, $answerKey, $studentAnswer); // This code is contributed by akt_mit?>",
"e": 6220,
"s": 5299,
"text": null
},
{
"code": "<script> // Javascript implementation of above approach // Function that calculates marks.function markingScheme(N, answerKey, studentAnswer){ var positive = 0, negative = 0, notattempt = 0; for (var i = 0; i < N; i++) { // for not attempt score + 0 if (studentAnswer[i] == 0) notattempt++; // for each correct answer score + 3 else if (answerKey[i] == studentAnswer[i]) positive++; // for each wrong answer score - 1 else if (answerKey[i] != studentAnswer[i]) negative++; } // calculate total marks return (positive * 3) + (negative * -1);} // Driver codevar answerKey = [ 1, 2, 3, 4, 1 ];var studentAnswer = [ 1, 2, 3, 4, 0 ]; var N = answerKey.length;document.write( markingScheme(N, answerKey, studentAnswer)); </script>",
"e": 7043,
"s": 6220,
"text": null
},
{
"code": null,
"e": 7046,
"s": 7043,
"text": "12"
},
{
"code": null,
"e": 7062,
"s": 7048,
"text": "Krishna_Yadav"
},
{
"code": null,
"e": 7072,
"s": 7062,
"text": "Sach_Code"
},
{
"code": null,
"e": 7078,
"s": 7072,
"text": "jit_t"
},
{
"code": null,
"e": 7087,
"s": 7078,
"text": "noob2000"
},
{
"code": null,
"e": 7094,
"s": 7087,
"text": "Arrays"
},
{
"code": null,
"e": 7107,
"s": 7094,
"text": "Mathematical"
},
{
"code": null,
"e": 7126,
"s": 7107,
"text": "School Programming"
},
{
"code": null,
"e": 7133,
"s": 7126,
"text": "Arrays"
},
{
"code": null,
"e": 7146,
"s": 7133,
"text": "Mathematical"
},
{
"code": null,
"e": 7244,
"s": 7146,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7276,
"s": 7244,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 7301,
"s": 7276,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 7348,
"s": 7301,
"text": "Search, insert and delete in an unsorted array"
},
{
"code": null,
"e": 7379,
"s": 7348,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 7437,
"s": 7379,
"text": "Find duplicates in O(n) time and O(1) extra space | Set 1"
},
{
"code": null,
"e": 7467,
"s": 7437,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 7510,
"s": 7467,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 7570,
"s": 7510,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 7585,
"s": 7570,
"text": "C++ Data Types"
}
] |
Visibility Modes in C++ with Examples
|
02 Feb, 2022
When a base class is derived by a derived class with the help of inheritance, the accessibility of base class by the derived class is controlled by visibility modes. The derived class doesn’t inherit access to private data members. However, it does inherit a full parent object, which contains any private members which that class declares.
CPP
// C++ implementation to show// Visibility modes #include <bits/stdc++.h>using namespace std; // Base class// Class A will be inheritedclass A {public: int x; protected: int y; private: int z;}; // Derived class// Class B will inherit Class Aclass B : public A {}; // main functionint main(){ B b; // x is public // so its value will be printed cout << b.x << endl; // y is protected // so it will give visibility error cout << b.y << endl; // z is not accessible from B // so it will give visibility error cout << b.z << endl;};
Compile Errors:
prog.cpp: In function 'int main()':
prog.cpp:14:6: error: 'int A::y' is protected
int y;
^
prog.cpp:34:12: error: within this context
cout << b.y << endl;
^
prog.cpp:17:6: error: 'int A::z' is private
int z;
^
prog.cpp:37:12: error: within this context
cout << b.z << endl;
^
What does visibility means in this program?
Since the member ‘x’ in A is public, its visibility will be open to all. It means that any class can access and use this x. That is the reason there is no error in ‘b.x’.
The member ‘y’ in A is protected, its visibility will be only to the derived class. It means that any derived class can access and use this y.
The member ‘z’ in A is private, its visibility will not be open to any other class. It means that any derived class cannot access and use this z.
Types of Visibility modes:
There are three types of Visibility modes:
Public Visibility mode: If we derive a subclass from a public base class. Then the public member of the base class will become public in the derived class and protected members of the base class will become protected in the derived class.
Public Visibility mode: If we derive a subclass from a public base class. Then the public member of the base class will become public in the derived class and protected members of the base class will become protected in the derived class.
CPP
// C++ implementation to show// Public Visibility mode #include <bits/stdc++.h>using namespace std; // Base class// Class A will be inheritedclass A {public: int x; protected: int y; private: int z;}; // Derived class// Class B will inherit Class A// using Public Visibility modeclass B : public A {}; // main functionint main(){ B b; // x is public and it will remain public // so its value will be printed cout << b.x << endl; // y is protected and it will remain protected // so it will give visibility error cout << b.y << endl; // z is not accessible from B as // z is private and it will remain private // so it will give visibility error cout << b.z << endl;};
Compile Errors:
Compile Errors:
prog.cpp: In function 'int main()':
prog.cpp:14:9: error: 'int A::y' is protected
int y;
^
prog.cpp:37:15: error: within this context
cout << b.y << endl;
^
prog.cpp:17:9: error: 'int A::z' is private
int z;
^
prog.cpp:42:15: error: within this context
cout << b.z << endl;
^
Protected Visibility mode: If we derive a subclass from a Protected base class. Then both public member and protected members of the base class will become protected in the derived class.
Protected Visibility mode: If we derive a subclass from a Protected base class. Then both public member and protected members of the base class will become protected in the derived class.
CPP
// C++ implementation to show// Protected Visibility mode #include <bits/stdc++.h>using namespace std; // Base class// Class A will be inheritedclass A {public: int x; protected: int y; private: int z;}; // Derived class// Class B will inherit Class A// using Protected Visibility modeclass B : protected A {}; // main functionint main(){ B b; // x is public and it will become protected // so it will give visibility error cout << b.x << endl; // y is protected and it will remain protected // so it will give visibility error cout << b.y << endl; // z is not accessible from B as // z is private and it will remain private // so it will give visibility error cout << b.z << endl;};
Compile Errors:
Compile Errors:
prog.cpp: In function 'int main()':
prog.cpp:11:9: error: 'int A::x' is inaccessible
int x;
^
prog.cpp:33:15: error: within this context
cout << b.x << endl;
^
prog.cpp:14:9: error: 'int A::y' is protected
int y;
^
prog.cpp:37:15: error: within this context
cout << b.y << endl;
^
prog.cpp:17:9: error: 'int A::z' is private
int z;
^
prog.cpp:42:15: error: within this context
cout << b.z << endl;
^
Private Visibility mode: If we derive a subclass from a Private base class. Then both public member and protected members of the base class will become Private in the derived class.
Private Visibility mode: If we derive a subclass from a Private base class. Then both public member and protected members of the base class will become Private in the derived class.
CPP
// C++ implementation to show// Private Visibility mode #include <bits/stdc++.h>using namespace std; // Base class// Class A will be inheritedclass A {public: int x; protected: int y; private: int z;}; // Derived class// Class B will inherit Class A// using Private Visibility modeclass B : private A {}; // main functionint main(){ B b; // x is public and it will become private // so it will give visibility error cout << b.x << endl; // y is protected and it will become private // so it will give visibility error cout << b.y << endl; // z is not accessible from B as // z is private and it will remain private // so it will give visibility error cout << b.z << endl;};
Compile Errors:
Compile Errors:
prog.cpp: In function 'int main()':
prog.cpp:11:9: error: 'int A::x' is inaccessible
int x;
^
prog.cpp:33:15: error: within this context
cout << b.x << endl;
^
prog.cpp:14:9: error: 'int A::y' is protected
int y;
^
prog.cpp:37:15: error: within this context
cout << b.y << endl;
^
prog.cpp:17:9: error: 'int A::z' is private
int z;
^
prog.cpp:42:15: error: within this context
cout << b.z << endl;
^
How to change the Visibility mode after inheritance?After inheriting a base class with the help of a specific Visibility mode, the members will automatically change its visibility as mentioned above. But inorder to change the visibility after this inheritance, we need to do it manually.Syntax:
<visibility_mode>:
using base::<member>;
For example:
// inorder to change the visibility of x to public
<public>:
using base::<x>;
Example: Consider a base class containing a public member ‘a’, protected members ‘b’ and ‘c’, and private members ‘d’ and ‘e’. Below program explains how to change the visibility of ‘b’ from protected to public.
CPP
// C++ implementation to show how to// change the Visibility modes #include <bits/stdc++.h>using namespace std; // Base class// Class A will be inheritedclass BaseClass { // Public memberspublic: int a; // Protected membersprotected: int b; int c; // Private membersprivate: int d; int e;}; // BaseClass will be inherited as private// to change all the members to private firstclass DerivedClass : private BaseClass { // Now change the visibility of b // from private to publicpublic: using BaseClass::b;}; // main functionint main(){ DerivedClass derivedClass; // d must be private and // hence generate visibility error cout << derivedClass.d << endl; // b must be now public and hence should // not generate visibility error cout << derivedClass.b << endl; return 0;};
Compile Errors:
prog.cpp: In function 'int main()':
prog.cpp:22:9: error: 'int BaseClass::d' is private
int d;
^
prog.cpp:47:26: error: within this context
cout << derivedClass.d << endl;
^
sumitgumber28
access modifiers
C++-Inheritance
Articles
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Flutter - InkWell Widget
Asymptotic Notations and how to calculate them
How to use gotoxy() in codeblocks?
Print all subsequences of a string using ArrayList
File globbing in Linux
Vector in C++ STL
Map in C++ Standard Template Library (STL)
std::sort() in C++ STL
Initialize a vector in C++ (7 different ways)
Bitwise Operators in C/C++
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n02 Feb, 2022"
},
{
"code": null,
"e": 397,
"s": 54,
"text": "When a base class is derived by a derived class with the help of inheritance, the accessibility of base class by the derived class is controlled by visibility modes. The derived class doesn’t inherit access to private data members. However, it does inherit a full parent object, which contains any private members which that class declares. "
},
{
"code": null,
"e": 401,
"s": 397,
"text": "CPP"
},
{
"code": "// C++ implementation to show// Visibility modes #include <bits/stdc++.h>using namespace std; // Base class// Class A will be inheritedclass A {public: int x; protected: int y; private: int z;}; // Derived class// Class B will inherit Class Aclass B : public A {}; // main functionint main(){ B b; // x is public // so its value will be printed cout << b.x << endl; // y is protected // so it will give visibility error cout << b.y << endl; // z is not accessible from B // so it will give visibility error cout << b.z << endl;};",
"e": 973,
"s": 401,
"text": null
},
{
"code": null,
"e": 991,
"s": 973,
"text": "Compile Errors: "
},
{
"code": null,
"e": 1311,
"s": 991,
"text": "prog.cpp: In function 'int main()':\nprog.cpp:14:6: error: 'int A::y' is protected\n int y;\n ^\nprog.cpp:34:12: error: within this context\n cout << b.y << endl;\n ^\nprog.cpp:17:6: error: 'int A::z' is private\n int z;\n ^\nprog.cpp:37:12: error: within this context\n cout << b.z << endl;\n ^"
},
{
"code": null,
"e": 1357,
"s": 1311,
"text": "What does visibility means in this program? "
},
{
"code": null,
"e": 1530,
"s": 1357,
"text": "Since the member ‘x’ in A is public, its visibility will be open to all. It means that any class can access and use this x. That is the reason there is no error in ‘b.x’. "
},
{
"code": null,
"e": 1673,
"s": 1530,
"text": "The member ‘y’ in A is protected, its visibility will be only to the derived class. It means that any derived class can access and use this y."
},
{
"code": null,
"e": 1819,
"s": 1673,
"text": "The member ‘z’ in A is private, its visibility will not be open to any other class. It means that any derived class cannot access and use this z."
},
{
"code": null,
"e": 1847,
"s": 1819,
"text": "Types of Visibility modes: "
},
{
"code": null,
"e": 1892,
"s": 1847,
"text": "There are three types of Visibility modes: "
},
{
"code": null,
"e": 2132,
"s": 1892,
"text": "Public Visibility mode: If we derive a subclass from a public base class. Then the public member of the base class will become public in the derived class and protected members of the base class will become protected in the derived class. "
},
{
"code": null,
"e": 2372,
"s": 2132,
"text": "Public Visibility mode: If we derive a subclass from a public base class. Then the public member of the base class will become public in the derived class and protected members of the base class will become protected in the derived class. "
},
{
"code": null,
"e": 2376,
"s": 2372,
"text": "CPP"
},
{
"code": "// C++ implementation to show// Public Visibility mode #include <bits/stdc++.h>using namespace std; // Base class// Class A will be inheritedclass A {public: int x; protected: int y; private: int z;}; // Derived class// Class B will inherit Class A// using Public Visibility modeclass B : public A {}; // main functionint main(){ B b; // x is public and it will remain public // so its value will be printed cout << b.x << endl; // y is protected and it will remain protected // so it will give visibility error cout << b.y << endl; // z is not accessible from B as // z is private and it will remain private // so it will give visibility error cout << b.z << endl;};",
"e": 3089,
"s": 2376,
"text": null
},
{
"code": null,
"e": 3107,
"s": 3089,
"text": "Compile Errors: "
},
{
"code": null,
"e": 3125,
"s": 3107,
"text": "Compile Errors: "
},
{
"code": null,
"e": 3469,
"s": 3125,
"text": "prog.cpp: In function 'int main()':\nprog.cpp:14:9: error: 'int A::y' is protected\n int y;\n ^\nprog.cpp:37:15: error: within this context\n cout << b.y << endl;\n ^\nprog.cpp:17:9: error: 'int A::z' is private\n int z;\n ^\nprog.cpp:42:15: error: within this context\n cout << b.z << endl;\n ^"
},
{
"code": null,
"e": 3659,
"s": 3469,
"text": " Protected Visibility mode: If we derive a subclass from a Protected base class. Then both public member and protected members of the base class will become protected in the derived class. "
},
{
"code": null,
"e": 3850,
"s": 3661,
"text": "Protected Visibility mode: If we derive a subclass from a Protected base class. Then both public member and protected members of the base class will become protected in the derived class. "
},
{
"code": null,
"e": 3854,
"s": 3850,
"text": "CPP"
},
{
"code": "// C++ implementation to show// Protected Visibility mode #include <bits/stdc++.h>using namespace std; // Base class// Class A will be inheritedclass A {public: int x; protected: int y; private: int z;}; // Derived class// Class B will inherit Class A// using Protected Visibility modeclass B : protected A {}; // main functionint main(){ B b; // x is public and it will become protected // so it will give visibility error cout << b.x << endl; // y is protected and it will remain protected // so it will give visibility error cout << b.y << endl; // z is not accessible from B as // z is private and it will remain private // so it will give visibility error cout << b.z << endl;};",
"e": 4583,
"s": 3854,
"text": null
},
{
"code": null,
"e": 4601,
"s": 4583,
"text": "Compile Errors: "
},
{
"code": null,
"e": 4619,
"s": 4601,
"text": "Compile Errors: "
},
{
"code": null,
"e": 5121,
"s": 4619,
"text": "prog.cpp: In function 'int main()':\nprog.cpp:11:9: error: 'int A::x' is inaccessible\n int x;\n ^\nprog.cpp:33:15: error: within this context\n cout << b.x << endl;\n ^\nprog.cpp:14:9: error: 'int A::y' is protected\n int y;\n ^\nprog.cpp:37:15: error: within this context\n cout << b.y << endl;\n ^\nprog.cpp:17:9: error: 'int A::z' is private\n int z;\n ^\nprog.cpp:42:15: error: within this context\n cout << b.z << endl;\n ^"
},
{
"code": null,
"e": 5306,
"s": 5121,
"text": " Private Visibility mode: If we derive a subclass from a Private base class. Then both public member and protected members of the base class will become Private in the derived class. "
},
{
"code": null,
"e": 5492,
"s": 5308,
"text": "Private Visibility mode: If we derive a subclass from a Private base class. Then both public member and protected members of the base class will become Private in the derived class. "
},
{
"code": null,
"e": 5496,
"s": 5492,
"text": "CPP"
},
{
"code": "// C++ implementation to show// Private Visibility mode #include <bits/stdc++.h>using namespace std; // Base class// Class A will be inheritedclass A {public: int x; protected: int y; private: int z;}; // Derived class// Class B will inherit Class A// using Private Visibility modeclass B : private A {}; // main functionint main(){ B b; // x is public and it will become private // so it will give visibility error cout << b.x << endl; // y is protected and it will become private // so it will give visibility error cout << b.y << endl; // z is not accessible from B as // z is private and it will remain private // so it will give visibility error cout << b.z << endl;};",
"e": 6215,
"s": 5496,
"text": null
},
{
"code": null,
"e": 6233,
"s": 6215,
"text": "Compile Errors: "
},
{
"code": null,
"e": 6251,
"s": 6233,
"text": "Compile Errors: "
},
{
"code": null,
"e": 6753,
"s": 6251,
"text": "prog.cpp: In function 'int main()':\nprog.cpp:11:9: error: 'int A::x' is inaccessible\n int x;\n ^\nprog.cpp:33:15: error: within this context\n cout << b.x << endl;\n ^\nprog.cpp:14:9: error: 'int A::y' is protected\n int y;\n ^\nprog.cpp:37:15: error: within this context\n cout << b.y << endl;\n ^\nprog.cpp:17:9: error: 'int A::z' is private\n int z;\n ^\nprog.cpp:42:15: error: within this context\n cout << b.z << endl;\n ^"
},
{
"code": null,
"e": 7054,
"s": 6757,
"text": "How to change the Visibility mode after inheritance?After inheriting a base class with the help of a specific Visibility mode, the members will automatically change its visibility as mentioned above. But inorder to change the visibility after this inheritance, we need to do it manually.Syntax: "
},
{
"code": null,
"e": 7099,
"s": 7054,
"text": "<visibility_mode>:\n using base::<member>;"
},
{
"code": null,
"e": 7114,
"s": 7099,
"text": "For example: "
},
{
"code": null,
"e": 7196,
"s": 7114,
"text": "// inorder to change the visibility of x to public\n<public>:\n using base::<x>;"
},
{
"code": null,
"e": 7409,
"s": 7196,
"text": "Example: Consider a base class containing a public member ‘a’, protected members ‘b’ and ‘c’, and private members ‘d’ and ‘e’. Below program explains how to change the visibility of ‘b’ from protected to public. "
},
{
"code": null,
"e": 7413,
"s": 7409,
"text": "CPP"
},
{
"code": "// C++ implementation to show how to// change the Visibility modes #include <bits/stdc++.h>using namespace std; // Base class// Class A will be inheritedclass BaseClass { // Public memberspublic: int a; // Protected membersprotected: int b; int c; // Private membersprivate: int d; int e;}; // BaseClass will be inherited as private// to change all the members to private firstclass DerivedClass : private BaseClass { // Now change the visibility of b // from private to publicpublic: using BaseClass::b;}; // main functionint main(){ DerivedClass derivedClass; // d must be private and // hence generate visibility error cout << derivedClass.d << endl; // b must be now public and hence should // not generate visibility error cout << derivedClass.b << endl; return 0;};",
"e": 8249,
"s": 7413,
"text": null
},
{
"code": null,
"e": 8267,
"s": 8249,
"text": "Compile Errors: "
},
{
"code": null,
"e": 8486,
"s": 8267,
"text": "prog.cpp: In function 'int main()':\nprog.cpp:22:9: error: 'int BaseClass::d' is private\n int d;\n ^\nprog.cpp:47:26: error: within this context\n cout << derivedClass.d << endl;\n ^"
},
{
"code": null,
"e": 8502,
"s": 8488,
"text": "sumitgumber28"
},
{
"code": null,
"e": 8519,
"s": 8502,
"text": "access modifiers"
},
{
"code": null,
"e": 8535,
"s": 8519,
"text": "C++-Inheritance"
},
{
"code": null,
"e": 8544,
"s": 8535,
"text": "Articles"
},
{
"code": null,
"e": 8548,
"s": 8544,
"text": "C++"
},
{
"code": null,
"e": 8552,
"s": 8548,
"text": "CPP"
},
{
"code": null,
"e": 8650,
"s": 8552,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8675,
"s": 8650,
"text": "Flutter - InkWell Widget"
},
{
"code": null,
"e": 8722,
"s": 8675,
"text": "Asymptotic Notations and how to calculate them"
},
{
"code": null,
"e": 8757,
"s": 8722,
"text": "How to use gotoxy() in codeblocks?"
},
{
"code": null,
"e": 8808,
"s": 8757,
"text": "Print all subsequences of a string using ArrayList"
},
{
"code": null,
"e": 8831,
"s": 8808,
"text": "File globbing in Linux"
},
{
"code": null,
"e": 8849,
"s": 8831,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 8892,
"s": 8849,
"text": "Map in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 8915,
"s": 8892,
"text": "std::sort() in C++ STL"
},
{
"code": null,
"e": 8961,
"s": 8915,
"text": "Initialize a vector in C++ (7 different ways)"
}
] |
UGC-NET | UGC NET CS 2015 Dec – II | Question 29
|
02 May, 2018
A system has four processes and five allocatable resources. The current allocation and maximum needs are as follows:
Allocated Maximum Available
Process A 1 0 2 1 1 1 1 2 1 3 0 0 x 1 1
Process B 2 0 1 1 0 2 2 2 1 0
Process C 1 1 0 1 0 2 1 3 1 0
Process D 1 1 1 1 0 1 1 2 2 1
The smallest value of x for which the above system in safe state is __________.
(A) 1(B) 3(C) 2(D) Not safe for any value of x.Answer: (D)Explanation:
Allocated Maximum Available Need
Process A 1 0 2 1 1 1 1 2 1 3 0 0 x 1 1 0 1 0 0 2
Process B 2 0 1 1 0 2 2 2 1 0 0 2 1 0 0
Process C 1 1 0 1 0 2 1 3 1 0 1 0 3 0 0
Process D 1 1 1 1 0 1 1 2 2 1 0 0 1 1 1
The smallest value of x for which the above system in safe state is __________.
For x = 1 process D will execute and free 1 1 2 2 1 instances. Now none of the other process will execute.let x = 2 then process D will execute and free 1 1 3 2 1 instances. Now process C will execute and free 2 2 3 3 1 instances. With these free instances process B will execute, but process A will not execute because 5 resources needs 2 instances which will never be satisfied. That’s why system is not in safe state.So, option (D) is correct.Quiz of this Question
UGC-NET
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n02 May, 2018"
},
{
"code": null,
"e": 171,
"s": 54,
"text": "A system has four processes and five allocatable resources. The current allocation and maximum needs are as follows:"
},
{
"code": null,
"e": 473,
"s": 171,
"text": " Allocated Maximum Available\nProcess A 1 0 2 1 1 1 1 2 1 3 0 0 x 1 1\nProcess B 2 0 1 1 0 2 2 2 1 0 \nProcess C 1 1 0 1 0 2 1 3 1 0 \nProcess D 1 1 1 1 0 1 1 2 2 1 \nThe smallest value of x for which the above system in safe state is __________."
},
{
"code": null,
"e": 544,
"s": 473,
"text": "(A) 1(B) 3(C) 2(D) Not safe for any value of x.Answer: (D)Explanation:"
},
{
"code": null,
"e": 938,
"s": 544,
"text": " Allocated Maximum Available Need \nProcess A 1 0 2 1 1 1 1 2 1 3 0 0 x 1 1 0 1 0 0 2 \nProcess B 2 0 1 1 0 2 2 2 1 0 0 2 1 0 0\nProcess C 1 1 0 1 0 2 1 3 1 0 1 0 3 0 0\nProcess D 1 1 1 1 0 1 1 2 2 1 0 0 1 1 1 \nThe smallest value of x for which the above system in safe state is __________."
},
{
"code": null,
"e": 1406,
"s": 938,
"text": "For x = 1 process D will execute and free 1 1 2 2 1 instances. Now none of the other process will execute.let x = 2 then process D will execute and free 1 1 3 2 1 instances. Now process C will execute and free 2 2 3 3 1 instances. With these free instances process B will execute, but process A will not execute because 5 resources needs 2 instances which will never be satisfied. That’s why system is not in safe state.So, option (D) is correct.Quiz of this Question"
},
{
"code": null,
"e": 1414,
"s": 1406,
"text": "UGC-NET"
}
] |
Minimum steps to color the tree with given colors
|
03 Jun, 2021
Given a tree with N nodes which initially have no color and an array color[] of size N which represent the color of each node after the coloring process takes place. The task is to color the tree into the given colors using the smallest possible number of steps. On each step, one can choose a vertex v and a color x, and then color all vertices in the sub-tree of v (including v itself) with color x. Note that root is vertex number 1. Examples:
Input: color[] = { 1, 1, 2, 1, 3, 1}
Output: 4 Color the sub-tree rooted at node 1 with color 1. Then all the vertices have colors 1. Now, color the sub-tree rooted at 3 with color 2. Finally, color the sub-trees rooted at 5 and 6 with colors 3 and 1 respectively.Input: color[] = { 1, 2, 3, 2, 2, 3}
Output: 3
Approach: Call a DFS function at vertex 1 and initially keep answer as zero. Increment the answer whenever there is a difference in colors of child and parent nodes. See the below code for better understanding.Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // To store the required answerint ans = 0; // To store the graphvector<int> gr[100005]; // Function to add edgesvoid Add_Edge(int u, int v){ gr[u].push_back(v); gr[v].push_back(u);} // Dfs functionvoid dfs(int child, int par, int color[]){ // When there is difference in colors if (color[child] != color[par]) ans++; // For all it's child nodes for (auto it : gr[child]) { if (it == par) continue; dfs(it, child, color); }} // Driver codeint main(){ // Here zero is for parent of node 1 int color[] = { 0, 1, 2, 3, 2, 2, 3 }; // Adding edges in the graph Add_Edge(1, 2); Add_Edge(1, 3); Add_Edge(2, 4); Add_Edge(2, 5); Add_Edge(3, 6); // Dfs call dfs(1, 0, color); // Required answer cout << ans; return 0;}
// Java implementation of the approachimport java.util.*; class GFG{ // To store the required answerstatic int ans = 0; // To store the graphstatic Vector<Vector<Integer>> gr = new Vector<Vector<Integer>>(); // Function to add edgesstatic void Add_Edge(int u, int v){ gr.get(u).add(v); gr.get(v).add(u);} // Dfs functionstatic void dfs(int child, int par, int color[]){ // When there is difference in colors if (color[child] != color[par]) ans++; // For all it's child nodes for (int i = 0; i < gr.get(child).size(); i++) { if (gr.get(child).get(i) == par) continue; dfs(gr.get(child).get(i), child, color); }} // Driver codepublic static void main(String args[]){ for(int i = 0; i <= 10; i++) gr.add(new Vector<Integer>()); // Here zero is for parent of node 1 int color[] = { 0, 1, 2, 3, 2, 2, 3 }; // Adding edges in the graph Add_Edge(1, 2); Add_Edge(1, 3); Add_Edge(2, 4); Add_Edge(2, 5); Add_Edge(3, 6); // Dfs call dfs(1, 0, color); // Required answer System.out.println( ans);}} // This code is contributed by Arnab Kundu
# Python3 implementation of the approach # To store the required answerans = 0 # To store the graphgr = [[] for i in range(100005)] # Function to add edgesdef Add_Edge(u, v): gr[u].append(v) gr[v].append(u) # Dfs functiondef dfs(child, par, color): global ans # When there is difference in colors if (color[child] != color[par]): ans += 1 # For all it's child nodes for it in gr[child]: if (it == par): continue dfs(it, child, color) # Driver code # Here zero is for parent of node 1color = [0, 1, 2, 3, 2, 2, 3] # Adding edges in the graphAdd_Edge(1, 2)Add_Edge(1, 3)Add_Edge(2, 4)Add_Edge(2, 5)Add_Edge(3, 6) # Dfs calldfs(1, 0, color) # Required answerprint(ans) # This code is contributed# by mohit kumar
// C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ // To store the required answer static int ans = 0; // To store the graph static List<List<int>> gr = new List<List<int>>(); // Function to add edges static void Add_Edge(int u, int v) { gr[u].Add(v); gr[v].Add(u); } // Dfs function static void dfs(int child, int par, int []color) { // When there is difference in colors if (color[child] != color[par]) ans++; // For all it's child nodes for (int i = 0; i < gr[child].Count; i++) { if (gr[child][i] == par) continue; dfs(gr[child][i], child, color); } } // Driver code public static void Main(String []args) { for(int i = 0; i <= 10; i++) gr.Add(new List<int>()); // Here zero is for parent of node 1 int []color = { 0, 1, 2, 3, 2, 2, 3 }; // Adding edges in the graph Add_Edge(1, 2); Add_Edge(1, 3); Add_Edge(2, 4); Add_Edge(2, 5); Add_Edge(3, 6); // Dfs call dfs(1, 0, color); // Required answer Console.WriteLine( ans); }} // This code has been contributed by 29AjayKumar
<script>// Javascript implementation of the approach // To store the required answerlet ans = 0; // To store the graphlet gr = []; // Function to add edgesfunction Add_Edge(u,v){ gr[u].push(v); gr[v].push(u);} // Dfs functionfunction dfs(child,par,color){ // When there is difference in colors if (color[child] != color[par]) ans++; // For all it's child nodes for (let i = 0; i < gr[child].length; i++) { if (gr[child][i] == par) continue; dfs(gr[child][i], child, color); }} // Driver codefor(let i = 0; i <= 10; i++) gr.push([]); // Here zero is for parent of node 1 let color = [ 0, 1, 2, 3, 2, 2, 3 ]; // Adding edges in the graph Add_Edge(1, 2); Add_Edge(1, 3); Add_Edge(2, 4); Add_Edge(2, 5); Add_Edge(3, 6); // Dfs call dfs(1, 0, color); // Required answer document.write( ans); // This code is contributed by unknown2108</script>
3
mohit kumar 29
andrew1234
29AjayKumar
unknown2108
DFS
Graph Coloring
Graph
Mathematical
Tree
Mathematical
DFS
Graph
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Topological Sorting
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Find if there is a path between two vertices in a directed graph
Detect Cycle in a Directed Graph
Introduction to Data Structures
Program for Fibonacci numbers
Set in C++ Standard Template Library (STL)
Write a program to print all permutations of a given string
C++ Data Types
Merge two sorted arrays
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n03 Jun, 2021"
},
{
"code": null,
"e": 501,
"s": 52,
"text": "Given a tree with N nodes which initially have no color and an array color[] of size N which represent the color of each node after the coloring process takes place. The task is to color the tree into the given colors using the smallest possible number of steps. On each step, one can choose a vertex v and a color x, and then color all vertices in the sub-tree of v (including v itself) with color x. Note that root is vertex number 1. Examples: "
},
{
"code": null,
"e": 540,
"s": 501,
"text": "Input: color[] = { 1, 1, 2, 1, 3, 1} "
},
{
"code": null,
"e": 806,
"s": 540,
"text": "Output: 4 Color the sub-tree rooted at node 1 with color 1. Then all the vertices have colors 1. Now, color the sub-tree rooted at 3 with color 2. Finally, color the sub-trees rooted at 5 and 6 with colors 3 and 1 respectively.Input: color[] = { 1, 2, 3, 2, 2, 3} "
},
{
"code": null,
"e": 818,
"s": 806,
"text": "Output: 3 "
},
{
"code": null,
"e": 1083,
"s": 820,
"text": "Approach: Call a DFS function at vertex 1 and initially keep answer as zero. Increment the answer whenever there is a difference in colors of child and parent nodes. See the below code for better understanding.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1087,
"s": 1083,
"text": "C++"
},
{
"code": null,
"e": 1092,
"s": 1087,
"text": "Java"
},
{
"code": null,
"e": 1100,
"s": 1092,
"text": "Python3"
},
{
"code": null,
"e": 1103,
"s": 1100,
"text": "C#"
},
{
"code": null,
"e": 1114,
"s": 1103,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // To store the required answerint ans = 0; // To store the graphvector<int> gr[100005]; // Function to add edgesvoid Add_Edge(int u, int v){ gr[u].push_back(v); gr[v].push_back(u);} // Dfs functionvoid dfs(int child, int par, int color[]){ // When there is difference in colors if (color[child] != color[par]) ans++; // For all it's child nodes for (auto it : gr[child]) { if (it == par) continue; dfs(it, child, color); }} // Driver codeint main(){ // Here zero is for parent of node 1 int color[] = { 0, 1, 2, 3, 2, 2, 3 }; // Adding edges in the graph Add_Edge(1, 2); Add_Edge(1, 3); Add_Edge(2, 4); Add_Edge(2, 5); Add_Edge(3, 6); // Dfs call dfs(1, 0, color); // Required answer cout << ans; return 0;}",
"e": 2004,
"s": 1114,
"text": null
},
{
"code": "// Java implementation of the approachimport java.util.*; class GFG{ // To store the required answerstatic int ans = 0; // To store the graphstatic Vector<Vector<Integer>> gr = new Vector<Vector<Integer>>(); // Function to add edgesstatic void Add_Edge(int u, int v){ gr.get(u).add(v); gr.get(v).add(u);} // Dfs functionstatic void dfs(int child, int par, int color[]){ // When there is difference in colors if (color[child] != color[par]) ans++; // For all it's child nodes for (int i = 0; i < gr.get(child).size(); i++) { if (gr.get(child).get(i) == par) continue; dfs(gr.get(child).get(i), child, color); }} // Driver codepublic static void main(String args[]){ for(int i = 0; i <= 10; i++) gr.add(new Vector<Integer>()); // Here zero is for parent of node 1 int color[] = { 0, 1, 2, 3, 2, 2, 3 }; // Adding edges in the graph Add_Edge(1, 2); Add_Edge(1, 3); Add_Edge(2, 4); Add_Edge(2, 5); Add_Edge(3, 6); // Dfs call dfs(1, 0, color); // Required answer System.out.println( ans);}} // This code is contributed by Arnab Kundu",
"e": 3138,
"s": 2004,
"text": null
},
{
"code": "# Python3 implementation of the approach # To store the required answerans = 0 # To store the graphgr = [[] for i in range(100005)] # Function to add edgesdef Add_Edge(u, v): gr[u].append(v) gr[v].append(u) # Dfs functiondef dfs(child, par, color): global ans # When there is difference in colors if (color[child] != color[par]): ans += 1 # For all it's child nodes for it in gr[child]: if (it == par): continue dfs(it, child, color) # Driver code # Here zero is for parent of node 1color = [0, 1, 2, 3, 2, 2, 3] # Adding edges in the graphAdd_Edge(1, 2)Add_Edge(1, 3)Add_Edge(2, 4)Add_Edge(2, 5)Add_Edge(3, 6) # Dfs calldfs(1, 0, color) # Required answerprint(ans) # This code is contributed# by mohit kumar",
"e": 3906,
"s": 3138,
"text": null
},
{
"code": "// C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ // To store the required answer static int ans = 0; // To store the graph static List<List<int>> gr = new List<List<int>>(); // Function to add edges static void Add_Edge(int u, int v) { gr[u].Add(v); gr[v].Add(u); } // Dfs function static void dfs(int child, int par, int []color) { // When there is difference in colors if (color[child] != color[par]) ans++; // For all it's child nodes for (int i = 0; i < gr[child].Count; i++) { if (gr[child][i] == par) continue; dfs(gr[child][i], child, color); } } // Driver code public static void Main(String []args) { for(int i = 0; i <= 10; i++) gr.Add(new List<int>()); // Here zero is for parent of node 1 int []color = { 0, 1, 2, 3, 2, 2, 3 }; // Adding edges in the graph Add_Edge(1, 2); Add_Edge(1, 3); Add_Edge(2, 4); Add_Edge(2, 5); Add_Edge(3, 6); // Dfs call dfs(1, 0, color); // Required answer Console.WriteLine( ans); }} // This code has been contributed by 29AjayKumar",
"e": 5223,
"s": 3906,
"text": null
},
{
"code": "<script>// Javascript implementation of the approach // To store the required answerlet ans = 0; // To store the graphlet gr = []; // Function to add edgesfunction Add_Edge(u,v){ gr[u].push(v); gr[v].push(u);} // Dfs functionfunction dfs(child,par,color){ // When there is difference in colors if (color[child] != color[par]) ans++; // For all it's child nodes for (let i = 0; i < gr[child].length; i++) { if (gr[child][i] == par) continue; dfs(gr[child][i], child, color); }} // Driver codefor(let i = 0; i <= 10; i++) gr.push([]); // Here zero is for parent of node 1 let color = [ 0, 1, 2, 3, 2, 2, 3 ]; // Adding edges in the graph Add_Edge(1, 2); Add_Edge(1, 3); Add_Edge(2, 4); Add_Edge(2, 5); Add_Edge(3, 6); // Dfs call dfs(1, 0, color); // Required answer document.write( ans); // This code is contributed by unknown2108</script>",
"e": 6176,
"s": 5223,
"text": null
},
{
"code": null,
"e": 6178,
"s": 6176,
"text": "3"
},
{
"code": null,
"e": 6195,
"s": 6180,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 6206,
"s": 6195,
"text": "andrew1234"
},
{
"code": null,
"e": 6218,
"s": 6206,
"text": "29AjayKumar"
},
{
"code": null,
"e": 6230,
"s": 6218,
"text": "unknown2108"
},
{
"code": null,
"e": 6234,
"s": 6230,
"text": "DFS"
},
{
"code": null,
"e": 6249,
"s": 6234,
"text": "Graph Coloring"
},
{
"code": null,
"e": 6255,
"s": 6249,
"text": "Graph"
},
{
"code": null,
"e": 6268,
"s": 6255,
"text": "Mathematical"
},
{
"code": null,
"e": 6273,
"s": 6268,
"text": "Tree"
},
{
"code": null,
"e": 6286,
"s": 6273,
"text": "Mathematical"
},
{
"code": null,
"e": 6290,
"s": 6286,
"text": "DFS"
},
{
"code": null,
"e": 6296,
"s": 6290,
"text": "Graph"
},
{
"code": null,
"e": 6301,
"s": 6296,
"text": "Tree"
},
{
"code": null,
"e": 6399,
"s": 6301,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6419,
"s": 6399,
"text": "Topological Sorting"
},
{
"code": null,
"e": 6477,
"s": 6419,
"text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2"
},
{
"code": null,
"e": 6542,
"s": 6477,
"text": "Find if there is a path between two vertices in a directed graph"
},
{
"code": null,
"e": 6575,
"s": 6542,
"text": "Detect Cycle in a Directed Graph"
},
{
"code": null,
"e": 6607,
"s": 6575,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 6637,
"s": 6607,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 6680,
"s": 6637,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 6740,
"s": 6680,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 6755,
"s": 6740,
"text": "C++ Data Types"
}
] |
How to Build a SOS Mobile Application in Android Studio?
|
05 Jan, 2022
The SOS applications are basically advanced emergency apps that can rescue you and/or your loved ones if you and/or they find themselves in a life-threatening emergency situation and need immediate assistance. When you need some personal assistance, you can actually turn on your phone and can call or message someone for help. But in a life-threatening emergency like attack, sexual assault, robbery, harassment, accident, fire, birth assistance, we don’t have time to open our phone, instead, we need some accessibility methods by which we can reach out for help without actually operating the phone. In this article, we would be building such an application for android.
Can you think of some easiest ways of stimulating some functions in your phone, without actually turning ON your phone’s screen? One such way is by shaking your phone. We will be creating a service, and in that service, we would listen for a Shake Event by the phone. When we register a shake event i.e., when the user shakes the phone, we would send the user’s location with a predefined message to all the contacts which the user has previously added to the app. Now with every release of Android, Google has made some strict regulations regarding fetching of the User’s location, and also it is important when it comes to data security. And this makes it difficult to create such an SOS application for newer versions of Android.
Services,
Runtime Permission Management,
Populating ListView,
Broadcast Receiver,
Database Management in Android
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.
Create a folder Contacts, in this, we will handle all the files which would populate the ListView by the contacts that the user selects to send messages at the time of emergency.
Step 2.1: Creating model class for Contact
Create a model class that will hold the data of Contact, mainly Name and Phone Number. Apart from the usual constructor and getters and setters, we have an additional validate(String) method. This method checks if the retrieved phone number is in the correct format(+91XXXXXXXXXX) or not. If not, then it converts the string and returns the formatted string. Below is the code for the ContactModel.java file.
Java
public class ContactModel { private int id; private String phoneNo; private String name; // constructor public ContactModel(int id, String name, String phoneNo) { this.id = id; this.phoneNo = validate(phoneNo); this.name = name; } // validate the phone number, and reformat is necessary private String validate(String phone) { // creating StringBuilder for both the cases StringBuilder case1 = new StringBuilder("+91"); StringBuilder case2 = new StringBuilder(""); // check if the string already has a "+" if (phone.charAt(0) != '+') { for (int i = 0; i < phone.length(); i++) { // remove any spaces or "-" if (phone.charAt(i) != '-' && phone.charAt(i) != ' ') { case1.append(phone.charAt(i)); } } return case1.toString(); } else { for (int i = 0; i < phone.length(); i++) { // remove any spaces or "-" if (phone.charAt(i) != '-' || phone.charAt(i) != ' ') { case2.append(phone.charAt(i)); } } return case2.toString(); } } public String getPhoneNo() { return phoneNo; } public int getId() { return id; } public String getName() { return name; } public void setName(String name) { this.name = name; }}
Step 2.2: Creating a Database Helper class
We need to store all the contacts, the user selects, into a Database so that it is available every time the app needs it. We will populate the ListView with the help of this database and also at the time of sending messages, we will retrieve the contacts in a list from this database. Below is the code for the DbHelper.java file.
Java
import android.content.ContentValues;import android.content.Context;import android.database.Cursor;import android.database.sqlite.SQLiteDatabase;import android.database.sqlite.SQLiteOpenHelper; import java.util.ArrayList;import java.util.List; public class DbHelper extends SQLiteOpenHelper { // Database Version private static final int DATABASE_VERSION = 1; // Database Name private static final String DATABASE_NAME = "contactdata"; // Country table name private static final String TABLE_NAME= "contacts"; // Country Table Columns names private static final String KEY_ID = "id"; private static final String NAME = "Name"; private static final String PHONENO = "PhoneNo"; public DbHelper(Context context){ super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { // create the table for the first time String CREATE_COUNTRY_TABLE = "CREATE TABLE " + TABLE_NAME + "(" + KEY_ID + " INTEGER PRIMARY KEY," + NAME + " TEXT," + PHONENO + " TEXT" + ")"; db.execSQL(CREATE_COUNTRY_TABLE); } @Override public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) { } // method to add the contact public void addcontact(ContactModel contact){ SQLiteDatabase db=this.getWritableDatabase(); ContentValues c=new ContentValues(); c.put(NAME,contact.getName()); c.put(PHONENO,contact.getPhoneNo()); db.insert(TABLE_NAME,null,c); db.close(); } // method to retrieve all the contacts in List public List<ContactModel> getAllContacts(){ List<ContactModel> list=new ArrayList<>(); String query="SELECT * FROM "+TABLE_NAME; SQLiteDatabase db=this.getReadableDatabase(); Cursor c=db.rawQuery(query,null); if(c.moveToFirst()) { do { list.add(new ContactModel(c.getInt(0),c.getString(1),c.getString(2))); } while (c.moveToNext()); } return list; } // get the count of data, this will allow user // to not add more that five contacts in database public int count(){ int count=0; String query="SELECT COUNT(*) FROM "+TABLE_NAME; SQLiteDatabase db = this.getReadableDatabase(); Cursor c=db.rawQuery(query,null); if(c.getCount()>0){ c.moveToFirst(); count=c.getInt(0); } c.close(); return count; } // Deleting single country public void deleteContact(ContactModel contact) { SQLiteDatabase db = this.getWritableDatabase(); int i=db.delete(TABLE_NAME,KEY_ID + " = ?", new String[] { String.valueOf(contact.getId()) }); db.close(); }}
Step 2.3: Creating a CustomAdapter.java
In order to handle the data in ListView, we will need a Customised Adapter. We will add a LongClickListener on the LinerLayout so that whenever a user wants to delete an existing item from ListView he can simply long-press that item. And in return, we would show a dialog asking for confirmation. As the user confirms, we will also delete that item from the database too. Below is the code for the CustomAdapter.java file.
Java
import android.content.Context;import android.content.DialogInterface;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ArrayAdapter;import android.widget.LinearLayout;import android.widget.TextView;import android.widget.Toast; import androidx.annotation.NonNull; import com.google.android.material.dialog.MaterialAlertDialogBuilder;import com.raghav.sos.R; import java.util.List; public class CustomAdapter extends ArrayAdapter<ContactModel> { Context context; List<ContactModel> contacts; public CustomAdapter(@NonNull Context context, List<ContactModel> contacts) { super(context, 0, contacts); this.context = context; this.contacts = contacts; } @Override public View getView(int position, View convertView, ViewGroup parent) { // create a database helper object // to handle the database manipulations DbHelper db = new DbHelper(context); // Get the data item for this position ContactModel c = getItem(position); // Check if an existing view is being reused, otherwise inflate the view if (convertView == null) { convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_user, parent, false); } LinearLayout linearLayout = (LinearLayout) convertView.findViewById(R.id.linear); // Lookup view for data population TextView tvName = (TextView) convertView.findViewById(R.id.tvName); TextView tvPhone = (TextView) convertView.findViewById(R.id.tvPhone); // Populate the data into the template // view using the data object tvName.setText(c.getName()); tvPhone.setText(c.getPhoneNo()); linearLayout.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View view) { // generate an MaterialAlertDialog Box new MaterialAlertDialogBuilder(context) .setTitle("Remove Contact") .setMessage("Are you sure want to remove this contact?") .setPositiveButton("YES", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { // delete the specified contact from the database db.deleteContact(c); // remove the item from the list contacts.remove(c); // notify the listview that dataset has been changed notifyDataSetChanged(); Toast.makeText(context, "Contact removed!", Toast.LENGTH_SHORT).show(); } }) .setNegativeButton("NO", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { } }) .show(); return false; } }); // Return the completed view to render on screen return convertView; } // this method will update the ListView public void refresh(List<ContactModel> list) { contacts.clear(); contacts.addAll(list); notifyDataSetChanged(); }}
Step 2.4: item_user.xml
Layout file for each item in ListView.
XML
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/linear" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:padding="4dp"> <androidx.cardview.widget.CardView android:id="@+id/cardview" android:layout_width="match_parent" android:layout_height="wrap_content"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <TextView android:id="@+id/tvName" style="@style/TextAppearance.AppCompat.Medium" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Name" android:textColor="@color/design_default_color_secondary" /> <TextView android:id="@+id/tvPhone" style="@style/TextAppearance.AppCompat.Large" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Phone" android:textColor="@color/design_default_color_secondary_variant" android:textStyle="bold" /> </LinearLayout> </androidx.cardview.widget.CardView> </LinearLayout>
This module would contain all the necessary functionality for shake detection, running services, and registering a Broadcast Receiver.
Step 3.1: Creating ShakeDetector class
Here we implement the SensorEventListener which is used for receiving notifications from the SensorManager when there is a new or change in sensor data. Now, in order to register the shake event, the G-Force by which the sensor experience when the user shakes the phone must be greater than 1G. This is because there may be cases when the phone might shake while in the pocket, or in the car, etc. And also to resolve this drawback we include a count mechanism that would count the number of shakes, i.e. if the user shakes the device 3 consecutive times, then we would register a shake event. And to do so the time between the two successive shakes should be minimum i.e. around 500ms. We will also make the shake count to zero after 3 seconds of inactivity. This would allow the user to again shake the phone to send messages. Below is the code for the ShakeDetector.java file.
Java
import android.hardware.Sensor;import android.hardware.SensorEvent;import android.hardware.SensorEventListener;import android.hardware.SensorManager; public class ShakeDetector implements SensorEventListener { /* * The gForce that is necessary to register as shake. * Must be greater than 1G (one earth gravity unit). * You can install "G-Force", by Blake La Pierre * from the Google Play Store and run it to see how * many G's it takes to register a shake */ private static final float SHAKE_THRESHOLD_GRAVITY = 2.7F; private static final int SHAKE_SLOP_TIME_MS = 500; private static final int SHAKE_COUNT_RESET_TIME_MS = 3000; private OnShakeListener mListener; private long mShakeTimestamp; private int mShakeCount; public void setOnShakeListener(OnShakeListener listener) { this.mListener = listener; } public interface OnShakeListener { public void onShake(int count); } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { // ignore } @Override public void onSensorChanged(SensorEvent event) { if (mListener != null) { float x = event.values[0]; float y = event.values[1]; float z = event.values[2]; float gX = x / SensorManager.GRAVITY_EARTH; float gY = y / SensorManager.GRAVITY_EARTH; float gZ = z / SensorManager.GRAVITY_EARTH; // gForce will be close to 1 when there is no movement. Float f = new Float(gX * gX + gY * gY + gZ * gZ); Double d = Math.sqrt(f.doubleValue()); float gForce = d.floatValue(); if (gForce > SHAKE_THRESHOLD_GRAVITY) { final long now = System.currentTimeMillis(); // ignore shake events too close to each other (500ms) if (mShakeTimestamp + SHAKE_SLOP_TIME_MS > now) { return; } // reset the shake count after 3 seconds of no shakes if (mShakeTimestamp + SHAKE_COUNT_RESET_TIME_MS < now) { mShakeCount = 0; } mShakeTimestamp = now; mShakeCount++; mListener.onShake(mShakeCount); } } }}
Step 3.2: Creating the SensorService
Creating a sensor service. From the commencement of Android 6, Google has included some extra security checks regarding background services. Now handling of services is completely different as it was done previously.
Our main focus while building this app should be on how we can keep the service running even when the app is not running (even removed from the recent).
For service to run while the host application is Dead, is called Service to run in the background. And to make a service run in the background we need some extra permissions. In Android O and above we can’t have background service, instead, we can use the Foreground Services. Foreground services perform operations that are noticeable to the user.
A status bar warning with a priority of PRIORITY LOW or higher must be shown for each foreground operation. Users would be conscious that the app is running in the foreground and using machine resources in this manner. Unless the service is discontinued or withdrawn from the foreground, the message cannot be ignored.
Java
@RequiresApi(Build.VERSION_CODES.O)private void startMyOwnForeground(){ String NOTIFICATION_CHANNEL_ID = "example.permanence"; String channelName = "Background Service"; NotificationChannel chan = new NotificationChannel( NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_MIN); NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE); assert manager != null; manager.createNotificationChannel(chan); NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID); Notification notification = notificationBuilder.setOngoing(true) .setContentTitle("You are protected.") .setContentText("We are there for you") // this is important, otherwise the // notification will show the way you want i.e. // it will show some default notification .setSmallIcon(R.drawable.ic_launcher_foreground) .setPriority(NotificationManager.IMPORTANCE_MIN) .setCategory(Notification.CATEGORY_SERVICE) .build(); startForeground(2, notification);}
If you start a service starts with the START STICKY return type, it will run in the background even if the host activity is not running in the foreground. If Android has to forcibly close a program due to a memory error or other reasons, the service will be restarted without the user’s intervention.
Java
@Overridepublic int onStartCommand(Intent intent, int flags, int startId) { super.onStartCommand(intent, flags, startId); return START_STICKY;}
In order to make the user aware that the Shake event has been registered or say the messages have been delivered, we create a vibrate() method. This will make the phone vibrate in a defined wave format.
Java
// method to vibrate the phonepublic void vibrate(){ final Vibrator vibrator = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE); VibrationEffect vibEff; // Android Q and above have some predefined vibrating // patterns if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { vibEff = VibrationEffect.createPredefined(VibrationEffect.EFFECT_DOUBLE_CLICK); vibrator.cancel(); vibrator.vibrate(vibEff); } else { vibrator.vibrate(500); }}
Now, in order to fetch the user location, we will use FusedLocationProviderClient. The FusedLocationProviderClient has a function named getCurremtLocation(). This method provides the current location of the user when asked for. But this method requires the mobile phone’s GPS to be turned ON. Otherwise, it will return a null location. From Android O and above, in order to fetch location or anything which would reveal the user’s location to the app, the location services or the GPS should be turned ON. So, that the user is aware of the location usages by the app.
Java
FusedLocationProviderClient fusedLocationClient = LocationServices.getFusedLocationProviderClient(getApplicationContext()); fusedLocationClient.getCurrentLocation(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY, new CancellationToken() { @Override public boolean isCancellationRequested() { return false; } @NonNull @Override public CancellationToken onCanceledRequested( @NonNull OnTokenCanceledListener onTokenCanceledListener) { return null; } }) .addOnSuccessListener( new OnSuccessListener<Location>() { @Override public void onSuccess(Location location) { // check if location is null // for both the cases we will create // different messages if (location != null) { ... } else { ... } } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { ... } });
Further, when we retrieve the location successfully, we Create a SMSManager object which will help us to send messages to all the contacts from the database. In case the user’s location services are not ON, we can generate a different message without the coordinates. So that one receiving the emergency message knows that the host device didn’t have location services on at that moment. He can then directly coordinate with the nearby Police department who can then track the person’s device location.
Java
SmsManager smsManager = SmsManager.getDefault();DbHelper db = new DbHelper(SensorService.this);List<ContactModel> list = db.getAllContacts();for (ContactModel c : list) { String message = "Hey, " + c.getName() + "I am in DANGER, i need help. Please urgently reach me out. Here are my coordinates.\n " + "http://maps.google.com/?q=" + location.getLatitude() + "," + location.getLongitude(); smsManager.sendTextMessage(c.getPhoneNo(), null, message, null, null);}
Till now whatever we have done will work until the activity is in Foreground or Running. But what when the user kills the application? Or locks the phone? For this, we create a BroadcastReceiver.
Below is the complete code for the SensorService.java file.
Java
import android.annotation.SuppressLint;import android.app.Notification;import android.app.NotificationChannel;import android.app.NotificationManager;import android.app.Service;import android.content.Context;import android.content.Intent;import android.hardware.Sensor;import android.hardware.SensorManager;import android.location.Location;import android.os.Build;import android.os.IBinder;import android.os.VibrationEffect;import android.os.Vibrator;import android.telephony.SmsManager;import android.util.Log; import androidx.annotation.NonNull;import androidx.annotation.RequiresApi;import androidx.core.app.NotificationCompat; import com.google.android.gms.location.FusedLocationProviderClient;import com.google.android.gms.location.LocationRequest;import com.google.android.gms.location.LocationServices;import com.google.android.gms.tasks.CancellationToken;import com.google.android.gms.tasks.OnFailureListener;import com.google.android.gms.tasks.OnSuccessListener;import com.google.android.gms.tasks.OnTokenCanceledListener;import com.raghav.sos.Contacts.ContactModel;import com.raghav.sos.Contacts.DbHelper;import com.raghav.sos.R; import java.util.List; public class SensorService extends Service { private SensorManager mSensorManager; private Sensor mAccelerometer; private ShakeDetector mShakeDetector; public SensorService() { } @Override public IBinder onBind(Intent intent) { // TODO: Return the communication channel to the service. throw new UnsupportedOperationException("Not yet implemented"); } @Override public int onStartCommand(Intent intent, int flags, int startId) { super.onStartCommand(intent, flags, startId); return START_STICKY; } @Override public void onCreate() { super.onCreate(); // start the foreground service if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) startMyOwnForeground(); else startForeground(1, new Notification()); // ShakeDetector initialization mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); mShakeDetector = new ShakeDetector(); mShakeDetector.setOnShakeListener(new ShakeDetector.OnShakeListener() { @SuppressLint("MissingPermission") @Override public void onShake(int count) { // check if the user has shacked // the phone for 3 time in a row if (count == 3) { // vibrate the phone vibrate(); // create FusedLocationProviderClient to get the user location FusedLocationProviderClient fusedLocationClient = LocationServices.getFusedLocationProviderClient(getApplicationContext()); // use the PRIORITY_BALANCED_POWER_ACCURACY // so that the service doesn't use unnecessary power via GPS // it will only use GPS at this very moment fusedLocationClient.getCurrentLocation(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY, new CancellationToken() { @Override public boolean isCancellationRequested() { return false; } @NonNull @Override public CancellationToken onCanceledRequested(@NonNull OnTokenCanceledListener onTokenCanceledListener) { return null; } }).addOnSuccessListener(new OnSuccessListener<Location>() { @Override public void onSuccess(Location location) { // check if location is null // for both the cases we will // create different messages if (location != null) { // get the SMSManager SmsManager smsManager = SmsManager.getDefault(); // get the list of all the contacts in Database DbHelper db = new DbHelper(SensorService.this); List<ContactModel> list = db.getAllContacts(); // send SMS to each contact for (ContactModel c : list) { String message = "Hey, " + c.getName() + "I am in DANGER, i need help. Please urgently reach me out. Here are my coordinates.\n " + "http://maps.google.com/?q=" + location.getLatitude() + "," + location.getLongitude(); smsManager.sendTextMessage(c.getPhoneNo(), null, message, null, null); } } else { String message = "I am in DANGER, i need help. Please urgently reach me out.\n" + "GPS was turned off.Couldn't find location. Call your nearest Police Station."; SmsManager smsManager = SmsManager.getDefault(); DbHelper db = new DbHelper(SensorService.this); List<ContactModel> list = db.getAllContacts(); for (ContactModel c : list) { smsManager.sendTextMessage(c.getPhoneNo(), null, message, null, null); } } } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Log.d("Check: ", "OnFailure"); String message = "I am in DANGER, i need help. Please urgently reach me out.\n" + "GPS was turned off.Couldn't find location. Call your nearest Police Station."; SmsManager smsManager = SmsManager.getDefault(); DbHelper db = new DbHelper(SensorService.this); List<ContactModel> list = db.getAllContacts(); for (ContactModel c : list) { smsManager.sendTextMessage(c.getPhoneNo(), null, message, null, null); } } }); } } }); // register the listener mSensorManager.registerListener(mShakeDetector, mAccelerometer, SensorManager.SENSOR_DELAY_UI); } // method to vibrate the phone public void vibrate() { final Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE); VibrationEffect vibEff; // Android Q and above have some predefined vibrating patterns if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { vibEff = VibrationEffect.createPredefined(VibrationEffect.EFFECT_DOUBLE_CLICK); vibrator.cancel(); vibrator.vibrate(vibEff); } else { vibrator.vibrate(500); } } // For Build versions higher than Android Oreo, we launch // a foreground service in a different way. This is due to the newly // implemented strict notification rules, which require us to identify // our own notification channel in order to view them correctly. @RequiresApi(Build.VERSION_CODES.O) private void startMyOwnForeground() { String NOTIFICATION_CHANNEL_ID = "example.permanence"; String channelName = "Background Service"; NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_MIN); NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); assert manager != null; manager.createNotificationChannel(chan); NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID); Notification notification = notificationBuilder.setOngoing(true) .setContentTitle("You are protected.") .setContentText("We are there for you") // this is important, otherwise the notification will show the way // you want i.e. it will show some default notification .setSmallIcon(R.drawable.ic_launcher_foreground) .setPriority(NotificationManager.IMPORTANCE_MIN) .setCategory(Notification.CATEGORY_SERVICE) .build(); startForeground(2, notification); } @Override public void onDestroy() { // create an Intent to call the Broadcast receiver Intent broadcastIntent = new Intent(); broadcastIntent.setAction("restartservice"); broadcastIntent.setClass(this, ReactivateService.class); this.sendBroadcast(broadcastIntent); super.onDestroy(); } }
Step 3.3: Creating the Broadcast Receiver
Whenever a service is destroyed, the onDestroy method is called, and we will use that method to call a broadcast receiver before the service is actually destroyed.
The broadcast receiver in return again starts the service. And our problem is resolved!! The service now runs without the host activity in the background.
Below is the complete code for the ReactivateService.java file.
Java
import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.os.Build;import android.util.Log; public class ReactivateService extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Log.d("Check: ","Receiver Started"); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { context.startForegroundService(new Intent(context, SensorService.class)); } else { context.startService(new Intent(context, SensorService.class)); } }}
Step 4: Working with the MainActivity
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.Manifest;import android.annotation.SuppressLint;import android.app.Activity;import android.app.ActivityManager;import android.content.Context;import android.content.Intent;import android.content.pm.PackageManager;import android.database.Cursor;import android.net.Uri;import android.os.Build;import android.os.Bundle;import android.os.PowerManager;import android.provider.ContactsContract;import android.provider.Settings;import android.util.Log;import android.view.View;import android.widget.Button;import android.widget.ListView;import android.widget.Toast; import androidx.annotation.NonNull;import androidx.annotation.Nullable;import androidx.appcompat.app.AppCompatActivity;import androidx.core.app.ActivityCompat; import com.raghav.sos.Contacts.ContactModel;import com.raghav.sos.Contacts.CustomAdapter;import com.raghav.sos.Contacts.DbHelper;import com.raghav.sos.ShakeServices.ReactivateService;import com.raghav.sos.ShakeServices.SensorService; import java.util.List; public class MainActivity extends AppCompatActivity { private static final int IGNORE_BATTERY_OPTIMIZATION_REQUEST = 1002; private static final int PICK_CONTACT = 1; // create instances of various classes to be used Button button1; ListView listView; DbHelper db; List<ContactModel> list; CustomAdapter customAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // check for runtime permissions if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_DENIED) { requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.SEND_SMS, Manifest.permission.READ_CONTACTS}, 100); } } // this is a special permission required only by devices using // Android Q and above. The Access Background Permission is responsible // for populating the dialog with "ALLOW ALL THE TIME" option if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { requestPermissions(new String[]{Manifest.permission.ACCESS_BACKGROUND_LOCATION}, 100); } // check for BatteryOptimization, PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (pm != null && !pm.isIgnoringBatteryOptimizations(getPackageName())) { askIgnoreOptimization(); } } // start the service SensorService sensorService = new SensorService(); Intent intent = new Intent(this, sensorService.getClass()); if (!isMyServiceRunning(sensorService.getClass())) { startService(intent); } button1 = findViewById(R.id.Button1); listView = (ListView) findViewById(R.id.ListView); db = new DbHelper(this); list = db.getAllContacts(); customAdapter = new CustomAdapter(this, list); listView.setAdapter(customAdapter); button1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // calling of getContacts() if (db.count() != 5) { Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI); startActivityForResult(intent, PICK_CONTACT); } else { Toast.makeText(MainActivity.this, "Can't Add more than 5 Contacts", Toast.LENGTH_SHORT).show(); } } }); } // method to check if the service is running private boolean isMyServiceRunning(Class<?> serviceClass) { ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE); for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) { if (serviceClass.getName().equals(service.service.getClassName())) { Log.i("Service status", "Running"); return true; } } Log.i("Service status", "Not running"); return false; } @Override protected void onDestroy() { Intent broadcastIntent = new Intent(); broadcastIntent.setAction("restartservice"); broadcastIntent.setClass(this, ReactivateService.class); this.sendBroadcast(broadcastIntent); super.onDestroy(); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == 100) { if (grantResults[0] == PackageManager.PERMISSION_DENIED) { Toast.makeText(this, "Permissions Denied!\n Can't use the App!", Toast.LENGTH_SHORT).show(); } } } @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); // get the contact from the PhoneBook of device switch (requestCode) { case (PICK_CONTACT): if (resultCode == Activity.RESULT_OK) { Uri contactData = data.getData(); Cursor c = managedQuery(contactData, null, null, null, null); if (c.moveToFirst()) { String id = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts._ID)); String hasPhone = c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)); String phone = null; try { if (hasPhone.equalsIgnoreCase("1")) { Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + id, null, null); phones.moveToFirst(); phone = phones.getString(phones.getColumnIndex("data1")); } String name = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)); db.addcontact(new ContactModel(0, name, phone)); list = db.getAllContacts(); customAdapter.refresh(list); } catch (Exception ex) { } } } break; } } // this method prompts the user to remove any // battery optimisation constraints from the App private void askIgnoreOptimization() { if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) { @SuppressLint("BatteryLife") Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS); intent.setData(Uri.parse("package:" + getPackageName())); startActivityForResult(intent, IGNORE_BATTERY_OPTIMIZATION_REQUEST); } } }
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <Button android:id="@+id/Button1" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="12dp" android:background="#0F9D58" android:text="Add Emergency Contact " android:textColor="#FFFFFF" /> <ListView android:id="@+id/ListView" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout>
Step 5: Working with AndroidManifest.xml
XML
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" package="com.raghav.sos"> <uses-permission android:name="android.permission.READ_CONTACTS"/> <uses-permission android:name="android.permission.VIBRATE"/> <uses-permission android:name="android.permission.SEND_SMS"/> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <uses-permission android:name="android.permission.FOREGROUND_SERVICE"/> <!--This permission is necessary for devices with Android O and above, so that we can use the location ALL THE TIME--> <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION"/> <!-- We also ask user to remove any battery optimization constraints during runtime --> <uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS"/> <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/Theme.SOS"> <!-- register the receiver --> <receiver android:name=".ShakeServices.ReactivateService" android:enabled="true" android:exported="true"/> <!-- register the service --> <service android:name=".ShakeServices.SensorService" android:enabled="true" android:exported="true" /> <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>
Output:
Media error: Format(s) not supported or source(s) not found
You can add options for personal assistance emergencies like a map that indicates nearby police stations, hospitals, cabs, etc.You create a logic that sends the user location every 1 or 2 minutes without the user shaking the device again.You can add voice or/and video recording functionality.Also, you can add a call to multiple or a single person at the time of shake.You can try to add OpenCellId, this will allow you to fetch the location of the nearest mobile tower. But again remember that in order to calculate the location you would require some device information(no GPS) and that would require your GPS or location services to be turned ON.Doors to changes in the UI are always open.
You can add options for personal assistance emergencies like a map that indicates nearby police stations, hospitals, cabs, etc.
You create a logic that sends the user location every 1 or 2 minutes without the user shaking the device again.
You can add voice or/and video recording functionality.
Also, you can add a call to multiple or a single person at the time of shake.
You can try to add OpenCellId, this will allow you to fetch the location of the nearest mobile tower. But again remember that in order to calculate the location you would require some device information(no GPS) and that would require your GPS or location services to be turned ON.
Doors to changes in the UI are always open.
Notes:
1. Allow the app to autostart, in order to use the app while the screen is off.
2. Remove any battery optimization constraints on the app. This might make Android kill the service.
3. Allow all the permissions, especially allow location permissions by Allowing the app to use the device location all the time. This would allow the service to use the device location when the shake event is registered.
GitHub Link: https://github.com/raghavtilak/SOS
varshagumber28
Android-Studio
Picked
Android
Java
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n05 Jan, 2022"
},
{
"code": null,
"e": 728,
"s": 54,
"text": "The SOS applications are basically advanced emergency apps that can rescue you and/or your loved ones if you and/or they find themselves in a life-threatening emergency situation and need immediate assistance. When you need some personal assistance, you can actually turn on your phone and can call or message someone for help. But in a life-threatening emergency like attack, sexual assault, robbery, harassment, accident, fire, birth assistance, we don’t have time to open our phone, instead, we need some accessibility methods by which we can reach out for help without actually operating the phone. In this article, we would be building such an application for android."
},
{
"code": null,
"e": 1461,
"s": 728,
"text": "Can you think of some easiest ways of stimulating some functions in your phone, without actually turning ON your phone’s screen? One such way is by shaking your phone. We will be creating a service, and in that service, we would listen for a Shake Event by the phone. When we register a shake event i.e., when the user shakes the phone, we would send the user’s location with a predefined message to all the contacts which the user has previously added to the app. Now with every release of Android, Google has made some strict regulations regarding fetching of the User’s location, and also it is important when it comes to data security. And this makes it difficult to create such an SOS application for newer versions of Android."
},
{
"code": null,
"e": 1471,
"s": 1461,
"text": "Services,"
},
{
"code": null,
"e": 1502,
"s": 1471,
"text": "Runtime Permission Management,"
},
{
"code": null,
"e": 1523,
"s": 1502,
"text": "Populating ListView,"
},
{
"code": null,
"e": 1543,
"s": 1523,
"text": "Broadcast Receiver,"
},
{
"code": null,
"e": 1574,
"s": 1543,
"text": "Database Management in Android"
},
{
"code": null,
"e": 1736,
"s": 1574,
"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": 1915,
"s": 1736,
"text": "Create a folder Contacts, in this, we will handle all the files which would populate the ListView by the contacts that the user selects to send messages at the time of emergency."
},
{
"code": null,
"e": 1958,
"s": 1915,
"text": "Step 2.1: Creating model class for Contact"
},
{
"code": null,
"e": 2367,
"s": 1958,
"text": "Create a model class that will hold the data of Contact, mainly Name and Phone Number. Apart from the usual constructor and getters and setters, we have an additional validate(String) method. This method checks if the retrieved phone number is in the correct format(+91XXXXXXXXXX) or not. If not, then it converts the string and returns the formatted string. Below is the code for the ContactModel.java file."
},
{
"code": null,
"e": 2372,
"s": 2367,
"text": "Java"
},
{
"code": "public class ContactModel { private int id; private String phoneNo; private String name; // constructor public ContactModel(int id, String name, String phoneNo) { this.id = id; this.phoneNo = validate(phoneNo); this.name = name; } // validate the phone number, and reformat is necessary private String validate(String phone) { // creating StringBuilder for both the cases StringBuilder case1 = new StringBuilder(\"+91\"); StringBuilder case2 = new StringBuilder(\"\"); // check if the string already has a \"+\" if (phone.charAt(0) != '+') { for (int i = 0; i < phone.length(); i++) { // remove any spaces or \"-\" if (phone.charAt(i) != '-' && phone.charAt(i) != ' ') { case1.append(phone.charAt(i)); } } return case1.toString(); } else { for (int i = 0; i < phone.length(); i++) { // remove any spaces or \"-\" if (phone.charAt(i) != '-' || phone.charAt(i) != ' ') { case2.append(phone.charAt(i)); } } return case2.toString(); } } public String getPhoneNo() { return phoneNo; } public int getId() { return id; } public String getName() { return name; } public void setName(String name) { this.name = name; }}",
"e": 3833,
"s": 2372,
"text": null
},
{
"code": null,
"e": 3879,
"s": 3836,
"text": "Step 2.2: Creating a Database Helper class"
},
{
"code": null,
"e": 4212,
"s": 3881,
"text": "We need to store all the contacts, the user selects, into a Database so that it is available every time the app needs it. We will populate the ListView with the help of this database and also at the time of sending messages, we will retrieve the contacts in a list from this database. Below is the code for the DbHelper.java file."
},
{
"code": null,
"e": 4219,
"s": 4214,
"text": "Java"
},
{
"code": "import android.content.ContentValues;import android.content.Context;import android.database.Cursor;import android.database.sqlite.SQLiteDatabase;import android.database.sqlite.SQLiteOpenHelper; import java.util.ArrayList;import java.util.List; public class DbHelper extends SQLiteOpenHelper { // Database Version private static final int DATABASE_VERSION = 1; // Database Name private static final String DATABASE_NAME = \"contactdata\"; // Country table name private static final String TABLE_NAME= \"contacts\"; // Country Table Columns names private static final String KEY_ID = \"id\"; private static final String NAME = \"Name\"; private static final String PHONENO = \"PhoneNo\"; public DbHelper(Context context){ super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { // create the table for the first time String CREATE_COUNTRY_TABLE = \"CREATE TABLE \" + TABLE_NAME + \"(\" + KEY_ID + \" INTEGER PRIMARY KEY,\" + NAME + \" TEXT,\" + PHONENO + \" TEXT\" + \")\"; db.execSQL(CREATE_COUNTRY_TABLE); } @Override public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) { } // method to add the contact public void addcontact(ContactModel contact){ SQLiteDatabase db=this.getWritableDatabase(); ContentValues c=new ContentValues(); c.put(NAME,contact.getName()); c.put(PHONENO,contact.getPhoneNo()); db.insert(TABLE_NAME,null,c); db.close(); } // method to retrieve all the contacts in List public List<ContactModel> getAllContacts(){ List<ContactModel> list=new ArrayList<>(); String query=\"SELECT * FROM \"+TABLE_NAME; SQLiteDatabase db=this.getReadableDatabase(); Cursor c=db.rawQuery(query,null); if(c.moveToFirst()) { do { list.add(new ContactModel(c.getInt(0),c.getString(1),c.getString(2))); } while (c.moveToNext()); } return list; } // get the count of data, this will allow user // to not add more that five contacts in database public int count(){ int count=0; String query=\"SELECT COUNT(*) FROM \"+TABLE_NAME; SQLiteDatabase db = this.getReadableDatabase(); Cursor c=db.rawQuery(query,null); if(c.getCount()>0){ c.moveToFirst(); count=c.getInt(0); } c.close(); return count; } // Deleting single country public void deleteContact(ContactModel contact) { SQLiteDatabase db = this.getWritableDatabase(); int i=db.delete(TABLE_NAME,KEY_ID + \" = ?\", new String[] { String.valueOf(contact.getId()) }); db.close(); }}",
"e": 7002,
"s": 4219,
"text": null
},
{
"code": null,
"e": 7045,
"s": 7005,
"text": "Step 2.3: Creating a CustomAdapter.java"
},
{
"code": null,
"e": 7470,
"s": 7047,
"text": "In order to handle the data in ListView, we will need a Customised Adapter. We will add a LongClickListener on the LinerLayout so that whenever a user wants to delete an existing item from ListView he can simply long-press that item. And in return, we would show a dialog asking for confirmation. As the user confirms, we will also delete that item from the database too. Below is the code for the CustomAdapter.java file."
},
{
"code": null,
"e": 7477,
"s": 7472,
"text": "Java"
},
{
"code": "import android.content.Context;import android.content.DialogInterface;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ArrayAdapter;import android.widget.LinearLayout;import android.widget.TextView;import android.widget.Toast; import androidx.annotation.NonNull; import com.google.android.material.dialog.MaterialAlertDialogBuilder;import com.raghav.sos.R; import java.util.List; public class CustomAdapter extends ArrayAdapter<ContactModel> { Context context; List<ContactModel> contacts; public CustomAdapter(@NonNull Context context, List<ContactModel> contacts) { super(context, 0, contacts); this.context = context; this.contacts = contacts; } @Override public View getView(int position, View convertView, ViewGroup parent) { // create a database helper object // to handle the database manipulations DbHelper db = new DbHelper(context); // Get the data item for this position ContactModel c = getItem(position); // Check if an existing view is being reused, otherwise inflate the view if (convertView == null) { convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_user, parent, false); } LinearLayout linearLayout = (LinearLayout) convertView.findViewById(R.id.linear); // Lookup view for data population TextView tvName = (TextView) convertView.findViewById(R.id.tvName); TextView tvPhone = (TextView) convertView.findViewById(R.id.tvPhone); // Populate the data into the template // view using the data object tvName.setText(c.getName()); tvPhone.setText(c.getPhoneNo()); linearLayout.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View view) { // generate an MaterialAlertDialog Box new MaterialAlertDialogBuilder(context) .setTitle(\"Remove Contact\") .setMessage(\"Are you sure want to remove this contact?\") .setPositiveButton(\"YES\", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { // delete the specified contact from the database db.deleteContact(c); // remove the item from the list contacts.remove(c); // notify the listview that dataset has been changed notifyDataSetChanged(); Toast.makeText(context, \"Contact removed!\", Toast.LENGTH_SHORT).show(); } }) .setNegativeButton(\"NO\", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { } }) .show(); return false; } }); // Return the completed view to render on screen return convertView; } // this method will update the ListView public void refresh(List<ContactModel> list) { contacts.clear(); contacts.addAll(list); notifyDataSetChanged(); }}",
"e": 11003,
"s": 7477,
"text": null
},
{
"code": null,
"e": 11030,
"s": 11006,
"text": "Step 2.4: item_user.xml"
},
{
"code": null,
"e": 11071,
"s": 11032,
"text": "Layout file for each item in ListView."
},
{
"code": null,
"e": 11077,
"s": 11073,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:id=\"@+id/linear\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:orientation=\"vertical\" android:padding=\"4dp\"> <androidx.cardview.widget.CardView android:id=\"@+id/cardview\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\"> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\"> <TextView android:id=\"@+id/tvName\" style=\"@style/TextAppearance.AppCompat.Medium\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:text=\"Name\" android:textColor=\"@color/design_default_color_secondary\" /> <TextView android:id=\"@+id/tvPhone\" style=\"@style/TextAppearance.AppCompat.Large\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:text=\"Phone\" android:textColor=\"@color/design_default_color_secondary_variant\" android:textStyle=\"bold\" /> </LinearLayout> </androidx.cardview.widget.CardView> </LinearLayout>",
"e": 12509,
"s": 11077,
"text": null
},
{
"code": null,
"e": 12649,
"s": 12514,
"text": "This module would contain all the necessary functionality for shake detection, running services, and registering a Broadcast Receiver."
},
{
"code": null,
"e": 12690,
"s": 12651,
"text": "Step 3.1: Creating ShakeDetector class"
},
{
"code": null,
"e": 13572,
"s": 12692,
"text": "Here we implement the SensorEventListener which is used for receiving notifications from the SensorManager when there is a new or change in sensor data. Now, in order to register the shake event, the G-Force by which the sensor experience when the user shakes the phone must be greater than 1G. This is because there may be cases when the phone might shake while in the pocket, or in the car, etc. And also to resolve this drawback we include a count mechanism that would count the number of shakes, i.e. if the user shakes the device 3 consecutive times, then we would register a shake event. And to do so the time between the two successive shakes should be minimum i.e. around 500ms. We will also make the shake count to zero after 3 seconds of inactivity. This would allow the user to again shake the phone to send messages. Below is the code for the ShakeDetector.java file."
},
{
"code": null,
"e": 13579,
"s": 13574,
"text": "Java"
},
{
"code": "import android.hardware.Sensor;import android.hardware.SensorEvent;import android.hardware.SensorEventListener;import android.hardware.SensorManager; public class ShakeDetector implements SensorEventListener { /* * The gForce that is necessary to register as shake. * Must be greater than 1G (one earth gravity unit). * You can install \"G-Force\", by Blake La Pierre * from the Google Play Store and run it to see how * many G's it takes to register a shake */ private static final float SHAKE_THRESHOLD_GRAVITY = 2.7F; private static final int SHAKE_SLOP_TIME_MS = 500; private static final int SHAKE_COUNT_RESET_TIME_MS = 3000; private OnShakeListener mListener; private long mShakeTimestamp; private int mShakeCount; public void setOnShakeListener(OnShakeListener listener) { this.mListener = listener; } public interface OnShakeListener { public void onShake(int count); } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { // ignore } @Override public void onSensorChanged(SensorEvent event) { if (mListener != null) { float x = event.values[0]; float y = event.values[1]; float z = event.values[2]; float gX = x / SensorManager.GRAVITY_EARTH; float gY = y / SensorManager.GRAVITY_EARTH; float gZ = z / SensorManager.GRAVITY_EARTH; // gForce will be close to 1 when there is no movement. Float f = new Float(gX * gX + gY * gY + gZ * gZ); Double d = Math.sqrt(f.doubleValue()); float gForce = d.floatValue(); if (gForce > SHAKE_THRESHOLD_GRAVITY) { final long now = System.currentTimeMillis(); // ignore shake events too close to each other (500ms) if (mShakeTimestamp + SHAKE_SLOP_TIME_MS > now) { return; } // reset the shake count after 3 seconds of no shakes if (mShakeTimestamp + SHAKE_COUNT_RESET_TIME_MS < now) { mShakeCount = 0; } mShakeTimestamp = now; mShakeCount++; mListener.onShake(mShakeCount); } } }}",
"e": 15862,
"s": 13579,
"text": null
},
{
"code": null,
"e": 15902,
"s": 15865,
"text": "Step 3.2: Creating the SensorService"
},
{
"code": null,
"e": 16122,
"s": 15904,
"text": "Creating a sensor service. From the commencement of Android 6, Google has included some extra security checks regarding background services. Now handling of services is completely different as it was done previously. "
},
{
"code": null,
"e": 16277,
"s": 16124,
"text": "Our main focus while building this app should be on how we can keep the service running even when the app is not running (even removed from the recent)."
},
{
"code": null,
"e": 16630,
"s": 16279,
"text": "For service to run while the host application is Dead, is called Service to run in the background. And to make a service run in the background we need some extra permissions. In Android O and above we can’t have background service, instead, we can use the Foreground Services. Foreground services perform operations that are noticeable to the user. "
},
{
"code": null,
"e": 16951,
"s": 16632,
"text": "A status bar warning with a priority of PRIORITY LOW or higher must be shown for each foreground operation. Users would be conscious that the app is running in the foreground and using machine resources in this manner. Unless the service is discontinued or withdrawn from the foreground, the message cannot be ignored."
},
{
"code": null,
"e": 16958,
"s": 16953,
"text": "Java"
},
{
"code": "@RequiresApi(Build.VERSION_CODES.O)private void startMyOwnForeground(){ String NOTIFICATION_CHANNEL_ID = \"example.permanence\"; String channelName = \"Background Service\"; NotificationChannel chan = new NotificationChannel( NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_MIN); NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE); assert manager != null; manager.createNotificationChannel(chan); NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID); Notification notification = notificationBuilder.setOngoing(true) .setContentTitle(\"You are protected.\") .setContentText(\"We are there for you\") // this is important, otherwise the // notification will show the way you want i.e. // it will show some default notification .setSmallIcon(R.drawable.ic_launcher_foreground) .setPriority(NotificationManager.IMPORTANCE_MIN) .setCategory(Notification.CATEGORY_SERVICE) .build(); startForeground(2, notification);}",
"e": 18149,
"s": 16958,
"text": null
},
{
"code": null,
"e": 18453,
"s": 18152,
"text": "If you start a service starts with the START STICKY return type, it will run in the background even if the host activity is not running in the foreground. If Android has to forcibly close a program due to a memory error or other reasons, the service will be restarted without the user’s intervention."
},
{
"code": null,
"e": 18460,
"s": 18455,
"text": "Java"
},
{
"code": "@Overridepublic int onStartCommand(Intent intent, int flags, int startId) { super.onStartCommand(intent, flags, startId); return START_STICKY;}",
"e": 18611,
"s": 18460,
"text": null
},
{
"code": null,
"e": 18817,
"s": 18614,
"text": "In order to make the user aware that the Shake event has been registered or say the messages have been delivered, we create a vibrate() method. This will make the phone vibrate in a defined wave format."
},
{
"code": null,
"e": 18824,
"s": 18819,
"text": "Java"
},
{
"code": "// method to vibrate the phonepublic void vibrate(){ final Vibrator vibrator = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE); VibrationEffect vibEff; // Android Q and above have some predefined vibrating // patterns if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { vibEff = VibrationEffect.createPredefined(VibrationEffect.EFFECT_DOUBLE_CLICK); vibrator.cancel(); vibrator.vibrate(vibEff); } else { vibrator.vibrate(500); }}",
"e": 19316,
"s": 18824,
"text": null
},
{
"code": null,
"e": 19887,
"s": 19319,
"text": "Now, in order to fetch the user location, we will use FusedLocationProviderClient. The FusedLocationProviderClient has a function named getCurremtLocation(). This method provides the current location of the user when asked for. But this method requires the mobile phone’s GPS to be turned ON. Otherwise, it will return a null location. From Android O and above, in order to fetch location or anything which would reveal the user’s location to the app, the location services or the GPS should be turned ON. So, that the user is aware of the location usages by the app."
},
{
"code": null,
"e": 19894,
"s": 19889,
"text": "Java"
},
{
"code": "FusedLocationProviderClient fusedLocationClient = LocationServices.getFusedLocationProviderClient(getApplicationContext()); fusedLocationClient.getCurrentLocation(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY, new CancellationToken() { @Override public boolean isCancellationRequested() { return false; } @NonNull @Override public CancellationToken onCanceledRequested( @NonNull OnTokenCanceledListener onTokenCanceledListener) { return null; } }) .addOnSuccessListener( new OnSuccessListener<Location>() { @Override public void onSuccess(Location location) { // check if location is null // for both the cases we will create // different messages if (location != null) { ... } else { ... } } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { ... } });",
"e": 21126,
"s": 19894,
"text": null
},
{
"code": null,
"e": 21632,
"s": 21129,
"text": "Further, when we retrieve the location successfully, we Create a SMSManager object which will help us to send messages to all the contacts from the database. In case the user’s location services are not ON, we can generate a different message without the coordinates. So that one receiving the emergency message knows that the host device didn’t have location services on at that moment. He can then directly coordinate with the nearby Police department who can then track the person’s device location."
},
{
"code": null,
"e": 21639,
"s": 21634,
"text": "Java"
},
{
"code": "SmsManager smsManager = SmsManager.getDefault();DbHelper db = new DbHelper(SensorService.this);List<ContactModel> list = db.getAllContacts();for (ContactModel c : list) { String message = \"Hey, \" + c.getName() + \"I am in DANGER, i need help. Please urgently reach me out. Here are my coordinates.\\n \" + \"http://maps.google.com/?q=\" + location.getLatitude() + \",\" + location.getLongitude(); smsManager.sendTextMessage(c.getPhoneNo(), null, message, null, null);}",
"e": 22180,
"s": 21639,
"text": null
},
{
"code": null,
"e": 22379,
"s": 22183,
"text": "Till now whatever we have done will work until the activity is in Foreground or Running. But what when the user kills the application? Or locks the phone? For this, we create a BroadcastReceiver."
},
{
"code": null,
"e": 22441,
"s": 22381,
"text": "Below is the complete code for the SensorService.java file."
},
{
"code": null,
"e": 22448,
"s": 22443,
"text": "Java"
},
{
"code": "import android.annotation.SuppressLint;import android.app.Notification;import android.app.NotificationChannel;import android.app.NotificationManager;import android.app.Service;import android.content.Context;import android.content.Intent;import android.hardware.Sensor;import android.hardware.SensorManager;import android.location.Location;import android.os.Build;import android.os.IBinder;import android.os.VibrationEffect;import android.os.Vibrator;import android.telephony.SmsManager;import android.util.Log; import androidx.annotation.NonNull;import androidx.annotation.RequiresApi;import androidx.core.app.NotificationCompat; import com.google.android.gms.location.FusedLocationProviderClient;import com.google.android.gms.location.LocationRequest;import com.google.android.gms.location.LocationServices;import com.google.android.gms.tasks.CancellationToken;import com.google.android.gms.tasks.OnFailureListener;import com.google.android.gms.tasks.OnSuccessListener;import com.google.android.gms.tasks.OnTokenCanceledListener;import com.raghav.sos.Contacts.ContactModel;import com.raghav.sos.Contacts.DbHelper;import com.raghav.sos.R; import java.util.List; public class SensorService extends Service { private SensorManager mSensorManager; private Sensor mAccelerometer; private ShakeDetector mShakeDetector; public SensorService() { } @Override public IBinder onBind(Intent intent) { // TODO: Return the communication channel to the service. throw new UnsupportedOperationException(\"Not yet implemented\"); } @Override public int onStartCommand(Intent intent, int flags, int startId) { super.onStartCommand(intent, flags, startId); return START_STICKY; } @Override public void onCreate() { super.onCreate(); // start the foreground service if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) startMyOwnForeground(); else startForeground(1, new Notification()); // ShakeDetector initialization mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); mShakeDetector = new ShakeDetector(); mShakeDetector.setOnShakeListener(new ShakeDetector.OnShakeListener() { @SuppressLint(\"MissingPermission\") @Override public void onShake(int count) { // check if the user has shacked // the phone for 3 time in a row if (count == 3) { // vibrate the phone vibrate(); // create FusedLocationProviderClient to get the user location FusedLocationProviderClient fusedLocationClient = LocationServices.getFusedLocationProviderClient(getApplicationContext()); // use the PRIORITY_BALANCED_POWER_ACCURACY // so that the service doesn't use unnecessary power via GPS // it will only use GPS at this very moment fusedLocationClient.getCurrentLocation(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY, new CancellationToken() { @Override public boolean isCancellationRequested() { return false; } @NonNull @Override public CancellationToken onCanceledRequested(@NonNull OnTokenCanceledListener onTokenCanceledListener) { return null; } }).addOnSuccessListener(new OnSuccessListener<Location>() { @Override public void onSuccess(Location location) { // check if location is null // for both the cases we will // create different messages if (location != null) { // get the SMSManager SmsManager smsManager = SmsManager.getDefault(); // get the list of all the contacts in Database DbHelper db = new DbHelper(SensorService.this); List<ContactModel> list = db.getAllContacts(); // send SMS to each contact for (ContactModel c : list) { String message = \"Hey, \" + c.getName() + \"I am in DANGER, i need help. Please urgently reach me out. Here are my coordinates.\\n \" + \"http://maps.google.com/?q=\" + location.getLatitude() + \",\" + location.getLongitude(); smsManager.sendTextMessage(c.getPhoneNo(), null, message, null, null); } } else { String message = \"I am in DANGER, i need help. Please urgently reach me out.\\n\" + \"GPS was turned off.Couldn't find location. Call your nearest Police Station.\"; SmsManager smsManager = SmsManager.getDefault(); DbHelper db = new DbHelper(SensorService.this); List<ContactModel> list = db.getAllContacts(); for (ContactModel c : list) { smsManager.sendTextMessage(c.getPhoneNo(), null, message, null, null); } } } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Log.d(\"Check: \", \"OnFailure\"); String message = \"I am in DANGER, i need help. Please urgently reach me out.\\n\" + \"GPS was turned off.Couldn't find location. Call your nearest Police Station.\"; SmsManager smsManager = SmsManager.getDefault(); DbHelper db = new DbHelper(SensorService.this); List<ContactModel> list = db.getAllContacts(); for (ContactModel c : list) { smsManager.sendTextMessage(c.getPhoneNo(), null, message, null, null); } } }); } } }); // register the listener mSensorManager.registerListener(mShakeDetector, mAccelerometer, SensorManager.SENSOR_DELAY_UI); } // method to vibrate the phone public void vibrate() { final Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE); VibrationEffect vibEff; // Android Q and above have some predefined vibrating patterns if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { vibEff = VibrationEffect.createPredefined(VibrationEffect.EFFECT_DOUBLE_CLICK); vibrator.cancel(); vibrator.vibrate(vibEff); } else { vibrator.vibrate(500); } } // For Build versions higher than Android Oreo, we launch // a foreground service in a different way. This is due to the newly // implemented strict notification rules, which require us to identify // our own notification channel in order to view them correctly. @RequiresApi(Build.VERSION_CODES.O) private void startMyOwnForeground() { String NOTIFICATION_CHANNEL_ID = \"example.permanence\"; String channelName = \"Background Service\"; NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_MIN); NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); assert manager != null; manager.createNotificationChannel(chan); NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID); Notification notification = notificationBuilder.setOngoing(true) .setContentTitle(\"You are protected.\") .setContentText(\"We are there for you\") // this is important, otherwise the notification will show the way // you want i.e. it will show some default notification .setSmallIcon(R.drawable.ic_launcher_foreground) .setPriority(NotificationManager.IMPORTANCE_MIN) .setCategory(Notification.CATEGORY_SERVICE) .build(); startForeground(2, notification); } @Override public void onDestroy() { // create an Intent to call the Broadcast receiver Intent broadcastIntent = new Intent(); broadcastIntent.setAction(\"restartservice\"); broadcastIntent.setClass(this, ReactivateService.class); this.sendBroadcast(broadcastIntent); super.onDestroy(); } }",
"e": 31677,
"s": 22448,
"text": null
},
{
"code": null,
"e": 31722,
"s": 31680,
"text": "Step 3.3: Creating the Broadcast Receiver"
},
{
"code": null,
"e": 31889,
"s": 31724,
"text": "Whenever a service is destroyed, the onDestroy method is called, and we will use that method to call a broadcast receiver before the service is actually destroyed. "
},
{
"code": null,
"e": 32046,
"s": 31891,
"text": "The broadcast receiver in return again starts the service. And our problem is resolved!! The service now runs without the host activity in the background."
},
{
"code": null,
"e": 32112,
"s": 32048,
"text": "Below is the complete code for the ReactivateService.java file."
},
{
"code": null,
"e": 32119,
"s": 32114,
"text": "Java"
},
{
"code": "import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.os.Build;import android.util.Log; public class ReactivateService extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Log.d(\"Check: \",\"Receiver Started\"); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { context.startForegroundService(new Intent(context, SensorService.class)); } else { context.startService(new Intent(context, SensorService.class)); } }}",
"e": 32698,
"s": 32119,
"text": null
},
{
"code": null,
"e": 32739,
"s": 32701,
"text": "Step 4: Working with the MainActivity"
},
{
"code": null,
"e": 32931,
"s": 32741,
"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": 32938,
"s": 32933,
"text": "Java"
},
{
"code": "import android.Manifest;import android.annotation.SuppressLint;import android.app.Activity;import android.app.ActivityManager;import android.content.Context;import android.content.Intent;import android.content.pm.PackageManager;import android.database.Cursor;import android.net.Uri;import android.os.Build;import android.os.Bundle;import android.os.PowerManager;import android.provider.ContactsContract;import android.provider.Settings;import android.util.Log;import android.view.View;import android.widget.Button;import android.widget.ListView;import android.widget.Toast; import androidx.annotation.NonNull;import androidx.annotation.Nullable;import androidx.appcompat.app.AppCompatActivity;import androidx.core.app.ActivityCompat; import com.raghav.sos.Contacts.ContactModel;import com.raghav.sos.Contacts.CustomAdapter;import com.raghav.sos.Contacts.DbHelper;import com.raghav.sos.ShakeServices.ReactivateService;import com.raghav.sos.ShakeServices.SensorService; import java.util.List; public class MainActivity extends AppCompatActivity { private static final int IGNORE_BATTERY_OPTIMIZATION_REQUEST = 1002; private static final int PICK_CONTACT = 1; // create instances of various classes to be used Button button1; ListView listView; DbHelper db; List<ContactModel> list; CustomAdapter customAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // check for runtime permissions if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_DENIED) { requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.SEND_SMS, Manifest.permission.READ_CONTACTS}, 100); } } // this is a special permission required only by devices using // Android Q and above. The Access Background Permission is responsible // for populating the dialog with \"ALLOW ALL THE TIME\" option if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { requestPermissions(new String[]{Manifest.permission.ACCESS_BACKGROUND_LOCATION}, 100); } // check for BatteryOptimization, PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (pm != null && !pm.isIgnoringBatteryOptimizations(getPackageName())) { askIgnoreOptimization(); } } // start the service SensorService sensorService = new SensorService(); Intent intent = new Intent(this, sensorService.getClass()); if (!isMyServiceRunning(sensorService.getClass())) { startService(intent); } button1 = findViewById(R.id.Button1); listView = (ListView) findViewById(R.id.ListView); db = new DbHelper(this); list = db.getAllContacts(); customAdapter = new CustomAdapter(this, list); listView.setAdapter(customAdapter); button1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // calling of getContacts() if (db.count() != 5) { Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI); startActivityForResult(intent, PICK_CONTACT); } else { Toast.makeText(MainActivity.this, \"Can't Add more than 5 Contacts\", Toast.LENGTH_SHORT).show(); } } }); } // method to check if the service is running private boolean isMyServiceRunning(Class<?> serviceClass) { ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE); for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) { if (serviceClass.getName().equals(service.service.getClassName())) { Log.i(\"Service status\", \"Running\"); return true; } } Log.i(\"Service status\", \"Not running\"); return false; } @Override protected void onDestroy() { Intent broadcastIntent = new Intent(); broadcastIntent.setAction(\"restartservice\"); broadcastIntent.setClass(this, ReactivateService.class); this.sendBroadcast(broadcastIntent); super.onDestroy(); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == 100) { if (grantResults[0] == PackageManager.PERMISSION_DENIED) { Toast.makeText(this, \"Permissions Denied!\\n Can't use the App!\", Toast.LENGTH_SHORT).show(); } } } @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); // get the contact from the PhoneBook of device switch (requestCode) { case (PICK_CONTACT): if (resultCode == Activity.RESULT_OK) { Uri contactData = data.getData(); Cursor c = managedQuery(contactData, null, null, null, null); if (c.moveToFirst()) { String id = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts._ID)); String hasPhone = c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)); String phone = null; try { if (hasPhone.equalsIgnoreCase(\"1\")) { Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + \" = \" + id, null, null); phones.moveToFirst(); phone = phones.getString(phones.getColumnIndex(\"data1\")); } String name = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)); db.addcontact(new ContactModel(0, name, phone)); list = db.getAllContacts(); customAdapter.refresh(list); } catch (Exception ex) { } } } break; } } // this method prompts the user to remove any // battery optimisation constraints from the App private void askIgnoreOptimization() { if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) { @SuppressLint(\"BatteryLife\") Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS); intent.setData(Uri.parse(\"package:\" + getPackageName())); startActivityForResult(intent, IGNORE_BATTERY_OPTIMIZATION_REQUEST); } } }",
"e": 40187,
"s": 32938,
"text": null
},
{
"code": null,
"e": 40333,
"s": 40190,
"text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. "
},
{
"code": null,
"e": 40339,
"s": 40335,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\" tools:context=\".MainActivity\"> <Button android:id=\"@+id/Button1\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"12dp\" android:background=\"#0F9D58\" android:text=\"Add Emergency Contact \" android:textColor=\"#FFFFFF\" /> <ListView android:id=\"@+id/ListView\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" /> </LinearLayout>",
"e": 41091,
"s": 40339,
"text": null
},
{
"code": null,
"e": 41135,
"s": 41094,
"text": "Step 5: Working with AndroidManifest.xml"
},
{
"code": null,
"e": 41141,
"s": 41137,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" package=\"com.raghav.sos\"> <uses-permission android:name=\"android.permission.READ_CONTACTS\"/> <uses-permission android:name=\"android.permission.VIBRATE\"/> <uses-permission android:name=\"android.permission.SEND_SMS\"/> <uses-permission android:name=\"android.permission.ACCESS_FINE_LOCATION\"/> <uses-permission android:name=\"android.permission.ACCESS_COARSE_LOCATION\" /> <uses-permission android:name=\"android.permission.FOREGROUND_SERVICE\"/> <!--This permission is necessary for devices with Android O and above, so that we can use the location ALL THE TIME--> <uses-permission android:name=\"android.permission.ACCESS_BACKGROUND_LOCATION\"/> <!-- We also ask user to remove any battery optimization constraints during runtime --> <uses-permission android:name=\"android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS\"/> <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/Theme.SOS\"> <!-- register the receiver --> <receiver android:name=\".ShakeServices.ReactivateService\" android:enabled=\"true\" android:exported=\"true\"/> <!-- register the service --> <service android:name=\".ShakeServices.SensorService\" android:enabled=\"true\" android:exported=\"true\" /> <activity android:name=\".MainActivity\"> <intent-filter> <action android:name=\"android.intent.action.MAIN\" /> <category android:name=\"android.intent.category.LAUNCHER\" /> </intent-filter> </activity> </application> </manifest>",
"e": 43100,
"s": 41141,
"text": null
},
{
"code": null,
"e": 43111,
"s": 43103,
"text": "Output:"
},
{
"code": null,
"e": 43173,
"s": 43113,
"text": "Media error: Format(s) not supported or source(s) not found"
},
{
"code": null,
"e": 43867,
"s": 43173,
"text": "You can add options for personal assistance emergencies like a map that indicates nearby police stations, hospitals, cabs, etc.You create a logic that sends the user location every 1 or 2 minutes without the user shaking the device again.You can add voice or/and video recording functionality.Also, you can add a call to multiple or a single person at the time of shake.You can try to add OpenCellId, this will allow you to fetch the location of the nearest mobile tower. But again remember that in order to calculate the location you would require some device information(no GPS) and that would require your GPS or location services to be turned ON.Doors to changes in the UI are always open."
},
{
"code": null,
"e": 43995,
"s": 43867,
"text": "You can add options for personal assistance emergencies like a map that indicates nearby police stations, hospitals, cabs, etc."
},
{
"code": null,
"e": 44107,
"s": 43995,
"text": "You create a logic that sends the user location every 1 or 2 minutes without the user shaking the device again."
},
{
"code": null,
"e": 44163,
"s": 44107,
"text": "You can add voice or/and video recording functionality."
},
{
"code": null,
"e": 44241,
"s": 44163,
"text": "Also, you can add a call to multiple or a single person at the time of shake."
},
{
"code": null,
"e": 44522,
"s": 44241,
"text": "You can try to add OpenCellId, this will allow you to fetch the location of the nearest mobile tower. But again remember that in order to calculate the location you would require some device information(no GPS) and that would require your GPS or location services to be turned ON."
},
{
"code": null,
"e": 44566,
"s": 44522,
"text": "Doors to changes in the UI are always open."
},
{
"code": null,
"e": 44573,
"s": 44566,
"text": "Notes:"
},
{
"code": null,
"e": 44653,
"s": 44573,
"text": "1. Allow the app to autostart, in order to use the app while the screen is off."
},
{
"code": null,
"e": 44754,
"s": 44653,
"text": "2. Remove any battery optimization constraints on the app. This might make Android kill the service."
},
{
"code": null,
"e": 44975,
"s": 44754,
"text": "3. Allow all the permissions, especially allow location permissions by Allowing the app to use the device location all the time. This would allow the service to use the device location when the shake event is registered."
},
{
"code": null,
"e": 45025,
"s": 44977,
"text": "GitHub Link: https://github.com/raghavtilak/SOS"
},
{
"code": null,
"e": 45042,
"s": 45027,
"text": "varshagumber28"
},
{
"code": null,
"e": 45057,
"s": 45042,
"text": "Android-Studio"
},
{
"code": null,
"e": 45064,
"s": 45057,
"text": "Picked"
},
{
"code": null,
"e": 45072,
"s": 45064,
"text": "Android"
},
{
"code": null,
"e": 45077,
"s": 45072,
"text": "Java"
},
{
"code": null,
"e": 45082,
"s": 45077,
"text": "Java"
},
{
"code": null,
"e": 45090,
"s": 45082,
"text": "Android"
}
] |
How to remove timezone from a Timestamp column in a Pandas Dataframe
|
10 Sep, 2021
The world is divided into 24 timezones. We all know that different timezones are required as the entire globe is not lit at the same time. While for many instances we might not require timezones especially in cases where the data resides on a common server present at some location or even our local systems. In this article, we are going to see how to remove timezone from a Timestamp column in a pandas dataframe.
Creating dataframe for demonstration:
Python
import pandas as pdfrom datetime import datetime, timezone # CREATE THE PANDAS DATAFRAME# WITH TIMESTAMP COLUMNdf = pd.DataFrame({ "orderNo": [ "4278954", "3473895", "8763762", "4738289", "1294394" ], "timestamp": [ datetime.strptime("2021-06-01", "%Y-%m-%d").replace(tzinfo=timezone.utc), datetime.strptime("2021-06-02", "%Y-%m-%d").replace(tzinfo=timezone.utc), datetime.strptime("2021-06-03", "%Y-%m-%d").replace(tzinfo=timezone.utc), datetime.strptime("2021-06-04", "%Y-%m-%d").replace(tzinfo=timezone.utc), datetime.strptime("2021-06-05", "%Y-%m-%d").replace(tzinfo=timezone.utc) ]}) # PRINT THE DATATYPES OF# EACH COLUMN OF DATAFRAMEprint(df.dtypes) # VIEW THE DATAFRAMEprint(df)
Output:
Output for Code Block 1
The first part of the output tells us a timestamp column is a DateTime object. The UTC in squared brackets denotes that the timezone information is included which is actually UTC timestamp. It is because we have provided timezone as UTC.
Datetime.replace() function is used to replace the contents of the DateTime object with the given parameters.
Syntax: Datetime_object.replace(tzinfo)
Parameters:
tzinfo: New time zone info.
Returns: It returns the modified datetime object
Now, we will create a function to remove the timezone using the datetime module. The function will be applied to each record in the timestamp column.
Python
import pandas as pdfrom datetime import datetime, timezone # CREATE THE DATAFRAMEdf = pd.DataFrame({ "orderNo": [ "4278954", "3473895", "8763762", "4738289", "1294394" ], "timestamp": [ datetime.strptime("2021-06-01", "%Y-%m-%d").replace(tzinfo=timezone.utc), datetime.strptime("2021-06-02", "%Y-%m-%d").replace(tzinfo=timezone.utc), datetime.strptime("2021-06-03", "%Y-%m-%d").replace(tzinfo=timezone.utc), datetime.strptime("2021-06-04", "%Y-%m-%d").replace(tzinfo=timezone.utc), datetime.strptime("2021-06-05", "%Y-%m-%d").replace(tzinfo=timezone.utc) ]}) # PRINT THE DATATYPE OF# EACH COLUMN BEFORE MANIPULATIONprint(df.dtypes) # FUNCTION TO REMOVE TIMEZONEdef remove_timezone(dt): # HERE `dt` is a python datetime # object that used .replace() method return dt.replace(tzinfo=None) # APPLY THE ABOVE FUNCTION TO# REMOVE THE TIMEZONE INFORMATION# FROM EACH RECORD OF TIMESTAMP COLUMN IN DATAFRAMEdf['timestamp'] = df['timestamp'].apply(remove_timezone) # PRINT THE DATATYPE OF# EACH COLUMN AFTER MANIPULATIONprint(df.dtypes)
Output:
Output for Code Block 2
In the output, we can see that before the manipulation of the timezone, the DateTime column i.e. the “timestamp” column had the UTC timezone information. After applying the remove_timezone function on each record of the dataframe’s timestamp column, we do not see any UTC information present in the dataframe. The “timestamp“ column in the dataframe has python datetime objects as its values. So when each of these values passes through the in remove_timezone() function it makes use of the replace() method of the Python datetime module.
We can achieve the same without making use of the DateTime module. Let us see how –
Python
import pandas as pdfrom datetime import datetime, timezone # CREATE THE DATAFRAMEdf = pd.DataFrame({ "orderNo": [ "4278954", "3473895", "8763762", "4738289", "1294394" ], "timestamp": [ datetime.strptime( "2021-06-01", "%Y-%m-%d").replace(tzinfo=timezone.utc), datetime.strptime( "2021-06-02", "%Y-%m-%d").replace(tzinfo=timezone.utc), datetime.strptime( "2021-06-03", "%Y-%m-%d").replace(tzinfo=timezone.utc), datetime.strptime( "2021-06-04", "%Y-%m-%d").replace(tzinfo=timezone.utc), datetime.strptime( "2021-06-05", "%Y-%m-%d").replace(tzinfo=timezone.utc) ]}) # PRINT THE DATATYPE OF EACH COLUMN BEFORE# MANIPULATIONprint(df.dtypes) # REMOVING THE TIMEZONE INFORMATIONdf['timestamp'] = df['timestamp'].dt.tz_localize(None) # PRINT THE DATATYPE OF EACH COLUMN AFTER# MANIPULATIONprint(df.dtypes)
Output:
Output for Code Block 3
In the above example, we can see that the dt.tz_localize(None) method can be applied to the dataframe column to remove the timezone information. The output similar to the above example reflects that after manipulation, the UTC timezone information is no longer present in the timestamp column.
simranarora5sos
pandas-dataframe-program
Picked
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to iterate through Excel rows in Python?
Rotate axis tick labels in Seaborn and Matplotlib
Deque in Python
Queue in Python
Defaultdict in Python
Check if element exists in list in Python
Python Classes and Objects
Bar Plot in Matplotlib
reduce() in Python
Python | Get unique values from a list
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n10 Sep, 2021"
},
{
"code": null,
"e": 444,
"s": 28,
"text": "The world is divided into 24 timezones. We all know that different timezones are required as the entire globe is not lit at the same time. While for many instances we might not require timezones especially in cases where the data resides on a common server present at some location or even our local systems. In this article, we are going to see how to remove timezone from a Timestamp column in a pandas dataframe."
},
{
"code": null,
"e": 482,
"s": 444,
"text": "Creating dataframe for demonstration:"
},
{
"code": null,
"e": 489,
"s": 482,
"text": "Python"
},
{
"code": "import pandas as pdfrom datetime import datetime, timezone # CREATE THE PANDAS DATAFRAME# WITH TIMESTAMP COLUMNdf = pd.DataFrame({ \"orderNo\": [ \"4278954\", \"3473895\", \"8763762\", \"4738289\", \"1294394\" ], \"timestamp\": [ datetime.strptime(\"2021-06-01\", \"%Y-%m-%d\").replace(tzinfo=timezone.utc), datetime.strptime(\"2021-06-02\", \"%Y-%m-%d\").replace(tzinfo=timezone.utc), datetime.strptime(\"2021-06-03\", \"%Y-%m-%d\").replace(tzinfo=timezone.utc), datetime.strptime(\"2021-06-04\", \"%Y-%m-%d\").replace(tzinfo=timezone.utc), datetime.strptime(\"2021-06-05\", \"%Y-%m-%d\").replace(tzinfo=timezone.utc) ]}) # PRINT THE DATATYPES OF# EACH COLUMN OF DATAFRAMEprint(df.dtypes) # VIEW THE DATAFRAMEprint(df)",
"e": 1382,
"s": 489,
"text": null
},
{
"code": null,
"e": 1391,
"s": 1382,
"text": "Output: "
},
{
"code": null,
"e": 1415,
"s": 1391,
"text": "Output for Code Block 1"
},
{
"code": null,
"e": 1654,
"s": 1415,
"text": "The first part of the output tells us a timestamp column is a DateTime object. The UTC in squared brackets denotes that the timezone information is included which is actually UTC timestamp. It is because we have provided timezone as UTC. "
},
{
"code": null,
"e": 1765,
"s": 1654,
"text": "Datetime.replace() function is used to replace the contents of the DateTime object with the given parameters. "
},
{
"code": null,
"e": 1805,
"s": 1765,
"text": "Syntax: Datetime_object.replace(tzinfo)"
},
{
"code": null,
"e": 1817,
"s": 1805,
"text": "Parameters:"
},
{
"code": null,
"e": 1845,
"s": 1817,
"text": "tzinfo: New time zone info."
},
{
"code": null,
"e": 1894,
"s": 1845,
"text": "Returns: It returns the modified datetime object"
},
{
"code": null,
"e": 2044,
"s": 1894,
"text": "Now, we will create a function to remove the timezone using the datetime module. The function will be applied to each record in the timestamp column."
},
{
"code": null,
"e": 2051,
"s": 2044,
"text": "Python"
},
{
"code": "import pandas as pdfrom datetime import datetime, timezone # CREATE THE DATAFRAMEdf = pd.DataFrame({ \"orderNo\": [ \"4278954\", \"3473895\", \"8763762\", \"4738289\", \"1294394\" ], \"timestamp\": [ datetime.strptime(\"2021-06-01\", \"%Y-%m-%d\").replace(tzinfo=timezone.utc), datetime.strptime(\"2021-06-02\", \"%Y-%m-%d\").replace(tzinfo=timezone.utc), datetime.strptime(\"2021-06-03\", \"%Y-%m-%d\").replace(tzinfo=timezone.utc), datetime.strptime(\"2021-06-04\", \"%Y-%m-%d\").replace(tzinfo=timezone.utc), datetime.strptime(\"2021-06-05\", \"%Y-%m-%d\").replace(tzinfo=timezone.utc) ]}) # PRINT THE DATATYPE OF# EACH COLUMN BEFORE MANIPULATIONprint(df.dtypes) # FUNCTION TO REMOVE TIMEZONEdef remove_timezone(dt): # HERE `dt` is a python datetime # object that used .replace() method return dt.replace(tzinfo=None) # APPLY THE ABOVE FUNCTION TO# REMOVE THE TIMEZONE INFORMATION# FROM EACH RECORD OF TIMESTAMP COLUMN IN DATAFRAMEdf['timestamp'] = df['timestamp'].apply(remove_timezone) # PRINT THE DATATYPE OF# EACH COLUMN AFTER MANIPULATIONprint(df.dtypes)",
"e": 3299,
"s": 2051,
"text": null
},
{
"code": null,
"e": 3308,
"s": 3299,
"text": "Output: "
},
{
"code": null,
"e": 3332,
"s": 3308,
"text": "Output for Code Block 2"
},
{
"code": null,
"e": 3871,
"s": 3332,
"text": "In the output, we can see that before the manipulation of the timezone, the DateTime column i.e. the “timestamp” column had the UTC timezone information. After applying the remove_timezone function on each record of the dataframe’s timestamp column, we do not see any UTC information present in the dataframe. The “timestamp“ column in the dataframe has python datetime objects as its values. So when each of these values passes through the in remove_timezone() function it makes use of the replace() method of the Python datetime module."
},
{
"code": null,
"e": 3955,
"s": 3871,
"text": "We can achieve the same without making use of the DateTime module. Let us see how –"
},
{
"code": null,
"e": 3962,
"s": 3955,
"text": "Python"
},
{
"code": "import pandas as pdfrom datetime import datetime, timezone # CREATE THE DATAFRAMEdf = pd.DataFrame({ \"orderNo\": [ \"4278954\", \"3473895\", \"8763762\", \"4738289\", \"1294394\" ], \"timestamp\": [ datetime.strptime( \"2021-06-01\", \"%Y-%m-%d\").replace(tzinfo=timezone.utc), datetime.strptime( \"2021-06-02\", \"%Y-%m-%d\").replace(tzinfo=timezone.utc), datetime.strptime( \"2021-06-03\", \"%Y-%m-%d\").replace(tzinfo=timezone.utc), datetime.strptime( \"2021-06-04\", \"%Y-%m-%d\").replace(tzinfo=timezone.utc), datetime.strptime( \"2021-06-05\", \"%Y-%m-%d\").replace(tzinfo=timezone.utc) ]}) # PRINT THE DATATYPE OF EACH COLUMN BEFORE# MANIPULATIONprint(df.dtypes) # REMOVING THE TIMEZONE INFORMATIONdf['timestamp'] = df['timestamp'].dt.tz_localize(None) # PRINT THE DATATYPE OF EACH COLUMN AFTER# MANIPULATIONprint(df.dtypes)",
"e": 4898,
"s": 3962,
"text": null
},
{
"code": null,
"e": 4906,
"s": 4898,
"text": "Output:"
},
{
"code": null,
"e": 4930,
"s": 4906,
"text": "Output for Code Block 3"
},
{
"code": null,
"e": 5224,
"s": 4930,
"text": "In the above example, we can see that the dt.tz_localize(None) method can be applied to the dataframe column to remove the timezone information. The output similar to the above example reflects that after manipulation, the UTC timezone information is no longer present in the timestamp column."
},
{
"code": null,
"e": 5240,
"s": 5224,
"text": "simranarora5sos"
},
{
"code": null,
"e": 5265,
"s": 5240,
"text": "pandas-dataframe-program"
},
{
"code": null,
"e": 5272,
"s": 5265,
"text": "Picked"
},
{
"code": null,
"e": 5296,
"s": 5272,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 5310,
"s": 5296,
"text": "Python-pandas"
},
{
"code": null,
"e": 5317,
"s": 5310,
"text": "Python"
},
{
"code": null,
"e": 5415,
"s": 5317,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5460,
"s": 5415,
"text": "How to iterate through Excel rows in Python?"
},
{
"code": null,
"e": 5510,
"s": 5460,
"text": "Rotate axis tick labels in Seaborn and Matplotlib"
},
{
"code": null,
"e": 5526,
"s": 5510,
"text": "Deque in Python"
},
{
"code": null,
"e": 5542,
"s": 5526,
"text": "Queue in Python"
},
{
"code": null,
"e": 5564,
"s": 5542,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 5606,
"s": 5564,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 5633,
"s": 5606,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 5656,
"s": 5633,
"text": "Bar Plot in Matplotlib"
},
{
"code": null,
"e": 5675,
"s": 5656,
"text": "reduce() in Python"
}
] |
What is AbstractList Class in Java?
|
The AbstractList class provides an implementation of the List interface.
Programmer needs to extend this class and provide implementations for the get(int) and size() methods.
Programmer must override the set(int, E) method. If the list is variable-size the programmer must override the add(int, E) and remove(int) methods.
The following is the syntax:
public abstract class AbstractList<E>
extends AbstractCollection<E>
implements List<E>
To work with the AbstractList class, import the following package:
import java.util.AbstractList;
The following is an example to implement AbstractList class:
Live Demo
import java.util.LinkedList;
import java.util.AbstractList;
public class Demo {
public static void main(String[] args) {
AbstractList<Integer> myList = new LinkedList<Integer>();
myList.add(50);
myList.add(100);
myList.add(150);
myList.add(200);
myList.add(250);
myList.add(300);
myList.add(350);
myList.add(400);
System.out.println("Elements in the AbstractList class = " + myList);
}
}
Elements in the AbstractList class = [50, 100, 150, 200, 250, 300, 350, 400]
|
[
{
"code": null,
"e": 1260,
"s": 1187,
"text": "The AbstractList class provides an implementation of the List interface."
},
{
"code": null,
"e": 1363,
"s": 1260,
"text": "Programmer needs to extend this class and provide implementations for the get(int) and size() methods."
},
{
"code": null,
"e": 1511,
"s": 1363,
"text": "Programmer must override the set(int, E) method. If the list is variable-size the programmer must override the add(int, E) and remove(int) methods."
},
{
"code": null,
"e": 1540,
"s": 1511,
"text": "The following is the syntax:"
},
{
"code": null,
"e": 1627,
"s": 1540,
"text": "public abstract class AbstractList<E>\nextends AbstractCollection<E>\nimplements List<E>"
},
{
"code": null,
"e": 1694,
"s": 1627,
"text": "To work with the AbstractList class, import the following package:"
},
{
"code": null,
"e": 1725,
"s": 1694,
"text": "import java.util.AbstractList;"
},
{
"code": null,
"e": 1786,
"s": 1725,
"text": "The following is an example to implement AbstractList class:"
},
{
"code": null,
"e": 1797,
"s": 1786,
"text": " Live Demo"
},
{
"code": null,
"e": 2251,
"s": 1797,
"text": "import java.util.LinkedList;\nimport java.util.AbstractList;\npublic class Demo {\n public static void main(String[] args) {\n AbstractList<Integer> myList = new LinkedList<Integer>();\n myList.add(50);\n myList.add(100);\n myList.add(150);\n myList.add(200);\n myList.add(250);\n myList.add(300);\n myList.add(350);\n myList.add(400);\n System.out.println(\"Elements in the AbstractList class = \" + myList);\n }\n}"
},
{
"code": null,
"e": 2328,
"s": 2251,
"text": "Elements in the AbstractList class = [50, 100, 150, 200, 250, 300, 350, 400]"
}
] |
Python | Program to convert String to a List
|
07 Jul, 2022
In this program, we will try to convert a given string to a list, where spaces or any other special characters, according to the users choice, are encountered. To do this we use the split() method in string.
string.split("delimiter")
Examples:
Input : "Geeks for Geeks"
Output : ['Geeks', 'for', 'Geeks']
Input : "Geeks-for-Geeks"
Output : ['Geeks', 'for', 'Geeks']
Method#1: Using split() method
The split method is used to split the strings and store them in the list. The built-in method returns a list of the words in the string, using the “delimiter” as the delimiter string. If a delimiter is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace.
Python3
# Python code to convert string to list def Convert(string): li = list(string.split(" ")) return li # Driver code str1 = "Geeks for Geeks"print(Convert(str1))
Output:
['Geeks', 'for', 'Geeks']
Example 2:
Python3
# Python code to convert string to listdef Convert(string): li = list(string.split("-")) return li # Driver code str1 = "Geeks-for-Geeks"print(Convert(str1))
Output:
['Geeks', 'for', 'Geeks']
Method#2 : Using string slicing:
Python3
# Python code to convert string to list character-wisedef Convert(string): list1=[] list1[:0]=string return list1# Driver codestr1="ABCD"print(Convert(str1))
Output:
['A','B','C','D']
Method#3 : Using re.findall() method This task can be performed using regular expression. We can used the pattern to matched all the alphabet and make list with all the matched elements.
Python3
# Python code to convert string to list character-wise# Using re.findall methodimport re # Function which uses re.findall method to convert string to list character wise def Convert(string): return re.findall('[a-zA-Z]', string) # Driver codestr1="ABCD"print("List of character is : ",Convert(str1))
Output:
List of character is : ['A', 'B', 'C', 'D']
sagarbaisoya1
satyam00so
sagartomar9927
Python list-programs
Python string-programs
python-list
python-string
Python
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Convert integer to string in Python
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n07 Jul, 2022"
},
{
"code": null,
"e": 260,
"s": 52,
"text": "In this program, we will try to convert a given string to a list, where spaces or any other special characters, according to the users choice, are encountered. To do this we use the split() method in string."
},
{
"code": null,
"e": 286,
"s": 260,
"text": "string.split(\"delimiter\")"
},
{
"code": null,
"e": 296,
"s": 286,
"text": "Examples:"
},
{
"code": null,
"e": 419,
"s": 296,
"text": "Input : \"Geeks for Geeks\"\nOutput : ['Geeks', 'for', 'Geeks']\n\nInput : \"Geeks-for-Geeks\"\nOutput : ['Geeks', 'for', 'Geeks']"
},
{
"code": null,
"e": 450,
"s": 419,
"text": "Method#1: Using split() method"
},
{
"code": null,
"e": 904,
"s": 450,
"text": "The split method is used to split the strings and store them in the list. The built-in method returns a list of the words in the string, using the “delimiter” as the delimiter string. If a delimiter is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace."
},
{
"code": null,
"e": 912,
"s": 904,
"text": "Python3"
},
{
"code": "# Python code to convert string to list def Convert(string): li = list(string.split(\" \")) return li # Driver code str1 = \"Geeks for Geeks\"print(Convert(str1))",
"e": 1082,
"s": 912,
"text": null
},
{
"code": null,
"e": 1090,
"s": 1082,
"text": "Output:"
},
{
"code": null,
"e": 1116,
"s": 1090,
"text": "['Geeks', 'for', 'Geeks']"
},
{
"code": null,
"e": 1128,
"s": 1116,
"text": "Example 2: "
},
{
"code": null,
"e": 1136,
"s": 1128,
"text": "Python3"
},
{
"code": "# Python code to convert string to listdef Convert(string): li = list(string.split(\"-\")) return li # Driver code str1 = \"Geeks-for-Geeks\"print(Convert(str1))",
"e": 1304,
"s": 1136,
"text": null
},
{
"code": null,
"e": 1312,
"s": 1304,
"text": "Output:"
},
{
"code": null,
"e": 1338,
"s": 1312,
"text": "['Geeks', 'for', 'Geeks']"
},
{
"code": null,
"e": 1371,
"s": 1338,
"text": "Method#2 : Using string slicing:"
},
{
"code": null,
"e": 1379,
"s": 1371,
"text": "Python3"
},
{
"code": "# Python code to convert string to list character-wisedef Convert(string): list1=[] list1[:0]=string return list1# Driver codestr1=\"ABCD\"print(Convert(str1))",
"e": 1546,
"s": 1379,
"text": null
},
{
"code": null,
"e": 1554,
"s": 1546,
"text": "Output:"
},
{
"code": null,
"e": 1572,
"s": 1554,
"text": "['A','B','C','D']"
},
{
"code": null,
"e": 1760,
"s": 1572,
"text": "Method#3 : Using re.findall() method This task can be performed using regular expression. We can used the pattern to matched all the alphabet and make list with all the matched elements. "
},
{
"code": null,
"e": 1768,
"s": 1760,
"text": "Python3"
},
{
"code": "# Python code to convert string to list character-wise# Using re.findall methodimport re # Function which uses re.findall method to convert string to list character wise def Convert(string): return re.findall('[a-zA-Z]', string) # Driver codestr1=\"ABCD\"print(\"List of character is : \",Convert(str1))",
"e": 2077,
"s": 1768,
"text": null
},
{
"code": null,
"e": 2085,
"s": 2077,
"text": "Output:"
},
{
"code": null,
"e": 2130,
"s": 2085,
"text": "List of character is : ['A', 'B', 'C', 'D']"
},
{
"code": null,
"e": 2144,
"s": 2130,
"text": "sagarbaisoya1"
},
{
"code": null,
"e": 2155,
"s": 2144,
"text": "satyam00so"
},
{
"code": null,
"e": 2170,
"s": 2155,
"text": "sagartomar9927"
},
{
"code": null,
"e": 2191,
"s": 2170,
"text": "Python list-programs"
},
{
"code": null,
"e": 2214,
"s": 2191,
"text": "Python string-programs"
},
{
"code": null,
"e": 2226,
"s": 2214,
"text": "python-list"
},
{
"code": null,
"e": 2240,
"s": 2226,
"text": "python-string"
},
{
"code": null,
"e": 2247,
"s": 2240,
"text": "Python"
},
{
"code": null,
"e": 2259,
"s": 2247,
"text": "python-list"
},
{
"code": null,
"e": 2357,
"s": 2259,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2399,
"s": 2357,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2421,
"s": 2399,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2447,
"s": 2421,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2479,
"s": 2447,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2508,
"s": 2479,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2535,
"s": 2508,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2556,
"s": 2535,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2592,
"s": 2556,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 2615,
"s": 2592,
"text": "Introduction To PYTHON"
}
] |
Difference between char and nchar : MS SQL Server Datatypes
|
14 Sep, 2020
A database has a vast collection of data stored in an organized format. A database might contain a variety of data values stored in it. To avoid confusions, the data values are assigned a name based on its type. These are called datatypes. Datatypes help the users distinguish between different categories of data. MS SQL Server supports a wide range of datatypes for the users to be able to easily identify various categories of data and to use it accordingly.
1. Char :A character is a string of words dentod by single quotation marks. Character is shortened to char in MS SQL Server. It is a datatype that stores only non-unicode data. Non-unicode data is a format that doesn’t support the unicode standards. It takes 1 byte of data and the maximum storage capacity is of 8000 bytes.
Syntax –
column_name char(number _of_bytes);
2. n-char :A n-char is also a string of words that can store unicode data. nchar stands for national character. It takes up two bytes to store the data and can store upto 4000 chars. Unicode data refers to a universal coding standard for letters and other data. Each one is uniquely identified by designating a numeric value.
Syntax –
column_name nchar(number_of_bytes);
Difference between char and nchar : MS SQL Server Datatypes :
Syntax :
col_name char(n);
*n is the number of bytes.
Syntax :
col_name nchar(n);
*n is the number of bytes.
SQL-Server
Difference Between
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n14 Sep, 2020"
},
{
"code": null,
"e": 490,
"s": 28,
"text": "A database has a vast collection of data stored in an organized format. A database might contain a variety of data values stored in it. To avoid confusions, the data values are assigned a name based on its type. These are called datatypes. Datatypes help the users distinguish between different categories of data. MS SQL Server supports a wide range of datatypes for the users to be able to easily identify various categories of data and to use it accordingly."
},
{
"code": null,
"e": 815,
"s": 490,
"text": "1. Char :A character is a string of words dentod by single quotation marks. Character is shortened to char in MS SQL Server. It is a datatype that stores only non-unicode data. Non-unicode data is a format that doesn’t support the unicode standards. It takes 1 byte of data and the maximum storage capacity is of 8000 bytes."
},
{
"code": null,
"e": 824,
"s": 815,
"text": "Syntax –"
},
{
"code": null,
"e": 861,
"s": 824,
"text": "column_name char(number _of_bytes);\n"
},
{
"code": null,
"e": 1187,
"s": 861,
"text": "2. n-char :A n-char is also a string of words that can store unicode data. nchar stands for national character. It takes up two bytes to store the data and can store upto 4000 chars. Unicode data refers to a universal coding standard for letters and other data. Each one is uniquely identified by designating a numeric value."
},
{
"code": null,
"e": 1196,
"s": 1187,
"text": "Syntax –"
},
{
"code": null,
"e": 1233,
"s": 1196,
"text": "column_name nchar(number_of_bytes);\n"
},
{
"code": null,
"e": 1295,
"s": 1233,
"text": "Difference between char and nchar : MS SQL Server Datatypes :"
},
{
"code": null,
"e": 1304,
"s": 1295,
"text": "Syntax :"
},
{
"code": null,
"e": 1323,
"s": 1304,
"text": "col_name char(n); "
},
{
"code": null,
"e": 1350,
"s": 1323,
"text": "*n is the number of bytes."
},
{
"code": null,
"e": 1359,
"s": 1350,
"text": "Syntax :"
},
{
"code": null,
"e": 1379,
"s": 1359,
"text": "col_name nchar(n); "
},
{
"code": null,
"e": 1406,
"s": 1379,
"text": "*n is the number of bytes."
},
{
"code": null,
"e": 1417,
"s": 1406,
"text": "SQL-Server"
},
{
"code": null,
"e": 1436,
"s": 1417,
"text": "Difference Between"
},
{
"code": null,
"e": 1440,
"s": 1436,
"text": "SQL"
},
{
"code": null,
"e": 1444,
"s": 1440,
"text": "SQL"
}
] |
Java Program to Check If a Number is Spy number or not
|
04 Jan, 2021
A number is said to be a Spy number if the sum of all the digits is equal to the product of all digits. For performing the task we need to reverse through the number which will take log(N) time.
Example:
Input : 22
Output: Given number is a SPY number.
Explanation: Sum of the number is 4 (2 + 2)
Product of the number is as 4 (2 * 2)
Input : 1241
Output: Given number is not a SPY number.
Approach:
Calculate the sum of digits of the input Number.Calculate the product of digits of the input Number.If the sum of digits equals the product of digits then the number is Spy number otherwise not.
Calculate the sum of digits of the input Number.
Calculate the product of digits of the input Number.
If the sum of digits equals the product of digits then the number is Spy number otherwise not.
Below is the implementation of the above approach:
Java
// Java Program to Check If a Number is Spy number or notimport java.io.*; class GFG { public static void main(String[] args) { int product = 1, sum = 0, ld; int n = 22; // calculate sum and product of the number here. while (n > 0) { ld = n % 10; sum = sum + ld; product = product * ld; n = n / 10; } // compare the sum and product. if (sum == product) System.out.println( "Given number is spy number"); else System.out.println( "Given number is not spy number"); }}
Given number is spy number
Complexity: O(log(n))
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
List Interface in Java with Examples
Strings in Java
Different ways of Reading a text file in Java
Reverse an array in Java
How to remove an element from ArrayList in Java?
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
Traverse Through a HashMap in Java
Extends vs Implements in Java
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n04 Jan, 2021"
},
{
"code": null,
"e": 248,
"s": 53,
"text": "A number is said to be a Spy number if the sum of all the digits is equal to the product of all digits. For performing the task we need to reverse through the number which will take log(N) time."
},
{
"code": null,
"e": 259,
"s": 248,
"text": " Example:"
},
{
"code": null,
"e": 461,
"s": 259,
"text": "Input : 22\nOutput: Given number is a SPY number.\nExplanation: Sum of the number is 4 (2 + 2)\n Product of the number is as 4 (2 * 2) \nInput : 1241\nOutput: Given number is not a SPY number."
},
{
"code": null,
"e": 471,
"s": 461,
"text": "Approach:"
},
{
"code": null,
"e": 666,
"s": 471,
"text": "Calculate the sum of digits of the input Number.Calculate the product of digits of the input Number.If the sum of digits equals the product of digits then the number is Spy number otherwise not."
},
{
"code": null,
"e": 715,
"s": 666,
"text": "Calculate the sum of digits of the input Number."
},
{
"code": null,
"e": 768,
"s": 715,
"text": "Calculate the product of digits of the input Number."
},
{
"code": null,
"e": 863,
"s": 768,
"text": "If the sum of digits equals the product of digits then the number is Spy number otherwise not."
},
{
"code": null,
"e": 914,
"s": 863,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 919,
"s": 914,
"text": "Java"
},
{
"code": "// Java Program to Check If a Number is Spy number or notimport java.io.*; class GFG { public static void main(String[] args) { int product = 1, sum = 0, ld; int n = 22; // calculate sum and product of the number here. while (n > 0) { ld = n % 10; sum = sum + ld; product = product * ld; n = n / 10; } // compare the sum and product. if (sum == product) System.out.println( \"Given number is spy number\"); else System.out.println( \"Given number is not spy number\"); }}",
"e": 1553,
"s": 919,
"text": null
},
{
"code": null,
"e": 1581,
"s": 1553,
"text": "Given number is spy number\n"
},
{
"code": null,
"e": 1603,
"s": 1581,
"text": "Complexity: O(log(n))"
},
{
"code": null,
"e": 1610,
"s": 1603,
"text": "Picked"
},
{
"code": null,
"e": 1615,
"s": 1610,
"text": "Java"
},
{
"code": null,
"e": 1629,
"s": 1615,
"text": "Java Programs"
},
{
"code": null,
"e": 1634,
"s": 1629,
"text": "Java"
},
{
"code": null,
"e": 1732,
"s": 1634,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1769,
"s": 1732,
"text": "List Interface in Java with Examples"
},
{
"code": null,
"e": 1785,
"s": 1769,
"text": "Strings in Java"
},
{
"code": null,
"e": 1831,
"s": 1785,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 1856,
"s": 1831,
"text": "Reverse an array in Java"
},
{
"code": null,
"e": 1905,
"s": 1856,
"text": "How to remove an element from ArrayList in Java?"
},
{
"code": null,
"e": 1931,
"s": 1905,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 1965,
"s": 1931,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 2012,
"s": 1965,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 2047,
"s": 2012,
"text": "Traverse Through a HashMap in Java"
}
] |
Mathematics | Sequence, Series and Summations
|
31 Mar, 2020
It is a set of numbers in a definite order according to some definite rule (or rules).Each number of the set is called a term of the sequence and its length is the number of terms in it. We can write the sequence as . A finite sequence is generally described by a1, a2, a3.... an, and an infinite sequence is described by a1, a2, a3.... to infinity. A sequence {an} has the limit L and we write or as .For example:
2, 4, 6, 8 ...., 20 is a finite sequence obtained by adding 2 to the previous number.
10, 6, 2, -2, ..... is an infinite sequence obtained by subtracting 4 from the previous number.
If the terms of a sequence can be described by a formula, then the sequence is called a progression.
1, 1, 2, 3, 5, 8, 13, ....., is a progression called the Fibonacci sequence in which each term
is the sum of the previous two numbers.
More about progressions
Theorem 1: Given the sequence if we have a function f(x) such that f(n) = and then This theorem is basically telling us that we take the limits of sequences much like we take the limit of functions.
Theorem 2 (Squeeze Theorem): If for all n > N for some N and then
Theorem 3: If then . Note that in order for this theorem to hold the limit MUST be zero and it won’t work for a sequence whose limit is not zero.
Theorem 4: If and the function f is continuous at L, then
Theorem 5: The sequence is convergent if and divergent forall other values of r. Also,This theorem is a useful theorem giving the convergence/divergence and value (for when it’s convergent) of a sequence that arises on occasion.
If and are convergent sequences, the following properties hold:
provided
And the last property is
A series is simply the sum of the various terms of a sequence.If the sequence is the expression is called the series associated with it. A series is represented by ‘S’ or the Greek symbol . The series can be finite or infinte.Examples:
5 + 2 + (-1) + (-4) is a finite series obtained by subtracting 3 from the previous number.
1 + 1 + 2 + 3 + 5 is an infinite series called the Fibonacci series obtained from the
Fibonacci sequence.
If the sequence of partial sums is a convergent sequence (i.e. its limit exists and is finite) then the series is also called convergent i.e. if then . Likewise, if the sequence of partial sums is a divergent sequence (i.e. if or its limit doesn’t exist or is plus or minus infinity) then the series is also called divergent.
If and be convergent series then
If and be convergent series then
If be convergent series then
If and be convergent series then if for all n N then Theorems:
Theorem 1 (Comparison test): Suppose for for some k. Then(1) The convergence of implies the convergence of (2) The convergence of implies the convergence of
Theorem 2 (Limit Comparison test): Let and , and suppose that . Then converges if and only if converges.
Theorem 3 (Ratio test): Suppose that the following limit exists, . Then,(1) If converges(2) If diverges(3) If might either converge or diverge
Theorem 4 (Root test): Suppose that the following limit exists:, . Then,(1) If converges(2) If diverges(3) If might either converge or diverge
Theorem 5 (Absolute Convergence test): A series is said to be absolutely convergent if the series converges.
Theorem 6 (Conditional Convergence test): A series is said to be conditionally convergent if the series diverges but the series converges .
Theorem 7 (Alternating Series test): If , and , the ‘alternating series’ will converge.
Series Questions
Summation is the addition of a sequence of numbers. It is a convenient and simple form of shorthand used to give a concise expression for a sum of the values of a variable.The summation symbol, , instructs us to sum the elements of a sequence. A typical element of the sequence which is being summed appears to the right of the summation sign.
where c is any number. So, we can factor constants out of a summation.
So we can break up a summation across a sum or difference.
Note that while we can break up sums and differences as mentioned above, we can’t do the same thing for products and quotients. In other words,
, for any natural number .
. If the argument of the summation is a constant, then the sum is the limit range value times the constant.
Examples:
1) Sum of first n natural numbers: .
2) Sum of squares of first n natural numbers:
.
3) Sum of cubes of first n natural numbers:
.
4) The property of logarithms:
.
nidhi_biet
Akanksha_Rai
richajadon17
Discrete Mathematics
Engineering Mathematics
GATE CS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Inequalities in LaTeX
Difference between Propositional Logic and Predicate Logic
Arrow Symbols in LaTeX
Set Notations in LaTeX
Activation Functions
Layers of OSI Model
ACID Properties in DBMS
TCP/IP Model
Types of Operating Systems
Normal Forms in DBMS
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n31 Mar, 2020"
},
{
"code": null,
"e": 469,
"s": 52,
"text": "It is a set of numbers in a definite order according to some definite rule (or rules).Each number of the set is called a term of the sequence and its length is the number of terms in it. We can write the sequence as . A finite sequence is generally described by a1, a2, a3.... an, and an infinite sequence is described by a1, a2, a3.... to infinity. A sequence {an} has the limit L and we write or as .For example:"
},
{
"code": null,
"e": 653,
"s": 469,
"text": "2, 4, 6, 8 ...., 20 is a finite sequence obtained by adding 2 to the previous number.\n10, 6, 2, -2, ..... is an infinite sequence obtained by subtracting 4 from the previous number. \n"
},
{
"code": null,
"e": 754,
"s": 653,
"text": "If the terms of a sequence can be described by a formula, then the sequence is called a progression."
},
{
"code": null,
"e": 890,
"s": 754,
"text": "1, 1, 2, 3, 5, 8, 13, ....., is a progression called the Fibonacci sequence in which each term \nis the sum of the previous two numbers."
},
{
"code": null,
"e": 914,
"s": 890,
"text": "More about progressions"
},
{
"code": null,
"e": 1117,
"s": 914,
"text": "Theorem 1: Given the sequence if we have a function f(x) such that f(n) = and then This theorem is basically telling us that we take the limits of sequences much like we take the limit of functions."
},
{
"code": null,
"e": 1186,
"s": 1117,
"text": "Theorem 2 (Squeeze Theorem): If for all n > N for some N and then "
},
{
"code": null,
"e": 1333,
"s": 1186,
"text": "Theorem 3: If then . Note that in order for this theorem to hold the limit MUST be zero and it won’t work for a sequence whose limit is not zero."
},
{
"code": null,
"e": 1393,
"s": 1333,
"text": "Theorem 4: If and the function f is continuous at L, then "
},
{
"code": null,
"e": 1624,
"s": 1393,
"text": "Theorem 5: The sequence is convergent if and divergent forall other values of r. Also,This theorem is a useful theorem giving the convergence/divergence and value (for when it’s convergent) of a sequence that arises on occasion."
},
{
"code": null,
"e": 1690,
"s": 1624,
"text": "If and are convergent sequences, the following properties hold:"
},
{
"code": null,
"e": 1701,
"s": 1690,
"text": " provided "
},
{
"code": null,
"e": 1726,
"s": 1701,
"text": "And the last property is"
},
{
"code": null,
"e": 1965,
"s": 1726,
"text": "A series is simply the sum of the various terms of a sequence.If the sequence is the expression is called the series associated with it. A series is represented by ‘S’ or the Greek symbol . The series can be finite or infinte.Examples:"
},
{
"code": null,
"e": 2164,
"s": 1965,
"text": "5 + 2 + (-1) + (-4) is a finite series obtained by subtracting 3 from the previous number.\n1 + 1 + 2 + 3 + 5 is an infinite series called the Fibonacci series obtained from the \nFibonacci sequence.\n"
},
{
"code": null,
"e": 2492,
"s": 2164,
"text": "If the sequence of partial sums is a convergent sequence (i.e. its limit exists and is finite) then the series is also called convergent i.e. if then . Likewise, if the sequence of partial sums is a divergent sequence (i.e. if or its limit doesn’t exist or is plus or minus infinity) then the series is also called divergent."
},
{
"code": null,
"e": 2528,
"s": 2492,
"text": "If and be convergent series then "
},
{
"code": null,
"e": 2564,
"s": 2528,
"text": "If and be convergent series then "
},
{
"code": null,
"e": 2595,
"s": 2564,
"text": "If be convergent series then "
},
{
"code": null,
"e": 2662,
"s": 2595,
"text": "If and be convergent series then if for all n N then Theorems:"
},
{
"code": null,
"e": 2824,
"s": 2662,
"text": "Theorem 1 (Comparison test): Suppose for for some k. Then(1) The convergence of implies the convergence of (2) The convergence of implies the convergence of "
},
{
"code": null,
"e": 2932,
"s": 2824,
"text": "Theorem 2 (Limit Comparison test): Let and , and suppose that . Then converges if and only if converges."
},
{
"code": null,
"e": 3078,
"s": 2932,
"text": "Theorem 3 (Ratio test): Suppose that the following limit exists, . Then,(1) If converges(2) If diverges(3) If might either converge or diverge"
},
{
"code": null,
"e": 3224,
"s": 3078,
"text": "Theorem 4 (Root test): Suppose that the following limit exists:, . Then,(1) If converges(2) If diverges(3) If might either converge or diverge"
},
{
"code": null,
"e": 3335,
"s": 3224,
"text": "Theorem 5 (Absolute Convergence test): A series is said to be absolutely convergent if the series converges."
},
{
"code": null,
"e": 3478,
"s": 3335,
"text": "Theorem 6 (Conditional Convergence test): A series is said to be conditionally convergent if the series diverges but the series converges ."
},
{
"code": null,
"e": 3567,
"s": 3478,
"text": "Theorem 7 (Alternating Series test): If , and , the ‘alternating series’ will converge."
},
{
"code": null,
"e": 3584,
"s": 3567,
"text": "Series Questions"
},
{
"code": null,
"e": 3928,
"s": 3584,
"text": "Summation is the addition of a sequence of numbers. It is a convenient and simple form of shorthand used to give a concise expression for a sum of the values of a variable.The summation symbol, , instructs us to sum the elements of a sequence. A typical element of the sequence which is being summed appears to the right of the summation sign."
},
{
"code": null,
"e": 4000,
"s": 3928,
"text": " where c is any number. So, we can factor constants out of a summation."
},
{
"code": null,
"e": 4060,
"s": 4000,
"text": " So we can break up a summation across a sum or difference."
},
{
"code": null,
"e": 4204,
"s": 4060,
"text": "Note that while we can break up sums and differences as mentioned above, we can’t do the same thing for products and quotients. In other words,"
},
{
"code": null,
"e": 4231,
"s": 4204,
"text": ", for any natural number ."
},
{
"code": null,
"e": 4339,
"s": 4231,
"text": ". If the argument of the summation is a constant, then the sum is the limit range value times the constant."
},
{
"code": null,
"e": 4349,
"s": 4339,
"text": "Examples:"
},
{
"code": null,
"e": 4520,
"s": 4349,
"text": "1) Sum of first n natural numbers: .\n\n2) Sum of squares of first n natural numbers: \n.\n\n3) Sum of cubes of first n natural numbers: \n.\n\n4) The property of logarithms: \n.\n"
},
{
"code": null,
"e": 4531,
"s": 4520,
"text": "nidhi_biet"
},
{
"code": null,
"e": 4544,
"s": 4531,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 4557,
"s": 4544,
"text": "richajadon17"
},
{
"code": null,
"e": 4578,
"s": 4557,
"text": "Discrete Mathematics"
},
{
"code": null,
"e": 4602,
"s": 4578,
"text": "Engineering Mathematics"
},
{
"code": null,
"e": 4610,
"s": 4602,
"text": "GATE CS"
},
{
"code": null,
"e": 4708,
"s": 4610,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4730,
"s": 4708,
"text": "Inequalities in LaTeX"
},
{
"code": null,
"e": 4789,
"s": 4730,
"text": "Difference between Propositional Logic and Predicate Logic"
},
{
"code": null,
"e": 4812,
"s": 4789,
"text": "Arrow Symbols in LaTeX"
},
{
"code": null,
"e": 4835,
"s": 4812,
"text": "Set Notations in LaTeX"
},
{
"code": null,
"e": 4856,
"s": 4835,
"text": "Activation Functions"
},
{
"code": null,
"e": 4876,
"s": 4856,
"text": "Layers of OSI Model"
},
{
"code": null,
"e": 4900,
"s": 4876,
"text": "ACID Properties in DBMS"
},
{
"code": null,
"e": 4913,
"s": 4900,
"text": "TCP/IP Model"
},
{
"code": null,
"e": 4940,
"s": 4913,
"text": "Types of Operating Systems"
}
] |
Check if two arrays are equal or not | Practice | GeeksforGeeks
|
Given two arrays A and B of equal size N, the task is to find if given arrays are equal or not. Two arrays are said to be equal if both of them contain same set of elements, arrangements (or permutation) of elements may be different though.
Note : If there are repetitions, then counts of repeated elements must also be same for two array to be equal.
Example 1:
Input:
N = 5
A[] = {1,2,5,4,0}
B[] = {2,4,5,0,1}
Output: 1
Explanation: Both the array can be
rearranged to {0,1,2,4,5}
Example 2:
Input:
N = 3
A[] = {1,2,5}
B[] = {2,4,15}
Output: 0
Explanation: A[] and B[] have only
one common value.
Your Task:
Complete check() function which takes both the given array and their size as function arguments and returns true if the arrays are equal else returns false.The 0 and 1 printing is done by the driver code.
Expected Time Complexity : O(N)
Expected Auxilliary Space : O(N)
Constraints:
1<=N<=107
1<=A[],B[]<=1018
+2
omchaudhariofficialin 5 hours
C++ EASY | SIMPLE CODE
class Solution{
public:
//Function to check if two arrays are equal or not.
bool check(vector<ll> A, vector<ll> B, int N) {
//code here
int j=0;
vector<long long> arrA = A;
vector<long long> arrB = B;
sort(arrA.begin(), arrA.end());
sort(arrB.begin(), arrB.end());
for(auto &trg : arrA)
{
if(trg != arrB[j++])
{
return false;
}
}
return true;
}
};
0
hemasaikota5 hours ago
A.sort() B.sort() if(A==B): return True else: return False
0
ibrahimsaleem91236 hours ago
How is this python code ? Run time 0.41
#code here count=0 A.sort() B.sort() b = zip(A,B) for i,k in (b): if(i==k): count+=1 if(count==N): return 1 else: return 0
+1
dheeraj_giri8 hours ago
All test are correct : Python
def check(self,A,B,N): return sorted(A) == sorted(B)
0
swatidubey9149 hours ago
Easy and Best solution in java
class Solution{ //Function to check if two arrays are equal or not. public static boolean check(long A[],long B[],int N) { Arrays.sort(A); Arrays.sort(B); for(int i = 0 ; i < N ; i++){ if(A[i] != B[i]){ return false; } } return true; }}
0
amanji506715 hours ago
bool check(vector<ll> A, vector<ll> B, int N) { //code here unordered_map<ll,ll> mp1,mp2; for(int i=0;i<N;i++) { mp1[A[i]]++; mp2[B[i]]++; } for(auto pr:mp1) { if(pr.second!=mp2[pr.first]) return false; } return true; }
0
rajkunal1 day ago
class Solution{ public:
//Function to check if two arrays are equal or not. bool check(vector<ll> A, vector<ll> B, int N) { //code here sort(A.begin(),A.end()); sort(B.begin(),B.end()); for(int i=0;i<N;i++) { if(A[i]!=B[i]) return false; } return true; }};
+1
shahabuddinbravo401 day ago
class Solution{ public:
//Function to check if two arrays are equal or not. bool check(vector<ll> A, vector<ll> B, int N) {
unordered_map<ll,ll>m; // ll → long long for(auto &value : A) { m[value]++; } for(auto &value : B){ m[value]--; } for(auto &value : m){ if(value.second>0) return false; } return true; }};
-1
raviyadav80921 day ago
simple O(n ) solution . All cases passed
class Solution{ public:
bool check(vector<ll> A, vector<ll> B, int N) { sort(A.begin(), A.end()); sort(B.begin(), B.end()); int flag=1; for(int i=0;i<N;i++) { if(A[i] != B[i]){ flag=1;break;} else flag=0; } if(flag==1) return 0; else return 1; }};
+1
kanishk2512962 days ago
bool check(vector<ll> A, vector<ll> B, int N) {
//code here
unordered_set<int> m(A.begin(),A.end());
unordered_set<int> n(B.begin(),B.end());
int sum = 0;
for(int i=0; i<N; i++){
sum += (A[i]-B[i]);
if(m.count(B[i]) == 0) return false;
if(n.count(A[i]) == 0) return false;
}
return (sum == 0) ? true : false;
}
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.
Make sure you are not using ad-blockers.
Disable browser extensions.
We recommend using latest version of your browser for best experience.
Avoid using static/global variables in coding problems as your code is tested
against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases in coding problems 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": 590,
"s": 238,
"text": "Given two arrays A and B of equal size N, the task is to find if given arrays are equal or not. Two arrays are said to be equal if both of them contain same set of elements, arrangements (or permutation) of elements may be different though.\nNote : If there are repetitions, then counts of repeated elements must also be same for two array to be equal."
},
{
"code": null,
"e": 601,
"s": 590,
"text": "Example 1:"
},
{
"code": null,
"e": 723,
"s": 601,
"text": "Input:\nN = 5\nA[] = {1,2,5,4,0}\nB[] = {2,4,5,0,1}\nOutput: 1\nExplanation: Both the array can be \nrearranged to {0,1,2,4,5}\n"
},
{
"code": null,
"e": 734,
"s": 723,
"text": "Example 2:"
},
{
"code": null,
"e": 840,
"s": 734,
"text": "Input:\nN = 3\nA[] = {1,2,5}\nB[] = {2,4,15}\nOutput: 0\nExplanation: A[] and B[] have only \none common value."
},
{
"code": null,
"e": 1056,
"s": 840,
"text": "Your Task:\nComplete check() function which takes both the given array and their size as function arguments and returns true if the arrays are equal else returns false.The 0 and 1 printing is done by the driver code."
},
{
"code": null,
"e": 1121,
"s": 1056,
"text": "Expected Time Complexity : O(N)\nExpected Auxilliary Space : O(N)"
},
{
"code": null,
"e": 1161,
"s": 1121,
"text": "Constraints:\n1<=N<=107\n1<=A[],B[]<=1018"
},
{
"code": null,
"e": 1166,
"s": 1163,
"text": "+2"
},
{
"code": null,
"e": 1196,
"s": 1166,
"text": "omchaudhariofficialin 5 hours"
},
{
"code": null,
"e": 1219,
"s": 1196,
"text": "C++ EASY | SIMPLE CODE"
},
{
"code": null,
"e": 1763,
"s": 1221,
"text": "class Solution{\n public:\n\n //Function to check if two arrays are equal or not.\n bool check(vector<ll> A, vector<ll> B, int N) {\n //code here\n \n int j=0;\n \n vector<long long> arrA = A;\n vector<long long> arrB = B;\n \n sort(arrA.begin(), arrA.end());\n sort(arrB.begin(), arrB.end());\n \n for(auto &trg : arrA)\n {\n if(trg != arrB[j++])\n {\n return false;\n }\n }\n \n return true;\n }\n};"
},
{
"code": null,
"e": 1765,
"s": 1763,
"text": "0"
},
{
"code": null,
"e": 1788,
"s": 1765,
"text": "hemasaikota5 hours ago"
},
{
"code": null,
"e": 1892,
"s": 1788,
"text": " A.sort() B.sort() if(A==B): return True else: return False"
},
{
"code": null,
"e": 1894,
"s": 1892,
"text": "0"
},
{
"code": null,
"e": 1923,
"s": 1894,
"text": "ibrahimsaleem91236 hours ago"
},
{
"code": null,
"e": 1963,
"s": 1923,
"text": "How is this python code ? Run time 0.41"
},
{
"code": null,
"e": 2172,
"s": 1963,
"text": "#code here count=0 A.sort() B.sort() b = zip(A,B) for i,k in (b): if(i==k): count+=1 if(count==N): return 1 else: return 0"
},
{
"code": null,
"e": 2175,
"s": 2172,
"text": "+1"
},
{
"code": null,
"e": 2199,
"s": 2175,
"text": "dheeraj_giri8 hours ago"
},
{
"code": null,
"e": 2231,
"s": 2199,
"text": "All test are correct : Python "
},
{
"code": null,
"e": 2292,
"s": 2233,
"text": "def check(self,A,B,N): return sorted(A) == sorted(B)"
},
{
"code": null,
"e": 2294,
"s": 2292,
"text": "0"
},
{
"code": null,
"e": 2319,
"s": 2294,
"text": "swatidubey9149 hours ago"
},
{
"code": null,
"e": 2350,
"s": 2319,
"text": "Easy and Best solution in java"
},
{
"code": null,
"e": 2672,
"s": 2352,
"text": "class Solution{ //Function to check if two arrays are equal or not. public static boolean check(long A[],long B[],int N) { Arrays.sort(A); Arrays.sort(B); for(int i = 0 ; i < N ; i++){ if(A[i] != B[i]){ return false; } } return true; }}"
},
{
"code": null,
"e": 2674,
"s": 2672,
"text": "0"
},
{
"code": null,
"e": 2697,
"s": 2674,
"text": "amanji506715 hours ago"
},
{
"code": null,
"e": 3014,
"s": 2697,
"text": " bool check(vector<ll> A, vector<ll> B, int N) { //code here unordered_map<ll,ll> mp1,mp2; for(int i=0;i<N;i++) { mp1[A[i]]++; mp2[B[i]]++; } for(auto pr:mp1) { if(pr.second!=mp2[pr.first]) return false; } return true; }"
},
{
"code": null,
"e": 3016,
"s": 3014,
"text": "0"
},
{
"code": null,
"e": 3034,
"s": 3016,
"text": "rajkunal1 day ago"
},
{
"code": null,
"e": 3060,
"s": 3034,
"text": "class Solution{ public:"
},
{
"code": null,
"e": 3369,
"s": 3060,
"text": " //Function to check if two arrays are equal or not. bool check(vector<ll> A, vector<ll> B, int N) { //code here sort(A.begin(),A.end()); sort(B.begin(),B.end()); for(int i=0;i<N;i++) { if(A[i]!=B[i]) return false; } return true; }};"
},
{
"code": null,
"e": 3372,
"s": 3369,
"text": "+1"
},
{
"code": null,
"e": 3400,
"s": 3372,
"text": "shahabuddinbravo401 day ago"
},
{
"code": null,
"e": 3426,
"s": 3400,
"text": "class Solution{ public:"
},
{
"code": null,
"e": 3531,
"s": 3426,
"text": " //Function to check if two arrays are equal or not. bool check(vector<ll> A, vector<ll> B, int N) {"
},
{
"code": null,
"e": 3851,
"s": 3531,
"text": " unordered_map<ll,ll>m; // ll → long long for(auto &value : A) { m[value]++; } for(auto &value : B){ m[value]--; } for(auto &value : m){ if(value.second>0) return false; } return true; }};"
},
{
"code": null,
"e": 3854,
"s": 3851,
"text": "-1"
},
{
"code": null,
"e": 3877,
"s": 3854,
"text": "raviyadav80921 day ago"
},
{
"code": null,
"e": 3918,
"s": 3877,
"text": "simple O(n ) solution . All cases passed"
},
{
"code": null,
"e": 3946,
"s": 3920,
"text": "class Solution{ public:"
},
{
"code": null,
"e": 4336,
"s": 3946,
"text": " bool check(vector<ll> A, vector<ll> B, int N) { sort(A.begin(), A.end()); sort(B.begin(), B.end()); int flag=1; for(int i=0;i<N;i++) { if(A[i] != B[i]){ flag=1;break;} else flag=0; } if(flag==1) return 0; else return 1; }};"
},
{
"code": null,
"e": 4339,
"s": 4336,
"text": "+1"
},
{
"code": null,
"e": 4363,
"s": 4339,
"text": "kanishk2512962 days ago"
},
{
"code": null,
"e": 4774,
"s": 4363,
"text": " bool check(vector<ll> A, vector<ll> B, int N) {\n //code here\n unordered_set<int> m(A.begin(),A.end());\n unordered_set<int> n(B.begin(),B.end());\n int sum = 0;\n for(int i=0; i<N; i++){\n sum += (A[i]-B[i]);\n if(m.count(B[i]) == 0) return false;\n if(n.count(A[i]) == 0) return false;\n }\n return (sum == 0) ? true : false;\n }"
},
{
"code": null,
"e": 4920,
"s": 4774,
"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": 4956,
"s": 4920,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 4966,
"s": 4956,
"text": "\nProblem\n"
},
{
"code": null,
"e": 4976,
"s": 4966,
"text": "\nContest\n"
},
{
"code": null,
"e": 5039,
"s": 4976,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 5224,
"s": 5039,
"text": "Avoid using static/global variables in your code as your code is tested \n against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 5508,
"s": 5224,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code.\n On submission, your code is tested against multiple test cases consisting of all\n possible corner cases and stress constraints."
},
{
"code": null,
"e": 5654,
"s": 5508,
"text": "You can access the hints to get an idea about what is expected of you as well as\n the final solution code."
},
{
"code": null,
"e": 5731,
"s": 5654,
"text": "You can view the solutions submitted by other users from the submission tab."
},
{
"code": null,
"e": 5772,
"s": 5731,
"text": "Make sure you are not using ad-blockers."
},
{
"code": null,
"e": 5800,
"s": 5772,
"text": "Disable browser extensions."
},
{
"code": null,
"e": 5871,
"s": 5800,
"text": "We recommend using latest version of your browser for best experience."
},
{
"code": null,
"e": 6058,
"s": 5871,
"text": "Avoid using static/global variables in coding problems as your code is tested \n against multiple test cases and these tend to retain their previous values."
}
] |
Send SMS with REST Using Python
|
14 Sep, 2021
In this article, we are going to see how we can send SMS with REST using Python. The requests library can be used to make REST requests using Python to send SMS.
You need to first create a REST API KEY for sending SMS using Python Script. We have used Fast2SMS for creating API KEY.
You can go on the website and create an account after which you can have your own API KEY.
Create a Python File and copy the below code, Replace “API_KEY_OF_YOURS” with your API KEY, and in the numbers parameter, enter the number on which you want to send SMS, you can enter multiple numbers.
Following are the parameters used in GET API:
authorization – true, Provide “YOUR_API_KEY”. Sign up for API Key
message – true, Message “text” to be sent
language – false, Default language is “english”. API will detect “unicode” messages automatically.
route – true, For Quick SMS use “q”
numbers – true, You can send multiple mobile numbers separated by commas like: “XXXXXXXX98, YYYYYYYY89”
flash – false, This field is optional, it will use “0” as a default value or you can set it to “1” for sending a flash message.
Python
import requests url = "https://www.fast2sms.com/dev/bulkV2" querystring = { "authorization": "API_KEY_OF_YOURS", "message": "This is test Message sent from \ Python Script using REST API.", "language": "english", "route": "q", "numbers": "XXXXXXXX98, YYYYYYYY89"} headers = { 'cache-control': "no-cache"}try: response = requests.request("GET", url, headers = headers, params = querystring) print("SMS Successfully Sent")except: print("Oops! Something wrong")
Output:
SMS Successfully Sent
Message sent using REST in Python
Picked
Python-requests
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n14 Sep, 2021"
},
{
"code": null,
"e": 191,
"s": 28,
"text": "In this article, we are going to see how we can send SMS with REST using Python. The requests library can be used to make REST requests using Python to send SMS. "
},
{
"code": null,
"e": 312,
"s": 191,
"text": "You need to first create a REST API KEY for sending SMS using Python Script. We have used Fast2SMS for creating API KEY."
},
{
"code": null,
"e": 403,
"s": 312,
"text": "You can go on the website and create an account after which you can have your own API KEY."
},
{
"code": null,
"e": 605,
"s": 403,
"text": "Create a Python File and copy the below code, Replace “API_KEY_OF_YOURS” with your API KEY, and in the numbers parameter, enter the number on which you want to send SMS, you can enter multiple numbers."
},
{
"code": null,
"e": 651,
"s": 605,
"text": "Following are the parameters used in GET API:"
},
{
"code": null,
"e": 718,
"s": 651,
"text": "authorization – true, Provide “YOUR_API_KEY”. Sign up for API Key"
},
{
"code": null,
"e": 760,
"s": 718,
"text": "message – true, Message “text” to be sent"
},
{
"code": null,
"e": 859,
"s": 760,
"text": "language – false, Default language is “english”. API will detect “unicode” messages automatically."
},
{
"code": null,
"e": 895,
"s": 859,
"text": "route – true, For Quick SMS use “q”"
},
{
"code": null,
"e": 999,
"s": 895,
"text": "numbers – true, You can send multiple mobile numbers separated by commas like: “XXXXXXXX98, YYYYYYYY89”"
},
{
"code": null,
"e": 1127,
"s": 999,
"text": "flash – false, This field is optional, it will use “0” as a default value or you can set it to “1” for sending a flash message."
},
{
"code": null,
"e": 1134,
"s": 1127,
"text": "Python"
},
{
"code": "import requests url = \"https://www.fast2sms.com/dev/bulkV2\" querystring = { \"authorization\": \"API_KEY_OF_YOURS\", \"message\": \"This is test Message sent from \\ Python Script using REST API.\", \"language\": \"english\", \"route\": \"q\", \"numbers\": \"XXXXXXXX98, YYYYYYYY89\"} headers = { 'cache-control': \"no-cache\"}try: response = requests.request(\"GET\", url, headers = headers, params = querystring) print(\"SMS Successfully Sent\")except: print(\"Oops! Something wrong\")",
"e": 1699,
"s": 1134,
"text": null
},
{
"code": null,
"e": 1707,
"s": 1699,
"text": "Output:"
},
{
"code": null,
"e": 1729,
"s": 1707,
"text": "SMS Successfully Sent"
},
{
"code": null,
"e": 1763,
"s": 1729,
"text": "Message sent using REST in Python"
},
{
"code": null,
"e": 1770,
"s": 1763,
"text": "Picked"
},
{
"code": null,
"e": 1786,
"s": 1770,
"text": "Python-requests"
},
{
"code": null,
"e": 1801,
"s": 1786,
"text": "python-utility"
},
{
"code": null,
"e": 1808,
"s": 1801,
"text": "Python"
},
{
"code": null,
"e": 1906,
"s": 1808,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1938,
"s": 1906,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1965,
"s": 1938,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1986,
"s": 1965,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2009,
"s": 1986,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2065,
"s": 2009,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2096,
"s": 2065,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2138,
"s": 2096,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 2180,
"s": 2138,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 2219,
"s": 2180,
"text": "Python | Get unique values from a list"
}
] |
How to Execute SQL Server Stored Procedure in SQL Developer?
|
23 Sep, 2021
A stored procedure is a set of (T-SQL ) statements needed in times when we are having the repetitive usage of the same query. When there is a need to use a large query multiple times we can create a stored procedure once and execute the same wherever needed instead of writing the whole query again.
In this article let us see how to execute SQL Server Stored Procedure in MSSQL.
Syntax: For creating a stored procedure
CREATE PROCEDURE (or CREATE PROC) proc_name
AS
BEGIN
QUERY
END
Step 1: We creating a Database. For this use the below command to create a database named GeeksforGeeks.
Query:
CREATE DATABASE GeeksforGeeks;
Output:
Step 2:To use the GeeksforGeeks database use the below command.
Query:
USE GeeksforGeeks
Output:
Step 3:Now we creating a table. Create a table student_details with 3 columns using the following SQL query.
Query:
CREATE TABLE student_details(
stu_id VARCHAR(8),
stu_name VARCHAR(20),
stu_cgpa DECIMAL(4,2) );
Output:
Step 4: The query for Inserting rows into the Table. Inserting rows into student_details table using the following SQL query.
Query:
INSERT INTO student_details VALUES('40001','PRADEEP',9.6);
INSERT INTO student_details VALUES('40002','ASHOK',8.2);
INSERT INTO student_details VALUES('40003','PAVAN KUMAR',7.6);
INSERT INTO student_details VALUES('40004','NIKHIL',8.2);
INSERT INTO student_details VALUES('40005','RAHUL',7.0);
Output:
Step 5: Viewing the inserted data
Query:
SELECT * FROM student_details;
Output:
Query to create a stored procedure to view the table:
Query:
CREATE PROCEDURE view_details
AS
BEGIN
SELECT * FROM student_details;
END
Output:
For executing a stored procedure we use the below syntax:
Syntax:
EXEC proc_name
or
EXECUTE proc_name
or
proc_name
Query:
EXECUTE view_details
Output:
Query to create a stored procedure that takes the argument as stu_id and displays the cgpa of that id.
Query:
CREATE PROCEDURE get_student_cg_details
@stu_id VARCHAR(20)
AS
BEGIN
SELECT stu_id, stu_cgpa FROM student_details
WHERE stu_id= @stu_id
END
Output:
Query:
EXECUTE get_student_cg_details '40002'
Output:
Blogathon-2021
Picked
SQL-Server
Blogathon
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n23 Sep, 2021"
},
{
"code": null,
"e": 352,
"s": 52,
"text": "A stored procedure is a set of (T-SQL ) statements needed in times when we are having the repetitive usage of the same query. When there is a need to use a large query multiple times we can create a stored procedure once and execute the same wherever needed instead of writing the whole query again."
},
{
"code": null,
"e": 432,
"s": 352,
"text": "In this article let us see how to execute SQL Server Stored Procedure in MSSQL."
},
{
"code": null,
"e": 472,
"s": 432,
"text": "Syntax: For creating a stored procedure"
},
{
"code": null,
"e": 537,
"s": 472,
"text": "CREATE PROCEDURE (or CREATE PROC) proc_name\nAS\nBEGIN\n QUERY\nEND"
},
{
"code": null,
"e": 642,
"s": 537,
"text": "Step 1: We creating a Database. For this use the below command to create a database named GeeksforGeeks."
},
{
"code": null,
"e": 649,
"s": 642,
"text": "Query:"
},
{
"code": null,
"e": 680,
"s": 649,
"text": "CREATE DATABASE GeeksforGeeks;"
},
{
"code": null,
"e": 688,
"s": 680,
"text": "Output:"
},
{
"code": null,
"e": 752,
"s": 688,
"text": "Step 2:To use the GeeksforGeeks database use the below command."
},
{
"code": null,
"e": 759,
"s": 752,
"text": "Query:"
},
{
"code": null,
"e": 777,
"s": 759,
"text": "USE GeeksforGeeks"
},
{
"code": null,
"e": 785,
"s": 777,
"text": "Output:"
},
{
"code": null,
"e": 895,
"s": 785,
"text": "Step 3:Now we creating a table. Create a table student_details with 3 columns using the following SQL query."
},
{
"code": null,
"e": 902,
"s": 895,
"text": "Query:"
},
{
"code": null,
"e": 1007,
"s": 902,
"text": "CREATE TABLE student_details(\n stu_id VARCHAR(8),\n stu_name VARCHAR(20),\n stu_cgpa DECIMAL(4,2) );"
},
{
"code": null,
"e": 1015,
"s": 1007,
"text": "Output:"
},
{
"code": null,
"e": 1141,
"s": 1015,
"text": "Step 4: The query for Inserting rows into the Table. Inserting rows into student_details table using the following SQL query."
},
{
"code": null,
"e": 1148,
"s": 1141,
"text": "Query:"
},
{
"code": null,
"e": 1442,
"s": 1148,
"text": "INSERT INTO student_details VALUES('40001','PRADEEP',9.6);\nINSERT INTO student_details VALUES('40002','ASHOK',8.2);\nINSERT INTO student_details VALUES('40003','PAVAN KUMAR',7.6);\nINSERT INTO student_details VALUES('40004','NIKHIL',8.2);\nINSERT INTO student_details VALUES('40005','RAHUL',7.0);"
},
{
"code": null,
"e": 1450,
"s": 1442,
"text": "Output:"
},
{
"code": null,
"e": 1485,
"s": 1450,
"text": " Step 5: Viewing the inserted data"
},
{
"code": null,
"e": 1492,
"s": 1485,
"text": "Query:"
},
{
"code": null,
"e": 1523,
"s": 1492,
"text": "SELECT * FROM student_details;"
},
{
"code": null,
"e": 1531,
"s": 1523,
"text": "Output:"
},
{
"code": null,
"e": 1585,
"s": 1531,
"text": "Query to create a stored procedure to view the table:"
},
{
"code": null,
"e": 1592,
"s": 1585,
"text": "Query:"
},
{
"code": null,
"e": 1669,
"s": 1592,
"text": "CREATE PROCEDURE view_details\nAS\nBEGIN \n SELECT * FROM student_details;\nEND"
},
{
"code": null,
"e": 1677,
"s": 1669,
"text": "Output:"
},
{
"code": null,
"e": 1736,
"s": 1677,
"text": " For executing a stored procedure we use the below syntax:"
},
{
"code": null,
"e": 1744,
"s": 1736,
"text": "Syntax:"
},
{
"code": null,
"e": 1799,
"s": 1744,
"text": " EXEC proc_name\n or\n EXECUTE proc_name\n or \n proc_name"
},
{
"code": null,
"e": 1806,
"s": 1799,
"text": "Query:"
},
{
"code": null,
"e": 1827,
"s": 1806,
"text": "EXECUTE view_details"
},
{
"code": null,
"e": 1835,
"s": 1827,
"text": "Output:"
},
{
"code": null,
"e": 1938,
"s": 1835,
"text": "Query to create a stored procedure that takes the argument as stu_id and displays the cgpa of that id."
},
{
"code": null,
"e": 1945,
"s": 1938,
"text": "Query:"
},
{
"code": null,
"e": 2089,
"s": 1945,
"text": "CREATE PROCEDURE get_student_cg_details\n@stu_id VARCHAR(20)\nAS\nBEGIN \n SELECT stu_id, stu_cgpa FROM student_details\n WHERE stu_id= @stu_id\nEND"
},
{
"code": null,
"e": 2097,
"s": 2089,
"text": "Output:"
},
{
"code": null,
"e": 2104,
"s": 2097,
"text": "Query:"
},
{
"code": null,
"e": 2143,
"s": 2104,
"text": "EXECUTE get_student_cg_details '40002'"
},
{
"code": null,
"e": 2151,
"s": 2143,
"text": "Output:"
},
{
"code": null,
"e": 2166,
"s": 2151,
"text": "Blogathon-2021"
},
{
"code": null,
"e": 2173,
"s": 2166,
"text": "Picked"
},
{
"code": null,
"e": 2184,
"s": 2173,
"text": "SQL-Server"
},
{
"code": null,
"e": 2194,
"s": 2184,
"text": "Blogathon"
},
{
"code": null,
"e": 2198,
"s": 2194,
"text": "SQL"
},
{
"code": null,
"e": 2202,
"s": 2198,
"text": "SQL"
}
] |
Maximum cost path in an Undirected Graph such that no edge is visited twice in a row
|
24 Nov, 2021
Given an undirected graph having N vertices and M edges and each vertex is associated with a cost and a source vertex S is given. The task is to find the maximum cost path from source vertex S such that no edge is visited consecutively 2 or more times.
Examples:
Input: N = 5, M = 5, source = 1, cost[] = {2, 2, 8, 6, 9}, Below is the given graph:
Output: 21 Explanation: The maximum cost path matrix is given as: 1 -> 2 -> 0 -> 1 -> 4 Cost = 2 + 8 + 2 + 2 + 9 = 21
Input: N = 8, M = 8, source = 3, cost[] = {10, 11, 4, 12, 3, 4, 7, 9}
Output: 46
Explanation: The maximum cost path matrix is given as: 3 -> 0 -> 2 -> 1 -> 7
Approach: The idea is to check if there exists a loop exists in the graph, then all vertices of the loop need to be traversed and then traverse graph towards the leaf nodes with the maximum cost. And if the loop does not exist then the problem statement converts to find maximum cost path in any directed graph.
Below are the declaration used in the program:
dp[i]: stores the total cost to traverse the node ‘i’ and all it’s children node.
vis[i]: marks the nodes which have been visited.
canTake: stores the resultant sum of all node of maximum cost path excluding the leaf vertex and its children node, if it exists.
best: stores the cost of a maximum cost leaf node and its children node(if it exists).
check: boolean variable used as a flag to find a loop in the graph, its value changes to 0 when the loop is found.
Below are the steps:
Perform DFS traversal with flag variable check set to ‘1’ initially denoting no loop found.Simultaneously build the dp[] for each node with the maximum cost updated till that traversed node.If the adjacent node is found to be already visited and it is not the parent node then the loop is found and set the value of the check to 0.Add the cost of all nodes of the loop to canTake.After traversing adjacent nodes of the traversing node, no loop is found, then it represents the cost of the path leading from loop to leaf vertex and updates best to dp[i] if dp[i] is greater than best.After traversal of the graph, print the sum of canTake and best.
Perform DFS traversal with flag variable check set to ‘1’ initially denoting no loop found.
Simultaneously build the dp[] for each node with the maximum cost updated till that traversed node.
If the adjacent node is found to be already visited and it is not the parent node then the loop is found and set the value of the check to 0.
Add the cost of all nodes of the loop to canTake.
After traversing adjacent nodes of the traversing node, no loop is found, then it represents the cost of the path leading from loop to leaf vertex and updates best to dp[i] if dp[i] is greater than best.
After traversal of the graph, print the sum of canTake and best.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // To store the resulting// sum of the costint canTake; // To store largest// cost leaf vertexint best; vector<int> dp;vector<bool> vis; // DFS Traversal to find the update// the maximum cost of from any// node to leafint dfs(vector<vector<int> >& g, int* cost, int u, int pre){ // Mark vertex as visited vis[u] = true; // Store vertex initial cost dp[u] = cost[u]; // Initially assuming edge // not to be traversed bool check = 1; int cur = cost[u]; for (auto& x : g[u]) { // Back edge found so, // edge can be part of // traversal if (vis[x] && x != pre) { check = 0; } // New vertex is found else if (!vis[x]) { // Bitwise AND the current // check with the returned // check by the previous // DFS Call check &= dfs(g, cost, x, u); // Adds parent and its // children cost cur = max(cur, cost[u] + dp[x]); } } // Updates total cost of parent // including child nodes dp[u] = cur; // Edge is part of the cycle if (!check) { // Add cost of vertex // to the answer canTake += cost[u]; } else { // Updates the largest // cost leaf vertex best = max(best, dp[u]); } return check;} // Function to find the maximum cost// from source vertex such that no// two edges is traversed twiceint FindMaxCost(vector<vector<int> >& g, int* cost, int source){ // DFS Call dfs(g, cost, source, -1); // Print the maximum cost cout << canTake + best;} // Driver Codeint main(){ int n = 5, m = 5; dp.resize(n+1); vis.resize(n+1); // Cost Array int cost[] = { 2, 2, 8, 6, 9 }; vector<vector<int> > g(n); // Given Graph g[0].push_back(1); g[1].push_back(0); g[0].push_back(2); g[2].push_back(0); g[0].push_back(3); g[3].push_back(0); g[1].push_back(2); g[2].push_back(1); g[1].push_back(4); g[4].push_back(1); // Given Source Node int source = 1; // Function Call FindMaxCost(g, cost, source); return 0;}
// Java program for the above approachimport java.util.*; class GFG{ static int N = 100000; // To store the resulting// sum of the coststatic int canTake; // To store largest// cost leaf vertexstatic int best; static int []dp = new int[N];static boolean []vis = new boolean[N]; // DFS Traversal to find the update// the maximum cost of from any// node to leafstatic boolean dfs(Vector<Integer> []g, int []cost, int u, int pre){ // Mark vertex as visited vis[u] = true; // Store vertex initial cost dp[u] = cost[u]; // Initially assuming edge // not to be traversed boolean check = true; int cur = cost[u]; for(int x : g[u]) { // Back edge found so, // edge can be part of // traversal if (vis[x] && x != pre) { check = false; } // New vertex is found else if (!vis[x]) { // Bitwise AND the current // check with the returned // check by the previous // DFS Call check = dfs(g, cost, x, u) ? false : true; // Adds parent and its // children cost cur = Math.max(cur, cost[u] + dp[x]); } } // Updates total cost of parent // including child nodes dp[u] = cur; // Edge is part of the cycle if (!check) { // Add cost of vertex // to the answer canTake += cost[u]; } else { // Updates the largest // cost leaf vertex best = Math.max(best, dp[u]); } return check;} // Function to find the maximum cost// from source vertex such that no// two edges is traversed twicestatic void FindMaxCost(Vector<Integer> [] g, int []cost, int source){ // DFS call dfs(g, cost, source, -1); // Print the maximum cost System.out.print(canTake + best);} // Driver Codepublic static void main(String[] args){ int n = 5, m = 5; // Cost Array int cost[] = { 2, 2, 8, 6, 9 }; @SuppressWarnings("unchecked") Vector<Integer> []g = new Vector[n]; for(int i = 0; i < g.length; i++) g[i] = new Vector<Integer>(); // Given Graph g[0].add(1); g[1].add(0); g[0].add(2); g[2].add(0); g[0].add(3); g[3].add(0); g[1].add(2); g[2].add(1); g[1].add(4); g[4].add(1); // Given Source Node int source = 1; // Function call FindMaxCost(g, cost, source);}} // This code is contributed by Amit Katiyar
# Python3 program for the above approachN = 100000 # To store the resulting# sum of the costcanTake = 0 # To store largest# cost leaf vertexbest = 0 dp = [0 for i in range(N)]vis = [0 for i in range(N)] # DFS Traversal to find the update# the maximum cost of from any# node to leafdef dfs(g, cost, u, pre): global canTake, best # Mark vertex as visited vis[u] = True # Store vertex initial cost dp[u] = cost[u] # Initially assuming edge # not to be traversed check = 1 cur = cost[u] for x in g[u]: # Back edge found so, # edge can be part of # traversal if (vis[x] and x != pre): check = 0 # New vertex is found elif (not vis[x]): # Bitwise AND the current # check with the returned # check by the previous # DFS Call check &= dfs(g, cost, x, u) # Adds parent and its # children cost cur = max(cur, cost[u] + dp[x]) # Updates total cost of parent # including child nodes dp[u] = cur # Edge is part of the cycle if (not check): # Add cost of vertex # to the answer canTake += cost[u] else: # Updates the largest # cost leaf vertex best = max(best, dp[u]) return check # Function to find the maximum cost# from source vertex such that no# two edges is traversed twicedef FindMaxCost(g, cost, source): # DFS Call dfs(g, cost, source, -1) # Print the maximum cost print(canTake + best) # Driver Codeif __name__=='__main__': n = 5 m = 5 # Cost Array cost = [ 2, 2, 8, 6, 9 ] g = [[] for i in range(n)] # Given Graph g[0].append(1) g[1].append(0) g[0].append(2) g[2].append(0) g[0].append(3) g[3].append(0) g[1].append(2) g[2].append(1) g[1].append(4) g[4].append(1) # Given Source Node source = 1 # Function Call FindMaxCost(g, cost, source) # This code is contributed by rutvik_56
// C# program for// the above approachusing System;using System.Collections.Generic;class GFG{ static int N = 100000; // To store the resulting// sum of the coststatic int canTake; // To store largest// cost leaf vertexstatic int best; static int []dp = new int[N];static bool []vis = new bool[N]; // DFS Traversal to find the update// the maximum cost of from any// node to leafstatic bool dfs(List<int> []g, int []cost, int u, int pre){ // Mark vertex as visited vis[u] = true; // Store vertex initial cost dp[u] = cost[u]; // Initially assuming edge // not to be traversed bool check = true; int cur = cost[u]; foreach(int x in g[u]) { // Back edge found so, // edge can be part of // traversal if (vis[x] && x != pre) { check = false; } // New vertex is found else if (!vis[x]) { // Bitwise AND the current // check with the returned // check by the previous // DFS Call check = dfs(g, cost, x, u) ? false : true; // Adds parent and its // children cost cur = Math.Max(cur, cost[u] + dp[x]); } } // Updates total cost of parent // including child nodes dp[u] = cur; // Edge is part of the cycle if (!check) { // Add cost of vertex // to the answer canTake += cost[u]; } else { // Updates the largest // cost leaf vertex best = Math.Max(best, dp[u]); } return check;} // Function to find the maximum cost// from source vertex such that no// two edges is traversed twicestatic void FindMaxCost(List<int> [] g, int []cost, int source){ // DFS call dfs(g, cost, source, -1); // Print the maximum cost Console.Write(canTake + best);} // Driver Codepublic static void Main(String[] args){ int n = 5, m = 5; // Cost Array int []cost = {2, 2, 8, 6, 9}; List<int> []g = new List<int>[n]; for(int i = 0; i < g.Length; i++) g[i] = new List<int>(); // Given Graph g[0].Add(1); g[1].Add(0); g[0].Add(2); g[2].Add(0); g[0].Add(3); g[3].Add(0); g[1].Add(2); g[2].Add(1); g[1].Add(4); g[4].Add(1); // Given Source Node int source = 1; // Function call FindMaxCost(g, cost, source);}} // This code is contributed by Princi Singh
<script> // Javascript program for// the above approach var N = 100000; // To store the resulting// sum of the costvar canTake = 0; // To store largest// cost leaf vertexvar best = 0; var dp = Array(N).fill(0);var vis = Array(N).fill(false); // DFS Traversal to find the update// the maximum cost of from any// node to leaffunction dfs(g, cost, u, pre){ // Mark vertex as visited vis[u] = true; // Store vertex initial cost dp[u] = cost[u]; // Initially assuming edge // not to be traversed var check = true; var cur = cost[u]; for(var x of g[u]) { // Back edge found so, // edge can be part of // traversal if (vis[x] && x != pre) { check = false; } // New vertex is found else if (!vis[x]) { // Bitwise AND the current // check with the returned // check by the previous // DFS Call check = dfs(g, cost, x, u) ? false : true; // Adds parent and its // children cost cur = Math.max(cur, cost[u] + dp[x]); } } // Updates total cost of parent // including child nodes dp[u] = cur; // Edge is part of the cycle if (!check) { // push cost of vertex // to the answer canTake += cost[u]; } else { // Updates the largest // cost leaf vertex best = Math.max(best, dp[u]); } return check;} // Function to find the maximum cost// from source vertex such that no// two edges is traversed twicefunction FindMaxCost(g, cost, source){ // DFS call dfs(g, cost, source, -1); // Print the maximum cost document.write(canTake + best);} // Driver Codevar n = 5, m = 5;// Cost Arrayvar cost = [2, 2, 8, 6, 9];var g = Array.from(Array(n), ()=>Array()); // Given Graphg[0].push(1);g[1].push(0);g[0].push(2);g[2].push(0);g[0].push(3);g[3].push(0);g[1].push(2);g[2].push(1);g[1].push(4);g[4].push(1);// Given Source Nodevar source = 1;// Function callFindMaxCost(g, cost, source); </script>
21
Time Complexity: O(N + M) where N is a number of vertices and M is the number of edges.Auxiliary Space: O(N + M) where N is a number of vertices and M is a number of edges.
nidhi_biet
amit143katiyar
princi singh
rutvik_56
noob2000
ashutoshsinghgeeksforgeeks
Algorithms-Graph Traversals
DFS
Algorithms
Arrays
Dynamic Programming
Graph
Greedy
Recursion
Arrays
Dynamic Programming
Greedy
Recursion
DFS
Graph
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
What is Hashing | A Complete Tutorial
Find if there is a path between two vertices in an undirected graph
How to Start Learning DSA?
Complete Roadmap To Learn DSA From Scratch
Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete
Arrays in Java
Write a program to reverse an array or string
Maximum and minimum of an array using minimum number of comparisons
Largest Sum Contiguous Subarray
Arrays in C/C++
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n24 Nov, 2021"
},
{
"code": null,
"e": 305,
"s": 52,
"text": "Given an undirected graph having N vertices and M edges and each vertex is associated with a cost and a source vertex S is given. The task is to find the maximum cost path from source vertex S such that no edge is visited consecutively 2 or more times."
},
{
"code": null,
"e": 316,
"s": 305,
"text": "Examples: "
},
{
"code": null,
"e": 403,
"s": 316,
"text": "Input: N = 5, M = 5, source = 1, cost[] = {2, 2, 8, 6, 9}, Below is the given graph: "
},
{
"code": null,
"e": 521,
"s": 403,
"text": "Output: 21 Explanation: The maximum cost path matrix is given as: 1 -> 2 -> 0 -> 1 -> 4 Cost = 2 + 8 + 2 + 2 + 9 = 21"
},
{
"code": null,
"e": 593,
"s": 521,
"text": "Input: N = 8, M = 8, source = 3, cost[] = {10, 11, 4, 12, 3, 4, 7, 9} "
},
{
"code": null,
"e": 605,
"s": 593,
"text": "Output: 46 "
},
{
"code": null,
"e": 684,
"s": 605,
"text": "Explanation: The maximum cost path matrix is given as: 3 -> 0 -> 2 -> 1 -> 7 "
},
{
"code": null,
"e": 996,
"s": 684,
"text": "Approach: The idea is to check if there exists a loop exists in the graph, then all vertices of the loop need to be traversed and then traverse graph towards the leaf nodes with the maximum cost. And if the loop does not exist then the problem statement converts to find maximum cost path in any directed graph."
},
{
"code": null,
"e": 1045,
"s": 996,
"text": " Below are the declaration used in the program: "
},
{
"code": null,
"e": 1127,
"s": 1045,
"text": "dp[i]: stores the total cost to traverse the node ‘i’ and all it’s children node."
},
{
"code": null,
"e": 1176,
"s": 1127,
"text": "vis[i]: marks the nodes which have been visited."
},
{
"code": null,
"e": 1306,
"s": 1176,
"text": "canTake: stores the resultant sum of all node of maximum cost path excluding the leaf vertex and its children node, if it exists."
},
{
"code": null,
"e": 1393,
"s": 1306,
"text": "best: stores the cost of a maximum cost leaf node and its children node(if it exists)."
},
{
"code": null,
"e": 1508,
"s": 1393,
"text": "check: boolean variable used as a flag to find a loop in the graph, its value changes to 0 when the loop is found."
},
{
"code": null,
"e": 1530,
"s": 1508,
"text": "Below are the steps: "
},
{
"code": null,
"e": 2178,
"s": 1530,
"text": "Perform DFS traversal with flag variable check set to ‘1’ initially denoting no loop found.Simultaneously build the dp[] for each node with the maximum cost updated till that traversed node.If the adjacent node is found to be already visited and it is not the parent node then the loop is found and set the value of the check to 0.Add the cost of all nodes of the loop to canTake.After traversing adjacent nodes of the traversing node, no loop is found, then it represents the cost of the path leading from loop to leaf vertex and updates best to dp[i] if dp[i] is greater than best.After traversal of the graph, print the sum of canTake and best."
},
{
"code": null,
"e": 2270,
"s": 2178,
"text": "Perform DFS traversal with flag variable check set to ‘1’ initially denoting no loop found."
},
{
"code": null,
"e": 2370,
"s": 2270,
"text": "Simultaneously build the dp[] for each node with the maximum cost updated till that traversed node."
},
{
"code": null,
"e": 2512,
"s": 2370,
"text": "If the adjacent node is found to be already visited and it is not the parent node then the loop is found and set the value of the check to 0."
},
{
"code": null,
"e": 2562,
"s": 2512,
"text": "Add the cost of all nodes of the loop to canTake."
},
{
"code": null,
"e": 2766,
"s": 2562,
"text": "After traversing adjacent nodes of the traversing node, no loop is found, then it represents the cost of the path leading from loop to leaf vertex and updates best to dp[i] if dp[i] is greater than best."
},
{
"code": null,
"e": 2831,
"s": 2766,
"text": "After traversal of the graph, print the sum of canTake and best."
},
{
"code": null,
"e": 2882,
"s": 2831,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 2886,
"s": 2882,
"text": "C++"
},
{
"code": null,
"e": 2891,
"s": 2886,
"text": "Java"
},
{
"code": null,
"e": 2899,
"s": 2891,
"text": "Python3"
},
{
"code": null,
"e": 2902,
"s": 2899,
"text": "C#"
},
{
"code": null,
"e": 2913,
"s": 2902,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // To store the resulting// sum of the costint canTake; // To store largest// cost leaf vertexint best; vector<int> dp;vector<bool> vis; // DFS Traversal to find the update// the maximum cost of from any// node to leafint dfs(vector<vector<int> >& g, int* cost, int u, int pre){ // Mark vertex as visited vis[u] = true; // Store vertex initial cost dp[u] = cost[u]; // Initially assuming edge // not to be traversed bool check = 1; int cur = cost[u]; for (auto& x : g[u]) { // Back edge found so, // edge can be part of // traversal if (vis[x] && x != pre) { check = 0; } // New vertex is found else if (!vis[x]) { // Bitwise AND the current // check with the returned // check by the previous // DFS Call check &= dfs(g, cost, x, u); // Adds parent and its // children cost cur = max(cur, cost[u] + dp[x]); } } // Updates total cost of parent // including child nodes dp[u] = cur; // Edge is part of the cycle if (!check) { // Add cost of vertex // to the answer canTake += cost[u]; } else { // Updates the largest // cost leaf vertex best = max(best, dp[u]); } return check;} // Function to find the maximum cost// from source vertex such that no// two edges is traversed twiceint FindMaxCost(vector<vector<int> >& g, int* cost, int source){ // DFS Call dfs(g, cost, source, -1); // Print the maximum cost cout << canTake + best;} // Driver Codeint main(){ int n = 5, m = 5; dp.resize(n+1); vis.resize(n+1); // Cost Array int cost[] = { 2, 2, 8, 6, 9 }; vector<vector<int> > g(n); // Given Graph g[0].push_back(1); g[1].push_back(0); g[0].push_back(2); g[2].push_back(0); g[0].push_back(3); g[3].push_back(0); g[1].push_back(2); g[2].push_back(1); g[1].push_back(4); g[4].push_back(1); // Given Source Node int source = 1; // Function Call FindMaxCost(g, cost, source); return 0;}",
"e": 5173,
"s": 2913,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.*; class GFG{ static int N = 100000; // To store the resulting// sum of the coststatic int canTake; // To store largest// cost leaf vertexstatic int best; static int []dp = new int[N];static boolean []vis = new boolean[N]; // DFS Traversal to find the update// the maximum cost of from any// node to leafstatic boolean dfs(Vector<Integer> []g, int []cost, int u, int pre){ // Mark vertex as visited vis[u] = true; // Store vertex initial cost dp[u] = cost[u]; // Initially assuming edge // not to be traversed boolean check = true; int cur = cost[u]; for(int x : g[u]) { // Back edge found so, // edge can be part of // traversal if (vis[x] && x != pre) { check = false; } // New vertex is found else if (!vis[x]) { // Bitwise AND the current // check with the returned // check by the previous // DFS Call check = dfs(g, cost, x, u) ? false : true; // Adds parent and its // children cost cur = Math.max(cur, cost[u] + dp[x]); } } // Updates total cost of parent // including child nodes dp[u] = cur; // Edge is part of the cycle if (!check) { // Add cost of vertex // to the answer canTake += cost[u]; } else { // Updates the largest // cost leaf vertex best = Math.max(best, dp[u]); } return check;} // Function to find the maximum cost// from source vertex such that no// two edges is traversed twicestatic void FindMaxCost(Vector<Integer> [] g, int []cost, int source){ // DFS call dfs(g, cost, source, -1); // Print the maximum cost System.out.print(canTake + best);} // Driver Codepublic static void main(String[] args){ int n = 5, m = 5; // Cost Array int cost[] = { 2, 2, 8, 6, 9 }; @SuppressWarnings(\"unchecked\") Vector<Integer> []g = new Vector[n]; for(int i = 0; i < g.length; i++) g[i] = new Vector<Integer>(); // Given Graph g[0].add(1); g[1].add(0); g[0].add(2); g[2].add(0); g[0].add(3); g[3].add(0); g[1].add(2); g[2].add(1); g[1].add(4); g[4].add(1); // Given Source Node int source = 1; // Function call FindMaxCost(g, cost, source);}} // This code is contributed by Amit Katiyar",
"e": 7730,
"s": 5173,
"text": null
},
{
"code": "# Python3 program for the above approachN = 100000 # To store the resulting# sum of the costcanTake = 0 # To store largest# cost leaf vertexbest = 0 dp = [0 for i in range(N)]vis = [0 for i in range(N)] # DFS Traversal to find the update# the maximum cost of from any# node to leafdef dfs(g, cost, u, pre): global canTake, best # Mark vertex as visited vis[u] = True # Store vertex initial cost dp[u] = cost[u] # Initially assuming edge # not to be traversed check = 1 cur = cost[u] for x in g[u]: # Back edge found so, # edge can be part of # traversal if (vis[x] and x != pre): check = 0 # New vertex is found elif (not vis[x]): # Bitwise AND the current # check with the returned # check by the previous # DFS Call check &= dfs(g, cost, x, u) # Adds parent and its # children cost cur = max(cur, cost[u] + dp[x]) # Updates total cost of parent # including child nodes dp[u] = cur # Edge is part of the cycle if (not check): # Add cost of vertex # to the answer canTake += cost[u] else: # Updates the largest # cost leaf vertex best = max(best, dp[u]) return check # Function to find the maximum cost# from source vertex such that no# two edges is traversed twicedef FindMaxCost(g, cost, source): # DFS Call dfs(g, cost, source, -1) # Print the maximum cost print(canTake + best) # Driver Codeif __name__=='__main__': n = 5 m = 5 # Cost Array cost = [ 2, 2, 8, 6, 9 ] g = [[] for i in range(n)] # Given Graph g[0].append(1) g[1].append(0) g[0].append(2) g[2].append(0) g[0].append(3) g[3].append(0) g[1].append(2) g[2].append(1) g[1].append(4) g[4].append(1) # Given Source Node source = 1 # Function Call FindMaxCost(g, cost, source) # This code is contributed by rutvik_56",
"e": 9802,
"s": 7730,
"text": null
},
{
"code": "// C# program for// the above approachusing System;using System.Collections.Generic;class GFG{ static int N = 100000; // To store the resulting// sum of the coststatic int canTake; // To store largest// cost leaf vertexstatic int best; static int []dp = new int[N];static bool []vis = new bool[N]; // DFS Traversal to find the update// the maximum cost of from any// node to leafstatic bool dfs(List<int> []g, int []cost, int u, int pre){ // Mark vertex as visited vis[u] = true; // Store vertex initial cost dp[u] = cost[u]; // Initially assuming edge // not to be traversed bool check = true; int cur = cost[u]; foreach(int x in g[u]) { // Back edge found so, // edge can be part of // traversal if (vis[x] && x != pre) { check = false; } // New vertex is found else if (!vis[x]) { // Bitwise AND the current // check with the returned // check by the previous // DFS Call check = dfs(g, cost, x, u) ? false : true; // Adds parent and its // children cost cur = Math.Max(cur, cost[u] + dp[x]); } } // Updates total cost of parent // including child nodes dp[u] = cur; // Edge is part of the cycle if (!check) { // Add cost of vertex // to the answer canTake += cost[u]; } else { // Updates the largest // cost leaf vertex best = Math.Max(best, dp[u]); } return check;} // Function to find the maximum cost// from source vertex such that no// two edges is traversed twicestatic void FindMaxCost(List<int> [] g, int []cost, int source){ // DFS call dfs(g, cost, source, -1); // Print the maximum cost Console.Write(canTake + best);} // Driver Codepublic static void Main(String[] args){ int n = 5, m = 5; // Cost Array int []cost = {2, 2, 8, 6, 9}; List<int> []g = new List<int>[n]; for(int i = 0; i < g.Length; i++) g[i] = new List<int>(); // Given Graph g[0].Add(1); g[1].Add(0); g[0].Add(2); g[2].Add(0); g[0].Add(3); g[3].Add(0); g[1].Add(2); g[2].Add(1); g[1].Add(4); g[4].Add(1); // Given Source Node int source = 1; // Function call FindMaxCost(g, cost, source);}} // This code is contributed by Princi Singh",
"e": 12046,
"s": 9802,
"text": null
},
{
"code": "<script> // Javascript program for// the above approach var N = 100000; // To store the resulting// sum of the costvar canTake = 0; // To store largest// cost leaf vertexvar best = 0; var dp = Array(N).fill(0);var vis = Array(N).fill(false); // DFS Traversal to find the update// the maximum cost of from any// node to leaffunction dfs(g, cost, u, pre){ // Mark vertex as visited vis[u] = true; // Store vertex initial cost dp[u] = cost[u]; // Initially assuming edge // not to be traversed var check = true; var cur = cost[u]; for(var x of g[u]) { // Back edge found so, // edge can be part of // traversal if (vis[x] && x != pre) { check = false; } // New vertex is found else if (!vis[x]) { // Bitwise AND the current // check with the returned // check by the previous // DFS Call check = dfs(g, cost, x, u) ? false : true; // Adds parent and its // children cost cur = Math.max(cur, cost[u] + dp[x]); } } // Updates total cost of parent // including child nodes dp[u] = cur; // Edge is part of the cycle if (!check) { // push cost of vertex // to the answer canTake += cost[u]; } else { // Updates the largest // cost leaf vertex best = Math.max(best, dp[u]); } return check;} // Function to find the maximum cost// from source vertex such that no// two edges is traversed twicefunction FindMaxCost(g, cost, source){ // DFS call dfs(g, cost, source, -1); // Print the maximum cost document.write(canTake + best);} // Driver Codevar n = 5, m = 5;// Cost Arrayvar cost = [2, 2, 8, 6, 9];var g = Array.from(Array(n), ()=>Array()); // Given Graphg[0].push(1);g[1].push(0);g[0].push(2);g[2].push(0);g[0].push(3);g[3].push(0);g[1].push(2);g[2].push(1);g[1].push(4);g[4].push(1);// Given Source Nodevar source = 1;// Function callFindMaxCost(g, cost, source); </script>",
"e": 13958,
"s": 12046,
"text": null
},
{
"code": null,
"e": 13961,
"s": 13958,
"text": "21"
},
{
"code": null,
"e": 14137,
"s": 13963,
"text": "Time Complexity: O(N + M) where N is a number of vertices and M is the number of edges.Auxiliary Space: O(N + M) where N is a number of vertices and M is a number of edges. "
},
{
"code": null,
"e": 14148,
"s": 14137,
"text": "nidhi_biet"
},
{
"code": null,
"e": 14163,
"s": 14148,
"text": "amit143katiyar"
},
{
"code": null,
"e": 14176,
"s": 14163,
"text": "princi singh"
},
{
"code": null,
"e": 14186,
"s": 14176,
"text": "rutvik_56"
},
{
"code": null,
"e": 14195,
"s": 14186,
"text": "noob2000"
},
{
"code": null,
"e": 14222,
"s": 14195,
"text": "ashutoshsinghgeeksforgeeks"
},
{
"code": null,
"e": 14250,
"s": 14222,
"text": "Algorithms-Graph Traversals"
},
{
"code": null,
"e": 14254,
"s": 14250,
"text": "DFS"
},
{
"code": null,
"e": 14265,
"s": 14254,
"text": "Algorithms"
},
{
"code": null,
"e": 14272,
"s": 14265,
"text": "Arrays"
},
{
"code": null,
"e": 14292,
"s": 14272,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 14298,
"s": 14292,
"text": "Graph"
},
{
"code": null,
"e": 14305,
"s": 14298,
"text": "Greedy"
},
{
"code": null,
"e": 14315,
"s": 14305,
"text": "Recursion"
},
{
"code": null,
"e": 14322,
"s": 14315,
"text": "Arrays"
},
{
"code": null,
"e": 14342,
"s": 14322,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 14349,
"s": 14342,
"text": "Greedy"
},
{
"code": null,
"e": 14359,
"s": 14349,
"text": "Recursion"
},
{
"code": null,
"e": 14363,
"s": 14359,
"text": "DFS"
},
{
"code": null,
"e": 14369,
"s": 14363,
"text": "Graph"
},
{
"code": null,
"e": 14380,
"s": 14369,
"text": "Algorithms"
},
{
"code": null,
"e": 14478,
"s": 14380,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 14516,
"s": 14478,
"text": "What is Hashing | A Complete Tutorial"
},
{
"code": null,
"e": 14584,
"s": 14516,
"text": "Find if there is a path between two vertices in an undirected graph"
},
{
"code": null,
"e": 14611,
"s": 14584,
"text": "How to Start Learning DSA?"
},
{
"code": null,
"e": 14654,
"s": 14611,
"text": "Complete Roadmap To Learn DSA From Scratch"
},
{
"code": null,
"e": 14721,
"s": 14654,
"text": "Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete"
},
{
"code": null,
"e": 14736,
"s": 14721,
"text": "Arrays in Java"
},
{
"code": null,
"e": 14782,
"s": 14736,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 14850,
"s": 14782,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 14882,
"s": 14850,
"text": "Largest Sum Contiguous Subarray"
}
] |
Ruby getters and setters Method
|
11 Oct, 2019
In a Ruby class we may want to expose the instance variables (the variables that are defined prefixed by @ symbol) to other classes for encapsulation. Then, in that case, we use the getter and setter methods. these methods allow us to access a class’s instance variable from outside the class. Getter methods are used to get the value of an instance variable while the setter methods are used to set the value of an instance variable of some class.
# Ruby Program of getter methodclass CSWebsite # Constructor to initialize # the class with a name # instance variable def initialize(website) @website = website end # Classical get method def website @website endend # Creating an object of the classgfg = CSWebsite.new "www.geeksforgeeks.org"puts gfg.website
Output :
www.geeksforgeeks.org
In this example, if we don’t define the website method in the class, the puts statement used later (gfg.website) would give us an exception because the @website variable is the class’s instance variable and it should not be accessible outside the class by default.
Example 2: Simple set method
# Ruby Program of setter methodclass CSWebsite # Constructor to initialize # the class with a name # instance variable def initialize(website) @website = website end # Classical get method def website @website end # Classical set method def website=(website) @website = website endend # Creating an object of the classgfg = CSWebsite.new "www.geeksforgeeks.org"puts gfg.website # Change the instance variable from# Outside the classgfg.website="www.practice.geeksforgeeks.org"puts gfg.website
Output :
www.geeksforgeeks.org
www.practice.geeksforgeeks.org
In this example, if we don’t define the website= method in the class, then we can’t change the value of the class’s instance variable. With the help of this setter method, we reused the same object for multiple websites.
In the above examples, we can be seen that as the class grows we might have many getter and setter methods most of which follow the same format as shown above. To fix these growing lines of code, Ruby provides us with a quick way to generate the getter and setter methods without explicitly writing them as we did in the above examples. These methods are known as accessor methods. Their purpose is the same as that of a getter or setter.
There are three types of accessors in Ruby
attr_reader : This accessor generates the automatic Getter method for the given item.attr_writer : This accessor generates the automatic Setter method for the given item.attr_accessor : This accessor generates the automatic Getter & Setter method for the given item.
attr_reader : This accessor generates the automatic Getter method for the given item.
attr_writer : This accessor generates the automatic Setter method for the given item.
attr_accessor : This accessor generates the automatic Getter & Setter method for the given item.
attr_reader: accessor get methodExample 3:# Ruby Program of accessor getter methodclass CSWebsite # Constructor to initialize # the class with a name # instance variable def initialize(website) @website = website end # accessor get method attr_reader :websiteend # Creating an object of the classgfg = CSWebsite.new "www.geeksforgeeks.org"puts gfg.websiteOutput :www.geeksforgeeks.org
Here we have replaced the classical getter method with Ruby’s way to generate the getter method. The output remains the same as the attr_reader has the same function as shown in example 1.
# Ruby Program of accessor getter methodclass CSWebsite # Constructor to initialize # the class with a name # instance variable def initialize(website) @website = website end # accessor get method attr_reader :websiteend # Creating an object of the classgfg = CSWebsite.new "www.geeksforgeeks.org"puts gfg.website
Output :
www.geeksforgeeks.org
Here we have replaced the classical getter method with Ruby’s way to generate the getter method. The output remains the same as the attr_reader has the same function as shown in example 1.
attr_writer: accessor set methodExample 4:# Ruby Program of accessor getter and setter methodclass CSWebsite # Constructor to initialize # the class with a name # instance variable def initialize(website) @website = website end # accessor get method attr_reader :website # accessor set method attr_writer :websiteend # Creating an object of the classgfg = CSWebsite.new "www.geeksforgeeks.org"puts gfg.website # Change the instance variable from# Outside the classgfg.website="www.practice.geeksforgeeks.org"puts gfg.websiteOutput :www.geeksforgeeks.org
www.practice.geeksforgeeks.org
Here we have replaced the classical getter and setter method with Ruby’s way to generate them.
# Ruby Program of accessor getter and setter methodclass CSWebsite # Constructor to initialize # the class with a name # instance variable def initialize(website) @website = website end # accessor get method attr_reader :website # accessor set method attr_writer :websiteend # Creating an object of the classgfg = CSWebsite.new "www.geeksforgeeks.org"puts gfg.website # Change the instance variable from# Outside the classgfg.website="www.practice.geeksforgeeks.org"puts gfg.website
Output :
www.geeksforgeeks.org
www.practice.geeksforgeeks.org
Here we have replaced the classical getter and setter method with Ruby’s way to generate them.
attr_accessor: accessor get and set methodExample 5:# Ruby Program of accessor getter and setter methodclass CSWebsite # Constructor to initialize # the class with a name # instance variable def initialize(website) @website = website end # accessor get and set method attr_accessor :websiteend # Creating an object of the classgfg = CSWebsite.new "www.geeksforgeeks.org"puts gfg.website # Change the instance variable from# Outside the classgfg.website="www.practice.geeksforgeeks.org"puts gfg.websiteOutput :www.geeksforgeeks.org
www.practice.geeksforgeeks.org
Here both the accessors are replaced by a single attr_accessor as it functions as both a getter and a setter.
# Ruby Program of accessor getter and setter methodclass CSWebsite # Constructor to initialize # the class with a name # instance variable def initialize(website) @website = website end # accessor get and set method attr_accessor :websiteend # Creating an object of the classgfg = CSWebsite.new "www.geeksforgeeks.org"puts gfg.website # Change the instance variable from# Outside the classgfg.website="www.practice.geeksforgeeks.org"puts gfg.website
Output :
www.geeksforgeeks.org
www.practice.geeksforgeeks.org
Here both the accessors are replaced by a single attr_accessor as it functions as both a getter and a setter.
Mixed use of the accessors :A class may have many instance variables, based on which we may want to have different access permissions of those instance variables to other classes. Here, we see the mixed use of the accessors in a class.Example 6:# Ruby Program of accessor getter and setter methodclass CSWebsite # Constructor to initialize # the class with a name # instance variable def initialize(website, id) @website = website @id = id end # accessor get and set method attr_accessor :website attr_reader :idend # Creating an object of the classgfg = CSWebsite.new "www.geeksforgeeks.org", 12puts gfg.websiteputs gfg.idOutput :www.geeksforgeeks.org
12
Here the id instance variable is only given the get method using attr_reader because we don’t want some other class to change its id once it’s initialized.
# Ruby Program of accessor getter and setter methodclass CSWebsite # Constructor to initialize # the class with a name # instance variable def initialize(website, id) @website = website @id = id end # accessor get and set method attr_accessor :website attr_reader :idend # Creating an object of the classgfg = CSWebsite.new "www.geeksforgeeks.org", 12puts gfg.websiteputs gfg.id
Output :
www.geeksforgeeks.org
12
Here the id instance variable is only given the get method using attr_reader because we don’t want some other class to change its id once it’s initialized.
Picked
Ruby-Methods
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Make a Custom Array of Hashes in Ruby?
Global Variable in Ruby
Ruby | Enumerator each_with_index function
Ruby | Case Statement
Ruby | Array select() function
Ruby | unless Statement and unless Modifier
Ruby | Data Types
Ruby | Hash delete() function
Ruby For Beginners
Ruby | Array class find_index() operation
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n11 Oct, 2019"
},
{
"code": null,
"e": 503,
"s": 54,
"text": "In a Ruby class we may want to expose the instance variables (the variables that are defined prefixed by @ symbol) to other classes for encapsulation. Then, in that case, we use the getter and setter methods. these methods allow us to access a class’s instance variable from outside the class. Getter methods are used to get the value of an instance variable while the setter methods are used to set the value of an instance variable of some class."
},
{
"code": "# Ruby Program of getter methodclass CSWebsite # Constructor to initialize # the class with a name # instance variable def initialize(website) @website = website end # Classical get method def website @website endend # Creating an object of the classgfg = CSWebsite.new \"www.geeksforgeeks.org\"puts gfg.website",
"e": 832,
"s": 503,
"text": null
},
{
"code": null,
"e": 841,
"s": 832,
"text": "Output :"
},
{
"code": null,
"e": 864,
"s": 841,
"text": "www.geeksforgeeks.org\n"
},
{
"code": null,
"e": 1129,
"s": 864,
"text": "In this example, if we don’t define the website method in the class, the puts statement used later (gfg.website) would give us an exception because the @website variable is the class’s instance variable and it should not be accessible outside the class by default."
},
{
"code": null,
"e": 1158,
"s": 1129,
"text": "Example 2: Simple set method"
},
{
"code": "# Ruby Program of setter methodclass CSWebsite # Constructor to initialize # the class with a name # instance variable def initialize(website) @website = website end # Classical get method def website @website end # Classical set method def website=(website) @website = website endend # Creating an object of the classgfg = CSWebsite.new \"www.geeksforgeeks.org\"puts gfg.website # Change the instance variable from# Outside the classgfg.website=\"www.practice.geeksforgeeks.org\"puts gfg.website",
"e": 1679,
"s": 1158,
"text": null
},
{
"code": null,
"e": 1688,
"s": 1679,
"text": "Output :"
},
{
"code": null,
"e": 1742,
"s": 1688,
"text": "www.geeksforgeeks.org\nwww.practice.geeksforgeeks.org\n"
},
{
"code": null,
"e": 1963,
"s": 1742,
"text": "In this example, if we don’t define the website= method in the class, then we can’t change the value of the class’s instance variable. With the help of this setter method, we reused the same object for multiple websites."
},
{
"code": null,
"e": 2402,
"s": 1963,
"text": "In the above examples, we can be seen that as the class grows we might have many getter and setter methods most of which follow the same format as shown above. To fix these growing lines of code, Ruby provides us with a quick way to generate the getter and setter methods without explicitly writing them as we did in the above examples. These methods are known as accessor methods. Their purpose is the same as that of a getter or setter."
},
{
"code": null,
"e": 2445,
"s": 2402,
"text": "There are three types of accessors in Ruby"
},
{
"code": null,
"e": 2712,
"s": 2445,
"text": "attr_reader : This accessor generates the automatic Getter method for the given item.attr_writer : This accessor generates the automatic Setter method for the given item.attr_accessor : This accessor generates the automatic Getter & Setter method for the given item."
},
{
"code": null,
"e": 2798,
"s": 2712,
"text": "attr_reader : This accessor generates the automatic Getter method for the given item."
},
{
"code": null,
"e": 2884,
"s": 2798,
"text": "attr_writer : This accessor generates the automatic Setter method for the given item."
},
{
"code": null,
"e": 2981,
"s": 2884,
"text": "attr_accessor : This accessor generates the automatic Getter & Setter method for the given item."
},
{
"code": null,
"e": 3570,
"s": 2981,
"text": "attr_reader: accessor get methodExample 3:# Ruby Program of accessor getter methodclass CSWebsite # Constructor to initialize # the class with a name # instance variable def initialize(website) @website = website end # accessor get method attr_reader :websiteend # Creating an object of the classgfg = CSWebsite.new \"www.geeksforgeeks.org\"puts gfg.websiteOutput :www.geeksforgeeks.org\nHere we have replaced the classical getter method with Ruby’s way to generate the getter method. The output remains the same as the attr_reader has the same function as shown in example 1."
},
{
"code": "# Ruby Program of accessor getter methodclass CSWebsite # Constructor to initialize # the class with a name # instance variable def initialize(website) @website = website end # accessor get method attr_reader :websiteend # Creating an object of the classgfg = CSWebsite.new \"www.geeksforgeeks.org\"puts gfg.website",
"e": 3899,
"s": 3570,
"text": null
},
{
"code": null,
"e": 3908,
"s": 3899,
"text": "Output :"
},
{
"code": null,
"e": 3931,
"s": 3908,
"text": "www.geeksforgeeks.org\n"
},
{
"code": null,
"e": 4120,
"s": 3931,
"text": "Here we have replaced the classical getter method with Ruby’s way to generate the getter method. The output remains the same as the attr_reader has the same function as shown in example 1."
},
{
"code": null,
"e": 4820,
"s": 4120,
"text": "attr_writer: accessor set methodExample 4:# Ruby Program of accessor getter and setter methodclass CSWebsite # Constructor to initialize # the class with a name # instance variable def initialize(website) @website = website end # accessor get method attr_reader :website # accessor set method attr_writer :websiteend # Creating an object of the classgfg = CSWebsite.new \"www.geeksforgeeks.org\"puts gfg.website # Change the instance variable from# Outside the classgfg.website=\"www.practice.geeksforgeeks.org\"puts gfg.websiteOutput :www.geeksforgeeks.org\nwww.practice.geeksforgeeks.org\nHere we have replaced the classical getter and setter method with Ruby’s way to generate them."
},
{
"code": "# Ruby Program of accessor getter and setter methodclass CSWebsite # Constructor to initialize # the class with a name # instance variable def initialize(website) @website = website end # accessor get method attr_reader :website # accessor set method attr_writer :websiteend # Creating an object of the classgfg = CSWebsite.new \"www.geeksforgeeks.org\"puts gfg.website # Change the instance variable from# Outside the classgfg.website=\"www.practice.geeksforgeeks.org\"puts gfg.website",
"e": 5323,
"s": 4820,
"text": null
},
{
"code": null,
"e": 5332,
"s": 5323,
"text": "Output :"
},
{
"code": null,
"e": 5386,
"s": 5332,
"text": "www.geeksforgeeks.org\nwww.practice.geeksforgeeks.org\n"
},
{
"code": null,
"e": 5481,
"s": 5386,
"text": "Here we have replaced the classical getter and setter method with Ruby’s way to generate them."
},
{
"code": null,
"e": 6169,
"s": 5481,
"text": "attr_accessor: accessor get and set methodExample 5:# Ruby Program of accessor getter and setter methodclass CSWebsite # Constructor to initialize # the class with a name # instance variable def initialize(website) @website = website end # accessor get and set method attr_accessor :websiteend # Creating an object of the classgfg = CSWebsite.new \"www.geeksforgeeks.org\"puts gfg.website # Change the instance variable from# Outside the classgfg.website=\"www.practice.geeksforgeeks.org\"puts gfg.websiteOutput :www.geeksforgeeks.org\nwww.practice.geeksforgeeks.org\nHere both the accessors are replaced by a single attr_accessor as it functions as both a getter and a setter."
},
{
"code": "# Ruby Program of accessor getter and setter methodclass CSWebsite # Constructor to initialize # the class with a name # instance variable def initialize(website) @website = website end # accessor get and set method attr_accessor :websiteend # Creating an object of the classgfg = CSWebsite.new \"www.geeksforgeeks.org\"puts gfg.website # Change the instance variable from# Outside the classgfg.website=\"www.practice.geeksforgeeks.org\"puts gfg.website",
"e": 6635,
"s": 6169,
"text": null
},
{
"code": null,
"e": 6644,
"s": 6635,
"text": "Output :"
},
{
"code": null,
"e": 6698,
"s": 6644,
"text": "www.geeksforgeeks.org\nwww.practice.geeksforgeeks.org\n"
},
{
"code": null,
"e": 6808,
"s": 6698,
"text": "Here both the accessors are replaced by a single attr_accessor as it functions as both a getter and a setter."
},
{
"code": null,
"e": 7639,
"s": 6808,
"text": "Mixed use of the accessors :A class may have many instance variables, based on which we may want to have different access permissions of those instance variables to other classes. Here, we see the mixed use of the accessors in a class.Example 6:# Ruby Program of accessor getter and setter methodclass CSWebsite # Constructor to initialize # the class with a name # instance variable def initialize(website, id) @website = website @id = id end # accessor get and set method attr_accessor :website attr_reader :idend # Creating an object of the classgfg = CSWebsite.new \"www.geeksforgeeks.org\", 12puts gfg.websiteputs gfg.idOutput :www.geeksforgeeks.org\n12\nHere the id instance variable is only given the get method using attr_reader because we don’t want some other class to change its id once it’s initialized."
},
{
"code": "# Ruby Program of accessor getter and setter methodclass CSWebsite # Constructor to initialize # the class with a name # instance variable def initialize(website, id) @website = website @id = id end # accessor get and set method attr_accessor :website attr_reader :idend # Creating an object of the classgfg = CSWebsite.new \"www.geeksforgeeks.org\", 12puts gfg.websiteputs gfg.id",
"e": 8037,
"s": 7639,
"text": null
},
{
"code": null,
"e": 8046,
"s": 8037,
"text": "Output :"
},
{
"code": null,
"e": 8072,
"s": 8046,
"text": "www.geeksforgeeks.org\n12\n"
},
{
"code": null,
"e": 8228,
"s": 8072,
"text": "Here the id instance variable is only given the get method using attr_reader because we don’t want some other class to change its id once it’s initialized."
},
{
"code": null,
"e": 8235,
"s": 8228,
"text": "Picked"
},
{
"code": null,
"e": 8248,
"s": 8235,
"text": "Ruby-Methods"
},
{
"code": null,
"e": 8253,
"s": 8248,
"text": "Ruby"
},
{
"code": null,
"e": 8351,
"s": 8253,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8397,
"s": 8351,
"text": "How to Make a Custom Array of Hashes in Ruby?"
},
{
"code": null,
"e": 8421,
"s": 8397,
"text": "Global Variable in Ruby"
},
{
"code": null,
"e": 8464,
"s": 8421,
"text": "Ruby | Enumerator each_with_index function"
},
{
"code": null,
"e": 8486,
"s": 8464,
"text": "Ruby | Case Statement"
},
{
"code": null,
"e": 8517,
"s": 8486,
"text": "Ruby | Array select() function"
},
{
"code": null,
"e": 8561,
"s": 8517,
"text": "Ruby | unless Statement and unless Modifier"
},
{
"code": null,
"e": 8579,
"s": 8561,
"text": "Ruby | Data Types"
},
{
"code": null,
"e": 8609,
"s": 8579,
"text": "Ruby | Hash delete() function"
},
{
"code": null,
"e": 8628,
"s": 8609,
"text": "Ruby For Beginners"
}
] |
Check if a number starts with another number or not
|
23 Jun, 2022
Given two numbers A and B where (A > B), the task is to check if B is a prefix of A or not. Print “Yes” if it is a prefix Else print “No”.
Examples:
Input: A = 12345, B = 12 Output: Yes
Input: A = 12345, B = 345 Output: No
Approach:
Convert the given numbers A and B to strings str1 and str2 respectively.Traverse both the strings from the start of the strings.While traversing the strings, if at any index characters from str1 and str2 are unequal then print “No”.Else print “Yes”.
Convert the given numbers A and B to strings str1 and str2 respectively.
Traverse both the strings from the start of the strings.
While traversing the strings, if at any index characters from str1 and str2 are unequal then print “No”.
Else print “Yes”.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include "bits/stdc++.h"using namespace std; // Function to check if B is a// prefix of A or notbool checkprefix(int A, int B){ // Convert numbers into strings string s1 = to_string(A); string s2 = to_string(B); // Find the lengths of strings // s1 and s2 int n1 = s1.length(); int n2 = s2.length(); // Base Case if (n1 < n2) { return false; } // Traverse the strings s1 & s2 for (int i = 0; i < n2; i++) { // If at any index characters // are unequals then return false if (s1[i] != s2[i]) { return false; } } // Return true return true;} // Driver Codeint main(){ // Given numbers int A = 12345, B = 12; // Function Call bool result = checkprefix(A, B); // If B is a prefix of A, then // print "Yes" if (result) { cout << "Yes"; } else { cout << "No"; } return 0;}
// Java program for the above approachclass GFG{ // Function to check if B is a// prefix of A or notstatic boolean checkprefix(int A, int B){ // Convert numbers into Strings String s1 = String.valueOf(A); String s2 = String.valueOf(B); // Find the lengths of Strings // s1 and s2 int n1 = s1.length(); int n2 = s2.length(); // Base Case if (n1 < n2) { return false; } // Traverse the Strings s1 & s2 for(int i = 0; i < n2; i++) { // If at any index characters // are unequals then return false if (s1.charAt(i) != s2.charAt(1)) { return false; } } // Return true return true;} // Driver Codepublic static void main(String[] args){ // Given numbers int A = 12345, B = 12; // Function call boolean result = checkprefix(A, B); // If B is a prefix of A, then // print "Yes" if (!result) { System.out.print("Yes"); } else { System.out.print("No"); }}} // This code is contributed by amal kumar choubey
# Python3 program for the# above approach # Function to check if B is# a prefix of A or notdef checkprefix(A, B): # Convert numbers into strings s1 = str(A) s2 = str(B) # Find the length of s1 and s2 n1 = len(s1) n2 = len(s2) # Base case if n1 < n2: return False # Traverse the string s1 and s2 for i in range(0, n2): # If at any index characters # are unequal then return False if s1[i] != s2[i]: return False return True # Driver codeif __name__=='__main__': # Given numbers A = 12345 B = 12 # Function call result = checkprefix(A, B) # If B is a prefix of A , # then print Yes if result: print("Yes") else: print("No") # This code is contributed by virusbuddah_
// C# program for the above approachusing System; class GFG{ // Function to check if B is a// prefix of A or notstatic bool checkprefix(int A, int B){ // Convert numbers into Strings String s1 = A.ToString(); String s2 = B.ToString(); // Find the lengths of Strings // s1 and s2 int n1 = s1.Length; int n2 = s2.Length; // Base Case if (n1 < n2) { return false; } // Traverse the Strings s1 & s2 for(int i = 0; i < n2; i++) { // If at any index characters // are unequals then return false if (s1[i] != s2[i]) { return false; } } // Return true return true;} // Driver Codestatic public void Main (){ // Given numbers int A = 12345, B = 12; // Function call bool result = checkprefix(A, B); // If B is a prefix of A, then // print "Yes" if (result) { Console.Write("Yes"); } else { Console.Write("No"); }}} // This code is contributed by shubhamsingh10
<script> // javascript program for the above approach // Function to check if B is a// prefix of A or not function checkprefix( A, B){ // Convert numbers into Strings var s1 = A.toString(); var s2 = B.toString(); // Find the lengths of Strings // s1 and s2 var n1 = s1.length; var n2 = s2.length; // Base Case if (n1 < n2) { return false; } // Traverse the Strings s1 & s2 for(var i = 0; i < n2; i++) { // If at any index characters // are unequals then return false if (s1[i] != s2[i]) { return false; } } // Return true return true;} // Driver Code // Given numbers var A = 12345, B = 12; // Function call var result = checkprefix(A, B); // If B is a prefix of A, then // print "Yes" if (result) { document.write("Yes"); } else { document.write("No"); } </script>
Yes
Time Complexity: O(n2), where n2 is the size of string s2Auxiliary Space: O(1), as no extra space is required
Using in-built function: Using inbuilt function std::boost::algorithm::starts_with(), it can be checked whether any string contains prefix of another string or not.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>#include <boost/algorithm/string.hpp>using namespace std; // Function to check if B is a// prefix of A or notvoid checkprefix(int A, int B){ // Convert numbers into strings string s1 = to_string(A); string s2 = to_string(B); bool result; // Check if s2 is a prefix of s1 // or not using starts_with() function result = boost::algorithm::starts_with(s1, s2); // If result is true, print "Yes" if (result) { cout << "Yes"; } else { cout << "No"; }} // Driver Codeint main(){ // Given numbers int A = 12345, B = 12; // Function Call checkprefix(A, B); return 0;}
// Java program for the above approachclass GFG{ // Function to check if B is a// prefix of A or notstatic void checkprefix(int A, int B){ // Convert numbers into Strings String s1 = String.valueOf(A); String s2 = String.valueOf(B); boolean result; // Check if s2 is a prefix of s1 // or not using starts_with() function result = s1.startsWith(s2); // If result is true, print "Yes" if (result) { System.out.print("Yes"); } else { System.out.print("No"); }} // Driver Codepublic static void main(String[] args){ // Given numbers int A = 12345, B = 12; // Function call checkprefix(A, B);}} // This code is contributed by amal kumar choubey
# Python3 program for the# above approach # Function to check if B is# a prefix of A or notdef checkprefix(A, B): # Convert numbers into strings s1 = str(A) s2 = str(B) # Check if s2 is a prefix of s1 # or not using startswith() function result = s1.startswith(s2) # If result is true print Yes if result: print("Yes") else: print("No") # Driver codeif __name__=='__main__': # Given numbers A = 12345 B = 12 # Function call checkprefix(A, B) # This code is contributed by virusbuddah_
// C# program for the above approachusing System.Threading;using System.Globalization;using System; class GFG{ // Function to check if B is a// prefix of A or notstatic void checkprefix(int A, int B){ // Convert numbers into Strings string s1 = A.ToString(); string s2 = B.ToString(); bool result; // Check if s2 is a prefix of s1 // or not using starts_with() function result = s1.StartsWith(s2, false, CultureInfo.InvariantCulture); // If result is true, print "Yes" if (result) { Console.Write("Yes"); } else { Console.Write("No"); }} // Driver codestatic void Main(){ // Given numbers int A = 12345, B = 12; // Function call checkprefix(A, B);}} // This code is contributed by divyeshrabadiya07
<script> // JavaScript program for the above approach // Function to check if B is a // prefix of A or not function checkprefix(A, B) { // Convert numbers into Strings var s1 = A.toString(); var s2 = B.toString(); var result; // Check if s2 is a prefix of s1 // or not using starts_with() function result = s1.startsWith(s2); // If result is true, print "Yes" if (result) { document.write("Yes"); } else { document.write("No"); } } // Driver code // Given numbers var A = 12345, B = 12; // Function call checkprefix(A, B); </script>
Yes
Time Complexity: O(1)Auxiliary Space: O(1)
virusbuddha
Amal Kumar Choubey
SHUBHAMSINGH10
divyeshrabadiya07
bunnyram19
arorakashish0911
rdtank
singhh3010
cpp-boost
prefix
Mathematical
Pattern Searching
Strings
Strings
Mathematical
Pattern Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Operators in C / C++
Prime Numbers
Find minimum number of coins that make a given value
Algorithm to solve Rubik's Cube
KMP Algorithm for Pattern Searching
Rabin-Karp Algorithm for Pattern Searching
Check if a string is substring of another
Check if an URL is valid or not using Regular Expression
Boyer Moore Algorithm for Pattern Searching
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 Jun, 2022"
},
{
"code": null,
"e": 167,
"s": 28,
"text": "Given two numbers A and B where (A > B), the task is to check if B is a prefix of A or not. Print “Yes” if it is a prefix Else print “No”."
},
{
"code": null,
"e": 178,
"s": 167,
"text": "Examples: "
},
{
"code": null,
"e": 215,
"s": 178,
"text": "Input: A = 12345, B = 12 Output: Yes"
},
{
"code": null,
"e": 253,
"s": 215,
"text": "Input: A = 12345, B = 345 Output: No "
},
{
"code": null,
"e": 264,
"s": 253,
"text": "Approach: "
},
{
"code": null,
"e": 514,
"s": 264,
"text": "Convert the given numbers A and B to strings str1 and str2 respectively.Traverse both the strings from the start of the strings.While traversing the strings, if at any index characters from str1 and str2 are unequal then print “No”.Else print “Yes”."
},
{
"code": null,
"e": 587,
"s": 514,
"text": "Convert the given numbers A and B to strings str1 and str2 respectively."
},
{
"code": null,
"e": 644,
"s": 587,
"text": "Traverse both the strings from the start of the strings."
},
{
"code": null,
"e": 749,
"s": 644,
"text": "While traversing the strings, if at any index characters from str1 and str2 are unequal then print “No”."
},
{
"code": null,
"e": 767,
"s": 749,
"text": "Else print “Yes”."
},
{
"code": null,
"e": 819,
"s": 767,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 823,
"s": 819,
"text": "C++"
},
{
"code": null,
"e": 828,
"s": 823,
"text": "Java"
},
{
"code": null,
"e": 836,
"s": 828,
"text": "Python3"
},
{
"code": null,
"e": 839,
"s": 836,
"text": "C#"
},
{
"code": null,
"e": 850,
"s": 839,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include \"bits/stdc++.h\"using namespace std; // Function to check if B is a// prefix of A or notbool checkprefix(int A, int B){ // Convert numbers into strings string s1 = to_string(A); string s2 = to_string(B); // Find the lengths of strings // s1 and s2 int n1 = s1.length(); int n2 = s2.length(); // Base Case if (n1 < n2) { return false; } // Traverse the strings s1 & s2 for (int i = 0; i < n2; i++) { // If at any index characters // are unequals then return false if (s1[i] != s2[i]) { return false; } } // Return true return true;} // Driver Codeint main(){ // Given numbers int A = 12345, B = 12; // Function Call bool result = checkprefix(A, B); // If B is a prefix of A, then // print \"Yes\" if (result) { cout << \"Yes\"; } else { cout << \"No\"; } return 0;}",
"e": 1811,
"s": 850,
"text": null
},
{
"code": "// Java program for the above approachclass GFG{ // Function to check if B is a// prefix of A or notstatic boolean checkprefix(int A, int B){ // Convert numbers into Strings String s1 = String.valueOf(A); String s2 = String.valueOf(B); // Find the lengths of Strings // s1 and s2 int n1 = s1.length(); int n2 = s2.length(); // Base Case if (n1 < n2) { return false; } // Traverse the Strings s1 & s2 for(int i = 0; i < n2; i++) { // If at any index characters // are unequals then return false if (s1.charAt(i) != s2.charAt(1)) { return false; } } // Return true return true;} // Driver Codepublic static void main(String[] args){ // Given numbers int A = 12345, B = 12; // Function call boolean result = checkprefix(A, B); // If B is a prefix of A, then // print \"Yes\" if (!result) { System.out.print(\"Yes\"); } else { System.out.print(\"No\"); }}} // This code is contributed by amal kumar choubey",
"e": 2887,
"s": 1811,
"text": null
},
{
"code": "# Python3 program for the# above approach # Function to check if B is# a prefix of A or notdef checkprefix(A, B): # Convert numbers into strings s1 = str(A) s2 = str(B) # Find the length of s1 and s2 n1 = len(s1) n2 = len(s2) # Base case if n1 < n2: return False # Traverse the string s1 and s2 for i in range(0, n2): # If at any index characters # are unequal then return False if s1[i] != s2[i]: return False return True # Driver codeif __name__=='__main__': # Given numbers A = 12345 B = 12 # Function call result = checkprefix(A, B) # If B is a prefix of A , # then print Yes if result: print(\"Yes\") else: print(\"No\") # This code is contributed by virusbuddah_",
"e": 3734,
"s": 2887,
"text": null
},
{
"code": "// C# program for the above approachusing System; class GFG{ // Function to check if B is a// prefix of A or notstatic bool checkprefix(int A, int B){ // Convert numbers into Strings String s1 = A.ToString(); String s2 = B.ToString(); // Find the lengths of Strings // s1 and s2 int n1 = s1.Length; int n2 = s2.Length; // Base Case if (n1 < n2) { return false; } // Traverse the Strings s1 & s2 for(int i = 0; i < n2; i++) { // If at any index characters // are unequals then return false if (s1[i] != s2[i]) { return false; } } // Return true return true;} // Driver Codestatic public void Main (){ // Given numbers int A = 12345, B = 12; // Function call bool result = checkprefix(A, B); // If B is a prefix of A, then // print \"Yes\" if (result) { Console.Write(\"Yes\"); } else { Console.Write(\"No\"); }}} // This code is contributed by shubhamsingh10",
"e": 4757,
"s": 3734,
"text": null
},
{
"code": "<script> // javascript program for the above approach // Function to check if B is a// prefix of A or not function checkprefix( A, B){ // Convert numbers into Strings var s1 = A.toString(); var s2 = B.toString(); // Find the lengths of Strings // s1 and s2 var n1 = s1.length; var n2 = s2.length; // Base Case if (n1 < n2) { return false; } // Traverse the Strings s1 & s2 for(var i = 0; i < n2; i++) { // If at any index characters // are unequals then return false if (s1[i] != s2[i]) { return false; } } // Return true return true;} // Driver Code // Given numbers var A = 12345, B = 12; // Function call var result = checkprefix(A, B); // If B is a prefix of A, then // print \"Yes\" if (result) { document.write(\"Yes\"); } else { document.write(\"No\"); } </script> ",
"e": 5729,
"s": 4757,
"text": null
},
{
"code": null,
"e": 5733,
"s": 5729,
"text": "Yes"
},
{
"code": null,
"e": 5843,
"s": 5733,
"text": "Time Complexity: O(n2), where n2 is the size of string s2Auxiliary Space: O(1), as no extra space is required"
},
{
"code": null,
"e": 6008,
"s": 5843,
"text": "Using in-built function: Using inbuilt function std::boost::algorithm::starts_with(), it can be checked whether any string contains prefix of another string or not."
},
{
"code": null,
"e": 6059,
"s": 6008,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 6063,
"s": 6059,
"text": "C++"
},
{
"code": null,
"e": 6068,
"s": 6063,
"text": "Java"
},
{
"code": null,
"e": 6076,
"s": 6068,
"text": "Python3"
},
{
"code": null,
"e": 6079,
"s": 6076,
"text": "C#"
},
{
"code": null,
"e": 6090,
"s": 6079,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>#include <boost/algorithm/string.hpp>using namespace std; // Function to check if B is a// prefix of A or notvoid checkprefix(int A, int B){ // Convert numbers into strings string s1 = to_string(A); string s2 = to_string(B); bool result; // Check if s2 is a prefix of s1 // or not using starts_with() function result = boost::algorithm::starts_with(s1, s2); // If result is true, print \"Yes\" if (result) { cout << \"Yes\"; } else { cout << \"No\"; }} // Driver Codeint main(){ // Given numbers int A = 12345, B = 12; // Function Call checkprefix(A, B); return 0;}",
"e": 6781,
"s": 6090,
"text": null
},
{
"code": "// Java program for the above approachclass GFG{ // Function to check if B is a// prefix of A or notstatic void checkprefix(int A, int B){ // Convert numbers into Strings String s1 = String.valueOf(A); String s2 = String.valueOf(B); boolean result; // Check if s2 is a prefix of s1 // or not using starts_with() function result = s1.startsWith(s2); // If result is true, print \"Yes\" if (result) { System.out.print(\"Yes\"); } else { System.out.print(\"No\"); }} // Driver Codepublic static void main(String[] args){ // Given numbers int A = 12345, B = 12; // Function call checkprefix(A, B);}} // This code is contributed by amal kumar choubey",
"e": 7499,
"s": 6781,
"text": null
},
{
"code": "# Python3 program for the# above approach # Function to check if B is# a prefix of A or notdef checkprefix(A, B): # Convert numbers into strings s1 = str(A) s2 = str(B) # Check if s2 is a prefix of s1 # or not using startswith() function result = s1.startswith(s2) # If result is true print Yes if result: print(\"Yes\") else: print(\"No\") # Driver codeif __name__=='__main__': # Given numbers A = 12345 B = 12 # Function call checkprefix(A, B) # This code is contributed by virusbuddah_",
"e": 8069,
"s": 7499,
"text": null
},
{
"code": "// C# program for the above approachusing System.Threading;using System.Globalization;using System; class GFG{ // Function to check if B is a// prefix of A or notstatic void checkprefix(int A, int B){ // Convert numbers into Strings string s1 = A.ToString(); string s2 = B.ToString(); bool result; // Check if s2 is a prefix of s1 // or not using starts_with() function result = s1.StartsWith(s2, false, CultureInfo.InvariantCulture); // If result is true, print \"Yes\" if (result) { Console.Write(\"Yes\"); } else { Console.Write(\"No\"); }} // Driver codestatic void Main(){ // Given numbers int A = 12345, B = 12; // Function call checkprefix(A, B);}} // This code is contributed by divyeshrabadiya07",
"e": 8861,
"s": 8069,
"text": null
},
{
"code": "<script> // JavaScript program for the above approach // Function to check if B is a // prefix of A or not function checkprefix(A, B) { // Convert numbers into Strings var s1 = A.toString(); var s2 = B.toString(); var result; // Check if s2 is a prefix of s1 // or not using starts_with() function result = s1.startsWith(s2); // If result is true, print \"Yes\" if (result) { document.write(\"Yes\"); } else { document.write(\"No\"); } } // Driver code // Given numbers var A = 12345, B = 12; // Function call checkprefix(A, B); </script>",
"e": 9559,
"s": 8861,
"text": null
},
{
"code": null,
"e": 9563,
"s": 9559,
"text": "Yes"
},
{
"code": null,
"e": 9606,
"s": 9563,
"text": "Time Complexity: O(1)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 9618,
"s": 9606,
"text": "virusbuddha"
},
{
"code": null,
"e": 9637,
"s": 9618,
"text": "Amal Kumar Choubey"
},
{
"code": null,
"e": 9652,
"s": 9637,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 9670,
"s": 9652,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 9681,
"s": 9670,
"text": "bunnyram19"
},
{
"code": null,
"e": 9698,
"s": 9681,
"text": "arorakashish0911"
},
{
"code": null,
"e": 9705,
"s": 9698,
"text": "rdtank"
},
{
"code": null,
"e": 9716,
"s": 9705,
"text": "singhh3010"
},
{
"code": null,
"e": 9726,
"s": 9716,
"text": "cpp-boost"
},
{
"code": null,
"e": 9733,
"s": 9726,
"text": "prefix"
},
{
"code": null,
"e": 9746,
"s": 9733,
"text": "Mathematical"
},
{
"code": null,
"e": 9764,
"s": 9746,
"text": "Pattern Searching"
},
{
"code": null,
"e": 9772,
"s": 9764,
"text": "Strings"
},
{
"code": null,
"e": 9780,
"s": 9772,
"text": "Strings"
},
{
"code": null,
"e": 9793,
"s": 9780,
"text": "Mathematical"
},
{
"code": null,
"e": 9811,
"s": 9793,
"text": "Pattern Searching"
},
{
"code": null,
"e": 9909,
"s": 9811,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 9933,
"s": 9909,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 9954,
"s": 9933,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 9968,
"s": 9954,
"text": "Prime Numbers"
},
{
"code": null,
"e": 10021,
"s": 9968,
"text": "Find minimum number of coins that make a given value"
},
{
"code": null,
"e": 10053,
"s": 10021,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 10089,
"s": 10053,
"text": "KMP Algorithm for Pattern Searching"
},
{
"code": null,
"e": 10132,
"s": 10089,
"text": "Rabin-Karp Algorithm for Pattern Searching"
},
{
"code": null,
"e": 10174,
"s": 10132,
"text": "Check if a string is substring of another"
},
{
"code": null,
"e": 10231,
"s": 10174,
"text": "Check if an URL is valid or not using Regular Expression"
}
] |
How to Convert Strings to Floats in Pandas DataFrame?
|
28 Jul, 2020
In this article, we’ll look at different ways in which we can convert a string to a float in a pandas dataframe. Now, let’s create a Dataframe with ‘Year’ and ‘Inflation Rate’ as a column.
Python3
# importing pandas libraryimport pandas as pd # dictionaryData = {'Year': ['2016', '2017', '2018', '2019'], 'Inflation Rate': ['4.47', '5', '5.98', '4.1']}# create a dataframedf = pd.DataFrame(Data) # show the dataframeprint (df) # show the datatypesprint(df.dtypes)
Output:
Method 1: Using DataFrame.astype().
The method is used to cast a pandas object to a specified dtype.
Syntax: DataFrame.astype(self: ~ FrameOrSeries, dtype, copy: bool = True, errors: str = ‘raise’)
Returns: casted: type of caller
Example: In this example, we’ll convert each value of ‘Inflation Rate’ column to float.
Python3
# importing pandas libraryimport pandas as pd # dictionaryData = {'Year': ['2016', '2017', '2018', '2019'], 'Inflation Rate': ['4.47', '5', '5.98', '4.1']}# create a dataframedf = pd.DataFrame(Data) # converting each value # of column to a stringdf['Inflation Rate'] = df['Inflation Rate'].astype(float) # show the dataframeprint(df) # show the datatypesprint (df.dtypes)
Output:
Method 2: Using pandas.to_numeric() function.
The function is used to convert the argument to a numeric type.
Syntax: pandas.to_numeric(arg, errors=’raise’, downcast=None)
Returns: numeric if parsing succeeded. Note that the return type depends on the input. Series if Series, otherwise ndarray.
Example 1: In this example, we’ll convert each value of ‘Inflation Rate’ column to float.
Code:
Python3
# importing pandas libraryimport pandas as pd # creating a dictionaryData = {'Year': ['2016', '2017', '2018', '2019'], 'Inflation Rate': ['4.47', '5', '5.98', '4.1']}# create a dataframedf = pd.DataFrame(Data) # converting each value of column to a stringdf['Inflation Rate'] = pd.to_numeric(df['Inflation Rate']) # show the dataframeprint(df) # show the data typesprint (df.dtypes)
Output:
Example 2: Sometimes, we may not have a float value represented as a string. So, pd.to_numeric() function will show an error. To remove this error, we can use errors=’coerce’, to convert the value at this position to be converted to NaN.
Code:
Python3
# importing pandas as pdimport pandas as pd # dictionaryData = {'Year': ['2016', '2017', '2018', '2019'], 'Inflation Rate': ['4.47', '5', 'No data', '4.1']} # create a dataframedf = pd.DataFrame(Data) # converting each value of column to a stringdf['Inflation Rate'] = pd.to_numeric(df['Inflation Rate'], errors = 'coerce') # show the dataframeprint(df) # show the data typesprint (df.dtypes)
Output:
Note: String data type shows as an object.
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Jul, 2020"
},
{
"code": null,
"e": 217,
"s": 28,
"text": "In this article, we’ll look at different ways in which we can convert a string to a float in a pandas dataframe. Now, let’s create a Dataframe with ‘Year’ and ‘Inflation Rate’ as a column."
},
{
"code": null,
"e": 225,
"s": 217,
"text": "Python3"
},
{
"code": "# importing pandas libraryimport pandas as pd # dictionaryData = {'Year': ['2016', '2017', '2018', '2019'], 'Inflation Rate': ['4.47', '5', '5.98', '4.1']}# create a dataframedf = pd.DataFrame(Data) # show the dataframeprint (df) # show the datatypesprint(df.dtypes)",
"e": 546,
"s": 225,
"text": null
},
{
"code": null,
"e": 554,
"s": 546,
"text": "Output:"
},
{
"code": null,
"e": 590,
"s": 554,
"text": "Method 1: Using DataFrame.astype()."
},
{
"code": null,
"e": 656,
"s": 590,
"text": "The method is used to cast a pandas object to a specified dtype. "
},
{
"code": null,
"e": 754,
"s": 656,
"text": "Syntax: DataFrame.astype(self: ~ FrameOrSeries, dtype, copy: bool = True, errors: str = ‘raise’) "
},
{
"code": null,
"e": 786,
"s": 754,
"text": "Returns: casted: type of caller"
},
{
"code": null,
"e": 874,
"s": 786,
"text": "Example: In this example, we’ll convert each value of ‘Inflation Rate’ column to float."
},
{
"code": null,
"e": 882,
"s": 874,
"text": "Python3"
},
{
"code": "# importing pandas libraryimport pandas as pd # dictionaryData = {'Year': ['2016', '2017', '2018', '2019'], 'Inflation Rate': ['4.47', '5', '5.98', '4.1']}# create a dataframedf = pd.DataFrame(Data) # converting each value # of column to a stringdf['Inflation Rate'] = df['Inflation Rate'].astype(float) # show the dataframeprint(df) # show the datatypesprint (df.dtypes)",
"e": 1309,
"s": 882,
"text": null
},
{
"code": null,
"e": 1317,
"s": 1309,
"text": "Output:"
},
{
"code": null,
"e": 1363,
"s": 1317,
"text": "Method 2: Using pandas.to_numeric() function."
},
{
"code": null,
"e": 1428,
"s": 1363,
"text": "The function is used to convert the argument to a numeric type. "
},
{
"code": null,
"e": 1491,
"s": 1428,
"text": "Syntax: pandas.to_numeric(arg, errors=’raise’, downcast=None) "
},
{
"code": null,
"e": 1616,
"s": 1491,
"text": "Returns: numeric if parsing succeeded. Note that the return type depends on the input. Series if Series, otherwise ndarray. "
},
{
"code": null,
"e": 1706,
"s": 1616,
"text": "Example 1: In this example, we’ll convert each value of ‘Inflation Rate’ column to float."
},
{
"code": null,
"e": 1712,
"s": 1706,
"text": "Code:"
},
{
"code": null,
"e": 1720,
"s": 1712,
"text": "Python3"
},
{
"code": "# importing pandas libraryimport pandas as pd # creating a dictionaryData = {'Year': ['2016', '2017', '2018', '2019'], 'Inflation Rate': ['4.47', '5', '5.98', '4.1']}# create a dataframedf = pd.DataFrame(Data) # converting each value of column to a stringdf['Inflation Rate'] = pd.to_numeric(df['Inflation Rate']) # show the dataframeprint(df) # show the data typesprint (df.dtypes)",
"e": 2162,
"s": 1720,
"text": null
},
{
"code": null,
"e": 2171,
"s": 2162,
"text": "Output: "
},
{
"code": null,
"e": 2410,
"s": 2171,
"text": "Example 2: Sometimes, we may not have a float value represented as a string. So, pd.to_numeric() function will show an error. To remove this error, we can use errors=’coerce’, to convert the value at this position to be converted to NaN. "
},
{
"code": null,
"e": 2417,
"s": 2410,
"text": "Code: "
},
{
"code": null,
"e": 2425,
"s": 2417,
"text": "Python3"
},
{
"code": "# importing pandas as pdimport pandas as pd # dictionaryData = {'Year': ['2016', '2017', '2018', '2019'], 'Inflation Rate': ['4.47', '5', 'No data', '4.1']} # create a dataframedf = pd.DataFrame(Data) # converting each value of column to a stringdf['Inflation Rate'] = pd.to_numeric(df['Inflation Rate'], errors = 'coerce') # show the dataframeprint(df) # show the data typesprint (df.dtypes)",
"e": 2910,
"s": 2425,
"text": null
},
{
"code": null,
"e": 2919,
"s": 2910,
"text": "Output: "
},
{
"code": null,
"e": 2962,
"s": 2919,
"text": "Note: String data type shows as an object."
},
{
"code": null,
"e": 2986,
"s": 2962,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 3000,
"s": 2986,
"text": "Python-pandas"
},
{
"code": null,
"e": 3007,
"s": 3000,
"text": "Python"
},
{
"code": null,
"e": 3105,
"s": 3007,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3123,
"s": 3105,
"text": "Python Dictionary"
},
{
"code": null,
"e": 3165,
"s": 3123,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 3187,
"s": 3165,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 3222,
"s": 3187,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 3248,
"s": 3222,
"text": "Python String | replace()"
},
{
"code": null,
"e": 3280,
"s": 3248,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3309,
"s": 3280,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 3336,
"s": 3309,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3366,
"s": 3336,
"text": "Iterate over a list in Python"
}
] |
Minimum Cost of Simple Path between two nodes in a Directed and Weighted Graph
|
27 May, 2021
Given a directed graph, which may contain cycles, where every edge has weight, the task is to find the minimum cost of any simple path from a given source vertex ‘s’ to a given destination vertex ‘t’. Simple Path is the path from one vertex to another such that no vertex is visited more than once. If there is no simple path possible then return INF(infinite).
The graph is given as adjacency matrix representation where value of graph[i][j] indicates the weight of an edge from vertex i to vertex j and a value INF(infinite) indicates no edge from i to j.
Examples:
Input : V = 5, E = 6
s = 0, t = 2
graph[][] = 0 1 2 3 4
0 INF -1 INF 1 INF
1 INF INF -2 INF INF
2 -3 INF INF INF INF
3 INF INF -1 INF INF
4 INF INF INF 2 INF
Output : -3
Explanation :
The minimum cost simple path between 0 and 2 is given by:
0 -----> 1 ------> 2 whose cost is (-1) + (-2) = (-3).
Input : V = 5, E = 6
s = 0, t = 4
graph[][] = 0 1 2 3 4
0 INF -7 INF -2 INF
1 INF INF -11 INF INF
2 INF INF INF INF INF
3 INF INF INF 3 -4
4 INF INF INF INF INF
Output : -6
Explanation :
The minimum cost simple path between 0 and 2 is given by:
0 -----> 3 ------> 4 whose cost is (-2) + (-4) = (-6).
Approach :The main idea to solve the above problem is to traverse through all simple paths from s to t using a modified version of Depth First Search and find the minimum cost path amongst them. One important observation about DFS is that it traverses one path at a time, hence we can traverse separate paths independently using DFS by marking the nodes as unvisited before leaving them.A simple solution is to start from s, go to all adjacent vertices, and follow recursion for further adjacent vertices until we reach the destination. This algorithm will work even when negative weight cycles or self edges are present in the graph.
Below is the implementation of the above-mentioned approach:
C++
Java
Python3
C#
Javascript
// C++ code for printing Minimum Cost// Simple Path between two given nodes// in a directed and weighted graph#include <bits/stdc++.h>using namespace std; // Define number of vertices in// the graph and infinite value#define V 5#define INF INT_MAX // Function to do DFS through the nodesint minimumCostSimplePath(int u, int destination, bool visited[], int graph[][V]){ // check if we find the destination // then further cost will be 0 if (u == destination) return 0; // marking the current node as visited visited[u] = 1; int ans = INF; // traverse through all // the adjacent nodes for (int i = 0; i < V; i++) { if (graph[u][i] != INF && !visited[i]) { // cost of the further path int curr = minimumCostSimplePath(i, destination, visited, graph); // check if we have reached the destination if (curr < INF) { // Taking the minimum cost path ans = min(ans, graph[u][i] + curr); } } } // unmarking the current node // to make it available for other // simple paths visited[u] = 0; // returning the minimum cost return ans;} // driver codeint main(){ // initialising the graph int graph[V][V]; for (int i = 0; i < V; i++) { for (int j = 0; j < V; j++) { graph[i][j] = INF; } } // marking all nodes as unvisited bool visited[V] = { 0 }; // initialising the edges; graph[0][1] = -1; graph[0][3] = 1; graph[1][2] = -2; graph[2][0] = -3; graph[3][2] = -1; graph[4][3] = 2; // source and destination int s = 0, t = 2; // marking the source as visited visited[s] = 1; cout << minimumCostSimplePath(s, t, visited, graph); return 0;}
// Java code for printing Minimum Cost// Simple Path between two given nodes// in a directed and weighted graphimport java.util.*;import java.lang.*; class GFG{ // Define number of vertices in// the graph and infinite valuestatic int V = 5;static int INF = Integer.MAX_VALUE; // Function to do DFS through the nodesstatic int minimumCostSimplePath(int u, int destination, boolean visited[], int graph[][]){ // Check if we find the destination // then further cost will be 0 if (u == destination) return 0; // Marking the current node as visited visited[u] = true; int ans = INF; // Traverse through all // the adjacent nodes for(int i = 0; i < V; i++) { if (graph[u][i] != INF && !visited[i]) { // Cost of the further path int curr = minimumCostSimplePath(i, destination, visited, graph); // Check if we have reached the // destination if (curr < INF) { // Taking the minimum cost path ans = Math.min(ans, graph[u][i] + curr); } } } // Unmarking the current node // to make it available for other // simple paths visited[u] = false; // Returning the minimum cost return ans;} // Driver codepublic static void main(String[] args){ // Initialising the graph int graph[][] = new int[V][V]; for(int i = 0; i < V; i++) { for(int j = 0; j < V; j++) { graph[i][j] = INF; } } // Marking all nodes as unvisited boolean visited[] = new boolean[V]; // Initialising the edges; graph[0][1] = -1; graph[0][3] = 1; graph[1][2] = -2; graph[2][0] = -3; graph[3][2] = -1; graph[4][3] = 2; // Source and destination int s = 0, t = 2; // Marking the source as visited visited[s] = true; System.out.println(minimumCostSimplePath(s, t, visited, graph));}} // This code is contributed by offbeat
# Python3 code for printing Minimum Cost# Simple Path between two given nodes# in a directed and weighted graphimport sys V = 5INF = sys.maxsize # Function to do DFS through the nodesdef minimumCostSimplePath(u, destination, visited, graph): # Check if we find the destination # then further cost will be 0 if (u == destination): return 0 # Marking the current node as visited visited[u] = 1 ans = INF # Traverse through all # the adjacent nodes for i in range(V): if (graph[u][i] != INF and not visited[i]): # Cost of the further path curr = minimumCostSimplePath(i, destination, visited, graph) # Check if we have reached the destination if (curr < INF): # Taking the minimum cost path ans = min(ans, graph[u][i] + curr) # Unmarking the current node # to make it available for other # simple paths visited[u] = 0 # Returning the minimum cost return ans # Driver codeif __name__=="__main__": # Initialising the graph graph = [[INF for j in range(V)] for i in range(V)] # Marking all nodes as unvisited visited = [0 for i in range(V)] # Initialising the edges graph[0][1] = -1 graph[0][3] = 1 graph[1][2] = -2 graph[2][0] = -3 graph[3][2] = -1 graph[4][3] = 2 # Source and destination s = 0 t = 2 # Marking the source as visited visited[s] = 1 print(minimumCostSimplePath(s, t, visited, graph)) # This code is contributed by rutvik_56
// C# code for printing Minimum Cost// Simple Path between two given nodes// in a directed and weighted graphusing System;using System.Collections;using System.Collections.Generic;class GFG{ // Define number of vertices in // the graph and infinite value static int V = 5; static int INF = int.MaxValue; // Function to do DFS through the nodes static int minimumCostSimplePath(int u, int destination, bool[] visited, int[, ] graph) { // Check if we find the destination // then further cost will be 0 if (u == destination) return 0; // Marking the current node as visited visited[u] = true; int ans = INF; // Traverse through all // the adjacent nodes for (int i = 0; i < V; i++) { if (graph[u, i] != INF && !visited[i]) { // Cost of the further path int curr = minimumCostSimplePath(i, destination, visited, graph); // Check if we have reached the // destination if (curr < INF) { // Taking the minimum cost path ans = Math.Min(ans, graph[u, i] + curr); } } } // Unmarking the current node // to make it available for other // simple paths visited[u] = false; // Returning the minimum cost return ans; } // Driver code public static void Main(string[] args) { // Initialising the graph int[, ] graph = new int[V, V]; for (int i = 0; i < V; i++) { for (int j = 0; j < V; j++) { graph[i, j] = INF; } } // Marking all nodes as unvisited bool[] visited = new bool[V]; // Initialising the edges; graph[0, 1] = -1; graph[0, 3] = 1; graph[1, 2] = -2; graph[2, 0] = -3; graph[3, 2] = -1; graph[4, 3] = 2; // Source and destination int s = 0, t = 2; // Marking the source as visited visited[s] = true; Console.WriteLine(minimumCostSimplePath(s, t, visited, graph)); }} // This code is contributed by sanjeev2552
<script> // JavaScript code for printing Minimum Cost// Simple Path between two given nodes// in a directed and weighted graph // Define number of vertices in// the graph and infinite valuelet V = 5let INF = Number.MAX_SAFE_INTEGER // Function to do DFS through the nodesfunction minimumCostSimplePath(u, destination, visited, graph){ // check if we find the destination // then further cost will be 0 if (u == destination) return 0; // marking the current node as visited visited[u] = 1; let ans = INF; // traverse through all // the adjacent nodes for (let i = 0; i < V; i++) { if (graph[u][i] != INF && !visited[i]) { // cost of the further path let curr = minimumCostSimplePath(i, destination, visited, graph); // check if we have reached the destination if (curr < INF) { // Taking the minimum cost path ans = Math.min(ans, graph[u][i] + curr); } } } // unmarking the current node // to make it available for other // simple paths visited[u] = 0; // returning the minimum cost return ans;} // driver code // initialising the graph let graph = new Array(); for(let i = 0; i< V; i++){ graph.push([]) } for (let i = 0; i < V; i++) { for (let j = 0; j < V; j++) { graph[i][j] = INF; } } // marking all nodes as unvisited let visited = new Array(V).fill(0); // initialising the edges; graph[0][1] = -1; graph[0][3] = 1; graph[1][2] = -2; graph[2][0] = -3; graph[3][2] = -1; graph[4][3] = 2; // source and destination let s = 0, t = 2; // marking the source as visited visited[s] = 1; document.write(minimumCostSimplePath(s, t, visited, graph)); // This code is contributed by _saurabh_jaiswal </script>
-3
rutvik_56
offbeat
sanjeev2552
_saurabh_jaiswal
DFS
Arrays
Competitive Programming
Graph
Recursion
Write From Home
Arrays
Recursion
DFS
Graph
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n27 May, 2021"
},
{
"code": null,
"e": 416,
"s": 54,
"text": "Given a directed graph, which may contain cycles, where every edge has weight, the task is to find the minimum cost of any simple path from a given source vertex ‘s’ to a given destination vertex ‘t’. Simple Path is the path from one vertex to another such that no vertex is visited more than once. If there is no simple path possible then return INF(infinite)."
},
{
"code": null,
"e": 612,
"s": 416,
"text": "The graph is given as adjacency matrix representation where value of graph[i][j] indicates the weight of an edge from vertex i to vertex j and a value INF(infinite) indicates no edge from i to j."
},
{
"code": null,
"e": 622,
"s": 612,
"text": "Examples:"
},
{
"code": null,
"e": 1475,
"s": 622,
"text": "Input : V = 5, E = 6\n s = 0, t = 2\n graph[][] = 0 1 2 3 4 \n 0 INF -1 INF 1 INF\n 1 INF INF -2 INF INF\n 2 -3 INF INF INF INF\n 3 INF INF -1 INF INF\n 4 INF INF INF 2 INF\n \nOutput : -3 \nExplanation : \nThe minimum cost simple path between 0 and 2 is given by:\n0 -----> 1 ------> 2 whose cost is (-1) + (-2) = (-3). \n\nInput : V = 5, E = 6\n s = 0, t = 4\n graph[][] = 0 1 2 3 4 \n 0 INF -7 INF -2 INF\n 1 INF INF -11 INF INF\n 2 INF INF INF INF INF\n 3 INF INF INF 3 -4\n 4 INF INF INF INF INF\n \nOutput : -6\nExplanation : \nThe minimum cost simple path between 0 and 2 is given by:\n0 -----> 3 ------> 4 whose cost is (-2) + (-4) = (-6). "
},
{
"code": null,
"e": 2110,
"s": 1475,
"text": "Approach :The main idea to solve the above problem is to traverse through all simple paths from s to t using a modified version of Depth First Search and find the minimum cost path amongst them. One important observation about DFS is that it traverses one path at a time, hence we can traverse separate paths independently using DFS by marking the nodes as unvisited before leaving them.A simple solution is to start from s, go to all adjacent vertices, and follow recursion for further adjacent vertices until we reach the destination. This algorithm will work even when negative weight cycles or self edges are present in the graph."
},
{
"code": null,
"e": 2172,
"s": 2110,
"text": "Below is the implementation of the above-mentioned approach: "
},
{
"code": null,
"e": 2176,
"s": 2172,
"text": "C++"
},
{
"code": null,
"e": 2181,
"s": 2176,
"text": "Java"
},
{
"code": null,
"e": 2189,
"s": 2181,
"text": "Python3"
},
{
"code": null,
"e": 2192,
"s": 2189,
"text": "C#"
},
{
"code": null,
"e": 2203,
"s": 2192,
"text": "Javascript"
},
{
"code": "// C++ code for printing Minimum Cost// Simple Path between two given nodes// in a directed and weighted graph#include <bits/stdc++.h>using namespace std; // Define number of vertices in// the graph and infinite value#define V 5#define INF INT_MAX // Function to do DFS through the nodesint minimumCostSimplePath(int u, int destination, bool visited[], int graph[][V]){ // check if we find the destination // then further cost will be 0 if (u == destination) return 0; // marking the current node as visited visited[u] = 1; int ans = INF; // traverse through all // the adjacent nodes for (int i = 0; i < V; i++) { if (graph[u][i] != INF && !visited[i]) { // cost of the further path int curr = minimumCostSimplePath(i, destination, visited, graph); // check if we have reached the destination if (curr < INF) { // Taking the minimum cost path ans = min(ans, graph[u][i] + curr); } } } // unmarking the current node // to make it available for other // simple paths visited[u] = 0; // returning the minimum cost return ans;} // driver codeint main(){ // initialising the graph int graph[V][V]; for (int i = 0; i < V; i++) { for (int j = 0; j < V; j++) { graph[i][j] = INF; } } // marking all nodes as unvisited bool visited[V] = { 0 }; // initialising the edges; graph[0][1] = -1; graph[0][3] = 1; graph[1][2] = -2; graph[2][0] = -3; graph[3][2] = -1; graph[4][3] = 2; // source and destination int s = 0, t = 2; // marking the source as visited visited[s] = 1; cout << minimumCostSimplePath(s, t, visited, graph); return 0;}",
"e": 4050,
"s": 2203,
"text": null
},
{
"code": "// Java code for printing Minimum Cost// Simple Path between two given nodes// in a directed and weighted graphimport java.util.*;import java.lang.*; class GFG{ // Define number of vertices in// the graph and infinite valuestatic int V = 5;static int INF = Integer.MAX_VALUE; // Function to do DFS through the nodesstatic int minimumCostSimplePath(int u, int destination, boolean visited[], int graph[][]){ // Check if we find the destination // then further cost will be 0 if (u == destination) return 0; // Marking the current node as visited visited[u] = true; int ans = INF; // Traverse through all // the adjacent nodes for(int i = 0; i < V; i++) { if (graph[u][i] != INF && !visited[i]) { // Cost of the further path int curr = minimumCostSimplePath(i, destination, visited, graph); // Check if we have reached the // destination if (curr < INF) { // Taking the minimum cost path ans = Math.min(ans, graph[u][i] + curr); } } } // Unmarking the current node // to make it available for other // simple paths visited[u] = false; // Returning the minimum cost return ans;} // Driver codepublic static void main(String[] args){ // Initialising the graph int graph[][] = new int[V][V]; for(int i = 0; i < V; i++) { for(int j = 0; j < V; j++) { graph[i][j] = INF; } } // Marking all nodes as unvisited boolean visited[] = new boolean[V]; // Initialising the edges; graph[0][1] = -1; graph[0][3] = 1; graph[1][2] = -2; graph[2][0] = -3; graph[3][2] = -1; graph[4][3] = 2; // Source and destination int s = 0, t = 2; // Marking the source as visited visited[s] = true; System.out.println(minimumCostSimplePath(s, t, visited, graph));}} // This code is contributed by offbeat",
"e": 6197,
"s": 4050,
"text": null
},
{
"code": "# Python3 code for printing Minimum Cost# Simple Path between two given nodes# in a directed and weighted graphimport sys V = 5INF = sys.maxsize # Function to do DFS through the nodesdef minimumCostSimplePath(u, destination, visited, graph): # Check if we find the destination # then further cost will be 0 if (u == destination): return 0 # Marking the current node as visited visited[u] = 1 ans = INF # Traverse through all # the adjacent nodes for i in range(V): if (graph[u][i] != INF and not visited[i]): # Cost of the further path curr = minimumCostSimplePath(i, destination, visited, graph) # Check if we have reached the destination if (curr < INF): # Taking the minimum cost path ans = min(ans, graph[u][i] + curr) # Unmarking the current node # to make it available for other # simple paths visited[u] = 0 # Returning the minimum cost return ans # Driver codeif __name__==\"__main__\": # Initialising the graph graph = [[INF for j in range(V)] for i in range(V)] # Marking all nodes as unvisited visited = [0 for i in range(V)] # Initialising the edges graph[0][1] = -1 graph[0][3] = 1 graph[1][2] = -2 graph[2][0] = -3 graph[3][2] = -1 graph[4][3] = 2 # Source and destination s = 0 t = 2 # Marking the source as visited visited[s] = 1 print(minimumCostSimplePath(s, t, visited, graph)) # This code is contributed by rutvik_56",
"e": 7853,
"s": 6197,
"text": null
},
{
"code": "// C# code for printing Minimum Cost// Simple Path between two given nodes// in a directed and weighted graphusing System;using System.Collections;using System.Collections.Generic;class GFG{ // Define number of vertices in // the graph and infinite value static int V = 5; static int INF = int.MaxValue; // Function to do DFS through the nodes static int minimumCostSimplePath(int u, int destination, bool[] visited, int[, ] graph) { // Check if we find the destination // then further cost will be 0 if (u == destination) return 0; // Marking the current node as visited visited[u] = true; int ans = INF; // Traverse through all // the adjacent nodes for (int i = 0; i < V; i++) { if (graph[u, i] != INF && !visited[i]) { // Cost of the further path int curr = minimumCostSimplePath(i, destination, visited, graph); // Check if we have reached the // destination if (curr < INF) { // Taking the minimum cost path ans = Math.Min(ans, graph[u, i] + curr); } } } // Unmarking the current node // to make it available for other // simple paths visited[u] = false; // Returning the minimum cost return ans; } // Driver code public static void Main(string[] args) { // Initialising the graph int[, ] graph = new int[V, V]; for (int i = 0; i < V; i++) { for (int j = 0; j < V; j++) { graph[i, j] = INF; } } // Marking all nodes as unvisited bool[] visited = new bool[V]; // Initialising the edges; graph[0, 1] = -1; graph[0, 3] = 1; graph[1, 2] = -2; graph[2, 0] = -3; graph[3, 2] = -1; graph[4, 3] = 2; // Source and destination int s = 0, t = 2; // Marking the source as visited visited[s] = true; Console.WriteLine(minimumCostSimplePath(s, t, visited, graph)); }} // This code is contributed by sanjeev2552",
"e": 10226,
"s": 7853,
"text": null
},
{
"code": "<script> // JavaScript code for printing Minimum Cost// Simple Path between two given nodes// in a directed and weighted graph // Define number of vertices in// the graph and infinite valuelet V = 5let INF = Number.MAX_SAFE_INTEGER // Function to do DFS through the nodesfunction minimumCostSimplePath(u, destination, visited, graph){ // check if we find the destination // then further cost will be 0 if (u == destination) return 0; // marking the current node as visited visited[u] = 1; let ans = INF; // traverse through all // the adjacent nodes for (let i = 0; i < V; i++) { if (graph[u][i] != INF && !visited[i]) { // cost of the further path let curr = minimumCostSimplePath(i, destination, visited, graph); // check if we have reached the destination if (curr < INF) { // Taking the minimum cost path ans = Math.min(ans, graph[u][i] + curr); } } } // unmarking the current node // to make it available for other // simple paths visited[u] = 0; // returning the minimum cost return ans;} // driver code // initialising the graph let graph = new Array(); for(let i = 0; i< V; i++){ graph.push([]) } for (let i = 0; i < V; i++) { for (let j = 0; j < V; j++) { graph[i][j] = INF; } } // marking all nodes as unvisited let visited = new Array(V).fill(0); // initialising the edges; graph[0][1] = -1; graph[0][3] = 1; graph[1][2] = -2; graph[2][0] = -3; graph[3][2] = -1; graph[4][3] = 2; // source and destination let s = 0, t = 2; // marking the source as visited visited[s] = 1; document.write(minimumCostSimplePath(s, t, visited, graph)); // This code is contributed by _saurabh_jaiswal </script>",
"e": 12130,
"s": 10226,
"text": null
},
{
"code": null,
"e": 12133,
"s": 12130,
"text": "-3"
},
{
"code": null,
"e": 12145,
"s": 12135,
"text": "rutvik_56"
},
{
"code": null,
"e": 12153,
"s": 12145,
"text": "offbeat"
},
{
"code": null,
"e": 12165,
"s": 12153,
"text": "sanjeev2552"
},
{
"code": null,
"e": 12182,
"s": 12165,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 12186,
"s": 12182,
"text": "DFS"
},
{
"code": null,
"e": 12193,
"s": 12186,
"text": "Arrays"
},
{
"code": null,
"e": 12217,
"s": 12193,
"text": "Competitive Programming"
},
{
"code": null,
"e": 12223,
"s": 12217,
"text": "Graph"
},
{
"code": null,
"e": 12233,
"s": 12223,
"text": "Recursion"
},
{
"code": null,
"e": 12249,
"s": 12233,
"text": "Write From Home"
},
{
"code": null,
"e": 12256,
"s": 12249,
"text": "Arrays"
},
{
"code": null,
"e": 12266,
"s": 12256,
"text": "Recursion"
},
{
"code": null,
"e": 12270,
"s": 12266,
"text": "DFS"
},
{
"code": null,
"e": 12276,
"s": 12270,
"text": "Graph"
}
] |
How to convert Ordereddict to JSON?
|
02 Feb, 2021
In this article, we will learn How to convert a nested OrderedDict to JSON? Before this we must go through some concepts:
The full-form of JSON is JavaScript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called JSON. To use this feature, we import the JSON package in Python script.
The text in JSON is done through quoted-string which contains a value in key-value mapping within { }. It is similar to the dictionary in Python. JSON shows an API similar to users of Standard Library marshal and pickle modules and Python natively supports JSON features
An OrderedDict is a dictionary subclass that remembers the order that keys were first inserted. The only difference between dict and OrderedDict() is that:
OrderedDict preserves the order in which the keys are inserted. A regular dict doesn’t track the insertion order, and iterating it gives the values in an arbitrary order. By contrast, the order the items are inserted is remembered by OrderedDict.
To define the OrderedDict, we are using the collections module in python.
Python3
# import packagefrom collections import OrderedDict # define OrderedDictod1 = OrderedDict([('1','one'), ('2','two')]) # display dictionaryprint(type(od1))print(od1)
Output:
<class 'collections.OrderedDict'>
OrderedDict([('1', 'one'), ('2', 'two')])
To convert OrderedDict to JSON, we are using json.dumps().
The full-form of JSON is JavaScript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called JSON. To use this feature, we import the JSON package in Python script. The text in JSON is done through quoted-string which contains the value in key-value mapping within { }. It is similar to the dictionary in Python.
The json.dumps() function converts a Python object into a JSON string.
Python3
# import packagefrom collections import OrderedDictimport json # define OrderedDictod1 = OrderedDict([('1','one'), ('2','two')]) # check type i.e; OrderedDictprint(type(od1)) # convert to jsonod1 = json.dumps(od1) # check type i.e; strprint(type(od1)) # view valueprint(od1)
<class 'collections.OrderedDict'>
<class 'str'>
{"1": "one", "2": "two"}
We can give indent value to show the dictionary pattern.
Python3
# import packagefrom collections import OrderedDictimport json # define OrderedDictod1 = OrderedDict([('1', 'one'), ('2', 'two')]) # check type i.e; OrderedDictprint(type(od1)) # convert to jsonod1 = json.dumps(od1, indent=4) # check type i.e; strprint(type(od1)) # view valueprint(od1)
Output:
<class 'collections.OrderedDict'>
<class 'str'>
{
"1": "one",
"2": "two"
}
Picked
Python-json
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n02 Feb, 2021"
},
{
"code": null,
"e": 151,
"s": 28,
"text": "In this article, we will learn How to convert a nested OrderedDict to JSON? Before this we must go through some concepts:"
},
{
"code": null,
"e": 462,
"s": 151,
"text": "The full-form of JSON is JavaScript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called JSON. To use this feature, we import the JSON package in Python script. "
},
{
"code": null,
"e": 733,
"s": 462,
"text": "The text in JSON is done through quoted-string which contains a value in key-value mapping within { }. It is similar to the dictionary in Python. JSON shows an API similar to users of Standard Library marshal and pickle modules and Python natively supports JSON features"
},
{
"code": null,
"e": 889,
"s": 733,
"text": "An OrderedDict is a dictionary subclass that remembers the order that keys were first inserted. The only difference between dict and OrderedDict() is that:"
},
{
"code": null,
"e": 1136,
"s": 889,
"text": "OrderedDict preserves the order in which the keys are inserted. A regular dict doesn’t track the insertion order, and iterating it gives the values in an arbitrary order. By contrast, the order the items are inserted is remembered by OrderedDict."
},
{
"code": null,
"e": 1210,
"s": 1136,
"text": "To define the OrderedDict, we are using the collections module in python."
},
{
"code": null,
"e": 1218,
"s": 1210,
"text": "Python3"
},
{
"code": "# import packagefrom collections import OrderedDict # define OrderedDictod1 = OrderedDict([('1','one'), ('2','two')]) # display dictionaryprint(type(od1))print(od1)",
"e": 1404,
"s": 1218,
"text": null
},
{
"code": null,
"e": 1412,
"s": 1404,
"text": "Output:"
},
{
"code": null,
"e": 1488,
"s": 1412,
"text": "<class 'collections.OrderedDict'>\nOrderedDict([('1', 'one'), ('2', 'two')])"
},
{
"code": null,
"e": 1548,
"s": 1488,
"text": "To convert OrderedDict to JSON, we are using json.dumps(). "
},
{
"code": null,
"e": 2006,
"s": 1548,
"text": "The full-form of JSON is JavaScript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called JSON. To use this feature, we import the JSON package in Python script. The text in JSON is done through quoted-string which contains the value in key-value mapping within { }. It is similar to the dictionary in Python."
},
{
"code": null,
"e": 2077,
"s": 2006,
"text": "The json.dumps() function converts a Python object into a JSON string."
},
{
"code": null,
"e": 2085,
"s": 2077,
"text": "Python3"
},
{
"code": "# import packagefrom collections import OrderedDictimport json # define OrderedDictod1 = OrderedDict([('1','one'), ('2','two')]) # check type i.e; OrderedDictprint(type(od1)) # convert to jsonod1 = json.dumps(od1) # check type i.e; strprint(type(od1)) # view valueprint(od1)",
"e": 2384,
"s": 2085,
"text": null
},
{
"code": null,
"e": 2457,
"s": 2384,
"text": "<class 'collections.OrderedDict'>\n<class 'str'>\n{\"1\": \"one\", \"2\": \"two\"}"
},
{
"code": null,
"e": 2514,
"s": 2457,
"text": "We can give indent value to show the dictionary pattern."
},
{
"code": null,
"e": 2522,
"s": 2514,
"text": "Python3"
},
{
"code": "# import packagefrom collections import OrderedDictimport json # define OrderedDictod1 = OrderedDict([('1', 'one'), ('2', 'two')]) # check type i.e; OrderedDictprint(type(od1)) # convert to jsonod1 = json.dumps(od1, indent=4) # check type i.e; strprint(type(od1)) # view valueprint(od1)",
"e": 2832,
"s": 2522,
"text": null
},
{
"code": null,
"e": 2840,
"s": 2832,
"text": "Output:"
},
{
"code": null,
"e": 2923,
"s": 2840,
"text": "<class 'collections.OrderedDict'>\n<class 'str'>\n{\n \"1\": \"one\",\n \"2\": \"two\"\n}"
},
{
"code": null,
"e": 2930,
"s": 2923,
"text": "Picked"
},
{
"code": null,
"e": 2942,
"s": 2930,
"text": "Python-json"
},
{
"code": null,
"e": 2949,
"s": 2942,
"text": "Python"
}
] |
Bootstrap Tooltips
|
19 May, 2022
In this article, we would be discussing the tooltip plugin provided by bootstrap. Tooltip is quite useful for showing the description of different elements in the webpage. Tooltip can be invoked on any element in a webpage. Tooltips on bootstrap depends on the 3rd party library Tether for positioning. Hence, we need to include tether.min.js before bootstrap.js Now let’s see an example of a tooltip.
Now we will examine the code which generates the above tooltip
HTML
<!-- Tooltip on a header --><h3 data-toggle="tooltip" title="Hey! Tooltip here!"> Hover Over me to see a tooltip</h3>
In order to introduce tooltip, we add the data-toggle attribute to an element and we need to initialize the tooltip with jQuery. jQuery code for initializing a tooltip:
Javascript
<script> // jQuery code for initializing a tooltip $(document).ready(function () { // jQuery Attribute value selector to // select the specified element and // call the tooltip method on it $('[data-toggle="tooltip"]').tooltip(); });</script>
We can even customize this tool-tip according to our requirement, let’s explore different ways in which we can customize the tool-tip.
Placement of a tool tip : We can place a tool tip at top, bottom, left and right of an element.
Example:
Code for the above example:
HTML
<!-- Tooltips on simple buttons --><!-- Placement of tooltips --><div class="row" style="margin:30px"> <div class="col-2"> <button type="button" class="btn btn-info" data-toggle="tooltip" data-placement="top" title="Information Button"> Information </button> </div> <div class="col-2"> <button type="button" class="btn btn-success" data-toggle="tooltip" data-placement="right" title="Success Button"> Success </button> </div> <div class="col-2"> <button type="button" class="btn btn-danger" data-toggle="tooltip" data-placement="bottom" title="Danger button"> Danger </button> </div> <div class="col-2"> <button type="button" class="btn btn-warning" data-toggle="tooltip" data-placement="left" title="Warning button"> Warning </button> </div></div>
In the above code we have used the data-placement attribute in order to set the placement of tool tip, we have also used row and col classes provided by bootstrap grid system
Html within a tooltip: We can add html as a content of a tooltip.
Example:
Code for the above example:
HTML
<!-- Tooltip with html --><div class="row" style="margin:40px"> <button type="button" class="btn btn-warning" data-toggle="tooltip" data-placement="left" data-html="true" title= "<h4>Hey!</h4><p>Tooltip with html</p>"> Warning </button></div>
In the above code we have used the data-html attribute in order to add an html within a tool tip.
Offset for a Tooltip: We can set the offset of the tool-tip relative to the target.
Example:
Code for the above example:
HTML
<div class="row" style="margin:40px"> <button type="button" class="btn btn-warning" data-toggle="tooltip" data-placement="right" data-offset="20 0" title="Don't click on Warning Button"> Warning </button></div>
In the above code, we have used data-offset attribute to set the attribute
Note: The output of all the code below is non-static hence, the output is not shown here.
Animation on a tooltip: By default, the animation is added to the tooltip, i.e it fades in and fades out we can remove this animation.
HTML
<!-- Removing animation from the tooltip --><div class="row" style="margin:40px"> <button type="button" class="btn btn-warning" data-toggle="tooltip" data-placement="right" data-animation="false" title="Don't click on Warning Button"> Warning </button></div>
In the above code we have used the data-animation attribute and it is set to false in order to remove animation from the tooltip
Delay in appearance and disappearance: We could set a time interval for appearance and disappearance of a tooltip. We can set a delay in two ways:We set same delay time for showing and hiding
We set same delay time for showing and hiding
We set same delay time for showing and hiding
HTML
<!-- Delay in tooltip --><div class="row" style="margin:40px"> <button type="button" class="btn btn-warning" data-toggle="tooltip" data-placement="right" data-delay="1000" title="Don't click on Warning Button"> Warning </button></div>
In the above code we have used the data-delay attribute to delay the tool-tip number assigned to this attribute is in ms i.e tool tip will be delayed for 1000 ms.We can add different delay time intervals for showing and hiding of tool-tip.
In the above code we have used the data-delay attribute to delay the tool-tip number assigned to this attribute is in ms i.e tool tip will be delayed for 1000 ms.
We can add different delay time intervals for showing and hiding of tool-tip.
HTML code:
HTML
<!-- Delay in tooltip --><div class="row" style="margin:40px"> <button type="button" class="btn btn-warning" data-toggle="tooltip" data-placement="right" title="Don't click on Warning Button"> Warning </button></div>
There is no changes in the html code.
There is no changes in the html code.
jQuery code:
Javascript
<script> $(document).ready(function () { // jQuery Attribute value selector $('[data-toggle="tooltip"]').tooltip({ delay: { "show": 1000, "hide": 2000 } }); });</script>
Triggering of the tool-tip: We can add an event which will trigger a tooltip, by default a tooltip is triggered on “hover and focus“, various events that is allowed are,- click, hover, focus and manual.
HTML
<!-- triggering the tooltip --><div class="row" style="margin:40px"> <button type="button" class="btn btn-warning" data-toggle="tooltip" data-placement="right" data-trigger="click" title="Don't click on Warning Button"> Warning </button></div>
In the above code we have used the data-trigger attribute and value is set to be click, which means when user clicks on the element the tool-tip will appear
Akanksha_Rai
rajeev0719singh
surinderdawra388
sahilintern
Web technologies
Bootstrap
GBlog
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n19 May, 2022"
},
{
"code": null,
"e": 459,
"s": 54,
"text": "In this article, we would be discussing the tooltip plugin provided by bootstrap. Tooltip is quite useful for showing the description of different elements in the webpage. Tooltip can be invoked on any element in a webpage. Tooltips on bootstrap depends on the 3rd party library Tether for positioning. Hence, we need to include tether.min.js before bootstrap.js Now let’s see an example of a tooltip. "
},
{
"code": null,
"e": 523,
"s": 459,
"text": "Now we will examine the code which generates the above tooltip "
},
{
"code": null,
"e": 528,
"s": 523,
"text": "HTML"
},
{
"code": "<!-- Tooltip on a header --><h3 data-toggle=\"tooltip\" title=\"Hey! Tooltip here!\"> Hover Over me to see a tooltip</h3>",
"e": 649,
"s": 528,
"text": null
},
{
"code": null,
"e": 819,
"s": 649,
"text": "In order to introduce tooltip, we add the data-toggle attribute to an element and we need to initialize the tooltip with jQuery. jQuery code for initializing a tooltip: "
},
{
"code": null,
"e": 830,
"s": 819,
"text": "Javascript"
},
{
"code": "<script> // jQuery code for initializing a tooltip $(document).ready(function () { // jQuery Attribute value selector to // select the specified element and // call the tooltip method on it $('[data-toggle=\"tooltip\"]').tooltip(); });</script>",
"e": 1110,
"s": 830,
"text": null
},
{
"code": null,
"e": 1245,
"s": 1110,
"text": "We can even customize this tool-tip according to our requirement, let’s explore different ways in which we can customize the tool-tip."
},
{
"code": null,
"e": 1342,
"s": 1245,
"text": "Placement of a tool tip : We can place a tool tip at top, bottom, left and right of an element. "
},
{
"code": null,
"e": 1351,
"s": 1342,
"text": "Example:"
},
{
"code": null,
"e": 1383,
"s": 1354,
"text": "Code for the above example: "
},
{
"code": null,
"e": 1388,
"s": 1383,
"text": "HTML"
},
{
"code": "<!-- Tooltips on simple buttons --><!-- Placement of tooltips --><div class=\"row\" style=\"margin:30px\"> <div class=\"col-2\"> <button type=\"button\" class=\"btn btn-info\" data-toggle=\"tooltip\" data-placement=\"top\" title=\"Information Button\"> Information </button> </div> <div class=\"col-2\"> <button type=\"button\" class=\"btn btn-success\" data-toggle=\"tooltip\" data-placement=\"right\" title=\"Success Button\"> Success </button> </div> <div class=\"col-2\"> <button type=\"button\" class=\"btn btn-danger\" data-toggle=\"tooltip\" data-placement=\"bottom\" title=\"Danger button\"> Danger </button> </div> <div class=\"col-2\"> <button type=\"button\" class=\"btn btn-warning\" data-toggle=\"tooltip\" data-placement=\"left\" title=\"Warning button\"> Warning </button> </div></div>",
"e": 2349,
"s": 1388,
"text": null
},
{
"code": null,
"e": 2524,
"s": 2349,
"text": "In the above code we have used the data-placement attribute in order to set the placement of tool tip, we have also used row and col classes provided by bootstrap grid system"
},
{
"code": null,
"e": 2591,
"s": 2524,
"text": "Html within a tooltip: We can add html as a content of a tooltip. "
},
{
"code": null,
"e": 2600,
"s": 2591,
"text": "Example:"
},
{
"code": null,
"e": 2632,
"s": 2603,
"text": "Code for the above example: "
},
{
"code": null,
"e": 2637,
"s": 2632,
"text": "HTML"
},
{
"code": "<!-- Tooltip with html --><div class=\"row\" style=\"margin:40px\"> <button type=\"button\" class=\"btn btn-warning\" data-toggle=\"tooltip\" data-placement=\"left\" data-html=\"true\" title= \"<h4>Hey!</h4><p>Tooltip with html</p>\"> Warning </button></div>",
"e": 2914,
"s": 2637,
"text": null
},
{
"code": null,
"e": 3012,
"s": 2914,
"text": "In the above code we have used the data-html attribute in order to add an html within a tool tip."
},
{
"code": null,
"e": 3097,
"s": 3012,
"text": "Offset for a Tooltip: We can set the offset of the tool-tip relative to the target. "
},
{
"code": null,
"e": 3106,
"s": 3097,
"text": "Example:"
},
{
"code": null,
"e": 3138,
"s": 3108,
"text": " Code for the above example: "
},
{
"code": null,
"e": 3143,
"s": 3138,
"text": "HTML"
},
{
"code": "<div class=\"row\" style=\"margin:40px\"> <button type=\"button\" class=\"btn btn-warning\" data-toggle=\"tooltip\" data-placement=\"right\" data-offset=\"20 0\" title=\"Don't click on Warning Button\"> Warning </button></div>",
"e": 3388,
"s": 3143,
"text": null
},
{
"code": null,
"e": 3463,
"s": 3388,
"text": "In the above code, we have used data-offset attribute to set the attribute"
},
{
"code": null,
"e": 3553,
"s": 3463,
"text": "Note: The output of all the code below is non-static hence, the output is not shown here."
},
{
"code": null,
"e": 3689,
"s": 3553,
"text": "Animation on a tooltip: By default, the animation is added to the tooltip, i.e it fades in and fades out we can remove this animation. "
},
{
"code": null,
"e": 3694,
"s": 3689,
"text": "HTML"
},
{
"code": "<!-- Removing animation from the tooltip --><div class=\"row\" style=\"margin:40px\"> <button type=\"button\" class=\"btn btn-warning\" data-toggle=\"tooltip\" data-placement=\"right\" data-animation=\"false\" title=\"Don't click on Warning Button\"> Warning </button></div>",
"e": 3987,
"s": 3694,
"text": null
},
{
"code": null,
"e": 4116,
"s": 3987,
"text": "In the above code we have used the data-animation attribute and it is set to false in order to remove animation from the tooltip"
},
{
"code": null,
"e": 4309,
"s": 4116,
"text": "Delay in appearance and disappearance: We could set a time interval for appearance and disappearance of a tooltip. We can set a delay in two ways:We set same delay time for showing and hiding "
},
{
"code": null,
"e": 4356,
"s": 4309,
"text": "We set same delay time for showing and hiding "
},
{
"code": null,
"e": 4403,
"s": 4356,
"text": "We set same delay time for showing and hiding "
},
{
"code": null,
"e": 4408,
"s": 4403,
"text": "HTML"
},
{
"code": "<!-- Delay in tooltip --><div class=\"row\" style=\"margin:40px\"> <button type=\"button\" class=\"btn btn-warning\" data-toggle=\"tooltip\" data-placement=\"right\" data-delay=\"1000\" title=\"Don't click on Warning Button\"> Warning </button></div>",
"e": 4677,
"s": 4408,
"text": null
},
{
"code": null,
"e": 4918,
"s": 4677,
"text": "In the above code we have used the data-delay attribute to delay the tool-tip number assigned to this attribute is in ms i.e tool tip will be delayed for 1000 ms.We can add different delay time intervals for showing and hiding of tool-tip. "
},
{
"code": null,
"e": 5081,
"s": 4918,
"text": "In the above code we have used the data-delay attribute to delay the tool-tip number assigned to this attribute is in ms i.e tool tip will be delayed for 1000 ms."
},
{
"code": null,
"e": 5160,
"s": 5081,
"text": "We can add different delay time intervals for showing and hiding of tool-tip. "
},
{
"code": null,
"e": 5172,
"s": 5160,
"text": "HTML code: "
},
{
"code": null,
"e": 5177,
"s": 5172,
"text": "HTML"
},
{
"code": "<!-- Delay in tooltip --><div class=\"row\" style=\"margin:40px\"> <button type=\"button\" class=\"btn btn-warning\" data-toggle=\"tooltip\" data-placement=\"right\" title=\"Don't click on Warning Button\"> Warning </button></div>",
"e": 5421,
"s": 5177,
"text": null
},
{
"code": null,
"e": 5460,
"s": 5421,
"text": "There is no changes in the html code. "
},
{
"code": null,
"e": 5499,
"s": 5460,
"text": "There is no changes in the html code. "
},
{
"code": null,
"e": 5513,
"s": 5499,
"text": "jQuery code: "
},
{
"code": null,
"e": 5524,
"s": 5513,
"text": "Javascript"
},
{
"code": "<script> $(document).ready(function () { // jQuery Attribute value selector $('[data-toggle=\"tooltip\"]').tooltip({ delay: { \"show\": 1000, \"hide\": 2000 } }); });</script>",
"e": 5732,
"s": 5524,
"text": null
},
{
"code": null,
"e": 5936,
"s": 5732,
"text": "Triggering of the tool-tip: We can add an event which will trigger a tooltip, by default a tooltip is triggered on “hover and focus“, various events that is allowed are,- click, hover, focus and manual. "
},
{
"code": null,
"e": 5941,
"s": 5936,
"text": "HTML"
},
{
"code": "<!-- triggering the tooltip --><div class=\"row\" style=\"margin:40px\"> <button type=\"button\" class=\"btn btn-warning\" data-toggle=\"tooltip\" data-placement=\"right\" data-trigger=\"click\" title=\"Don't click on Warning Button\"> Warning </button></div>",
"e": 6220,
"s": 5941,
"text": null
},
{
"code": null,
"e": 6377,
"s": 6220,
"text": "In the above code we have used the data-trigger attribute and value is set to be click, which means when user clicks on the element the tool-tip will appear"
},
{
"code": null,
"e": 6390,
"s": 6377,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 6406,
"s": 6390,
"text": "rajeev0719singh"
},
{
"code": null,
"e": 6423,
"s": 6406,
"text": "surinderdawra388"
},
{
"code": null,
"e": 6435,
"s": 6423,
"text": "sahilintern"
},
{
"code": null,
"e": 6452,
"s": 6435,
"text": "Web technologies"
},
{
"code": null,
"e": 6462,
"s": 6452,
"text": "Bootstrap"
},
{
"code": null,
"e": 6468,
"s": 6462,
"text": "GBlog"
}
] |
PyQtGraph – Getting X and Y Co-ordinates of Line in Line Graph
|
23 Jan, 2022
In this article, we will see how we can get X & Y coordinates of the line i.e origin of the line of line graph in the PyQtGraph module. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, etc.) A line chart or line plot or line graph or curve chart is a type of chart that displays information as a series of data points called ‘markers’ connected by straight line segments. It is a basic type of chart common in many fields. The line graph is created with the help of plot class in PyQtGraph. X and Y are the positions of the line corresponding to the respective axis. It can be set with the help of setX and setY methods.
We can create a plot window and create lines on it with the help of commands given below.
# creating a pyqtgraph plot window
plt = pg.plot()
# plotting line in green color
# with dot symbol as x, not a mandatory field
line = plt.plot(x, y, pen='g', symbol='x', symbolPen='g',
symbolBrush=0.2, name='green')
In order to do this we use x and y methods with the line objectSyntax : line.x() and line.y()Argument : It takes no argumentReturn : It returns float value
Below is the implementation.
Python3
# importing Qt widgetsfrom PyQt5.QtWidgets import *import sys # importing pyqtgraph as pgimport pyqtgraph as pgfrom PyQt5.QtGui import * from PyQt5.QtCore import Qt # Bar Graph classclass BarGraphItem(pg.BarGraphItem): # constructor which inherit original # BarGraphItem def __init__(self, *args, **kwargs): pg.BarGraphItem.__init__(self, *args, **kwargs) # creating a mouse double click event def mouseDoubleClickEvent(self, e): # setting scale self.setScale(0.2) class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("PyQtGraph") # setting geometry self.setGeometry(100, 100, 600, 500) # icon icon = QIcon("skin.png") # setting icon to the window self.setWindowIcon(icon) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a widget object widget = QWidget() # creating a new label label = QLabel("GeeksforGeeks Line Plot") # making it multiline label.setWordWrap(True) # y values to plot by line 1 y = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # y values to plot by line 2 y2 = [3, 1, 5, 8, 9, 11, 16, 17, 14, 16] x = range(0, 10) # create plot window object plt = pg.plot() # showing x and y grids plt.showGrid(x=True, y=True) # adding legend plt.addLegend() # set properties of the label for y axis plt.setLabel('left', 'Vertical Values', units='y') # set properties of the label for x axis plt.setLabel('bottom', 'Horizontal Values', units='s') # setting horizontal range plt.setXRange(0, 20) # setting vertical range plt.setYRange(0, 20) # plotting line in green color # with dot symbol as x, not a mandatory field line1 = plt.plot(x, y, pen='g', symbol='x', symbolPen='g', symbolBrush=0.2, name='green') # plotting line2 with blue color # with dot symbol as o line2 = plt.plot(x, y2, pen='b', symbol='o', symbolPen='b', symbolBrush=0.2, name='blue') # setting X pos to the line1 line1.setX(-2) # setting Y pos of line 1 line1.setY(5) # getting X & Y pos of line 1 valuex = line1.x() valuey = line1.y() # setting text to the label label.setText("X & Y pos : " + str(valuex) + ", " + str(valuey)) # label minimum width label.setMinimumWidth(120) # Creating a grid layout layout = QGridLayout() # setting this layout to the widget widget.setLayout(layout) # adding label to the layout layout.addWidget(label, 1, 0) # plot window goes on right side, spanning 3 rows layout.addWidget(plt, 0, 1, 3, 1) # setting this widget as central widget of the main window self.setCentralWidget(widget) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
Output :
simmytarika5
anikakapoor
adnanirshad158
Python-gui
Python-PyQtGraph
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 Jan, 2022"
},
{
"code": null,
"e": 842,
"s": 28,
"text": "In this article, we will see how we can get X & Y coordinates of the line i.e origin of the line of line graph in the PyQtGraph module. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, etc.) A line chart or line plot or line graph or curve chart is a type of chart that displays information as a series of data points called ‘markers’ connected by straight line segments. It is a basic type of chart common in many fields. The line graph is created with the help of plot class in PyQtGraph. X and Y are the positions of the line corresponding to the respective axis. It can be set with the help of setX and setY methods."
},
{
"code": null,
"e": 932,
"s": 842,
"text": "We can create a plot window and create lines on it with the help of commands given below."
},
{
"code": null,
"e": 1167,
"s": 932,
"text": "# creating a pyqtgraph plot window\nplt = pg.plot()\n\n# plotting line in green color\n# with dot symbol as x, not a mandatory field\nline = plt.plot(x, y, pen='g', symbol='x', symbolPen='g', \n symbolBrush=0.2, name='green')"
},
{
"code": null,
"e": 1324,
"s": 1167,
"text": "In order to do this we use x and y methods with the line objectSyntax : line.x() and line.y()Argument : It takes no argumentReturn : It returns float value "
},
{
"code": null,
"e": 1353,
"s": 1324,
"text": "Below is the implementation."
},
{
"code": null,
"e": 1361,
"s": 1353,
"text": "Python3"
},
{
"code": "# importing Qt widgetsfrom PyQt5.QtWidgets import *import sys # importing pyqtgraph as pgimport pyqtgraph as pgfrom PyQt5.QtGui import * from PyQt5.QtCore import Qt # Bar Graph classclass BarGraphItem(pg.BarGraphItem): # constructor which inherit original # BarGraphItem def __init__(self, *args, **kwargs): pg.BarGraphItem.__init__(self, *args, **kwargs) # creating a mouse double click event def mouseDoubleClickEvent(self, e): # setting scale self.setScale(0.2) class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"PyQtGraph\") # setting geometry self.setGeometry(100, 100, 600, 500) # icon icon = QIcon(\"skin.png\") # setting icon to the window self.setWindowIcon(icon) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a widget object widget = QWidget() # creating a new label label = QLabel(\"GeeksforGeeks Line Plot\") # making it multiline label.setWordWrap(True) # y values to plot by line 1 y = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # y values to plot by line 2 y2 = [3, 1, 5, 8, 9, 11, 16, 17, 14, 16] x = range(0, 10) # create plot window object plt = pg.plot() # showing x and y grids plt.showGrid(x=True, y=True) # adding legend plt.addLegend() # set properties of the label for y axis plt.setLabel('left', 'Vertical Values', units='y') # set properties of the label for x axis plt.setLabel('bottom', 'Horizontal Values', units='s') # setting horizontal range plt.setXRange(0, 20) # setting vertical range plt.setYRange(0, 20) # plotting line in green color # with dot symbol as x, not a mandatory field line1 = plt.plot(x, y, pen='g', symbol='x', symbolPen='g', symbolBrush=0.2, name='green') # plotting line2 with blue color # with dot symbol as o line2 = plt.plot(x, y2, pen='b', symbol='o', symbolPen='b', symbolBrush=0.2, name='blue') # setting X pos to the line1 line1.setX(-2) # setting Y pos of line 1 line1.setY(5) # getting X & Y pos of line 1 valuex = line1.x() valuey = line1.y() # setting text to the label label.setText(\"X & Y pos : \" + str(valuex) + \", \" + str(valuey)) # label minimum width label.setMinimumWidth(120) # Creating a grid layout layout = QGridLayout() # setting this layout to the widget widget.setLayout(layout) # adding label to the layout layout.addWidget(label, 1, 0) # plot window goes on right side, spanning 3 rows layout.addWidget(plt, 0, 1, 3, 1) # setting this widget as central widget of the main window self.setCentralWidget(widget) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())",
"e": 4595,
"s": 1361,
"text": null
},
{
"code": null,
"e": 4605,
"s": 4595,
"text": "Output : "
},
{
"code": null,
"e": 4620,
"s": 4607,
"text": "simmytarika5"
},
{
"code": null,
"e": 4632,
"s": 4620,
"text": "anikakapoor"
},
{
"code": null,
"e": 4647,
"s": 4632,
"text": "adnanirshad158"
},
{
"code": null,
"e": 4658,
"s": 4647,
"text": "Python-gui"
},
{
"code": null,
"e": 4675,
"s": 4658,
"text": "Python-PyQtGraph"
},
{
"code": null,
"e": 4682,
"s": 4675,
"text": "Python"
}
] |
SQL Query to Exclude Multiple Values
|
13 Sep, 2021
To exclude multiple values to be fetched from a table we can use multiple OR statements but when we want to exclude a lot of values it becomes lengthy to write multiple AND statements, To avoid this we can use the NOT IN clause with the array of values that need to be excluded with the WHERE statement.
In this article let us see the SQL query to exclude multiple values using both AND and NOT IN clauses.
Use the below command to create a database named GeeksforGeeks:
CREATE DATABASE GeeksforGeeks
To use the GeeksforGeeks database use the below command:
USE GeeksforGeeks
Create a table student_details with 4 columns using the following SQL query:
CREATE TABLE student_details(
stu_id VARCHAR(8),
branch VARCHAR(20),
course_code VARCHAR(10),
backlogs VARCHAR(10)
);
To view the description of the tables in the database using the following SQL query:
EXEC sp_columns student_details;
Inserting rows into student_details tables using the following SQL query:
INSERT INTO student_details VALUES
('191401','E.C.E','ECPC-251', 'NO'),
('191302','I.C.E','ICPC-221','YES'),
('191305','I.C.E','ICPC-225','YES'),
('191410','E.C.E','ECPC-251', 'YES'),
('191210','M.E','MEPC-103', 'YES'),
('191215','M.E','MEPC-101', 'NO'),
('191505','C.E','CEPC-501', 'NO'),
('191525','C.E','CEPC-502', 'NO');
Viewing the table student_details after inserting rows by using the following SQL query:
SELECT* FROM employee_details;
1. Query to find the students other than ‘ECE’, ‘ICE’, ‘ME’
Using NOT IN:
Syntax:
SELECT * FROM table_name
WHERE req_column NOT IN(data1,data2,data3,....)
Query:
SELECT* FROM student_details
WHERE branch NOT IN ('E.C.E','I.C.E','M.E');
Using AND:
Syntax:
SELECT * FROM table_name
WHERE condition1 AND condition2 AND condition3;
Query:
SELECT* FROM student_details
WHERE branch<>'E.C.E' AND branch <> 'I.C.E' AND branch<>'M.E';
2. Query to update the backlogs to NO other than students of C.E and M.E.
UPDATE student_details
SET backlogs='NO' WHERE branch NOT IN ('C.E','M.E');
SELECT* FROM student_details;
Blogathon-2021
Picked
SQL-Query
Blogathon
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Import JSON Data into SQL Server?
Scrape LinkedIn Using Selenium And Beautiful Soup in Python
SQL Query to Convert Datetime to Date
Python program to convert XML to Dictionary
Shared ViewModel in Android
SQL | DDL, DQL, DML, DCL and TCL Commands
SQL | Join (Inner, Left, Right and Full Joins)
SQL | WITH clause
How to find Nth highest salary from a table
SQL | ALTER (RENAME)
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n13 Sep, 2021"
},
{
"code": null,
"e": 332,
"s": 28,
"text": "To exclude multiple values to be fetched from a table we can use multiple OR statements but when we want to exclude a lot of values it becomes lengthy to write multiple AND statements, To avoid this we can use the NOT IN clause with the array of values that need to be excluded with the WHERE statement."
},
{
"code": null,
"e": 435,
"s": 332,
"text": "In this article let us see the SQL query to exclude multiple values using both AND and NOT IN clauses."
},
{
"code": null,
"e": 499,
"s": 435,
"text": "Use the below command to create a database named GeeksforGeeks:"
},
{
"code": null,
"e": 529,
"s": 499,
"text": "CREATE DATABASE GeeksforGeeks"
},
{
"code": null,
"e": 586,
"s": 529,
"text": "To use the GeeksforGeeks database use the below command:"
},
{
"code": null,
"e": 604,
"s": 586,
"text": "USE GeeksforGeeks"
},
{
"code": null,
"e": 682,
"s": 604,
"text": "Create a table student_details with 4 columns using the following SQL query:"
},
{
"code": null,
"e": 800,
"s": 682,
"text": "CREATE TABLE student_details(\nstu_id VARCHAR(8),\nbranch VARCHAR(20),\ncourse_code VARCHAR(10),\nbacklogs VARCHAR(10)\n);"
},
{
"code": null,
"e": 885,
"s": 800,
"text": "To view the description of the tables in the database using the following SQL query:"
},
{
"code": null,
"e": 918,
"s": 885,
"text": "EXEC sp_columns student_details;"
},
{
"code": null,
"e": 992,
"s": 918,
"text": "Inserting rows into student_details tables using the following SQL query:"
},
{
"code": null,
"e": 1334,
"s": 992,
"text": "INSERT INTO student_details VALUES\n ('191401','E.C.E','ECPC-251', 'NO'),\n ('191302','I.C.E','ICPC-221','YES'),\n ('191305','I.C.E','ICPC-225','YES'),\n ('191410','E.C.E','ECPC-251', 'YES'),\n ('191210','M.E','MEPC-103', 'YES'),\n ('191215','M.E','MEPC-101', 'NO'),\n ('191505','C.E','CEPC-501', 'NO'),\n ('191525','C.E','CEPC-502', 'NO');"
},
{
"code": null,
"e": 1423,
"s": 1334,
"text": "Viewing the table student_details after inserting rows by using the following SQL query:"
},
{
"code": null,
"e": 1454,
"s": 1423,
"text": "SELECT* FROM employee_details;"
},
{
"code": null,
"e": 1514,
"s": 1454,
"text": "1. Query to find the students other than ‘ECE’, ‘ICE’, ‘ME’"
},
{
"code": null,
"e": 1528,
"s": 1514,
"text": "Using NOT IN:"
},
{
"code": null,
"e": 1536,
"s": 1528,
"text": "Syntax:"
},
{
"code": null,
"e": 1609,
"s": 1536,
"text": "SELECT * FROM table_name\nWHERE req_column NOT IN(data1,data2,data3,....)"
},
{
"code": null,
"e": 1616,
"s": 1609,
"text": "Query:"
},
{
"code": null,
"e": 1690,
"s": 1616,
"text": "SELECT* FROM student_details\nWHERE branch NOT IN ('E.C.E','I.C.E','M.E');"
},
{
"code": null,
"e": 1701,
"s": 1690,
"text": "Using AND:"
},
{
"code": null,
"e": 1709,
"s": 1701,
"text": "Syntax:"
},
{
"code": null,
"e": 1782,
"s": 1709,
"text": "SELECT * FROM table_name\nWHERE condition1 AND condition2 AND condition3;"
},
{
"code": null,
"e": 1789,
"s": 1782,
"text": "Query:"
},
{
"code": null,
"e": 1881,
"s": 1789,
"text": "SELECT* FROM student_details\nWHERE branch<>'E.C.E' AND branch <> 'I.C.E' AND branch<>'M.E';"
},
{
"code": null,
"e": 1955,
"s": 1881,
"text": "2. Query to update the backlogs to NO other than students of C.E and M.E."
},
{
"code": null,
"e": 2061,
"s": 1955,
"text": "UPDATE student_details\nSET backlogs='NO' WHERE branch NOT IN ('C.E','M.E');\nSELECT* FROM student_details;"
},
{
"code": null,
"e": 2076,
"s": 2061,
"text": "Blogathon-2021"
},
{
"code": null,
"e": 2083,
"s": 2076,
"text": "Picked"
},
{
"code": null,
"e": 2093,
"s": 2083,
"text": "SQL-Query"
},
{
"code": null,
"e": 2103,
"s": 2093,
"text": "Blogathon"
},
{
"code": null,
"e": 2107,
"s": 2103,
"text": "SQL"
},
{
"code": null,
"e": 2111,
"s": 2107,
"text": "SQL"
},
{
"code": null,
"e": 2209,
"s": 2111,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2250,
"s": 2209,
"text": "How to Import JSON Data into SQL Server?"
},
{
"code": null,
"e": 2310,
"s": 2250,
"text": "Scrape LinkedIn Using Selenium And Beautiful Soup in Python"
},
{
"code": null,
"e": 2348,
"s": 2310,
"text": "SQL Query to Convert Datetime to Date"
},
{
"code": null,
"e": 2392,
"s": 2348,
"text": "Python program to convert XML to Dictionary"
},
{
"code": null,
"e": 2420,
"s": 2392,
"text": "Shared ViewModel in Android"
},
{
"code": null,
"e": 2462,
"s": 2420,
"text": "SQL | DDL, DQL, DML, DCL and TCL Commands"
},
{
"code": null,
"e": 2509,
"s": 2462,
"text": "SQL | Join (Inner, Left, Right and Full Joins)"
},
{
"code": null,
"e": 2527,
"s": 2509,
"text": "SQL | WITH clause"
},
{
"code": null,
"e": 2571,
"s": 2527,
"text": "How to find Nth highest salary from a table"
}
] |
Minimize count of connections required to be rearranged to make all the computers connected
|
08 Oct, 2021
Given an integer N, denoting the number of computers connected by cables forming a network and a 2D array connections[][], with each row (i, j) representing a connection between ith and jth computer, the task is to connect all the computers either directly or indirectly by removing any of the given connections and connecting two disconnected computers. If it’s not possible to connect all the computers, print -1. Otherwise, print the minimum number of such operations required.
Examples:
Input: N = 4, connections[][] = {{0, 1}, {0, 2}, {1, 2}}Output: 1Explanation: Remove the connection between computers 1 and 2 and connect the computers 1 and 3.
Input: N = 5, connections[][] = {{0, 1}, {0, 2}, {3, 4}, {2, 3}}Output: 0
Approach: The idea is to use a concept similar to that of Minimum Spanning Tree, as in a Graph with N nodes, only N – 1 edges are required to make all the nodes connected.
Redundant edges = Total edges – [(Number of Nodes – 1) – (Number of components – 1)]
If Redundant edges > (Number of components – 1) : It is clear that there are enough wires that can be used to connect disconnected computers. Otherwise, print -1.
Follow the steps below to solve the problem:
Initialize an unordered map, say adj to store the adjacency list from the given information about edges.Initialize a vector of boolean datatype, say visited, to store whether a node is visited or not.Generate the adjacency list and also calculate the number of edges.Initialize a variable, say components, to store the count of connected components.Traverse the nodes of the graph using DFS to count the number of connected components and store it in the variable components.Initialize a variable, say redundant, and store the number of redundant edges using the above formula.If redundant edges > components – 1, then the minimum number of required operations is equal to components – 1. Otherwise, print -1.
Initialize an unordered map, say adj to store the adjacency list from the given information about edges.
Initialize a vector of boolean datatype, say visited, to store whether a node is visited or not.
Generate the adjacency list and also calculate the number of edges.
Initialize a variable, say components, to store the count of connected components.
Traverse the nodes of the graph using DFS to count the number of connected components and store it in the variable components.
Initialize a variable, say redundant, and store the number of redundant edges using the above formula.
If redundant edges > components – 1, then the minimum number of required operations is equal to components – 1. Otherwise, print -1.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to visit the nodes of a graphvoid DFS(unordered_map<int, vector<int> >& adj, int node, vector<bool>& visited){ // If current node is already visited if (visited[node]) return; // If current node is not visited visited[node] = true; // Recurse for neighbouring nodes for (auto x : adj[node]) { // If the node is not visited if (visited[x] == false) DFS(adj, x, visited); }} // Utility function to check if it is// possible to connect all computers or notint makeConnectedUtil(int N, int connections[][2], int M){ // Stores whether a // node is visited or not vector<bool> visited(N, false); // Build the adjacency list unordered_map<int, vector<int> > adj; // Stores count of edges int edges = 0; // Building adjacency list // from the given edges for (int i = 0; i < M; ++i) { // Add edges adj[connections[i][0]].push_back( connections[i][1]); adj[connections[i][1]].push_back( connections[i][0]); // Increment count of edges edges += 1; } // Stores count of components int components = 0; for (int i = 0; i < N; ++i) { // If node is not visited if (visited[i] == false) { // Increment components components += 1; // Perform DFS DFS(adj, i, visited); } } // At least N - 1 edges are required if (edges < N - 1) return -1; // Count redundant edges int redundant = edges - ((N - 1) - (components - 1)); // Check if components can be // rearranged using redundant edges if (redundant >= (components - 1)) return components - 1; return -1;} // Function to check if it is possible// to connect all the computers or notvoid makeConnected(int N, int connections[][2], int M){ // Stores counmt of minimum // operations required int minOps = makeConnectedUtil( N, connections, M); // Print the minimum number // of operations required cout << minOps;} // Driver Codeint main(){ // Given number of computers int N = 4; // Given set of connections int connections[][2] = { { 0, 1 }, { 0, 2 }, { 1, 2 } }; int M = sizeof(connections) / sizeof(connections[0]); // Function call to check if it is // possible to connect all computers or not makeConnected(N, connections, M); return 0;}
// Java program for the above approachimport java.io.*;import java.util.*; class GFG { // Function to visit the nodes of a graph public static void DFS(HashMap<Integer, ArrayList<Integer> > adj, int node, boolean visited[]) { // If current node is already visited if (visited[node]) return; // If current node is not visited visited[node] = true; // Recurse for neighbouring nodes for (int x : adj.get(node)) { // If the node is not visited if (visited[x] == false) DFS(adj, x, visited); } } // Utility function to check if it is // possible to connect all computers or not public static int makeConnectedUtil(int N, int connections[][], int M) { // Stores whether a // node is visited or not boolean visited[] = new boolean[N]; // Build the adjacency list HashMap<Integer, ArrayList<Integer> > adj = new HashMap<>(); // Initialize the adjacency list for (int i = 0; i < N; i++) { adj.put(i, new ArrayList<Integer>()); } // Stores count of edges int edges = 0; // Building adjacency list // from the given edges for (int i = 0; i < M; ++i) { // Get neighbours list ArrayList<Integer> l1 = adj.get(connections[i][0]); ArrayList<Integer> l2 = adj.get(connections[i][0]); // Add edges l1.add(connections[i][1]); l2.add(connections[i][0]); // Increment count of edges edges += 1; } // Stores count of components int components = 0; for (int i = 0; i < N; ++i) { // If node is not visited if (visited[i] == false) { // Increment components components += 1; // Perform DFS DFS(adj, i, visited); } } // At least N - 1 edges are required if (edges < N - 1) return -1; // Count redundant edges int redundant = edges - ((N - 1) - (components - 1)); // Check if components can be // rearranged using redundant edges if (redundant >= (components - 1)) return components - 1; return -1; } // Function to check if it is possible // to connect all the computers or not public static void makeConnected(int N, int connections[][], int M) { // Stores counmt of minimum // operations required int minOps = makeConnectedUtil(N, connections, M); // Print the minimum number // of operations required System.out.println(minOps); } // Driver Code public static void main(String[] args) { // Given number of computers int N = 4; // Given set of connections int connections[][] = { { 0, 1 }, { 0, 2 }, { 1, 2 } }; int M = connections.length; // Function call to check if it is // possible to connect all computers or not makeConnected(N, connections, M); }} // This code is contributed by kingash.
# Python3 code for the above approach # Function to visit the nodes of a graphdef DFS(adj, node, visited): # If current node is already visited if (visited[node]): return # If current node is not visited visited[node] = True # Recurse for neighbouring nodes if(node in adj): for x in adj[node]: # If the node is not visited if (visited[x] == False): DFS(adj, x, visited) # Utility function to check if it is# possible to connect all computers or notdef makeConnectedUtil(N, connections, M): # Stores whether a # node is visited or not visited = [False for i in range(N)] # Build the adjacency list adj = {} # Stores count of edges edges = 0 # Building adjacency list # from the given edges for i in range(M): # Add edges if (connections[i][0] in adj): adj[connections[i][0]].append( connections[i][1]) else: adj[connections[i][0]] = [] if (connections[i][1] in adj): adj[connections[i][1]].append( connections[i][0]) else: adj[connections[i][1]] = [] # Increment count of edges edges += 1 # Stores count of components components = 0 for i in range(N): # If node is not visited if (visited[i] == False): # Increment components components += 1 # Perform DFS DFS(adj, i, visited) # At least N - 1 edges are required if (edges < N - 1): return -1 # Count redundant edges redundant = edges - ((N - 1) - (components - 1)) # Check if components can be # rearranged using redundant edges if (redundant >= (components - 1)): return components - 1 return -1 # Function to check if it is possible# to connect all the computers or notdef makeConnected(N, connections, M): # Stores counmt of minimum # operations required minOps = makeConnectedUtil(N, connections, M) # Print the minimum number # of operations required print(minOps) # Driver Codeif __name__ == '__main__': # Given number of computers N = 4 # Given set of connections connections = [ [ 0, 1 ], [ 0, 2 ], [ 1, 2 ] ] M = len(connections) # Function call to check if it is # possible to connect all computers or not makeConnected(N, connections, M) # This code is contributed by ipg2016107
// C# program for the above approachusing System;using System.Collections.Generic;class GFG { // Function to visit the nodes of a graph public static void DFS(Dictionary<int, List<int>> adj, int node, bool[] visited) { // If current node is already visited if (visited[node]) return; // If current node is not visited visited[node] = true; // Recurse for neighbouring nodes foreach(int x in adj[node]) { // If the node is not visited if (visited[x] == false) DFS(adj, x, visited); } } // Utility function to check if it is // possible to connect all computers or not public static int makeConnectedUtil(int N, int[,] connections, int M) { // Stores whether a // node is visited or not bool[] visited = new bool[N]; // Build the adjacency list Dictionary<int, List<int>> adj = new Dictionary<int, List<int>>(); // Initialize the adjacency list for (int i = 0; i < N; i++) { adj[i] = new List<int>(); } // Stores count of edges int edges = 0; // Building adjacency list // from the given edges for (int i = 0; i < M; ++i) { // Get neighbours list List<int> l1 = adj[connections[i,0]]; List<int> l2 = adj[connections[i,0]]; // Add edges l1.Add(connections[i,1]); l2.Add(connections[i,0]); // Increment count of edges edges += 1; } // Stores count of components int components = 0; for (int i = 0; i < N; ++i) { // If node is not visited if (visited[i] == false) { // Increment components components += 1; // Perform DFS DFS(adj, i, visited); } } // At least N - 1 edges are required if (edges < N - 1) return -1; // Count redundant edges int redundant = edges - ((N - 1) - (components - 1)); // Check if components can be // rearranged using redundant edges if (redundant >= (components - 1)) return components - 1; return -1; } // Function to check if it is possible // to connect all the computers or not public static void makeConnected(int N, int[,] connections, int M) { // Stores counmt of minimum // operations required int minOps = makeConnectedUtil(N, connections, M); // Print the minimum number // of operations required Console.WriteLine(minOps); } static void Main() { // Given number of computers int N = 4; // Given set of connections int[,] connections = { { 0, 1 }, { 0, 2 }, { 1, 2 } }; int M = connections.GetLength(0); // Function call to check if it is // possible to connect all computers or not makeConnected(N, connections, M); }} // This code is contributed by decode2207.
<script> // Javascript program for the above approach // Function to visit the nodes of a graph function DFS(adj, node, visited) { // If current node is already visited if (visited[node]) return; // If current node is not visited visited[node] = true; // Recurse for neighbouring nodes for(let x = 0; x < adj[node].length; x++) { // If the node is not visited if (visited[adj[node][x]] == false) DFS(adj, adj[node][x], visited); } } // Utility function to check if it is // possible to connect all computers or not function makeConnectedUtil(N, connections, M) { // Stores whether a // node is visited or not let visited = new Array(N); visited.fill(false); // Build the adjacency list let adj = new Map(); // Initialize the adjacency list for (let i = 0; i < N; i++) { adj[i] = []; } // Stores count of edges let edges = 0; // Building adjacency list // from the given edges for (let i = 0; i < M; ++i) { // Get neighbours list let l1 = adj[connections[i][0]]; let l2 = adj[connections[i][0]]; // Add edges l1.push(connections[i][1]); l2.push(connections[i][0]); // Increment count of edges edges += 1; } // Stores count of components let components = 0; for (let i = 0; i < N; ++i) { // If node is not visited if (visited[i] == false) { // Increment components components += 1; // Perform DFS DFS(adj, i, visited); } } // At least N - 1 edges are required if (edges < N - 1) return -1; // Count redundant edges let redundant = edges - ((N - 1) - (components - 1)); // Check if components can be // rearranged using redundant edges if (redundant >= (components - 1)) return components - 1; return -1; } // Function to check if it is possible // to connect all the computers or not function makeConnected(N, connections, M) { // Stores counmt of minimum // operations required let minOps = makeConnectedUtil(N, connections, M); // Print the minimum number // of operations required document.write(minOps); } // Given number of computers let N = 4; // Given set of connections let connections = [ [0, 1], [0, 2], [1, 2] ]; let M = connections.length; // Function call to check if it is // possible to connect all computers or not makeConnected(N, connections, M); // This code is contributed by sureh07.</script>
1
Time Complexity: O(N + M)Auxiliary Space: O(N)
Kingash
ipg2016107
simmytarika5
varshagumber28
decode2207
suresh07
connected-components
DFS
Minimum Spanning Tree
Graph
Greedy
Mathematical
Recursion
Greedy
Mathematical
Recursion
DFS
Graph
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n08 Oct, 2021"
},
{
"code": null,
"e": 533,
"s": 52,
"text": "Given an integer N, denoting the number of computers connected by cables forming a network and a 2D array connections[][], with each row (i, j) representing a connection between ith and jth computer, the task is to connect all the computers either directly or indirectly by removing any of the given connections and connecting two disconnected computers. If it’s not possible to connect all the computers, print -1. Otherwise, print the minimum number of such operations required."
},
{
"code": null,
"e": 543,
"s": 533,
"text": "Examples:"
},
{
"code": null,
"e": 704,
"s": 543,
"text": "Input: N = 4, connections[][] = {{0, 1}, {0, 2}, {1, 2}}Output: 1Explanation: Remove the connection between computers 1 and 2 and connect the computers 1 and 3."
},
{
"code": null,
"e": 778,
"s": 704,
"text": "Input: N = 5, connections[][] = {{0, 1}, {0, 2}, {3, 4}, {2, 3}}Output: 0"
},
{
"code": null,
"e": 950,
"s": 778,
"text": "Approach: The idea is to use a concept similar to that of Minimum Spanning Tree, as in a Graph with N nodes, only N – 1 edges are required to make all the nodes connected."
},
{
"code": null,
"e": 1035,
"s": 950,
"text": "Redundant edges = Total edges – [(Number of Nodes – 1) – (Number of components – 1)]"
},
{
"code": null,
"e": 1198,
"s": 1035,
"text": "If Redundant edges > (Number of components – 1) : It is clear that there are enough wires that can be used to connect disconnected computers. Otherwise, print -1."
},
{
"code": null,
"e": 1243,
"s": 1198,
"text": "Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 1953,
"s": 1243,
"text": "Initialize an unordered map, say adj to store the adjacency list from the given information about edges.Initialize a vector of boolean datatype, say visited, to store whether a node is visited or not.Generate the adjacency list and also calculate the number of edges.Initialize a variable, say components, to store the count of connected components.Traverse the nodes of the graph using DFS to count the number of connected components and store it in the variable components.Initialize a variable, say redundant, and store the number of redundant edges using the above formula.If redundant edges > components – 1, then the minimum number of required operations is equal to components – 1. Otherwise, print -1."
},
{
"code": null,
"e": 2058,
"s": 1953,
"text": "Initialize an unordered map, say adj to store the adjacency list from the given information about edges."
},
{
"code": null,
"e": 2155,
"s": 2058,
"text": "Initialize a vector of boolean datatype, say visited, to store whether a node is visited or not."
},
{
"code": null,
"e": 2223,
"s": 2155,
"text": "Generate the adjacency list and also calculate the number of edges."
},
{
"code": null,
"e": 2306,
"s": 2223,
"text": "Initialize a variable, say components, to store the count of connected components."
},
{
"code": null,
"e": 2433,
"s": 2306,
"text": "Traverse the nodes of the graph using DFS to count the number of connected components and store it in the variable components."
},
{
"code": null,
"e": 2536,
"s": 2433,
"text": "Initialize a variable, say redundant, and store the number of redundant edges using the above formula."
},
{
"code": null,
"e": 2669,
"s": 2536,
"text": "If redundant edges > components – 1, then the minimum number of required operations is equal to components – 1. Otherwise, print -1."
},
{
"code": null,
"e": 2720,
"s": 2669,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 2724,
"s": 2720,
"text": "C++"
},
{
"code": null,
"e": 2729,
"s": 2724,
"text": "Java"
},
{
"code": null,
"e": 2737,
"s": 2729,
"text": "Python3"
},
{
"code": null,
"e": 2740,
"s": 2737,
"text": "C#"
},
{
"code": null,
"e": 2751,
"s": 2740,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to visit the nodes of a graphvoid DFS(unordered_map<int, vector<int> >& adj, int node, vector<bool>& visited){ // If current node is already visited if (visited[node]) return; // If current node is not visited visited[node] = true; // Recurse for neighbouring nodes for (auto x : adj[node]) { // If the node is not visited if (visited[x] == false) DFS(adj, x, visited); }} // Utility function to check if it is// possible to connect all computers or notint makeConnectedUtil(int N, int connections[][2], int M){ // Stores whether a // node is visited or not vector<bool> visited(N, false); // Build the adjacency list unordered_map<int, vector<int> > adj; // Stores count of edges int edges = 0; // Building adjacency list // from the given edges for (int i = 0; i < M; ++i) { // Add edges adj[connections[i][0]].push_back( connections[i][1]); adj[connections[i][1]].push_back( connections[i][0]); // Increment count of edges edges += 1; } // Stores count of components int components = 0; for (int i = 0; i < N; ++i) { // If node is not visited if (visited[i] == false) { // Increment components components += 1; // Perform DFS DFS(adj, i, visited); } } // At least N - 1 edges are required if (edges < N - 1) return -1; // Count redundant edges int redundant = edges - ((N - 1) - (components - 1)); // Check if components can be // rearranged using redundant edges if (redundant >= (components - 1)) return components - 1; return -1;} // Function to check if it is possible// to connect all the computers or notvoid makeConnected(int N, int connections[][2], int M){ // Stores counmt of minimum // operations required int minOps = makeConnectedUtil( N, connections, M); // Print the minimum number // of operations required cout << minOps;} // Driver Codeint main(){ // Given number of computers int N = 4; // Given set of connections int connections[][2] = { { 0, 1 }, { 0, 2 }, { 1, 2 } }; int M = sizeof(connections) / sizeof(connections[0]); // Function call to check if it is // possible to connect all computers or not makeConnected(N, connections, M); return 0;}",
"e": 5348,
"s": 2751,
"text": null
},
{
"code": "// Java program for the above approachimport java.io.*;import java.util.*; class GFG { // Function to visit the nodes of a graph public static void DFS(HashMap<Integer, ArrayList<Integer> > adj, int node, boolean visited[]) { // If current node is already visited if (visited[node]) return; // If current node is not visited visited[node] = true; // Recurse for neighbouring nodes for (int x : adj.get(node)) { // If the node is not visited if (visited[x] == false) DFS(adj, x, visited); } } // Utility function to check if it is // possible to connect all computers or not public static int makeConnectedUtil(int N, int connections[][], int M) { // Stores whether a // node is visited or not boolean visited[] = new boolean[N]; // Build the adjacency list HashMap<Integer, ArrayList<Integer> > adj = new HashMap<>(); // Initialize the adjacency list for (int i = 0; i < N; i++) { adj.put(i, new ArrayList<Integer>()); } // Stores count of edges int edges = 0; // Building adjacency list // from the given edges for (int i = 0; i < M; ++i) { // Get neighbours list ArrayList<Integer> l1 = adj.get(connections[i][0]); ArrayList<Integer> l2 = adj.get(connections[i][0]); // Add edges l1.add(connections[i][1]); l2.add(connections[i][0]); // Increment count of edges edges += 1; } // Stores count of components int components = 0; for (int i = 0; i < N; ++i) { // If node is not visited if (visited[i] == false) { // Increment components components += 1; // Perform DFS DFS(adj, i, visited); } } // At least N - 1 edges are required if (edges < N - 1) return -1; // Count redundant edges int redundant = edges - ((N - 1) - (components - 1)); // Check if components can be // rearranged using redundant edges if (redundant >= (components - 1)) return components - 1; return -1; } // Function to check if it is possible // to connect all the computers or not public static void makeConnected(int N, int connections[][], int M) { // Stores counmt of minimum // operations required int minOps = makeConnectedUtil(N, connections, M); // Print the minimum number // of operations required System.out.println(minOps); } // Driver Code public static void main(String[] args) { // Given number of computers int N = 4; // Given set of connections int connections[][] = { { 0, 1 }, { 0, 2 }, { 1, 2 } }; int M = connections.length; // Function call to check if it is // possible to connect all computers or not makeConnected(N, connections, M); }} // This code is contributed by kingash.",
"e": 8588,
"s": 5348,
"text": null
},
{
"code": "# Python3 code for the above approach # Function to visit the nodes of a graphdef DFS(adj, node, visited): # If current node is already visited if (visited[node]): return # If current node is not visited visited[node] = True # Recurse for neighbouring nodes if(node in adj): for x in adj[node]: # If the node is not visited if (visited[x] == False): DFS(adj, x, visited) # Utility function to check if it is# possible to connect all computers or notdef makeConnectedUtil(N, connections, M): # Stores whether a # node is visited or not visited = [False for i in range(N)] # Build the adjacency list adj = {} # Stores count of edges edges = 0 # Building adjacency list # from the given edges for i in range(M): # Add edges if (connections[i][0] in adj): adj[connections[i][0]].append( connections[i][1]) else: adj[connections[i][0]] = [] if (connections[i][1] in adj): adj[connections[i][1]].append( connections[i][0]) else: adj[connections[i][1]] = [] # Increment count of edges edges += 1 # Stores count of components components = 0 for i in range(N): # If node is not visited if (visited[i] == False): # Increment components components += 1 # Perform DFS DFS(adj, i, visited) # At least N - 1 edges are required if (edges < N - 1): return -1 # Count redundant edges redundant = edges - ((N - 1) - (components - 1)) # Check if components can be # rearranged using redundant edges if (redundant >= (components - 1)): return components - 1 return -1 # Function to check if it is possible# to connect all the computers or notdef makeConnected(N, connections, M): # Stores counmt of minimum # operations required minOps = makeConnectedUtil(N, connections, M) # Print the minimum number # of operations required print(minOps) # Driver Codeif __name__ == '__main__': # Given number of computers N = 4 # Given set of connections connections = [ [ 0, 1 ], [ 0, 2 ], [ 1, 2 ] ] M = len(connections) # Function call to check if it is # possible to connect all computers or not makeConnected(N, connections, M) # This code is contributed by ipg2016107",
"e": 11084,
"s": 8588,
"text": null
},
{
"code": "// C# program for the above approachusing System;using System.Collections.Generic;class GFG { // Function to visit the nodes of a graph public static void DFS(Dictionary<int, List<int>> adj, int node, bool[] visited) { // If current node is already visited if (visited[node]) return; // If current node is not visited visited[node] = true; // Recurse for neighbouring nodes foreach(int x in adj[node]) { // If the node is not visited if (visited[x] == false) DFS(adj, x, visited); } } // Utility function to check if it is // possible to connect all computers or not public static int makeConnectedUtil(int N, int[,] connections, int M) { // Stores whether a // node is visited or not bool[] visited = new bool[N]; // Build the adjacency list Dictionary<int, List<int>> adj = new Dictionary<int, List<int>>(); // Initialize the adjacency list for (int i = 0; i < N; i++) { adj[i] = new List<int>(); } // Stores count of edges int edges = 0; // Building adjacency list // from the given edges for (int i = 0; i < M; ++i) { // Get neighbours list List<int> l1 = adj[connections[i,0]]; List<int> l2 = adj[connections[i,0]]; // Add edges l1.Add(connections[i,1]); l2.Add(connections[i,0]); // Increment count of edges edges += 1; } // Stores count of components int components = 0; for (int i = 0; i < N; ++i) { // If node is not visited if (visited[i] == false) { // Increment components components += 1; // Perform DFS DFS(adj, i, visited); } } // At least N - 1 edges are required if (edges < N - 1) return -1; // Count redundant edges int redundant = edges - ((N - 1) - (components - 1)); // Check if components can be // rearranged using redundant edges if (redundant >= (components - 1)) return components - 1; return -1; } // Function to check if it is possible // to connect all the computers or not public static void makeConnected(int N, int[,] connections, int M) { // Stores counmt of minimum // operations required int minOps = makeConnectedUtil(N, connections, M); // Print the minimum number // of operations required Console.WriteLine(minOps); } static void Main() { // Given number of computers int N = 4; // Given set of connections int[,] connections = { { 0, 1 }, { 0, 2 }, { 1, 2 } }; int M = connections.GetLength(0); // Function call to check if it is // possible to connect all computers or not makeConnected(N, connections, M); }} // This code is contributed by decode2207.",
"e": 14145,
"s": 11084,
"text": null
},
{
"code": "<script> // Javascript program for the above approach // Function to visit the nodes of a graph function DFS(adj, node, visited) { // If current node is already visited if (visited[node]) return; // If current node is not visited visited[node] = true; // Recurse for neighbouring nodes for(let x = 0; x < adj[node].length; x++) { // If the node is not visited if (visited[adj[node][x]] == false) DFS(adj, adj[node][x], visited); } } // Utility function to check if it is // possible to connect all computers or not function makeConnectedUtil(N, connections, M) { // Stores whether a // node is visited or not let visited = new Array(N); visited.fill(false); // Build the adjacency list let adj = new Map(); // Initialize the adjacency list for (let i = 0; i < N; i++) { adj[i] = []; } // Stores count of edges let edges = 0; // Building adjacency list // from the given edges for (let i = 0; i < M; ++i) { // Get neighbours list let l1 = adj[connections[i][0]]; let l2 = adj[connections[i][0]]; // Add edges l1.push(connections[i][1]); l2.push(connections[i][0]); // Increment count of edges edges += 1; } // Stores count of components let components = 0; for (let i = 0; i < N; ++i) { // If node is not visited if (visited[i] == false) { // Increment components components += 1; // Perform DFS DFS(adj, i, visited); } } // At least N - 1 edges are required if (edges < N - 1) return -1; // Count redundant edges let redundant = edges - ((N - 1) - (components - 1)); // Check if components can be // rearranged using redundant edges if (redundant >= (components - 1)) return components - 1; return -1; } // Function to check if it is possible // to connect all the computers or not function makeConnected(N, connections, M) { // Stores counmt of minimum // operations required let minOps = makeConnectedUtil(N, connections, M); // Print the minimum number // of operations required document.write(minOps); } // Given number of computers let N = 4; // Given set of connections let connections = [ [0, 1], [0, 2], [1, 2] ]; let M = connections.length; // Function call to check if it is // possible to connect all computers or not makeConnected(N, connections, M); // This code is contributed by sureh07.</script>",
"e": 17050,
"s": 14145,
"text": null
},
{
"code": null,
"e": 17052,
"s": 17050,
"text": "1"
},
{
"code": null,
"e": 17101,
"s": 17054,
"text": "Time Complexity: O(N + M)Auxiliary Space: O(N)"
},
{
"code": null,
"e": 17111,
"s": 17103,
"text": "Kingash"
},
{
"code": null,
"e": 17122,
"s": 17111,
"text": "ipg2016107"
},
{
"code": null,
"e": 17135,
"s": 17122,
"text": "simmytarika5"
},
{
"code": null,
"e": 17150,
"s": 17135,
"text": "varshagumber28"
},
{
"code": null,
"e": 17161,
"s": 17150,
"text": "decode2207"
},
{
"code": null,
"e": 17170,
"s": 17161,
"text": "suresh07"
},
{
"code": null,
"e": 17191,
"s": 17170,
"text": "connected-components"
},
{
"code": null,
"e": 17195,
"s": 17191,
"text": "DFS"
},
{
"code": null,
"e": 17217,
"s": 17195,
"text": "Minimum Spanning Tree"
},
{
"code": null,
"e": 17223,
"s": 17217,
"text": "Graph"
},
{
"code": null,
"e": 17230,
"s": 17223,
"text": "Greedy"
},
{
"code": null,
"e": 17243,
"s": 17230,
"text": "Mathematical"
},
{
"code": null,
"e": 17253,
"s": 17243,
"text": "Recursion"
},
{
"code": null,
"e": 17260,
"s": 17253,
"text": "Greedy"
},
{
"code": null,
"e": 17273,
"s": 17260,
"text": "Mathematical"
},
{
"code": null,
"e": 17283,
"s": 17273,
"text": "Recursion"
},
{
"code": null,
"e": 17287,
"s": 17283,
"text": "DFS"
},
{
"code": null,
"e": 17293,
"s": 17287,
"text": "Graph"
}
] |
Mapping external values to dataframe values in Pandas
|
08 Jan, 2019
Mapping external value to a dataframe means using different sets of values to add in that dataframe by keeping the keys of external dictionary as same as the one column of that dataframe.
To add external values in dataframe, we use dictionary which has keys and values which we want to add in the dataframe. By adding external values in the dataframe one column will be added to the current dataframe. We can also map or combine one dataframe to other dataframe with the help of pandas.
Method #1: Using mapping function
By using this mapping function we can add one more column to an existing dataframe. Just keep in mind that no key values will be repeated it will make the data inconsistent.
# Creating new dataframeimport pandas as pd initial_data = {'First_name': ['Ram', 'Mohan', 'Tina', 'Jeetu', 'Meera'], 'Last_name': ['Kumar', 'Sharma', 'Ali', 'Gandhi', 'Kumari'], 'Age': [42, 52, 36, 21, 23], 'City': ['Mumbai', 'Noida', 'Pune', 'Delhi', 'Bihar']} df = pd.DataFrame(initial_data, columns = ['First_name', 'Last_name', 'Age', 'City']) # Create new column using dictionarynew_data = { "Ram":"B.Com", "Mohan":"IAS", "Tina":"LLB", "Jeetu":"B.Tech", "Meera":"MBBS" } # combine this new data with existing DataFramedf["Qualification"] = df["First_name"].map(new_data) print(df)
First_name Last_name Age City Qualification
0 Ram Kumar 42 Mumbai B.Com
1 Mohan Sharma 52 Noida IAS
2 Tina Ali 36 Pune LLB
3 Jeetu Gandhi 21 Delhi B.Tech
4 Meera Kumari 23 Bihar MBBS
Method #2: Using replace function
In this method, we can add or replace some of the value of the dataframe by some defined external values.
# Creating new dataframeimport pandas as pdinitial_data = {'First_name': ['Ram', 'Mohan', 'Tina', 'Jeetu', 'Meera'], 'Last_name': ['Kumar', 'Sharma', 'Ali', 'Gandhi', 'Kumari'], 'Age': [42, 52, 36, 21, 23], 'City': ['Mumbai', 'Noida', 'Pune', 'Delhi', 'Bihar']} df = pd.DataFrame(initial_data, columns = ['First_name', 'Last_name', 'Age', 'City']) # Create new column using dictionarynew_data = { "Ram":"Shyam", "Tina":"Riya", "Jeetu":"Jitender" } print(df, end ="\n\n") # combine this new data with existing DataFramedf = df.replace({"First_name":new_data})print(df)
First_name Last_name Age City
0 Ram Kumar 42 Mumbai
1 Mohan Sharma 52 Noida
2 Tina Ali 36 Pune
3 Jeetu Gandhi 21 Delhi
4 Meera Kumari 23 Bihar
First_name Last_name Age City
0 Shyam Kumar 42 Mumbai
1 Mohan Sharma 52 Noida
2 Riya Ali 36 Pune
3 Jitender Gandhi 21 Delhi
4 Meera Kumari 23 Bihar
Method #3: Using update function
In this method we can update the dataframe values by using index values we can change the value of columns by external data.
# Creating new dataframeimport pandas as pd initial_data = {'First_name': ['Ram', 'Mohan', 'Tina', 'Jeetu', 'Meera'], 'Last_name': ['Kumar', 'Sharma', 'Ali', 'Gandhi', 'Kumari'], 'Age': [42, 52, 36, 21, 23], 'City': ['Mumbai', 'Noida', 'Pune', 'Delhi', 'Bihar']} df = pd.DataFrame(initial_data, columns = ['First_name', 'Last_name', 'Age', 'City']) # Create new column using dictionarynew_data = { 0:"Shyam", 2:"Riya", 3:"Jitender" } # combine this new data with existing DataFramedf["First_name"].update(pd.Series(new_data))print(df)
First_name Last_name Age City
0 Shyam Kumar 42 Mumbai
1 Mohan Sharma 52 Noida
2 Riya Ali 36 Pune
3 Jitender Gandhi 21 Delhi
4 Meera Kumari 23 Bihar
pandas-dataframe-program
Picked
Python pandas-dataFrame
Python-pandas
Technical Scripter 2018
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to iterate through Excel rows in Python?
Deque in Python
Defaultdict in Python
Queue in Python
Rotate axis tick labels in Seaborn and Matplotlib
Check if element exists in list in Python
Python Classes and Objects
Bar Plot in Matplotlib
Python OOPs Concepts
How To Convert Python Dictionary To JSON?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n08 Jan, 2019"
},
{
"code": null,
"e": 216,
"s": 28,
"text": "Mapping external value to a dataframe means using different sets of values to add in that dataframe by keeping the keys of external dictionary as same as the one column of that dataframe."
},
{
"code": null,
"e": 515,
"s": 216,
"text": "To add external values in dataframe, we use dictionary which has keys and values which we want to add in the dataframe. By adding external values in the dataframe one column will be added to the current dataframe. We can also map or combine one dataframe to other dataframe with the help of pandas."
},
{
"code": null,
"e": 549,
"s": 515,
"text": "Method #1: Using mapping function"
},
{
"code": null,
"e": 723,
"s": 549,
"text": "By using this mapping function we can add one more column to an existing dataframe. Just keep in mind that no key values will be repeated it will make the data inconsistent."
},
{
"code": "# Creating new dataframeimport pandas as pd initial_data = {'First_name': ['Ram', 'Mohan', 'Tina', 'Jeetu', 'Meera'], 'Last_name': ['Kumar', 'Sharma', 'Ali', 'Gandhi', 'Kumari'], 'Age': [42, 52, 36, 21, 23], 'City': ['Mumbai', 'Noida', 'Pune', 'Delhi', 'Bihar']} df = pd.DataFrame(initial_data, columns = ['First_name', 'Last_name', 'Age', 'City']) # Create new column using dictionarynew_data = { \"Ram\":\"B.Com\", \"Mohan\":\"IAS\", \"Tina\":\"LLB\", \"Jeetu\":\"B.Tech\", \"Meera\":\"MBBS\" } # combine this new data with existing DataFramedf[\"Qualification\"] = df[\"First_name\"].map(new_data) print(df)",
"e": 1440,
"s": 723,
"text": null
},
{
"code": null,
"e": 1742,
"s": 1440,
"text": "First_name Last_name Age City Qualification\n0 Ram Kumar 42 Mumbai B.Com\n1 Mohan Sharma 52 Noida IAS\n2 Tina Ali 36 Pune LLB\n3 Jeetu Gandhi 21 Delhi B.Tech\n4 Meera Kumari 23 Bihar MBBS\n"
},
{
"code": null,
"e": 1777,
"s": 1742,
"text": " Method #2: Using replace function"
},
{
"code": null,
"e": 1883,
"s": 1777,
"text": "In this method, we can add or replace some of the value of the dataframe by some defined external values."
},
{
"code": "# Creating new dataframeimport pandas as pdinitial_data = {'First_name': ['Ram', 'Mohan', 'Tina', 'Jeetu', 'Meera'], 'Last_name': ['Kumar', 'Sharma', 'Ali', 'Gandhi', 'Kumari'], 'Age': [42, 52, 36, 21, 23], 'City': ['Mumbai', 'Noida', 'Pune', 'Delhi', 'Bihar']} df = pd.DataFrame(initial_data, columns = ['First_name', 'Last_name', 'Age', 'City']) # Create new column using dictionarynew_data = { \"Ram\":\"Shyam\", \"Tina\":\"Riya\", \"Jeetu\":\"Jitender\" } print(df, end =\"\\n\\n\") # combine this new data with existing DataFramedf = df.replace({\"First_name\":new_data})print(df)",
"e": 2580,
"s": 1883,
"text": null
},
{
"code": null,
"e": 3012,
"s": 2580,
"text": "First_name Last_name Age City\n0 Ram Kumar 42 Mumbai\n1 Mohan Sharma 52 Noida\n2 Tina Ali 36 Pune\n3 Jeetu Gandhi 21 Delhi\n4 Meera Kumari 23 Bihar\n\n First_name Last_name Age City\n0 Shyam Kumar 42 Mumbai\n1 Mohan Sharma 52 Noida\n2 Riya Ali 36 Pune\n3 Jitender Gandhi 21 Delhi\n4 Meera Kumari 23 Bihar\n"
},
{
"code": null,
"e": 3046,
"s": 3012,
"text": " Method #3: Using update function"
},
{
"code": null,
"e": 3171,
"s": 3046,
"text": "In this method we can update the dataframe values by using index values we can change the value of columns by external data."
},
{
"code": "# Creating new dataframeimport pandas as pd initial_data = {'First_name': ['Ram', 'Mohan', 'Tina', 'Jeetu', 'Meera'], 'Last_name': ['Kumar', 'Sharma', 'Ali', 'Gandhi', 'Kumari'], 'Age': [42, 52, 36, 21, 23], 'City': ['Mumbai', 'Noida', 'Pune', 'Delhi', 'Bihar']} df = pd.DataFrame(initial_data, columns = ['First_name', 'Last_name', 'Age', 'City']) # Create new column using dictionarynew_data = { 0:\"Shyam\", 2:\"Riya\", 3:\"Jitender\" } # combine this new data with existing DataFramedf[\"First_name\"].update(pd.Series(new_data))print(df)",
"e": 3835,
"s": 3171,
"text": null
},
{
"code": null,
"e": 4050,
"s": 3835,
"text": "First_name Last_name Age City\n0 Shyam Kumar 42 Mumbai\n1 Mohan Sharma 52 Noida\n2 Riya Ali 36 Pune\n3 Jitender Gandhi 21 Delhi\n4 Meera Kumari 23 Bihar\n"
},
{
"code": null,
"e": 4075,
"s": 4050,
"text": "pandas-dataframe-program"
},
{
"code": null,
"e": 4082,
"s": 4075,
"text": "Picked"
},
{
"code": null,
"e": 4106,
"s": 4082,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 4120,
"s": 4106,
"text": "Python-pandas"
},
{
"code": null,
"e": 4144,
"s": 4120,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 4151,
"s": 4144,
"text": "Python"
},
{
"code": null,
"e": 4170,
"s": 4151,
"text": "Technical Scripter"
},
{
"code": null,
"e": 4268,
"s": 4170,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4313,
"s": 4268,
"text": "How to iterate through Excel rows in Python?"
},
{
"code": null,
"e": 4329,
"s": 4313,
"text": "Deque in Python"
},
{
"code": null,
"e": 4351,
"s": 4329,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 4367,
"s": 4351,
"text": "Queue in Python"
},
{
"code": null,
"e": 4417,
"s": 4367,
"text": "Rotate axis tick labels in Seaborn and Matplotlib"
},
{
"code": null,
"e": 4459,
"s": 4417,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 4486,
"s": 4459,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 4509,
"s": 4486,
"text": "Bar Plot in Matplotlib"
},
{
"code": null,
"e": 4530,
"s": 4509,
"text": "Python OOPs Concepts"
}
] |
How to define an array class in C#?
|
The Array class is the base class for all the arrays in C#. It is defined in the System namespace and has the following properties −
To define an array class, you can try to run the following code, wherein we are sorting an array −
Live Demo
using System;
namespace Demo {
class MyArray {
static void Main(string[] args) {
int[] list = { 45, 19, 9, 28, 87};
int[] temp = list;
Console.Write("Original Array: ");
foreach (int i in list) {
Console.Write(i + " ");
}
Console.WriteLine();
Array.Sort(list);
Console.Write("Sorted Array: ");
foreach (int i in list) {
Console.Write(i + " ");
}
Console.WriteLine();
Console.ReadKey();
}
}
}
Original Array: 45 19 9 28 87
Sorted Array: 9 19 28 45 87
|
[
{
"code": null,
"e": 1320,
"s": 1187,
"text": "The Array class is the base class for all the arrays in C#. It is defined in the System namespace and has the following properties −"
},
{
"code": null,
"e": 1419,
"s": 1320,
"text": "To define an array class, you can try to run the following code, wherein we are sorting an array −"
},
{
"code": null,
"e": 1430,
"s": 1419,
"text": " Live Demo"
},
{
"code": null,
"e": 1976,
"s": 1430,
"text": "using System;\n\nnamespace Demo {\n class MyArray {\n static void Main(string[] args) {\n int[] list = { 45, 19, 9, 28, 87};\n int[] temp = list;\n Console.Write(\"Original Array: \");\n\n foreach (int i in list) {\n Console.Write(i + \" \");\n }\n Console.WriteLine();\n\n Array.Sort(list);\n Console.Write(\"Sorted Array: \");\n\n foreach (int i in list) {\n Console.Write(i + \" \");\n }\n Console.WriteLine();\n Console.ReadKey();\n }\n }\n}"
},
{
"code": null,
"e": 2034,
"s": 1976,
"text": "Original Array: 45 19 9 28 87\nSorted Array: 9 19 28 45 87"
}
] |
Python | Pandas Series.dt.floor
|
20 Mar, 2019
Series.dt can be used to access the values of the series as datetimelike and return several properties. Pandas Series.dt.floor() function perform floor operation on the data to the specified freq.
Syntax: Series.dt.floor(*args, **kwargs)
Parameter :freq : The frequency level to floor the index to
Returns : DatetimeIndex, TimedeltaIndex, or Series
Example #1: Use Series.dt.floor() function to floor the datetime data of the given series object to the specified frequency.
# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['2012-12-31 08:45', '2019-1-1 12:30', '2008-02-2 10:30', '2010-1-1 09:25', '2019-12-31 00:00']) # Creating the indexidx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] # set the indexsr.index = idx # Convert the underlying data to datetime sr = pd.to_datetime(sr) # Print the seriesprint(sr)
Output :
Now we will use Series.dt.floor() function to floor the datetime values in the given series object to Daily frequency.
# floor to daily frequencyresult = sr.dt.floor(freq = 'D') # print the resultprint(result)
Output :
As we can see in the output, the Series.dt.floor() function has successfully floored the datetime values in the given series object to the specified frequency.
Example #2 : Use Series.dt.floor() function to floor the datetime data of the given series object to the specified frequency.
# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(pd.date_range('2012-12-31 09:45', periods = 5, freq = 'T', tz = 'Asia / Calcutta')) # Creating the indexidx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] # set the indexsr.index = idx # Print the seriesprint(sr)
Output :
Now we will use Series.dt.floor() function to floor the datetime values in the given series object to Hourly frequency.
# floor to hourly frequencyresult = sr.dt.floor(freq = 'H') # print the resultprint(result)
Output :
As we can see in the output, the Series.dt.floor() function has successfully floored the datetime values in the given series object to the specified frequency.
Python pandas-series-datetime
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n20 Mar, 2019"
},
{
"code": null,
"e": 225,
"s": 28,
"text": "Series.dt can be used to access the values of the series as datetimelike and return several properties. Pandas Series.dt.floor() function perform floor operation on the data to the specified freq."
},
{
"code": null,
"e": 266,
"s": 225,
"text": "Syntax: Series.dt.floor(*args, **kwargs)"
},
{
"code": null,
"e": 326,
"s": 266,
"text": "Parameter :freq : The frequency level to floor the index to"
},
{
"code": null,
"e": 377,
"s": 326,
"text": "Returns : DatetimeIndex, TimedeltaIndex, or Series"
},
{
"code": null,
"e": 502,
"s": 377,
"text": "Example #1: Use Series.dt.floor() function to floor the datetime data of the given series object to the specified frequency."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['2012-12-31 08:45', '2019-1-1 12:30', '2008-02-2 10:30', '2010-1-1 09:25', '2019-12-31 00:00']) # Creating the indexidx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] # set the indexsr.index = idx # Convert the underlying data to datetime sr = pd.to_datetime(sr) # Print the seriesprint(sr)",
"e": 894,
"s": 502,
"text": null
},
{
"code": null,
"e": 903,
"s": 894,
"text": "Output :"
},
{
"code": null,
"e": 1022,
"s": 903,
"text": "Now we will use Series.dt.floor() function to floor the datetime values in the given series object to Daily frequency."
},
{
"code": "# floor to daily frequencyresult = sr.dt.floor(freq = 'D') # print the resultprint(result)",
"e": 1114,
"s": 1022,
"text": null
},
{
"code": null,
"e": 1123,
"s": 1114,
"text": "Output :"
},
{
"code": null,
"e": 1283,
"s": 1123,
"text": "As we can see in the output, the Series.dt.floor() function has successfully floored the datetime values in the given series object to the specified frequency."
},
{
"code": null,
"e": 1409,
"s": 1283,
"text": "Example #2 : Use Series.dt.floor() function to floor the datetime data of the given series object to the specified frequency."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(pd.date_range('2012-12-31 09:45', periods = 5, freq = 'T', tz = 'Asia / Calcutta')) # Creating the indexidx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] # set the indexsr.index = idx # Print the seriesprint(sr)",
"e": 1734,
"s": 1409,
"text": null
},
{
"code": null,
"e": 1743,
"s": 1734,
"text": "Output :"
},
{
"code": null,
"e": 1863,
"s": 1743,
"text": "Now we will use Series.dt.floor() function to floor the datetime values in the given series object to Hourly frequency."
},
{
"code": "# floor to hourly frequencyresult = sr.dt.floor(freq = 'H') # print the resultprint(result)",
"e": 1956,
"s": 1863,
"text": null
},
{
"code": null,
"e": 1965,
"s": 1956,
"text": "Output :"
},
{
"code": null,
"e": 2125,
"s": 1965,
"text": "As we can see in the output, the Series.dt.floor() function has successfully floored the datetime values in the given series object to the specified frequency."
},
{
"code": null,
"e": 2155,
"s": 2125,
"text": "Python pandas-series-datetime"
},
{
"code": null,
"e": 2169,
"s": 2155,
"text": "Python-pandas"
},
{
"code": null,
"e": 2176,
"s": 2169,
"text": "Python"
}
] |
Number of subsequences in a string divisible by n
|
22 Apr, 2021
Given a string consisting of digits 0-9, count the number of subsequences in it divisible by m.Examples:
Input : str = "1234", n = 4
Output : 4
The subsequences 4, 12, 24 and 124 are
divisible by 4.
Input : str = "330", n = 6
Output : 4
The subsequences 30, 30, 330 and 0 are
divisible by n.
Input : str = "676", n = 6
Output : 3
The subsequences 6, 6 and 66
This problem can be recursively defined. Let remainder of a string with value x be ‘r’ when divided with n. Adding one more character to this string changes its remainder to (r*10 + newdigit) % n. For every new character, we have two choices, either add it in all current subsequences or ignore it. Thus, we have an optimal substructure. Following shows the brute force version of this:
string str = "330";
int n = 6
// idx is value of current index in str
// rem is current remainder
int count(int idx, int rem)
{
// If last character reached
if (idx == n)
return (rem == 0)? 1 : 0;
int ans = 0;
// we exclude it, thus remainder
// remains the same
ans += count(idx+1, rem);
// we include it and thus new remainder
ans += count(idx+1, (rem*10 + str[idx]-'0')%n);
return ans;
}
The above recursive solution has overlapping subproblems as shown in below recursion tree.
input string = "330"
(0,0) ===> at 0th index with 0 remainder
(exclude 0th / (include 0th character)
character) /
(1,0) (1,3) ======> at index 1 with 3 as
(E)/ (I) /(E) the current remainder
(2,0) (2,3) (2,3)
|-------|
These two subproblems overlap
Thus, we can apply Dynamic Programming. Below is implementation .
C++
Java
Python 3
C#
Javascript
// C++ program to count subsequences of a// string divisible by n.#include<bits/stdc++.h>using namespace std; // Returns count of subsequences of str// divisible by n.int countDivisibleSubseq(string str, int n){ int len = str.length(); // division by n can leave only n remainder // [0..n-1]. dp[i][j] indicates number of // subsequences in string [0..i] which leaves // remainder j after division by n. int dp[len][n]; memset(dp, 0, sizeof(dp)); // Filling value for first digit in str dp[0][(str[0]-'0')%n]++; for (int i=1; i<len; i++) { // start a new subsequence with index i dp[i][(str[i]-'0')%n]++; for (int j=0; j<n; j++) { // exclude i'th character from all the // current subsequences of string [0...i-1] dp[i][j] += dp[i-1][j]; // include i'th character in all the current // subsequences of string [0...i-1] dp[i][(j*10 + (str[i]-'0'))%n] += dp[i-1][j]; } } return dp[len-1][0];} // Driver codeint main(){ string str = "1234"; int n = 4; cout << countDivisibleSubseq(str, n); return 0;}
//Java program to count subsequences of a// string divisible by n class GFG { // Returns count of subsequences of str// divisible by n. static int countDivisibleSubseq(String str, int n) { int len = str.length(); // division by n can leave only n remainder // [0..n-1]. dp[i][j] indicates number of // subsequences in string [0..i] which leaves // remainder j after division by n. int dp[][] = new int[len][n]; // Filling value for first digit in str dp[0][(str.charAt(0) - '0') % n]++; for (int i = 1; i < len; i++) { // start a new subsequence with index i dp[i][(str.charAt(i) - '0') % n]++; for (int j = 0; j < n; j++) { // exclude i'th character from all the // current subsequences of string [0...i-1] dp[i][j] += dp[i - 1][j]; // include i'th character in all the current // subsequences of string [0...i-1] dp[i][(j * 10 + (str.charAt(i) - '0')) % n] += dp[i - 1][j]; } } return dp[len - 1][0]; } // Driver code public static void main(String[] args) { String str = "1234"; int n = 4; System.out.print(countDivisibleSubseq(str, n)); }}// This code is contributed by 29AjayKumar
# Python 3 program to count subsequences# of a string divisible by n. # Returns count of subsequences of# str divisible by n.def countDivisibleSubseq(str, n): l = len(str) # division by n can leave only n remainder # [0..n-1]. dp[i][j] indicates number of # subsequences in string [0..i] which leaves # remainder j after division by n. dp = [[0 for x in range(l)] for y in range(n)] # Filling value for first digit in str dp[0][(ord(str[0]) - ord('0')) % n] += 1 for i in range(1, l): # start a new subsequence with index i dp[i][(ord(str[i]) - ord('0')) % n] += 1 for j in range(n): # exclude i'th character from all the # current subsequences of string [0...i-1] dp[i][j] += dp[i - 1][j] # include i'th character in all the current # subsequences of string [0...i-1] dp[i][(j * 10 + (ord(str[i]) - ord('0'))) % n] += dp[i - 1][j] return dp[l - 1][0] # Driver codeif __name__ == "__main__": str = "1234" n = 4 print(countDivisibleSubseq(str, n)) # This code is contributed by ita_c
//C# program to count subsequences of a// string divisible by n using System;class GFG { // Returns count of subsequences of str// divisible by n. static int countDivisibleSubseq(string str, int n) { int len = str.Length; // division by n can leave only n remainder // [0..n-1]. dp[i][j] indicates number of // subsequences in string [0..i] which leaves // remainder j after division by n. int[,] dp = new int[len,n]; // Filling value for first digit in str dp[0,(str[0] - '0') % n]++; for (int i = 1; i < len; i++) { // start a new subsequence with index i dp[i,(str[i] - '0') % n]++; for (int j = 0; j < n; j++) { // exclude i'th character from all the // current subsequences of string [0...i-1] dp[i,j] += dp[i - 1,j]; // include i'th character in all the current // subsequences of string [0...i-1] dp[i,(j * 10 + (str[i] - '0')) % n] += dp[i - 1,j]; } } return dp[len - 1,0]; } // Driver code public static void Main() { String str = "1234"; int n = 4; Console.Write(countDivisibleSubseq(str, n)); }}
<script>//Javascript program to count subsequences of a// string divisible by n // Returns count of subsequences of str // divisible by n. function countDivisibleSubseq(str,n) { let len = str.length; // division by n can leave only n remainder // [0..n-1]. dp[i][j] indicates number of // subsequences in string [0..i] which leaves // remainder j after division by n. let dp = new Array(len); for(let i = 0; i < len; i++) { dp[i] = new Array(n); for(let j = 0; j < n; j++) { dp[i][j] = 0; } } // Filling value for first digit in str dp[0][(str[0] - '0') % n]++; for (let i = 1; i < len; i++) { // start a new subsequence with index i dp[i][(str[i] - '0') % n]++; for (let j = 0; j < n; j++) { // exclude i'th character from all the // current subsequences of string [0...i-1] dp[i][j] += dp[i - 1][j]; // include i'th character in all the current // subsequences of string [0...i-1] dp[i][(j * 10 + (str[i] - '0')) % n] += dp[i - 1][j]; } } return dp[len - 1][0]; } // Driver code let str = "1234"; let n = 4; document.write(countDivisibleSubseq(str, n)); // This code is contributed by avanitrachhadiya2155</script>
Output:
4
Time Complexity : O(len * n) Auxiliary Space : O(len * n)This article is contributed by Ekta Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
29AjayKumar
ukasp
ManasChhabra2
avanitrachhadiya2155
divisibility
Modular Arithmetic
subsequence
Dynamic Programming
Dynamic Programming
Modular Arithmetic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n22 Apr, 2021"
},
{
"code": null,
"e": 159,
"s": 52,
"text": "Given a string consisting of digits 0-9, count the number of subsequences in it divisible by m.Examples: "
},
{
"code": null,
"e": 421,
"s": 159,
"text": "Input : str = \"1234\", n = 4\nOutput : 4\nThe subsequences 4, 12, 24 and 124 are \ndivisible by 4.\n \nInput : str = \"330\", n = 6\nOutput : 4\nThe subsequences 30, 30, 330 and 0 are \ndivisible by n.\n\nInput : str = \"676\", n = 6\nOutput : 3\nThe subsequences 6, 6 and 66"
},
{
"code": null,
"e": 811,
"s": 423,
"text": "This problem can be recursively defined. Let remainder of a string with value x be ‘r’ when divided with n. Adding one more character to this string changes its remainder to (r*10 + newdigit) % n. For every new character, we have two choices, either add it in all current subsequences or ignore it. Thus, we have an optimal substructure. Following shows the brute force version of this: "
},
{
"code": null,
"e": 1251,
"s": 811,
"text": "string str = \"330\";\nint n = 6\n\n// idx is value of current index in str\n// rem is current remainder\nint count(int idx, int rem)\n{\n // If last character reached\n if (idx == n)\n return (rem == 0)? 1 : 0;\n\n int ans = 0;\n\n // we exclude it, thus remainder\n // remains the same\n ans += count(idx+1, rem);\n\n // we include it and thus new remainder\n ans += count(idx+1, (rem*10 + str[idx]-'0')%n);\n\n return ans;\n}"
},
{
"code": null,
"e": 1343,
"s": 1251,
"text": "The above recursive solution has overlapping subproblems as shown in below recursion tree. "
},
{
"code": null,
"e": 1685,
"s": 1343,
"text": " input string = \"330\"\n (0,0) ===> at 0th index with 0 remainder\n(exclude 0th / (include 0th character)\n character) / \n (1,0) (1,3) ======> at index 1 with 3 as \n (E)/ (I) /(E) the current remainder\n (2,0) (2,3) (2,3)\n |-------|\n These two subproblems overlap "
},
{
"code": null,
"e": 1752,
"s": 1685,
"text": "Thus, we can apply Dynamic Programming. Below is implementation . "
},
{
"code": null,
"e": 1756,
"s": 1752,
"text": "C++"
},
{
"code": null,
"e": 1761,
"s": 1756,
"text": "Java"
},
{
"code": null,
"e": 1770,
"s": 1761,
"text": "Python 3"
},
{
"code": null,
"e": 1773,
"s": 1770,
"text": "C#"
},
{
"code": null,
"e": 1784,
"s": 1773,
"text": "Javascript"
},
{
"code": "// C++ program to count subsequences of a// string divisible by n.#include<bits/stdc++.h>using namespace std; // Returns count of subsequences of str// divisible by n.int countDivisibleSubseq(string str, int n){ int len = str.length(); // division by n can leave only n remainder // [0..n-1]. dp[i][j] indicates number of // subsequences in string [0..i] which leaves // remainder j after division by n. int dp[len][n]; memset(dp, 0, sizeof(dp)); // Filling value for first digit in str dp[0][(str[0]-'0')%n]++; for (int i=1; i<len; i++) { // start a new subsequence with index i dp[i][(str[i]-'0')%n]++; for (int j=0; j<n; j++) { // exclude i'th character from all the // current subsequences of string [0...i-1] dp[i][j] += dp[i-1][j]; // include i'th character in all the current // subsequences of string [0...i-1] dp[i][(j*10 + (str[i]-'0'))%n] += dp[i-1][j]; } } return dp[len-1][0];} // Driver codeint main(){ string str = \"1234\"; int n = 4; cout << countDivisibleSubseq(str, n); return 0;}",
"e": 2940,
"s": 1784,
"text": null
},
{
"code": "//Java program to count subsequences of a// string divisible by n class GFG { // Returns count of subsequences of str// divisible by n. static int countDivisibleSubseq(String str, int n) { int len = str.length(); // division by n can leave only n remainder // [0..n-1]. dp[i][j] indicates number of // subsequences in string [0..i] which leaves // remainder j after division by n. int dp[][] = new int[len][n]; // Filling value for first digit in str dp[0][(str.charAt(0) - '0') % n]++; for (int i = 1; i < len; i++) { // start a new subsequence with index i dp[i][(str.charAt(i) - '0') % n]++; for (int j = 0; j < n; j++) { // exclude i'th character from all the // current subsequences of string [0...i-1] dp[i][j] += dp[i - 1][j]; // include i'th character in all the current // subsequences of string [0...i-1] dp[i][(j * 10 + (str.charAt(i) - '0')) % n] += dp[i - 1][j]; } } return dp[len - 1][0]; } // Driver code public static void main(String[] args) { String str = \"1234\"; int n = 4; System.out.print(countDivisibleSubseq(str, n)); }}// This code is contributed by 29AjayKumar",
"e": 4276,
"s": 2940,
"text": null
},
{
"code": "# Python 3 program to count subsequences# of a string divisible by n. # Returns count of subsequences of# str divisible by n.def countDivisibleSubseq(str, n): l = len(str) # division by n can leave only n remainder # [0..n-1]. dp[i][j] indicates number of # subsequences in string [0..i] which leaves # remainder j after division by n. dp = [[0 for x in range(l)] for y in range(n)] # Filling value for first digit in str dp[0][(ord(str[0]) - ord('0')) % n] += 1 for i in range(1, l): # start a new subsequence with index i dp[i][(ord(str[i]) - ord('0')) % n] += 1 for j in range(n): # exclude i'th character from all the # current subsequences of string [0...i-1] dp[i][j] += dp[i - 1][j] # include i'th character in all the current # subsequences of string [0...i-1] dp[i][(j * 10 + (ord(str[i]) - ord('0'))) % n] += dp[i - 1][j] return dp[l - 1][0] # Driver codeif __name__ == \"__main__\": str = \"1234\" n = 4 print(countDivisibleSubseq(str, n)) # This code is contributed by ita_c",
"e": 5450,
"s": 4276,
"text": null
},
{
"code": "//C# program to count subsequences of a// string divisible by n using System;class GFG { // Returns count of subsequences of str// divisible by n. static int countDivisibleSubseq(string str, int n) { int len = str.Length; // division by n can leave only n remainder // [0..n-1]. dp[i][j] indicates number of // subsequences in string [0..i] which leaves // remainder j after division by n. int[,] dp = new int[len,n]; // Filling value for first digit in str dp[0,(str[0] - '0') % n]++; for (int i = 1; i < len; i++) { // start a new subsequence with index i dp[i,(str[i] - '0') % n]++; for (int j = 0; j < n; j++) { // exclude i'th character from all the // current subsequences of string [0...i-1] dp[i,j] += dp[i - 1,j]; // include i'th character in all the current // subsequences of string [0...i-1] dp[i,(j * 10 + (str[i] - '0')) % n] += dp[i - 1,j]; } } return dp[len - 1,0]; } // Driver code public static void Main() { String str = \"1234\"; int n = 4; Console.Write(countDivisibleSubseq(str, n)); }}",
"e": 6716,
"s": 5450,
"text": null
},
{
"code": "<script>//Javascript program to count subsequences of a// string divisible by n // Returns count of subsequences of str // divisible by n. function countDivisibleSubseq(str,n) { let len = str.length; // division by n can leave only n remainder // [0..n-1]. dp[i][j] indicates number of // subsequences in string [0..i] which leaves // remainder j after division by n. let dp = new Array(len); for(let i = 0; i < len; i++) { dp[i] = new Array(n); for(let j = 0; j < n; j++) { dp[i][j] = 0; } } // Filling value for first digit in str dp[0][(str[0] - '0') % n]++; for (let i = 1; i < len; i++) { // start a new subsequence with index i dp[i][(str[i] - '0') % n]++; for (let j = 0; j < n; j++) { // exclude i'th character from all the // current subsequences of string [0...i-1] dp[i][j] += dp[i - 1][j]; // include i'th character in all the current // subsequences of string [0...i-1] dp[i][(j * 10 + (str[i] - '0')) % n] += dp[i - 1][j]; } } return dp[len - 1][0]; } // Driver code let str = \"1234\"; let n = 4; document.write(countDivisibleSubseq(str, n)); // This code is contributed by avanitrachhadiya2155</script>",
"e": 8187,
"s": 6716,
"text": null
},
{
"code": null,
"e": 8197,
"s": 8187,
"text": "Output: "
},
{
"code": null,
"e": 8199,
"s": 8197,
"text": "4"
},
{
"code": null,
"e": 8674,
"s": 8199,
"text": "Time Complexity : O(len * n) Auxiliary Space : O(len * n)This article is contributed by Ekta Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. 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": 8686,
"s": 8674,
"text": "29AjayKumar"
},
{
"code": null,
"e": 8692,
"s": 8686,
"text": "ukasp"
},
{
"code": null,
"e": 8706,
"s": 8692,
"text": "ManasChhabra2"
},
{
"code": null,
"e": 8727,
"s": 8706,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 8740,
"s": 8727,
"text": "divisibility"
},
{
"code": null,
"e": 8759,
"s": 8740,
"text": "Modular Arithmetic"
},
{
"code": null,
"e": 8771,
"s": 8759,
"text": "subsequence"
},
{
"code": null,
"e": 8791,
"s": 8771,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 8811,
"s": 8791,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 8830,
"s": 8811,
"text": "Modular Arithmetic"
}
] |
How to install pip in macOS ?
|
01 Jul, 2022
Before we start with how to install pip for Python on macOS, let’s first go through the basic introduction to Python.
Python is a widely-used general-purpose, high-level programming language. Python is a programming language that lets you work quickly and integrate systems more efficiently. 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). pip uses PyPI as the default source for packages and their dependencies. In this article, we will see How to Install PIP on a Mac. Using pip you can install any package using the following syntax:
pip install package_name
pip can be downloaded and installed usingthe command line by going through the following steps:
Step 1: Download the get-pip.py(https://bootstrap.pypa.io/get-pip.py) file and store it in the same directory as python is installed. or Use the following command to download pip directly
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
Step 2: Now execute the downloaded file using the below command
python3 get-pip.py
Step 3: Wait through the installation process.
Voila! pip is now installed on your system.
One can easily verify if the pip has been installed correctly by performing a version check on the same. Just go to the command line and execute the following command:
pip3 --version
pip --version
You can use the following command in your terminal to upgrade your pip.
python3 -m pip install –upgrade pip
To install a specific version you can enter the following version number to install the specific version.
pip install --upgrade pip==1.2.1
You can use one of the commands to uninstall the pip command based on your system.
pip uninstall pip
sudo apt-get remove python-pip
surajkumarguptaintern
Python-pip
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
Convert integer to string in Python
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n01 Jul, 2022"
},
{
"code": null,
"e": 171,
"s": 52,
"text": "Before we start with how to install pip for Python on macOS, let’s first go through the basic introduction to Python. "
},
{
"code": null,
"e": 745,
"s": 171,
"text": "Python is a widely-used general-purpose, high-level programming language. Python is a programming language that lets you work quickly and integrate systems more efficiently. 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). pip uses PyPI as the default source for packages and their dependencies. In this article, we will see How to Install PIP on a Mac. Using pip you can install any package using the following syntax:"
},
{
"code": null,
"e": 770,
"s": 745,
"text": "pip install package_name"
},
{
"code": null,
"e": 867,
"s": 770,
"text": "pip can be downloaded and installed usingthe command line by going through the following steps:"
},
{
"code": null,
"e": 1056,
"s": 867,
"text": "Step 1: Download the get-pip.py(https://bootstrap.pypa.io/get-pip.py) file and store it in the same directory as python is installed. or Use the following command to download pip directly"
},
{
"code": null,
"e": 1112,
"s": 1056,
"text": "curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py"
},
{
"code": null,
"e": 1176,
"s": 1112,
"text": "Step 2: Now execute the downloaded file using the below command"
},
{
"code": null,
"e": 1195,
"s": 1176,
"text": "python3 get-pip.py"
},
{
"code": null,
"e": 1244,
"s": 1195,
"text": "Step 3: Wait through the installation process. "
},
{
"code": null,
"e": 1290,
"s": 1246,
"text": "Voila! pip is now installed on your system."
},
{
"code": null,
"e": 1458,
"s": 1290,
"text": "One can easily verify if the pip has been installed correctly by performing a version check on the same. Just go to the command line and execute the following command:"
},
{
"code": null,
"e": 1487,
"s": 1458,
"text": "pip3 --version\npip --version"
},
{
"code": null,
"e": 1562,
"s": 1489,
"text": "You can use the following command in your terminal to upgrade your pip. "
},
{
"code": null,
"e": 1598,
"s": 1562,
"text": "python3 -m pip install –upgrade pip"
},
{
"code": null,
"e": 1704,
"s": 1598,
"text": "To install a specific version you can enter the following version number to install the specific version."
},
{
"code": null,
"e": 1737,
"s": 1704,
"text": "pip install --upgrade pip==1.2.1"
},
{
"code": null,
"e": 1820,
"s": 1737,
"text": "You can use one of the commands to uninstall the pip command based on your system."
},
{
"code": null,
"e": 1869,
"s": 1820,
"text": "pip uninstall pip\nsudo apt-get remove python-pip"
},
{
"code": null,
"e": 1891,
"s": 1869,
"text": "surajkumarguptaintern"
},
{
"code": null,
"e": 1902,
"s": 1891,
"text": "Python-pip"
},
{
"code": null,
"e": 1909,
"s": 1902,
"text": "Python"
},
{
"code": null,
"e": 2007,
"s": 1909,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2025,
"s": 2007,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2067,
"s": 2025,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2089,
"s": 2067,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2124,
"s": 2089,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2150,
"s": 2124,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2179,
"s": 2150,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2206,
"s": 2179,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2236,
"s": 2206,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 2257,
"s": 2236,
"text": "Python OOPs Concepts"
}
] |
Max Heap in Python
|
06 Jul, 2022
A Max-Heap is a complete binary tree in which the value in each internal node is greater than or equal to the values in the children of that node. Mapping the elements of a heap into an array is trivial: if a node is stored a index k, then its left child is stored at index 2k + 1 and its right child at index 2k + 2.
Examples of Max Heap :
A max Heap is a Complete Binary Tree. A max heap is typically represented as an array. The root element will be at Arr[0]. Below table shows indexes of other nodes for the ith node, i.e., Arr[i]:
Arr[(i-1)/2] Returns the parent node.
Arr[(2*i)+1] Returns the left child node.
Arr[(2*i)+2] Returns the right child node.
getMax(): It returns the root element of Max Heap. Time Complexity of this operation is O(1).extractMax(): Removes the maximum element from MaxHeap. Time Complexity of this Operation is O(log n) as this operation needs to maintain the heap property (by calling heapify()) after removing the root.insert(): Inserting a new key takes O(log n) time. We add a new key at the end of the tree. If the new key is smaller than its parent, then we don’t need to do anything. Otherwise, we need to traverse up to fix the violated heap property.
getMax(): It returns the root element of Max Heap. Time Complexity of this operation is O(1).
extractMax(): Removes the maximum element from MaxHeap. Time Complexity of this Operation is O(log n) as this operation needs to maintain the heap property (by calling heapify()) after removing the root.
insert(): Inserting a new key takes O(log n) time. We add a new key at the end of the tree. If the new key is smaller than its parent, then we don’t need to do anything. Otherwise, we need to traverse up to fix the violated heap property.
Note: In the below implementation, we do indexing from index 1 to simplify the implementation.
Python
# Python3 implementation of Max Heapimport sys class MaxHeap: def __init__(self, maxsize): self.maxsize = maxsize self.size = 0 self.Heap = [0] * (self.maxsize + 1) self.Heap[0] = sys.maxsize self.FRONT = 1 # Function to return the position of # parent for the node currently # at pos def parent(self, pos): return pos // 2 # Function to return the position of # the left child for the node currently # at pos def leftChild(self, pos): return 2 * pos # Function to return the position of # the right child for the node currently # at pos def rightChild(self, pos): return (2 * pos) + 1 # Function that returns true if the passed # node is a leaf node def isLeaf(self, pos): if pos >= (self.size//2) and pos <= self.size: return True return False # Function to swap two nodes of the heap def swap(self, fpos, spos): self.Heap[fpos], self.Heap[spos] = (self.Heap[spos], self.Heap[fpos]) # Function to heapify the node at pos def maxHeapify(self, pos): # If the node is a non-leaf node and smaller # than any of its child if not self.isLeaf(pos): if (self.Heap[pos] < self.Heap[self.leftChild(pos)] or self.Heap[pos] < self.Heap[self.rightChild(pos)]): # Swap with the left child and heapify # the left child if (self.Heap[self.leftChild(pos)] > self.Heap[self.rightChild(pos)]): self.swap(pos, self.leftChild(pos)) self.maxHeapify(self.leftChild(pos)) # Swap with the right child and heapify # the right child else: self.swap(pos, self.rightChild(pos)) self.maxHeapify(self.rightChild(pos)) # Function to insert a node into the heap def insert(self, element): if self.size >= self.maxsize: return self.size += 1 self.Heap[self.size] = element current = self.size while (self.Heap[current] > self.Heap[self.parent(current)]): self.swap(current, self.parent(current)) current = self.parent(current) # Function to print the contents of the heap def Print(self): for i in range(1, (self.size // 2) + 1): print("PARENT : " + str(self.Heap[i]) + "LEFT CHILD : " + str(self.Heap[2 * i]) + "RIGHT CHILD : " + str(self.Heap[2 * i + 1])) # Function to remove and return the maximum # element from the heap def extractMax(self): popped = self.Heap[self.FRONT] self.Heap[self.FRONT] = self.Heap[self.size] self.size -= 1 self.maxHeapify(self.FRONT) return popped # Driver Codeif __name__ == "__main__": print('The maxHeap is ') maxHeap = MaxHeap(15) maxHeap.insert(5) maxHeap.insert(3) maxHeap.insert(17) maxHeap.insert(10) maxHeap.insert(84) maxHeap.insert(19) maxHeap.insert(6) maxHeap.insert(22) maxHeap.insert(9) maxHeap.Print() print("The Max val is " + str(maxHeap.extractMax()))
The maxHeap is
PARENT : 84LEFT CHILD : 22RIGHT CHILD : 19
PARENT : 22LEFT CHILD : 17RIGHT CHILD : 10
PARENT : 19LEFT CHILD : 5RIGHT CHILD : 6
PARENT : 17LEFT CHILD : 3RIGHT CHILD : 9
The Max val is 84
We use heapq class to implement Heap in Python. By default Min Heap is implemented by this class. But we multiply each value by -1 so that we can use it as MaxHeap.
Python3
# Python3 program to demonstrate working of heapq from heapq import heappop, heappush, heapify # Creating empty heapheap = []heapify(heap) # Adding items to the heap using heappush# function by multiplying them with -1heappush(heap, -1 * 10)heappush(heap, -1 * 30)heappush(heap, -1 * 20)heappush(heap, -1 * 400) # printing the value of maximum elementprint("Head value of heap : " + str(-1 * heap[0])) # printing the elements of the heapprint("The heap elements : ")for i in heap: print((-1*i), end=" ")print("\n") element = heappop(heap) # printing the elements of the heapprint("The heap elements : ")for i in heap: print(-1 * i, end = ' ')
Head value of heap : 400
The heap elements :
400 30 20 10
The heap elements :
30 10 20
We use heapq class to implement Heaps in Python. By default Min Heap is implemented by this class.
To implement MaxHeap not limiting to only numbers but any type of object(String, Tuple, Object etc) we should
Create a Wrapper class for the item in the list.Override the __lt__ dunder method to give inverse result.
Create a Wrapper class for the item in the list.
Override the __lt__ dunder method to give inverse result.
Following is the implementation of the method mentioned here.
Python3
from functools import total_orderingimport heapq # why total_ordering: https://www.geeksforgeeks.org/python-functools-total_ordering/ @total_orderingclass Wrapper: def __init__(self, val): self.val = val def __lt__(self, other): return self.val > other.val def __eq__(self, other): return self.val == other.val # Working on exiting list of intheap = [10, 20, 400, 30]wrapper_heap = list(map(lambda item: Wrapper(item), heap)) heapq.heapify(wrapper_heap)max_item = heapq.heappop(wrapper_heap) # This will give the max valueprint("Top of numbers are: {max_item.val}") # Working on existing list of strheap = ["this", "code", "is", "wonderful"]wrapper_heap = list(map(lambda item: Wrapper(item), heap))heapq.heapify(wrapper_heap) print("The string heap elements in order: ")while wrapper_heap: top_item = heapq.heappop(wrapper_heap) print(top_item.val, end=" ")
Top of numbers are: {max_item.val}
The string heap elements in order:
wonderful this is code
ignacio hugo gomez
super_sam
Python-Data-Structures
Technical Scripter 2019
Heap
Python
Technical Scripter
Heap
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
Priority Queue in Python
Insertion and Deletion in Heaps
Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash)
Sort a nearly sorted (or K sorted) array
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
Python Dictionary
How to get column names in Pandas dataframe
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n06 Jul, 2022"
},
{
"code": null,
"e": 372,
"s": 54,
"text": "A Max-Heap is a complete binary tree in which the value in each internal node is greater than or equal to the values in the children of that node. Mapping the elements of a heap into an array is trivial: if a node is stored a index k, then its left child is stored at index 2k + 1 and its right child at index 2k + 2."
},
{
"code": null,
"e": 397,
"s": 372,
"text": " Examples of Max Heap : "
},
{
"code": null,
"e": 596,
"s": 399,
"text": "A max Heap is a Complete Binary Tree. A max heap is typically represented as an array. The root element will be at Arr[0]. Below table shows indexes of other nodes for the ith node, i.e., Arr[i]: "
},
{
"code": null,
"e": 635,
"s": 596,
"text": "Arr[(i-1)/2] Returns the parent node. "
},
{
"code": null,
"e": 678,
"s": 635,
"text": "Arr[(2*i)+1] Returns the left child node. "
},
{
"code": null,
"e": 721,
"s": 678,
"text": "Arr[(2*i)+2] Returns the right child node."
},
{
"code": null,
"e": 1256,
"s": 721,
"text": "getMax(): It returns the root element of Max Heap. Time Complexity of this operation is O(1).extractMax(): Removes the maximum element from MaxHeap. Time Complexity of this Operation is O(log n) as this operation needs to maintain the heap property (by calling heapify()) after removing the root.insert(): Inserting a new key takes O(log n) time. We add a new key at the end of the tree. If the new key is smaller than its parent, then we don’t need to do anything. Otherwise, we need to traverse up to fix the violated heap property."
},
{
"code": null,
"e": 1350,
"s": 1256,
"text": "getMax(): It returns the root element of Max Heap. Time Complexity of this operation is O(1)."
},
{
"code": null,
"e": 1554,
"s": 1350,
"text": "extractMax(): Removes the maximum element from MaxHeap. Time Complexity of this Operation is O(log n) as this operation needs to maintain the heap property (by calling heapify()) after removing the root."
},
{
"code": null,
"e": 1793,
"s": 1554,
"text": "insert(): Inserting a new key takes O(log n) time. We add a new key at the end of the tree. If the new key is smaller than its parent, then we don’t need to do anything. Otherwise, we need to traverse up to fix the violated heap property."
},
{
"code": null,
"e": 1889,
"s": 1793,
"text": "Note: In the below implementation, we do indexing from index 1 to simplify the implementation. "
},
{
"code": null,
"e": 1896,
"s": 1889,
"text": "Python"
},
{
"code": "# Python3 implementation of Max Heapimport sys class MaxHeap: def __init__(self, maxsize): self.maxsize = maxsize self.size = 0 self.Heap = [0] * (self.maxsize + 1) self.Heap[0] = sys.maxsize self.FRONT = 1 # Function to return the position of # parent for the node currently # at pos def parent(self, pos): return pos // 2 # Function to return the position of # the left child for the node currently # at pos def leftChild(self, pos): return 2 * pos # Function to return the position of # the right child for the node currently # at pos def rightChild(self, pos): return (2 * pos) + 1 # Function that returns true if the passed # node is a leaf node def isLeaf(self, pos): if pos >= (self.size//2) and pos <= self.size: return True return False # Function to swap two nodes of the heap def swap(self, fpos, spos): self.Heap[fpos], self.Heap[spos] = (self.Heap[spos], self.Heap[fpos]) # Function to heapify the node at pos def maxHeapify(self, pos): # If the node is a non-leaf node and smaller # than any of its child if not self.isLeaf(pos): if (self.Heap[pos] < self.Heap[self.leftChild(pos)] or self.Heap[pos] < self.Heap[self.rightChild(pos)]): # Swap with the left child and heapify # the left child if (self.Heap[self.leftChild(pos)] > self.Heap[self.rightChild(pos)]): self.swap(pos, self.leftChild(pos)) self.maxHeapify(self.leftChild(pos)) # Swap with the right child and heapify # the right child else: self.swap(pos, self.rightChild(pos)) self.maxHeapify(self.rightChild(pos)) # Function to insert a node into the heap def insert(self, element): if self.size >= self.maxsize: return self.size += 1 self.Heap[self.size] = element current = self.size while (self.Heap[current] > self.Heap[self.parent(current)]): self.swap(current, self.parent(current)) current = self.parent(current) # Function to print the contents of the heap def Print(self): for i in range(1, (self.size // 2) + 1): print(\"PARENT : \" + str(self.Heap[i]) + \"LEFT CHILD : \" + str(self.Heap[2 * i]) + \"RIGHT CHILD : \" + str(self.Heap[2 * i + 1])) # Function to remove and return the maximum # element from the heap def extractMax(self): popped = self.Heap[self.FRONT] self.Heap[self.FRONT] = self.Heap[self.size] self.size -= 1 self.maxHeapify(self.FRONT) return popped # Driver Codeif __name__ == \"__main__\": print('The maxHeap is ') maxHeap = MaxHeap(15) maxHeap.insert(5) maxHeap.insert(3) maxHeap.insert(17) maxHeap.insert(10) maxHeap.insert(84) maxHeap.insert(19) maxHeap.insert(6) maxHeap.insert(22) maxHeap.insert(9) maxHeap.Print() print(\"The Max val is \" + str(maxHeap.extractMax()))",
"e": 5233,
"s": 1896,
"text": null
},
{
"code": null,
"e": 5436,
"s": 5233,
"text": "The maxHeap is \nPARENT : 84LEFT CHILD : 22RIGHT CHILD : 19\nPARENT : 22LEFT CHILD : 17RIGHT CHILD : 10\nPARENT : 19LEFT CHILD : 5RIGHT CHILD : 6\nPARENT : 17LEFT CHILD : 3RIGHT CHILD : 9\nThe Max val is 84\n"
},
{
"code": null,
"e": 5602,
"s": 5436,
"text": "We use heapq class to implement Heap in Python. By default Min Heap is implemented by this class. But we multiply each value by -1 so that we can use it as MaxHeap. "
},
{
"code": null,
"e": 5610,
"s": 5602,
"text": "Python3"
},
{
"code": "# Python3 program to demonstrate working of heapq from heapq import heappop, heappush, heapify # Creating empty heapheap = []heapify(heap) # Adding items to the heap using heappush# function by multiplying them with -1heappush(heap, -1 * 10)heappush(heap, -1 * 30)heappush(heap, -1 * 20)heappush(heap, -1 * 400) # printing the value of maximum elementprint(\"Head value of heap : \" + str(-1 * heap[0])) # printing the elements of the heapprint(\"The heap elements : \")for i in heap: print((-1*i), end=\" \")print(\"\\n\") element = heappop(heap) # printing the elements of the heapprint(\"The heap elements : \")for i in heap: print(-1 * i, end = ' ')",
"e": 6259,
"s": 5610,
"text": null
},
{
"code": null,
"e": 6351,
"s": 6259,
"text": "Head value of heap : 400\nThe heap elements : \n400 30 20 10 \n\nThe heap elements : \n30 10 20 "
},
{
"code": null,
"e": 6450,
"s": 6351,
"text": "We use heapq class to implement Heaps in Python. By default Min Heap is implemented by this class."
},
{
"code": null,
"e": 6560,
"s": 6450,
"text": "To implement MaxHeap not limiting to only numbers but any type of object(String, Tuple, Object etc) we should"
},
{
"code": null,
"e": 6666,
"s": 6560,
"text": "Create a Wrapper class for the item in the list.Override the __lt__ dunder method to give inverse result."
},
{
"code": null,
"e": 6715,
"s": 6666,
"text": "Create a Wrapper class for the item in the list."
},
{
"code": null,
"e": 6773,
"s": 6715,
"text": "Override the __lt__ dunder method to give inverse result."
},
{
"code": null,
"e": 6835,
"s": 6773,
"text": "Following is the implementation of the method mentioned here."
},
{
"code": null,
"e": 6843,
"s": 6835,
"text": "Python3"
},
{
"code": "from functools import total_orderingimport heapq # why total_ordering: https://www.geeksforgeeks.org/python-functools-total_ordering/ @total_orderingclass Wrapper: def __init__(self, val): self.val = val def __lt__(self, other): return self.val > other.val def __eq__(self, other): return self.val == other.val # Working on exiting list of intheap = [10, 20, 400, 30]wrapper_heap = list(map(lambda item: Wrapper(item), heap)) heapq.heapify(wrapper_heap)max_item = heapq.heappop(wrapper_heap) # This will give the max valueprint(\"Top of numbers are: {max_item.val}\") # Working on existing list of strheap = [\"this\", \"code\", \"is\", \"wonderful\"]wrapper_heap = list(map(lambda item: Wrapper(item), heap))heapq.heapify(wrapper_heap) print(\"The string heap elements in order: \")while wrapper_heap: top_item = heapq.heappop(wrapper_heap) print(top_item.val, end=\" \")",
"e": 7742,
"s": 6843,
"text": null
},
{
"code": null,
"e": 7837,
"s": 7742,
"text": "Top of numbers are: {max_item.val}\nThe string heap elements in order: \nwonderful this is code "
},
{
"code": null,
"e": 7856,
"s": 7837,
"text": "ignacio hugo gomez"
},
{
"code": null,
"e": 7866,
"s": 7856,
"text": "super_sam"
},
{
"code": null,
"e": 7889,
"s": 7866,
"text": "Python-Data-Structures"
},
{
"code": null,
"e": 7913,
"s": 7889,
"text": "Technical Scripter 2019"
},
{
"code": null,
"e": 7918,
"s": 7913,
"text": "Heap"
},
{
"code": null,
"e": 7925,
"s": 7918,
"text": "Python"
},
{
"code": null,
"e": 7944,
"s": 7925,
"text": "Technical Scripter"
},
{
"code": null,
"e": 7949,
"s": 7944,
"text": "Heap"
},
{
"code": null,
"e": 8047,
"s": 7949,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8079,
"s": 8047,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 8104,
"s": 8079,
"text": "Priority Queue in Python"
},
{
"code": null,
"e": 8136,
"s": 8104,
"text": "Insertion and Deletion in Heaps"
},
{
"code": null,
"e": 8206,
"s": 8136,
"text": "Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash)"
},
{
"code": null,
"e": 8247,
"s": 8206,
"text": "Sort a nearly sorted (or K sorted) array"
},
{
"code": null,
"e": 8275,
"s": 8247,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 8325,
"s": 8275,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 8347,
"s": 8325,
"text": "Python map() function"
},
{
"code": null,
"e": 8365,
"s": 8347,
"text": "Python Dictionary"
}
] |
Fierce – DNS reconnaissance tool for locating non-contiguous IP space
|
14 Sep, 2021
Understanding the network structure of the organization is very important. So to locate targets both inside and outside a corporate network there is a tool designed in the Python Language known as Fierce. This tool is different from other tools as its main objective is to locate non-contiguous IP spaces and hostnames against specified domains or subdomains. The Fierce tool doesn’t scan the total internet for our results but the results which it finds are really helpful in the process. This tool is open-source and free to use. The Fierce tool is very easier to use due to its tags of flags features.
Note: Make Sure You have Python Installed on your System, as this is a python-based tool. Click to check the Installation process: Python Installation Steps on Linux
Step 1: Check whether Python Environment is Established or not, use the following command.
python3
Step 2: Open up your Kali Linux terminal and move to the Desktop directory using the following command.
cd Desktop
Step 3: You are on Desktop now, create a new directory called Fierce using the following command. In this directory, we will complete the installation of the Fierce tool.
mkdir Fierce
Step 4: Now switch to the Fierce directory using the following command.
cd Fierce
Step 5: Now you have to install the tool. You have to clone the tool from Github.
git clone git clone https://github.com/mschwager/fierce.git
Step 6: The tool has been downloaded successfully in the Fierce directory. Now list out the contents of the tool by using the below command.
ls
Step 7: You can observe that there is a new directory created for the Fierce tool that has been generated while we were installing the tool. Now move to that directory using the below command:
cd fierce
Step 8: Once again to discover the contents of the tool, use the below command.
ls
Step 9: Download the required packages for running the tool, use the following command.
pip3 install -r requirements.txt
Step 10: Now we are done with our installation, Use the below command to view the help (gives a better understanding of the tool) index of the tool.
python3 fierce/fierce.py -h
The fierce tool has the attributes to perform Reverse Lookups for the specified range of IP addresses. [–dns-file] option is used.The fierce tool has the attribute to enumerate Domain Name System Records on the Target domain. [–dns-servers] option is usedThe fierce tool has the attribute of performing Internal as well as External IP ranges Enumeration. [–range] option is used.Class C IP addresses are also supported by the Fierce tool. [–traverse] option is used.The fierce tool has the attribute to Scan Name Server Directory and also Zone Transfer attack.
The fierce tool has the attributes to perform Reverse Lookups for the specified range of IP addresses. [–dns-file] option is used.
The fierce tool has the attribute to enumerate Domain Name System Records on the Target domain. [–dns-servers] option is used
The fierce tool has the attribute of performing Internal as well as External IP ranges Enumeration. [–range] option is used.
Class C IP addresses are also supported by the Fierce tool. [–traverse] option is used.
The fierce tool has the attribute to Scan Name Server Directory and also Zone Transfer attack.
The fierce tool is the most helpful tool for the Reconnaissance, Information Gathering, and Scanning phase in the process of Penetration Testing or Network Testing. The working of this tool is very simple. At the very first stage, the tool performs scanning with brute-forcing attacks and can also perform zone transfer attacks on the target is possible. There are massive word lists that contain possible words, through which subdomains of the target can be enumerated. If the subdomain is not in the list, then there is no chance of detection of the subdomain on the target.
Unfortunately, there is no inbuilt function available for storing the results of the Fierce scan on the target at your disk. Although no saving function is available, so there is no feature to save the output in various formats. But you can redirect the output of the scan into any text file with some Linux skills and terminal commands.
One of the amazing functions or features of the Fierce tool is the Range scan. You can scan the range of IP address with a single click. –the range is the option that is mandatory while performing a range scan. You need to specify the IP address; like ( 192.168.28.4/24).
A brute-forcing attack or method approach is used for enumeration or detection of subdomains associated with the target domain. The inbuilt wordlist file is activated when the installation of the Fierce tool is done on the system. But Fierce tool allows users to use custom subdomains wordlists with a massive number of possible subdomains words. –subdomain-file is the option for using the custom wordlists for brute-forcing.
Example 1: Basic
fierce --domain geeksforgeeks.org --subdomains write admin videos
In this Example, We are performing a simple scan using the subdomain words which include write, admin, videos. We have chosen geeksfoegeeks.org as our target.
Example 2: Traverse IPs near discovered domains to search for contiguous blocks with the –traverse flag
fierce --domain geeksforgeeks.org --subdomains videos --traverse 10
In this Example, We are scanning domains near discovered records. Our target domain is geeksforgeeks.org
Example 3: Attempt an HTTP connection on domains discovered with the –connect flag
fierce --domain stackoverflow.com --subdomains mail --connect
In this Example, We are attempting HTTP connection on the domains using the connect flag. We have chosen a different target for this Example, which is stackoverflow.com.
Example 4: Exchange speed for breadth with the –wide flag, which looks for nearby domains on all IPs of the /24 of a discovered domain
fierce --domain geeksforgeeks.org --wide
In this example, We will scan the entire class of discovered records. (Full Detailed Scan)
Example 5: Zone transfers are rare these days, but they give us the keys to the DNS castle.
fierce --domain geeksforgeeks.org
In this Example, We are performing a basic scan without any arguments on geeksforgeeks.org
Kali-Linux
Linux-Tools
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n14 Sep, 2021"
},
{
"code": null,
"e": 633,
"s": 28,
"text": "Understanding the network structure of the organization is very important. So to locate targets both inside and outside a corporate network there is a tool designed in the Python Language known as Fierce. This tool is different from other tools as its main objective is to locate non-contiguous IP spaces and hostnames against specified domains or subdomains. The Fierce tool doesn’t scan the total internet for our results but the results which it finds are really helpful in the process. This tool is open-source and free to use. The Fierce tool is very easier to use due to its tags of flags features."
},
{
"code": null,
"e": 799,
"s": 633,
"text": "Note: Make Sure You have Python Installed on your System, as this is a python-based tool. Click to check the Installation process: Python Installation Steps on Linux"
},
{
"code": null,
"e": 890,
"s": 799,
"text": "Step 1: Check whether Python Environment is Established or not, use the following command."
},
{
"code": null,
"e": 898,
"s": 890,
"text": "python3"
},
{
"code": null,
"e": 1002,
"s": 898,
"text": "Step 2: Open up your Kali Linux terminal and move to the Desktop directory using the following command."
},
{
"code": null,
"e": 1013,
"s": 1002,
"text": "cd Desktop"
},
{
"code": null,
"e": 1184,
"s": 1013,
"text": "Step 3: You are on Desktop now, create a new directory called Fierce using the following command. In this directory, we will complete the installation of the Fierce tool."
},
{
"code": null,
"e": 1198,
"s": 1184,
"text": "mkdir Fierce "
},
{
"code": null,
"e": 1270,
"s": 1198,
"text": "Step 4: Now switch to the Fierce directory using the following command."
},
{
"code": null,
"e": 1281,
"s": 1270,
"text": "cd Fierce "
},
{
"code": null,
"e": 1363,
"s": 1281,
"text": "Step 5: Now you have to install the tool. You have to clone the tool from Github."
},
{
"code": null,
"e": 1423,
"s": 1363,
"text": "git clone git clone https://github.com/mschwager/fierce.git"
},
{
"code": null,
"e": 1564,
"s": 1423,
"text": "Step 6: The tool has been downloaded successfully in the Fierce directory. Now list out the contents of the tool by using the below command."
},
{
"code": null,
"e": 1567,
"s": 1564,
"text": "ls"
},
{
"code": null,
"e": 1760,
"s": 1567,
"text": "Step 7: You can observe that there is a new directory created for the Fierce tool that has been generated while we were installing the tool. Now move to that directory using the below command:"
},
{
"code": null,
"e": 1771,
"s": 1760,
"text": "cd fierce "
},
{
"code": null,
"e": 1851,
"s": 1771,
"text": "Step 8: Once again to discover the contents of the tool, use the below command."
},
{
"code": null,
"e": 1854,
"s": 1851,
"text": "ls"
},
{
"code": null,
"e": 1942,
"s": 1854,
"text": "Step 9: Download the required packages for running the tool, use the following command."
},
{
"code": null,
"e": 1975,
"s": 1942,
"text": "pip3 install -r requirements.txt"
},
{
"code": null,
"e": 2124,
"s": 1975,
"text": "Step 10: Now we are done with our installation, Use the below command to view the help (gives a better understanding of the tool) index of the tool."
},
{
"code": null,
"e": 2152,
"s": 2124,
"text": "python3 fierce/fierce.py -h"
},
{
"code": null,
"e": 2714,
"s": 2152,
"text": "The fierce tool has the attributes to perform Reverse Lookups for the specified range of IP addresses. [–dns-file] option is used.The fierce tool has the attribute to enumerate Domain Name System Records on the Target domain. [–dns-servers] option is usedThe fierce tool has the attribute of performing Internal as well as External IP ranges Enumeration. [–range] option is used.Class C IP addresses are also supported by the Fierce tool. [–traverse] option is used.The fierce tool has the attribute to Scan Name Server Directory and also Zone Transfer attack."
},
{
"code": null,
"e": 2846,
"s": 2714,
"text": "The fierce tool has the attributes to perform Reverse Lookups for the specified range of IP addresses. [–dns-file] option is used."
},
{
"code": null,
"e": 2972,
"s": 2846,
"text": "The fierce tool has the attribute to enumerate Domain Name System Records on the Target domain. [–dns-servers] option is used"
},
{
"code": null,
"e": 3097,
"s": 2972,
"text": "The fierce tool has the attribute of performing Internal as well as External IP ranges Enumeration. [–range] option is used."
},
{
"code": null,
"e": 3185,
"s": 3097,
"text": "Class C IP addresses are also supported by the Fierce tool. [–traverse] option is used."
},
{
"code": null,
"e": 3280,
"s": 3185,
"text": "The fierce tool has the attribute to Scan Name Server Directory and also Zone Transfer attack."
},
{
"code": null,
"e": 3857,
"s": 3280,
"text": "The fierce tool is the most helpful tool for the Reconnaissance, Information Gathering, and Scanning phase in the process of Penetration Testing or Network Testing. The working of this tool is very simple. At the very first stage, the tool performs scanning with brute-forcing attacks and can also perform zone transfer attacks on the target is possible. There are massive word lists that contain possible words, through which subdomains of the target can be enumerated. If the subdomain is not in the list, then there is no chance of detection of the subdomain on the target."
},
{
"code": null,
"e": 4195,
"s": 3857,
"text": "Unfortunately, there is no inbuilt function available for storing the results of the Fierce scan on the target at your disk. Although no saving function is available, so there is no feature to save the output in various formats. But you can redirect the output of the scan into any text file with some Linux skills and terminal commands."
},
{
"code": null,
"e": 4467,
"s": 4195,
"text": "One of the amazing functions or features of the Fierce tool is the Range scan. You can scan the range of IP address with a single click. –the range is the option that is mandatory while performing a range scan. You need to specify the IP address; like ( 192.168.28.4/24)."
},
{
"code": null,
"e": 4894,
"s": 4467,
"text": "A brute-forcing attack or method approach is used for enumeration or detection of subdomains associated with the target domain. The inbuilt wordlist file is activated when the installation of the Fierce tool is done on the system. But Fierce tool allows users to use custom subdomains wordlists with a massive number of possible subdomains words. –subdomain-file is the option for using the custom wordlists for brute-forcing."
},
{
"code": null,
"e": 4911,
"s": 4894,
"text": "Example 1: Basic"
},
{
"code": null,
"e": 4977,
"s": 4911,
"text": "fierce --domain geeksforgeeks.org --subdomains write admin videos"
},
{
"code": null,
"e": 5136,
"s": 4977,
"text": "In this Example, We are performing a simple scan using the subdomain words which include write, admin, videos. We have chosen geeksfoegeeks.org as our target."
},
{
"code": null,
"e": 5240,
"s": 5136,
"text": "Example 2: Traverse IPs near discovered domains to search for contiguous blocks with the –traverse flag"
},
{
"code": null,
"e": 5308,
"s": 5240,
"text": "fierce --domain geeksforgeeks.org --subdomains videos --traverse 10"
},
{
"code": null,
"e": 5413,
"s": 5308,
"text": "In this Example, We are scanning domains near discovered records. Our target domain is geeksforgeeks.org"
},
{
"code": null,
"e": 5496,
"s": 5413,
"text": "Example 3: Attempt an HTTP connection on domains discovered with the –connect flag"
},
{
"code": null,
"e": 5558,
"s": 5496,
"text": "fierce --domain stackoverflow.com --subdomains mail --connect"
},
{
"code": null,
"e": 5728,
"s": 5558,
"text": "In this Example, We are attempting HTTP connection on the domains using the connect flag. We have chosen a different target for this Example, which is stackoverflow.com."
},
{
"code": null,
"e": 5863,
"s": 5728,
"text": "Example 4: Exchange speed for breadth with the –wide flag, which looks for nearby domains on all IPs of the /24 of a discovered domain"
},
{
"code": null,
"e": 5904,
"s": 5863,
"text": "fierce --domain geeksforgeeks.org --wide"
},
{
"code": null,
"e": 5995,
"s": 5904,
"text": "In this example, We will scan the entire class of discovered records. (Full Detailed Scan)"
},
{
"code": null,
"e": 6087,
"s": 5995,
"text": "Example 5: Zone transfers are rare these days, but they give us the keys to the DNS castle."
},
{
"code": null,
"e": 6121,
"s": 6087,
"text": "fierce --domain geeksforgeeks.org"
},
{
"code": null,
"e": 6212,
"s": 6121,
"text": "In this Example, We are performing a basic scan without any arguments on geeksforgeeks.org"
},
{
"code": null,
"e": 6223,
"s": 6212,
"text": "Kali-Linux"
},
{
"code": null,
"e": 6235,
"s": 6223,
"text": "Linux-Tools"
},
{
"code": null,
"e": 6246,
"s": 6235,
"text": "Linux-Unix"
}
] |
How to change a select’s options based on another dropdown using React?
|
18 Nov, 2020
React is a declarative, efficient, and flexible JavaScript library for building user interfaces. It’s ‘V’ in MVC. ReactJS is an open-source, component-based front end library responsible only for the view layer of the application. It is maintained by Facebook.
Select in HTML allows us to choose among multiple values using the dropdown. Here, we are talking about changing select options based on another dropdown. In React, it is very easy to achieve with the help of the state. For those who don’t about state here is a brief of it.
The STATE of a component is an object that holds some information that may change over the lifetime of the component.
If you want to know more about the state, please refer to state in react geeksforgeeks and state and lifecycle reactjs.org.
React has both Class-Based components and Functional Component so for this article, we will use Functional Component. In the Functional component, the state can be managed using useState hook.
We want to change the selects options based on other dropdowns so we will follow the below steps.
Create a state variable that is initially null or undefined.Create different arrays for different dropdowns.Create a local variable say type that will hold any of the array based on the dropdown selected.Create a function that will be called whenever an option from the dropdown is selected, this function will change the state variable so that the value of type can be determined dynamically.Lastly, use type variables to create a different set of options that the user will see.
Create a state variable that is initially null or undefined.
Create different arrays for different dropdowns.
Create a local variable say type that will hold any of the array based on the dropdown selected.
Create a function that will be called whenever an option from the dropdown is selected, this function will change the state variable so that the value of type can be determined dynamically.
Lastly, use type variables to create a different set of options that the user will see.
Now we will create a Component using all the steps described above.
App.js: Below is the code for App.js component.
Javascript
import * as React from "react"; const App = () => { /** "selected" here is state variable which will hold the * value of currently selected dropdown. */ const [selected, setSelected] = React.useState(""); /** Function that will set different values to state variable * based on which dropdown is selected */ const changeSelectOptionHandler = (event) => { setSelected(event.target.value); }; /** Different arrays for different dropdowns */ const algorithm = [ "Searching Algorithm", "Sorting Algorithm", "Graph Algorithm", ]; const language = ["C++", "Java", "Python", "C#"]; const dataStructure = ["Arrays", "LinkedList", "Stack", "Queue"]; /** Type variable to store different array for different dropdown */ let type = null; /** This will be used to create set of options that user will see */ let options = null; /** Setting Type variable according to dropdown */ if (selected === "Algorithm") { type = algorithm; } else if (selected === "Language") { type = language; } else if (selected === "Data Structure") { type = dataStructure; } /** If "Type" is null or undefined then options will be null, * otherwise it will create a options iterable based on our array */ if (type) { options = type.map((el) => <option key={el}>{el}</option>); } return ( <div style={{ padding: "16px", margin: "16px", }} > <form> <div> {/** Bind changeSelectOptionHandler to onChange method of select. * This method will trigger every time different * option is selected. */} <select onChange={changeSelectOptionHandler}> <option>Choose...</option> <option>Algorithm</option> <option>Language</option> <option>Data Structure</option> </select> </div> <div> <select> { /** This is where we have used our options variable */ options } </select> </div> </form> </div> );}; export default App;
Output:
Note: You can also use the Class-Based component, logic would be the same.
react-js
Technical Scripter 2020
JavaScript
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
How to append HTML code to a div using JavaScript ?
How to Open URL in New Tab using JavaScript ?
Roadmap to Learn JavaScript For Beginners
How to get character array from string in JavaScript?
How do you run JavaScript script through the Terminal?
JavaScript | console.log() with Examples
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n18 Nov, 2020"
},
{
"code": null,
"e": 289,
"s": 28,
"text": "React is a declarative, efficient, and flexible JavaScript library for building user interfaces. It’s ‘V’ in MVC. ReactJS is an open-source, component-based front end library responsible only for the view layer of the application. It is maintained by Facebook."
},
{
"code": null,
"e": 564,
"s": 289,
"text": "Select in HTML allows us to choose among multiple values using the dropdown. Here, we are talking about changing select options based on another dropdown. In React, it is very easy to achieve with the help of the state. For those who don’t about state here is a brief of it."
},
{
"code": null,
"e": 682,
"s": 564,
"text": "The STATE of a component is an object that holds some information that may change over the lifetime of the component."
},
{
"code": null,
"e": 806,
"s": 682,
"text": "If you want to know more about the state, please refer to state in react geeksforgeeks and state and lifecycle reactjs.org."
},
{
"code": null,
"e": 999,
"s": 806,
"text": "React has both Class-Based components and Functional Component so for this article, we will use Functional Component. In the Functional component, the state can be managed using useState hook."
},
{
"code": null,
"e": 1097,
"s": 999,
"text": "We want to change the selects options based on other dropdowns so we will follow the below steps."
},
{
"code": null,
"e": 1578,
"s": 1097,
"text": "Create a state variable that is initially null or undefined.Create different arrays for different dropdowns.Create a local variable say type that will hold any of the array based on the dropdown selected.Create a function that will be called whenever an option from the dropdown is selected, this function will change the state variable so that the value of type can be determined dynamically.Lastly, use type variables to create a different set of options that the user will see."
},
{
"code": null,
"e": 1639,
"s": 1578,
"text": "Create a state variable that is initially null or undefined."
},
{
"code": null,
"e": 1688,
"s": 1639,
"text": "Create different arrays for different dropdowns."
},
{
"code": null,
"e": 1785,
"s": 1688,
"text": "Create a local variable say type that will hold any of the array based on the dropdown selected."
},
{
"code": null,
"e": 1975,
"s": 1785,
"text": "Create a function that will be called whenever an option from the dropdown is selected, this function will change the state variable so that the value of type can be determined dynamically."
},
{
"code": null,
"e": 2063,
"s": 1975,
"text": "Lastly, use type variables to create a different set of options that the user will see."
},
{
"code": null,
"e": 2131,
"s": 2063,
"text": "Now we will create a Component using all the steps described above."
},
{
"code": null,
"e": 2179,
"s": 2131,
"text": "App.js: Below is the code for App.js component."
},
{
"code": null,
"e": 2190,
"s": 2179,
"text": "Javascript"
},
{
"code": "import * as React from \"react\"; const App = () => { /** \"selected\" here is state variable which will hold the * value of currently selected dropdown. */ const [selected, setSelected] = React.useState(\"\"); /** Function that will set different values to state variable * based on which dropdown is selected */ const changeSelectOptionHandler = (event) => { setSelected(event.target.value); }; /** Different arrays for different dropdowns */ const algorithm = [ \"Searching Algorithm\", \"Sorting Algorithm\", \"Graph Algorithm\", ]; const language = [\"C++\", \"Java\", \"Python\", \"C#\"]; const dataStructure = [\"Arrays\", \"LinkedList\", \"Stack\", \"Queue\"]; /** Type variable to store different array for different dropdown */ let type = null; /** This will be used to create set of options that user will see */ let options = null; /** Setting Type variable according to dropdown */ if (selected === \"Algorithm\") { type = algorithm; } else if (selected === \"Language\") { type = language; } else if (selected === \"Data Structure\") { type = dataStructure; } /** If \"Type\" is null or undefined then options will be null, * otherwise it will create a options iterable based on our array */ if (type) { options = type.map((el) => <option key={el}>{el}</option>); } return ( <div style={{ padding: \"16px\", margin: \"16px\", }} > <form> <div> {/** Bind changeSelectOptionHandler to onChange method of select. * This method will trigger every time different * option is selected. */} <select onChange={changeSelectOptionHandler}> <option>Choose...</option> <option>Algorithm</option> <option>Language</option> <option>Data Structure</option> </select> </div> <div> <select> { /** This is where we have used our options variable */ options } </select> </div> </form> </div> );}; export default App;",
"e": 4274,
"s": 2190,
"text": null
},
{
"code": null,
"e": 4282,
"s": 4274,
"text": "Output:"
},
{
"code": null,
"e": 4357,
"s": 4282,
"text": "Note: You can also use the Class-Based component, logic would be the same."
},
{
"code": null,
"e": 4366,
"s": 4357,
"text": "react-js"
},
{
"code": null,
"e": 4390,
"s": 4366,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 4401,
"s": 4390,
"text": "JavaScript"
},
{
"code": null,
"e": 4420,
"s": 4401,
"text": "Technical Scripter"
},
{
"code": null,
"e": 4518,
"s": 4420,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4579,
"s": 4518,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 4651,
"s": 4579,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 4691,
"s": 4651,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 4732,
"s": 4691,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 4784,
"s": 4732,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 4830,
"s": 4784,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 4872,
"s": 4830,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 4926,
"s": 4872,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 4981,
"s": 4926,
"text": "How do you run JavaScript script through the Terminal?"
}
] |
bg - Unix, Linux Command
|
bg - Sends job to background.
bg [PID...]
bg sends the specified jobs to the background. A background job is executed simultaneously with fish, and does not have access to the keyboard. If no job is specified, the last job to be used is put in the background. The PID of the desired process is usually found by using process expansion.
To put the job with job id 0 in the background.
|
[
{
"code": null,
"e": 10741,
"s": 10711,
"text": "bg - Sends job to background."
},
{
"code": null,
"e": 10753,
"s": 10741,
"text": "bg [PID...]"
},
{
"code": null,
"e": 11047,
"s": 10753,
"text": "bg sends the specified jobs to the background. A background job is executed simultaneously with fish, and does not have access to the keyboard. If no job is specified, the last job to be used is put in the background. The PID of the desired process is usually found by using process expansion."
}
] |
Static method in Interface in Java
|
22 Sep, 2021
Static Methods in Interface are those methods, which are defined in the interface with the keyword static. Unlike other methods in Interface, these static methods contain the complete definition of the function and since the definition is complete and the method is static, therefore these methods cannot be overridden or changed in the implementation class.Similar to Default Method in Interface, the static method in an interface can be defined in the interface, but cannot be overridden in Implementation Classes. To use a static method, Interface name should be instantiated with it, as it is a part of the Interface only.Below programs illustrate static methods in interfaces:Program 1: To demonstrate use of Static method in Interface.In this program, a simple static method is defined and declared in an interface which is being called in the main() method of the Implementation Class InterfaceDemo. Unlike the default method, the static method defines in Interface hello(), cannot be overridden in implementing the class.
Java
// Java program to demonstrate// static method in Interface. interface NewInterface { // static method static void hello() { System.out.println("Hello, New Static Method Here"); } // Public and abstract method of Interface void overrideMethod(String str);} // Implementation Classpublic class InterfaceDemo implements NewInterface { public static void main(String[] args) { InterfaceDemo interfaceDemo = new InterfaceDemo(); // Calling the static method of interface NewInterface.hello(); // Calling the abstract method of interface interfaceDemo.overrideMethod("Hello, Override Method here"); } // Implementing interface method @Override public void overrideMethod(String str) { System.out.println(str); }}
Hello, New Static Method Here
Hello, Override Method here
Program 2: To demonstrate Scope of Static method.In this program, the scope of the static method definition is within the interface only. If same name method is implemented in the implementation class then that method becomes a static member of that respective class.
Java
// Java program to demonstrate scope// of static method in Interface. interface PrintDemo { // Static Method static void hello() { System.out.println("Called from Interface PrintDemo"); }} public class InterfaceDemo implements PrintDemo { public static void main(String[] args) { // Call Interface method as Interface // name is preceding with method PrintDemo.hello(); // Call Class static method hello(); } // Class Static method is defined static void hello() { System.out.println("Called from Class"); }}
Called from Interface PrintDemo
Called from Class
solokiran1
ruhelaa48
java-interfaces
Static Keyword
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Collections in Java
Singleton Class in Java
Multidimensional Arrays in Java
Set in Java
Stack Class in Java
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n22 Sep, 2021"
},
{
"code": null,
"e": 1083,
"s": 52,
"text": "Static Methods in Interface are those methods, which are defined in the interface with the keyword static. Unlike other methods in Interface, these static methods contain the complete definition of the function and since the definition is complete and the method is static, therefore these methods cannot be overridden or changed in the implementation class.Similar to Default Method in Interface, the static method in an interface can be defined in the interface, but cannot be overridden in Implementation Classes. To use a static method, Interface name should be instantiated with it, as it is a part of the Interface only.Below programs illustrate static methods in interfaces:Program 1: To demonstrate use of Static method in Interface.In this program, a simple static method is defined and declared in an interface which is being called in the main() method of the Implementation Class InterfaceDemo. Unlike the default method, the static method defines in Interface hello(), cannot be overridden in implementing the class. "
},
{
"code": null,
"e": 1088,
"s": 1083,
"text": "Java"
},
{
"code": "// Java program to demonstrate// static method in Interface. interface NewInterface { // static method static void hello() { System.out.println(\"Hello, New Static Method Here\"); } // Public and abstract method of Interface void overrideMethod(String str);} // Implementation Classpublic class InterfaceDemo implements NewInterface { public static void main(String[] args) { InterfaceDemo interfaceDemo = new InterfaceDemo(); // Calling the static method of interface NewInterface.hello(); // Calling the abstract method of interface interfaceDemo.overrideMethod(\"Hello, Override Method here\"); } // Implementing interface method @Override public void overrideMethod(String str) { System.out.println(str); }}",
"e": 1894,
"s": 1088,
"text": null
},
{
"code": null,
"e": 1952,
"s": 1894,
"text": "Hello, New Static Method Here\nHello, Override Method here"
},
{
"code": null,
"e": 2223,
"s": 1954,
"text": "Program 2: To demonstrate Scope of Static method.In this program, the scope of the static method definition is within the interface only. If same name method is implemented in the implementation class then that method becomes a static member of that respective class. "
},
{
"code": null,
"e": 2228,
"s": 2223,
"text": "Java"
},
{
"code": "// Java program to demonstrate scope// of static method in Interface. interface PrintDemo { // Static Method static void hello() { System.out.println(\"Called from Interface PrintDemo\"); }} public class InterfaceDemo implements PrintDemo { public static void main(String[] args) { // Call Interface method as Interface // name is preceding with method PrintDemo.hello(); // Call Class static method hello(); } // Class Static method is defined static void hello() { System.out.println(\"Called from Class\"); }}",
"e": 2824,
"s": 2228,
"text": null
},
{
"code": null,
"e": 2874,
"s": 2824,
"text": "Called from Interface PrintDemo\nCalled from Class"
},
{
"code": null,
"e": 2887,
"s": 2876,
"text": "solokiran1"
},
{
"code": null,
"e": 2897,
"s": 2887,
"text": "ruhelaa48"
},
{
"code": null,
"e": 2913,
"s": 2897,
"text": "java-interfaces"
},
{
"code": null,
"e": 2928,
"s": 2913,
"text": "Static Keyword"
},
{
"code": null,
"e": 2933,
"s": 2928,
"text": "Java"
},
{
"code": null,
"e": 2938,
"s": 2933,
"text": "Java"
},
{
"code": null,
"e": 3036,
"s": 2938,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3087,
"s": 3036,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 3118,
"s": 3087,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 3137,
"s": 3118,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 3167,
"s": 3137,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 3185,
"s": 3167,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 3205,
"s": 3185,
"text": "Collections in Java"
},
{
"code": null,
"e": 3229,
"s": 3205,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 3261,
"s": 3229,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 3273,
"s": 3261,
"text": "Set in Java"
}
] |
random.triangular() method in Python
|
17 May, 2020
triangular() is an inbuilt method of the random module. It is used to return a random floating point number within a range with a bias towards one extreme.
Syntax : random.triangular(low, high, mode)
Parameters :low : the lower limit of the random numberhigh : the upper limit of the random numbermode : additional bias; low < mode < high
if the parameters are (10, 100, 20) then due to the bias, most of the random numbers generated will be closer to 10 as opposed to 100.
Returns : a random floating number
Example 1:
# import the random moduleimport random # determining the values of the parameterslow = 10high = 100mode = 20 # using the triangular() methodprint(random.triangular(low, high, mode))
Output :
22.614510550239572
Example 2: If we generate the number multiple times we can probably identify the bias.
# import the random moduleimport random # determining the values of the parameterslow = 10high = 100mode = 20 # running the triangular method with the# same parameters multiple timesfor i in range(10): print(random.triangular(low, high, mode))
Output :
58.645768016894735
46.690692250503226
33.57590419190895
52.331804090351305
33.09451214875767
12.03845752596168
32.816080679206294
20.4739124559502
82.49208123077557
63.511062284733015
Example 3: We can visualize the triangular pattern by plotting a graph.
# import the required librariesimport randomimport matplotlib.pyplot as plt # store the random numbers in a listnums = []low = 10high = 100mode = 20 for i in range(10000): temp = random.triangular(low, high, mode) nums.append(temp) # plotting a graphplt.hist(nums, bins = 200)plt.show()
Output :
Python-random
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python Dictionary
Different ways to create Pandas Dataframe
Taking input in Python
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n17 May, 2020"
},
{
"code": null,
"e": 184,
"s": 28,
"text": "triangular() is an inbuilt method of the random module. It is used to return a random floating point number within a range with a bias towards one extreme."
},
{
"code": null,
"e": 228,
"s": 184,
"text": "Syntax : random.triangular(low, high, mode)"
},
{
"code": null,
"e": 367,
"s": 228,
"text": "Parameters :low : the lower limit of the random numberhigh : the upper limit of the random numbermode : additional bias; low < mode < high"
},
{
"code": null,
"e": 502,
"s": 367,
"text": "if the parameters are (10, 100, 20) then due to the bias, most of the random numbers generated will be closer to 10 as opposed to 100."
},
{
"code": null,
"e": 537,
"s": 502,
"text": "Returns : a random floating number"
},
{
"code": null,
"e": 548,
"s": 537,
"text": "Example 1:"
},
{
"code": "# import the random moduleimport random # determining the values of the parameterslow = 10high = 100mode = 20 # using the triangular() methodprint(random.triangular(low, high, mode))",
"e": 733,
"s": 548,
"text": null
},
{
"code": null,
"e": 742,
"s": 733,
"text": "Output :"
},
{
"code": null,
"e": 761,
"s": 742,
"text": "22.614510550239572"
},
{
"code": null,
"e": 848,
"s": 761,
"text": "Example 2: If we generate the number multiple times we can probably identify the bias."
},
{
"code": "# import the random moduleimport random # determining the values of the parameterslow = 10high = 100mode = 20 # running the triangular method with the# same parameters multiple timesfor i in range(10): print(random.triangular(low, high, mode))",
"e": 1097,
"s": 848,
"text": null
},
{
"code": null,
"e": 1106,
"s": 1097,
"text": "Output :"
},
{
"code": null,
"e": 1290,
"s": 1106,
"text": "58.645768016894735\n46.690692250503226\n33.57590419190895\n52.331804090351305\n33.09451214875767\n12.03845752596168\n32.816080679206294\n20.4739124559502\n82.49208123077557\n63.511062284733015"
},
{
"code": null,
"e": 1362,
"s": 1290,
"text": "Example 3: We can visualize the triangular pattern by plotting a graph."
},
{
"code": "# import the required librariesimport randomimport matplotlib.pyplot as plt # store the random numbers in a listnums = []low = 10high = 100mode = 20 for i in range(10000): temp = random.triangular(low, high, mode) nums.append(temp) # plotting a graphplt.hist(nums, bins = 200)plt.show()",
"e": 1664,
"s": 1362,
"text": null
},
{
"code": null,
"e": 1673,
"s": 1664,
"text": "Output :"
},
{
"code": null,
"e": 1687,
"s": 1673,
"text": "Python-random"
},
{
"code": null,
"e": 1694,
"s": 1687,
"text": "Python"
},
{
"code": null,
"e": 1792,
"s": 1694,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1820,
"s": 1792,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 1870,
"s": 1820,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 1892,
"s": 1870,
"text": "Python map() function"
},
{
"code": null,
"e": 1936,
"s": 1892,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 1954,
"s": 1936,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1996,
"s": 1954,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2019,
"s": 1996,
"text": "Taking input in Python"
},
{
"code": null,
"e": 2041,
"s": 2019,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2076,
"s": 2041,
"text": "Read a file line by line in Python"
}
] |
Matplotlib.pyplot.ginput() in Python
|
30 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. There are various plots which can be used in Pyplot are Line Plot, Contour, Histogram, Scatter, 3D Plot, etc.
The ginput() method pyplot module of matplotlib library is used to block call to interact with a figure.
Syntax: matplotlib.pyplot.ginput(n=1, timeout=30, show_clicks=True, mouse_add=1, mouse_pop=3, mouse_stop=2)
Parameters: This method accept the following parameters that are described below:
n : This parameter is the number of mouse clicks to accumulate.
timeout : This parameter is the number of seconds to wait before timing out.
show_clicks : This parameter is used to show a red cross at the location of each click.
mouse_add : This parameter is the Mouse button used to add points.
mouse_pop : This parameter is the Mouse button used to remove the most recently added point.
mouse_stop : This parameter is the Mouse button used to stop input.
Returns: This method return the list of the clicked (x, y) coordinates.
Below examples illustrate the matplotlib.pyplot.ginput() function in matplotlib.pyplot:
Example 1:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as npt = np.arange(10) plt.plot(t, np.sin(t)) plt.title('matplotlib.pyplot.ginput()\ function Example', fontweight ="bold") print("After 3 clicks :")x = plt.ginput(3)print(x) plt.show()
Output:
After 3 clicks :
[(4.460080645161289, 0.5915838985273842),
(4.460080645161289, 0.5915838985273842),
(4.460080645161289, 0.5915838985273842)]
Example 2:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np np.random.seed(10**7) x1 = np.random.rand(103, 53) plt.title('matplotlib.pyplot.ginput() function\ Example', fontweight ="bold") print("After 2 clicks :")plt.imshow(x1)x = plt.ginput(2) print(x) plt.show()
Output:
After 2 clicks :
[(8.443181818181813, 38.90530303030302),
(8.443181818181813, 38.90530303030302)]
Matplotlib Pyplot-class
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Apr, 2020"
},
{
"code": null,
"e": 333,
"s": 28,
"text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. There are various plots which can be used in Pyplot are Line Plot, Contour, Histogram, Scatter, 3D Plot, etc."
},
{
"code": null,
"e": 438,
"s": 333,
"text": "The ginput() method pyplot module of matplotlib library is used to block call to interact with a figure."
},
{
"code": null,
"e": 546,
"s": 438,
"text": "Syntax: matplotlib.pyplot.ginput(n=1, timeout=30, show_clicks=True, mouse_add=1, mouse_pop=3, mouse_stop=2)"
},
{
"code": null,
"e": 628,
"s": 546,
"text": "Parameters: This method accept the following parameters that are described below:"
},
{
"code": null,
"e": 692,
"s": 628,
"text": "n : This parameter is the number of mouse clicks to accumulate."
},
{
"code": null,
"e": 769,
"s": 692,
"text": "timeout : This parameter is the number of seconds to wait before timing out."
},
{
"code": null,
"e": 857,
"s": 769,
"text": "show_clicks : This parameter is used to show a red cross at the location of each click."
},
{
"code": null,
"e": 924,
"s": 857,
"text": "mouse_add : This parameter is the Mouse button used to add points."
},
{
"code": null,
"e": 1017,
"s": 924,
"text": "mouse_pop : This parameter is the Mouse button used to remove the most recently added point."
},
{
"code": null,
"e": 1085,
"s": 1017,
"text": "mouse_stop : This parameter is the Mouse button used to stop input."
},
{
"code": null,
"e": 1157,
"s": 1085,
"text": "Returns: This method return the list of the clicked (x, y) coordinates."
},
{
"code": null,
"e": 1245,
"s": 1157,
"text": "Below examples illustrate the matplotlib.pyplot.ginput() function in matplotlib.pyplot:"
},
{
"code": null,
"e": 1256,
"s": 1245,
"text": "Example 1:"
},
{
"code": "# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as npt = np.arange(10) plt.plot(t, np.sin(t)) plt.title('matplotlib.pyplot.ginput()\\ function Example', fontweight =\"bold\") print(\"After 3 clicks :\")x = plt.ginput(3)print(x) plt.show()",
"e": 1537,
"s": 1256,
"text": null
},
{
"code": null,
"e": 1545,
"s": 1537,
"text": "Output:"
},
{
"code": null,
"e": 1689,
"s": 1545,
"text": "After 3 clicks :\n[(4.460080645161289, 0.5915838985273842), \n(4.460080645161289, 0.5915838985273842), \n(4.460080645161289, 0.5915838985273842)]\n"
},
{
"code": null,
"e": 1700,
"s": 1689,
"text": "Example 2:"
},
{
"code": "# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np np.random.seed(10**7) x1 = np.random.rand(103, 53) plt.title('matplotlib.pyplot.ginput() function\\ Example', fontweight =\"bold\") print(\"After 2 clicks :\")plt.imshow(x1)x = plt.ginput(2) print(x) plt.show()",
"e": 2012,
"s": 1700,
"text": null
},
{
"code": null,
"e": 2020,
"s": 2012,
"text": "Output:"
},
{
"code": null,
"e": 2120,
"s": 2020,
"text": "After 2 clicks :\n[(8.443181818181813, 38.90530303030302), \n(8.443181818181813, 38.90530303030302)]\n"
},
{
"code": null,
"e": 2144,
"s": 2120,
"text": "Matplotlib Pyplot-class"
},
{
"code": null,
"e": 2162,
"s": 2144,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 2169,
"s": 2162,
"text": "Python"
},
{
"code": null,
"e": 2267,
"s": 2169,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2285,
"s": 2267,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2327,
"s": 2285,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2349,
"s": 2327,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2384,
"s": 2349,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2410,
"s": 2384,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2442,
"s": 2410,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2471,
"s": 2442,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2498,
"s": 2471,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2528,
"s": 2498,
"text": "Iterate over a list in Python"
}
] |
numpy.trunc() in Python
|
04 Dec, 2020
The numpy.trunc() is a mathematical function that returns the truncated value of the elements of array. The trunc of the scalar x is the nearest integer i which, closer to zero than x. This simply means that, the fractional part of the signed number x is discarded by this function.
Syntax : numpy.trunc(x[, out]) = ufunc ‘trunc’)Parameters :
a : [array_like] Input array
Return :The truncated of each element, with float data-type
Code #1 : Working
# Python program explaining# trunc() function import numpy as np in_array = [.5, 1.5, 2.5, 3.5, 4.5, 10.1]print ("Input array : \n", in_array) truncoff_values = np.trunc(in_array)print ("\nRounded values : \n", truncoff_values) in_array = [.53, 1.54, .71]print ("\nInput array : \n", in_array) truncoff_values = np.trunc(in_array)print ("\nRounded values : \n", truncoff_values) in_array = [.5538, 1.33354, .71445]print ("\nInput array : \n", in_array) truncoff_values = np.trunc(in_array)print ("\nRounded values : \n", truncoff_values)
Output :
Input array :
[0.5, 1.5, 2.5, 3.5, 4.5, 10.1]
Rounded values :
[ 0. 1. 2. 3. 4. 10.]
Input array :
[0.53, 1.54, 0.71]
Rounded values :
[ 0. 1. 0.]
Input array :
[0.5538, 1.33354, 0.71445]
Rounded values :
[ 0. 1. 0.]
Code 2 : Working
# Python program explaining# trunc() function import numpy as np in_array = [1.67, 4.5, 7, 9, 12]print ("Input array : \n", in_array) truncoff_values = np.trunc(in_array)print ("\nRounded values : \n", truncoff_values) in_array = [133.000, 344.54, 437.56, 44.9, 1.2]print ("\nInput array : \n", in_array) truncoff_values = np.trunc(in_array)print ("\nRounded values upto 2: \n", truncoff_values)
Output :
Input array :
[1.67, 4.5, 7, 9, 12]
Rounded values :
[ 1. 4. 7. 9. 12.]
Input array :
[133.0, 344.54, 437.56, 44.9, 1.2]
Rounded values upto 2:
[ 133. 344. 437. 44. 1.]
References : https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.trunc.html#numpy.trunc.
Python numpy-Mathematical Function
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Introduction To PYTHON
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Create a directory in Python
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n04 Dec, 2020"
},
{
"code": null,
"e": 311,
"s": 28,
"text": "The numpy.trunc() is a mathematical function that returns the truncated value of the elements of array. The trunc of the scalar x is the nearest integer i which, closer to zero than x. This simply means that, the fractional part of the signed number x is discarded by this function."
},
{
"code": null,
"e": 371,
"s": 311,
"text": "Syntax : numpy.trunc(x[, out]) = ufunc ‘trunc’)Parameters :"
},
{
"code": null,
"e": 400,
"s": 371,
"text": "a : [array_like] Input array"
},
{
"code": null,
"e": 460,
"s": 400,
"text": "Return :The truncated of each element, with float data-type"
},
{
"code": null,
"e": 478,
"s": 460,
"text": "Code #1 : Working"
},
{
"code": "# Python program explaining# trunc() function import numpy as np in_array = [.5, 1.5, 2.5, 3.5, 4.5, 10.1]print (\"Input array : \\n\", in_array) truncoff_values = np.trunc(in_array)print (\"\\nRounded values : \\n\", truncoff_values) in_array = [.53, 1.54, .71]print (\"\\nInput array : \\n\", in_array) truncoff_values = np.trunc(in_array)print (\"\\nRounded values : \\n\", truncoff_values) in_array = [.5538, 1.33354, .71445]print (\"\\nInput array : \\n\", in_array) truncoff_values = np.trunc(in_array)print (\"\\nRounded values : \\n\", truncoff_values)",
"e": 1025,
"s": 478,
"text": null
},
{
"code": null,
"e": 1034,
"s": 1025,
"text": "Output :"
},
{
"code": null,
"e": 1282,
"s": 1034,
"text": "Input array : \n [0.5, 1.5, 2.5, 3.5, 4.5, 10.1]\n\nRounded values : \n [ 0. 1. 2. 3. 4. 10.]\n\nInput array : \n [0.53, 1.54, 0.71]\n\nRounded values : \n [ 0. 1. 0.]\n\nInput array : \n [0.5538, 1.33354, 0.71445]\n\nRounded values : \n [ 0. 1. 0.]"
},
{
"code": null,
"e": 1301,
"s": 1284,
"text": "Code 2 : Working"
},
{
"code": "# Python program explaining# trunc() function import numpy as np in_array = [1.67, 4.5, 7, 9, 12]print (\"Input array : \\n\", in_array) truncoff_values = np.trunc(in_array)print (\"\\nRounded values : \\n\", truncoff_values) in_array = [133.000, 344.54, 437.56, 44.9, 1.2]print (\"\\nInput array : \\n\", in_array) truncoff_values = np.trunc(in_array)print (\"\\nRounded values upto 2: \\n\", truncoff_values)",
"e": 1704,
"s": 1301,
"text": null
},
{
"code": null,
"e": 1713,
"s": 1704,
"text": "Output :"
},
{
"code": null,
"e": 1908,
"s": 1713,
"text": "Input array : \n [1.67, 4.5, 7, 9, 12]\n\nRounded values : \n [ 1. 4. 7. 9. 12.]\n\nInput array : \n [133.0, 344.54, 437.56, 44.9, 1.2]\n\nRounded values upto 2: \n [ 133. 344. 437. 44. 1.]"
},
{
"code": null,
"e": 2009,
"s": 1908,
"text": " References : https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.trunc.html#numpy.trunc."
},
{
"code": null,
"e": 2044,
"s": 2009,
"text": "Python numpy-Mathematical Function"
},
{
"code": null,
"e": 2057,
"s": 2044,
"text": "Python-numpy"
},
{
"code": null,
"e": 2064,
"s": 2057,
"text": "Python"
},
{
"code": null,
"e": 2162,
"s": 2064,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2194,
"s": 2162,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2221,
"s": 2194,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2252,
"s": 2221,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2275,
"s": 2252,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2296,
"s": 2275,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2352,
"s": 2296,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2394,
"s": 2352,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 2436,
"s": 2394,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 2475,
"s": 2436,
"text": "Python | Get unique values from a list"
}
] |
Coroutine in Python
|
27 Jan, 2022
Prerequisite: GeneratorsWe all are familiar with function which is also known as a subroutine, procedure, sub-process, etc. A function is a sequence of instructions packed as a unit to perform a certain task. When the logic of a complex function is divided into several self-contained steps that are themselves functions, then these functions are called helper functions or subroutines.
Subroutines in Python are called by the main function which is responsible for coordinating the use of these subroutines. Subroutines have a single entry point.
Coroutines are generalizations of subroutines. They are used for cooperative multitasking where a process voluntarily yield (give away) control periodically or when idle in order to enable multiple applications to be run simultaneously. The difference between coroutine and subroutine is :
Unlike subroutines, coroutines have many entry points for suspending and resuming execution. Coroutine can suspend its execution and transfer control to other coroutine and can resume again execution from the point it left off.
Unlike subroutines, there is no main function to call coroutines in a particular order and coordinate the results. Coroutines are cooperative that means they link together to form a pipeline. One coroutine may consume input data and send it to other that process it. Finally, there may be a coroutine to display the result.
Coroutine Vs Thread
Now you might be thinking how coroutine is different from threads, both seem to do the same job. In the case of threads, it’s an operating system (or run time environment) that switches between threads according to the scheduler. While in the case of a coroutine, it’s the programmer and programming language which decides when to switch coroutines. Coroutines work cooperatively multitask by suspending and resuming at set points by the programmer.
Python Coroutine
In Python, coroutines are similar to generators but with few extra methods and slight changes in how we use yield statements. Generators produce data for iteration while coroutines can also consume data. In Python 2.5, a slight modification to the yield statement was introduced, now yield can also be used as an expression. For example on the right side of the assignment –
line = (yield)
whatever value we send to coroutine is captured and returned by (yield) expression.
A value can be sent to the coroutine by send() method. For example, consider this coroutine which prints out the name having the prefix “Dear” in it. We will send names to coroutine using send() method.
Python3
# Python3 program for demonstrating# coroutine execution def print_name(prefix): print("Searching prefix:{}".format(prefix)) while True: name = (yield) if prefix in name: print(name) # calling coroutine, nothing will happencorou = print_name("Dear") # This will start execution of coroutine and# Prints first line "Searching prefix..."# and advance execution to the first yield expressioncorou.__next__() # sending inputscorou.send("Atul")corou.send("Dear Atul")
Output:
Searching prefix:Dear
Dear Atul
Execution of Coroutine
The execution of the coroutine is similar to the generator. When we call coroutine nothing happens, it runs only in response to the next() and sends () method. This can be seen clearly in the above example, as only after calling __next__() method, our coroutine starts executing. After this call, execution advances to the first yield expression, now execution pauses and waits for the value to be sent to corou object. When the first value is sent to it, it checks for prefix and print name if prefix present. After printing the name, it goes through the loop until it encounters the name = (yield) expression again.
Closing a Coroutine
Coroutine might run indefinitely, to close coroutine close() method is used. When a coroutine is closed it generates GeneratorExit exception which can be caught in the caught usual way. After closing the coroutine, if we try to send values, it will raise the StopIteration exception. Following is a simple example :
Python3
# Python3 program for demonstrating# closing a coroutine def print_name(prefix): print("Searching prefix:{}".format(prefix)) try : while True: name = (yield) if prefix in name: print(name) except GeneratorExit: print("Closing coroutine!!") corou = print_name("Dear")corou.__next__()corou.send("Atul")corou.send("Dear Atul")corou.close()
Output:
Searching prefix:Dear
Dear Atul
Closing coroutine!!
Chaining coroutines for creating pipeline
Coroutines can be used to set pipes. We can chain together coroutines and push data through the pipe using send() method. A pipe needs :
An initial source(producer) derives the whole pipeline. The producer is usually not a coroutine, it’s just a simple method.
A sink, which is the endpoint of the pipe. A sink might collect all data and display it.
Following is a simple example of chaining –
Python3
# Python3 program for demonstrating# coroutine chaining def producer(sentence, next_coroutine): ''' Producer which just split strings and feed it to pattern_filter coroutine ''' tokens = sentence.split(" ") for token in tokens: next_coroutine.send(token) next_coroutine.close() def pattern_filter(pattern="ing", next_coroutine=None): ''' Search for pattern in received token and if pattern got matched, send it to print_token() coroutine for printing ''' print("Searching for {}".format(pattern)) try: while True: token = (yield) if pattern in token: next_coroutine.send(token) except GeneratorExit: print("Done with filtering!!") def print_token(): ''' Act as a sink, simply print the received tokens ''' print("I'm sink, i'll print tokens") try: while True: token = (yield) print(token) except GeneratorExit: print("Done with printing!") pt = print_token()pt.__next__()pf = pattern_filter(next_coroutine = pt)pf.__next__() sentence = "Bob is running behind a fast moving car"producer(sentence, pf)
Output:
I'm sink, i'll print tokens
Searching for ing
running
moving
Done with filtering!!
Done with printing!
References
http://www.dabeaz.com/coroutines/Coroutines.pdf
https://en.wikipedia.org/wiki/Coroutine
This article is contributed by Atul Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. 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.
ddeevviissaavviittaa
sagar0719kumar
amartyaghoshgfg
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n27 Jan, 2022"
},
{
"code": null,
"e": 439,
"s": 52,
"text": "Prerequisite: GeneratorsWe all are familiar with function which is also known as a subroutine, procedure, sub-process, etc. A function is a sequence of instructions packed as a unit to perform a certain task. When the logic of a complex function is divided into several self-contained steps that are themselves functions, then these functions are called helper functions or subroutines."
},
{
"code": null,
"e": 601,
"s": 439,
"text": "Subroutines in Python are called by the main function which is responsible for coordinating the use of these subroutines. Subroutines have a single entry point. "
},
{
"code": null,
"e": 893,
"s": 601,
"text": "Coroutines are generalizations of subroutines. They are used for cooperative multitasking where a process voluntarily yield (give away) control periodically or when idle in order to enable multiple applications to be run simultaneously. The difference between coroutine and subroutine is : "
},
{
"code": null,
"e": 1121,
"s": 893,
"text": "Unlike subroutines, coroutines have many entry points for suspending and resuming execution. Coroutine can suspend its execution and transfer control to other coroutine and can resume again execution from the point it left off."
},
{
"code": null,
"e": 1445,
"s": 1121,
"text": "Unlike subroutines, there is no main function to call coroutines in a particular order and coordinate the results. Coroutines are cooperative that means they link together to form a pipeline. One coroutine may consume input data and send it to other that process it. Finally, there may be a coroutine to display the result."
},
{
"code": null,
"e": 1465,
"s": 1445,
"text": "Coroutine Vs Thread"
},
{
"code": null,
"e": 1917,
"s": 1465,
"text": "Now you might be thinking how coroutine is different from threads, both seem to do the same job. In the case of threads, it’s an operating system (or run time environment) that switches between threads according to the scheduler. While in the case of a coroutine, it’s the programmer and programming language which decides when to switch coroutines. Coroutines work cooperatively multitask by suspending and resuming at set points by the programmer. "
},
{
"code": null,
"e": 1934,
"s": 1917,
"text": "Python Coroutine"
},
{
"code": null,
"e": 2310,
"s": 1934,
"text": "In Python, coroutines are similar to generators but with few extra methods and slight changes in how we use yield statements. Generators produce data for iteration while coroutines can also consume data. In Python 2.5, a slight modification to the yield statement was introduced, now yield can also be used as an expression. For example on the right side of the assignment – "
},
{
"code": null,
"e": 2325,
"s": 2310,
"text": "line = (yield)"
},
{
"code": null,
"e": 2410,
"s": 2325,
"text": "whatever value we send to coroutine is captured and returned by (yield) expression. "
},
{
"code": null,
"e": 2614,
"s": 2410,
"text": "A value can be sent to the coroutine by send() method. For example, consider this coroutine which prints out the name having the prefix “Dear” in it. We will send names to coroutine using send() method. "
},
{
"code": null,
"e": 2622,
"s": 2614,
"text": "Python3"
},
{
"code": "# Python3 program for demonstrating# coroutine execution def print_name(prefix): print(\"Searching prefix:{}\".format(prefix)) while True: name = (yield) if prefix in name: print(name) # calling coroutine, nothing will happencorou = print_name(\"Dear\") # This will start execution of coroutine and# Prints first line \"Searching prefix...\"# and advance execution to the first yield expressioncorou.__next__() # sending inputscorou.send(\"Atul\")corou.send(\"Dear Atul\")",
"e": 3116,
"s": 2622,
"text": null
},
{
"code": null,
"e": 3125,
"s": 3116,
"text": "Output: "
},
{
"code": null,
"e": 3157,
"s": 3125,
"text": "Searching prefix:Dear\nDear Atul"
},
{
"code": null,
"e": 3180,
"s": 3157,
"text": "Execution of Coroutine"
},
{
"code": null,
"e": 3800,
"s": 3180,
"text": "The execution of the coroutine is similar to the generator. When we call coroutine nothing happens, it runs only in response to the next() and sends () method. This can be seen clearly in the above example, as only after calling __next__() method, our coroutine starts executing. After this call, execution advances to the first yield expression, now execution pauses and waits for the value to be sent to corou object. When the first value is sent to it, it checks for prefix and print name if prefix present. After printing the name, it goes through the loop until it encounters the name = (yield) expression again. "
},
{
"code": null,
"e": 3820,
"s": 3800,
"text": "Closing a Coroutine"
},
{
"code": null,
"e": 4137,
"s": 3820,
"text": "Coroutine might run indefinitely, to close coroutine close() method is used. When a coroutine is closed it generates GeneratorExit exception which can be caught in the caught usual way. After closing the coroutine, if we try to send values, it will raise the StopIteration exception. Following is a simple example : "
},
{
"code": null,
"e": 4145,
"s": 4137,
"text": "Python3"
},
{
"code": "# Python3 program for demonstrating# closing a coroutine def print_name(prefix): print(\"Searching prefix:{}\".format(prefix)) try : while True: name = (yield) if prefix in name: print(name) except GeneratorExit: print(\"Closing coroutine!!\") corou = print_name(\"Dear\")corou.__next__()corou.send(\"Atul\")corou.send(\"Dear Atul\")corou.close()",
"e": 4558,
"s": 4145,
"text": null
},
{
"code": null,
"e": 4567,
"s": 4558,
"text": "Output: "
},
{
"code": null,
"e": 4619,
"s": 4567,
"text": "Searching prefix:Dear\nDear Atul\nClosing coroutine!!"
},
{
"code": null,
"e": 4661,
"s": 4619,
"text": "Chaining coroutines for creating pipeline"
},
{
"code": null,
"e": 4800,
"s": 4661,
"text": "Coroutines can be used to set pipes. We can chain together coroutines and push data through the pipe using send() method. A pipe needs : "
},
{
"code": null,
"e": 4924,
"s": 4800,
"text": "An initial source(producer) derives the whole pipeline. The producer is usually not a coroutine, it’s just a simple method."
},
{
"code": null,
"e": 5013,
"s": 4924,
"text": "A sink, which is the endpoint of the pipe. A sink might collect all data and display it."
},
{
"code": null,
"e": 5058,
"s": 5013,
"text": "Following is a simple example of chaining – "
},
{
"code": null,
"e": 5066,
"s": 5058,
"text": "Python3"
},
{
"code": "# Python3 program for demonstrating# coroutine chaining def producer(sentence, next_coroutine): ''' Producer which just split strings and feed it to pattern_filter coroutine ''' tokens = sentence.split(\" \") for token in tokens: next_coroutine.send(token) next_coroutine.close() def pattern_filter(pattern=\"ing\", next_coroutine=None): ''' Search for pattern in received token and if pattern got matched, send it to print_token() coroutine for printing ''' print(\"Searching for {}\".format(pattern)) try: while True: token = (yield) if pattern in token: next_coroutine.send(token) except GeneratorExit: print(\"Done with filtering!!\") def print_token(): ''' Act as a sink, simply print the received tokens ''' print(\"I'm sink, i'll print tokens\") try: while True: token = (yield) print(token) except GeneratorExit: print(\"Done with printing!\") pt = print_token()pt.__next__()pf = pattern_filter(next_coroutine = pt)pf.__next__() sentence = \"Bob is running behind a fast moving car\"producer(sentence, pf)",
"e": 6226,
"s": 5066,
"text": null
},
{
"code": null,
"e": 6235,
"s": 6226,
"text": "Output: "
},
{
"code": null,
"e": 6338,
"s": 6235,
"text": "I'm sink, i'll print tokens\nSearching for ing\nrunning\nmoving\nDone with filtering!!\nDone with printing!"
},
{
"code": null,
"e": 6350,
"s": 6338,
"text": "References "
},
{
"code": null,
"e": 6398,
"s": 6350,
"text": "http://www.dabeaz.com/coroutines/Coroutines.pdf"
},
{
"code": null,
"e": 6438,
"s": 6398,
"text": "https://en.wikipedia.org/wiki/Coroutine"
},
{
"code": null,
"e": 6857,
"s": 6438,
"text": "This article is contributed by Atul Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. 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": 6878,
"s": 6857,
"text": "ddeevviissaavviittaa"
},
{
"code": null,
"e": 6893,
"s": 6878,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 6909,
"s": 6893,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 6916,
"s": 6909,
"text": "Python"
}
] |
How to make a C++ class whose objects can only be dynamically allocated?
|
21 Jun, 2022
The problem is to create a class such that the non-dynamic allocation of object causes compiler error. For example, create a class ‘Test’ with following rules.
CPP
Test t1; // Should generate compiler errorTest *t3 = new Test; // Should work fine
The idea is to create a private destructor in the class. When we make a private destructor, the compiler would generate a compiler error for non-dynamically allocated objects because compiler need to remove them from stack segment once they are not in use. Since compiler is not responsible for deallocation of dynamically allocated objects (programmer should explicitly deallocate them), compiler won’t have any problem with them. To avoid memory leak, we create a friend function destructTest() which can be called by users of class to destroy objects.
CPP
#include <iostream>using namespace std; // A class whose object can only be dynamically createdclass Test{private: ~Test() { cout << "Destroying Object\n"; }public: Test() { cout << "Object Created\n"; }friend void destructTest(Test* );}; // Only this function can destruct objects of Testvoid destructTest(Test* ptr){ delete ptr; cout << "Object Destroyed\n";} int main(){ /* Uncommenting following line would cause compiler error */ // Test t1; // create an object Test *ptr = new Test; // destruct the object to avoid memory leak destructTest(ptr); return 0;}
Output:
Object Created
Destroying Object
Object Destroyed
Time Complexity: O(1)
Auxiliary Space: O(1)
If we don’t want to create a friend function, we can also overload delete and delete[] operators in Test, this way we don’t have to call a specific function to delete dynamically allocated objects. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
sweetyty
tarakki100
cpp-constructor
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Function Pointer in C
Multidimensional Arrays in C / C++
Left Shift and Right Shift Operators in C/C++
Different Methods to Reverse a String in C++
Vector in C++ STL
Map in C++ Standard Template Library (STL)
Initialize a vector in C++ (7 different ways)
Set in C++ Standard Template Library (STL)
vector erase() and clear() in C++
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n21 Jun, 2022"
},
{
"code": null,
"e": 215,
"s": 54,
"text": "The problem is to create a class such that the non-dynamic allocation of object causes compiler error. For example, create a class ‘Test’ with following rules. "
},
{
"code": null,
"e": 219,
"s": 215,
"text": "CPP"
},
{
"code": "Test t1; // Should generate compiler errorTest *t3 = new Test; // Should work fine",
"e": 303,
"s": 219,
"text": null
},
{
"code": null,
"e": 859,
"s": 303,
"text": "The idea is to create a private destructor in the class. When we make a private destructor, the compiler would generate a compiler error for non-dynamically allocated objects because compiler need to remove them from stack segment once they are not in use. Since compiler is not responsible for deallocation of dynamically allocated objects (programmer should explicitly deallocate them), compiler won’t have any problem with them. To avoid memory leak, we create a friend function destructTest() which can be called by users of class to destroy objects. "
},
{
"code": null,
"e": 863,
"s": 859,
"text": "CPP"
},
{
"code": "#include <iostream>using namespace std; // A class whose object can only be dynamically createdclass Test{private: ~Test() { cout << \"Destroying Object\\n\"; }public: Test() { cout << \"Object Created\\n\"; }friend void destructTest(Test* );}; // Only this function can destruct objects of Testvoid destructTest(Test* ptr){ delete ptr; cout << \"Object Destroyed\\n\";} int main(){ /* Uncommenting following line would cause compiler error */ // Test t1; // create an object Test *ptr = new Test; // destruct the object to avoid memory leak destructTest(ptr); return 0;}",
"e": 1462,
"s": 863,
"text": null
},
{
"code": null,
"e": 1470,
"s": 1462,
"text": "Output:"
},
{
"code": null,
"e": 1520,
"s": 1470,
"text": "Object Created\nDestroying Object\nObject Destroyed"
},
{
"code": null,
"e": 1542,
"s": 1520,
"text": "Time Complexity: O(1)"
},
{
"code": null,
"e": 1564,
"s": 1542,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 1886,
"s": 1564,
"text": "If we don’t want to create a friend function, we can also overload delete and delete[] operators in Test, this way we don’t have to call a specific function to delete dynamically allocated objects. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above"
},
{
"code": null,
"e": 1895,
"s": 1886,
"text": "sweetyty"
},
{
"code": null,
"e": 1906,
"s": 1895,
"text": "tarakki100"
},
{
"code": null,
"e": 1922,
"s": 1906,
"text": "cpp-constructor"
},
{
"code": null,
"e": 1933,
"s": 1922,
"text": "C Language"
},
{
"code": null,
"e": 1937,
"s": 1933,
"text": "C++"
},
{
"code": null,
"e": 1941,
"s": 1937,
"text": "CPP"
},
{
"code": null,
"e": 2039,
"s": 1941,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2056,
"s": 2039,
"text": "Substring in C++"
},
{
"code": null,
"e": 2078,
"s": 2056,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 2113,
"s": 2078,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 2159,
"s": 2113,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 2204,
"s": 2159,
"text": "Different Methods to Reverse a String in C++"
},
{
"code": null,
"e": 2222,
"s": 2204,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 2265,
"s": 2222,
"text": "Map in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 2311,
"s": 2265,
"text": "Initialize a vector in C++ (7 different ways)"
},
{
"code": null,
"e": 2354,
"s": 2311,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
What is the difference between find() and filter() methods in JavaScript ?
|
04 Apr, 2022
The find() method is used to find all the descendant elements of the selected element. It finds the element in the DOM tree by traversing through the root to leaf.
The filter() method is used to filters all the elements and returns the element that matches and the element that do not match are removed.
The only difference is the filter() method search through all the elements while find() method search through all the child elements only.
Example 1: This example uses the find() method to search the element.<!DOCTYPE html><html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <script> $(document).ready(function() { $("ul").find(":odd") .css("background-color", "yellow"); }); </script></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <h4>Find() Method</h4> <ul> <li>GeeksforGeeks1.</li> <li>GeeksforGeeks2.</li> <ol> <li>GeeksforGeeks3.</li> <li>GeeksforGeeks4.</li> <ul> <li>GeeksforGeeks5.</li> <li>GeeksforGeeks6.</li> </ul> </ol> </ul></body> </html>
<!DOCTYPE html><html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <script> $(document).ready(function() { $("ul").find(":odd") .css("background-color", "yellow"); }); </script></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <h4>Find() Method</h4> <ul> <li>GeeksforGeeks1.</li> <li>GeeksforGeeks2.</li> <ol> <li>GeeksforGeeks3.</li> <li>GeeksforGeeks4.</li> <ul> <li>GeeksforGeeks5.</li> <li>GeeksforGeeks6.</li> </ul> </ol> </ul></body> </html>
Output:
Example 2: Changes made when we use the filter() method for searching.<!DOCTYPE html><html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <script> $(document).ready(function() { $("ul").filter(":odd"). css("background-color", "yellow"); }); </script></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <h4>Find() Method</h4> <ul> <li>GeeksforGeeks1.</li> <li>GeeksforGeeks2.</li> <ol> <li>GeeksforGeeks3.</li> <li>GeeksforGeeks4.</li> <ul> <li>GeeksforGeeks5.</li> <li>GeeksforGeeks6.</li> </ul> </ol> </ul></body> </html>
<!DOCTYPE html><html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <script> $(document).ready(function() { $("ul").filter(":odd"). css("background-color", "yellow"); }); </script></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <h4>Find() Method</h4> <ul> <li>GeeksforGeeks1.</li> <li>GeeksforGeeks2.</li> <ol> <li>GeeksforGeeks3.</li> <li>GeeksforGeeks4.</li> <ul> <li>GeeksforGeeks5.</li> <li>GeeksforGeeks6.</li> </ul> </ol> </ul></body> </html>
Output:
Let us see the Differences in Tabular Form -:
Its syntax is -:
array.find(function(value, Index, array),thisValue)
Its syntax is -:
array.filter(function(value, Index, array), thisValue)
mayank007rawa
HTML-Misc
JavaScript-Misc
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
Roadmap to Learn JavaScript For Beginners
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n04 Apr, 2022"
},
{
"code": null,
"e": 192,
"s": 28,
"text": "The find() method is used to find all the descendant elements of the selected element. It finds the element in the DOM tree by traversing through the root to leaf."
},
{
"code": null,
"e": 332,
"s": 192,
"text": "The filter() method is used to filters all the elements and returns the element that matches and the element that do not match are removed."
},
{
"code": null,
"e": 471,
"s": 332,
"text": "The only difference is the filter() method search through all the elements while find() method search through all the child elements only."
},
{
"code": null,
"e": 1275,
"s": 471,
"text": "Example 1: This example uses the find() method to search the element.<!DOCTYPE html><html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <script> $(document).ready(function() { $(\"ul\").find(\":odd\") .css(\"background-color\", \"yellow\"); }); </script></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <h4>Find() Method</h4> <ul> <li>GeeksforGeeks1.</li> <li>GeeksforGeeks2.</li> <ol> <li>GeeksforGeeks3.</li> <li>GeeksforGeeks4.</li> <ul> <li>GeeksforGeeks5.</li> <li>GeeksforGeeks6.</li> </ul> </ol> </ul></body> </html>"
},
{
"code": "<!DOCTYPE html><html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <script> $(document).ready(function() { $(\"ul\").find(\":odd\") .css(\"background-color\", \"yellow\"); }); </script></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <h4>Find() Method</h4> <ul> <li>GeeksforGeeks1.</li> <li>GeeksforGeeks2.</li> <ol> <li>GeeksforGeeks3.</li> <li>GeeksforGeeks4.</li> <ul> <li>GeeksforGeeks5.</li> <li>GeeksforGeeks6.</li> </ul> </ol> </ul></body> </html>",
"e": 2010,
"s": 1275,
"text": null
},
{
"code": null,
"e": 2018,
"s": 2010,
"text": "Output:"
},
{
"code": null,
"e": 2821,
"s": 2018,
"text": "Example 2: Changes made when we use the filter() method for searching.<!DOCTYPE html><html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <script> $(document).ready(function() { $(\"ul\").filter(\":odd\"). css(\"background-color\", \"yellow\"); }); </script></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <h4>Find() Method</h4> <ul> <li>GeeksforGeeks1.</li> <li>GeeksforGeeks2.</li> <ol> <li>GeeksforGeeks3.</li> <li>GeeksforGeeks4.</li> <ul> <li>GeeksforGeeks5.</li> <li>GeeksforGeeks6.</li> </ul> </ol> </ul></body> </html>"
},
{
"code": "<!DOCTYPE html><html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <script> $(document).ready(function() { $(\"ul\").filter(\":odd\"). css(\"background-color\", \"yellow\"); }); </script></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <h4>Find() Method</h4> <ul> <li>GeeksforGeeks1.</li> <li>GeeksforGeeks2.</li> <ol> <li>GeeksforGeeks3.</li> <li>GeeksforGeeks4.</li> <ul> <li>GeeksforGeeks5.</li> <li>GeeksforGeeks6.</li> </ul> </ol> </ul></body> </html>",
"e": 3554,
"s": 2821,
"text": null
},
{
"code": null,
"e": 3562,
"s": 3554,
"text": "Output:"
},
{
"code": null,
"e": 3608,
"s": 3562,
"text": "Let us see the Differences in Tabular Form -:"
},
{
"code": null,
"e": 3625,
"s": 3608,
"text": "Its syntax is -:"
},
{
"code": null,
"e": 3677,
"s": 3625,
"text": "array.find(function(value, Index, array),thisValue)"
},
{
"code": null,
"e": 3694,
"s": 3677,
"text": "Its syntax is -:"
},
{
"code": null,
"e": 3749,
"s": 3694,
"text": "array.filter(function(value, Index, array), thisValue)"
},
{
"code": null,
"e": 3763,
"s": 3749,
"text": "mayank007rawa"
},
{
"code": null,
"e": 3773,
"s": 3763,
"text": "HTML-Misc"
},
{
"code": null,
"e": 3789,
"s": 3773,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 3800,
"s": 3789,
"text": "JavaScript"
},
{
"code": null,
"e": 3817,
"s": 3800,
"text": "Web Technologies"
},
{
"code": null,
"e": 3844,
"s": 3817,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 3942,
"s": 3844,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4003,
"s": 3942,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 4075,
"s": 4003,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 4115,
"s": 4075,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 4156,
"s": 4115,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 4198,
"s": 4156,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 4260,
"s": 4198,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 4293,
"s": 4260,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 4354,
"s": 4293,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 4404,
"s": 4354,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Python Time Module
|
30 Nov, 2021
In this article, we will discuss the time module and various functions provided by this module with the help of good examples.
As the name suggests Python time module allows to work with time in Python. It allows functionality like getting the current time, pausing the Program from executing, etc. So before starting with this module we need to import it.
The time module comes with Python’s standard utility module, so there is no need to install it externally. We can simply import it using the import statement.
import time
The epoch is the point where the time starts and is platform-dependent. On Windows and most Unix systems, the epoch is January 1, 1970, 00:00:00 (UTC), and leap seconds are not counted towards the time in seconds since the epoch. To check what the epoch is on a given platform we can use time.gmtime(0).
Example: Getting epoch
Python3
import time print(time.gmtime(0))
Output:
time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=1, tm_isdst=0)
From the above example, you can see that epoch is 1 January 1970. This means that 2 January 1970 can be expressed as 86400 seconds since epoch as there are 86400 seconds in a day.
Note: The time before the epoch can still be represented in seconds but it will be negative. For example, 31 December 1969 will be represented as -86400 seconds.
Getting current time in seconds since epoch
time.time() methods return the current time in seconds since epoch. It returns a floating-point number.
Example: Current time in seconds since epoch
Python3
import time curr = time.time()print("Current time in seconds since epoch =", curr)
Current time in seconds since epoch = 1627908387.764925
time.ctime() function returns a 24 character time string but takes seconds as argument and computes time till mentioned seconds. If no argument is passed, time is calculated till the present.
Example: Getting time string from seconds
Python3
import time # getting current time by passing# the number of seconds since epochcurr = time.ctime(1627908313.717886)print("Current time:", curr)
Current time: Mon Aug 2 12:45:13 2021
Execution can be delayed using time.sleep() method. This method is used to halt the program execution for the time specified in the arguments.
Example: Delaying execution time of programs in Python.
Python3
import time for i in range(4): # using sleep() to hault execution time.sleep(1) print(i)
0
1
2
3
Struct_time class helps to access local time i.e. non-epochal timestamps. It returns a named tuple whose value can be accessed by both index and attribute name. Its object contains the following attributes –
This class contains various functions. Let’s discuss each function in detail.
localtime() method returns the struct_time object in local time. It takes the number of seconds passed since epoch as an argument. If the seconds parameter is not given then the current time returned by time.time() method is used.
Example: Getting local time from epoch
Python3
# importing time moduleimport time # Convert the current time in seconds# since the epoch to a# time.struct_time object in Local timeobj = time.localtime(1627987508.6496193) print(obj)
Output
time.struct_time(tm_year=2021, tm_mon=8, tm_mday=3, tm_hour=16, tm_min=15, tm_sec=8, tm_wday=1, tm_yday=215, tm_isdst=0)
time.mktime() is the inverse function of time.localtime() which converts the time expressed in seconds since the epoch to a time.struct_time object in local time.
Example: Converting the struct_time object to seconds since epoch
Python3
# importing time moduleimport time obj1 = time.gmtime(1627987508.6496193) # Convert the time.struct_time# object to local time expressed in# seconds since the epoch# using time.mktime() methodtime_sec = time.mktime(obj1) # Print the local time in secondsprint("Local time (in seconds):", time_sec)
Local time (in seconds): 1627987508.0
time.gmtime() is used to convert a time expressed in seconds since the epoch to a time.struct_time object in UTC in which tm_isdst attribute is always 0. If the seconds parameter is not given then the current time returned by time.time() method is used.
Example: Use of time.gmtime() method
Python3
# importing time moduleimport time # Convert the current time in seconds# since the epoch to a# time.struct_time object in UTCobj = time.gmtime(1627987508.6496193) # Print the time.struct.time objectprint(obj)
Output
time.struct_time(tm_year=2021, tm_mon=8, tm_mday=3, tm_hour=10, tm_min=45, tm_sec=8, tm_wday=1, tm_yday=215, tm_isdst=0)
time.strftime() function converts a tuple or struct_time representing a time as returned by gmtime() or localtime() to a string as specified by the format argument. If t is not provided, the current time as returned by localtime() is used. The format must be a string. ValueError is raised if any field in t is outside of the allowed range.
Example: Converting struct_time object to a string using strftime() method
Python3
from time import gmtime, strftime # using simple format of showing times = strftime("%a, %d %b %Y %H:%M:%S", gmtime(1627987508.6496193))print(s)
Tue, 03 Aug 2021 10:45:08
time.asctime() method is used to convert a tuple or a time.struct_time object representing a time as returned by time.gmtime() or time.localtime() method to a string of the following form:
Day Mon Date Hour:Min:Sec Year
Example: Converting tuple to time.struct_time object to string
Python3
# importing time moduleimport time obj = time.gmtime(1627987508.6496193) # Convert the time.struct_time# object to a string of the# form 'Day Mon Date Hour:Min:Sec Year'# using time.asctime() methodtime_str = time.asctime(obj)print(time_str) obj = time.localtime(1627987508.6496193) # Convert the time.struct_time# object to a string of the# form 'Day Mon Date Hour:Min:Sec Year'# using time.asctime() methodtime_str = time.asctime(obj)print(time_str)
Tue Aug 3 10:45:08 2021
Tue Aug 3 10:45:08 2021
time.strptime() method converts the string representing time to the struct_time object.
Example: Converting string to struct_time object.
Python3
import time string = "Tue, 03 Aug 2021 10:45:08"obj = time.strptime(string, "%a, %d %b %Y %H:%M:%S") print(obj)
Output
time.struct_time(tm_year=2021, tm_mon=8, tm_mday=3, tm_hour=10, tm_min=45, tm_sec=8, tm_wday=1, tm_yday=215, tm_isdst=-1)
rkbhola5
python-modules
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n30 Nov, 2021"
},
{
"code": null,
"e": 181,
"s": 53,
"text": "In this article, we will discuss the time module and various functions provided by this module with the help of good examples. "
},
{
"code": null,
"e": 412,
"s": 181,
"text": "As the name suggests Python time module allows to work with time in Python. It allows functionality like getting the current time, pausing the Program from executing, etc. So before starting with this module we need to import it. "
},
{
"code": null,
"e": 571,
"s": 412,
"text": "The time module comes with Python’s standard utility module, so there is no need to install it externally. We can simply import it using the import statement."
},
{
"code": null,
"e": 583,
"s": 571,
"text": "import time"
},
{
"code": null,
"e": 887,
"s": 583,
"text": "The epoch is the point where the time starts and is platform-dependent. On Windows and most Unix systems, the epoch is January 1, 1970, 00:00:00 (UTC), and leap seconds are not counted towards the time in seconds since the epoch. To check what the epoch is on a given platform we can use time.gmtime(0)."
},
{
"code": null,
"e": 910,
"s": 887,
"text": "Example: Getting epoch"
},
{
"code": null,
"e": 918,
"s": 910,
"text": "Python3"
},
{
"code": "import time print(time.gmtime(0))",
"e": 952,
"s": 918,
"text": null
},
{
"code": null,
"e": 960,
"s": 952,
"text": "Output:"
},
{
"code": null,
"e": 1077,
"s": 960,
"text": "time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=1, tm_isdst=0)"
},
{
"code": null,
"e": 1257,
"s": 1077,
"text": "From the above example, you can see that epoch is 1 January 1970. This means that 2 January 1970 can be expressed as 86400 seconds since epoch as there are 86400 seconds in a day."
},
{
"code": null,
"e": 1419,
"s": 1257,
"text": "Note: The time before the epoch can still be represented in seconds but it will be negative. For example, 31 December 1969 will be represented as -86400 seconds."
},
{
"code": null,
"e": 1463,
"s": 1419,
"text": "Getting current time in seconds since epoch"
},
{
"code": null,
"e": 1567,
"s": 1463,
"text": "time.time() methods return the current time in seconds since epoch. It returns a floating-point number."
},
{
"code": null,
"e": 1612,
"s": 1567,
"text": "Example: Current time in seconds since epoch"
},
{
"code": null,
"e": 1620,
"s": 1612,
"text": "Python3"
},
{
"code": "import time curr = time.time()print(\"Current time in seconds since epoch =\", curr)",
"e": 1704,
"s": 1620,
"text": null
},
{
"code": null,
"e": 1760,
"s": 1704,
"text": "Current time in seconds since epoch = 1627908387.764925"
},
{
"code": null,
"e": 1952,
"s": 1760,
"text": "time.ctime() function returns a 24 character time string but takes seconds as argument and computes time till mentioned seconds. If no argument is passed, time is calculated till the present."
},
{
"code": null,
"e": 1994,
"s": 1952,
"text": "Example: Getting time string from seconds"
},
{
"code": null,
"e": 2002,
"s": 1994,
"text": "Python3"
},
{
"code": "import time # getting current time by passing# the number of seconds since epochcurr = time.ctime(1627908313.717886)print(\"Current time:\", curr)",
"e": 2147,
"s": 2002,
"text": null
},
{
"code": null,
"e": 2186,
"s": 2147,
"text": "Current time: Mon Aug 2 12:45:13 2021"
},
{
"code": null,
"e": 2329,
"s": 2186,
"text": "Execution can be delayed using time.sleep() method. This method is used to halt the program execution for the time specified in the arguments."
},
{
"code": null,
"e": 2385,
"s": 2329,
"text": "Example: Delaying execution time of programs in Python."
},
{
"code": null,
"e": 2393,
"s": 2385,
"text": "Python3"
},
{
"code": "import time for i in range(4): # using sleep() to hault execution time.sleep(1) print(i)",
"e": 2496,
"s": 2393,
"text": null
},
{
"code": null,
"e": 2504,
"s": 2496,
"text": "0\n1\n2\n3"
},
{
"code": null,
"e": 2713,
"s": 2504,
"text": "Struct_time class helps to access local time i.e. non-epochal timestamps. It returns a named tuple whose value can be accessed by both index and attribute name. Its object contains the following attributes – "
},
{
"code": null,
"e": 2791,
"s": 2713,
"text": "This class contains various functions. Let’s discuss each function in detail."
},
{
"code": null,
"e": 3022,
"s": 2791,
"text": "localtime() method returns the struct_time object in local time. It takes the number of seconds passed since epoch as an argument. If the seconds parameter is not given then the current time returned by time.time() method is used."
},
{
"code": null,
"e": 3061,
"s": 3022,
"text": "Example: Getting local time from epoch"
},
{
"code": null,
"e": 3069,
"s": 3061,
"text": "Python3"
},
{
"code": "# importing time moduleimport time # Convert the current time in seconds# since the epoch to a# time.struct_time object in Local timeobj = time.localtime(1627987508.6496193) print(obj)",
"e": 3254,
"s": 3069,
"text": null
},
{
"code": null,
"e": 3261,
"s": 3254,
"text": "Output"
},
{
"code": null,
"e": 3382,
"s": 3261,
"text": "time.struct_time(tm_year=2021, tm_mon=8, tm_mday=3, tm_hour=16, tm_min=15, tm_sec=8, tm_wday=1, tm_yday=215, tm_isdst=0)"
},
{
"code": null,
"e": 3545,
"s": 3382,
"text": "time.mktime() is the inverse function of time.localtime() which converts the time expressed in seconds since the epoch to a time.struct_time object in local time."
},
{
"code": null,
"e": 3611,
"s": 3545,
"text": "Example: Converting the struct_time object to seconds since epoch"
},
{
"code": null,
"e": 3619,
"s": 3611,
"text": "Python3"
},
{
"code": "# importing time moduleimport time obj1 = time.gmtime(1627987508.6496193) # Convert the time.struct_time# object to local time expressed in# seconds since the epoch# using time.mktime() methodtime_sec = time.mktime(obj1) # Print the local time in secondsprint(\"Local time (in seconds):\", time_sec)",
"e": 3917,
"s": 3619,
"text": null
},
{
"code": null,
"e": 3955,
"s": 3917,
"text": "Local time (in seconds): 1627987508.0"
},
{
"code": null,
"e": 4209,
"s": 3955,
"text": "time.gmtime() is used to convert a time expressed in seconds since the epoch to a time.struct_time object in UTC in which tm_isdst attribute is always 0. If the seconds parameter is not given then the current time returned by time.time() method is used."
},
{
"code": null,
"e": 4246,
"s": 4209,
"text": "Example: Use of time.gmtime() method"
},
{
"code": null,
"e": 4254,
"s": 4246,
"text": "Python3"
},
{
"code": "# importing time moduleimport time # Convert the current time in seconds# since the epoch to a# time.struct_time object in UTCobj = time.gmtime(1627987508.6496193) # Print the time.struct.time objectprint(obj)",
"e": 4464,
"s": 4254,
"text": null
},
{
"code": null,
"e": 4471,
"s": 4464,
"text": "Output"
},
{
"code": null,
"e": 4592,
"s": 4471,
"text": "time.struct_time(tm_year=2021, tm_mon=8, tm_mday=3, tm_hour=10, tm_min=45, tm_sec=8, tm_wday=1, tm_yday=215, tm_isdst=0)"
},
{
"code": null,
"e": 4933,
"s": 4592,
"text": "time.strftime() function converts a tuple or struct_time representing a time as returned by gmtime() or localtime() to a string as specified by the format argument. If t is not provided, the current time as returned by localtime() is used. The format must be a string. ValueError is raised if any field in t is outside of the allowed range."
},
{
"code": null,
"e": 5008,
"s": 4933,
"text": "Example: Converting struct_time object to a string using strftime() method"
},
{
"code": null,
"e": 5016,
"s": 5008,
"text": "Python3"
},
{
"code": "from time import gmtime, strftime # using simple format of showing times = strftime(\"%a, %d %b %Y %H:%M:%S\", gmtime(1627987508.6496193))print(s)",
"e": 5173,
"s": 5016,
"text": null
},
{
"code": null,
"e": 5199,
"s": 5173,
"text": "Tue, 03 Aug 2021 10:45:08"
},
{
"code": null,
"e": 5388,
"s": 5199,
"text": "time.asctime() method is used to convert a tuple or a time.struct_time object representing a time as returned by time.gmtime() or time.localtime() method to a string of the following form:"
},
{
"code": null,
"e": 5419,
"s": 5388,
"text": "Day Mon Date Hour:Min:Sec Year"
},
{
"code": null,
"e": 5482,
"s": 5419,
"text": "Example: Converting tuple to time.struct_time object to string"
},
{
"code": null,
"e": 5490,
"s": 5482,
"text": "Python3"
},
{
"code": "# importing time moduleimport time obj = time.gmtime(1627987508.6496193) # Convert the time.struct_time# object to a string of the# form 'Day Mon Date Hour:Min:Sec Year'# using time.asctime() methodtime_str = time.asctime(obj)print(time_str) obj = time.localtime(1627987508.6496193) # Convert the time.struct_time# object to a string of the# form 'Day Mon Date Hour:Min:Sec Year'# using time.asctime() methodtime_str = time.asctime(obj)print(time_str)",
"e": 5944,
"s": 5490,
"text": null
},
{
"code": null,
"e": 5994,
"s": 5944,
"text": "Tue Aug 3 10:45:08 2021\nTue Aug 3 10:45:08 2021"
},
{
"code": null,
"e": 6082,
"s": 5994,
"text": "time.strptime() method converts the string representing time to the struct_time object."
},
{
"code": null,
"e": 6132,
"s": 6082,
"text": "Example: Converting string to struct_time object."
},
{
"code": null,
"e": 6140,
"s": 6132,
"text": "Python3"
},
{
"code": "import time string = \"Tue, 03 Aug 2021 10:45:08\"obj = time.strptime(string, \"%a, %d %b %Y %H:%M:%S\") print(obj)",
"e": 6252,
"s": 6140,
"text": null
},
{
"code": null,
"e": 6259,
"s": 6252,
"text": "Output"
},
{
"code": null,
"e": 6381,
"s": 6259,
"text": "time.struct_time(tm_year=2021, tm_mon=8, tm_mday=3, tm_hour=10, tm_min=45, tm_sec=8, tm_wday=1, tm_yday=215, tm_isdst=-1)"
},
{
"code": null,
"e": 6390,
"s": 6381,
"text": "rkbhola5"
},
{
"code": null,
"e": 6405,
"s": 6390,
"text": "python-modules"
},
{
"code": null,
"e": 6412,
"s": 6405,
"text": "Python"
},
{
"code": null,
"e": 6510,
"s": 6412,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6528,
"s": 6510,
"text": "Python Dictionary"
},
{
"code": null,
"e": 6570,
"s": 6528,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 6592,
"s": 6570,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 6627,
"s": 6592,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 6653,
"s": 6627,
"text": "Python String | replace()"
},
{
"code": null,
"e": 6685,
"s": 6653,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 6714,
"s": 6685,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 6741,
"s": 6714,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 6771,
"s": 6741,
"text": "Iterate over a list in Python"
}
] |
Method Overriding in Python
|
23 Jan, 2020
Prerequisite: Inheritance in Python
Method overriding is an ability of any object-oriented programming language that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its super-classes or parent classes. When a method in a subclass has the same name, same parameters or signature and same return type(or sub-type) as a method in its super-class, then the method in the subclass is said to override the method in the super-class.
The version of a method that is executed will be determined by the object that is used to invoke it. If an object of a parent class is used to invoke the method, then the version in the parent class will be executed, but if an object of the subclass is used to invoke the method, then the version in the child class will be executed. In other words, it is the type of the object being referred to (not the type of the reference variable) that determines which version of an overridden method will be executed.
Example:
# Python program to demonstrate # method overriding # Defining parent classclass Parent(): # Constructor def __init__(self): self.value = "Inside Parent" # Parent's show method def show(self): print(self.value) # Defining child classclass Child(Parent): # Constructor def __init__(self): self.value = "Inside Child" # Child's show method def show(self): print(self.value) # Driver's codeobj1 = Parent()obj2 = Child() obj1.show()obj2.show()
Output:
Inside Parent
Inside Child
Multiple Inheritance: When a class is derived from more than one base class it is called multiple Inheritance.Example: Let’s consider an example where we want to override a method of one parent class only. Below is the implementation.# Python program to demonstrate# overriding in multiple inheritance # Defining parent class 1class Parent1(): # Parent's show method def show(self): print("Inside Parent1") # Defining Parent class 2class Parent2(): # Parent's show method def display(self): print("Inside Parent2") # Defining child classclass Child(Parent1, Parent2): # Child's show method def show(self): print("Inside Child") # Driver's codeobj = Child() obj.show()obj.display()Output:Inside Child
Inside Parent2
Multilevel Inheritance: When we have a child and grandchild relationship.Example: Let’s consider an example where we want to override only one method of one of its parent classes. Below is the implementation.# Python program to demonstrate# overriding in multilevel inheritance # Python program to demonstrate# overriding in multilevel inheritance class Parent(): # Parent's show method def display(self): print("Inside Parent") # Inherited or Sub class (Note Parent in bracket) class Child(Parent): # Child's show method def show(self): print("Inside Child") # Inherited or Sub class (Note Child in bracket) class GrandChild(Child): # Child's show method def show(self): print("Inside GrandChild") # Driver code g = GrandChild() g.show()g.display()Output:Inside GrandChild
Inside Parent
Multiple Inheritance: When a class is derived from more than one base class it is called multiple Inheritance.Example: Let’s consider an example where we want to override a method of one parent class only. Below is the implementation.# Python program to demonstrate# overriding in multiple inheritance # Defining parent class 1class Parent1(): # Parent's show method def show(self): print("Inside Parent1") # Defining Parent class 2class Parent2(): # Parent's show method def display(self): print("Inside Parent2") # Defining child classclass Child(Parent1, Parent2): # Child's show method def show(self): print("Inside Child") # Driver's codeobj = Child() obj.show()obj.display()Output:Inside Child
Inside Parent2
Example: Let’s consider an example where we want to override a method of one parent class only. Below is the implementation.
# Python program to demonstrate# overriding in multiple inheritance # Defining parent class 1class Parent1(): # Parent's show method def show(self): print("Inside Parent1") # Defining Parent class 2class Parent2(): # Parent's show method def display(self): print("Inside Parent2") # Defining child classclass Child(Parent1, Parent2): # Child's show method def show(self): print("Inside Child") # Driver's codeobj = Child() obj.show()obj.display()
Output:
Inside Child
Inside Parent2
Multilevel Inheritance: When we have a child and grandchild relationship.Example: Let’s consider an example where we want to override only one method of one of its parent classes. Below is the implementation.# Python program to demonstrate# overriding in multilevel inheritance # Python program to demonstrate# overriding in multilevel inheritance class Parent(): # Parent's show method def display(self): print("Inside Parent") # Inherited or Sub class (Note Parent in bracket) class Child(Parent): # Child's show method def show(self): print("Inside Child") # Inherited or Sub class (Note Child in bracket) class GrandChild(Child): # Child's show method def show(self): print("Inside GrandChild") # Driver code g = GrandChild() g.show()g.display()Output:Inside GrandChild
Inside Parent
Example: Let’s consider an example where we want to override only one method of one of its parent classes. Below is the implementation.
# Python program to demonstrate# overriding in multilevel inheritance # Python program to demonstrate# overriding in multilevel inheritance class Parent(): # Parent's show method def display(self): print("Inside Parent") # Inherited or Sub class (Note Parent in bracket) class Child(Parent): # Child's show method def show(self): print("Inside Child") # Inherited or Sub class (Note Child in bracket) class GrandChild(Child): # Child's show method def show(self): print("Inside GrandChild") # Driver code g = GrandChild() g.show()g.display()
Output:
Inside GrandChild
Inside Parent
Parent class methods can also be called within the overridden methods. This can generally be achieved by two ways.
Using Classname: Parent’s class methods can be called by using the Parent classname.method inside the overridden method.Example:# Python program to demonstrate# calling the parent's class method# inside the overridden method class Parent(): def show(self): print("Inside Parent") class Child(Parent): def show(self): # Calling the parent's class # method Parent.show(self) print("Inside Child") # Driver's codeobj = Child()obj.show()Output:Inside Parent
Inside Child
Example:
# Python program to demonstrate# calling the parent's class method# inside the overridden method class Parent(): def show(self): print("Inside Parent") class Child(Parent): def show(self): # Calling the parent's class # method Parent.show(self) print("Inside Child") # Driver's codeobj = Child()obj.show()
Output:
Inside Parent
Inside Child
Using Super(): Python super() function provides us the facility to refer to the parent class explicitly. It is basically useful where we have to call superclass functions. It returns the proxy object that allows us to refer parent class by ‘super’.Example 1:# Python program to demonstrate# calling the parent's class method# inside the overridden method using# super() class Parent(): def show(self): print("Inside Parent") class Child(Parent): def show(self): # Calling the parent's class # method super().show() print("Inside Child") # Driver's codeobj = Child()obj.show()Output:Inside Parent
Inside Child
Example 2:# Program to define the use of super() # function in multiple inheritance class GFG1: def __init__(self): print('HEY !!!!!! GfG I am initialised(Class GEG1)') def sub_GFG(self, b): print('Printing from class GFG1:', b) # class GFG2 inherits the GFG1 class GFG2(GFG1): def __init__(self): print('HEY !!!!!! GfG I am initialised(Class GEG2)') super().__init__() def sub_GFG(self, b): print('Printing from class GFG2:', b) super().sub_GFG(b + 1) # class GFG3 inherits the GFG1 ang GFG2 both class GFG3(GFG2): def __init__(self): print('HEY !!!!!! GfG I am initialised(Class GEG3)') super().__init__() def sub_GFG(self, b): print('Printing from class GFG3:', b) super().sub_GFG(b + 1) # main function if __name__ == '__main__': # created the object gfg gfg = GFG3() # calling the function sub_GFG3() from class GHG3 # which inherits both GFG1 and GFG2 classes gfg.sub_GFG(10)Output:HEY !!!!!! GfG I am initialised(Class GEG3)
HEY !!!!!! GfG I am initialised(Class GEG2)
HEY !!!!!! GfG I am initialised(Class GEG1)
Printing from class GFG3: 10
Printing from class GFG2: 11
Printing from class GFG1: 12
Example 1:
# Python program to demonstrate# calling the parent's class method# inside the overridden method using# super() class Parent(): def show(self): print("Inside Parent") class Child(Parent): def show(self): # Calling the parent's class # method super().show() print("Inside Child") # Driver's codeobj = Child()obj.show()
Output:
Inside Parent
Inside Child
Example 2:
# Program to define the use of super() # function in multiple inheritance class GFG1: def __init__(self): print('HEY !!!!!! GfG I am initialised(Class GEG1)') def sub_GFG(self, b): print('Printing from class GFG1:', b) # class GFG2 inherits the GFG1 class GFG2(GFG1): def __init__(self): print('HEY !!!!!! GfG I am initialised(Class GEG2)') super().__init__() def sub_GFG(self, b): print('Printing from class GFG2:', b) super().sub_GFG(b + 1) # class GFG3 inherits the GFG1 ang GFG2 both class GFG3(GFG2): def __init__(self): print('HEY !!!!!! GfG I am initialised(Class GEG3)') super().__init__() def sub_GFG(self, b): print('Printing from class GFG3:', b) super().sub_GFG(b + 1) # main function if __name__ == '__main__': # created the object gfg gfg = GFG3() # calling the function sub_GFG3() from class GHG3 # which inherits both GFG1 and GFG2 classes gfg.sub_GFG(10)
Output:
HEY !!!!!! GfG I am initialised(Class GEG3)
HEY !!!!!! GfG I am initialised(Class GEG2)
HEY !!!!!! GfG I am initialised(Class GEG1)
Printing from class GFG3: 10
Printing from class GFG2: 11
Printing from class GFG1: 12
Python-OOP
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Convert integer to string in Python
Introduction To PYTHON
Python | os.path.join() method
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n23 Jan, 2020"
},
{
"code": null,
"e": 89,
"s": 53,
"text": "Prerequisite: Inheritance in Python"
},
{
"code": null,
"e": 549,
"s": 89,
"text": "Method overriding is an ability of any object-oriented programming language that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its super-classes or parent classes. When a method in a subclass has the same name, same parameters or signature and same return type(or sub-type) as a method in its super-class, then the method in the subclass is said to override the method in the super-class."
},
{
"code": null,
"e": 1059,
"s": 549,
"text": "The version of a method that is executed will be determined by the object that is used to invoke it. If an object of a parent class is used to invoke the method, then the version in the parent class will be executed, but if an object of the subclass is used to invoke the method, then the version in the child class will be executed. In other words, it is the type of the object being referred to (not the type of the reference variable) that determines which version of an overridden method will be executed."
},
{
"code": null,
"e": 1068,
"s": 1059,
"text": "Example:"
},
{
"code": "# Python program to demonstrate # method overriding # Defining parent classclass Parent(): # Constructor def __init__(self): self.value = \"Inside Parent\" # Parent's show method def show(self): print(self.value) # Defining child classclass Child(Parent): # Constructor def __init__(self): self.value = \"Inside Child\" # Child's show method def show(self): print(self.value) # Driver's codeobj1 = Parent()obj2 = Child() obj1.show()obj2.show()",
"e": 1624,
"s": 1068,
"text": null
},
{
"code": null,
"e": 1632,
"s": 1624,
"text": "Output:"
},
{
"code": null,
"e": 1660,
"s": 1632,
"text": "Inside Parent\nInside Child\n"
},
{
"code": null,
"e": 3377,
"s": 1660,
"text": "Multiple Inheritance: When a class is derived from more than one base class it is called multiple Inheritance.Example: Let’s consider an example where we want to override a method of one parent class only. Below is the implementation.# Python program to demonstrate# overriding in multiple inheritance # Defining parent class 1class Parent1(): # Parent's show method def show(self): print(\"Inside Parent1\") # Defining Parent class 2class Parent2(): # Parent's show method def display(self): print(\"Inside Parent2\") # Defining child classclass Child(Parent1, Parent2): # Child's show method def show(self): print(\"Inside Child\") # Driver's codeobj = Child() obj.show()obj.display()Output:Inside Child\nInside Parent2\nMultilevel Inheritance: When we have a child and grandchild relationship.Example: Let’s consider an example where we want to override only one method of one of its parent classes. Below is the implementation.# Python program to demonstrate# overriding in multilevel inheritance # Python program to demonstrate# overriding in multilevel inheritance class Parent(): # Parent's show method def display(self): print(\"Inside Parent\") # Inherited or Sub class (Note Parent in bracket) class Child(Parent): # Child's show method def show(self): print(\"Inside Child\") # Inherited or Sub class (Note Child in bracket) class GrandChild(Child): # Child's show method def show(self): print(\"Inside GrandChild\") # Driver code g = GrandChild() g.show()g.display()Output:Inside GrandChild\nInside Parent\n"
},
{
"code": null,
"e": 4206,
"s": 3377,
"text": "Multiple Inheritance: When a class is derived from more than one base class it is called multiple Inheritance.Example: Let’s consider an example where we want to override a method of one parent class only. Below is the implementation.# Python program to demonstrate# overriding in multiple inheritance # Defining parent class 1class Parent1(): # Parent's show method def show(self): print(\"Inside Parent1\") # Defining Parent class 2class Parent2(): # Parent's show method def display(self): print(\"Inside Parent2\") # Defining child classclass Child(Parent1, Parent2): # Child's show method def show(self): print(\"Inside Child\") # Driver's codeobj = Child() obj.show()obj.display()Output:Inside Child\nInside Parent2\n"
},
{
"code": null,
"e": 4331,
"s": 4206,
"text": "Example: Let’s consider an example where we want to override a method of one parent class only. Below is the implementation."
},
{
"code": "# Python program to demonstrate# overriding in multiple inheritance # Defining parent class 1class Parent1(): # Parent's show method def show(self): print(\"Inside Parent1\") # Defining Parent class 2class Parent2(): # Parent's show method def display(self): print(\"Inside Parent2\") # Defining child classclass Child(Parent1, Parent2): # Child's show method def show(self): print(\"Inside Child\") # Driver's codeobj = Child() obj.show()obj.display()",
"e": 4891,
"s": 4331,
"text": null
},
{
"code": null,
"e": 4899,
"s": 4891,
"text": "Output:"
},
{
"code": null,
"e": 4928,
"s": 4899,
"text": "Inside Child\nInside Parent2\n"
},
{
"code": null,
"e": 5817,
"s": 4928,
"text": "Multilevel Inheritance: When we have a child and grandchild relationship.Example: Let’s consider an example where we want to override only one method of one of its parent classes. Below is the implementation.# Python program to demonstrate# overriding in multilevel inheritance # Python program to demonstrate# overriding in multilevel inheritance class Parent(): # Parent's show method def display(self): print(\"Inside Parent\") # Inherited or Sub class (Note Parent in bracket) class Child(Parent): # Child's show method def show(self): print(\"Inside Child\") # Inherited or Sub class (Note Child in bracket) class GrandChild(Child): # Child's show method def show(self): print(\"Inside GrandChild\") # Driver code g = GrandChild() g.show()g.display()Output:Inside GrandChild\nInside Parent\n"
},
{
"code": null,
"e": 5953,
"s": 5817,
"text": "Example: Let’s consider an example where we want to override only one method of one of its parent classes. Below is the implementation."
},
{
"code": "# Python program to demonstrate# overriding in multilevel inheritance # Python program to demonstrate# overriding in multilevel inheritance class Parent(): # Parent's show method def display(self): print(\"Inside Parent\") # Inherited or Sub class (Note Parent in bracket) class Child(Parent): # Child's show method def show(self): print(\"Inside Child\") # Inherited or Sub class (Note Child in bracket) class GrandChild(Child): # Child's show method def show(self): print(\"Inside GrandChild\") # Driver code g = GrandChild() g.show()g.display()",
"e": 6595,
"s": 5953,
"text": null
},
{
"code": null,
"e": 6603,
"s": 6595,
"text": "Output:"
},
{
"code": null,
"e": 6636,
"s": 6603,
"text": "Inside GrandChild\nInside Parent\n"
},
{
"code": null,
"e": 6751,
"s": 6636,
"text": "Parent class methods can also be called within the overridden methods. This can generally be achieved by two ways."
},
{
"code": null,
"e": 7303,
"s": 6751,
"text": "Using Classname: Parent’s class methods can be called by using the Parent classname.method inside the overridden method.Example:# Python program to demonstrate# calling the parent's class method# inside the overridden method class Parent(): def show(self): print(\"Inside Parent\") class Child(Parent): def show(self): # Calling the parent's class # method Parent.show(self) print(\"Inside Child\") # Driver's codeobj = Child()obj.show()Output:Inside Parent\nInside Child\n"
},
{
"code": null,
"e": 7312,
"s": 7303,
"text": "Example:"
},
{
"code": "# Python program to demonstrate# calling the parent's class method# inside the overridden method class Parent(): def show(self): print(\"Inside Parent\") class Child(Parent): def show(self): # Calling the parent's class # method Parent.show(self) print(\"Inside Child\") # Driver's codeobj = Child()obj.show()",
"e": 7702,
"s": 7312,
"text": null
},
{
"code": null,
"e": 7710,
"s": 7702,
"text": "Output:"
},
{
"code": null,
"e": 7738,
"s": 7710,
"text": "Inside Parent\nInside Child\n"
},
{
"code": null,
"e": 9699,
"s": 7738,
"text": "Using Super(): Python super() function provides us the facility to refer to the parent class explicitly. It is basically useful where we have to call superclass functions. It returns the proxy object that allows us to refer parent class by ‘super’.Example 1:# Python program to demonstrate# calling the parent's class method# inside the overridden method using# super() class Parent(): def show(self): print(\"Inside Parent\") class Child(Parent): def show(self): # Calling the parent's class # method super().show() print(\"Inside Child\") # Driver's codeobj = Child()obj.show()Output:Inside Parent\nInside Child\nExample 2:# Program to define the use of super() # function in multiple inheritance class GFG1: def __init__(self): print('HEY !!!!!! GfG I am initialised(Class GEG1)') def sub_GFG(self, b): print('Printing from class GFG1:', b) # class GFG2 inherits the GFG1 class GFG2(GFG1): def __init__(self): print('HEY !!!!!! GfG I am initialised(Class GEG2)') super().__init__() def sub_GFG(self, b): print('Printing from class GFG2:', b) super().sub_GFG(b + 1) # class GFG3 inherits the GFG1 ang GFG2 both class GFG3(GFG2): def __init__(self): print('HEY !!!!!! GfG I am initialised(Class GEG3)') super().__init__() def sub_GFG(self, b): print('Printing from class GFG3:', b) super().sub_GFG(b + 1) # main function if __name__ == '__main__': # created the object gfg gfg = GFG3() # calling the function sub_GFG3() from class GHG3 # which inherits both GFG1 and GFG2 classes gfg.sub_GFG(10)Output:HEY !!!!!! GfG I am initialised(Class GEG3)\nHEY !!!!!! GfG I am initialised(Class GEG2)\nHEY !!!!!! GfG I am initialised(Class GEG1)\nPrinting from class GFG3: 10\nPrinting from class GFG2: 11\nPrinting from class GFG1: 12\n"
},
{
"code": null,
"e": 9710,
"s": 9699,
"text": "Example 1:"
},
{
"code": "# Python program to demonstrate# calling the parent's class method# inside the overridden method using# super() class Parent(): def show(self): print(\"Inside Parent\") class Child(Parent): def show(self): # Calling the parent's class # method super().show() print(\"Inside Child\") # Driver's codeobj = Child()obj.show()",
"e": 10112,
"s": 9710,
"text": null
},
{
"code": null,
"e": 10120,
"s": 10112,
"text": "Output:"
},
{
"code": null,
"e": 10148,
"s": 10120,
"text": "Inside Parent\nInside Child\n"
},
{
"code": null,
"e": 10159,
"s": 10148,
"text": "Example 2:"
},
{
"code": "# Program to define the use of super() # function in multiple inheritance class GFG1: def __init__(self): print('HEY !!!!!! GfG I am initialised(Class GEG1)') def sub_GFG(self, b): print('Printing from class GFG1:', b) # class GFG2 inherits the GFG1 class GFG2(GFG1): def __init__(self): print('HEY !!!!!! GfG I am initialised(Class GEG2)') super().__init__() def sub_GFG(self, b): print('Printing from class GFG2:', b) super().sub_GFG(b + 1) # class GFG3 inherits the GFG1 ang GFG2 both class GFG3(GFG2): def __init__(self): print('HEY !!!!!! GfG I am initialised(Class GEG3)') super().__init__() def sub_GFG(self, b): print('Printing from class GFG3:', b) super().sub_GFG(b + 1) # main function if __name__ == '__main__': # created the object gfg gfg = GFG3() # calling the function sub_GFG3() from class GHG3 # which inherits both GFG1 and GFG2 classes gfg.sub_GFG(10)",
"e": 11191,
"s": 10159,
"text": null
},
{
"code": null,
"e": 11199,
"s": 11191,
"text": "Output:"
},
{
"code": null,
"e": 11419,
"s": 11199,
"text": "HEY !!!!!! GfG I am initialised(Class GEG3)\nHEY !!!!!! GfG I am initialised(Class GEG2)\nHEY !!!!!! GfG I am initialised(Class GEG1)\nPrinting from class GFG3: 10\nPrinting from class GFG2: 11\nPrinting from class GFG1: 12\n"
},
{
"code": null,
"e": 11430,
"s": 11419,
"text": "Python-OOP"
},
{
"code": null,
"e": 11437,
"s": 11430,
"text": "Python"
},
{
"code": null,
"e": 11535,
"s": 11437,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 11577,
"s": 11535,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 11599,
"s": 11577,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 11625,
"s": 11599,
"text": "Python String | replace()"
},
{
"code": null,
"e": 11657,
"s": 11625,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 11686,
"s": 11657,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 11713,
"s": 11686,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 11734,
"s": 11713,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 11770,
"s": 11734,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 11793,
"s": 11770,
"text": "Introduction To PYTHON"
}
] |
SQL Query to Find the Year from Date
|
26 Apr, 2021
Overview :You will be able to understand the implementation to Find the Year from Date in SQL with the help of an example. Here we will see, how to find or extract the year from the given date in MS SQL Server’s database table with the help of SQL query. For the purpose of demonstration, we will be creating a demo_orders table in a database called “geeks“.
Steps to implement SQL Query to Find the Year from Date :Here, we will discuss the steps to implement the SQL Query to Find the Year from Date as follows.
Step-1: Creating the Database :Use the below SQL statement to create a database called geeks as follows.
CREATE DATABASE geeks;
Step-2: Using the Database :Use the below SQL statement to switch the database context to geeks as follows.
USE geeks;
Step-3 : Creating Table :We have the following demo table in our geeks database.
CREATE TABLE demo_orders(
ORDER_ID INT IDENTITY(1,1) PRIMARY KEY,
--IDENTITY(1,1) is same as AUTO_INCREMENT in MySQL.
--Starts from 1 and increases by 1 with each inserted row.
ITEM_NAME VARCHAR(30) NOT NULL,
ORDER_DATE DATE
);
Step-4: Verifying table :You can use the below statement to query the description of the created table as follows.
EXEC SP_COLUMNS demo_orders;
Output :
Step-5: Adding data to the table :Use the below statement to add data to the demo_orders table as follows.
INSERT INTO demo_orders
--no need to mention columns explicitly as we are inserting into all columns and ID gets
--automatically incremented.
VALUES
('Maserati', '2007-10-03'),
('BMW', '2010-07-23'),
('Mercedes Benz', '2012-11-12'),
('Ferrari', '2016-05-09'),
('Lamborghini', '2020-10-20');
Step-6: Verifying Inserted data :To verify the contents of the table use the below statements as follows.
SELECT * FROM demo_orders;
Output :
Step-7: Implementation of Query to Find the Year from Date :Now let’s find the year of the order with ITEM_NAME as ‘Maserati’ with the help of the YEAR() function. Below is the syntax to retrieve the year from the given date.
Syntax –
SELECT YEAR(<date_string>);
--or within a table--
SELECT YEAR(<column_table>) FROM <table_name>;
Example –
SELECT YEAR(ORDER_DATE) AS YEAR_OF_ORDER
FROM demo_orders
WHERE ITEM_NAME='Maserati';
Output :
Step-8: Implementation of Query to Find day, month and year from Date :Similarly, we can find the respective day and month of the given date using DAY() and MONTH() functions.
Example –
SELECT day(order_date)[day], --here [day] is the identifier name for the column in the output.
month(order_date)[month],
year(order_date)[year]
FROM demo_orders
WHERE ITEM_NAME='Lamborghini';
Output :
DBMS-SQL
Picked
DBMS
SQL
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Types of Functional dependencies in DBMS
MySQL | Regular expressions (Regexp)
OLAP Guidelines (Codd's Rule)
Difference between OLAP and OLTP in DBMS
What is Temporary Table in SQL?
SQL | DDL, DQL, DML, DCL and TCL Commands
How to find Nth highest salary from a table
SQL | ALTER (RENAME)
How to Update Multiple Columns in Single Update Statement in SQL?
Window functions in SQL
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n26 Apr, 2021"
},
{
"code": null,
"e": 412,
"s": 53,
"text": "Overview :You will be able to understand the implementation to Find the Year from Date in SQL with the help of an example. Here we will see, how to find or extract the year from the given date in MS SQL Server’s database table with the help of SQL query. For the purpose of demonstration, we will be creating a demo_orders table in a database called “geeks“."
},
{
"code": null,
"e": 567,
"s": 412,
"text": "Steps to implement SQL Query to Find the Year from Date :Here, we will discuss the steps to implement the SQL Query to Find the Year from Date as follows."
},
{
"code": null,
"e": 672,
"s": 567,
"text": "Step-1: Creating the Database :Use the below SQL statement to create a database called geeks as follows."
},
{
"code": null,
"e": 695,
"s": 672,
"text": "CREATE DATABASE geeks;"
},
{
"code": null,
"e": 803,
"s": 695,
"text": "Step-2: Using the Database :Use the below SQL statement to switch the database context to geeks as follows."
},
{
"code": null,
"e": 814,
"s": 803,
"text": "USE geeks;"
},
{
"code": null,
"e": 895,
"s": 814,
"text": "Step-3 : Creating Table :We have the following demo table in our geeks database."
},
{
"code": null,
"e": 1129,
"s": 895,
"text": "CREATE TABLE demo_orders(\n ORDER_ID INT IDENTITY(1,1) PRIMARY KEY, \n --IDENTITY(1,1) is same as AUTO_INCREMENT in MySQL.\n --Starts from 1 and increases by 1 with each inserted row.\n ITEM_NAME VARCHAR(30) NOT NULL,\n ORDER_DATE DATE\n);"
},
{
"code": null,
"e": 1244,
"s": 1129,
"text": "Step-4: Verifying table :You can use the below statement to query the description of the created table as follows."
},
{
"code": null,
"e": 1273,
"s": 1244,
"text": "EXEC SP_COLUMNS demo_orders;"
},
{
"code": null,
"e": 1282,
"s": 1273,
"text": "Output :"
},
{
"code": null,
"e": 1389,
"s": 1282,
"text": "Step-5: Adding data to the table :Use the below statement to add data to the demo_orders table as follows."
},
{
"code": null,
"e": 1682,
"s": 1389,
"text": "INSERT INTO demo_orders \n--no need to mention columns explicitly as we are inserting into all columns and ID gets \n--automatically incremented.\nVALUES\n('Maserati', '2007-10-03'),\n('BMW', '2010-07-23'),\n('Mercedes Benz', '2012-11-12'),\n('Ferrari', '2016-05-09'),\n('Lamborghini', '2020-10-20');"
},
{
"code": null,
"e": 1788,
"s": 1682,
"text": "Step-6: Verifying Inserted data :To verify the contents of the table use the below statements as follows."
},
{
"code": null,
"e": 1815,
"s": 1788,
"text": "SELECT * FROM demo_orders;"
},
{
"code": null,
"e": 1824,
"s": 1815,
"text": "Output :"
},
{
"code": null,
"e": 2050,
"s": 1824,
"text": "Step-7: Implementation of Query to Find the Year from Date :Now let’s find the year of the order with ITEM_NAME as ‘Maserati’ with the help of the YEAR() function. Below is the syntax to retrieve the year from the given date."
},
{
"code": null,
"e": 2059,
"s": 2050,
"text": "Syntax –"
},
{
"code": null,
"e": 2156,
"s": 2059,
"text": "SELECT YEAR(<date_string>);\n--or within a table--\nSELECT YEAR(<column_table>) FROM <table_name>;"
},
{
"code": null,
"e": 2166,
"s": 2156,
"text": "Example –"
},
{
"code": null,
"e": 2252,
"s": 2166,
"text": "SELECT YEAR(ORDER_DATE) AS YEAR_OF_ORDER\nFROM demo_orders\nWHERE ITEM_NAME='Maserati';"
},
{
"code": null,
"e": 2261,
"s": 2252,
"text": "Output :"
},
{
"code": null,
"e": 2437,
"s": 2261,
"text": "Step-8: Implementation of Query to Find day, month and year from Date :Similarly, we can find the respective day and month of the given date using DAY() and MONTH() functions."
},
{
"code": null,
"e": 2447,
"s": 2437,
"text": "Example –"
},
{
"code": null,
"e": 2655,
"s": 2447,
"text": "SELECT day(order_date)[day], --here [day] is the identifier name for the column in the output.\n month(order_date)[month], \n year(order_date)[year]\nFROM demo_orders \nWHERE ITEM_NAME='Lamborghini';"
},
{
"code": null,
"e": 2664,
"s": 2655,
"text": "Output :"
},
{
"code": null,
"e": 2673,
"s": 2664,
"text": "DBMS-SQL"
},
{
"code": null,
"e": 2680,
"s": 2673,
"text": "Picked"
},
{
"code": null,
"e": 2685,
"s": 2680,
"text": "DBMS"
},
{
"code": null,
"e": 2689,
"s": 2685,
"text": "SQL"
},
{
"code": null,
"e": 2694,
"s": 2689,
"text": "DBMS"
},
{
"code": null,
"e": 2698,
"s": 2694,
"text": "SQL"
},
{
"code": null,
"e": 2796,
"s": 2698,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2837,
"s": 2796,
"text": "Types of Functional dependencies in DBMS"
},
{
"code": null,
"e": 2874,
"s": 2837,
"text": "MySQL | Regular expressions (Regexp)"
},
{
"code": null,
"e": 2904,
"s": 2874,
"text": "OLAP Guidelines (Codd's Rule)"
},
{
"code": null,
"e": 2945,
"s": 2904,
"text": "Difference between OLAP and OLTP in DBMS"
},
{
"code": null,
"e": 2977,
"s": 2945,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 3019,
"s": 2977,
"text": "SQL | DDL, DQL, DML, DCL and TCL Commands"
},
{
"code": null,
"e": 3063,
"s": 3019,
"text": "How to find Nth highest salary from a table"
},
{
"code": null,
"e": 3084,
"s": 3063,
"text": "SQL | ALTER (RENAME)"
},
{
"code": null,
"e": 3150,
"s": 3084,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
}
] |
GATE | GATE-CS-2009 | Question 35
|
28 Jun, 2021
The running time of an algorithm is represented by the following recurrence relation:
if n <= 3 then T(n) = n
else T(n) = T(n/3) + cn
Which one of the following represents the time complexity of the algorithm? <pre>(A) (n)(B) (n log n)(C) (n^2)(D) (n^2log n) </pre>
(A) A(B) B(C) C(D) DAnswer: (A)Explanation:
Answer(A)
T(n) = cn + T(n/3)
= cn + cn/3 + T(n/9)
= cn + cn/3 + cn/9 + T(n/27)
Taking the sum of infinite GP series. The value of T(n) will
be less than this sum.
T(n) <= cn(1/(1-1/3))
<= 3cn/2
or we can say
cn <= T(n) <= 3cn/2
Therefore T(n) = (n)
This can also be solved using Master Theorem for solving recurrences. The given expression lies in Case 3 of the theorem.
Quiz of this Question
GATE-CS-2009
GATE-GATE-CS-2009
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 138,
"s": 52,
"text": "The running time of an algorithm is represented by the following recurrence relation:"
},
{
"code": null,
"e": 199,
"s": 138,
"text": " if n <= 3 then T(n) = n\n else T(n) = T(n/3) + cn\n"
},
{
"code": null,
"e": 331,
"s": 199,
"text": "Which one of the following represents the time complexity of the algorithm? <pre>(A) (n)(B) (n log n)(C) (n^2)(D) (n^2log n) </pre>"
},
{
"code": null,
"e": 376,
"s": 331,
"text": " (A) A(B) B(C) C(D) DAnswer: (A)Explanation:"
},
{
"code": null,
"e": 386,
"s": 376,
"text": "Answer(A)"
},
{
"code": null,
"e": 642,
"s": 386,
"text": "T(n) = cn + T(n/3)\n = cn + cn/3 + T(n/9)\n = cn + cn/3 + cn/9 + T(n/27)\nTaking the sum of infinite GP series. The value of T(n) will\nbe less than this sum.\nT(n) <= cn(1/(1-1/3))\n <= 3cn/2\n\nor we can say \ncn <= T(n) <= 3cn/2\nTherefore T(n) = (n)"
},
{
"code": null,
"e": 764,
"s": 642,
"text": "This can also be solved using Master Theorem for solving recurrences. The given expression lies in Case 3 of the theorem."
},
{
"code": null,
"e": 786,
"s": 764,
"text": "Quiz of this Question"
},
{
"code": null,
"e": 799,
"s": 786,
"text": "GATE-CS-2009"
},
{
"code": null,
"e": 817,
"s": 799,
"text": "GATE-GATE-CS-2009"
},
{
"code": null,
"e": 822,
"s": 817,
"text": "GATE"
}
] |
SharePoint - Features & Elements
|
In this chapter, we will take a look at features and elements. Features are in some ways the component model in SharePoint. They allow you to define logical units of functionality.
For example, you might want to have the ability within a site −
To create a list with a specific schema,
To create a list with a specific schema,
Have a page that will show the data from that list, and then
Have a page that will show the data from that list, and then
Have a link or a menu option somewhere within the site to navigate to that page.
Have a link or a menu option somewhere within the site to navigate to that page.
You could create a feature, which defines that logical grouping of functionality. The individual pieces of functionality are defined by elements.
So there would be an element which −
Creates the list and sets the schema.
Creates the list and sets the schema.
Provisions the page into your SharePoint site, and
Provisions the page into your SharePoint site, and
Creates the menu option or the link.
Creates the menu option or the link.
The feature defines the unit and then the elements define the individual pieces of functionality inside of that unit. We discussed about the three kinds of elements −
A list instance to create a list.
A list instance to create a list.
A module to provision a page.
A module to provision a page.
A custom action to create a menu option or a link.
A custom action to create a menu option or a link.
However, there are many other kinds of elements that can be created within SharePoint. Another important concept to understand about features is that of activation and deactivation.
For example, if an end user wants the above-mentioned functionality to be added to his site, he would activate the corresponding feature that would create the list, add the menu option or link, and provision the page into their site. Later he could deactivate the feature to remove the functionality.
It is important to note that on deactivation of a feature, some elements are automatically removed. For example, SharePoint would automatically remove the menu option or link, which is defined by a custom action.
Others are not removed automatically. Therefore, in our case, the list instance and the page would not be removed automatically.
Hence, as a developer, you need to understand what elements get removed automatically and which ones do not. If you want to remove the ones that do not get removed automatically, you can write in code in a feature receiver.
Let us look at the working with features and elements. We will start with the end users view of features.
Step 1 − Open your SharePoint site.
Step 2 − To go to the Site settings, you have two links that enable you to manage features.
The first link Manage Site features is under Site Actions, which enables you to manage site scope features.
The first link Manage Site features is under Site Actions, which enables you to manage site scope features.
The other link Site collection features under Site Collection Administration, which enables you to manage site collection scope features.
The other link Site collection features under Site Collection Administration, which enables you to manage site collection scope features.
Step 3 − If you click on either of these links, you will be taken to a page, which shows the currently active and inactive features. For each of the features, you have an option to activate or deactivate the feature.
Let us look at a simple example by creating a new SharePoint Solutions Empty Project.
Step 1 − Let us call this FeaturesAndElements and click OK.
Step 2 − Specify the site you want to use and select the Deploy as a farm solution option and then click Finish.
The first thing we want to create is the feature. In the Solution Explorer, you can see a Features folder, which is currently empty.
Step 3 − Right-click on the Features folder and choose Add Feature. It creates a Feature named Feature1, and it opens up the Feature designer. The default Title is the title of project, plus the title of the feature.
Step 4 − Rename the feature from Feature1 to Sample.
Title and Description are what the user sees in the page where they activate and deactivate the features.
Set the Title to Sample Feature and the Description to Adds the Contacts list and the page is used to view the list. The other thing we need to set is the Scope of the feature, which is the activation scope.
It can be Farm, a WebApplication, a Site collection or a Site. In this case, we are going to provision a list and a page. Since, both live in a SharePoint site, so we will pick Web here.
Step 5 − Let us start adding features in our elements. The first element will be the list and we will create a contacts list. Right-click on your project and choose Add → New Item...
Step 6 − Select List in the middle pane and enter Contacts in the name field. Click Add.
Step 7 − You will see the List Creation Wizard. Create a list called Contacts based on the Contacts list. Click Finish to create the list or at least create the element, which will eventually create the list.
Given below is the screenshot of the list designer.
Step 8 − This designer is just an XML editor. Open the file Elements.xml under Contacts and add the following data.
<?xml version = "1.0" encoding = "utf-8"?>
<Elements xmlns = "http://schemas.microsoft.com/sharepoint/">
<ListInstance Title = "Contacts" OnQuickLaunch = "TRUE" TemplateType = "105"
FeatureId = "00bfea71-7e6d-4186-9ba8-c047ac750105"
Url = "Lists/Contacts" Description = "">
<Data>
<Rows>
<Row>
<Field Name = "ID">1</Field>
<Field Name = "Last Name">Anders</Field>
<Field Name = "First Name">Maria</Field>
<Field Name = "Company">Alfreds Futerkiste</Field>
<Field Name = "Business Phone">030-0074321</Field>
</Row>
<Row>
<Field Name = "ID">2</Field>
<Field Name = "Last Name">Hardy</Field>
<Field Name = "First Name">Thomas</Field>
<Field Name = "Company">Around the Horn</Field>
<Field Name = "Business Phone">(171) 555-7788</Field>
</Row>
<Row>
<Field Name = "ID">3</Field>
<Field Name = "Last Name">Lebihan</Field>
<Field Name = "First Name">Laurence</Field>
<Field Name = "Company">Bon app'</Field>
<Field Name = "Business Phone">91.24.45.40</Field>
</Row>
<Row>
<Field Name = "ID">4</Field>
<Field Name = "Last Name">Ashworth</Field>
<Field Name = "First Name">Victoria</Field>
<Field Name = "Company">B's Beverages</Field>
<Field Name = "Business Phone">(171) 555-1212</Field>
</Row>
<Row>
<Field Name = "ID">5</Field>
<Field Name = "Last Name">Mendel</Field>
<Field Name = "First Name">Roland</Field>
<Field Name = "Company">Ernst Handel</Field>
<Field Name = "Business Phone">7675-3425</Field>
</Row>
</Rows>
</Data>
</ListInstance>
</Elements>
Note the following −
Inside the ListInstance element, we have an element called Data and it has some rows inside it.
Inside the ListInstance element, we have an element called Data and it has some rows inside it.
ListInstance will have attributes Contacts, whether or not we show in the quick launch.
ListInstance will have attributes Contacts, whether or not we show in the quick launch.
We want a list based on contact template. Here, TemplateType is set to 105. This is not a random number but a number with a meaning.
We want a list based on contact template. Here, TemplateType is set to 105. This is not a random number but a number with a meaning.
Each of the default kinds of list you can have in SharePoint such as an Announcements list, a Task list, a Contacts list and so on, has a number associated with it. Therefore, if you change 105 to 107, you will get a different kind of list.
Each of the default kinds of list you can have in SharePoint such as an Announcements list, a Task list, a Contacts list and so on, has a number associated with it. Therefore, if you change 105 to 107, you will get a different kind of list.
FeatureId is the guide associated with the definition of contacts list.
FeatureId is the guide associated with the definition of contacts list.
Step 9 − Now we want to have a page, which shows data from this list. Right-click on your project and choose Add → New Item... Choose Module in the middle pane, enter SitePage in the name field, and click Add.
You will see a node called SitePage, which has two files, Elements.xml and Sample.txt file. We do not want to provision this sample.txt file, but we want to provision a SitePage.
Step 10 − Rename the text file to Contacts.aspx and replace the following code −
<%@ Assembly Name = "Microsoft.SharePoint, Version = 14.0.0.0, Culture = neutral,
PublicKeyToken = 71e9bce111e9429c" %>
<%@ Page MasterPageFile = "~masterurl/default.master"
meta:progid = "SharePoint.WebPartPage.Document" %>
<%@ Register TagPrefix = "SharePoint"
Namespace = "Microsoft.SharePoint.WebControls"
Assembly = "Microsoft.SharePoint, Version = 14.0.0.0, Culture = neutral,
PublicKeyToken = 71e9bce111e9429c" %>
<asp:Content ID = "Content2" runat = "server" ContentPlaceHolderID = "PlaceHolderMain">
<SharePoint:SPDataSource runat = "server"
ID = "ContactsDataSource" DataSourceMode = "List"
UseInternalName = "false">
<SelectParameters>
<asp:Parameter Name = "ListName" DefaultValue = "Contacts" />
</SelectParameters>
</SharePoint:SPDataSource>
<SharePoint:SPGridView runat = "server"
ID = "ContactsGridView" DataSourceID = "ContactsDataSource"
AutoGenerateColumns = "false" RowStyle-BackColor = "#DDDDDD"
AlternatingRowStyle-BackColor = "#EEEEEE">
<Columns>
<asp:BoundField HeaderText = "Company"
HeaderStyle-HorizontalAlign = "Left" DataField = "Company" />
<asp:BoundField HeaderText = "First Name"
HeaderStyle-HorizontalAlign = "Left" DataField = "First Name" />
<asp:BoundField HeaderText = "Last Name"
HeaderStyle-HorizontalAlign = "Left" DataField = "Last Name" />
<asp:BoundField HeaderText = "Phone"
HeaderStyle-HorizontalAlign = "Left" DataField = "Business Phone" />
</Columns>
</SharePoint:SPGridView>
</asp:Content>
<asp:Content ID = "PageTitle" ContentPlaceHolderID = "PlaceHolderPageTitle"
runat = "server">
Contacts
</asp:Content>
<asp:Content ID = "PageTitleInTitleArea"
ContentPlaceHolderID = "PlaceHolderPageTitleInTitleArea" runat = "server" >
Contacts
</asp:Content>
The SitePage has an SP.DataSource file, which we will use to make the Contacts list data, something we can bind to in our page. The SP.GridView will show the Contacts information.
That is our SitePage and now let us look at the Feature.
Notice, in Items in the Feature, Contacts list instance and Module provision on our SitePage have been added as elements.
Visual Studio understands that elements on their own cannot do anything. Elements need to be a part of a Feature. Hence, when you add an element, you need to add it into the feature.
Step 11 − Go to your project and right-click, and choose Add → New Item...
Here we want to add a CustomAction, so select Empty Element in the middle pane, call this Action and then click Add.
If you come back to your Feature, you can see that the element has now been added to Feature as shown in the screenshot given below.
Step 12 − Come back to Elements.xml under Action and replace the following code −
<?xml version = "1.0" encoding = "utf-8"?>
<Elements xmlns = "http://schemas.microsoft.com/sharepoint/">
<CustomAction
Id = "SiteActionsToolbar"
GroupId = "SiteActions"
Location = "Microsoft.SharePoint.StandardMenu"
Sequence = "100"
Title = "Contacts"
Description = "A page showing some sample data">
<UrlAction Url = "~site/SitePages/Contacts.aspx"/>
</CustomAction>
</Elements>
Now if you want to add a link or a menu option, you need to define where you are going to add it and it is a combination of the Location and GroupId, which define them. This combination of values indicates that the menu option should be added to the SiteActions menu.
There are many other combinations of values, which add the link or the menu in other places within our SharePoint site. This is something you would have to research to find out what is the proper combination of values that you need when you want to add a menu option somewhere within SharePoint.
Step 13 − Double click on the Feature, you will see the Feature designer. Feature designer is a fancy editor of the Feature Manifest, which is an XML document.
Important points −
The feature defines the logical grouping of elements. Here, our Feature is referring to our three Element manifests that we have just created.
The feature defines the logical grouping of elements. Here, our Feature is referring to our three Element manifests that we have just created.
When you activate the Feature, SharePoint will look at the individual Element manifest and add the list, the page, and the link into our SharePoint site.
When you activate the Feature, SharePoint will look at the individual Element manifest and add the list, the page, and the link into our SharePoint site.
When you deploy using Visual Studio, it automatically activates any Features in your project. Since, we want to go through the process of activating the Feature, we are going to tell Visual Studio not to do that.
When you deploy using Visual Studio, it automatically activates any Features in your project. Since, we want to go through the process of activating the Feature, we are going to tell Visual Studio not to do that.
Step 14 − Go to the Project Properties by going to the SharePoint tab. Change the Deployment Configuration to No Activation.
Let us test this.
Step 15 − Right-click on your project in Solution Explorer and choose Deploy. It will package up all the stuff in your project and deploy it out to your SharePoint Development Farm.
Once it is deployed successfully, you will see it in the Output window.
Step 16 − Go to the SharePoint site and Refresh it. Go to the Site Settings → Site Actions.
Step 17 − Select the Manage site features because your Custom Feature was Web scoped and you will see your Sample Feature. You can see that this feature has not been activated, so let us go ahead and activate it.
You will see the Contacts list in the left pane.
Step 18 − Click Contact and the data that we had in the list will be displayed.
Step 19 − Go to Site actions menu. There is an option to navigate to the Contacts page. That is our CustomAction.
Step 20 − If you click Contacts, then you will see your SitePage, showing the data from the Contacts list.
13 Lectures
3 hours
Darwish
124 Lectures
6.5 hours
JM Ekhteyari
44 Lectures
3.5 hours
Simon Sez IT
23 Lectures
1.5 hours
Sonic Performance
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2496,
"s": 2315,
"text": "In this chapter, we will take a look at features and elements. Features are in some ways the component model in SharePoint. They allow you to define logical units of functionality."
},
{
"code": null,
"e": 2560,
"s": 2496,
"text": "For example, you might want to have the ability within a site −"
},
{
"code": null,
"e": 2601,
"s": 2560,
"text": "To create a list with a specific schema,"
},
{
"code": null,
"e": 2642,
"s": 2601,
"text": "To create a list with a specific schema,"
},
{
"code": null,
"e": 2703,
"s": 2642,
"text": "Have a page that will show the data from that list, and then"
},
{
"code": null,
"e": 2764,
"s": 2703,
"text": "Have a page that will show the data from that list, and then"
},
{
"code": null,
"e": 2845,
"s": 2764,
"text": "Have a link or a menu option somewhere within the site to navigate to that page."
},
{
"code": null,
"e": 2926,
"s": 2845,
"text": "Have a link or a menu option somewhere within the site to navigate to that page."
},
{
"code": null,
"e": 3072,
"s": 2926,
"text": "You could create a feature, which defines that logical grouping of functionality. The individual pieces of functionality are defined by elements."
},
{
"code": null,
"e": 3109,
"s": 3072,
"text": "So there would be an element which −"
},
{
"code": null,
"e": 3147,
"s": 3109,
"text": "Creates the list and sets the schema."
},
{
"code": null,
"e": 3185,
"s": 3147,
"text": "Creates the list and sets the schema."
},
{
"code": null,
"e": 3236,
"s": 3185,
"text": "Provisions the page into your SharePoint site, and"
},
{
"code": null,
"e": 3287,
"s": 3236,
"text": "Provisions the page into your SharePoint site, and"
},
{
"code": null,
"e": 3324,
"s": 3287,
"text": "Creates the menu option or the link."
},
{
"code": null,
"e": 3361,
"s": 3324,
"text": "Creates the menu option or the link."
},
{
"code": null,
"e": 3528,
"s": 3361,
"text": "The feature defines the unit and then the elements define the individual pieces of functionality inside of that unit. We discussed about the three kinds of elements −"
},
{
"code": null,
"e": 3562,
"s": 3528,
"text": "A list instance to create a list."
},
{
"code": null,
"e": 3596,
"s": 3562,
"text": "A list instance to create a list."
},
{
"code": null,
"e": 3626,
"s": 3596,
"text": "A module to provision a page."
},
{
"code": null,
"e": 3656,
"s": 3626,
"text": "A module to provision a page."
},
{
"code": null,
"e": 3707,
"s": 3656,
"text": "A custom action to create a menu option or a link."
},
{
"code": null,
"e": 3758,
"s": 3707,
"text": "A custom action to create a menu option or a link."
},
{
"code": null,
"e": 3940,
"s": 3758,
"text": "However, there are many other kinds of elements that can be created within SharePoint. Another important concept to understand about features is that of activation and deactivation."
},
{
"code": null,
"e": 4241,
"s": 3940,
"text": "For example, if an end user wants the above-mentioned functionality to be added to his site, he would activate the corresponding feature that would create the list, add the menu option or link, and provision the page into their site. Later he could deactivate the feature to remove the functionality."
},
{
"code": null,
"e": 4454,
"s": 4241,
"text": "It is important to note that on deactivation of a feature, some elements are automatically removed. For example, SharePoint would automatically remove the menu option or link, which is defined by a custom action."
},
{
"code": null,
"e": 4583,
"s": 4454,
"text": "Others are not removed automatically. Therefore, in our case, the list instance and the page would not be removed automatically."
},
{
"code": null,
"e": 4807,
"s": 4583,
"text": "Hence, as a developer, you need to understand what elements get removed automatically and which ones do not. If you want to remove the ones that do not get removed automatically, you can write in code in a feature receiver."
},
{
"code": null,
"e": 4913,
"s": 4807,
"text": "Let us look at the working with features and elements. We will start with the end users view of features."
},
{
"code": null,
"e": 4949,
"s": 4913,
"text": "Step 1 − Open your SharePoint site."
},
{
"code": null,
"e": 5041,
"s": 4949,
"text": "Step 2 − To go to the Site settings, you have two links that enable you to manage features."
},
{
"code": null,
"e": 5149,
"s": 5041,
"text": "The first link Manage Site features is under Site Actions, which enables you to manage site scope features."
},
{
"code": null,
"e": 5257,
"s": 5149,
"text": "The first link Manage Site features is under Site Actions, which enables you to manage site scope features."
},
{
"code": null,
"e": 5395,
"s": 5257,
"text": "The other link Site collection features under Site Collection Administration, which enables you to manage site collection scope features."
},
{
"code": null,
"e": 5533,
"s": 5395,
"text": "The other link Site collection features under Site Collection Administration, which enables you to manage site collection scope features."
},
{
"code": null,
"e": 5750,
"s": 5533,
"text": "Step 3 − If you click on either of these links, you will be taken to a page, which shows the currently active and inactive features. For each of the features, you have an option to activate or deactivate the feature."
},
{
"code": null,
"e": 5836,
"s": 5750,
"text": "Let us look at a simple example by creating a new SharePoint Solutions Empty Project."
},
{
"code": null,
"e": 5896,
"s": 5836,
"text": "Step 1 − Let us call this FeaturesAndElements and click OK."
},
{
"code": null,
"e": 6009,
"s": 5896,
"text": "Step 2 − Specify the site you want to use and select the Deploy as a farm solution option and then click Finish."
},
{
"code": null,
"e": 6142,
"s": 6009,
"text": "The first thing we want to create is the feature. In the Solution Explorer, you can see a Features folder, which is currently empty."
},
{
"code": null,
"e": 6359,
"s": 6142,
"text": "Step 3 − Right-click on the Features folder and choose Add Feature. It creates a Feature named Feature1, and it opens up the Feature designer. The default Title is the title of project, plus the title of the feature."
},
{
"code": null,
"e": 6412,
"s": 6359,
"text": "Step 4 − Rename the feature from Feature1 to Sample."
},
{
"code": null,
"e": 6518,
"s": 6412,
"text": "Title and Description are what the user sees in the page where they activate and deactivate the features."
},
{
"code": null,
"e": 6726,
"s": 6518,
"text": "Set the Title to Sample Feature and the Description to Adds the Contacts list and the page is used to view the list. The other thing we need to set is the Scope of the feature, which is the activation scope."
},
{
"code": null,
"e": 6913,
"s": 6726,
"text": "It can be Farm, a WebApplication, a Site collection or a Site. In this case, we are going to provision a list and a page. Since, both live in a SharePoint site, so we will pick Web here."
},
{
"code": null,
"e": 7096,
"s": 6913,
"text": "Step 5 − Let us start adding features in our elements. The first element will be the list and we will create a contacts list. Right-click on your project and choose Add → New Item..."
},
{
"code": null,
"e": 7185,
"s": 7096,
"text": "Step 6 − Select List in the middle pane and enter Contacts in the name field. Click Add."
},
{
"code": null,
"e": 7394,
"s": 7185,
"text": "Step 7 − You will see the List Creation Wizard. Create a list called Contacts based on the Contacts list. Click Finish to create the list or at least create the element, which will eventually create the list."
},
{
"code": null,
"e": 7446,
"s": 7394,
"text": "Given below is the screenshot of the list designer."
},
{
"code": null,
"e": 7562,
"s": 7446,
"text": "Step 8 − This designer is just an XML editor. Open the file Elements.xml under Contacts and add the following data."
},
{
"code": null,
"e": 9565,
"s": 7562,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n\n<Elements xmlns = \"http://schemas.microsoft.com/sharepoint/\">\n <ListInstance Title = \"Contacts\" OnQuickLaunch = \"TRUE\" TemplateType = \"105\" \n FeatureId = \"00bfea71-7e6d-4186-9ba8-c047ac750105\"\n Url = \"Lists/Contacts\" Description = \"\">\n <Data>\n <Rows>\n\n <Row>\n <Field Name = \"ID\">1</Field>\n <Field Name = \"Last Name\">Anders</Field>\n <Field Name = \"First Name\">Maria</Field>\n <Field Name = \"Company\">Alfreds Futerkiste</Field>\n <Field Name = \"Business Phone\">030-0074321</Field>\n </Row>\n\n <Row>\n <Field Name = \"ID\">2</Field>\n <Field Name = \"Last Name\">Hardy</Field>\n <Field Name = \"First Name\">Thomas</Field>\n <Field Name = \"Company\">Around the Horn</Field>\n <Field Name = \"Business Phone\">(171) 555-7788</Field>\n </Row>\n\n <Row>\n <Field Name = \"ID\">3</Field>\n <Field Name = \"Last Name\">Lebihan</Field>\n <Field Name = \"First Name\">Laurence</Field>\n <Field Name = \"Company\">Bon app'</Field>\n <Field Name = \"Business Phone\">91.24.45.40</Field>\n </Row>\n\n <Row>\n <Field Name = \"ID\">4</Field>\n <Field Name = \"Last Name\">Ashworth</Field>\n <Field Name = \"First Name\">Victoria</Field>\n <Field Name = \"Company\">B's Beverages</Field>\n <Field Name = \"Business Phone\">(171) 555-1212</Field>\n </Row>\n\n <Row>\n <Field Name = \"ID\">5</Field>\n <Field Name = \"Last Name\">Mendel</Field>\n <Field Name = \"First Name\">Roland</Field>\n <Field Name = \"Company\">Ernst Handel</Field>\n <Field Name = \"Business Phone\">7675-3425</Field>\n </Row>\n\n </Rows>\n </Data>\n </ListInstance>\n</Elements>"
},
{
"code": null,
"e": 9586,
"s": 9565,
"text": "Note the following −"
},
{
"code": null,
"e": 9682,
"s": 9586,
"text": "Inside the ListInstance element, we have an element called Data and it has some rows inside it."
},
{
"code": null,
"e": 9778,
"s": 9682,
"text": "Inside the ListInstance element, we have an element called Data and it has some rows inside it."
},
{
"code": null,
"e": 9866,
"s": 9778,
"text": "ListInstance will have attributes Contacts, whether or not we show in the quick launch."
},
{
"code": null,
"e": 9954,
"s": 9866,
"text": "ListInstance will have attributes Contacts, whether or not we show in the quick launch."
},
{
"code": null,
"e": 10087,
"s": 9954,
"text": "We want a list based on contact template. Here, TemplateType is set to 105. This is not a random number but a number with a meaning."
},
{
"code": null,
"e": 10220,
"s": 10087,
"text": "We want a list based on contact template. Here, TemplateType is set to 105. This is not a random number but a number with a meaning."
},
{
"code": null,
"e": 10461,
"s": 10220,
"text": "Each of the default kinds of list you can have in SharePoint such as an Announcements list, a Task list, a Contacts list and so on, has a number associated with it. Therefore, if you change 105 to 107, you will get a different kind of list."
},
{
"code": null,
"e": 10702,
"s": 10461,
"text": "Each of the default kinds of list you can have in SharePoint such as an Announcements list, a Task list, a Contacts list and so on, has a number associated with it. Therefore, if you change 105 to 107, you will get a different kind of list."
},
{
"code": null,
"e": 10774,
"s": 10702,
"text": "FeatureId is the guide associated with the definition of contacts list."
},
{
"code": null,
"e": 10846,
"s": 10774,
"text": "FeatureId is the guide associated with the definition of contacts list."
},
{
"code": null,
"e": 11056,
"s": 10846,
"text": "Step 9 − Now we want to have a page, which shows data from this list. Right-click on your project and choose Add → New Item... Choose Module in the middle pane, enter SitePage in the name field, and click Add."
},
{
"code": null,
"e": 11235,
"s": 11056,
"text": "You will see a node called SitePage, which has two files, Elements.xml and Sample.txt file. We do not want to provision this sample.txt file, but we want to provision a SitePage."
},
{
"code": null,
"e": 11316,
"s": 11235,
"text": "Step 10 − Rename the text file to Contacts.aspx and replace the following code −"
},
{
"code": null,
"e": 13210,
"s": 11316,
"text": "<%@ Assembly Name = \"Microsoft.SharePoint, Version = 14.0.0.0, Culture = neutral,\n PublicKeyToken = 71e9bce111e9429c\" %>\n\n<%@ Page MasterPageFile = \"~masterurl/default.master\"\n meta:progid = \"SharePoint.WebPartPage.Document\" %>\n\n<%@ Register TagPrefix = \"SharePoint\"\n Namespace = \"Microsoft.SharePoint.WebControls\"\n Assembly = \"Microsoft.SharePoint, Version = 14.0.0.0, Culture = neutral,\n PublicKeyToken = 71e9bce111e9429c\" %>\n\n<asp:Content ID = \"Content2\" runat = \"server\" ContentPlaceHolderID = \"PlaceHolderMain\">\n <SharePoint:SPDataSource runat = \"server\"\n ID = \"ContactsDataSource\" DataSourceMode = \"List\"\n UseInternalName = \"false\">\n <SelectParameters>\n <asp:Parameter Name = \"ListName\" DefaultValue = \"Contacts\" />\n </SelectParameters>\n </SharePoint:SPDataSource>\n \n <SharePoint:SPGridView runat = \"server\"\n ID = \"ContactsGridView\" DataSourceID = \"ContactsDataSource\"\n AutoGenerateColumns = \"false\" RowStyle-BackColor = \"#DDDDDD\"\n AlternatingRowStyle-BackColor = \"#EEEEEE\">\n <Columns>\n <asp:BoundField HeaderText = \"Company\"\n HeaderStyle-HorizontalAlign = \"Left\" DataField = \"Company\" />\n <asp:BoundField HeaderText = \"First Name\"\n HeaderStyle-HorizontalAlign = \"Left\" DataField = \"First Name\" />\n <asp:BoundField HeaderText = \"Last Name\"\n HeaderStyle-HorizontalAlign = \"Left\" DataField = \"Last Name\" />\n <asp:BoundField HeaderText = \"Phone\"\n HeaderStyle-HorizontalAlign = \"Left\" DataField = \"Business Phone\" />\n </Columns>\n </SharePoint:SPGridView>\n</asp:Content>\n\n<asp:Content ID = \"PageTitle\" ContentPlaceHolderID = \"PlaceHolderPageTitle\"\n runat = \"server\">\n Contacts\n</asp:Content>\n\n<asp:Content ID = \"PageTitleInTitleArea\"\n ContentPlaceHolderID = \"PlaceHolderPageTitleInTitleArea\" runat = \"server\" >\n Contacts\n</asp:Content>"
},
{
"code": null,
"e": 13390,
"s": 13210,
"text": "The SitePage has an SP.DataSource file, which we will use to make the Contacts list data, something we can bind to in our page. The SP.GridView will show the Contacts information."
},
{
"code": null,
"e": 13447,
"s": 13390,
"text": "That is our SitePage and now let us look at the Feature."
},
{
"code": null,
"e": 13569,
"s": 13447,
"text": "Notice, in Items in the Feature, Contacts list instance and Module provision on our SitePage have been added as elements."
},
{
"code": null,
"e": 13752,
"s": 13569,
"text": "Visual Studio understands that elements on their own cannot do anything. Elements need to be a part of a Feature. Hence, when you add an element, you need to add it into the feature."
},
{
"code": null,
"e": 13827,
"s": 13752,
"text": "Step 11 − Go to your project and right-click, and choose Add → New Item..."
},
{
"code": null,
"e": 13944,
"s": 13827,
"text": "Here we want to add a CustomAction, so select Empty Element in the middle pane, call this Action and then click Add."
},
{
"code": null,
"e": 14077,
"s": 13944,
"text": "If you come back to your Feature, you can see that the element has now been added to Feature as shown in the screenshot given below."
},
{
"code": null,
"e": 14159,
"s": 14077,
"text": "Step 12 − Come back to Elements.xml under Action and replace the following code −"
},
{
"code": null,
"e": 14588,
"s": 14159,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n\n<Elements xmlns = \"http://schemas.microsoft.com/sharepoint/\">\n <CustomAction\n Id = \"SiteActionsToolbar\"\n GroupId = \"SiteActions\"\n Location = \"Microsoft.SharePoint.StandardMenu\"\n Sequence = \"100\"\n Title = \"Contacts\"\n Description = \"A page showing some sample data\">\n <UrlAction Url = \"~site/SitePages/Contacts.aspx\"/>\n </CustomAction>\n</Elements>"
},
{
"code": null,
"e": 14856,
"s": 14588,
"text": "Now if you want to add a link or a menu option, you need to define where you are going to add it and it is a combination of the Location and GroupId, which define them. This combination of values indicates that the menu option should be added to the SiteActions menu."
},
{
"code": null,
"e": 15152,
"s": 14856,
"text": "There are many other combinations of values, which add the link or the menu in other places within our SharePoint site. This is something you would have to research to find out what is the proper combination of values that you need when you want to add a menu option somewhere within SharePoint."
},
{
"code": null,
"e": 15312,
"s": 15152,
"text": "Step 13 − Double click on the Feature, you will see the Feature designer. Feature designer is a fancy editor of the Feature Manifest, which is an XML document."
},
{
"code": null,
"e": 15331,
"s": 15312,
"text": "Important points −"
},
{
"code": null,
"e": 15474,
"s": 15331,
"text": "The feature defines the logical grouping of elements. Here, our Feature is referring to our three Element manifests that we have just created."
},
{
"code": null,
"e": 15617,
"s": 15474,
"text": "The feature defines the logical grouping of elements. Here, our Feature is referring to our three Element manifests that we have just created."
},
{
"code": null,
"e": 15771,
"s": 15617,
"text": "When you activate the Feature, SharePoint will look at the individual Element manifest and add the list, the page, and the link into our SharePoint site."
},
{
"code": null,
"e": 15925,
"s": 15771,
"text": "When you activate the Feature, SharePoint will look at the individual Element manifest and add the list, the page, and the link into our SharePoint site."
},
{
"code": null,
"e": 16138,
"s": 15925,
"text": "When you deploy using Visual Studio, it automatically activates any Features in your project. Since, we want to go through the process of activating the Feature, we are going to tell Visual Studio not to do that."
},
{
"code": null,
"e": 16351,
"s": 16138,
"text": "When you deploy using Visual Studio, it automatically activates any Features in your project. Since, we want to go through the process of activating the Feature, we are going to tell Visual Studio not to do that."
},
{
"code": null,
"e": 16476,
"s": 16351,
"text": "Step 14 − Go to the Project Properties by going to the SharePoint tab. Change the Deployment Configuration to No Activation."
},
{
"code": null,
"e": 16494,
"s": 16476,
"text": "Let us test this."
},
{
"code": null,
"e": 16676,
"s": 16494,
"text": "Step 15 − Right-click on your project in Solution Explorer and choose Deploy. It will package up all the stuff in your project and deploy it out to your SharePoint Development Farm."
},
{
"code": null,
"e": 16748,
"s": 16676,
"text": "Once it is deployed successfully, you will see it in the Output window."
},
{
"code": null,
"e": 16840,
"s": 16748,
"text": "Step 16 − Go to the SharePoint site and Refresh it. Go to the Site Settings → Site Actions."
},
{
"code": null,
"e": 17053,
"s": 16840,
"text": "Step 17 − Select the Manage site features because your Custom Feature was Web scoped and you will see your Sample Feature. You can see that this feature has not been activated, so let us go ahead and activate it."
},
{
"code": null,
"e": 17102,
"s": 17053,
"text": "You will see the Contacts list in the left pane."
},
{
"code": null,
"e": 17182,
"s": 17102,
"text": "Step 18 − Click Contact and the data that we had in the list will be displayed."
},
{
"code": null,
"e": 17296,
"s": 17182,
"text": "Step 19 − Go to Site actions menu. There is an option to navigate to the Contacts page. That is our CustomAction."
},
{
"code": null,
"e": 17403,
"s": 17296,
"text": "Step 20 − If you click Contacts, then you will see your SitePage, showing the data from the Contacts list."
},
{
"code": null,
"e": 17436,
"s": 17403,
"text": "\n 13 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 17445,
"s": 17436,
"text": " Darwish"
},
{
"code": null,
"e": 17481,
"s": 17445,
"text": "\n 124 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 17495,
"s": 17481,
"text": " JM Ekhteyari"
},
{
"code": null,
"e": 17530,
"s": 17495,
"text": "\n 44 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 17544,
"s": 17530,
"text": " Simon Sez IT"
},
{
"code": null,
"e": 17579,
"s": 17544,
"text": "\n 23 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 17598,
"s": 17579,
"text": " Sonic Performance"
},
{
"code": null,
"e": 17605,
"s": 17598,
"text": " Print"
},
{
"code": null,
"e": 17616,
"s": 17605,
"text": " Add Notes"
}
] |
Square matrix rotation in JavaScript
|
We are required to write a JavaScript function that takes in an array of arrays of n * n order (square matrix). The function should rotate the array by 90 degrees (clockwise). The condition is that we have to do this in place (without allocating any extra array).
For example −
If the input array is −
const arr = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
Then the rotated array should look like −
const output = [
[7, 4, 1],
[8, 5, 2],
[9, 6, 3],
];
Following is the code −
const arr = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
const rotateArray = (arr = []) => {
for (let rowIndex = 0; rowIndex < arr.length; rowIndex += 1) {
for (let columnIndex = rowIndex + 1; columnIndex < arr.length;
columnIndex += 1) {
[
arr[columnIndex][rowIndex],
arr[rowIndex][columnIndex],
] = [
arr[rowIndex][columnIndex],
arr[columnIndex][rowIndex],
];
}
}
for (let rowIndex = 0; rowIndex < arr.length; rowIndex += 1) {
for (let columnIndex = 0; columnIndex < arr.length / 2;
columnIndex += 1) {
[
arr[rowIndex][arr.length - columnIndex - 1],
arr[rowIndex][columnIndex],
] = [
arr[rowIndex][columnIndex],
arr[rowIndex][arr.length - columnIndex - 1],
];
}
}
};
rotateArray(arr);
console.log(arr);
Following is the output on console −
[ [ 7, 4, 1 ], [ 8, 5, 2 ], [ 9, 6, 3 ] ]
|
[
{
"code": null,
"e": 1326,
"s": 1062,
"text": "We are required to write a JavaScript function that takes in an array of arrays of n * n order (square matrix). The function should rotate the array by 90 degrees (clockwise). The condition is that we have to do this in place (without allocating any extra array)."
},
{
"code": null,
"e": 1340,
"s": 1326,
"text": "For example −"
},
{
"code": null,
"e": 1364,
"s": 1340,
"text": "If the input array is −"
},
{
"code": null,
"e": 1422,
"s": 1364,
"text": "const arr = [\n [1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]\n];"
},
{
"code": null,
"e": 1464,
"s": 1422,
"text": "Then the rotated array should look like −"
},
{
"code": null,
"e": 1526,
"s": 1464,
"text": "const output = [\n [7, 4, 1],\n [8, 5, 2],\n [9, 6, 3],\n];"
},
{
"code": null,
"e": 1550,
"s": 1526,
"text": "Following is the code −"
},
{
"code": null,
"e": 2454,
"s": 1550,
"text": "const arr = [\n [1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]\n];\nconst rotateArray = (arr = []) => {\n for (let rowIndex = 0; rowIndex < arr.length; rowIndex += 1) {\n for (let columnIndex = rowIndex + 1; columnIndex < arr.length;\n columnIndex += 1) {\n [\n arr[columnIndex][rowIndex],\n arr[rowIndex][columnIndex],\n ] = [\n arr[rowIndex][columnIndex],\n arr[columnIndex][rowIndex],\n ];\n }\n }\n for (let rowIndex = 0; rowIndex < arr.length; rowIndex += 1) {\n for (let columnIndex = 0; columnIndex < arr.length / 2;\n columnIndex += 1) {\n [\n arr[rowIndex][arr.length - columnIndex - 1],\n arr[rowIndex][columnIndex],\n ] = [\n arr[rowIndex][columnIndex],\n arr[rowIndex][arr.length - columnIndex - 1],\n ];\n }\n }\n};\nrotateArray(arr);\nconsole.log(arr);"
},
{
"code": null,
"e": 2491,
"s": 2454,
"text": "Following is the output on console −"
},
{
"code": null,
"e": 2533,
"s": 2491,
"text": "[ [ 7, 4, 1 ], [ 8, 5, 2 ], [ 9, 6, 3 ] ]"
}
] |
How to add a button dynamically in android?
|
This example demonstrates how do I add a button dynamically in android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/relativeLayout"
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
RelativeLayout relativeLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
relativeLayout = findViewById(R.id.relativeLayout);
Button button = new Button(this);
button.setText("Dynamically created Button");
button.setLayoutParams(new
RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "This button is created dynamically",
Toast.LENGTH_SHORT).show();
}
});
if (relativeLayout != null){
relativeLayout.addView(button);
}
}
}
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": 1134,
"s": 1062,
"text": "This example demonstrates how do I add a button dynamically in android."
},
{
"code": null,
"e": 1263,
"s": 1134,
"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": 1328,
"s": 1263,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 1690,
"s": 1328,
"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:id=\"@+id/relativeLayout\"\n android:gravity=\"center\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n</RelativeLayout>"
},
{
"code": null,
"e": 1747,
"s": 1690,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 2884,
"s": 1747,
"text": "import android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.Button;\nimport android.widget.RelativeLayout;\nimport android.widget.Toast;\npublic class MainActivity extends AppCompatActivity {\n RelativeLayout relativeLayout;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n relativeLayout = findViewById(R.id.relativeLayout);\n Button button = new Button(this);\n button.setText(\"Dynamically created Button\");\n button.setLayoutParams(new\n RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,\n ViewGroup.LayoutParams.WRAP_CONTENT));\n button.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n Toast.makeText(MainActivity.this, \"This button is created dynamically\",\n Toast.LENGTH_SHORT).show();\n }\n });\n if (relativeLayout != null){\n relativeLayout.addView(button);\n }\n }\n}"
},
{
"code": null,
"e": 2939,
"s": 2884,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 3645,
"s": 2939,
"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 <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": 3992,
"s": 3645,
"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 −"
}
] |
Excel Tutorial
|
Excel is the world's most used spreadsheet program
Excel is a powerful tool to use for mathematical functions
Start learning Excel now »
Learn Excel
We use practical examples to give the user a better understanding of the concepts.
Example values can be copied from the tutorial and into your spreadsheet, making it easy for you to tag along
step-by-step:
We have created active learning activities, so you can test and build your knowledge. Making the learning experience more fun and engaging.
Solve Case »
Excel is the world's most used spreadsheet program.
Example use areas:
Data analytics
Project management
Finance and accounting
Data analytics
Project management
Finance and accounting
Complete the Excel formula:
1+1
Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
|
[
{
"code": null,
"e": 51,
"s": 0,
"text": "Excel is the world's most used spreadsheet program"
},
{
"code": null,
"e": 110,
"s": 51,
"text": "Excel is a powerful tool to use for mathematical functions"
},
{
"code": null,
"e": 137,
"s": 110,
"text": "Start learning Excel now »"
},
{
"code": null,
"e": 149,
"s": 137,
"text": "Learn Excel"
},
{
"code": null,
"e": 232,
"s": 149,
"text": "We use practical examples to give the user a better understanding of the concepts."
},
{
"code": null,
"e": 357,
"s": 232,
"text": "Example values can be copied from the tutorial and into your spreadsheet, making it easy for you to tag along \nstep-by-step:"
},
{
"code": null,
"e": 497,
"s": 357,
"text": "We have created active learning activities, so you can test and build your knowledge. Making the learning experience more fun and engaging."
},
{
"code": null,
"e": 510,
"s": 497,
"text": "Solve Case »"
},
{
"code": null,
"e": 562,
"s": 510,
"text": "Excel is the world's most used spreadsheet program."
},
{
"code": null,
"e": 581,
"s": 562,
"text": "Example use areas:"
},
{
"code": null,
"e": 640,
"s": 581,
"text": "\nData analytics\nProject management\nFinance and accounting\n"
},
{
"code": null,
"e": 655,
"s": 640,
"text": "Data analytics"
},
{
"code": null,
"e": 674,
"s": 655,
"text": "Project management"
},
{
"code": null,
"e": 697,
"s": 674,
"text": "Finance and accounting"
},
{
"code": null,
"e": 725,
"s": 697,
"text": "Complete the Excel formula:"
},
{
"code": null,
"e": 730,
"s": 725,
"text": "1+1\n"
},
{
"code": null,
"e": 749,
"s": 730,
"text": "Start the Exercise"
},
{
"code": null,
"e": 782,
"s": 749,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 824,
"s": 782,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 931,
"s": 824,
"text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:"
},
{
"code": null,
"e": 950,
"s": 931,
"text": "help@w3schools.com"
}
] |
How to insert an image in to Oracle database using Java program?
|
To hold an image in Oracle database generally blob type is used. Therefore, make sure that you have a table created with a blob datatype as:
Name Null? Type
----------------------------------------- -------- ----------------------------
NAME VARCHAR2(255)
IMAGE BLOB
To insert an image in to Oracle database, follow the steps given below:
You can connect to a database using the getConnection() method of the DriverManager class
Connect to the Oracle database by passing the Oracle URL which is jdbc:oracle:thin:@localhost:1521/xe (for express edition), username and password as parameters to the getConnection() method.
String oracleUrl = "jdbc:oracle:thin:@localhost:1521/xe";
Connection con = DriverManager.getConnection(oracleUrl, "user_name", "password");
Create a PreparedStatement object using the prepareStatement() method of the Connection interface. To this method pass the insert query (with place holders) as a parameter.
PreparedStatement pstmt = con.prepareStatement("INSERT INTO MyTable VALUES(?, ?)");
Set the values to the place holders using the setter methods of the PreparedStatement interface. Chose the methods according to the datatype of the column. For Example if the column is of VARCHAR type use setString() method and if it is of INT type you can use setInt() method.
And if it is of Blob type you can set value to it using the setBinaryStream() or setBlob() methods. To these methods pass an integer variable representing the parameter index and an object of InputStream class as parameters.
pstmt.setString(1, "sample image");
//Inserting Blob type
InputStream in = new FileInputStream("E:\\images\\cat.jpg");
pstmt.setBlob(2, in);
Execute the above created PreparedStatement object using the execute() method of the PreparedStatement interface.
import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class InsertImageToOracleDB {
public static void main(String args[]) throws Exception{
//Registering the Driver
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver ());
//Getting the connection
String oracleUrl = "jdbc:oracle:thin:@localhost:1521/xe";
Connection con = DriverManager.getConnection(oracleUrl, "system", "password");
System.out.println("Connected to Oracle database.....");
PreparedStatement pstmt = con.prepareStatement("INSERT INTO MyTable VALUES(?,?)");
pstmt.setString(1, "sample image");
//Inserting Blob type
InputStream in = new FileInputStream("E:\\images\\cat.jpg");
pstmt.setBlob(2, in);
//Executing the statement
pstmt.execute();
System.out.println("Record inserted");
}
}
Connected to Oracle database.....
Record inserted.....
|
[
{
"code": null,
"e": 1203,
"s": 1062,
"text": "To hold an image in Oracle database generally blob type is used. Therefore, make sure that you have a table created with a blob datatype as:"
},
{
"code": null,
"e": 1329,
"s": 1203,
"text": "Name Null? Type\n----------------------------------------- -------- ----------------------------\nNAME VARCHAR2(255)\nIMAGE BLOB"
},
{
"code": null,
"e": 1401,
"s": 1329,
"text": "To insert an image in to Oracle database, follow the steps given below:"
},
{
"code": null,
"e": 1491,
"s": 1401,
"text": "You can connect to a database using the getConnection() method of the DriverManager class"
},
{
"code": null,
"e": 1683,
"s": 1491,
"text": "Connect to the Oracle database by passing the Oracle URL which is jdbc:oracle:thin:@localhost:1521/xe (for express edition), username and password as parameters to the getConnection() method."
},
{
"code": null,
"e": 1823,
"s": 1683,
"text": "String oracleUrl = \"jdbc:oracle:thin:@localhost:1521/xe\";\nConnection con = DriverManager.getConnection(oracleUrl, \"user_name\", \"password\");"
},
{
"code": null,
"e": 1996,
"s": 1823,
"text": "Create a PreparedStatement object using the prepareStatement() method of the Connection interface. To this method pass the insert query (with place holders) as a parameter."
},
{
"code": null,
"e": 2080,
"s": 1996,
"text": "PreparedStatement pstmt = con.prepareStatement(\"INSERT INTO MyTable VALUES(?, ?)\");"
},
{
"code": null,
"e": 2358,
"s": 2080,
"text": "Set the values to the place holders using the setter methods of the PreparedStatement interface. Chose the methods according to the datatype of the column. For Example if the column is of VARCHAR type use setString() method and if it is of INT type you can use setInt() method."
},
{
"code": null,
"e": 2583,
"s": 2358,
"text": "And if it is of Blob type you can set value to it using the setBinaryStream() or setBlob() methods. To these methods pass an integer variable representing the parameter index and an object of InputStream class as parameters."
},
{
"code": null,
"e": 2724,
"s": 2583,
"text": "pstmt.setString(1, \"sample image\");\n//Inserting Blob type\nInputStream in = new FileInputStream(\"E:\\\\images\\\\cat.jpg\");\npstmt.setBlob(2, in);"
},
{
"code": null,
"e": 2838,
"s": 2724,
"text": "Execute the above created PreparedStatement object using the execute() method of the PreparedStatement interface."
},
{
"code": null,
"e": 3800,
"s": 2838,
"text": "import java.io.FileInputStream;\nimport java.io.InputStream;\nimport java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.PreparedStatement;\npublic class InsertImageToOracleDB {\n public static void main(String args[]) throws Exception{\n //Registering the Driver\n DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver ());\n //Getting the connection\n String oracleUrl = \"jdbc:oracle:thin:@localhost:1521/xe\";\n Connection con = DriverManager.getConnection(oracleUrl, \"system\", \"password\");\n System.out.println(\"Connected to Oracle database.....\");\n PreparedStatement pstmt = con.prepareStatement(\"INSERT INTO MyTable VALUES(?,?)\");\n pstmt.setString(1, \"sample image\");\n //Inserting Blob type\n InputStream in = new FileInputStream(\"E:\\\\images\\\\cat.jpg\");\n pstmt.setBlob(2, in);\n //Executing the statement\n pstmt.execute();\n System.out.println(\"Record inserted\");\n }\n}"
},
{
"code": null,
"e": 3855,
"s": 3800,
"text": "Connected to Oracle database.....\nRecord inserted....."
}
] |
Continuous Numeric Data. Strategies for working with continuous... | by Dipanjan (DJ) Sarkar | Towards Data Science
|
“Money makes the world go round” is something which you cannot ignore whether to choose to agree or disagree with it. A more apt saying in today’s digital revolutionary age would be “Data makes the world go round”. Indeed data has become a first class asset for businesses, corporations and organizations irrespective of their size and scale. Any intelligent system regardless of their complexity needs to be powered by data. At the heart of any intelligent system, we have one or more algorithms based on machine learning, deep learning or statistical methods which consume this data to gather knowledge and provide intelligent insights over a period of time. Algorithms are pretty naive by themselves and cannot work out of the box on raw data. Hence the need for engineering meaningful features from raw data is of utmost importance which can be understood and consumed by these algorithms.
Any intelligent system basically consists of an end-to-end pipeline starting from ingesting raw data, leveraging data processing techniques to wrangle, process and engineer meaningful features and attributes from this data. Then we usually leverage techniques like statistical models or machine learning models to model on these features and then deploy this model if necessary for future usage based on the problem to be solved at hand. A typical standard machine learning pipeline based on the CRISP-DM industry standard process model is depicted below.
Ingesting raw data and building models on top of this data directly would be foolhardy since we wouldn’t get desired results or performance and also algorithms are not intelligent enough to automatically extract meaningful features from raw data (there are automated feature extraction techniques which are enabled nowadays with deep learning methodologies to some extent, but more on that later!).
Our main area of focus falls under the data preparation aspect as pointed out in the figure above, where we deal with various methodologies to extract meaningful attributes or features from the raw data after it has gone through necessary wrangling and pre-processing.
Feature engineering is an essential part of building any intelligent system. Even though you have a lot of newer methodologies coming in like deep learning and meta-heuristics which aid in automated machine learning, each problem is domain specific and better features (suited to the problem) is often the deciding factor of the performance of your system. Feature Engineering is an art as well as a science and this is the reason Data Scientists often spend 70% of their time in the data preparation phase before modeling. Let’s look at a few quotes relevant to feature engineering from several renowned people in the world of Data Science.
“Coming up with features is difficult, time-consuming, requires expert knowledge. ‘Applied machine learning’ is basically feature engineering.”
— Prof. Andrew Ng.
This basically reinforces what we mentioned earlier about data scientists spending close to 80% of their time in engineering features which is a difficult and time-consuming process, requiring both domain knowledge and mathematical computations.
“Feature engineering is the process of transforming raw data into features that better represent the underlying problem to the predictive models, resulting in improved model accuracy on unseen data.”
— Dr. Jason Brownlee
This gives us an idea about feature engineering being the process of transforming data into features to act as inputs for machine learning models such that good quality features help in improving the overall model performance. Features are also very much dependent on the underlying problem. Thus, even though the machine learning task might be same in different scenarios, like classification of emails into spam and non-spam or classifying handwritten digits, the features extracted in each scenario will be very different from the other.
Prof. Pedro Domingos from the University of Washington, in his paper titled, “A Few Useful Things to Know about Machine Learning” tells us the following.
“At the end of the day, some machine learning projects succeed and some fail. What makes the difference? Easily the most important factor is the features used.”
— Prof. Pedro Domingos
The final quote which should motivate you about feature engineering is from renowned Kaggler, Xavier Conort. Most of you already know that tough real-world machine learning problems are often posted on Kaggle regularly which is usually open to everyone.
“The algorithms we used are very standard for Kagglers. ...We spent most of our efforts in feature engineering. ... We were also very careful to discard features likely to expose us to the risk of over-fitting our model.”
— Xavier Conort
A feature is typically a specific representation on top of raw data, which is an individual, measurable attribute, typically depicted by a column in a dataset. Considering a generic two-dimensional dataset, each observation is depicted by a row and each feature by a column, which will have a specific value for an observation.
Thus like in the example in the figure above, each row typically indicates a feature vector and the entire set of features across all the observations forms a two-dimensional feature matrix also known as a feature-set. This is akin to data frames or spreadsheets representing two-dimensional data. Typically machine learning algorithms work with these numeric matrices or tensors and hence most feature engineering techniques deal with converting raw data into some numeric representations which can be easily understood by these algorithms.
Features can be of two major types based on the dataset. Inherent raw features are obtained directly from the dataset with no extra data manipulation or engineering. Derived features are usually obtained from feature engineering, where we extract features from existing data attributes. A simple example would be creating a new feature “Age” from an employee dataset containing “Birthdate” by just subtracting their birth date from the current date.
There are diverse types and formats of data including structured and unstructured data. In this article, we will discuss various feature engineering strategies for dealing with structured continuous numeric data. All these examples are a part of one of my recent books ‘Practical Machine Learning with Python’ and you can access relevant datasets and code used in this article on GitHub. A big shout out also goes to Gabriel Moreira who helped me by providing some excellent pointers on feature engineering techniques.
Numeric data typically represents data in the form of scalar values depicting observations, recordings or measurements. Here, by numeric data, we mean continuous data and not discrete data which is typically represented as categorical data. Numeric data can also be represented as a vector of values where each value or entity in the vector can represent a specific feature. Integers and floats are the most common and widely used numeric data types for continuous numeric data. Even though numeric data can be directly fed into machine learning models, you would still need to engineer features which are relevant to the scenario, problem and domain before building a model. Hence the need for feature engineering still remains. Let’s leverage python and look at some strategies for feature engineering on numeric data. We load up the following necessary dependencies first (typically in a Jupyter notebook).
import pandas as pdimport matplotlib.pyplot as pltimport numpy as npimport scipy.stats as spstats%matplotlib inline
Like we mentioned earlier, raw numeric data can often be fed directly to machine learning models based on the context and data format. Raw measures are typically indicated using numeric variables directly as features without any form of transformation or engineering. Typically these features can indicate values or counts. Let’s load up one of our datasets, the Pokémon dataset also available on Kaggle.
poke_df = pd.read_csv('datasets/Pokemon.csv', encoding='utf-8') poke_df.head()
Pokémon is a huge media franchise surrounding fictional characters called Pokémon which stands for pocket monsters. In short, you can think of them as fictional animals with superpowers! This dataset consists of these characters with various statistics for each character.
If you closely observe the data frame snapshot in the above figure, you can see that several attributes represent numeric raw values which can be used directly. The following snippet depicts some of these features with more emphasis.
poke_df[['HP', 'Attack', 'Defense']].head()
Thus, you can directly use these attributes as features which are depicted in the above data frame. These include each Pokémon’s HP (Hit Points), Attack and Defense stats. In fact, we can also compute some basic statistical measures on these fields.
poke_df[['HP', 'Attack', 'Defense']].describe()
With this you can get a good idea about statistical measures in these features like count, average, standard deviation and quartiles.
Another form of raw measures include features which represent frequencies, counts or occurrences of specific attributes. Let’s look at a sample of data from the millionsong dataset which depicts counts or frequencies of songs which have been heard by various users.
popsong_df = pd.read_csv('datasets/song_views.csv', encoding='utf-8')popsong_df.head(10)
It is quite evident from the above snapshot that the listen_count field can be used directly as a frequency\count based numeric feature.
Often raw frequencies or counts may not be relevant for building a model based on the problem which is being solved. For instance if I’m building a recommendation system for song recommendations, I would just want to know if a person is interested or has listened to a particular song. This doesn’t require the number of times a song has been listened to since I am more concerned about the various songs he\she has listened to. In this case, a binary feature is preferred as opposed to a count based feature. We can binarize our listen_count field as follows.
watched = np.array(popsong_df['listen_count']) watched[watched >= 1] = 1popsong_df['watched'] = watched
You can also use scikit-learn's Binarizer class here from its preprocessing module to perform the same task instead of numpy arrays.
from sklearn.preprocessing import Binarizerbn = Binarizer(threshold=0.9)pd_watched = bn.transform([popsong_df['listen_count']])[0]popsong_df['pd_watched'] = pd_watchedpopsong_df.head(11)
You can clearly see from the above snapshot that both the methods have produced the same result. Thus we get a binarized feature indicating if the song was listened to or not by each user which can be then further used in a relevant model.
Often when dealing with continuous numeric attributes like proportions or percentages, we may not need the raw values having a high amount of precision. Hence it often makes sense to round off these high precision percentages into numeric integers. These integers can then be directly used as raw values or even as categorical (discrete-class based) features. Let’s try applying this concept in a dummy dataset depicting store items and their popularity percentages.
items_popularity = pd.read_csv('datasets/item_popularity.csv', encoding='utf-8')items_popularity['popularity_scale_10'] = np.array( np.round((items_popularity['pop_percent'] * 10)), dtype='int')items_popularity['popularity_scale_100'] = np.array( np.round((items_popularity['pop_percent'] * 100)), dtype='int')items_popularity
Based on the above ouputs, you can guess that we tried two forms of rounding. The features depict the item popularities now both on a scale of 1–10 and on a scale of 1–100. You can use these values both as numerical or categorical features based on the scenario and problem.
Supervised machine learning models usually try to model the output responses (discrete classes or continuous values) as a function of the input feature variables. For example, a simple linear regression equation can be depicted as
where the input features are depicted by variables
having weights or coefficients denoted by
respectively and the goal is to predict the response y.
In this case, this simple linear model depicts the relationship between the output and inputs, purely based on the individual, separate input features.
However, often in several real-world scenarios, it makes sense to also try and capture the interactions between these feature variables as a part of the input feature set. A simple depiction of the extension of the above linear regression formulation with interaction features would be
where the features represented by
denote the interaction features. Let’s try engineering some interaction features on our Pokémon dataset now.
atk_def = poke_df[['Attack', 'Defense']]atk_def.head()
From the output data frame, we can see that we have two numeric (continuous) features, Attack and Defence. We will now build features up to the 2nd degree by leveraging scikit-learn.
from sklearn.preprocessing import PolynomialFeaturespf = PolynomialFeatures(degree=2, interaction_only=False, include_bias=False)res = pf.fit_transform(atk_def)resOutput------array([[ 49., 49., 2401., 2401., 2401.], [ 62., 63., 3844., 3906., 3969.], [ 82., 83., 6724., 6806., 6889.], ..., [ 110., 60., 12100., 6600., 3600.], [ 160., 60., 25600., 9600., 3600.], [ 110., 120., 12100., 13200., 14400.]])
The above feature matrix depicts a total of five features including the new interaction features. We can see the degree of each feature in the above matrix as follows.
pd.DataFrame(pf.powers_, columns=['Attack_degree', 'Defense_degree'])
Looking at this output, we now know what each feature actually represents from the degrees depicted here. Armed with this knowledge, we can assign a name to each feature now as follows. This is just for ease of understanding and you should name your features with better, easy to access and simple names.
intr_features = pd.DataFrame(res, columns=['Attack', 'Defense', 'Attack^2', 'Attack x Defense', 'Defense^2'])intr_features.head(5)
Thus the above data frame represents our original features along with their interaction features.
The problem of working with raw, continuous numeric features is that often the distribution of values in these features will be skewed. This signifies that some values will occur quite frequently while some will be quite rare. Besides this, there is also another problem of the varying range of values in any of these features. For instance view counts of specific music videos could be abnormally large (Despacito we’re looking at you!) and some could be really small. Directly using these features can cause a lot of issues and adversely affect the model. Hence there are strategies to deal with this, which include binning and transformations.
Binning, also known as quantization is used for transforming continuous numeric features into discrete ones (categories). These discrete values or numbers can be thought of as categories or bins into which the raw, continuous numeric values are binned or grouped into. Each bin represents a specific degree of intensity and hence a specific range of continuous numeric values fall into it. Specific strategies of binning data include fixed-width and adaptive binning. Let’s use a subset of data from a dataset extracted from the 2016 FreeCodeCamp Developer\Coder survey which talks about various attributes pertaining to coders and software developers.
fcc_survey_df = pd.read_csv('datasets/fcc_2016_coder_survey_subset.csv', encoding='utf-8')fcc_survey_df[['ID.x', 'EmploymentField', 'Age', 'Income']].head()
The ID.x variable is basically a unique identifier for each coder\developer who took the survey and the other fields are pretty self-explanatory.
Just like the name indicates, in fixed-width binning, we have specific fixed widths for each of the bins which are usually pre-defined by the user analyzing the data. Each bin has a pre-fixed range of values which should be assigned to that bin on the basis of some domain knowledge, rules or constraints. Binning based on rounding is one of the ways, where you can use the rounding operation which we discussed earlier to bin raw values.
Let’s now consider the Age feature from the coder survey dataset and look at its distribution.
fig, ax = plt.subplots()fcc_survey_df['Age'].hist(color='#A9C5D3', edgecolor='black', grid=False)ax.set_title('Developer Age Histogram', fontsize=12)ax.set_xlabel('Age', fontsize=12)ax.set_ylabel('Frequency', fontsize=12)
The above histogram depicting developer ages is slightly right skewed as expected (lesser aged developers). We will now assign these raw age values into specific bins based on the following scheme
Age Range: Bin--------------- 0 - 9 : 010 - 19 : 120 - 29 : 230 - 39 : 340 - 49 : 450 - 59 : 560 - 69 : 6 ... and so on
We can easily do this using what we learnt in the Rounding section earlier where we round off these raw age values by taking the floor value after dividing it by 10.
fcc_survey_df['Age_bin_round'] = np.array(np.floor( np.array(fcc_survey_df['Age']) / 10.))fcc_survey_df[['ID.x', 'Age', 'Age_bin_round']].iloc[1071:1076]
You can see the corresponding bins for each age have been assigned based on rounding. But what if we need more flexibility? What if we want to decide and fix the bin widths based on our own rules\logic? Binning based on custom ranges will help us achieve this. Let’s define some custom age ranges for binning developer ages using the following scheme.
Age Range : Bin--------------- 0 - 15 : 116 - 30 : 231 - 45 : 346 - 60 : 461 - 75 : 575 - 100 : 6
Based on this custom binning scheme, we will now label the bins for each developer age value and we will store both the bin range as well as the corresponding label.
bin_ranges = [0, 15, 30, 45, 60, 75, 100]bin_names = [1, 2, 3, 4, 5, 6]fcc_survey_df['Age_bin_custom_range'] = pd.cut( np.array( fcc_survey_df['Age']), bins=bin_ranges)fcc_survey_df['Age_bin_custom_label'] = pd.cut( np.array( fcc_survey_df['Age']), bins=bin_ranges, labels=bin_names)# view the binned features fcc_survey_df[['ID.x', 'Age', 'Age_bin_round', 'Age_bin_custom_range', 'Age_bin_custom_label']].iloc[10a71:1076]
The drawback in using fixed-width binning is that due to us manually deciding the bin ranges, we can end up with irregular bins which are not uniform based on the number of data points or values which fall in each bin. Some of the bins might be densely populated and some of them might be sparsely populated or even empty! Adaptive binning is a safer strategy in these scenarios where we let the data speak for itself! That’s right, we use the data distribution itself to decide our bin ranges.
Quantile based binning is a good strategy to use for adaptive binning. Quantiles are specific values or cut-points which help in partitioning the continuous valued distribution of a specific numeric field into discrete contiguous bins or intervals. Thus, q-Quantiles help in partitioning a numeric attribute into q equal partitions. Popular examples of quantiles include the 2-Quantile known as the median which divides the data distribution into two equal bins, 4-Quantiles known as the quartiles which divide the data into 4 equal bins and 10-Quantiles also known as the deciles which create 10 equal width bins. Let’s now look at the data distribution for the developer Income field.
fig, ax = plt.subplots()fcc_survey_df['Income'].hist(bins=30, color='#A9C5D3', edgecolor='black', grid=False)ax.set_title('Developer Income Histogram', fontsize=12)ax.set_xlabel('Developer Income', fontsize=12)ax.set_ylabel('Frequency', fontsize=12)
The above distribution depicts a right skew in the income with lesser developers earning more money and vice versa. Let’s take a 4-Quantile or a quartile based adaptive binning scheme. We can obtain the quartiles easily as follows.
quantile_list = [0, .25, .5, .75, 1.]quantiles = fcc_survey_df['Income'].quantile(quantile_list)quantilesOutput------0.00 6000.00.25 20000.00.50 37000.00.75 60000.01.00 200000.0Name: Income, dtype: float64
Let’s now visualize these quantiles in the original distribution histogram!
fig, ax = plt.subplots()fcc_survey_df['Income'].hist(bins=30, color='#A9C5D3', edgecolor='black', grid=False)for quantile in quantiles: qvl = plt.axvline(quantile, color='r')ax.legend([qvl], ['Quantiles'], fontsize=10)ax.set_title('Developer Income Histogram with Quantiles', fontsize=12)ax.set_xlabel('Developer Income', fontsize=12)ax.set_ylabel('Frequency', fontsize=12)
The red lines in the distribution above depict the quartile values and our potential bins. Let’s now leverage this knowledge to build our quartile based binning scheme.
quantile_labels = ['0-25Q', '25-50Q', '50-75Q', '75-100Q']fcc_survey_df['Income_quantile_range'] = pd.qcut( fcc_survey_df['Income'], q=quantile_list)fcc_survey_df['Income_quantile_label'] = pd.qcut( fcc_survey_df['Income'], q=quantile_list, labels=quantile_labels)fcc_survey_df[['ID.x', 'Age', 'Income', 'Income_quantile_range', 'Income_quantile_label']].iloc[4:9]
This should give you a good idea of how quantile based adaptive binning works. An important point to remember here is that the resultant outcome of binning leads to discrete valued categorical features and you might need an additional step of feature engineering on the categorical data before using it in any model. We will cover feature engineering strategies for categorical data shortly in the next part!
We talked about the adverse effects of skewed data distributions briefly earlier. Let’s look at a different strategy of feature engineering now by making use of statistical or mathematical transformations.We will look at the Log transform as well as the Box-Cox transform. Both of these transform functions belong to the Power Transform family of functions, typically used to create monotonic data transformations. Their main significance is that they help in stabilizing variance, adhering closely to the normal distribution and making the data independent of the mean based on its distribution
The log transform belongs to the power transform family of functions. This function can be mathematically represented as
which reads as log of x to the base b is equal to y. This can then be translated into
which indicates as to what power must the base b be raised to in order to get x. The natural logarithm uses b=e where e = 2.71828 popularly known as Euler’s number. You can also use base b=10 used popularly in the decimal system.
Log transforms are useful when applied to skewed distributions as they tend to expand the values which fall in the range of lower magnitudes and tend to compress or reduce the values which fall in the range of higher magnitudes. This tends to make the skewed distribution as normal-like as possible. Let’s use log transform on our developer Income feature which we used earlier.
fcc_survey_df['Income_log'] = np.log((1+ fcc_survey_df['Income']))fcc_survey_df[['ID.x', 'Age', 'Income', 'Income_log']].iloc[4:9]
The Income_log field depicts the transformed feature after log transformation. Let’s look at the data distribution on this transformed field now.
income_log_mean = np.round(np.mean(fcc_survey_df['Income_log']), 2)fig, ax = plt.subplots()fcc_survey_df['Income_log'].hist(bins=30, color='#A9C5D3', edgecolor='black', grid=False)plt.axvline(income_log_mean, color='r')ax.set_title('Developer Income Histogram after Log Transform', fontsize=12)ax.set_xlabel('Developer Income (log scale)', fontsize=12)ax.set_ylabel('Frequency', fontsize=12)ax.text(11.5, 450, r'$\mu$='+str(income_log_mean), fontsize=10)
Based on the above plot, we can clearly see that the distribution is more normal-like or gaussian as compared to the skewed distribution on the original data.
The Box-Cox transform is another popular function belonging to the power transform family of functions. This function has a pre-requisite that the numeric values to be transformed must be positive (similar to what log transform expects). In case they are negative, shifting using a constant value helps. Mathematically, the Box-Cox transform function can be denoted as follows.
Such that the resulted transformed output y is a function of input x and the transformation parameter λ such that when λ = 0, the resultant transform is the natural log transform which we discussed earlier. The optimal value of λ is usually determined using a maximum likelihood or log-likelihood estimation. Let’s now apply the Box-Cox transform on our developer income feature. First we get the optimal lambda value from the data distribution by removing the non-null values as follows.
income = np.array(fcc_survey_df['Income'])income_clean = income[~np.isnan(income)]l, opt_lambda = spstats.boxcox(income_clean)print('Optimal lambda value:', opt_lambda)Output------Optimal lambda value: 0.117991239456
Now that we have obtained the optimal λ value, let us use the Box-Cox transform for two values of λ such that λ = 0 and λ = λ(optimal) and transform the developer Income feature.
fcc_survey_df['Income_boxcox_lambda_0'] = spstats.boxcox( (1+fcc_survey_df['Income']), lmbda=0)fcc_survey_df['Income_boxcox_lambda_opt'] = spstats.boxcox( fcc_survey_df['Income'], lmbda=opt_lambda)fcc_survey_df[['ID.x', 'Age', 'Income', 'Income_log', 'Income_boxcox_lambda_0', 'Income_boxcox_lambda_opt']].iloc[4:9]
The transformed features are depicted in the above data frame. Just like we expected, Income_log and Income_boxcox_lamba_0 have the same values. Let’s look at the distribution of the transformed Income feature after transforming with the optimal λ.
income_boxcox_mean = np.round( np.mean( fcc_survey_df['Income_boxcox_lambda_opt']),2)fig, ax = plt.subplots()fcc_survey_df['Income_boxcox_lambda_opt'].hist(bins=30, color='#A9C5D3', edgecolor='black', grid=False)plt.axvline(income_boxcox_mean, color='r')ax.set_title('Developer Income Histogram after Box–Cox Transform', fontsize=12)ax.set_xlabel('Developer Income (Box–Cox transform)', fontsize=12)ax.set_ylabel('Frequency', fontsize=12)ax.text(24, 450, r'$\mu$='+str(income_boxcox_mean), fontsize=10)
The distribution looks more normal-like similar to what we obtained after the log transform.
Feature engineering is a very important aspect of machine learning and data science and should never be ignored. While we have automated feature engineering methodologies like deep learning as well as automated machine learning frameworks like AutoML (which still stresses that it requires good features to work well!). Feature engineering is here to stay and even some of these automated methodologies often require specific engineered features based on the data type, domain and the problem to be solved.
We looked at popular strategies for feature engineering on continuous numeric data in this article. In the next part, we will look at popular strategies for dealing with discrete, categorical data and then move on to unstructured data types in future articles. Stay tuned!
All the code and datasets used in this article can be accessed from my GitHub
The code is also available as a Jupyter notebook
|
[
{
"code": null,
"e": 1065,
"s": 171,
"text": "“Money makes the world go round” is something which you cannot ignore whether to choose to agree or disagree with it. A more apt saying in today’s digital revolutionary age would be “Data makes the world go round”. Indeed data has become a first class asset for businesses, corporations and organizations irrespective of their size and scale. Any intelligent system regardless of their complexity needs to be powered by data. At the heart of any intelligent system, we have one or more algorithms based on machine learning, deep learning or statistical methods which consume this data to gather knowledge and provide intelligent insights over a period of time. Algorithms are pretty naive by themselves and cannot work out of the box on raw data. Hence the need for engineering meaningful features from raw data is of utmost importance which can be understood and consumed by these algorithms."
},
{
"code": null,
"e": 1621,
"s": 1065,
"text": "Any intelligent system basically consists of an end-to-end pipeline starting from ingesting raw data, leveraging data processing techniques to wrangle, process and engineer meaningful features and attributes from this data. Then we usually leverage techniques like statistical models or machine learning models to model on these features and then deploy this model if necessary for future usage based on the problem to be solved at hand. A typical standard machine learning pipeline based on the CRISP-DM industry standard process model is depicted below."
},
{
"code": null,
"e": 2020,
"s": 1621,
"text": "Ingesting raw data and building models on top of this data directly would be foolhardy since we wouldn’t get desired results or performance and also algorithms are not intelligent enough to automatically extract meaningful features from raw data (there are automated feature extraction techniques which are enabled nowadays with deep learning methodologies to some extent, but more on that later!)."
},
{
"code": null,
"e": 2289,
"s": 2020,
"text": "Our main area of focus falls under the data preparation aspect as pointed out in the figure above, where we deal with various methodologies to extract meaningful attributes or features from the raw data after it has gone through necessary wrangling and pre-processing."
},
{
"code": null,
"e": 2931,
"s": 2289,
"text": "Feature engineering is an essential part of building any intelligent system. Even though you have a lot of newer methodologies coming in like deep learning and meta-heuristics which aid in automated machine learning, each problem is domain specific and better features (suited to the problem) is often the deciding factor of the performance of your system. Feature Engineering is an art as well as a science and this is the reason Data Scientists often spend 70% of their time in the data preparation phase before modeling. Let’s look at a few quotes relevant to feature engineering from several renowned people in the world of Data Science."
},
{
"code": null,
"e": 3075,
"s": 2931,
"text": "“Coming up with features is difficult, time-consuming, requires expert knowledge. ‘Applied machine learning’ is basically feature engineering.”"
},
{
"code": null,
"e": 3094,
"s": 3075,
"text": "— Prof. Andrew Ng."
},
{
"code": null,
"e": 3340,
"s": 3094,
"text": "This basically reinforces what we mentioned earlier about data scientists spending close to 80% of their time in engineering features which is a difficult and time-consuming process, requiring both domain knowledge and mathematical computations."
},
{
"code": null,
"e": 3540,
"s": 3340,
"text": "“Feature engineering is the process of transforming raw data into features that better represent the underlying problem to the predictive models, resulting in improved model accuracy on unseen data.”"
},
{
"code": null,
"e": 3561,
"s": 3540,
"text": "— Dr. Jason Brownlee"
},
{
"code": null,
"e": 4102,
"s": 3561,
"text": "This gives us an idea about feature engineering being the process of transforming data into features to act as inputs for machine learning models such that good quality features help in improving the overall model performance. Features are also very much dependent on the underlying problem. Thus, even though the machine learning task might be same in different scenarios, like classification of emails into spam and non-spam or classifying handwritten digits, the features extracted in each scenario will be very different from the other."
},
{
"code": null,
"e": 4256,
"s": 4102,
"text": "Prof. Pedro Domingos from the University of Washington, in his paper titled, “A Few Useful Things to Know about Machine Learning” tells us the following."
},
{
"code": null,
"e": 4417,
"s": 4256,
"text": "“At the end of the day, some machine learning projects succeed and some fail. What makes the difference? Easily the most important factor is the features used.”"
},
{
"code": null,
"e": 4440,
"s": 4417,
"text": "— Prof. Pedro Domingos"
},
{
"code": null,
"e": 4694,
"s": 4440,
"text": "The final quote which should motivate you about feature engineering is from renowned Kaggler, Xavier Conort. Most of you already know that tough real-world machine learning problems are often posted on Kaggle regularly which is usually open to everyone."
},
{
"code": null,
"e": 4916,
"s": 4694,
"text": "“The algorithms we used are very standard for Kagglers. ...We spent most of our efforts in feature engineering. ... We were also very careful to discard features likely to expose us to the risk of over-fitting our model.”"
},
{
"code": null,
"e": 4932,
"s": 4916,
"text": "— Xavier Conort"
},
{
"code": null,
"e": 5260,
"s": 4932,
"text": "A feature is typically a specific representation on top of raw data, which is an individual, measurable attribute, typically depicted by a column in a dataset. Considering a generic two-dimensional dataset, each observation is depicted by a row and each feature by a column, which will have a specific value for an observation."
},
{
"code": null,
"e": 5802,
"s": 5260,
"text": "Thus like in the example in the figure above, each row typically indicates a feature vector and the entire set of features across all the observations forms a two-dimensional feature matrix also known as a feature-set. This is akin to data frames or spreadsheets representing two-dimensional data. Typically machine learning algorithms work with these numeric matrices or tensors and hence most feature engineering techniques deal with converting raw data into some numeric representations which can be easily understood by these algorithms."
},
{
"code": null,
"e": 6252,
"s": 5802,
"text": "Features can be of two major types based on the dataset. Inherent raw features are obtained directly from the dataset with no extra data manipulation or engineering. Derived features are usually obtained from feature engineering, where we extract features from existing data attributes. A simple example would be creating a new feature “Age” from an employee dataset containing “Birthdate” by just subtracting their birth date from the current date."
},
{
"code": null,
"e": 6771,
"s": 6252,
"text": "There are diverse types and formats of data including structured and unstructured data. In this article, we will discuss various feature engineering strategies for dealing with structured continuous numeric data. All these examples are a part of one of my recent books ‘Practical Machine Learning with Python’ and you can access relevant datasets and code used in this article on GitHub. A big shout out also goes to Gabriel Moreira who helped me by providing some excellent pointers on feature engineering techniques."
},
{
"code": null,
"e": 7681,
"s": 6771,
"text": "Numeric data typically represents data in the form of scalar values depicting observations, recordings or measurements. Here, by numeric data, we mean continuous data and not discrete data which is typically represented as categorical data. Numeric data can also be represented as a vector of values where each value or entity in the vector can represent a specific feature. Integers and floats are the most common and widely used numeric data types for continuous numeric data. Even though numeric data can be directly fed into machine learning models, you would still need to engineer features which are relevant to the scenario, problem and domain before building a model. Hence the need for feature engineering still remains. Let’s leverage python and look at some strategies for feature engineering on numeric data. We load up the following necessary dependencies first (typically in a Jupyter notebook)."
},
{
"code": null,
"e": 7797,
"s": 7681,
"text": "import pandas as pdimport matplotlib.pyplot as pltimport numpy as npimport scipy.stats as spstats%matplotlib inline"
},
{
"code": null,
"e": 8203,
"s": 7797,
"text": "Like we mentioned earlier, raw numeric data can often be fed directly to machine learning models based on the context and data format. Raw measures are typically indicated using numeric variables directly as features without any form of transformation or engineering. Typically these features can indicate values or counts. Let’s load up one of our datasets, the Pokémon dataset also available on Kaggle."
},
{
"code": null,
"e": 8282,
"s": 8203,
"text": "poke_df = pd.read_csv('datasets/Pokemon.csv', encoding='utf-8') poke_df.head()"
},
{
"code": null,
"e": 8557,
"s": 8282,
"text": "Pokémon is a huge media franchise surrounding fictional characters called Pokémon which stands for pocket monsters. In short, you can think of them as fictional animals with superpowers! This dataset consists of these characters with various statistics for each character."
},
{
"code": null,
"e": 8791,
"s": 8557,
"text": "If you closely observe the data frame snapshot in the above figure, you can see that several attributes represent numeric raw values which can be used directly. The following snippet depicts some of these features with more emphasis."
},
{
"code": null,
"e": 8835,
"s": 8791,
"text": "poke_df[['HP', 'Attack', 'Defense']].head()"
},
{
"code": null,
"e": 9086,
"s": 8835,
"text": "Thus, you can directly use these attributes as features which are depicted in the above data frame. These include each Pokémon’s HP (Hit Points), Attack and Defense stats. In fact, we can also compute some basic statistical measures on these fields."
},
{
"code": null,
"e": 9134,
"s": 9086,
"text": "poke_df[['HP', 'Attack', 'Defense']].describe()"
},
{
"code": null,
"e": 9268,
"s": 9134,
"text": "With this you can get a good idea about statistical measures in these features like count, average, standard deviation and quartiles."
},
{
"code": null,
"e": 9534,
"s": 9268,
"text": "Another form of raw measures include features which represent frequencies, counts or occurrences of specific attributes. Let’s look at a sample of data from the millionsong dataset which depicts counts or frequencies of songs which have been heard by various users."
},
{
"code": null,
"e": 9649,
"s": 9534,
"text": "popsong_df = pd.read_csv('datasets/song_views.csv', encoding='utf-8')popsong_df.head(10)"
},
{
"code": null,
"e": 9786,
"s": 9649,
"text": "It is quite evident from the above snapshot that the listen_count field can be used directly as a frequency\\count based numeric feature."
},
{
"code": null,
"e": 10347,
"s": 9786,
"text": "Often raw frequencies or counts may not be relevant for building a model based on the problem which is being solved. For instance if I’m building a recommendation system for song recommendations, I would just want to know if a person is interested or has listened to a particular song. This doesn’t require the number of times a song has been listened to since I am more concerned about the various songs he\\she has listened to. In this case, a binary feature is preferred as opposed to a count based feature. We can binarize our listen_count field as follows."
},
{
"code": null,
"e": 10451,
"s": 10347,
"text": "watched = np.array(popsong_df['listen_count']) watched[watched >= 1] = 1popsong_df['watched'] = watched"
},
{
"code": null,
"e": 10584,
"s": 10451,
"text": "You can also use scikit-learn's Binarizer class here from its preprocessing module to perform the same task instead of numpy arrays."
},
{
"code": null,
"e": 10771,
"s": 10584,
"text": "from sklearn.preprocessing import Binarizerbn = Binarizer(threshold=0.9)pd_watched = bn.transform([popsong_df['listen_count']])[0]popsong_df['pd_watched'] = pd_watchedpopsong_df.head(11)"
},
{
"code": null,
"e": 11011,
"s": 10771,
"text": "You can clearly see from the above snapshot that both the methods have produced the same result. Thus we get a binarized feature indicating if the song was listened to or not by each user which can be then further used in a relevant model."
},
{
"code": null,
"e": 11478,
"s": 11011,
"text": "Often when dealing with continuous numeric attributes like proportions or percentages, we may not need the raw values having a high amount of precision. Hence it often makes sense to round off these high precision percentages into numeric integers. These integers can then be directly used as raw values or even as categorical (discrete-class based) features. Let’s try applying this concept in a dummy dataset depicting store items and their popularity percentages."
},
{
"code": null,
"e": 11913,
"s": 11478,
"text": "items_popularity = pd.read_csv('datasets/item_popularity.csv', encoding='utf-8')items_popularity['popularity_scale_10'] = np.array( np.round((items_popularity['pop_percent'] * 10)), dtype='int')items_popularity['popularity_scale_100'] = np.array( np.round((items_popularity['pop_percent'] * 100)), dtype='int')items_popularity"
},
{
"code": null,
"e": 12188,
"s": 11913,
"text": "Based on the above ouputs, you can guess that we tried two forms of rounding. The features depict the item popularities now both on a scale of 1–10 and on a scale of 1–100. You can use these values both as numerical or categorical features based on the scenario and problem."
},
{
"code": null,
"e": 12419,
"s": 12188,
"text": "Supervised machine learning models usually try to model the output responses (discrete classes or continuous values) as a function of the input feature variables. For example, a simple linear regression equation can be depicted as"
},
{
"code": null,
"e": 12470,
"s": 12419,
"text": "where the input features are depicted by variables"
},
{
"code": null,
"e": 12512,
"s": 12470,
"text": "having weights or coefficients denoted by"
},
{
"code": null,
"e": 12568,
"s": 12512,
"text": "respectively and the goal is to predict the response y."
},
{
"code": null,
"e": 12720,
"s": 12568,
"text": "In this case, this simple linear model depicts the relationship between the output and inputs, purely based on the individual, separate input features."
},
{
"code": null,
"e": 13006,
"s": 12720,
"text": "However, often in several real-world scenarios, it makes sense to also try and capture the interactions between these feature variables as a part of the input feature set. A simple depiction of the extension of the above linear regression formulation with interaction features would be"
},
{
"code": null,
"e": 13040,
"s": 13006,
"text": "where the features represented by"
},
{
"code": null,
"e": 13150,
"s": 13040,
"text": "denote the interaction features. Let’s try engineering some interaction features on our Pokémon dataset now."
},
{
"code": null,
"e": 13205,
"s": 13150,
"text": "atk_def = poke_df[['Attack', 'Defense']]atk_def.head()"
},
{
"code": null,
"e": 13388,
"s": 13205,
"text": "From the output data frame, we can see that we have two numeric (continuous) features, Attack and Defence. We will now build features up to the 2nd degree by leveraging scikit-learn."
},
{
"code": null,
"e": 13920,
"s": 13388,
"text": "from sklearn.preprocessing import PolynomialFeaturespf = PolynomialFeatures(degree=2, interaction_only=False, include_bias=False)res = pf.fit_transform(atk_def)resOutput------array([[ 49., 49., 2401., 2401., 2401.], [ 62., 63., 3844., 3906., 3969.], [ 82., 83., 6724., 6806., 6889.], ..., [ 110., 60., 12100., 6600., 3600.], [ 160., 60., 25600., 9600., 3600.], [ 110., 120., 12100., 13200., 14400.]])"
},
{
"code": null,
"e": 14088,
"s": 13920,
"text": "The above feature matrix depicts a total of five features including the new interaction features. We can see the degree of each feature in the above matrix as follows."
},
{
"code": null,
"e": 14193,
"s": 14088,
"text": "pd.DataFrame(pf.powers_, columns=['Attack_degree', 'Defense_degree'])"
},
{
"code": null,
"e": 14498,
"s": 14193,
"text": "Looking at this output, we now know what each feature actually represents from the degrees depicted here. Armed with this knowledge, we can assign a name to each feature now as follows. This is just for ease of understanding and you should name your features with better, easy to access and simple names."
},
{
"code": null,
"e": 14760,
"s": 14498,
"text": "intr_features = pd.DataFrame(res, columns=['Attack', 'Defense', 'Attack^2', 'Attack x Defense', 'Defense^2'])intr_features.head(5)"
},
{
"code": null,
"e": 14858,
"s": 14760,
"text": "Thus the above data frame represents our original features along with their interaction features."
},
{
"code": null,
"e": 15505,
"s": 14858,
"text": "The problem of working with raw, continuous numeric features is that often the distribution of values in these features will be skewed. This signifies that some values will occur quite frequently while some will be quite rare. Besides this, there is also another problem of the varying range of values in any of these features. For instance view counts of specific music videos could be abnormally large (Despacito we’re looking at you!) and some could be really small. Directly using these features can cause a lot of issues and adversely affect the model. Hence there are strategies to deal with this, which include binning and transformations."
},
{
"code": null,
"e": 16158,
"s": 15505,
"text": "Binning, also known as quantization is used for transforming continuous numeric features into discrete ones (categories). These discrete values or numbers can be thought of as categories or bins into which the raw, continuous numeric values are binned or grouped into. Each bin represents a specific degree of intensity and hence a specific range of continuous numeric values fall into it. Specific strategies of binning data include fixed-width and adaptive binning. Let’s use a subset of data from a dataset extracted from the 2016 FreeCodeCamp Developer\\Coder survey which talks about various attributes pertaining to coders and software developers."
},
{
"code": null,
"e": 16315,
"s": 16158,
"text": "fcc_survey_df = pd.read_csv('datasets/fcc_2016_coder_survey_subset.csv', encoding='utf-8')fcc_survey_df[['ID.x', 'EmploymentField', 'Age', 'Income']].head()"
},
{
"code": null,
"e": 16461,
"s": 16315,
"text": "The ID.x variable is basically a unique identifier for each coder\\developer who took the survey and the other fields are pretty self-explanatory."
},
{
"code": null,
"e": 16900,
"s": 16461,
"text": "Just like the name indicates, in fixed-width binning, we have specific fixed widths for each of the bins which are usually pre-defined by the user analyzing the data. Each bin has a pre-fixed range of values which should be assigned to that bin on the basis of some domain knowledge, rules or constraints. Binning based on rounding is one of the ways, where you can use the rounding operation which we discussed earlier to bin raw values."
},
{
"code": null,
"e": 16995,
"s": 16900,
"text": "Let’s now consider the Age feature from the coder survey dataset and look at its distribution."
},
{
"code": null,
"e": 17244,
"s": 16995,
"text": "fig, ax = plt.subplots()fcc_survey_df['Age'].hist(color='#A9C5D3', edgecolor='black', grid=False)ax.set_title('Developer Age Histogram', fontsize=12)ax.set_xlabel('Age', fontsize=12)ax.set_ylabel('Frequency', fontsize=12)"
},
{
"code": null,
"e": 17441,
"s": 17244,
"text": "The above histogram depicting developer ages is slightly right skewed as expected (lesser aged developers). We will now assign these raw age values into specific bins based on the following scheme"
},
{
"code": null,
"e": 17570,
"s": 17441,
"text": "Age Range: Bin--------------- 0 - 9 : 010 - 19 : 120 - 29 : 230 - 39 : 340 - 49 : 450 - 59 : 560 - 69 : 6 ... and so on"
},
{
"code": null,
"e": 17736,
"s": 17570,
"text": "We can easily do this using what we learnt in the Rounding section earlier where we round off these raw age values by taking the floor value after dividing it by 10."
},
{
"code": null,
"e": 17919,
"s": 17736,
"text": "fcc_survey_df['Age_bin_round'] = np.array(np.floor( np.array(fcc_survey_df['Age']) / 10.))fcc_survey_df[['ID.x', 'Age', 'Age_bin_round']].iloc[1071:1076]"
},
{
"code": null,
"e": 18271,
"s": 17919,
"text": "You can see the corresponding bins for each age have been assigned based on rounding. But what if we need more flexibility? What if we want to decide and fix the bin widths based on our own rules\\logic? Binning based on custom ranges will help us achieve this. Let’s define some custom age ranges for binning developer ages using the following scheme."
},
{
"code": null,
"e": 18380,
"s": 18271,
"text": "Age Range : Bin--------------- 0 - 15 : 116 - 30 : 231 - 45 : 346 - 60 : 461 - 75 : 575 - 100 : 6"
},
{
"code": null,
"e": 18546,
"s": 18380,
"text": "Based on this custom binning scheme, we will now label the bins for each developer age value and we will store both the bin range as well as the corresponding label."
},
{
"code": null,
"e": 19324,
"s": 18546,
"text": "bin_ranges = [0, 15, 30, 45, 60, 75, 100]bin_names = [1, 2, 3, 4, 5, 6]fcc_survey_df['Age_bin_custom_range'] = pd.cut( np.array( fcc_survey_df['Age']), bins=bin_ranges)fcc_survey_df['Age_bin_custom_label'] = pd.cut( np.array( fcc_survey_df['Age']), bins=bin_ranges, labels=bin_names)# view the binned features fcc_survey_df[['ID.x', 'Age', 'Age_bin_round', 'Age_bin_custom_range', 'Age_bin_custom_label']].iloc[10a71:1076]"
},
{
"code": null,
"e": 19819,
"s": 19324,
"text": "The drawback in using fixed-width binning is that due to us manually deciding the bin ranges, we can end up with irregular bins which are not uniform based on the number of data points or values which fall in each bin. Some of the bins might be densely populated and some of them might be sparsely populated or even empty! Adaptive binning is a safer strategy in these scenarios where we let the data speak for itself! That’s right, we use the data distribution itself to decide our bin ranges."
},
{
"code": null,
"e": 20506,
"s": 19819,
"text": "Quantile based binning is a good strategy to use for adaptive binning. Quantiles are specific values or cut-points which help in partitioning the continuous valued distribution of a specific numeric field into discrete contiguous bins or intervals. Thus, q-Quantiles help in partitioning a numeric attribute into q equal partitions. Popular examples of quantiles include the 2-Quantile known as the median which divides the data distribution into two equal bins, 4-Quantiles known as the quartiles which divide the data into 4 equal bins and 10-Quantiles also known as the deciles which create 10 equal width bins. Let’s now look at the data distribution for the developer Income field."
},
{
"code": null,
"e": 20785,
"s": 20506,
"text": "fig, ax = plt.subplots()fcc_survey_df['Income'].hist(bins=30, color='#A9C5D3', edgecolor='black', grid=False)ax.set_title('Developer Income Histogram', fontsize=12)ax.set_xlabel('Developer Income', fontsize=12)ax.set_ylabel('Frequency', fontsize=12)"
},
{
"code": null,
"e": 21017,
"s": 20785,
"text": "The above distribution depicts a right skew in the income with lesser developers earning more money and vice versa. Let’s take a 4-Quantile or a quartile based adaptive binning scheme. We can obtain the quartiles easily as follows."
},
{
"code": null,
"e": 21243,
"s": 21017,
"text": "quantile_list = [0, .25, .5, .75, 1.]quantiles = fcc_survey_df['Income'].quantile(quantile_list)quantilesOutput------0.00 6000.00.25 20000.00.50 37000.00.75 60000.01.00 200000.0Name: Income, dtype: float64"
},
{
"code": null,
"e": 21319,
"s": 21243,
"text": "Let’s now visualize these quantiles in the original distribution histogram!"
},
{
"code": null,
"e": 21738,
"s": 21319,
"text": "fig, ax = plt.subplots()fcc_survey_df['Income'].hist(bins=30, color='#A9C5D3', edgecolor='black', grid=False)for quantile in quantiles: qvl = plt.axvline(quantile, color='r')ax.legend([qvl], ['Quantiles'], fontsize=10)ax.set_title('Developer Income Histogram with Quantiles', fontsize=12)ax.set_xlabel('Developer Income', fontsize=12)ax.set_ylabel('Frequency', fontsize=12)"
},
{
"code": null,
"e": 21907,
"s": 21738,
"text": "The red lines in the distribution above depict the quartile values and our potential bins. Let’s now leverage this knowledge to build our quartile based binning scheme."
},
{
"code": null,
"e": 22511,
"s": 21907,
"text": "quantile_labels = ['0-25Q', '25-50Q', '50-75Q', '75-100Q']fcc_survey_df['Income_quantile_range'] = pd.qcut( fcc_survey_df['Income'], q=quantile_list)fcc_survey_df['Income_quantile_label'] = pd.qcut( fcc_survey_df['Income'], q=quantile_list, labels=quantile_labels)fcc_survey_df[['ID.x', 'Age', 'Income', 'Income_quantile_range', 'Income_quantile_label']].iloc[4:9]"
},
{
"code": null,
"e": 22920,
"s": 22511,
"text": "This should give you a good idea of how quantile based adaptive binning works. An important point to remember here is that the resultant outcome of binning leads to discrete valued categorical features and you might need an additional step of feature engineering on the categorical data before using it in any model. We will cover feature engineering strategies for categorical data shortly in the next part!"
},
{
"code": null,
"e": 23516,
"s": 22920,
"text": "We talked about the adverse effects of skewed data distributions briefly earlier. Let’s look at a different strategy of feature engineering now by making use of statistical or mathematical transformations.We will look at the Log transform as well as the Box-Cox transform. Both of these transform functions belong to the Power Transform family of functions, typically used to create monotonic data transformations. Their main significance is that they help in stabilizing variance, adhering closely to the normal distribution and making the data independent of the mean based on its distribution"
},
{
"code": null,
"e": 23637,
"s": 23516,
"text": "The log transform belongs to the power transform family of functions. This function can be mathematically represented as"
},
{
"code": null,
"e": 23723,
"s": 23637,
"text": "which reads as log of x to the base b is equal to y. This can then be translated into"
},
{
"code": null,
"e": 23953,
"s": 23723,
"text": "which indicates as to what power must the base b be raised to in order to get x. The natural logarithm uses b=e where e = 2.71828 popularly known as Euler’s number. You can also use base b=10 used popularly in the decimal system."
},
{
"code": null,
"e": 24332,
"s": 23953,
"text": "Log transforms are useful when applied to skewed distributions as they tend to expand the values which fall in the range of lower magnitudes and tend to compress or reduce the values which fall in the range of higher magnitudes. This tends to make the skewed distribution as normal-like as possible. Let’s use log transform on our developer Income feature which we used earlier."
},
{
"code": null,
"e": 24463,
"s": 24332,
"text": "fcc_survey_df['Income_log'] = np.log((1+ fcc_survey_df['Income']))fcc_survey_df[['ID.x', 'Age', 'Income', 'Income_log']].iloc[4:9]"
},
{
"code": null,
"e": 24609,
"s": 24463,
"text": "The Income_log field depicts the transformed feature after log transformation. Let’s look at the data distribution on this transformed field now."
},
{
"code": null,
"e": 25110,
"s": 24609,
"text": "income_log_mean = np.round(np.mean(fcc_survey_df['Income_log']), 2)fig, ax = plt.subplots()fcc_survey_df['Income_log'].hist(bins=30, color='#A9C5D3', edgecolor='black', grid=False)plt.axvline(income_log_mean, color='r')ax.set_title('Developer Income Histogram after Log Transform', fontsize=12)ax.set_xlabel('Developer Income (log scale)', fontsize=12)ax.set_ylabel('Frequency', fontsize=12)ax.text(11.5, 450, r'$\\mu$='+str(income_log_mean), fontsize=10)"
},
{
"code": null,
"e": 25269,
"s": 25110,
"text": "Based on the above plot, we can clearly see that the distribution is more normal-like or gaussian as compared to the skewed distribution on the original data."
},
{
"code": null,
"e": 25647,
"s": 25269,
"text": "The Box-Cox transform is another popular function belonging to the power transform family of functions. This function has a pre-requisite that the numeric values to be transformed must be positive (similar to what log transform expects). In case they are negative, shifting using a constant value helps. Mathematically, the Box-Cox transform function can be denoted as follows."
},
{
"code": null,
"e": 26136,
"s": 25647,
"text": "Such that the resulted transformed output y is a function of input x and the transformation parameter λ such that when λ = 0, the resultant transform is the natural log transform which we discussed earlier. The optimal value of λ is usually determined using a maximum likelihood or log-likelihood estimation. Let’s now apply the Box-Cox transform on our developer income feature. First we get the optimal lambda value from the data distribution by removing the non-null values as follows."
},
{
"code": null,
"e": 26353,
"s": 26136,
"text": "income = np.array(fcc_survey_df['Income'])income_clean = income[~np.isnan(income)]l, opt_lambda = spstats.boxcox(income_clean)print('Optimal lambda value:', opt_lambda)Output------Optimal lambda value: 0.117991239456"
},
{
"code": null,
"e": 26532,
"s": 26353,
"text": "Now that we have obtained the optimal λ value, let us use the Box-Cox transform for two values of λ such that λ = 0 and λ = λ(optimal) and transform the developer Income feature."
},
{
"code": null,
"e": 27054,
"s": 26532,
"text": "fcc_survey_df['Income_boxcox_lambda_0'] = spstats.boxcox( (1+fcc_survey_df['Income']), lmbda=0)fcc_survey_df['Income_boxcox_lambda_opt'] = spstats.boxcox( fcc_survey_df['Income'], lmbda=opt_lambda)fcc_survey_df[['ID.x', 'Age', 'Income', 'Income_log', 'Income_boxcox_lambda_0', 'Income_boxcox_lambda_opt']].iloc[4:9]"
},
{
"code": null,
"e": 27303,
"s": 27054,
"text": "The transformed features are depicted in the above data frame. Just like we expected, Income_log and Income_boxcox_lamba_0 have the same values. Let’s look at the distribution of the transformed Income feature after transforming with the optimal λ."
},
{
"code": null,
"e": 27883,
"s": 27303,
"text": "income_boxcox_mean = np.round( np.mean( fcc_survey_df['Income_boxcox_lambda_opt']),2)fig, ax = plt.subplots()fcc_survey_df['Income_boxcox_lambda_opt'].hist(bins=30, color='#A9C5D3', edgecolor='black', grid=False)plt.axvline(income_boxcox_mean, color='r')ax.set_title('Developer Income Histogram after Box–Cox Transform', fontsize=12)ax.set_xlabel('Developer Income (Box–Cox transform)', fontsize=12)ax.set_ylabel('Frequency', fontsize=12)ax.text(24, 450, r'$\\mu$='+str(income_boxcox_mean), fontsize=10)"
},
{
"code": null,
"e": 27976,
"s": 27883,
"text": "The distribution looks more normal-like similar to what we obtained after the log transform."
},
{
"code": null,
"e": 28483,
"s": 27976,
"text": "Feature engineering is a very important aspect of machine learning and data science and should never be ignored. While we have automated feature engineering methodologies like deep learning as well as automated machine learning frameworks like AutoML (which still stresses that it requires good features to work well!). Feature engineering is here to stay and even some of these automated methodologies often require specific engineered features based on the data type, domain and the problem to be solved."
},
{
"code": null,
"e": 28756,
"s": 28483,
"text": "We looked at popular strategies for feature engineering on continuous numeric data in this article. In the next part, we will look at popular strategies for dealing with discrete, categorical data and then move on to unstructured data types in future articles. Stay tuned!"
},
{
"code": null,
"e": 28834,
"s": 28756,
"text": "All the code and datasets used in this article can be accessed from my GitHub"
}
] |
Python Pandas - Sort DataFrame in descending order according to the element frequency
|
To sort data in ascending or descending order, use sort_values() method. For descending order, use the following in the sort_values() method −
ascending=False
Import the required library −
import pandas as pd
Create a DataFrame with 3 columns −
dataFrame = pd.DataFrame(
{
"Car": ['BMW', 'Lexus', 'BMW', 'Mustang', 'Mercedes', 'Lexus'],"Reg_Price": [7000, 1500, 5000, 8000, 9000, 2000],"Place": ['Pune', 'Delhi', 'Mumbai', 'Hyderabad', 'Bangalore', 'Chandigarh']
}
)
To sort DataFrame in descending order according to the element frequency, we need to count the occurrences. Therefore, count() is also used with sort_values() set for descending order sort −
dataFrame.groupby(['Car'])['Reg_Price'].count().reset_index(name='Count').sort_values(['Count'], ascending=False)
Following is the code −
import pandas as pd
# Create DataFrame
dataFrame = pd.DataFrame(
{
"Car": ['BMW', 'Lexus', 'BMW', 'Mustang', 'Mercedes', 'Lexus'],"Reg_Price": [7000, 1500, 5000, 8000, 9000, 2000],"Place": ['Pune', 'Delhi', 'Mumbai', 'Hyderabad', 'Bangalore', 'Chandigarh']
}
)
print"DataFrame ...\n",dataFrame
# Sort DataFrame in descending order according to the element frequency
dataFrame = dataFrame.groupby(['Car'])['Reg_Price'].count().reset_index(name='Count').sort_values(['Count'], ascending=False)
print"\nSorting DataFrame ...\n",dataFrame
This will produce the following output −
DataFrame ...
Car Place Reg_Price
0 BMW Pune 7000
1 Lexus Delhi 1500
2 BMW Mumbai 5000
3 Mustang Hyderabad 8000
4 Mercedes Bangalore 9000
5 Lexus Chandigarh 2000
Sorting DataFrame ...
Car Count
0 BMW 2
1 Lexus 2
2 Mercedes 1
3 Mustang 1
|
[
{
"code": null,
"e": 1205,
"s": 1062,
"text": "To sort data in ascending or descending order, use sort_values() method. For descending order, use the following in the sort_values() method −"
},
{
"code": null,
"e": 1221,
"s": 1205,
"text": "ascending=False"
},
{
"code": null,
"e": 1251,
"s": 1221,
"text": "Import the required library −"
},
{
"code": null,
"e": 1272,
"s": 1251,
"text": "import pandas as pd\n"
},
{
"code": null,
"e": 1308,
"s": 1272,
"text": "Create a DataFrame with 3 columns −"
},
{
"code": null,
"e": 1542,
"s": 1308,
"text": "dataFrame = pd.DataFrame(\n {\n \"Car\": ['BMW', 'Lexus', 'BMW', 'Mustang', 'Mercedes', 'Lexus'],\"Reg_Price\": [7000, 1500, 5000, 8000, 9000, 2000],\"Place\": ['Pune', 'Delhi', 'Mumbai', 'Hyderabad', 'Bangalore', 'Chandigarh']\n }\n)"
},
{
"code": null,
"e": 1733,
"s": 1542,
"text": "To sort DataFrame in descending order according to the element frequency, we need to count the occurrences. Therefore, count() is also used with sort_values() set for descending order sort −"
},
{
"code": null,
"e": 1847,
"s": 1733,
"text": "dataFrame.groupby(['Car'])['Reg_Price'].count().reset_index(name='Count').sort_values(['Count'], ascending=False)"
},
{
"code": null,
"e": 1871,
"s": 1847,
"text": "Following is the code −"
},
{
"code": null,
"e": 2422,
"s": 1871,
"text": "import pandas as pd\n\n# Create DataFrame\ndataFrame = pd.DataFrame(\n {\n \"Car\": ['BMW', 'Lexus', 'BMW', 'Mustang', 'Mercedes', 'Lexus'],\"Reg_Price\": [7000, 1500, 5000, 8000, 9000, 2000],\"Place\": ['Pune', 'Delhi', 'Mumbai', 'Hyderabad', 'Bangalore', 'Chandigarh']\n }\n)\n\nprint\"DataFrame ...\\n\",dataFrame\n\n# Sort DataFrame in descending order according to the element frequency\ndataFrame = dataFrame.groupby(['Car'])['Reg_Price'].count().reset_index(name='Count').sort_values(['Count'], ascending=False)\n\nprint\"\\nSorting DataFrame ...\\n\",dataFrame"
},
{
"code": null,
"e": 2463,
"s": 2422,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2845,
"s": 2463,
"text": "DataFrame ...\n Car Place Reg_Price\n0 BMW Pune 7000\n1 Lexus Delhi 1500\n2 BMW Mumbai 5000\n3 Mustang Hyderabad 8000\n4 Mercedes Bangalore 9000\n5 Lexus Chandigarh 2000\n\nSorting DataFrame ...\n Car Count\n0 BMW 2\n1 Lexus 2\n2 Mercedes 1\n3 Mustang 1"
}
] |
How to pass arguments to animation.FuncAnimation() in Matplotlib?
|
To pass arguments to animation.FuncAnimation() for a contour plot in Matplotlib in Python, we can take the following steps −
Create a random data of 10☓10 dimension.
Create a figure and a set of subplots using subplots() method.
Make an animation by repeatedly calling a function *func* using FuncAnimation() class
To update the contour value in the function, we can define a method animate() that can be used in FuncAnimation() class.
To display the figure, use show() method.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
data = np.random.randn(800).reshape(10, 10, 8)
fig, ax = plt.subplots()
def animate(i):
ax.clear()
ax.contourf(data[:, :, i])
ani = animation.FuncAnimation(fig, animate, 5, interval=50, blit=False)
plt.show()
|
[
{
"code": null,
"e": 1187,
"s": 1062,
"text": "To pass arguments to animation.FuncAnimation() for a contour plot in Matplotlib in Python, we can take the following steps −"
},
{
"code": null,
"e": 1228,
"s": 1187,
"text": "Create a random data of 10☓10 dimension."
},
{
"code": null,
"e": 1291,
"s": 1228,
"text": "Create a figure and a set of subplots using subplots() method."
},
{
"code": null,
"e": 1377,
"s": 1291,
"text": "Make an animation by repeatedly calling a function *func* using FuncAnimation() class"
},
{
"code": null,
"e": 1498,
"s": 1377,
"text": "To update the contour value in the function, we can define a method animate() that can be used in FuncAnimation() class."
},
{
"code": null,
"e": 1540,
"s": 1498,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 1939,
"s": 1540,
"text": "import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\n\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\ndata = np.random.randn(800).reshape(10, 10, 8)\nfig, ax = plt.subplots()\n\ndef animate(i):\n ax.clear()\n ax.contourf(data[:, :, i])\n\nani = animation.FuncAnimation(fig, animate, 5, interval=50, blit=False)\n\nplt.show()"
}
] |
Lucene - First Application
|
In this chapter, we will learn the actual programming with Lucene Framework. Before you start writing your first example using Lucene framework, you have to make sure that you have set up your Lucene environment properly as explained in Lucene - Environment Setup tutorial. It is recommended you have the working knowledge of Eclipse IDE.
Let us now proceed by writing a simple Search Application which will print the number of search results found. We'll also see the list of indexes created during this process.
The first step is to create a simple Java Project using Eclipse IDE. Follow the option File > New -> Project and finally select Java Project wizard from the wizard list. Now name your project as LuceneFirstApplication using the wizard window as follows −
Once your project is created successfully, you will have following content in your Project Explorer −
Let us now add Lucene core Framework library in our project. To do this, right click on your project name LuceneFirstApplication and then follow the following option available in context menu: Build Path -> Configure Build Path to display the Java Build Path window as follows −
Now use Add External JARs button available under Libraries tab to add the following core JAR from the Lucene installation directory −
lucene-core-3.6.2
Let us now create actual source files under the LuceneFirstApplication project. First we need to create a package called com.tutorialspoint.lucene. To do this, right-click on src in package explorer section and follow the option : New -> Package.
Next we will create LuceneTester.java and other java classes under the com.tutorialspoint.lucene package.
This class is used to provide various constants to be used across the sample application.
package com.tutorialspoint.lucene;
public class LuceneConstants {
public static final String CONTENTS = "contents";
public static final String FILE_NAME = "filename";
public static final String FILE_PATH = "filepath";
public static final int MAX_SEARCH = 10;
}
This class is used as a .txt file filter.
package com.tutorialspoint.lucene;
import java.io.File;
import java.io.FileFilter;
public class TextFileFilter implements FileFilter {
@Override
public boolean accept(File pathname) {
return pathname.getName().toLowerCase().endsWith(".txt");
}
}
This class is used to index the raw data so that we can make it searchable using the Lucene library.
package com.tutorialspoint.lucene;
import java.io.File;
import java.io.FileFilter;
import java.io.FileReader;
import java.io.IOException;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
public class Indexer {
private IndexWriter writer;
public Indexer(String indexDirectoryPath) throws IOException {
//this directory will contain the indexes
Directory indexDirectory =
FSDirectory.open(new File(indexDirectoryPath));
//create the indexer
writer = new IndexWriter(indexDirectory,
new StandardAnalyzer(Version.LUCENE_36),true,
IndexWriter.MaxFieldLength.UNLIMITED);
}
public void close() throws CorruptIndexException, IOException {
writer.close();
}
private Document getDocument(File file) throws IOException {
Document document = new Document();
//index file contents
Field contentField = new Field(LuceneConstants.CONTENTS, new FileReader(file));
//index file name
Field fileNameField = new Field(LuceneConstants.FILE_NAME,
file.getName(),Field.Store.YES,Field.Index.NOT_ANALYZED);
//index file path
Field filePathField = new Field(LuceneConstants.FILE_PATH,
file.getCanonicalPath(),Field.Store.YES,Field.Index.NOT_ANALYZED);
document.add(contentField);
document.add(fileNameField);
document.add(filePathField);
return document;
}
private void indexFile(File file) throws IOException {
System.out.println("Indexing "+file.getCanonicalPath());
Document document = getDocument(file);
writer.addDocument(document);
}
public int createIndex(String dataDirPath, FileFilter filter)
throws IOException {
//get all files in the data directory
File[] files = new File(dataDirPath).listFiles();
for (File file : files) {
if(!file.isDirectory()
&& !file.isHidden()
&& file.exists()
&& file.canRead()
&& filter.accept(file)
){
indexFile(file);
}
}
return writer.numDocs();
}
}
This class is used to search the indexes created by the Indexer to search the requested content.
package com.tutorialspoint.lucene;
import java.io.File;
import java.io.IOException;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
public class Searcher {
IndexSearcher indexSearcher;
QueryParser queryParser;
Query query;
public Searcher(String indexDirectoryPath)
throws IOException {
Directory indexDirectory =
FSDirectory.open(new File(indexDirectoryPath));
indexSearcher = new IndexSearcher(indexDirectory);
queryParser = new QueryParser(Version.LUCENE_36,
LuceneConstants.CONTENTS,
new StandardAnalyzer(Version.LUCENE_36));
}
public TopDocs search( String searchQuery)
throws IOException, ParseException {
query = queryParser.parse(searchQuery);
return indexSearcher.search(query, LuceneConstants.MAX_SEARCH);
}
public Document getDocument(ScoreDoc scoreDoc)
throws CorruptIndexException, IOException {
return indexSearcher.doc(scoreDoc.doc);
}
public void close() throws IOException {
indexSearcher.close();
}
}
This class is used to test the indexing and search capability of lucene library.
package com.tutorialspoint.lucene;
import java.io.IOException;
import org.apache.lucene.document.Document;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
public class LuceneTester {
String indexDir = "E:\\Lucene\\Index";
String dataDir = "E:\\Lucene\\Data";
Indexer indexer;
Searcher searcher;
public static void main(String[] args) {
LuceneTester tester;
try {
tester = new LuceneTester();
tester.createIndex();
tester.search("Mohan");
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
private void createIndex() throws IOException {
indexer = new Indexer(indexDir);
int numIndexed;
long startTime = System.currentTimeMillis();
numIndexed = indexer.createIndex(dataDir, new TextFileFilter());
long endTime = System.currentTimeMillis();
indexer.close();
System.out.println(numIndexed+" File indexed, time taken: "
+(endTime-startTime)+" ms");
}
private void search(String searchQuery) throws IOException, ParseException {
searcher = new Searcher(indexDir);
long startTime = System.currentTimeMillis();
TopDocs hits = searcher.search(searchQuery);
long endTime = System.currentTimeMillis();
System.out.println(hits.totalHits +
" documents found. Time :" + (endTime - startTime));
for(ScoreDoc scoreDoc : hits.scoreDocs) {
Document doc = searcher.getDocument(scoreDoc);
System.out.println("File: "
+ doc.get(LuceneConstants.FILE_PATH));
}
searcher.close();
}
}
We have used 10 text files from record1.txt to record10.txt containing names and other details of the students and put them in the directory E:\Lucene\Data. Test Data. An index directory path should be created as E:\Lucene\Index. After running this program, you can see the list of index files created in that folder.
Once you are done with the creation of the source, the raw data, the data directory and the index directory, you are ready for compiling and running of your program. To do this, keep the LuceneTester.Java file tab active and use either the Run option available in the Eclipse IDE or use Ctrl + F11 to compile and run your LuceneTester application. If the application runs successfully, it will print the following message in Eclipse IDE's console −
Indexing E:\Lucene\Data\record1.txt
Indexing E:\Lucene\Data\record10.txt
Indexing E:\Lucene\Data\record2.txt
Indexing E:\Lucene\Data\record3.txt
Indexing E:\Lucene\Data\record4.txt
Indexing E:\Lucene\Data\record5.txt
Indexing E:\Lucene\Data\record6.txt
Indexing E:\Lucene\Data\record7.txt
Indexing E:\Lucene\Data\record8.txt
Indexing E:\Lucene\Data\record9.txt
10 File indexed, time taken: 109 ms
1 documents found. Time :0
File: E:\Lucene\Data\record4.txt
Once you've run the program successfully, you will have the following content in your index directory −
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2182,
"s": 1843,
"text": "In this chapter, we will learn the actual programming with Lucene Framework. Before you start writing your first example using Lucene framework, you have to make sure that you have set up your Lucene environment properly as explained in Lucene - Environment Setup tutorial. It is recommended you have the working knowledge of Eclipse IDE."
},
{
"code": null,
"e": 2357,
"s": 2182,
"text": "Let us now proceed by writing a simple Search Application which will print the number of search results found. We'll also see the list of indexes created during this process."
},
{
"code": null,
"e": 2612,
"s": 2357,
"text": "The first step is to create a simple Java Project using Eclipse IDE. Follow the option File > New -> Project and finally select Java Project wizard from the wizard list. Now name your project as LuceneFirstApplication using the wizard window as follows −"
},
{
"code": null,
"e": 2714,
"s": 2612,
"text": "Once your project is created successfully, you will have following content in your Project Explorer −"
},
{
"code": null,
"e": 2993,
"s": 2714,
"text": "Let us now add Lucene core Framework library in our project. To do this, right click on your project name LuceneFirstApplication and then follow the following option available in context menu: Build Path -> Configure Build Path to display the Java Build Path window as follows −"
},
{
"code": null,
"e": 3127,
"s": 2993,
"text": "Now use Add External JARs button available under Libraries tab to add the following core JAR from the Lucene installation directory −"
},
{
"code": null,
"e": 3145,
"s": 3127,
"text": "lucene-core-3.6.2"
},
{
"code": null,
"e": 3392,
"s": 3145,
"text": "Let us now create actual source files under the LuceneFirstApplication project. First we need to create a package called com.tutorialspoint.lucene. To do this, right-click on src in package explorer section and follow the option : New -> Package."
},
{
"code": null,
"e": 3498,
"s": 3392,
"text": "Next we will create LuceneTester.java and other java classes under the com.tutorialspoint.lucene package."
},
{
"code": null,
"e": 3588,
"s": 3498,
"text": "This class is used to provide various constants to be used across the sample application."
},
{
"code": null,
"e": 3862,
"s": 3588,
"text": "package com.tutorialspoint.lucene;\n\npublic class LuceneConstants {\n public static final String CONTENTS = \"contents\";\n public static final String FILE_NAME = \"filename\";\n public static final String FILE_PATH = \"filepath\";\n public static final int MAX_SEARCH = 10;\n}"
},
{
"code": null,
"e": 3904,
"s": 3862,
"text": "This class is used as a .txt file filter."
},
{
"code": null,
"e": 4168,
"s": 3904,
"text": "package com.tutorialspoint.lucene;\n\nimport java.io.File;\nimport java.io.FileFilter;\n\npublic class TextFileFilter implements FileFilter {\n\n @Override\n public boolean accept(File pathname) {\n return pathname.getName().toLowerCase().endsWith(\".txt\");\n }\n}"
},
{
"code": null,
"e": 4269,
"s": 4168,
"text": "This class is used to index the raw data so that we can make it searchable using the Lucene library."
},
{
"code": null,
"e": 6691,
"s": 4269,
"text": "package com.tutorialspoint.lucene;\n\nimport java.io.File;\nimport java.io.FileFilter;\nimport java.io.FileReader;\nimport java.io.IOException;\n\nimport org.apache.lucene.analysis.standard.StandardAnalyzer;\nimport org.apache.lucene.document.Document;\nimport org.apache.lucene.document.Field;\nimport org.apache.lucene.index.CorruptIndexException;\nimport org.apache.lucene.index.IndexWriter;\nimport org.apache.lucene.store.Directory;\nimport org.apache.lucene.store.FSDirectory;\nimport org.apache.lucene.util.Version;\n\npublic class Indexer {\n\n private IndexWriter writer;\n\n public Indexer(String indexDirectoryPath) throws IOException {\n //this directory will contain the indexes\n Directory indexDirectory = \n FSDirectory.open(new File(indexDirectoryPath));\n\n //create the indexer\n writer = new IndexWriter(indexDirectory, \n new StandardAnalyzer(Version.LUCENE_36),true, \n IndexWriter.MaxFieldLength.UNLIMITED);\n }\n\n public void close() throws CorruptIndexException, IOException {\n writer.close();\n }\n\n private Document getDocument(File file) throws IOException {\n Document document = new Document();\n\n //index file contents\n Field contentField = new Field(LuceneConstants.CONTENTS, new FileReader(file));\n //index file name\n Field fileNameField = new Field(LuceneConstants.FILE_NAME,\n file.getName(),Field.Store.YES,Field.Index.NOT_ANALYZED);\n //index file path\n Field filePathField = new Field(LuceneConstants.FILE_PATH,\n file.getCanonicalPath(),Field.Store.YES,Field.Index.NOT_ANALYZED);\n\n document.add(contentField);\n document.add(fileNameField);\n document.add(filePathField);\n\n return document;\n } \n\n private void indexFile(File file) throws IOException {\n System.out.println(\"Indexing \"+file.getCanonicalPath());\n Document document = getDocument(file);\n writer.addDocument(document);\n }\n\n public int createIndex(String dataDirPath, FileFilter filter) \n throws IOException {\n //get all files in the data directory\n File[] files = new File(dataDirPath).listFiles();\n\n for (File file : files) {\n if(!file.isDirectory()\n && !file.isHidden()\n && file.exists()\n && file.canRead()\n && filter.accept(file)\n ){\n indexFile(file);\n }\n }\n return writer.numDocs();\n }\n}"
},
{
"code": null,
"e": 6788,
"s": 6691,
"text": "This class is used to search the indexes created by the Indexer to search the requested content."
},
{
"code": null,
"e": 8355,
"s": 6788,
"text": "package com.tutorialspoint.lucene;\n\nimport java.io.File;\nimport java.io.IOException;\n\nimport org.apache.lucene.analysis.standard.StandardAnalyzer;\nimport org.apache.lucene.document.Document;\nimport org.apache.lucene.index.CorruptIndexException;\nimport org.apache.lucene.queryParser.ParseException;\nimport org.apache.lucene.queryParser.QueryParser;\nimport org.apache.lucene.search.IndexSearcher;\nimport org.apache.lucene.search.Query;\nimport org.apache.lucene.search.ScoreDoc;\nimport org.apache.lucene.search.TopDocs;\nimport org.apache.lucene.store.Directory;\nimport org.apache.lucene.store.FSDirectory;\nimport org.apache.lucene.util.Version;\n\npublic class Searcher {\n\t\n IndexSearcher indexSearcher;\n QueryParser queryParser;\n Query query;\n \n public Searcher(String indexDirectoryPath) \n throws IOException {\n Directory indexDirectory = \n FSDirectory.open(new File(indexDirectoryPath));\n indexSearcher = new IndexSearcher(indexDirectory);\n queryParser = new QueryParser(Version.LUCENE_36,\n LuceneConstants.CONTENTS,\n new StandardAnalyzer(Version.LUCENE_36));\n }\n \n public TopDocs search( String searchQuery) \n throws IOException, ParseException {\n query = queryParser.parse(searchQuery);\n return indexSearcher.search(query, LuceneConstants.MAX_SEARCH);\n }\n\n public Document getDocument(ScoreDoc scoreDoc) \n throws CorruptIndexException, IOException {\n return indexSearcher.doc(scoreDoc.doc);\t\n }\n\n public void close() throws IOException {\n indexSearcher.close();\n }\n}"
},
{
"code": null,
"e": 8436,
"s": 8355,
"text": "This class is used to test the indexing and search capability of lucene library."
},
{
"code": null,
"e": 10196,
"s": 8436,
"text": "package com.tutorialspoint.lucene;\n\nimport java.io.IOException;\n\nimport org.apache.lucene.document.Document;\nimport org.apache.lucene.queryParser.ParseException;\nimport org.apache.lucene.search.ScoreDoc;\nimport org.apache.lucene.search.TopDocs;\n\npublic class LuceneTester {\n\t\n String indexDir = \"E:\\\\Lucene\\\\Index\";\n String dataDir = \"E:\\\\Lucene\\\\Data\";\n Indexer indexer;\n Searcher searcher;\n\n public static void main(String[] args) {\n LuceneTester tester;\n try {\n tester = new LuceneTester();\n tester.createIndex();\n tester.search(\"Mohan\");\n } catch (IOException e) {\n e.printStackTrace();\n } catch (ParseException e) {\n e.printStackTrace();\n }\n }\n\n private void createIndex() throws IOException {\n indexer = new Indexer(indexDir);\n int numIndexed;\n long startTime = System.currentTimeMillis();\t\n numIndexed = indexer.createIndex(dataDir, new TextFileFilter());\n long endTime = System.currentTimeMillis();\n indexer.close();\n System.out.println(numIndexed+\" File indexed, time taken: \"\n +(endTime-startTime)+\" ms\");\t\t\n }\n\n private void search(String searchQuery) throws IOException, ParseException {\n searcher = new Searcher(indexDir);\n long startTime = System.currentTimeMillis();\n TopDocs hits = searcher.search(searchQuery);\n long endTime = System.currentTimeMillis();\n \n System.out.println(hits.totalHits +\n \" documents found. Time :\" + (endTime - startTime));\n for(ScoreDoc scoreDoc : hits.scoreDocs) {\n Document doc = searcher.getDocument(scoreDoc);\n System.out.println(\"File: \"\n + doc.get(LuceneConstants.FILE_PATH));\n }\n searcher.close();\n }\n}"
},
{
"code": null,
"e": 10514,
"s": 10196,
"text": "We have used 10 text files from record1.txt to record10.txt containing names and other details of the students and put them in the directory E:\\Lucene\\Data. Test Data. An index directory path should be created as E:\\Lucene\\Index. After running this program, you can see the list of index files created in that folder."
},
{
"code": null,
"e": 10963,
"s": 10514,
"text": "Once you are done with the creation of the source, the raw data, the data directory and the index directory, you are ready for compiling and running of your program. To do this, keep the LuceneTester.Java file tab active and use either the Run option available in the Eclipse IDE or use Ctrl + F11 to compile and run your LuceneTester application. If the application runs successfully, it will print the following message in Eclipse IDE's console −"
},
{
"code": null,
"e": 11421,
"s": 10963,
"text": "Indexing E:\\Lucene\\Data\\record1.txt\nIndexing E:\\Lucene\\Data\\record10.txt\nIndexing E:\\Lucene\\Data\\record2.txt\nIndexing E:\\Lucene\\Data\\record3.txt\nIndexing E:\\Lucene\\Data\\record4.txt\nIndexing E:\\Lucene\\Data\\record5.txt\nIndexing E:\\Lucene\\Data\\record6.txt\nIndexing E:\\Lucene\\Data\\record7.txt\nIndexing E:\\Lucene\\Data\\record8.txt\nIndexing E:\\Lucene\\Data\\record9.txt\n10 File indexed, time taken: 109 ms\n1 documents found. Time :0\nFile: E:\\Lucene\\Data\\record4.txt\n"
},
{
"code": null,
"e": 11525,
"s": 11421,
"text": "Once you've run the program successfully, you will have the following content in your index directory −"
},
{
"code": null,
"e": 11532,
"s": 11525,
"text": " Print"
},
{
"code": null,
"e": 11543,
"s": 11532,
"text": " Add Notes"
}
] |
Deep Learning for Computer Vision | by Rachit Tayal | Towards Data Science
|
Deep learning in computer vision has made rapid progress over a short period. Some of the applications where deep learning is used in computer vision include face recognition systems, self-driving cars, etc.
This article introduces convolutional neural networks, also known as convnets, a type of deep-learning model universally used in computer vision applications. We’ll be deep-diving into understanding its components, layers like convolutional layer, pooling layers, and fully connected layers and how they can be applied to solve various problems.
So let’s get started.
Above is an image of a cat, as a kid we are told that this animal is a cat. As we grow up learning and seeing more images of cats, our brain registers the various features of it like the shape of eyes, ears, facial structure, whiskers, etc. and next time we see an image of an animal possessing those features, we’re able to predict it as a cat because that is something we’ve learned with experience.
Now we need to emulate the same behavior to computers. Such a class of problem is known as an image classification problem in computer vision, where we try to identify the object present in the image.
Given an image, first computers should be able to extract its features and then based on those features, predict as to what that object is. How can they achieve that? Well, the short answer is by using CNNs. How they do it is something we’ll deep dive into.
So the objective of CNN is to perform 2 tasks: first is feature extraction and second is aggregating all the extracted features and making a prediction based on it.
Before we deep dive into individual components, let’s see how CNN looks like.
From the above image, we can see three types of layers namely: Convolutional Layer, Pooling Layer, and Fully Connected Layer. (We’ll be discussing these in following sections)
It’s totally fine if the above image does not make complete sense. The reason we’re seeing this is to have a mental image of how CNN looks like so that it becomes easy for us to connect the dots once we’re done understanding its various layers.
Convolution is one of the fundamental building blocks of CNNs. The prime objective of the convolutional operation is to extract features like edges, curves, corners, gradient orientation, etc from the input image. We’ll understand the convolution operation with an edge detection example.
Given an image and we want to extract all the horizontal and vertical edges in that image. The below image depicts the same.
Consider we have a grayscale image of 6x6. Now to detect edges in that image, we construct a 3x3 matrix. In CNN terminology it’s called a filter or a kernel. Using these two matrices, we’ll perform the convolutional operation. The resultant matrix i.e. the output of the convolution operation will be a matrix of size 4x4. The below figure depicts the same.
Now, how we compute the elements of the resulting 4x4 matrix is as follows:To compute the top-left element, we are going to take the 3x3 filter and paste it on top of the 3x3 region of the original input image. Next, we’ll do the element-wise product to give us the desired value.
Next, to figure out the second element, we’re gonna take the filter i.e. the yellow square and shift it one step to the right and do the same element-wise product and then add them together. Similarly we can fill all the elements of that row.
Now to get the element in the next row, we’ll shift the filter one down to the next row and repeat the same element-wise product and adding them together. Therefore we can fill in the rest of the elements likewise. Below shows us the final result.
A couple of points here. A 6x6 matrix when convolved using a 3x3 matrix gives us a 4x4 matrix. These are essentially matrices. But the matrix on the left is convenient to interpret as the input image, one in the middle to interpret as a filter and one on the right to interpret as output feature.
The output feature dimension is calculated as follows:
n x n input image f x f filteroutput dimension = (n - f + 1)Above example: 6 x 6 input image 3 x 3 filter (6 - 3 + 1) x (6 - 3 + 1)output dimensions = 4 x 4
NOTE: The values of our filters are often called weights. How we are deciding the values of weights is something learned during the training. They are initialized with some random values and keep adjusting with every training step.
Every time we perform convolution operation, we are losing some of the information present in the border pixels. Also, our image shrinks a little in size. There are times when we would want to reduce the output size to save resource consumption during training. However, there might be times when we would want to keep the spatial dimensions of output and input the same. To accomplish that, we can use the concept of padding.
Padding is nothing but adding an appropriate number of rows and columns on each side of the input feature. Padding essentially makes the feature maps produced by the filters the same size as the original image.
In the figure (left), a blue square of dimensions 5x5 represents our input image, which has been padded by adding rows of zeros on each side. when convolved using a 3x3 filter, the output dimensions are the same as that of input i.e 5x5 as depicted by a green square. Had we not used the padding, output dimensions would have been 3x3. Therefore padding of 1 kept the spatial dimensions of input and output the same.
Let’s understand the terminologies based on whether padding is being added or not.
Valid: When no padding is added during convolution and our resultant output is of shrunk size. Example:
Input size: 6 x 6 (i x i)Filter size: 3 x 3 (f x f)Output size: (i – f + 1) (6 – 3 + 1) = 4 = 4 x 4
Same: When padding is added such that output size is the same as input size. To calculate the output dimension, our above formula is modified to factor in the padding parameter. Example:
Input size: 6 x 6 (i x i)Filter size: 3 x 3 (f x f)Padding: 1 (p)Output size: (i + 2p - f +1) (6 + 2x1 – 3 + 1) = 6 = 6 x 6
NOTE: By convention filter size f, is usually odd else padding will be asymmetric. Some of the most common filter sizes used are 3x3, 5x5, and 1x1.
In our working example, to calculate the next element we were shifting the filter by one to the right. The number of rows we’re moving our filter over the input image is our stride parameter.
The stride defines the step size of the filter when traversing the image. By default it’s probably 1 in any framework.
In the figure (left), a blue square of 5x5 represents our input image. When convolved using a 3x3 filter, with a stride value of 2, we got a downsampled output map with dimensions 2x2. Had we kept stride of 1, the output dimensions would have been 3x3.
Therefore, we can increase the stride(step) length to save space or cut calculation time during training. However, we’ll be foregoing some information when doing so, hence it’s a trade-off between resource consumption (be it CPU or memory) and information retrieval from the input.
NOTE: In general we usually keep the stride value to 1 and use other ways to downsample our feature map like using the pooling layer.
The prime objective of the convolutional operation is to extract meaningful information from input image like edges, curves, etc. Below animation summaries how elements are calculated in a convolutional operation.
The below equation summarises dimensions for the output feature map.
Examples using the above equation:
6x6 input image, 3x3 filter | 7x7 input image, 3x3 filterpadding p=1 & stride, s=1 | padding p=1 & stride, s=2 | |Output size: | Output size:(6 + 2*1 – 3)/1 + 1 = 6 | (7 + 2*1 - 3)/2 = 46 x 6 | 4 x 4
We have done convolution over matrices. Let’s now understand how to perform the convolution operation over volumes which will make it much more powerful. Previously we had a grayscale image of 6x6. Now let’s consider we have a 6x6 RGB image, so it’ll have dimensions 6x6x3 and instead of having a 3x3 filter, this time we’ll have 3x3x3 filters.
The output will still be a size of 4x4 (same as before), however, elements will be calculated by doing the element-wise product in each channel and adding them together as depicted below:
One point to note here is that the number of channels in the input and filter has to be equal. Why we are doing this is because it allows us to use different filters across channels like having an edge detector in all channels, to extract more meaningful information. So the idea is the same. Get as much information in our output feature map as we can.
NOTE: The number of channels in the filter is usually not specified explicitly. It is assumed to be equal to the depth of input. For example, if we have an input of dimensions 26x26x64 and we are convolving using a filter of size 3x3, it is implicit that the number of channels in our filter will be 64, hence its actual dimensions are 3x3x64.
Now we know how to convolve over volumes, so how about the idea that we increase the number of filters. Each filter extract some features like one is extracting the vertical edges the other horizontal or lines at 45 degrees etc. In other words, extending the convolution to use multiple filters.
Expanding our working example, we still have an input of 6x6x3. Now instead of one, we have two filters of dimensions 3x3 (depth of 3 is implicit). The convolution operation is performed in a similar fashion using each filter. Therefore, we’ll get two 4x4 output feature maps. On stacking one on top of another, we can say the output dimensions be 4x4x2 as depicted below:
So we can detect multiple features now based on our number of filters. The true power of convolution is unleashed since now we can extract a lot of semantic information from our input.
Let’s consider an example to understand the number of values (weights) present in multiple filters:
Input Volume dimensions: 26x26x64 filter Size: 3x3(since input depth=64, filter depth will also be 64)and we have 32 such filters being used for feature extractionHence, total number of weights in our filter will be: weights in one filter = 3 x 3 x 64 = 576 Total filters = 32 Total weights = 32 x 576 = 18,432
This is all about the convolutional operation. Let’s now see how a typical convolution layer in a CNN looks like:
In the above example, we got two 4x4 output maps. Now for each of these output maps we are going to add a bias. Bias is a real number and we add it to all our 16 elements of each feature map. Bias is like the intercept added in a linear equation to model the real-world scenario. Then we’ll add non-linearity by applying an activation function.
A neural network without an activation function would simply be a linear regression model, which has limited power and does not work well most of the time. Without activation function our neural network would not be able to learn and model complicated kinds of data such as images, videos, etc.
There are multiple candidates for activation functions, most popular is the ReLU activation function.
ReLU function if sees a positive integer, will return the same number and when sees a negative number, it will return zero.
It rectifies the vanishing gradient problem. Also it is 6 times better in convergence from the tanh activation function. (More about activation functions will be covered in another post).
Below figure depicts and bias addition and applying ReLU activation to our example:
This entire computation where we went from 6x6x3 to 4x4x2 output maps is one convolution layer in CNNs. The objective of the Convolution Operation is to extract the high-level features such as edges, from the input image. Convnets need not be limited to only a single convolutional layer.
Conventionally, the first convolutional layer is responsible for capturing low-level features such as edges, color, gradient orientation, etc. With added layers, the architecture adapts to the high-level features as well, giving us a network that has the wholesome understanding of images in the dataset, similar to how we would.
Other than convolutional layers, convnets also use Pooling layers to reduce the size of our representation to speed up computation. Pooling is responsible for reducing the spatial size of the Convolved Feature and hence decrease the computational power required to process the data.
How the operation works is as follows:
In the figure (left), a 2x2 window is traversed over input image with stride 2 and the maximum value is retained in each quadrant. This is called the Max Pooling operation.
The most common form is a pooling layer with filters of size 2x2 applied with a stride of 2 downsamples every depth slice in the input by 2 along both width and height. The intuition is if there is a feature present in any quadrant, pooling will try to retain that feature by maintaining the high number with which the activation function will fire up
Pooling reduces the number of feature map coefficients to process and induce network to learn spatial hierarchies of features i.e. making successive convolution layers look at increasingly large windows in terms of the fraction of the original input they cover.
There are two types of Pooling: Max and Average Pooling. Max Pooling returns the maximum value from the portion of the image covered by the filter. Average Pooling returns the average of all the values from the portion of the image covered by the Kernel.
NOTE: There are no parameters to learn during training in the pooling layer. Pooling sizes with larger receptive fields are too destructive.
The objective of a fully connected layer is to take the results of the convolution/pooling process and use them to classify the image into a label. These would act as identical to the layers in a traditional deep neural network. The main difference is the inputs would be in the shape and form created by the earlier stages of the CNN (Convolutional and Pooling layers).
Flattening is converting the data into a 1-dimensional array for inputting it to the fully connected layer.
FC input layer takes a flattened vector as input and applies weights and activation to predict the correct label. The FC output layer gives the final probabilities for each label. The difference between both layers is the activation function. ReLU in input while softmax in output. (We’ll be covering that in more depth in a separate post)
CNN primarily has two objectives: Feature extraction and classification.
CNNs have 3 layers namely, convolutional, pooling, and fully connected layers. Each CNN layer learns filters of increasing complexity.
The first layers learn basic feature detection filters: edges, corners, etc
The middle layers learn filters that detect parts of objects. For faces, they might learn to respond to eyes, noses, etc
The last layers have higher representations: they learn to recognize full objects, in different shapes and positions.
To implement a sample CNN, you can follow the guided implementation here.
No rights reserved
by the author.
|
[
{
"code": null,
"e": 380,
"s": 172,
"text": "Deep learning in computer vision has made rapid progress over a short period. Some of the applications where deep learning is used in computer vision include face recognition systems, self-driving cars, etc."
},
{
"code": null,
"e": 726,
"s": 380,
"text": "This article introduces convolutional neural networks, also known as convnets, a type of deep-learning model universally used in computer vision applications. We’ll be deep-diving into understanding its components, layers like convolutional layer, pooling layers, and fully connected layers and how they can be applied to solve various problems."
},
{
"code": null,
"e": 748,
"s": 726,
"text": "So let’s get started."
},
{
"code": null,
"e": 1150,
"s": 748,
"text": "Above is an image of a cat, as a kid we are told that this animal is a cat. As we grow up learning and seeing more images of cats, our brain registers the various features of it like the shape of eyes, ears, facial structure, whiskers, etc. and next time we see an image of an animal possessing those features, we’re able to predict it as a cat because that is something we’ve learned with experience."
},
{
"code": null,
"e": 1351,
"s": 1150,
"text": "Now we need to emulate the same behavior to computers. Such a class of problem is known as an image classification problem in computer vision, where we try to identify the object present in the image."
},
{
"code": null,
"e": 1609,
"s": 1351,
"text": "Given an image, first computers should be able to extract its features and then based on those features, predict as to what that object is. How can they achieve that? Well, the short answer is by using CNNs. How they do it is something we’ll deep dive into."
},
{
"code": null,
"e": 1774,
"s": 1609,
"text": "So the objective of CNN is to perform 2 tasks: first is feature extraction and second is aggregating all the extracted features and making a prediction based on it."
},
{
"code": null,
"e": 1852,
"s": 1774,
"text": "Before we deep dive into individual components, let’s see how CNN looks like."
},
{
"code": null,
"e": 2028,
"s": 1852,
"text": "From the above image, we can see three types of layers namely: Convolutional Layer, Pooling Layer, and Fully Connected Layer. (We’ll be discussing these in following sections)"
},
{
"code": null,
"e": 2273,
"s": 2028,
"text": "It’s totally fine if the above image does not make complete sense. The reason we’re seeing this is to have a mental image of how CNN looks like so that it becomes easy for us to connect the dots once we’re done understanding its various layers."
},
{
"code": null,
"e": 2562,
"s": 2273,
"text": "Convolution is one of the fundamental building blocks of CNNs. The prime objective of the convolutional operation is to extract features like edges, curves, corners, gradient orientation, etc from the input image. We’ll understand the convolution operation with an edge detection example."
},
{
"code": null,
"e": 2687,
"s": 2562,
"text": "Given an image and we want to extract all the horizontal and vertical edges in that image. The below image depicts the same."
},
{
"code": null,
"e": 3045,
"s": 2687,
"text": "Consider we have a grayscale image of 6x6. Now to detect edges in that image, we construct a 3x3 matrix. In CNN terminology it’s called a filter or a kernel. Using these two matrices, we’ll perform the convolutional operation. The resultant matrix i.e. the output of the convolution operation will be a matrix of size 4x4. The below figure depicts the same."
},
{
"code": null,
"e": 3326,
"s": 3045,
"text": "Now, how we compute the elements of the resulting 4x4 matrix is as follows:To compute the top-left element, we are going to take the 3x3 filter and paste it on top of the 3x3 region of the original input image. Next, we’ll do the element-wise product to give us the desired value."
},
{
"code": null,
"e": 3569,
"s": 3326,
"text": "Next, to figure out the second element, we’re gonna take the filter i.e. the yellow square and shift it one step to the right and do the same element-wise product and then add them together. Similarly we can fill all the elements of that row."
},
{
"code": null,
"e": 3817,
"s": 3569,
"text": "Now to get the element in the next row, we’ll shift the filter one down to the next row and repeat the same element-wise product and adding them together. Therefore we can fill in the rest of the elements likewise. Below shows us the final result."
},
{
"code": null,
"e": 4114,
"s": 3817,
"text": "A couple of points here. A 6x6 matrix when convolved using a 3x3 matrix gives us a 4x4 matrix. These are essentially matrices. But the matrix on the left is convenient to interpret as the input image, one in the middle to interpret as a filter and one on the right to interpret as output feature."
},
{
"code": null,
"e": 4169,
"s": 4114,
"text": "The output feature dimension is calculated as follows:"
},
{
"code": null,
"e": 4368,
"s": 4169,
"text": "n x n input image f x f filteroutput dimension = (n - f + 1)Above example: 6 x 6 input image 3 x 3 filter (6 - 3 + 1) x (6 - 3 + 1)output dimensions = 4 x 4"
},
{
"code": null,
"e": 4600,
"s": 4368,
"text": "NOTE: The values of our filters are often called weights. How we are deciding the values of weights is something learned during the training. They are initialized with some random values and keep adjusting with every training step."
},
{
"code": null,
"e": 5027,
"s": 4600,
"text": "Every time we perform convolution operation, we are losing some of the information present in the border pixels. Also, our image shrinks a little in size. There are times when we would want to reduce the output size to save resource consumption during training. However, there might be times when we would want to keep the spatial dimensions of output and input the same. To accomplish that, we can use the concept of padding."
},
{
"code": null,
"e": 5238,
"s": 5027,
"text": "Padding is nothing but adding an appropriate number of rows and columns on each side of the input feature. Padding essentially makes the feature maps produced by the filters the same size as the original image."
},
{
"code": null,
"e": 5655,
"s": 5238,
"text": "In the figure (left), a blue square of dimensions 5x5 represents our input image, which has been padded by adding rows of zeros on each side. when convolved using a 3x3 filter, the output dimensions are the same as that of input i.e 5x5 as depicted by a green square. Had we not used the padding, output dimensions would have been 3x3. Therefore padding of 1 kept the spatial dimensions of input and output the same."
},
{
"code": null,
"e": 5738,
"s": 5655,
"text": "Let’s understand the terminologies based on whether padding is being added or not."
},
{
"code": null,
"e": 5842,
"s": 5738,
"text": "Valid: When no padding is added during convolution and our resultant output is of shrunk size. Example:"
},
{
"code": null,
"e": 5973,
"s": 5842,
"text": "Input size: 6 x 6 (i x i)Filter size: 3 x 3 (f x f)Output size: (i – f + 1) (6 – 3 + 1) = 4 = 4 x 4"
},
{
"code": null,
"e": 6160,
"s": 5973,
"text": "Same: When padding is added such that output size is the same as input size. To calculate the output dimension, our above formula is modified to factor in the padding parameter. Example:"
},
{
"code": null,
"e": 6363,
"s": 6160,
"text": "Input size: 6 x 6 (i x i)Filter size: 3 x 3 (f x f)Padding: 1 (p)Output size: (i + 2p - f +1) (6 + 2x1 – 3 + 1) = 6 = 6 x 6"
},
{
"code": null,
"e": 6511,
"s": 6363,
"text": "NOTE: By convention filter size f, is usually odd else padding will be asymmetric. Some of the most common filter sizes used are 3x3, 5x5, and 1x1."
},
{
"code": null,
"e": 6703,
"s": 6511,
"text": "In our working example, to calculate the next element we were shifting the filter by one to the right. The number of rows we’re moving our filter over the input image is our stride parameter."
},
{
"code": null,
"e": 6822,
"s": 6703,
"text": "The stride defines the step size of the filter when traversing the image. By default it’s probably 1 in any framework."
},
{
"code": null,
"e": 7075,
"s": 6822,
"text": "In the figure (left), a blue square of 5x5 represents our input image. When convolved using a 3x3 filter, with a stride value of 2, we got a downsampled output map with dimensions 2x2. Had we kept stride of 1, the output dimensions would have been 3x3."
},
{
"code": null,
"e": 7357,
"s": 7075,
"text": "Therefore, we can increase the stride(step) length to save space or cut calculation time during training. However, we’ll be foregoing some information when doing so, hence it’s a trade-off between resource consumption (be it CPU or memory) and information retrieval from the input."
},
{
"code": null,
"e": 7491,
"s": 7357,
"text": "NOTE: In general we usually keep the stride value to 1 and use other ways to downsample our feature map like using the pooling layer."
},
{
"code": null,
"e": 7705,
"s": 7491,
"text": "The prime objective of the convolutional operation is to extract meaningful information from input image like edges, curves, etc. Below animation summaries how elements are calculated in a convolutional operation."
},
{
"code": null,
"e": 7774,
"s": 7705,
"text": "The below equation summarises dimensions for the output feature map."
},
{
"code": null,
"e": 7809,
"s": 7774,
"text": "Examples using the above equation:"
},
{
"code": null,
"e": 8151,
"s": 7809,
"text": "6x6 input image, 3x3 filter | 7x7 input image, 3x3 filterpadding p=1 & stride, s=1 | padding p=1 & stride, s=2 | |Output size: | Output size:(6 + 2*1 – 3)/1 + 1 = 6 | (7 + 2*1 - 3)/2 = 46 x 6 | 4 x 4"
},
{
"code": null,
"e": 8496,
"s": 8151,
"text": "We have done convolution over matrices. Let’s now understand how to perform the convolution operation over volumes which will make it much more powerful. Previously we had a grayscale image of 6x6. Now let’s consider we have a 6x6 RGB image, so it’ll have dimensions 6x6x3 and instead of having a 3x3 filter, this time we’ll have 3x3x3 filters."
},
{
"code": null,
"e": 8684,
"s": 8496,
"text": "The output will still be a size of 4x4 (same as before), however, elements will be calculated by doing the element-wise product in each channel and adding them together as depicted below:"
},
{
"code": null,
"e": 9038,
"s": 8684,
"text": "One point to note here is that the number of channels in the input and filter has to be equal. Why we are doing this is because it allows us to use different filters across channels like having an edge detector in all channels, to extract more meaningful information. So the idea is the same. Get as much information in our output feature map as we can."
},
{
"code": null,
"e": 9382,
"s": 9038,
"text": "NOTE: The number of channels in the filter is usually not specified explicitly. It is assumed to be equal to the depth of input. For example, if we have an input of dimensions 26x26x64 and we are convolving using a filter of size 3x3, it is implicit that the number of channels in our filter will be 64, hence its actual dimensions are 3x3x64."
},
{
"code": null,
"e": 9678,
"s": 9382,
"text": "Now we know how to convolve over volumes, so how about the idea that we increase the number of filters. Each filter extract some features like one is extracting the vertical edges the other horizontal or lines at 45 degrees etc. In other words, extending the convolution to use multiple filters."
},
{
"code": null,
"e": 10051,
"s": 9678,
"text": "Expanding our working example, we still have an input of 6x6x3. Now instead of one, we have two filters of dimensions 3x3 (depth of 3 is implicit). The convolution operation is performed in a similar fashion using each filter. Therefore, we’ll get two 4x4 output feature maps. On stacking one on top of another, we can say the output dimensions be 4x4x2 as depicted below:"
},
{
"code": null,
"e": 10236,
"s": 10051,
"text": "So we can detect multiple features now based on our number of filters. The true power of convolution is unleashed since now we can extract a lot of semantic information from our input."
},
{
"code": null,
"e": 10336,
"s": 10236,
"text": "Let’s consider an example to understand the number of values (weights) present in multiple filters:"
},
{
"code": null,
"e": 10655,
"s": 10336,
"text": "Input Volume dimensions: 26x26x64 filter Size: 3x3(since input depth=64, filter depth will also be 64)and we have 32 such filters being used for feature extractionHence, total number of weights in our filter will be: weights in one filter = 3 x 3 x 64 = 576 Total filters = 32 Total weights = 32 x 576 = 18,432"
},
{
"code": null,
"e": 10769,
"s": 10655,
"text": "This is all about the convolutional operation. Let’s now see how a typical convolution layer in a CNN looks like:"
},
{
"code": null,
"e": 11114,
"s": 10769,
"text": "In the above example, we got two 4x4 output maps. Now for each of these output maps we are going to add a bias. Bias is a real number and we add it to all our 16 elements of each feature map. Bias is like the intercept added in a linear equation to model the real-world scenario. Then we’ll add non-linearity by applying an activation function."
},
{
"code": null,
"e": 11409,
"s": 11114,
"text": "A neural network without an activation function would simply be a linear regression model, which has limited power and does not work well most of the time. Without activation function our neural network would not be able to learn and model complicated kinds of data such as images, videos, etc."
},
{
"code": null,
"e": 11511,
"s": 11409,
"text": "There are multiple candidates for activation functions, most popular is the ReLU activation function."
},
{
"code": null,
"e": 11635,
"s": 11511,
"text": "ReLU function if sees a positive integer, will return the same number and when sees a negative number, it will return zero."
},
{
"code": null,
"e": 11823,
"s": 11635,
"text": "It rectifies the vanishing gradient problem. Also it is 6 times better in convergence from the tanh activation function. (More about activation functions will be covered in another post)."
},
{
"code": null,
"e": 11907,
"s": 11823,
"text": "Below figure depicts and bias addition and applying ReLU activation to our example:"
},
{
"code": null,
"e": 12196,
"s": 11907,
"text": "This entire computation where we went from 6x6x3 to 4x4x2 output maps is one convolution layer in CNNs. The objective of the Convolution Operation is to extract the high-level features such as edges, from the input image. Convnets need not be limited to only a single convolutional layer."
},
{
"code": null,
"e": 12526,
"s": 12196,
"text": "Conventionally, the first convolutional layer is responsible for capturing low-level features such as edges, color, gradient orientation, etc. With added layers, the architecture adapts to the high-level features as well, giving us a network that has the wholesome understanding of images in the dataset, similar to how we would."
},
{
"code": null,
"e": 12809,
"s": 12526,
"text": "Other than convolutional layers, convnets also use Pooling layers to reduce the size of our representation to speed up computation. Pooling is responsible for reducing the spatial size of the Convolved Feature and hence decrease the computational power required to process the data."
},
{
"code": null,
"e": 12848,
"s": 12809,
"text": "How the operation works is as follows:"
},
{
"code": null,
"e": 13021,
"s": 12848,
"text": "In the figure (left), a 2x2 window is traversed over input image with stride 2 and the maximum value is retained in each quadrant. This is called the Max Pooling operation."
},
{
"code": null,
"e": 13373,
"s": 13021,
"text": "The most common form is a pooling layer with filters of size 2x2 applied with a stride of 2 downsamples every depth slice in the input by 2 along both width and height. The intuition is if there is a feature present in any quadrant, pooling will try to retain that feature by maintaining the high number with which the activation function will fire up"
},
{
"code": null,
"e": 13635,
"s": 13373,
"text": "Pooling reduces the number of feature map coefficients to process and induce network to learn spatial hierarchies of features i.e. making successive convolution layers look at increasingly large windows in terms of the fraction of the original input they cover."
},
{
"code": null,
"e": 13890,
"s": 13635,
"text": "There are two types of Pooling: Max and Average Pooling. Max Pooling returns the maximum value from the portion of the image covered by the filter. Average Pooling returns the average of all the values from the portion of the image covered by the Kernel."
},
{
"code": null,
"e": 14031,
"s": 13890,
"text": "NOTE: There are no parameters to learn during training in the pooling layer. Pooling sizes with larger receptive fields are too destructive."
},
{
"code": null,
"e": 14402,
"s": 14031,
"text": "The objective of a fully connected layer is to take the results of the convolution/pooling process and use them to classify the image into a label. These would act as identical to the layers in a traditional deep neural network. The main difference is the inputs would be in the shape and form created by the earlier stages of the CNN (Convolutional and Pooling layers)."
},
{
"code": null,
"e": 14510,
"s": 14402,
"text": "Flattening is converting the data into a 1-dimensional array for inputting it to the fully connected layer."
},
{
"code": null,
"e": 14850,
"s": 14510,
"text": "FC input layer takes a flattened vector as input and applies weights and activation to predict the correct label. The FC output layer gives the final probabilities for each label. The difference between both layers is the activation function. ReLU in input while softmax in output. (We’ll be covering that in more depth in a separate post)"
},
{
"code": null,
"e": 14923,
"s": 14850,
"text": "CNN primarily has two objectives: Feature extraction and classification."
},
{
"code": null,
"e": 15058,
"s": 14923,
"text": "CNNs have 3 layers namely, convolutional, pooling, and fully connected layers. Each CNN layer learns filters of increasing complexity."
},
{
"code": null,
"e": 15134,
"s": 15058,
"text": "The first layers learn basic feature detection filters: edges, corners, etc"
},
{
"code": null,
"e": 15255,
"s": 15134,
"text": "The middle layers learn filters that detect parts of objects. For faces, they might learn to respond to eyes, noses, etc"
},
{
"code": null,
"e": 15373,
"s": 15255,
"text": "The last layers have higher representations: they learn to recognize full objects, in different shapes and positions."
},
{
"code": null,
"e": 15447,
"s": 15373,
"text": "To implement a sample CNN, you can follow the guided implementation here."
},
{
"code": null,
"e": 15466,
"s": 15447,
"text": "No rights reserved"
}
] |
ASP.NET Core - Views
|
In an ASP.NET Core MVC application, there is nothing like a page and it also doesn’t include anything that directly corresponds to a page when you specify a path in the URL. The closest thing to a page in an ASP.NET Core MVC application is known as a view.
As you know that in ASP.NET MVC application, all incoming browser requests are handled by the controller and these requests are mapped to the controller actions.
As you know that in ASP.NET MVC application, all incoming browser requests are handled by the controller and these requests are mapped to the controller actions.
A controller action might return a view or it might also perform some other type of action such as redirecting to another controller action.
A controller action might return a view or it might also perform some other type of action such as redirecting to another controller action.
With the MVC framework, the most popular method for creating HTML is to use the Razor view engine of ASP.NET MVC.
With the MVC framework, the most popular method for creating HTML is to use the Razor view engine of ASP.NET MVC.
To use this view engine, a controller action produces a ViewResult object, and a ViewResult can carry the name of the Razor view that we want to use.
To use this view engine, a controller action produces a ViewResult object, and a ViewResult can carry the name of the Razor view that we want to use.
The view will be a file on the file system and the ViewResult can also carry along a model object to the view and the view can use this model object when it creates the HTML.
The view will be a file on the file system and the ViewResult can also carry along a model object to the view and the view can use this model object when it creates the HTML.
When the MVC framework sees that your controller action produces a ViewResult, the framework will find the view on the file system, execute the view, which produces HTML, and it is this HTML which the framework sends back to the client.
When the MVC framework sees that your controller action produces a ViewResult, the framework will find the view on the file system, execute the view, which produces HTML, and it is this HTML which the framework sends back to the client.
Let us now take a simple example to understand how this works in our application by changing the HomeController Index method implementation as shown in the following program.
using FirstAppDemo.Models;
using Microsoft.AspNet.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace FirstAppdemo.Controllers {
public class HomeController : Controller {
public ViewResult Index() {
var employee = new Employee { ID = 1, Name = "Mark Upston"};
return View();
}
}
}
Inside HomeController, instead of producing an ObjectResult, let us just return what the View() method returns. The View method doesn't return an ObjectResult. It creates a new ViewResult, so we will also change the return type of the Index method to ViewResult. The View method does accept some parameters here. We will invoke this method without any other parameter. Let us save your file and refresh your browser.
This is because the MVC framework has to go out and find that view but there is no view right now.
Views by default in a C# ASP.NET project are files that have a *.cshtml extension and the views follow a specific convention. By default, all views live in a Views folder in the project.
Views by default in a C# ASP.NET project are files that have a *.cshtml extension and the views follow a specific convention. By default, all views live in a Views folder in the project.
The view location and the view file name will be derived by ASP.NET MVC if you don't give it any additional information.
The view location and the view file name will be derived by ASP.NET MVC if you don't give it any additional information.
If we need to render a view from the Index action of the HomeController, the first place that the MVC framework will look for that view is inside the Views folder.
If we need to render a view from the Index action of the HomeController, the first place that the MVC framework will look for that view is inside the Views folder.
It will go into a Home folder and then look for a file called Index.cshtml − the file name starts with Index because we are in the Index action.
It will go into a Home folder and then look for a file called Index.cshtml − the file name starts with Index because we are in the Index action.
The MVC framework will also look in a Shared folder and views that you place inside the Shared folder, you can use them anywhere in the application.
The MVC framework will also look in a Shared folder and views that you place inside the Shared folder, you can use them anywhere in the application.
In order for our view result to work properly, let us create this Index.cshtml file in the correct location. So in our project, we first need to add a folder that will contain all of our views and call it Views. Inside the Views folder, we will add another folder for views that are associated with our HomeController and call that folder Home. Right-click on the Home folder and select Add → New Item.
In the left pane, select the MVC View Page and enter index.cshtml in the name field and click on the Add button.
Let us add the following code in the index.cshtml file.
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>Home</title>
</head>
<body>
<h1>Welcome!</h1>
<div>
This message is from the View...
</div>
</body>
</html>
You can now see a *.cshtml file. It can contain HTML markup and any markup that we have in this file will be sent directly to the client. Save this file and refresh your browser.
Now the Home controller via a ViewResult has rendered this view to the client and all of the markup that is in that index.cshtml file, that is what was sent to the client.
Let us go back to the HomeController and the View method. This View method has a couple of different overloads, and pass the employee model as parameter.
using FirstAppDemo.Models;
using Microsoft.AspNet.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace FirstAppdemo.Controllers {
public class HomeController : Controller {
public ViewResult Index() {
var employee = new Employee { ID = 1, Name = "Mark Upston"};
return View(employee);
}
}
}
The View method that just takes a model object and that will use the default view, which is Index. Here we just want to pass in that model information and use that model inside Index.cshtml as shown in the following program.
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>Home</title>
</head>
<body>
<h1>Welcome!</h1>
<div>
@Model.Name
</div>
</body>
</html>
When we use the @ sign in a Razor view, then the Razor view engine is going to treat whatever you type as a C# expression. Razor view contains some built-in members that we can access inside the C# expressions. One of the most important members is the Model. When you say @Model, then you will get the model object that you have passed into the view from the controller. So here the @Model.Name will display the employee name inside the view.
Let us now save all the files. After this, refresh your browser to see the following output.
You can now see the employee name as in the above screenshot.
51 Lectures
5.5 hours
Anadi Sharma
44 Lectures
4.5 hours
Kaushik Roy Chowdhury
42 Lectures
18 hours
SHIVPRASAD KOIRALA
57 Lectures
3.5 hours
University Code
40 Lectures
2.5 hours
University Code
138 Lectures
9 hours
Bhrugen Patel
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2718,
"s": 2461,
"text": "In an ASP.NET Core MVC application, there is nothing like a page and it also doesn’t include anything that directly corresponds to a page when you specify a path in the URL. The closest thing to a page in an ASP.NET Core MVC application is known as a view."
},
{
"code": null,
"e": 2880,
"s": 2718,
"text": "As you know that in ASP.NET MVC application, all incoming browser requests are handled by the controller and these requests are mapped to the controller actions."
},
{
"code": null,
"e": 3042,
"s": 2880,
"text": "As you know that in ASP.NET MVC application, all incoming browser requests are handled by the controller and these requests are mapped to the controller actions."
},
{
"code": null,
"e": 3183,
"s": 3042,
"text": "A controller action might return a view or it might also perform some other type of action such as redirecting to another controller action."
},
{
"code": null,
"e": 3324,
"s": 3183,
"text": "A controller action might return a view or it might also perform some other type of action such as redirecting to another controller action."
},
{
"code": null,
"e": 3438,
"s": 3324,
"text": "With the MVC framework, the most popular method for creating HTML is to use the Razor view engine of ASP.NET MVC."
},
{
"code": null,
"e": 3552,
"s": 3438,
"text": "With the MVC framework, the most popular method for creating HTML is to use the Razor view engine of ASP.NET MVC."
},
{
"code": null,
"e": 3702,
"s": 3552,
"text": "To use this view engine, a controller action produces a ViewResult object, and a ViewResult can carry the name of the Razor view that we want to use."
},
{
"code": null,
"e": 3852,
"s": 3702,
"text": "To use this view engine, a controller action produces a ViewResult object, and a ViewResult can carry the name of the Razor view that we want to use."
},
{
"code": null,
"e": 4027,
"s": 3852,
"text": "The view will be a file on the file system and the ViewResult can also carry along a model object to the view and the view can use this model object when it creates the HTML."
},
{
"code": null,
"e": 4202,
"s": 4027,
"text": "The view will be a file on the file system and the ViewResult can also carry along a model object to the view and the view can use this model object when it creates the HTML."
},
{
"code": null,
"e": 4439,
"s": 4202,
"text": "When the MVC framework sees that your controller action produces a ViewResult, the framework will find the view on the file system, execute the view, which produces HTML, and it is this HTML which the framework sends back to the client."
},
{
"code": null,
"e": 4676,
"s": 4439,
"text": "When the MVC framework sees that your controller action produces a ViewResult, the framework will find the view on the file system, execute the view, which produces HTML, and it is this HTML which the framework sends back to the client."
},
{
"code": null,
"e": 4851,
"s": 4676,
"text": "Let us now take a simple example to understand how this works in our application by changing the HomeController Index method implementation as shown in the following program."
},
{
"code": null,
"e": 5245,
"s": 4851,
"text": "using FirstAppDemo.Models; \nusing Microsoft.AspNet.Mvc; \n\nusing System; \nusing System.Collections.Generic; \nusing System.Linq; \nusing System.Threading.Tasks; \n\nnamespace FirstAppdemo.Controllers { \n public class HomeController : Controller { \n public ViewResult Index() { \n var employee = new Employee { ID = 1, Name = \"Mark Upston\"}; \n return View(); \n } \n } \n}"
},
{
"code": null,
"e": 5662,
"s": 5245,
"text": "Inside HomeController, instead of producing an ObjectResult, let us just return what the View() method returns. The View method doesn't return an ObjectResult. It creates a new ViewResult, so we will also change the return type of the Index method to ViewResult. The View method does accept some parameters here. We will invoke this method without any other parameter. Let us save your file and refresh your browser."
},
{
"code": null,
"e": 5761,
"s": 5662,
"text": "This is because the MVC framework has to go out and find that view but there is no view right now."
},
{
"code": null,
"e": 5948,
"s": 5761,
"text": "Views by default in a C# ASP.NET project are files that have a *.cshtml extension and the views follow a specific convention. By default, all views live in a Views folder in the project."
},
{
"code": null,
"e": 6135,
"s": 5948,
"text": "Views by default in a C# ASP.NET project are files that have a *.cshtml extension and the views follow a specific convention. By default, all views live in a Views folder in the project."
},
{
"code": null,
"e": 6256,
"s": 6135,
"text": "The view location and the view file name will be derived by ASP.NET MVC if you don't give it any additional information."
},
{
"code": null,
"e": 6377,
"s": 6256,
"text": "The view location and the view file name will be derived by ASP.NET MVC if you don't give it any additional information."
},
{
"code": null,
"e": 6541,
"s": 6377,
"text": "If we need to render a view from the Index action of the HomeController, the first place that the MVC framework will look for that view is inside the Views folder."
},
{
"code": null,
"e": 6705,
"s": 6541,
"text": "If we need to render a view from the Index action of the HomeController, the first place that the MVC framework will look for that view is inside the Views folder."
},
{
"code": null,
"e": 6850,
"s": 6705,
"text": "It will go into a Home folder and then look for a file called Index.cshtml − the file name starts with Index because we are in the Index action."
},
{
"code": null,
"e": 6995,
"s": 6850,
"text": "It will go into a Home folder and then look for a file called Index.cshtml − the file name starts with Index because we are in the Index action."
},
{
"code": null,
"e": 7144,
"s": 6995,
"text": "The MVC framework will also look in a Shared folder and views that you place inside the Shared folder, you can use them anywhere in the application."
},
{
"code": null,
"e": 7293,
"s": 7144,
"text": "The MVC framework will also look in a Shared folder and views that you place inside the Shared folder, you can use them anywhere in the application."
},
{
"code": null,
"e": 7696,
"s": 7293,
"text": "In order for our view result to work properly, let us create this Index.cshtml file in the correct location. So in our project, we first need to add a folder that will contain all of our views and call it Views. Inside the Views folder, we will add another folder for views that are associated with our HomeController and call that folder Home. Right-click on the Home folder and select Add → New Item."
},
{
"code": null,
"e": 7809,
"s": 7696,
"text": "In the left pane, select the MVC View Page and enter index.cshtml in the name field and click on the Add button."
},
{
"code": null,
"e": 7865,
"s": 7809,
"text": "Let us add the following code in the index.cshtml file."
},
{
"code": null,
"e": 8098,
"s": 7865,
"text": "<html xmlns = \"http://www.w3.org/1999/xhtml\"> \n <head> \n <title>Home</title> \n </head>\n\n <body> \n <h1>Welcome!</h1> \n \n <div> \n This message is from the View... \n </div> \n </body> \n\n</html> "
},
{
"code": null,
"e": 8277,
"s": 8098,
"text": "You can now see a *.cshtml file. It can contain HTML markup and any markup that we have in this file will be sent directly to the client. Save this file and refresh your browser."
},
{
"code": null,
"e": 8449,
"s": 8277,
"text": "Now the Home controller via a ViewResult has rendered this view to the client and all of the markup that is in that index.cshtml file, that is what was sent to the client."
},
{
"code": null,
"e": 8603,
"s": 8449,
"text": "Let us go back to the HomeController and the View method. This View method has a couple of different overloads, and pass the employee model as parameter."
},
{
"code": null,
"e": 9005,
"s": 8603,
"text": "using FirstAppDemo.Models; \nusing Microsoft.AspNet.Mvc; \n\nusing System; \nusing System.Collections.Generic; \nusing System.Linq;\nusing System.Threading.Tasks; \n\nnamespace FirstAppdemo.Controllers { \n public class HomeController : Controller { \n public ViewResult Index() { \n var employee = new Employee { ID = 1, Name = \"Mark Upston\"}; \n return View(employee); \n } \n } \n} "
},
{
"code": null,
"e": 9230,
"s": 9005,
"text": "The View method that just takes a model object and that will use the default view, which is Index. Here we just want to pass in that model information and use that model inside Index.cshtml as shown in the following program."
},
{
"code": null,
"e": 9444,
"s": 9230,
"text": "<html xmlns = \"http://www.w3.org/1999/xhtml\"> \n <head> \n <title>Home</title> \n </head> \n \n <body> \n <h1>Welcome!</h1> \n \n <div> \n @Model.Name \n </div> \n </body> \n</html> "
},
{
"code": null,
"e": 9887,
"s": 9444,
"text": "When we use the @ sign in a Razor view, then the Razor view engine is going to treat whatever you type as a C# expression. Razor view contains some built-in members that we can access inside the C# expressions. One of the most important members is the Model. When you say @Model, then you will get the model object that you have passed into the view from the controller. So here the @Model.Name will display the employee name inside the view."
},
{
"code": null,
"e": 9980,
"s": 9887,
"text": "Let us now save all the files. After this, refresh your browser to see the following output."
},
{
"code": null,
"e": 10042,
"s": 9980,
"text": "You can now see the employee name as in the above screenshot."
},
{
"code": null,
"e": 10077,
"s": 10042,
"text": "\n 51 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 10091,
"s": 10077,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 10126,
"s": 10091,
"text": "\n 44 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 10149,
"s": 10126,
"text": " Kaushik Roy Chowdhury"
},
{
"code": null,
"e": 10183,
"s": 10149,
"text": "\n 42 Lectures \n 18 hours \n"
},
{
"code": null,
"e": 10203,
"s": 10183,
"text": " SHIVPRASAD KOIRALA"
},
{
"code": null,
"e": 10238,
"s": 10203,
"text": "\n 57 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 10255,
"s": 10238,
"text": " University Code"
},
{
"code": null,
"e": 10290,
"s": 10255,
"text": "\n 40 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 10307,
"s": 10290,
"text": " University Code"
},
{
"code": null,
"e": 10341,
"s": 10307,
"text": "\n 138 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 10356,
"s": 10341,
"text": " Bhrugen Patel"
},
{
"code": null,
"e": 10363,
"s": 10356,
"text": " Print"
},
{
"code": null,
"e": 10374,
"s": 10363,
"text": " Add Notes"
}
] |
Favoring Composition Over Inheritance In Java With Examples - GeeksforGeeks
|
22 Feb, 2021
Favoring Composition over Inheritance is a principle in object-oriented programming (OOP). Classes should achieve polymorphic behavior and code reuse by their composition rather than inheritance from a base or parent class. To get the higher design flexibility, the design principle says that composition should be favored over inheritance.
Inheritance should only be used when subclass ‘is a’ superclass. Don’t use inheritance to get code reuse. If there is no ‘is a’ relationship, then use composition for code reuse.
Reasons to Favour Composition over Inheritance in Java and OOP:
The fact that Java does not support multiple inheritances is one reason for favoring composition over inheritance in Java. Since you can only extend one class in Java, but if you need multiple features, such as reading and writing character data into a file, you need Reader and Writer functionality. It makes your job simple to have them as private members, and this is called Composition.Composition offers better test-ability of a class than Inheritance. If one class consists of another class, you can easily construct a Mock Object representing a composed class for the sake of testing. This privilege is not given by inheritance.Although both Composition and Inheritance allow you to reuse code, one of Inheritance’s disadvantages is that it breaks encapsulation. If the subclass depends on the action of the superclass for its function, it suddenly becomes fragile. When super-class behavior changes, sub-class functionality can be broken without any modification on its part.In the timeless classic Design Patterns, several object-oriented design patterns listed by Gang of Four: Elements of Reusable Object-Oriented Software, favor Composition over Inheritance. Strategy design pattern, where composition and delegation are used to modify the behavior of Context without touching context code, is a classical example of this. Instead of getting it by inheritance, because Context uses composition to carry strategy, it is simple to have a new implementation of strategy at run-time.Another reason why composition is preferred over inheritance is flexibility. If you use Composition, you are flexible enough to replace the better and updated version of the Composed class implementation. One example is the use of the comparator class, which provides features for comparison.
The fact that Java does not support multiple inheritances is one reason for favoring composition over inheritance in Java. Since you can only extend one class in Java, but if you need multiple features, such as reading and writing character data into a file, you need Reader and Writer functionality. It makes your job simple to have them as private members, and this is called Composition.
Composition offers better test-ability of a class than Inheritance. If one class consists of another class, you can easily construct a Mock Object representing a composed class for the sake of testing. This privilege is not given by inheritance.
Although both Composition and Inheritance allow you to reuse code, one of Inheritance’s disadvantages is that it breaks encapsulation. If the subclass depends on the action of the superclass for its function, it suddenly becomes fragile. When super-class behavior changes, sub-class functionality can be broken without any modification on its part.
In the timeless classic Design Patterns, several object-oriented design patterns listed by Gang of Four: Elements of Reusable Object-Oriented Software, favor Composition over Inheritance. Strategy design pattern, where composition and delegation are used to modify the behavior of Context without touching context code, is a classical example of this. Instead of getting it by inheritance, because Context uses composition to carry strategy, it is simple to have a new implementation of strategy at run-time.
Another reason why composition is preferred over inheritance is flexibility. If you use Composition, you are flexible enough to replace the better and updated version of the Composed class implementation. One example is the use of the comparator class, which provides features for comparison.
Inheritance :
Inheritance is the design strategy to implement a relationship between objects in object-oriented programming. The extends keyword is used to implement inheritance in Java.
class Person {
String title;
String name;
int age;
}
class Employee extends Person {
int salary;
String title;
}
In the above example, The Employee “is a” Person or inherits from Person. All inheritance relationships are “is-a” relationships. The Employee also shadows the title property from Person, meaning Employee. title will return the Employee’s title, not the Person.
Composition :
In object-oriented programming, the composition is the architecture strategy for executing a relationship between objects. Java composition is done using instance variables from other objects.
class Person {
String title;
String name;
int age;
public Person(String title, String name, String age) {
this.title = title;
this.name = name;
this.age = age;
}
}
class Employee {
int salary;
private Person person;
public Employee(Person p, int salary) {
this.person = p;
this.salary = salary;
}
}
Person p = new Person ("Mr.", "Kapil", 25);
Employee kapil = new Employee (p, 100000);
The composition is typically “has a” or “uses a” relationship. Here the Employee class has a Person. It does not inherit from Person but instead gets the Person object passed to it, which is why it “has a” Person.
Composition over Inheritance
Now say you want to create a Manager type, so you end up with the below syntax, which is not allowed in java (multiple Inheritance is not allowed in java) :
//multiple inheritance not allowed
class Manager extends Person, Employee {
}
now we have to favor composition over Inheritance using the below syntax:
Class Manager {
public string title;
public Manager(Person p, Employee e)
{
this.title = e.title;
}
}
java-inheritance
Java-Object Oriented
Picked
Java
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
Internal Working of HashMap in Java
Introduction to Java
Comparator Interface in Java with Examples
PriorityQueue in Java
|
[
{
"code": null,
"e": 25237,
"s": 25209,
"text": "\n22 Feb, 2021"
},
{
"code": null,
"e": 25579,
"s": 25237,
"text": "Favoring Composition over Inheritance is a principle in object-oriented programming (OOP). Classes should achieve polymorphic behavior and code reuse by their composition rather than inheritance from a base or parent class. To get the higher design flexibility, the design principle says that composition should be favored over inheritance. "
},
{
"code": null,
"e": 25758,
"s": 25579,
"text": "Inheritance should only be used when subclass ‘is a’ superclass. Don’t use inheritance to get code reuse. If there is no ‘is a’ relationship, then use composition for code reuse."
},
{
"code": null,
"e": 25822,
"s": 25758,
"text": "Reasons to Favour Composition over Inheritance in Java and OOP:"
},
{
"code": null,
"e": 27606,
"s": 25822,
"text": "The fact that Java does not support multiple inheritances is one reason for favoring composition over inheritance in Java. Since you can only extend one class in Java, but if you need multiple features, such as reading and writing character data into a file, you need Reader and Writer functionality. It makes your job simple to have them as private members, and this is called Composition.Composition offers better test-ability of a class than Inheritance. If one class consists of another class, you can easily construct a Mock Object representing a composed class for the sake of testing. This privilege is not given by inheritance.Although both Composition and Inheritance allow you to reuse code, one of Inheritance’s disadvantages is that it breaks encapsulation. If the subclass depends on the action of the superclass for its function, it suddenly becomes fragile. When super-class behavior changes, sub-class functionality can be broken without any modification on its part.In the timeless classic Design Patterns, several object-oriented design patterns listed by Gang of Four: Elements of Reusable Object-Oriented Software, favor Composition over Inheritance. Strategy design pattern, where composition and delegation are used to modify the behavior of Context without touching context code, is a classical example of this. Instead of getting it by inheritance, because Context uses composition to carry strategy, it is simple to have a new implementation of strategy at run-time.Another reason why composition is preferred over inheritance is flexibility. If you use Composition, you are flexible enough to replace the better and updated version of the Composed class implementation. One example is the use of the comparator class, which provides features for comparison."
},
{
"code": null,
"e": 27997,
"s": 27606,
"text": "The fact that Java does not support multiple inheritances is one reason for favoring composition over inheritance in Java. Since you can only extend one class in Java, but if you need multiple features, such as reading and writing character data into a file, you need Reader and Writer functionality. It makes your job simple to have them as private members, and this is called Composition."
},
{
"code": null,
"e": 28243,
"s": 27997,
"text": "Composition offers better test-ability of a class than Inheritance. If one class consists of another class, you can easily construct a Mock Object representing a composed class for the sake of testing. This privilege is not given by inheritance."
},
{
"code": null,
"e": 28592,
"s": 28243,
"text": "Although both Composition and Inheritance allow you to reuse code, one of Inheritance’s disadvantages is that it breaks encapsulation. If the subclass depends on the action of the superclass for its function, it suddenly becomes fragile. When super-class behavior changes, sub-class functionality can be broken without any modification on its part."
},
{
"code": null,
"e": 29101,
"s": 28592,
"text": "In the timeless classic Design Patterns, several object-oriented design patterns listed by Gang of Four: Elements of Reusable Object-Oriented Software, favor Composition over Inheritance. Strategy design pattern, where composition and delegation are used to modify the behavior of Context without touching context code, is a classical example of this. Instead of getting it by inheritance, because Context uses composition to carry strategy, it is simple to have a new implementation of strategy at run-time."
},
{
"code": null,
"e": 29394,
"s": 29101,
"text": "Another reason why composition is preferred over inheritance is flexibility. If you use Composition, you are flexible enough to replace the better and updated version of the Composed class implementation. One example is the use of the comparator class, which provides features for comparison."
},
{
"code": null,
"e": 29408,
"s": 29394,
"text": "Inheritance :"
},
{
"code": null,
"e": 29581,
"s": 29408,
"text": "Inheritance is the design strategy to implement a relationship between objects in object-oriented programming. The extends keyword is used to implement inheritance in Java."
},
{
"code": null,
"e": 29700,
"s": 29581,
"text": "class Person {\n String title;\n String name;\n int age;\n}\n\nclass Employee extends Person {\n int salary;\n String title;\n}"
},
{
"code": null,
"e": 29962,
"s": 29700,
"text": "In the above example, The Employee “is a” Person or inherits from Person. All inheritance relationships are “is-a” relationships. The Employee also shadows the title property from Person, meaning Employee. title will return the Employee’s title, not the Person."
},
{
"code": null,
"e": 29976,
"s": 29962,
"text": "Composition :"
},
{
"code": null,
"e": 30170,
"s": 29976,
"text": "In object-oriented programming, the composition is the architecture strategy for executing a relationship between objects. Java composition is done using instance variables from other objects. "
},
{
"code": null,
"e": 30592,
"s": 30170,
"text": "class Person {\n String title;\n String name;\n int age;\n\n public Person(String title, String name, String age) {\n this.title = title;\n this.name = name;\n this.age = age;\n }\n\n}\n\nclass Employee {\n int salary;\n private Person person;\n\n public Employee(Person p, int salary) {\n this.person = p;\n this.salary = salary;\n }\n}\n\nPerson p = new Person (\"Mr.\", \"Kapil\", 25);\nEmployee kapil = new Employee (p, 100000);"
},
{
"code": null,
"e": 30806,
"s": 30592,
"text": "The composition is typically “has a” or “uses a” relationship. Here the Employee class has a Person. It does not inherit from Person but instead gets the Person object passed to it, which is why it “has a” Person."
},
{
"code": null,
"e": 30835,
"s": 30806,
"text": "Composition over Inheritance"
},
{
"code": null,
"e": 30992,
"s": 30835,
"text": "Now say you want to create a Manager type, so you end up with the below syntax, which is not allowed in java (multiple Inheritance is not allowed in java) :"
},
{
"code": null,
"e": 31027,
"s": 30992,
"text": "//multiple inheritance not allowed"
},
{
"code": null,
"e": 31070,
"s": 31027,
"text": "class Manager extends Person, Employee {\n}"
},
{
"code": null,
"e": 31144,
"s": 31070,
"text": "now we have to favor composition over Inheritance using the below syntax:"
},
{
"code": null,
"e": 31254,
"s": 31144,
"text": "Class Manager {\n public string title;\n public Manager(Person p, Employee e)\n {\n this.title = e.title;\n }\n}"
},
{
"code": null,
"e": 31271,
"s": 31254,
"text": "java-inheritance"
},
{
"code": null,
"e": 31292,
"s": 31271,
"text": "Java-Object Oriented"
},
{
"code": null,
"e": 31299,
"s": 31292,
"text": "Picked"
},
{
"code": null,
"e": 31304,
"s": 31299,
"text": "Java"
},
{
"code": null,
"e": 31309,
"s": 31304,
"text": "Java"
},
{
"code": null,
"e": 31407,
"s": 31309,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31422,
"s": 31407,
"text": "Stream In Java"
},
{
"code": null,
"e": 31443,
"s": 31422,
"text": "Constructors in Java"
},
{
"code": null,
"e": 31462,
"s": 31443,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 31492,
"s": 31462,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 31538,
"s": 31492,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 31555,
"s": 31538,
"text": "Generics in Java"
},
{
"code": null,
"e": 31591,
"s": 31555,
"text": "Internal Working of HashMap in Java"
},
{
"code": null,
"e": 31612,
"s": 31591,
"text": "Introduction to Java"
},
{
"code": null,
"e": 31655,
"s": 31612,
"text": "Comparator Interface in Java with Examples"
}
] |
midpoint() in C++20 with Examples - GeeksforGeeks
|
27 Aug, 2021
The function midpoint() computes the midpoint of the integers, floating-points, or pointers a and b.Header File:
<numeric>
Parameters: This function accepts two data types like integers, floating points, pointer values.
Return:
It returns the midpoints of the given data types.Algorithm this function implements:
Half the sum of a and b without any overflow. Same as, (a + b)/2.
If a and b are integer types and the sum is odd, the result is rounded towards a.
If a and b are floating-point types, at most one inexact operation occurs (rounded towards zero).
If a and b are pointing to x[i] and x[j] respectively of the same array object x (for the purpose of pointer arithmetic), the result will be a pointer to x[i + (j – i)/2] (or, equivalently x[std::midpoint(i, j)]) where the division rounds towards zero. If a and b do not point to elements of the same array object, the behavior is undefined.
Uses Of midpoint() function:
Middle point of two integers using midpoint(): Below is the C++ Program to demonstrate the middle point of two integer numbers using midpoint():
C++
// C++ program to demonstrate the// midpoint function#include <iostream>#include <numeric>using namespace std; // Driver Codeint main(){ // a and b both of integer type int a = 3; int b = 6; cout << "midpoint(" << a << ", " << b << "): " << midpoint(a, b) << endl; a = 6; b = 3; cout << "midpoint(" << a << ", " << b << "): " << midpoint(a, b) << endl; return 0;}
Output:
midpoint() can handle cases like an overflow: Below is the C++ program to demonstrate how to handle overflow using midpoint():
C++
// C++ program for the above approach#include <climits>#include <iostream>#include <numeric>using namespace std; // Driver Codeint main(){ // a stores maximum storable // value of integer int a = INT_MAX; // b stores maximum storable // value of integer - 2 int b = INT_MAX - 2; cout << "a: " << a << endl << "b: " << b << endl << "Incorrect (overflow" << " and wrapping): " << (a + b) / 2 << endl << "Correct: " << midpoint(a, b) << "\n\n"; return 0;}
Output:
Middle point of two floating number using midpoint(): Below is the C++ program to demonstrate how to find the middle point of two floating-point numbers using midpoint():
C++
// C++ program for the above approach#include <iostream>#include <numeric> using namespace std; int main(){ // x and y both floating type float x = 6.56; float y = 7.23; cout << "midpoint(" << x << ", " << y << "): " << midpoint(x, y) << endl; x = 2.0; y = 3.0; cout << "midpoint(" << x << ", " << y << "): " << midpoint(x, y) << endl << endl;}
Output:
Middle point between two pointers pointing to the same object using midpoint(): Below is the C++ program to demonstrate how to find the middle point of two pointers pointing to the same object using midpoint():
C++
// C++ program for the above approach#include <iostream>#include <numeric>using namespace std; // Driver Codeint main(){ // str is a character array char str[] = "GeeksforGeeks"; // str1 is pointing to the // 5-th element in str char* str1 = &str[4]; // str2 is pointing to the // 10-th element in str char* str2 = &str[9]; // str1 and str2 is pointing same // object str therefore, we can // logically compute and point a // middle element in str cout << "midpoint('" << *str1 << "', '" << *str2 << "'): '" << *midpoint(str1, str2) << "'" << endl; cout << "midpoint('" << *str2 << "', '" << *str1 << "'): '" << *midpoint(str2, str1) << "'" << endl;}
Output:
kalrap615
Functions
C++
C++ Programs
Functions
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Sorting a vector in C++
Friend class and function in C++
std::string class in C++
Header files in C/C++ and its uses
Program to print ASCII Value of a character
How to return multiple values from a function in C or C++?
C++ Program for QuickSort
Sorting a Map by value in C++ STL
|
[
{
"code": null,
"e": 25343,
"s": 25315,
"text": "\n27 Aug, 2021"
},
{
"code": null,
"e": 25457,
"s": 25343,
"text": "The function midpoint() computes the midpoint of the integers, floating-points, or pointers a and b.Header File: "
},
{
"code": null,
"e": 25467,
"s": 25457,
"text": "<numeric>"
},
{
"code": null,
"e": 25565,
"s": 25467,
"text": " Parameters: This function accepts two data types like integers, floating points, pointer values."
},
{
"code": null,
"e": 25573,
"s": 25565,
"text": "Return:"
},
{
"code": null,
"e": 25658,
"s": 25573,
"text": "It returns the midpoints of the given data types.Algorithm this function implements:"
},
{
"code": null,
"e": 25724,
"s": 25658,
"text": "Half the sum of a and b without any overflow. Same as, (a + b)/2."
},
{
"code": null,
"e": 25806,
"s": 25724,
"text": "If a and b are integer types and the sum is odd, the result is rounded towards a."
},
{
"code": null,
"e": 25904,
"s": 25806,
"text": "If a and b are floating-point types, at most one inexact operation occurs (rounded towards zero)."
},
{
"code": null,
"e": 26246,
"s": 25904,
"text": "If a and b are pointing to x[i] and x[j] respectively of the same array object x (for the purpose of pointer arithmetic), the result will be a pointer to x[i + (j – i)/2] (or, equivalently x[std::midpoint(i, j)]) where the division rounds towards zero. If a and b do not point to elements of the same array object, the behavior is undefined."
},
{
"code": null,
"e": 26275,
"s": 26246,
"text": "Uses Of midpoint() function:"
},
{
"code": null,
"e": 26420,
"s": 26275,
"text": "Middle point of two integers using midpoint(): Below is the C++ Program to demonstrate the middle point of two integer numbers using midpoint():"
},
{
"code": null,
"e": 26424,
"s": 26420,
"text": "C++"
},
{
"code": "// C++ program to demonstrate the// midpoint function#include <iostream>#include <numeric>using namespace std; // Driver Codeint main(){ // a and b both of integer type int a = 3; int b = 6; cout << \"midpoint(\" << a << \", \" << b << \"): \" << midpoint(a, b) << endl; a = 6; b = 3; cout << \"midpoint(\" << a << \", \" << b << \"): \" << midpoint(a, b) << endl; return 0;}",
"e": 26847,
"s": 26424,
"text": null
},
{
"code": null,
"e": 26855,
"s": 26847,
"text": "Output:"
},
{
"code": null,
"e": 26983,
"s": 26855,
"text": "midpoint() can handle cases like an overflow: Below is the C++ program to demonstrate how to handle overflow using midpoint(): "
},
{
"code": null,
"e": 26987,
"s": 26983,
"text": "C++"
},
{
"code": "// C++ program for the above approach#include <climits>#include <iostream>#include <numeric>using namespace std; // Driver Codeint main(){ // a stores maximum storable // value of integer int a = INT_MAX; // b stores maximum storable // value of integer - 2 int b = INT_MAX - 2; cout << \"a: \" << a << endl << \"b: \" << b << endl << \"Incorrect (overflow\" << \" and wrapping): \" << (a + b) / 2 << endl << \"Correct: \" << midpoint(a, b) << \"\\n\\n\"; return 0;}",
"e": 27515,
"s": 26987,
"text": null
},
{
"code": null,
"e": 27523,
"s": 27515,
"text": "Output:"
},
{
"code": null,
"e": 27694,
"s": 27523,
"text": "Middle point of two floating number using midpoint(): Below is the C++ program to demonstrate how to find the middle point of two floating-point numbers using midpoint():"
},
{
"code": null,
"e": 27698,
"s": 27694,
"text": "C++"
},
{
"code": "// C++ program for the above approach#include <iostream>#include <numeric> using namespace std; int main(){ // x and y both floating type float x = 6.56; float y = 7.23; cout << \"midpoint(\" << x << \", \" << y << \"): \" << midpoint(x, y) << endl; x = 2.0; y = 3.0; cout << \"midpoint(\" << x << \", \" << y << \"): \" << midpoint(x, y) << endl << endl;}",
"e": 28115,
"s": 27698,
"text": null
},
{
"code": null,
"e": 28123,
"s": 28115,
"text": "Output:"
},
{
"code": null,
"e": 28335,
"s": 28123,
"text": "Middle point between two pointers pointing to the same object using midpoint(): Below is the C++ program to demonstrate how to find the middle point of two pointers pointing to the same object using midpoint(): "
},
{
"code": null,
"e": 28339,
"s": 28335,
"text": "C++"
},
{
"code": "// C++ program for the above approach#include <iostream>#include <numeric>using namespace std; // Driver Codeint main(){ // str is a character array char str[] = \"GeeksforGeeks\"; // str1 is pointing to the // 5-th element in str char* str1 = &str[4]; // str2 is pointing to the // 10-th element in str char* str2 = &str[9]; // str1 and str2 is pointing same // object str therefore, we can // logically compute and point a // middle element in str cout << \"midpoint('\" << *str1 << \"', '\" << *str2 << \"'): '\" << *midpoint(str1, str2) << \"'\" << endl; cout << \"midpoint('\" << *str2 << \"', '\" << *str1 << \"'): '\" << *midpoint(str2, str1) << \"'\" << endl;}",
"e": 29084,
"s": 28339,
"text": null
},
{
"code": null,
"e": 29092,
"s": 29084,
"text": "Output:"
},
{
"code": null,
"e": 29102,
"s": 29092,
"text": "kalrap615"
},
{
"code": null,
"e": 29112,
"s": 29102,
"text": "Functions"
},
{
"code": null,
"e": 29116,
"s": 29112,
"text": "C++"
},
{
"code": null,
"e": 29129,
"s": 29116,
"text": "C++ Programs"
},
{
"code": null,
"e": 29139,
"s": 29129,
"text": "Functions"
},
{
"code": null,
"e": 29143,
"s": 29139,
"text": "CPP"
},
{
"code": null,
"e": 29241,
"s": 29143,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29269,
"s": 29241,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 29289,
"s": 29269,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 29313,
"s": 29289,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 29346,
"s": 29313,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 29371,
"s": 29346,
"text": "std::string class in C++"
},
{
"code": null,
"e": 29406,
"s": 29371,
"text": "Header files in C/C++ and its uses"
},
{
"code": null,
"e": 29450,
"s": 29406,
"text": "Program to print ASCII Value of a character"
},
{
"code": null,
"e": 29509,
"s": 29450,
"text": "How to return multiple values from a function in C or C++?"
},
{
"code": null,
"e": 29535,
"s": 29509,
"text": "C++ Program for QuickSort"
}
] |
Distance traveled by Hour and Minute hand in given Time interval - GeeksforGeeks
|
30 Sep, 2021
Given two numbers H and M which denotes the length of the hour and minute hand and two time intervals(say T1 & T2) in form of HH:MM, the task is to find the distance traveled by hour hand and minute hand between time T1 and T2.
Examples:
Input: H = 5, M = 7, T1 = “1:30”, T2 = “10:50” Output: Distance travelled by minute hand: 410.50144006906635 Distance travelled by hour hand: 24.434609527920614
Input: H = 4, M = 5, T1 = “1:30”, T2 = “10:50” Output: Distance travelled by minute hand: 293.21531433504737 Distance travelled by hour hand: 19.54768762233649
Approach:
Find the difference between the two time intervals T1 and T2 by using the approach discussed in this article.
Change the time duration obtained above into minutes as:
Total Minutes = hours * 60 + minutes
Since minute hand covers one rotation in 60 minutes, therefore, number of rotations covered by minute hand(say rm) is given by
Since hour hand covers one rotation in 60*12 = 720 minutes, therefore, number of rotations covered by hour hand(say rh) is given by
The total distance traverse by the hour hand is given by
The total distance traverse by the minute hand is given by
Below is the implementation of the above approach:
Python
# Python program for the above approach import math # Function to remove ':' and convert# it into an integerdef removeColon(s): if (len(s) == 4): s = s[:1]+s[2:] if (len(s) == 5): s = s[:2]+s[3:] return int(s) # function which find the difference# between time intervaldef diff(s1, s2): # Change string as 2:21 to 221 time1 = removeColon(s1) time2 = removeColon(s2) # Difference between hours hourDiff = time2 // 100 - time1 // 100 - 1; # Difference between minutes minDiff = time2 % 100 + (60 - time1 % 100) if (minDiff >= 60): hourDiff+= 1 minDiff = minDiff - 60 # Convert answer again in string # with ':' res = str(hourDiff) + ':' + str(minDiff) return res # Function for finding the distance travelled# by minute hand and hour handdef disTravel(T1, T2, M, H): # Find the duration between these time dur = diff(T1, T2) # Remove colon from the dur and # convert in int s = removeColon(dur) # Convert the time in to minute # hour * 60 + min totalMinute =(s//100)*60 + s % 100 # Count min hand rotation rm = totalMinute / 60; # Count hour hand rotation rh = totalMinute / 720; # Compute distance traveled by min hand minuteDistance = rm * 2* math.pi * M; # Compute distance traveled by hour hand hourDistance = rh * 2* math.pi * H; return minuteDistance, hourDistance # Driver Code # Given Time IntervalsT1 ="1:30"T2 ="10:50" # Given hour and minute hand lengthH = 5M = 7 # Function CallminuteDistance, hourDistance = disTravel(T1, T2, M, H) # Print the distance traveled by minute# and hour handprint("Distance traveled by minute hand: " ,minuteDistance)print("Distance traveled by hour hand: " ,hourDistance )
Distance traveled by minute hand: 410.50144006906635
Distance traveled by hour hand: 24.434609527920614
kashishsoda
Time and Distance
Geometric
Mathematical
Mathematical
Geometric
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Haversine formula to find distance between two points on a sphere
Program to find slope of a line
Equation of circle when three points on the circle are given
Program to find line passing through 2 Points
Maximum Manhattan distance between a distinct pair from N coordinates
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7
|
[
{
"code": null,
"e": 26561,
"s": 26533,
"text": "\n30 Sep, 2021"
},
{
"code": null,
"e": 26789,
"s": 26561,
"text": "Given two numbers H and M which denotes the length of the hour and minute hand and two time intervals(say T1 & T2) in form of HH:MM, the task is to find the distance traveled by hour hand and minute hand between time T1 and T2."
},
{
"code": null,
"e": 26800,
"s": 26789,
"text": "Examples: "
},
{
"code": null,
"e": 26961,
"s": 26800,
"text": "Input: H = 5, M = 7, T1 = “1:30”, T2 = “10:50” Output: Distance travelled by minute hand: 410.50144006906635 Distance travelled by hour hand: 24.434609527920614"
},
{
"code": null,
"e": 27122,
"s": 26961,
"text": "Input: H = 4, M = 5, T1 = “1:30”, T2 = “10:50” Output: Distance travelled by minute hand: 293.21531433504737 Distance travelled by hour hand: 19.54768762233649 "
},
{
"code": null,
"e": 27133,
"s": 27122,
"text": "Approach: "
},
{
"code": null,
"e": 27243,
"s": 27133,
"text": "Find the difference between the two time intervals T1 and T2 by using the approach discussed in this article."
},
{
"code": null,
"e": 27301,
"s": 27243,
"text": "Change the time duration obtained above into minutes as: "
},
{
"code": null,
"e": 27338,
"s": 27301,
"text": "Total Minutes = hours * 60 + minutes"
},
{
"code": null,
"e": 27466,
"s": 27338,
"text": "Since minute hand covers one rotation in 60 minutes, therefore, number of rotations covered by minute hand(say rm) is given by "
},
{
"code": null,
"e": 27599,
"s": 27466,
"text": "Since hour hand covers one rotation in 60*12 = 720 minutes, therefore, number of rotations covered by hour hand(say rh) is given by "
},
{
"code": null,
"e": 27657,
"s": 27599,
"text": "The total distance traverse by the hour hand is given by "
},
{
"code": null,
"e": 27717,
"s": 27657,
"text": "The total distance traverse by the minute hand is given by "
},
{
"code": null,
"e": 27768,
"s": 27717,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 27775,
"s": 27768,
"text": "Python"
},
{
"code": "# Python program for the above approach import math # Function to remove ':' and convert# it into an integerdef removeColon(s): if (len(s) == 4): s = s[:1]+s[2:] if (len(s) == 5): s = s[:2]+s[3:] return int(s) # function which find the difference# between time intervaldef diff(s1, s2): # Change string as 2:21 to 221 time1 = removeColon(s1) time2 = removeColon(s2) # Difference between hours hourDiff = time2 // 100 - time1 // 100 - 1; # Difference between minutes minDiff = time2 % 100 + (60 - time1 % 100) if (minDiff >= 60): hourDiff+= 1 minDiff = minDiff - 60 # Convert answer again in string # with ':' res = str(hourDiff) + ':' + str(minDiff) return res # Function for finding the distance travelled# by minute hand and hour handdef disTravel(T1, T2, M, H): # Find the duration between these time dur = diff(T1, T2) # Remove colon from the dur and # convert in int s = removeColon(dur) # Convert the time in to minute # hour * 60 + min totalMinute =(s//100)*60 + s % 100 # Count min hand rotation rm = totalMinute / 60; # Count hour hand rotation rh = totalMinute / 720; # Compute distance traveled by min hand minuteDistance = rm * 2* math.pi * M; # Compute distance traveled by hour hand hourDistance = rh * 2* math.pi * H; return minuteDistance, hourDistance # Driver Code # Given Time IntervalsT1 =\"1:30\"T2 =\"10:50\" # Given hour and minute hand lengthH = 5M = 7 # Function CallminuteDistance, hourDistance = disTravel(T1, T2, M, H) # Print the distance traveled by minute# and hour handprint(\"Distance traveled by minute hand: \" ,minuteDistance)print(\"Distance traveled by hour hand: \" ,hourDistance )",
"e": 29562,
"s": 27775,
"text": null
},
{
"code": null,
"e": 29668,
"s": 29562,
"text": "Distance traveled by minute hand: 410.50144006906635\nDistance traveled by hour hand: 24.434609527920614"
},
{
"code": null,
"e": 29682,
"s": 29670,
"text": "kashishsoda"
},
{
"code": null,
"e": 29700,
"s": 29682,
"text": "Time and Distance"
},
{
"code": null,
"e": 29710,
"s": 29700,
"text": "Geometric"
},
{
"code": null,
"e": 29723,
"s": 29710,
"text": "Mathematical"
},
{
"code": null,
"e": 29736,
"s": 29723,
"text": "Mathematical"
},
{
"code": null,
"e": 29746,
"s": 29736,
"text": "Geometric"
},
{
"code": null,
"e": 29844,
"s": 29746,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29910,
"s": 29844,
"text": "Haversine formula to find distance between two points on a sphere"
},
{
"code": null,
"e": 29942,
"s": 29910,
"text": "Program to find slope of a line"
},
{
"code": null,
"e": 30003,
"s": 29942,
"text": "Equation of circle when three points on the circle are given"
},
{
"code": null,
"e": 30049,
"s": 30003,
"text": "Program to find line passing through 2 Points"
},
{
"code": null,
"e": 30119,
"s": 30049,
"text": "Maximum Manhattan distance between a distinct pair from N coordinates"
},
{
"code": null,
"e": 30149,
"s": 30119,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 30209,
"s": 30149,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 30224,
"s": 30209,
"text": "C++ Data Types"
},
{
"code": null,
"e": 30267,
"s": 30224,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
Python list copy() method - GeeksforGeeks
|
03 Aug, 2021
Sometimes, there is a need to reuse any object, hence copy methods are always of great utility. Python in its language offers a number of ways to achieve this. This particular article aims at demonstrating the copy method present in the list. Since the list is widely used hence, its copy is also necessary.
Syntax:
list.copy()
Parameters:
The copy() method doesn’t take any parameters
Returns:
Returns a shallow copy of a list. A shallow copy means any modification in the new list won’t be reflected in the original list.
Python3
# Python 3 code to demonstrate# working of list.copy() # Initializing listlis1 = [ 1, 2, 3, 4 ] # Using copy() to create a shallow copylis2 = lis1.copy() # Printing new listprint ("The new list created is : " + str(lis2)) # Adding new element to new listlis2.append(5) # Printing lists after adding new element# No change in old listprint ("The new list after adding new element : " + str(lis2))print ("The old list after adding new element to new list : " + str(lis1))
Output:
The new list created is : [1, 2, 3, 4]
The new list after adding new element : [1, 2, 3, 4, 5]
The old list after adding new element to new list : [1, 2, 3, 4]
Note:
A shallow copy means if we modify any of the nested list elements, changes are reflected in both the list as they point to the same reference. Whereas in deep copy, when we add an element in any of the lists, only that list is modified. When we use the “=” operator the new list refers to the same object, hence any change (append, remove, change of value) in one list is reflected on both. But when we use the list.copy() method, changes made to one list or not reflected on other except for in nested elements (like list within a list), Here we should use the copy.deepcopy() from the copy module to avoid this problem. Please refer to this article Deep Copy vs Shallow copy.
Techniques to deep copy: Using copy.deepcopy()
Using copy.deepcopy()
Techniques to shallow copy: Using copy.copy()Using list.copy()Using slicing
Using copy.copy()
Using list.copy()
Using slicing
Python3
# Python 3 code to demonstrate# techniques of deep and shallow copyimport copy # Initializing listlist1 = [ 1, [2, 3] , 4 ] # all changes are reflectedlist2 = list1 # shallow copy - changes to# nested list is reflected,# same as copy.copy(), slicing list3 = list1.copy() # deep copy - no change is reflectedlist4 = copy.deepcopy(list1) list1.append(5)list1[1][1] = 999 print("list 1 after modification:\n", list1)print("list 2 after modification:\n", list2)print("list 3 after modification:\n", list3)print("list 4 after modification:\n", list4)
Output:
list 1 after modification:
[1, [2, 999], 4, 5]
list 2 after modification:
[1, [2, 999], 4, 5]
list 3 after modification:
[1, [2, 999], 4]
list 4 after modification:
[1, [2, 3], 4]
murugappan19cs
AmiyaRanjanRout
python-list
python-list-functions
Python
python-list
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": 25376,
"s": 25348,
"text": "\n03 Aug, 2021"
},
{
"code": null,
"e": 25685,
"s": 25376,
"text": "Sometimes, there is a need to reuse any object, hence copy methods are always of great utility. Python in its language offers a number of ways to achieve this. This particular article aims at demonstrating the copy method present in the list. Since the list is widely used hence, its copy is also necessary. "
},
{
"code": null,
"e": 25694,
"s": 25685,
"text": "Syntax: "
},
{
"code": null,
"e": 25706,
"s": 25694,
"text": "list.copy()"
},
{
"code": null,
"e": 25719,
"s": 25706,
"text": "Parameters: "
},
{
"code": null,
"e": 25765,
"s": 25719,
"text": "The copy() method doesn’t take any parameters"
},
{
"code": null,
"e": 25775,
"s": 25765,
"text": "Returns: "
},
{
"code": null,
"e": 25906,
"s": 25775,
"text": "Returns a shallow copy of a list. A shallow copy means any modification in the new list won’t be reflected in the original list. "
},
{
"code": null,
"e": 25914,
"s": 25906,
"text": "Python3"
},
{
"code": "# Python 3 code to demonstrate# working of list.copy() # Initializing listlis1 = [ 1, 2, 3, 4 ] # Using copy() to create a shallow copylis2 = lis1.copy() # Printing new listprint (\"The new list created is : \" + str(lis2)) # Adding new element to new listlis2.append(5) # Printing lists after adding new element# No change in old listprint (\"The new list after adding new element : \" + str(lis2))print (\"The old list after adding new element to new list : \" + str(lis1))",
"e": 26385,
"s": 25914,
"text": null
},
{
"code": null,
"e": 26394,
"s": 26385,
"text": "Output: "
},
{
"code": null,
"e": 26555,
"s": 26394,
"text": "The new list created is : [1, 2, 3, 4]\nThe new list after adding new element : [1, 2, 3, 4, 5]\nThe old list after adding new element to new list : [1, 2, 3, 4]"
},
{
"code": null,
"e": 26562,
"s": 26555,
"text": "Note: "
},
{
"code": null,
"e": 27241,
"s": 26562,
"text": "A shallow copy means if we modify any of the nested list elements, changes are reflected in both the list as they point to the same reference. Whereas in deep copy, when we add an element in any of the lists, only that list is modified. When we use the “=” operator the new list refers to the same object, hence any change (append, remove, change of value) in one list is reflected on both. But when we use the list.copy() method, changes made to one list or not reflected on other except for in nested elements (like list within a list), Here we should use the copy.deepcopy() from the copy module to avoid this problem. Please refer to this article Deep Copy vs Shallow copy. "
},
{
"code": null,
"e": 27288,
"s": 27241,
"text": "Techniques to deep copy: Using copy.deepcopy()"
},
{
"code": null,
"e": 27310,
"s": 27288,
"text": "Using copy.deepcopy()"
},
{
"code": null,
"e": 27386,
"s": 27310,
"text": "Techniques to shallow copy: Using copy.copy()Using list.copy()Using slicing"
},
{
"code": null,
"e": 27404,
"s": 27386,
"text": "Using copy.copy()"
},
{
"code": null,
"e": 27422,
"s": 27404,
"text": "Using list.copy()"
},
{
"code": null,
"e": 27436,
"s": 27422,
"text": "Using slicing"
},
{
"code": null,
"e": 27444,
"s": 27436,
"text": "Python3"
},
{
"code": "# Python 3 code to demonstrate# techniques of deep and shallow copyimport copy # Initializing listlist1 = [ 1, [2, 3] , 4 ] # all changes are reflectedlist2 = list1 # shallow copy - changes to# nested list is reflected,# same as copy.copy(), slicing list3 = list1.copy() # deep copy - no change is reflectedlist4 = copy.deepcopy(list1) list1.append(5)list1[1][1] = 999 print(\"list 1 after modification:\\n\", list1)print(\"list 2 after modification:\\n\", list2)print(\"list 3 after modification:\\n\", list3)print(\"list 4 after modification:\\n\", list4)",
"e": 27990,
"s": 27444,
"text": null
},
{
"code": null,
"e": 28000,
"s": 27990,
"text": "Output: "
},
{
"code": null,
"e": 28184,
"s": 28000,
"text": "list 1 after modification:\n [1, [2, 999], 4, 5]\nlist 2 after modification:\n [1, [2, 999], 4, 5]\nlist 3 after modification:\n [1, [2, 999], 4]\nlist 4 after modification:\n [1, [2, 3], 4]"
},
{
"code": null,
"e": 28199,
"s": 28184,
"text": "murugappan19cs"
},
{
"code": null,
"e": 28215,
"s": 28199,
"text": "AmiyaRanjanRout"
},
{
"code": null,
"e": 28227,
"s": 28215,
"text": "python-list"
},
{
"code": null,
"e": 28249,
"s": 28227,
"text": "python-list-functions"
},
{
"code": null,
"e": 28256,
"s": 28249,
"text": "Python"
},
{
"code": null,
"e": 28268,
"s": 28256,
"text": "python-list"
},
{
"code": null,
"e": 28366,
"s": 28268,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28384,
"s": 28366,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28419,
"s": 28384,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 28451,
"s": 28419,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28473,
"s": 28451,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28515,
"s": 28473,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28545,
"s": 28515,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 28571,
"s": 28545,
"text": "Python String | replace()"
},
{
"code": null,
"e": 28600,
"s": 28571,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 28644,
"s": 28600,
"text": "Reading and Writing to text files in Python"
}
] |
Python | sympy.sympify() method - GeeksforGeeks
|
18 Jun, 2019
With the help of sympy.sympify() method, we are able to convert the expression of string type to general mathematical expression.
Syntax : sympy.sympify()Return : Return the expression.
Example #1 :In this example we can see that by using sympy.sympify(), we are converting the string of expression into real mathematical expression.
# Import sympyfrom sympy import * # Define symbols and trigo expressionx, y = symbols('x y')expn = "x**2 + 3 * x - 1 / 2" # Use sympy.sympify() methodgfg = sympify(expn) print(gfg)
Output :
x**2 + 3*x – 1/2
Example #2 :
# Import sympyfrom sympy import * # Define symbols and trigo expressionx, y = symbols('x y')expn = "x**2 + 3 * x - 1 / 2" # Use sympy.sympify() methodgfg = sympify(expn)gfg = gfg.subs(x, 3) print(gfg)
Output :
35/2
SymPy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n18 Jun, 2019"
},
{
"code": null,
"e": 25667,
"s": 25537,
"text": "With the help of sympy.sympify() method, we are able to convert the expression of string type to general mathematical expression."
},
{
"code": null,
"e": 25723,
"s": 25667,
"text": "Syntax : sympy.sympify()Return : Return the expression."
},
{
"code": null,
"e": 25871,
"s": 25723,
"text": "Example #1 :In this example we can see that by using sympy.sympify(), we are converting the string of expression into real mathematical expression."
},
{
"code": "# Import sympyfrom sympy import * # Define symbols and trigo expressionx, y = symbols('x y')expn = \"x**2 + 3 * x - 1 / 2\" # Use sympy.sympify() methodgfg = sympify(expn) print(gfg)",
"e": 26055,
"s": 25871,
"text": null
},
{
"code": null,
"e": 26064,
"s": 26055,
"text": "Output :"
},
{
"code": null,
"e": 26081,
"s": 26064,
"text": "x**2 + 3*x – 1/2"
},
{
"code": null,
"e": 26094,
"s": 26081,
"text": "Example #2 :"
},
{
"code": "# Import sympyfrom sympy import * # Define symbols and trigo expressionx, y = symbols('x y')expn = \"x**2 + 3 * x - 1 / 2\" # Use sympy.sympify() methodgfg = sympify(expn)gfg = gfg.subs(x, 3) print(gfg)",
"e": 26298,
"s": 26094,
"text": null
},
{
"code": null,
"e": 26307,
"s": 26298,
"text": "Output :"
},
{
"code": null,
"e": 26312,
"s": 26307,
"text": "35/2"
},
{
"code": null,
"e": 26318,
"s": 26312,
"text": "SymPy"
},
{
"code": null,
"e": 26325,
"s": 26318,
"text": "Python"
},
{
"code": null,
"e": 26423,
"s": 26325,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26455,
"s": 26423,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26497,
"s": 26455,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26539,
"s": 26497,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26566,
"s": 26539,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 26622,
"s": 26566,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26644,
"s": 26622,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26683,
"s": 26644,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 26714,
"s": 26683,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 26743,
"s": 26714,
"text": "Create a directory in Python"
}
] |
How to Draw a Circle Using Matplotlib in Python? - GeeksforGeeks
|
13 Sep, 2021
A Circle is a mathematical figure formed by joining all points lying on the same plane and are at equal distance from a given point. We can plot a circle in python using Matplotlib. There are multiple ways to plot a Circle in python using Matplotlib.
Method 1: Using matplotlib.patches.Circle() function.
Matplotlib has a special function matplotlib.patches.Circle() in order to plot circles.
Syntax: class matplotlib.patches.Circle(xy, radius=5, **kwargs)
Example 1: Plotting a colored Circle using matplotlib.patches.Circle()
Python3
# Demonstrating use of matplotlib.patches.Circle() function# to plot a colored Circle import matplotlib.pyplot as plt figure, axes = plt.subplots()Drawing_colored_circle = plt.Circle(( 0.6 , 0.6 ), 0.2 ) axes.set_aspect( 1 )axes.add_artist( Drawing_colored_circle )plt.title( 'Colored Circle' )plt.show()
Output:
Example 2: Plotting an un-colored Circle using matplotlib.patches.Circle()
Python3
# Demonstrating use of matplotlib.patches.Circle() function# to plot an un-colored Circle import matplotlib.pyplot as plt figure, axes = plt.subplots()Drawing_uncolored_circle = plt.Circle( (0.6, 0.6 ), 0.3 , fill = False ) axes.set_aspect( 1 )axes.add_artist( Drawing_uncolored_circle )plt.title( 'Circle' )plt.show()
Output:
Method 2: Using Circle Equation
Example 1: Plotting a Circle using Parametric equation of a circle
Python3
# Program to plot a Circle# using Parametric equation of a Circle import numpy as npimport matplotlib.pyplot as plt theta = np.linspace( 0 , 2 * np.pi , 150 ) radius = 0.4 a = radius * np.cos( theta )b = radius * np.sin( theta ) figure, axes = plt.subplots( 1 ) axes.plot( a, b )axes.set_aspect( 1 ) plt.title( 'Parametric Equation Circle' )plt.show()
Output:
Example 2: Using Center-Radius form of a circle equation
Python3
# Program to plot a Circle# using Center-Radius form of circle equation import numpy as npimport matplotlib.pyplot as plt x = np.linspace( -0.7 , 0.7 , 150 )y = np.linspace( -0.7 , 0.7 , 150 ) a, b = np.meshgrid( x , y ) C = a ** 2 + b ** 2 - 0.2 figure, axes = plt.subplots() axes.contour( a , b , C , [0] )axes.set_aspect( 1 ) plt.title( 'Center-Radius form Circle' )plt.show()
Output:
Method 3: Using the Scatter Plot of points
Example:
Python3
# Program to plot a Circle# using Scatter plot of points import matplotlib.pyplot as plt plt.scatter( 0 , 0 , s = 7000 )plt.title( 'Circle' ) plt.xlim( -0.85 , 0.85 )plt.ylim( -0.95 , 0.95 ) plt.title( "Scatter plot of points Circle" )plt.show()
Output:
simmytarika5
Python-matplotlib
Technical Scripter 2020
Python
Technical Scripter
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": 25887,
"s": 25859,
"text": "\n13 Sep, 2021"
},
{
"code": null,
"e": 26139,
"s": 25887,
"text": "A Circle is a mathematical figure formed by joining all points lying on the same plane and are at equal distance from a given point. We can plot a circle in python using Matplotlib. There are multiple ways to plot a Circle in python using Matplotlib. "
},
{
"code": null,
"e": 26193,
"s": 26139,
"text": "Method 1: Using matplotlib.patches.Circle() function."
},
{
"code": null,
"e": 26282,
"s": 26193,
"text": "Matplotlib has a special function matplotlib.patches.Circle() in order to plot circles. "
},
{
"code": null,
"e": 26346,
"s": 26282,
"text": "Syntax: class matplotlib.patches.Circle(xy, radius=5, **kwargs)"
},
{
"code": null,
"e": 26417,
"s": 26346,
"text": "Example 1: Plotting a colored Circle using matplotlib.patches.Circle()"
},
{
"code": null,
"e": 26425,
"s": 26417,
"text": "Python3"
},
{
"code": "# Demonstrating use of matplotlib.patches.Circle() function# to plot a colored Circle import matplotlib.pyplot as plt figure, axes = plt.subplots()Drawing_colored_circle = plt.Circle(( 0.6 , 0.6 ), 0.2 ) axes.set_aspect( 1 )axes.add_artist( Drawing_colored_circle )plt.title( 'Colored Circle' )plt.show()",
"e": 26730,
"s": 26425,
"text": null
},
{
"code": null,
"e": 26738,
"s": 26730,
"text": "Output:"
},
{
"code": null,
"e": 26813,
"s": 26738,
"text": "Example 2: Plotting an un-colored Circle using matplotlib.patches.Circle()"
},
{
"code": null,
"e": 26821,
"s": 26813,
"text": "Python3"
},
{
"code": "# Demonstrating use of matplotlib.patches.Circle() function# to plot an un-colored Circle import matplotlib.pyplot as plt figure, axes = plt.subplots()Drawing_uncolored_circle = plt.Circle( (0.6, 0.6 ), 0.3 , fill = False ) axes.set_aspect( 1 )axes.add_artist( Drawing_uncolored_circle )plt.title( 'Circle' )plt.show()",
"e": 27214,
"s": 26821,
"text": null
},
{
"code": null,
"e": 27222,
"s": 27214,
"text": "Output:"
},
{
"code": null,
"e": 27254,
"s": 27222,
"text": "Method 2: Using Circle Equation"
},
{
"code": null,
"e": 27321,
"s": 27254,
"text": "Example 1: Plotting a Circle using Parametric equation of a circle"
},
{
"code": null,
"e": 27329,
"s": 27321,
"text": "Python3"
},
{
"code": "# Program to plot a Circle# using Parametric equation of a Circle import numpy as npimport matplotlib.pyplot as plt theta = np.linspace( 0 , 2 * np.pi , 150 ) radius = 0.4 a = radius * np.cos( theta )b = radius * np.sin( theta ) figure, axes = plt.subplots( 1 ) axes.plot( a, b )axes.set_aspect( 1 ) plt.title( 'Parametric Equation Circle' )plt.show()",
"e": 27681,
"s": 27329,
"text": null
},
{
"code": null,
"e": 27689,
"s": 27681,
"text": "Output:"
},
{
"code": null,
"e": 27746,
"s": 27689,
"text": "Example 2: Using Center-Radius form of a circle equation"
},
{
"code": null,
"e": 27754,
"s": 27746,
"text": "Python3"
},
{
"code": "# Program to plot a Circle# using Center-Radius form of circle equation import numpy as npimport matplotlib.pyplot as plt x = np.linspace( -0.7 , 0.7 , 150 )y = np.linspace( -0.7 , 0.7 , 150 ) a, b = np.meshgrid( x , y ) C = a ** 2 + b ** 2 - 0.2 figure, axes = plt.subplots() axes.contour( a , b , C , [0] )axes.set_aspect( 1 ) plt.title( 'Center-Radius form Circle' )plt.show()",
"e": 28134,
"s": 27754,
"text": null
},
{
"code": null,
"e": 28142,
"s": 28134,
"text": "Output:"
},
{
"code": null,
"e": 28186,
"s": 28142,
"text": "Method 3: Using the Scatter Plot of points "
},
{
"code": null,
"e": 28195,
"s": 28186,
"text": "Example:"
},
{
"code": null,
"e": 28203,
"s": 28195,
"text": "Python3"
},
{
"code": "# Program to plot a Circle# using Scatter plot of points import matplotlib.pyplot as plt plt.scatter( 0 , 0 , s = 7000 )plt.title( 'Circle' ) plt.xlim( -0.85 , 0.85 )plt.ylim( -0.95 , 0.95 ) plt.title( \"Scatter plot of points Circle\" )plt.show()",
"e": 28449,
"s": 28203,
"text": null
},
{
"code": null,
"e": 28457,
"s": 28449,
"text": "Output:"
},
{
"code": null,
"e": 28470,
"s": 28457,
"text": "simmytarika5"
},
{
"code": null,
"e": 28488,
"s": 28470,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 28512,
"s": 28488,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 28519,
"s": 28512,
"text": "Python"
},
{
"code": null,
"e": 28538,
"s": 28519,
"text": "Technical Scripter"
},
{
"code": null,
"e": 28636,
"s": 28538,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28654,
"s": 28636,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28689,
"s": 28654,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 28721,
"s": 28689,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28743,
"s": 28721,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28785,
"s": 28743,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28815,
"s": 28785,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 28841,
"s": 28815,
"text": "Python String | replace()"
},
{
"code": null,
"e": 28870,
"s": 28841,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 28914,
"s": 28870,
"text": "Reading and Writing to text files in Python"
}
] |
Alpha and Beta test - GeeksforGeeks
|
26 Nov, 2020
In the previous article, we discussed hypothesis testing which is the backbone of inferential statistics. We previously discussed the basic hypothesis testing including Null and Alternate Hypothesis, z-test, etc. Now, in this discussed more Type I and Type II error, level of significance (alpha), and Power(beta).
The p-value is defined as the probability of obtaining a result or more extreme than what was actually observed in the normal distribution. Generally, we take the level of significance=0.05, it means if the observed p-value is less than the level -of-significance then, we reject the null hypothesis.
To calculate the p-value, we need the table particular test statistics (t-test, z-test, f-test) and whether it is a one-tailed, two-tailed test.
p-value
Type I Error
Correct decision
Correct decision
Type II error
Type I Error (Alpha): Now, if we reject the null hypothesis based on the level of significance p-value calculations, there is a possibility that the samples, in reality, belong to the same (null) distribution, and we incorrectly rejected it, this is called Type I error and it is denoted by alpha
Type II Error (Beta): Now, on the basis of the level of significance and p-value, if we accept a sample that does not really belong to the same distribution then, it is referred to as Type II error
Confidence Interval: The confidence interval is the region in which is we can confidently reject the null hypothesis. It is calculated by subtracting alpha and 1
Power: Power is the probability of correctly rejecting the null hypothesis and accepting the Alternative Hypothesis (HA). Power can be calculated by subtracting beta from 1.
The higher the power makes lower the probability of making a Type II error. Lower power means a higher risk of performing a Type II error and vice-versa. Generally, 0.80 power is considered good enough. Power is also dependent on the following factors:
Effect size: Effect size is simply the way of measuring the strength of the relationship between two variables. There are many ways of calculating effect sizes such as Pearson correlations for calculating correlations between two variables, Cohen’s d test for measuring the difference between groups, or simply by calculating the difference between means of different groups.
Sample Size: The number of observations that are included in the statistical sample.
Significance: Level of significance used in the test (alpha).
Steps to Perform Power Analysis
State the Null Hypothesis (H0) and Alternative Hypothesis (HA).
State the alpha risk level (level of significance).
Choose the appropriate statistical test.
Decide the Effect size.
Create sampling plans and determine the sample size. After that gather the sample.
Calculate the test statistic by determining the p-value.If p-value < alpha, then we reject the null hypothesis.
If p-value < alpha, then we reject the null hypothesis.
Repeat the above steps a few times.
Special diet distribution vs Normal diet distribution
Suppose there is two distribution representing the weights of two groups of people, the left representing people on diet and right representing people who take normal food.
We take some samples from both the distribution and calculate their means.
Here, our null hypothesis will be both samples are from the same distribution (no effect of diet plan) and the alternate hypothesis will be that both samples are from a different distribution.
Now, we calculate the p-value from these samples.
If our p-value is smaller than the level of significance then we correctly reject the null hypothesis that both these samples are from the same distribution.
else, we don’t reject the null hypothesis.
Now, we repeat the above steps numerous times (i.e 1000, 10000), etc. and we calculate the probability of correctly rejecting the null hypothesis i.e. Power.
Python3
# Necessary Importsimport numpy as npfrom statsmodels.stats.power import TTestIndPowerimport matplotlib.pyplot as plt # here effect size is taken as (u1-u2) /sdeffect_size = (60-50)/10alpha = 0.05samples =20p_analysis = TTestIndPower()power = p_analysis.solve_power(effect_size=effect_size, alpha=alpha, nobs1 = samples, ratio =1)print("Power is ",power)
0.8689530131730794
Engineering Mathematics
Machine Learning
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between Propositional Logic and Predicate Logic
Complement of Graph
Introduction of Statistics and its Types
Multivariate Optimization and its Types - Data Science
Secant Method of Numerical analysis
Naive Bayes Classifiers
Linear Regression (Python Implementation)
ML | Linear Regression
Reinforcement learning
Removing stop words with NLTK in Python
|
[
{
"code": null,
"e": 26137,
"s": 26109,
"text": "\n26 Nov, 2020"
},
{
"code": null,
"e": 26452,
"s": 26137,
"text": "In the previous article, we discussed hypothesis testing which is the backbone of inferential statistics. We previously discussed the basic hypothesis testing including Null and Alternate Hypothesis, z-test, etc. Now, in this discussed more Type I and Type II error, level of significance (alpha), and Power(beta)."
},
{
"code": null,
"e": 26754,
"s": 26452,
"text": " The p-value is defined as the probability of obtaining a result or more extreme than what was actually observed in the normal distribution. Generally, we take the level of significance=0.05, it means if the observed p-value is less than the level -of-significance then, we reject the null hypothesis."
},
{
"code": null,
"e": 26899,
"s": 26754,
"text": "To calculate the p-value, we need the table particular test statistics (t-test, z-test, f-test) and whether it is a one-tailed, two-tailed test."
},
{
"code": null,
"e": 26907,
"s": 26899,
"text": "p-value"
},
{
"code": null,
"e": 26920,
"s": 26907,
"text": "Type I Error"
},
{
"code": null,
"e": 26937,
"s": 26920,
"text": "Correct decision"
},
{
"code": null,
"e": 26954,
"s": 26937,
"text": "Correct decision"
},
{
"code": null,
"e": 26968,
"s": 26954,
"text": "Type II error"
},
{
"code": null,
"e": 27265,
"s": 26968,
"text": "Type I Error (Alpha): Now, if we reject the null hypothesis based on the level of significance p-value calculations, there is a possibility that the samples, in reality, belong to the same (null) distribution, and we incorrectly rejected it, this is called Type I error and it is denoted by alpha"
},
{
"code": null,
"e": 27463,
"s": 27265,
"text": "Type II Error (Beta): Now, on the basis of the level of significance and p-value, if we accept a sample that does not really belong to the same distribution then, it is referred to as Type II error"
},
{
"code": null,
"e": 27625,
"s": 27463,
"text": "Confidence Interval: The confidence interval is the region in which is we can confidently reject the null hypothesis. It is calculated by subtracting alpha and 1"
},
{
"code": null,
"e": 27799,
"s": 27625,
"text": "Power: Power is the probability of correctly rejecting the null hypothesis and accepting the Alternative Hypothesis (HA). Power can be calculated by subtracting beta from 1."
},
{
"code": null,
"e": 28053,
"s": 27799,
"text": "The higher the power makes lower the probability of making a Type II error. Lower power means a higher risk of performing a Type II error and vice-versa. Generally, 0.80 power is considered good enough. Power is also dependent on the following factors: "
},
{
"code": null,
"e": 28429,
"s": 28053,
"text": "Effect size: Effect size is simply the way of measuring the strength of the relationship between two variables. There are many ways of calculating effect sizes such as Pearson correlations for calculating correlations between two variables, Cohen’s d test for measuring the difference between groups, or simply by calculating the difference between means of different groups."
},
{
"code": null,
"e": 28514,
"s": 28429,
"text": "Sample Size: The number of observations that are included in the statistical sample."
},
{
"code": null,
"e": 28576,
"s": 28514,
"text": "Significance: Level of significance used in the test (alpha)."
},
{
"code": null,
"e": 28608,
"s": 28576,
"text": "Steps to Perform Power Analysis"
},
{
"code": null,
"e": 28672,
"s": 28608,
"text": "State the Null Hypothesis (H0) and Alternative Hypothesis (HA)."
},
{
"code": null,
"e": 28724,
"s": 28672,
"text": "State the alpha risk level (level of significance)."
},
{
"code": null,
"e": 28765,
"s": 28724,
"text": "Choose the appropriate statistical test."
},
{
"code": null,
"e": 28789,
"s": 28765,
"text": "Decide the Effect size."
},
{
"code": null,
"e": 28872,
"s": 28789,
"text": "Create sampling plans and determine the sample size. After that gather the sample."
},
{
"code": null,
"e": 28984,
"s": 28872,
"text": "Calculate the test statistic by determining the p-value.If p-value < alpha, then we reject the null hypothesis."
},
{
"code": null,
"e": 29040,
"s": 28984,
"text": "If p-value < alpha, then we reject the null hypothesis."
},
{
"code": null,
"e": 29076,
"s": 29040,
"text": "Repeat the above steps a few times."
},
{
"code": null,
"e": 29130,
"s": 29076,
"text": "Special diet distribution vs Normal diet distribution"
},
{
"code": null,
"e": 29303,
"s": 29130,
"text": "Suppose there is two distribution representing the weights of two groups of people, the left representing people on diet and right representing people who take normal food."
},
{
"code": null,
"e": 29378,
"s": 29303,
"text": "We take some samples from both the distribution and calculate their means."
},
{
"code": null,
"e": 29571,
"s": 29378,
"text": "Here, our null hypothesis will be both samples are from the same distribution (no effect of diet plan) and the alternate hypothesis will be that both samples are from a different distribution."
},
{
"code": null,
"e": 29621,
"s": 29571,
"text": "Now, we calculate the p-value from these samples."
},
{
"code": null,
"e": 29779,
"s": 29621,
"text": "If our p-value is smaller than the level of significance then we correctly reject the null hypothesis that both these samples are from the same distribution."
},
{
"code": null,
"e": 29822,
"s": 29779,
"text": "else, we don’t reject the null hypothesis."
},
{
"code": null,
"e": 29980,
"s": 29822,
"text": "Now, we repeat the above steps numerous times (i.e 1000, 10000), etc. and we calculate the probability of correctly rejecting the null hypothesis i.e. Power."
},
{
"code": null,
"e": 29988,
"s": 29980,
"text": "Python3"
},
{
"code": "# Necessary Importsimport numpy as npfrom statsmodels.stats.power import TTestIndPowerimport matplotlib.pyplot as plt # here effect size is taken as (u1-u2) /sdeffect_size = (60-50)/10alpha = 0.05samples =20p_analysis = TTestIndPower()power = p_analysis.solve_power(effect_size=effect_size, alpha=alpha, nobs1 = samples, ratio =1)print(\"Power is \",power)",
"e": 30344,
"s": 29988,
"text": null
},
{
"code": null,
"e": 30364,
"s": 30344,
"text": "0.8689530131730794\n"
},
{
"code": null,
"e": 30388,
"s": 30364,
"text": "Engineering Mathematics"
},
{
"code": null,
"e": 30405,
"s": 30388,
"text": "Machine Learning"
},
{
"code": null,
"e": 30422,
"s": 30405,
"text": "Machine Learning"
},
{
"code": null,
"e": 30520,
"s": 30422,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30579,
"s": 30520,
"text": "Difference between Propositional Logic and Predicate Logic"
},
{
"code": null,
"e": 30599,
"s": 30579,
"text": "Complement of Graph"
},
{
"code": null,
"e": 30640,
"s": 30599,
"text": "Introduction of Statistics and its Types"
},
{
"code": null,
"e": 30695,
"s": 30640,
"text": "Multivariate Optimization and its Types - Data Science"
},
{
"code": null,
"e": 30731,
"s": 30695,
"text": "Secant Method of Numerical analysis"
},
{
"code": null,
"e": 30755,
"s": 30731,
"text": "Naive Bayes Classifiers"
},
{
"code": null,
"e": 30797,
"s": 30755,
"text": "Linear Regression (Python Implementation)"
},
{
"code": null,
"e": 30820,
"s": 30797,
"text": "ML | Linear Regression"
},
{
"code": null,
"e": 30843,
"s": 30820,
"text": "Reinforcement learning"
}
] |
Python-Tkinter Treeview scrollbar - GeeksforGeeks
|
15 Oct, 2021
Python has several options for constructing GUI and python tkinter is one of them. It is the standard GUI library for Python, which helps in making GUI applications easily. It provides an efficient object-oriented interface to the tk GUI toolkit. It also has multiple controls called widgets like text boxes, scrollbars, buttons, etc. Moreover, Tkinter has some geometry management methods namely, pack(), grid(), and, place() which are helpful in organizing widgets.Note: For more information, refer to Python GUI – tkinter
When a scrollbar uses treeview widgets, then that type of scrollbar is called as treeview scrollbar. Where, a treeview widget is helpful in displaying more than one feature of every item listed in the tree to the right side of the tree in the form of columns. However, it can be implemented using tkinter in python with the help of some widgets and geometry management methods as supported by tkinter. Below example illustrates the usage of Treeview Scrollbar using Python-tkinter: Example 1:
Python
# Python program to illustrate the usage of# treeview scrollbars using tkinter from tkinter import ttkimport tkinter as tk # Creating tkinter windowwindow = tk.Tk()window.resizable(width = 1, height = 1) # Using treeview widgettreev = ttk.Treeview(window, selectmode ='browse') # Calling pack method w.r.to treeviewtreev.pack(side ='right') # Constructing vertical scrollbar# with treeviewverscrlbar = ttk.Scrollbar(window, orient ="vertical", command = treev.yview) # Calling pack method w.r.to vertical# scrollbarverscrlbar.pack(side ='right', fill ='x') # Configuring treeviewtreev.configure(xscrollcommand = verscrlbar.set) # Defining number of columnstreev["columns"] = ("1", "2", "3") # Defining headingtreev['show'] = 'headings' # Assigning the width and anchor to the# respective columnstreev.column("1", width = 90, anchor ='c')treev.column("2", width = 90, anchor ='se')treev.column("3", width = 90, anchor ='se') # Assigning the heading names to the# respective columnstreev.heading("1", text ="Name")treev.heading("2", text ="Sex")treev.heading("3", text ="Age") # Inserting the items and their features to the# columns builttreev.insert("", 'end', text ="L1", values =("Nidhi", "F", "25"))treev.insert("", 'end', text ="L2", values =("Nisha", "F", "23"))treev.insert("", 'end', text ="L3", values =("Preeti", "F", "27"))treev.insert("", 'end', text ="L4", values =("Rahul", "M", "20"))treev.insert("", 'end', text ="L5", values =("Sonu", "F", "18"))treev.insert("", 'end', text ="L6", values =("Rohit", "M", "19"))treev.insert("", 'end', text ="L7", values =("Geeta", "F", "25"))treev.insert("", 'end', text ="L8", values =("Ankit", "M", "22"))treev.insert("", 'end', text ="L10", values =("Mukul", "F", "25"))treev.insert("", 'end', text ="L11", values =("Mohit", "M", "16"))treev.insert("", 'end', text ="L12", values =("Vivek", "M", "22"))treev.insert("", 'end', text ="L13", values =("Suman", "F", "30")) # Calling mainloopwindow.mainloop()
Output:
In the above program, we have used pack() method of the geometry management methods. And, we have constructed only vertical scrollbar as per the requirement of the code but you can construct both the bars as per your requirements. Moreover, anchors are used here in order to define the positions of the text. However, you can also use other geometry management methods in order to construct the treeview scrollbar.
surindertarika1234
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
|
[
{
"code": null,
"e": 42676,
"s": 42648,
"text": "\n15 Oct, 2021"
},
{
"code": null,
"e": 43202,
"s": 42676,
"text": "Python has several options for constructing GUI and python tkinter is one of them. It is the standard GUI library for Python, which helps in making GUI applications easily. It provides an efficient object-oriented interface to the tk GUI toolkit. It also has multiple controls called widgets like text boxes, scrollbars, buttons, etc. Moreover, Tkinter has some geometry management methods namely, pack(), grid(), and, place() which are helpful in organizing widgets.Note: For more information, refer to Python GUI – tkinter "
},
{
"code": null,
"e": 43697,
"s": 43202,
"text": "When a scrollbar uses treeview widgets, then that type of scrollbar is called as treeview scrollbar. Where, a treeview widget is helpful in displaying more than one feature of every item listed in the tree to the right side of the tree in the form of columns. However, it can be implemented using tkinter in python with the help of some widgets and geometry management methods as supported by tkinter. Below example illustrates the usage of Treeview Scrollbar using Python-tkinter: Example 1: "
},
{
"code": null,
"e": 43704,
"s": 43697,
"text": "Python"
},
{
"code": "# Python program to illustrate the usage of# treeview scrollbars using tkinter from tkinter import ttkimport tkinter as tk # Creating tkinter windowwindow = tk.Tk()window.resizable(width = 1, height = 1) # Using treeview widgettreev = ttk.Treeview(window, selectmode ='browse') # Calling pack method w.r.to treeviewtreev.pack(side ='right') # Constructing vertical scrollbar# with treeviewverscrlbar = ttk.Scrollbar(window, orient =\"vertical\", command = treev.yview) # Calling pack method w.r.to vertical# scrollbarverscrlbar.pack(side ='right', fill ='x') # Configuring treeviewtreev.configure(xscrollcommand = verscrlbar.set) # Defining number of columnstreev[\"columns\"] = (\"1\", \"2\", \"3\") # Defining headingtreev['show'] = 'headings' # Assigning the width and anchor to the# respective columnstreev.column(\"1\", width = 90, anchor ='c')treev.column(\"2\", width = 90, anchor ='se')treev.column(\"3\", width = 90, anchor ='se') # Assigning the heading names to the# respective columnstreev.heading(\"1\", text =\"Name\")treev.heading(\"2\", text =\"Sex\")treev.heading(\"3\", text =\"Age\") # Inserting the items and their features to the# columns builttreev.insert(\"\", 'end', text =\"L1\", values =(\"Nidhi\", \"F\", \"25\"))treev.insert(\"\", 'end', text =\"L2\", values =(\"Nisha\", \"F\", \"23\"))treev.insert(\"\", 'end', text =\"L3\", values =(\"Preeti\", \"F\", \"27\"))treev.insert(\"\", 'end', text =\"L4\", values =(\"Rahul\", \"M\", \"20\"))treev.insert(\"\", 'end', text =\"L5\", values =(\"Sonu\", \"F\", \"18\"))treev.insert(\"\", 'end', text =\"L6\", values =(\"Rohit\", \"M\", \"19\"))treev.insert(\"\", 'end', text =\"L7\", values =(\"Geeta\", \"F\", \"25\"))treev.insert(\"\", 'end', text =\"L8\", values =(\"Ankit\", \"M\", \"22\"))treev.insert(\"\", 'end', text =\"L10\", values =(\"Mukul\", \"F\", \"25\"))treev.insert(\"\", 'end', text =\"L11\", values =(\"Mohit\", \"M\", \"16\"))treev.insert(\"\", 'end', text =\"L12\", values =(\"Vivek\", \"M\", \"22\"))treev.insert(\"\", 'end', text =\"L13\", values =(\"Suman\", \"F\", \"30\")) # Calling mainloopwindow.mainloop()",
"e": 45860,
"s": 43704,
"text": null
},
{
"code": null,
"e": 45869,
"s": 45860,
"text": "Output: "
},
{
"code": null,
"e": 46285,
"s": 45869,
"text": "In the above program, we have used pack() method of the geometry management methods. And, we have constructed only vertical scrollbar as per the requirement of the code but you can construct both the bars as per your requirements. Moreover, anchors are used here in order to define the positions of the text. However, you can also use other geometry management methods in order to construct the treeview scrollbar. "
},
{
"code": null,
"e": 46304,
"s": 46285,
"text": "surindertarika1234"
},
{
"code": null,
"e": 46319,
"s": 46304,
"text": "Python-tkinter"
},
{
"code": null,
"e": 46326,
"s": 46319,
"text": "Python"
},
{
"code": null,
"e": 46424,
"s": 46326,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 46452,
"s": 46424,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 46502,
"s": 46452,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 46524,
"s": 46502,
"text": "Python map() function"
},
{
"code": null,
"e": 46568,
"s": 46524,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 46603,
"s": 46568,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 46635,
"s": 46603,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 46657,
"s": 46635,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 46699,
"s": 46657,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 46729,
"s": 46699,
"text": "Iterate over a list in Python"
}
] |
User Login in Android using Back4App - GeeksforGeeks
|
06 Nov, 2021
We have seen implementing User Registration in Android using Back4App. In that article, we have implemented User Registration in our App. In this article, we will take a look at the implementation of User Login in our Android App.
We will be building a simple application in which we will be displaying a user login form in Android App and using this login form we will allow our user to login inside our application. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language.
This article is the continuation of User Registration in Android using Back4App.
Step 1: Working with the activity_main.xml file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><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"> <!--text view for heading--> <TextView android:id="@+id/idTVHeader" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="30dp" android:gravity="center_horizontal" android:padding="5dp" android:text="Welcome to Geeks for Geeks \n Login Form" android:textAlignment="center" android:textColor="@color/purple_700" android:textSize="18sp" /> <!--edit text for user name--> <EditText android:id="@+id/idEdtUserName" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/idTVHeader" android:layout_marginStart="10dp" android:layout_marginTop="50dp" android:layout_marginEnd="10dp" android:hint="Enter UserName" android:inputType="textEmailAddress" /> <!--edit text for user password--> <EditText android:id="@+id/idEdtPassword" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/idEdtUserName" android:layout_marginStart="10dp" android:layout_marginTop="20dp" android:layout_marginEnd="10dp" android:hint="Enter Password" android:inputType="textPassword" /> <!--button to register our new user--> <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="20dp" android:layout_marginEnd="10dp" android:text="Login" android:textAllCaps="false" /> </RelativeLayout>
Step 2: Creating a new activity to redirect our user after registration
Navigate to the app > java > your app’s package name > Right-click on it > New > Empty Activity and name it as HomeActivity. or you may also refer to this article How to Create New Activity in Android Studio?
Step 3: Working with the activity_home.xml file
Navigate to the app > res > layout > activity_home.xml file and add the below code to it.
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=".HomeActivity"> <!--text view for displaying heading--> <TextView android:id="@+id/idTVHeader" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerInParent="true" android:gravity="center_horizontal" android:text="Welcome back again to Geeks for Geeks" android:textAlignment="center" android:textColor="@color/purple_700" android:textSize="18sp" /> <!--text view for displaying user name--> <TextView android:id="@+id/idTVUserName" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/idTVHeader" android:layout_centerInParent="true" android:layout_marginTop="20dp" android:gravity="center_horizontal" android:text="UserName" android:textAlignment="center" android:textColor="@color/purple_700" android:textSize="25sp" /> <!--button for making user log out--> <Button android:id="@+id/idBtnLogout" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/idTVUserName" android:layout_centerInParent="true" android:layout_marginTop="10dp" android:text="LogOut" android:textAllCaps="false" /> </RelativeLayout>
Step 4: Working with the HomeActivity.java file
Navigate to the app > java > your app’s package name > HomeActivity.java file and add the below code to it. Comments are added inside the code to understand the code in more detail.
Java
import android.content.Intent;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.TextView;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import com.parse.ParseUser; public class HomeActivity extends AppCompatActivity { // creating a variable // for our text view.. private TextView userNameTV; // button for logout private Button logoutBtn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_home); logoutBtn = findViewById(R.id.idBtnLogout); // initializing our variables userNameTV = findViewById(R.id.idTVUserName); // getting data from intent. String name = getIntent().getStringExtra("username"); // setting data to our text view. userNameTV.setText(name); // initializing click listener for logout button logoutBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // calling a method to logout our user. ParseUser.logOutInBackground(e -> { if (e == null) { Toast.makeText(HomeActivity.this, "User Logged Out", Toast.LENGTH_SHORT).show(); Intent i = new Intent(HomeActivity.this, MainActivity.class); startActivity(i); finish(); } }); } }); }}
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.Intent;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; import com.parse.ParseUser; public class MainActivity extends AppCompatActivity { // creating variables for our edit text and buttons. private EditText userNameEdt, passwordEdt; private Button loginBtn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initializing our edit text and buttons. userNameEdt = findViewById(R.id.idEdtUserName); passwordEdt = findViewById(R.id.idEdtPassword); loginBtn = findViewById(R.id.idBtnLogin); // adding on click listener for our button. loginBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // on below line we are getting data from our edit text. String userName = userNameEdt.getText().toString(); String password = passwordEdt.getText().toString(); // checking if the entered text is empty or not. if (TextUtils.isEmpty(userName) && TextUtils.isEmpty(password)) { Toast.makeText(MainActivity.this, "Please enter user name and password", Toast.LENGTH_SHORT).show(); } // calling a method to login our user. loginUser(userName, password); } }); } private void loginUser(String userName, String password) { // calling a method to login a user. ParseUser.logInInBackground(userName, password, (parseUser, e) -> { // after login checking if the user is null or not. if (parseUser != null) { // if the user is not null then we will display a toast message // with user login and passing that user to new activity. Toast.makeText(this, "Login Successful ", Toast.LENGTH_SHORT).show(); Intent i = new Intent(MainActivity.this, HomeActivity.class); i.putExtra("username", userName); startActivity(i); } else { // display an toast message when user logout of the app. ParseUser.logOut(); Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_LONG).show(); } }); }}
Now run your app and see the output of the app:
Output:
Check out the project on the below link: https://github.com/ChaitanyaMunje/GFG-Back4App/tree/LoginForm
kalrap615
Android
Java
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Create and Add Data to SQLite Database in Android?
Broadcast Receiver in Android With Example
Resource Raw Folder in Android Studio
Services in Android with Example
Android RecyclerView in Kotlin
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
|
[
{
"code": null,
"e": 25755,
"s": 25727,
"text": "\n06 Nov, 2021"
},
{
"code": null,
"e": 25987,
"s": 25755,
"text": "We have seen implementing User Registration in Android using Back4App. In that article, we have implemented User Registration in our App. In this article, we will take a look at the implementation of User Login in our Android App. "
},
{
"code": null,
"e": 26341,
"s": 25987,
"text": "We will be building a simple application in which we will be displaying a user login form in Android App and using this login form we will allow our user to login inside our application. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. "
},
{
"code": null,
"e": 26422,
"s": 26341,
"text": "This article is the continuation of User Registration in Android using Back4App."
},
{
"code": null,
"e": 26470,
"s": 26422,
"text": "Step 1: Working with the activity_main.xml file"
},
{
"code": null,
"e": 26613,
"s": 26470,
"text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. "
},
{
"code": null,
"e": 26617,
"s": 26613,
"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\"> <!--text view for heading--> <TextView android:id=\"@+id/idTVHeader\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"30dp\" android:gravity=\"center_horizontal\" android:padding=\"5dp\" android:text=\"Welcome to Geeks for Geeks \\n Login Form\" android:textAlignment=\"center\" android:textColor=\"@color/purple_700\" android:textSize=\"18sp\" /> <!--edit text for user name--> <EditText android:id=\"@+id/idEdtUserName\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/idTVHeader\" android:layout_marginStart=\"10dp\" android:layout_marginTop=\"50dp\" android:layout_marginEnd=\"10dp\" android:hint=\"Enter UserName\" android:inputType=\"textEmailAddress\" /> <!--edit text for user password--> <EditText android:id=\"@+id/idEdtPassword\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/idEdtUserName\" android:layout_marginStart=\"10dp\" android:layout_marginTop=\"20dp\" android:layout_marginEnd=\"10dp\" android:hint=\"Enter Password\" android:inputType=\"textPassword\" /> <!--button to register our new user--> <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=\"20dp\" android:layout_marginEnd=\"10dp\" android:text=\"Login\" android:textAllCaps=\"false\" /> </RelativeLayout>",
"e": 28631,
"s": 26617,
"text": null
},
{
"code": null,
"e": 28704,
"s": 28631,
"text": " Step 2: Creating a new activity to redirect our user after registration"
},
{
"code": null,
"e": 28913,
"s": 28704,
"text": "Navigate to the app > java > your app’s package name > Right-click on it > New > Empty Activity and name it as HomeActivity. or you may also refer to this article How to Create New Activity in Android Studio?"
},
{
"code": null,
"e": 28961,
"s": 28913,
"text": "Step 3: Working with the activity_home.xml file"
},
{
"code": null,
"e": 29053,
"s": 28961,
"text": "Navigate to the app > res > layout > activity_home.xml file and add the below code to it. "
},
{
"code": null,
"e": 29057,
"s": 29053,
"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=\".HomeActivity\"> <!--text view for displaying heading--> <TextView android:id=\"@+id/idTVHeader\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_centerInParent=\"true\" android:gravity=\"center_horizontal\" android:text=\"Welcome back again to Geeks for Geeks\" android:textAlignment=\"center\" android:textColor=\"@color/purple_700\" android:textSize=\"18sp\" /> <!--text view for displaying user name--> <TextView android:id=\"@+id/idTVUserName\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/idTVHeader\" android:layout_centerInParent=\"true\" android:layout_marginTop=\"20dp\" android:gravity=\"center_horizontal\" android:text=\"UserName\" android:textAlignment=\"center\" android:textColor=\"@color/purple_700\" android:textSize=\"25sp\" /> <!--button for making user log out--> <Button android:id=\"@+id/idBtnLogout\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/idTVUserName\" android:layout_centerInParent=\"true\" android:layout_marginTop=\"10dp\" android:text=\"LogOut\" android:textAllCaps=\"false\" /> </RelativeLayout>",
"e": 30687,
"s": 29057,
"text": null
},
{
"code": null,
"e": 30736,
"s": 30687,
"text": " Step 4: Working with the HomeActivity.java file"
},
{
"code": null,
"e": 30919,
"s": 30736,
"text": "Navigate to the app > java > your app’s package name > HomeActivity.java file and add the below code to it. Comments are added inside the code to understand the code in more detail. "
},
{
"code": null,
"e": 30924,
"s": 30919,
"text": "Java"
},
{
"code": "import android.content.Intent;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.TextView;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import com.parse.ParseUser; public class HomeActivity extends AppCompatActivity { // creating a variable // for our text view.. private TextView userNameTV; // button for logout private Button logoutBtn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_home); logoutBtn = findViewById(R.id.idBtnLogout); // initializing our variables userNameTV = findViewById(R.id.idTVUserName); // getting data from intent. String name = getIntent().getStringExtra(\"username\"); // setting data to our text view. userNameTV.setText(name); // initializing click listener for logout button logoutBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // calling a method to logout our user. ParseUser.logOutInBackground(e -> { if (e == null) { Toast.makeText(HomeActivity.this, \"User Logged Out\", Toast.LENGTH_SHORT).show(); Intent i = new Intent(HomeActivity.this, MainActivity.class); startActivity(i); finish(); } }); } }); }}",
"e": 32532,
"s": 30924,
"text": null
},
{
"code": null,
"e": 32581,
"s": 32532,
"text": " Step 5: Working with the MainActivity.java file"
},
{
"code": null,
"e": 32772,
"s": 32581,
"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": 32777,
"s": 32772,
"text": "Java"
},
{
"code": "import android.content.Intent;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; import com.parse.ParseUser; public class MainActivity extends AppCompatActivity { // creating variables for our edit text and buttons. private EditText userNameEdt, passwordEdt; private Button loginBtn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initializing our edit text and buttons. userNameEdt = findViewById(R.id.idEdtUserName); passwordEdt = findViewById(R.id.idEdtPassword); loginBtn = findViewById(R.id.idBtnLogin); // adding on click listener for our button. loginBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // on below line we are getting data from our edit text. String userName = userNameEdt.getText().toString(); String password = passwordEdt.getText().toString(); // checking if the entered text is empty or not. if (TextUtils.isEmpty(userName) && TextUtils.isEmpty(password)) { Toast.makeText(MainActivity.this, \"Please enter user name and password\", Toast.LENGTH_SHORT).show(); } // calling a method to login our user. loginUser(userName, password); } }); } private void loginUser(String userName, String password) { // calling a method to login a user. ParseUser.logInInBackground(userName, password, (parseUser, e) -> { // after login checking if the user is null or not. if (parseUser != null) { // if the user is not null then we will display a toast message // with user login and passing that user to new activity. Toast.makeText(this, \"Login Successful \", Toast.LENGTH_SHORT).show(); Intent i = new Intent(MainActivity.this, HomeActivity.class); i.putExtra(\"username\", userName); startActivity(i); } else { // display an toast message when user logout of the app. ParseUser.logOut(); Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_LONG).show(); } }); }}",
"e": 35401,
"s": 32777,
"text": null
},
{
"code": null,
"e": 35450,
"s": 35401,
"text": " Now run your app and see the output of the app:"
},
{
"code": null,
"e": 35460,
"s": 35450,
"text": "Output: "
},
{
"code": null,
"e": 35563,
"s": 35460,
"text": "Check out the project on the below link: https://github.com/ChaitanyaMunje/GFG-Back4App/tree/LoginForm"
},
{
"code": null,
"e": 35575,
"s": 35565,
"text": "kalrap615"
},
{
"code": null,
"e": 35583,
"s": 35575,
"text": "Android"
},
{
"code": null,
"e": 35588,
"s": 35583,
"text": "Java"
},
{
"code": null,
"e": 35593,
"s": 35588,
"text": "Java"
},
{
"code": null,
"e": 35601,
"s": 35593,
"text": "Android"
},
{
"code": null,
"e": 35699,
"s": 35601,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35757,
"s": 35699,
"text": "How to Create and Add Data to SQLite Database in Android?"
},
{
"code": null,
"e": 35800,
"s": 35757,
"text": "Broadcast Receiver in Android With Example"
},
{
"code": null,
"e": 35838,
"s": 35800,
"text": "Resource Raw Folder in Android Studio"
},
{
"code": null,
"e": 35871,
"s": 35838,
"text": "Services in Android with Example"
},
{
"code": null,
"e": 35902,
"s": 35871,
"text": "Android RecyclerView in Kotlin"
},
{
"code": null,
"e": 35917,
"s": 35902,
"text": "Arrays in Java"
},
{
"code": null,
"e": 35961,
"s": 35917,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 35983,
"s": 35961,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 36034,
"s": 35983,
"text": "Object Oriented Programming (OOPs) Concept in Java"
}
] |
numpy.isnan() in Python - GeeksforGeeks
|
28 Mar, 2022
The numpy.isnan() function tests element-wise whether it is NaN or not and returns the result as a boolean array. Syntax :
numpy.isnan(array [, out])
Parameters :
array : [array_like]Input array or object whose elements, we need to test for infinity
out : [ndarray, optional]Output array placed with result.
Its type is preserved and it must be of the right shape to hold the output.
Return :
boolean array containing the result. For scalar input, the result is a new boolean with value
True if the input is positive or negative infinity; otherwise the value is False.
For array input, the result is a boolean array with the same shape as the input and the values
are True where the corresponding element of the input is positive or negative infinity;
elsewhere the values are False.
Code 1 :
Python
# Python Program illustrating# numpy.isnan() method import numpy as geek print("Is NaN : ", geek.isnan(1), "\n") print("Is NaN : ", geek.isnan(0), "\n") # not a numberprint("Is NaN : ", geek.isnan(geek.nan), "\n") # infinityprint("Is NaN : ", geek.isnan(geek.inf), "\n") print("Is NaN : ", geek.isnan(geek.NINF), "\n") x = geek.array([-geek.inf, 0., geek.inf])y = geek.array([2, 2, 2])print("Checking for NaN : ", geek.isnan(x, y))
Output :
Is NaN : False
Is NaN : False
Is NaN : True
Is NaN : False
Is NaN : False
Checking for NaN : [0 0 0]
Code 2 :
Python
# Python Program illustrating# numpy.isnan() method import numpy as geek # Returns True/False value for each elementb = geek.arange(20).reshape(5, 4) print("\n",b)print("\nIs NaN(Not a Number): \n", geek.isnan(b)) b = [[1j], [geek.nan]]print("\nIs NaN(Not a Number) : \n", geek.isnan(b))
Output :
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]
[12 13 14 15]
[16 17 18 19]]
Is NaN(Not a Number):
[[False False False False]
[False False False False]
[False False False False]
[False False False False]
[False False False False]]
Is NaN(Not a Number) :
[[False]
[ True]]
References : https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.isnan.html
Note : These codes won’t run on online IDE’s. So please, run them on your systems to explore the working.
This article is contributed by Mohit Gupta_OMG . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. 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.
Akanksha_Rai
vinayedula
Python numpy-Logic Functions
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Read a file line by line in Python
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
Reading and Writing to text files in Python
*args and **kwargs in Python
Convert integer to string in Python
|
[
{
"code": null,
"e": 26053,
"s": 26025,
"text": "\n28 Mar, 2022"
},
{
"code": null,
"e": 26177,
"s": 26053,
"text": "The numpy.isnan() function tests element-wise whether it is NaN or not and returns the result as a boolean array. Syntax : "
},
{
"code": null,
"e": 26204,
"s": 26177,
"text": "numpy.isnan(array [, out])"
},
{
"code": null,
"e": 26218,
"s": 26204,
"text": "Parameters : "
},
{
"code": null,
"e": 26447,
"s": 26218,
"text": "array : [array_like]Input array or object whose elements, we need to test for infinity\nout : [ndarray, optional]Output array placed with result.\n Its type is preserved and it must be of the right shape to hold the output."
},
{
"code": null,
"e": 26457,
"s": 26447,
"text": "Return : "
},
{
"code": null,
"e": 26849,
"s": 26457,
"text": "boolean array containing the result. For scalar input, the result is a new boolean with value\nTrue if the input is positive or negative infinity; otherwise the value is False.\nFor array input, the result is a boolean array with the same shape as the input and the values\nare True where the corresponding element of the input is positive or negative infinity; \nelsewhere the values are False."
},
{
"code": null,
"e": 26859,
"s": 26849,
"text": "Code 1 : "
},
{
"code": null,
"e": 26866,
"s": 26859,
"text": "Python"
},
{
"code": "# Python Program illustrating# numpy.isnan() method import numpy as geek print(\"Is NaN : \", geek.isnan(1), \"\\n\") print(\"Is NaN : \", geek.isnan(0), \"\\n\") # not a numberprint(\"Is NaN : \", geek.isnan(geek.nan), \"\\n\") # infinityprint(\"Is NaN : \", geek.isnan(geek.inf), \"\\n\") print(\"Is NaN : \", geek.isnan(geek.NINF), \"\\n\") x = geek.array([-geek.inf, 0., geek.inf])y = geek.array([2, 2, 2])print(\"Checking for NaN : \", geek.isnan(x, y))",
"e": 27300,
"s": 26866,
"text": null
},
{
"code": null,
"e": 27310,
"s": 27300,
"text": "Output : "
},
{
"code": null,
"e": 27427,
"s": 27310,
"text": "Is NaN : False \n\nIs NaN : False \n\nIs NaN : True \n\nIs NaN : False \n\nIs NaN : False \n\nChecking for NaN : [0 0 0]"
},
{
"code": null,
"e": 27437,
"s": 27427,
"text": "Code 2 : "
},
{
"code": null,
"e": 27444,
"s": 27437,
"text": "Python"
},
{
"code": "# Python Program illustrating# numpy.isnan() method import numpy as geek # Returns True/False value for each elementb = geek.arange(20).reshape(5, 4) print(\"\\n\",b)print(\"\\nIs NaN(Not a Number): \\n\", geek.isnan(b)) b = [[1j], [geek.nan]]print(\"\\nIs NaN(Not a Number) : \\n\", geek.isnan(b))",
"e": 27755,
"s": 27444,
"text": null
},
{
"code": null,
"e": 27765,
"s": 27755,
"text": "Output : "
},
{
"code": null,
"e": 28048,
"s": 27765,
"text": " [[ 0 1 2 3]\n [ 4 5 6 7]\n [ 8 9 10 11]\n [12 13 14 15]\n [16 17 18 19]]\n\nIs NaN(Not a Number): \n [[False False False False]\n [False False False False]\n [False False False False]\n [False False False False]\n [False False False False]]\n\nIs NaN(Not a Number) : \n [[False]\n [ True]]"
},
{
"code": null,
"e": 28136,
"s": 28048,
"text": "References : https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.isnan.html "
},
{
"code": null,
"e": 28242,
"s": 28136,
"text": "Note : These codes won’t run on online IDE’s. So please, run them on your systems to explore the working."
},
{
"code": null,
"e": 28667,
"s": 28242,
"text": "This article is contributed by Mohit Gupta_OMG . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. 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": 28680,
"s": 28667,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 28691,
"s": 28680,
"text": "vinayedula"
},
{
"code": null,
"e": 28720,
"s": 28691,
"text": "Python numpy-Logic Functions"
},
{
"code": null,
"e": 28733,
"s": 28720,
"text": "Python-numpy"
},
{
"code": null,
"e": 28740,
"s": 28733,
"text": "Python"
},
{
"code": null,
"e": 28838,
"s": 28740,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28856,
"s": 28838,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28888,
"s": 28856,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28923,
"s": 28888,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 28945,
"s": 28923,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28987,
"s": 28945,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 29017,
"s": 28987,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 29043,
"s": 29017,
"text": "Python String | replace()"
},
{
"code": null,
"e": 29087,
"s": 29043,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 29116,
"s": 29087,
"text": "*args and **kwargs in Python"
}
] |
NULL undeclared error in C/C++ and how to resolve it - GeeksforGeeks
|
21 Jun, 2020
What is undeclared Error:When we use some constant in our program may be they are built-in constant and may be created by a user according to the requirement. But when we use some constant and they are not built-in and also not defined by a user in that condition we get an undeclared error.
Below is the code that shows the example of NULL undeclared Error:
using namespace std; // Driver Codeint main(){ // NULL declared int* num = NULL; return 0;}
The above code will show an error as “NULL undeclared Error”. The reason for the NULL undeclared error is “NULL” is not a built-in constant.
Why do we need NULL?When we create some pointer in our program they are used to store addresses. But an uninitialized pointer variable is very dangerous so that we can assign them NULL which means they are not pointing to any memory location so our program runs smoothly and securely.Now if NULL is not built-in constant how we can overcome the NULL undeclared error.
Below are some code which is used to remove the NULL undeclared Error:
Assign 0: Instead of assigning NULL to num we can simply assign 0 which indicate that it is not pointing any address so the simplest solution is simply assigning 0.Below code shows it’s implementation:using namespace std; // Driver Codeint main(){ int* num = 0; return 0;}Include “stddef.h” Header file: In stddef.h header file NULL is already defined so we can include this header file in our program and our program will compile and execute without any error.Below code shows it’s implementation:#include <stddef.h> // Driver Codeint main(){ int* num = NULL; return 0;}Include iostream Header File: In C++ if we want to execute our program without NULL undeclered error we can simply include iostream in our program and make it happen without any error.Below code shows it’s implementation:#include <iostream>using namespace std; // Driver Codeint main(){ int* num = NULL; return 0;}#define NULL 0: Usingt #define NULL 0 line in our program we can solve the NULL undeclared error.Below code shows it’s implementation:#define NULL 0using namespace std; // Driver Codeint main(){ int* num = NULL; return 0;}In newer C++(C++11 and higher):: nullptr is a built-in constant so we can use it instead of using NULL.#include <iostream>using namespace std; // Driver Codeint main(){ int* num = nullptr; return 0;}My Personal Notes
arrow_drop_upSave
Assign 0: Instead of assigning NULL to num we can simply assign 0 which indicate that it is not pointing any address so the simplest solution is simply assigning 0.Below code shows it’s implementation:using namespace std; // Driver Codeint main(){ int* num = 0; return 0;}
using namespace std; // Driver Codeint main(){ int* num = 0; return 0;}
Include “stddef.h” Header file: In stddef.h header file NULL is already defined so we can include this header file in our program and our program will compile and execute without any error.Below code shows it’s implementation:#include <stddef.h> // Driver Codeint main(){ int* num = NULL; return 0;}
#include <stddef.h> // Driver Codeint main(){ int* num = NULL; return 0;}
Include iostream Header File: In C++ if we want to execute our program without NULL undeclered error we can simply include iostream in our program and make it happen without any error.Below code shows it’s implementation:#include <iostream>using namespace std; // Driver Codeint main(){ int* num = NULL; return 0;}
#include <iostream>using namespace std; // Driver Codeint main(){ int* num = NULL; return 0;}
#define NULL 0: Usingt #define NULL 0 line in our program we can solve the NULL undeclared error.Below code shows it’s implementation:#define NULL 0using namespace std; // Driver Codeint main(){ int* num = NULL; return 0;}
#define NULL 0using namespace std; // Driver Codeint main(){ int* num = NULL; return 0;}
In newer C++(C++11 and higher):: nullptr is a built-in constant so we can use it instead of using NULL.#include <iostream>using namespace std; // Driver Codeint main(){ int* num = nullptr; return 0;}My Personal Notes
arrow_drop_upSave
#include <iostream>using namespace std; // Driver Codeint main(){ int* num = nullptr; return 0;}
C++-Exception Handling
Articles
C Language
C Programs
C++
C++ Programs
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Time Complexity and Space Complexity
Docker - COPY Instruction
Time complexities of different data structures
Difference between Class and Object
SQL | Date functions
Arrays in C/C++
Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()
std::sort() in C++ STL
Bitwise Operators in C/C++
Substring in C++
|
[
{
"code": null,
"e": 25666,
"s": 25638,
"text": "\n21 Jun, 2020"
},
{
"code": null,
"e": 25958,
"s": 25666,
"text": "What is undeclared Error:When we use some constant in our program may be they are built-in constant and may be created by a user according to the requirement. But when we use some constant and they are not built-in and also not defined by a user in that condition we get an undeclared error."
},
{
"code": null,
"e": 26025,
"s": 25958,
"text": "Below is the code that shows the example of NULL undeclared Error:"
},
{
"code": "using namespace std; // Driver Codeint main(){ // NULL declared int* num = NULL; return 0;}",
"e": 26127,
"s": 26025,
"text": null
},
{
"code": null,
"e": 26268,
"s": 26127,
"text": "The above code will show an error as “NULL undeclared Error”. The reason for the NULL undeclared error is “NULL” is not a built-in constant."
},
{
"code": null,
"e": 26636,
"s": 26268,
"text": "Why do we need NULL?When we create some pointer in our program they are used to store addresses. But an uninitialized pointer variable is very dangerous so that we can assign them NULL which means they are not pointing to any memory location so our program runs smoothly and securely.Now if NULL is not built-in constant how we can overcome the NULL undeclared error."
},
{
"code": null,
"e": 26707,
"s": 26636,
"text": "Below are some code which is used to remove the NULL undeclared Error:"
},
{
"code": null,
"e": 28084,
"s": 26707,
"text": "Assign 0: Instead of assigning NULL to num we can simply assign 0 which indicate that it is not pointing any address so the simplest solution is simply assigning 0.Below code shows it’s implementation:using namespace std; // Driver Codeint main(){ int* num = 0; return 0;}Include “stddef.h” Header file: In stddef.h header file NULL is already defined so we can include this header file in our program and our program will compile and execute without any error.Below code shows it’s implementation:#include <stddef.h> // Driver Codeint main(){ int* num = NULL; return 0;}Include iostream Header File: In C++ if we want to execute our program without NULL undeclered error we can simply include iostream in our program and make it happen without any error.Below code shows it’s implementation:#include <iostream>using namespace std; // Driver Codeint main(){ int* num = NULL; return 0;}#define NULL 0: Usingt #define NULL 0 line in our program we can solve the NULL undeclared error.Below code shows it’s implementation:#define NULL 0using namespace std; // Driver Codeint main(){ int* num = NULL; return 0;}In newer C++(C++11 and higher):: nullptr is a built-in constant so we can use it instead of using NULL.#include <iostream>using namespace std; // Driver Codeint main(){ int* num = nullptr; return 0;}My Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 28364,
"s": 28084,
"text": "Assign 0: Instead of assigning NULL to num we can simply assign 0 which indicate that it is not pointing any address so the simplest solution is simply assigning 0.Below code shows it’s implementation:using namespace std; // Driver Codeint main(){ int* num = 0; return 0;}"
},
{
"code": "using namespace std; // Driver Codeint main(){ int* num = 0; return 0;}",
"e": 28443,
"s": 28364,
"text": null
},
{
"code": null,
"e": 28750,
"s": 28443,
"text": "Include “stddef.h” Header file: In stddef.h header file NULL is already defined so we can include this header file in our program and our program will compile and execute without any error.Below code shows it’s implementation:#include <stddef.h> // Driver Codeint main(){ int* num = NULL; return 0;}"
},
{
"code": "#include <stddef.h> // Driver Codeint main(){ int* num = NULL; return 0;}",
"e": 28831,
"s": 28750,
"text": null
},
{
"code": null,
"e": 29153,
"s": 28831,
"text": "Include iostream Header File: In C++ if we want to execute our program without NULL undeclered error we can simply include iostream in our program and make it happen without any error.Below code shows it’s implementation:#include <iostream>using namespace std; // Driver Codeint main(){ int* num = NULL; return 0;}"
},
{
"code": "#include <iostream>using namespace std; // Driver Codeint main(){ int* num = NULL; return 0;}",
"e": 29254,
"s": 29153,
"text": null
},
{
"code": null,
"e": 29484,
"s": 29254,
"text": "#define NULL 0: Usingt #define NULL 0 line in our program we can solve the NULL undeclared error.Below code shows it’s implementation:#define NULL 0using namespace std; // Driver Codeint main(){ int* num = NULL; return 0;}"
},
{
"code": "#define NULL 0using namespace std; // Driver Codeint main(){ int* num = NULL; return 0;}",
"e": 29580,
"s": 29484,
"text": null
},
{
"code": null,
"e": 29822,
"s": 29580,
"text": "In newer C++(C++11 and higher):: nullptr is a built-in constant so we can use it instead of using NULL.#include <iostream>using namespace std; // Driver Codeint main(){ int* num = nullptr; return 0;}My Personal Notes\narrow_drop_upSave"
},
{
"code": "#include <iostream>using namespace std; // Driver Codeint main(){ int* num = nullptr; return 0;}",
"e": 29926,
"s": 29822,
"text": null
},
{
"code": null,
"e": 29949,
"s": 29926,
"text": "C++-Exception Handling"
},
{
"code": null,
"e": 29958,
"s": 29949,
"text": "Articles"
},
{
"code": null,
"e": 29969,
"s": 29958,
"text": "C Language"
},
{
"code": null,
"e": 29980,
"s": 29969,
"text": "C Programs"
},
{
"code": null,
"e": 29984,
"s": 29980,
"text": "C++"
},
{
"code": null,
"e": 29997,
"s": 29984,
"text": "C++ Programs"
},
{
"code": null,
"e": 30001,
"s": 29997,
"text": "CPP"
},
{
"code": null,
"e": 30099,
"s": 30001,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30136,
"s": 30099,
"text": "Time Complexity and Space Complexity"
},
{
"code": null,
"e": 30162,
"s": 30136,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 30209,
"s": 30162,
"text": "Time complexities of different data structures"
},
{
"code": null,
"e": 30245,
"s": 30209,
"text": "Difference between Class and Object"
},
{
"code": null,
"e": 30266,
"s": 30245,
"text": "SQL | Date functions"
},
{
"code": null,
"e": 30282,
"s": 30266,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 30360,
"s": 30282,
"text": "Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()"
},
{
"code": null,
"e": 30383,
"s": 30360,
"text": "std::sort() in C++ STL"
},
{
"code": null,
"e": 30410,
"s": 30383,
"text": "Bitwise Operators in C/C++"
}
] |
Node.js dns.lookup() Method - GeeksforGeeks
|
13 Oct, 2021
The dns.lookup() method is an inbuilt application programming interface of the dns module which is used to resolve IP addresses of the specified hostname for given parameters into the first found A (IPv4) or AAAA (IPv6) record.
Syntax:
dns.lookup( hostname, options, callback )
Parameters: This method has three parameters as mentioned above and described below:
hostname: This parameter specifies a string which denotes the hostname to be checked.
options: It is in the form of an integer or an object. It specifies the options to be used during lookup.family: It is an integer value that specifies the family of the record. The value must be in 4, 6 or 0 where 0 indicates to return both IPv4 and IPv6 value, 4 indicates to return IPv4 and 6 indicates to return IPv6. Its default value is 0.hints: It is a number that specifies one or more getaddrinfo flag(s). More than one flags can be passed by doing bitwise OR of their values.all: It is a Boolean parameter. If it set to TRUE then callback returns all resolved address in an array otherwise it returns single address. Its default value is FALSE.verbatim: It is a Boolean parameter. If its value is set to TRUE then callback get all resolved IPv4 and IPv6 address as returned by DNS resolver unordered. If set to FALSE IPv4 addresses are placed before IPv6 addresses. Default value is FALSE now but expected to be TRUE in near future.
family: It is an integer value that specifies the family of the record. The value must be in 4, 6 or 0 where 0 indicates to return both IPv4 and IPv6 value, 4 indicates to return IPv4 and 6 indicates to return IPv6. Its default value is 0.hints: It is a number that specifies one or more getaddrinfo flag(s). More than one flags can be passed by doing bitwise OR of their values.all: It is a Boolean parameter. If it set to TRUE then callback returns all resolved address in an array otherwise it returns single address. Its default value is FALSE.verbatim: It is a Boolean parameter. If its value is set to TRUE then callback get all resolved IPv4 and IPv6 address as returned by DNS resolver unordered. If set to FALSE IPv4 addresses are placed before IPv6 addresses. Default value is FALSE now but expected to be TRUE in near future.
family: It is an integer value that specifies the family of the record. The value must be in 4, 6 or 0 where 0 indicates to return both IPv4 and IPv6 value, 4 indicates to return IPv4 and 6 indicates to return IPv6. Its default value is 0.
hints: It is a number that specifies one or more getaddrinfo flag(s). More than one flags can be passed by doing bitwise OR of their values.
all: It is a Boolean parameter. If it set to TRUE then callback returns all resolved address in an array otherwise it returns single address. Its default value is FALSE.
verbatim: It is a Boolean parameter. If its value is set to TRUE then callback get all resolved IPv4 and IPv6 address as returned by DNS resolver unordered. If set to FALSE IPv4 addresses are placed before IPv6 addresses. Default value is FALSE now but expected to be TRUE in near future.
callback: It specifies a function to be called after DNS resolution of the hostnames is done.error:It specifies error if generated. For example ‘ENOTFOUND’ is set if the hostname does not exist or the lookup fails.address: It is a string representation of IPv4 and IPv6 addresses.family: It is an integer value that specifies the family of the record. The value must be in 4, 6 or 0 where 0 indicates it’s not an IPv4 or IPv6 address. 0 is an indicator of fault in the name resolution service used by the operating system.Return Value: This method returns error, family of IP addresses and IP addresses through callback function. These data are passed as parameters to the callback function.Below examples illustrate the use of dns.lookup() method in Node.js:Example 1:// Node.js program to demonstrate the // dns.lookup() method // Accessing dns moduleconst dns = require('dns'); // Setting options for dns.lookup() methodconst options = { // Setting family as 6 i.e. IPv6 family: 6, hints: dns.ADDRCONFIG | dns.V4MAPPED,}; // Calling dns.lookup() for hostname geeksforgeeks.org// and displaying them in console as a callbackdns.lookup('geeksforgeeks.org', options, (err, address, family) => console.log('address: %j family: IPv%s', address, family));Output:address: "fd00:0:13:13::22da:3e74" family: IPv6
Example 2:// Node.js program to demonstrate the // dns.lookup() method // Accessing dns moduleconst dns = require('dns'); // Setting options for dns.lookup()// method, all as trueconst options = { all:true,}; // Calling dns.lookup() for hostname// geeksforgeeks.org and displaying// them in console as a callbackdns.lookup('geeksforgeeks.org', options, (err, addresses) => console.log('addresses: %j', addresses));Output:addresses: [
{"address":"34.218.62.116","family":4},
{"address":"fd00:0:13:13::22da:3e74","family":6}
]
Note: The above program will compile and run by using the node index.js command.Reference: https://nodejs.org/api/dns.html#dns_dns_lookup_hostname_options_callbackMy Personal Notes
arrow_drop_upSave
error:It specifies error if generated. For example ‘ENOTFOUND’ is set if the hostname does not exist or the lookup fails.address: It is a string representation of IPv4 and IPv6 addresses.family: It is an integer value that specifies the family of the record. The value must be in 4, 6 or 0 where 0 indicates it’s not an IPv4 or IPv6 address. 0 is an indicator of fault in the name resolution service used by the operating system.
error:It specifies error if generated. For example ‘ENOTFOUND’ is set if the hostname does not exist or the lookup fails.
address: It is a string representation of IPv4 and IPv6 addresses.
family: It is an integer value that specifies the family of the record. The value must be in 4, 6 or 0 where 0 indicates it’s not an IPv4 or IPv6 address. 0 is an indicator of fault in the name resolution service used by the operating system.
Return Value: This method returns error, family of IP addresses and IP addresses through callback function. These data are passed as parameters to the callback function.
Below examples illustrate the use of dns.lookup() method in Node.js:
Example 1:
// Node.js program to demonstrate the // dns.lookup() method // Accessing dns moduleconst dns = require('dns'); // Setting options for dns.lookup() methodconst options = { // Setting family as 6 i.e. IPv6 family: 6, hints: dns.ADDRCONFIG | dns.V4MAPPED,}; // Calling dns.lookup() for hostname geeksforgeeks.org// and displaying them in console as a callbackdns.lookup('geeksforgeeks.org', options, (err, address, family) => console.log('address: %j family: IPv%s', address, family));
Output:
address: "fd00:0:13:13::22da:3e74" family: IPv6
Example 2:
// Node.js program to demonstrate the // dns.lookup() method // Accessing dns moduleconst dns = require('dns'); // Setting options for dns.lookup()// method, all as trueconst options = { all:true,}; // Calling dns.lookup() for hostname// geeksforgeeks.org and displaying// them in console as a callbackdns.lookup('geeksforgeeks.org', options, (err, addresses) => console.log('addresses: %j', addresses));
Output:
addresses: [
{"address":"34.218.62.116","family":4},
{"address":"fd00:0:13:13::22da:3e74","family":6}
]
Note: The above program will compile and run by using the node index.js command.
Reference: https://nodejs.org/api/dns.html#dns_dns_lookup_hostname_options_callback
Node.js-dns-module
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
Node.js fs.readFileSync() Method
Node.js fs.writeFile() Method
How to update NPM ?
Difference between promise and async await in Node.js
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
|
[
{
"code": null,
"e": 38501,
"s": 38473,
"text": "\n13 Oct, 2021"
},
{
"code": null,
"e": 38729,
"s": 38501,
"text": "The dns.lookup() method is an inbuilt application programming interface of the dns module which is used to resolve IP addresses of the specified hostname for given parameters into the first found A (IPv4) or AAAA (IPv6) record."
},
{
"code": null,
"e": 38737,
"s": 38729,
"text": "Syntax:"
},
{
"code": null,
"e": 38779,
"s": 38737,
"text": "dns.lookup( hostname, options, callback )"
},
{
"code": null,
"e": 38864,
"s": 38779,
"text": "Parameters: This method has three parameters as mentioned above and described below:"
},
{
"code": null,
"e": 38950,
"s": 38864,
"text": "hostname: This parameter specifies a string which denotes the hostname to be checked."
},
{
"code": null,
"e": 39892,
"s": 38950,
"text": "options: It is in the form of an integer or an object. It specifies the options to be used during lookup.family: It is an integer value that specifies the family of the record. The value must be in 4, 6 or 0 where 0 indicates to return both IPv4 and IPv6 value, 4 indicates to return IPv4 and 6 indicates to return IPv6. Its default value is 0.hints: It is a number that specifies one or more getaddrinfo flag(s). More than one flags can be passed by doing bitwise OR of their values.all: It is a Boolean parameter. If it set to TRUE then callback returns all resolved address in an array otherwise it returns single address. Its default value is FALSE.verbatim: It is a Boolean parameter. If its value is set to TRUE then callback get all resolved IPv4 and IPv6 address as returned by DNS resolver unordered. If set to FALSE IPv4 addresses are placed before IPv6 addresses. Default value is FALSE now but expected to be TRUE in near future."
},
{
"code": null,
"e": 40729,
"s": 39892,
"text": "family: It is an integer value that specifies the family of the record. The value must be in 4, 6 or 0 where 0 indicates to return both IPv4 and IPv6 value, 4 indicates to return IPv4 and 6 indicates to return IPv6. Its default value is 0.hints: It is a number that specifies one or more getaddrinfo flag(s). More than one flags can be passed by doing bitwise OR of their values.all: It is a Boolean parameter. If it set to TRUE then callback returns all resolved address in an array otherwise it returns single address. Its default value is FALSE.verbatim: It is a Boolean parameter. If its value is set to TRUE then callback get all resolved IPv4 and IPv6 address as returned by DNS resolver unordered. If set to FALSE IPv4 addresses are placed before IPv6 addresses. Default value is FALSE now but expected to be TRUE in near future."
},
{
"code": null,
"e": 40969,
"s": 40729,
"text": "family: It is an integer value that specifies the family of the record. The value must be in 4, 6 or 0 where 0 indicates to return both IPv4 and IPv6 value, 4 indicates to return IPv4 and 6 indicates to return IPv6. Its default value is 0."
},
{
"code": null,
"e": 41110,
"s": 40969,
"text": "hints: It is a number that specifies one or more getaddrinfo flag(s). More than one flags can be passed by doing bitwise OR of their values."
},
{
"code": null,
"e": 41280,
"s": 41110,
"text": "all: It is a Boolean parameter. If it set to TRUE then callback returns all resolved address in an array otherwise it returns single address. Its default value is FALSE."
},
{
"code": null,
"e": 41569,
"s": 41280,
"text": "verbatim: It is a Boolean parameter. If its value is set to TRUE then callback get all resolved IPv4 and IPv6 address as returned by DNS resolver unordered. If set to FALSE IPv4 addresses are placed before IPv6 addresses. Default value is FALSE now but expected to be TRUE in near future."
},
{
"code": null,
"e": 43651,
"s": 41569,
"text": "callback: It specifies a function to be called after DNS resolution of the hostnames is done.error:It specifies error if generated. For example ‘ENOTFOUND’ is set if the hostname does not exist or the lookup fails.address: It is a string representation of IPv4 and IPv6 addresses.family: It is an integer value that specifies the family of the record. The value must be in 4, 6 or 0 where 0 indicates it’s not an IPv4 or IPv6 address. 0 is an indicator of fault in the name resolution service used by the operating system.Return Value: This method returns error, family of IP addresses and IP addresses through callback function. These data are passed as parameters to the callback function.Below examples illustrate the use of dns.lookup() method in Node.js:Example 1:// Node.js program to demonstrate the // dns.lookup() method // Accessing dns moduleconst dns = require('dns'); // Setting options for dns.lookup() methodconst options = { // Setting family as 6 i.e. IPv6 family: 6, hints: dns.ADDRCONFIG | dns.V4MAPPED,}; // Calling dns.lookup() for hostname geeksforgeeks.org// and displaying them in console as a callbackdns.lookup('geeksforgeeks.org', options, (err, address, family) => console.log('address: %j family: IPv%s', address, family));Output:address: \"fd00:0:13:13::22da:3e74\" family: IPv6\nExample 2:// Node.js program to demonstrate the // dns.lookup() method // Accessing dns moduleconst dns = require('dns'); // Setting options for dns.lookup()// method, all as trueconst options = { all:true,}; // Calling dns.lookup() for hostname// geeksforgeeks.org and displaying// them in console as a callbackdns.lookup('geeksforgeeks.org', options, (err, addresses) => console.log('addresses: %j', addresses));Output:addresses: [\n {\"address\":\"34.218.62.116\",\"family\":4},\n {\"address\":\"fd00:0:13:13::22da:3e74\",\"family\":6}\n]\nNote: The above program will compile and run by using the node index.js command.Reference: https://nodejs.org/api/dns.html#dns_dns_lookup_hostname_options_callbackMy Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 44081,
"s": 43651,
"text": "error:It specifies error if generated. For example ‘ENOTFOUND’ is set if the hostname does not exist or the lookup fails.address: It is a string representation of IPv4 and IPv6 addresses.family: It is an integer value that specifies the family of the record. The value must be in 4, 6 or 0 where 0 indicates it’s not an IPv4 or IPv6 address. 0 is an indicator of fault in the name resolution service used by the operating system."
},
{
"code": null,
"e": 44203,
"s": 44081,
"text": "error:It specifies error if generated. For example ‘ENOTFOUND’ is set if the hostname does not exist or the lookup fails."
},
{
"code": null,
"e": 44270,
"s": 44203,
"text": "address: It is a string representation of IPv4 and IPv6 addresses."
},
{
"code": null,
"e": 44513,
"s": 44270,
"text": "family: It is an integer value that specifies the family of the record. The value must be in 4, 6 or 0 where 0 indicates it’s not an IPv4 or IPv6 address. 0 is an indicator of fault in the name resolution service used by the operating system."
},
{
"code": null,
"e": 44683,
"s": 44513,
"text": "Return Value: This method returns error, family of IP addresses and IP addresses through callback function. These data are passed as parameters to the callback function."
},
{
"code": null,
"e": 44752,
"s": 44683,
"text": "Below examples illustrate the use of dns.lookup() method in Node.js:"
},
{
"code": null,
"e": 44763,
"s": 44752,
"text": "Example 1:"
},
{
"code": "// Node.js program to demonstrate the // dns.lookup() method // Accessing dns moduleconst dns = require('dns'); // Setting options for dns.lookup() methodconst options = { // Setting family as 6 i.e. IPv6 family: 6, hints: dns.ADDRCONFIG | dns.V4MAPPED,}; // Calling dns.lookup() for hostname geeksforgeeks.org// and displaying them in console as a callbackdns.lookup('geeksforgeeks.org', options, (err, address, family) => console.log('address: %j family: IPv%s', address, family));",
"e": 45274,
"s": 44763,
"text": null
},
{
"code": null,
"e": 45282,
"s": 45274,
"text": "Output:"
},
{
"code": null,
"e": 45331,
"s": 45282,
"text": "address: \"fd00:0:13:13::22da:3e74\" family: IPv6\n"
},
{
"code": null,
"e": 45342,
"s": 45331,
"text": "Example 2:"
},
{
"code": "// Node.js program to demonstrate the // dns.lookup() method // Accessing dns moduleconst dns = require('dns'); // Setting options for dns.lookup()// method, all as trueconst options = { all:true,}; // Calling dns.lookup() for hostname// geeksforgeeks.org and displaying// them in console as a callbackdns.lookup('geeksforgeeks.org', options, (err, addresses) => console.log('addresses: %j', addresses));",
"e": 45763,
"s": 45342,
"text": null
},
{
"code": null,
"e": 45771,
"s": 45763,
"text": "Output:"
},
{
"code": null,
"e": 45884,
"s": 45771,
"text": "addresses: [\n {\"address\":\"34.218.62.116\",\"family\":4},\n {\"address\":\"fd00:0:13:13::22da:3e74\",\"family\":6}\n]\n"
},
{
"code": null,
"e": 45965,
"s": 45884,
"text": "Note: The above program will compile and run by using the node index.js command."
},
{
"code": null,
"e": 46049,
"s": 45965,
"text": "Reference: https://nodejs.org/api/dns.html#dns_dns_lookup_hostname_options_callback"
},
{
"code": null,
"e": 46068,
"s": 46049,
"text": "Node.js-dns-module"
},
{
"code": null,
"e": 46076,
"s": 46068,
"text": "Node.js"
},
{
"code": null,
"e": 46093,
"s": 46076,
"text": "Web Technologies"
},
{
"code": null,
"e": 46191,
"s": 46093,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 46239,
"s": 46191,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 46272,
"s": 46239,
"text": "Node.js fs.readFileSync() Method"
},
{
"code": null,
"e": 46302,
"s": 46272,
"text": "Node.js fs.writeFile() Method"
},
{
"code": null,
"e": 46322,
"s": 46302,
"text": "How to update NPM ?"
},
{
"code": null,
"e": 46376,
"s": 46322,
"text": "Difference between promise and async await in Node.js"
},
{
"code": null,
"e": 46416,
"s": 46376,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 46461,
"s": 46416,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 46504,
"s": 46461,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 46554,
"s": 46504,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Implementing Dijkstra Algorithm | Practice | GeeksforGeeks
|
Given a weighted, undirected and connected graph of V vertices and E edges, Find the shortest distance of all the vertex's from the source vertex S.
Note: The Graph doesn't contain any negative weight cycle.
Example 1:
Input:
S = 0
Output:
0 9
Explanation:
The source vertex is 0. Hence, the shortest
distance of node 0 is 0 and the shortest
distance from node 9 is 9 - 0 = 9.
Example 2:
Input:
S = 2
Output:
4 3 0
Explanation:
For nodes 2 to 0, we can follow the path-
2-1-0. This has a distance of 1+3 = 4,
whereas the path 2-0 has a distance of 6. So,
the Shortest path from 2 to 0 is 4.
The other distances are pretty straight-forward.
Your Task:
You don't need to read input or print anything. Your task is to complete the function dijkstra() which takes number of vertices V and an adjacency list adj as input parameters and returns a list of integers, where ith integer denotes the shortest distance of the ith node from Source node. Here adj[i] contains a list of lists containing two integers where the first integer j denotes that there is an edge between i and j and second integer w denotes that the weight between edge i and j is w.
Expected Time Complexity: O(V2).
Expected Auxiliary Space: O(V2).
0
smdakhtar0071 day ago
// done using Stack data structure done in 0.09
class Solution
{
public:
//Function to find the shortest distance of all the vertices
//from the source vertex S.
vector <int> dijkstra(int V, vector<vector<int>> adj[], int S)
{
set<pair<int,int>>st;
vector<int> distance(V,INT_MAX);
distance[S] = 0 ;
st.insert({0,S});
while(!st.empty()){
pair<int,int>temp = *st.begin();
st.erase(st.begin());
int node = temp.second;
int nxt_dis = temp.first;
for(auto it : adj[node]){
if(distance[it[0]] > nxt_dis + it[1]){
distance[it[0]] = nxt_dis+it[1];
st.insert({distance[it[0]],it[0]});
}
}
}
return distance;
}
};
+1
aarushsrivastava5 days ago
vector <int> dijkstra(int V, vector<vector<int>> adj[], int S)
{
// Code here
priority_queue<pair<int,int>, vector<pair<int,int>>, greater<pair<int,int>>> q;
vector<int> dist(V, INT_MAX);
dist[S] = 0;
q.push({0, S});
while(!q.empty()){
int node = q.top().second;
int dis = q.top().first;
q.pop();
for(auto it : adj[node]){
int next = it[0];
int nextdis = it[1];
if(dis + nextdis < dist[next]){
dist[next] = dis + nextdis;
q.push({dist[next], next});
}
}
}
return dist;
}
0
amishasahu3281 week ago
vector<int> dijkstra(int V, vector<vector<int>> adj[], int S)
{
// Code here
// By default, C++ creates a max-heap for priority queue.
// // min-heap ; In pair => (dist,from)
priority_queue<pair<int,int>, vector<pair<int,int>>, greater<pair<int,int>>> pq;
vector<int> distance(V+1, INT_MAX);
distance[S] = 0;
pq.push({0,S});
while(!pq.empty())
{
int dis = pq.top().first;
int prev = pq.top().second;
pq.pop();
for(auto it: adj[prev])
{
if(distance[it[0]] > distance[prev]+it[1]){
distance[it[0]] = distance[prev]+it[1];
pq.push({distance[it[0]], it[0]});
}
}
}
return distance;
}
0
itsmemritu1 week ago
typedef pair<int, int> pii; vector <int> dijkstra(int V, vector<vector<int>> adj[], int S) { // Code here vector<int>ans(V,INT_MAX); priority_queue<pii,vector<pii>,greater<pii>>pq; vector<bool>visited(V,false); ans[S]=0; pq.push({0,S}); while(!pq.empty()){ int k=pq.top().second; int t=pq.top().first; pq.pop(); if(visited[k]){ continue; } visited[k]=true; for(auto it:adj[k]){ int weight=it[1]; int v=it[0]; if(ans[v]>ans[k]+weight){ ans[v]=ans[k]+weight; pq.push({ans[v],v}); } } } return ans; }
+1
pawananjanimth12 weeks ago
Solution using Set:
vector <int> dijkstra(int V, vector<vector<int>> adj[], int S)
{
// Code here
vector<int> dist(V+1,INT_MAX);
dist[S]=0;
set<pair<int,int>> st;
st.insert({S,0});
while(!st.empty())
{
pair<int,int> p = *(st.begin());
int node = p.first;
int node_dist = p.second;
st.erase(p);
for(auto v:adj[node])
{
if(node_dist+v[1]<dist[v[0]])
{
if(st.find({v[0],v[1]})!=st.end()) st.erase({v[0],v[1]});
dist[v[0]] = node_dist + v[1];
st.insert({v[0],dist[v[0]]});
}
}
}
return dist;
}
0
sknwd88643 weeks ago
vector <int> dijkstra(int V, vector<vector<int>> adj[], int S) { // Code here // dijkstra's algorithm using priority_queue vector<int> dist(V , INT_MAX); // distance array dist[S]=0; // in min heap , we Store weight & node weight first then node vector<bool> visited(V , false); priority_queue< pair<int , int> , vector<pair<int , int>> , greater< pair<int , int>>> pq; pq.push({0 , S}); while(!pq.empty()) { auto t= pq.top(); pq.pop(); // int w=t.first; int node=t.second; visited[node]=true; // traverse its adjacent for(int i=0;i<adj[node].size();i++) { int v=adj[node][i][0]; int w=adj[node][i][1]; if(visited[v]==false) { if(dist[v]>dist[node] + w ) { dist[v]=dist[node] + w; // value i.e distance is updated // it is not INT_MAX pq.push({dist[v] , v}); } } } } return dist; }
+1
devashishbakare3 weeks ago
Java Solution with explanation
class Solution
{
static class pair implements Comparable<pair>{
int ver;
int wt;
public pair(int n,int d)
{
this.wt=d;
this.ver=n;
}
public int compareTo(pair p)
{
return this.wt - p.wt;
}
}
//Function to find the shortest distance of all the vertices
//from the source vertex S.
static int[] dijkstra(int V, ArrayList<ArrayList<ArrayList<Integer>>> adj, int S)
{
// Write your code here
//create ans array and initised them as a infinity
int[] ans=new int[V];
Arrays.fill(ans,Integer.MAX_VALUE);
//source shortest length always zero
ans[S]=0;
PriorityQueue<pair> pq = new PriorityQueue<>();
//add first element with 0 as distance
pq.add(new pair(S,0));
while(pq.size()>0)
{
pair p = pq.poll();
//get the adjucent of all the pop vertex
for(ArrayList<Integer> x:adj.get(p.ver))
{
//if newly found path is smaller thean the previous path,
if( ans[p.ver] + x.get(1) < ans[x.get(0)] )
{
//then update the sortest path
ans[x.get(0)] = ans[p.ver]+x.get(1);
//add that element in priority queue for next element to move shotest weightt
//coz its greedy approtch
pq.add(new pair(x.get(0),ans[x.get(0)]));
}
}
}
//returning the final answer
return ans;
}
}
0
shivam26120023 weeks ago
vector <int> dijkstra(int V, vector<vector<int>> adj[], int S) { vector<int> dist(V,INT_MAX); dist[S]=0; queue<int> q; q.push(S); while(!q.empty()){ int node=q.front(); q.pop(); for(auto i:adj[node]) { if(dist[node]+i[1]<dist[i[0]]) { dist[i[0]]=dist[node]+i[1]; q.push(i[0]);} } } return dist; }
0
19bcs13143 weeks ago
my solution using priority queue using bfs
class Pair implements Comparable<Pair> {
int v,wt;
Pair(int v,int wt){
this.v=v;
this.wt=wt;
}
public int compareTo(Pair obj){
return this.wt-obj.wt;
}
}
class Solution
{
//Function to find the shortest distance of all the vertices
//from the source vertex S.
static int[] dijkstra(int v, ArrayList<ArrayList<ArrayList<Integer>>> adj, int src)
{
int ans[]=new int[v];
PriorityQueue<Pair> q=new PriorityQueue<>();
q.add(new Pair(src,0));
boolean[] visit=new boolean[v];
while(q.size()!=0){
Pair temp=q.remove();
if(visit[temp.v]==true){
continue;
}
visit[temp.v]=true;
ans[temp.v]=temp.wt;
ArrayList<ArrayList<Integer>> l=adj.get(temp.v);
for(int i=0;i<l.size();i++){
ArrayList<Integer> ls=l.get(i);
int u=ls.get(0);
int wet=ls.get(1);
if(visit[u]==false ){
q.add(new Pair(u,temp.wt+wet));
}
}
}
return ans;
}
}
0
saurabhsathe12344 weeks ago
C++ : 0.1 ms
1 . Without using min heap :
vector <int> dijkstra(int V, vector<vector<int>> adj[], int S)
{
// Code here
vector<int> dist(V,INT_MAX);
vector<int> fin(V,false);
dist[S] = 0;
for(int c=0;c<V;c++)
{
int u = -1;
for(int i=0;i<V;i++)
{
if( !fin[i] && (u==-1 || dist[i] < dist[u]))
{
u=i;
}
}
fin[u] = true ;
for(auto it : adj[u]){
int node = it[0];
int d = it[1];
if( !fin[node] && (dist[node] > dist[u] + d))
{
dist[node] = dist[u] + d;
}
}
}
return dist;
}
2. with min heap :
vector <int> dijkstra(int V, vector<vector<int>> adj[], int S)
{
// Code here
vector<int> dist(V,INT_MAX);
vector<int> fin(V,false);
priority_queue< pair<int,int> , vector<pair<int,int>> ,
greater<pair<int,int>> > pq;
dist[S] = 0;
pq.push({0,S});
while(!pq.empty())
{
int u = pq.top().second;
fin[u] = true;
for(auto it : adj[u]){
int node = it[0];
int d = it[1];
if( !fin[node] && (dist[node] > dist[u] + d))
{
dist[node] = dist[u] + d;
pq.push({dist[node],node});
}
}
pq.pop();
}
return dist;
}
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": 446,
"s": 238,
"text": "Given a weighted, undirected and connected graph of V vertices and E edges, Find the shortest distance of all the vertex's from the source vertex S.\nNote: The Graph doesn't contain any negative weight cycle."
},
{
"code": null,
"e": 459,
"s": 448,
"text": "Example 1:"
},
{
"code": null,
"e": 621,
"s": 459,
"text": "Input:\n\nS = 0\nOutput:\n0 9\nExplanation:\nThe source vertex is 0. Hence, the shortest \ndistance of node 0 is 0 and the shortest \ndistance from node 9 is 9 - 0 = 9.\n"
},
{
"code": null,
"e": 634,
"s": 623,
"text": "Example 2:"
},
{
"code": null,
"e": 888,
"s": 634,
"text": "Input:\n\nS = 2\nOutput:\n4 3 0\nExplanation:\nFor nodes 2 to 0, we can follow the path-\n2-1-0. This has a distance of 1+3 = 4,\nwhereas the path 2-0 has a distance of 6. So,\nthe Shortest path from 2 to 0 is 4.\nThe other distances are pretty straight-forward.\n"
},
{
"code": null,
"e": 1398,
"s": 890,
"text": "Your Task:\nYou don't need to read input or print anything. Your task is to complete the function dijkstra() which takes number of vertices V and an adjacency list adj as input parameters and returns a list of integers, where ith integer denotes the shortest distance of the ith node from Source node. Here adj[i] contains a list of lists containing two integers where the first integer j denotes that there is an edge between i and j and second integer w denotes that the weight between edge i and j is w."
},
{
"code": null,
"e": 1466,
"s": 1400,
"text": "Expected Time Complexity: O(V2).\nExpected Auxiliary Space: O(V2)."
},
{
"code": null,
"e": 1470,
"s": 1468,
"text": "0"
},
{
"code": null,
"e": 1492,
"s": 1470,
"text": "smdakhtar0071 day ago"
},
{
"code": null,
"e": 2349,
"s": 1492,
"text": "// done using Stack data structure done in 0.09 \nclass Solution\n{\n\tpublic:\n\t//Function to find the shortest distance of all the vertices\n //from the source vertex S.\n vector <int> dijkstra(int V, vector<vector<int>> adj[], int S)\n {\n set<pair<int,int>>st;\n vector<int> distance(V,INT_MAX);\n distance[S] = 0 ;\n st.insert({0,S});\n while(!st.empty()){\n pair<int,int>temp = *st.begin();\n st.erase(st.begin());\n int node = temp.second;\n int nxt_dis = temp.first; \n for(auto it : adj[node]){\n if(distance[it[0]] > nxt_dis + it[1]){\n distance[it[0]] = nxt_dis+it[1];\n st.insert({distance[it[0]],it[0]});\n }\n }\n \n }\n return distance;\n \n \n }\n};"
},
{
"code": null,
"e": 2352,
"s": 2349,
"text": "+1"
},
{
"code": null,
"e": 2379,
"s": 2352,
"text": "aarushsrivastava5 days ago"
},
{
"code": null,
"e": 3085,
"s": 2379,
"text": " vector <int> dijkstra(int V, vector<vector<int>> adj[], int S)\n {\n // Code here\n priority_queue<pair<int,int>, vector<pair<int,int>>, greater<pair<int,int>>> q;\n vector<int> dist(V, INT_MAX);\n dist[S] = 0;\n q.push({0, S});\n while(!q.empty()){\n int node = q.top().second;\n int dis = q.top().first;\n q.pop();\n for(auto it : adj[node]){\n int next = it[0];\n int nextdis = it[1];\n if(dis + nextdis < dist[next]){\n dist[next] = dis + nextdis;\n q.push({dist[next], next});\n }\n }\n }\n return dist;\n }"
},
{
"code": null,
"e": 3087,
"s": 3085,
"text": "0"
},
{
"code": null,
"e": 3111,
"s": 3087,
"text": "amishasahu3281 week ago"
},
{
"code": null,
"e": 3931,
"s": 3111,
"text": "vector<int> dijkstra(int V, vector<vector<int>> adj[], int S)\n {\n // Code here\n // By default, C++ creates a max-heap for priority queue.\n // // min-heap ; In pair => (dist,from)\n priority_queue<pair<int,int>, vector<pair<int,int>>, greater<pair<int,int>>> pq;\n vector<int> distance(V+1, INT_MAX);\n distance[S] = 0;\n pq.push({0,S});\n while(!pq.empty())\n {\n int dis = pq.top().first;\n int prev = pq.top().second;\n pq.pop();\n for(auto it: adj[prev])\n {\n if(distance[it[0]] > distance[prev]+it[1]){\n distance[it[0]] = distance[prev]+it[1];\n pq.push({distance[it[0]], it[0]});\n }\n }\n }\n return distance;\n }"
},
{
"code": null,
"e": 3933,
"s": 3931,
"text": "0"
},
{
"code": null,
"e": 3954,
"s": 3933,
"text": "itsmemritu1 week ago"
},
{
"code": null,
"e": 4691,
"s": 3954,
"text": " typedef pair<int, int> pii; vector <int> dijkstra(int V, vector<vector<int>> adj[], int S) { // Code here vector<int>ans(V,INT_MAX); priority_queue<pii,vector<pii>,greater<pii>>pq; vector<bool>visited(V,false); ans[S]=0; pq.push({0,S}); while(!pq.empty()){ int k=pq.top().second; int t=pq.top().first; pq.pop(); if(visited[k]){ continue; } visited[k]=true; for(auto it:adj[k]){ int weight=it[1]; int v=it[0]; if(ans[v]>ans[k]+weight){ ans[v]=ans[k]+weight; pq.push({ans[v],v}); } } } return ans; }"
},
{
"code": null,
"e": 4694,
"s": 4691,
"text": "+1"
},
{
"code": null,
"e": 4721,
"s": 4694,
"text": "pawananjanimth12 weeks ago"
},
{
"code": null,
"e": 4741,
"s": 4721,
"text": "Solution using Set:"
},
{
"code": null,
"e": 5645,
"s": 4741,
"text": " vector <int> dijkstra(int V, vector<vector<int>> adj[], int S)\n {\n // Code here\n vector<int> dist(V+1,INT_MAX);\n \n dist[S]=0;\n \n set<pair<int,int>> st;\n \n st.insert({S,0});\n \n while(!st.empty())\n {\n pair<int,int> p = *(st.begin());\n \n int node = p.first;\n \n int node_dist = p.second;\n \n st.erase(p);\n \n for(auto v:adj[node])\n {\n if(node_dist+v[1]<dist[v[0]])\n {\n if(st.find({v[0],v[1]})!=st.end()) st.erase({v[0],v[1]});\n \n dist[v[0]] = node_dist + v[1];\n \n st.insert({v[0],dist[v[0]]});\n }\n }\n \n }\n \n \n return dist;\n }"
},
{
"code": null,
"e": 5647,
"s": 5645,
"text": "0"
},
{
"code": null,
"e": 5668,
"s": 5647,
"text": "sknwd88643 weeks ago"
},
{
"code": null,
"e": 7020,
"s": 5668,
"text": " vector <int> dijkstra(int V, vector<vector<int>> adj[], int S) { // Code here // dijkstra's algorithm using priority_queue vector<int> dist(V , INT_MAX); // distance array dist[S]=0; // in min heap , we Store weight & node weight first then node vector<bool> visited(V , false); priority_queue< pair<int , int> , vector<pair<int , int>> , greater< pair<int , int>>> pq; pq.push({0 , S}); while(!pq.empty()) { auto t= pq.top(); pq.pop(); // int w=t.first; int node=t.second; visited[node]=true; // traverse its adjacent for(int i=0;i<adj[node].size();i++) { int v=adj[node][i][0]; int w=adj[node][i][1]; if(visited[v]==false) { if(dist[v]>dist[node] + w ) { dist[v]=dist[node] + w; // value i.e distance is updated // it is not INT_MAX pq.push({dist[v] , v}); } } } } return dist; }"
},
{
"code": null,
"e": 7023,
"s": 7020,
"text": "+1"
},
{
"code": null,
"e": 7050,
"s": 7023,
"text": "devashishbakare3 weeks ago"
},
{
"code": null,
"e": 7081,
"s": 7050,
"text": "Java Solution with explanation"
},
{
"code": null,
"e": 8722,
"s": 7083,
"text": "class Solution\n{\n static class pair implements Comparable<pair>{\n int ver;\n int wt;\n public pair(int n,int d)\n {\n this.wt=d;\n this.ver=n;\n }\n public int compareTo(pair p)\n {\n return this.wt - p.wt;\n }\n}\n\n //Function to find the shortest distance of all the vertices\n //from the source vertex S.\n static int[] dijkstra(int V, ArrayList<ArrayList<ArrayList<Integer>>> adj, int S)\n {\n // Write your code here\n //create ans array and initised them as a infinity\n int[] ans=new int[V];\n Arrays.fill(ans,Integer.MAX_VALUE);\n \n //source shortest length always zero\n ans[S]=0;\n \n PriorityQueue<pair> pq = new PriorityQueue<>();\n \n //add first element with 0 as distance\n pq.add(new pair(S,0));\n \n while(pq.size()>0)\n {\n \n pair p = pq.poll();\n \n //get the adjucent of all the pop vertex \n for(ArrayList<Integer> x:adj.get(p.ver))\n {\n //if newly found path is smaller thean the previous path,\n \n if( ans[p.ver] + x.get(1) < ans[x.get(0)] )\n {\n //then update the sortest path \n ans[x.get(0)] = ans[p.ver]+x.get(1);\n \n //add that element in priority queue for next element to move shotest weightt\n //coz its greedy approtch\n \n pq.add(new pair(x.get(0),ans[x.get(0)]));\n \n }\n }\n }\n //returning the final answer\n return ans;\n }\n}"
},
{
"code": null,
"e": 8724,
"s": 8722,
"text": "0"
},
{
"code": null,
"e": 8749,
"s": 8724,
"text": "shivam26120023 weeks ago"
},
{
"code": null,
"e": 9201,
"s": 8749,
"text": " vector <int> dijkstra(int V, vector<vector<int>> adj[], int S) { vector<int> dist(V,INT_MAX); dist[S]=0; queue<int> q; q.push(S); while(!q.empty()){ int node=q.front(); q.pop(); for(auto i:adj[node]) { if(dist[node]+i[1]<dist[i[0]]) { dist[i[0]]=dist[node]+i[1]; q.push(i[0]);} } } return dist; }"
},
{
"code": null,
"e": 9203,
"s": 9201,
"text": "0"
},
{
"code": null,
"e": 9224,
"s": 9203,
"text": "19bcs13143 weeks ago"
},
{
"code": null,
"e": 9270,
"s": 9226,
"text": "my solution using priority queue using bfs "
},
{
"code": null,
"e": 10570,
"s": 9270,
"text": "\nclass Pair implements Comparable<Pair> {\n int v,wt;\n\n Pair(int v,int wt){\n this.v=v;\n this.wt=wt;\n }\n \n public int compareTo(Pair obj){\n return this.wt-obj.wt;\n }\n}\n\nclass Solution\n{\n //Function to find the shortest distance of all the vertices\n //from the source vertex S.\n static int[] dijkstra(int v, ArrayList<ArrayList<ArrayList<Integer>>> adj, int src)\n {\n\n int ans[]=new int[v];\n\n PriorityQueue<Pair> q=new PriorityQueue<>();\n \n q.add(new Pair(src,0));\n boolean[] visit=new boolean[v];\n while(q.size()!=0){\n Pair temp=q.remove();\n \n if(visit[temp.v]==true){\n continue;\n }\n visit[temp.v]=true;\n ans[temp.v]=temp.wt;\n\n ArrayList<ArrayList<Integer>> l=adj.get(temp.v);\n \n for(int i=0;i<l.size();i++){\n ArrayList<Integer> ls=l.get(i);\n \n int u=ls.get(0);\n int wet=ls.get(1);\n \n if(visit[u]==false ){\n q.add(new Pair(u,temp.wt+wet));\n }\n }\n \n }\n\n return ans;\n \n \n }\n}\n"
},
{
"code": null,
"e": 10572,
"s": 10570,
"text": "0"
},
{
"code": null,
"e": 10600,
"s": 10572,
"text": "saurabhsathe12344 weeks ago"
},
{
"code": null,
"e": 10613,
"s": 10600,
"text": "C++ : 0.1 ms"
},
{
"code": null,
"e": 10642,
"s": 10613,
"text": "1 . Without using min heap :"
},
{
"code": null,
"e": 11444,
"s": 10644,
"text": " vector <int> dijkstra(int V, vector<vector<int>> adj[], int S)\n {\n // Code here\n vector<int> dist(V,INT_MAX);\n vector<int> fin(V,false);\n dist[S] = 0;\n for(int c=0;c<V;c++)\n {\n int u = -1;\n for(int i=0;i<V;i++)\n {\n if( !fin[i] && (u==-1 || dist[i] < dist[u]))\n {\n u=i;\n }\n }\n \n fin[u] = true ;\n \n for(auto it : adj[u]){\n int node = it[0];\n int d = it[1];\n if( !fin[node] && (dist[node] > dist[u] + d))\n {\n dist[node] = dist[u] + d;\n }\n }\n \n }\n return dist;\n \n }"
},
{
"code": null,
"e": 11463,
"s": 11444,
"text": "2. with min heap :"
},
{
"code": null,
"e": 12327,
"s": 11463,
"text": "vector <int> dijkstra(int V, vector<vector<int>> adj[], int S)\n {\n // Code here\n vector<int> dist(V,INT_MAX);\n vector<int> fin(V,false);\n priority_queue< pair<int,int> , vector<pair<int,int>> , \n greater<pair<int,int>> > pq;\n \n \n dist[S] = 0;\n pq.push({0,S});\n \n while(!pq.empty())\n {\n int u = pq.top().second;\n fin[u] = true;\n \n for(auto it : adj[u]){\n int node = it[0];\n int d = it[1];\n if( !fin[node] && (dist[node] > dist[u] + d))\n {\n dist[node] = dist[u] + d;\n pq.push({dist[node],node});\n }\n }\n pq.pop();\n }\n \n return dist;\n \n }"
},
{
"code": null,
"e": 12473,
"s": 12327,
"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": 12509,
"s": 12473,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 12519,
"s": 12509,
"text": "\nProblem\n"
},
{
"code": null,
"e": 12529,
"s": 12519,
"text": "\nContest\n"
},
{
"code": null,
"e": 12592,
"s": 12529,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 12740,
"s": 12592,
"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": 12948,
"s": 12740,
"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": 13054,
"s": 12948,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Multi-Line printing in Python - GeeksforGeeks
|
21 Jan, 2019
We have already seen the basic use of print function previous article. Now, let’s see how to use print function for multi-line printing. This can easily be done using multiline string i.e. three single quotes ''' Geeksforgeeks ''' .
Let’s see different examples to see the demonstration for the same.
Example #1:
# basic example for multi-line printingprint('''=======================================| || || GeeksforGeeks || || |=======================================''' )
=======================================
| |
| |
| GeeksforGeeks |
| |
| |
=======================================
Example #2:
# basic example2 for multi-line printingprint( '''list.head second third | | | | | | +----+------+ +----+------+ +----+------+ | 1 | None | | 2 | None | | 3 | None | +----+------+ +----+------+ +----+------+ ''' )
list.head second third
| | |
| | |
+----+------+ +----+------+ +----+------+
| 1 | None | | 2 | None | | 3 | None |
+----+------+ +----+------+ +----+------+
python-basics
python-io
Python
python-io
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()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Check if element exists in list in Python
Convert integer to string in Python
|
[
{
"code": null,
"e": 25808,
"s": 25780,
"text": "\n21 Jan, 2019"
},
{
"code": null,
"e": 26041,
"s": 25808,
"text": "We have already seen the basic use of print function previous article. Now, let’s see how to use print function for multi-line printing. This can easily be done using multiline string i.e. three single quotes ''' Geeksforgeeks ''' ."
},
{
"code": null,
"e": 26109,
"s": 26041,
"text": "Let’s see different examples to see the demonstration for the same."
},
{
"code": null,
"e": 26121,
"s": 26109,
"text": "Example #1:"
},
{
"code": "# basic example for multi-line printingprint('''=======================================| || || GeeksforGeeks || || |=======================================''' )",
"e": 26451,
"s": 26121,
"text": null
},
{
"code": null,
"e": 26732,
"s": 26451,
"text": "=======================================\n| |\n| |\n| GeeksforGeeks |\n| |\n| |\n=======================================\n"
},
{
"code": null,
"e": 26744,
"s": 26732,
"text": "Example #2:"
},
{
"code": "# basic example2 for multi-line printingprint( '''list.head second third | | | | | | +----+------+ +----+------+ +----+------+ | 1 | None | | 2 | None | | 3 | None | +----+------+ +----+------+ +----+------+ ''' )",
"e": 27107,
"s": 26744,
"text": null
},
{
"code": null,
"e": 27412,
"s": 27107,
"text": "list.head second third \n | | | \n | | | \n +----+------+ +----+------+ +----+------+ \n | 1 | None | | 2 | None | | 3 | None | \n +----+------+ +----+------+ +----+------+\n"
},
{
"code": null,
"e": 27426,
"s": 27412,
"text": "python-basics"
},
{
"code": null,
"e": 27436,
"s": 27426,
"text": "python-io"
},
{
"code": null,
"e": 27443,
"s": 27436,
"text": "Python"
},
{
"code": null,
"e": 27453,
"s": 27443,
"text": "python-io"
},
{
"code": null,
"e": 27551,
"s": 27453,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27569,
"s": 27551,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27604,
"s": 27569,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 27636,
"s": 27604,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27678,
"s": 27636,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27704,
"s": 27678,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27733,
"s": 27704,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 27777,
"s": 27733,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 27814,
"s": 27777,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 27856,
"s": 27814,
"text": "Check if element exists in list in Python"
}
] |
How to select a column of a matrix by column name in R?
|
When we create a matrix in R, its column names are not defined but we can name them or might import a matrix that might have column names. If the column names are not defined then we simply use column numbers to extract the columns but if we have column names then we can select the column by name as well as its name.
M1 <-matrix(1:25,nrow=5)
M1
[,1] [,2] [,3] [,4] [,5]
[1,] 1 6 11 16 21
[2,] 2 7 12 17 22
[3,] 3 8 13 18 23
[4,] 4 9 14 19 24
[5,] 5 10 15 20 25
colnames(M1) <-c("C1","C2","C3","C4","C5")
M1
C1 C2 C3 C4 C5
[1,] 1 6 11 16 21
[2,] 2 7 12 17 22
[3,] 3 8 13 18 23
[4,] 4 9 14 19 24
[5,] 5 10 15 20 25
M1[,"C1"]
[1] 1 2 3 4 5
M1[,"C2"]
[1] 6 7 8 9 10
M1[,"C4"]
[1] 16 17 18 19 20
M1[,"C5"]
[1] 21 22 23 24 25
M2 <-matrix(sample(1:100,36),nrow=6)
M2
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 97 53 27 60 13 8
[2,] 41 98 38 73 74 57
[3,] 65 54 15 49 9 5
[4,] 46 87 100 19 94 62
[5,] 6 23 91 45 34 32
[6,] 71 51 26 85 29
colnames(M2) <-c("Rate","Percentage","Class","Group","ID","Section")
M2
Rate Percentage Class Group ID Section
[1,] 97 53 27 60 13 8
[2,] 41 98 38 73 74 57
[3,] 65 54 15 49 9 5
[4,] 46 87 100 19 94 62
[5,] 6 23 91 45 34 32
[6,] 71 51 26 85 29 70
M2[,"Rate"]
[1] 97 41 65 46 6 71
M2[,"Percentage"]
[1] 53 98 54 87 23 51
M2[,"Class"]
[1] 27 38 15 100 91 26
M2[,"Group"]
[1] 60 73 49 19 45 85
M2[,"ID"]
[1] 13 74 9 94 34 29
M2[,"Section"]
[1] 8 57 5 62 32 70
M3 <-matrix(1:100,nrow=10)
colnames(M3) <-c("Var1","Var2","Var3","Var4","Var5","Var6","Var7","Var8","Var9","Var10")
M3
Var1 Var2 Var3 Var4 Var5 Var6 Var7 Var8 Var9 Var10
[1,] 1 11 21 31 41 51 61 71 81 91
[2,] 2 12 22 32 42 52 62 72 82 92
[3,] 3 13 23 33 43 53 63 73 83 93
[4,] 4 14 24 34 44 54 64 74 84 94
[5,] 5 15 25 35 45 55 65 75 85 95
[6,] 6 16 26 36 46 56 66 76 86 96
[7,] 7 17 27 37 47 57 67 77 87 97
[8,] 8 18 28 38 48 58 68 78 88 98
[9,] 9 19 29 39 49 59 69 79 89 99
[10,] 10 20 30 40 50 60 70 80 90 100
M3[,"Var1"]
[1] 1 2 3 4 5 6 7 8 9 10
M3[,"Var5"]
[1] 41 42 43 44 45 46 47 48 49 50
M3[,"Var7"]
[1] 61 62 63 64 65 66 67 68 69 70
M3[,"Var9"]
[1] 81 82 83 84 85 86 87 88 89 90
|
[
{
"code": null,
"e": 1381,
"s": 1062,
"text": "When we create a matrix in R, its column names are not defined but we can name them or might import a matrix that might have column names. If the column names are not defined then we simply use column numbers to extract the columns but if we have column names then we can select the column by name as well as its name."
},
{
"code": null,
"e": 1409,
"s": 1381,
"text": "M1 <-matrix(1:25,nrow=5)\nM1"
},
{
"code": null,
"e": 1525,
"s": 1409,
"text": "[,1] [,2] [,3] [,4] [,5]\n[1,] 1 6 11 16 21\n[2,] 2 7 12 17 22\n[3,] 3 8 13 18 23\n[4,] 4 9 14 19 24\n[5,] 5 10 15 20 25"
},
{
"code": null,
"e": 1571,
"s": 1525,
"text": "colnames(M1) <-c(\"C1\",\"C2\",\"C3\",\"C4\",\"C5\")\nM1"
},
{
"code": null,
"e": 1677,
"s": 1571,
"text": "C1 C2 C3 C4 C5\n[1,] 1 6 11 16 21\n[2,] 2 7 12 17 22\n[3,] 3 8 13 18 23\n[4,] 4 9 14 19 24\n[5,] 5 10 15 20 25"
},
{
"code": null,
"e": 1687,
"s": 1677,
"text": "M1[,\"C1\"]"
},
{
"code": null,
"e": 1701,
"s": 1687,
"text": "[1] 1 2 3 4 5"
},
{
"code": null,
"e": 1711,
"s": 1701,
"text": "M1[,\"C2\"]"
},
{
"code": null,
"e": 1726,
"s": 1711,
"text": "[1] 6 7 8 9 10"
},
{
"code": null,
"e": 1736,
"s": 1726,
"text": "M1[,\"C4\"]"
},
{
"code": null,
"e": 1755,
"s": 1736,
"text": "[1] 16 17 18 19 20"
},
{
"code": null,
"e": 1765,
"s": 1755,
"text": "M1[,\"C5\"]"
},
{
"code": null,
"e": 1784,
"s": 1765,
"text": "[1] 21 22 23 24 25"
},
{
"code": null,
"e": 1824,
"s": 1784,
"text": "M2 <-matrix(sample(1:100,36),nrow=6)\nM2"
},
{
"code": null,
"e": 1986,
"s": 1824,
"text": "[,1] [,2] [,3] [,4] [,5] [,6]\n[1,] 97 53 27 60 13 8\n[2,] 41 98 38 73 74 57\n[3,] 65 54 15 49 9 5\n[4,] 46 87 100 19 94 62\n[5,] 6 23 91 45 34 32\n[6,] 71 51 26 85 29"
},
{
"code": null,
"e": 2058,
"s": 1986,
"text": "colnames(M2) <-c(\"Rate\",\"Percentage\",\"Class\",\"Group\",\"ID\",\"Section\")\nM2"
},
{
"code": null,
"e": 2232,
"s": 2058,
"text": "Rate Percentage Class Group ID Section\n[1,] 97 53 27 60 13 8\n[2,] 41 98 38 73 74 57\n[3,] 65 54 15 49 9 5\n[4,] 46 87 100 19 94 62\n[5,] 6 23 91 45 34 32\n[6,] 71 51 26 85 29 70"
},
{
"code": null,
"e": 2244,
"s": 2232,
"text": "M2[,\"Rate\"]"
},
{
"code": null,
"e": 2265,
"s": 2244,
"text": "[1] 97 41 65 46 6 71"
},
{
"code": null,
"e": 2284,
"s": 2265,
"text": "M2[,\"Percentage\"]\n"
},
{
"code": null,
"e": 2306,
"s": 2284,
"text": "[1] 53 98 54 87 23 51"
},
{
"code": null,
"e": 2319,
"s": 2306,
"text": "M2[,\"Class\"]"
},
{
"code": null,
"e": 2342,
"s": 2319,
"text": "[1] 27 38 15 100 91 26"
},
{
"code": null,
"e": 2356,
"s": 2342,
"text": "M2[,\"Group\"]\n"
},
{
"code": null,
"e": 2378,
"s": 2356,
"text": "[1] 60 73 49 19 45 85"
},
{
"code": null,
"e": 2388,
"s": 2378,
"text": "M2[,\"ID\"]"
},
{
"code": null,
"e": 2409,
"s": 2388,
"text": "[1] 13 74 9 94 34 29"
},
{
"code": null,
"e": 2425,
"s": 2409,
"text": "M2[,\"Section\"]\n"
},
{
"code": null,
"e": 2445,
"s": 2425,
"text": "[1] 8 57 5 62 32 70"
},
{
"code": null,
"e": 2564,
"s": 2445,
"text": "M3 <-matrix(1:100,nrow=10)\ncolnames(M3) <-c(\"Var1\",\"Var2\",\"Var3\",\"Var4\",\"Var5\",\"Var6\",\"Var7\",\"Var8\",\"Var9\",\"Var10\")\nM3"
},
{
"code": null,
"e": 2958,
"s": 2564,
"text": "Var1 Var2 Var3 Var4 Var5 Var6 Var7 Var8 Var9 Var10\n[1,] 1 11 21 31 41 51 61 71 81 91\n[2,] 2 12 22 32 42 52 62 72 82 92\n[3,] 3 13 23 33 43 53 63 73 83 93\n[4,] 4 14 24 34 44 54 64 74 84 94\n[5,] 5 15 25 35 45 55 65 75 85 95\n[6,] 6 16 26 36 46 56 66 76 86 96\n[7,] 7 17 27 37 47 57 67 77 87 97\n[8,] 8 18 28 38 48 58 68 78 88 98\n[9,] 9 19 29 39 49 59 69 79 89 99\n[10,] 10 20 30 40 50 60 70 80 90 100"
},
{
"code": null,
"e": 2970,
"s": 2958,
"text": "M3[,\"Var1\"]"
},
{
"code": null,
"e": 2995,
"s": 2970,
"text": "[1] 1 2 3 4 5 6 7 8 9 10"
},
{
"code": null,
"e": 3007,
"s": 2995,
"text": "M3[,\"Var5\"]"
},
{
"code": null,
"e": 3041,
"s": 3007,
"text": "[1] 41 42 43 44 45 46 47 48 49 50"
},
{
"code": null,
"e": 3053,
"s": 3041,
"text": "M3[,\"Var7\"]"
},
{
"code": null,
"e": 3087,
"s": 3053,
"text": "[1] 61 62 63 64 65 66 67 68 69 70"
},
{
"code": null,
"e": 3099,
"s": 3087,
"text": "M3[,\"Var9\"]"
},
{
"code": null,
"e": 3133,
"s": 3099,
"text": "[1] 81 82 83 84 85 86 87 88 89 90"
}
] |
Tryit Editor v3.7
|
Tryit: Force all buttons to have the same look with !important
|
[] |
Differences between anonymous class and lambda expression in Java?
|
Anonymous class is an inner class without a name, which means that we can declare and instantiate class at the same time. A lambda expression is a short form for writing an anonymous class. By using a lambda expression, we can declare methods without any name.
An anonymous class object generates a separate class file after compilation that increases the size of a jar file while a lambda expression is converted into a private method. It uses invokedynamic bytecode instruction to bind this method dynamically, which saves time and memory.
We use this keyword to represent the current class in lambda expression while in the case of an anonymous class, this keyword can represent that particular anonymous class.
Anonymous classes can be used in case of more than one abstract method while a lambda expression specifically used for functional interfaces.
We need to provide the function body only in lambda expression while in the case of an anonymous class, we need to write the redundant class definition.
public class ThreadTest {
public static void main(String[] args) {
Runnable r1 = new Runnable() { // Anonymous class
@Override
public void run() {
System.out.println("Using Anonymous class");
}
};
Runnable r2 = () -> { // lambda expression
System.out.println("Using Lambda Expression");
};
new Thread(r1).start();
new Thread(r2).start();
}
}
Using Anonymous class
Using Lambda Expression
|
[
{
"code": null,
"e": 1323,
"s": 1062,
"text": "Anonymous class is an inner class without a name, which means that we can declare and instantiate class at the same time. A lambda expression is a short form for writing an anonymous class. By using a lambda expression, we can declare methods without any name."
},
{
"code": null,
"e": 1604,
"s": 1323,
"text": "An anonymous class object generates a separate class file after compilation that increases the size of a jar file while a lambda expression is converted into a private method. It uses invokedynamic bytecode instruction to bind this method dynamically, which saves time and memory."
},
{
"code": null,
"e": 1777,
"s": 1604,
"text": "We use this keyword to represent the current class in lambda expression while in the case of an anonymous class, this keyword can represent that particular anonymous class."
},
{
"code": null,
"e": 1919,
"s": 1777,
"text": "Anonymous classes can be used in case of more than one abstract method while a lambda expression specifically used for functional interfaces."
},
{
"code": null,
"e": 2072,
"s": 1919,
"text": "We need to provide the function body only in lambda expression while in the case of an anonymous class, we need to write the redundant class definition."
},
{
"code": null,
"e": 2489,
"s": 2072,
"text": "public class ThreadTest {\n public static void main(String[] args) {\n Runnable r1 = new Runnable() { // Anonymous class\n @Override\n public void run() {\n System.out.println(\"Using Anonymous class\");\n }\n };\n Runnable r2 = () -> { // lambda expression\n System.out.println(\"Using Lambda Expression\");\n };\n new Thread(r1).start();\n new Thread(r2).start();\n }\n}"
},
{
"code": null,
"e": 2535,
"s": 2489,
"text": "Using Anonymous class\nUsing Lambda Expression"
}
] |
Finding square root of a number without using Math.sqrt() in JavaScript
|
We are required to write a JavaScript function that takes in a positive integer as the only argument. The function should find and return the square root of the number provided as the input.
Following is the code −
const squareRoot = (num, precision = 0) => {
if (num <= 0) {
return 0;
};
let res = 1;
const deviation = 1 / (10 ** precision);
while (Math.abs(num - (res ** 2)) > deviation) {
res -= ((res ** 2) - num) / (2 * res);
};
return Math.round(res * (10 ** precision)) / (10 ** precision);
};
console.log(squareRoot(16));
console.log(squareRoot(161, 3));
console.log(squareRoot(1611, 4));
Following is the output on console −
4
12.689
40.1373
|
[
{
"code": null,
"e": 1253,
"s": 1062,
"text": "We are required to write a JavaScript function that takes in a positive integer as the only argument. The function should find and return the square root of the number provided as the input."
},
{
"code": null,
"e": 1277,
"s": 1253,
"text": "Following is the code −"
},
{
"code": null,
"e": 1692,
"s": 1277,
"text": "const squareRoot = (num, precision = 0) => {\n if (num <= 0) {\n return 0;\n };\n let res = 1;\n const deviation = 1 / (10 ** precision);\n while (Math.abs(num - (res ** 2)) > deviation) {\n res -= ((res ** 2) - num) / (2 * res);\n };\n return Math.round(res * (10 ** precision)) / (10 ** precision);\n};\nconsole.log(squareRoot(16));\nconsole.log(squareRoot(161, 3));\nconsole.log(squareRoot(1611, 4));"
},
{
"code": null,
"e": 1729,
"s": 1692,
"text": "Following is the output on console −"
},
{
"code": null,
"e": 1746,
"s": 1729,
"text": "4\n12.689\n40.1373"
}
] |
Number.doubleValue() method in java with examples - GeeksforGeeks
|
20 Jun, 2018
The java.lang.Number.doubleValue() is an inbuilt method in java that returns the value of the specified number casted as a double data type. This may involve rounding or truncation.
Syntax:
public abstract double doubleValue()
Parameters: This method does not accepts any parameter.
Return value: This method returns the numeric value represented by this object after conversion to type double.
Below programs illustrate the Number.doubleValue()method:
Program 1:
// java program that demonstrates// the Number.doubleValue()public class gfg { public static void main(String[] args) { // number as integer Integer x = new Integer(1234785456); // print value as double System.out.println(x.doubleValue()); // number as float Float y = new Float(98745876f); // print value as double System.out.println(y.doubleValue()); }}
1.234785456E9
9.8745872E7
Program 2:
// java program that demonstrates// the Number.doubleValue() public class gfg { public static void main(String[] args) { // number as integer Integer x = new Integer(123); // print value as double System.out.println(x.doubleValue()); // number as float Float y = new Float(9876f); // print value as double System.out.println(y.doubleValue()); }}
123.0
9876.0
Java-Functions
Java-lang package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
How to iterate any Map in Java
Initialize an ArrayList in Java
Interfaces in Java
ArrayList in Java
Multidimensional Arrays in Java
Stack Class in Java
Singleton Class in Java
LinkedList in Java
|
[
{
"code": null,
"e": 24087,
"s": 24059,
"text": "\n20 Jun, 2018"
},
{
"code": null,
"e": 24269,
"s": 24087,
"text": "The java.lang.Number.doubleValue() is an inbuilt method in java that returns the value of the specified number casted as a double data type. This may involve rounding or truncation."
},
{
"code": null,
"e": 24277,
"s": 24269,
"text": "Syntax:"
},
{
"code": null,
"e": 24315,
"s": 24277,
"text": "public abstract double doubleValue()\n"
},
{
"code": null,
"e": 24371,
"s": 24315,
"text": "Parameters: This method does not accepts any parameter."
},
{
"code": null,
"e": 24483,
"s": 24371,
"text": "Return value: This method returns the numeric value represented by this object after conversion to type double."
},
{
"code": null,
"e": 24541,
"s": 24483,
"text": "Below programs illustrate the Number.doubleValue()method:"
},
{
"code": null,
"e": 24552,
"s": 24541,
"text": "Program 1:"
},
{
"code": "// java program that demonstrates// the Number.doubleValue()public class gfg { public static void main(String[] args) { // number as integer Integer x = new Integer(1234785456); // print value as double System.out.println(x.doubleValue()); // number as float Float y = new Float(98745876f); // print value as double System.out.println(y.doubleValue()); }}",
"e": 24979,
"s": 24552,
"text": null
},
{
"code": null,
"e": 25006,
"s": 24979,
"text": "1.234785456E9\n9.8745872E7\n"
},
{
"code": null,
"e": 25017,
"s": 25006,
"text": "Program 2:"
},
{
"code": "// java program that demonstrates// the Number.doubleValue() public class gfg { public static void main(String[] args) { // number as integer Integer x = new Integer(123); // print value as double System.out.println(x.doubleValue()); // number as float Float y = new Float(9876f); // print value as double System.out.println(y.doubleValue()); }}",
"e": 25435,
"s": 25017,
"text": null
},
{
"code": null,
"e": 25449,
"s": 25435,
"text": "123.0\n9876.0\n"
},
{
"code": null,
"e": 25464,
"s": 25449,
"text": "Java-Functions"
},
{
"code": null,
"e": 25482,
"s": 25464,
"text": "Java-lang package"
},
{
"code": null,
"e": 25487,
"s": 25482,
"text": "Java"
},
{
"code": null,
"e": 25492,
"s": 25487,
"text": "Java"
},
{
"code": null,
"e": 25590,
"s": 25492,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25599,
"s": 25590,
"text": "Comments"
},
{
"code": null,
"e": 25612,
"s": 25599,
"text": "Old Comments"
},
{
"code": null,
"e": 25663,
"s": 25612,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 25693,
"s": 25663,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 25724,
"s": 25693,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 25756,
"s": 25724,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 25775,
"s": 25756,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 25793,
"s": 25775,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 25825,
"s": 25793,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 25845,
"s": 25825,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 25869,
"s": 25845,
"text": "Singleton Class in Java"
}
] |
10 Python File System Methods You Should Know - GeeksforGeeks
|
19 Oct, 2021
While programming in any language, interaction between the programs and the operating system (Windows, Linux, macOS) can become important at some point in any developer’s life. This interaction may include moving files from one location to another, creating a new file, deleting a file, etc.
In this article, we will discuss 10 essential file system methods of the OS and Shutil module in Python that helps to interact with our operating system and use OS-dependent functionalities.
os.getcwd() method tells us the location of the current working directory (CWD).
Example:
Python3
# Python program to explain os.getcwd() method # importing os moduleimport os # Get the current working# directory (CWD)cwd = os.getcwd() # Print the current working# directory (CWD)print("Current working directory:", cwd)
Output:
Current working directory: /home/nikhil/Desktop/gfg
os.chdir() method in Python used to change the current working directory to a specified path. It takes only a single argument as a new directory path.
Python3
# Python3 program to change the# directory of file using os.chdir() method # import os libraryimport os # change the current directory# to specified directoryos.chdir(r"C:\Users\Gfg\Desktop\geeks") print("Directory changed")
Output:
Directory changed
os.listdir() method in python is used to get the list of all files and directories in the specified directory. If we don’t specify any directory, then list of files and directories in the current working directory will be returned.
Example:
Python3
# Python program to explain os.listdir() method # importing os moduleimport os # Get the path of current working directorypath = '/home' # Get the list of all files and directories# in current working directorydir_list = os.listdir(path) print("Files and directories in '", path, "' :")print(dir_list)
Output:
Files and directories in ' /home ' :
['nikhil']
os.walk() generate the file names in a directory tree by walking the tree either top-down or bottom-up. For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple (dirpath, dirnames, filenames).
Example:
Python3
# Driver functionimport os for (root,dirs,files) in os.walk('/home/nikhil/Desktop/', topdown=True): print (root) print (dirs) print (files) print ('--------------------------------')
Output:
os.path.join() method in Python join one or more path components intelligently. This method concatenates various path components with exactly one directory separator (‘/’) following each non-empty part except the last path component. If the last path component to be joined is empty then a directory separator (‘/’) is put at the end.
Python3
# Python program to explain os.path.join() method # importing os moduleimport os # Pathpath = "/home" # Join various path componentsprint(os.path.join(path, "User/Desktop", "file.txt")) # Pathpath = "User/Documents" # Join various path componentsprint(os.path.join(path, "/home", "file.txt")) # In above example '/home'# represents an absolute path# so all previous components i.e User / Documents# are thrown away and joining continues# from the absolute path component i.e / home. # Pathpath = "/home" # Join various path componentsprint(os.path.join(path, "User/Public/", "Documents", "")) # In above example the last# path component is empty# so a directory separator ('/')# will be put at the end# along with the concatenated value
/home/User/Desktop/file.txt
/home/file.txt
/home/User/Public/Documents/
os.makedirs() method in Python is used to create a directory recursively. That means while making leaf directory if any intermediate-level directory is missing, os.makedirs() method will create them all. For example consider the following path:
/home/User/Documents/GeeksForGeeks/Authors/nikhil
Suppose we want to create a directory ‘nikhil’ but Directory ‘GeeksForGeeks’ and ‘Authors’ are unavailable in the path. Then os.makedirs() method will create all unavailable/missing directories in the specified path. ‘GeeksForGeeks’ and ‘Authors’ will be created first then ‘nikhil’ directory will be created.
Example:
Python3
# Python program to explain os.makedirs() method # importing os moduleimport os # Leaf directorydirectory = "nikhil" # Parent Directoriesparent_dir = "/home/User/Documents/GeeksForGeeks/Authors" # Pathpath = os.path.join(parent_dir, directory) # Create the directory# 'ihritik'os.makedirs(path)print("Directory '%s' created" %directory)
Output:
Directory 'nikhil' created
shutil.copy2() method in Python is used to copy the content of the source file to the destination file or directory. This method is identical to shutil.copy() method but it also tries to preserve the file’s metadata.
Example:
Directory Used
Python3
# Python program to explain shutil.copy2() method # importing os moduleimport os # importing shutil moduleimport shutil # pathpath = '/home/nikhil/Desktop/new' # List files and directories# in '/home/User/Documents'print("Before copying file:")print(os.listdir(path)) # Source pathsource = "/home/nikhil/Desktop/new/pdf.py" # Print the metadeta# of source filemetadata = os.stat(source)print("Metadata:", metadata, "\n") # Destination pathdestination = "/home/nikhil/Desktop/new/copy_pdf.py" # Copy the content of# source to destinationdest = shutil.copy2(source, destination) # List files and directories# in "/home / User / Documents"print("After copying file:")print(os.listdir(path)) # Print the metadata# of the destination filematadata = os.stat(destination)print("Metadata:", metadata) # Print path of newly# created fileprint("Destination path:", dest)
Output:
Before copying file:
[‘pdf.py’, ‘pdf1.pdf’]
Metadata: os.stat_result(st_mode=33204, st_ino=58068385, st_dev=2050, st_nlink=1, st_uid=1000, st_gid=1000, st_size=887, st_atime=1619538642, st_mtime=1618307699, st_ctime=1618307700)
After copying file:
[‘copy_pdf.py’, ‘pdf.py’, ‘pdf1.pdf’]
Metadata: os.stat_result(st_mode=33204, st_ino=58068385, st_dev=2050, st_nlink=1, st_uid=1000, st_gid=1000, st_size=887, st_atime=1619538642, st_mtime=1618307699, st_ctime=1618307700)
Destination path: /home/nikhil/Desktop/new/copy_pdf.py
Directory
shutil.move() method Recursively moves a file or directory (source) to another location (destination) and returns the destination. If the destination directory already exists then src is moved inside that directory. If the destination already exists but is not a directory then it may be overwritten depending on os.rename() semantics.
Example:
Directory Used
Python3
# Python program to explain shutil.move() method # importing os moduleimport os # importing shutil moduleimport shutil # pathpath = '/home/nikhil/Desktop/' # List files and directories# in 'C:/Users/Rajnish/Desktop/GeeksforGeeks'print("Before moving file:")print(os.listdir(path)) # Source pathsource = '/home/nikhil/Desktop/new' # Destination pathdestination = '/home/nikhil/Desktop/new2' # Move the content of# source to destinationdest = shutil.move(source, destination) # List files and directories# in "C:/Users / Rajnish / Desktop / GeeksforGeeks"print("After moving file:")print(os.listdir(path)) # Print path of newly# created fileprint("Destination path:", dest)
Output:
os.remove() method in Python is used to remove or delete a file path. This method can not remove or delete a directory.
Example:
Python3
# Python program to explain os.remove() method # importing os moduleimport os # File namefile = 'file.txt' # File locationlocation = "/home/User/Documents" # Pathpath = os.path.join(location, file) # Remove the file# 'file.txt'os.remove(path)print("%s has been removed successfully" %file)
Output:
file.txt has been removed successfully
shutil.rmtree() is used to delete an entire directory tree, path must point to a directory.
Example: Suppose the directory and sub-directories are as follow.
# Parent directory:
# Directory inside parent directory:
# File inside the sub-directory:
Python3
# Python program to demonstrate# shutil.rmtree() import shutilimport os # locationlocation = "D:/Pycharm projects/GeeksforGeeks/" # directorydir = "Authors" # pathpath = os.path.join(location, dir) # removing directoryshutil.rmtree(path)
Output:
Refer to the below articles for our complete tutorial on the OS module and Shutil module.
OS Module in Python with Examples
Shutil Module in Python
python-os-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Python Classes and Objects
Create a directory in Python
|
[
{
"code": null,
"e": 23901,
"s": 23873,
"text": "\n19 Oct, 2021"
},
{
"code": null,
"e": 24194,
"s": 23901,
"text": "While programming in any language, interaction between the programs and the operating system (Windows, Linux, macOS) can become important at some point in any developer’s life. This interaction may include moving files from one location to another, creating a new file, deleting a file, etc. "
},
{
"code": null,
"e": 24385,
"s": 24194,
"text": "In this article, we will discuss 10 essential file system methods of the OS and Shutil module in Python that helps to interact with our operating system and use OS-dependent functionalities."
},
{
"code": null,
"e": 24466,
"s": 24385,
"text": "os.getcwd() method tells us the location of the current working directory (CWD)."
},
{
"code": null,
"e": 24475,
"s": 24466,
"text": "Example:"
},
{
"code": null,
"e": 24483,
"s": 24475,
"text": "Python3"
},
{
"code": "# Python program to explain os.getcwd() method # importing os moduleimport os # Get the current working# directory (CWD)cwd = os.getcwd() # Print the current working# directory (CWD)print(\"Current working directory:\", cwd)",
"e": 24725,
"s": 24483,
"text": null
},
{
"code": null,
"e": 24733,
"s": 24725,
"text": "Output:"
},
{
"code": null,
"e": 24785,
"s": 24733,
"text": "Current working directory: /home/nikhil/Desktop/gfg"
},
{
"code": null,
"e": 24936,
"s": 24785,
"text": "os.chdir() method in Python used to change the current working directory to a specified path. It takes only a single argument as a new directory path."
},
{
"code": null,
"e": 24944,
"s": 24936,
"text": "Python3"
},
{
"code": "# Python3 program to change the# directory of file using os.chdir() method # import os libraryimport os # change the current directory# to specified directoryos.chdir(r\"C:\\Users\\Gfg\\Desktop\\geeks\") print(\"Directory changed\")",
"e": 25172,
"s": 24944,
"text": null
},
{
"code": null,
"e": 25180,
"s": 25172,
"text": "Output:"
},
{
"code": null,
"e": 25198,
"s": 25180,
"text": "Directory changed"
},
{
"code": null,
"e": 25430,
"s": 25198,
"text": "os.listdir() method in python is used to get the list of all files and directories in the specified directory. If we don’t specify any directory, then list of files and directories in the current working directory will be returned."
},
{
"code": null,
"e": 25439,
"s": 25430,
"text": "Example:"
},
{
"code": null,
"e": 25447,
"s": 25439,
"text": "Python3"
},
{
"code": "# Python program to explain os.listdir() method # importing os moduleimport os # Get the path of current working directorypath = '/home' # Get the list of all files and directories# in current working directorydir_list = os.listdir(path) print(\"Files and directories in '\", path, \"' :\")print(dir_list)",
"e": 25757,
"s": 25447,
"text": null
},
{
"code": null,
"e": 25765,
"s": 25757,
"text": "Output:"
},
{
"code": null,
"e": 25813,
"s": 25765,
"text": "Files and directories in ' /home ' :\n['nikhil']"
},
{
"code": null,
"e": 26048,
"s": 25813,
"text": "os.walk() generate the file names in a directory tree by walking the tree either top-down or bottom-up. For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple (dirpath, dirnames, filenames)."
},
{
"code": null,
"e": 26057,
"s": 26048,
"text": "Example:"
},
{
"code": null,
"e": 26065,
"s": 26057,
"text": "Python3"
},
{
"code": "# Driver functionimport os for (root,dirs,files) in os.walk('/home/nikhil/Desktop/', topdown=True): print (root) print (dirs) print (files) print ('--------------------------------')",
"e": 26261,
"s": 26065,
"text": null
},
{
"code": null,
"e": 26269,
"s": 26261,
"text": "Output:"
},
{
"code": null,
"e": 26605,
"s": 26269,
"text": "os.path.join() method in Python join one or more path components intelligently. This method concatenates various path components with exactly one directory separator (‘/’) following each non-empty part except the last path component. If the last path component to be joined is empty then a directory separator (‘/’) is put at the end. "
},
{
"code": null,
"e": 26613,
"s": 26605,
"text": "Python3"
},
{
"code": "# Python program to explain os.path.join() method # importing os moduleimport os # Pathpath = \"/home\" # Join various path componentsprint(os.path.join(path, \"User/Desktop\", \"file.txt\")) # Pathpath = \"User/Documents\" # Join various path componentsprint(os.path.join(path, \"/home\", \"file.txt\")) # In above example '/home'# represents an absolute path# so all previous components i.e User / Documents# are thrown away and joining continues# from the absolute path component i.e / home. # Pathpath = \"/home\" # Join various path componentsprint(os.path.join(path, \"User/Public/\", \"Documents\", \"\")) # In above example the last# path component is empty# so a directory separator ('/')# will be put at the end# along with the concatenated value",
"e": 27363,
"s": 26613,
"text": null
},
{
"code": null,
"e": 27435,
"s": 27363,
"text": "/home/User/Desktop/file.txt\n/home/file.txt\n/home/User/Public/Documents/"
},
{
"code": null,
"e": 27680,
"s": 27435,
"text": "os.makedirs() method in Python is used to create a directory recursively. That means while making leaf directory if any intermediate-level directory is missing, os.makedirs() method will create them all. For example consider the following path:"
},
{
"code": null,
"e": 27730,
"s": 27680,
"text": "/home/User/Documents/GeeksForGeeks/Authors/nikhil"
},
{
"code": null,
"e": 28041,
"s": 27730,
"text": "Suppose we want to create a directory ‘nikhil’ but Directory ‘GeeksForGeeks’ and ‘Authors’ are unavailable in the path. Then os.makedirs() method will create all unavailable/missing directories in the specified path. ‘GeeksForGeeks’ and ‘Authors’ will be created first then ‘nikhil’ directory will be created. "
},
{
"code": null,
"e": 28050,
"s": 28041,
"text": "Example:"
},
{
"code": null,
"e": 28058,
"s": 28050,
"text": "Python3"
},
{
"code": "# Python program to explain os.makedirs() method # importing os moduleimport os # Leaf directorydirectory = \"nikhil\" # Parent Directoriesparent_dir = \"/home/User/Documents/GeeksForGeeks/Authors\" # Pathpath = os.path.join(parent_dir, directory) # Create the directory# 'ihritik'os.makedirs(path)print(\"Directory '%s' created\" %directory)",
"e": 28407,
"s": 28058,
"text": null
},
{
"code": null,
"e": 28415,
"s": 28407,
"text": "Output:"
},
{
"code": null,
"e": 28442,
"s": 28415,
"text": "Directory 'nikhil' created"
},
{
"code": null,
"e": 28659,
"s": 28442,
"text": "shutil.copy2() method in Python is used to copy the content of the source file to the destination file or directory. This method is identical to shutil.copy() method but it also tries to preserve the file’s metadata."
},
{
"code": null,
"e": 28668,
"s": 28659,
"text": "Example:"
},
{
"code": null,
"e": 28683,
"s": 28668,
"text": "Directory Used"
},
{
"code": null,
"e": 28691,
"s": 28683,
"text": "Python3"
},
{
"code": "# Python program to explain shutil.copy2() method # importing os moduleimport os # importing shutil moduleimport shutil # pathpath = '/home/nikhil/Desktop/new' # List files and directories# in '/home/User/Documents'print(\"Before copying file:\")print(os.listdir(path)) # Source pathsource = \"/home/nikhil/Desktop/new/pdf.py\" # Print the metadeta# of source filemetadata = os.stat(source)print(\"Metadata:\", metadata, \"\\n\") # Destination pathdestination = \"/home/nikhil/Desktop/new/copy_pdf.py\" # Copy the content of# source to destinationdest = shutil.copy2(source, destination) # List files and directories# in \"/home / User / Documents\"print(\"After copying file:\")print(os.listdir(path)) # Print the metadata# of the destination filematadata = os.stat(destination)print(\"Metadata:\", metadata) # Print path of newly# created fileprint(\"Destination path:\", dest)",
"e": 29565,
"s": 28691,
"text": null
},
{
"code": null,
"e": 29573,
"s": 29565,
"text": "Output:"
},
{
"code": null,
"e": 29594,
"s": 29573,
"text": "Before copying file:"
},
{
"code": null,
"e": 29617,
"s": 29594,
"text": "[‘pdf.py’, ‘pdf1.pdf’]"
},
{
"code": null,
"e": 29801,
"s": 29617,
"text": "Metadata: os.stat_result(st_mode=33204, st_ino=58068385, st_dev=2050, st_nlink=1, st_uid=1000, st_gid=1000, st_size=887, st_atime=1619538642, st_mtime=1618307699, st_ctime=1618307700)"
},
{
"code": null,
"e": 29821,
"s": 29801,
"text": "After copying file:"
},
{
"code": null,
"e": 29859,
"s": 29821,
"text": "[‘copy_pdf.py’, ‘pdf.py’, ‘pdf1.pdf’]"
},
{
"code": null,
"e": 30043,
"s": 29859,
"text": "Metadata: os.stat_result(st_mode=33204, st_ino=58068385, st_dev=2050, st_nlink=1, st_uid=1000, st_gid=1000, st_size=887, st_atime=1619538642, st_mtime=1618307699, st_ctime=1618307700)"
},
{
"code": null,
"e": 30098,
"s": 30043,
"text": "Destination path: /home/nikhil/Desktop/new/copy_pdf.py"
},
{
"code": null,
"e": 30108,
"s": 30098,
"text": "Directory"
},
{
"code": null,
"e": 30444,
"s": 30108,
"text": "shutil.move() method Recursively moves a file or directory (source) to another location (destination) and returns the destination. If the destination directory already exists then src is moved inside that directory. If the destination already exists but is not a directory then it may be overwritten depending on os.rename() semantics."
},
{
"code": null,
"e": 30453,
"s": 30444,
"text": "Example:"
},
{
"code": null,
"e": 30468,
"s": 30453,
"text": "Directory Used"
},
{
"code": null,
"e": 30476,
"s": 30468,
"text": "Python3"
},
{
"code": "# Python program to explain shutil.move() method # importing os moduleimport os # importing shutil moduleimport shutil # pathpath = '/home/nikhil/Desktop/' # List files and directories# in 'C:/Users/Rajnish/Desktop/GeeksforGeeks'print(\"Before moving file:\")print(os.listdir(path)) # Source pathsource = '/home/nikhil/Desktop/new' # Destination pathdestination = '/home/nikhil/Desktop/new2' # Move the content of# source to destinationdest = shutil.move(source, destination) # List files and directories# in \"C:/Users / Rajnish / Desktop / GeeksforGeeks\"print(\"After moving file:\")print(os.listdir(path)) # Print path of newly# created fileprint(\"Destination path:\", dest)",
"e": 31163,
"s": 30476,
"text": null
},
{
"code": null,
"e": 31171,
"s": 31163,
"text": "Output:"
},
{
"code": null,
"e": 31292,
"s": 31171,
"text": "os.remove() method in Python is used to remove or delete a file path. This method can not remove or delete a directory. "
},
{
"code": null,
"e": 31301,
"s": 31292,
"text": "Example:"
},
{
"code": null,
"e": 31309,
"s": 31301,
"text": "Python3"
},
{
"code": "# Python program to explain os.remove() method # importing os moduleimport os # File namefile = 'file.txt' # File locationlocation = \"/home/User/Documents\" # Pathpath = os.path.join(location, file) # Remove the file# 'file.txt'os.remove(path)print(\"%s has been removed successfully\" %file)",
"e": 31608,
"s": 31309,
"text": null
},
{
"code": null,
"e": 31616,
"s": 31608,
"text": "Output:"
},
{
"code": null,
"e": 31655,
"s": 31616,
"text": "file.txt has been removed successfully"
},
{
"code": null,
"e": 31747,
"s": 31655,
"text": "shutil.rmtree() is used to delete an entire directory tree, path must point to a directory."
},
{
"code": null,
"e": 31813,
"s": 31747,
"text": "Example: Suppose the directory and sub-directories are as follow."
},
{
"code": null,
"e": 31833,
"s": 31813,
"text": "# Parent directory:"
},
{
"code": null,
"e": 31870,
"s": 31833,
"text": "# Directory inside parent directory:"
},
{
"code": null,
"e": 31903,
"s": 31870,
"text": "# File inside the sub-directory:"
},
{
"code": null,
"e": 31911,
"s": 31903,
"text": "Python3"
},
{
"code": "# Python program to demonstrate# shutil.rmtree() import shutilimport os # locationlocation = \"D:/Pycharm projects/GeeksforGeeks/\" # directorydir = \"Authors\" # pathpath = os.path.join(location, dir) # removing directoryshutil.rmtree(path)",
"e": 32154,
"s": 31911,
"text": null
},
{
"code": null,
"e": 32162,
"s": 32154,
"text": "Output:"
},
{
"code": null,
"e": 32252,
"s": 32162,
"text": "Refer to the below articles for our complete tutorial on the OS module and Shutil module."
},
{
"code": null,
"e": 32286,
"s": 32252,
"text": "OS Module in Python with Examples"
},
{
"code": null,
"e": 32310,
"s": 32286,
"text": "Shutil Module in Python"
},
{
"code": null,
"e": 32327,
"s": 32310,
"text": "python-os-module"
},
{
"code": null,
"e": 32334,
"s": 32327,
"text": "Python"
},
{
"code": null,
"e": 32432,
"s": 32334,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32441,
"s": 32432,
"text": "Comments"
},
{
"code": null,
"e": 32454,
"s": 32441,
"text": "Old Comments"
},
{
"code": null,
"e": 32486,
"s": 32454,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 32542,
"s": 32486,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 32584,
"s": 32542,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 32626,
"s": 32584,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 32662,
"s": 32626,
"text": "Python | Pandas dataframe.groupby()"
},
{
"code": null,
"e": 32701,
"s": 32662,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 32723,
"s": 32701,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 32754,
"s": 32723,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 32781,
"s": 32754,
"text": "Python Classes and Objects"
}
] |
Get started Spark with Databricks and PySpark | by Andrew Zhu | Towards Data Science
|
In the beginning, the Master Programmer created the relational database and file system. But the file system in a single machine became limited and slow. The data darkness was on the surface of database. The spirit of map-reducing was brooding upon the surface of the big data.
And Master Programmer said, let there be Spark, and there was Spark.
If the relational database is a well-maintained data garden; Hadoop is a clutter data forest, and it can grow to an unlimited size.
To put data into the garden, data need to be carefully cleaned and grow there structurally. While in the Hadoop forest, ladies and gentlemen, don’t worry, any data is fine here, text, numerical numbers, even audio and videos with no data size and type limitation.
But there are still some shortages in Hadoop, where Spark comes to solve. Here list 4 key differences for me.
In Hadoop, every mapping and reducing action use disk storage as the data middle man, and disk operation is slow. Spark optimize the process by leveraging memory direct data access. In other words, store some intermediate data in memory to boost the performance. (That is why you always read the official Spark introduction portray itself much faster than Hadoop, nothing magic here.)Hadoop is basically a distributed file system that can be extended to unlimited size with its map-reducer and batch scheduler. But you need to use Java to implement real applications. Spark comes to provide operation languages like Python, and R. Provide useful tools for data streaming, Machine Learning, and data analytic.Hadoop doesn’t include a job scheduler and needs 3rd — party scheduler involved, Sparks comes with its own job scheduler.Hadoop is much cheaper and low RAM required. Spark requires more RAM. Ok, this one is an advantage of Hadoop instead of a disadvantage.
In Hadoop, every mapping and reducing action use disk storage as the data middle man, and disk operation is slow. Spark optimize the process by leveraging memory direct data access. In other words, store some intermediate data in memory to boost the performance. (That is why you always read the official Spark introduction portray itself much faster than Hadoop, nothing magic here.)
Hadoop is basically a distributed file system that can be extended to unlimited size with its map-reducer and batch scheduler. But you need to use Java to implement real applications. Spark comes to provide operation languages like Python, and R. Provide useful tools for data streaming, Machine Learning, and data analytic.
Hadoop doesn’t include a job scheduler and needs 3rd — party scheduler involved, Sparks comes with its own job scheduler.
Hadoop is much cheaper and low RAM required. Spark requires more RAM. Ok, this one is an advantage of Hadoop instead of a disadvantage.
And with PySpark, we can interact with Spark fully in pure plain Python code, in Jupyter Notebook, or Databricks Notebook. This is a great plus from Spark.
Spark is open-sourced, free, and powerful, why bother using Databricks? To set up a useful Spark cluster, and leverage the distributed storage, we need to build at least 2 machines, virtually or physically. Next, set up the Driver and worker nodes, configure the network and securities, etc.
A lot more manual work to be done for simply run a Spark “hello world”. Don’t mention if you get error messages like JAVA_HOME can’t be found, or can’t find Spark path.
Databricks provides a unbox and ready-to-use environment by solving all these tedious configurations.
Take Azure Databricks for example, after several mouse clicks, and several minutes waiting for the cluster to spin up. We have a fully-featured Spark system. They call it Databricks.
Unlike the free Spark, Databricks is usually charged by the cluster size and usage. Be careful, choose the right size when creating your first instance.
One more thing to note, please do remember the Databricks runtime version you selected. I’d prefer to select the LTS 7.3. later, when you install the databricks-connect the version should be the same.
I am going to use Python to do everything, so should I install pyspark package? No, To use Python to control Databricks, we need first uninstall the pyspark package to avoid conflicts.
pip uninstall pyspark
Next, install the databricks-connect. which include all PySpark functions with a different name. (Ensure you already have Java 8+ installed in your local machine)
pip install -U "databricks-connect==7.3.*"
Before configuring the client connection to Databricks cluster, go to the Databricks UI grab the following information and write down to your note. Detail steps can be found here
access token: dapib0fxxxxxxxxx6d288bac04855bccccdworkspace URL: https://adb-8091234370581234.18.azuredatabricks.net/cluster id: 1234-12345-abcdef123port number:15001org id: 8091234370581234 ,org id also appears in the workspace url.
access token: dapib0fxxxxxxxxx6d288bac04855bccccd
workspace URL: https://adb-8091234370581234.18.azuredatabricks.net/
cluster id: 1234-12345-abcdef123
port number:15001
org id: 8091234370581234 ,org id also appears in the workspace url.
When you have all the above information ready, go configure your local PySpark connection to the Databricks cluster.
databricks-connect configure
follow the guide, you won’t miss the path. After this, use this Python code to test the connection.
# python from pyspark.sql import SparkSessionspark = SparkSession.builder.getOrCreate()print('spark session created.')
If you are welcomed with “spark session created.”, a live and kicking Spark cluster is running in the cloud. We can do some big data analysis now.
Hadoop’s HDFS from Hadoop allows users to build scalable massive storage upon local disks. BDFS is almost the same as HDFS. The difference is its backend storage is cloud-based.
You can use dbutils to remotely manage the BDFS with Python,
To get dbutils object handler in your local Python context. The official document assumes you are using Databricks Notebook and omit this step. Makes users confused when trying to use it in plain Python code.
from pyspark.dbutils import DBUtilsdbutils = DBUtils(spark) # the spark object here # is already initialized above
List the files and folders from the /mnt/ folder
dbutils.fs.ls('dbfs:/mnt/')
And you will get information like this:
[FileInfo(path='dbfs:/mnt/folder1/', name='folder1/', size=123), FileInfo(path='dbfs:/mnt/folder2/', name='folder2/', size=123), FileInfo(path='dbfs:/mnt/tmp/', name='tmp/', size=123)]
The dbutils official document list all other operations.
Prepare A Bible CSV file on your local disk. Replace the [username] with yours to run the below code.
import urllib.requestbible_url = "https://raw.githubusercontent.com/scrollmapper/bible_databases/master/csv/t_kjv.csv"urllib.request.urlretrieve(bible_url,"/home/[username]/temp/bible_kjv.csv")
Now, upload the bible CSV file to BDFS.
bible_csv_path = "file:/home/[username]/temp/bible_kjv.csv"dbutils.fs.cp(bible_csv_path,"/tmp/bible_kjv.csv")
Use mv to replace cp if you decide to move the file instead of copying.
Read the just uploaded Bible CSV file and encapsulate it in a Spark Dataframe(in contrast to Pandas Dataframe).
bible_spark_df = spark.read.format('csv')\ .options(header='true')\ .load('/tmp/bible_kjv.csv')bible_spark_df.show()
You shall see result
+-------+---+---+---+--------------------+| id| b| c| v| t|+-------+---+---+---+--------------------+|1001001| 1| 1| 1|In the beginning ...||1001002| 1| 1| 2|And the earth was...||1001003| 1| 1| 3|And God said, Let...|...|1001019| 1| 1| 19|And the evening a...||1001020| 1| 1| 20|And God said, Let...|+-------+---+---+---+--------------------+only showing top 20 rows
If you are Pandas Dataframe fans, it is easy to transform data to Pandas Dataframe
bible_pandas_df = bible_spark_df.toPandas()
Let’s use Spark Dataframe to see how many verses of each book.
bible_spark_df.groupBy("b")\ .count()\ .sort("count",ascending=False)\ .show()
You shall see the result
Book 1 is Genesis, this book contains 1533 verses.
With the help of creating a temp view, we can also query the data using Spark SQL
bible_spark_df.createOrReplaceTempView('bible')bible_sql_result = spark.sql(''' select * from bible where id == 1001001''')bible_sql_result.show()
The query result
+-------+---+---+---+--------------------+| id| b| c| v| t|+-------+---+---+---+--------------------+|1001001| 1| 1| 1|In the beginning ...|+-------+---+---+---+--------------------+
Save Spark Dataframe back to BDFS as a JSON file.
bible_spark_df.write.format('json').save('/tmp/bible_kjv.json')
For all Spark dataset operations, check out The Spark SQL, DataFrames and Datasets Guide
Spark also supports Hive database and tables, in the above sample, I create a temp view to enable the SQL query. But the temp view will disappear when the session end. To enable store data in Hive Table and can be queried with Spark SQL for the long run. we can store data in Hive tables.
First, create a Hive database
spark.sql("create database test_hive_db")
Next, write the bible spark Dataframe as a table. The database name here is kind of like a table folder.
bible_spark_df.write.saveAsTable('test_hive_db.bible_kjv')
For all information about Spark Hive table operations, check out Hive Tables
Congratulation and Thank you, if you read through here. When I started learning Spark and Databricks, I got stuck when Book authors tried to introduce the Spark backend architecture with complex diagrams. I wrote this for those who never touched Spark before and want to get hands dirty without getting confused.
If you run all code successfully, you should be in a good position to start using Spark and Databricks. Spark and Databricks are just tools shouldn’t be that complex, can it be more complex than Python? (kidding)
One more thing to note, the default Databricks Get Started tutorial use Databricks Notebook, which is good and beautiful. But in real projects and work, you may want to write code to plain Python and manage your work in a git repository. I found Visual Studio Code with Python and Databricks extension is a wonderful tool that fully supports Databricks and Spark.
Hope this helpful to you.
|
[
{
"code": null,
"e": 449,
"s": 171,
"text": "In the beginning, the Master Programmer created the relational database and file system. But the file system in a single machine became limited and slow. The data darkness was on the surface of database. The spirit of map-reducing was brooding upon the surface of the big data."
},
{
"code": null,
"e": 518,
"s": 449,
"text": "And Master Programmer said, let there be Spark, and there was Spark."
},
{
"code": null,
"e": 650,
"s": 518,
"text": "If the relational database is a well-maintained data garden; Hadoop is a clutter data forest, and it can grow to an unlimited size."
},
{
"code": null,
"e": 914,
"s": 650,
"text": "To put data into the garden, data need to be carefully cleaned and grow there structurally. While in the Hadoop forest, ladies and gentlemen, don’t worry, any data is fine here, text, numerical numbers, even audio and videos with no data size and type limitation."
},
{
"code": null,
"e": 1024,
"s": 914,
"text": "But there are still some shortages in Hadoop, where Spark comes to solve. Here list 4 key differences for me."
},
{
"code": null,
"e": 1989,
"s": 1024,
"text": "In Hadoop, every mapping and reducing action use disk storage as the data middle man, and disk operation is slow. Spark optimize the process by leveraging memory direct data access. In other words, store some intermediate data in memory to boost the performance. (That is why you always read the official Spark introduction portray itself much faster than Hadoop, nothing magic here.)Hadoop is basically a distributed file system that can be extended to unlimited size with its map-reducer and batch scheduler. But you need to use Java to implement real applications. Spark comes to provide operation languages like Python, and R. Provide useful tools for data streaming, Machine Learning, and data analytic.Hadoop doesn’t include a job scheduler and needs 3rd — party scheduler involved, Sparks comes with its own job scheduler.Hadoop is much cheaper and low RAM required. Spark requires more RAM. Ok, this one is an advantage of Hadoop instead of a disadvantage."
},
{
"code": null,
"e": 2374,
"s": 1989,
"text": "In Hadoop, every mapping and reducing action use disk storage as the data middle man, and disk operation is slow. Spark optimize the process by leveraging memory direct data access. In other words, store some intermediate data in memory to boost the performance. (That is why you always read the official Spark introduction portray itself much faster than Hadoop, nothing magic here.)"
},
{
"code": null,
"e": 2699,
"s": 2374,
"text": "Hadoop is basically a distributed file system that can be extended to unlimited size with its map-reducer and batch scheduler. But you need to use Java to implement real applications. Spark comes to provide operation languages like Python, and R. Provide useful tools for data streaming, Machine Learning, and data analytic."
},
{
"code": null,
"e": 2821,
"s": 2699,
"text": "Hadoop doesn’t include a job scheduler and needs 3rd — party scheduler involved, Sparks comes with its own job scheduler."
},
{
"code": null,
"e": 2957,
"s": 2821,
"text": "Hadoop is much cheaper and low RAM required. Spark requires more RAM. Ok, this one is an advantage of Hadoop instead of a disadvantage."
},
{
"code": null,
"e": 3113,
"s": 2957,
"text": "And with PySpark, we can interact with Spark fully in pure plain Python code, in Jupyter Notebook, or Databricks Notebook. This is a great plus from Spark."
},
{
"code": null,
"e": 3405,
"s": 3113,
"text": "Spark is open-sourced, free, and powerful, why bother using Databricks? To set up a useful Spark cluster, and leverage the distributed storage, we need to build at least 2 machines, virtually or physically. Next, set up the Driver and worker nodes, configure the network and securities, etc."
},
{
"code": null,
"e": 3574,
"s": 3405,
"text": "A lot more manual work to be done for simply run a Spark “hello world”. Don’t mention if you get error messages like JAVA_HOME can’t be found, or can’t find Spark path."
},
{
"code": null,
"e": 3676,
"s": 3574,
"text": "Databricks provides a unbox and ready-to-use environment by solving all these tedious configurations."
},
{
"code": null,
"e": 3859,
"s": 3676,
"text": "Take Azure Databricks for example, after several mouse clicks, and several minutes waiting for the cluster to spin up. We have a fully-featured Spark system. They call it Databricks."
},
{
"code": null,
"e": 4012,
"s": 3859,
"text": "Unlike the free Spark, Databricks is usually charged by the cluster size and usage. Be careful, choose the right size when creating your first instance."
},
{
"code": null,
"e": 4213,
"s": 4012,
"text": "One more thing to note, please do remember the Databricks runtime version you selected. I’d prefer to select the LTS 7.3. later, when you install the databricks-connect the version should be the same."
},
{
"code": null,
"e": 4398,
"s": 4213,
"text": "I am going to use Python to do everything, so should I install pyspark package? No, To use Python to control Databricks, we need first uninstall the pyspark package to avoid conflicts."
},
{
"code": null,
"e": 4420,
"s": 4398,
"text": "pip uninstall pyspark"
},
{
"code": null,
"e": 4583,
"s": 4420,
"text": "Next, install the databricks-connect. which include all PySpark functions with a different name. (Ensure you already have Java 8+ installed in your local machine)"
},
{
"code": null,
"e": 4626,
"s": 4583,
"text": "pip install -U \"databricks-connect==7.3.*\""
},
{
"code": null,
"e": 4805,
"s": 4626,
"text": "Before configuring the client connection to Databricks cluster, go to the Databricks UI grab the following information and write down to your note. Detail steps can be found here"
},
{
"code": null,
"e": 5038,
"s": 4805,
"text": "access token: dapib0fxxxxxxxxx6d288bac04855bccccdworkspace URL: https://adb-8091234370581234.18.azuredatabricks.net/cluster id: 1234-12345-abcdef123port number:15001org id: 8091234370581234 ,org id also appears in the workspace url."
},
{
"code": null,
"e": 5088,
"s": 5038,
"text": "access token: dapib0fxxxxxxxxx6d288bac04855bccccd"
},
{
"code": null,
"e": 5156,
"s": 5088,
"text": "workspace URL: https://adb-8091234370581234.18.azuredatabricks.net/"
},
{
"code": null,
"e": 5189,
"s": 5156,
"text": "cluster id: 1234-12345-abcdef123"
},
{
"code": null,
"e": 5207,
"s": 5189,
"text": "port number:15001"
},
{
"code": null,
"e": 5275,
"s": 5207,
"text": "org id: 8091234370581234 ,org id also appears in the workspace url."
},
{
"code": null,
"e": 5392,
"s": 5275,
"text": "When you have all the above information ready, go configure your local PySpark connection to the Databricks cluster."
},
{
"code": null,
"e": 5421,
"s": 5392,
"text": "databricks-connect configure"
},
{
"code": null,
"e": 5521,
"s": 5421,
"text": "follow the guide, you won’t miss the path. After this, use this Python code to test the connection."
},
{
"code": null,
"e": 5640,
"s": 5521,
"text": "# python from pyspark.sql import SparkSessionspark = SparkSession.builder.getOrCreate()print('spark session created.')"
},
{
"code": null,
"e": 5787,
"s": 5640,
"text": "If you are welcomed with “spark session created.”, a live and kicking Spark cluster is running in the cloud. We can do some big data analysis now."
},
{
"code": null,
"e": 5965,
"s": 5787,
"text": "Hadoop’s HDFS from Hadoop allows users to build scalable massive storage upon local disks. BDFS is almost the same as HDFS. The difference is its backend storage is cloud-based."
},
{
"code": null,
"e": 6026,
"s": 5965,
"text": "You can use dbutils to remotely manage the BDFS with Python,"
},
{
"code": null,
"e": 6235,
"s": 6026,
"text": "To get dbutils object handler in your local Python context. The official document assumes you are using Databricks Notebook and omit this step. Makes users confused when trying to use it in plain Python code."
},
{
"code": null,
"e": 6375,
"s": 6235,
"text": "from pyspark.dbutils import DBUtilsdbutils = DBUtils(spark) # the spark object here # is already initialized above"
},
{
"code": null,
"e": 6424,
"s": 6375,
"text": "List the files and folders from the /mnt/ folder"
},
{
"code": null,
"e": 6452,
"s": 6424,
"text": "dbutils.fs.ls('dbfs:/mnt/')"
},
{
"code": null,
"e": 6492,
"s": 6452,
"text": "And you will get information like this:"
},
{
"code": null,
"e": 6677,
"s": 6492,
"text": "[FileInfo(path='dbfs:/mnt/folder1/', name='folder1/', size=123), FileInfo(path='dbfs:/mnt/folder2/', name='folder2/', size=123), FileInfo(path='dbfs:/mnt/tmp/', name='tmp/', size=123)]"
},
{
"code": null,
"e": 6734,
"s": 6677,
"text": "The dbutils official document list all other operations."
},
{
"code": null,
"e": 6836,
"s": 6734,
"text": "Prepare A Bible CSV file on your local disk. Replace the [username] with yours to run the below code."
},
{
"code": null,
"e": 7030,
"s": 6836,
"text": "import urllib.requestbible_url = \"https://raw.githubusercontent.com/scrollmapper/bible_databases/master/csv/t_kjv.csv\"urllib.request.urlretrieve(bible_url,\"/home/[username]/temp/bible_kjv.csv\")"
},
{
"code": null,
"e": 7070,
"s": 7030,
"text": "Now, upload the bible CSV file to BDFS."
},
{
"code": null,
"e": 7180,
"s": 7070,
"text": "bible_csv_path = \"file:/home/[username]/temp/bible_kjv.csv\"dbutils.fs.cp(bible_csv_path,\"/tmp/bible_kjv.csv\")"
},
{
"code": null,
"e": 7252,
"s": 7180,
"text": "Use mv to replace cp if you decide to move the file instead of copying."
},
{
"code": null,
"e": 7364,
"s": 7252,
"text": "Read the just uploaded Bible CSV file and encapsulate it in a Spark Dataframe(in contrast to Pandas Dataframe)."
},
{
"code": null,
"e": 7513,
"s": 7364,
"text": "bible_spark_df = spark.read.format('csv')\\ .options(header='true')\\ .load('/tmp/bible_kjv.csv')bible_spark_df.show()"
},
{
"code": null,
"e": 7534,
"s": 7513,
"text": "You shall see result"
},
{
"code": null,
"e": 7940,
"s": 7534,
"text": "+-------+---+---+---+--------------------+| id| b| c| v| t|+-------+---+---+---+--------------------+|1001001| 1| 1| 1|In the beginning ...||1001002| 1| 1| 2|And the earth was...||1001003| 1| 1| 3|And God said, Let...|...|1001019| 1| 1| 19|And the evening a...||1001020| 1| 1| 20|And God said, Let...|+-------+---+---+---+--------------------+only showing top 20 rows"
},
{
"code": null,
"e": 8023,
"s": 7940,
"text": "If you are Pandas Dataframe fans, it is easy to transform data to Pandas Dataframe"
},
{
"code": null,
"e": 8067,
"s": 8023,
"text": "bible_pandas_df = bible_spark_df.toPandas()"
},
{
"code": null,
"e": 8130,
"s": 8067,
"text": "Let’s use Spark Dataframe to see how many verses of each book."
},
{
"code": null,
"e": 8248,
"s": 8130,
"text": "bible_spark_df.groupBy(\"b\")\\ .count()\\ .sort(\"count\",ascending=False)\\ .show()"
},
{
"code": null,
"e": 8273,
"s": 8248,
"text": "You shall see the result"
},
{
"code": null,
"e": 8324,
"s": 8273,
"text": "Book 1 is Genesis, this book contains 1533 verses."
},
{
"code": null,
"e": 8406,
"s": 8324,
"text": "With the help of creating a temp view, we can also query the data using Spark SQL"
},
{
"code": null,
"e": 8560,
"s": 8406,
"text": "bible_spark_df.createOrReplaceTempView('bible')bible_sql_result = spark.sql(''' select * from bible where id == 1001001''')bible_sql_result.show()"
},
{
"code": null,
"e": 8577,
"s": 8560,
"text": "The query result"
},
{
"code": null,
"e": 8788,
"s": 8577,
"text": "+-------+---+---+---+--------------------+| id| b| c| v| t|+-------+---+---+---+--------------------+|1001001| 1| 1| 1|In the beginning ...|+-------+---+---+---+--------------------+"
},
{
"code": null,
"e": 8838,
"s": 8788,
"text": "Save Spark Dataframe back to BDFS as a JSON file."
},
{
"code": null,
"e": 8902,
"s": 8838,
"text": "bible_spark_df.write.format('json').save('/tmp/bible_kjv.json')"
},
{
"code": null,
"e": 8991,
"s": 8902,
"text": "For all Spark dataset operations, check out The Spark SQL, DataFrames and Datasets Guide"
},
{
"code": null,
"e": 9280,
"s": 8991,
"text": "Spark also supports Hive database and tables, in the above sample, I create a temp view to enable the SQL query. But the temp view will disappear when the session end. To enable store data in Hive Table and can be queried with Spark SQL for the long run. we can store data in Hive tables."
},
{
"code": null,
"e": 9310,
"s": 9280,
"text": "First, create a Hive database"
},
{
"code": null,
"e": 9352,
"s": 9310,
"text": "spark.sql(\"create database test_hive_db\")"
},
{
"code": null,
"e": 9457,
"s": 9352,
"text": "Next, write the bible spark Dataframe as a table. The database name here is kind of like a table folder."
},
{
"code": null,
"e": 9516,
"s": 9457,
"text": "bible_spark_df.write.saveAsTable('test_hive_db.bible_kjv')"
},
{
"code": null,
"e": 9593,
"s": 9516,
"text": "For all information about Spark Hive table operations, check out Hive Tables"
},
{
"code": null,
"e": 9906,
"s": 9593,
"text": "Congratulation and Thank you, if you read through here. When I started learning Spark and Databricks, I got stuck when Book authors tried to introduce the Spark backend architecture with complex diagrams. I wrote this for those who never touched Spark before and want to get hands dirty without getting confused."
},
{
"code": null,
"e": 10119,
"s": 9906,
"text": "If you run all code successfully, you should be in a good position to start using Spark and Databricks. Spark and Databricks are just tools shouldn’t be that complex, can it be more complex than Python? (kidding)"
},
{
"code": null,
"e": 10483,
"s": 10119,
"text": "One more thing to note, the default Databricks Get Started tutorial use Databricks Notebook, which is good and beautiful. But in real projects and work, you may want to write code to plain Python and manage your work in a git repository. I found Visual Studio Code with Python and Databricks extension is a wonderful tool that fully supports Databricks and Spark."
}
] |
How to skip a middleware in Express.js ? - GeeksforGeeks
|
09 Apr, 2021
If we want to skip a middleware we can pass parameters to the middleware function and decide based on that parameter which middleware to call and which middleware to not call.
Prerequisite:
express.js: To handle routing.
Setting up environment and execution:
Step 1: Initialize node projectnpm init
Step 1: Initialize node project
npm init
Step 2: Install required modulesnpm install express
Step 2: Install required modules
npm install express
Example:
index.js
const express = require("express");// const database = require('./sqlConnection'); const app = express(); // Start server on port 5000app.listen(5000, () => { console.log(`Server is up and running on 5000 ...`);}); // define middleware 1let middleware1 = (req, res, next) => { // decide a parameter req.shouldRunMiddleware2 = false; console.log("Middleware 1 is running !"); next();} // define middleware 2let middleware2 = (req, res, next) => { if(!req.shouldRunMiddleware2) { console.log("Skipped middleware 2"); return next(); } console.log("Middleware 2 is running !");} // define middleware 3let middleware3 = (req, res, next) => { console.log("Middleware 3 is running !");} // create route for home page '/'app.get("/", middleware1, middleware2, middleware3);
Output: Run the below command to start the server. After that go to http://localhost:5000 on browser to see output in console
node index.js
In browser.
Console:
Express.js
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Express.js express.Router() Function
Express.js req.params Property
JWT Authentication with Node.js
Mongoose Populate() Method
How to build a basic CRUD app with Node.js and ReactJS ?
Roadmap to Become a Web Developer in 2022
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
Convert a string to an integer in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 25022,
"s": 24994,
"text": "\n09 Apr, 2021"
},
{
"code": null,
"e": 25198,
"s": 25022,
"text": "If we want to skip a middleware we can pass parameters to the middleware function and decide based on that parameter which middleware to call and which middleware to not call."
},
{
"code": null,
"e": 25212,
"s": 25198,
"text": "Prerequisite:"
},
{
"code": null,
"e": 25243,
"s": 25212,
"text": "express.js: To handle routing."
},
{
"code": null,
"e": 25281,
"s": 25243,
"text": "Setting up environment and execution:"
},
{
"code": null,
"e": 25321,
"s": 25281,
"text": "Step 1: Initialize node projectnpm init"
},
{
"code": null,
"e": 25353,
"s": 25321,
"text": "Step 1: Initialize node project"
},
{
"code": null,
"e": 25362,
"s": 25353,
"text": "npm init"
},
{
"code": null,
"e": 25414,
"s": 25362,
"text": "Step 2: Install required modulesnpm install express"
},
{
"code": null,
"e": 25447,
"s": 25414,
"text": "Step 2: Install required modules"
},
{
"code": null,
"e": 25467,
"s": 25447,
"text": "npm install express"
},
{
"code": null,
"e": 25476,
"s": 25467,
"text": "Example:"
},
{
"code": null,
"e": 25485,
"s": 25476,
"text": "index.js"
},
{
"code": "const express = require(\"express\");// const database = require('./sqlConnection'); const app = express(); // Start server on port 5000app.listen(5000, () => { console.log(`Server is up and running on 5000 ...`);}); // define middleware 1let middleware1 = (req, res, next) => { // decide a parameter req.shouldRunMiddleware2 = false; console.log(\"Middleware 1 is running !\"); next();} // define middleware 2let middleware2 = (req, res, next) => { if(!req.shouldRunMiddleware2) { console.log(\"Skipped middleware 2\"); return next(); } console.log(\"Middleware 2 is running !\");} // define middleware 3let middleware3 = (req, res, next) => { console.log(\"Middleware 3 is running !\");} // create route for home page '/'app.get(\"/\", middleware1, middleware2, middleware3);",
"e": 26302,
"s": 25485,
"text": null
},
{
"code": null,
"e": 26428,
"s": 26302,
"text": "Output: Run the below command to start the server. After that go to http://localhost:5000 on browser to see output in console"
},
{
"code": null,
"e": 26442,
"s": 26428,
"text": "node index.js"
},
{
"code": null,
"e": 26454,
"s": 26442,
"text": "In browser."
},
{
"code": null,
"e": 26463,
"s": 26454,
"text": "Console:"
},
{
"code": null,
"e": 26474,
"s": 26463,
"text": "Express.js"
},
{
"code": null,
"e": 26481,
"s": 26474,
"text": "Picked"
},
{
"code": null,
"e": 26489,
"s": 26481,
"text": "Node.js"
},
{
"code": null,
"e": 26506,
"s": 26489,
"text": "Web Technologies"
},
{
"code": null,
"e": 26604,
"s": 26506,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26641,
"s": 26604,
"text": "Express.js express.Router() Function"
},
{
"code": null,
"e": 26672,
"s": 26641,
"text": "Express.js req.params Property"
},
{
"code": null,
"e": 26704,
"s": 26672,
"text": "JWT Authentication with Node.js"
},
{
"code": null,
"e": 26731,
"s": 26704,
"text": "Mongoose Populate() Method"
},
{
"code": null,
"e": 26788,
"s": 26731,
"text": "How to build a basic CRUD app with Node.js and ReactJS ?"
},
{
"code": null,
"e": 26830,
"s": 26788,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 26892,
"s": 26830,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 26935,
"s": 26892,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 26980,
"s": 26935,
"text": "Convert a string to an integer in JavaScript"
}
] |
Insertion Sort | Practice | GeeksforGeeks
|
The task is to complete the insert() function which is used to implement Insertion Sort.
Example 1:
Input:
N = 5
arr[] = { 4, 1, 3, 9, 7}
Output:
1 3 4 7 9
Example 2:
Input:
N = 10
arr[] = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1}
Output:
1 2 3 4 5 6 7 8 9 10
Expected Time Complexity: O(N*N).
Expected Auxiliary Space: O(1).
Constraints:
1 <= N <= 1000
1 <= arr[i] <= 1000
0
koulikmaity1 day ago
void insertionSort(int arr[], int n) { for(int i=1; i<n; i++) { int key = arr[i]; int j = i-1; while(arr[j] > key && j>=0) { arr[j+1] = arr[j]; j--; } arr[j+1] = key; } }
0
futureprogrammer283 days ago
public void insertionSort(int arr[], int n)
{
//code
for(int i=1;i<arr.length;i++){
int ele=arr[i];
int j=i-1;
while(j>=0 && arr[j]>ele){
arr[j+1]=arr[j];
j--;
}
arr[j+1]=ele;
}
}
0
vikaschandra8051101 week ago
void insertionSort(int arr[], int n) { //code here for(int i=1; i<n; i++){ int current=arr[i]; int j; for( j=i-1; j>=0; j--){ if(arr[j]>current){ arr[j+1]=arr[j]; } else break; } arr[j+1]=current; } }
0
haulya1 week ago
void insertionSort(int arr[], int n){ //code here for(int i=1; i < n; i++){ int j = i-1; int key = arr[i]; while (arr[j] > key && j >= 0){ arr[j+1] = arr[j]; j--; } arr[j+1] = key; }}
0
haulya
This comment was deleted.
0
himanshu567843 weeks ago
void insertionSort(int x[], int n) { int i,j,value; for(i=1;i<n;i++) { value=x[i]; for(j=i;j>0 && x[j-1]>value;j--) { x[j]=x[j-1]; } x[j]=value; } }
0
nagapavaneswarreddy27033 weeks ago
class Solution{ public: void insert(int arr[], int i) { cout<<"please enter the no of elements"; cin>>i; cout<<"please enter the elements"; for(int j=0;j<i;j++) {cin>>arr[j];} cout<<"the order of sorted elements are"<<insertionSort(arr,i); } //Function to sort the array using insertion sort algorithm. public: void insertionSort(int arr[], int n) { int i; for(i=2;i<n;i++) {int j=i-1; int key; key=arr[i]; while(j>0&&arr[j]>key) {arr[j+1]=arr[j]; j=j-1;} arr[i+1]=key; } };
0
mdubaid203 weeks ago
class Solution: def insertionSort(self, arr, n): #code here for i in range(n-1): if arr[i+1]<arr[i]: key = arr[i+1] for j in range(i+1): if key < arr[j]: min = j break k = i+1 while min<k<=i+1: arr[k] = arr[k-1] k = k-1 arr[min] = key return arr
0
hritikpatani3 weeks ago
void insertionSort(int arr[], int n) { int temp=0; for(int i=1;i<n;i++){ int k = i; for(int j=i-1;j>=0;j--){ if(arr[k] < arr[j]){ temp = arr[k]; arr[k] = arr[j]; arr[j] = temp; k--; } } } }
0
demishassabis4 weeks ago
class Solution
{
public:
void insert(int arr[], int i)
{
//NO NEED TO CODE THIS
}
public:
//Function to sort the array using insertion sort algorithm.
void insertionSort(int arr[], int n)
{
for(int j=1; j<n; j++)
{
int i = j-1;
int key = arr[j];
while(i>=0 and arr[i]>key)
{
arr[i+1] = arr[i];
i--;
}
arr[i+1] = key;
}
}
};
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": 328,
"s": 238,
"text": "The task is to complete the insert() function which is used to implement Insertion Sort. "
},
{
"code": null,
"e": 340,
"s": 328,
"text": "\nExample 1:"
},
{
"code": null,
"e": 397,
"s": 340,
"text": "Input:\nN = 5\narr[] = { 4, 1, 3, 9, 7}\nOutput:\n1 3 4 7 9\n"
},
{
"code": null,
"e": 408,
"s": 397,
"text": "Example 2:"
},
{
"code": null,
"e": 491,
"s": 408,
"text": "Input:\nN = 10\narr[] = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1}\nOutput:\n1 2 3 4 5 6 7 8 9 10"
},
{
"code": null,
"e": 558,
"s": 491,
"text": "\nExpected Time Complexity: O(N*N).\nExpected Auxiliary Space: O(1)."
},
{
"code": null,
"e": 607,
"s": 558,
"text": "\nConstraints:\n1 <= N <= 1000\n1 <= arr[i] <= 1000"
},
{
"code": null,
"e": 609,
"s": 607,
"text": "0"
},
{
"code": null,
"e": 630,
"s": 609,
"text": "koulikmaity1 day ago"
},
{
"code": null,
"e": 911,
"s": 630,
"text": "void insertionSort(int arr[], int n) { for(int i=1; i<n; i++) { int key = arr[i]; int j = i-1; while(arr[j] > key && j>=0) { arr[j+1] = arr[j]; j--; } arr[j+1] = key; } }"
},
{
"code": null,
"e": 913,
"s": 911,
"text": "0"
},
{
"code": null,
"e": 942,
"s": 913,
"text": "futureprogrammer283 days ago"
},
{
"code": null,
"e": 1240,
"s": 942,
"text": "public void insertionSort(int arr[], int n)\n {\n //code \n for(int i=1;i<arr.length;i++){\n int ele=arr[i];\n int j=i-1;\n while(j>=0 && arr[j]>ele){\n arr[j+1]=arr[j];\n j--;\n }\n arr[j+1]=ele;\n }\n }"
},
{
"code": null,
"e": 1242,
"s": 1240,
"text": "0"
},
{
"code": null,
"e": 1271,
"s": 1242,
"text": "vikaschandra8051101 week ago"
},
{
"code": null,
"e": 1637,
"s": 1271,
"text": " void insertionSort(int arr[], int n) { //code here for(int i=1; i<n; i++){ int current=arr[i]; int j; for( j=i-1; j>=0; j--){ if(arr[j]>current){ arr[j+1]=arr[j]; } else break; } arr[j+1]=current; } }"
},
{
"code": null,
"e": 1639,
"s": 1637,
"text": "0"
},
{
"code": null,
"e": 1656,
"s": 1639,
"text": "haulya1 week ago"
},
{
"code": null,
"e": 1882,
"s": 1656,
"text": "void insertionSort(int arr[], int n){ //code here for(int i=1; i < n; i++){ int j = i-1; int key = arr[i]; while (arr[j] > key && j >= 0){ arr[j+1] = arr[j]; j--; } arr[j+1] = key; }}"
},
{
"code": null,
"e": 1884,
"s": 1882,
"text": "0"
},
{
"code": null,
"e": 1891,
"s": 1884,
"text": "haulya"
},
{
"code": null,
"e": 1917,
"s": 1891,
"text": "This comment was deleted."
},
{
"code": null,
"e": 1919,
"s": 1917,
"text": "0"
},
{
"code": null,
"e": 1944,
"s": 1919,
"text": "himanshu567843 weeks ago"
},
{
"code": null,
"e": 2124,
"s": 1944,
"text": " void insertionSort(int x[], int n) { int i,j,value; for(i=1;i<n;i++) { value=x[i]; for(j=i;j>0 && x[j-1]>value;j--) { x[j]=x[j-1]; } x[j]=value; } } "
},
{
"code": null,
"e": 2126,
"s": 2124,
"text": "0"
},
{
"code": null,
"e": 2161,
"s": 2126,
"text": "nagapavaneswarreddy27033 weeks ago"
},
{
"code": null,
"e": 2768,
"s": 2161,
"text": "class Solution{ public: void insert(int arr[], int i) { cout<<\"please enter the no of elements\"; cin>>i; cout<<\"please enter the elements\"; for(int j=0;j<i;j++) {cin>>arr[j];} cout<<\"the order of sorted elements are\"<<insertionSort(arr,i); } //Function to sort the array using insertion sort algorithm. public: void insertionSort(int arr[], int n) { int i; for(i=2;i<n;i++) {int j=i-1; int key; key=arr[i]; while(j>0&&arr[j]>key) {arr[j+1]=arr[j]; j=j-1;} arr[i+1]=key; } }; "
},
{
"code": null,
"e": 2770,
"s": 2768,
"text": "0"
},
{
"code": null,
"e": 2791,
"s": 2770,
"text": "mdubaid203 weeks ago"
},
{
"code": null,
"e": 3287,
"s": 2791,
"text": "class Solution: def insertionSort(self, arr, n): #code here for i in range(n-1): if arr[i+1]<arr[i]: key = arr[i+1] for j in range(i+1): if key < arr[j]: min = j break k = i+1 while min<k<=i+1: arr[k] = arr[k-1] k = k-1 arr[min] = key return arr "
},
{
"code": null,
"e": 3289,
"s": 3287,
"text": "0"
},
{
"code": null,
"e": 3313,
"s": 3289,
"text": "hritikpatani3 weeks ago"
},
{
"code": null,
"e": 3601,
"s": 3313,
"text": "void insertionSort(int arr[], int n) { int temp=0; for(int i=1;i<n;i++){ int k = i; for(int j=i-1;j>=0;j--){ if(arr[k] < arr[j]){ temp = arr[k]; arr[k] = arr[j]; arr[j] = temp; k--; } } } }"
},
{
"code": null,
"e": 3603,
"s": 3601,
"text": "0"
},
{
"code": null,
"e": 3628,
"s": 3603,
"text": "demishassabis4 weeks ago"
},
{
"code": null,
"e": 4130,
"s": 3628,
"text": "class Solution\n{\n public:\n void insert(int arr[], int i)\n {\n //NO NEED TO CODE THIS\n }\n \n public:\n //Function to sort the array using insertion sort algorithm.\n void insertionSort(int arr[], int n)\n {\n for(int j=1; j<n; j++)\n {\n int i = j-1;\n int key = arr[j];\n while(i>=0 and arr[i]>key)\n {\n arr[i+1] = arr[i];\n i--;\n }\n arr[i+1] = key;\n }\n }\n};\n"
},
{
"code": null,
"e": 4278,
"s": 4132,
"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": 4314,
"s": 4278,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 4324,
"s": 4314,
"text": "\nProblem\n"
},
{
"code": null,
"e": 4334,
"s": 4324,
"text": "\nContest\n"
},
{
"code": null,
"e": 4397,
"s": 4334,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 4545,
"s": 4397,
"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": 4753,
"s": 4545,
"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": 4859,
"s": 4753,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Bank of America Interview Experience | On-Campus 2020 - GeeksforGeeks
|
21 Dec, 2020
Bank of America visited our campus for the post of Senior Tech Associate, at five different locations for the full-time offer. There was a total of three rounds for this position and each round was an elimination round.
Round 1(Video Interview): The first round was held at the HireVue platform and had 2 coding questions and 3 video questions to complete in a duration of 90 minutes.
The Coding Questions Asked were:
Given a String. Convert the String to alternate lowercase, uppercase.Input: This is a book
Output: ThIs Is A bOoKCheck for Balanced Brackets in an expression (well-formedness) using Stack
Given a String. Convert the String to alternate lowercase, uppercase.Input: This is a book
Output: ThIs Is A bOoK
Given a String. Convert the String to alternate lowercase, uppercase.
Input: This is a book
Output: ThIs Is A bOoK
Check for Balanced Brackets in an expression (well-formedness) using Stack
The video Questions asked were:
Explain in detail you’re training, technical background?Have you been in a challenging situation, how do you handle it?Explain the approach you used to solve the 2nd coding question. Also include corner test cases. (Explain from Brute, better to optimal solution)
Explain in detail you’re training, technical background?
Have you been in a challenging situation, how do you handle it?
Explain the approach you used to solve the 2nd coding question. Also include corner test cases. (Explain from Brute, better to optimal solution)
After this round, 300 students moved to the next round.
Round 2(Technical F2F Interview): It was a resume centric Interview. They first asked me to explain all my projects and then to jump to DBMS, Oops, and OS concepts.
Some questions asked from DBMS-
What is data, information?
Advantages of DBMS and Acid properties.
What are transactions and different states in a transaction?
SQL vs NoSQL
How to convert relational to a non-relational database.
From oops, they asked polymorphism, its different types with Example.
At last, they asked me questions related to OS-
What is the OS?
Which is the main part of the OS?
How does kernel work?
I was then shortlisted for the next round.
Round 3(HR Round): There were two interviewers in the panel and after their introduction, the discussion moved to my projects.
As I have mentioned Face Recognition, he gave me a situation, how will you handle it. I want you to identify a person after 5 years(He wanted to know my approach)
Where do you see yourself after 5 years?
How well-equipped you are with working remotely?
Why do you want to join Bank of America?
Last, they asked do you have any questions from them, I asked some basic questions about Bank of America.
Tip:
Read about the company from the company website, LinkedIn, and their achievements.
Be through with your resume.
71 students selected from our campus. I was one of them. Thanks, https://www.geeksforgeeks.org/ for providing amazing content.
Bank of America
Marketing
On-Campus
Interview Experiences
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Amazon Interview Experience
Amazon Interview Experience for SDE-1 (On-Campus)
Microsoft Interview Experience for Internship (Via Engage)
Directi Interview | Set 7 (Programming Questions)
Zoho Interview | Set 3 (Off-Campus)
Amazon Interview Experience for SDE-1
Amazon Interview Experience for SDE-1 (Off-Campus)
Difference between ANN, CNN and RNN
Amazon Interview Experience (Off-Campus) 2022
Amazon Interview Experience for SDE-1(Off-Campus)
|
[
{
"code": null,
"e": 25012,
"s": 24984,
"text": "\n21 Dec, 2020"
},
{
"code": null,
"e": 25232,
"s": 25012,
"text": "Bank of America visited our campus for the post of Senior Tech Associate, at five different locations for the full-time offer. There was a total of three rounds for this position and each round was an elimination round."
},
{
"code": null,
"e": 25397,
"s": 25232,
"text": "Round 1(Video Interview): The first round was held at the HireVue platform and had 2 coding questions and 3 video questions to complete in a duration of 90 minutes."
},
{
"code": null,
"e": 25430,
"s": 25397,
"text": "The Coding Questions Asked were:"
},
{
"code": null,
"e": 25618,
"s": 25430,
"text": "Given a String. Convert the String to alternate lowercase, uppercase.Input: This is a book\nOutput: ThIs Is A bOoKCheck for Balanced Brackets in an expression (well-formedness) using Stack"
},
{
"code": null,
"e": 25732,
"s": 25618,
"text": "Given a String. Convert the String to alternate lowercase, uppercase.Input: This is a book\nOutput: ThIs Is A bOoK"
},
{
"code": null,
"e": 25802,
"s": 25732,
"text": "Given a String. Convert the String to alternate lowercase, uppercase."
},
{
"code": null,
"e": 25847,
"s": 25802,
"text": "Input: This is a book\nOutput: ThIs Is A bOoK"
},
{
"code": null,
"e": 25922,
"s": 25847,
"text": "Check for Balanced Brackets in an expression (well-formedness) using Stack"
},
{
"code": null,
"e": 25954,
"s": 25922,
"text": "The video Questions asked were:"
},
{
"code": null,
"e": 26218,
"s": 25954,
"text": "Explain in detail you’re training, technical background?Have you been in a challenging situation, how do you handle it?Explain the approach you used to solve the 2nd coding question. Also include corner test cases. (Explain from Brute, better to optimal solution)"
},
{
"code": null,
"e": 26275,
"s": 26218,
"text": "Explain in detail you’re training, technical background?"
},
{
"code": null,
"e": 26339,
"s": 26275,
"text": "Have you been in a challenging situation, how do you handle it?"
},
{
"code": null,
"e": 26484,
"s": 26339,
"text": "Explain the approach you used to solve the 2nd coding question. Also include corner test cases. (Explain from Brute, better to optimal solution)"
},
{
"code": null,
"e": 26540,
"s": 26484,
"text": "After this round, 300 students moved to the next round."
},
{
"code": null,
"e": 26705,
"s": 26540,
"text": "Round 2(Technical F2F Interview): It was a resume centric Interview. They first asked me to explain all my projects and then to jump to DBMS, Oops, and OS concepts."
},
{
"code": null,
"e": 26737,
"s": 26705,
"text": "Some questions asked from DBMS-"
},
{
"code": null,
"e": 26764,
"s": 26737,
"text": "What is data, information?"
},
{
"code": null,
"e": 26804,
"s": 26764,
"text": "Advantages of DBMS and Acid properties."
},
{
"code": null,
"e": 26865,
"s": 26804,
"text": "What are transactions and different states in a transaction?"
},
{
"code": null,
"e": 26878,
"s": 26865,
"text": "SQL vs NoSQL"
},
{
"code": null,
"e": 26934,
"s": 26878,
"text": "How to convert relational to a non-relational database."
},
{
"code": null,
"e": 27004,
"s": 26934,
"text": "From oops, they asked polymorphism, its different types with Example."
},
{
"code": null,
"e": 27052,
"s": 27004,
"text": "At last, they asked me questions related to OS-"
},
{
"code": null,
"e": 27068,
"s": 27052,
"text": "What is the OS?"
},
{
"code": null,
"e": 27102,
"s": 27068,
"text": "Which is the main part of the OS?"
},
{
"code": null,
"e": 27124,
"s": 27102,
"text": "How does kernel work?"
},
{
"code": null,
"e": 27167,
"s": 27124,
"text": "I was then shortlisted for the next round."
},
{
"code": null,
"e": 27294,
"s": 27167,
"text": "Round 3(HR Round): There were two interviewers in the panel and after their introduction, the discussion moved to my projects."
},
{
"code": null,
"e": 27457,
"s": 27294,
"text": "As I have mentioned Face Recognition, he gave me a situation, how will you handle it. I want you to identify a person after 5 years(He wanted to know my approach)"
},
{
"code": null,
"e": 27498,
"s": 27457,
"text": "Where do you see yourself after 5 years?"
},
{
"code": null,
"e": 27547,
"s": 27498,
"text": "How well-equipped you are with working remotely?"
},
{
"code": null,
"e": 27588,
"s": 27547,
"text": "Why do you want to join Bank of America?"
},
{
"code": null,
"e": 27694,
"s": 27588,
"text": "Last, they asked do you have any questions from them, I asked some basic questions about Bank of America."
},
{
"code": null,
"e": 27699,
"s": 27694,
"text": "Tip:"
},
{
"code": null,
"e": 27782,
"s": 27699,
"text": "Read about the company from the company website, LinkedIn, and their achievements."
},
{
"code": null,
"e": 27811,
"s": 27782,
"text": "Be through with your resume."
},
{
"code": null,
"e": 27939,
"s": 27811,
"text": "71 students selected from our campus. I was one of them. Thanks, https://www.geeksforgeeks.org/ for providing amazing content. "
},
{
"code": null,
"e": 27955,
"s": 27939,
"text": "Bank of America"
},
{
"code": null,
"e": 27965,
"s": 27955,
"text": "Marketing"
},
{
"code": null,
"e": 27975,
"s": 27965,
"text": "On-Campus"
},
{
"code": null,
"e": 27997,
"s": 27975,
"text": "Interview Experiences"
},
{
"code": null,
"e": 28095,
"s": 27997,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28123,
"s": 28095,
"text": "Amazon Interview Experience"
},
{
"code": null,
"e": 28173,
"s": 28123,
"text": "Amazon Interview Experience for SDE-1 (On-Campus)"
},
{
"code": null,
"e": 28232,
"s": 28173,
"text": "Microsoft Interview Experience for Internship (Via Engage)"
},
{
"code": null,
"e": 28282,
"s": 28232,
"text": "Directi Interview | Set 7 (Programming Questions)"
},
{
"code": null,
"e": 28318,
"s": 28282,
"text": "Zoho Interview | Set 3 (Off-Campus)"
},
{
"code": null,
"e": 28356,
"s": 28318,
"text": "Amazon Interview Experience for SDE-1"
},
{
"code": null,
"e": 28407,
"s": 28356,
"text": "Amazon Interview Experience for SDE-1 (Off-Campus)"
},
{
"code": null,
"e": 28443,
"s": 28407,
"text": "Difference between ANN, CNN and RNN"
},
{
"code": null,
"e": 28489,
"s": 28443,
"text": "Amazon Interview Experience (Off-Campus) 2022"
}
] |
How to restrict MySQL `LIKE` operator to begin with specific characters?
|
Let us first create a table −
mysql> create table DemoTable
(
FirstName varchar(40)
);
Query OK, 0 rows affected (0.52 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('John');
Query OK, 1 row affected (0.08 sec)
mysql> insert into DemoTable values('Adam');
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable values('David');
Query OK, 1 row affected (0.21 sec)
mysql> insert into DemoTable values('Mike');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values('Sam');
Query OK, 1 row affected (0.09 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+-----------+
|FirstName |
+-----------+
| John |
| Adam |
| David |
| Mike |
| Sam |
+-----------+
5 rows in set (0.00 sec)
Following is the query to restrict `LIKE` operator to begin with specific characters −
mysql> select *from DemoTable where FirstName LIKE 'D%' or FirstName LIKE 'S%';
This will produce the following output −
+-----------+
| FirstName |
+-----------+
| David |
| Sam |
+-----------+
2 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1092,
"s": 1062,
"text": "Let us first create a table −"
},
{
"code": null,
"e": 1189,
"s": 1092,
"text": "mysql> create table DemoTable\n(\n FirstName varchar(40)\n);\nQuery OK, 0 rows affected (0.52 sec)"
},
{
"code": null,
"e": 1245,
"s": 1189,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 1650,
"s": 1245,
"text": "mysql> insert into DemoTable values('John');\nQuery OK, 1 row affected (0.08 sec)\nmysql> insert into DemoTable values('Adam');\nQuery OK, 1 row affected (0.09 sec)\nmysql> insert into DemoTable values('David');\nQuery OK, 1 row affected (0.21 sec)\nmysql> insert into DemoTable values('Mike');\nQuery OK, 1 row affected (0.16 sec)\nmysql> insert into DemoTable values('Sam');\nQuery OK, 1 row affected (0.09 sec)"
},
{
"code": null,
"e": 1710,
"s": 1650,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 1741,
"s": 1710,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 1782,
"s": 1741,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1933,
"s": 1782,
"text": "+-----------+\n|FirstName |\n+-----------+\n| John |\n| Adam |\n| David |\n| Mike |\n| Sam |\n+-----------+\n5 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2020,
"s": 1933,
"text": "Following is the query to restrict `LIKE` operator to begin with specific characters −"
},
{
"code": null,
"e": 2100,
"s": 2020,
"text": "mysql> select *from DemoTable where FirstName LIKE 'D%' or FirstName LIKE 'S%';"
},
{
"code": null,
"e": 2141,
"s": 2100,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2250,
"s": 2141,
"text": "+-----------+\n| FirstName |\n+-----------+\n| David |\n| Sam |\n+-----------+\n2 rows in set (0.00 sec)"
}
] |
Simplification - Online Quiz
|
Following quiz provides Multiple Choice Questions (MCQs) related to Simplification. You will have to read all the given answers and click over the correct answer. If you are not sure about the answer then you can check the answer using Show Answer button. You can use Next Quiz button to check new set of questions in the quiz.
Q 1 - 5852 / 28 * ? - 1653 = 1064
A - 9
B - 13
C - 15
D - 18
let 5852 / 28 * x ? 1653 = 1064.
Then , 5852 * 1/28 *x = ( 1064 + 1653 ) = 2717 ⇒ 209 x = 2717 ⇒ x = 2717 / 209 = 13.
Q 2 - 108 / 36 of 1/3 + 2/5 * 15/4 = ?
A - 35/4
B - 25/4
C - 5/2
D - 21/2
given exp. = 108 /36 of 1/3+ 2/5 *15/4
= 108/ 12+ 2/5 *15/4 = 9+ 3/2 = 21/2
Q 3 - 9 - (11/9) of (36/11) /(36/7) of (7/9) = ?
A - 5/4
B - 8
C - 680/81
D - 9
given exp = 9- 11/9 of 36/11/ 36/7 of 7/9 =9-4/4=( 9-1) = 8
Q 4 - 6994/7 + 6995/7 +6996/7 +6997/7 +6998/7 +6999/7 =?
A - 2998
B - 5979
C - 5997
D - 5994
Give Exp. = (999 * 6 ) + (1/7 + 2/7 + 3/7+ 4/7+ 5/7+ 6/7)
= 5994 + ( 1+ 2+ 3+ 4 +5+ 6) / 7 = 5994 + 21/7
= 5994+ 3 = 5997.
Q 5 - If 1/ 1+ 1 / 1+ 1/x = 2 then x = ?
A - ? 1/3
B - ? 1
C - 1/3
D - 1
1/(1+ 1/ (1+1/x)) = 2
⇒ 1/(1+x/(x+1)) = 2
⇒ (x+1)/ (2x+1) = 2
⇒ x+1= 4x+2
⇒ 3x= -1
⇒ x= -1/3
Q 6 - (1+ 1/ x+1) (1+ 1/ x+2) (1+ 1/ x+3) (1+ 1/ x+4)= ?
A - x+5/ x+1
B - (x+ 1/ x+5 )
C - 1/ (x+5)
D - x+6/ x+5
given exp.= (x+2)/ (x+1)* (x+3)/(x+2) *(x+4)/ (x+3)* (x+5) (x+4)
= (x+5)/ (x+1)
Q 7 - if x/ 2y = 3/2 , then (2x+y)/(x-2y) = ?
A - 1/7
B - 7
C - 7.1
D - none of these
x / 2y = 3/2 ⇒ x/y = ( 2 * 3/2 ) = 3.
2x +y / x - 2y = 2 ( x/y ) + 1 / (x/y) - 2 = 2* 3 + 1 / 3-2 = 7/1 = 7.
Q 8 - if x= (1-a), y=(2a+1) and x = y , then a = ?
A - 2
B - 1/2
C - 0
D - -1
x= y ⇒(1-a) = (2a+1) ⇒ 3a = 0 ⇒ a = 0.
Q 9 - ((856+167)2 +(856-167)2)/(856*856+ 167*167)= ?
A - 1
B - 2
C - 689
D - 1023
given exp. = (a+b)2 +(a-b)2/ (a2+b2), where a = 856 , b = 167
= 2 (a2+b2) /(a2+b2) = 2
Q 10 - An organization have three share holder A, B and C. all of the shareholder get the share of profit in that way 1/3 share of the profit gets A. while 1/4 share of the profit received by B and rest of the part of the profit Rs. 5000 becomes the share of C. Find out the share of profit Received by A?
A - 2500 Rs
B - 3000 Rs
C - 3500 Rs
D - 4000 Rs
Let the total profit be rs. x. then,
x/3 + x/4 +5000 = x ⇒ 4x+ 3x+ 60000 = 12x
⇒ 5x = 60000 ⇒ x = 12000.
Share of profit received by A = (1/3 * 12000) = 4000 Rs.
87 Lectures
22.5 hours
Programming Line
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 4220,
"s": 3892,
"text": "Following quiz provides Multiple Choice Questions (MCQs) related to Simplification. You will have to read all the given answers and click over the correct answer. If you are not sure about the answer then you can check the answer using Show Answer button. You can use Next Quiz button to check new set of questions in the quiz."
},
{
"code": null,
"e": 4254,
"s": 4220,
"text": "Q 1 - 5852 / 28 * ? - 1653 = 1064"
},
{
"code": null,
"e": 4260,
"s": 4254,
"text": "A - 9"
},
{
"code": null,
"e": 4267,
"s": 4260,
"text": "B - 13"
},
{
"code": null,
"e": 4274,
"s": 4267,
"text": "C - 15"
},
{
"code": null,
"e": 4281,
"s": 4274,
"text": "D - 18"
},
{
"code": null,
"e": 4399,
"s": 4281,
"text": "let 5852 / 28 * x ? 1653 = 1064.\nThen , 5852 * 1/28 *x = ( 1064 + 1653 ) = 2717 ⇒ 209 x = 2717 ⇒ x = 2717 / 209 = 13."
},
{
"code": null,
"e": 4439,
"s": 4399,
"text": "Q 2 - 108 / 36 of 1/3 + 2/5 * 15/4 = ?"
},
{
"code": null,
"e": 4448,
"s": 4439,
"text": "A - 35/4"
},
{
"code": null,
"e": 4457,
"s": 4448,
"text": "B - 25/4"
},
{
"code": null,
"e": 4465,
"s": 4457,
"text": "C - 5/2"
},
{
"code": null,
"e": 4474,
"s": 4465,
"text": "D - 21/2"
},
{
"code": null,
"e": 4550,
"s": 4474,
"text": "given exp. = 108 /36 of 1/3+ 2/5 *15/4\n= 108/ 12+ 2/5 *15/4 = 9+ 3/2 = 21/2"
},
{
"code": null,
"e": 4600,
"s": 4550,
"text": "Q 3 - 9 - (11/9) of (36/11) /(36/7) of (7/9) = ?"
},
{
"code": null,
"e": 4608,
"s": 4600,
"text": "A - 5/4"
},
{
"code": null,
"e": 4614,
"s": 4608,
"text": "B - 8"
},
{
"code": null,
"e": 4625,
"s": 4614,
"text": "C - 680/81"
},
{
"code": null,
"e": 4631,
"s": 4625,
"text": "D - 9"
},
{
"code": null,
"e": 4691,
"s": 4631,
"text": "given exp = 9- 11/9 of 36/11/ 36/7 of 7/9 =9-4/4=( 9-1) = 8"
},
{
"code": null,
"e": 4748,
"s": 4691,
"text": "Q 4 - 6994/7 + 6995/7 +6996/7 +6997/7 +6998/7 +6999/7 =?"
},
{
"code": null,
"e": 4757,
"s": 4748,
"text": "A - 2998"
},
{
"code": null,
"e": 4766,
"s": 4757,
"text": "B - 5979"
},
{
"code": null,
"e": 4775,
"s": 4766,
"text": "C - 5997"
},
{
"code": null,
"e": 4784,
"s": 4775,
"text": "D - 5994"
},
{
"code": null,
"e": 4907,
"s": 4784,
"text": "Give Exp. = (999 * 6 ) + (1/7 + 2/7 + 3/7+ 4/7+ 5/7+ 6/7)\n= 5994 + ( 1+ 2+ 3+ 4 +5+ 6) / 7 = 5994 + 21/7\n= 5994+ 3 = 5997."
},
{
"code": null,
"e": 4948,
"s": 4907,
"text": "Q 5 - If 1/ 1+ 1 / 1+ 1/x = 2 then x = ?"
},
{
"code": null,
"e": 4958,
"s": 4948,
"text": "A - ? 1/3"
},
{
"code": null,
"e": 4966,
"s": 4958,
"text": "B - ? 1"
},
{
"code": null,
"e": 4974,
"s": 4966,
"text": "C - 1/3"
},
{
"code": null,
"e": 4980,
"s": 4974,
"text": "D - 1"
},
{
"code": null,
"e": 5073,
"s": 4980,
"text": "1/(1+ 1/ (1+1/x)) = 2\n⇒ 1/(1+x/(x+1)) = 2\n⇒ (x+1)/ (2x+1) = 2\n⇒ x+1= 4x+2\n⇒ 3x= -1\n⇒ x= -1/3"
},
{
"code": null,
"e": 5130,
"s": 5073,
"text": "Q 6 - (1+ 1/ x+1) (1+ 1/ x+2) (1+ 1/ x+3) (1+ 1/ x+4)= ?"
},
{
"code": null,
"e": 5144,
"s": 5130,
"text": "A - x+5/ x+1"
},
{
"code": null,
"e": 5161,
"s": 5144,
"text": "B - (x+ 1/ x+5 )"
},
{
"code": null,
"e": 5174,
"s": 5161,
"text": "C - 1/ (x+5)"
},
{
"code": null,
"e": 5187,
"s": 5174,
"text": "D - x+6/ x+5"
},
{
"code": null,
"e": 5269,
"s": 5187,
"text": "given exp.= (x+2)/ (x+1)* (x+3)/(x+2) *(x+4)/ (x+3)* (x+5) (x+4)\n= (x+5)/ (x+1)"
},
{
"code": null,
"e": 5317,
"s": 5269,
"text": "Q 7 - if x/ 2y = 3/2 , then (2x+y)/(x-2y) = ?"
},
{
"code": null,
"e": 5325,
"s": 5317,
"text": "A - 1/7"
},
{
"code": null,
"e": 5331,
"s": 5325,
"text": "B - 7"
},
{
"code": null,
"e": 5339,
"s": 5331,
"text": "C - 7.1"
},
{
"code": null,
"e": 5357,
"s": 5339,
"text": "D - none of these"
},
{
"code": null,
"e": 5467,
"s": 5357,
"text": "x / 2y = 3/2 ⇒ x/y = ( 2 * 3/2 ) = 3.\n2x +y / x - 2y = 2 ( x/y ) + 1 / (x/y) - 2 = 2* 3 + 1 / 3-2 = 7/1 = 7."
},
{
"code": null,
"e": 5518,
"s": 5467,
"text": "Q 8 - if x= (1-a), y=(2a+1) and x = y , then a = ?"
},
{
"code": null,
"e": 5524,
"s": 5518,
"text": "A - 2"
},
{
"code": null,
"e": 5532,
"s": 5524,
"text": "B - 1/2"
},
{
"code": null,
"e": 5538,
"s": 5532,
"text": "C - 0"
},
{
"code": null,
"e": 5545,
"s": 5538,
"text": "D - -1"
},
{
"code": null,
"e": 5584,
"s": 5545,
"text": "x= y ⇒(1-a) = (2a+1) ⇒ 3a = 0 ⇒ a = 0."
},
{
"code": null,
"e": 5637,
"s": 5584,
"text": "Q 9 - ((856+167)2 +(856-167)2)/(856*856+ 167*167)= ?"
},
{
"code": null,
"e": 5643,
"s": 5637,
"text": "A - 1"
},
{
"code": null,
"e": 5649,
"s": 5643,
"text": "B - 2"
},
{
"code": null,
"e": 5657,
"s": 5649,
"text": "C - 689"
},
{
"code": null,
"e": 5666,
"s": 5657,
"text": "D - 1023"
},
{
"code": null,
"e": 5756,
"s": 5666,
"text": "given exp. = (a+b)2 +(a-b)2/ (a2+b2), where a = 856 , b = 167\n= 2 (a2+b2) /(a2+b2) = 2"
},
{
"code": null,
"e": 6072,
"s": 5756,
"text": "Q 10 - An organization have three share holder A, B and C. all of the shareholder get the share of profit in that way 1/3 share of the profit gets A. while 1/4 share of the profit received by B and rest of the part of the profit Rs. 5000 becomes the share of C. Find out the share of profit Received by A?"
},
{
"code": null,
"e": 6084,
"s": 6072,
"text": "A - 2500 Rs"
},
{
"code": null,
"e": 6096,
"s": 6084,
"text": "B - 3000 Rs"
},
{
"code": null,
"e": 6108,
"s": 6096,
"text": "C - 3500 Rs"
},
{
"code": null,
"e": 6120,
"s": 6108,
"text": "D - 4000 Rs"
},
{
"code": null,
"e": 6286,
"s": 6120,
"text": "Let the total profit be rs. x. then,\nx/3 + x/4 +5000 = x ⇒ 4x+ 3x+ 60000 = 12x\n⇒ 5x = 60000 ⇒ x = 12000.\nShare of profit received by A = (1/3 * 12000) = 4000 Rs."
},
{
"code": null,
"e": 6322,
"s": 6286,
"text": "\n 87 Lectures \n 22.5 hours \n"
},
{
"code": null,
"e": 6340,
"s": 6322,
"text": " Programming Line"
},
{
"code": null,
"e": 6347,
"s": 6340,
"text": " Print"
},
{
"code": null,
"e": 6358,
"s": 6347,
"text": " Add Notes"
}
] |
atq command in linux with examples - GeeksforGeeks
|
04 Apr, 2019
atq displays the list of pending jobs which are scheduled by the user. If the user is the superuser then the pending jobs of all the users will be displayed. The output lines display Job number, date, hour, queue, and username for each job.
Syntax:
atq [-V] [-q queue]
Options:
-V: It will display the version number to standard error and exit successfully.
-q: Shows job of specified queue. A queue can be denoted by any single letter from a to z and A to Z. For ‘at’, a is the default queue and for ‘batch’, b queue is default. For a currently running job, queue name will be designated with “=”. If a job is submitted to a queue designated with an uppercase letter, the job is treated as if it were submitted to batch at the time of the job.atq without arguments display all pending jobs of User.atq without arguments display all pending jobs of all users if the root is the user.To display jobs which belong to a specific queue:atq -q QueueBelow image is showing all the jobs which belongs to queue ‘m’.Alternative Command for atq:at -l Showing all the jobs.Showing all the jobs which belongs to queue ‘a’.My Personal Notes
arrow_drop_upSave
atq without arguments display all pending jobs of User.
atq without arguments display all pending jobs of all users if the root is the user.
To display jobs which belong to a specific queue:atq -q QueueBelow image is showing all the jobs which belongs to queue ‘m’.
atq -q Queue
Below image is showing all the jobs which belongs to queue ‘m’.
Alternative Command for atq:
at -l
Showing all the jobs.
Showing all the jobs which belongs to queue ‘a’.
linux-command
Linux-misc-commands
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
scp command in Linux with Examples
nohup Command in Linux with Examples
mv command in Linux with examples
Thread functions in C/C++
Docker - COPY Instruction
chown command in Linux with Examples
nslookup command in Linux with Examples
SED command in Linux | Set 2
Named Pipe or FIFO with example C program
uniq Command in LINUX with examples
|
[
{
"code": null,
"e": 24015,
"s": 23987,
"text": "\n04 Apr, 2019"
},
{
"code": null,
"e": 24256,
"s": 24015,
"text": "atq displays the list of pending jobs which are scheduled by the user. If the user is the superuser then the pending jobs of all the users will be displayed. The output lines display Job number, date, hour, queue, and username for each job."
},
{
"code": null,
"e": 24264,
"s": 24256,
"text": "Syntax:"
},
{
"code": null,
"e": 24284,
"s": 24264,
"text": "atq [-V] [-q queue]"
},
{
"code": null,
"e": 24293,
"s": 24284,
"text": "Options:"
},
{
"code": null,
"e": 24373,
"s": 24293,
"text": "-V: It will display the version number to standard error and exit successfully."
},
{
"code": null,
"e": 25161,
"s": 24373,
"text": "-q: Shows job of specified queue. A queue can be denoted by any single letter from a to z and A to Z. For ‘at’, a is the default queue and for ‘batch’, b queue is default. For a currently running job, queue name will be designated with “=”. If a job is submitted to a queue designated with an uppercase letter, the job is treated as if it were submitted to batch at the time of the job.atq without arguments display all pending jobs of User.atq without arguments display all pending jobs of all users if the root is the user.To display jobs which belong to a specific queue:atq -q QueueBelow image is showing all the jobs which belongs to queue ‘m’.Alternative Command for atq:at -l Showing all the jobs.Showing all the jobs which belongs to queue ‘a’.My Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 25217,
"s": 25161,
"text": "atq without arguments display all pending jobs of User."
},
{
"code": null,
"e": 25302,
"s": 25217,
"text": "atq without arguments display all pending jobs of all users if the root is the user."
},
{
"code": null,
"e": 25427,
"s": 25302,
"text": "To display jobs which belong to a specific queue:atq -q QueueBelow image is showing all the jobs which belongs to queue ‘m’."
},
{
"code": null,
"e": 25440,
"s": 25427,
"text": "atq -q Queue"
},
{
"code": null,
"e": 25504,
"s": 25440,
"text": "Below image is showing all the jobs which belongs to queue ‘m’."
},
{
"code": null,
"e": 25533,
"s": 25504,
"text": "Alternative Command for atq:"
},
{
"code": null,
"e": 25540,
"s": 25533,
"text": "at -l "
},
{
"code": null,
"e": 25562,
"s": 25540,
"text": "Showing all the jobs."
},
{
"code": null,
"e": 25611,
"s": 25562,
"text": "Showing all the jobs which belongs to queue ‘a’."
},
{
"code": null,
"e": 25625,
"s": 25611,
"text": "linux-command"
},
{
"code": null,
"e": 25645,
"s": 25625,
"text": "Linux-misc-commands"
},
{
"code": null,
"e": 25652,
"s": 25645,
"text": "Picked"
},
{
"code": null,
"e": 25663,
"s": 25652,
"text": "Linux-Unix"
},
{
"code": null,
"e": 25761,
"s": 25663,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25770,
"s": 25761,
"text": "Comments"
},
{
"code": null,
"e": 25783,
"s": 25770,
"text": "Old Comments"
},
{
"code": null,
"e": 25818,
"s": 25783,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 25855,
"s": 25818,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 25889,
"s": 25855,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 25915,
"s": 25889,
"text": "Thread functions in C/C++"
},
{
"code": null,
"e": 25941,
"s": 25915,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 25978,
"s": 25941,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 26018,
"s": 25978,
"text": "nslookup command in Linux with Examples"
},
{
"code": null,
"e": 26047,
"s": 26018,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 26089,
"s": 26047,
"text": "Named Pipe or FIFO with example C program"
}
] |
Check if it is possible to convert one string into another with given constraints - GeeksforGeeks
|
19 May, 2021
Given two strings contains three characters i.e ‘A’, ‘B ‘and ‘#’ only. Check is it possible to convert first string into another string by performing following operations on string first. 1- ‘A’ can move towards Left only 2- ‘B’ can move towards Right only 3- Neither ‘A’ nor ‘B’ cross each other If it is possible then print “Yes” otherwise “No”.Examples:
Input : str1=” #A#B#B# “, str2=” A###B#B ” Output :Yes Explanation : ‘A’ in str1 is right to the ‘A’ in str2 so ‘A’ of str1 can move easily towards the left because there is no ‘B’ on its left positions and for first ‘B’ in str1 is left to the ‘B’ in str2 so ‘B’ of str2 can move easily towards the right because there is no ‘A’ on its right positions and it is same for next ‘B’ so str1 can be easily converted into str2.Input :str1=” #A#B# “, str2=” #B#A# ” Output :No Explanation : Here first ‘A’ in str1 is left to the ‘A’ in str2 and according to the condition ‘A’ can’tmove towards right. so str1 can’t be converted into str2.
Method : 1-Length of Both string must be same 2-No. of A’s and B’s in both the strings must be equal 3-Order of A and B in both the strings should be same(for ex: if ‘A’ is coming before ‘B’in string second then the same sequence must be follow on string first)
C++
Java
Python3
C#
Javascript
// C++ Program for above implementation#include <bits/stdc++.h>using namespace std; // Function to check is it possible to convert// first string into another string or not.bool isItPossible(string str1, string str2, int m, int n){ // To Check Length of Both String is Equal or Not if (m != n) return false; // To Check Frequency of A's and B's are // equal in both strings or not. if (count(str1.begin(), str1.end(), 'A') != count(str2.begin(), str2.end(), 'A') || count(str1.begin(), str1.end(), 'B') != count(str2.begin(), str2.end(), 'B')) return false; // Start traversing for (int i = 0; i < m; i++) { if (str1[i] != '#') { for (int j = 0; j < n; j++) { // To Check no two elements cross each other. if ((str2[j] != str1[i]) && str2[j] != '#') return false; if (str2[j] == str1[i]) { str2[j] = '#'; // To Check Is it Possible to Move // towards Left or not. if (str1[i] == 'A' && i < j) return false; // To Check Is it Possible to Move // towards Right or not. if (str1[i] == 'B' && i > j) return false; break; } } } } return true;} // Drivers codeint main(){ string str1 = "A#B#"; string str2 = "A##B"; int m = str1.length(); int n = str2.length(); isItPossible(str1, str2, m, n) ? cout << "Yes\n" : cout << "No\n"; return 0;}
// Java Program for above implementationclass GFG{ // Function to check is it possible to convert// first String into another String or not.static boolean isItPossible(char[] str1, char[] str2, int m, int n){ // To Check Length of Both String is Equal or Not if (m != n) return false; // To Check Frequency of A's and B's are // equal in both Strings or not. if (count(str1, 'A') != count(str2, 'A') || count(str1, 'B') != count(str2, 'B')) return false; // Start traversing for (int i = 0; i < m; i++) { if (str1[i] != '#') { for (int j = 0; j < n; j++) { // To Check no two elements cross each other. if ((str2[j] != str1[i]) && str2[j] != '#') return false; if (str2[j] == str1[i]) { str2[j] = '#'; // To Check Is it Possible to Move // towards Left or not. if (str1[i] == 'A' && i < j) return false; // To Check Is it Possible to Move // towards Right or not. if (str1[i] == 'B' && i > j) return false; break; } } } } return true;} private static int count(char[] str1, char c) { int count = 0; for(char temp : str1) { if(c == temp) count++; } return count;} // Drivers codepublic static void main(String[] args){ String str1 = "A#B#"; String str2 = "A##B"; int m = str1.length(); int n = str2.length(); System.out.print(isItPossible(str1.toCharArray(), str2.toCharArray(), m, n) ? "Yes\n":"No\n"); }} // This code is contributed by Rajput-Ji
# Python Program for above implementation # Function to check is it possible to convert# first string into another string or not.def isItPossible(str1, str2, m, n): # To Check Length of Both String is Equal or Not if (m != n): return False # To Check Frequency of A's and B's are # equal in both strings or not. if str1.count('A') != str2.count('A') \ or str1.count('B') != str2.count('B'): return False # Start traversing for i in range(m): if (str1[i] != '#'): for j in range(n): # To Check no two elements cross each other. if ((str2[j] != str1[i]) and str2[j] != '#'): return False if (str2[j] == str1[i]): str2[j] = '#' # To Check Is it Possible to Move # towards Left or not. if (str1[i] == 'A' and i < j): return False # To Check Is it Possible to Move # towards Right or not. if (str1[i] == 'B' and i > j): return False break return True # Drivers code str1 = "A#B#"str2 = "A##B" m = len(str1)n = len(str2) str1 = list(str1)str2 = list(str2) if(isItPossible(str1, str2, m, n)): print("Yes")else: print("No") # This code is contributed by ankush_953
// C# Program for above implementationusing System; class GFG{ // Function to check is it possible to convert// first String into another String or not.static bool isItPossible(char[] str1, char[] str2, int m, int n){ // To Check Length of Both String is Equal or Not if (m != n) return false; // To Check Frequency of A's and B's are // equal in both Strings or not. if (count(str1, 'A') != count(str2, 'A') || count(str1, 'B') != count(str2, 'B')) return false; // Start traversing for (int i = 0; i < m; i++) { if (str1[i] != '#') { for (int j = 0; j < n; j++) { // To Check no two elements cross each other. if ((str2[j] != str1[i]) && str2[j] != '#') return false; if (str2[j] == str1[i]) { str2[j] = '#'; // To Check Is it Possible to Move // towards Left or not. if (str1[i] == 'A' && i < j) return false; // To Check Is it Possible to Move // towards Right or not. if (str1[i] == 'B' && i > j) return false; break; } } } } return true;} private static int count(char[] str1, char c) { int count = 0; foreach(char temp in str1) { if(c == temp) count++; } return count;} // Drivers codepublic static void Main(String[] args){ String str1 = "A#B#"; String str2 = "A##B"; int m = str1.Length; int n = str2.Length; Console.Write(isItPossible(str1.ToCharArray(), str2.ToCharArray(), m, n) ? "Yes\n":"No\n"); }} // This code is contributed by Rajput-Ji
<script> // js Program for above implementationfunction getFreq(string,chr) { let ans = 0; for (var i=0; i<string.length;i++) { if( chr == string.charAt(i)) ans++; } return ans;};// Function to check is it possible to convert// first string into another string or not.function isItPossible(str1, str2, m, n){ // To Check Length of Both String is Equal or Not if (m != n) return false; // To Check Frequency of A's and B's are // equal in both strings or not. if (getFreq(str1, 'A') != getFreq(str2, 'A') || getFreq(str1, 'B') != getFreq(str2, 'B')) return false; // Start traversing for (let i = 0; i < m; i++) { if (str1[i] != '#') { for (let j = 0; j < n; j++) { // To Check no two elements cross each other. if ((str2[j] != str1[i]) && str2[j] != '#') return false; if (str2[j] == str1[i]) { str2 = str2.substr(0,j)+'#'+str2.substr(j+1); // To Check Is it Possible to Move // towards Left or not. if (str1[i] == 'A' && i < j) return false; // To Check Is it Possible to Move // towards Right or not. if (str1[i] == 'B' && i > j) return false; break; } } } } return true;} // Drivers codelet str1 = "A#B#";let str2 = "A##B"; let m = str1.length;let n = str2.length;isItPossible(str1, str2, m, n) ?document.write( "Yes<br>") : document.write( "No<br>"); </script>
Output:
Yes
Time Complexity : O(n^2)
ankush_953
Rajput-Ji
rohan07
Competitive Programming
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 15 Websites for Coding Challenges and Competitions
Breadth First Traversal ( BFS ) on a 2D array
Shortest path in a directed graph by Dijkstra’s algorithm
Count of strings whose prefix match with the given string to a given length k
Graph implementation using STL for competitive programming | Set 2 (Weighted graph)
Write a program to reverse an array or string
Reverse a string in Java
Longest Common Subsequence | DP-4
Write a program to print all permutations of a given string
C++ Data Types
|
[
{
"code": null,
"e": 25036,
"s": 25008,
"text": "\n19 May, 2021"
},
{
"code": null,
"e": 25395,
"s": 25036,
"text": "Given two strings contains three characters i.e ‘A’, ‘B ‘and ‘#’ only. Check is it possible to convert first string into another string by performing following operations on string first. 1- ‘A’ can move towards Left only 2- ‘B’ can move towards Right only 3- Neither ‘A’ nor ‘B’ cross each other If it is possible then print “Yes” otherwise “No”.Examples: "
},
{
"code": null,
"e": 26029,
"s": 25395,
"text": "Input : str1=” #A#B#B# “, str2=” A###B#B ” Output :Yes Explanation : ‘A’ in str1 is right to the ‘A’ in str2 so ‘A’ of str1 can move easily towards the left because there is no ‘B’ on its left positions and for first ‘B’ in str1 is left to the ‘B’ in str2 so ‘B’ of str2 can move easily towards the right because there is no ‘A’ on its right positions and it is same for next ‘B’ so str1 can be easily converted into str2.Input :str1=” #A#B# “, str2=” #B#A# ” Output :No Explanation : Here first ‘A’ in str1 is left to the ‘A’ in str2 and according to the condition ‘A’ can’tmove towards right. so str1 can’t be converted into str2. "
},
{
"code": null,
"e": 26294,
"s": 26031,
"text": "Method : 1-Length of Both string must be same 2-No. of A’s and B’s in both the strings must be equal 3-Order of A and B in both the strings should be same(for ex: if ‘A’ is coming before ‘B’in string second then the same sequence must be follow on string first) "
},
{
"code": null,
"e": 26298,
"s": 26294,
"text": "C++"
},
{
"code": null,
"e": 26303,
"s": 26298,
"text": "Java"
},
{
"code": null,
"e": 26311,
"s": 26303,
"text": "Python3"
},
{
"code": null,
"e": 26314,
"s": 26311,
"text": "C#"
},
{
"code": null,
"e": 26325,
"s": 26314,
"text": "Javascript"
},
{
"code": "// C++ Program for above implementation#include <bits/stdc++.h>using namespace std; // Function to check is it possible to convert// first string into another string or not.bool isItPossible(string str1, string str2, int m, int n){ // To Check Length of Both String is Equal or Not if (m != n) return false; // To Check Frequency of A's and B's are // equal in both strings or not. if (count(str1.begin(), str1.end(), 'A') != count(str2.begin(), str2.end(), 'A') || count(str1.begin(), str1.end(), 'B') != count(str2.begin(), str2.end(), 'B')) return false; // Start traversing for (int i = 0; i < m; i++) { if (str1[i] != '#') { for (int j = 0; j < n; j++) { // To Check no two elements cross each other. if ((str2[j] != str1[i]) && str2[j] != '#') return false; if (str2[j] == str1[i]) { str2[j] = '#'; // To Check Is it Possible to Move // towards Left or not. if (str1[i] == 'A' && i < j) return false; // To Check Is it Possible to Move // towards Right or not. if (str1[i] == 'B' && i > j) return false; break; } } } } return true;} // Drivers codeint main(){ string str1 = \"A#B#\"; string str2 = \"A##B\"; int m = str1.length(); int n = str2.length(); isItPossible(str1, str2, m, n) ? cout << \"Yes\\n\" : cout << \"No\\n\"; return 0;}",
"e": 28007,
"s": 26325,
"text": null
},
{
"code": "// Java Program for above implementationclass GFG{ // Function to check is it possible to convert// first String into another String or not.static boolean isItPossible(char[] str1, char[] str2, int m, int n){ // To Check Length of Both String is Equal or Not if (m != n) return false; // To Check Frequency of A's and B's are // equal in both Strings or not. if (count(str1, 'A') != count(str2, 'A') || count(str1, 'B') != count(str2, 'B')) return false; // Start traversing for (int i = 0; i < m; i++) { if (str1[i] != '#') { for (int j = 0; j < n; j++) { // To Check no two elements cross each other. if ((str2[j] != str1[i]) && str2[j] != '#') return false; if (str2[j] == str1[i]) { str2[j] = '#'; // To Check Is it Possible to Move // towards Left or not. if (str1[i] == 'A' && i < j) return false; // To Check Is it Possible to Move // towards Right or not. if (str1[i] == 'B' && i > j) return false; break; } } } } return true;} private static int count(char[] str1, char c) { int count = 0; for(char temp : str1) { if(c == temp) count++; } return count;} // Drivers codepublic static void main(String[] args){ String str1 = \"A#B#\"; String str2 = \"A##B\"; int m = str1.length(); int n = str2.length(); System.out.print(isItPossible(str1.toCharArray(), str2.toCharArray(), m, n) ? \"Yes\\n\":\"No\\n\"); }} // This code is contributed by Rajput-Ji",
"e": 29827,
"s": 28007,
"text": null
},
{
"code": "# Python Program for above implementation # Function to check is it possible to convert# first string into another string or not.def isItPossible(str1, str2, m, n): # To Check Length of Both String is Equal or Not if (m != n): return False # To Check Frequency of A's and B's are # equal in both strings or not. if str1.count('A') != str2.count('A') \\ or str1.count('B') != str2.count('B'): return False # Start traversing for i in range(m): if (str1[i] != '#'): for j in range(n): # To Check no two elements cross each other. if ((str2[j] != str1[i]) and str2[j] != '#'): return False if (str2[j] == str1[i]): str2[j] = '#' # To Check Is it Possible to Move # towards Left or not. if (str1[i] == 'A' and i < j): return False # To Check Is it Possible to Move # towards Right or not. if (str1[i] == 'B' and i > j): return False break return True # Drivers code str1 = \"A#B#\"str2 = \"A##B\" m = len(str1)n = len(str2) str1 = list(str1)str2 = list(str2) if(isItPossible(str1, str2, m, n)): print(\"Yes\")else: print(\"No\") # This code is contributed by ankush_953",
"e": 31235,
"s": 29827,
"text": null
},
{
"code": "// C# Program for above implementationusing System; class GFG{ // Function to check is it possible to convert// first String into another String or not.static bool isItPossible(char[] str1, char[] str2, int m, int n){ // To Check Length of Both String is Equal or Not if (m != n) return false; // To Check Frequency of A's and B's are // equal in both Strings or not. if (count(str1, 'A') != count(str2, 'A') || count(str1, 'B') != count(str2, 'B')) return false; // Start traversing for (int i = 0; i < m; i++) { if (str1[i] != '#') { for (int j = 0; j < n; j++) { // To Check no two elements cross each other. if ((str2[j] != str1[i]) && str2[j] != '#') return false; if (str2[j] == str1[i]) { str2[j] = '#'; // To Check Is it Possible to Move // towards Left or not. if (str1[i] == 'A' && i < j) return false; // To Check Is it Possible to Move // towards Right or not. if (str1[i] == 'B' && i > j) return false; break; } } } } return true;} private static int count(char[] str1, char c) { int count = 0; foreach(char temp in str1) { if(c == temp) count++; } return count;} // Drivers codepublic static void Main(String[] args){ String str1 = \"A#B#\"; String str2 = \"A##B\"; int m = str1.Length; int n = str2.Length; Console.Write(isItPossible(str1.ToCharArray(), str2.ToCharArray(), m, n) ? \"Yes\\n\":\"No\\n\"); }} // This code is contributed by Rajput-Ji",
"e": 33077,
"s": 31235,
"text": null
},
{
"code": "<script> // js Program for above implementationfunction getFreq(string,chr) { let ans = 0; for (var i=0; i<string.length;i++) { if( chr == string.charAt(i)) ans++; } return ans;};// Function to check is it possible to convert// first string into another string or not.function isItPossible(str1, str2, m, n){ // To Check Length of Both String is Equal or Not if (m != n) return false; // To Check Frequency of A's and B's are // equal in both strings or not. if (getFreq(str1, 'A') != getFreq(str2, 'A') || getFreq(str1, 'B') != getFreq(str2, 'B')) return false; // Start traversing for (let i = 0; i < m; i++) { if (str1[i] != '#') { for (let j = 0; j < n; j++) { // To Check no two elements cross each other. if ((str2[j] != str1[i]) && str2[j] != '#') return false; if (str2[j] == str1[i]) { str2 = str2.substr(0,j)+'#'+str2.substr(j+1); // To Check Is it Possible to Move // towards Left or not. if (str1[i] == 'A' && i < j) return false; // To Check Is it Possible to Move // towards Right or not. if (str1[i] == 'B' && i > j) return false; break; } } } } return true;} // Drivers codelet str1 = \"A#B#\";let str2 = \"A##B\"; let m = str1.length;let n = str2.length;isItPossible(str1, str2, m, n) ?document.write( \"Yes<br>\") : document.write( \"No<br>\"); </script>",
"e": 34795,
"s": 33077,
"text": null
},
{
"code": null,
"e": 34805,
"s": 34795,
"text": "Output: "
},
{
"code": null,
"e": 34809,
"s": 34805,
"text": "Yes"
},
{
"code": null,
"e": 34835,
"s": 34809,
"text": "Time Complexity : O(n^2) "
},
{
"code": null,
"e": 34846,
"s": 34835,
"text": "ankush_953"
},
{
"code": null,
"e": 34856,
"s": 34846,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 34864,
"s": 34856,
"text": "rohan07"
},
{
"code": null,
"e": 34888,
"s": 34864,
"text": "Competitive Programming"
},
{
"code": null,
"e": 34896,
"s": 34888,
"text": "Strings"
},
{
"code": null,
"e": 34904,
"s": 34896,
"text": "Strings"
},
{
"code": null,
"e": 35002,
"s": 34904,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35057,
"s": 35002,
"text": "Top 15 Websites for Coding Challenges and Competitions"
},
{
"code": null,
"e": 35103,
"s": 35057,
"text": "Breadth First Traversal ( BFS ) on a 2D array"
},
{
"code": null,
"e": 35161,
"s": 35103,
"text": "Shortest path in a directed graph by Dijkstra’s algorithm"
},
{
"code": null,
"e": 35239,
"s": 35161,
"text": "Count of strings whose prefix match with the given string to a given length k"
},
{
"code": null,
"e": 35323,
"s": 35239,
"text": "Graph implementation using STL for competitive programming | Set 2 (Weighted graph)"
},
{
"code": null,
"e": 35369,
"s": 35323,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 35394,
"s": 35369,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 35428,
"s": 35394,
"text": "Longest Common Subsequence | DP-4"
},
{
"code": null,
"e": 35488,
"s": 35428,
"text": "Write a program to print all permutations of a given string"
}
] |
Find any K distinct odd integers such that their sum is equal to N - GeeksforGeeks
|
08 Apr, 2021
Given two integers N and K, the task is to find any K distinct odd integers such that their sum is equal to N. If no such integers exists, print -1.Examples:
Input: N = 10, K = 2 Output: 1, 9 Explanation: There are two possible distinct odd integers, such that their sum is equal to N. Possible K integers can be – {(1, 9), (3, 7)}Input: N = 5, K = 4 Output: -1 Explanation: There are no such 4 distinct odd integers such that their sum is 5.
Approach:
The key observation in this problem is if N and K have different parity then it is not possible to find K such distinct integers such that their sum is equal to N,
Otherwise such K – 1 integers will consist of first K-1 odd positive integers
The Kth odd number will be equal to (N – the sum of first (K-1) odd integers)
Kth Odd number = N - sum of first K-1 integer
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation to find k// odd integers such that their sum is N #include <bits/stdc++.h>using namespace std; // Function to find K odd integers// such that their sum is Nvoid oddIntegers(int n, int k){ // Condition to check if there // exist such K integers if (n % 2 != k % 2) { cout << "-1" << "\n"; return; } int sum = 0; int i = 1; int j = 1; // Loop to find first K-1 // distinct odd integers while (j < k) { sum = sum + i; cout << i << " "; i = i + 2; j++; } // Final Kth odd number int finalOdd = n - sum; cout << finalOdd << "\n";} // Driver codeint main(){ int n = 10; int k = 2; oddIntegers(n, k); return 0;}
// Java implementation to find k// odd integers such that their sum is Nclass GFG{ // Function to find K odd integers// such that their sum is Nstatic void oddIntegers(int n, int k){ // Condition to check if there // exist such K integers if (n % 2 != k % 2) { System.out.println("-1"); return; } int sum = 0; int i = 1; int j = 1; // Loop to find first K-1 // distinct odd integers while (j < k) { sum = sum + i; System.out.print(i+" "); i = i + 2; j++; } // Final Kth odd number int finalOdd = n - sum; System.out.println(finalOdd);} // Driver codepublic static void main (String[] args){ int n = 10; int k = 2; oddIntegers(n, k);}} // This code is contributed by shubhamsingh
# Python3 implementation to find k# odd integers such that their sum is N # Function to find K odd integers# such that their sum is Ndef oddIntegers(n, k) : # Condition to check if there # exist such K integers if (n % 2 != k % 2) : print("-1"); return; sum = 0; i = 1; j = 1; # Loop to find first K-1 # distinct odd integers while (j < k) : sum += i; print(i,end= " "); i += 2; j += 1; # Final Kth odd number finalOdd = n - sum; print(finalOdd); # Driver codeif __name__ == "__main__" : n = 10; k = 2; oddIntegers(n, k); # This code is contributed by AnkitRai01
// C# implementation to find k// odd integers such that their sum is Nusing System; class GFG{ // Function to find K odd integers// such that their sum is Nstatic void oddints(int n, int k){ // Condition to check if there // exist such K integers if (n % 2 != k % 2) { Console.WriteLine("-1"); return; } int sum = 0; int i = 1; int j = 1; // Loop to find first K-1 // distinct odd integers while (j < k) { sum = sum + i; Console.Write(i+" "); i = i + 2; j++; } // Final Kth odd number int finalOdd = n - sum; Console.WriteLine(finalOdd);} // Driver codepublic static void Main(String[] args){ int n = 10; int k = 2; oddints(n, k);}} // This code is contributed by PrinciRaj1992
<script> // JavaScript implementation to find k// odd integers such that their sum is N // Function to find K odd integers// such that their sum is N function oddIntegers(n , k) { // Condition to check if there // exist such K integers if (n % 2 != k % 2) { document.write("-1"); return; } var sum = 0; var i = 1; var j = 1; // Loop to find first K-1 // distinct odd integers while (j < k) { sum = sum + i; document.write(i + " "); i = i + 2; j++; } // Final Kth odd number var finalOdd = n - sum; document.write(finalOdd); } // Driver code var n = 10; var k = 2; oddIntegers(n, k); // This code contributed by Rajput-Ji </script>
1 9
Performance Analysis:
Time Complexity: As in the above approach, There is a loop to find such K odd integers which takes O(K) time in worst case. Hence the Time Complexity will be O(K).
Auxiliary Space Complexity: As in the above approach, There is no extra space used. Hence the auxiliary space complexity will be O(1).
ankthon
SHUBHAMSINGH10
princiraj1992
Rajput-Ji
Numbers
Mathematical
Mathematical
Numbers
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Merge two sorted arrays
Modulo Operator (%) in C/C++ with Examples
Prime Numbers
Program for Decimal to Binary Conversion
Find all factors of a natural number | Set 1
Program to find sum of elements in a given array
The Knight's tour problem | Backtracking-1
Program for factorial of a number
Operators in C / C++
Minimum number of jumps to reach end
|
[
{
"code": null,
"e": 24681,
"s": 24653,
"text": "\n08 Apr, 2021"
},
{
"code": null,
"e": 24841,
"s": 24681,
"text": "Given two integers N and K, the task is to find any K distinct odd integers such that their sum is equal to N. If no such integers exists, print -1.Examples: "
},
{
"code": null,
"e": 25128,
"s": 24841,
"text": "Input: N = 10, K = 2 Output: 1, 9 Explanation: There are two possible distinct odd integers, such that their sum is equal to N. Possible K integers can be – {(1, 9), (3, 7)}Input: N = 5, K = 4 Output: -1 Explanation: There are no such 4 distinct odd integers such that their sum is 5. "
},
{
"code": null,
"e": 25142,
"s": 25130,
"text": "Approach: "
},
{
"code": null,
"e": 25306,
"s": 25142,
"text": "The key observation in this problem is if N and K have different parity then it is not possible to find K such distinct integers such that their sum is equal to N,"
},
{
"code": null,
"e": 25384,
"s": 25306,
"text": "Otherwise such K – 1 integers will consist of first K-1 odd positive integers"
},
{
"code": null,
"e": 25464,
"s": 25384,
"text": "The Kth odd number will be equal to (N – the sum of first (K-1) odd integers) "
},
{
"code": null,
"e": 25511,
"s": 25464,
"text": "Kth Odd number = N - sum of first K-1 integer"
},
{
"code": null,
"e": 25565,
"s": 25513,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 25569,
"s": 25565,
"text": "C++"
},
{
"code": null,
"e": 25574,
"s": 25569,
"text": "Java"
},
{
"code": null,
"e": 25582,
"s": 25574,
"text": "Python3"
},
{
"code": null,
"e": 25585,
"s": 25582,
"text": "C#"
},
{
"code": null,
"e": 25596,
"s": 25585,
"text": "Javascript"
},
{
"code": "// C++ implementation to find k// odd integers such that their sum is N #include <bits/stdc++.h>using namespace std; // Function to find K odd integers// such that their sum is Nvoid oddIntegers(int n, int k){ // Condition to check if there // exist such K integers if (n % 2 != k % 2) { cout << \"-1\" << \"\\n\"; return; } int sum = 0; int i = 1; int j = 1; // Loop to find first K-1 // distinct odd integers while (j < k) { sum = sum + i; cout << i << \" \"; i = i + 2; j++; } // Final Kth odd number int finalOdd = n - sum; cout << finalOdd << \"\\n\";} // Driver codeint main(){ int n = 10; int k = 2; oddIntegers(n, k); return 0;}",
"e": 26337,
"s": 25596,
"text": null
},
{
"code": "// Java implementation to find k// odd integers such that their sum is Nclass GFG{ // Function to find K odd integers// such that their sum is Nstatic void oddIntegers(int n, int k){ // Condition to check if there // exist such K integers if (n % 2 != k % 2) { System.out.println(\"-1\"); return; } int sum = 0; int i = 1; int j = 1; // Loop to find first K-1 // distinct odd integers while (j < k) { sum = sum + i; System.out.print(i+\" \"); i = i + 2; j++; } // Final Kth odd number int finalOdd = n - sum; System.out.println(finalOdd);} // Driver codepublic static void main (String[] args){ int n = 10; int k = 2; oddIntegers(n, k);}} // This code is contributed by shubhamsingh",
"e": 27118,
"s": 26337,
"text": null
},
{
"code": "# Python3 implementation to find k# odd integers such that their sum is N # Function to find K odd integers# such that their sum is Ndef oddIntegers(n, k) : # Condition to check if there # exist such K integers if (n % 2 != k % 2) : print(\"-1\"); return; sum = 0; i = 1; j = 1; # Loop to find first K-1 # distinct odd integers while (j < k) : sum += i; print(i,end= \" \"); i += 2; j += 1; # Final Kth odd number finalOdd = n - sum; print(finalOdd); # Driver codeif __name__ == \"__main__\" : n = 10; k = 2; oddIntegers(n, k); # This code is contributed by AnkitRai01",
"e": 27788,
"s": 27118,
"text": null
},
{
"code": "// C# implementation to find k// odd integers such that their sum is Nusing System; class GFG{ // Function to find K odd integers// such that their sum is Nstatic void oddints(int n, int k){ // Condition to check if there // exist such K integers if (n % 2 != k % 2) { Console.WriteLine(\"-1\"); return; } int sum = 0; int i = 1; int j = 1; // Loop to find first K-1 // distinct odd integers while (j < k) { sum = sum + i; Console.Write(i+\" \"); i = i + 2; j++; } // Final Kth odd number int finalOdd = n - sum; Console.WriteLine(finalOdd);} // Driver codepublic static void Main(String[] args){ int n = 10; int k = 2; oddints(n, k);}} // This code is contributed by PrinciRaj1992",
"e": 28575,
"s": 27788,
"text": null
},
{
"code": "<script> // JavaScript implementation to find k// odd integers such that their sum is N // Function to find K odd integers// such that their sum is N function oddIntegers(n , k) { // Condition to check if there // exist such K integers if (n % 2 != k % 2) { document.write(\"-1\"); return; } var sum = 0; var i = 1; var j = 1; // Loop to find first K-1 // distinct odd integers while (j < k) { sum = sum + i; document.write(i + \" \"); i = i + 2; j++; } // Final Kth odd number var finalOdd = n - sum; document.write(finalOdd); } // Driver code var n = 10; var k = 2; oddIntegers(n, k); // This code contributed by Rajput-Ji </script>",
"e": 29417,
"s": 28575,
"text": null
},
{
"code": null,
"e": 29421,
"s": 29417,
"text": "1 9"
},
{
"code": null,
"e": 29447,
"s": 29423,
"text": "Performance Analysis: "
},
{
"code": null,
"e": 29611,
"s": 29447,
"text": "Time Complexity: As in the above approach, There is a loop to find such K odd integers which takes O(K) time in worst case. Hence the Time Complexity will be O(K)."
},
{
"code": null,
"e": 29746,
"s": 29611,
"text": "Auxiliary Space Complexity: As in the above approach, There is no extra space used. Hence the auxiliary space complexity will be O(1)."
},
{
"code": null,
"e": 29756,
"s": 29748,
"text": "ankthon"
},
{
"code": null,
"e": 29771,
"s": 29756,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 29785,
"s": 29771,
"text": "princiraj1992"
},
{
"code": null,
"e": 29795,
"s": 29785,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 29803,
"s": 29795,
"text": "Numbers"
},
{
"code": null,
"e": 29816,
"s": 29803,
"text": "Mathematical"
},
{
"code": null,
"e": 29829,
"s": 29816,
"text": "Mathematical"
},
{
"code": null,
"e": 29837,
"s": 29829,
"text": "Numbers"
},
{
"code": null,
"e": 29935,
"s": 29837,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29944,
"s": 29935,
"text": "Comments"
},
{
"code": null,
"e": 29957,
"s": 29944,
"text": "Old Comments"
},
{
"code": null,
"e": 29981,
"s": 29957,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 30024,
"s": 29981,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 30038,
"s": 30024,
"text": "Prime Numbers"
},
{
"code": null,
"e": 30079,
"s": 30038,
"text": "Program for Decimal to Binary Conversion"
},
{
"code": null,
"e": 30124,
"s": 30079,
"text": "Find all factors of a natural number | Set 1"
},
{
"code": null,
"e": 30173,
"s": 30124,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 30216,
"s": 30173,
"text": "The Knight's tour problem | Backtracking-1"
},
{
"code": null,
"e": 30250,
"s": 30216,
"text": "Program for factorial of a number"
},
{
"code": null,
"e": 30271,
"s": 30250,
"text": "Operators in C / C++"
}
] |
Calculate the frequency of each word in the given string - GeeksforGeeks
|
26 Nov, 2021
Given a string str, the task is to find the frequency of each word in a string.
Examples:
Input: str = “Geeks For Geeks” Output: For 1 Geeks 2 Explanation: For occurs 1 time and Geeks occurs 2 times in the given string str.
Input: str = “learning to code is learning to create and innovate” Output: and 1 code 1 create 1 innovate 1 is 1 learning 2 to 2 Explanation: The words and, code, create, innovate, is occurs 1 time; and learning, to occurs 2 times in the given string str.
Approach: To solve the problem mentioned above we have to follow the steps given below:
Use a Map data structure to store the occurrence of each word in the string.
Traverse the entire string and check whether the current word is present in map or not. If it is present, then update the frequency of the current word else insert the word with frequency 1.
Traverse in the map and print the frequency of each word.
Below is the implementation of the above approach:
C++
Java
Python3
C#
// C++ program to calculate the frequency// of each word in the given string #include <bits/stdc++.h>using namespace std; // Function to print frequency of each wordvoid printFrequency(string str){ map<string, int> M; // String for storing the words string word = ""; for (int i = 0; i < str.size(); i++) { // Check if current character // is blank space then it // means we have got one word if (str[i] == ' ') { // If the current word // is not found then insert // current word with frequency 1 if (M.find(word) == M.end()) { M.insert(make_pair(word, 1)); word = ""; } // update the frequency else { M[word]++; word = ""; } } else word += str[i]; } // Storing the last word of the string if (M.find(word) == M.end()) M.insert(make_pair(word, 1)); // Update the frequency else M[word]++; // Traverse the map // to print the frequency for (auto& it : M) { cout << it.first << " - " << it.second << endl; }} // Driver Codeint main(){ string str = "Geeks For Geeks"; printFrequency(str); return 0;}
// Java implementation of the above// approach import java.util.Map;import java.util.TreeMap;public class Frequency_Of_String_Words { // Function to count frequency of // words in the given string static void count_freq(String str) { Map<String,Integer> mp=new TreeMap<>(); // Splitting to find the word String arr[]=str.split(" "); // Loop to iterate over the words for(int i=0;i<arr.length;i++) { // Condition to check if the // array element is present // the hash-map if(mp.containsKey(arr[i])) { mp.put(arr[i], mp.get(arr[i])+1); } else { mp.put(arr[i],1); } } // Loop to iterate over the // elements of the map for(Map.Entry<String,Integer> entry: mp.entrySet()) { System.out.println(entry.getKey()+ " - "+entry.getValue()); } } // Driver Code public static void main(String[] args) { String str = "Geeks For Geeks"; // Function Call count_freq(str); }}
# Python3 program to calculate the frequency# of each word in the given string # Function to print frequency of each worddef printFrequency(strr): M = {} # string for storing the words word = "" for i in range(len(strr)): # Check if current character # is blank space then it # means we have got one word if (strr[i] == ' '): # If the current word # is not found then insert # current word with frequency 1 if (word not in M): M[word] = 1 word = "" # update the frequency else: M[word] += 1 word = "" else: word += strr[i] # Storing the last word of the string if (word not in M): M[word] = 1 # Update the frequency else: M[word] += 1 # Traverse the map # to print the frequency for it in M: print(it, "-", M[it]) # Driver Codestrr = "Geeks For Geeks"printFrequency(strr) # This code is contributed by shubhamsingh10
// C# implementation of the above// approachusing System;using System.Collections.Generic; class GFG{ // Function to count frequency of// words in the given stringstatic void count_freq(String str){ SortedDictionary<String, int> mp = new SortedDictionary<String, int>(); // Splitting to find the word String []arr = str.Split(' '); // Loop to iterate over the words for(int i = 0; i < arr.Length; i++) { // Condition to check if the // array element is present // the hash-map if (mp.ContainsKey(arr[i])) { mp[arr[i]] = mp[arr[i]] + 1; } else { mp.Add(arr[i], 1); } } // Loop to iterate over the // elements of the map foreach(KeyValuePair<String, int> entry in mp) { Console.WriteLine(entry.Key + " - " + entry.Value); }} // Driver Codepublic static void Main(String[] args){ String str = "Geeks For Geeks"; // Function call count_freq(str);}} // This code is contributed by Rajput-Ji
For - 1
Geeks - 2
SHUBHAMSINGH10
Rajput-Ji
surinderdawra388
ankita_saini
cpp-map
frequency-counting
STL
School Programming
Strings
Strings
STL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Constructors in Java
Exceptions in Java
Ternary Operator in Python
Inline Functions in C++
Destructors in C++
Write a program to reverse an array or string
Longest Common Subsequence | DP-4
Write a program to print all permutations of a given string
Check for Balanced Brackets in an expression (well-formedness) using Stack
KMP Algorithm for Pattern Searching
|
[
{
"code": null,
"e": 24232,
"s": 24204,
"text": "\n26 Nov, 2021"
},
{
"code": null,
"e": 24312,
"s": 24232,
"text": "Given a string str, the task is to find the frequency of each word in a string."
},
{
"code": null,
"e": 24323,
"s": 24312,
"text": "Examples: "
},
{
"code": null,
"e": 24457,
"s": 24323,
"text": "Input: str = “Geeks For Geeks” Output: For 1 Geeks 2 Explanation: For occurs 1 time and Geeks occurs 2 times in the given string str."
},
{
"code": null,
"e": 24714,
"s": 24457,
"text": "Input: str = “learning to code is learning to create and innovate” Output: and 1 code 1 create 1 innovate 1 is 1 learning 2 to 2 Explanation: The words and, code, create, innovate, is occurs 1 time; and learning, to occurs 2 times in the given string str. "
},
{
"code": null,
"e": 24803,
"s": 24714,
"text": "Approach: To solve the problem mentioned above we have to follow the steps given below: "
},
{
"code": null,
"e": 24880,
"s": 24803,
"text": "Use a Map data structure to store the occurrence of each word in the string."
},
{
"code": null,
"e": 25071,
"s": 24880,
"text": "Traverse the entire string and check whether the current word is present in map or not. If it is present, then update the frequency of the current word else insert the word with frequency 1."
},
{
"code": null,
"e": 25129,
"s": 25071,
"text": "Traverse in the map and print the frequency of each word."
},
{
"code": null,
"e": 25181,
"s": 25129,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 25185,
"s": 25181,
"text": "C++"
},
{
"code": null,
"e": 25190,
"s": 25185,
"text": "Java"
},
{
"code": null,
"e": 25198,
"s": 25190,
"text": "Python3"
},
{
"code": null,
"e": 25201,
"s": 25198,
"text": "C#"
},
{
"code": "// C++ program to calculate the frequency// of each word in the given string #include <bits/stdc++.h>using namespace std; // Function to print frequency of each wordvoid printFrequency(string str){ map<string, int> M; // String for storing the words string word = \"\"; for (int i = 0; i < str.size(); i++) { // Check if current character // is blank space then it // means we have got one word if (str[i] == ' ') { // If the current word // is not found then insert // current word with frequency 1 if (M.find(word) == M.end()) { M.insert(make_pair(word, 1)); word = \"\"; } // update the frequency else { M[word]++; word = \"\"; } } else word += str[i]; } // Storing the last word of the string if (M.find(word) == M.end()) M.insert(make_pair(word, 1)); // Update the frequency else M[word]++; // Traverse the map // to print the frequency for (auto& it : M) { cout << it.first << \" - \" << it.second << endl; }} // Driver Codeint main(){ string str = \"Geeks For Geeks\"; printFrequency(str); return 0;}",
"e": 26504,
"s": 25201,
"text": null
},
{
"code": "// Java implementation of the above// approach import java.util.Map;import java.util.TreeMap;public class Frequency_Of_String_Words { // Function to count frequency of // words in the given string static void count_freq(String str) { Map<String,Integer> mp=new TreeMap<>(); // Splitting to find the word String arr[]=str.split(\" \"); // Loop to iterate over the words for(int i=0;i<arr.length;i++) { // Condition to check if the // array element is present // the hash-map if(mp.containsKey(arr[i])) { mp.put(arr[i], mp.get(arr[i])+1); } else { mp.put(arr[i],1); } } // Loop to iterate over the // elements of the map for(Map.Entry<String,Integer> entry: mp.entrySet()) { System.out.println(entry.getKey()+ \" - \"+entry.getValue()); } } // Driver Code public static void main(String[] args) { String str = \"Geeks For Geeks\"; // Function Call count_freq(str); }}",
"e": 27687,
"s": 26504,
"text": null
},
{
"code": "# Python3 program to calculate the frequency# of each word in the given string # Function to print frequency of each worddef printFrequency(strr): M = {} # string for storing the words word = \"\" for i in range(len(strr)): # Check if current character # is blank space then it # means we have got one word if (strr[i] == ' '): # If the current word # is not found then insert # current word with frequency 1 if (word not in M): M[word] = 1 word = \"\" # update the frequency else: M[word] += 1 word = \"\" else: word += strr[i] # Storing the last word of the string if (word not in M): M[word] = 1 # Update the frequency else: M[word] += 1 # Traverse the map # to print the frequency for it in M: print(it, \"-\", M[it]) # Driver Codestrr = \"Geeks For Geeks\"printFrequency(strr) # This code is contributed by shubhamsingh10",
"e": 28811,
"s": 27687,
"text": null
},
{
"code": "// C# implementation of the above// approachusing System;using System.Collections.Generic; class GFG{ // Function to count frequency of// words in the given stringstatic void count_freq(String str){ SortedDictionary<String, int> mp = new SortedDictionary<String, int>(); // Splitting to find the word String []arr = str.Split(' '); // Loop to iterate over the words for(int i = 0; i < arr.Length; i++) { // Condition to check if the // array element is present // the hash-map if (mp.ContainsKey(arr[i])) { mp[arr[i]] = mp[arr[i]] + 1; } else { mp.Add(arr[i], 1); } } // Loop to iterate over the // elements of the map foreach(KeyValuePair<String, int> entry in mp) { Console.WriteLine(entry.Key + \" - \" + entry.Value); }} // Driver Codepublic static void Main(String[] args){ String str = \"Geeks For Geeks\"; // Function call count_freq(str);}} // This code is contributed by Rajput-Ji",
"e": 29947,
"s": 28811,
"text": null
},
{
"code": null,
"e": 29965,
"s": 29947,
"text": "For - 1\nGeeks - 2"
},
{
"code": null,
"e": 29982,
"s": 29967,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 29992,
"s": 29982,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 30009,
"s": 29992,
"text": "surinderdawra388"
},
{
"code": null,
"e": 30022,
"s": 30009,
"text": "ankita_saini"
},
{
"code": null,
"e": 30030,
"s": 30022,
"text": "cpp-map"
},
{
"code": null,
"e": 30049,
"s": 30030,
"text": "frequency-counting"
},
{
"code": null,
"e": 30053,
"s": 30049,
"text": "STL"
},
{
"code": null,
"e": 30072,
"s": 30053,
"text": "School Programming"
},
{
"code": null,
"e": 30080,
"s": 30072,
"text": "Strings"
},
{
"code": null,
"e": 30088,
"s": 30080,
"text": "Strings"
},
{
"code": null,
"e": 30092,
"s": 30088,
"text": "STL"
},
{
"code": null,
"e": 30190,
"s": 30092,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30199,
"s": 30190,
"text": "Comments"
},
{
"code": null,
"e": 30212,
"s": 30199,
"text": "Old Comments"
},
{
"code": null,
"e": 30233,
"s": 30212,
"text": "Constructors in Java"
},
{
"code": null,
"e": 30252,
"s": 30233,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 30279,
"s": 30252,
"text": "Ternary Operator in Python"
},
{
"code": null,
"e": 30303,
"s": 30279,
"text": "Inline Functions in C++"
},
{
"code": null,
"e": 30322,
"s": 30303,
"text": "Destructors in C++"
},
{
"code": null,
"e": 30368,
"s": 30322,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 30402,
"s": 30368,
"text": "Longest Common Subsequence | DP-4"
},
{
"code": null,
"e": 30462,
"s": 30402,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 30537,
"s": 30462,
"text": "Check for Balanced Brackets in an expression (well-formedness) using Stack"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.